Issue
I'm trying to figure out how to project a percent variation change on a given starting amount.
To be clear, I have a dataframe which contains for each date the daily percent change. I would like to apply this percent change on a starting value in this case 100 to see its evolution over time. I have already customized the daily variation to ease the calculation as follow: Customized variation = 1 + Daily Variation/100
Amount at 100 (first row last columns is given) and this is the columns I can't find the formula to get the result
I have tried many way with Pandas but it looks like it doesn't want to execute the shift on Amount columns.
I pass to my function a Pandas Serie containing the date and the daily variation in percent.
Then I calculate the daily Var customised as follow:
df_col_actif_var['daily_var_custo'] = (1 + df_col_actif_var/100)
And finally I try to build up the last column containing the expected results:
df_col_actif_var['std'] = df_col_actif_var['std'].shift(1) * (df_col_actif_var['daily_var_custo'])
But doesn't works
Please Help !
Solution
IIUC, you can use:
df['Amount'] = (df['Daily Variation']
.shift(-1).cumsum()
.add(100).shift(1, fill_value=100))
print(df)
# Output
Date Daily Variation Customized Variation Amount
0 Day 1 -0.75 0.9925 100.00
1 Day 2 1.02 1.1020 101.02
2 Day 3 -0.19 0.9981 100.83
3 Day 4 -0.42 0.9958 100.41
4 Day 5 -0.53 0.9947 99.88
Step by step:
# shift to remove -0.75
>>> out = df['Daily Variation'].shift(-1)
0 1.02
1 -0.19
2 -0.42
3 -0.53
4 NaN
# compute cumulative sum
>>> out = out.cumsum()
0 1.02
1 0.83
2 0.41
3 -0.12
4 NaN
# add your base value 100
>>> out = out.add(100)
0 101.02
1 100.83
2 100.41
3 99.88
4 NaN
# shift back to align values and fill the first row to your base value
>>> out = out.shift(1, fill_value=100)
0 100.00
1 101.02
2 100.83
3 100.41
4 99.88
Another way to do it but I prefer to chain methods :-). However the math is much more simpler.
df['Amount'] = df.loc[1:, 'Daily Variation']
df.loc[0, 'Amount'] = 100
df['Amount'] = df['Amount'].cumsum()
Answered By - Corralien
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.