The maths of statistical arbitrage: from a fitted spread to a trade
A pair of stocks can move together for years and still lose money when you trade the gap between them. A regression can fit past prices closely while its residual keeps drifting. A spread can mean revert while its expected profit is smaller than the cost of entering and exiting.
The mathematics helps us separate those questions.
Here and are prices in dollars per share at time . The residual is the difference between A's observed price and its model estimate. It is measured in dollars per A share. The intercept 10 is also in dollars per A share. The slope 1.5 converts a dollar move per B share into a predicted dollar move per A share.
When A was $104 and B was $60, the model estimate for A was $100. The residual was $4. We sold 100 shares of A and bought 150 shares of B.
But where did 10 and 1.5 come from? Why should $4 be unusual? And what evidence would make us expect it to fall?
Estimate the relationship before judging the gap
Suppose these five artificial observations are our training sample. We use a small sample so you can calculate the fit by hand. Five observations do not establish a trading strategy.
| Observation | B price | A price | Fitted A price | Residual |
|---|---|---|---|---|
| 1 | $58.00 | $98.00 | $97.00 | $1.00 |
| 2 | $59.00 | $97.50 | $98.50 | −$1.00 |
| 3 | $60.00 | $100.00 | $100.00 | $0.00 |
| 4 | $61.00 | $100.50 | $101.50 | −$1.00 |
| 5 | $62.00 | $104.00 | $103.00 | $1.00 |
For one explanatory variable and an intercept, the solution is:
The bars denote sample averages. In our table, and . Subtract each series’ average to centre its values. The centred B values are . The centred A values are .
The numerator is:
The denominator is . Therefore:

Our residuals sum to zero. Their centred cross-product with B is also zero:
They are not evidence that the residual is stationary, independent, normally distributed, or likely to reverse tomorrow. The fit makes the historical errors satisfy these equations. It does not establish a future equilibrium.
Correlation asks a different question from cointegration
Return correlation describes whether percentage changes tend to move together. Cointegration concerns whether a particular combination of nonstationary price levels has a stationary residual.
A simple counterexample makes the distinction visible. Suppose:
where is a common random shock and is an independent additional shock. Both have zero mean and finite variance. If the common shock dominates, the two price changes will be highly correlated. When price changes are small relative to price levels, their percentage returns can also look strongly related.
Yet the spread satisfies:
It is a random walk. Its conditional expected next value is its current value, and its variance grows with time. Similar daily movements have not created a restoring force.
Compare that with a model in which the residual itself follows:
Assume independent shocks with zero mean and constant finite variance. If we also start the residual in its stationary distribution, this residual is stationary. If B is a random walk and A equals , the two prices can share a nonstationary trend while their specified combination remains stationary.

Test the fitted residual using the right reference distribution
One residual-test regression has the form:
Here , is the number of lagged changes, are coefficients, and is the regression error. The lagged changes help account for dependence between observations over time. Under the unit-root null, ; a sufficiently negative test statistic can support rejection.
statsmodels.tsa.stattools.coint implements the appropriate reference distribution. Its documentation specifies the I(1) assumption, first-stage deterministic terms, and MacKinnon-based p-values and critical values. An intercept-only relationship and a relationship with a deterministic time trend represent different hypotheses. Source: statsmodels cointegration test documentation.An illustrative decision would be: if a test statistic were and the returned 5% critical value were , reject at that level because . These numbers are hypothetical. Use the actual critical values returned for your specification and sample.
Rejection does not identify an entry threshold or establish profitability. Failure to reject does not prove the absence of a relationship. Testing hundreds of pairs also creates a selection problem. Account for that search when judging the smallest p-value. It is not equivalent to one test chosen in advance. Preserve a separate period for evaluating the selected strategy.
Convert the residual into an unusualness score
A $4 residual may be enormous for one pair and routine for another. Standardisation puts the gap on the scale of its historical fluctuations:
Here is an estimated residual mean and is an estimated residual standard deviation, both in dollars per A share. Their ratio is dimensionless.
Suppose a separate training window with substantially more observations gives and . Our $4 residual gives . A residual of $0.50 gives .
A rule might enter a short-spread position above 2 and exit when the score falls below 0.5. These are candidate rules to evaluate, not universal trading constants.
A score of 2 is not automatically a 97.5th-percentile event. That interpretation requires a suitable distributional model. Financial residuals may have skew, heavy tails, serial dependence, and changing volatility.
For a clean first experiment, estimate the mean, standard deviation, and hedge coefficients on training data and freeze them during evaluation. If you instead update them, specify exactly which past observations were available at each decision. A larger estimated standard deviation can reduce the z-score even if prices have not converged profitably. Updating the intercept can move the model’s reference level toward a losing position. That model change does not recover the loss.
Estimate the speed of adjustment
A stationary residual can revert too slowly to trade economically. While you wait, you pay borrow and financing charges and keep capital committed to the position.
A simple autoregressive model is:
The intercept has residual-dollar units. The persistence is dimensionless. Assume independent, zero-mean innovations of fixed finite variance. If , the stationary mean is .
Writing gives . Repeated conditional expectations imply:
For , the half-life of this expected deviation is:
With daily observations and , this is about 3.11 trading days. A $4 deviation has conditional expected deviations of $3.20 after one day, $2.56 after two, and $2.048 after three.

