一维时间序列数据的 Durbin-Watson 统计量

Durbin–Watson statistic for one dimensional time series data

我正在尝试确定一个时间序列(如一个浮点数列表)是否与其自身相关。我已经玩过 statsmodels (http://statsmodels.sourceforge.net/devel/generated/statsmodels.tsa.stattools.acf.html) 中的 acf 函数,现在我正在研究 Durbin–Watson 统计是否有价值。

看来这种东西应该行得通:

from statsmodels.regression.linear_model import OLS
import numpy as np

data = np.arange(100)  # this should be highly correlated
ols_res = OLS(data)
dw_res = np.sum(np.diff(ols_res.resid.values))

如果你运行这个,你会得到:

Traceback (most recent call last):
...
  File "/usr/lib/pymodules/python2.7/statsmodels/regression/linear_model.py", line 165, in initialize
    self.nobs = float(self.wexog.shape[0])
AttributeError: 'NoneType' object has no attribute 'shape'

似乎D/W通常用于比较两个时间序列(例如http://connor-johnson.com/2014/02/18/linear-regression-with-python/)的相关性,所以我认为问题是我没有通过另一个时间序列来相比于。也许这应该在 exog 参数中传递给 OLS?

exog : array-like

A nobs x k array where nobs is the number of observations and k is
the number of regressors.

(来自 http://statsmodels.sourceforge.net/devel/generated/statsmodels.regression.linear_model.OLS.html

旁注:我不确定 "nobs x k" 数组的含义。也许数组是 x by k?

那么我应该在这里做什么?我是否应该通过 data 两次, 或者我自己手动延迟,或者?

谢谢!

OLS 是需要 y 和 x(或 endog 和 exog)的回归。在您的情况下,x 至少需要是一个常数,即。 np.ones(len(endog), 1).

此外,您需要对模型进行拟合,即ols_res = OLS(y, x).fit()

nobs x k 表示二维,行中有 nobs 观察,列中有 k 个变量,即 exog.shape 是 (nobs, k)

Durbin Watson 是序列相关的检验统计量。它包含在 OLS 汇总输出中。 statsmodels 中还包含其他没有自相关的测试。

(我建议您完成一些示例或教程笔记本。)

我已经接受了 user333700 的回答,但我想post跟进一个代码片段。

这个小程序计算线性范围的 durbin-watson 相关性(应该高度相关,因此给出接近 0 的值)然后计算随机值(应该不相关,因此给出接近的值到 2):

from statsmodels.regression.linear_model import OLS
import numpy as np
from statsmodels.stats.stattools import durbin_watson



def dw(data):
    ols_res = OLS(data, np.ones(len(data))).fit()
    return durbin_watson(ols_res.resid)


print("dw of range=%f" % dw(np.arange(2000)))
print("dw of rand=%f" % dw(np.random.randn(2000)))

当运行:

dw of range=0.000003
dw of rand=2.036162

所以我觉得这看起来不错:)