Act V · Portfolios, Strategies and the Firm
Part 33 of 43Statistical Arbitrage
Two prices are tied by an elastic band. When is trading the stretch a strategy, and when is it a way to find out the band was never there?
Statistical arbitrage began in a bank's back office in the 1980s with pairs of similar stocks. The part rebuilds it in stages: pairs chosen by distance, the cointegration test and the screening problem it creates (test enough pairs and noise passes), the Ornstein-Uhlenbeck spread and its half-life, residuals from a factor model in place of pairs, and hedge ratios that drift, tracked with a Kalman filter. The research chapter answers the practical question: given a cost, how far should the spread stretch before you trade? Crowding and decay close the part.
What you need. Parts 7 and 31.
What you will be able to do
Undergraduate
- Explain a pairs trade and what could make the spread not come back.
Master's
- Test for cointegration and correct for the number of pairs screened; fit an Ornstein-Uhlenbeck process and compute its half-life.
- Build residual (eigenportfolio) signals and trade them with an s-score rule, net of costs.
PhD
- Derive the optimal entry band for an OU spread by renewal-reward and first-passage times, and the small-cost law in which the band scales with the cube root of the cost.
Industry
- Explain capacity and crowding in stat arb, and how a desk decides a spread has broken.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Undergraduate 11 min · Master's 44 min · PhD 57 min · Industry 23 min.
- 0Two prices on an elastic bandUndergraduate3 min
- 1From Morgan Stanley's back office to the quant firmsIndustry3 min
- 2Pairs by distanceUndergraduate4 min
- 3Cointegration and the screening problemMaster's4 min
- 4The Ornstein-Uhlenbeck spreadMaster's4 min
- 5Eigenportfolios and residualsMaster's5 min
- 6Hedge ratios that moveMaster's3 min
- 7Reversal and lead-lagMaster's4 min
- 8Learning the residualPhD4 min
- 9Liquidity, crowding and decayIndustry4 min
- 10An evaluation protocolIndustry1 min
- 11Rule 33: the stat-arb bookIndustry5 min
- For the researcher: the optimal band for a mean-reverting spreadPhD9 min
- Recap, desk questions, problemsAll tracks5 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.
Two prices on an elastic bandUndergraduate3 min
Statistical arbitrage: trading the gap between prices that ought to move together, on the bet that the gap will close.
Two prices that wander together. Each has a shared stochastic trend and a stationary component; that does not make every return unpredictable. But the gap between them is tied to an elastic band: it stretches and snaps back. Sell the one that has run ahead and buy the one that lagged, when the gap is wide; close when it is shut. In this chosen model the common log trend cancels. Funding, changing hedge weights and real execution remain separate questions.
That is the textbook promise. This part tests it. On the American industries, the classic pairs rule lost money over half a century. Pairs that pass a cointegration test in one year are about 7 percent of them, barely twice the rate for random walks with no connection at all, and passing once says almost nothing about passing again. What remains to assess is subtler: synthetic factor residuals, fitted on rolling windows, and a mathematical band rule for a known Ornstein-Uhlenbeck process. Apparent residual reversion and a fitted cost proxy do not establish executable returns.
Where this sits. Part thirty-two followed trends; this part bets against them, at the scale of days and of single securities. It uses Part five's Ornstein-Uhlenbeck process, Part seven's cointegration and Kalman filter, Part thirty-one's factor model and costs, and the crowding of August 2007, which began in exactly this kind of book.
Edward Thorp's Princeton/Newport Partners traded hedged convertible arbitrage from 1969; a group at Morgan Stanley traded pairs of stocks in the mid-1980s; and in 1988 David Shaw founded his firm while Renaissance's Medallion fund began. Academics measured the reversal it harvested in 1990, re-ran the pairs rule in 2006, and watched it crowd and crash in 2007. The modern era: residuals of factor models, optimal trading bands derived for the Ornstein-Uhlenbeck process, liquidity as the source of the return, and neural networks trained on residual paths.
The plan: the history; pairs by distance, re-run; cointegration, and why screening for it misleads; the Ornstein-Uhlenbeck spread and its half-life; residuals against eigenportfolios; hedge ratios that move; reversal and lead-lag; a network trained on residual paths; liquidity, crowding and decay; a residual book evaluated through an accounting and timing protocol; and an exact band theorem within a specified model.
In the House, the research desk studies residual signals. A fitted factor hedge reduces model exposures, but estimation error, financing, crowding and execution remain. This lesson does not establish a live book.
1From Morgan Stanley's back office to the quant firmsIndustry3 min
Statistical arbitrage was not invented in a university. It grew out of trading desks that had more computing power than ideas about what to do with it.
The first firm file is older than the name. Edward Thorp, who had beaten blackjack with probability, and Jay Regan founded Princeton/Newport Partners in 1969. They bought convertible bonds and warrants that a model said were cheap, and sold the stock against them, so the market's direction hardly mattered. Thorp's model of the option inside was, as he later wrote, close to Black and Scholes's, before theirs was published: Part ten's formula, used as a trading tool.
The name came from Morgan Stanley. In the mid-1980s Gerry Bamberger, and then a group led by Nunzio Tartaglia, used computers to find pairs of stocks whose prices had drifted apart, and bet on their reunion, in size. As reported, the group earned about fifty million dollars in 1987, and it was disbanded in 1989 after weaker years. Its alumni spread the idea across Wall Street.
One of those alumni was David Shaw, a computer scientist from Columbia, who founded his firm in 1988. It began with computerised statistical arbitrage in equities, many small mean-reversion bets hedged against the market and industries, and grew into one of the largest systematic investment firms. The design was the one this part builds: a factor model to remove what is common, and a bet that what is left reverts.
And Renaissance Technologies, founded by the mathematician James Simons. Its Medallion fund, started in 1988, became famous for returns far above any other fund's, as reported, while its methods stayed private. It later returned outside investors' money, and runs mostly for its own employees: the profit-maximising size of Part thirty-one, chosen by a firm that owns its strategy.
Morgan Stanley tried again. In 1993 Peter Muller started a quantitative group inside the bank, Process Driven Trading, which, as reported, ran statistical arbitrage among other strategies with the bank's own capital, and was spun out as an independent firm in 2012, after new rules limited banks' proprietary trading. The pattern repeats through this history: the methods start inside a bank and end up in independent firms.
What changed. In the beginning, a few desks had computers, spreads were wide and competitors were slow: pairs held for weeks earned large returns. Then prices went decimal, markets went electronic, and many firms ran the same models: holding periods shrank to days and hours, and the edge per trade shrank with them. Liquidity provision is an important proposed source of return. Cheap execution helps, but inventory risk, adverse selection and competition also matter; the historical stories do not identify a single cause.
Pause and predict. A strategy's edge is three basis points a trade, and it trades every position daily. What happens when spreads fall from ten basis points to two, and why might it still get worse?
2Pairs by distanceUndergraduate4 min
In 2006 Evan Gatev, William Goetzmann and Geert Rouwenhorst wrote down the rule the desks had used, and tested it on forty years of American stocks.
The rule has no model at all. Normalise each asset's total-return index to one. Over a year, measure the distance between every pair of paths, and keep the twenty closest. Over the next six months, when a pair's gap exceeds twice its formation standard deviation, sell the high one and buy the low one, and close when the paths cross. These window choices resemble the paper, but the implementation is an industry proxy. It selects complete research histories retrospectively, restarts the trading indices each half-year, and applies lagged discrete positions to half the return difference. It is not fixed-share stock P and L.
The paper that made the rule famous. Evan Gatev, William Goetzmann and Geert Rouwenhorst ran it on American stocks from 1962 to 2002. The top twenty pairs earned, as reported, average annualised excess returns of up to eleven percent. The profits survived waiting a day before trading, which reduces a bid-ask bounce concern, and exceeded their estimated costs. They were lower in later years. Our industry result is a different implementation and universe, so it cannot by itself extend that stock result.
One pair, the closest at the start of the second half of 2008: the telecommunications and business-services industries. In the formation year they moved almost as one. In the trading window the gap broke through its band within a month as the crisis hit them differently, took about three months to close, and then opened the other way. A pair that was close in calm times is not necessarily close in a crisis.
The result, decade by decade. In the 1960s and 70s the rule lost steadily; in the 90s and 2010s it earned a little. Over the whole period, a Sharpe ratio of -0.25 before costs, on a return of -0.5 percent a year. On industries, the implemented distance proxy has a negative sample mean; that is a result about this universe and convention.
Why not? Whole industries carry momentum, as Tobias Moskowitz and Mark Grinblatt found: two industries drifting apart are often a trend beginning, not noise reverting. Stocks and industry averages are different units. Some stock residuals may revert; the cited stock paper reports up to eleven percent a year for its own sample and capital convention. That is not a guarantee for an individual stock gap. And the rule has no model: it never asks why two paths moved together, so it cannot tell a temporary gap from a permanent break.
And the literature agrees. Binh Do and Robert Faff found the rule's returns on stocks declining steadily after the 1980s, with much of what remained earned in turbulent markets. Costs make it worse: every round trip trades four times on two legs. A rule without a reason decays first. The next chapters add the reason: a model of why a spread should revert at all.
A backtest on portfolios hides the short leg. On stocks it is real. Borrowing a share to sell it costs a fee, usually small, but tens of percent a year for hard-to-borrow names, and the expensive stock in a pair is often the one everyone else wants to short. The lender can recall the share at any time, and Joseph Engelberg, Adam Reed and Matthew Ringgenberg showed that the risk of rising fees and recalls itself deters arbitrage. And the rules can change: in September 2008 the SEC temporarily banned short sales of hundreds of financial stocks. A pair whose short leg cannot be held is not a pair.
Pause and predict. A pair's gap reverts with a half-life of twenty days, and you can hold for six months at most. Is a two-standard-deviation trigger too wide, too narrow, or about right?
3Cointegration and the screening problemMaster's4 min
Part seven introduced cointegration: two wandering series with a combination that does not wander. It is the right model for a pair. Finding pairs with it is another matter.
The definition. Each log price has a unit root: it wanders. But some combination, one price minus beta times the other, is stationary: that is the spread, and beta is the hedge ratio. Granger's representation theorem says that then at least one price moves to close the gap. The representation describes statistical adjustment under its assumptions; it does not identify arbitrageurs or prove a causal force that will close the gap on a trading deadline.
The Engle-Granger test, from Part seven. Regress one log price on the other. Test the fitted residual with a constant and one lagged difference. This implementation uses a fixed reference critical value of minus three point three four, rather than minus two: the regression chose the hedge ratio that makes the residual look as stationary as possible, so the test must ask for more.
Now screen the industries, one year at a time. In a typical year about 7 percent of industry pairs pass the test. Run the same test on pairs of independent random walks, which share nothing, and 3.7 percent pass: the test's own false-positive rate estimated from three hundred simulated controls, with sampling uncertainty. The same seeded sample of three hundred industry pairs is screened each year. Excess passes suggest a difference from these controls, but do not identify which ties are real or the fraction of discoveries that are false.
The harder test: does a pair that passes this year pass next year? Of the pairs that passed in one year, 8.1 percent passed again the next. For a pair chosen at random, the rate is 7.3 percent. Passing once is almost no evidence of passing again in this sample. Overlapping assets, repeated annual tests and estimated spreads matter; this is descriptive persistence, not a calibrated probability that each discovery is false.
And the half-lives of the pairs that passed. Fit an autoregression to each spread; the half-life is log two over minus the log of its coefficient. The median is about 8 trading days: fast reversion, measured on the same year that picked the pair. A pair is chosen because its spread happened to revert quickly in that sample, so its measured half-life is biased short. Selection again.
Beyond pairs: baskets. For several prices, write the changes as an error-correction model: each price moves partly in response to how far the system is from its long-run ties. The matrix of that response factors into speeds and cointegrating portfolios; its rank is the number of independent spreads. Soren Johansen's test reads the rank from eigenvalues, one likelihood-ratio test for the whole basket. But the screening problem only grows: every subset of a universe is a candidate basket, and every basket tested is a trial.
The purest pair there is. Royal Dutch and Shell were two listed shares with fixed claims, sixty to forty, on the cash flows of one group. Their prices should have been tied exactly. Kenneth Froot and Emil Dabora found they deviated from parity for long periods, by more than ten percent at times, and that each share moved with its own home market. Long-Term Capital Management held this trade when it failed in 1998, as reported. The gap closed for good only in 2005, when the companies unified. Even a contract does not make a spread revert on your schedule.
The screening problem, and three answers. With forty-nine assets there are eleven hundred seventy-six pairs. Five hundred stocks give one hundred twenty-four thousand seven hundred fifty pairs. At a calibrated five percent marginal size, all-null expected false passes are about fifty-nine or six thousand two hundred thirty-eight: Part twenty-six's counter applies to pairs. Pairs chosen for a reason, the same product, the same supply chain, two share classes of one company, supply an economic hypothesis. That hypothesis still needs stability checks and an evaluation fixed before its outcomes are inspected. Or skip pairs altogether: remove what all assets share with a factor model, and let each asset's residual revert on its own.
Pause and predict. You test two thousand unrelated pairs at the five percent level and keep the ones that pass. About how many is that, and how many of them pass again next year?
4The Ornstein-Uhlenbeck spreadMaster's4 min
A spread that reverts needs a model of how it reverts. The simplest, and the one the industry uses, is Part five's Ornstein-Uhlenbeck process.
The model. The spread is pulled toward its mean theta at speed kappa, and shaken by noise. Its distribution at any future time is exact: the expected gap decays exponentially, and the variance settles at sigma squared over two kappa. Two numbers describe a spread for a trader: its equilibrium standard deviation, which sets the size of the bets, and its half-life, which sets how long they last.
Estimation is a regression. Sampled daily, the OU process is exactly a first-order autoregression. Its slope is e to the minus kappa, its intercept and noise give theta and the equilibrium spread. So the House fits a spread by least squares on its own history, and reads the half-life off a slope between zero and one. The helper removes nonfinite values, which compresses gaps in the observation clock; use regularly spaced data or account for that limit.
A simulated spread with a half-life of ten days. It crosses its mean often and rarely stays far for long. The dashed lines are one and a quarter equilibrium deviations, where Avellaneda and Lee open a trade. Fitted on these three hundred days, the half-life comes out at 12.0 days. This is one chosen simulated path, not an accuracy guarantee. Next, short-window uncertainty.
The trading signal is the s-score. The spread's distance from its fitted mean, in equilibrium deviations. Marco Avellaneda and Jeong-Hyun Lee opened at one and a quarter and closed near the mean, with thresholds they chose on American stocks. And they traded only spreads whose fitted half-life was short enough to be estimated at all. Why those thresholds, and not others, is the research chapter's question.
On a short one, the estimate is biased. The autoregressive slope is pulled down in short samples, under the usual stationary, intercept-fitted large-sample approximation, by about one plus three b over sample length: Kendall's bias, the same one behind Part six's predictive regressions. Simulate a ten-day half-life: estimated on thirty days, the median comes out at 3.3; on sixty, 5.2; on a year, 8.4. And a screen that keeps the fastest-looking spreads keeps the most biased estimates. The displayed medians condition on finite fits; invalid or nonreverting fits are omitted, so these are not unconditional half-life medians.
How well sixty days pin down a speed. With an autoregressive slope of point nine, the half-life is 6.6 days, but two standard errors either way run from 2.9 days at the fast end to a slope of one at the slow end: no reversion at all. The slower the spread, the wider the range. The s-score uses this estimate every day: a book of s-scores is a book of very uncertain speeds, which is a warning against treating fitted speeds as known. The research theorem holds the equilibrium width fixed when comparing speeds; since that width itself depends on sigma and kappa, this is a conditional scaling result.
Where should the bands be? William Bertram computed the expected length of a trade on an OU spread in closed form, and the bands that maximise the return per unit time. Tim Leung and Xin Li treated entry and exit as optimal stopping problems, with costs and a stop-loss. The research chapter proves a version of its own, from first-passage times, and finds that the best band, measured in equilibrium deviations, depends only on the cost.
Pause and predict. A spread's daily autoregressive slope is point nine five. What is its half-life, and roughly what would a sixty-day sample estimate it as, on average?
5Eigenportfolios and residualsMaster's5 min
Avellaneda and Lee studied factor residuals instead of isolated pairs. We examine an industry proxy, keeping its original calculations fixed and separating synthetic residual statistics from executable wealth.
The idea. Write each asset's return as exposures to a few common factors, plus a residual: Part thirty-one's risk model, with the factors taken from the data. Add up the residuals: that is the asset's price with the market, sectors and styles removed. Treat it as an Ornstein-Uhlenbeck spread and trade its s-score. Each asset becomes a pair with the whole market, and there is no screening of pairs at all.
The factors are eigenportfolios. Take the correlation matrix of the last year's daily returns and its eigenvectors, Part thirty's spectrum again. Invest in each eigenvector, scaled by each asset's volatility. The first eigenportfolio is the market; the next few are sectors and styles. On the forty-nine industries the House keeps five, re-estimated every month.
The implementation matters. Regress each industry on five factors with an intercept over the last sixty observations. The factors use trailing two hundred fifty-two day correlations through the current close, refitted every twenty-one days. The intercept makes fitted residuals sum to approximately zero in each window. Their cumulative path is therefore tied down at its endpoint: apparent reversion can partly be a fitting constraint. Tomorrow's synthetic residual subtracts the fitted intercept as well as factor returns. A stock-minus-factor hedge does not automatically earn that subtracted intercept. Its weights also need financing and rebalancing. These statistics are a diagnostic proxy, not verified cash-flow profit.
Avellaneda and Lee's own refinements. How many factors? They used fifteen eigenportfolios, or as many as explain fifty-five percent of the variance, and also tried sector funds as factors; Part thirty's spectrum keeps the eigenvalues above the noise edge. They adjust the s-score for the residual's own drift, so a residual that is trending is not mistaken for one that is stretched. And they measure time in traded volume rather than days, which, they report, made the residuals revert more cleanly.
The stored industry proxy, with Avellaneda and Lee's thresholds. Before its cost charge, the annualized synthetic mean is 3.6 percent, with Sharpe 0.88. With its five-basis-point, two-leg turnover proxy, the mean is -1.6 percent and Sharpe -0.39. The normalization is the number of active industry signals, not the total gross capital of industry and hedge positions. Cumulative lines add these synthetic daily values. Positive gross performance does not by itself establish economically tradable reversion.
Nine stored research configurations: eight combinations of factor count, fitting window and entry threshold, plus the mathematical band. The best gross configuration has sample Sharpe 1.36. Its charged proxy Sharpe is -0.41, with discrete-signal turnover 25 percent daily. The research-band proxy has charged Sharpe 0.21, and turnover 11 percent. It was added after the earlier comparisons. All nine share data and modeling choices. This comparison is neither independent confirmation of the band nor an executable cost audit; no new registration or sealed evaluation is performed here.
All nine rules on one picture. Before costs they are bunched together, Sharpe ratios around 1.0. After costs they fall onto a line in turnover: every ten points of daily turnover cost about 0.39 of Sharpe ratio. The choice of factors and windows moves a rule a little up or down; how much it trades moves it along the line, and that is what decides the sign.
By era, for the research-band proxy. Before costs, Sharpe ratios of 1.46, 0.74 and 1.11: strongest in the 1990s, weakest from 2003 to 2010, and partly back after. After costs, 0.59, -0.22 and 0.15. Almost all of the net profit was earned in the first era. The same costs that are a small tax on a strong premium wipe out a weak one.
The cost proxy has three important limits. It charges twice a fixed one-way rate times changes in discrete signals divided by the new active count. It does not reconstruct each hedge trade. When that count changes, held positions are rescaled, but those trades are missing from the turnover measure. When the new book is empty, the code sets net profit to zero and omits the final exit charge even if signals changed. These omissions can understate costs; separate hedges can overstate them before netting. The combined error has no proven conservative direction. The original financial algorithm is preserved, and the lesson labels its output as a proxy.
For actual holdings, netting has a useful algebraic bound. Each industry position suggests a factor hedge. The triangle inequality says the absolute trade in their sum cannot exceed the sum of absolute separate trades, for the same holdings and linear unit costs. This does not validate the stored turnover proxy, which never reconstructs those hedge holdings and omits some rebalancing and exits. Full cash-flow accounting, borrow, financing, impact and actual tradable factor exposures are prerequisites for a net-performance claim.
Pause and predict. A residual book earns a gross Sharpe ratio of point eight at four percent volatility, and turns over twenty percent of its gross every day. At five basis points a side on both legs, what is left?
6Hedge ratios that moveMaster's3 min
Cointegration assumes one fixed hedge ratio. Real relationships drift. The Kalman filter of Part seven lets the hedge ratio move, and in doing so sets a trap.
The model. One log price is an intercept plus a hedge ratio times the other, plus noise. But the intercept and the hedge ratio are themselves random walks: a state that the filter tracks. One choice matters: the ratio of the state's noise to the observation's, which decides how fast the hedge ratio may move.
The filter predicts and then updates. The state covariance grows by q times the identity. The gain depends on the current loading vector and observation variance. Today's observed log prices update the coefficients. The innovation uses the prior state but today's x as well as today's y. It becomes available at the current close. Whether a subsequent holding earns a return requires explicit holdings and rebalancing; the innovation itself is not that wealth.
Bitcoin and ether, 2018 to 2020: two prices with an obvious common driver. One regression on all three years gives a hedge ratio of 0.96. A sixty-day rolling regression swings wildly, from near zero to almost three. The Kalman filter gives a smooth, slowly moving ratio between about two thirds and one. Which spread is the right one to trade?
Descriptive diagnostics for two different constructions. The full-sample fixed ratio is retrospective. Its residual ADF statistic is -1.40, and the fitted half-life 279 days. The adaptive innovation has statistic -14.8 and fitted half-life 1.3 days. Applying a fixed Engle-Granger reference to this generated adaptive series does not supply a calibrated cointegration test. A stationary-looking innovation is not proof of a stable fixed combination or profitable holdings.
The square-root rule is a scalar illustration. For a random-walk state observed with constant unit loading and small q over r, the steady gain is approximately the square root of q over r. Its exponential memory length is approximately the reciprocal gain. That gives about one hundred or ten observations for ratios of one in ten thousand or one in one hundred. Our two-state intercept-and-beta regression instead has the changing loading vector one and the current log price. Price levels, units and covariance matter. Those scalar numbers are not its universal effective window.
It is a trap. The Kalman spread is the filter's forecast error. A good filter's forecast errors are close to white noise, so of course they test as stationary, with a half-life of about a day. The spread looks like it reverts because the hedge ratio moves to absorb every gap, not because the prices converge. A trade on it is a bet that the filter will correct itself, which it does by changing the ratio, not by moving the prices.
So: use the filter to size the hedge, not to prove there is a pair. Test the spread out of sample, on its profit, not on its stationarity. And choose the speed slowly: a fast filter manufactures reversion, and every choice of its speed is a trial.
Pause and predict. A filter's one-step forecast errors have an autoregressive slope of point three. Is the pair cointegrated?
7Reversal and lead-lagMaster's4 min
Every stat-arb book is, underneath, a contrarian: it buys what fell and sells what rose, relative to something. In 1990 Andrew Lo and Craig MacKinlay asked what such a contrarian is really paid for.
The contrarian, in its purest form. Weight each asset against its relative move last period. Its profit is the sum of weights times this period's returns. Bruce Lehmann found in 1990 that weekly losers beat weekly winners among stocks. The natural reading is overreaction: prices overshoot and come back. Lo and MacKinlay showed it is not the only reading.
Their decomposition is exact. The contrarian's expected profit is three terms in the autocovariance matrix of returns. The first is own reversal: assets that reverse their own moves. Overreaction is one possible explanation; microstructure and other dynamics can also generate it. The second is cross-autocovariance: one asset's move predicting another's next move. That cross term can pay even when own lag covariances vanish; slow news diffusion is one possible explanation, not identified by covariance alone. The third is a cost: the spread of mean returns.
Lead-lag, measured on Kenneth French's size deciles, in consecutive blocks of five observations since 1963, rather than calendar weeks. The previous five-observation block return of the largest stocks predicts the next block return of the smallest, a correlation of +0.15. The reverse is -0.06. Small caps also predict themselves, +0.21: this is positive sample own autocorrelation. It describes continuation but does not alone identify adjustment speed or cause.
The finite-sample comparison needs care. The displayed own and cross terms use lagged covariance products centered on the full-sample mean. The realized contrarian profit averages uncentered lagged return products. Their normalization and edge observations differ. The population expectation identity is exact under stationary moments, but these sample implementations need not agree to the last digit. The difference is a boundary mean term; the notes derive it. Similar-looking rounded numbers do not establish an exact software identity or a causal explanation.
The terms also change across eras. The pre-1991 sample and later sample show different covariance patterns, using five-observation return blocks whose first date assigns the era. Faster trading, liquidity, measurement and changing markets are possible explanations, but this before-and-after comparison cannot identify why the terms changed. A covariance decomposition describes second moments; it does not prove news diffusion, irrational overreaction, or that arbitrageurs removed a particular opportunity.
Two warnings about measured reversal. Richard Roll's model: trades print at the bid or at the ask, at random, around an efficient price. So recorded price changes are negatively autocorrelated even when the efficient price is a random walk. That reversal cannot be traded: it is the bid-ask spread itself. Bruce Lehmann's weekly contrarian profits on stocks were partly this. And stocks that trade late carry yesterday's news into today's closing prices, which makes lead-lag appear even where no one could act on it. Portfolios and residuals reduce both effects; they do not remove them.
Why the unit and the horizon matter. Over days to a month, single stocks reverse: Narasimhan Jegadeesh and Bruce Lehmann. Over three to twelve months, industries continue: Tobias Moskowitz and Mark Grinblatt found industry momentum, and that it explains much of stock momentum. That is why the industry contrarian of Chapter nine loses. And over three to five years both reverse again, Werner De Bondt and Richard Thaler's long-horizon reversal. Reversion is a statement about a unit and a horizon, never about prices in general.
Read the decomposition as an accounting of population moments. Own reversal and cross-autocovariance can both contribute, with different signs across assets and horizons. Their labels do not identify mechanisms. Removing fitted factors changes these moments but need not isolate pure own reversal; residual construction and omitted common dynamics still matter. Cross-market lead-lag is a candidate hypothesis where prices incorporate information at different speeds. Implementability requires observation timing, executable quotes and net costs, not correlation alone.
Pause and predict. Every asset on its own follows a random walk, but large caps' returns predict small caps' returns a week later. Does the contrarian make money or lose it?
8Learning the residualPhD4 min
The s-score reads one number from a residual's path: how far it is from its mean. A network could read the whole shape. Does it find more?
The claim. In 2021 Jorge Guijarro-Ordonez, Markus Pelger and Greg Zanotti took the Avellaneda-Lee pipeline and learned every step. A convolutional transformer reads each residual's last thirty days. And the allocation is trained to maximise the portfolio's Sharpe ratio directly. They report a high out-of-sample Sharpe ratio on large American stocks, still profitable after trading costs, from patterns of trend and reversion that an Ornstein-Uhlenbeck model cannot express.
The machine-learning literature on stat arb, briefly. Christopher Krauss, Xuan Anh Do and Nicolas Huck trained deep networks, boosted trees and random forests on the lagged returns of S and P five hundred stocks; their ensemble earned, as reported, over forty-five basis points a day before costs, much less after them, and less in the later years. The deep stat-arb paper learned the whole pipeline and reported robustness to costs. The common thread: thousands of single stocks, signals read from many days at once, and decay over time.
The stored network uses a chronological split within the research data. Each input is a thirty-component cumulative residual path relative to its endpoint, scaled by volatility. Its last component is always zero. The target is tomorrow's synthetic residual return. Training ends in 2012, validation is 2013 through 2016, and nominal test dates are 2017 through 2020. Complete-history universe selection and reuse of the research period limit independence. This is a smaller MLP experiment, not a replication of the published transformer, and these dates must not be called untouched discovery evidence.
The network is Part twenty-seven's small ensemble: thirty inputs, two hidden layers of thirty-two and sixteen units, three random seeds averaged, a light penalty, and early stopping. It is much smaller than a transformer, but it can represent nonlinear patterns in the path that the s-score ignores: a residual that has just turned, one that is still falling, one that overshot.
On the test years. The correlation between the network's forecast and tomorrow's residual is 0.0034: almost nothing. Its forecast is nearly unrelated to the s-score's raw material, how far the residual has moved over the month: a correlation of 0.06. And yesterday's residual move alone predicts nothing. With so little to learn from day to day, a flexible model mostly learns noise.
The test. On the same days, the plain s-score rule earns a gross Sharpe ratio of 1.26. The network earns 0.24 before costs. And after costs, -7.2: because it rebalances to its forecast every day, it trades 95 percent of its book daily, and pays for it.
Why it fails here, and why that is not a verdict on the paper. The universe is wrong: forty-nine industries have little residual predictability; the paper used hundreds of single stocks. The objective is wrong: a forecast rebalanced daily ignores costs, while the paper trains the allocation on the Sharpe ratio after costs, so its network learns to trade less. And a near-zero daily signal needs years of data to tell from noise, and every architecture tried is another trial.
The lessons concern model comparison and accounting. Flexible predictors require signal, enough data, and a loss consistent with the trading objective. A mean-reversion prior can constrain a model, but does not establish that fitted residual profits are real cash flows. Here forecasts are demeaned and normalized to unit gross before daily rebalancing, with a fixed two-leg cost proxy. Different turnover, financing and hedge reconstruction affect comparability. The chronological split is informative about this stored experiment; it does not independently validate the paper or establish a live allocation.
Pause and predict. A forecast has a daily information coefficient of point zero one across forty-nine assets. Roughly how many years of daily data are needed before its IC is two standard errors from zero?
9Liquidity, crowding and decayIndustry4 min
A reversal strategy buys from people who are selling in a hurry. Its return is the price of that hurry. That idea explains when it pays, when it crashes, and why it fades.
The theory. Sanford Grossman and Merton Miller: an investor who must trade now accepts a worse price, and whoever takes the other side is paid when the price recovers. Reversal is the price of immediacy. In a crisis, the liquidity providers' own capital is scarce. So the expected return of reversal should rise with market stress. Stefan Nagel found exactly that for American stocks: reversal returns rise with the VIX, and peaked in 2008.
A descriptive industry regression. Monthly outcomes add the daily gross-normalized contrarian P and L arithmetically; they are not compounded portfolio wealth. The predictor is the previous month's last VIX close. The stored slope is -0.39 basis points per VIX point, with t-statistic -0.26. That standard error assumes independent homoskedastic regression errors; it is not HAC robust. Its sample Sharpe is -0.66. These results neither replicate Nagel's stock design nor prove that industry returns contain no liquidity effect.
The calmest and most stressed research-sample VIX fifths have mean proxy outcomes -0.36 and -0.31 percent. These groups are defined from this sample's VIX distribution; they are descriptive associations. The scatter clips extreme observations for display. Neither the regression nor these groups identify the causal price of immediacy. Universe, timing, dependence and the return convention all affect the comparison with the stock literature.
Why a reversal can widen before it closes. Andrei Shleifer and Robert Vishny: arbitrageurs manage other people's money, and investors judge them by recent returns. A spread that widens costs the arbitrageur capital, investors withdraw, and the forced selling widens it further. So the best trades arrive exactly when the arbitrageur has the least capital to take them. The limits of arbitrage are limits on capital, not on ideas.
Who demands immediacy, concretely? Index funds when a stock joins an index: they must buy on one day, and Andrei Shleifer found that inclusion raised prices. Mutual funds with outflows: Joshua Coval and Erik Stafford showed their forced sales push prices below value, and the prices recover over the following months. And funds meeting margin calls or rebalancing on a calendar. Each is a seller who cares about the date rather than the price, and the stat-arb trader is paid for taking the other side.
Crowding is the other face of liquidity. August 2007, from Part thirty-one: market-neutral stat-arb books lost heavily in three days as a crowd unwound the same positions, then rebounded. Stat arb is especially prone to crowds, because the same data and the same factor models lead different firms to the same residual trades. And the rebound is the theory again: forced selling is immediacy demanded at any price, and the cited contrarian series rebounded sharply. A rebound in that research series does not prove that every fund could hold its positions, avoid margin calls or earn the same return.
And decay. Avellaneda and Lee found that their residual strategy's returns on American stocks fell after the early 2000s, as the distance rule had after the 1980s. As more firms trade a reversal, it is harvested faster, and the edge moves to shorter horizons, then into market making, Part thirty-eight's subject. What remains is a few basis points a trade, and the firm with the cheapest execution keeps it.
Pause and predict. A reversal strategy earns two basis points a day before costs, and trades forty percent of its book daily at five basis points a side. What does it earn after costs?
10An evaluation protocolIndustry1 min
Even an ideal clean return series can be imprecise. Under the simple independent-return approximation, the annual Sharpe standard error is roughly one over the square root of years. A Sharpe of point three is two such standard errors from zero only after about forty-four point four years. This is a planning calculation, not a universal sample-size guarantee. Serial correlation, skew, changing volatility and strategy selection alter it. The appropriate conclusion here is a documented research proxy and a clear evaluation specification, with no sealed-year verdict.
11Rule 33: the stat-arb bookIndustry5 min
The House's thirty-third rule: what a reversion strategy must show before the House trades it. Reversion is easy to find before costs and hard to keep after them, so the rule is mostly about costs, and about the trials it took to find the rule.
The research sheet gathers verified ordinary outputs. The distance proxy has a negative sample mean. Annual cointegration pass rates exceed the simulated control rate, with limited persistence. The adaptive Kalman innovation looks stationary, which is not a fixed cointegrating portfolio. Lo and MacKinlay's covariance terms describe own and cross dependence. Residual and network results use synthetic residual P and L with incomplete cost accounting. The VIX regression is a descriptive industry comparison with conventional errors. No row on this sheet establishes an executable portfolio or a sealed-year verdict.
The OU fit regresses the next observation on the previous one with an intercept. A slope outside zero to one is incompatible with this stationary mean-reverting OU mapping. For a valid slope and positive regular sampling interval, speed is minus log slope divided by the interval; the fitted mean divides the intercept by one minus slope. Innovation variation determines equilibrium width. This helper first removes nonfinite observations, compressing any time gaps, and estimates innovation deviation with two regression degrees of freedom. Fitted speed and width remain uncertain.
The band-rate code divides the fixed reward m minus c by mean waiting plus mean holding time. The first-passage formulas assume a known OU process with positive kappa and sigma, continuous monitoring, unit exposure and a fixed round-trip cost in spread units. Simpson quadrature evaluates the integrals. The optimizer searches a bounded grid and refines once; it is a numerical approximation within this policy family. It does not solve financing, risk budgets, a changing factor model, or general optimal stopping.
The decomposition code returns three moment terms and a realized sample profit. In the population, expected contrarian profit is a weighted own covariance term plus off-diagonal covariance, minus the cross-sectional variance of means. That last term is subtracted. In this finite implementation the full-sample centering mean and lagged endpoint means differ, leaving a boundary correction. The notes derive it explicitly; equality to the last digit is not asserted. A covariance identity also does not identify why prices moved.
And the s-score itself. At every day, fit the Ornstein-Uhlenbeck process to the last sixty values of the cumulative residual; if the fit is mean-reverting, the score is today's distance from the fitted mean in equilibrium deviations, and the fitted speed is kept beside it. A residual that does not revert gets no score at all, and is not traded.
The tools this part adds. Spreads; pairs; the decomposition; the theorem; and its check by simulation. And the thirty-third rule. A reversion strategy enters the House only with its profit shown after the costs of every leg, hedges included; its bands derived from those costs, not from habit; every pair, window and band it was chosen from counted as a trial; its spread tested out of sample on profit, not on stationarity; and its crowding risk stated: who else holds the same residuals.
Capacity and leverage remain design constraints, not outputs certified by this research proxy. Trading larger quantities can raise impact and erode a small edge; the impact model needs data and units appropriate to actual instruments. Leverage increases both opportunities and margin risk, and is never compelled merely by low reported volatility. This lesson establishes no live capital allocation. A trading decision would require audited holdings, financing, liquidity and an independent evaluation under a fixed risk mandate.
A proposed monitoring design must also be explicit. Measure actual turnover, execution cost, financing and factor exposures, allowing for model error rather than expecting exact neutrality. Track residual dispersion and fit failures as diagnostics; a lower OU pass rate does not uniquely identify factor-model failure. A loss limit, liquidity reserve or size cut is a prospective policy choice requiring calibration and funding analysis. The illustrative three-daily-volatility weekly trigger is not computed or validated by the stored strategy and is not adopted here.
The rule against three cases. A pairs fund showing a Sharpe ratio of three: ask whether that is before costs, how many pairs were screened, and whether the hedge ratio was fitted on the same days. A basket with a half-life of one day: ask whether its spread is a filter's forecast error. A residual book that lost in August 2007: ask who else held the same residuals, and whether the fund could have held on for a week.
For the researcher: the optimal band for a mean-reverting spreadPhD9 min
For the researcher. Every stat-arb book chooses bands, usually by habit: one and a quarter deviations, or two. This chapter derives the profit rate of a band rule exactly, and the band that maximises it.
The setup fixes a known Ornstein-Uhlenbeck process with positive kappa and sigma, centered at zero. Parameters are constant and the path is monitored continuously. While flat, wait until either band at distance m is reached; then hold one unit against the displacement and exit at zero. A completed cycle earns m minus a fixed round-trip cost c in spread units. We maximize long-run expected profit per time within this family. This is not a Sharpe objective, a return on committed capital, or a solution with financing, stops, breaks or a risk budget.
Lemma one, the renewal-reward theorem. Each cycle has two legs: waiting at the mean until the spread reaches the band, then holding until it returns. By the strong Markov property every cycle starts afresh at the mean, so the cycles are independent and identical. Then the long-run profit per unit time is the expected reward per cycle over the expected length of a cycle. So everything reduces to two expected first-passage times.
Lemma two, the first-passage times. Let f of x be the expected time to reach the boundary from x. By Dynkin's formula, the OU generator applied to f is minus one, with f zero on the boundary: Part eight's Feynman-Kac, with a running cost of one per unit time. Multiply by the integrating factor, and the left side becomes an exact derivative. The equation integrates twice.
The two solutions. From minus m to the mean, the condition far away is that the slope stays bounded, which starts the inner integral at minus infinity. From the mean to either band, symmetry makes the slope zero at the mean, which starts it at zero. The inner integrals are error functions, and the outer ones a one-dimensional quadrature.
The theorem is about this fixed policy family. The two expected passage times sum, after scaling, to the square root of half pi times the integral from zero to u of exp z squared over two, divided by kappa. Here u is m over equilibrium width and d is c over that width. Differentiating the reward rate gives the equation I of u equals u minus d times exp u squared over two. For positive cost it has exactly one solution above d: the derivative changes sign there. At zero cost the best rate is only a supremum as the positive band shrinks to zero. Speed scales the rate when width and dimensionless cost are held fixed.
The two times. Holding, from the band back to the mean, grows slowly with the band: the further out, the stronger the pull back. Waiting, from the mean to the band, starts at zero and grows explosively, because reaching a distant band against the pull is rare. Wide bands are paid for in waiting.
The profit rate, for three costs. Each curve rises from zero at the cost, peaks, and falls as waiting takes over. The dots are the optima: higher costs push the best band outward. At a cost of three tenths of a deviation, the best band is 1.03 deviations: close to Avellaneda and Lee's one and a quarter, which corresponds to a cost of roughly half a deviation.
The dimensionless optimum is a function of cost in equilibrium-width units. The displayed points are bounded numerical searches, not symbolic exact optimizers. The zero-cost grid point has a positive minimum band, whereas the mathematical optimum is a limiting supremum at zero. For small positive cost the true band grows asymptotically as the cube root of three times that cost. This shares an exponent with Part thirty-one's holdings band under quadratic risk, but the objective and derivation differ. A fixed one-and-a-quarter threshold corresponds to just one dimensionless cost within this particular OU model.
A corollary that surprises people. For a tiny band, the holding time is linear in the band, and the waiting time quadratic. So with no costs the profit rate tends to a finite limit, sigma times the root of kappa over pi, not to infinity: trading infinitely often does not earn infinitely fast. In the curve's units, the root of two over pi, 0.798. Costs then decide how far from that limit the best band must retreat.
The cube root has a precise small-cost asymptotic derivation. Expand the two passage times for a small band, measured in equilibrium deviations. The time back to the mean has a negative quadratic term. The time out to the band has exactly the opposite one. In the length of a cycle, they cancel. So the first correction to the linear term is cubic, and setting the derivative of the profit rate to zero gives: to leading order the band cubed is three times the cost. The small-cost law. The best band is the cube root of three times the cost, in equilibrium deviations, with no free constant and no dependence on the speed. And the fraction of the frictionless profit lost to costs grows like the cost to the power two thirds.
Checked against the numerical optimum. At a cost of a hundredth of a deviation the law is within 0.7 percent of the numerical band; at a cost of 0.3 deviations, already a large cost, it is within 7 percent. It is the same cube root as Part thirty-one's no-trade band, for a different reason: there the cost was traded against quadratic risk, here against the time a cycle takes.
A worked example. A residual two percent wide, with an eight-day half-life, and a round trip costing twenty basis points on both legs: a cost of a tenth of a deviation. The best band is 1.38 percent, 0.69 deviations, and the small-cost law gives 0.67. A cycle takes about 11 days, and the rule earns 10.9 basis points a day for each unit held. Avellaneda and Lee's habit of one and a quarter deviations would be nearly twice as wide.
The stored simulation is a timing illustration on a grid, at half, once, and one point six times each numerical optimum. Exact OU transitions connect grid dates, but crossings between dates are missed. Every completed trade is credited at the band and mean, not the actual overshoot execution prices. Thus it does not simulate an executable grid-trading cash account. The final column combines a fine step of point zero zero zero five and a coarse step four times larger as twice fine minus coarse, assuming a leading square-root-step bias. This extrapolation is heuristic. Equal seeds do not create coupled Brownian paths, and this table has no Monte Carlo error bars or guaranteed ranking.
The stored industry comparison is a research illustration of two proxy policies. Fixed thresholds have synthetic gross Sharpe 0.88, and charged proxy Sharpe -0.39. The mathematical-band configuration has 1.13 and 0.21, with discrete-signal turnover 11 percent versus 21. Bands are interpolated from thirty-one cost points with endpoint clipping. Known-parameter OU theory does not validate fitted bridges or omitted cash flows. All these comparisons reuse research data and incomplete trading-cost accounting; Chapter ten specifies what a fuller evaluation would require.
Where the theorem sits. William Bertram used the same renewal argument for an entry level and an exit level, with the passage times from the process's known series. Tim Leung and Xin Li treat entry and exit as optimal stopping problems with discounting and a stop-loss, whose answer is a pair of free boundaries rather than a fixed cycle. And Part thirty-one's no-trade band, a cost traded against quadratic risk, grows with the same cube root: two different problems, one exponent.
Three extensions require additional modeling. Uncertain parameters and learning while trading change the known-parameter optimum; this chapter supplies no general solution. Structural breaks and a stop-loss change the cycle and objective. Existing optimal-stopping literature treats specified versions, but does not make our fixed-band formula universal. Correlated spreads, financing, a portfolio risk budget and nonlinear impact create a joint control problem. These are directions for further work, not claims that no related solution exists anywhere in the literature.
Pause and predict. Two spreads have the same equilibrium deviation and the same cost, but one reverts twice as fast. How do their optimal bands and their profit rates compare?
Recap, desk questions, problemsAll tracks5 min
Part thirty-three in fourteen lines. Statistical arbitrage grew from quantitative trading desks into a family of reversion strategies. The industry distance proxy has a negative sample mean under its implementation. Cointegration screens have limited persistence and noisy null calibration. An OU regression supplies a conditional model of speed and width, with uncertain estimates. Rolling fitted residuals can look mean reverting partly because they sum to zero. A Kalman innovation is a forecast error, not a fixed cointegrating wealth portfolio. Contrarian expectations split into own covariance, cross covariance and a mean-dispersion cost.
The small network uses a chronological split inside reused research data and a synthetic residual target. The VIX comparison is descriptive with conventional regression errors. All residual configurations need a fuller holdings and cost audit before net investment claims. No sealed-year strategy result is used. Rule thirty-three asks for every leg's costs, honest research selection, information timing and crowding risk. Within a known OU model, first-passage times give the symmetric policy's profit rate and a unique positive-cost optimum. A cube-root law approximates that optimum for small dimensionless costs.
Six desk questions. Two prices are cointegrated: what do you trade, and what can go wrong? The spread, and the tie, the estimate and the screen. What is an s-score? A residual's distance from its fitted mean, in equilibrium deviations. And is a Kalman spread with a one-day half-life a pair? Not on that evidence.
Where does a contrarian's profit come from? Own reversal and lead-lag. Why did the residual book lose with the standard bands? Every trade is two trades. And how should the band depend on costs? Through one curve, with a cube root near zero. Full solutions are in the notes.
The pause questions, answered under explicit assumptions. Cheap execution can make a fixed edge affordable, while competition may reduce the edge. A twenty-day half-life and six-month holding cap do not determine an optimal entry band. The cost, objective, width and finite-horizon policy are also needed. Under a calibrated five-percent null test, two thousand unrelated pairs give one hundred expected passes. If next year's null outcomes are also independent over time, five of those pass again in expectation. Cross-pair independence is not needed for the first expectation, but temporal dependence changes the second.
A slope of point nine five gives a half-life of 13.5 daily intervals. The first-order Kendall slope-bias approximation maps to about 6 days, but a nonlinear function of an expected slope is not an expected fitted half-life. In the specified constant-turnover cost illustration, gross mean is three point two percent, costs five point zero four percent, and net -1.84 percent annually. The net Sharpe approximation keeps volatility fixed. Forecast-error autocorrelation may indicate misspecification; it does not establish cointegration.
With zero means, zero own lag covariance and a positive off-diagonal covariance, the contrarian has positive expected cross-term profit. Under independent pooled observations, IC point zero one across forty-nine assets needs about 3.24 years for a two-standard-error separation. Correlated assets and dates reduce effective sample size. Under the basic iid Sharpe approximation, point three needs 44.4 years. For turnover defined as summed absolute traded weight, forty percent times five basis points costs two basis points daily; two gross leaves zero. At fixed equilibrium width and cost, doubling OU speed leaves the optimal band fixed and doubles this model's profit rate.
And twelve problems: a spread's speed; false passes in a screen; a band from the curve; a residual book after costs; the contrarian's cross term; a filter's errors; a reversal after costs; how long an IC and a Sharpe ratio take to prove; and the small-cost law. Then two qualifying-exam problems: the theorem from Dynkin's formula, and the frictionless limit with the cube-root law. Solutions, in English and Chinese, are in the notes.
Where this comes back. Part thirty-four goes inside the firms that run stat-arb books. Part thirty-seven measures what a trade really costs, the number this whole part depended on. Part thirty-eight is market making, reversion at the shortest horizon. And the finale deflates every row.
The reading spans cointegration, reversal, liquidity and modern prediction. Reported stock-paper results and firm histories are attributed to their sources. The charts use the nine verified ordinary computations, while chosen mathematical examples and grid simulations are labeled. Numerical formulas, descriptive data comparisons and independently evaluated trading performance are different kinds of evidence. This part makes no new sealed-year performance claim.
The House now has research diagnostics and a mathematical band theorem. The stored residual proxy does not establish a live, market-neutral, profitable book: actual holdings, cash flows, costs and independent evaluation remain necessary. Reproducibility makes the calculation inspectable; interpretation determines what it proves. Next, Part thirty-four: inside a quant firm. How the firms that run these books organize research, risk, execution and incentives, and how capacity affects their decisions.
Where it goes next. The costs that set the band are measured in Parts 36-37; who provides the liquidity a stat-arb book consumes is Part 38.
Key results
The part's results in one place, for revision.
Try it
Lab 33 · The optimal band for a mean-reverting spread
Simulate an Ornstein-Uhlenbeck spread, recover its speed and equilibrium width by regression, and find the entry band that maximizes profit per unit time for a given round-trip cost, by formula and by simulation. Then shrink the cost and watch the band shrink like its cube root.
python -m videos.quant.labs 33
needs numpy, scipy, matplotlib, numba · download lab33.py ·
source on GitHubTrue kappa, equilibrium sd 12.0, 0.0714 half-life 15 days
Fitted from 20 years of days 11.6, 0.0724
Optimal band at cost 0.2 sd enter at 0.89 sd; profit rate 0.461 a year per unit
Band against cost: fitted exponent 0.35 (small-cost law: 1/3)
Halving the cost does not halve the band: m*/s_eq ~ (3c/s_eq)^(1/3).
The code (55 lines; it asserts its own result)
"""Lab 33: trade a mean-reverting spread: fit it, choose the band, and check the cube-root law."""
import numpy as np
from videos.quant import labs
from explainer.quant.house import sim, statarb
TITLE = "The optimal band for a mean-reverting spread"
GOAL = ("Simulate an Ornstein-Uhlenbeck spread, recover its speed and equilibrium width by regression, and find "
"the entry band that maximizes profit per unit time for a given round-trip cost, by formula and by "
"simulation. Then shrink the cost and watch the band shrink like its cube root.")
TASKS = [
"Estimate kappa from only 250 observations, 200 times. How biased is it, and what does that do to the band?",
"Let the spread's mean drift slowly (a random walk in theta). What does the fixed band earn now?",
"Trade at grid prices (book_at_bands=False) with dt = 1/252. How much does discrete monitoring add?",
]
def run(seed=0):
kappa, sigma = 12.0, 0.35 # a half-life of about three weeks
s_eq = sigma / np.sqrt(2 * kappa)
x = sim.ou_exact(0.0, kappa, 0.0, sigma, 20.0, 5040, 1, seed=seed)[0]
fit = statarb.ou_fit(x, dt=20.0 / 5040)
cost = 0.2 * s_eq # a round trip costs a fifth of the spread's equilibrium sd
m_star, rate_star = statarb.optimal_band(kappa, sigma, cost)
bands = np.linspace(0.3, 2.6, 10) * s_eq
theory = np.array([statarb.band_rate(m, kappa, sigma, cost) for m in bands])
simulated = np.array([statarb.simulate_band(m, kappa, sigma, cost, T=150.0, dt=1e-4, seed=seed)["rate"] for m in bands])
lab = labs.Lab()
lab.row("True kappa, equilibrium sd", f"{kappa:.1f}, {s_eq:.4f} half-life {252 * np.log(2) / kappa:.0f} days")
lab.row("Fitted from 20 years of days", f"{fit['kappa']:.1f}, {fit['s_eq']:.4f}")
lab.row("Optimal band at cost 0.2 sd", f"enter at {m_star / s_eq:.2f} sd; profit rate {rate_star:.3f} a year per unit")
costs = np.array([0.4, 0.2, 0.1, 0.05, 0.025, 0.0125]) * s_eq
m_c = np.array([statarb.optimal_band(kappa, sigma, c)[0] for c in costs])
slope = np.polyfit(np.log(costs[2:]), np.log(m_c[2:]), 1)[0]
lab.row("Band against cost: fitted exponent", f"{slope:.2f} (small-cost law: 1/3)")
lab.note = "Halving the cost does not halve the band: m*/s_eq ~ (3c/s_eq)^(1/3)."
assert abs(fit["kappa"] - kappa) < 4 and abs(fit["s_eq"] - s_eq) < 0.1 * s_eq
assert np.abs(simulated - theory).max() < 0.08 * rate_star + 0.02 and 0.27 < slope < 0.42
fig, ax = labs.figure(2, size=(11, 4.2))
t = np.arange(600) / 252
ax[0].plot(t, x[:600] / s_eq, color=labs.SPOT, lw=0.9)
for y in (m_star / s_eq, -m_star / s_eq):
ax[0].axhline(y, color=labs.P, ls="--", lw=1)
ax[0].axhline(0, color=labs.MUTED, lw=0.8)
ax[0].set(title="The spread and the optimal band", xlabel="years", ylabel="spread, in equilibrium sd")
ax[1].plot(bands / s_eq, theory, color=labs.P, label="renewal-reward formula")
ax[1].plot(bands / s_eq, simulated, "o", color=labs.SPOT, ms=4, label="simulated, 150 years")
ax[1].axvline(m_star / s_eq, color=labs.P, ls=":", lw=1)
ax[1].axhline(0, color=labs.MUTED, lw=0.8)
ax[1].set(title="Profit per year against the entry band", xlabel="entry band, in equilibrium sd")
ax[1].legend(fontsize=8)
lab.fig = fig
return lab
Now change it
- Estimate kappa from only 250 observations, 200 times. How biased is it, and what does that do to the band?
- Let the spread's mean drift slowly (a random walk in theta). What does the fixed band earn now?
- Trade at grid prices (book_at_bands=False) with dt = 1/252. How much does discrete monitoring add?
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, answered
- What is traded in a cointegrated pair?
Answer
A fixed linear combination such as y − βx is a statistical spread. A trade requires actual shares, normalization and cash flows. The relation can break; β is estimated; screening creates selection; funding and shorting can bind. - What is an s-score?
Answer
(X − θ̂)/ŝ for a specified fitted OU spread, with a valid regular-interval fit. It measures distance in fitted equilibrium-width units, not the probability of a profitable trade. Historical thresholds are policy choices. - Does a short-lived Kalman innovation prove cointegration?
Answer
No. Its adaptation can produce stationary-looking forecast errors without a stable fixed linear combination or profitable rebalanced holdings. Check the information set and the return objective. - Where can contrarian expected profit come from?
Answer
Weighted own lag covariance, off-diagonal lag covariance and a negative mean-dispersion term. These are moment contributions, not identified causal mechanisms. - Why do residual results need a cost audit?
Answer
The stored algorithm charges a proxy, omits some rescaling and exits, and does not establish full hedge and cash holdings. Actual trades, financing and gross capital must be reconstructed before an investment claim. - How does the OU band depend on cost?
Answer
Under the stated fixed policy and known-parameter assumptions, u* depends on d alone. For d ↓ 0, u* ∼ (3d)^(1/3). Speed comparisons hold equilibrium width fixed; this is conditional scaling.
Problems, with worked solutions
Twelve exercises with complete solutions
Basic 1 — Speed from a daily slope
A spread's daily AR(1) slope is 0.9: its speed \(\kappa\) and half-life.
Solution
Given b = 0.9 and Δt = one day, b = exp(−κΔt) implies κ = −ln(0.9) = 0.1053605 per day. Since the conditional mean displacement decays as exp(−κt), halving requires exp(−κh) = 1/2. Thus h = ln 2/κ = 6.5788 trading days. This is decay of the conditional mean, not a guaranteed hitting time. The mapping assumes a stationary OU sampled regularly.
Basic 2 — False passes and a family-wise bound
All 1{,}176 pairs of 49 industries tested at 5%: the expected false passes, and the Bonferroni level.
Solution
Forty-nine assets give M = 49×48/2 = 1,176 unordered pairs. If every null is true and each test has calibrated size α = 0.05, linearity of expectation gives E[V] = ΣPr(reject null j) = 1,176×0.05 = 58.8 false passes; cross-pair independence is unnecessary. To bound the probability of any false pass by 0.05, the union bound permits marginal level α/M = 0.000042517 = 4.2517×10⁻⁵. This is Bonferroni, valid under dependence for valid individual tests. The fixed −3.34 screen is not automatically calibrated at that adjusted level; it needs appropriate critical values or valid p-values.
Basic 3 — A cost-scaled band
A spread with \(s_{\text{eq}} = 2\%\) and round-trip cost 0.6%: \(c/s_{\text{eq}}\), and the best band from the curve.
Solution
Choose equilibrium width s = 2% and fixed round-trip spread cost c = 0.6%, so d = c/s = 0.3. The stored numerical policy calculation gives u ≈ 1.032879, hence m = su ≈ 0.02065758 = 2.065758%. This number is a bounded quadrature/grid approximation. The leading small-cost law gives u ≈ (0.9)^(1/3) = 0.965489, or m ≈ 1.930979%. Cost 0.3 is not infinitesimal, so the asymptotic error is unsurprising. The units are spread displacement, not gross portfolio capital.
Basic 4 — A specified residual cost illustration
A residual book: gross Sharpe 0.8 at 4% volatility, 20% daily turnover, 5 bp a side on both legs. Net return.
Solution
Choose annual gross Sharpe 0.8, annual volatility 4%, daily turnover τ = 0.2 per leg, two legs and one-way cost k = 5 bp per traded dollar. Gross mean is 0.8×0.04 = 0.032 = 3.2% annually. Under constant turnover and 252 trading days, annual cost is 2kτ×252 = 2×0.0005×0.2×252 = 0.0504 = 5.04%. Net mean is −0.0184 = −1.84%. If costs are deterministic and volatility unchanged, net Sharpe is −0.0184/0.04 = −0.46. This chosen arithmetic does not fix the stored algorithm's missing holdings and turnover.
Basic 5 — One cross-covariance
Two zero-mean assets with \(\operatorname{Cov}(r_{2,t}, r_{1,t-1}) = \gamma\) and no other autocovariance: the contrarian's expected profit.
Solution
For N = 2, choose zero means and zero own lag covariances; let the only nonzero element of Γ = Cov(r_t,r_{t−1}) be Γ₂₁ = γ. The contrarian weights are w_i = −(r_{i,t−1} − r̄_{t−1})/2. Explicitly, w₂ = (r₁,t−1 − r₂,t−1)/4 and w₁ = −w₂. Taking E[w₁r₁,t + w₂r₂,t] leaves γ/4. Equivalently the off-diagonal term is γ/N², own and mean-dispersion terms vanish. Profit is positive only if γ > 0, before implementation costs; no own-price reversal is required.
Basic 6 — Correlated innovations
A filter's one-step forecast errors have AR(1) slope 0.3. What does that say about cointegration?
Solution
An innovation with AR(1) slope 0.3 retains positive serial dependence under that descriptive fit. It may indicate misspecification or unmodeled dynamics, but does not uniquely identify a slow filter. Cointegration instead requires integrated price series with a stable stationary fixed combination under the relevant definition. Adaptive residual stationarity, or its failure, is insufficient. Specify a fixed spread, estimate with prior information, check stability, and evaluate actual subsequent holdings after costs. The innovation statistic alone supplies no verdict.
Advanced 7 — Turnover units
A reversal earns 2 bp a day gross and trades 40% of its book daily at 5 bp a side. Net.
Solution
Choose gross mean 2 bp/day and define τ = Σ|Δw_j| = 0.4 as total one-way traded gross weight. With k = 5 bp per dollar, cost is kτ = 2 bp/day and net mean is 0 bp/day. If “turnover” instead means half that sum, use 2kτ, producing 4 bp cost and −2 bp net. If τ is specified separately for two legs, add both legs. No extra round-trip factor is justified without a definition. The stated answer zero uses the first convention and deterministic linear costs; financing and impact are excluded.
Advanced 8 — IC sample size
A daily IC of 0.01 across 49 assets: the iid-approximation years for two standard errors.
Solution
For a small correlation from n independent, comparable forecast/target pairs, use se(IC) ≈ 1/√n. To separate IC = 0.01 from zero by two standard errors requires 0.01√n ≥ 2, so n ≥ 40,000. With 49 independent pairs each day, T ≥ 40,000/49 = 816.3265 days; 252 days/year gives 3.2394 years. Cross-sectional correlation, overlapping targets, serial dependence and selection reduce effective information, so this pooled iid calculation is a conditional planning illustration. It is neither guaranteed power nor proof after 3.24 years.
Advanced 9 — Sharpe precision
A true Sharpe ratio of 0.3: the iid-approximation years for two standard errors.
Solution
Under the basic iid-return, low-Sharpe approximation, annual Sharpe standard error is about 1/√Y for Y years. For true annual Sharpe 0.3, set 0.3√Y = 2, giving Y = (2/0.3)² = 44.4444 years. This equates expected signal to two approximate standard errors; it is not a 95% power calculation. Higher moments, serial dependence, varying risk, estimator details and research selection alter it. Five years would give approximate error 0.4472, larger than 0.3, even before those complications.
Advanced 10 — Small-cost arithmetic
Use the small-cost law to find the band for \(c/s_{\text{eq}} = 0.01\) and the share of the frictionless rate kept.
Solution
Choose d = 0.01. The leading asymptotic band is u = (3d)^(1/3) = 0.3107233. The leading retained frictionless rate is 1 − (3d)^(2/3)/2 = 0.9517255, about 95.17%. The unchanged bounded optimizer gives u ≈ 0.3129916 and rate 0.7598024 in κ = s = 1 units. Dividing by R(0⁺) = √(2/π) = 0.7978846 gives approximately 0.95227. This is a numerical comparison against an asymptotic prediction, not an exact finite-cost equality or evidence from market data.
Qualifying 11 — Passage times, renewal and a unique optimum
(qual) For \(dX = -\kappa X\,dt + \sigma dW\), derive \(\mathbb E_{-m}[T_0]\) and \(\mathbb E_0[\tau_m]\) from Dynkin's formula, prove the renewal-reward rate \(R(m) = (m - c)/(\mathbb E_0[\tau_m] + \mathbb E_{-m}[T_0])\), and show by scaling that \(m^*/s_{\text{eq}}\) depends on \(c/s_{\text{eq}}\) alone.
Solution
Assume the OU model and policy stated above, start flat at zero, and take m > 0. Each cycle first hits either ±m and then returns to zero. Strong Markov and symmetry make successive full-cycle durations identically distributed and independent; their expectations are finite for this positive recurrent OU process and finite m. A full cycle has fixed reward m − c. The renewal-reward theorem gives almost-sure long-run completed-cycle rate R = (m−c)/(E₀τ_m + E₋ₘT₀). Incomplete-cycle mark-to-market needs its own accounting if one defines a wealth process; this policy formula concerns the renewal reward.
For a hitting-time expectation f(x), Dynkin's equation is (σ²/2)f″ − κxf′ = −1 in the continuation region, with zero value at the target boundary. Multiplying by exp(−κx²/σ²) yields
[ (e^{-\kappa x^2/\sigma^2}f')'=-\frac{2}{\sigma^2}e^{-\kappa x^2/\sigma^2}. ]
For hitting zero from x < 0, exclude the explosive homogeneous solution at the natural left boundary (the bounded-slope solution suffices). Then f′(y) = −(2/σ²)exp(κy²/σ²)∫₋∞ʸ exp(−κz²/σ²)dz. Integrate from −m to 0, using f(0)=0, to obtain
[ E_{-m}T_0=\frac{2}{\sigma^2}\int_{-m}^0e^{\kappa y^2/\sigma^2}\int_{-\infty}^y e^{-\kappa z^2/\sigma^2}dz,dy. ]
For exit from (−m,m), the expectation is even, so f′(0)=0; integrating the same equation from 0 gives the inner lower limit 0. With f(m)=0,
[ E_0\tau_m=\frac{2}{\sigma^2}\int_0^m e^{\kappa y^2/\sigma^2}\int_0^y e^{-\kappa z^2/\sigma^2}dz,dy. ]
Set x = sz and τ = κt. The scaled SDE is dZ = −Z dτ + √2 dB, with generator ∂²_z − z∂_z (not ½∂²_z − z∂_z). Mean physical times scale by 1/κ. Reflecting the negative integral and adding it to the positive one cancels their variable inner pieces, leaving κ(E₀τ_m + E₋ₘT₀) = a∫₀ᵘ exp(z²/2)dz = aI(u). Thus R = (κs/a)(u−d)/I(u).
For u > d, differentiate: the sign of R′ is the sign of I(u) − (u−d)exp(u²/2). Define H(u)=u−exp(−u²/2)I(u). The first-order equation is H(u)=d. H(0)=0 and H′(u)=u exp(−u²/2)I(u)>0 for u>0; also H(u)→∞ because exp(−u²/2)I(u)∼1/u. There is exactly one root for d>0, above d since H(u)<u. The derivative is positive before it and negative after it, and the rate tends to zero as u→∞, establishing the unique global maximum in this policy family. Its dimensionless band depends on d alone.
Qualifying 12 — Frictionless limit and cube-root asymptotics
(qual) With \(c = 0\) show \(R(m) \to \sigma\sqrt{\kappa/\pi}\) as \(m \to 0\); then show the \(m^2\) terms of the two passage times cancel, and deduce \(m^*/s_{\text{eq}} \sim (3c/s_{\text{eq}})^{1/3}\) and \(R(m^*)/R(0^+) = 1 - \frac12(3c/s_{\text{eq}})^{2/3} + o(c^{2/3})\).
Solution
Expand in u=m/s, keeping κ times the expected times dimensionless. With a=√(π/2), the integrand exp(y²/2)∫₋∞ʸ exp(−z²/2)dz equals a+y+ay²/2+y³/3+ay⁴/8+… . Integrating over [−u,0] gives κE₋ₘT₀ = au − u²/2 + au³/6 − u⁴/12 + au⁵/40 + O(u⁶). The waiting integral gives κE₀τ_m = u²/2 + u⁴/12 + O(u⁶). Even terms cancel; their sum is aI(u)=a(u+u³/6+u⁵/40+…). With d=0, R=(κs/a)u/I(u)→κs/a=σ√(κ/π). Since I(u)>u for u>0, this value is strictly above every positive-band rate: it is a supremum, not an attained finite optimum.
For positive small d, expand the exact first-order relation d=H(u)=u−exp(−u²/2)I(u). Multiplying series gives exp(−u²/2)I(u)=u−u³/3+u⁵/15+O(u⁷). Hence d=u³/3−u⁵/15+O(u⁷), and the unique root satisfies u³=3d+O(d^(5/3)), so u∼(3d)^(1/3).
The rate divided by its frictionless limit is (u−d)/I(u)=(1−d/u)/(1+u²/6+O(u⁴)). At the optimum d/u=u²/3+O(u⁴), yielding 1−u²/2+O(u⁴)=1−½(3d)^(2/3)+o(d^(2/3)). The exponent resembles a quadratic-risk holdings band, but here it comes from the OU cycle-time expansion and fixed renewal reward. It is not a universal transaction-cost theorem.
Reading and notes
The part's papers
from READING.md
- Lehmann, B. (1990). "Fads, martingales, and market efficiency." QJE.
- Lo, A. W., MacKinlay, A. C. (1990). "When are contrarian profits due to stock market overreaction?" RFS.
- Elliott, R., van der Hoek, J., Malcolm, W. (2005). "Pairs trading." Quantitative Finance.
- Gatev, E., Goetzmann, W., Rouwenhorst, K. G. (2006). "Pairs trading: performance of a relative-value arbitrage rule." RFS.
- Avellaneda, M., Lee, J.-H. (2010). "Statistical arbitrage in the US equities market." Quantitative Finance.
- Bertram, W. (2010). "Analytic solutions for optimal statistical arbitrage trading." Physica A.
- Do, B., Faff, R. (2010). "Does simple pairs trading still work?" FAJ.
- Nagel, S. (2012). "Evaporating liquidity." RFS.
- Leung, T., Li, X. (2015). "Optimal mean reversion trading with transaction costs and stop-loss exit." Int. J. Theoretical and Applied Finance.
- Krauss, C. (2017). "Statistical arbitrage pairs trading strategies: review and outlook." J. Economic Surveys.
- Guijarro-Ordonez, J., Pelger, M., Zanotti, G. (2021). "Deep learning statistical arbitrage." arXiv:2106.04028 (revised 2022).
- Krauss, C., Do, X. A., Huck, N. (2017). "Deep neural networks, gradient-boosted trees, random forests: statistical arbitrage on the S&P 500." EJOR.
- Engle, R., Granger, C. (1987). "Co-integration and error correction." Econometrica.
- Johansen, S. (1991). "Estimation and hypothesis testing of cointegration vectors in Gaussian vector autoregressive models." Econometrica.
- Froot, K., Dabora, E. (1999). "How are stock prices affected by the location of trade?" JFE.
- Roll, R. (1984). "A simple implicit measure of the effective bid-ask spread in an efficient market." JF.
- Grossman, S., Miller, M. (1988). "Liquidity and market structure." JF.
- Shleifer, A., Vishny, R. (1997). "The limits of arbitrage." JF.
- Coval, J., Stafford, E. (2007). "Asset fire sales (and purchases) in equity markets." JFE.
- Engelberg, J., Reed, A., Ringgenberg, M. (2018). "Short-selling risk." JF.
- Khandani, A., Lo, A. W. (2011). "What happened to the quants in August 2007? Evidence from factors and transactions data." J. Financial Markets.
Papers and sources
Reading
Vidyamurthy, Pairs Trading (2004); Pole, Statistical Arbitrage (2007); Chan, Algorithmic Trading (2013); Pedersen, Efficiently Inefficient (2015); Leung and Li, Optimal Mean Reversion Trading (2016). Papers include Engle–Granger (1987), Grossman–Miller (1988), Lehmann and Lo–MacKinlay (1990), Johansen (1991), Gatev–Goetzmann–Rouwenhorst (2006), Khandani–Lo (2007/2011), Avellaneda–Lee and Bertram (2010), Nagel (2012), Krauss–Do–Huck (2017), and Guijarro-Ordonez–Pelger–Zanotti (2021). Firm histories are public reported accounts. This is education in methods.
For the researcher
The band theorem
Assume dX = −κX dt + σ dW with κ, σ > 0, known constant parameters and continuous monitoring. Wait flat from 0 until |X| = m, hold one unit against the displacement, and exit at 0. Pay a constant round-trip cost c ≥ 0 in spread units. There is no risk budget, stop, discounting, financing cost or structural break. The objective is long-run expected profit per time within this symmetric policy family, not Sharpe or a return on invested capital.
Let s = σ/√(2κ), u = m/s, d = c/s, a = √(π/2), and I(u) = ∫₀ᵘ exp(z²/2) dz. The mean cycle time is a I(u)/κ, so
[ R(m)=\frac{\kappa s}{a}\frac{u-d}{I(u)}. ]
For d > 0 the unique optimum solves I(u*) = (u* − d) exp(u²/2), with u > d. For d = 0 the supremum is approached as m ↓ 0, with R(0⁺) = σ√(κ/π); no positive band attains it. At fixed s and c, changing κ scales the rate but leaves the band fixed. Holding σ instead changes s and therefore the dimensionless cost.
The library evaluates first-passage integrals by Simpson quadrature and uses a bounded grid optimizer (0.02s to 3s with one refinement). A returned zero-cost positive band is a grid artifact, not the attained frictionless optimum. band_curve replaces zero cost by a small positive value. Stored grid simulations use exact OU transitions between dates but credit each completed cycle m − c at the ideal band/mean, excluding execution overshoots. They illustrate crossing-time discretization. Twice fine minus coarse is a heuristic square-root-step extrapolation, not certified continuous-time execution; equal seeds do not couple the Brownian paths, and the nine-row rate table has no Monte Carlo error bars.
Data, scope and reproducibilityEvidence and scope
Each unchanged original was invoked once: pairs, coint, pca, kalman, lomac, nagel, deep, theory, smallc. All nine passed the public-input barriers. No function retry, refresh, new market trial, registry mutation or sealed strategy payload access occurred. The loader rejects every envelope-prefixed name before cache metadata or counted access, and rendering requires existing ordinary caches.
French industry and size data are restricted to research through 2020 by the original readers. The BTC/ETH example uses 2018–2020 after public raw assembled bars are parsed; those raw public files extend beyond 2020. Public raw parsing is distinct from accessing a sealed strategy experiment. Cboe VIX supports a descriptive industry regression. Complete-history coverage selects universes retrospectively rather than supplying point-in-time membership. Reported stock-paper results and firm histories are attributed, not reproduced.
Verified ordinary values include:
| Diagnostic | Value | Interpretation |
|---|---|---|
| Distance proxy, 43 complete-history industries, 1964–2020 | Sharpe −0.248 | Negative sample mean under this implementation; not a GGR stock replication |
| Annual fixed-critical cointegration screen | 7.29% passes | Same seeded 300 industry pairs each year |
| Independent random-walk controls | 3.67% passes | 300 simulated 252-step controls; uncertain calibration |
| Pass next year conditional on passing | 8.14% | Descriptive persistence with repeated assets and tests |
| Fixed-band synthetic residual proxy | Gross 0.879; charged −0.392 Sharpe | Fitted residual P&L and incomplete cost accounting |
| Mathematical-band synthetic proxy | Gross 1.134; charged 0.211 Sharpe | Same reused research sample; no independent band validation |
| Three-seed MLP, nominal 2017–2020 test | IC 0.003409; charged Sharpe −7.222 | Synthetic target, retrospective universe and a chronological research split |
| Pure OU illustration, dimensionless cost 0.3 | Numerical band 1.032879 widths | Bounded grid optimizer, not an exact symbolic root |
The restoration logs, source audit, public-input events, checksums and protected-file checks are in renders/qa/quant33/. The artifact-bound completion evidence below distinguishes construction diagnostics, final visual reviews and sampled CPU speech checks. A silent preview or sampled speech analysis does not establish continuous production listening.
Data, scope and reproducibilityImplementation conventions that affect interpretation
- Distance pairs normalize each formation path by its first observed price. Trading indices restart each half-year. Lagged discrete positions multiply half the return difference; these are not fixed-share buy-and-hold pairs. The
tripsfield counts openings, including positions not explicitly liquidated at the final boundary.cost_yearis a rough conversion, not reconstructed net wealth. - The cointegration screen uses a constant, one lagged difference and a fixed residual critical value −3.34. It is not a universal 5% calibration or a false-discovery probability. Selected half-lives are estimated on the selection window. A representation theorem does not identify a causal economic force.
- OU mapping requires a positive regular interval and 0 < b < 1. The helper drops nonfinite values, compressing gaps, and estimates innovation deviation with two regression degrees of freedom. Kendall's slope-bias formula is a stationary intercept-fitted asymptotic approximation. Applying a nonlinear half-life map to an expected slope does not give the expected fitted half-life.
- PCA correlations use trailing 252 observations through the current close and refit every 21 observations. Residual OLS includes an intercept: its residuals sum to approximately zero, tying the cumulative path down at its window endpoint. Apparent reversion can partly be a finite-window fitting constraint.
- Next-period synthetic residual P&L subtracts the intercept as well as factor returns; an asset-minus-hedge cash account does not automatically receive that subtraction. Normalization is by active industry signals, not total industry-plus-hedge gross capital.
- The cost proxy is twice fixed one-way cost times discrete-signal changes divided by the new active count. It misses rescaling of continuing positions as that count changes. When the new book is empty, net P&L is set to zero and the final exit charge is omitted. Separate hedge approximations can overstate other costs. There is no proven conservative direction for the combined error.
- Nine residual configurations reuse research data. The mathematical band's lookup uses 31 cost points with endpoint clipping. This is not independent discovery or a globally optimal portfolio policy.
- Kalman gain depends on both state covariance and the current loading vector (1, log BTC price). The √(r/q) memory analogy assumes a scalar state with constant unit loading and small q/r; it is not a universal window for the two-state regression. An innovation observed at today's close is not prior tradable wealth. Fixed-residual test critical values do not calibrate an adaptive generated innovation.
- “Weekly” output uses consecutive blocks of five observations, not calendar weeks. An era is assigned by the block's first date. The population Lo–MacKinlay identity is exact; its sample estimates can differ from realized profit because full-sample centering and lagged endpoint means differ. Moment terms do not identify overreaction or news diffusion causally.
- The VIX regression sums daily gross-normalized contrarian P&L arithmetically within months. It uses the previous month's final VIX close and conventional independent homoskedastic errors, not HAC errors. VIX quintiles are descriptive research-sample groups. This is not a replication of Nagel's stock design.
- The MLP averages three seeds, trains through 2012, validates in 2013–2016 and uses nominal test dates 2017–2020. Each 30-component path ends in zero by construction. Complete-history coverage and research reuse limit independence. Demeaned, unit-gross forecasts and a fixed two-leg cost proxy do not establish full financed wealth.
NotesA finite-sample correction for the lead-lag table
Let μ be the full-T sample mean, X_t=r_t−μ, H=I−11ᵀ/N, and Γ̂=(T−k)⁻¹Σ X_tX_{t−k}ᵀ. The plug-in total is −tr(Γ̂H)/N − μᵀHμ/N. Expanding the realized −(T−k)⁻¹Σr_tᵀHr_{t−k}/N gives that plug-in plus
[ \delta=-\frac1N\mu^\top H(\overline X_{\rm now}+\overline X_{\rm lag}). ]
The lagged endpoint subarrays need not have zero means even though the full array does. That is why rounded sample equality is not an exact identity. Stationary population expectations remove the centering cross terms under their assumptions, without supplying causal attribution.
Chapter notesChapters
- Hook: common trends and a chosen mean-reverting log gap; statistical and economic claims.
- History: Thorp, Morgan Stanley, D. E. Shaw, Renaissance and PDT, as reported.
- Distance pairs: formation and trading conventions, retrospective coverage, shorting and cost limits.
- Cointegration: fixed-critical screens, noisy controls, selection, persistence, baskets and economic hypotheses.
- OU: exact regular-interval AR(1) map, s-scores, slope bias and nonlinear half-life uncertainty.
- PCA residuals: eigenportfolios, constrained cumulative residual endpoints, synthetic P&L and cost omissions.
- Kalman: prior-state innovation, current regressor, retrospective fixed ratio and the scalar memory analogy.
- Lead-lag: population covariance identity, finite-sample boundary correction, five-observation blocks and microstructure.
- Deep: a small MLP, chronological research split, prediction targets and trading objectives.
- Liquidity: descriptive lagged-VIX regression, conventional errors, crowding and limits of arbitrage.
- Evaluation protocol: information clock, holdings, cash, actual turnover, research selection and precision; no sealed verdict.
- House: source excerpts, interpretation, risk design, capacity and proposed monitoring.
- Research: symmetric OU cycle, first-passage times, unique positive-cost optimum, frictionless supremum and cube-root asymptotics.
- Recap, six desk questions and twelve exercises: six basic, four advanced, two qualifying.
中文讲义
本讲的中文说明、交易台问题与习题解答(与英文版对应)。
导言量化金融,从零搭建 — 第33部分:统计套利
本部分讨论配对、协整筛选、OU价差、因子残差、动态对冲、反转、流动性及交易区间定理。保留compute.py与公司金融算法,使用九个已核验的普通计算结果,不使用封存年份的策略结果,也不据此建立实际配置。
Desk questions, with solutions区间定理与六个交易台问题
假定κ、σ为已知正常数,连续监控dX=−κXdt+σdW。空仓等到|X|=m,逆向持有一个单位,到零退出,支付固定往返成本c≥0,单位与价差相同。目标是这个对称规则族的长期期望利润每时间,不是夏普或资本回报;没有融资、止损、风险预算、折现或断裂。令s=σ/√(2κ)、u=m/s、d=c/s、a=√(π/2)、I(u)=∫₀ᵘexp(z²/2)dz。周期期望为aI(u)/κ,故R=(κs/a)(u−d)/I(u)。正成本时唯一最优解满足I(u*)=(u*−d)exp(u²/2),且u>d。零成本的σ√(κ/π)是m趋零时的上确界,不由任何正区间取得。固定s及c时,速度只缩放利润;固定σ则s也会变。
- 协整时交易什么? 固定线性价差是统计对象;实际交易还需份额、现金和分母。联系可能断裂,估计与筛选有误,借券融资也可能受限。
- s分数是什么? 对指定OU拟合的(X−θ̂)/ŝ,表示相对拟合宽度的偏离,不是获利概率;阈值是政策选择。
- 短命卡尔曼创新证明协整吗? 不证明。动态修正可以形成平稳外观,但并未给出稳定固定组合或盈利的调仓财富。
- 逆向期望利润来自哪里? 自身滞后协方差、非对角滞后协方差和负均值离散项,是矩的贡献而非已识别因果。
- 残差结果为何需要成本审计? 现有代理缺少部分缩放和退出交易,也未建立完整现金和对冲持仓;必须重构实际交易与融资。
- 区间如何依赖成本? 在指定已知参数规则下,u只取决于d,小成本时u∼(3d)^(1/3)。这不是一般投资组合控制定理。
数值库用辛普森积分和0.02s至3s的有界网格加一次细化,不是符号精确根。零成本返回的正下界不是数学最优值。网格模拟在观测日期间使用精确OU转移,但按理想区间与零点给每次交易计m−c,不按超调成交;两倍细网格减粗网格是平方根步长偏差的启发式外推,同种子并未耦合布朗路径,九行速率表没有蒙特卡洛误差条。
Problems, with worked solutions十二道完整解答:六基础、四进阶、两资格题
基础1 — 斜率与速度
给定b=0.9、间隔一天,由b=exp(−κΔt)得κ=−ln0.9=每天0.1053605。条件期望偏离按exp(−κt)衰减,令其为1/2得半衰期h=ln2/κ=6.5788交易日。它描述条件均值减半,不保证实际首达时间。必须满足规则采样及平稳OU映射的假设。
基础2 — 假通过与家族错误
49个资产有M=49×48/2=1176个无序对。若全部原假设为真且各检验真实大小为0.05,期望假拒绝数E[V]=ΣPr(拒绝第j个真原假设)=58.8,不要求不同配对独立。要使至少一次假拒绝的概率不超过0.05,用并集上界将每项水平设为0.05/1176=4.2517×10⁻⁵,即Bonferroni校正。相关检验仍可使用,但单项p值或临界值必须有效;固定−3.34不自动提供这个调整后的水平。
基础3 — 成本尺度
指定s=2%、固定价差单位往返费c=0.6%,得d=0.3。已核验普通数值计算给u≈1.032879,故m=su≈0.02065758,即2.065758%。这是假定规则下的有界积分网格近似。小成本首项给u≈0.9^(1/3)=0.965489,即m≈1.930979%;d并非无穷小,存在近似误差。这里百分比是价差位移,不是投资组合资本收益。
基础4 — 指定成本算例
指定年毛夏普0.8、年波动4%、每条腿日换手0.2、两条腿、每交易一美元单向费5基点。毛均值0.8×0.04=3.2%/年。252日恒定换手的成本为2×0.0005×0.2×252=5.04%/年,净均值−1.84%。若费用确定且波动不变,净夏普为−0.0184/0.04=−0.46。这个指定算术不修复原残差算法缺少的持仓与换手。
基础5 — 单一交叉协方差
N=2、均值零、自身滞后协方差零,仅Γ₂₁=Cov(r₂,t,r₁,t−1)=γ非零。逆向权重w₂=(r₁,t−1−r₂,t−1)/4,w₁=−w₂。展开E[w₁r₁,t+w₂r₂,t],仅保留γ/4;也等于非对角项γ/N²。只有γ>0时该毛期望为正,不要求任何资产自身反转,执行成本还未计入。
基础6 — 创新相关
创新的描述AR(1)斜率0.3说明仍有正序列依赖,可能涉及模型误设或遗漏动态,并不唯一说明滤波过慢。协整要求积分价格之间存在稳定的固定平稳线性组合。自适应误差平稳或不平稳均不足以单独判断。应先定义固定价差、使用先前信息估计、检查稳定性,再评价实际后续持仓和成本。仅凭这个创新统计没有协整结论。
进阶7 — 换手定义
给毛均值每日2基点,并定义τ=Σ|Δw_j|=0.4为单向总交易权重,费k=5基点,则成本kτ=2基点,净均值为零。如果换手指绝对变化和的一半,应使用2kτ,成本4基点、净−2基点;若每条腿各有0.4,须另加两条腿。没有明确约定就不能再随意乘往返倍数。答案零使用第一种定义,排除融资与冲击。
进阶8 — IC需要多少样本
小相关的n个独立且可比预测目标对,近似标准误为1/√n。令0.01√n≥2,得n≥40000。若每天49对相互独立,则需要40000/49=816.3265天,除以252为3.2394年。相关资产、时间依赖、目标重叠及选择降低有效信息。该合并独立同分布计算只是条件规划,不保证检验功效,也不是三点二四年后必然证明。
进阶9 — 夏普精度
在基本独立同分布、低夏普近似下,以年计标准误约1/√Y。对真实年夏普0.3,令0.3√Y=2,得Y=(2/0.3)²=44.4444年。这是期望信号达到两个近似标准误,不是95%检验功效计算。高阶矩、自相关、变化风险、估计器与选择均会改变它。五年的近似误差0.4472已大于0.3,尚未考虑这些复杂因素。
进阶10 — 小成本算术
指定d=0.01,渐近区间u=(3d)^(1/3)=0.3107233。保留的无摩擦速率近似1−(3d)^(2/3)/2=0.9517255,即95.17%。原有界优化器给u≈0.3129916,κ=s=1时速率0.7598024;除以无摩擦极限√(2/π)=0.7978846得约0.95227。这是渐近预测与数值近似的比较,不是有限成本精确等式,也不是市场证据。
资格11 — 首达、更新与唯一最优
采用上述正常数OU模型,从零空仓开始,m>0。每个周期先到±m之一,再回零。强马尔可夫性和对称性使完整周期时长独立同分布;正再生OU对有限区间有有限的这些期望。每周期固定报酬m−c,更新报酬定理给长期完成周期利润率R=(m−c)/(E₀τ_m+E₋ₘT₀)。如要定义包括未完成周期浮盈亏的财富,还须明确其现金与记账;此式针对更新报酬。
首达期望f(x)在继续区间满足(σ²/2)f″−κxf′=−1,目标边界f=0。乘exp(−κx²/σ²)得 (exp(−κx²/σ²)f′)′=−(2/σ²)exp(−κx²/σ²)。从x<0到零时,在自然左边界排除爆炸齐次解,采用有界斜率解,可得 f′(y)=−(2/σ²)exp(κy²/σ²)∫₋∞ʸexp(−κz²/σ²)dz。 从−m积分到零并用f(0)=0,得到 E₋ₘT₀=(2/σ²)∫₋ₘ⁰exp(κy²/σ²)∫₋∞ʸexp(−κz²/σ²)dzdy。 从零退出(−m,m)时f为偶函数,f′(0)=0;同一微分方程从零积分,内积分下限变零,再用f(m)=0,得到 E₀τ_m=(2/σ²)∫₀ᵐexp(κy²/σ²)∫₀ʸexp(−κz²/σ²)dzdy。
设x=sz、τ=κt,尺度过程为dZ=−Zdτ+√2dB,生成元∂²_z−z∂_z;此处二阶项前不是1/2。实际时间按1/κ缩放。将负向积分反射后与正向积分相加,内积分的变量部分抵消,剩κE[周期]=a∫₀ᵘexp(z²/2)dz=aI(u)。因此R=(κs/a)(u−d)/I(u)。
在u>d上,R导数符号等于I(u)−(u−d)exp(u²/2)的符号。定义H(u)=u−exp(−u²/2)I(u),最优条件是H(u)=d。H(0)=0,且H′(u)=u exp(−u²/2)I(u)>0;由exp(−u²/2)I(u)∼1/u,H趋无穷。因此正d恰有一个解;因H(u)<u,解大于d。解前R增加、解后减少,u趋无穷时速率趋零,故为此规则族唯一全局最大值。无量纲最优区间只依赖d。
资格12 — 无摩擦与立方根
用u=m/s展开κ乘期望时间。令a=√(π/2),被积式exp(y²/2)∫₋∞ʸexp(−z²/2)dz=a+y+ay²/2+y³/3+ay⁴/8+… 。在[−u,0]积分得 κE₋ₘT₀=au−u²/2+au³/6−u⁴/12+au⁵/40+O(u⁶)。等待积分给 κE₀τ_m=u²/2+u⁴/12+O(u⁶)。偶次项抵消,总和为aI(u)=a(u+u³/6+u⁵/40+…)。 零成本时R=(κs/a)u/I(u)趋κs/a=σ√(κ/π)。u>0时I(u)>u,所有正区间速率都严格小于该值,因此这是上确界而非可达到的正区间最优值。
对正小d,精确一阶条件d=H(u)。级数相乘得exp(−u²/2)I(u)=u−u³/3+u⁵/15+O(u⁷),故d=u³/3−u⁵/15+O(u⁷)。唯一根满足u³=3d+O(d^(5/3)),即u∼(3d)^(1/3)。
相对无摩擦速率为(u−d)/I(u)=(1−d/u)/(1+u²/6+O(u⁴))。最优点上d/u=u²/3+O(u⁴),所以比值为1−u²/2+O(u⁴)=1−½(3d)^(2/3)+o(d^(2/3))。指数与二次风险下的持仓区间相似,但此处来自OU周期时间与固定更新报酬,不能据此声称通用成本定理。
Data, scope and reproducibility证据与解释边界
pairs、coint、pca、kalman、lomac、nagel、deep、theory、smallc各执行一次并通过冻结公共输入检查;没有重试、刷新、新市场试验、登记修改或封存策略载荷访问。加载器先拒绝所有以envelope开头的名称,再检查普通缓存。French研究数据截止2020年;BTC/ETH读入的公共原始文件延伸至2025年,之后按原代码筛到2018–2020年。这与读取封存策略载荷不同。完整研究历史决定资产覆盖,属于事后完整性筛选,并非当时可得的成员表。
核验值包括:43行业距离代理夏普−0.248;年度协整通过率7.29%,300条随机游走对照通过率3.67%,次年再次通过8.14%;标准区间残差代理毛夏普0.879、扣代理成本后−0.392,数学区间为1.134与0.211;小网络名义测试期IC为0.003409,扣代理成本后夏普−7.222。它们是指定实现的描述统计,不证明可实施财富。普通结果、输入事件与哈希记录保存在renders/qa/quant33/。
关键约定如下:距离法每半年重启交易指数,滞后离散仓位乘收益差的一半;trips统计开仓,不保证全部完成往返或期末平仓。协整使用同一批300行业对、常数和一个差分滞后及固定−3.34门槛;不是普适的5%校准。OU映射要求规则正间隔及0<b<1,删除缺失值会压缩时间。肯德尔斜率偏差的近似经过非线性半衰期映射后,不等于平均半衰期。
PCA用截至当日的252观测窗口,每21观测重估。含截距OLS残差和约为零,累计残差的窗口终点因此被钉住,表观回归可部分来自拟合约束。次期合成残差扣掉截距及因子收益,不能直接视为资产减对冲的真实现金流。分母是活跃行业信号数,不是全部对冲后的总敞口。成本按离散信号变化除以新活跃数估计,遗漏活跃数改变时持续仓位的缩放;新仓位全空时又把净利润设零,漏掉退出费用。单独对冲近似可能向另一方向偏误,合计误差没有已证实的保守方向。
卡尔曼两状态增益受当前载荷向量与价格单位影响,√(r/q)记忆长度只属标量恒定单位载荷的小噪声比近似。当前创新不是先前可交易财富,也不能用固定协整检验的临界值直接校准。所谓周度是连续五观测块,不是日历周。Lo–MacKinlay总体恒等式精确,但样本全期中心化与滞后子样本端点均值不同,实际利润可含边界修正。协方差分解不识别因果。VIX月结果是日代理利润的算术和,使用前月末VIX和常规独立同方差误差,不是HAC,也不是Nagel股票设计的复现。三种子MLP使用截至2012年训练、2013–16验证及2017–20名义测试;研究期复用和事后覆盖限制独立性,30维路径末项恒零。
章节依次为开篇、历史、距离配对、协整、OU、PCA、卡尔曼、领先滞后、网络、流动性、评估协议、公司代码与风险、研究定理、回顾和习题。第十章说明信息时钟、真实持仓与现金、成本、选择和精度,不给封存期结论。
Build the film
python -m videos.quant.quant33.compute # the part's numbers, into .cache/quant33
python tools/make.py quant33 # the narrated film, English and Chinese
EXPLAINER_TTS=silent python tools/qa_scene.py quant33 Hook # one chapter, silent, with a contact sheet
Scenes: videos/quant/quant33. Setup: see the course page. Source of these notes: the part's README and the scenes' narration.