MulaiMulai sekarang secara gratis

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.

Latihan ini adalah bagian dari kursus

Machine Learning for Finance in Python

Lihat Kursus

Petunjuk latihan

  • 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().

Latihan interaktif praktis

Cobalah latihan ini dengan menyelesaikan kode contoh berikut.

# 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())
Edit dan Jalankan Kode