Strategies8 min read
How to Calculate a Pairs-Trading Spread
Learn how to calculate a pairs-trading spread: align price data, estimate a training-only hedge ratio, calculate residuals, and audit units.
By TerraTrade Team

How to calculate a pairs-trading spread#
A pairs-trading spread is a calculated difference between two aligned price series. The calculation is straightforward; the choices behind it are not. Which price field did you use? Did both observations come from the same session? Was the hedge ratio estimated before the period you are evaluating? Does the resulting number represent dollars, a price residual, or something else?
This worksheet walks through those decisions without treating a small or reverting-looking residual as a trade signal. First define and align the data, then estimate coefficients on a training period, calculate residuals with those fixed coefficients, and audit the result. Whether a spread has useful statistical properties—and whether a trading strategy based on it is viable—requires separate tests.
What exactly is a pairs-trading spread?#
For a common levels-based construction, designate one instrument’s price as Y and the other’s as X, then fit the relationship:
Yₜ = α + βXₜ + εₜ
The estimated residual is Yₜ − α̂ − β̂Xₜ. Here, β̂ is the fitted slope, α̂ is the intercept when included, and the residual is the observed Y price minus the model’s fitted Y price. This is one explicit spread convention, not a universal definition of pairs trading. Cointegration research studies whether a linear combination of time series has relevant long-run statistical properties; calculating a residual alone does not establish that it does. Vol. 55, No. 2, Mar., 1987 of Econometrica | JSTOR
Complete these fields before fitting. Keeping the choices visible helps you distinguish a change in the data or model from a change in the spread itself.
- Instrument definitions: X = ________; Y = ________.
- Price field and frequency: for example, split-adjusted daily close for both series.
- Currency and adjustment convention: ________.
- Timestamp convention and time zone: ________.
- Model convention: levels or log prices; intercept included or omitted.
- Training dates: ________; later test dates: ________.
The first risk is a mismatched row, not a difficult formula. Normalize timestamps and decide what counts as the same observation before calculating the spread. In particular, check trading calendars, holidays, session definitions, and whether the instruments’ recorded closes refer to comparable times.
- Parse timestamps consistently, account for time zones, sort chronologically, and inspect duplicate timestamps. Time-series libraries provide date and time-zone handling, but the researcher still has to choose the intended matching rule. Time series / date functionality — pandas 3.0.6 documentation
- Match observations that represent the same intended market session or sampling point. A daily close in one instrument should not be silently paired with the next available close in the other.
- For a basic daily worksheet, an inner join on timestamps retains only dates present in both series. Record the dates dropped. Do not fill missing prices or carry values forward unless that is a deliberate, documented methodology.
- Split the aligned series chronologically into training (formation) data and a later test period. Do not shuffle time-series observations.
A formation-period estimate applied to a later period is a documented research design in pairs-trading literature, not proof of profitability or a guarantee that the relationship persists. Keeping estimation separate from evaluation helps prevent future information leaking into a historical test. Pairs trading: is it applicable to exchange-traded funds? - ScienceDirect
- Fix the dependent and explanatory series: regress Y on X, not whichever order happens to be convenient in code.
- Fit Yₜ = α + βXₜ + εₜ using training observations only.
- Record α̂ and β̂, the training window, the price field, and whether an intercept was included.
- Apply those training estimates to each aligned observation in the later test period. Do not refit using test-period observations if the test is intended to simulate information available after training.
Procedure 3: calculate the residual#
For each aligned date, use the same training-estimated coefficients:
Spreadₜ = Yₜ − α̂training − β̂trainingXₜ
For example, suppose a training fit produces α̂ = 2 and β̂ = 0.8. On an aligned observation with Xₜ = 50 and Yₜ = 44, the residual is 44 − 2 − (0.8 × 50) = 2. These values are illustrative arithmetic, not market data. The result does not establish that the residual is stationary, expected to revert, or suitable for a strategy.
If you choose to omit the intercept, calculate Yₜ − β̂Xₜ and label that convention. It is a different construction, not an interchangeable shortcut.
Use a small audit table alongside the spread series. Each row should be reproducible from the recorded inputs and fixed training coefficients.
| Construction or check | What to record | What it helps prevent |
|---|---|---|
| Timestamp alignment | Matched timestamp, time zone, session convention, and any match gap | Comparing observations from different times |
| Price inputs | Xₜ and Yₜ; field, currency, and adjustment method | Mixing inconsistent units or price definitions |
| Fitted model | Training window, dependent series, α̂, β̂, intercept choice | Unrecorded model changes or test-data leakage |
| Residual | Yₜ − α̂training − β̂trainingXₜ, with units labeled | Calling a residual a portfolio value or dollar-neutral spread |
| Missing observations | Dates removed or any explicit fill rule | Silent calendar mismatches or imputation |
The arithmetic inherits its units from the inputs. A number can be calculated correctly yet described incorrectly if the data are adjusted prices, logarithms, or instruments with different contract multipliers.
- If X and Y are both prices in dollars per share, β̂ has units of Y-price per unit of X-price; the residual is in the units of Y.
- If the model uses log prices, label the result a log-price residual. It is not a dollar spread.
- A regression slope is not automatically a tradeable number of shares or contracts. Any conversion to positions requires a separate, explicit sizing and contract-value calculation.
- Check whether splits, dividends, futures rolls, or other data adjustments affect comparability. Record the source convention rather than assuming the series are directly comparable.
This article addresses construction, not a complete strategy. To turn a residual into a testable strategy, state hypotheses rather than treating statistical vocabulary as a signal:
- Setup definition: a candidate pair consists of two specified, time-aligned price series and a declared residual formula. The setup is eligible for study only after the data and model choices are recorded.
- Entry hypothesis: if later research suggests a measurable deviation from a defined reference level, test a prewritten condition for entering a hypothetical position. The spread calculation alone supplies no entry threshold.
- Invalidation hypothesis: define in advance what evidence would end the test—for example, a predeclared relationship-break condition or a data-quality failure. Do not choose an invalidation rule after inspecting favorable outcomes.
- Exit hypothesis: separately test a specified exit condition, time limit, or other rule on held-out data. The residual formula itself specifies no exit.
- Failure conditions: the relationship may shift; aligned closes may not represent synchronized exposure; adjustment or roll conventions may distort comparisons; and estimated coefficients may be unstable. A residual may not exhibit the properties a strategy assumes.
A reproducible backtest should make it possible for another person—or future you—to rebuild the same spread without using information that was unavailable at the time.
- Freeze the pair-selection rule, data source, price field, timestamp convention, model form, and training window before examining test results.
- Fit α̂ and β̂ on training data only; calculate test residuals using those fixed estimates.
- Predefine any proposed entry, invalidation, and exit hypotheses, including how positions would be translated from residual units into instruments. Treat them as test rules, not recommendations.
- Evaluate the later period without refitting from future observations. If you evaluate repeated rolling fits, specify when each fit becomes available and apply it only afterward.
- Inspect residual behavior and model stability separately from hypothetical trading performance. Include realistic costs and execution assumptions in any strategy test; do not infer live results from a residual plot.
- Keep a journal record of the data version, coefficients, dates, and deviations from the test plan.
Useful journal tags describe decisions and data issues, not whether the pair later made money. A controlled vocabulary makes it easier to review whether problems cluster around alignment, model estimation, or test design.
- spread-construction
- timestamp-mismatch
- missing-data-rule
- adjustment-convention
- training-window
- hedge-ratio-refit
- intercept-choice
- units-check
- out-of-sample
A disciplined spread worksheet gives you a consistent object to analyze. It does not answer whether the relationship is stable or whether a trading rule has an edge; those questions need distinct, out-of-sample evidence.
What this calculation can—and cannot—tell you
Strengths
- ✓The formula is transparent and can be audited observation by observation.
- ✓Separating training from test data reduces one common source of look-ahead bias.
- ✓Recording timestamps, units, and model choices makes the result reproducible.
Limitations
- —The fitted relationship and residual depend on model choices, sampling, and data quality.
- —A calculated residual does not show that a pair is cointegrated, will revert, or is tradeable.
- —The regression slope is not automatically a position size or a risk measure.
Frequently asked questions#
Is a pairs-trading spread always Y minus beta times X?
Not necessarily. For a levels regression with an intercept, the residual is Yₜ − α̂ − β̂Xₜ, and it carries the units of Y. It is not automatically a dollar-neutral portfolio or a position-sizing rule.
Do I need an intercept in the regression?
No. The fitted intercept changes the residual. Ordinary least squares in statsmodels does not add one by default, so include it explicitly if that is the model you intend. statsmodels.regression.linear_model.OLS — statsmodels 0.15.0
What should I do when the instruments have different trading calendars?
Choose a documented matching convention that reflects the observations you intend to compare. For a basic daily worksheet, an inner join on shared timestamps is transparent; record dropped dates and avoid silently matching one market’s close to another’s later close.
Can I calculate the hedge ratio on the full dataset?
Estimate the coefficients on the training period and apply them to later observations if your test is meant to represent what was knowable then. Re-estimating with test data changes the experiment and can introduce look-ahead bias. Pairs trading: is it applicable to exchange-traded funds? - ScienceDirect
Does a small residual mean the pair will revert?
No. A residual is the output of a chosen model. Whether it has the statistical properties required by a particular strategy is a separate question; a residual calculation alone does not demonstrate reversion. Vol. 55, No. 2, Mar., 1987 of Econometrica | JSTOR
Summary: build the spread before you test it#
The practical sequence is simple: define the series, align timestamps, estimate the model on training data, apply fixed coefficients, and audit the units. Only then ask whether the resulting residual supports a testable hypothesis.

