← back

Calculate Portfolio Variance

#183 · Financial ML · Easy

⊣ Solve on deep-ml.com

Problem

Calculate the Portfolio Variance for a portfolio of assets given their individual weights, variances, and the covariance matrix. Portfolio variance measures the total risk of a weighted combination of assets.

Solution

1
2
3
4
import numpy as np

def portfolio_variance(weights: np.ndarray, cov_matrix: np.ndarray) -> float:
    return float(weights @ cov_matrix @ weights)

Explanation

  1. Portfolio variance is w^T * Sigma * w where w is the weight vector and Sigma is the covariance matrix.
  2. This accounts for both individual asset variances (diagonal of Sigma) and pairwise covariances (off-diagonal).
  3. Diversification benefit: if assets are not perfectly correlated, portfolio variance is less than the weighted sum of individual variances.
  4. Example: for two assets with weights [0.6, 0.4], variances [0.04, 0.09], and correlation 0.5, the covariance matrix is [[0.04, 0.03], [0.03, 0.09]], and portfolio variance is 0.6^20.04 + 20.60.40.03 + 0.4^2*0.09 = 0.0432.

Complexity

  • Time: O(n^2) where n is the number of assets (matrix-vector multiplication)
  • Space: O(1) beyond the inputs