Act V · Portfolios, Strategies and the Firm
Part 30 of 43Portfolio Construction
The optimizer promises the best portfolio. Why does the one it builds from data do worse than splitting your money equally?
Mean-variance optimization takes estimates as truth and puts the most weight where the estimates are most wrong: it maximizes error. With as many assets as observations the sample covariance matrix is nearly singular and the optimizer reports almost no risk at all. The part measures the promise against the delivery, then repairs the inputs: shrinkage of the covariance (Ledoit and Wolf), constraints that act as shrinkage, Black-Litterman's blend of views with the market, risk parity and hierarchical methods that avoid inverting the matrix. Kelly returns as the growth-optimal portfolio, and a network is trained to go from features to weights in one step.
What you need. Parts 23 and 25; linear algebra (eigenvalues).
What you will be able to do
Undergraduate
- Explain why an optimizer amplifies estimation error and why 1/N is hard to beat.
- Compute a minimum-variance portfolio of a few assets.
Master's
- Shrink a covariance matrix and show the effect on out-of-sample risk; clean eigenvalues with the Marchenko-Pastur edge.
- Build Black-Litterman, risk-parity, hierarchical-risk-parity and minimum-CVaR portfolios.
PhD
- Derive the exact in- and out-of-sample variance of the sample minimum-variance portfolio for Gaussian returns, and its limit as K/T tends to a constant.
Industry
- Specify an optimizer for production: constraints, turnover control, and how its output is evaluated.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Undergraduate 12 min · Master's 40 min · PhD 55 min · Industry 16 min.
- 0The optimizer's promiseUndergraduate2 min
- 1Error maximisationUndergraduate4 min
- 2The humble 1/NUndergraduate3 min
- 3Covariance in high dimensionMaster's3 min
- 4Shrinkage: Ledoit and WolfMaster's4 min
- 5Constraints as shrinkageMaster's2 min
- 6Black-LittermanMaster's4 min
- 7Risk parity and HRPMaster's3 min
- 8Robust optimisation and CVaRMaster's3 min
- 9Kelly, Cover and FernholzPhD5 min
- 10Entropy poolingMaster's3 min
- 11End-to-end portfoliosPhD3 min
- 12Evaluation protocol and fixed arithmeticIndustry3 min
- 13Rule 30: the optimizerIndustry2 min
- For the researcher: why the optimizer underestimates its own riskPhD7 min
- Recap, desk questions, problemsAll tracks3 min
Also on this page: Lecture · Key results · Try it · Lab · Problems · Reading · 中文 · Build the film.
Lecture
The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film. A dashed box stands for a number the film computes when it is rendered (hover over it to see what is computed); the README's figures for each chapter, where it lists them, follow the chapter's text.
The optimizer's promiseUndergraduate2 min
Part thirty. Portfolio construction: how to turn estimates into weights, why the optimizer turns errors into conviction, and what to do about it.
In a controlled simulation, declare the forty-nine industries' research-period moments to be the population truth. Give each optimizer sixty independent Gaussian observations and target one percent monthly excess return. Across draws, median reported volatility is percent a month. Evaluate those same weights under the stipulated moments: median expected excess return is percent at percent volatility, about times the reported risk. These are componentwise medians, not one portfolio, and population-model evaluations rather than historical deliveries.
Where this sits. This part opens the fifth act: portfolios, strategies and the firm. The fourth act asked which signals are real; this one asks how to hold them. Part twenty-nine ended on a theorem about estimated means; this part is about estimated covariances, and about the rules that try to need neither.
Harry Markowitz posed the problem in 1952; John Kelly asked the long-run question in 1956; the mathematics of random matrices arrived in 1967, and Robert Merton drew the frontier in closed form in 1972. Then the reckoning: Richard Michaud's error maximisation, Cover's universal portfolio, Black and Litterman's market prior, and physicists cleaning correlation matrices. And the modern answers: risk as a linear program, constraints understood as shrinkage, Ledoit and Wolf's estimators, the humbling contest against one over N, hierarchical risk parity, and nonlinear shrinkage.
The plan: why optimizers maximise errors, and how one over N embarrasses them; what random matrix theory says about a covariance matrix; shrinkage, and why constraints are shrinkage in disguise; Black-Litterman, risk parity and its hierarchical cousin; robust optimisation and tail risk; growth, from Kelly to Cover and Fernholz; views on whole distributions; a network that learns weights directly; evaluation protocol and fixed arithmetic, with sealed strategy results excluded; and the optimizer's risk illusion under a stated model.
In the House, the portfolio desk gets its optimizer: estimators that know their own noise, allocation rules that need fewer estimates, and a rule for what any optimized portfolio must report about itself.
1Error maximisationUndergraduate4 min
Markowitz gave us the recipe in 1952: feed in expected returns and covariances, and out comes the best portfolio. What does the optimizer do with the errors in its inputs?
The recipe. Find the least risky fully invested portfolio with a given mean. Lagrange multipliers give the weights in closed form, and the set of best portfolios, the frontier, is a hyperbola. But the means and covariances are estimated, and the optimizer cannot tell an estimate from the truth.
Sensitivity in a stipulated population model. Use the industries' 1970 through 2020 moments as truth, and raise software's annualised mean by percentage points: its own sixty-month IID standard-error scale. For the normalised inverse-covariance mean direction, gross exposure starts at , and total absolute weight change is . Software moves from to . Other means have their own, correlated uncertainty; they do not all suffer this exact error simultaneously.
A known-truth simulation. Declare the industries' research-period mean and covariance to be fixed Gaussian population moments; draw sixty observations per fit. The green curve uses those stipulated moments. Twelve stored estimated frontiers show how sampling changes the target-return problem. Their positions are conditional on this experiment, not a theorem that every estimated frontier must be optimistic. The axes retain the full stored coordinates.
Now ask each estimated optimizer for a portfolio earning one percent a month, and then judge it under the truth. In red, what each one promised: about one percent at a volatility of percent, better than the true frontier allows. In teal, what it delivered: a median of percent a month at percent volatility, times the risk it promised, and below the true frontier. Richard Michaud called mean-variance optimization an error maximizer: it seeks out the assets whose estimates are most flattering, which are the ones most likely to be wrong.
Compare two sample sizes in the same stipulated population. Median reported volatility changes from to percent monthly, and model-evaluated volatility from to . Median largest absolute weight changes from to . IID means have a square-root sample-size scale, but inverse covariance and constrained optimisation losses do not share one universal rate. More observations can also mean a less stable historical regime.
Resampling in this fixed Gaussian experiment. For the first hundred base draws, average thirty target-return portfolios fitted to resamples of each draw's estimated distribution. Median population volatility is percent for the resampled weights, compared with for their matched plain portfolios. Both negative expected returns and high-volatility outcomes remain visible. Resampling can reduce variability, but it does not supply independent information about a shared input error; this experiment does not establish a universal ranking.
Why estimation can matter. Chopra and Ziemba study sensitivity to errors in means, variances and covariances under specified loss and calibration assumptions. Their relative-cost findings are not a universal ten-to-one conversion. Covariance inversion amplifies estimated small-eigenvalue directions; their uncertainty and portfolio exposure both matter. Selection on flattering estimates creates optimism across repeated samples, without implying every fitted portfolio or every self-report is wrong in the same direction. The research chapter states an exact narrower model.
Pause and predict. With twenty years of data instead of five, how far do the estimated frontiers move toward the truth?
2The humble 1/NUndergraduate3 min
The simplest rule needs no estimates at all: divide the money equally. Can any optimizer beat it out of sample?
In 2009 Victor DeMiguel, Lorenzo Garlappi and Raman Uppal ran the contest Part twenty-three previewed. Fourteen optimizers, from the plain sample rule to Bayesian and constrained versions, against equal weights on seven data sets. None beat one over N consistently. Their calibration: the sample mean-variance rule would need about three thousand months of data to beat it with twenty-five assets, and about six thousand with fifty. That is two hundred and fifty, and five hundred, years.
Our retrospective rolling comparison uses forty-nine industries, 1980 through 2020, with ten-year trailing windows. Equal weights have annualised Sharpe ; the saved normalised sample inverse-covariance mean direction has , with target-weight turnover percent a month. Normalisation can reverse its positive-Sharpe direction and produce high gross exposure. Constant-correlation and nonlinear GMV record and . These selected research comparisons do not prove that estimated means always fail or identify a future winner.
Compare a common trailing-window risk metric with realised risk. Outlined bars apply the sample covariance to every rule's weights, even when a different covariance estimator chose those weights. Filled bars measure the following monthly portfolio returns. Sample GMV records percent against . This is not each shrinkage estimator reporting its own forecast, nor a proof that every inverted matrix always understates risk. The research theorem studies a narrower fixed Gaussian model.
A fixed cost sensitivity, not a complete net backtest. Charge ten or fifty basis points on absolute target-weight changes and subtract the average charge from the mean, keeping gross volatility in the denominator. Shrunk GMV's proxy Sharpe is or ; sample GMV reaches at fifty basis points. The turnover proxy omits drift between rebalances, financing and impact. Fixed equal weights therefore show zero target-change cost even though maintaining them can require trading. Actual net Sharpe also depends on the time path of costs.
Window length changes the noise and recency trade-off. Here sample GMV's annualised realised volatility is percent with sixty months and with a hundred and twenty. Constant-correlation shrinkage records and . This research sample shows less sensitivity after shrinkage; it does not guarantee that a short window is safe or optimal when covariance changes.
If neither the optimizer nor one over N is right, combine them. Raymond Kan and Guofu Zhou proposed in 2007 a three-fund rule: cash, the estimated tangency portfolio, and the estimated minimum-variance portfolio, mixed to minimise the expected loss from estimation error. Jun Tu and Zhou then combined an optimizer directly with one over N, with the mixing weight chosen from the data. The common thread runs through the whole part: every fix shrinks something toward something simpler, whether the means, the covariance or the weights themselves.
Pause and predict. Equal money needs no estimated expected-return or covariance inputs. Which exposures, asset-selection and implementation risks does that leave unresolved?
3Covariance in high dimensionMaster's3 min
A covariance matrix of forty-nine industries has distinct numbers, estimated from a few years of data. How much of it is noise?
A random-matrix null benchmark. Form the displayed uncentred sample covariance from independent standard Gaussian entries. As dimensions and observations grow at fixed ratio q between zero and one, Marchenko and Pastur's eigenvalue density has the shown support. Sample correlations have related asymptotic behaviour; the finite edges are not exact confidence bounds. At series and observations, the benchmark endpoints are about and . Dependence, changing volatility and missing-data treatment can change this reference.
Daily industry correlations for . Independently permuting each series keeps its marginal observations but disrupts contemporaneous and temporal dependence; this is one shuffled control, compared with a Gaussian asymptotic reference. All forty-nine eigenvalues are plotted at their actual coordinates, including the top value . There are above the reference edge, and the largest contributes percent of standardised variance. Being inside the band does not prove that an economic mode is noise. The original daily reader zero-fills missing values.
Read this decomposition cautiously. The leading eigenvector is a broad common direction in standardised industry returns; it is not the capitalization-weighted market portfolio. Other large modes can reflect sector comovement, with loadings and signs determined by this sample. The bulk contains sampling noise and may contain real weak structure. Inversion magnifies small estimated eigenvalues, so an optimiser can become sensitive to errors there. The MP benchmark alone does not identify the correct economic rank.
Look at the two leading directions in the 2019 sample. The leading loadings are broad and close to the equal-loading reference one seventh, in standardised-return coordinates. This is a common mode, not an investable market-cap portfolio. The second contrasts the industry groups labelled on screen; its sign is arbitrary. The remaining values sit below the reference edge, which does not establish that all those directions lack economic signal.
The leading share changes across sample years. It peaks at percent in and is percent in 2019. These are proportions of standardised variance, not capital weights or counts of independent bets. Stronger common movement can weaken diversification in some stress periods; it does not make every remaining variance contribution vanish.
Compare two particular sample years. In 2008 the top eigenvalue is , accounting for percent of standardised variance. This shows stronger common movement in that sample. It does not reduce the covariance to exactly one factor, prove a universal crisis law, or eliminate all diversification. A covariance fitted in another regime may understate a concentrated common exposure.
One proposed regularizer is eigenvalue clipping. Decompose the sample correlation matrix. In the local rule, replace every eigenvalue below the MP upper edge by that group's average, retaining values above it. This is a modelling choice inspired by random-matrix cleaning, not a test that the bulk lacks signal. The trace is preserved at that averaging step; subsequent diagonal renormalisation restores unit variances and can change the final spectrum again. Benefits depend on the population, window and loss.
Pause and predict. With forty-nine industries and only sixty months of data, where are the edges of the noise band?
4Shrinkage: Ledoit and WolfMaster's4 min
The sample covariance spreads its eigenvalues too far apart. How far should we pull it back, and toward what?
Shrinkage trades variance for bias. Blend a sample covariance S with a structured target F, which can still be badly misspecified. For a fixed target and unbiased S, the unconstrained squared-Frobenius-error optimum has the displayed noise-over-distance ratio; restricting the blend to zero through one clips the optimum. A target estimated from the same data needs covariance terms. Ledoit and Wolf estimate intensities under stated large-dimensional assumptions. The local scaled-identity routine uses demeaned divisor-T moments and caps its estimated ratio at one.
Different targets encode different beliefs. The constant-correlation target retains individual estimated variances and uses an estimated average correlation. Its fitted-target dependence requires its own intensity formula. A single-index covariance instead uses estimated loadings and residual variances. Structure can reduce variance but introduces bias and parameter uncertainty. A small parameter count alone does not guarantee a good target, and the appropriate loss may be portfolio risk rather than covariance Frobenius error.
Nonlinear spectral shrinkage. Keep sample eigenvectors and choose directional variances. A scaled-identity linear target shares those eigenvectors; a constant-correlation target generally does not. Under squared Frobenius loss, the rotation-equivariant oracle is each sample eigenvector's true directional variance. It is not a portfolio-loss oracle. Ledoit and Wolf's analytical estimator uses spectral density and Hilbert-transform estimates under large-dimensional assumptions. It estimates, rather than equals, the oracle; the local implementation covers fewer assets than demeaned observations.
One simulated hundred-and-twenty-observation window. Grey shows sorted population eigenvalues, red sorted sample eigenvalues; the smallest population eigenvalue is times the smallest sample value. This comparison does not match eigenvector directions. The oracle curve instead evaluates population variance along sample eigenvectors, ordered by sample eigenvalue. It is optimal within that eigenbasis under Frobenius loss. The saved nonlinear estimator is compared with that oracle. Closeness is an observed finite example, not exact oracle recovery or a guarantee of portfolio-optimal shrinkage.
A fixed Gaussian population experiment. Compare each fitted GMV portfolio's true variance with the population minimum, averaged over a hundred draws per sample size. With sixty observations, sample GMV has ratio ; constant-correlation shrinkage has , and nonlinear shrinkage . At two hundred and forty observations, clipping has versus sample . These outcomes are conditional on this population and implementation. Linear shrinkage uses divisor T, while the sample and nonlinear routines use T minus one. No universal dominance follows.
Structure is another regularizer. A factor covariance models common variation plus diagonal residual risk; low parameter count reduces some estimation burden but does not eliminate noise or misspecification. A market-index factor and a first principal component are distinct constructions. The saved one-PCA-factor rule uses the latter. Its retrospective rolling Sharpe is , with percent trailing sample-covariance risk and percent realised volatility. The first number is not its factor-model covariance forecast. This is selected research evidence, not a causal identification of improvement.
Estimated intensities over ten-year research windows. The constant-correlation blend ranges from to ; the scaled-identity intensity stays below . Different targets and denominators produce different intensities. A smaller intensity does not by itself prove a target is better or worse. Here the identity removes common correlations, whereas the constant-correlation target preserves an estimated average relationship.
A practical trade-off. A longer history can reduce sampling error while mixing different covariance regimes. The displayed noise and drift terms are schematic, not an estimated universal loss curve. For independent, equally informative observations, an infinite geometric weight sequence has Kish effective size one plus lambda over one minus lambda; serial dependence changes the information content. Daily data supply roughly twenty observations per month, but neither independence nor a twentyfold precision gain is automatic. Forecast horizon, asynchronous trading and changing volatility still matter.
Pause and predict. If a fixed target equals the known population covariance exactly, which blend minimises Frobenius loss? How does estimating the target scale from the same data change the question?
5Constraints as shrinkageMaster's2 min
Constraints can regularize fitted portfolio weights, but they also remove feasible choices. Why can a restriction help under estimation error, and what does its exact covariance identity prove?
The last ten years of research data give a concrete example. Unconstrained GMV has dollars short per dollar net invested. The long-only solution holds industries. Restrictions can reduce estimation sensitivity, but with the population covariance known, adding a constraint cannot lower the unconstrained minimum variance. Any future benefit is an estimation and implementation question, not a theorem of dominance.
Jagannathan and Ma's algebra. For positive-definite input covariance and a unit budget, write stationarity, nonnegative multipliers and complementarity at the long-only optimum. Subtract half the multiplier-vector outer products from the covariance. A positive multiplier marks a binding constraint, not necessarily an asset shorted in the full unconstrained solution. The adjusted matrix has the same curvature as the original on zero-budget directions, so the same weights minimise its quadratic over all unit-budget weights. It need not be positive definite on the whole space. The stored numerical agreement is shown on screen.
Interpret the identity with care. Shorts arise from the whole estimated covariance system, not a rule that every large covariance must be an error. Positive lower-bound multipliers reduce the corresponding adjusted entries. On the unit-budget affine set, the correction is equivalent to a linear penalty, with original curvature preserved. This can regularize noisy weights but may discard useful hedges. Out-of-sample improvement depends on the population, estimates and trading costs; it is not guaranteed by the algebra.
Out of sample, on the industries. With five-year windows the unconstrained sample portfolio realised percent volatility; long only, : the constraint did as much as formal shrinkage. With ten-year windows the gap narrows, as there is less noise for the constraint to remove.
Other constraints regularize different features. A gross-exposure bound controls the L1 norm of fully invested weights, as studied by DeMiguel and coauthors. At unit net investment, an L1 bound of one forces nonnegative weights. Intermediate bounds still require a tuning policy. A squared-L2 upper bound adds a nonnegative diagonal term through its multiplier: ridge covariance regularization, equivalent up to scale to an identity blend when the input trace is positive. The chosen multiplier need not equal a Ledoit-Wolf intensity.
Pause and predict. Add an upper limit of five percent on every weight. Which covariances does its multiplier change, and in which direction?
6Black-LittermanMaster's4 min
Black and Litterman's 1992 global portfolio paper starts from an equilibrium prior instead of treating noisy sample means as certain. The question is which excess returns make given benchmark weights optimal, and how specified views change that prior.
Reverse optimisation is a conditional construction. Under compatible mean-variance and equilibrium assumptions, benchmark weights can be represented as an optimum. Given covariance, positive risk aversion and benchmark weights, implied excess returns are delta times covariance times weights. Their stability depends on all those inputs. Here delta is itself estimated from the last decade's sample market excess mean and variance, giving ; no means-free identification of risk preference is claimed.
A Gaussian model for uncertainty about means. The prior is centred at implied returns, with covariance tau times Sigma. Views are linear measurements of means with independent Gaussian errors of covariance Omega; Omega is an error covariance, not a confidence probability. The posterior mean blends prior and view precisions. Without views the mean remains Pi, and using unchanged Sigma in the risky-demand rule recovers the benchmark. Covariance-weighted propagation can alter expected returns beyond assets explicitly named in a view.
An example on the industries. The market's weights imply that software should earn percent a year over cash, and utilities . Now a view that sounds bullish on software: it will beat utilities by percent a year. But equilibrium already says percent. Relative to the market, the view is bearish, and the posterior spread falls to percent. A view in Black-Litterman is a statement about what the market has not already priced.
And the portfolio. The posterior portfolio moves percent of weight out of software and into utilities, and leaves every other industry at its market weight. Compare the naive alternative: plug the decade's sample means into the same optimizer, and the weights' absolute values sum to . Black-Litterman is shrinkage of the means toward equilibrium, with the views as the only departures.
Allocation depends on the covariance convention. The preceding numerical example optimises the posterior mean with unchanged Sigma. Now consider a predictive covariance Sigma plus posterior mean-uncertainty M, under the same Gaussian model. The unconstrained risky demand can be decomposed into a scaled benchmark plus portfolios in the rows of P; no unit-budget or long-only constraint is added here. Joint views and their covariance determine the coefficients. With predictive covariance, even a view agreeing with the prior mean can change risk and weights. The simple zero-mean-tilt statement belongs to the unchanged-Sigma convention.
Vary the view-error variance multiplier while holding this prior fixed. At the finite low-uncertainty endpoint the posterior spread is percent; at the high-uncertainty endpoint it is percent. Zero error variance and infinite error variance are limiting cases, not these finite endpoints. This multiplier is not a confidence probability; multiple correlated views need their full error covariance and an audited calibration policy.
A different prior shrinks industry means toward their estimated GMV mean. This local Bayes-Stein-inspired rule uses the displayed data-dependent shrinkage formula; it is not a universal finite-sample improvement for every allocation loss. Its mean intensity is . With the same constant-correlation covariance, the saved rolling normalised directions have Sharpe and . Selection, leverage and sign normalisation remain relevant; these observations do not prove that all estimated means are untradable.
Pause and predict. What happens to the posterior and the portfolio if the view is held with no confidence at all?
7Risk parity and HRPMaster's3 min
If expected returns are too noisy to use, perhaps a portfolio should be built from risk alone. Not the least risk, which leans on the smallest eigenvalues, but risk spread evenly.
Equal money is not equal variance contribution. Under the fitted covariance, is the largest contributor to the equal-weight portfolio, at percent; the smallest contribution is percent. Contributor rank is not necessarily standalone-volatility rank. ERC instead chooses positive weights for equal contribution shares under this estimate. Those shares can change when covariance changes.
Risk contributions and a convex construction. The displayed shares are each weight times covariance times weights, divided by portfolio variance. They equal volatility-contribution shares when variance is positive. For positive-definite covariance and strictly positive budgets, Spinu's quadratic minus weighted log objective is strictly convex on positive y. Its first-order conditions give y_i times Sigma-y_i equal to the budget. Normalising y produces unique budgeted variance shares. Numerical convergence must still be checked; the local solver uses Newton steps that preserve positivity.
Hierarchical risk parity starts with a sample-dependent ordering. Following Lopez de Prado's construction, use single linkage on the displayed correlation distance and read the leaves in tree order. This can reveal groups of related industries, but it does not guarantee an exactly block-diagonal covariance, stable clusters or optimal future allocations.
Reordering the same covariance does not change its information. The original industry ordering appears on the left. A single-linkage leaf order places related industries nearer each other on the right; the matrix need not become block diagonal. HRP's recursive splits use within-cluster inverse-variance proxies. Errors in clustering or covariance can propagate across allocations, so the hierarchy is not an error-isolation guarantee.
Then the allocation, as the House runs it. Split the ordered list of assets in half. Give each half the inverse-variance portfolio of its members, and split the money between the halves in inverse proportion to those portfolios' variances. Repeat inside each half, down to single assets. No matrix is ever inverted, so the smallest, noisiest eigenvalues never get the chance to dominate.
Side by side. The rules run from equal money, through equal risk, to minimum variance. In sample, minimum variance has by far the lowest volatility, percent against for HRP and for risk parity. But it concentrates its weight and trusts every estimate; risk parity and HRP give up some in-sample risk for weights that do not depend on inverting a noisy matrix. Which trade is worth it is a question for out-of-sample data, under a frozen evaluation protocol.
Research-period rolling results. HRP records volatility percent and Sharpe ; ERC has percent and ; equal weights have percent and . HRP's target-weight turnover proxy is percent monthly. Avoiding a matrix inverse does not eliminate estimation, concentration, regime or execution risk. HRP is not generally equal risk contribution, and neither method has a guarantee against losses.
Pause and predict. Two uncorrelated assets, with volatilities of ten and twenty percent. What weights give them equal risk contributions?
8Robust optimisation and CVaRMaster's3 min
Two more ways to make the optimizer humble: plan for the worst inputs, and measure risk by the losses that matter, not by variance.
Robust optimisation first. Choose the weights that do best when nature picks the worst expected returns from a set of plausible ones. Make the set an ellipsoid around the estimate, shaped by the estimate's own uncertainty. The worst case has a closed form: the estimated return minus kappa times the uncertainty of the bet. The optimizer is charged for leaning on noisy estimates, which is Chapter one's disease, treated at its source.
The uncertainty-set shape matters. If mean uncertainty is Sigma over T, the penalty is proportional to portfolio volatility. Without a budget constraint, a nonzero optimum lies along inverse Sigma times the estimated mean, with reduced scale; if the uncertainty radius exceeds the available signal, zero risky exposure can be optimal. With a unit budget and no other constraints, stationarity increases the effective risk-aversion coefficient and moves along the GMV-plus-mean-tilt family. This is a property of this ellipsoidal model, not all robust portfolios.
Expected shortfall with a precise tail convention. Average the worst five-percent probability mass of an integrable loss; with atoms, only the required fraction of the quantile mass is included. A conditional average above the quantile need not equal it. Rockafellar and Uryasev express it as the minimum over alpha of alpha plus scaled expected positive excess; a suitable quantile minimises this expression. For equally weighted scenarios and linear portfolio losses, budget and long-only constraints give the displayed linear program. Historical scenarios, feasibility and costs still limit interpretation.
A fixed VaR counterexample. Take two independent bonds, each losing one unit with probability four percent and zero otherwise. Each has ninety-five-percent VaR zero. The sum loses at least one unit with probability seven point eight four percent, so its VaR is one: subadditivity fails. VaR can also make optimisation nonconvex, depending on the loss distribution. Integrable-loss expected shortfall is convex and subadditive; its scenario formulation is a linear program. This does not guarantee positive returns or that every observed diversification change improves every risk statistic.
All fitted monthly excess returns from 1970 through 2020, including positive months at their actual coordinates. The green distribution is minimum variance and the red distribution minimum CVaR, with minimum variance's five-percent quantile marked. Counts below minus six percent are and ; counts below minus two percent are and . These fixed thresholds describe this fitted sample, rather than proving that any particular month was moved causally or that fewer holdings caused the result.
A retrospective scenario comparison. On the fitted sample, the scoring helper reports CVaR percent monthly for the CVaR portfolio and for minimum variance. The helper evaluates an interpolated quantile and positive excess, which can differ from the exact discrete LP optimum. On rolling ten-year windows the scored outcomes are and . Five percent of scenarios gives nominal tail mass equivalent to observations; the optimisation still imposes all scenario constraints. This illustrates tail-estimation sensitivity without establishing a universal data requirement or risk-measure ranking.
Pause and predict. With a hundred and twenty monthly scenarios, how many of them determine the CVaR at ninety-five percent? And at ninety-nine?
9Kelly, Cover and FernholzPhD5 min
Mean-variance is a one-period idea. An investor who reinvests for decades cares about something else: how fast wealth compounds. Three answers, from three traditions.
Kelly under a specified model. For self-financing constant risky exposures in a continuous diffusion with constant known excess drift and covariance, log-growth rate is risk-free growth plus mean minus half variance. Positive-definite covariance gives inverse Sigma times mu as the growth optimum among this admissible class. Long-run comparisons need stationarity and integrability; universal finite-time domination is not implied. Plugging the research sample's market moments into that model gives leverage . This is a retrospective fitted quantity, not known future Kelly leverage.
Compare a diffusion approximation with a historical discrete path. The quadratic peaks at the fitted Kelly leverage. The monthly log-wealth calculation over the displayed leverage grid peaks at ; only solvent grid points have finite log growth. Twice Kelly returns to risk-free growth in the quadratic model, not necessarily in the discrete realised path. Estimation, financing and left-tail solvency can favour smaller exposure, but there is no universal half-Kelly prescription.
A scalar estimation-risk calculation. Assume known variance and an independent unbiased Gaussian mean estimate with variance sigma squared over T, in consistent annual units. Substituting a fixed fraction c into the quadratic growth model adds that estimation variance to the penalty. The displayed growth is excess over cash. The optimal fraction is true squared Sharpe divided by true squared Sharpe plus one over T. It is not feasible without knowing or estimating true strength. Substituting the historical fitted market strength gives at fifty-one years and at five. These are illustrative plugs into the model, not optimal allocations certified by the data.
The second answer needs no model at all. Consider every constant-rebalanced mix of the assets, and its wealth so far. Thomas Cover's universal portfolio of 1991 holds their average, weighted by how well each has done. And he proved that its wealth trails the best mix chosen in hindsight by at most a polynomial factor in time: it grows at the same exponential rate as the best constant mix, whatever the market does.
A finite-mixture illustration on and . The saved computation uses a fixed grid of constant monthly rebalanced mixes. The best grid mix in hindsight assigns percent to gold and multiplies wealth times. Uniformly averaging those grid portfolios yields times, a ratio . Since the mixture contains its best grid component with weight one over , their wealth ratio cannot exceed . This finite-mixture bound differs from Cover's continuous-uniform two-asset bound n plus one, here . Neither includes trading costs or guarantees beating buy-and-hold in every path.
Two comparison classes. For a continuous uniform mixture over long-only constant mixes with strictly positive price relatives and frictionless rebalancing, Cover's polynomial wealth bound gives a per-period log gap tending to zero. For two assets and months that continuous bound is percent monthly; the saved grid computation instead has the separate finite-mixture bound just shown. A fixed grid competes with its grid best, not every continuous weight. Neither result compares with arbitrary dynamic foresight strategies, and costs can change the conclusion.
Fernholz's continuous-time stochastic portfolio theory is a different result. Positive market weights raised to p below one tilt toward smaller names. Under a continuous self-financing model, the generating-function identity separates the change in diversity from an accumulated excess-growth term. A bounded adverse change in diversity and sufficient nondegeneracy are additional conditions for long-horizon relative outperformance. The saved monthly industry-cap proxy records average relative log return percent annually. Broad retrospective baskets, discrete rebalancing and omitted costs make this an illustration, not a verification of continuous-time relative arbitrage.
The excess-growth identity in continuous time. For nonnegative fully invested weights and a positive-semidefinite instantaneous covariance, half the weighted individual variances minus portfolio variance equals a weighted sum of pairwise relative variances. It is nonnegative; strict positivity needs positive weight on a pair with nonzero relative variance, rather than merely unequal volatility labels. With constant weights, normalised log portfolio wealth equals the weighted log asset-price relatives plus accumulated excess growth. The term is relative to that weighted log benchmark, not a guarantee of positive absolute or market-relative returns after costs.
Pause and predict. An investor bets twice the Kelly fraction. What is the growth rate, and why?
10Entropy poolingMaster's3 min
Meucci's entropy pooling changes probabilities over supplied scenarios to satisfy feasible views while minimising relative entropy. It does not require Gaussian returns, but it does require a stated scenario set, prior and constraint convention.
The idea. Keep the historical scenarios, and change only their probabilities: find the distribution closest to the prior in relative entropy that satisfies the views. The answer tilts each scenario's probability exponentially, by how much that scenario agrees with the views. The tilt has one multiplier per view, found by a small convex problem, however many scenarios there are.
A chosen stress on research-period monthly excess-return scenarios: banks' mean is set to minus percent monthly. Bars show new probabilities relative to one over . The largest weights occur in , , and . The exponential tilt favours scenarios with bank losses because that is how this supplied constraint is satisfied. It has not discovered a forecast or a new causal crisis model. The entropy-based effective number is ; it measures probability concentration, not independent observations or forecast accuracy.
The tilted empirical distribution changes together. In this scenario library the mean changes are largest for and outside banks. Covariances and tails can change because entire scenarios are reweighted, but this is conditional arithmetic rather than causal transmission. Linear moment or event-probability constraints are directly tractable. A variance about a changing posterior mean or an arbitrary correlation/ranking constraint need not be linear in probabilities; it requires a suitable formulation and feasibility check.
A fixed-centre second-moment stress. Require the expected squared market excess return around its prior mean to equal four times prior variance. The posterior mean is not separately held fixed. The annualised root of that fixed-centre moment moves from to percent. It is not generally posterior standard deviation. In this tilted library, average industry correlation changes from to . That is a consequence of the supplied scenarios and stress, not an automatic law of volatility or evidence against every Gaussian model.
Three practical points. Partial confidence is a blend of the posterior and the prior probabilities. Inequalities, such as one industry doing worse than another, are handled by the same convex dual. And the method can only reweight what happened. A crisis worse than any in the sample cannot be expressed without first adding scenarios that contain it.
Pause and predict. You impose a view that the prior already satisfies. What are the posterior probabilities?
11End-to-end portfoliosPhD3 min
The classical pipeline has two steps: forecast, then optimise. A neural network can skip the forecast and learn the weights directly, trained on the quantity the investor cares about. Does it help?
The saved demonstration has an important information leak. A shared small network scores four trailing-return features per industry; softmax gives positive unit-sum weights. Training optimises realised Sharpe, with weight decay, on 1975 through 2005. Nominal validation is 2006 through 2020, but feature centring and scaling use both periods before the split. These are retrospective diagnostic results, not a clean chronological evaluation. The original computation is retained and the leak is disclosed rather than silently retrained.
The idea comes from published work. Zihao Zhang, Stefan Zohren and Stephen Roberts trained a network to map the recent prices of a few index funds directly to portfolio weights, with the Sharpe ratio as the loss. They report beating the classical allocations they compared with, from 2011 to 2020. Note the universe: a handful of funds, so very few weights to learn. Ours has forty-nine.
Saved score history for one seed. The last logged pre-update training Sharpe is . The corresponding validation score is evaluated after that update and is ; the equal-weight diagnostic is . Global feature scaling leaks validation moments, and validation is repeatedly inspected. Score curves are saved, but intermediate portfolio-weight snapshots are not, so this is not a replay of changing allocations or a certified independent test.
The final saved comparison uses a different score convention from the pre-update training log. All final table scores evaluate final weights. The two-step heuristic solves an inverse shrunk-covariance mean direction, clips negative components and renormalises; that is not the exact long-only mean-variance optimizer. Its training and diagnostic validation Sharpes are and . Different objectives, features and the network's leaked scaling prevent attributing the gap purely to end-to-end versus two-step learning.
What the saved demonstration establishes. The largest diagnostic-period weight averages percent and effective holdings , showing concentration in this fit. There are training months, a single seed, weight decay and repeated validation inspection; the feature-scaling leak remains. These facts do not isolate the cause of poor generalisation. Decision-focused methods can incorporate costs and constraints, but their value needs matched information, appropriate regularisation, frozen preprocessing and valid evaluation. No new fit is run to improve this result.
There is a principled middle ground. The classical pipeline fits the forecast for accuracy, then optimises as if the forecast were true. What matters is the regret of the decision: what was lost by acting on the forecast. Adam Elmachtoub and Paul Grigas gave a convex upper bound on that regret, so a forecast can be trained for the decision it feeds while keeping the optimizer's structure, and its constraints, in place. That is where decision-focused learning is heading.
Pause and predict. How would you build shrinkage into the network, without changing its loss?
12Evaluation protocol and fixed arithmeticIndustry3 min
This chapter uses no sealed strategy result. A portfolio comparison needs a complete information, allocation, execution and reporting policy before its performance can be interpreted.
Freeze more than a covariance formula. Fix data timing, preprocessing, estimation, constraints and tuning. Define trades from actual drifted holdings, with cash, financing and costs. State the benchmark, risk goal and inferential policy. Equal weights, minimum variance and HRP answer different objectives; a single Sharpe ranking does not resolve all of them.
Existing metadata counts registrations through Part twenty-nine and through Part thirty, an increment of . These are historical bookkeeping totals, not independent statistical tests. Restoring ordinary calculations creates no new registration. The strategy experiment remains excluded; no performance, significance or power conclusion is supplied.
A fixed two-asset covariance toy. Choose uncorrelated annual volatilities ten and twenty percent, known exactly. Minimum variance gives eighty and twenty percent weights and volatility percent. Equal risk contributions give two thirds and one third, with percent volatility. Equal money gives percent. This shows that equal money, equal risk and minimum variance differ; it does not compare returns or estimation performance.
A second fixed toy shows why target-weight turnover misses trades. Start with half a dollar in each asset. Choose a ten-percent return for the first and zero for the second. Values become fifty-five and fifty cents, so pretrade weights are eleven twenty-firsts and ten twenty-firsts. To return to equal weights before fees, sell two and a half cents of the first and buy the same amount of the second. The target never changed, but trading was required.
Under a chosen five-basis-point fee per dollar traded, five cents of gross trades cost basis points of initial wealth. The fee denominator is traded dollars; the reported cost denominator is initial wealth. This arithmetic pays fees separately and does not solve a self-financing post-fee rebalance. It supplies no historical net performance or complete implementation model.
Inference needs a defined comparison. Use paired observations and a method appropriate to dependence and the selected loss. A wide uncertainty interval is not proof of equality, and a variance objective is not an expected-return objective. Preserve selection and revision history. No test statistic or strategy verdict is computed in this chapter.
Pause and predict. Why can an unchanged equal-weight target still require trades, and which denominator converts a per-dollar-traded fee into portfolio cost?
13Rule 30: the optimizerIndustry2 min
The House's thirtieth rule: what an optimized portfolio must report about itself before the House will trade it.
The first portfolio-desk sheet. Ordinary Gaussian simulations show an estimation gap under stipulated truth. The daily spectrum has modes above a null reference, without identifying every smaller mode as noise. The rolling comparison evaluates selected rules and exposes variance-estimation sensitivity. Research-period next-year/sample variance ratios are descriptive, whereas the Gaussian theorem has explicit population assumptions. Existing counts are bookkeeping, and the sealed strategy result is excluded. No historical strategy verdict follows from this sheet.
Chapter four's estimator, as the House implements it, in twelve lines. Demean the returns. The target is the average variance times the identity. Its distance from the sample matrix, and the sample matrix's own noise, measured observation by observation, give the intensity, capped at one. No tuning, no cross-validation: the data choose how much to distrust themselves.
The original long-only solver uses a primal active-set method. On free assets, solve the equality-constrained subproblem; if a weight would cross zero, stop at the boundary and fix it. When a target is reached, test multipliers and release a violating bound. Positive-definite input and numerical tolerances matter; the implementation also has an iteration cap. Solver correctness does not establish statistical or implementation performance.
The tools this part adds. Covariance estimators; Markowitz's rules; views; risk-based allocation; tails; growth; and the theory of the risk illusion. And the thirtieth rule. An optimized portfolio enters the House only with its covariance shrunk or cleaned, and the method recorded; with its risk reported both in sample and on data its weights did not see; with its gross exposure, turnover and largest weight stated; and compared, after costs, with one over N and with a risk-based rule that needs no expected returns at all.
Three review cases. For a low-volatility backtest, ask for timing, K over T, covariance estimator, frozen preprocessing and independent risk measurement; the Gaussian multiplier is a model benchmark, not a known correction for every backtest. For a highly levered estimated-mean portfolio, inspect sign normalisation, concentration, financing and paired net comparisons. A risk-parity loss is possible without a solver defect. Correlation and volatility estimates, leverage and regime changes must be checked before causal explanations are claimed.
For the researcher: why the optimizer underestimates its own riskPhD7 min
For the researcher: exact sampling laws under a fixed Gaussian model. Sample GMV's self-reported variance is biased downward across repeated samples, while its true population variance cannot beat the population minimum. That does not mean every realised self-report is too low. We will state the assumptions, distributions and limits separately.
Fix a population before drawing data. Let returns be independent identically distributed Gaussian vectors with fixed positive-definite covariance Sigma. The population GMV has unit budget and no inequality constraints. From T observations form the demeaned divisor-T-minus-one covariance, so n times the estimate is Wishart with n equal to T minus one. Require n at least K for an invertible sample covariance. The reported variance uses that fitted covariance; the true variance evaluates the same fitted weights under fixed Sigma. The latter is population risk, not one future sample variance.
The in-sample distribution. Reported GMV variance is the reciprocal of the ones-vector quadratic form in the inverse estimate. For fixed nonzero a and full-rank Wishart W, the ratio of population inverse quadratic form to Wishart inverse quadratic form is chi-square with n minus K plus one degrees of freedom. Set a to ones and W to n times the sample covariance. Expected reported variance relative to the population minimum is n minus K plus one over n. It is below one for K greater than one, but the chi-square has an unbounded upper tail: an individual report can exceed the minimum or its own population risk.
Why the lemma holds, in four lines. Change coordinates so the fixed vector is the first axis; the ratio does not change. The top-left entry of an inverse matrix is one over a Schur complement: the first variance left over after regressing on the others. For a Wishart matrix that complement is again Wishart, a scaled chi-square, with K minus one fewer degrees of freedom: each of the other coordinates uses one up. Divide by the true complement, and the ratio is a chi-square with n minus K plus one degrees of freedom. The optimizer's optimism is exactly those lost degrees of freedom.
The population risk distribution. Whiten and rotate the transformed budget vector to the first coordinate. In these coordinates sample GMV weights are one followed by minus the regression coefficient beta. Conditional on the remaining Wishart block C, beta is normal with covariance C inverse. Mixing over C gives a spherical multivariate t with n minus K plus two degrees of freedom. Population risk relative to its minimum is one plus beta squared, giving the displayed F law for K at least two. Its finite expectation requires n greater than K and equals n minus one over n minus K. With one asset the true-risk ratio is exactly one.
A sequence of dimensions and samples. Let K and T grow with K over T tending to gamma strictly below one. Under the stated IID Gaussian model the chi-square and F components concentrate. Reported variance divided by the population minimum tends in probability to one minus gamma; true risk tends to one over one minus gamma. Their random ratio tends to one over one minus gamma squared. With gamma one half the limiting multiplier is four. Extensions beyond normality need explicit moment, dependence and spectral regularity conditions. The limit alone does not validate every heavy-tailed or changing-covariance backtest.
Check it, with the industries' own covariance as the truth. The red line is the limit of what the optimizer reports, the teal one the limit of what it has. The dots are simulations, a thousand samples at each length. At ten years of data they give and , against exact values of and . At five years the true variance is times the minimum, while the optimizer reports .
The saved thousand-draw distributions at T equal to a hundred and twenty. Here the displayed reported-risk counts lie below the population minimum, and every cached draw falls within the shown bins. Each height is its count divided by a thousand, not its fraction of the peak. This finite sample does not remove the chi-square upper tail. True population variance is at least the population minimum by definition of the optimum. Its right tail reflects directional estimation error. Neither fact implies that the reported variance is below true variance for every possible draw.
The exact laws concern sample-covariance GMV. The teal curve is its high-dimensional limit; the dots average a hundred Gaussian draws in Chapter four, so finite-sample expectations and Monte Carlo variation remain relevant. At sixty observations, nonlinear shrinkage has true-risk ratio , versus for sample covariance. This different estimator has a different law. Its improvement in the chosen population is not a universal escape from estimation risk.
A descriptive check on research-period industry returns. With sixty-month windows, average forecast variance and average next-twelve-month realised variance correspond to and percent annualised volatility. Their ratio is , versus for the ratio of Gaussian expectations. At a hundred and twenty months the values are and . This is a ratio of averages, not an average of individual ratios. The comparison does not identify how much of the gap comes from tails, dependence, covariance changes or noisy realised-variance measurement.
Descriptive research-period calibration. Red is the ratio of average next-year realised variance to average sample-covariance forecast; yellow is a Gaussian ratio of expectations. The constant-correlation rule, now assessed with its own fitted covariance, gives ratios and , versus sample values and . This differs from Chapter two's common sample-risk proxy. Changing weights and forecast estimators together does not isolate a causal shrinkage effect, and it does not ensure conditional risk forecasts are accurate.
What the bias correction means. Under the fixed IID Gaussian model and n greater than K, multiply the sample-GMV reported variance by the displayed ratio of expectations. Across repeated training samples this estimates the ensemble mean of fitted weights' true variance without bias. It is not a conditional guarantee for this particular fitted portfolio, and not the expected ratio of true to reported variance. Shrinkage changes the estimator and its distribution; the sample-only factor does not automatically transfer. Independent, appropriately timed data can measure risk with its own uncertainty. Dependence, regime changes, selection and execution still need separate treatment.
Three research directions. Derive useful finite-sample or robust risk laws for explicitly specified heavy-tailed, dependent and changing-covariance models. Broad distribution classes need not admit one universal formula. Optimise the estimator for portfolio loss, rather than assume Frobenius covariance loss has the same optimum; account for tuning and implementation costs. When K is at least T, demeaning makes the sample covariance singular. Ridge, factor and other regularizers define different feasible estimation problems that need their own assumptions and validation.
Pause and predict. In the IID Gaussian high-dimensional GMV model, take gamma equal to one hundred over two hundred and fifty. What is the limiting true-to-reported variance ratio, and why is it not a known ratio for one fitted portfolio?
Recap, desk questions, problemsAll tracks3 min
The first seven lessons. Gaussian simulations separate fitted promises from population evaluation. Retrospective rolling comparisons do not prove universal failure of means. Random-matrix support is a null benchmark, not a noise classifier. Shrinkage depends on its target and loss. Constraints have an exact unit-budget identity, without guaranteed future improvement. Black-Litterman depends on prior and covariance conventions. ERC and HRP need different interpretations and still face estimation risk.
The remaining lessons. CVaR requires a discrete tail convention and enough relevant scenarios. Kelly needs a stated model, and a finite portfolio grid differs from Cover's continuous theorem. Entropy pooling reweights supplied scenarios. The saved network has a validation-scaling leak. Evaluation protocol and fixed arithmetic replace a strategy verdict. The research proof gives exact Gaussian sampling laws and ensemble bias, not a guarantee that every realised report understates risk.
Six desk checks. Ask how an objective selects flattering errors. A low reported variance does not identify its true risk without assumptions. A constraint identity does not guarantee better future performance.
Without views, Black-Litterman's weights depend on the covariance convention. Fractional Kelly is a model calculation, not a universal half-bet rule. An unchanged equal-weight target can still require trading because holdings drift. Full solutions are in the bilingual notes.
Twelve problems in three groups. The first six derive fixed-covariance weights, the MP null benchmark, fixed-target shrinkage, no-view Black-Litterman and diffusion Kelly. Problems seven through ten separate continuous and finite-mixture bounds, calculate discrete tail risk and entropy probabilities, and compare exact Gaussian expectations with high-dimensional limits. Two qualifying problems prove the Wishart and F sampling laws with their conditions, then establish Jagannathan-Ma on the unit-budget affine set. Complete English and Chinese solutions are in the notes.
These questions return later. Part thirty-one studies factor risk models, costs and decisions through time. Part thirty-two considers macro allocation. Part forty develops risk measures and expected shortfall. The finale reviews the full record and evaluation policy; a bookkeeping or statistical correction alone does not certify a selected strategy.
The notes identify the textbooks and papers for each method, from Markowitz to nonlinear shrinkage and decision-focused learning. Measured quantities come from audited ordinary originals; population simulations and fixed arithmetic have explicit labels. Paper claims remain attributed, and the sealed strategy experiment is excluded.
The House now has a portfolio desk: estimators that know their noise, rules that need fewer estimates, and a duty to report risk on data the weights never saw. Next, Part thirty-one: risk models, costs and trading through time. The fundamental law of active management, derived; factor risk models; and how to trade toward a moving target when every trade costs money.
Where it goes next. The portfolio needs a risk model and a cost model before it can trade: Part 31.
Key results
The part's results in one place, for revision.
Try it
Lab 30 · The minimum-variance portfolio and its broken promise
Estimate a covariance matrix from T months of K assets and build the minimum-variance portfolio. Compare the risk it promises with the risk it delivers as K/T grows, against the exact formulas, then repeat with Ledoit-Wolf shrinkage and with 1/N.
python -m videos.quant.labs 30
needs numpy, scipy, matplotlib, numba · download lab30.py ·
source on GitHubK = 10 assets, T = 120 promised 0.92 delivered 1.09 (theory 1.08) Ledoit-Wolf 1.09 1/N 1.47
K = 30 assets, T = 120 promised 0.76 delivered 1.33 (theory 1.33) Ledoit-Wolf 1.17 1/N 1.44
K = 60 assets, T = 120 promised 0.49 delivered 2.03 (theory 2.00) Ledoit-Wolf 1.50 1/N 2.63
K = 90 assets, T = 120 promised 0.26 delivered 4.03 (theory 4.07) Ledoit-Wolf 1.73 1/N 3.14
K = 110 assets, T = 120 promised 0.08 delivered 13.46 (theory 13.11) Ledoit-Wolf 1.84 1/N 3.16
Variances relative to the true minimum. The sample optimizer promises (1 - K/T) and delivers 1/(1 - K/T): the gap is the square of that ratio.
The code (60 lines; it asserts its own result)
"""Lab 30: the optimizer underestimates its own risk; shrinkage gives most of it back."""
import numpy as np
from videos.quant import labs
from explainer.quant.house import portfolio
TITLE = "The minimum-variance portfolio and its broken promise"
GOAL = ("Estimate a covariance matrix from T months of K assets and build the minimum-variance portfolio. Compare "
"the risk it promises with the risk it delivers as K/T grows, against the exact formulas, then repeat with "
"Ledoit-Wolf shrinkage and with 1/N.")
TASKS = [
"Add long_only=True to portfolio.gmv. Why do constraints behave like shrinkage (Jagannathan and Ma)?",
"Swap lw_identity for lw_constcorr or lw_nonlinear. Which target suits a one-factor market?",
"Give the assets fat-tailed returns (multivariate t). Do the exact Gaussian formulas still hold?",
]
def run(seed=0):
rng = np.random.default_rng(seed)
T = 120
lab = labs.Lab()
Ks = np.array([10, 30, 60, 90, 110])
rows = {k: [] for k in ("promised", "delivered", "theory_in", "theory_out", "lw", "equal")}
for K in Ks:
beta = rng.uniform(0.6, 1.4, K)
Sigma = np.outer(beta, beta) * 0.04 ** 2 + np.diag(rng.uniform(0.04, 0.09, K) ** 2)
w_star = portfolio.gmv(Sigma)
v_min = w_star @ Sigma @ w_star
sim = portfolio.gmv_sim(Sigma, T, 150, rng)
th = portfolio.gmv_theory(int(K), T)
lw, eq = [], np.full(K, 1 / K)
for _ in range(25):
R = rng.multivariate_normal(np.zeros(K), Sigma, T)
w = portfolio.gmv(portfolio.lw_identity(R)[0])
lw.append(w @ Sigma @ w / v_min)
for k, v in zip(rows, (np.mean(sim["in"]), np.mean(sim["out"]), th["in"], th["out"], np.mean(lw), eq @ Sigma @ eq / v_min)):
rows[k].append(v)
lab.row(f"K = {K:>3} assets, T = 120", f"promised {rows['promised'][-1]:.2f} delivered {rows['delivered'][-1]:5.2f} "
f"(theory {th['out']:5.2f}) Ledoit-Wolf {rows['lw'][-1]:.2f} 1/N {rows['equal'][-1]:.2f}")
lab.note = ("Variances relative to the true minimum. The sample optimizer promises (1 - K/T) and delivers "
"1/(1 - K/T): the gap is the square of that ratio.")
assert np.allclose(rows["promised"], rows["theory_in"], rtol=0.08) and np.allclose(rows["delivered"], rows["theory_out"], rtol=0.15)
assert rows["lw"][-1] < 0.5 * rows["delivered"][-1] and rows["lw"][2] < rows["delivered"][2]
fig, ax = labs.figure(1, size=(9.6, 4.4))
g = np.linspace(0.02, 0.95, 100)
ax.plot(g, 1 / (1 - g), color=labs.LOSS, label="delivered: 1 / (1 - K/T)")
ax.plot(g, 1 - g, color=labs.GAIN, label="promised: 1 - K/T")
ax.plot(Ks / T, rows["delivered"], "o", color=labs.LOSS)
ax.plot(Ks / T, rows["promised"], "o", color=labs.GAIN)
ax.plot(Ks / T, rows["lw"], "s-", color=labs.P, label="Ledoit-Wolf shrinkage, delivered")
ax.plot(Ks / T, rows["equal"], "^--", color=labs.CASH, label="1/N")
ax.axhline(1, color=labs.MUTED, lw=0.8)
ax.set_yscale("log")
ax.set(title="Variance of the minimum-variance portfolio, relative to the true minimum", xlabel="assets per observation, K/T",
ylim=(0.05, 30))
ax.legend(fontsize=8)
lab.fig = fig
return lab
Now change it
- Add long_only=True to portfolio.gmv. Why do constraints behave like shrinkage (Jagannathan and Ma)?
- Swap lw_identity for lw_constcorr or lw_nonlinear. Which target suits a one-factor market?
- Give the assets fat-tailed returns (multivariate t). Do the exact Gaussian formulas still hold?
Problems, with solutions
Try each problem before opening its solution; the last two of each set are at qualifying-exam level.
Desk questions, with solutions
Six desk checks
- Flattering estimates: an objective can select input errors. Specify objective, normalisation, loss, constraints and evaluation rather than infer one universal source of failure.
- 49 assets,60 months,3%reported volatility: no true volatility follows from those facts alone. Gaussian ratios are benchmarks; audit assumptions, timing and independent risk measurement.
- Long-only improves: the adjusted quadratic identity explains a possible regularizer, not a guaranteed future benefit or causal attribution.
- No-view BL: posterior mean staysΠ; unchangedΣ recovers benchmark risky demand, while predictive(1+τ)Σ scales it by 1/(1+τ), absent other constraints.
- Estimated Kelly: full or half Kelly is not a universal recommendation. The fraction needs true strength, known variance and specified estimation/solvency assumptions.
- Fixed 1/N: relative returns drift holdings. Actual rebalance trades depend on pretrade weights and fee/cash conventions even when targets do not change.
Problems, with worked solutions
Problems 1–6: complete solutions
1. GMV. Two uncorrelated assets have annual volatilities 10% and 20%. Derive unit-budget GMV weights and volatility.
Solution
For uncorrelated variances.01 and.04, minimise.01 w²+.04(1−w)². Its derivative.02 w−.08(1−w)=0 givesw₁=.8,w₂=.2. Variance=.0064+.0016=.008, volatility√.008=.0894427. These are known covariance unit-budget weights.
2. ERC. For the same chosen covariance, derive positive equal-risk-contribution weights and volatility; compare equal money.
Solution
Equal variance contributions require(w₁σ₁)²=(w₂σ₂)². Positive weights givew₁/w₂=σ₂/σ₁=2, hence(2/3,1/3). Variance=2(.1×2/3)²=.00888889 and volatility.0942809. Equal weights have variance(.01+.04)/4=.0125 and volatility.111803. Different objectives produce different weights.
3. MP support. Compute the Marchenko–Pastur null support at N=49,T=60. State why it is not a finite-sample test of economic noise.
Solution
q=49/60=.816667,√q=.903696; edges(1±√q)²=.00927444 and 3.62405889. The reference assumes the specified independent unit-variance high-dimensional null. These finite substituted edges are not confidence limits or proof that modes in the band lack economic signal.
4. Intensity. For fixed target F and unbiased S, derive the Frobenius-optimal linear intensity, clipped to [0,1]. What changes if F is estimated from S?
Solution
Let A=E||S−Σ||²_Fand B=||F−Σ||²_F, with fixed F and E[S]=Σ. The cross term vanishes, so risk(δ)=δ²B+(1−δ)²A. Differentiation givesδ*=A/(A+B)=E||S−Σ||²/E||S−F||²; restrict it to[0,1], with allδ equivalent if A+B=0. If F is estimated from S, cross-covariance terms need not vanish, so this fixed-target derivation does not supply the fitted-target optimum.
5. BL. Black–Litterman with no views: give the posterior mean and risky demands under unchanged versus predictive covariance, with no budget constraint.
Solution
With no informative views, mean posterior isΠ=δΣ w_m and mean-uncertainty covariance M=τΣ. Using unchangedΣ gives risky demandΣ⁻¹Π/δ=w_m. Using predictiveΣ+M givesw_m/(1+τ). Other budgets, long-only constraints or rescaling define different allocation problems. Setting P=0 with positive-definiteΩhas this no-information limit; a singular defaultΩmust not be blindly inverted.
6. Kelly. In a known-parameter diffusion, market excess drift is 6%, volatility16%. Compute Kelly leverage and quadratic excess growth at twice Kelly.
Solution
In the known-parameter diffusion, f*=.06/.16²=2.34375. Excess growth is fμ−f²σ²/2. Atf=2 f*, it is 2μ²/σ²−2μ²/σ²=0, so total growth equals the risk-free rate in this model. This is not a discrete-path or solvency guarantee.
Problems, with worked solutions
Problems 7–10: complete solutions
7. Two mixture bounds. For two assets derive Cover's continuous-uniform per-period bound; separately derive the M-component uniform finite-mixture bound. Distinguish their hindsight comparison classes.
Solution
For positive gross returns, a frictionless continuous-uniform two-asset mixture satisfiesbest_continuous/mixture≤n+1, hence the log growth gap≤log(n+1)/n→0. For M fixed portfolios with equal initial capital, mixture wealth=(Σ_j S_j)/M≥max_j S_j/M, givingbest_grid/mixture≤M and log gap≤log M/n. The second competes only with its grid. A fixed grid does not approximate every continuous optimum with a certified error; neither theorem competes with arbitrary dynamic foresight strategies or includes costs.
8. Tail mass. Five equally likely losses are -2,0,1,5,10. Compute exact expected shortfall at 80% and60%, accounting for quantile mass.
Solution
At 80%, worst 20%is exactly the loss 10, giving ES=10. At 60%, worst 40%is losses 5 and 10, giving ES=7.5. Equivalently minimiseα+E[(L−α)⁺]/(1−β); quantile atoms are included only as much as necessary. Simply averaging every observation at or above a chosen quantile can use too much mass.
9. Entropy. Two scenarios have returns -10% and+10% and positive equal prior weights. Impose a+5% mean and solve the entropy-pooling probabilities.
Solution
q₁+q₂=1 and−.1 q₁+.1 q₂=.05 giveq₁=.25,q₂=.75. This is the only feasible probability vector, so it also minimises relative entropy to the positive prior. No Gaussian assumption is needed; support is fixed to the two supplied scenarios.
10. Ratios. In the IID Gaussian GMV model with K=100,T=250, compute exact expected in/out ratios, their ratio, and the gamma=.4 limiting ratio. Distinguish ratio of expectations from expected ratio.
Solution
K = 100,T=250,n=249 give E[v_in/v*]=150/249=.6024096 and E[v_out/v*]=248/149=1.6644295. Their ratio is(248/149)/(150/249), about 2.7630. The high-dimensional reference atγ=.4 is 1/.6²=2.77778. Neither is a known ratio for one fit. In the Gaussian model the report's Schur residual is independent of the regression coefficients determining out-risk, so when n > K+1 the expected random ratio is[(n−1)/(n−K)]×[n/(n−K−1)], a different quantity.
Problems, with worked solutions
Problems 11–12: qualifying solutions
11. Sampling laws and correction. (qual) Prove the inverse-Wishart quadratic chi-square lemma using a Schur complement. Derive the GMV out-risk F law via Gaussian regression, its mean conditions, concentration limits and ensemble bias correction.
Solution
Rotate a fixed nonzeroa into the first coordinate, transformingΣ and Wtogether. Partition W. Block inversion gives(W⁻¹)₁₁=1/s, where s=W₁₁−W₁₂W₂₂⁻¹W₂₁. View W as the cross-product ofn Gaussian observations. Regressing the first column on the other K−1 leavesn−K+1 residual degrees of freedom, so s/σ₁₁·₂~χ²_{n−K+1}. Since(Σ⁻¹)₁₁=1/σ₁₁·₂, this proves the inverse-quadratic lemma. Takinga=1 and W=n S gives the reported-risk law and expectation(n−K+1)/n.
For out-risk, whiten and rotate the transformed budget to the first coordinate, scaling so population minimum variance is one. Write W=[[a,b'];[b,C]], C~W ishart_{K−1}(n,I). The fitted unit-budget weights are(1,−β)withβ=C⁻¹b. Conditional on C, β~N(0,C⁻¹); integrating over Cgives√νβ a spherical multivariate t_νwithν=n−K+2. Therefore||β||²=(K−1)F_{K−1,ν}/νand true-risk ratio 1+||β||²has the stated law. Its mean needsν>2, i.e.n > K, and equals 1+(K−1)/(n−K)=(n−1)/(n−K). K = 1 is degenerate. The Gaussian regression residual producing the in-law is independent ofβ.
For K,T→∞withγ<1, the appropriate chi-square degrees of freedom diverge and chi-square/df→1 in probability. The F component likewise concentrates when its dimensions grow; fixed K withγ=0 also gives the unit limits. Slutsky then gives the in/out limits and their random ratio. Dividing E[v_out/v*]by E[v_in/v*]gives the bias factor n(n−1)/[(n−K)(n−K+1)]. Multiplying the report by it estimates the ensemble mean E[v_out]without bias; it does not condition on the fitted sample. Shrinkage, dependence, tails and changingΣ require separate laws.
12. Adjusted quadratic. (qual) With S positive definite, prove long-only GMV equivalence for adjusted S-1/2(lambda1'+1lambda'). Use zero-budget directions to explain why full-space positive definiteness of the adjusted matrix is unnecessary.
Solution
Let S≻0 andwsolve minw'Swsubject to 1'w=1,w≥0. KKT gives 2 Sw−γ1−λ=0, λ≥0 andλ_iw_i=0. Define S~=S−(λ1'+1λ')/2. Then S~w=Sw−λ/2=γ1/2. For any other unit-budgetu=w+v,1'v=0. The objective difference isu'S~u−w'S~w=2 v'S~w+v'S~v=v'Sv>0 forv≠0, because the rank correction vanishes on zero-budget directions. Thuswuniquely minimises the adjusted quadratic on that affine set even if S~is not positive definite on the whole space. This proves an algebraic equivalence, not future dominance or an identification of every unconstrained short.
Reading and notes
The part's papers
from READING.md
-
Marchenko, V., Pastur, L. (1967). "Distribution of eigenvalues for some sets of random matrices." Mat. Sbornik.
-
Michaud, R. (1989). "The Markowitz optimization enigma: is 'optimized' optimal?" FAJ.
-
Best, M., Grauer, R. (1991). "On the sensitivity of mean-variance-efficient portfolios to changes in asset means." RFS.
-
Cover, T. (1991). "Universal portfolios." Mathematical Finance.
-
Black, F., Litterman, R. (1992). "Global portfolio optimization." FAJ.
-
Chopra, V., Ziemba, W. (1993). "The effect of errors in means, variances, and covariances on optimal portfolio choice." JPM.
-
He, G., Litterman, R. (1999). "The intuition behind Black–Litterman model portfolios." Goldman Sachs.
-
Laloux, L., Cizeau, P., Bouchaud, J.-P., Potters, M. (1999). "Noise dressing of financial correlation matrices." PRL; Plerou, V., et al. (1999). "Universal and nonuniversal properties of cross correlations in financial time series." PRL.
-
Rockafellar, R. T., Uryasev, S. (2000). "Optimization of conditional value-at-risk." J. Risk.
-
Fernholz, R. (2002). Stochastic Portfolio Theory; Fernholz, R., Karatzas, I. (2009). "Stochastic portfolio theory: an overview." Handbook of Numerical Analysis.
-
Goldfarb, D., Iyengar, G. (2003). "Robust portfolio selection problems." Mathematics of Operations Research.
-
Jagannathan, R., Ma, T. (2003). "Risk reduction in large portfolios: why imposing the wrong constraints helps." Journal of Finance.
-
Ledoit, O., Wolf, M. (2004). "A well-conditioned estimator for large-dimensional covariance matrices." JMVA; "Honey, I shrunk the sample covariance matrix." JPM.
-
Kan, R., Zhou, G. (2007). "Optimal portfolio choice with parameter uncertainty." JFQA.
-
Meucci, A. (2008). "Fully flexible views: theory and practice." Risk.
-
DeMiguel, V., Garlappi, L., Uppal, R. (2009). "Optimal versus naive diversification: how inefficient is the 1/N portfolio strategy?" RFS.
-
Brandt, M., Santa-Clara, P., Valkanov, R. (2009). "Parametric portfolio policies." RFS.
-
Maillard, S., Roncalli, T., Teïletche, J. (2010). "The properties of equally weighted risk contribution portfolios." JPM.
-
Asness, C., Frazzini, A., Pedersen, L. H. (2012). "Leverage aversion and risk parity." FAJ.
-
Ledoit, O., Wolf, M. (2012). "Nonlinear shrinkage estimation of large-dimensional covariance matrices." Annals of Statistics; (2017) "Nonlinear shrinkage of the covariance matrix for portfolio selection: Markowitz meets Goldilocks." RFS; (2020) "Analytical nonlinear shrinkage of large-dimensional covariance matrices." Annals of Statistics.
-
López de Prado, M. (2016). "Building diversified portfolios that outperform out of sample." JPM.
-
Bun, J., Bouchaud, J.-P., Potters, M. (2017). "Cleaning large correlation matrices: tools from random matrix theory." Physics Reports.
-
Donti, P., Amos, B., Kolter, J. Z. (2017). "Task-based end-to-end model learning in stochastic optimization." NeurIPS.
-
Zhang, Z., Zohren, S., Roberts, S. (2020). "Deep learning for portfolio optimization." J. Financial Data Science.
-
Pedersen, L. H., Babu, A., Levine, A. (2021). "Enhanced portfolio optimization." FAJ.
-
Butler, A., Kwon, R. (2023). "Integrating prediction in mean-variance portfolio optimization." Quantitative Finance.
-
Added in the build (checked at the source, November 2026): Jorion, P. (1986). "Bayes-Stein estimation for portfolio analysis." JFQA 21; Jobson, J. D., Korkie, B. (1981). "Performance hypothesis testing with the Sharpe and Treynor measures." JF 36; Memmel, C. (2003). "Performance hypothesis testing with the Sharpe ratio." Finance Letters 1; Scherer, B. (2002). "Portfolio resampling: review and critique." FAJ 58; Kempf, A., Memmel, C. (2006). "Estimating the global minimum variance portfolio." Schmalenbach Business Review 58; Bai, Z., Liu, H., Wong, W.-K. (2009). "Enhancement of the applicability of Markowitz's portfolio optimization by utilizing random matrix theory." Mathematical Finance 19; El Karoui, N. (2010). "High-dimensionality effects in the Markowitz problem and other quadratic programs with linear constraints: risk underestimation." Annals of Statistics 38; Tu, J., Zhou, G. (2011). "Markowitz meets Talmud." JFE 99; DeMiguel, V., Garlappi, L., Nogales, F., Uppal, R. (2009). "A generalized approach to portfolio optimization: improving performance by constraining portfolio norms." Management Science 55; Spinu, F. (2013). "An algorithm for computing risk parity weights." SSRN; Maillard, S., Roncalli, T., Teïletche, J. (2010). "The properties of equally weighted risk contribution portfolios." JPM 36; Ledoit, O., Wolf, M. (2017). "Nonlinear shrinkage of the covariance matrix for portfolio selection: Markowitz meets Goldilocks." RFS 30; Ledoit, O., Wolf, M. (2020). "Analytical nonlinear shrinkage of large-dimensional covariance matrices." Annals of Statistics 48; Bodnar, T., Parolya, N., Schmid, W. (2018). "Estimation of the global minimum variance portfolio in high dimensions." EJOR 266; Zhang, Z., Zohren, S., Roberts, S. (2020). "Deep learning for portfolio optimization." JFDS 2, arXiv 2005.13665; Elmachtoub, A., Grigas, P. (2022). "Smart 'predict, then optimize'." Management Science 68; Muirhead, R. (1982). Aspects of Multivariate Statistical Theory. Wiley.
Papers and sources
Papers, chapter by chapter
- ch. 1: Markowitz (1952); Merton (1972); Michaud (1989); Best and Grauer (1991); Chopra and Ziemba (1993); Scherer (2002).
- ch. 2: DeMiguel, Garlappi and Uppal (2009), RFS 22; Kan and Zhou (2007), JFQA 42; Tu and Zhou (2011), JFE 99.
- ch. 3: Marchenko and Pastur (1967); Laloux, Cizeau, Bouchaud and Potters (1999); Bun, Bouchaud and Potters (2017).
- ch. 4: Ledoit and Wolf (2003, 2004a, 2004b, 2020).
- ch. 5: Jagannathan and Ma (2003), JF 58; DeMiguel, Garlappi, Nogales and Uppal (2009), Management Science 55.
- ch. 6: Black and Litterman (1992), FAJ; He and Litterman (1999); Jorion (1986), JFQA 21.
- ch. 7: Maillard, Roncalli and Teïletche (2010); Spinu (2013); López de Prado (2016), JPM.
- ch. 8: Goldfarb and Iyengar (2003); Ceria and Stubbs (2006); Artzner, Delbaen, Eber and Heath (1999); Rockafellar and Uryasev (2000).
- ch. 9: Kelly (1956); Breiman (1961); Cover (1991); Fernholz (2002).
- ch. 10: Meucci (2008), "Fully flexible views".
- ch. 11: Zhang, Zohren and Roberts (2020), JFDS; Elmachtoub and Grigas (2022), Management Science.
- ch. 12: Jobson and Korkie (1981); Memmel (2003).
- Research: Muirhead (1982); Kempf and Memmel (2006); Bai, Liu and Wong (2009); El Karoui (2010); Ledoit and Wolf (2017); Bodnar, Parolya and Schmid (2018).
For the researcher
Research: exact Gaussian sampling laws
Fix IID Gaussian returns with positive-definite covarianceΣ. There are K assets and T observations, n=T−1, and S is the demeaned divisor-n sample covariance. Require n ≥ K for full rank. Unit-budget GMV is unrestricted apart from its budget. Write v*=1/(1'Σ⁻¹1), v_in=1/(1'S⁻¹1) and v_out=w_hat'Σ w_hat. For fixed nonzeroa and W~W ishart_K(n,Σ),
\[\frac{a'\Sigma^{-1}a}{a'W^{-1}a}\sim\chi^2_{n-K+1},\qquad \frac{v_{in}}{v_*}\sim\frac{\chi^2_{n-K+1}}n.\]
For K ≥ 2,
\[\frac{v_{out}}{v_*}\sim1+\frac{K-1}{n-K+2}F_{K-1,n-K+2},\qquad E\frac{v_{out}}{v_*}=\frac{n-1}{n-K}\quad(n>K).\]
When K = 1, the out-risk ratio is identically one. Downward bias of the report is an ensemble expectation, not a statement that every draw understates risk. The chi-square upper tail is unbounded. Under K,T→∞ and K/T→γ<1, the in/out ratios concentrate at 1−γ and 1/(1−γ); their random ratio tends to 1/(1−γ)². Extensions require explicit moment, dependence and spectral conditions.
Multiplyingv_in by n(n−1)/[(n−K+1)(n−K)] is ensemble-unbiased for E[v_out] under this fixed Gaussian model. It is not a conditional forecast guarantee for the fitted portfolio, nor E[v_out/v_in]. Research-period next-year variance ratios are descriptive ratios of averages under changing conditions, not direct measurements of the fixed population law.
Data, scope and reproducibilityData, computations and interpretation
The unchanged originals use Kenneth French's 49 value-weighted industry portfolios and monthly risk-free rates through December 2020, daily industry returns through 2020 for spectra, and firm-count/mean-size blocks for industry-cap proxies. The archived files are parsed before their through-date masks. Frozen subset hashes verify those subsets; they do not establish historical publication timing, complete point-in-time membership or attainable execution. Simulations stipulate the full 1970–2020 research sample moments as a fixed Gaussian population; they do not measure historical future delivery.
All compute.py files, House routines and three registries remain unchanged. Permitted ordinary items are universe, michaud, rolling, spectrum, shrink, constraints, bl, riskparity, cvar, growth, views, e2e, theory, factor. The envelope original and its cache/payload are excluded. No force, refresh, new market trial, registration, opening or strategy scoring is performed. Existing metadata is 23,480 through Part 29, 23,525 through Part 30, 23,562 globally; the increment 45 is bookkeeping, not independent tests.
The presentation distinguishes these details of the saved algorithms:
- Rolling returns are monthly excess returns. All Chapter 2
pred_volvalues evaluate weights using the trailing sample covariance, including weights selected with shrinkage. They are not each estimator's own covariance forecast. The research chapter's shrinkage comparison instead uses its own fitted covariance. - The rolling rule keyed “inverse volatility” actually uses inverse variance. The standalone risk-parity snapshot uses inverse standard deviation. Cache identifiers are retained; these are distinct rules.
- Tangency weights are the inverse-covariance mean direction normalised by its weight sum. A negative denominator reverses its positive-Sharpe orientation; near-zero denominators can produce extreme gross exposures. This saved rule is not a universally well-behaved maximum-positive-Sharpe allocation.
- Turnover is half the absolute change in target weights, excluding drifted holdings. Costs subtract average chosen charges from mean returns and retain gross volatility. This is a sensitivity proxy, with financing, borrow, slippage and impact omitted. Maintaining a fixed 1/N target can require trades despite zero target-weight changes.
- Sample covariance and nonlinear shrinkage use divisor T−1; the local linear shrinkage routines use demeaned divisor T moments. Fixed-target unbiased-S intensity algebra does not transfer unchanged to a target estimated from S. The spectral oracle minimises Frobenius loss within sample eigenvectors, not portfolio loss. Sorted population eigenvalues are not the same directional objects.
- MP support is an asymptotic null benchmark. In-bulk eigenvalues can contain weak structure; outliers need economic interpretation. The daily original zero-fills missing returns. Clipping preserves trace before diagonal renormalisation, which can alter eigenvalues. Correlation heatmaps retain negative entries.
- Jagannathan–Ma is an exact adjusted quadratic identity on the unit-budget affine set. Full-space positive definiteness of the adjusted matrix is unnecessary, and future performance improvement is not guaranteed. Binding multipliers do not simply identify every asset that the original unconstrained optimum shorted.
- Black–Litterman estimates delta from sample moments and uses a specified Gaussian prior/view model. Its view-error multiplier is not a confidence probability. The numerical example uses unchanged covariance; predictive covariance adds posterior mean uncertainty and can change weights even when a view agrees with the prior mean. Unconstrained risky demands need not sum to one.
- ERC equalises fitted variance-contribution shares. HRP uses a sample-dependent single-linkage order and inverse-variance cluster proxies; it is not generally ERC or GMV and does not isolate estimation errors across clusters.
- Expected shortfall averages the worst probability mass, taking a fraction of quantile atoms when needed. The LP uses the exact scenario objective. The score helper uses an interpolated quantile and positive-part formula; finite discrete conventions can differ.
- Kelly's quadratic log-growth expression is exact in the specified diffusion and approximate for discrete returns. Historical fitted leverage and the scalar fractional-Kelly calculation do not identify future optimal exposure or a universal half-Kelly prescription. Discrete solvency and financing need separate modelling.
- Cover's continuous-uniform theorem differs from the saved uniform mixture of 201 grid portfolios. The grid best/mixture wealth ratio is at most 201, while the two-asset continuous bound is n+1. A fixed grid does not certify its continuous hindsight optimum. The monthly industry-cap diversity illustration is not a verification of continuous-time relative arbitrage after costs.
- Entropy effective scenarios measure probability concentration, not independent observations. The market stress fixes a second moment about the prior mean; its displayed root is not generally posterior standard deviation, since the posterior mean is not constrained to stay fixed. Arbitrary correlations and ranks need a suitable feasible formulation.
- The original end-to-end demonstration scales features using both training and validation before its 1975–2005/2006–2020 split, leaking validation moments. Validation is repeatedly inspected. Logged training scores are pre-update and validation scores post-update; final tables use final weights. Only one seed and score histories are saved, without intermediate weight checkpoints. The two-step comparator clips an inverse-covariance direction positive and renormalises; it is not the exact long-only MV solver. These are retrospective diagnostics, with no new fit to seek a better result.
All optimizer-cloud coordinates, including negative model means and high volatility, remain visible. Spectrum and return histograms do not fold out-of-range values into boundary bins. Research histogram heights are counts/1000. The displayed T=120 histograms retain all 1,000 counts each. The saved T=60 out-risk bins 0–6 contain 664 counts, and T=80 contain 999; those other cached histograms lose tail locations. Their omitted counts are disclosed without inventing values or rerunning the simulation.
Data, scope and reproducibilityEvaluation protocol and fixed arithmetic
Freeze the entire information and trading procedure: data vintage, availability, preprocessing, windows, hyperparameters, solver, constraints, stopping, benchmarks and reporting. Specify drifted holdings, cash, fills, financing, borrow and costs. Use paired comparisons and inference appropriate to dependence and selection. A wide interval does not establish equivalence; one fresh period alone does not cure leakage or low power. No sealed strategy verdict is supplied.
Two chosen uncorrelated annual volatilities 10% and 20% give GMV weights(.8,.2) and volatility 8.944%; ERC weights(2/3,1/3) give 9.428%; equal money gives 11.180%. These are fixed covariance calculations, with no historical assets or return comparison.
A separate fixed one-period toy starts with half a dollar in each asset and simple returns(10%,0). Pretrade values become(.55,.50), wealth 1.05 and weights(11/21,10/21). Returning to equal weights before fees sells .025 and buys .025. The target has not changed, but gross trading is .05 initial dollars. At a chosen 5 bp per dollar traded, the fee is.05×.0005=.000025 initial dollars, or0.25 bp of initial wealth. Fees are paid separately; this is not a self-financing post-fee rebalance or a complete net-return model.
中文讲义
本讲的中文说明、交易台问题与习题解答(与英文版对应)。
导言第30部分:组合构建
科学表述、双语构建与实际画面审阅已完成。十四个获准的常规原始计算已恢复,没有重试。完整成片连续听审与发音审查仍单独待办;封存策略在计数/缓存入口之前即被排除。
十六个场景讨论估计误差、等权、随机矩阵参考、协方差收缩、约束、Black–Litterman、ERC与HRP、鲁棒优化、CVaR、增长、熵池化、端到端学习、评估协议、研究证明和完整习题。材料用于方法教育。
Desk questions, with solutions六个交易台检查
- 乐观误差为何被选择:看目标、归一化、约束、损失和评估,不能归因于一个普遍机制。
- 49资产60个月、报告3%波动:不能据此知道真实风险;高斯倍数只是条件模型参考。
- 只做多改善:调整二次型恒等式不是未来优势保证。
- 无观点BL:均值保持Π,不变Σ恢复基准风险需求;预测(1+τ)Σ给基准/(1+τ),另加约束会变。
- 估计Kelly:分数需要真实强度、已知方差和明确误差及偿付假设,不能普遍选一半。
- 固定等权仍需交易:收益使持仓漂移,交易来自成交前权重,费用分母另需说明。
Problems, with worked solutions习题1–6:完整解答
1. GMV。 两项不相关资产年波动率为 10% 与 20%。推导单位预算 GMV 权重及波动率。
解答
最小化.01w²+.04(1−w)²,一阶条件.02w−.08(1−w)=0,得(.8,.2)。方差.008,波动.0894427。已知协方差、预算为一,不含收益预测。
2. ERC。 同一选定协方差下,推导正的等风险贡献权重与波动率,并与等金额配置比较。
解答
正权重下(w₁σ₁)²=(w₂σ₂)²给权重比2,得(2/3,1/3)。方差.00888889、波动.0942809。等权方差.0125、波动.111803。等钱、等风险和最小方差目标不同。
3. MP。 计算 N=49、T=60 时 Marchenko–Pastur 零假设支持区间;说明为何不是经济噪声的有限样本检验。
解答
q=49/60=.816667,平方根.903696,边界(1±√q)²约.00927444、3.62405889。独立单位方差、高维渐近零假设下成立;代入有限维度不是置信界,更不识别经济信号。
4. 强度。 固定目标 F、无偏 S 下,推导截断到 [0,1] 的 Frobenius 最优线性强度。若 F 由 S 估计,有何变化?
解答
令A=E||S−Σ||²、B=||F−Σ||²。F固定且S无偏使交叉项为零,风险δ²B+(1−δ)²A,导数为零得δ=A/(A+B),等于噪声/样本到目标的期望平方距离;限制到[0,1],若分母零则所有δ相同。F也由S估计时交叉协方差不能忽略,原推导不直接适用。
5. BL。 无观点的 Black–Litterman:无预算约束时,分别给出原协方差与预测协方差下的后验均值和风险资产需求。
解答
无信息观点下均值Π=δΣw_m,均值不确定性M=τΣ。用Σ优化得w_m;用Σ+M得w_m/(1+τ),这里没有额外预算约束。若P=0,取正定Ω才可直接用精度公式;不能盲目反演默认的奇异零矩阵。
6. Kelly。 已知参数扩散模型中,市场超额漂移为 6%,波动率 16%。计算凯利杠杆及两倍凯利时的二次超额增长率。
解答
已知参数扩散模型f*=.06/.16²=2.34375。二次超额增长fμ−f²σ²/2,在2f*处为零,总增长等于无风险率。这不是离散路径或不破产保证。
Problems, with worked solutions习题7–10:完整解答
7. 混合界。 两项资产下推导 Cover 连续均匀混合的每期界;另推导 M 分量均匀有限混合界,区分两者的事后比较类。
解答
正价格比、无摩擦再平衡时,两资产连续均匀混合满足连续事后最优/混合≤n+1,故每期对数增长差≤log(n+1)/n→0。M个固定组合等初始资本的混合财富为ΣS_j/M≥maxS_j/M,故网格最优/混合≤M,每期差≤logM/n。后者只竞争网格,不能认证连续最优近似误差,也不竞争任意动态先知策略、不含成本。
8. ES。 五个等概率损失为 -2、0、1、5、10。计入分位数质量,计算 80% 与 60% 的精确预期亏损。
解答
80%时最坏20%正好是10,ES=10;60%时最坏40%是5和10,ES=7.5。按概率质量计,分位点原子只取所需部分;无条件把所有“大于等于分位点”的观测平均,可能取多了质量。也可直接最小化α+E[(L−α)⁺]/(1−β)。
9. 熵。 两个情景收益为 -10% 与 +10%,先验权重相等且为正。施加 +5% 均值,求熵池化概率。
解答
q₁+q₂=1、−.1q₁+.1q₂=.05给(.25,.75)。这是唯一可行概率向量,所以也是相对正先验的熵最优;不需高斯,仅使用所给两情景。
10. 倍数。 IID 高斯 GMV 中,K=100、T=250。计算内外风险相对总体最小方差的精确期望比率、两者之比及 gamma=.4 的极限比率,区分期望之比与比率的期望。
解答
K=100、T=250、n=249:报告风险相对总体最小值的期望150/249=.6024096,真风险期望248/149=1.6644295。期望之比约2.7630,γ=.4的极限参考2.77778。都不是某次拟合的已知倍数。高斯下报告的舒尔残差与决定真风险的回归系数独立,n>K+1时随机比的期望为[(n−1)/(n−K)]×[n/(n−K−1)],与期望之比不同。
Problems, with worked solutions习题11–12:资格题完整证明
11. 分布及修正。 (资格题)以 Schur 补证明逆 Wishart 二次型卡方引理;用高斯回归推导 GMV 外部风险的 F 分布、均值条件、集中极限及系综偏差校正。
解答
固定非零a可通过同时变换a、W、Σ转到第一坐标。分块逆矩阵给(W⁻¹)₁₁=1/s,s=W₁₁−W₁₂W₂₂⁻¹W₂₁。把W写作n个高斯向量的交叉积,将第一列对其他K−1列回归,残差自由度n−K+1,因此s/σ₁₁·₂为该自由度χ²;而(Σ⁻¹)₁₁=1/σ₁₁·₂,得到逆二次型引理。取a=1、W=nS,报告风险比为χ²_{n−K+1}/n,期望(n−K+1)/n。
真风险方面,先白化并旋转变换后的预算向量到第一坐标,缩放至总体最小方差为一。写W=[[a,b'];[b,C]],C为K−1维、n自由度单位尺度Wishart。拟合单位预算权重为(1,−β),β=C⁻¹b。给定C,β为N(0,C⁻¹);积分C得到√νβ服从球面对称多元t,ν=n−K+2。故||β||²=(K−1)F_{K−1,ν}/ν,真风险比为1+||β||²。有限均值需ν>2即n>K,得(n−1)/(n−K)。K=1时真风险比恒一。报告风险所用回归残差与β独立。
K、T共同趋大且K/T→γ<1时,相应χ²/自由度依概率趋一,F部分也集中;固定K且γ=0亦得一。由Slutsky,报告、真风险和随机比的极限依次为1−γ、1/(1−γ)、1/(1−γ)²。两个期望相除得修正n(n−1)/[(n−K)(n−K+1)];乘报告风险无偏估计的是重复训练总体中E[v_out],不是给定拟合的条件风险,更不是随机比的期望。正态性、独立性、固定正定Σ及秩条件不能省略,收缩有不同分布。
12. 调整二次型。 (资格题)S 正定时,证明仅多头 GMV 与调整矩阵 \(S-\frac12(\lambda\mathbf1^\top+\mathbf1\lambda^\top)\) 的无约束解等价;用零预算方向说明为何无需调整矩阵在全空间正定。
解答
S正定,预算一且w≥0。KKT为2Sw−γ1−λ=0、λ≥0、λ_iw_i=0。定义S~=S−(λ1'+1λ')/2,则S~w=γ1/2。任意其他单位预算u=w+v有1'v=0。二次型差2v'S~w+v'S~v=v'Sv,非零v时严格正,因为调整项在零预算方向消失。故w在预算仿射空间上唯一最优,毋须S~在全空间正定。恒等式不保证未来改善,也不识别所有原无约束空头。
参考文献对应上方逐章列表。最终冻结源上的双语节点、英文动画及精确标记区间现均已实际审阅;诊断与最终批准分开保存。完整成片连续听审与发音认证仍单独待办。
Review log of the earlier QA passes on this part: docs/qa/quant/part30.md.
Data, scope and reproducibility数据及边界
原始代码使用French的49个市值加权行业组合、截至2020年的月度/日度收益与无风险利率,以及行业公司数量和平均规模。读取归档后才按截止日期筛选。冻结子集的哈希不证明历史发布时点、完整的时点成员或可成交性。模拟把1970–2020年的研究矩指定为固定高斯总体,不能称为历史未来交付。
计算代码、House算法和三份登记文件不变。只恢复前文列出的十四个常规项目,不访问envelope策略缓存或载荷,不强制重算、刷新、新增市场试验、登记、开启或评分。既有累计登记为第29部分23,480、第30部分23,525、全系列23,562;增加45是记账,不是独立检验数。
第二章所有规则的预测风险都用尾随样本协方差评价权重,不是各收缩估计器自报的风险。研究章另用收缩规则自己的拟合协方差,两个口径不同。滚动键名inverse volatility实际是逆方差,独立风险平价快照才用逆标准差。切点方向按权重和归一化,负分母可反转正夏普方向,接近零可产生极大总敞口。
换手仅取目标权重变化的一半,漏掉持仓漂移。成本表从均值中扣平均费用,保留毛波动率,故是敏感性近似。固定等权目标不等于零交易。样本和非线性收缩用T−1分母,局部线性收缩用去均值后的T分母。固定目标的强度公式不直接适用于同数据估出的目标;样本特征向量下的Frobenius先知值也不是组合损失先知值。
MP区间是渐近零假设参考,不是噪声分类器。原日度代码把缺失收益填零;特征值平均步骤保迹,随后的对角归一化仍可改变谱。负相关保留符号。Jagannathan–Ma只需预算为一的仿射空间上有相同曲率,不要求修改矩阵在全空间正定,更不保证未来改善。
BL中的delta也来自样本估计;观点误差方差倍数不是置信概率。不变协方差和含均值不确定性的预测协方差给不同需求;后者在观点均值等于先验时仍可能改权重。ERC等化拟合方差贡献,HRP用聚类和逆方差簇代理,两者不是同一个优化器,也不隔离估计误差。
离散ES按最坏概率质量计,必要时只取分位点原子的一部分。历史情景LP与插值分位点评分约定可能略有不同。Kelly二次增长属于所述扩散模型;拟合杠杆和分数Kelly不构成未来最优或普遍半Kelly规则。Cover连续均匀混合定理与201点网格混合不同;网格最优/混合财富比上界201,连续两资产上界n+1。行业市值的月度多样性例子不验证连续时间、扣费后相对套利。
熵有效情景数衡量概率集中度,不是独立样本数。市场压力约束是围绕先验均值的二阶矩,后验均值未固定,其平方根不一定是后验标准差。端到端原始示范在划分训练与验证前,用两个时期共同标准化特征,泄漏验证矩;验证还被反复观察。日志训练分数在更新前、验证在更新后,最终表用最终权重。只有一个种子和分数轨迹,无中间权重检查点;两步对照是逆矩阵方向截负并归一化,不是精确只做多MV解。这些是保留缺陷并披露的回顾诊断,不重新训练寻求更好成绩。
优化云图保留负模型均值和高波动尾部。直方图不把区间外数值折到边界。研究T=120的两组直方图各保留1000计数,柱高为计数/1000。缓存T=60的0–6真风险区间仅664计数,T=80有999;其他尾部的位置未存,不虚构、不重跑。
Notes协议与固定算术
冻结数据时点、预处理、窗口、调参、求解器、约束、停止和报告政策;明确漂移持仓、现金、成交、融资、借券与成本。配对比较需考虑相依和选择。宽区间不证明等价,一个新时期也不自动解决泄漏或低检验力。不提供封存策略结论。
固定不相关年波动10%、20%:GMV权重(.8,.2),波动8.944%;ERC权重(2/3,1/3),波动9.428%;等权波动11.180%。另一个单期玩具从各半美元开始,指定收益(10%,0),成交前价值(.55,.50),总值1.05,权重(11/21,10/21)。费用前恢复等权需卖.025、买.025,毛交易.05初始美元。每成交美元5基点则费用.000025初始美元,即初始财富.25基点。费用另付,未求扣费后自融资再平衡。
Build the film
python -m videos.quant.quant30.compute # the part's numbers, into .cache/quant30
python tools/make.py quant30 # the narrated film, English and Chinese
EXPLAINER_TTS=silent python tools/qa_scene.py quant30 Hook # one chapter, silent, with a contact sheet
Scenes: videos/quant/quant30. Setup: see the course page. Source of these notes: the part's README and the scenes' narration.