我正在尝试确定时间序列(例如,一个浮点数列表)是否与其自身相关。我已经玩过 acf
statsmodels ( http://statsmodels.sourceforge.net/devel/generated/statsmodels.tsa.stattools.acf.html ) 中的函数,现在我正在研究 Durbin-Watson 统计是否有值(value)。
看起来这种事情应该有效:
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
来自 k
?那我应该在这里做什么?我是否有望通过
data
两次,或者自己手动滞后,或者?
谢谢!
最佳答案
我已经接受了 user333700 的回答,但我想发布一个代码片段跟进。
这个小程序计算线性范围的 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
所以我认为这看起来不错:)
关于python - 一维时间序列数据的 Durbin-Watson 统计量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43322076/