# Cointegration

A Statistics concept (Relationships) in the LuxAlgo Library, with 1 indicator implementation.

## What is Cointegration?

Cointegration is a long-run statistical tether between price series. Two or more series that each wander without a fixed mean are cointegrated when some linear combination of them is stationary: the weighted spread oscillates around a stable level even though the individual legs drift freely. The idea was formalized by Engle and Granger (1987). The Engle-Granger procedure tests it by regressing one leg on the other and checking the residual for [stationarity](https://www.luxalgo.com/library/concept/stationarity-and-efficiency-tests/); the Johansen test generalizes to several series at once and counts how many independent cointegrating relationships exist. It is distinct from [correlation](https://www.luxalgo.com/library/concept/correlation/), which measures whether returns move together bar to bar, not whether levels stay anchored over months.

The concept reshaped econometrics enough to earn Engle and Granger the 2003 Nobel memorial prize: it legitimized working with trending series by asking whether combinations of them, rather than the series themselves, behave. Trading adopted it as the statistical backbone of relative-value work, with the Johansen framework extending the idea from pairs to baskets, where several assets share common drivers and multiple stable spreads can coexist.

The concept matters because it is the statistical justification for spread and pairs trading: if the spread is stationary, deviations from its mean are expected, though never guaranteed, to be corrected, so the spread can be normalized (commonly z-scored) and faded at extremes with a hedge ratio taken from the cointegrating regression. The standing caveat is fragility: a relationship estimated in one window can weaken or break when fundamentals change, and a spread can keep widening far longer than a backtest suggests.

Practice adds two disciplines the textbook omits. Reversion speed matters as much as reversion existence, so desks estimate the spread's half-life (how many bars a deviation typically takes to decay halfway) and skip pairs that revert too slowly to trade; and search intensity poisons naive screens, since testing thousands of pairs at conventional thresholds manufactures dozens of spurious 'relationships' by chance alone, which out-of-sample verification and economic-linkage requirements exist to filter.

## How to test for cointegration

The workflow runs from economic candidates to statistical verification to tradability checks.

1. Start with economically linked candidates (shared sector, index, or input costs); statistical screens without a linkage story breed false positives.
2. Estimate the hedge ratio by [regressing](https://www.luxalgo.com/library/concept/linear-regression/) one leg's levels on the other's over the formation window.
3. Test the residual spread for stationarity (the Engle-Granger step); for baskets, use the Johansen procedure, which also yields the weights.
4. Normalize the spread as a [z-score](https://www.luxalgo.com/library/concept/z-score/) of its own history so entry and exit thresholds are comparable across pairs.
5. Estimate the half-life of reversion from the spread's own decay; too slow means untradable regardless of statistical significance.
6. Re-test on rolling windows and monitor the spread's [autocorrelation](https://www.luxalgo.com/library/concept/autocorrelation/) structure: a relationship is a hypothesis under continuous review, not a certificate.

## How it's calculated

Tests whether two non-stationary price series share a stationary linear combination, the mean reverting spread that pairs trading exploits.

```
Y_t = α + β × X_t + ε_t (OLS regression of one price series on the other)
S_t = Y_t - α - β × X_t (the spread, the regression residual)
ΔS_t = γ × S_{t-1} + Σ over i = 1..k of φ_i × ΔS_{t-i} + u_t (ADF test regression on the spread)
Cointegrated when γ < 0 and its t statistic is more negative than the Engle-Granger critical value

  X_t, Y_t: prices (usually log prices) of the two instruments at time t
  t: time index
  α: regression intercept
  β: hedge ratio, units of X held per unit of Y
  ε_t: OLS regression residual
  S_t: the spread at time t, the estimated residual
  Δ: one period difference operator, ΔS_t = S_t - S_{t-1}
  γ: mean reversion coefficient in the ADF regression
  i: lag index in the ADF sum
  k: number of augmenting lags (chosen by an information criterion)
  φ_i: coefficient on the i-th lagged spread change
  u_t: ADF regression error term
```

This is the Engle-Granger two step method; the Johansen test is the multivariate alternative and estimates the relationship differently.

Both series should individually be integrated of order one, meaning stationary after one differencing, before the test is meaningful.

Because β is estimated rather than known, the ADF statistic must be compared against the stricter Engle-Granger critical values.

## How traders use it

- Pairs selection and sizing: screen related instruments for cointegration, take the hedge ratio from the regression, and trade z-score extremes of the spread back toward its mean, the core of a [pairs trading stack](https://www.luxalgo.com/library/concept/pairs-trading-stack/).
- Relationship monitoring: re-test the spread on rolling windows so positions are only taken while the equilibrium still appears intact, and stand down when the residual stops testing stationary.
- Hedging: constructing offsetting positions whose combined value tracks the stationary combination, reducing exposure to the common drift the legs share.
- Holding-period design: the spread's estimated half-life sets expected trade duration and time-stops, so positions are exited when reversion is overdue rather than held on faith.
- Basket construction: Johansen weights define multi-asset spreads (one index against its components, related commodities against each other) that isolate a stationary relationship no single pair offers.

## Cointegration vs related concepts

- **Correlation** (https://www.luxalgo.com/library/concept/correlation/): Correlation measures whether returns move together over short horizons. Cointegration is about price levels sharing a long-run equilibrium: assets can be strongly correlated yet drift apart permanently, or weakly correlated yet tethered over long horizons. Spread trading rests on the tether, not the day-to-day echo.
- **Stationarity & Efficiency Tests** (https://www.luxalgo.com/library/concept/stationarity-and-efficiency-tests/): Stationarity tests interrogate a single series; cointegration asks whether a combination of non-stationary series becomes stationary. The Engle-Granger procedure literally ends in a stationarity test on the regression residual, which is why the two topics travel together.
- **Autocorrelation** (https://www.luxalgo.com/library/concept/autocorrelation/): Autocorrelation describes a single series' memory at fixed lags; a cointegrated spread is interesting precisely because its autocorrelation structure implies decay toward a mean. Half-life estimation is autocorrelation analysis applied to the spread the cointegration test certified.

## FAQ

### What is the difference between correlation and cointegration?

Correlation says returns move together in the short run; cointegration says a combination of price levels keeps returning to a stable relationship in the long run. Two assets can correlate strongly for months while their prices drift apart for good, and a genuinely cointegrated pair can show weak daily correlation. Mean-reversion spread trades rest on cointegration, because only a stationary spread has a mean worth fading.

### Do cointegrated pairs always revert to the mean?

No. Stationarity of the spread in the tested window implies a tendency to revert within that sample, not a contract. Relationships break when fundamentals diverge (index changes, business shifts, regime changes), the tests themselves have limited power, and even intact spreads can widen far beyond historical extremes before turning. Serious pairs workflows re-test the relationship on rolling windows and cap the loss per divergence.

### Should I use the Engle-Granger or Johansen test?

Engle-Granger for two assets: simple, transparent, and it hands back the hedge ratio directly, with the known quirk that results can depend on which leg is regressed on which. Johansen for three or more, or when you want the number of independent relationships and the basket weights in one framework. Many desks run Engle-Granger for screening and Johansen for anything promoted to a basket.

### What is the half-life of a spread and why does it matter?

The typical time a deviation takes to decay halfway back to the mean, estimated from the spread's own mean-reversion speed. It converts 'stationary' into 'tradable': a spread with a three-day half-life suits short-horizon fading, while a ninety-day half-life demands capital patience most strategies lack. It also calibrates time-stops, since a deviation that has outlived several half-lives is evidence the relationship changed.

### How often should a cointegration relationship be re-tested?

Continuously in spirit, on a rolling schedule in practice: re-run the test as each new window of data completes, and gate new entries on the relationship still passing. The formation window's length sets the trade-off, long windows are statistically steadier but slower to notice a break, short ones adapt quickly and false-alarm more. Position exits additionally rely on divergence caps rather than waiting for the statistics to confirm the obvious.

### Why do cointegrated relationships break down?

Because the tether was economic, not mathematical: mergers, index reconstitutions, business-model drift, regulatory shifts, or one leg's idiosyncratic shock can end the shared dynamics the statistics were measuring. Breaks are also discovered late by construction, since the test needs data to notice. That is why pair traders treat every relationship as provisional and size each divergence as if it might be the one that never comes back.

## Implementations in the Library

- Cointegration (LuxAlgo): https://www.luxalgo.com/library/indicator/cointegration/

## Related concepts

- Correlation: https://www.luxalgo.com/library/concept/correlation/
- Beta: https://www.luxalgo.com/library/concept/beta/
- Alpha: https://www.luxalgo.com/library/concept/alpha/
- Autocorrelation: https://www.luxalgo.com/library/concept/autocorrelation/
- Lead-lag Detection: https://www.luxalgo.com/library/concept/lead-lag-detection/
- Pairs Trading Stack: https://www.luxalgo.com/library/concept/pairs-trading-stack/
- Stationarity & Efficiency Tests: https://www.luxalgo.com/library/concept/stationarity-and-efficiency-tests/

---

Source: https://www.luxalgo.com/library/concept/cointegration/ (LuxAlgo Library, the encyclopedia of trading & technical analysis). Free to use with attribution: https://www.luxalgo.com/library/license/