Session Ready
Exercise

Calculate covariances for volatility

In MPT, we quantify risk via volatility. The math for calculating portfolio volatility is complex, and it requires daily returns covariances. We'll now loop through each month in the returns_monthly DataFrame, and calculate the covariance of the daily returns.

With pandas datetime indices, we can access the month and year with df.index.month and df.index.year. We'll use this to create a mask for returns_daily that gives us the daily returns for the current month and year in the loop. We then use the mask to subset the DataFrame like this: df[mask]. This gets entries in the returns_daily DataFrame which are in the current month and year in each cycle of the loop. Finally, we'll use pandas' .cov() method to get the covariance of daily returns.

Instructions
100 XP
  • Loop through the index of returns_monthly.
  • Create a mask for returns_daily which uses the current month and year from returns_monthly, and matches this to the current month and year from i in the loop.
  • Use the mask on returns_daily and calculate covariances using .cov().