Let's say I have a day over day growth rate data as follows, in which the initial values are unknown to us:
date dod_change
0 2020-1-1 0.262713
1 2020-1-2 0.216778
2 2020-1-3 0.217069
3 2020-1-4 0.268117
4 2020-1-5 0.341397
.. ... ...
660 2021-10-22 0.579067
661 2021-10-23 0.616211
662 2021-10-24 0.680849
663 2021-10-25 0.718568
664 2021-10-26 0.682004
Obviously, the logic of calculation of dod_change is current_day_value/previous_day_value - 1, ie., for 2020-1-1's dod_change=0.262713 is calculate by the (initial value of 2020-1-1)/(initial value of 2019-12-31) - 1
Now I wonder if it's possible to write a function to calculate an approximate daily year over year's growth rate based on dod_change? For example, we could set the initial value for 2019-12-31 as 100, then calculate each day's approximate initial value, then apply function below to get yoy data:
def calculate_daily_yoy(x):
do = pd.DateOffset(years = 1)
x_yoy = x.pct_change(freq = do)
return pd.DataFrame(x_yoy, columns=x.columns)
But I dont't know how to write a function to calculate the initial value for each day, anyone could help? Sincere thanks.
To generate example data for testing:
import pandas as pd
import numpy as np
np.random.seed(2021)
df = pd.DataFrame({'date': pd.date_range('2015', periods = 720, freq = 'D'),
'dod_change1': np.random.uniform(-0.5, 0.5, size = 720),
'dod_change2': np.random.uniform(-0.1, 0.1, size = 720)})
print(df)
Out:
date dod_change1 dod_change2
0 2015-01-01 0.105978 0.046144
1 2015-01-02 0.233369 -0.042252
2 2015-01-03 -0.361053 -0.072793
3 2015-01-04 -0.187327 -0.070694
4 2015-01-05 0.497243 0.054125
.. ... ... ...
715 2016-12-16 -0.180490 -0.049211
716 2016-12-17 -0.349578 0.034892
717 2016-12-18 0.312242 -0.099226
718 2016-12-19 -0.153010 0.095887
719 2016-12-20 -0.347153 -0.036274
[720 rows x 3 columns]
Reference: