Join stock DataFrames and calculate returns
Our first step towards calculating modern portfolio theory (MPT) portfolios is to get daily and monthly returns. Eventually we're going to get the best portfolios of each month based on the Sharpe ratio. The easiest way to do this is to put all our stock prices into one DataFrame, then to resample them to the daily and monthly time frames. We need daily price changes to calculate volatility, which we will use as our measure of risk.
This exercise is part of the course
Machine Learning for Finance in Python
Exercise instructions
- Join together
lng_df
,spy_df
, andsmlv_df
usingpd.concat()
into thefull_df
DataFrame. - Resample the
full_df
to Business Month Start ('BMS'
) frequency. - Get the daily percent change of
full_df
with.pct_change()
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Join 3 stock dataframes together
full_df = pd.concat(____, axis=1).dropna()
# Resample the full dataframe to monthly timeframe
monthly_df = full_df.resample(____).first()
# Calculate daily returns of stocks
returns_daily = ____
# Calculate monthly returns of the stocks
returns_monthly = monthly_df.pct_change().dropna()
print(returns_monthly.tail())