2017-04-06 113 views
1

我有一個數據幀,看起來像:成交量加權移動平均線

   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/CumDiv其中CumSum = (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) 

這顯然是不行的,所以我很感興趣,進攻是最好的方法。

在此先感謝

+0

你有輸出來驗證? –

回答

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

與cumdiv的條件> = 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()