时间序列分析 - 移动平均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为例,其窗口形状为钟型,曲线函数为:

w(n)=0.5(1-cos(\frac{2\pi n}{N-1}))

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

  • 2
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值