QQuant, Built

Act IV · Return Premia (P)

Part 27 of 43

Machine Learning for Returns

Master'sstarts at this level52 min of film 18 chaptersprerequisites: Part 6, Part 26

A model that explains four tenths of one percent of next month's returns is a good model. What can machine learning add when the signal is that small?

Returns are almost all noise, so the usual instincts from image and language models fail: more capacity fits more noise. The part trains the standard zoo on the cross-section of stocks (penalized regressions, trees, networks, ensembles), shows where the gains come from, and takes the 'virtue of complexity' claim seriously, with its critics. The theory chapter explains double descent with random-matrix tools: why the ridgeless interpolator can generalize, and why at return-like signal-to-noise only regularization helps. Autoencoders, adversarial discount factors, attention across assets and conformal intervals follow.

What you need. Parts 6 and 26; AI, Built, Parts 4-13 for the networks.

What you will be able to do

Undergraduate

  • Explain why predicting returns is a low signal-to-noise problem and what out-of-sample R squared means.

Master's

  • Train and evaluate ridge, lasso, gradient-boosted trees and network ensembles on a panel of returns with proper time splits.
  • Turn predictions into portfolios and measure what survives costs; put a conformal interval on a forecast.

PhD

  • Derive the out-of-sample risk of ridge and ridgeless regression as P/N grows (Marchenko-Pastur; Hastie, Montanari, Rosset and Tibshirani) and relate random features to kernels.

Industry

  • Describe a production pipeline for learned signals: labels, purging, monitoring, and what firms have said in public about theirs.

Contents

Each chapter has a home level. Choose a track to see what to read and watch: Undergraduate 8 min · Master's 41 min · PhD 52 min · Industry 18 min.

  1. 0Four tenths of a percentUndergraduate3 min
  2. 1A low signal-to-noise worldUndergraduate2 min
  3. 2The model zooMaster's4 min
  4. 3Where the edge livesMaster's2 min
  5. 4The virtue of complexityMaster's3 min
  6. 5The criticsMaster's3 min
  7. 6The theory of overparameterised predictionPhD5 min
  8. 7Autoencoder asset pricingMaster's3 min
  9. 8Deep SDFs with adversarial momentsPhD3 min
  10. 9Attention across assetsMaster's3 min
  11. 10Images of pricesMaster's3 min
  12. 11Foundation modelsPhD4 min
  13. 12The practitioner's toolkitIndustry3 min
  14. 13Conformal predictionMaster's3 min
  15. 14From the public record: Two Sigma and RenaissanceIndustry3 min
  16. 15Registration and evaluation for learned modelsIndustry3 min
  17. 16Rule 27: the model deskIndustry2 min
  18. 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.

Four tenths of a percentUndergraduate3 min

Machine learning for returns: what models with thousands or millions of parameters can learn from prices, what they cannot, and how to tell the difference.

Gu, Kelly and Xiu's twenty twenty stock study used roughly thirty thousand companies and ninety-four characteristics. The paper reports monthly out-of-sample R squared around point three three to point four zero percent, against a zero forecast. This is not literally a fraction of variance explained. Its best neural-network portfolio has historical gross Sharpe ratios of one point three five with market-cap weights and two point four five with equal weights. These are the authors' stock results, not our crypto illustration, and not attainable-return promises.

Use an explicit idealisation. A symmetric binary signal determines the conditional mean, with independent residual noise. Position by its sign. In this model, population R squared maps to the displayed annual Sharpe formula. One percent gives for one bet. Independent equal-risk bets multiply it by the square root of their number. All saved curves are shown across their full range. Dependence, estimation, constraints and costs change the calculation. An arbitrary measured out-of-sample R squared alone does not determine a portfolio's attainable Sharpe ratio.

The tools are older than the finance. Backpropagation was popularised in 1986; the lasso came in 1996; random forests and gradient boosting in 2001; random features in 2007; and in 2012 deep networks began winning at images, and in 2017 the transformer arrived. Marcos Lopez de Prado's practitioner's toolkit appeared in 2018, double descent was named in 2019, and in 2020 Gu, Kelly and Xiu brought the whole repertoire to the cross-section of stock returns. Since then: autoencoders, images of price charts, models with more parameters than observations, adversarial discount factors and transformers across assets; and, in 2025, a forceful critique and the first foundation models trained on market data.

The plan is to examine weak return signals, a smaller crypto model illustration and its data limitations, random-feature complexity and its critics, and Gaussian proportional-limit risk. Then come autoencoders, discount-factor portfolios, attention, chart images, foundation-model protocols, practitioner tools and conformal assumptions. Public firm records illustrate governance. The registration chapter explains existing metadata and fair comparisons while leaving the panel and sealed experiment originals excluded.

The research desk gains a model shop and an audit of what its examples support. The unchanged originals retain simplified training, period and calibration conventions. We explain those limitations, compare information sets and baselines, and preserve existing registrations. No new market trial is registered and no sealed experiment is opened or scored.

1A low signal-to-noise worldUndergraduate2 min

Why predicting returns is a different kind of machine-learning problem. These original regressions use fifteen monthly predictors, separately, to fit the next month's volatility-normalised market return. The best in-sample R squared is percent. The scaling volatility uses preceding returns, excluding the target month. Updated economic observations still need publication and vintage clocks for a deployable forecast. Welch and Goyal's published out-of-sample comparisons against a historical mean are a separate study, rather than these in-sample fits.

Return prediction presents several difficulties. Competition and implementation costs can limit exploitable signals, although small R squared is not a logical necessity. A century of monthly observations supplies only twelve hundred dates, and assets share common movements. Economic relationships and regimes can change; observed decay does not isolate trading as its unique cause. Losses also depend on position sizing and the sizes of mistakes, especially in stressed markets.

These are fixed synthetic illustrations, rather than measured signal-to-noise estimates for photographs or markets. The left panel has lower noise around a sine signal. The right uses ten times the noise standard deviation, or one hundred times its variance. Each panel displays every point with its full vertical range. Shrinkage, averaging and independent evaluation can help, but no remedy guarantees a useful trading forecast.

Under squared loss with the usual conditional-mean and training-randomness assumptions, expected error separates into irreducible noise, squared bias and estimation variance. Low signal makes that trade-off important, but does not make variance the only term. Our out-of-sample R squared compares squared error with a zero forecast. A historical-mean benchmark asks a different question. Neither estimate alone identifies attainable Sharpe, and a negative result does not establish that return prediction is impossible.

Pause and predict. In the explicit binary-signal idealisation, use population R squared of half a percent and five hundred independent equal-risk bets. Calculate the ideal annual Sharpe. Then state why arbitrary measured out-of-sample R squared does not imply that result.

2The model zooMaster's4 min

A nine-model illustration inspired by Gu, Kelly and Xiu, using the original venue-specific USDT-quoted coin research calculations. Its archive selection, target clocks and execution assumptions need examination; it is not a replication of the American stock experiment.

Start with the source boundary. The frozen public list contains 701 symbol names. That is later archive coverage, not a reconstruction of what an investor could have bought in each research week. The original reader keeps symbols with at least thirty recorded daily observations and reads public archives through 2025 before applying its research masks. Included weeks need at least ten eligible coins. Eligibility uses sixty calendar days since the first available close and a past-twenty-eight-day median quote volume of at least 250,000 USDT. The next-week target uses the last available close in the following seven days, or the current close when none is observed. That is not a verified liquidation return or proof that delisting losses are complete. This review excludes the panel-sealing output. We can explain the input protocol without showing its future-universe counts or opening a strategy experiment.

The illustration uses fifteen characteristics per coin. Momentum spans several past horizons. Risk features include volatility, extremes, skewness, Bitcoin beta and residual variation. Liquidity proxies include quote volume, price range and Amihud illiquidity; age measures days since the first available close, rather than a verified exchange listing date. Each date's features become cross-sectional ranks from minus one to one, and missing ranks become zero. Even the pointwise models therefore already use relative cross-sectional information.

Nine models illustrate three families. Least squares uses all fifteen predictors, or a chosen three-variable crypto baseline. This is not the stock paper's exact characteristic design. Elastic net combines shrinkage and sparsity; a zero coefficient does not prove a feature useless. Principal components target predictor variation, while partial least squares uses target covariance. Boosted trees add small corrective trees. Three network depths average five seeds with regularisation and early stopping. These are simplified implementations inspired by the literature, rather than an exact replication.

The original illustration expands its research window. It selects penalties and stopping times using the final twenty-six weeks before each test year. It refits for twenty nineteen and twenty twenty, but subtracting seven from an integer date is not seven calendar days. A late-December feature can have a target ending in early January. Training and validation labels are winsorised separately using their own outcomes; test targets stay raw. These limitations remain in the unchanged algorithm, so this is not a clean calendar-purged protocol.

The unchanged ensemble fits a fresh network for each seed, with seeded batches and mean squared error. Validation selects an early stopping point. Averaging can reduce seed variation when errors are imperfectly correlated, but does not remove shared bias or guarantee useful information. In this original, validation outcomes also select the model; they are not an untouched later calibration set.

The original zero-benchmark out-of-sample R squared ranges from to percent. This describes these model configurations and dates, rather than all possible return forecasts. Equal-weight quintile long-short gross Sharpe ratios range from to . Same-close fills, short availability and costs are not established. The full white ranges show two approximate IID-normal standard errors, using weekly Sharpe units before annualisation. Dependence and selection are omitted. Overlapping individual intervals do not replace inference on paired strategy differences.

Precision and power are different. For stationary IID normal weekly returns, the annualised Sharpe standard error uses the weekly Sharpe inside its variance correction. An annual Sharpe of one over two years gives about point seven one. The simpler two-standard-error heuristic is four divided by annual Sharpe squared: about four years at one and sixteen at half. It is not a prospective power calculation. A model comparison needs paired returns and their covariance, dependence and selection adjustments. Extra correlated assets do not supply proportionally more independent dates.

These are training sensitivities, not causal importance. For each model, the six largest absolute changes are selected and their signed values displayed. Replacing a characteristic by its median may interact with correlated inputs. This does not identify liquidity frictions as the cause of a return pattern, or establish that a feature will help on future dates.

Pause and predict. Estimate the uncertainty of annual Sharpe one over two years under IID normal weekly returns. Then identify the extra information needed for a paired model comparison and a prospective power calculation.

3Where the edge livesMaster's2 min

Examine where an apparent forecasting return comes from, what it costs to trade, and what these small descriptive comparisons cannot identify.

Published studies motivate the questions. Avramov, Cheng and Metzker examine how economic restrictions, difficult-to-arbitrage stocks and trading costs alter machine-learning portfolio results in their American-stock sample. Leippold, Wang and Zhou study a different Chinese-market setting with different predictors, participants and constraints. Neither paper supplies a universal cross-market ranking. Our smaller crypto illustration examines quote-volume splits, without identifying the causal source of their differences.

The original splits each week's eligible coins by past quote volume, then sorts forecasts into thirds within each half. The more-liquid mean gross Sharpe is . The less-liquid mean is , and of models have a larger value there. These are selected, dependent, short-sample comparisons. They do not establish significance, a causal illiquidity premium, or a return achievable after spreads, impact and borrow.

