quant.futures

Pairs lab guide

Stat-arb lab

What the statistical arbitrage lab does, how to use each page, and what every number means. Read top to bottom once; afterwards the glossary at the end is the part you will come back to.

1 · What this is

A pairs trade bets that two prices that have moved together will keep moving together. You go long the one that has fallen behind and short the one that has run ahead, in a ratio chosen so that the combined position is insensitive to the market as a whole. If the historical relationship holds, the gap closes and the trade earns the gap; if the relationship has broken, it does not.

The lab turns that idea into a repeatable, measurable process. It keeps a daily price history for a universe of futures, ETFs and stocks; tests every candidate pair for cointegration (the statistical form of “moves together”); turns the spread between the two legs into a z-score; backtests entry and exit rules walk-forward with explicit costs; and runs the same decision logic every evening against the watchlist, pushing changes to Discord.

It is a research arena, not an order router. Nothing here trades. Every alert says what the model would do and why, and the decision stays yours.

2 · The research workflow

  1. Load data. On the dashboard press Refresh data. New tickers download ten years of daily bars; known ones refresh a two-week overlap so revised settlements are picked up.
  2. Scan. Run a scan over the watchlist (the ten pairs from the brief) or the whole universe. Every ordered pair gets the full evidence table; the rolling stability test runs only for pairs that pass the cheap filters. The result is a ranked table with a qualified / not-qualified verdict and the reasons.
  3. Analyze. Open a pair. Look at the spread, at how β and the p-value drifted, and above all at the conditional forward returns: when z was beyond ±2, did the spread actually come back over the next 5–20 days? If that table is flat, no rule will rescue the pair.
  4. Backtest. Run the walk-forward engine over the pairs that survive, with costs on and the sensitivity grid enabled. Judge the result by the deflated Sharpe and the plateau in the grid, never by the best cell.
  5. Watch. Put the survivors on the watchlist. The daily job scans them after the US close, keeps a position state per pair and pushes every state change to Discord. Run it in dry-run mode for two weeks first and compare its decisions with the backtest.
  6. Paper trade. Record what you would have done against what the job said for three to six months. The gap between the paper record and the backtest is the number that decides whether real capital is sensible.

3 · Core concepts

Cointegration is not correlation

Correlation says the daily returns of two assets tend to have the same sign. Cointegration says a fixed combination of their price levels is stationary: it wanders but keeps coming back to a mean. Two assets can be highly correlated and still drift apart forever (think of two tech stocks with different growth), and two assets can have weak daily correlation yet be tied by an arbitrage relationship (the same oil delivered in two places). Pairs trading needs the second property. The lab reports both so the difference is visible.

The regression and the spread

All tests use log prices. The hedge regression is log Y = α + β·log X + ε. β is the hedge ratio: a 1 % move in X maps to a β % move in Y. The residual ε is the spread, and the whole strategy is a statement about ε: it should be stationary with a half-life short enough to trade.

Three estimators of β are shown side by side. OLS is the textbook one but treats X as noise-free, which is why β(Y on X) is not 1/β(X on Y). TLS (orthogonal regression) is symmetric in the legs. Johansen comes from a system estimate. If the three disagree a lot, the relationship is poorly identified and position sizing will be fragile.

The evidence stack

One p-value is a weak reason to risk money, so each pair gets several independent tests:

TestWhat it checksRead it as
Engle-Granger (both ways)Whether the OLS residual has a unit root. The default gate.p < 0.05 in both directions is the comfortable case; agreement matters more than the exact value.
ADF on the spreadThe same question asked of the spread directly.Should agree with Engle-Granger; a split is a warning.
Johansen traceSystem test for at least one cointegrating vector.Statistic above the 95 % critical value = pass. Used as cross-validation, optional as a gate.
Hurst exponentLong-memory scaling of the spread.Below 0.5 mean reverting, 0.5 random walk, above trending. A rough estimate; one voice, not a verdict.
BH q-valueEngle-Granger p-value corrected for the number of pairs tested in the scan (Benjamini–Hochberg).Scanning 1 800 ordered pairs at p < 0.05 yields ~90 false positives by chance. The q-value is the honest number.

Half-life

Fitting Δs(t) = λ·s(t−1) + c gives the speed of mean reversion; the half-life is −ln 2 / λ, the number of days for half of a deviation to decay. λ ≥ 0 means no reversion at all and disqualifies the pair outright. The point estimate is noisy on two years of data, so the lab also shows a block-bootstrap 90 % interval: “HL = 8 (5–16)” is a different statement from “HL = 8”.

z-score and its window

z = (spread − mean) / std over a trailing window. The brief proposed a window of 2 × half-life. On synthetic spreads with a known half-life that window understates the stationary variance (it spans only two half-lives), inflates z, and fires the 3.5σ stop on most trades: the same cointegrated pair that scores a Sharpe of 1.4–1.7 with a 60-day window scores ≈ 0 with 2 × HL. The lab therefore defaults to window = clip(4 × HL, 20, 120) and exposes the multiple as a parameter so the choice can be tested rather than assumed.

4 · When a pair qualifies

All conditions must hold at the scan date; each is configurable.

