σμ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 4 · Calling it for real›Topic 4.2·~1 hr 30 minAdvanced

Capstone: a covariance and eigenvalue pipeline with a cost model

Skill positionModule 4 of 4 · Topic 2 of 2
4.2 Capstone: a covariance and eigenvalue pipeline with a cost model
—Lab score— / 100Total XP—Streak—
Lecture0% read

3 min readCode examples: 4

  1. 01The idea in plain words
  2. 02Real prices in, aligned returns out
  3. 03The covariance and its shape
  4. 04How the shape changes through the years
  5. 05Costing the rolling job
  6. 06What the tasks ask

At the end of 2009 the single biggest direction of five large stocks carried 80.4% of their variance, and the covariance matrix had a condition number of 45.7. In August 2026 the same direction carries 30.3% and the condition number is 3.7. Running that measurement for 6,447 rolling windows takes 0.043 seconds laid out well and 11.6 seconds laid out badly. How do you build, and cost, a job like that?

01

The idea in plain words

Where we are. This is the last topic, and it uses all the others. The stages of the job are the stages of the skill: the three BLAS levels set the cost of each step (topic 1), the covariance is a tiled dgemm (2), on data whose layout we state truthfully (3), with an eigen-decomposition (4) called the way production code does (5), whose answer we judge by its condition number (6), and the whole thing is spread over the cores (7) with a library chosen from a table (8) and reachable from C (9).

  • StageWhat it uses from the skill
  • load_returns_matrixPrices to returnsaligned dates, plain Python
  • covariance_matrixLevel 3 producttopic 1 and 2
  • eigen_reportEigen-decomposition and conditiontopics 4, 5 and 6
  • pipeline_reportCost on many corestopics 7 and 8
02

Real prices in, aligned returns out

The data folder holds the daily bars of AAPL, JPM, XOM, JNJ and KO. Each starts on a different day, so the first job is to keep only the dates all five share and turn the closes into simple returns. PATHS is the list of the five files.

main.pyPython
# Five price files in, one table of aligned daily returns outdates, rows = load_returns_matrix(PATHS)print(len(rows), "days of returns from", dates[0], "to", dates[-1], "|", len(rows[0]), "stocks")1print("last day:", [f"{r * 100:+.2f}%" for r in rows[-1]])
6696 days of returns from 2000-01-04 to 2026-08-21 | 5 stocks
last day: ['-0.63%', '+0.01%', '-0.63%', '+1.07%', '+0.66%']
  1. 16,696 days: the five files overlap from 4 January 2000, and every row has one return per stock.
03

The covariance and its shape

main.pyPython
# The covariance of the last 250 days: one dgemm, charged to the counterblas = Blas()cov = covariance_matrix(blas, rows[-250:])print("flops", blas.flops, "words", blas.words, "| flops per word", round(blas.intensity(), 2))1report = eigen_report(blas, cov)print("share of the variance, smallest to largest direction (%):", [round(s * 100, 1) for s in report["share"]])print("condition number:", round(report["condition"], 2), "| after the eigen step: flops", blas.flops)2print("largest direction (AAPL, JPM, XOM, JNJ, KO):", [round(v, 2) for v in report["top_vector"]])
flops 12500 words 2525 | flops per word 4.95
share of the variance, smallest to largest direction (%): [8.2, 16.3, 19.7, 25.5, 30.3]
condition number: 3.67 | after the eigen step: flops 12666
largest direction (AAPL, JPM, XOM, JNJ, KO): [0.64, 0.33, -0.68, -0.07, -0.08]
  1. 1The same 12,500 flops over 2,525 words as in the first topic: the product is cheap and its intensity is about five.
  2. 2A condition number under 4: the matrix is well conditioned, so its eigen-decomposition can be trusted to about 15 digits.
04

How the shape changes through the years

We repeat the measurement on the 250 days that end on the last trading day of selected years. When markets fall together, one direction (everything moving with the market) swallows the variance and the matrix becomes harder to work with.

