Python – How do I plot the confidence interval for the stattools ccf function?

How do I plot the confidence interval for the stattools ccf function?… here is a solution to the problem.

How do I plot the confidence interval for the stattools ccf function?

I’m using ccf to compute the cross-correlation function from a statistical model. It works fine, except I don’t see how to plot the confidence interval. I noticed that ACF seems to have more features. This is a toy example, just to let you see:

import numpy as np
import matplotlib.pyplot as plt
import statsmodels.tsa.stattools as stattools

def create(n):
    x = np.zeros(n)
    for i in range(1, n):
        if np.random.rand() < 0.9:
            if np.random.rand() < 0.5:
                x[i] = x[i-1] + 1
        else:
            x[i] = np.random.randint(0,100)
    return x
x = create(4000)
y = create(4000)
plt.plot(stattools.ccf(x, y)[:100])

This gives:

enter image description here

Solution

Unfortunately, statsmodels crosscorrelation function (ccf) No confidence interval is provided. In R, ccf() also prints confidence intervals.

Here, we need to calculate the confidence interval ourselves and then plot it. The confidence interval here is calculated as 2/np.sqrt(lags). For basic information about cross-correlation confidence intervals, see

import numpy as np
import matplotlib.pyplot as plt
import statsmodels.tsa.stattools as stattools

def create(n):
    x = np.zeros(n)
    for i in range(1, n):
        if np.random.rand() < 0.9:
            if np.random.rand() < 0.5:
                x[i] = x[i-1] + 1
        else:
            x[i] = np.random.randint(0,100)
    return x
x = create(4000)
y = create(4000)

lags= 4000
sl = 2 / np.sqrt(lags)

plt.plot(x, list(np.ones(lags) * sl), color='r')
plt.plot(x, list(np.ones(lags) * -sl), color='r')

plt.plot(stattools.ccf(x, y)[:100])

This will result in the following graph with additional red lines:
CI Plot

Related Problems and Solutions