解决方案
您要计算的是滚动版本的相对标准偏差 (RSD),也称为变异系数 (CV)。请参阅Wikipedia 和
Investopedia 了解有关定义的更多详细信息。
RSD = CV = SD/Mean
让我们先制作一些时间序列数据。
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()
以下代码将为您提供所需的内容。
选项-A
window = 60
rolling_rsd = ts.rolling(window=window).std()/ts.rolling(window=window).mean()
选项-B
或者,您可以使用这个便利功能:
def rsd(ts, window = 60):
"""
Returns the Relative Standard Deviation (RSD),
a.k.a Coefficient of Variation (CV) for a
given rolling window size on a time series data-column.
ts = time series data
window = window size to compute rolling mean, std, rsd
Example:
rolling_rsd, rolling_mean, rolling_std = rsd(ts, window = 60)
"""
rolling_mean = ts.rolling(window=window).mean()
rolling_std = ts.rolling(window=window).std()
rolling_rsd = rolling_std/rolling_mean
return (rolling_rsd, rolling_mean, rolling_std)
详细示例
我将使用便利功能,rsd() 用于以下示例。
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--')
# Using convenience function: rsd()
# calculate rolling RSD, MEAN and STD with window = 60
(rolling_rsd, rolling_mean, rolling_std) = rsd(ts, window = 60)
# calculate a 60 day rolling mean and plot
rolling_mean.plot(style='k')
# add the 60 day rolling standard deviation (STD) to the plot
rolling_std.plot(style='b')
# add the 60 day rolling relative standard deviation (RSD) to the plot
rolling_rsd.plot(style='r')
注意:
您也可以直接如下计算(如果您不想使用其他函数)。
# calculate a 60 day rolling standard deviation (rsd)
rolling_rsd = ts.rolling(window=60).std()/ts.rolling(window=60).mean()
相关解决方案/问题:
- How can I simply calculate the rolling/moving variance of a time series in python?