Check the boundary cases before interpreting a half-life. As approaches 1 from below, the half-life grows without bound. At , there is no finite restoring half-life. Values with are explosive in this causal model. At , the expected deviation disappears at the next observation. For negative with magnitude below one, the conditional expected deviation alternates in sign. You can use to calculate how quickly its amplitude halves. The expected path no longer moves steadily toward the mean. At , shocks also prevent stationary finite-variance behaviour under these assumptions.
A continuous-time Ornstein–Uhlenbeck model writes the restoring force as . Here is a rate in inverse time, is residual volatility per square root of time, and is Brownian motion. Its exact sampled persistence is , giving half-life . This is a useful next model. The daily AR(1) already answers our immediate question: how quickly does the fitted conditional mean decay?
Estimated persistence is uncertain, especially near one or in short samples. A point estimate of three days is not a guaranteed holding period or an automatic stop-loss rule.
Translate the statistical spread into share-level profit
Return to our trade: short 100 A and long 150 B. Keep those quantities fixed until exit.
If A falls from $104 to $102 while B rises from $60 to $61, the gross profit is:
The residual fell from 4 to . Since our coefficients stayed fixed:
Subtract $125 of assumed total execution, borrow, and financing costs, and the net result is $225. The intercept cancels from the price change. It is not a $1,000 cash payment earned when we enter.
This identity explains why the slope matters for sizing. Shorting 100 A and buying 100 B would leave an additional exposure to B's movement. The residual chart would no longer measure the price changes of the portfolio we actually hold.
If we change the hedge coefficient while holding a position, spread changes also contain model changes:
The last two terms change the chart even when they produce no trading profit. Actual portfolio profit uses the quantities held over each interval. Track cash when rebalancing. Buying more shares uses cash. Changing the short position changes both cash proceeds and the shares you owe. Record each trade and its cost. Do not treat a residual change caused by refitting as trading profit.
Choose the neutrality you actually intend
At entry, our A short has value $10,400 and our B long has value $9,000. Net risky-asset dollar exposure is −$1,400. The price-regression hedge is therefore not dollar neutral.
To be dollar neutral at those prices, 100 short A shares would require long B shares. That is a different portfolio from the 150-share statistical hedge.
Market-beta neutrality is different again. If the return betas to a market factor are and , approximate dollar market-factor exposure is:
where signed quantities are positive for longs and negative for shorts. Setting this to zero need not match either dollar neutrality or the price-regression ratio. Sector, currency, and commodity exposures can also survive the hedge.
A log-price regression creates another distinction:
Before coding, write down whether your model uses prices or logs, what its slope means, and which risk you want the positions to offset.
Turn the equations into a reproducible experiment
The steps now connect. Fit a relationship using past data and examine its residual. Estimate the deviation’s size and adjustment speed. Translate the signal into share quantities. Then calculate profit and costs from the actual trades.
The test can support a relationship. The ledger tells us whether our chosen implementation earned money under its stated assumptions.
Further reading
- Ganapathy Vidyamurthy, Pairs Trading: Quantitative Methods and Analysis, Chapter 5, for cointegration, common trends, and error correction.
- Ernest P. Chan, Quantitative Trading: How to Build Your Own Algorithmic Trading Business, Chapter 7, for mean-reverting strategies, cointegration, and adjustment speed.
- statsmodels augmented Engle–Granger test documentation, for the implemented hypotheses and reference distributions.
All numeric trading examples and figures in this article are invented for teaching. The five-observation table demonstrates arithmetic, not empirical evidence.
Go deeper with lessons, derivations and worked exercises behind this article.