简体   繁体   English

计算 pandas df 中的运行回报

[英]Calculate a running return in pandas df

I have a df with daily return rates.我有一个每日退货率的 df。 I inserted a column to start with an initial investment of $100 for day 1. I'm trying to calculate the running return each day as below我插入了一个列,从第 1 天的初始投资 100 美元开始。我正在尝试计算每天的运行回报,如下所示

import pandas as pd

d = {'day': [1, 2, 3], 'return': [1.00, 1.04, 1.02], 'init_invest': [100, 0, 0]}
df = pd.DataFrame(data=d)

Let's call the new column "value" In this example, I'd like to see让我们将新列称为“值”在这个例子中,我想看看

Day 1 value = 100 x 1.00 = 100
Day 2 value = 100 x 1.04 = 104
Day 3 value = 104 x 1.02 = 106.08

At first I thought I needed to use shift here, but that hasn't worked out.起初我以为我需要在这里使用 shift ,但这并没有成功。 How can I create this new calculation multiplying rate* the prior row's value?我怎样才能创建这个新的计算乘率*前一行的值?

For your case, since you know all the returns, you can use that directly for calculation.对于你的情况,因为你知道所有的回报,你可以直接用它来计算。

Day 1 value is given.
Day 2 value = day 1 value * 1.04 = 104
Day 3 value = day 1 value * 1.04 * 1.02 = 106.08

df["init_invest"] = df["return"].cumprod() * df["init_invest"].iloc[0]

   day  return  init_invest
0    1    1.00       100.00
1    2    1.04       104.00
2    3    1.02       106.08
``

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM