pandas.DataFrame.ewm()
import pandas as pd
import numpy as np
df = pd.DataFrame([0.0, np.nan, 1.0, 2.0, np.nan, 3.0])
print(df)
0
0 0.0
1 NaN
2 1.0
3 2.0
4 NaN
5 3.0
print('span=2,ignore_na=False, adjust= True :\n', df.ewm(span=2,ignore_na=False, adjust= True).mean())
print('\n span=2,ignore_na=True, adjust= True :\n', df.ewm(span=2,ignore_na=True, adjust= True).mean())
- 忽略nan,就是从计算yt时候向前看,nan值不看,加权向历史走去
- 不忽略nan时候,nan处也付给权重,但是最后算的结果nan位置的权重被占掉了。
- 我们应该选择
ignore_na=True
合理一些。- nan数据的那个时刻的ewma由其前面历史数据计算得到,只有历史数据包括子自己全是nan,结果才是nan,这其实相当于是将平均的结果用其前面一个值填充!!!!
我们看下计算结果:
span=2,ignore_na=False, adjust= True :
0
0 0.000000
1 0.000000
2 0.900000
3 1.702703
4 1.702703
5 2.828571
span=2,ignore_na=True, adjust= True :
0
0 0.000000
1 0.000000
2 0.750000
3 1.615385
4 1.615385
5 2.550000
滑动平均ewa时如何计算的?
When
adjust=True
we have y0=x0 y 0 = x 0 and from the last representation above we have yt=αxt+(1−α)yt−1 y t = α x t + ( 1 − α ) y t − 1 , therefore there is an assumption that x0 x 0 is not an ordinary value but rather an exponentially weighted moment of the infinite series up to that point.
adjust=True
:
adjust=False
:
http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.ewm.html
http://pandas.pydata.org/pandas-docs/stable/computation.html#exponentially-weighted-windows