σμimplied vol · KKmax(S−K,0)udβρᵢⱼfat tailsPnL · drawdownyield · TdSₜ = μSₜ dt + σSₜ dWₜC = S·N(d₁) − K·e⁻ʳᵀ·N(d₂)σₚ² = wᵀΣwd₁ = [ln(S/K) + (r + σ²⁄2)T] ⁄ σ√T∂V/∂t + ½σ²S²·∂²V/∂S² + rS·∂V/∂S − rV = 0Sharpe = (Rₚ − R_f) ⁄ σₚVaR₉₉ = μ − 2.33σρ = Cov(X,Y) ⁄ σₓσᵧE[Rₚ] = Σ wᵢ·E[Rᵢ]φ(x) = e^(−x²/2) ⁄ √2πE[Rᵢ] = R_f + βᵢ(E[Rₘ] − R_f)dXₜ = θ(μ − Xₜ)dt + σ dWₜσ²ₜ = ω + α·ε²ₜ₋₁ + β·σ²ₜ₋₁C − P = S − K·e⁻ʳᵀΔ = ∂V/∂S Γ = ∂²V/∂S²p = (e^(rΔt) − d) ⁄ (u − d)rₜ = ln(Pₜ ⁄ Pₜ₋₁)E[Xₜ₊₁ | ℱₜ] = Xₜf* = (bp − q) ⁄ bz = (x − μ) ⁄ σP(N=k) = λᵏe^(−λ) ⁄ k!Θ = −∂V/∂Tν = S·φ(d₁)·√Tmin wᵀΣw s.t. wᵀμ = μ*∫Σ∂∞λ
uantCraft AcademyRoadmapsSkills
Ctrl K
AO
+1.2k Learners
LoginJoin ↗
RoadmapsSkills
AO
+1.2k Learners
Login
  • English
  • Français
  • Español
  • العربية
  • Português
  • Deutsch
  • 日本語
  • 中文
σμimplied vol · KKmax(S−K,0)udβρᵢⱼfat tailsPnL · drawdownyield · TdSₜ = μSₜ dt + σSₜ dWₜC = S·N(d₁) − K·e⁻ʳᵀ·N(d₂)σₚ² = wᵀΣwd₁ = [ln(S/K) + (r + σ²⁄2)T] ⁄ σ√T∂V/∂t + ½σ²S²·∂²V/∂S² + rS·∂V/∂S − rV = 0Sharpe = (Rₚ − R_f) ⁄ σₚVaR₉₉ = μ − 2.33σρ = Cov(X,Y) ⁄ σₓσᵧE[Rₚ] = Σ wᵢ·E[Rᵢ]φ(x) = e^(−x²/2) ⁄ √2πE[Rᵢ] = R_f + βᵢ(E[Rₘ] − R_f)dXₜ = θ(μ − Xₜ)dt + σ dWₜσ²ₜ = ω + α·ε²ₜ₋₁ + β·σ²ₜ₋₁C − P = S − K·e⁻ʳᵀΔ = ∂V/∂S Γ = ∂²V/∂S²p = (e^(rΔt) − d) ⁄ (u − d)rₜ = ln(Pₜ ⁄ Pₜ₋₁)E[Xₜ₊₁ | ℱₜ] = Xₜf* = (bp − q) ⁄ bz = (x − μ) ⁄ σP(N=k) = λᵏe^(−λ) ⁄ k!Θ = −∂V/∂Tν = S·φ(d₁)·√Tmin wᵀΣw s.t. wᵀμ = μ*∫Σ∂∞λ
uantCraft AcademyRoadmapsSkills
Ctrl K
AO
+1.2k Learners
LoginJoin ↗
RoadmapsSkills
AO
+1.2k Learners
Login
  • English
  • Français
  • Español
  • العربية
  • Português
  • Deutsch
  • 日本語
  • 中文
BLAS and LAPACK skill›Module 2 · Solving and decomposing›Topic 2.1·~55 minAdvanced

LAPACK drivers for solving and decomposing

Skill positionModule 2 of 4 · Topic 1 of 3
2.1 LAPACK drivers for solving and decomposing
—Lab score— / 100Total XP—Streak—
Lecture0% read

3 min readCode examples: 3

  1. 01The idea in plain words
  2. 02Solving a system: the safest portfolio
  3. 03Fitting a regression: how much do the others explain?
  4. 04Finding the directions: eigenvalues
  5. 05What the tasks ask

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.

01

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
02

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.

main.pyPython
# 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 %)
  1. 170 flops for the factorisation of a 5 by 5 matrix; it grows as n³.
  2. 2The solve adds only 45 more: this half grows as n², so it is cheap to repeat.
Solve; do not invert

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.

03

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.

main.pyPython
# 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
  1. 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.
04

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.

main.pyPython
# 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]
  1. 1The biggest direction mixes AAPL and JPM against XOM; with five loosely related stocks no single factor dominates, it explains 30%.
Cost of one 5 by 5 problemCounted by lu_factor and lu_solve
Factor (flops)70grows as n³
Solve (flops)45grows as n²
Minimum-variance volatility10.92%equal weights: 11.03
Biggest eigen-direction30.3%of total variance
05

What the tasks ask

  1. 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. 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. 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.

Key takeaways

  • One question, one driver Square systems use LU, regressions use QR, symmetric matrices use eigen routines. Pick by the question, not by habit.
  • Factor once, solve many times The factorisation grows as n³ and each solve as n², so reuse the factors and never form an inverse.
  • Drivers return answers, but how far to trust them? Next: calling these routines the way real code does, and reading the error code they return. Two topics later: conditioning.
Quick check
You must solve Σ w = b for 1,000 different vectors b with the same matrix Σ. What is the cheapest plan?
Pick an answer.

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
Explorer · lab-4-1
▾ lab-4-1
…
bash · in-browser
learner@quantcraft:~/lab-4-1$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

Everything in lab-4-1 goes back to the starter files and the terminal is cleared. Your current solution will be lost — this can't be undone.

Will be reset
  • main.py → starter code
  • Terminal history and test output
  • Unsubmitted changes
Will be kept
  • Best lab score
  • Your XP and streak
  • Lecture progress and notes