Trading Dev AcademyFree quant education

Free lesson · Statistical arbitrage

Causal z-scores and a complete entry–exit state machine

Open interactive lessonPractice calculationsExplore labs

Start with the idea

A z-score expresses a residual in units of its recent variability. It becomes a strategy only after you specify position state, entry, exit, invalidation, execution timing and what happens when orders fill partially.

Symbols, units & horizon
  • z_t: dimensionless standardised residual
  • s_t: current residual
  • s̄_(t−1): mean from the previous window
  • σ̂_(t−1): positive sample standard deviation from that window
  • e: entry threshold
  • x: exit threshold with 0≤x
  • q: spread direction, long +1 or short −1
  • Between boundaries: retain state
  • Invalidated relationship: flat

When and why to use this

Use a state machine to make the signal’s implied turnover, holding time and exposure reproducible before any ML model is introduced.

Compute the mean and scale from information available at the decision. A common convention estimates both from preceding bars and compares the current residual with that reference. Including the current bar can also be causal at its close, but must not imply execution at an earlier price.

Use hysteresis: a wider threshold to enter and a narrower threshold to exit prevents repeatedly trading around a single boundary. A time stop limits exposure to a slow convergence process; a structural stop handles a broken relationship. Neither should be chosen by repeatedly peeking at test losses.

Trade sizing should reflect residual risk and actual leg exposures. A z-score of two across two pairs need not imply equal dollar risk. When the historical scale is zero, tiny or stale, skip rather than divide by an arbitrary tiny number and create a huge signal.

zt=st−s‾t−1σ^t−1,qt={−1zt>e1zt<−e0|zt|<x
Model assumptions, derivation and arithmetic

Causal z-scores and a complete entry–exit state machine

  1. Subtract the past reference mean to measure displacement, then divide by the past scale to compare displacements across windows.
  2. A high positive residual is expensive relative to the fitted relation, so a convergence hypothesis proposes a short spread; a low residual proposes a long.
  3. Implement the branches with state: a flat position may enter, an open position exits near zero, and other observations preserve the existing direction. Invalidation overrides the signal.
Work it by hand

Past mean=1, SD=2, current residual=6 gives z=2.5. With entry 2 and exit .5, a flat strategy proposes short; at z=1 it remains short and at z=.3 it closes.

Apply it in a strategy

  • Compute residuals from the versioned hedge and statistics from an explicitly bounded historical window.
  • Log desired state separately from filled state; simulate order arrival and two-leg execution.
  • Compare fixed thresholds with a volatility- or cost-aware variant under the same validation budget.

Research deliverable

Save a decision log with timestamps, previous state, z-score, desired state, orders and realised holdings; inspect transitions by hand.

Python implementation

Self-contained teaching example. Python 3.10+; dependencies and input conventions are shown in the code and notation. Run in your own Python environment.

def spread_state(previous,z,entry=2,exit=.5,valid=True):
    if not 0<=exit<entry or previous not in (-1,0,1): raise ValueError("Invalid thresholds or state")
    if not valid: return 0
    if previous:
        return 0 if abs(z)<exit else previous
    return -1 if z>entry else 1 if z<-entry else 0

print([spread_state(0,2.5),spread_state(-1,1),spread_state(-1,.3)])

Continue learning

Statistical Arbitrage: Relative Value to Tradable Portfolios — all lessons
  1. What statistical arbitrage is—and where it applies
  2. Construct the spread: price ratios, log ratios and executable units
  3. Cointegration, reversion speed and structural breaks
  4. Causal z-scores and a complete entry–exit state machine
  5. From pairs to residual baskets and factor neutrality
  6. Two-leg backtesting, borrow, capacity and ML extensions

Quantitative finance and development glossary · Python resources and libraries · Research sources and limitations