These are fixed fee-times-turnover scenarios. The gross portfolios use quote-volume weights, not market-capitalisation value weights. At ten basis points, annual scenario costs range from to percent. At fifty basis points, of have a negative scenario net arithmetic return. These calculations omit a validated historical fee schedule, spread, impact, borrow and capacity model. The original turnover convention is retained; these are not executable net-return estimates.

Evaluate economic restrictions as protocol choices. Compare liquid assets and stressed periods using rules fixed before evaluation; removing observations after seeing results creates another selection. A disappearing edge does not identify its cause. State turnover, fills, spreads, impact, fees and borrow, including position size. Compare weighting and long-only choices when relevant. Quote-volume weights are not market-cap weights. These are evaluation questions, not new strategies tested in this review.

Pause and predict with a fixed hypothetical scenario. A signal's gross Sharpe is one point two on all assets and point two on a predeclared liquid half. What information about costs, capacity, uncertainty and selection is needed before deciding who could trade it?

4The virtue of complexityMaster's3 min

Random-feature complexity, regularisation and their conditional empirical and mathematical behaviour. The illustration is inspired by Kelly, Malamud and Zhou. Fixed Gaussian random projections produce sine and cosine features. Their large-feature limit approximates a specified kernel, rather than guaranteeing that any finite map learns an economic signal. The unchanged original fits rolling twelve-month ridge regressions and averages feature draws. More features than observations permits interpolation only with suitable rank and a zero-penalty limit. Positive ridge usually does not fit every point exactly. Complexity, regularisation and scaling must be considered together.

The original saved grid contains capacity and penalty settings. Several selected penalty curves are displayed; this is an illustrative implementation, not an exact independent replication of the paper. At complexity one thousand and penalty point one, gross scaled-return timing Sharpe is ; at complexity one it is . The corresponding scaled-market benchmark is . The saved grid is descriptive and does not justify choosing a configuration after seeing its research results.

The full saved R-squared curves matter. At complexity one and penalty one thousandth, the zero-benchmark value is percent. At complexity one thousand and penalty point one, it is percent. A peak near interpolation and subsequent error reduction can occur under particular scaling and noise assumptions. Positive ridge, feature normalisation and finite random maps change the shape. These R-squared numbers alone cannot order coefficient norms or prove discovery of a new economic signal.

A second original illustration uses crypto observations and saved random-feature fits. It displays the complete saved test-R-squared curves, including extreme negative values. A symmetric logarithmic vertical scale compresses large magnitudes; the ticks retain original R-squared percentages and the transformation is stated. Training draws change across capacities and penalties, so this is not a perfectly paired capacity ablation. A near-zero penalty is only approximately ridgeless. The shapes illustrate this implementation; neither a reduced peak nor a larger model establishes a tradable edge.

Why can extra capacity sometimes reduce error? In suitable overparameterised models, the minimum-norm solution distributes fitted directions and changes the variance-bias trade-off. Feature scaling and signal orientation matter. Near a poorly conditioned interpolation threshold, small singular values can amplify noise. Positive ridge suppresses those directions. The curve does not identify whether new economic information was learned. A matched-information baseline and independent evaluation remain necessary.

Pause and predict. Two differently sized random-feature ridge models have R squared minus forty and plus one percent. Can those values alone rank coefficient norms? Identify the missing feature scaling, penalties and model details.

5The criticsMaster's3 min

The critics, and what twelve thousand random features turn out to be doing. Nagel's critique motivates inspecting the dual forecast. Random-feature ridge combines training outcomes through feature inner products and a regularised Gram inverse. With a fixed finite input set and a positive penalty, Gaussian feature inner products converge to their kernel and so does the ridge forecast. A near-identity training Gram simplifies that inverse. Tiny test similarities then imply small similarity-weighted forecasts; they do not by themselves imply equal positive momentum weights. Finite-feature randomness, scaling and the information set still matter.

The saved diagnostic averages absolute feature inner products by training lag. The exact Gaussian test-kernel median is , while its maximum is . A small median does not mean that every pair is dissimilar. Absolute averages also discard signs. These summaries diagnose a selected implementation and do not identify a universal momentum mechanism.

Compare selected gross research strategies. The random-feature timer's Sharpe is , the twelve-month scaled-return average has , and the one-month rule has . The complex forecast's correlation with the twelve-month rule is . These are different selected models, not proof of equivalence. A fair deployment comparison also requires matched tuning effort, information, position scaling and costs.

Now a fixed-seed artificial stress example. The target follows an autoregression with coefficient , while the feature model retains the real financial predictors. The reversal baseline directly receives the artificial target's lag, which is not among those predictors. Its saved Sharpe is , compared with for the random-feature model. This mismatched information set prevents the conclusion that any successful learner should have discovered reversal. It is an illustration, not a decisive replication of the paper or a test of all high-dimensional learning.

Separate theory from this diagnostic. Large models are not automatically useless; risk depends on regularisation, scaling, signal and noise. A selected gross timing comparison and a mismatched synthetic baseline do not establish that all complexity gains are disguised momentum or that learning failed. The useful research question is which simple model captures a complex forecast's behaviour. Compare them at matched information and tuning budgets, then evaluate on genuinely independent data. No additional market strategy is run here.

Pause and predict. A deep network's daily stock forecasts have a correlation of point eight with a one-month reversal signal. Before paying for the network, what two tests would you run?

6The theory of overparameterised predictionPhD5 min

Derive Gaussian proportional-limit ridge risk, distinguish it from finite-sample error, and compare the numerical formula with saved simulation draws.

Specify the model and the risk. Independent standard-Gaussian features multiply a fixed coefficient vector of squared length r squared, with independent mean-zero noise of variance sigma squared. Ridge uses the sample covariance and a positive penalty. The zero-penalty limit is the pseudoinverse; it interpolates when the design has full row rank. Gaussian designs with more columns than rows satisfy this almost surely. Excess prediction risk excludes fresh observation noise. Its deterministic proportional limit assumes observations and features grow together at a fixed ratio; this is not an exact finite-sample guarantee.

Everything runs through one object: the eigenvalues of the sample covariance. The true covariance is the identity, every eigenvalue one. The sample's are not. With a quarter as many features as observations they spread from a quarter to more than two. As gamma approaches one, the spread widens and the smallest eigenvalue slides towards zero: the lower edge of the Marchenko-Pastur law is one minus root gamma, squared. Past one, a share of the eigenvalues is exactly zero: directions the data say nothing about. Inverting a matrix with eigenvalues near zero multiplies the noise by their inverse. That, in one picture, is the spike of Chapter 4.

Now the proof, in five lines. Substitute the model into the estimator. The error splits into a part that shrinks the true coefficients towards zero, which the penalty causes, and a part that is filtered noise. Square it and average over the noise: the cross term vanishes, leaving a squared bias and a variance. The bias is a quadratic form in the unknown b. Because the law of standard normal data is unchanged by any rotation, only b's length can matter, and the quadratic form concentrates at its trace. Both terms are now normalised traces of functions of the sample covariance, and by Marchenko and Pastur those converge to integrals against the law we just saw. So the risk of ridge, in the limit, is a deterministic function of four numbers: the complexity, the penalty, the signal and the noise.

Take the zero-penalty limit under this Gaussian proportional model. Below ratio one, excess variance is sigma squared times gamma divided by one minus gamma. Above one, unseen directions add signal bias, and variance falls as one over gamma minus one. The singular threshold is excluded from these finite expressions. With positive signal and noise, the stated oracle ridge penalty removes that singularity. An estimated penalty in a dependent market sequence is not guaranteed to behave like this oracle.

Compare asymptotic excess risk with saved finite simulations. The vertical scale is logarithmic in one plus risk, allowing every saved curve and simulation range to remain visible. The singular point at gamma one is excluded. Dots and bars are medians and ten-to-ninety-percent ranges of thirty draws at N equal to ; agreement is approximate. With signal and noise both one, above-threshold ridgeless excess risk equals one plus one divided by gamma times gamma minus one, always above the zero-forecast excess risk one. Stronger signal can change that comparison. Oracle ridge is a model-specific yardstick, not a market guarantee.

This separate dense-Gaussian example changes what the learner observes. Only a subset of the signal features is available, and unobserved independent contributions act as extra noise. Its plotted score is total mean squared error, including noise; the zero-forecast benchmark is . At the final saved capacity, ridgeless total error is , or zero-benchmark R squared percent. Oracle ridge gives percent. These values describe the stated signal allocation, not a universal benefit of size. Misspecification can make additional observed features valuable. Whether real return predictability has this structure remains an empirical question; the illustration does not answer it.

The kernel limit is more precise than the broad empirical critique. Paired sine and cosine features turn their inner product into a sample mean of cosines of Gaussian projections. Its expectation is the Gaussian characteristic function, and pointwise Monte Carlo error is of order one over square root of the feature count. This is stochastic fixed-input scaling, not a deterministic uniform error guarantee. On a fixed finite input set with positive regularisation, kernel convergence passes to the ridge forecast. It does not prove every finite-feature forecast equals a simple momentum strategy.

Several research questions remain. Is useful predictability sparse or distributed across many small signals, and how much evidence distinguishes those possibilities? Dependence, heavy tails, changing distributions and signal decay can alter Gaussian IID risk calculations. No blanket market-risk formula follows from this example. Very wide networks can approach fixed kernels in particular lazy-training or neural-tangent limits. Feature-learning regimes differ. The economic contribution of each needs evidence matched to the actual training regime.

Pause and predict. In the isotropic model with signal and noise both equal to one, at what gamma above one does the ridgeless risk equal the risk of predicting zero? And what is it at gamma equals one half?

7Autoencoder asset pricingMaster's3 min

From forecasting returns one asset at a time to explaining them all at once: factor models, learned.

A conditional factor model separates exposures and common realised factors. Characteristics determine each asset's exposures through a shared map. The original forms sixteen managed-return summaries from current returns and past ranked characteristics. These algebraic portfolios do not by themselves establish executable trading rules. A restricted linear arm maps those summaries into factor returns. Training jointly minimises reconstruction error. Factor rotations and scales require identifying normalisations. The architecture is inspired by conditional autoencoder asset pricing; its implementation and evaluation are smaller and more restricted than the cited paper.

Distinguish a theoretical linear factor model from our restricted implementation. Linear betas use a loading matrix with identification normalisations. Fixing that matrix gives unrestricted per-period least-squares factors. Fixing the factors gives a pooled normal equation; alternating these steps need not reach a global solution in one iteration. Under equal orthonormalisation, a globally optimal loading space follows from an eigenproblem. Our autoencoder instead gradient-fits a restricted managed-portfolio factor arm, with possible beta biases; it is inspired by IPCA rather than identical to unrestricted alternating least squares.

Read the two arms carefully. Past characteristics enter the beta network to produce exposures. Contemporaneous managed returns enter a restricted linear factor arm. Their inner product reconstructs a contemporaneous asset return. The linear-beta, one-hidden-layer and two-hidden-layer versions differ in their beta maps. The linear-beta implementation is not unrestricted IPCA, and feeding realised returns into factor extraction does not forecast those returns.

Total fit uses contemporaneous test-week returns in the factor arm. Parameters were trained earlier, but these factor inputs are realised in the evaluation week, so this is reconstruction rather than a forecast. For one factor the saved total R squared ranges from to percent. The largest saved total fit is percent for with factors. We have not identified a particular factor as the market or isolated why nonlinear versions differ. Zero-benchmark reconstruction R squared is also not literally a variance fraction.

