brooks08
brooks08

Reputation: 39

Calculate a running return in pandas df

I have a df with daily return rates. 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

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. How can I create this new calculation multiplying rate* the prior row's value?

Upvotes: 0

Views: 566

Answers (1)

Yilun Zhang
Yilun Zhang

Reputation: 9018

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
``

Upvotes: 1

Related Questions