时间序列分析 - 移动平均SMA, EMA(EWMA) 之python
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 plt
import statsmodels.api as sm
data_loader = sm.datasets.sunspots.load_pandas()
df = data_loader.data
print("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"].values
plt.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 309
inital df head:
YEAR SUNACTIVITY
0 1700.0 5.0
1 1701.0 11.0
2 1702.0 16.0
3 1703.0 23.0
4 1704.0 36.0
5 1705.0 58.0
6 1706.0 29.0
7 1707.0 20.0
8 1708.0 10.0
9 1709.0 8.0
10 1710.0 3.0
11 1711.0 0.0
12 1712.0 0.0
13 1713.0 2.0
14 1714.0 11.0
15 1715.0 27.0
16 1716.0 47.0
17 1717.0 63.0
18 1718.0 60.0
19 1719.0 39.0
SMA head:
0 NaN
1 NaN
2 NaN
3 NaN
4 NaN
5 NaN
6 NaN
7 NaN
8 NaN
9 21.6
10 21.4
11 20.3
12 18.7
13 16.6
14 14.1
15 11.0
16 12.8
17 17.1
18 22.1
19 25.2
Name: SUNACTIVITY, dtype: float64
EMA head:
0 NaN
1 NaN
2 NaN
3 NaN
4 NaN
5 NaN
6 NaN
7 NaN
8 NaN
9 20.690866
10 17.076843
11 13.664921
12 10.982917
13 9.244962
14 9.580603
15 12.880856
16 19.296004
17 27.462651
18 33.512151
19 34.528305
Name: SUNACTIVITY, dtype: float64
参考:
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.rolling.html
http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.ewm.html
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.mean.html