import pandas_datareader.data as web
import pandas as pd
import numpy as np
import datetime as dt
# SET START AND END DATES OF THE SERIES
sdt = dt.datetime(2019, 1, 1)
edt = dt.datetime(2021, 9, 1)
cpi = web.DataReader("CPIAUCNS", "fred", sdt, edt)
df1 = pd.DataFrame({'month': [dt.datetime.strftime(i, "%Y-%m") for i in cpi.index]})
df1['qtr'] = [str(x.year) + "-Q" + str(x.quarter) for x in cpi.index]
df1['m_cpi'] = cpi.values
df1.index = cpi.index
grp = df1.groupby('qtr', as_index = False)
df2 = grp['m_cpi'].agg({'q_cpi': np.mean})
df3 = pd.merge(df1, df2, how = 'inner', left_on = 'qtr', right_on = 'qtr')
maxm_cpi = np.array(df3.m_cpi)[-1]
maxq_cpi = np.array(df3.q_cpi)[-1]
df3['m_factor'] = maxm_cpi / df3.m_cpi
df3['q_factor'] = maxq_cpi / df3.q_cpi
df3.index = cpi.index
final = df3.sort_index(ascending = False)
final.head()