首页 > 解决方案 > 如何绘制 stattools ccf 函数的置信区间?

问题描述

我正在使用statsmodels中的ccf计算互相关函数。它工作正常,除了我看不到如何绘制置信区间。我注意到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])

这给出了:

在此处输入图像描述

标签: pythonmatplotlibstatisticsstatsmodels

解决方案


不幸的是,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])

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


推荐阅读