One - One Code All

Blog Content

用pandas datafram计算累积收益cumprod

Python 统计学-科学计算   2016-06-21 21:38:33

方案1:

如果它们是每日简单回报,而您想要累积回报,那么您肯定需要每日复合数字?

df['perc_ret'] = (1 + df.Daily_rets).cumprod() - 1  # Or df.Daily_rets.add(1).cumprod().sub(1)

如果它们是日志返回,那么可以使用cumsum。

如果性能很重要,请使用:

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


方案2:


你不能简单地用cumsum把它们加起来

例如,如果你有数组[1.1,1.1],你应该有2.21,而不是2.2

import numpy as np
# daily return:
df['daily_return'] = df['close'].pct_change()
# calculate cumluative return
df['cumluative_return'] = np.exp(np.log1p(df['daily_return']).cumsum())


参考:https://stackoverflow.com/questions/35365545/calculating-cumulative-returns-with-pandas-dataframe



上一篇:Python中虚拟环境venv的基本用法
下一篇:python测试用例覆盖率工具coverage教程(命令行工具)

The minute you think of giving up, think of the reason why you held on so long.