CommencerCommencer gratuitement

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.

Cet exercice fait partie du cours

Machine Learning for Finance in Python

Afficher le cours

Instructions

  • Join together lng_df, spy_df, and smlv_df using pd.concat() into the full_df DataFrame.
  • Resample the full_df to Business Month Start ('BMS') frequency.
  • Get the daily percent change of full_df with .pct_change().

Exercice interactif pratique

Essayez cet exercice en complétant cet exemple de 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())
Modifier et exécuter le code