ConditionDefaultWhy
Engle-Granger p< 0.05The relationship exists at conventional confidence.
Half-life3 – 40 daysShorter is noise and execution cost; longer ties capital up for months and is hard to distinguish from a trend.
Stability≥ 80 % of last 60 days with p < 0.05A pair that only just passed today is often a pair that fails next week. This is the main defence against false positives.
β sign and driftβ > 0, CV of rolling β < 0.5A negative β is a different trade; a β that swings is a hedge that cannot be sized.

The stability test is expensive (one regression and unit-root test per day), so the scan only runs it for pairs that already pass the point-in-time conditions. Pairs that fail show the cheapest failing reason first in the table; hover for the rest.

5 · Signal rules

One state machine drives both the backtest and the daily job, so the backtest is a statement about the live system rather than a cousin of it. Decisions happen at the close; fills happen the next day.

RuleDefaultNote
Entryz ≥ +2 short spread · z ≤ −2 long spreadShort spread = sell Y, buy β·X in notional. Long spread is the mirror.
Exit|z| ≤ 0.5, or z crosses zeroBoth variants are in the sensitivity grid; cross-zero holds longer and earns more per trade when the pair is honest.
Stop|z| ≥ 3.5 against the positionFollowed by a cooldown. Only adverse moves stop; a favourable overshoot is simply a bigger win.
Time stopheld > 3 × half-lifeIf it has not reverted in three half-lives, the half-life was wrong.
BreakdownEG p > 0.10 for 5 consecutive daysThe relationship itself has failed while you are in it: exit, cooldown, and the pair stops qualifying for new entries.
Parameter freezeonβ, mean and std are fixed at entry so the exit is judged against what was known then. Switch off to compare with daily refreshed parameters.

Priority when several fire on the same day: stop → breakdown → time stop → exit. An exit never re-enters the same day.

6 · Hedge sizing

Because β is a log-price elasticity, the position that tracks the spread has notional(X) = β × notional(Y), where notional = quantity × price × contract multiplier. (The brief wrote it the other way round; with a log regression this is the correct direction.) Given a gross notional budget per pair, the Y leg gets budget / (1 + β) and the X leg the rest.

Fractional sizing is the research truth: legs can be any real quantity, so the ratio is exactly β. Integer sizing rounds to whole contracts, micro contracts first (MNQ, MES, MGC, MCL…), reports how far the realised ratio drifted from β, and marks positions that round to zero as infeasible. Running both gives the tradeability tax: the return you lose purely to lot sizes. Entry alerts also carry a two-sigma adverse-move estimate in dollars on the Y notional.

7 · Reading a backtest

What makes it walk-forward

For every trading day t, α, β, half-life, the z window and the p-value are computed from the formation window that ends at t−1. The signal is evaluated at t’s close and filled at t+1’s open (or close). A test in the code base randomises every price after a date T and asserts that every trade and every equity point up to T is identical, so nothing can leak backwards.

Costs

Commission per contract per side, slippage in ticks per leg per fill (converted with each contract’s tick value), and a roll cost per leg: charged on the roll calendar’s dates for equity index futures, otherwise as a daily expectation from the instrument’s contract months per year. ETFs and stocks have no roll cost.

Portfolio

Capital × gross leverage is split equally across the pairs in the run (or by inverse spread volatility). Max concurrent caps how many pairs can be open at once; a signal that arrives when the slots are full is skipped, not queued. The P&L correlation heatmap shows whether your pairs are one bet in disguise — NQ/ES, ES/YM and NQ/YM usually are.

The honesty metrics

  • Sharpe with a bootstrap interval. Blocks of 20 days are resampled 500 times. If the interval straddles zero the point estimate is not telling you much.
  • Deflated Sharpe probability. With the sensitivity grid on, the engine ran N parameter combinations; the best of N zero-skill strategies would also look good. The deflated Sharpe is the probability that the true Sharpe beats that best-of-N null, using the observed dispersion of the grid, skew and kurtosis. Below ≈ 0.9 the result could be selection.
  • Benchmark. Equal-weight buy-and-hold of the Y legs over the same span, with its own drawdown, so the strategy is compared with the simplest alternative.
  • Exit mix. A strategy that exits mostly on stops is a strategy whose z window or stop level is wrong, whatever the total return says.
  • Sensitivity plateau. Choose parameters from a region of the grid that is uniformly acceptable. A lone bright cell is noise.

8 · Page by page

Dashboard

Six blocks in reading order: data coverage and actions; the latest scan as a sortable table (click a header); the watchlist the daily job uses; the live state per pair with the frozen entry parameters; the signal feed (pushed or not); and the job history. “no_data” in the job list is the normal outcome on a US holiday.

Analyze

Pick Y and X (or arrive from a dashboard link or a Discord alert). Tiles summarise the current state; the evidence table lists every test; the two charts show the spread/z and β/p through time; the forward-return table is the diagnostic that matters most. Cross-group pairs show a settlement note — switch the price source to the 15:00 ET snapshot to read both legs at the same instant.

Backtest

