体积加权移动平均线

时间:2017-04-06 14:32:51

标签: python python-2.7 python-3.x pandas

我有一个看起来像这样的DataFrame:

              LAST PRICE        VOLUME     volume_ratio
date                                                             
2005-01-03      1202.08     1.332210e+09       1.23       
2005-01-04      1188.05     1.552646e+09       1.55       
2005-01-05      1183.74     1.428365e+09       1.65         
2005-01-06      1187.89     1.331004e+09       1.23         
2005-01-07      1186.19     1.273960e+09       0.83        
2005-01-10      1190.25     1.213694e+09       1.06 

使用period = 5,我想计算VAMA = CumSum/CumDivCumSum = (df['volume_ratio']*df['LAST PRICE']).cumsum()的移动平均线CumDiv = df['volume_ratio'].cumsum(),条件为CumDiv <= Period

最初我认为使用expanding.sum()df.apply会起作用,但我正在努力;类似的东西:

cum_div = df['volume_ratio'].expanding(min_periods = 1).sum()
cum_summ = (df['LAST PRICE']*df['volume_ratio']).expanding(min_periods                =1).sum()

df['cum_sum'] = df.apply(lambda x: cum_summ if cum_div <= 13, axis = 1)

这显然不起作用,所以我对攻击它的最佳方式感兴趣。

提前致谢

2 个答案:

答案 0 :(得分:2)

仅使用rolling http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rolling.html

df['myrollingmean'] = df.VAMA.rolling(window = 5).mean()

答案 1 :(得分:0)

(df['LAST PRICE']*df['volume_ratio']).cumsum()\
        .div(df['volume_ratio'].cumsum()).rolling(window=5).mean()

条件为cumdiv&gt; = 5

(df['LAST PRICE']*df['volume_ratio']).cumsum()\
        .div(np.where(df['volume_ratio'].cumsum()<=5,df['volume_ratio'].cumsum(),np.nan))\
        .rolling(window=5).mean()