A covariance matrix is only worth having if you can ask it questions: which mix of five stocks has the least risk, how much of one stock's move do the other four explain, which direction do all five move together most? Each question is one LAPACK call, and each costs a different amount.
The idea in plain words
Where we are. The first three topics were about BLAS: what its calls cost, how a tiled product keeps the cache happy, and how a matrix is laid out in memory for a call. Now we use those pieces. LAPACK is the library of *recipes* built on top of BLAS: each routine, called a driver, solves a complete problem. The next topic calls these drivers the way real code does, through a function that returns an error code.
- DriverThe question it answers
- gesvSolve A x = bLU with pivotingabout 2n³/3 flops
- gelsMinimise |A x − b| (regression)QR by reflectionsabout 2mn² flops
- syevEigenvalues of a symmetric matrixrotations or tridiagonal forma few n³ flops
- gesvdSingular values and vectors of any matrixsame family as syevthe most expensive of the four
Solving a system: the safest portfolio
The mix of the five stocks with the smallest variance has weights proportional to the solution of Σ w = 1, where Σ is the covariance matrix and 1 a vector of ones. This is a square system, so it is a job for LU. The routine gesv does two things: it factors the matrix once (the expensive part) and then solves by substitution (the cheap part). We keep them as two functions because the factors can be reused for many right-hand sides.
# Minimum-variance weights: factor the covariance matrix once, then solve cov w = 1blas = Blas()lu, piv = lu_factor(blas, cov)print("factor: flops", blas.flops, "words", blas.words, "| row swaps:", [i for i, p in enumerate(piv) if i != p])1raw = lu_solve(blas, lu, piv, [1.0] * 5)weights = [x / sum(raw) for x in raw]print("solve: flops", blas.flops, "words", blas.words, "in total")2print("weights:", [round(w, 3) for w in weights])risk = sum(weights[i] * cov[i][j] * weights[j] for i in range(5) for j in range(5))print("yearly volatility:", round((risk * 252) ** 0.5 * 100, 2), "% (equal weights: 11.03 %)")
factor: flops 70 words 50 | row swaps: [] solve: flops 115 words 85 in total weights: [0.147, 0.242, 0.176, 0.199, 0.236] yearly volatility: 10.92 % (equal weights: 11.03 %)
- 170 flops for the factorisation of a 5 by 5 matrix; it grows as n³.
- 2The solve adds only 45 more: this half grows as n², so it is cheap to repeat.
It is tempting to compute the inverse of Σ and multiply. Do not: an inverse costs about three times the factorisation and is less accurate. When you need Σ⁻¹ b, factor once and call the solve step.
Fitting a regression: how much do the others explain?
The second question has more rows than unknowns: 250 days, four explaining stocks. There is no exact solution, so gels finds the coefficients that make the leftover as small as possible, with the Householder method. It never forms XᵀX at all, which keeps the answer accurate when columns are similar.
# Regress AAPL's daily return on JPM, XOM, JNJ and KO (the columns of X are AAPL, JPM, XOM, JNJ, KO)others = [[row[j] for j in range(1, 5)] for row in X]aapl = [row[0] for row in X]beta = gels(others, aapl)fitted = [sum(beta[j] * row[j] for j in range(4)) for row in others]leftover = sum((a - f) ** 2 for a, f in zip(aapl, fitted))print("betas on JPM, XOM, JNJ, KO:", [round(b, 3) for b in beta])print("share of AAPL's variance explained:", round(1 - leftover / sum(a * a for a in aapl), 3))1
betas on JPM, XOM, JNJ, KO: [0.194, -0.133, 0.003, 0.207] share of AAPL's variance explained: 0.064
- 1Only 6% of the daily variance of AAPL is explained by the four others in the last year: the leftover is mostly its own news.
Finding the directions: eigenvalues
The third question asks which combinations of the five stocks carry the most variance. The answer is the eigenvectors of Σ, each with an eigenvalue that is the variance along that direction. syev is for symmetric matrices like Σ. The related gesvd returns the singular values of any matrix, such as X itself: they are the square roots of the eigenvalues of XᵀX.
# The variance along each direction of the covariance matrix, and the biggest directionvalues, vectors = syev(cov)total = sum(values)print("eigenvalues (e-4):", [round(v * 1e4, 2) for v in values])print("share of total variance:", [round(v / total * 100, 1) for v in values], "%")top = [row[4] for row in vectors]print("biggest direction (AAPL, JPM, XOM, JNJ, KO):", [round(t, 2) for t in top])1
eigenvalues (e-4): [0.81, 1.6, 1.94, 2.51, 2.99] share of total variance: [8.2, 16.3, 19.7, 25.5, 30.3] % biggest direction (AAPL, JPM, XOM, JNJ, KO): [0.64, 0.33, -0.68, -0.07, -0.08]
- 1The biggest direction mixes AAPL and JPM against XOM; with five loosely related stocks no single factor dominates, it explains 30%.
What the tasks ask
- 1`lu_factor` and `lu_solve`Factor with the largest-entry pivot in each column, keep the multipliers below the diagonal, then solve by two substitutions. Both charge the exact counts above and reject a singular matrix or wrong shapes before counting.
- 2`gels`Reflect each column to zero below the diagonal, applying the same reflections to b, then go up the triangle. The tests check that the leftover is perpendicular to every column.
- 3`syev`Rotate away the off-diagonal entries pair by pair until the matrix is diagonal, then return the eigenvalues sorted with the vectors reordered to match.
Σ w = b for 1,000 different vectors b with the same matrix Σ. What is the cheapest plan?Lab · what's graded
4 tasks · 100 pts- Factor with
lu_factor25 pts - Solve with
lu_solve25 pts - Fit least squares with
gels25 pts - Find eigenvalues with
syev25 pts