There's more...

We will also discuss how to account for inflation in the returns series. To do so, we continue with the example used in this recipe.

We first download the monthly Consumer Price Index (CPI) values from Quandl and calculate the percentage change (simple return) in the index. We can then merge the inflation data with Apple's stock returns, and account for inflation by using the following formula:

Here, Rt is a time t simple return and is the inflation rate.

Execute the following steps to account for inflation in the returns series.

  1. Import libraries and authenticate:
import pandas as pd
import quandl

QUANDL_KEY = '{key}'
quandl.ApiConfig.api_key = QUANDL_KEY

  1. Create a DataFrame with all possible dates, and left join the prices to it:
df_all_dates = pd.DataFrame(index=pd.date_range(start='1999-12-31', 
end='2010-12-31'))
df = df_all_dates.join(df[['adj_close']], how='left')
.fillna(method='ffill')
.asfreq('M')

We used a left join, which is a type of join (used for merging DataFrames) that returns all rows from the left table and the matched rows from the right table while leaving the unmatched rows empty. In case the last day of the month was not a trading day, we used the last known price of that month (fillna(method='ffill')). Lastly, we selected the end-of-month rows only by applying asfreq('M').

  1. Download the inflation data from Quandl:
df_cpi = quandl.get(dataset='RATEINF/CPI_USA', 
start_date='1999-12-01',
end_date='2010-12-31')
df_cpi.rename(columns={'Value':'cpi'}, inplace=True)
  1. Merge the inflation data to the prices:
df_merged = df.join(df_cpi, how='left')
  1. Calculate the simple returns and inflation rate:
df_merged['simple_rtn'] = df_merged.adj_close.pct_change()
df_merged['inflation_rate'] = df_merged.cpi.pct_change()
  1. Adjust the returns for inflation:
df_merged['real_rtn'] = (df_merged.simple_rtn + 1) / (df_merged.inflation_rate + 1) - 1

The output looks as follows:

The DataFrame contains all the intermediate results, and the real_rtn column contains the inflation-adjusted returns.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.247.5