Four blocks of configuration (pairs, estimation, rules and costs, capital and sizing), then results: metric tiles with hover explanations, equity and drawdown, per-pair attribution, correlation, sensitivity heatmaps and the trade list. Earlier runs reopen from the table at the bottom and reload their configuration into the form.

9 · Data caveats

  • Front-month futures series roll. The vendor’s =F tickers are unadjusted front-month series; on roll day the price jumps by the calendar spread and the pairs spread sees a shock that is not a trading opportunity. Equity index pairs read the project’s roll calendar and the charts mark those dates; other futures flag large single-day moves as “gaps” in the scan table. A continuous, back-adjusted series from a paid vendor is the proper fix and remains an open purchase decision.
  • Settlement times differ. Gold settles at 13:30 ET, oil at 14:30, Treasuries at 15:00, equity indices at 16:00. A settlement-based spread between two groups mixes two moments. The 1m store lets both legs be read at one wall-clock time instead; the option is on the Analyze page and in the scan configuration.
  • Adjusted closes for ETFs and stocks. Dividends would otherwise appear as spread shocks on every ex-date. Futures use the plain close.
  • Revisions. Vendors revise settlements for a day or two; the refresh overwrites, and the daily job always re-reads a two-week overlap.
  • Holidays. Legs are inner-joined on trading dates with at most one day of forward fill, so a single-exchange holiday is bridged and a longer hole is dropped rather than invented.

10 · The daily job and Discord

The job runs inside the fetcher process at 23:00 UTC on weekdays (two to three hours after the US close, with no change needed across daylight-saving transitions). Steps: refresh daily bars → confirm a bar exists for the expected trading date (otherwise record no_data and stop) → scan the watchlist → step each pair’s state through the shared state machine → write state and events → push un-notified events to the webhook.

It is safe to re-run on the same day: a pair already advanced to today’s date is not stepped again, the signal log refuses duplicate (date, pair, event) rows, and only events without a push timestamp are posted. Admins can trigger a dry run from the dashboard.

VariableDefaultMeaning
PAIRS_WEBHOOK_URL—Discord webhook for alerts (keep it separate from the ops channel). Empty = nothing is posted.
PAIRS_DRY_RUNfalseScan and persist, post nothing. Use it for the first two weeks.
PAIRS_CRON0 23 * * 1-5Schedule in UTC.
PAIRS_CAPITAL1 000 000Notional the entry alert sizes against (integer contracts, micro first).
PAIRS_DAILY_DIGESTtrueOne compact message per day listing every watchlist pair’s z, p and half-life.
PAIRS_NOTIFY_NO_DATAfalseAlso post when no new bar arrived (holidays would otherwise be silent).
PAIRS_HISTORY_YEARS10History requested for tickers seen for the first time.

Each alert links back to the pair’s Analyze page. An entry message shows z, β, half-life, p-value, stability, the suggested integer legs with their rounding error and the two-sigma adverse estimate; an exit message shows the reason and the days held. Every message ends with “research only, not an order”.

11 · Glossary

Spread
log Y − α − β·log X. The thing that is supposed to mean-revert.
z
Spread minus its trailing mean, divided by its trailing standard deviation.
β (hedge ratio)
Slope of log Y on log X; sets notional(X) = β·notional(Y).
Half-life (HL)
Days for half of a spread deviation to decay, from the OU regression.
Formation window
Trailing days used to estimate α, β and HL; 504 ≈ two years.
Stability
Share of the last 60 days on which the pair tested cointegrated.
BH q-value
False-discovery-rate adjusted p-value across all pairs in a scan.
Hit rate
In the forward table: share of cases where the spread moved back toward its mean.
Long / short spread
Long spread = buy Y, sell X. Short spread = sell Y, buy X.
Sharpe
Annualised mean daily return over its standard deviation (zero risk-free rate).
Sortino
Like Sharpe but only downside deviation in the denominator.
Calmar
Annual return divided by the absolute maximum drawdown.
CVaR 95
Average of the worst 5 % of daily returns.
Deflated Sharpe p
Probability the true Sharpe exceeds the best-of-N-trials null.
Tradeability tax
Fractional-sizing return minus integer-contract return.
Breakdown
EG p above threshold for consecutive days while in a position.
Dry run
The job computes and records everything but posts nothing.
Snapshot source
Prices read from the 1m store at one New York time for every leg.

12 · Known limits and next steps

  • Classic pairs-trading returns have declined since the 2000s in the academic record; expect thin edges and let the deflated Sharpe keep you honest.
  • Relationships break for structural reasons (negative oil in 2020, a changed index methodology). The breakdown rule is a detector, not a prophecy; calibrate its threshold on the pairs you actually trade.
  • Front-month roll gaps pollute every futures spread until a continuous series is sourced.
  • The engine is two-legged. Johansen already produces the cointegrating vector for three or four legs (a Treasury-curve basket, NQ/ES/YM together); a basket engine is the natural next module.
  • Position sizing is unconstrained by any account rule on purpose. If you later trade this inside a funded account, add that layer on top rather than inside the research code.
  • Intraday signals are out of scope here even though the 1m store would support them; the daily cadence is deliberate for a swing horizon.

Design record: docs/ADR-010-pairs-lab.md in the repository.