Forecasting is a different calculation. The original substitutes mean fitted factors from training plus validation for contemporaneous factors. Saved predictive R squared ranges from to percent. Changing premia, exposure error, estimation and model restrictions can all contribute. The saved outputs do not uniquely identify the cause. Describing co-movement can support risk management, but is not the same task as predicting expected returns.

Pause and predict. A factor model explains half the variance of returns but forecasts worse than zero. Name two ways to estimate the factor premia better, and say what each one assumes.

8Deep SDFs with adversarial momentsPhD3 min

Learn a restricted return-span discount-factor projection, and distinguish its training objective from a positive arbitrage-free pricing certificate.

The ideal pricing condition and the fitted approximation differ. Under suitable no-arbitrage conditions, a positive stochastic discount factor prices excess returns. A linear return-span projection of the form one minus portfolio return can satisfy unconditional moments while taking negative values; positivity is not imposed here. Conditional moments are equivalent to suitable unconditional tests against all measurable conditioning functions. A finite adversarial function class only checks selected moments, not all functions and every asset's pricing error.

State an unconditional finite-moment calculation with positive-definite return covariance. Substitution gives mean returns equal to the return second-moment matrix times the weights. Sherman--Morrison gives covariance-inverse mean divided by one plus squared tangency Sharpe. These are canonical unrestricted projection weights; network and normalisation constraints change the problem. The Hansen--Jagannathan bound uses discount-factor standard deviation divided by its positive mean. A learned portfolio's Sharpe alone cannot certify positivity, all conditional moments or maximum-Sharpe optimality.

The House implementation uses a finite adversarial game. Its portfolio weights are normalised by their absolute sum. It averages moments across assets within each week and then across weeks, using winsorised log-return training targets. The adversary supplies a finite function family plus a constant channel over three alternating rounds. That channel adds a pooled unconditional target; it does not enforce each individual asset moment. No positivity, convergence or exact pricing certificate follows from this finite objective.

The saved evaluation reports gross simple-return portfolios, although training uses winsorised log-return targets. The linear managed-portfolio comparator has Sharpe . The adversarial portfolio has , compared with for the equal-weight market. Different constraints and parameterisations prevent interpreting this as an isolated architecture ablation. Costs and short feasibility remain unmodelled.

A descriptive exposure diagnostic helps interpret the saved path. Annualised arithmetic market means are percent in the training-era sample and percent in the later research sample. These are not compounded annual returns. The adversarial portfolio's market correlation is . This can diagnose substantial signed market exposure, but does not establish why optimisation chose it, exact training-moment pricing, or a uniquely identified premia mechanism. A richer exposure analysis and matched restrictions would be needed for causal conclusions.

Pause and predict. Propose an explicit market-exposure bound for a learned discount-factor portfolio. State the estimation and normalisation choices, the opportunities it excludes, and why the bound does not certify every pricing moment.

9Attention across assetsMaster's3 min

The pointwise models already use cross-sectional ranks. Attention adds learned set interactions beyond that relative preprocessing.

Why model a set of assets jointly? Cross-sectional context may change the interpretation of a characteristic, although our inputs already encode ranks among peers. Interactions may represent shared states or lead-lag structure, but the saved model comparison does not establish either mechanism. Published asset-pricing transformers motivate exploring these interactions. Their reported improvements concern their own data and evaluation designs; our smaller crypto example is not a replication.

The mechanism is AI, Built's thirteenth part, applied to a cross-section. Embed each coin's characteristics. From the embedding, each coin forms a query, what it is looking for; a key, what it offers to be found by; and a value, what it contributes. Coin i's attention to coin j is a softmax of how well its query matches j's key, across all the coins of that week. And its forecast reads its own embedding plus the attention-weighted average of everyone's values. One layer, four heads, trained like every other model here.

One useful property is permutation equivariance. Shared rowwise maps and attention without fixed slot embeddings relabel forecasts when the inputs are relabelled. This symmetry does not guarantee accuracy. Deep Sets representations need regularity, cardinality and latent-dimension conditions. A plain mean loses set size unless size is supplied or fixed. Uniform attention averages learned value vectors. That operation is not automatically demeaning, identifying a market factor or demonstrating that no leaders exist.

Inspect one selected seed and week, with attention heads averaged. The matrix shows the first rows and columns with original weights and a zero-to-maximum colour scale. Omitted columns retain the remaining mass. The saved full-matrix top-five share is percent, compared with uniform percent over assets. This descriptive heatmap does not establish attention behaviour in all weeks, causal feature importance or the absence of leaders.

The original research comparison reports zero-benchmark R squared of percent for attention and for the pointwise network. Their gross long-short Sharpes are and . Both use ranked relative inputs. Their parameter counts, training effort and architectures differ, so the comparison is not a pure attention ablation. The outputs do not isolate sample size, overfitting or a learned market factor as the cause.

Pause and predict. Prove attention's row-permutation equivariance. Distinguish a fixed row-slot embedding from an asset identity or alphabetical rank that moves with the asset. The latter need not break reindexing equivariance.

10Images of pricesMaster's3 min

Technical analysts have looked at price charts for a century. What happens when a network built to see does the looking?

A chart-image representation converts recent history into pixels. This original uses a twenty-day window, high-low marks, moving averages and volume; its open is proxied by the previous close. That differs from observing every true opening price. Window scaling removes the absolute price level, while preserving selected relative geometry. The two displayed examples are selected for extreme network predictions in the test sample. They are neither representative random examples nor proof that those predictions were correct.

The House uses a small two-block convolutional classifier. Shared filters scan local pixel patterns, followed by pooling, nonlinearities and a linear probability head. Convolution is translation equivariant under suitable boundary conventions, but padding, pooling and the head can make pattern position matter. The complete classifier is not necessarily shift invariant. Cross-entropy trains a five-day direction target. Classification probability, ranking quality and net trading value are distinct evaluation questions.

Jiang, Kelly and Xiu report evidence from stock-chart experiments. Their learned chart signals differ from selected hand-crafted trend benchmarks. Their paper reports portfolio improvements under its own sample, portfolio and implementation choices. It also studies transfer across horizons and markets. These are the authors' findings, rather than a universal chart-predictability result or a replication by this much smaller coin network.

The saved crypto classifier has test direction accuracy percent. The majority-class diagnostic is percent, calculated from test-label prevalence; it is a hindsight benchmark, not a training-locked trading rule. Gross portfolio Sharpe is for the CNN and for momentum, with rank correlation . Five-day targets are sampled weekly. Costs, borrow, overlapping training windows and limited history constrain interpretation. The comparison does not identify a single missing pattern as the cause.

Consider sample size and inductive bias without overclaiming causation. Counting convolution, affine batch-normalisation and linear-head parameters gives trainable scalars. The original uses training images, with overlapping windows. The cited stock study has a different and much larger design. Model priors, optimisation, target definition, sample chronology and trading assumptions all differ. These outputs alone do not identify insufficient data as the unique cause, or prove that a simple rule always wins.

Pause and predict. Distinguish local convolutional equivariance from invariance of the complete chart classifier. Give a pattern whose age within the window should matter for a forecast.

11Foundation modelsPhD4 min

Foundation-model forecasting: distinguish corpus, target, transfer protocol and genuinely prospective evaluation. Several model families transfer forecasting behaviour across series. Chronos rescales observations, discretises them into tokens and models sequences probabilistically. TimesFM uses patches of numerical observations in a pretrained transformer. Its training corpus and forecasting head differ from Chronos. Kronos tokenises multivariate financial candlesticks. Its authors describe more than twelve billion records across forty-five exchanges. Zero-shot describes adaptation rules for a task; it does not itself establish disjoint training data, prospective timing or economic profitability.

How does a number become a word? Divide by the context's average size, so that a penny stock and an index look alike. Cut the scaled range into bins: each value is now a token from a vocabulary of a few thousand. Train with the language model's own loss, the probability of the next token given all the earlier ones, which teaches a whole distribution of what comes next, not one number. Then forecast by sampling paths, as a language model writes sentences, and read off a median, a quantile, or a volatility. Kronos's tokenizer goes a step further and codes a whole candlestick into a coarse token and a fine one.

The verified Kronos paper is arXiv twenty-five oh-eight, oh-two-seven-three-nine, first posted in August twenty twenty-five. Its abstract reports relative RankIC improvements of ninety-three percent versus a leading time-series foundation model and eighty-seven percent versus the best non-pretrained comparator, nine percent lower volatility-forecast MAE and twenty-two percent higher generative fidelity. These are relative benchmark metrics, not percentage-point accuracy or trading returns. We have not run Kronos. Corpus dates, entities, target definitions, comparator adaptation and trading assumptions require separate examination. Corpus size alone does not demonstrate leakage or transfer success.

The unchanged pocket-model protocol uses a more specific target. It predicts next-day log absolute return with a small positive offset, centred by the preceding sixty-day context mean. This is not realised integrated volatility or return direction. Eligible crypto histories run from the available archive through twenty twenty, without an explicit twenty eighteen lower cut. Validation randomly splits overlapping windows rather than holding out later dates. The network is not fine-tuned on the five ETFs, while their HAR coefficients and exponential-average offsets use each fund's first half. ETF evaluation can begin before the end of crypto pretraining, so this is retrospective cross-asset transfer rather than a prospective forecast from twenty fifteen.

The original transfer calculation is unavailable. Its normal attempt stopped when the frozen SPY input failed the unchanged source hash check. It produced no accepted result cache, and did not reach the other four ETF comparisons. We do not refresh the frozen source, retry the fit or report a numerical ranking. The preceding window is explicitly simulated to explain the source protocol; it is not a replacement transfer experiment. The target, random overlapping-window validation and retrospective chronology can still be audited from code, without claiming empirical transfer success.

What can transfer? Shared statistical structures such as clustering may motivate cross-asset learning, but useful transfer needs evidence for the stated target and chronology. It cannot be learned anywhere and safely used everywhere. Return direction and centred log-move prediction are different tasks. A statistical gain need not pay after trading costs. Inspect corpus dates and entities, pretrained checkpoints and adaptation choices. A large corpus creates potential contamination routes, but size alone proves no overlap. Predefine a genuinely later or appropriately entity-disjoint evaluation before consulting its outcomes.

Pause and predict. A model pretrained through twenty twenty-four is evaluated on twenty twenty-three. Identify possible temporal and entity-overlap routes without assuming they occurred. State the corpus evidence needed and design a genuinely prospective evaluation.

12The practitioner's toolkitIndustry3 min

Practitioner tools: activity sampling, finite fractional filters, daily-close labels and concurrency weights, each with explicit implementation limits.

The original changes the sampling clock. It uses hourly base volume times close as a traded-value proxy and closes an activity bar when a cumulative threshold is crossed. Multiple crossings inside one hour collapse to one observed end, so the bar count need not match the daily count. These are activity bars, not imbalance or run bars. Saved excess kurtosis is for activity bars and for daily returns. Both can remain fat-tailed. The saved histogram omits observations outside six standard deviations; their counts are disclosed. Squared-return autocorrelations are and , without a universal claim that the sampling scheme removes clustering.

