pandas:
pandas.DataFrame.rolling
pandas.DataFrame.ewm
pandas.DataFrame.mean
其中rolling可以指定窗口类型win_type,比如boxcar, boxcar, triang, blackman, hanning, bartlett
以hanning window为例,其窗口形状为钟型,曲线函数为:
python代码:
import matplotlib.pyplot as pltimport statsmodels.api as smdata_loader = sm.datasets.sunspots.load_pandas()df = data_loader.dataprint("df length is %d" %len(df))print("inital df head:")print(df.head(20))print("SMA head:")print(df["SUNACTIVITY"].rolling(window=10).mean().head(20))print("EMA head:")print(df["SUNACTIVITY"].ewm(span=10,min_periods=10).mean().head(20))year_range = df["YEAR"].valuesplt.plot(year_range, df["SUNACTIVITY"].values, label="Original")plt.plot(year_range, df["SUNACTIVITY"].rolling(window=10).mean(), label="SMA wave")plt.plot(year_range, df["SUNACTIVITY"].rolling(window=10, win_type='hanning').mean(), label="SMA wave with Hanning window")plt.plot(year_range, df["SUNACTIVITY"].ewm(span=10,min_periods=10).mean(), label="EMA wave")plt.legend()plt.show()
输出结果:
df length is 309inital df head:YEAR SUNACTIVITY0 1700.05.01 1701.0 11.02 1702.0 16.03 1703.0 23.04 1704.0 36.05 1705.0 58.06 1706.0 29.07 1707.0 20.08 1708.0 10.09 1709.08.010 1710.03.011 1711.00.012 1712.00.013 1713.02.014 1714.0 11.015 1715.0 27.016 1716.0 47.017 1717.0 63.018 1718.0 60.019 1719.0 39.0SMA head:0NaN1NaN2NaN3NaN4NaN5NaN6NaN7NaN8NaN921.610 21.411 20.312 18.713 16.614 14.115 11.016 12.817 17.118 22.119 25.2Name: SUNACTIVITY, dtype: float64EMA head:0 NaN1 NaN2 NaN3 NaN4 NaN5 NaN6 NaN7 NaN8 NaN920.69086610 17.07684311 13.66492112 10.982917139.244962149.58060315 12.88085616 19.29600417 27.46265118 33.51215119 34.528305Name: SUNACTIVITY, dtype: float64
参考:
/pandas-docs/stable/reference/api/pandas.DataFrame.rolling.html
/pandas-docs/stable/reference/api/pandas.DataFrame.ewm.html
/pandas-docs/stable/reference/api/pandas.DataFrame.mean.html
如果觉得《时间序列分析 - 移动平均SMA EMA(EWMA) 之python》对你有帮助,请点赞、收藏,并留下你的观点哦!