Add the same stock twice to a portfolio and its covariance matrix is singular. LAPACK does not raise an error: it returns the answer anyway, together with the number 6. What does that number say, and who has to read it?
The idea in plain words
Where we are. In the last topic you wrote the recipes behind LU, least squares and eigenvalues. This topic is about calling such routines the way production code does, and it is mostly about conventions that look odd to a Python programmer because LAPACK was written in Fortran in the 1970s and kept its habits. The next topic asks the question those habits cannot answer: when is a returned answer actually good?
Four habits matter. First, a routine returns an integer info instead of raising an exception. Second, counting starts at 1, as in Fortran: the pivot row numbers it returns are 1-based. Third, some routines need a work area whose size you must request, and refuse to run if it is too small. Fourth, a routine reads only the part of the matrix it needs: dsyev looks at the lower triangle and trusts that the upper one matches.
- infoWhat it tells you
- info == 0The call rannot a promise the answer is good
- info < 0Argument number -info was illegala bug in the caller
- info > 0The numbers caused troublesingular matrix or no convergence
A duplicated stock
Here cov is the 5 by 5 covariance matrix of the stocks from the earlier topics. We add JPM a second time as a sixth column. Its twin is perfectly correlated with it, so the six rows cannot all be independent and dgetrf stops at the sixth pivot.
# JPM twice: the sixth column repeats the secondtwin = covariance([row + [row[1]] for row in X])lu, piv, info = dgetrf(Blas(), twin)print("info:", info, "| pivots (1-based):", piv)1try: check_info("dgetrf", info)except LinAlgError as error: print("LinAlgError:", error)
info: 6 | pivots (1-based): [1, 2, 3, 4, 5, 6] LinAlgError: dgetrf: U(6,6) is exactly zero, the matrix is singular
- 1
info6 says: the sixth diagonal entry of U is exactly zero.
LAPACK reports a zero pivot only when it is exactly zero. If the sixth column is the sum of the first two instead of a copy, rounding leaves a pivot of about −5·10⁻²⁰, info is 0, and the solution is meaningless. The next topic measures how much to trust a solution.
Pivots count from 1
piv[k] is the row swapped with row k + 1, and the swaps happen one after another, so the list is not itself a permutation. piv_to_perm replays the swaps to give the order of the rows. To see real swaps we hand over the rows in reverse order; the pivot search puts the largest entry of each column back on top.
# Hand over the rows in reverse order so that the pivot search has work to dobackwards = [cov[i] for i in (4, 3, 2, 1, 0)]lu, piv, info = dgetrf(Blas(), backwards)print("info", info, "| piv (1-based):", piv)print("perm (0-based):", piv_to_perm(piv))1
info 0 | piv (1-based): [5, 4, 3, 4, 5] perm (0-based): [4, 3, 2, 1, 0]
- 1The rows come back in the order 4, 3, 2, 1, 0: row 0 of P A is row 4 of what we handed over, and so on.
Factor once, solve many times
dgesv is convenient, but it factors on every call. When the same matrix meets several right-hand sides, call dgetrf once and dgetrs for each one. Here two questions are put to the same covariance matrix: the minimum-variance mix, and the mix that hedges a position in the first stock.
# Two right-hand sides against one covariance matrix: factor once with solve_manyquestions = [[1.0] * 5, [1.0, 0.0, 0.0, 0.0, 0.0]]shared = Blas()answers = solve_many(shared, cov, questions)print("solve_many: flops", shared.flops, "words", shared.words)separate = Blas()for b in questions: dgesv(separate, cov, b)print("two dgesv calls: flops", separate.flops, "words", separate.words)1print("same first answer from dgesv?", all(abs(x - y) < 1e-6 * abs(y) for x, y in zip(answers[0], dgesv(Blas(), cov, questions[0])[2])))
solve_many: flops 160 words 120 two dgesv calls: flops 230 words 170 same first answer from dgesv? True
- 1Factor once (70 flops) plus two solves (45 each) is 160; calling
dgesvtwice factors twice and costs 230.
Workspace and the lower triangle
# dsyev needs a work area; ask how big, and see what happens when it is too smallprint("minimum lwork for 5 stocks:", lwork_dsyev(5))w, v, info = dsyev(Blas(), cov, 4)print("lwork 4 ->", "info", info)1w, v = eigh(Blas(), cov)print("eigh ->", [round(x * 1e4, 2) for x in w])messy = [[row[j] if j <= i else 99.0 for j in range(5)] for i, row in enumerate(cov)]print("garbage above the diagonal, same eigenvalues?", [round(x * 1e4, 2) for x in eigh(Blas(), messy)[0]] == [round(x * 1e4, 2) for x in w])
minimum lwork for 5 stocks: 14 lwork 4 -> info -8 eigh -> [0.81, 1.6, 1.94, 2.51, 2.99] garbage above the diagonal, same eigenvalues? True
- 1
info−8 says argument 8, the workspace size, was illegal: a bug in the caller, not in the numbers.
What the tasks ask
- 1`check_info`Turn
infointo the exception Python code expects: nothing for 0,ValueErrorfor a negative value,LinAlgErrorfor a positive one, with the exact messages in the README. - 2`piv_to_perm`Replay the 1-based swaps on
[0, 1, ..., n-1]. - 3`solve_many` and `eigh`Two wrappers in the style of production code: one factorisation for many solves, and a workspace query before the eigen call, each call followed by
check_info.
dgetrf returns info = 3 for a 6 by 6 covariance matrix. What does it tell you?Lab · what's graded
4 tasks · 100 pts- Read the code with
check_info25 pts - Read 1-based pivots with
piv_to_perm25 pts - Factor once with
solve_many25 pts - Ask for workspace with
eigh25 pts