Fractional filtering requires careful interpretation. The infinite fractional-difference weights have polynomial decay for a noninteger order, but this implementation truncates them. Prices need not have a unit root and ordinary returns need not be stationary. The first sampled order crossing the fixed-lag ADF threshold is , with correlation to log price; the order-one correlation is . A correlation is not a preserved-memory fraction. Fixed critical values and selecting among several orders do not certify stationarity or useful forecasting information.

Triple barriers define a target rather than a complete execution model. The fixed illustration shows upper, lower and timeout boundaries. The unchanged empirical helper checks daily closes and arithmetic price changes; recent volatility sets the scale, and a timeout receives the realised return's sign, rather than always zero. Intraday crossings, executable fills and costs are absent. Volatility scaling does not guarantee equal risk in calm and stressed markets.

Meta-labelling here filters a fixed momentum side. Its target is whether the side matches the daily-close barrier or timeout sign, not merely whether a profit barrier was hit. The original training split does not purge crossing label spans, and its boosted fit does not use uniqueness weights. The saved filter keeps percent of opportunities. Precision is percent before filtering and afterward. Per-opportunity mean-to-standard-deviation ratios are and . These gross, overlapping opportunities are not an executable independent portfolio track record.

Uniqueness measures average inverse label concurrency. The saved labels have mean weight and sum . This is not an equivalent number of independent observations. For inclusive fixed spans from i to i plus h, interior concurrency is h plus one, giving uniqueness one over h plus one. Half-open spans use a different convention. Early barriers and sample edges alter the average. Dependence and the estimator still determine standard errors, and the original meta-classifier does not use these weights.

Pause and predict. A secondary model doubles the precision of your bets, but takes only one bet in ten. When is that better than taking every bet, and how would you decide before trading?

13Conformal predictionMaster's3 min

Prediction intervals: separate the exchangeable rank theorem, a selected empirical illustration and the boundary conditions behind adaptive counting guarantees.

Split conformal starts with a predictor fitted independently of calibration labels. Compute calibration residual scores using that fixed predictor. Choose rank k equal to the ceiling of n plus one times one minus alpha. If k exceeds n, use infinite width; the unchanged House helper instead caps the rank at n. Construct the prediction interval from that score quantile. Conditional on training, exchangeable calibration and new scores imply marginal coverage at least one minus alpha. Ties can make it conservative. This is not per-asset or regime-conditional coverage, and model selection on calibration labels removes the standard independent-fitting argument.

The original crypto intervals reuse the validation labels for both model selection and calibration. That violates the standard independent-fitting construction before considering coin dependence, drift and imperfect calendar boundaries. Saved nominal ninety-percent coverage is percent and nominal eighty-percent coverage is . The worst saved ninety-percent week is percent. All weekly values are visible on zero-to-one axes. Near-nominal pooled coverage is descriptive, not certification. A time sequence need not logically violate exchangeability, but the needed symmetry is not justified by this selected market sample.

A second original illustration forecasts Bitcoin daily log returns as zero. A fixed interval is calibrated on the first one hundred and twenty observations. Its half-width is percent in log-return units. Saved later coverage is percent. This describes a fixed historical path; it neither proves exchangeability nor identifies an optimal width. The plot includes every saved absolute return and the full interval threshold.

Adaptive counting starts with an exact telescoping identity. After a miss, lower the working level; after a hit, raise it. Summing the updates relates average error to the change in the working level. A vanishing counting error requires the state change to be sublinear in time; a bounded state suffices. Ideal infinite-interval and empty-set boundary conventions can ensure a finite bound. The unchanged House implementation uses a finite past maximum and zero width instead, so it does not inherit that arbitrary-sequence guarantee.

The saved Bitcoin path has coverage percent for the adaptive finite-quantile rule and percent for the fixed interval. Every rolling coverage value is displayed. These are descriptive outcomes of the original rule with step point zero one and a one-hundred-twenty-day window. They do not certify arbitrary-sequence, conditional or future coverage.

A fixed mathematical counterexample shows the limitation. Let residual scores increase strictly forever. Each new score exceeds the finite past maximum, so every interval misses, even after the working level becomes negative. The level then decreases without bound. The telescoping identity remains correct, but its remainder does not vanish. Infinite-width boundary conventions would change this example; this original does not use them. No additional market experiment is needed to see the distinction.

Pause and predict. A conformal interval for a strategy's monthly return is calibrated on the 2010s and covers ninety percent there. In 2020 it covers seventy. Is the guarantee broken, and what would you change?

14From the public record: Two Sigma and RenaissanceIndustry3 min

Two firms that run on models, as far as the public record shows them.

Renaissance Technologies was founded in 1982 by James Simons. Gregory Zuckerman's 2019 history reports Medallion's annual averages from 1988 through 2018 at about sixty-six percent before fees and thirty-nine percent after fees. Access became restricted to insiders after outside capital was returned. These are reported historical averages from that account, not an audited current offering or a return available to a new investor. Its proprietary models and signal construction are not public. The history can motivate questions about breadth, turnover and capacity, but it cannot establish which machine-learning architecture or causal mechanism produced the record.

Two Sigma was co-founded in 2001 and describes an investment process built around data, research and engineering. Its public identity does not reveal its current proprietary signals or their contribution to returns. The useful comparison here is organisational: many models require a reproducible chain from data and code to positions, with records of who can change a model and how those changes are detected. The next source provides a dated example of failures in that chain.

On January sixteenth, 2025, the SEC announced settled charges against Two Sigma Investments and Two Sigma Advisers. According to its order, employees recognised model vulnerabilities in or before March 2019, but the firm waited until August 2023 to address them and failed to supervise an employee's unauthorised changes to more than a dozen models. The advisers agreed to ninety million dollars in total penalties, without admitting or denying the findings, and voluntarily repaid affected funds and accounts 165 million dollars. The settlement also included separate whistleblower-protection violations. This is a dated account of the firm settlement, not a statement about the current status of separate proceedings. It shows why recorded model changes, access controls, review and prompt remediation belong in an investment process.

Three protocol lessons can be drawn without pretending to know a proprietary strategy. Ask how many economically distinct exposures support a reported result, and which common risks make nominal breadth redundant. Ask how turnover, market impact, access restrictions and capital affect what can be earned at a particular scale. A closed fund alone does not identify its capacity limit. And preserve an auditable chain of model versions, reviews and authorised changes. These are questions to investigate and controls to implement; the public histories do not prove a universal recipe for exceptional returns.

Pause and predict. A historical account reports high after-fee returns and a fund declines new capital. What capacity explanation is plausible, what other explanations remain possible, and what evidence would distinguish them?

15Registration and evaluation for learned modelsIndustry3 min

The original panel-sealing routine and strategy envelope are excluded from this review. This chapter designs an evaluation protocol without loading their caches, opening a strategy experiment or reporting a sealed score.

The object to freeze is the entire pipeline. Record when each input was available, which assets entered the archive, when each label matures, and which price can actually be traded after the decision. Fit transformations inside training. Allocate distinct roles to validation and calibration, and freeze seeds, optimisation budgets and stopping choices. Define positions, capital and costs. A trading-volume-weighted long-short illustration does not become a market-cap portfolio or an executable strategy merely because its forecasts were held out.

A comparison needs a common task before it needs a bigger network. Match the information, horizon, training dates, tuning opportunities, compute budget and economic constraints. A reversal rule with a target's own lag has information that a model fed unrelated predictors may lack. Count architecture, feature, penalty and seed choices, including informal revisions and validation reuse. A single final display does not erase the selection that produced it. Then state the uncertainty question: uncertainty about one mean is different from a paired model difference, a searched winner, or an interval under exchangeability.

The existing registration ledger through Part twenty-seven contains configurations, more than the count through Part twenty-six. Those are already recorded metadata. This review adds no registration, strategy opening or market trial. It restores only audited ordinary originals and keeps the excluded experiment routines unchanged. A recorded count remains a lower bound on the broader search. Correlated configurations and adaptive research do not become independent tests because their names were counted.

For a mean comparison, use the paired difference. The variance of A minus B includes their covariance. In a fixed mathematical example, both standard deviations are one, correlation is point eight, and there are one hundred independent paired observations. The difference has standard deviation about point six three two, so its mean has standard error about point zero six three two. Ignoring covariance would answer the wrong precision question. These are invented arbitrary units, not a new strategy test or a formula for a difference of Sharpe ratios. Serial dependence, estimated risk and selection require further analysis.

The boundary remains explicit. The panel-sealing output and strategy envelope are not loaded, opened or scored. Original ordinary research calculations can read later public archive vintages and have calendar-boundary contamination; that does not certify a fresh evaluation. Before declaring a winner, explain its information, paired errors, search history and execution assumptions. A result becomes useful through that evidence, not through the size of the model or a registration timestamp alone.

16Rule 27: the model deskIndustry2 min

The House's twenty-seventh rule: evaluate the full forecasting protocol, including its limitations. The evidence sheet separates measurements from guarantees. The original crypto zoo's zero-benchmark R squared ranges from to percent. Calendar label boundaries remain imperfect. Ridge theory is asymptotic, and autoencoder total fit extracts factors from contemporaneous test returns. The adversarial portfolio and chart network are descriptive gross-return illustrations. Split coverage is percent, but reused calibration labels prevent the standard theorem from certifying it. Finite adaptive quantiles lack a universal sequence guarantee. The panel and sealed experiment originals remain excluded.

This unchanged House routine evaluates proportional-limit Gaussian excess prediction risk. Fresh observation noise is excluded. The zero-eigenvalue atom contributes lost signal, while the positive spectrum contributes bias and variance. The integrals use finite numerical quadrature, and finite simulation draws need not agree exactly. The misspecified helper uses a different convention: total mean squared error, including noise.

The model shop now contains linear models, trees and networks; random features and kernels; Gaussian risk limits; autoencoders, discount-factor portfolios, set models and chart images. It also contains activity bars, fractional filters, overlapping-label diagnostics and calibration tools. Each comes with a stated information set and mathematical scope.

Rule twenty-seven. Judge the complete protocol. Match information, tuning effort and simple baselines. Respect availability clocks, actual label spans and selection. Report paired uncertainty, dependence and the search history. State calibration assumptions, execution, costs and capacity. Distinguish descriptive fit from a forecast that could have been made and traded at the time. A fashionable architecture and a narrow empirical interval do not supply missing assumptions.

Apply the rule. Perfect training fit alone decides little; check rank, regularisation and out-of-sample risk. A short comparison needs paired returns and justified inference. Near-nominal coverage needs an independently calibrated predictor and correct boundary conventions. A synthetic reversal comparison needs the same lagged information for every learner. These are questions for evaluating evidence, rather than new historical strategy tests.

Recap, desk questions, problemsAll tracks3 min

Part twenty-seven in fourteen qualified lines. Weak signals and breadth need a stated data-generating model. The crypto illustration retains calendar and execution limitations. Liquidity differences and fee scenarios are descriptive. Positive ridge does not automatically interpolate. The artificial reversal baseline has a different information set. Gaussian risk limits separate excess error from total mean squared error. Autoencoder total fit extracts factors using contemporaneous returns, rather than forecasting those returns.

