Calculating cumulative returns with pandas dataframe

前端 未结 3 978

I have this dataframe

Poloniex_DOGE_BTC   Poloniex_XMR_BTC    Daily_rets  perc_ret
172 0.006085    -0.000839   0.003309    0
173 0.006229    0.002111    0.005135         


        
3条回答
  •  囚心锁ツ
    2021-02-02 16:47

    If performance is important, use numpy.cumprod:

    np.cumprod(1 + df['Daily_rets'].values) - 1
    

    Timings:

    #7k rows
    df = pd.concat([df] * 1000, ignore_index=True)
    
    In [191]: %timeit np.cumprod(1 + df['Daily_rets'].values) - 1
    41 µs ± 282 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
    
    In [192]: %timeit (1 + df.Daily_rets).cumprod() - 1
    554 µs ± 3.63 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
    

提交回复
热议问题