Sources#
- Vol. 55, No. 2, Mar., 1987 of Econometrica | JSTOR — jstor.org
- Pairs trading: is it applicable to exchange-traded funds? - ScienceDirect — doi.org
- Time series / date functionality — pandas 3.0.6 documentation — pandas.pydata.org
- statsmodels.regression.linear_model.OLS — statsmodels 0.15.0 — statsmodels.org
- https://github.com/Tjindl/pairs-trading — github.com
- https://github.com/Stermer72/pairs-trading — github.com
- https://research.cbs.dk/en/studentProjects/quantitative-trading-strategies-momentum-trading-amp-pairs-tradin/ — research.cbs.dk
- https://www.researchgate.net/publication/336813411_Dynamic_Pair_Selection_with_Machine_Learning_Clustering_Cointegration_Testing_a_Stop-Loss_Policy_and_Partial_Pair_Order_Buffering — researchgate.net
- https://www.mdpi.com/2071-1050/12/17/6791 — mdpi.com
- https://github.com/khshalnuaimi/pairs-trading — github.com
- https://www.mdpi.com/2076-3417/12/3/944 — mdpi.com
- https://pandas.pydata.org/docs/reference/api/pandas.merge_asof.html — pandas.pydata.org
- https://citeseerx.ist.psu.edu/document?doi=9eb7e587923335f73f085d2e8cb964c72e76d014&repid=rep1&type=pdf — citeseerx.ist.psu.edu
- https://www.sciencedirect.com/science/article/abs/pii/S0377221710004820 — sciencedirect.com
- https://arxiv.org/abs/2109.10662 — arxiv.org
- https://repository.rice.edu/bitstreams/e947dc21-5ed8-4be3-ab2d-40eb833770f1/download — repository.rice.edu
KEEP READING

Market Insights7 min read
How to Read Treasury Auction Results
Read Treasury auction results without turning them into a signal: high yield, WI comparison, bid-to-cover, and bidder categories—what each shows (and can’t).
Read post
Strategies7 min read
How to Calculate Session VWAP From OHLCV Data
Build session VWAP from historical OHLCV bars in a spreadsheet, with cumulative formulas, a worked example, and data-quality checks.
Read post
Strategies8 min read
How to Test a Time Stop for Intraday Trades
Test an intraday time stop against unchanged price exits with a practical worksheet for net P&L, MAE, MFE, and execution costs.
Read post