The adversarial portfolio's market correlation does not certify pricing moments or identify a cause. Attention adds interactions beyond already ranked inputs, and a selected heatmap is not a general interpretation. Chart comparisons do not isolate why an architecture succeeds or fails. Foundation transfer needs an explicit target, chronology and adaptation protocol. Practitioner tools require precise finite-sample conventions. Empirical conformal coverage is descriptive when assumptions fail, and adaptive boundary rules matter. Governance and full-protocol evaluation close the part; the sealed experiment remains unopened and unscored.

Six desk questions. The binary-signal idealisation gives about five point four nine annual Sharpe for five hundred independent bets, rather than a universal promise from measured R squared. Perfect training fit alone is inconclusive. Direction accuracy alone omits move sizes, risk and costs.

Two years give an approximate annual Sharpe standard error of point seven one only under suitable independent-return assumptions. A meta-model must justify lost breadth and costs rather than precision alone. A regime's coverage need not equal marginal coverage. Check independent calibration, exchangeability and the actual adaptive implementation before claiming a guarantee.

The first six problems derive the explicit binary-signal calculation, a paired-mean standard error, the zero-penalty ridge limit, a Gaussian random-feature kernel, canonical linear discount-factor weights and Brownian barrier probabilities. Each solution states the information and mathematical assumptions.

Problems seven through ten derive fractional-weight decay, inclusive-label uniqueness, attention equivariance and the adaptive-level telescoping identity. The adaptive solution includes a counterexample for finite-maximum boundary rules. Uniqueness weights do not automatically count independent observations.

Two qualifying problems establish the split-conformal rank theorem under independent fitting and exchangeable scores, then derive finite-sample and proportional-limit Gaussian regression risk. The last comparison fixes signal and noise explicitly. All twelve problems have full English and Chinese solutions in the notes.

These questions return in text models, automated alpha search, covariance estimation, costs and capacity, and firm model governance. Later parts must keep the same discipline: clear information clocks, honest search accounting and inference matched to the implementation. The finale can discuss the research record without reopening or scoring sealed experiments.

The textbooks and papers distinguish published evidence from our smaller illustrations. Gu, Kelly and Xiu's stock results and the Kronos benchmark improvements are author-reported, not replicated here. The January sixteen, twenty twenty-five SEC release documents the dated firm settlement. Numerical illustrations use labelled mathematical examples or successfully verified ordinary originals. The panel and sealed experiment originals are excluded.

The House now has a model shop: every learner from least squares to a transformer, the theory that says when size helps, and the discipline that says when to believe it. It has learned that the hardest part of machine learning for returns is not the model but the test. Next, Part twenty-eight: text, language models and alternative data. Models that read the news and the Fed, and the subtle ways in which a model trained on the internet already knows how the story ends.

Where it goes next. Text is the next source of signal (Part 28); searching for formulas instead of fitting them is Part 29.

Key results

The part's results in one place, for revision.

