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.
This exercise is part of the course
Machine Learning for Finance in Python
Exercise instructions
- Loop through the index of
returns_monthly
. - Create a mask for
returns_daily
which uses the current month and year fromreturns_monthly
, and matches this to the current month and year fromi
in the loop. - Use the mask on
returns_daily
and calculate covariances using.cov()
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Daily covariance of stocks (for each monthly period)
covariances = {}
rtd_idx = returns_daily.index
for i in returns_monthly.____:
# Mask daily returns for each month and year, and calculate covariance
mask = (rtd_idx.month == i.month) & (rtd_idx.____ == i.____)
# Use the mask to get daily returns for the current month and year of monthy returns index
covariances[i] = returns_daily[____].cov()
print(covariances[i])