如何简单地计算python中时间序列的滚动/移动方差?

问题描述 投票:10回答:2

我有一个简单的时间序列,我正在努力估计移动窗口内的方差。更具体地说,我无法解决与实现滑动窗口功能的方式有关的一些问题。例如,使用NumPy和窗口大小= 20时:

def rolling_window(a, window):
    shape = a.shape[:-1] + (a.shape[-1] - window + 1, window)
    strides = a.strides + (a.strides[-1],)
    return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides) 

rolling_window(data, 20)
np.var(rolling_window(data, 20), -1)
datavar=np.var(rolling_window(data, 20), -1)

在这个想法中,也许我错了。有谁知道一个直截了当的方法吗?任何帮助/建议都是最受欢迎的。

python numpy time-series variance sliding-window
2个回答
13
投票

你应该看看pandas。例如:

import pandas as pd
import numpy as np

# some sample data
ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000)).cumsum()

#plot the time series
ts.plot(style='k--')

# calculate a 60 day rolling mean and plot
pd.rolling_mean(ts, 60).plot(style='k')

# add the 20 day rolling variance:
pd.rolling_std(ts, 20).plot(style='b')


8
投票

Pandas rolling_meanrolling_std函数已被弃用,取而代之的是更为通用的“滚动”框架。 @ elyase的例子可以修改为:

import pandas as pd
import numpy as np
%matplotlib inline

# some sample data
ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000)).cumsum()

#plot the time series
ts.plot(style='k--')

# calculate a 60 day rolling mean and plot
ts.rolling(window=60).mean().plot(style='k')

# add the 20 day rolling variance:
ts.rolling(window=20).std().plot(style='b')

rolling函数支持许多不同的窗口类型,如here所记录。可以在rolling对象上调用许多函数,包括var和其他有趣的统计数据(skewkurtquantile等)。我坚持使用std,因为情节与平均值在同一个图表上,这在单位方面更有意义。

© www.soinside.com 2019 - 2024. All rights reserved.