main.pyPython
# The largest direction's share of the variance, and the condition number, at the end of selected yearslast_day = {}for position, date in enumerate(dates):    last_day[date[:4]] = positionfor year in ("2004", "2008", "2009", "2013", "2017", "2020", "2024"):    end = last_day[year]    window = covariance_matrix(Blas(), rows[end - 249:end + 1])    result = eigen_report(Blas(), window)    print(year, f"largest direction {result['share'][-1] * 100:5.1f}%   condition {result['condition']:5.1f}")1
2004 largest direction  62.5%   condition  10.6
2008 largest direction  64.7%   condition  39.5
2009 largest direction  80.4%   condition  45.7
2013 largest direction  46.9%   condition  10.2
2017 largest direction  39.2%   condition   5.0
2020 largest direction  70.8%   condition  27.7
2024 largest direction  35.7%   condition   6.4
  1. 12009 and 2020 stand out: in a crash the stocks fall together, one direction holds 71 to 80% of the risk, and the condition number is 5 to 9 times that of calm years like 2017.
05

Costing the rolling job

A window is 12,666 flops, tiny, and the job has 6,447 of them. Topic 7 already told us what to do with many small independent jobs: one single-threaded worker per core. pipeline_report runs the layout search and compares it with the naive choice of 8 workers that each ask for 8 threads.

main.pyPython
# What the rolling job costs on an 8-core machine (4 billion flops per second per core, 50 microseconds per thread)windows = len(rows) - 249report = pipeline_report(windows, 5, 250, 8, 4e9, 5e-5)print("flops per window:", report["flops_per_window"], "| total:", f"{report['flops_per_window'] * windows:.3g}")print("best layout (workers, threads):", report["layout"], "->", round(report["seconds"], 4), "s")print("8 workers x 8 threads:", round(report["naive_seconds"], 2), "s |", round(report["speedup"]), "times slower")1print("one thread, one worker:", round(batch_time(windows, report["flops_per_window"], 1, 1, 8, 4e9, 5e-5), 3), "s")
flops per window: 12666 | total: 8.17e+07
best layout (workers, threads): (8, 1) -> 0.0429 s
8 workers x 8 threads: 11.62 s | 271 times slower
one thread, one worker: 0.343 s
  1. 1The best layout is 8 single-threaded workers. A naive 64 threads on 8 cores takes 271 times longer, as topic 7 predicted.
The rolling job on five stocks6,447 windows of 250 days, 8 cores
One window12,666flops: 12,500 + 166
Best layout8 × 10.043 s in all
Naive layout8 × 811.6 s: 271 times slower
Top direction 2009 / now80.4 / 30.3%condition 45.7 / 3.7
Seconds for the whole job
8 workers x 1 thread0.043
1 worker x 1 thread0.343
1 worker x 8 threads2.581
8 workers x 8 threads11.62
Turn the model into a measurement

The cost model tells you where to look, not what the clock will say. On a real machine, run the covariance and eigen steps from NumPy for a few windows with OMP_NUM_THREADS set to 1 and to the number of cores, in one worker and in several, and keep the layout that is fastest. The shape of the answer (many small jobs favour many single-threaded workers) is robust; the exact numbers are not.

06

What the tasks ask

  1. 1
    `load_returns_matrix`Read the files by column name with csv.DictReader, keep the common dates, and return the dates and the table of simple returns.
  2. 2
    `covariance_matrix` and `eigen_report`The covariance from one dgemm after removing the means and dividing by T − 1, and the report built from eigh: values, shares of variance, the top eigenvector and the condition number.
  3. 3
    `pipeline_report`Cost the rolling job with the threading model: flops per window, the best layout, the seconds it takes and what the naive layout would cost.

Key takeaways

  • Cost first, then optimise Counting flops and words, and modelling the threads, tells you what a job should cost before you run it.
  • Trust is part of the result Ship the condition number with the eigenvalues. In a crash the matrix gets harder, exactly when you need it most.
  • You have the whole chain From a flop count to a C call, a solver you can trust and a layout for the cores. The same ideas carry over to sparse matrices, GPU libraries and MKL.
Quick check
You must compute a 250-day covariance matrix of 5 stocks for 6,000 rolling windows on an 8-core machine. Which layout does the model prefer?
Pick an answer.

Lab · what's graded

4 tasks · 100 pts
  • Load aligned returns with load_returns_matrix25 pts
  • Build the covariance with covariance_matrix25 pts
  • Describe it with eigen_report25 pts
  • Cost the job with pipeline_report25 pts
Explorer · lab-10-1
▾ lab-10-1
▾ data
…
bash · in-browser
learner@quantcraft:~/lab-10-1$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

Everything in lab-10-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