liveBook · Manning

Covariance

As explained in Build a Robo-Advisor with Python (From Scratch)

Covariance is a measure of how two asset returns vary together, combining their volatilities with their correlation.

Covariance measures how two asset returns vary together by combining their volatilities with their correlation. It turns pairwise relationships into inputs for portfolio-risk calculations. section 2.2

For assets i and j, Cov(rᵢ,rⱼ) = σᵢσⱼ Corr(rᵢ,rⱼ). When i = j, covariance becomes the asset’s variance, so variances occupy the diagonal of a covariance matrix and pairwise covariances occupy its off-diagonal elements. section 2.2

Use covariance to calculate portfolio volatility:

  • Construct a covariance matrix from a correlation matrix and individual volatilities: Cov = diag(σ) @ Corr @ diag(σ). section 2.2
  • Combine asset weights with the matrix: σₚ = (wᵀΣw)¹ᐟ², equivalently the square root of the double sum of weighted covariances. section 2.2
  • Estimate covariances from historical returns with pandas; annualize daily covariance values by multiplying by 252. section 3.2.1

Three-asset covariance matrix

Given volatilities and correlations for three assets, the resulting matrix is [[0.0225, 0.003, 0.008925], [0.003, 0.04, 0.0182], [0.008925, 0.0182, 0.1225]]. Applying portfolio weights with w @ Cov @ w.T produces a portfolio standard deviation of 20.7%. section 2.2

Listing 2.3 Computing the covariance matrix from volatilities and correlations
Corr = [[ 1.  ,  0.1 ,  0.17],
        [ 0.1 ,  1.  ,  0.26],
        [ 0.17,  0.26,  1.  ]]

Cov = np.diag(sigma) @ Corr @ np.diag(sigma)  #1
print('Covariance matrix: \n', Cov)

Inspect the NumPy listing that converts volatilities and correlations into a covariance matrix. section 2.2

stock_returns.cov() * 252

Inspect the pandas expression that estimates an annualized covariance matrix from historical returns. section 3.2.1

How Build a Robo-Advisor with Python (From Scratch) covers it

How deep it goes
Explains formulas, matrix construction, portfolio aggregation, and historical estimation, but defers sophisticated time-varying volatility methods.
Examples
Uses three-asset NumPy matrices, weighted portfolio volatility, and AAPL, FE, and WMT historical covariance estimates.
What it assumes
Assumes familiarity with asset returns, volatility, correlation, portfolio weights, and basic matrix operations.
What you can do after
Apply covariance with NumPy or pandas to build covariance matrices and calculate portfolio standard deviation.
How it connects
Connects volatility, correlation, variance, covariance matrices, portfolio standard deviation, historical returns, and multifactor models.

Also explained in

Compare how 5 books explain covariance →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build a Robo-Advisor with Python (From Scratch). The section links point to the parts of the book it draws on.