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
CodePudding user response:
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
CodePudding user response:
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)