0

i am trying to get a balance column in a python dataframe with an initial static value.

The logic:

start balance = 1000

current balance = previous current balance*(1+df['return'])

My attempt:

df.at[1,'current balance'] = 1000
df['current balance'] = df['current balance'].shift(1)*(1+df['return])

I can't get this output

Output dataframe:

return  current balance
0.01    1010.00
0.03    1040.30
0.045   1087.11
Vince
  • 507
  • 8
  • 21
  • https://stackoverflow.com/questions/34855859/is-there-a-way-in-pandas-to-use-previous-row-value-in-dataframe-apply-when-previ – QWERTYL Nov 20 '22 at 18:19
  • 1
    @QWERTYL: there is no obvious vectorized solution for the question you link, whereas there is one here. Not the same question at all. – Pierre D Nov 21 '22 at 19:18

2 Answers2

1

Standard compound return:

initial_balance = 1000
df['current balance'] = (1 + df['return']).cumprod() * initial_balance

>>> df
   return  current balance
0   0.010        1010.0000
1   0.030        1040.3000
2   0.045        1087.1135
Pierre D
  • 24,012
  • 7
  • 60
  • 96
1

I would approach this by getting my df columns ready in lists and then add those rather than changing values in the df itself.

There's probably a more elegant solution but this should work:

df_return = [0.00, 0.01, 0.03, 0.045]
df_current_balance = [1000]
# Calculate the current value for each return value
for x in range(1, len(df_return)):
    df_current_balance.append(df_current_balance[x - 1] * (1 + df_return[x]))

output = {"return": df_return[1:], "current balance": df_current_balance[1:]}

df = pd.DataFrame(output)
MDavidson
  • 67
  • 2