如何在 python 中简单地计算时间序列的滚动/移动方差?
- 作者: 哈撒尅1
- 来源: 51数据库
- 2022-11-17
问题描述
我有一个简单的时间序列,我正在努力估计移动窗口内的方差.更具体地说,我无法弄清楚与实现滑动窗口功能的方式有关的一些问题.例如,当使用 NumPy 且窗口大小 = 20 时:
I have a simple time series and I am struggling to estimate the variance within a moving window. More specifically, I cannot figure some issues out relating to the way of implementing a sliding window function. For example, when using NumPy and window size = 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)
也许我在某个地方弄错了,在这个思路上.有谁知道一个简单的方法来做到这一点?任何帮助/建议都将受到欢迎.
Perhaps I am mistaken somewhere, in this line of thought. Does anyone know a straightforward way to do this? Any help/advice would be most welcome.
推荐答案
你应该看看 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')
推荐阅读
热点文章
Discord.py(重写)on_member_update 无法正常工作
0
Discord.py 在 vc 中获取用户分钟数
0
discord.py 重写 |为我的命令出错
0
Discord.py rewrite 如何 DM 命令?
0
播放音频时,最后一部分被切断.如何解决这个问题?(discord.py)
0
在消息删除消息 Discord.py
0
如何使 discord.py 机器人私人/直接消息不是作者的人?
0
(Discord.py) 如何获取整个嵌入内容?
0
Discord bot 尽管获得了许可,但不能提及所有人
0
Discord.py discord.NotFound 异常
0