Out-of-sample R squared\[R^2_{\text{oos}}=1-\frac{\sum_t(r_{t+1}-\hat r_{t+1})^2}{\sum_t r_{t+1}^2}\]
Ridge\[\hat\beta_\lambda=(X'X+\lambda I)^{-1}X'y\]
Ridgeless risk\[\mathcal R(\gamma)=\sigma^2\frac{\gamma}{1-\gamma}\ (\gamma<1),\qquad r^2\Bigl(1-\frac1\gamma\Bigr)+\frac{\sigma^2}{\gamma-1}\ (\gamma>1)\]
Sharpe from R squared\[\mathrm{SR}^2_{\text{timing}}\approx\frac{\mathrm{SR}^2_{\text{buy-hold}}+R^2}{1-R^2}\]

Try it

Lab 27 · Double descent, and why returns need the ridge

Fit linear models with more and more parameters to 200 observations at a return-like signal-to-noise ratio. Compare the minimum-norm interpolator and ridge with the random-matrix prediction of their out-of-sample risk.

Figure produced by Lab 27: Double descent, and why returns need the ridge
Produced by the lab below, seed 0, in 0.4 s. Simulated data.
python -m videos.quant.labs 27 needs numpy, scipy, matplotlib, numba · download lab27.py · source on GitHub
P/N = 0.5: risk          ridgeless    4.24 (theory    4.00)   ridge  0.76 (theory  0.77)
P/N = 0.9: risk          ridgeless   41.67 (theory   35.99)   ridge  1.11 (theory  1.07)
P/N = 1.1: risk          ridgeless   41.36 (theory   40.08)   ridge  1.21 (theory  1.18)
P/N = 2.0: risk          ridgeless    4.28 (theory    4.50)   ridge  1.44 (theory  1.43)
P/N = 5.0: risk          ridgeless    1.80 (theory    1.80)   ridge  1.41 (theory  1.41)
Risk of predicting zero  1.00

The interpolator explodes at P = N and recovers beyond it; at this signal-to-noise ratio only the regularized model ever beats predicting zero.
The code (52 lines; it asserts its own result)
"""Lab 27: double descent: out-of-sample risk of ridge and of the interpolator, theory against simulation."""

import numpy as np

from videos.quant import labs
from explainer.quant.house import ml

TITLE = "Double descent, and why returns need the ridge"
GOAL = ("Fit linear models with more and more parameters to 200 observations at a return-like signal-to-noise "
        "ratio. Compare the minimum-norm interpolator and ridge with the random-matrix prediction of their "
        "out-of-sample risk.")
TASKS = [
    "Raise the signal (r2 = 5). Where is the ridgeless risk now smallest: at few parameters or at many?",
    "Scan the penalty at P/N = 2. Is the optimum near s2 * gamma / r2, as the theory says?",
    "Feed ml.rff features of a nonlinear signal instead of an exactly linear one. Does the picture survive?",
]


def run(seed=0):
    N, r2, s2 = 200, 1.0, 4.0  # one part signal to four parts noise
    gammas = np.array([0.1, 0.25, 0.5, 0.75, 0.9, 1.1, 1.25, 1.5, 2.0, 3.0, 5.0])
    grid = np.concatenate([np.linspace(0.05, 0.97, 60), np.linspace(1.03, 5, 80)])
    lab = labs.Lab()
    sims = {}
    for name, lam in (("ridgeless (lam -> 0)", 1e-6), ("ridge, lam = 1", 1.0)):
        sims[name] = np.array([ml.ridge_risk_sim(N, int(g * N), lam, r2, s2, seeds=10).mean() for g in gammas])
    th = {name: np.array([ml.ridge_risk_theory(g, lam, r2, s2)["risk"] for g in gammas])
          for name, lam in (("ridgeless (lam -> 0)", 1e-6), ("ridge, lam = 1", 1.0))}
    for g in (0.5, 0.9, 1.1, 2.0, 5.0):
        i = int(np.argmin(np.abs(gammas - g)))
        lab.row(f"P/N = {g:>3}: risk", f"ridgeless {sims['ridgeless (lam -> 0)'][i]:7.2f} (theory {th['ridgeless (lam -> 0)'][i]:7.2f})   "
                                       f"ridge {sims['ridge, lam = 1'][i]:5.2f} (theory {th['ridge, lam = 1'][i]:5.2f})")
    lab.row("Risk of predicting zero", f"{r2:.2f}")
    lab.note = ("The interpolator explodes at P = N and recovers beyond it; at this signal-to-noise ratio only the "
                "regularized model ever beats predicting zero.")
    rel = np.abs(sims["ridge, lam = 1"] / th["ridge, lam = 1"] - 1)
    assert rel.max() < 0.25 and sims["ridgeless (lam -> 0)"][4] > 10 * r2 and sims["ridge, lam = 1"].min() < r2

    fig, ax = labs.figure(1, size=(9.6, 4.4))
    colors = {"ridgeless (lam -> 0)": labs.LOSS, "ridge, lam = 1": labs.GAIN}
    for name, lam in (("ridgeless (lam -> 0)", 1e-6), ("ridge, lam = 1", 1.0)):
        ax.plot(grid, [ml.ridge_risk_theory(g, lam, r2, s2)["risk"] for g in grid], color=colors[name], label=f"{name}: theory")
        ax.plot(gammas, sims[name], "o", color=colors[name], ms=5)
    ax.axhline(r2, color=labs.MUTED, ls="--", lw=1)
    ax.text(4.2, r2 * 1.12, "predict zero", color=labs.MUTED, fontsize=8)
    ax.axvline(1.0, color=labs.P, ls=":", lw=1)
    ax.set_yscale("log")
    ax.set(title="Out-of-sample risk against model size (dots: simulation, N = 200)", xlabel="parameters per observation, P/N",
           ylabel="excess risk", ylim=(0.3, 200))
    ax.legend(fontsize=8)
    lab.fig = fig
    return lab

Now change it

  1. Raise the signal (r2 = 5). Where is the ridgeless risk now smallest: at few parameters or at many?
  2. Scan the penalty at P/N = 2. Is the optimum near s2 * gamma / r2, as the theory says?
  3. Feed ml.rff features of a nonlinear signal instead of an exactly linear one. Does the picture survive?

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 questions, with solutions

  1. Half a percent population \(R^2\), 500 independent binary-signal bets?
    AnswerUnder the explicitly stated model, \(\sqrt{12(500)(0.005)/0.995}=5.49\) annual Sharpe. Measured OOS \(R^2\) alone does not justify the model, independent bets, known parameters or trading assumptions.
  2. A million parameters and perfect training fit?
    AnswerThis alone decides little. Check rank, penalty, scaling, signal/noise assumptions, matched-information baselines and independent predictive risk. Positive ridge does not generally interpolate.
  3. Direction accuracy 55%?
    AnswerNeed move sizes, base rates, position sizes, covariance, turnover, execution and costs. Accuracy alone cannot determine net value.
  4. Annual Sharpe one over two years?
    AnswerThe IID-normal weekly approximation gives \(SE=\sqrt{(1+1/104)/2}\simeq0.71\) and an illustrative normal 95% range near \([-0.39,2.39]\). This omits dependence, selection and small-sample uncertainty. A paired model comparison needs return covariance; power additionally needs an alternative and a rejection rule.
  5. Meta-model doubles precision but keeps one bet in ten?
    AnswerCompare net profit and risk per unit time, accounting for move sizes, lost breadth and overlapping positions. In a simplified independent equal-scale setting, losing a factor ten in breadth requires a \(\sqrt{10}\) increase in per-bet Sharpe to preserve total Sharpe. Precision does not determine that increase.
  6. A nominal 90% interval covers 70% in one regime?
    AnswerA marginal theorem is not regime-conditional coverage. Check independent fitting, calibration/new-score exchangeability and implementation boundaries. Rolling or adaptive changes create a different protocol that needs its own evaluation; the original finite-max rule has no arbitrary-sequence certificate.

Problems, with worked solutions

Twelve problems with full solutions

Problems 1–6 develop the basic calculations; 7–10 extend the implementation analysis; 11–12 are qualifying problems. Numbering is continuous across the three screen pages.

  1. Binary signal and breadth. Binary signal \(S=\pm1\), \(r=aS+\varepsilon\): derive population \(R^2\), sign-strategy Sharpe and independent-bet scaling.

    Solution

    Let \(S=\pm1\) equiprobably, \(r=aS+\varepsilon\), with independent mean-zero \(\varepsilon\), variance \(\sigma^2\), independent across months. Forecast \(aS\). Its population squared-error reduction versus zero is \(1-\sigma^2/(a^2+\sigma^2)=a^2/(a^2+\sigma^2)\). The sign-position payoff is \(Sr=a+S\varepsilon\), with mean \(a\) and variance \(\sigma^2\). Its monthly Sharpe is \(a/\sigma=\sqrt{R^2/(1-R^2)}\) for \(a\ge0\). Independent months annualise by \(\sqrt{12}\); \(N\) independent equal-risk bets multiply the ratio by \(\sqrt N\). Dependence, estimated forecasts and trading constraints invalidate a universal mapping from arbitrary empirical OOS \(R^2\).

  2. Paired means. Paired means: derive \(\operatorname{Var}(A-B)\). For unit SDs, correlation 0.8 and 100 independent pairs, find the SE.

    Solution

    For \(D=A-B\), \(\operatorname{Var}D=\sigma_A^2+\sigma_B^2-2\rho\sigma_A\sigma_B\). With unit standard deviations and \(\rho=0.8\), variance is 0.4 and SD is \(\sqrt{0.4}=0.63246\). For 100 independent pairs, \(SE(\bar D)=\sqrt{0.4/100}=0.06325\). Correlated dates require a long-run variance estimator. This is a mean comparison in arbitrary units, not a Sharpe-difference formula.

  3. Zero-penalty ridge. Use the SVD to derive the zero-penalty ridge limit. State when it interpolates.

    Solution

    For a compact SVD \(X=UDV^\top\), \(\hat b_\lambda=V\operatorname{diag}(d_j/(d_j^2+N\lambda))U^\top y\). As \(\lambda\downarrow0\), nonzero singular directions give \(VD^{-1}U^\top y=X^+y\). This is the minimum-norm least-squares solution, since null-space additions increase norm. It interpolates iff \(y\) lies in the column space of \(X\), in particular for every \(y\) when \(X\) has full row rank. \(P>N\) alone is insufficient without that rank condition. Positive ridge generally does not interpolate.

  4. Gaussian random Fourier features. Gaussian random Fourier features: derive the kernel expectation and pointwise Monte Carlo error rate.

    Solution

    For \(w\sim N(0,\eta^2I)\), \(w^\top\Delta\) is normal with variance \(\eta^2\|\Delta\|^2\). Its characteristic function gives \(E\cos(w^\top\Delta)=\exp(-\eta^2\|\Delta\|^2/2)\). Paired sine/cosine maps with \(M\) independent frequencies have inner product \(M^{-1}\sum_j\cos(w_j^\top\Delta)\). Each summand is bounded, so its sample-mean variance is at most \(1/M\) and pointwise error is \(O_p(M^{-1/2})\). This is not a deterministic uniform guarantee over all possible inputs.

  5. Canonical projection and HJ bound. For \(M=1-w^\top R\), derive the unconditional canonical weights and the correctly normalised Hansen–Jagannathan bound.

    Solution

    Let \(R\) be excess returns, \(E R=\mu\), \(\operatorname{Cov}R=\Sigma\succ0\), and \(s^2=\mu^\top\Sigma^{-1}\mu\). For \(M=1-w^\top R\), \(E[MR]=0\) gives \((\Sigma+\mu\mu^\top)w=\mu\). Sherman–Morrison yields \(w=\Sigma^{-1}\mu/(1+s^2)\). Hence \(E M=1/(1+s^2)\) and \(\operatorname{sd}M=s/(1+s^2)\). For any priced portfolio, \(E M\,E R_p=-\operatorname{Cov}(M,R_p)\), so Cauchy–Schwarz gives \(|SR_p|\le\operatorname{sd}M/E M\). The projection attains the unrestricted tangency ratio \(s\), but may be negative in some states; it is not automatically a positive arbitrage-free SDF or the solution of a constrained conditional network problem.

  6. Brownian barriers. Brownian drift \(\mu\), volatility \(\sigma>0\), barriers \(\pm b\): derive the upper-first probability without a time limit.

    Solution

    Let \(X_t=\mu t+\sigma W_t\), \(\sigma>0\), start at zero, and stop on first hitting \(\pm b\), \(b>0\). The upper-hit probability solves \((\sigma^2/2)u''+\mu u'=0\) on \((-b,b)\), with \(u(-b)=0\), \(u(b)=1\). Solving gives \(u(0)=(1-e^{-2\mu b/\sigma^2})/(1-e^{-4\mu b/\sigma^2})=1/(1+e^{-2\mu b/\sigma^2})\). Its continuous limit at \(\mu=0\) is \(1/2\). A finite horizon, discrete closes, overshoots and costs define a different problem.

  7. Fractional-filter decay. For noninteger \(0<d<1\), derive fractional-filter weights and their asymptotic decay. What does truncation not prove?

    Solution

    With \(w_0=1\) and \(w_k=-w_{k-1}(d-k+1)/k\), repeated multiplication gives \(w_k=(-1)^k{d\choose k}=\Gamma(k-d)/[\Gamma(-d)\Gamma(k+1)]\) for noninteger \(0<d<1\). The gamma-ratio asymptotic gives \(w_k\sim k^{-d-1}/\Gamma(-d)\); the prefactor is negative for this range of \(d\). Polynomial decay is an infinite-filter property. Finite truncation, an ADF rejection or high correlation with the original price does not prove stationarity, preserved economic information or forecasting value. Fractionally differencing an \(I(1)\) process by 0.3 need not make it stationary.

  8. Inclusive uniqueness. Inclusive labels \([i,i+h]\): derive interior concurrency and uniqueness. Compare half-open spans and independent sample size.

    Solution

    With one label starting each integer day and fixed inclusive span \([i,i+h]\), an interior day is covered by starts \(t-h,\ldots,t\), namely \(h+1\) labels. Average inverse concurrency for an interior label is therefore \(1/(h+1)\). A half-open span covering exactly \(h\) dates instead gives \(1/h\). Early barrier endings and sample edges change the weights. Summing uniqueness weights is a concurrency diagnostic, not a universal effective independent sample size or a replacement for covariance-based inference.

  9. Attention equivariance. Prove row-permutation equivariance of attention. Distinguish fixed slot embeddings from identities that move with assets.

    Solution

    Shared rowwise projections under permutation \(P\) give \(Q'=PQ\), \(K'=PK\), \(V'=PV\). Therefore \(Q'K'^\top=P(QK^\top)P^\top\). Rowwise softmax commutes with the simultaneous row/column permutation, so \(A'=PAP^\top\) and \(A'V'=PAV\). Shared output maps, residuals and rowwise feed-forward operations preserve this property. A fixed nonpermuted row-slot embedding can break it. An identity or alphabetical-rank feature that moves with its asset is part of the permuted row and need not break reindexing equivariance. Symmetry alone gives no predictive guarantee.

  10. Adaptive counting and a counterexample. Derive the adaptive-level telescoping identity and its bounded-state condition. Give a finite-maximum counterexample.

    Solution

    Sum \(a_{t+1}=a_t+\gamma(\alpha-e_t)\) to get \(T^{-1}\sum_te_t-\alpha=(a_1-a_{T+1})/(\gamma T)\). For finite scores, ideal conventions of an infinite interval when \(a_t\le0\) and an empty set when \(a_t\ge1\), with \(a_1\in[0,1]\), keep the state in \([-\gamma,1+\gamma]\). Consequently the absolute discrepancy is at most \([\max(a_1,1-a_1)+\gamma]/(\gamma T)\). The House instead uses a finite past maximum and a zero-width interval at the boundaries. Strictly increasing residual scores exceed every finite past maximum, so \(e_t=1\) forever and \(a_t\to-\infty\) for \(\alpha<1\). The identity still holds, but its remainder need not vanish. Zero residuals also distinguish width-zero from an empty set.

  11. (qual) Split conformal. (qual) Prove split-conformal marginal coverage with independent fitting and exchangeable scores; include ties and \(k>n\).

    Solution

    Conditional on an independently fitted predictor, suppose the \(n\) calibration scores and the new score are exchangeable. With distinct scores, the new rank is uniform on \(1,\ldots,n+1\). Let \(k=\lceil(n+1)(1-\alpha)\rceil\), and choose the \(k\)th calibration order statistic, using infinity if \(k>n\). Then coverage is \(k/(n+1)\ge1-\alpha\), and it is at most \(1-\alpha+1/(n+1)\). Random tie breaking recovers the uniform-rank argument; inclusive intervals without random tie breaking can only increase coverage, so the upper bound need not hold with ties. If \(k=n+1\), infinite width covers surely. These are marginal statements; selection on calibration outcomes invalidates the standard conditional argument. The capped finite-order helper does not provide the all-alpha theorem.

  12. (qual) Gaussian finite-sample risk and limits.

    Solution

    Let \(X\) have IID \(N(0,1)\) entries, independent noise variance \(\sigma^2\), fixed \(\|b\|^2=r^2\) and independent isotropic test covariates. For \(P<N-1\), OLS has conditional coefficient covariance \(\sigma^2(X^\top X)^{-1}\); the Wishart inverse mean is \(I/(N-P-1)\). Thus expected excess prediction risk is \(\sigma^2P/(N-P-1)\), tending to \(\sigma^2\gamma/(1-\gamma)\) when \(P/N\to\gamma<1\). For \(P>N+1\), minimum-norm error separates into lost signal \((I-X^+X)b\) and fitted noise \(X^+\varepsilon\). Rotational invariance gives expected squared bias \(r^2(1-N/P)\); \(XX^\top\) is Wishart with \(P\) degrees of freedom, yielding variance \(\sigma^2N/(P-N-1)\). The limit is \(r^2(1-1/\gamma)+\sigma^2/(\gamma-1)\). For \(r^2=\sigma^2=1\) and \(\gamma>1\), this equals \(1+1/[\gamma(\gamma-1)]>1\), the zero-forecast excess risk; at \(\gamma=1/2\), excess risk is one. Add fresh noise variance one for total MSE. For stronger signal \(r^2>\sigma^2\), above-threshold ridgeless excess risk can beat zero when \(\gamma>r^2/(r^2-\sigma^2)\); the unit-signal conclusion is not universal.

Reading and notes

The part's papers

from READING.md

  • Rahimi, A., Recht, B. (2007). "Random features for large-scale kernel machines." NeurIPS.
  • Easley, D., López de Prado, M., O'Hara, M. (2012). "The volume clock: insights into the high-frequency paradigm." JPM.
  • Rapach, D., Strauss, J., Zhou, G. (2013). "International stock return predictability: what is the role of the United States?" Journal of Finance.
  • Lundberg, S., Lee, S.-I. (2017). "A unified approach to interpreting model predictions." NeurIPS.
  • Krauss, C., Do, X. A., Huck, N. (2017). "Deep neural networks, gradient-boosted trees, random forests: statistical arbitrage on the S&P 500." EJOR.
  • Fischer, T., Krauss, C. (2018). "Deep learning with long short-term memory networks for financial market predictions." EJOR.
  • López de Prado, M. (2018). Advances in Financial Machine Learning: information-driven bars, triple-barrier labels, meta-labeling, fractional differentiation.
  • Belkin, M., Hsu, D., Ma, S., Mandal, S. (2019). "Reconciling modern machine-learning practice and the classical bias–variance trade-off." PNAS.
  • Gu, S., Kelly, B., Xiu, D. (2020). "Empirical asset pricing via machine learning." RFS.
  • Israel, R., Kelly, B., Moskowitz, T. (2020). "Can machines 'learn' finance?" J. Investment Management.
  • Gu, S., Kelly, B., Xiu, D. (2021). "Autoencoder asset pricing models." J. Econometrics.
  • Gibbs, I., Candès, E. (2021). "Adaptive conformal inference under distribution shift." NeurIPS.
  • Leippold, M., Wang, Q., Zhou, W. (2022). "Machine learning in the Chinese stock market." JFE.
  • Hastie, T., Montanari, A., Rosset, S., Tibshirani, R. (2022). "Surprises in high-dimensional ridgeless least squares interpolation." Annals of Statistics.
  • Avramov, D., Cheng, S., Metzker, L. (2023). "Machine learning vs. economic restrictions: evidence from stock return predictability." Management Science.
  • Jiang, J., Kelly, B., Xiu, D. (2023). "(Re-)Imag(in)ing price trends." Journal of Finance.
  • Kelly, B., Xiu, D. (2023). "Financial machine learning." Foundations and Trends in Finance.
  • Chen, L., Pelger, M., Zhu, J. (2024). "Deep learning in asset pricing." Management Science.
  • Kelly, B., Malamud, S., Zhou, K. (2024). "The virtue of complexity in return prediction." Journal of Finance.
  • Didisheim, A., Ke, S., Kelly, B., Malamud, S. (2023). "Complexity in factor pricing models." Working paper (verify).
  • Jensen, T., Kelly, B., Malamud, S., Pedersen, L. H. (2024). "Machine learning and the implementable efficient frontier." Working paper (verify: venue).
  • Kelly, B., Kuznetsov, B., Malamud, S., Xu, T. A. (2025). "Artificial intelligence asset pricing models." NBER WP (verify).
  • Nagel, S. (2025). "Seemingly virtuous complexity in return prediction." Working paper (verify).
  • Buncic, D. (2025). Comment on the virtue of complexity (verify: title).
  • Shi, Y., et al. (2025). "Kronos: a foundation model for the language of financial markets." arXiv (verify).
  • Cong, L. W., Tang, K., Wang, J., Zhang, Y. (2021). "AlphaPortfolio: direct construction through deep reinforcement learning and interpretable AI." Working paper (verify).

Papers and sources

References

Books: Kelly and Xiu, Financial Machine Learning (2023), chapters 1–9; Lopez de Prado, Advances in Financial Machine Learning, chapters 2–5 and 10; Hastie, Tibshirani and Friedman, The Elements of Statistical Learning, chapters 3, 10 and 11; Goodfellow, Bengio and Courville, Deep Learning, chapters 6–9; Isichenko, Quantitative Portfolio Management, chapter 2.

Research includes Marchenko and Pastur (1967); Grinold (1989); Hansen and Jagannathan (1991); Vovk, Gammerman and Shafer (2005); Rahimi and Recht (2007); Welch and Goyal (2008); Zaheer et al. (2017); Dobriban and Wager (2018); Lei et al. (2018); Belkin et al. (2019); Kelly, Pruitt and Su (2019); Bartlett et al. (2020); Gu, Kelly and Xiu (2020, 2021); Israel, Kelly and Moskowitz (2020); Gibbs and Candès (2021); Giannone, Lenza and Primiceri (2021); Hastie et al. (2022); Mei and Montanari (2022); Leippold, Wang and Zhou (2022); Avramov, Cheng and Metzker (2023); Jiang, Kelly and Xiu (2023); Chen, Pelger and Zhu (2024); Kelly, Malamud and Zhou (2024); Ansari et al. (2024); Das et al. (2024); Nagel (2025); Kelly, Kuznetsov, Malamud and Xu (2025); Shi et al. (2025).

Verified primary references:

  • Gu, Kelly and Xiu, official paper: author-reported monthly OOS \(R^2\) around 0.33–0.40%; best NN gross long-short Sharpe 1.35 with market-cap weights, 2.45 with equal weights. These historical stock results are not this crypto illustration.
  • Kronos, arXiv:2508.02739, first posted August 2025: author-reported relative RankIC +93%/+87%, volatility MAE −9%, generative fidelity +22% on the paper's benchmarks. Not replicated here; corpus size alone proves no leakage.
  • SEC release 2025-15, 16 January 2025: firm settlement, $90 million total penalties ($45 million per adviser) and $165 million voluntary repayments; the release also covers separate whistleblower-protection violations. Do not attribute all penalties solely to model changes or infer current individual-case status.
  • Zuckerman (2019): reported Medallion arithmetic annual averages 66.1% gross and 39.1% net over 1988–2018. Public historical reporting is not an audited current offering or an investor-attainable forecast.
Data, scope and reproducibilityMathematical scope

For a symmetric binary signal \(S=\pm1\), \(r=aS+\varepsilon\) with independent mean-zero noise variance \(\sigma^2\), forecast \(aS\) and sign position \(S\), population \(R^2=a^2/(a^2+\sigma^2)\) yields annual Sharpe \(\sqrt{12R^2/(1-R^2)}\). Independent equal-risk bets multiply this by \(\sqrt N\). Arbitrary measured out-of-sample \(R^2\) does not determine attainable Sharpe, sign accuracy or a literal explained-variance fraction.

For IID normal weekly returns, annual Sharpe variance is approximately \((1+SR_{ann}^2/(2q))/T_{years}\), \(q=52\). The approximation \(SE\simeq1/\sqrt{T_{years}}\) and two-SE length \(4/SR_{ann}^2\) are precision heuristics, not prospective power calculations. Paired strategy comparisons need their covariance, dependence and selection history.

The Gaussian ridge theorem assumes isotropic independent Gaussian features, independent noise, stated signal scaling and proportional dimension. Numerical limits use finite quadrature. Simulation medians and ranges are not exact finite-sample equality. Restricted managed-factor autoencoders are not identical to unrestricted ALS IPCA; their total fit uses contemporaneous test returns, while prediction uses mean factors from training plus validation.

Split conformal requires calibration labels independent of predictor fitting/selection and exchangeable calibration/new scores conditional on fitting. Rank \(k=\lceil(n+1)(1-\alpha)\rceil\) uses infinite width when \(k>n\); the unchanged helper caps \(k\) at \(n\). The crypto NN2 reuses validation labels for selection and calibration, so standard split-conformal coverage does not certify that example. Coverage is marginal, not per-regime.

The adaptive update always telescopes, but arbitrary-sequence counting bounds need appropriate boundary conventions or another bounded-state argument. The House uses finite past maxima and zero widths instead of infinite intervals and empty sets. Strictly increasing residual scores can therefore cause every interval to miss and drive the working level to negative infinity. An empirical Bitcoin coverage value is descriptive.

Chapter notesChapters and qualifications
Scene Subject and scope
Hook GKX's author-reported stock results; an explicitly specified binary-signal breadth example
Signal In-sample monthly volatility-normalised predictor fits; zero and historical-mean benchmarks differ
Zoo Venue-specific USDT archive; later symbol coverage is not an investable point-in-time universe
Limits Quote-volume splits and fixed turnover/fee scenarios; no causal or executable-capacity conclusion
Complexity Positive ridge need not interpolate; capacity and feature scaling matter
Critics Kernel diagnostics; artificial reversal baseline has different information
Theory Gaussian proportional limits; excess risk excludes fresh noise, misspecified total MSE includes it
Autoencoder Restricted managed-factor implementation; contemporaneous reconstruction differs from forecasting
DeepSDF Finite pooled moments and L1-normalised weights; no positivity or general pricing certificate
Attention Set interactions beyond already ranked inputs; one selected seed/week heatmap is descriptive
Images Previous-close open proxy; selected images, overlapping training windows and gross comparisons
Foundation Context-centred log absolute moves; retrospective transfer chronology and unequal adaptation
Toolkit Activity bars, finite filters, daily-close barriers and concurrency weights
Conformal Independent calibration and exchangeable scores; actual finite-boundary adaptive rule has limits
Firms Dated public reports and the 16 January 2025 SEC firm settlement
Envelope Registration and evaluation protocol; fixed paired-mean arithmetic, no sealed scores
House Rule 27: evaluate the full information, selection, calibration and execution protocol
Outro Fourteen qualified recap lines, six desk questions and twelve worked problems

The frozen public symbol list contains 701 names. Original eligibility uses at least 30 recorded daily observations, weeks with at least ten eligible coins, 60 calendar days since the first observed close and a past-28-day median quote volume of at least 250,000 USDT. Missing-price and last-close fallbacks do not certify liquidation or delisting returns. Quote volume is not market capitalisation. Same-close forecasts and gross long-short returns do not establish attainable fills or short availability.

Subtracting seven from an integer YYYYMMDD date is not seven calendar days. The original zoo/conformal period cuts can retain late-December features whose seven-day labels end in January. Training and validation labels are winsorised separately using their own outcome quantiles; test labels stay raw. These original limitations are disclosed rather than repaired by a substitute market test.

Companion films in this repository

中文讲义

本讲的中文说明、交易台问题与习题解答(与英文版对应)。

导言中文说明

本讲区分三类证据:文献作者报告的股票结果、明确给定假设的数学例子,以及较小规模的原始加密资产计算。训练拟合、名义覆盖率和复杂架构都不能补足评估中缺少的假设。科学表述修订、双语构造与实际渲染视觉审查已完成,证据见下文;完整生产成片连续听审和发音检查仍为独立待办。

十三项普通计算已尝试完成,十二项成功;预训练迁移在首个SPY冻结输入哈希不符时停止,未产生结果缓存,后续四只ETF未评估。数值结果保留缺失,不刷新、不重试,也不做替代历史策略。模拟窗口仅解释协议。

金融算法、House库和全局登记数据保持原字节。panel会调用封存,envelope会登记并打开实验,因此二者均不得计算、加载或评分。普通读取器可能先读取截至2025年的公开档案再应用研究期掩码;不能声称所有2020年后的公开数据从未读取。已有只读计数是第27讲累计10,457次、全系列23,562次;本次不新增试验,不强制刷新,不修改登记,不读取封存策略载荷。无法通过冻结输入校验的原始结果必须保留缺失状态。

701个名称是后来的公开档案覆盖,不能等同于逐时可投资样本池。60天按首次观测价格后的日历天数计算,成交额以USDT计价,不是市值。最后可用收盘价及缺失回退不保证完整退市清算收益。整数日期减7并非减7个日历日,部分年末标签可延伸至下一年。训练与验证目标分别按各自结果分位数缩尾;测试目标不缩尾。这些局限保持并披露,不另做替代历史策略测试。

理论岭回归风险是各向同性高斯、独立噪声与比例维数下的极限,超额风险不含新观测噪声;设定错误例子画的是包含噪声的总均方误差。自编码器总拟合用当期已实现收益提取因子,不能称为预测;预测版使用训练加验证期的因子均值。有限对抗矩不能认证正随机折现因子、每项条件矩或全局最优。

分裂共形要求预测器拟合和选择独立于校准标签,并要求给定拟合结果后,校准与新分数可交换。原始NN2重复使用验证标签进行选择和校准,不满足标准论证。边际覆盖也不是每个市场状态的覆盖。自适应更新的望远镜恒等式总成立,但任意序列计数界依赖边界约定和有界状态;House使用有限历史最大值及零宽区间,不自动继承无限区间与空集规则的保证。

Desk questions, with solutions六个交易台问题与解答
  1. 二值信号、总体\(R^2=0.5\%\)、500个独立等风险下注? 明确模型下年化夏普为\(\sqrt{12\times500\times0.005/0.995}\approx5.49\)。任意测得的样本外\(R^2\)不能单独确定可实现夏普;还需独立性、已知参数和交易假设。
  2. 参数比样本多且训练完美拟合? 单凭这一点无法判断。检查秩、惩罚、特征尺度、信噪比、同等信息基准与独立预测风险。正惩罚岭回归通常不插值。
  3. 方向准确率55%? 还需涨跌幅、基准比例、仓位、协方差、换手、成交与成本。准确率不能决定净价值。
  4. 两年年化夏普为1? 独立正态周收益近似给出标准误\(\sqrt{(1+1/104)/2}\approx0.71\),示意95%区间约为\([-0.39,2.39]\)。它未处理相依、选择或小样本误差。成对比较需要收益协方差;功效还需备择和拒绝规则。
  5. 元模型精确率翻倍但只保留十分之一机会? 比较单位时间扣费后的收益和风险,考虑涨跌幅、广度损失及重叠仓位。独立等尺度简化下,广度缩小十倍要求单笔夏普提高\(\sqrt{10}\)倍才能维持总体夏普;精确率本身不能确定这一点。
  6. 名义90%区间在一个状态只覆盖70%? 边际定理并不保证状态条件覆盖。先检查独立校准、可交换性和真实边界规则。滚动或自适应修改形成新协议,需要另行评估;原始有限最大值规则没有任意序列认证。
Problems, with worked solutions十二道习题与完整解答
  1. 二值信号与广度。 二值信号\(S=\pm1\)、\(r=aS+\varepsilon\):推导总体\(R^2\)、符号策略夏普及独立下注缩放。

    解答

    设\(S=\pm1\)等概率,\(r=aS+\varepsilon\),噪声独立、均值零、方差\(\sigma^2\),月份相互独立。预测\(aS\)相对零预测的总体平方误差改善为\(a^2/(a^2+\sigma^2)\)。按信号符号持仓得到\(Sr=a+S\varepsilon\),均值\(a\)、方差\(\sigma^2\),月夏普为\(a/\sigma=\sqrt{R^2/(1-R^2)}\)(\(a\ge0\))。独立月份乘\(\sqrt{12}\),\(N\)个独立等风险下注再乘\(\sqrt N\)。相依、预测估计和交易约束会改变映射,任意经验样本外\(R^2\)不能普遍推出可实现夏普。

  2. 成对均值。 成对均值:推导\(\operatorname{Var}(A-B)\)。标准差均为1、相关0.8、100组独立配对时,标准误是多少?

    解答

    令\(D=A-B\),则\(\operatorname{Var}D=\sigma_A^2+\sigma_B^2-2\rho\sigma_A\sigma_B\)。两者标准差均为1、相关系数0.8时,方差0.4,标准差\(\sqrt{0.4}=0.63246\)。100组独立配对的均值差标准误为\(\sqrt{0.4/100}=0.06325\)。日期相依时应估计长期方差。这是任意单位的均值比较,不是夏普差公式。

  3. 零惩罚岭极限。 用奇异值分解推导零惩罚岭极限,并说明何时插值。

    解答

    紧致奇异值分解\(X=UDV^\top\)给出\(\hat b_\lambda=V\operatorname{diag}[d_j/(d_j^2+N\lambda)]U^\top y\)。令\(\lambda\downarrow0\)得\(VD^{-1}U^\top y=X^+y\)。任何零空间附加项都增加范数,因此这是最小范数最小二乘解。当且仅当\(y\)在\(X\)的列空间中时插值;满行秩时对每个\(y\)都插值。只有\(P>N\)而无秩条件并不足够;正惩罚通常不插值。

  4. 高斯随机傅里叶特征。

    解答

    若\(w\sim N(0,\eta^2I)\),则\(w^\top\Delta\)为方差\(\eta^2\|\Delta\|^2\)的正态变量。特征函数实部给出\(E\cos(w^\top\Delta)=e^{-\eta^2\|\Delta\|^2/2}\)。配对正弦余弦、\(M\)个独立频率的内积是余弦样本均值;每项有界,均值方差不超过\(1/M\),固定输入处误差为\(O_p(M^{-1/2})\)。这不是所有输入上一致成立的确定性保证。

  5. 典范投影与HJ界。 对于\(M=1-w^\top R\),推导典范无条件权重及正确归一化的汉森–贾甘纳坦界。

    解答

    超额收益均值\(\mu\)、协方差\(\Sigma\succ0\),设\(s^2=\mu^\top\Sigma^{-1}\mu\)。\(M=1-w^\top R\)和\(E[MR]=0\)给出\((\Sigma+\mu\mu^\top)w=\mu\)。谢尔曼–莫里森公式得\(w=\Sigma^{-1}\mu/(1+s^2)\),故\(E M=1/(1+s^2)\),标准差\(s/(1+s^2)\)。任一定价组合满足\(E M E R_p=-\operatorname{Cov}(M,R_p)\),柯西–施瓦茨给出\(|SR_p|\le\operatorname{sd}M/E M\)。无约束投影达到切点比率\(s\),但可能在某些状态取负;不能自动视为正的无套利折现因子或受约束条件网络的解。

  6. 布朗双障碍。 布朗漂移\(\mu\)、波动率\(\sigma>0\)、障碍\(\pm b\):推导无限期限内先到上障碍的概率。

    解答

    \(X_t=\mu t+\sigma W_t\)、\(\sigma>0\),从零出发,首次到达\(\pm b\)时停止。上障碍先到概率满足\((\sigma^2/2)u''+\mu u'=0\),边界\(u(-b)=0,u(b)=1\)。解得\(u(0)=(1-e^{-2\mu b/\sigma^2})/(1-e^{-4\mu b/\sigma^2})=1/(1+e^{-2\mu b/\sigma^2})\)。\(\mu\to0\)时极限为二分之一。有限期限、离散收盘、跳越和成本是不同问题。

  7. 分数阶权重衰减。 非整数\(0<d<1\)时,推导分数阶权重及渐近衰减。截断不能证明什么?

    解答

    \(w_0=1\),递推\(w_k=-w_{k-1}(d-k+1)/k\)给出\(w_k=(-1)^k{d\choose k}=\Gamma(k-d)/[\Gamma(-d)\Gamma(k+1)]\),其中非整数\(0<d<1\)。伽马函数比值渐近得\(w_k\sim k^{-d-1}/\Gamma(-d)\),该范围内前因子为负。这是无限滤波性质。有限截断、ADF拒绝或与原价格高相关都不能证明平稳、保留经济信息或具备预测价值;对\(I(1)\)过程做0.3阶差分不一定使其平稳。

  8. 含端点唯一性。 含端点标签\([i,i+h]\):推导内部并发度和唯一性,比较半开跨度及独立样本量。

    解答

    每日启动一个固定标签\([i,i+h]\)且两端计入时,内部日期由\(t-h,\ldots,t\)启动的\(h+1\)个标签覆盖。因此内部平均逆并发度为\(1/(h+1)\)。若用恰含\(h\)个日期的半开区间,则为\(1/h\)。提前触及障碍和样本边缘会改变平均值。唯一性之和是并发诊断,不是普适独立样本量,也不能替代协方差推断。

  9. 注意力等变性。 证明注意力行置换等变性;区分固定槽位嵌入与随资产移动的身份特征。

    解答

    行置换\(P\)使共享投影变为\(Q'=PQ,K'=PK,V'=PV\),分数矩阵变为\(P(QK^\top)P^\top\)。逐行softmax与同时行列置换可交换,所以\(A'=PAP^\top\)且\(A'V'=PAV\)。共享输出映射、残差和逐行前馈保持性质。固定且不随行移动的位置嵌入可能破坏它;随资产同行置换的身份或字母排序特征则不一定破坏重新索引等变性。对称性不保证预测有效。

  10. 自适应计数及反例。

    解答

    累加\(a_{t+1}=a_t+\gamma(\alpha-e_t)\)得\(T^{-1}\sum e_t-\alpha=(a_1-a_{T+1})/(\gamma T)\)。对有限分数,理想边界在\(a_t\le0\)时用无限区间、\(a_t\ge1\)时用空集,且\(a_1\in[0,1]\),可将状态限制在\([-\gamma,1+\gamma]\)。于是误差绝对值不超过\([\max(a_1,1-a_1)+\gamma]/(\gamma T)\)。House却使用有限历史最大值和零宽区间。严格递增残差始终超过有限历史最大值,导致每次都漏盖,\(\alpha<1\)时\(a_t\to-\infty\)。恒等式仍正确,余项却不趋零。零残差也说明零宽区间不等于空集。

  11. (资格考试)分裂共形。

    解答

    给定独立拟合的预测器,假设\(n\)个校准分数和新分数可交换。无并列时,新秩在\(1,\ldots,n+1\)均匀分布。令\(k=\lceil(n+1)(1-\alpha)\rceil\),采用第\(k\)个校准次序统计量;\(k>n\)时取无限宽。覆盖率为\(k/(n+1)\ge1-\alpha\),且不超过\(1-\alpha+1/(n+1)\)。随机打破并列可恢复均匀秩;不随机且含边界的区间可能更保守,因此有并列时上界不必成立。\(k=n+1\)时无限宽必然覆盖。这是边际结论,校准标签参与选择会破坏标准条件论证;有限次序截顶的辅助函数不提供所有显著性水平的定理。

  12. (资格考试)高斯有限样本与极限风险。

    解答

    \(X\)元素独立标准正态,独立噪声方差\(\sigma^2\),固定\(\|b\|^2=r^2\),测试协变量独立且各向同性。\(P<N-1\)时OLS条件协方差为\(\sigma^2(X^\top X)^{-1}\);逆Wishart均值为\(I/(N-P-1)\),故期望超额预测风险为\(\sigma^2P/(N-P-1)\),比例极限为\(\sigma^2\gamma/(1-\gamma)\)。\(P>N+1\)时最小范数误差分成丢失信号\((I-X^+X)b\)及拟合噪声\(X^+\varepsilon\)。旋转不变性给出期望偏差平方\(r^2(1-N/P)\);\(XX^\top\)是自由度\(P\)的Wishart矩阵,噪声项为\(\sigma^2N/(P-N-1)\)。极限为\(r^2(1-1/\gamma)+\sigma^2/(\gamma-1)\)。信号和噪声均为1、\(\gamma>1\)时等于\(1+1/[\gamma(\gamma-1)]>1\),高于零预测超额风险;\(\gamma=1/2\)时超额风险为1。总均方误差还需加新噪声方差1。较强信号\(r^2>\sigma^2\)下,\(\gamma>r^2/(r^2-\sigma^2)\)时可优于零预测,因此单位信号例子的结论并不普遍。

Review log of the earlier QA passes on this part: docs/qa/quant/part27.md.

Build the film

python -m videos.quant.quant27.compute      # the part's numbers, into .cache/quant27
python tools/make.py quant27                # the narrated film, English and Chinese
EXPLAINER_TTS=silent python tools/qa_scene.py quant27 Hook   # one chapter, silent, with a contact sheet

Scenes: videos/quant/quant27. Setup: see the course page. Source of these notes: the part's README and the scenes' narration.