如何绘制 stattools ccf 函数的置信区间?

How to plot confidence intervals for stattools ccf function?

我正在计算互相关函数 ccf from statsmodels. It works fine except I can't see how to also plot the confidence intervals. I notice that acf 似乎有更多的功能。这是一个玩具示例,只是为了让您看看:

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])

这给出:

不幸的是,置信区间不是由 statsmodels 互相关函数提供的 (ccf)。在 R 中,ccf() 还会打印置信区间。

这里需要我们自己计算置信区间,然后绘制出来。此处的置信区间计算为 2 / np.sqrt(lags)。有关互相关置信区间的基本信息,请参阅:

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])

这将导致以下带有附加红线的图: