Five stocks, 250 trading days: the covariance matrix of their returns costs 12,500 arithmetic operations, yet it moves only 2,525 numbers in and out of memory. Why does the second figure matter as much as the first, and what changes if the matrix is bigger?
The idea in plain words
Where we are. This is the first topic of the BLAS and LAPACK skill, so nothing comes before it. By the end you will have written the three kinds of BLAS routine in Python and measured what each costs. The next topics take the most important one apart (why a matrix times matrix is fast), and every topic after that works on the same covariance matrix of returns.
Every numerical routine does two kinds of work. It does arithmetic: additions and multiplications, which we count as flops. And it moves numbers: it must fetch each input from memory and write each result back, which we count as words. A fast CPU can do a lot of arithmetic in the time it takes to bring a single number from memory, so a routine is often limited by the second kind of work, not the first.
Flops divided by words: how many operations each number fetched from memory pays for. Low means the routine waits on memory; high means it keeps the CPU busy.
Three levels, three costs
BLAS sorts its routines into three levels by what they combine. Level 1 works on vectors (a dot product, y := alpha * x + y). Level 2 combines a matrix with a vector. Level 3 combines a matrix with a matrix. The table gives the cost of each for vectors of length n and square matrices of size n by n.
- RoutineCost for size n
- level 1: daxpyWhat does it cost?2n flops3n words
- level 2: dgemvWhat does it cost?2n² flopsn² + 2n words
- level 3: dgemmWhat does it cost?2n³ flops3n² words
Read the table slowly. The arithmetic grows as n, n² and n³, but the memory traffic grows as n, n² and n². Only at level 3 does the work grow faster than the data: a matrix times matrix does about n times more arithmetic than it has numbers to fetch. That single fact is why so much effort goes into making level 3 fast, and the next topic shows how.
Levels 1 and 2 on real returns
Here R holds the last 250 daily returns of AAPL, JPM, XOM, JNJ and KO (250 rows, one column per stock) and X is R with each column's average removed. The first example runs ddot on two columns, and daxpy to build the return of a two-stock mix.
# Level 1: a dot product and an axpy on two columns of 250 returnsaapl = [row[0] for row in X]jpm = [row[1] for row in X]blas = Blas()cross = ddot(blas, aapl, jpm)print("cross product:", round(cross, 5), "| flops", blas.flops, "words", blas.words)1blas = Blas()mix = daxpy(blas, 0.5, aapl, [0.5 * v for v in jpm])print("mix of two stocks:", len(mix), "days | flops", blas.flops, "words", blas.words, "| flops per word", round(blas.intensity(), 2))2
cross product: 0.00902 | flops 500 words 500 mix of two stocks: 250 days | flops 500 words 750 | flops per word 0.67
- 1500 flops over 500 words: one operation per number fetched.
- 2Even less: 500 flops over 750 words, because y is read and written.
Level 2 comes next. A portfolio that puts 20% in each of the five stocks has, on every day, a return equal to the matrix X times the weight vector w. That is dgemv: 250 rows, 5 columns, and one answer per day.
# Level 2: the daily return of an equal-weight portfolio is a matrix times a vectorweights = [0.2, 0.2, 0.2, 0.2, 0.2]blas = Blas()daily = dgemv(blas, X, weights)1print("days:", len(daily), "| flops", blas.flops, "words", blas.words, "| flops per word", round(blas.intensity(), 2))
days: 250 | flops 2500 words 1505 | flops per word 1.66
- 1A 250 by 5 matrix is read once: 1,250 numbers, plus 5 weights and 250 results, for 2,500 flops.
Level 3: the covariance matrix
The covariance matrix of the five stocks is Xᵀ X divided by 249. The matrix Xᵀ is 5 by 250 and X is 250 by 5, so this one dgemm call produces the whole 5 by 5 table of how the stocks move together. Then the portfolio variance is a dgemv and a ddot, the two lower levels again.
# Level 3: covariance = X^T X / 249, then the portfolio variance with the lower levelsXt = [list(col) for col in zip(*X)]blas = Blas()cov = [[v / 249 for v in row] for row in dgemm(blas, Xt, X)]1print("covariance: flops", blas.flops, "words", blas.words, "| flops per word", round(blas.intensity(), 2))print("AAPL variance:", round(cov[0][0] * 1e4, 2), "e-4 | AAPL with JPM:", round(cov[0][1] * 1e4, 2), "e-4")blas = Blas()variance = ddot(blas, weights, dgemv(blas, cov, weights))2print("portfolio volatility a year:", round((variance * 252) ** 0.5 * 100, 1), "% | flops", blas.flops, "words", blas.words)
covariance: flops 12500 words 2525 | flops per word 4.95 AAPL variance: 2.5 e-4 | AAPL with JPM: 0.36 e-4 portfolio volatility a year: 11.0 % | flops 60 words 45
- 112,500 flops over 2,525 words: about five operations per number moved, three times better than the matrix times vector above.
- 2The small final step costs 60 flops: the result is the annual volatility of the equal-weight mix.
The routines count each number moved exactly once, as if it stayed in the CPU after the first fetch. A real machine cannot keep a big matrix that close, so a plain triple loop moves the same number many times. The next topic counts that honestly with a cache, and shows how blocking brings the real cost back toward these ideal figures.
What the tasks ask
- 1`daxpy`Return alpha * x + y as a new list and charge 2n flops and 3n words.
- 2`dgemv` and `dgemm`Return the product as new lists, charge the exact flops and words, and reject shapes that do not fit before counting anything.
- 3`intensity`Run the routine of the chosen level on arrays of ones and return flops per word. It is the table above, measured instead of quoted.
Lab · what's graded
4 tasks · 100 pts- Level 1:
daxpy25 pts - Level 2:
dgemv25 pts - Level 3:
dgemm25 pts - Flops per word with
intensity25 pts