Stat Arb Explained: Signals, Costs and a Checked Python Example
Understand statistical arbitrage, pairs trading, neutrality and failure modes. Follow a checked signal-to-P&L example, vary costs and download Python and data.
On this page
Stat arb is short for statistical arbitrage: systematic trading that uses estimated relationships between assets to construct positions with an expected, uncertain payoff. Many implementations trade long and short portfolios and seek to limit market or factor exposure. A relationship can break, a hedge can be imperfect, and costs can absorb the entire edge. This guide follows the idea from a research hypothesis to a dated signal, next-session execution and a net P&L ledger.
What to know first
- Stat arb is a family of strategies. Pairs trading is one useful starting point; basket, factor-residual and cross-sectional models answer different research questions.
- Equal long and short dollar amounts establish dollar neutrality at entry. They do not establish zero market beta, zero sector risk or a risk-free payoff.
- A signal computed from a closing price must use a later executable price. The example observes yesterday’s close, enters at today’s open and exits at today’s close.
- The downloadable example uses invented prices, frozen training parameters, both trade legs, entry and exit costs, and a simplified short-borrow charge.
- With this specific synthetic path, 5 bp per dollar traded and 6% annual borrow leave +2.788668%; 50 bp produce −1.720162%. These are accounting outputs, not evidence of a profitable strategy.
What does stat arb mean?
The abbreviation usually refers to statistical arbitrage in quantitative finance. The trader estimates a relationship, identifies a deviation, and takes a position whose expected payoff depends on that deviation resolving. A model might compare an equity with its sector, a security with a basket, or two related instruments.
The word statistical matters. An estimated mean or conditional forecast is uncertain, and a cheap-looking asset can become cheaper. Classical arbitrage is a stronger claim about a payoff under specified prices, trading and funding conditions. Stat arb usually exposes capital to an uncertain outcome.
Consider two businesses exposed to a similar economic driver. One price falls sharply while the other barely moves. A researcher might investigate whether temporary order flow caused the difference. An earnings surprise or permanent change in profitability could instead explain it. The price gap is an observation; “temporary mispricing” is a hypothesis to test.
Many implementations aim for low market exposure. Some use short-horizon reversals, while others combine signals or forecast residual returns. Holding period and technology requirements follow the actual strategy. Daily statistical research does not inherently require co-location or sub-millisecond execution. Avellaneda and Lee’s research paper describes market-neutral models based on PCA and sector-ETF residuals. Its historical results belong to its own datasets and assumptions; they are not a present-day profit forecast.
Pairs trading, baskets and cross-sectional stat arb
Pairs trading uses a relationship between two instruments. The simplest long–short example makes the arithmetic visible, but a single pair has concentration risk and is not an institutional portfolio in miniature. Many positions can also share the same hidden exposure.
| Approach | Research object | Position construction | Main question before trusting it |
|---|---|---|---|
| Two-asset pairs | A chosen spread or relative-price relationship | Long one leg, short the other with a defined hedge ratio | Does the relationship persist beyond the formation sample? |
| Basket relative value | One instrument relative to several comparators | Trade the instrument against a weighted basket | Are basket weights stable and genuinely hedging the intended risks? |
| Cross-sectional reversal | Returns relative to peers or risk factors | Rank a point-in-time universe and constrain a long–short book | Are reversals robust after costs, event filters and universe changes? |
| Factor-residual modelling | The part of returns unexplained by estimated factors | Forecast residual returns and control factor exposures | Do the fitted factors remove the intended risk without using future data? |
| Learned residual signals | Conditional forecasts after a risk representation | Translate forecasts into cost-aware constrained weights | Does added model complexity improve untouched evaluation data? |
These descriptions define research tasks, not universal rules for holding periods, Sharpe ratios or capital requirements. An ETF creation/redemption trade involves an operational mechanism different from a statistical ETF-residual forecast. A product’s market price differing from a reported NAV does not automatically create an executable risk-free trade.
For a deeper research example beyond basic pairs, Guijarro-Ordonez, Pelger and Zanotti separate residual-portfolio construction, signal modelling and trading policy in a learned framework. That is a useful way to separate assumptions, even if your first implementation is a small transparent model.
Start with a hypothesis you can explain, a baseline and an accounting convention. Increasing the number of assets or using a neural network adds decisions to validate. It does not repair a weak economic explanation or a timing error.
How a stat arb system moves from data to orders
The signal is only one layer. The complete process must connect the observations available at a particular time to executable positions and an auditable result.
- Define the tradable universe. Record exchange, currency, listing dates, liquidity, corporate actions and short availability. A current constituent list applied to old dates can remove failed firms and create survivorship bias.
- Build point-in-time features. Store observation and availability times. A financial statement released in April cannot inform a January trade just because the accounting period ended in December.
- Estimate a relationship on training data. Fit hedge ratios, means, variances and factor loadings without including the evaluation period. Choose normalisation and threshold rules before inspecting evaluation outcomes.
- Forecast and size. Translate a forecast into weights subject to risk, borrow, liquidity and turnover constraints. A large z-score alone does not tell you the expected dollar profit or a safe leverage level.
- Simulate execution. Specify the first executable price after the signal, partial fills, order sizes and the costs on each leg. Record what happens when one leg fails to fill.
- Evaluate and monitor. Separate gross return, execution cost, borrow, financing and net return. Inspect drawdowns, concentration, factor exposures, subperiods and sensitivity to less favourable assumptions.
A compact cost-aware allocation objective can be written as expected return − risk penalty − trading-cost penalty, with separate constraints on net dollars, estimated beta, sectors, gross exposure and individual positions. Its inputs are estimates. An optimiser can solve the chosen objective accurately while the underlying assumptions are wrong.
One useful operational check is a missing-data event. If one asset is halted or a borrow quote is unavailable, does the strategy retain yesterday’s position, close the available leg or abstain? The decision belongs in the research specification before it becomes a surprising live exposure.
Dollar neutral, beta neutral and cointegrated are different
Suppose weights are +0.5 in A and −0.5 in B, expressed as fractions of account equity. Their sum is zero and their absolute sum is one. That means no net dollars and gross exposure of 100% at entry.
If A’s estimated market beta is 1.4 and B’s is 0.8, the portfolio beta is 0.5 × 1.4 − 0.5 × 0.8 = 0.30. The dollar-neutral portfolio still carries positive market exposure. Price changes also cause its dollar balance to drift after entry.
| Term | What it measures | What it does not prove |
|---|---|---|
| Dollar neutrality | Signed position notionals sum to zero | Zero beta or protection from a sector shock |
| Beta neutrality | Estimated market sensitivity is near zero | Stable beta in a crisis or zero exposure to other factors |
| Sector/factor neutrality | Selected exposures meet specified limits | That omitted exposures are absent |
| Correlation | Co-movement over a chosen sample | A stable equilibrium of price levels |
| Cointegration | A stationary linear combination under the model’s integration assumptions | Tradable profit after costs or immunity to a structural break |
Correlation between returns and cointegration of price levels answer different questions. A high return correlation can coexist with a spread that drifts. A pair that passed a formation-period test can fail in the next regime.
The statsmodels cointegration documentation states that its augmented Engle–Granger test has a null of no cointegration and assumes I(1) input series. Use the appropriate residual-test critical values and document trend and lag choices. Screening thousands of pairs and retaining the smallest p-values also creates a multiple-testing problem.
The accounting example below tests neither integration order nor cointegration. It deliberately uses a constant comparator and invented prices to isolate timing and cost calculations. Six training observations would be inadequate evidence for a real relationship.
A dated example: yesterday’s signal, today’s trade
Every price in this example is invented. The dates make the information order explicit; they do not turn synthetic values into historical quotes. This is a repeatable accounting exercise.
Formation dates are 14, 15, 16, 17, 18 and 21 September 2026. A closes at 99, 100, 101, 99, 100, 101; B closes at 100 each day. Define spread as A / B − 1. Its training mean is 0 and its population standard deviation is 0.008164965809277268. Both remain frozen during evaluation.
At each evaluation opening, use the previous session’s close:
- z greater than 1: short A with weight −0.5, long B with weight +0.5.
- z less than −1: long A with weight +0.5, short B with weight −0.5.
- Otherwise: hold cash for that session.
- Enter at the new session’s open and close both positions at its close. There is no overnight position. The opening/closing fill assumptions are optimistic; costs are explicit.
On 22 September the available A close is 101, so z is 1.224745 and the signal shorts A. A then opens at 104 and closes at 102. With B unchanged, gross return is −0.5 × (102 / 104 − 1) = 0.009615384615, or 96.154 bp on equity.
Costs apply to executed notional. Entry turnover is 1. Closing turnover is 0.5 × 102/104 + 0.5 = 0.990384615385. Total turnover is therefore 1.990384615385. At 5 bp per dollar traded, execution consumes 9.952 bp. A simplified borrow charge of 0.5 × 6% / 252 consumes 1.190 bp. The session’s net return is 85.011 bp.
The next session illustrates the failure case: A rises from 103 to 106 while the strategy is short. The earlier positive z-score does not prevent a loss.
| Synthetic date | Prior-close z | A open → close | A weight | Gross, bp | Turnover / equity | Execution, bp | Borrow, bp | Net, bp |
|---|---|---|---|---|---|---|---|---|
| 2026-09-22 | 1.225 | 104 → 102 | −0.50 | 96.154 | 1.9904 | 9.952 | 1.190 | 85.011 |
| 2026-09-23 | 2.449 | 103 → 106 | −0.50 | −145.631 | 2.0146 | 10.073 | 1.190 | −156.894 |
| 2026-09-24 | 7.348 | 106 → 101 | −0.50 | 235.849 | 1.9764 | 9.882 | 1.190 | 224.777 |
| 2026-09-25 | 1.225 | 102 → 100 | −0.50 | 98.039 | 1.9902 | 9.951 | 1.190 | 86.898 |
| 2026-09-28 | 0.000 | 100 → 98 | 0.00 | 0.000 | 0.0000 | 0.000 | 0.000 | 0.000 |
| 2026-09-29 | −2.449 | 98 → 99 | +0.50 | 51.020 | 2.0051 | 10.026 | 1.190 | 39.804 |
B opens and closes at 100 throughout. Weights reset relative to beginning-of-session equity. Compounding each net return yields +2.788668% across these six synthetic sessions; gross compounded return is +3.360799%. Summing daily returns is a different calculation. No annualised Sharpe or expected annual return is justified by this designed miniature.
Download the synthetic prices, full precision ledger and verified outputs to inspect each calculation.
How turnover and short borrow change the result
A basis point is 0.01%, or 0.0001 as a decimal. “Five basis points of cost” is incomplete unless you identify the denominator and whether the figure is per side or round trip.
Here the cost input is per dollar executed on each entry and exit, applied to both legs. A portfolio with 100% gross exposure usually trades approximately 200% of equity when it opens and completely closes. Closing notionals drift with prices, so the code uses the actual closing-price ratios.
For each session:
net return = weighted asset returns − turnover × cost_bp / 10,000 − short entry weight × annual borrow rate / 252
The borrow convention is intentionally simple. Actual charging periods, rates, collateral terms and rebates depend on the instrument and broker; an intraday position may be billed differently. Financing, taxes, dividend obligations, locate fees and asymmetric fill costs are not modelled here.
| Execution cost per dollar traded | Annual borrow assumption | Six-session net compounded result |
|---|---|---|
| 0 bp | 6% | +3.299690% |
| 5 bp | 6% | +2.788668% |
| 10 bp | 6% | +2.279670% |
| 25 bp | 6% | +0.764761% |
| 50 bp | 6% | −1.720162% |
Zero execution cost still leaves a borrow deduction. Zero execution and zero borrow exactly reproduce the gross path. Increasing costs changes net performance while leaving the signals and gross outcomes fixed.
The explorer below recalculates the same verified ledger. Use it to understand cost units and compounding. Its defaults are teaching assumptions, not claims about available institutional or retail execution.
Reprice the synthetic ledger
Same signals and prices. Change the cost assumptions to see their effect on the six-session result. All observations are invented.
- Gross compounded
- +3.360799%
- Net compounded
- +2.788668%
| Synthetic date | Gross, bp | Execution, bp | Borrow, bp | Net, bp |
|---|---|---|---|---|
| 2026-09-22 | 96.154 | 9.952 | 1.190 | 85.011 |
| 2026-09-23 | -145.631 | 10.073 | 1.190 | -156.894 |
| 2026-09-24 | 235.849 | 9.882 | 1.190 | 224.777 |
| 2026-09-25 | 98.039 | 9.951 | 1.190 | 86.898 |
| 2026-09-28 | 0.000 | 0.000 | 0.000 | 0.000 |
| 2026-09-29 | 51.020 | 10.026 | 1.190 | 39.804 |
Execution is charged on entry and actual closing notionals. Borrow uses short entry weight × annual rate / 252. Signals stay fixed. Neither this path nor its parameters estimate live profitability.
Run the complete minimal Python calculation
This version uses only the Python standard library and includes all its data. It runs in Python 3.10 or later. The downloadable version adds the full ledger, exports and accounting checks; it was run locally with Python 3.14.0.
from statistics import mean, pstdev
training = [99, 100, 101, 99, 100, 101]
spreads = [a / 100 - 1 for a in training]
mu, sd = mean(spreads), pstdev(spreads)
days = [
("2026-09-22", 104, 102),
("2026-09-23", 103, 106),
("2026-09-24", 106, 101),
("2026-09-25", 102, 100),
("2026-09-28", 100, 98),
("2026-09-29", 98, 99),
]
previous_close, nav = training[-1], 1.0
for date, opening, closing in days:
z = (previous_close / 100 - 1 - mu) / sd
direction = -1 if z > 1 else (1 if z < -1 else 0)
wa, wb = 0.5 * direction, -0.5 * direction
gross = wa * (closing / opening - 1) # B remains 100
turnover = abs(wa) * (1 + closing / opening) + 2 * abs(wb)
execution = turnover * 5 / 10000
borrow = max(-wa, -wb, 0) * 0.06 / 252
net = gross - execution - borrow
nav *= 1 + net
print(date, f"z={z:.3f}", f"net={net*10000:.3f} bp")
previous_close = closing
print(f"Net compounded return: {nav-1:.6%}")
Expected final line:
Net compounded return: 2.788668%
Download the checked Python file. Run python stat-arb-example.py to print the ledger. In a folder without existing outputs, python stat-arb-example.py --export writes JSON and two CSV files beside the script. Exports use exclusive file creation to avoid replacing another result.
The checked version independently verifies first-session P&L and turnover, a losing divergence session, the no-position session, cost monotonicity and the equality of zero-cost results with gross results. It also changes a future close and confirms that the earlier position is unchanged. That check catches a common information-timing mistake.
The toy rule exits at every close. A strategy holding until a spread threshold is crossed needs a different state machine and overnight accounting. Copying this intraday P&L formula into an overnight strategy would omit the close-to-open return. A trading specification must agree with the backtest’s position timing.
What a credible research backtest must add
A working example demonstrates the calculation. It does not validate the hypothesis. Moving to actual prices requires more evidence and a research plan that survives unfavourable results.
Use chronological separation. Fit on a formation sample, choose the model on a separate validation period and preserve a final evaluation period. If you inspect that final period and redesign the strategy, it has become development data. In walk-forward evaluation, re-estimate only with information available before each new test window.
Record the search process. Count pairs, universes, features, windows and thresholds tried. One attractive Sharpe selected from many trials can arise without predictive power. Report the baseline and failed variants alongside the selected model.
Model executable instruments. Adjusted prices may be useful for signal research while actual traded prices and cash flows are needed for accounting. Include splits, dividends, delistings, halts and timezone alignment. A close recorded in another market after your decision time is future information.
Evaluate the distribution of outcomes. Report net results by period and instrument, exposure, turnover, drawdown depth and duration, and how much P&L comes from a few events. Overlapping trades create dependence; uncertainty estimates should respect the time structure.
Stress implementation. Increase spread and market impact, delay entry, remove unavailable shorts and simulate failed hedge fills. Compare capacity at different order sizes. A cost model that scales linearly forever misses liquidity limits.
No universal rule such as “net Sharpe above 1 proves an edge” can replace these checks. An observed ratio depends on the sample, return definition, dependence and the choices made before reporting it. Neutral factor loadings also do not by themselves establish predictive alpha.
The Pro walk-forward validation lesson offers a structured continuation for research practice. The checks above remain fully available here; no paid lesson is needed to understand the example’s accounting.
Why statistical arbitrage fails
The most informative stress case is often a relationship that stops reverting.
A structural break
A merger, financing change or new information can make the old equilibrium obsolete. A wider spread may signal a changed business rather than a better entry. Monitor the model’s residual behaviour and define abstention or review conditions before increasing risk.
Crowding and forced exits
Different funds can hold similar trades. A forced liquidation pushes prices away from estimated fair relationships, causes losses for other holders and may trigger their own reductions. Khandani and Lo’s 2007 investigation proposed an unwinding explanation for the August 2007 quant losses using fund data and strategy simulations. It is a research hypothesis grounded in that evidence, not a complete observation of every participant’s book.
A zero net-dollar constraint does not protect against shared positions, disappearing liquidity or financing pressure. Stress correlated exits as well as broad-market shocks.
Short availability and costs
A short can become expensive or unavailable. Dividends create additional cash obligations for equity shorts, and an early recall can force an exit before expected convergence. FINRA’s explanation of short selling describes borrowing shares, margin requirements and the potential loss when repurchasing at a higher price. Specific borrow terms need a live broker agreement.
Execution and capacity
A small backtest order may fit inside a quoted spread; a larger portfolio may move the market. One leg can fill while the hedge does not. A closing auction can be disrupted. These events change the actual exposure and cannot be repaired by subtracting a uniform cost after the fact.
Hidden model and data errors
A good-looking result can come from full-sample normalisation, future constituents, revised data, stale quotes or an incorrect short-return formula. Inspect a few sessions at the share and cash-flow level before trusting aggregate statistics. The first question is whether the simulator represents the specified trade.
A practical first stat arb research project
Aim for a compact research record that another person can reproduce.
- Reproduce the synthetic ledger. Explain why the signal uses the previous close, why the opening gap is not earned, and why both entry and exit incur costs.
- Specify one real hypothesis. Choose related instruments and explain why a deviation might be temporary. Record an alternative explanation that would invalidate the trade.
- Build a dated dataset. Preserve raw data, corporate-action decisions, timezone rules and the universe at each date. State whether short availability is observed or assumed.
- Choose a transparent baseline. Freeze formation length, hedge convention, entry and exit rules, and risk limits. Compare against a cash or simple residual baseline using the same cost assumptions.
- Run chronological evaluation. Save decisions made before each test window. Inspect gross/net divergence, exposures, losing periods and parameter sensitivity.
- Write a one-page verdict. State what survived, what failed, what remains assumed and what evidence would change the conclusion. A negative result with correct accounting is useful research.
For research roles, a small defensible study demonstrates more than a complicated chart without its data. The important skills are statistical reasoning, point-in-time data handling, position accounting and explaining uncertainty. Employer-specific strategies and interview requirements must come from that employer’s own material.
Use the trading-cost calculator to explore a separate gross-to-net scenario, or start with returns and drawdown analysis to learn return conventions. These tools support individual research tasks; they are not a full statistical-arbitrage execution platform.
Frequently asked questions
Is statistical arbitrage risk-free?
No. The forecast is estimated and a relationship can break. Long and short positions can both lose, borrow can become unavailable, and execution can fail. Even a beta-neutral estimate is model-dependent. The term describes a statistical trading approach rather than a guaranteed arbitrage payoff.
Is stat arb the same as pairs trading?
Pairs trading is one form of statistical relative-value trading using two instruments. Broader stat arb can use baskets, factor residuals and cross-sectional portfolios. A two-asset example is useful for understanding accounting, but scaling it requires portfolio-level risk, dependence and execution controls.
Do I need cointegration for every statistical arbitrage strategy?
No. Cointegration is relevant to certain price-level spread models. Cross-sectional return forecasts and other residual approaches have different assumptions. If you use a cointegration test, check integration order, formation-only fitting, trend and lag choices, and the effect of screening many candidates. Passing a test does not establish profitable execution.
Does stat arb always use high-frequency trading?
No. Some implementations operate at very short horizons, but the family also includes daily and longer-horizon research. Required data, infrastructure and cost models depend on the signal and holding period. A daily accounting exercise does not demonstrate the feasibility of a high-frequency system.
Can I use this example as a live trading strategy?
The example is designed to explain timing, turnover and costs. All prices are invented, the comparator is constant, and no relationship or predictive edge has been established. It assumes full open and close fills, flat overnight positions and a simplified borrow charge. It omits operational requirements needed for a live system.
Is stat arb still profitable in 2026?
There is no single return for a strategy family. A present-day profitability claim needs dated data, implementation and financing assumptions, capacity estimates, an independent evaluation period and uncertainty around net outcomes. Historical academic performance, a selected fund return or this synthetic exercise cannot answer that question for a new model.
How much capital and which programming language do I need?
There is no universal capital minimum. Margin, minimum position sizes, borrow, capacity, drawdown reserves and infrastructure costs depend on the instruments and implementation. Python is useful for research, and this exercise needs only the standard library. Production language and infrastructure choices should follow measurable operational requirements.
Why do the weights not earn the previous close-to-open move?
The signal is observed at the previous close, but the assumed entry is the next open. Positions do not exist during that opening gap. The model earns only that session’s open-to-close moves and exits at the close. An overnight strategy needs explicit holdings and separate accounting for overnight returns.
Sources and verification
Checked October 3, 2026. Each note identifies the source’s purpose and limitations. Open employer pages for current vacancies and use research papers with their own dates, datasets and assumptions.
- Avellaneda and Lee — Statistical Arbitrage in the U.S. Equities Market
NYU-hosted author manuscript, 15 June 2009, of the 2010 paper. Supports the residual and factor-model research context. Historical estimates are not copied as contemporary expected returns. Checked 3 October 2026.
- Guijarro-Ordonez, Pelger and Zanotti — Deep Learning Statistical Arbitrage
Primary research separating residual construction, signals and trading policy. Cited as a framework, without representing its historical results as current profitability.
- Khandani and Lo — What Happened to the Quants in August 2007?
MIT-hosted primary study. Supports the dated unwind hypothesis and crowding discussion. Hypothesis is explicitly distinguished from comprehensive observation of fund positions.
- statsmodels — augmented Engle–Granger cointegration test
Official API reference for the no-cointegration null and I(1) input assumption. This page’s miniature does not claim to perform that test.
- FINRA — stocks and short selling
Primary investor education on borrowing shares, margin and short-sale risk. Actual fees and financing conventions must be obtained from the broker and instrument terms.
- Original checked example, synthetic data and accounting ledger
Locally executed Python 3.14.0 output on 3 October 2026. All observations are invented; results demonstrate arithmetic and timing. Code, data and exact outputs are freely downloadable.