[英]python pandas portfolio return
I've got a dataframe with market data and one column dedicated to daily returns. 我有一个包含市场数据的数据框和一个专门用于每日收益的列。 I'm having a hard time creating a portfolio to start at $100,000.00 in value, and compute its cumulative return through the life of the data series. 我很难创建一个起价为$ 100,000.00的投资组合,并计算其在整个数据系列中的累计回报。
Ideally, I'd like to compute the 'portfolio' column using pandas but I'm having trouble doing so. 理想情况下,我想使用熊猫来计算“投资组合”列,但是这样做很麻烦。 See below target output. 参见下面的目标输出。 Thank you. 谢谢。
index date index return portfolio
0 19900101 2000 Nan 100000.00
1 19900102 2002 0.001 100100.00
2 19900103 2020 0.00899 100999.90
3 19900104 2001 -0.00941 100049.49
By using cumprod
通过使用cumprod
df['P']=df['return'].add(1).fillna(1).cumprod()*100000
df
Out[843]:
index date index.1 return portfolio P
0 0 19900101 2000 NaN 100000.00 100000.00000
1 1 19900102 2002 0.00100 100100.00 100100.00000
2 2 19900103 2020 0.00899 100999.90 100999.89900
3 3 19900104 2001 -0.00941 100049.49 100049.48995
Some adjustments: 一些调整:
df=df.replace('Nan',np.nan)
df['return']=pd.to_numeric(df['return'])
starting_value = 100000
df = df.assign(portfolio=(1 + df['return'].fillna(0)).cumprod().mul(starting_value))
>>> df
index date index.1 return portfolio
0 0 19900101 2000 NaN 100000.00000
1 1 19900102 2002 0.00100 100100.00000
2 2 19900103 2020 0.00899 100999.89900
3 3 19900104 2001 -0.00941 100049.48995
To visualize what is happening, cumprod
is calculating compounded returns, eg cum_r3 = (1 + r1) * (1 + r2) * (1 + r3)
. 为了可视化正在发生的事情, cumprod
正在计算复合收益,例如cum_r3 = (1 + r1) * (1 + r2) * (1 + r3)
。
>>> (1 + df['return'].fillna(0)).cumprod()
0 1.000000
1 1.001000
2 1.009999
3 1.000495
Name: return, dtype: float64
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.