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?
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
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.
# 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%']
- 16,696 days: the five files overlap from 4 January 2000, and every row has one return per stock.
The covariance and its shape
# 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]
- 1The same 12,500 flops over 2,525 words as in the first topic: the product is cheap and its intensity is about five.
- 2A condition number under 4: the matrix is well conditioned, so its eigen-decomposition can be trusted to about 15 digits.
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.
# 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
- 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.
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.
# 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
- 1The best layout is 8 single-threaded workers. A naive 64 threads on 8 cores takes 271 times longer, as topic 7 predicted.
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.
What the tasks ask
- 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`covariance_matrix` and `eigen_report`The covariance from one
dgemmafter removing the means and dividing by T − 1, and the report built fromeigh: values, shares of variance, the top eigenvector and the condition number. - 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.
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