Home › Templates › Pairs trading spreadsheet
Pairs Trading Spreadsheet: Hedge Ratio, Z-Score Signals and Trade Log
A free pairs trading spreadsheet for Excel and Google Sheets. Paste daily closes for two stocks (up to 500 rows). The sheet estimates the hedge ratio by regression, builds the spread and its rolling z-score, applies your entry, exit and stop levels, sizes both legs dollar-neutral or beta-neutral, and logs every round trip with P/L per leg, commissions and short borrow fees. It also reports correlation, the half-life of mean reversion and a cointegration test statistic.
Use it in Google Sheets: choose File → Import → Upload in Sheets and pick the .xlsx, or upload it to Google Drive and open it with Google Sheets. No sign-up, no add-in, no price feed: you paste the prices.
| # | Spread | Entry | Exit | Days | z in | z out | Reason | Leg A | Leg B | Costs | Net P/L |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | Short | 2025-11-12 | 2025-11-17 | 5 | +2.69 | +0.46 | Exit | $60.30 | −$165.15 | $11.78 | −$116.63 |
| 2 | Short | 2025-11-19 | 2025-11-28 | 9 | +2.57 | +0.31 | Exit | $491.92 | −$349.44 | $13.11 | $129.37 |
| 3 | Long | 2025-12-19 | 2025-12-24 | 5 | −2.22 | −0.24 | Exit | $254.52 | −$106.43 | $12.31 | $135.78 |
| 4 | Long | 2026-01-01 | 2026-01-07 | 6 | −2.20 | +0.21 | Exit | $714.87 | −$343.68 | $12.78 | $358.41 |
| 5 | Short | 2026-02-10 | 2026-03-02 | 20 | +2.15 | −0.25 | Exit | $460.00 | −$339.45 | $17.73 | $102.82 |
| 6 | Long | 2026-03-17 | 2026-04-02 | 16 | −2.41 | −0.50 | Exit | $742.22 | −$659.75 | $18.30 | $64.17 |
| 7 | Short | 2026-04-13 | 2026-04-22 | 9 | +2.50 | +0.46 | Exit | $190.74 | $107.01 | $13.22 | $284.53 |
| 8 | Long | 2026-05-27 | 2026-06-15 | 19 | −2.33 | −0.17 | Exit | $937.60 | −$640.80 | $19.20 | $277.60 |
| 9 | Long | 2026-06-25 | 2026-06-29 | 4 | −2.01 | −0.27 | Exit | −$179.19 | $159.84 | $10.82 | −$30.17 |
| 10 | Short | 2026-07-09 | 2026-07-15 | 6 | +2.22 | +3.69 | Stop | −$1,148.40 | −$194.88 | $11.08 | −$1,354.36 |
| 11 | Short | 2026-09-01 | 2026-09-02 | 1 | +2.12 | −0.30 | Exit | $210.94 | −$125.87 | $7.47 | $77.60 |
| 12 | Long | 2026-09-07 | 2026-09-16 | 9 | −2.46 | −0.22 | Exit | $36.09 | $175.16 | $11.67 | $199.58 |
| Total, 12 trades (9 above 0, 1 stop) | $128.72 | ||||||||||
What pairs trading is
Pairs trading buys one stock and shorts a related one when the gap between them is unusually wide, then closes both when the gap narrows. The bet is on the spread, not on the market. The best-known academic test describes the rule like this:
“We open a position in a pair when prices diverge by more than two historical standard deviations, as estimated during the pairs formation period. We unwind the position at the next crossing of the prices.”Gatev, Goetzmann and Rouwenhorst, NBER Working Paper 7032 (1999)
The published version, “Pairs Trading: Performance of a Relative-Value Arbitrage Rule” (Review of Financial Studies 19(3), 2006, pp. 797–827, doi:10.1093/rfs/hhj020), tested US stocks “with daily data over 1962–2002” and paired stocks by “minimum distance between normalized historical prices” (abstract on EconPapers). In the working paper, pairs were formed over twelve months and traded over the next six.
This template uses a regression variant that many traders use instead of the distance method: a log-price hedge ratio, a rolling z-score of the spread, and explicit exit and stop levels. It is a different rule from the paper's, so the paper's results do not carry over to it.
What's inside the spreadsheet
| Tab | What it does |
|---|---|
| Start here | Steps, formulas, colour key, limits, sources, disclaimer. Says the Example data is synthetic. |
| Data | Yellow settings (rows 4–17) and an empty paste area: date, price A, price B from row 35, up to 500 rows. |
| Signals | Results block (beta, alpha, R², correlations, half-life, cointegration t and critical values, data and settings checks) and one formula row per price row: ln prices, spread, rolling mean and SD, z-score, signal, stop lock, executed position. |
| Trade log | Up to 60 round trips: direction, dates, z in and out, exit reason, prices, shares, P/L of each leg, commissions, borrow fee, net P/L, % of gross exposure, running total. |
| Example | The same model filled with a 500-row synthetic pair, including a deliberate regime break. |
| Dashboard | Your data next to the Example: pair statistics, trade counts, net P/L, costs, latest z-score and position, plus two native z-score charts with the bands. |
Settings
| Setting | Default | What it controls |
|---|---|---|
| Rolling window W | 20 rows | Rows in the rolling mean and SD of the spread. |
| Entry / exit / stop | |z| 2.0 / 0.5 / 3.5 | Open beyond ±2, close back inside ±0.5, cut beyond ±3.5. After a stop, no new entry until |z| ≤ exit. |
| Formation rows F | 250 | Rows used for beta, half-life and the test. Trades start after row F. Blank = all rows (flagged as in-sample). |
| Execution | Next row close | Trade at the close after the signal, or at the signal's own close. |
| Sizing | Beta-neutral | $beta of B per $1 of A, or equal dollars (dollar-neutral). |
| Dollars in leg A | $10,000 | Shares A = INT(amount ÷ price A). |
| Commissions | $0.005/share, $1 min | Per order; 4 orders per round trip. |
| Borrow fee, day count | 1.5% a year, 360 | On the short leg's entry value, per calendar day held. |
How to use it
- Download daily closes for two stocks over the same dates. Use adjusted closes if your source has them, and the same source for both.
- On the Data tab, paste date, price A and price B from row 35, oldest first, with no blank rows. Paste values only.
- Set the formation rows to roughly the first half of your history (it must be below your number of rows), then the window and z levels.
- On Signals, check that the data check (E5) and settings check (E6) say OK.
- Read the cointegration result and half-life before the trade log. If the test shows no evidence of cointegration, the z-score signals have little basis.
- Read the Trade log and Dashboard. Change one setting at a time and note how much results move.
The formulas
These are the formulas on the Signals tab (row 35 is the first data row; settings live on Data). Every column is wrapped in IF($A35="","",…) so empty rows stay blank. No macros, no array formulas, no OFFSET or INDIRECT.
| Result | Formula in the file |
|---|---|
| Hedge ratio beta | =SLOPE(INDEX($E$35:$E$534,1):INDEX($E$35:$E$534,F), INDEX($F$35:$F$534,1):INDEX($F$35:$F$534,F)) (ln A on ln B, first F rows); alpha with INTERCEPT |
| Spread | =E35-beta*F35-alpha |
| Rolling mean, SD | =AVERAGE(INDEX($G$35:$G$534,A35-W+1):G35) and the same with STDEV |
| z-score | =(G35-H35)/I35 |
| Signal position | flat → −1 if z>=entry and z<stop; +1 if z<=-entry and z>-stop. Long (+1) → 0 if z>=-exit or z<=-stop. Short (−1) → 0 if z<=exit or z>=stop. |
| Executed position | =IF(lag=1,N(L34),L35): the previous row's signal when you trade at the next close |
| Shares | =INT(amount/A_entry); B: =INT(ratio*amount/B_entry), ratio = beta or 1 |
| P/L per leg | A: =side*sharesA*(A_exit-A_entry); B: =-side*sharesB*(B_exit-B_entry) |
| Commissions | =2*MAX(min,per_share*sharesA)+2*MAX(min,per_share*sharesB) |
| Borrow fee | =IF(side=1,sharesB*B_entry,sharesA*A_entry)*rate*days/day_count |
| Half-life | =-LN(2)/SLOPE(Δspread rows 2..F, previous spread rows 2..F) |
| Cointegration t | =b/(STEYX(Δspread, previous spread)/SQRT(DEVSQ(previous spread))) |
Dollar-neutral or beta-neutral
The spread is ln A − beta × ln B. A 1% move in B moves the spread by beta × 1%, so holding $beta of B for each $1 of A makes the dollar P/L track the spread. That is the beta-neutral option. Dollar-neutral holds equal dollars in both legs; it is simpler and is closer to the one-dollar-long, one-dollar-short pairs in the Gatev study, but it leaves a net exposure of (1 − beta) to B's moves. Shares are rounded down, so legs are never exactly balanced.
Half-life and the cointegration test
Engle and Granger defined the idea that makes pairs trading work: series that each wander, but whose combination does not. In their words, a vector of series “is said to be cointegrated with cointegrating vector a if each element is stationary only after differencing while linear combinations a′xt are themselves stationary” (“Co-Integration and Error Correction: Representation, Estimation, and Testing”, Econometrica 55(2), 1987, pp. 251–276; abstract on EconPapers).
The sheet runs one regression on the formation rows: the change in the spread on the previous spread, Δst = c + b × st−1. Two numbers come out of it.
- Half-life. If b is negative, a gap shrinks by a factor (1 + b) each row. Treating the spread as an Ornstein–Uhlenbeck (mean-reverting) process gives the usual approximation −ln(2) ÷ b; the exact discrete answer is ln(0.5) ÷ ln(1 + b). Both are shown.
- Test statistic. t = b ÷ se(b), an Engle–Granger style test. It is compared with critical values from MacKinnon's response surfaces (Queen’s Economics Department Working Paper 1227, 2010, Table 2, N = 2, constant): 5% = −3.33613 − 6.1101/T − 6.823/T², 10% = −3.04445 − 4.2412/T − 2.720/T², 1% = −3.89644 − 10.9519/T − 22.527/T². A t below the critical value rejects “no cointegration”.
In the example, b = -0.1224, so the half-life is 5.7 rows (exact 5.3), and t = -3.79 against a 5% value of -3.36 for T = 249. The data were simulated with a true half-life of 9.6 rows, so the estimate is off by about 40% even on 250 clean rows. Treat a half-life as a rough scale, not a timer.
What the test does not do. MacKinnon notes that the test value changes with which series is the regressand, so try swapping A and B when the result is close. The sheet uses no lagged differences (not an augmented test), and the critical values assume the errors are independent. A pass on the formation rows is evidence about the past, not a guarantee about the trading rows.
Worked example from the sample data
Example settings: W = 20, entry 2.0, exit 0.5, stop 3.5, formation rows 250, next-row execution, beta-neutral, $10,000 in leg A, $0.005 a share with a $1 minimum, 1.5% borrow fee on a 360-day count.
Trade 4 (exit). On row 303 the z-score fell to −2.20, below −2. The sheet bought the spread at the next close (row 304): 611 shares of A at $16.34 and 358 shares of B short at $34.51 (beta × $10,000 ÷ $34.51, rounded down). z was back above −0.5 on row 307, so it closed on row 308. Leg A made $714.87, leg B lost $343.68, costs were $9.69 commissions and $3.09 borrow fee: net $358.41.
| Trade 10: the stop | Calculation | Result |
|---|---|---|
| Signal | row 438, z = +2.22 ≥ 2: short the spread | — |
| Entry (row 439 close) | short 522 A at $19.13; buy 336 B at $36.83 | — |
| Stop signal | row 442, z = +3.69 ≥ 3.5 (the synthetic jump) | — |
| Leg A | −1 × 522 × ($21.33 − $19.13) | −$1,148.40 |
| Leg B | +1 × 336 × ($36.25 − $36.83) | −$194.88 |
| Commissions | 2 × max($1, 0.005 × 522) + 2 × max($1, 0.005 × 336) | $8.58 |
| Borrow fee | 522 × $19.13 × 1.5% × 6 ÷ 360 | $2.50 |
| Net P/L | legs − costs | −$1,354.36 |
Over rows 251–500 the example makes 12 trades: 9 end above 0, and the one stop loses $1,354.36, which wipes out most of the $1,629.88 that the 9 winning trades made together, leaving $128.72 after $108.25 of commissions and $51.20 of borrow fees. The spread was built to mean-revert, and one break still took most of the profit.
Correlation is not cointegration
High correlation is the most common reason people pick a pair, and it is weak evidence. Two trending prices correlate even with no link between them. A check you can repeat: two independent random walks with the same upward drift (500 rows, Python seed 7, the same settings as the example) give a correlation of log prices of 0.93, a correlation of daily returns of 0.06, and a cointegration t of -2.16, which does not get below even the 10% critical value of -3.06. The sheet still reports a “half-life” of 17.9 rows for that pair, which is why the test comes before the half-life.
The example pair, by contrast, shows 0.985 for log prices, 0.829 for returns and passes the 5% test, because it was simulated as cointegrated.
Look-ahead bias and regime breaks
- Hedge ratio fitted on the same rows you trade. If beta comes from all 500 rows, every trade “knew” the future relationship. Leave the formation rows blank and the sheet says “In sample: beta uses all rows (look-ahead bias)”. The default keeps rows 1–250 for estimation and trades only rows 251–500.
- Trading at the signal close. The z-score uses the close, so trading at that same close assumes you could act on a price you only see at the end. Gatev, Goetzmann and Rouwenhorst checked this: “we explore the effect of waiting a day before initiating a position,” and “The average excess returns drop by about 200 basis points” (NBER w7032). The template's default is the next row's close.
- Regime breaks. Mergers, a new business line, an index change or a takeover bid can end a relationship. The example's rows 420–449 drift and row 442 jumps; the rolling mean partly follows the drift, so the z-score understates it, and the stop takes the loss. A stop limits a break; it cannot prevent it.
- Overfitting. Trying many windows and z levels on the same history and keeping the best one makes the result look better than any future trade will be.
Short-side costs
Every pairs trade has a short leg. Investor.gov notes that when you short, “your brokerage firm will charge you interest on the loan, and you are subject to the margin rules,” and “If the stock you borrow pays a dividend, you must pay the dividend to the person or firm making the loan” (Investor Bulletin: An Introduction to Short Sales). The template charges a borrow fee on the short leg and commissions on all four orders. Dividends owed on the short leg, margin interest and slippage are not modelled; use adjusted prices to keep dividends from showing up as fake spread moves. For a full short-side ledger see the short selling spreadsheet.
Common mistakes
- Choosing pairs by correlation alone. Run the cointegration test and look at the spread chart.
- Mismatched dates. Both prices on a row must be the same day's close. One missing day shifts every return.
- Raw prices across a split. A 2-for-1 split looks like a 50% crash. Use split-adjusted closes.
- Too few formation rows. Fifty rows give a noisy beta and a noisier half-life. The example's half-life estimate is off by about 40% with 250 rows.
- Window much shorter than the half-life. If gaps take 30 rows to halve and the window is 10, the rolling mean chases the spread and signals fade.
- Ignoring the borrow fee. Hard-to-borrow stocks can charge far more than the 1.5% in the example. Check your broker's rate for the short leg.
Limits
Daily closes only; you paste the prices. One hedge ratio for the whole trading period (no rolling re-estimation, no Kalman filter) and no rebalancing during a trade. The cointegration test has no lagged differences and uses one regression direction. Fills are at closing prices with no slippage or bid-ask spread. Dividends on the short leg, margin interest, taxes and broker recalls are not included. Calendar days drive the borrow fee; rows drive the half-life. US-style per-share commissions; one currency.
FAQ
How do you calculate the hedge ratio for pairs trading?
Regress the log price of stock A on the log price of stock B over a formation window. The slope is the hedge ratio: in Excel, =SLOPE(ln A range, ln B range), with =INTERCEPT for the constant. The spread is then ln A − beta × ln B − alpha. In the synthetic example, 250 rows give beta = 1.2382, so a beta-neutral trade holds about $1.24 of B for every $1 of A.
What z-score should you use to enter a pairs trade?
There is no correct value. Gatev, Goetzmann and Rouwenhorst opened positions when prices diverged by two historical standard deviations. Higher entry levels give fewer trades; a stop level caps how far you let the spread run. Test any choice out of sample.
What is the difference between correlation and cointegration?
Correlation measures whether two series move together; cointegration means a combination of them stays stationary, so gaps tend to close. Two unrelated random walks with the same upward drift can show a high price correlation: in a seeded simulation on this page, 0.93 for log prices, 0.06 for daily returns, and a cointegration t statistic of -2.16, which does not pass even the 10% critical value.
How do you calculate the half-life of mean reversion?
Regress the daily change in the spread on the previous day's spread. If the slope b is negative, the half-life is −ln(2) ÷ b periods (the exact discrete version is ln(0.5) ÷ ln(1 + b)). In Excel: =-LN(2)/SLOPE(change range, lagged spread range). The example gives b = -0.1224 and a half-life of 5.7 rows.
Can you do pairs trading in Excel or Google Sheets?
Yes for daily closes: SLOPE, INTERCEPT, AVERAGE, STDEV, CORREL and INDEX are enough to build the spread, z-score and signals, and this template uses only those. A spreadsheet will not place orders, stream prices or handle intraday data.
Is pairs trading profitable?
No one can promise that. Gatev, Goetzmann and Rouwenhorst (2006) reported positive historical excess returns for US stocks from 1962 to 2002, but their working paper found that waiting one day before trading reduced average excess returns by about 200 basis points. Costs, borrow fees, slippage and broken relationships can erase the edge.
Related tools and templates
- Position size calculatorShares for a set risk per trade
- Correlation matrix spreadsheetScreen many stocks before testing a pair
- Stock beta spreadsheetBeta of a stock against an index
- Short selling spreadsheetBorrow fees, dividends owed, margin
- Trading cost spreadsheetCommissions, spreads and fees
- Drawdown calculatorPeak-to-trough losses
- Sharpe ratio calculatorReturn per unit of volatility
- All templatesFree spreadsheets
Educational template only, not investment advice. Results on past or synthetic data do not predict future returns, and short selling can lose more than the amount invested. The Example pair is synthetic: prices were generated with a fixed random seed and do not describe any real company. Sources: Gatev, Goetzmann and Rouwenhorst, Review of Financial Studies 2006 (doi.org) and NBER Working Paper 7032 (nber.org); Engle and Granger, Econometrica 1987 (econometricsociety.org); MacKinnon, QED Working Paper 1227, 2010 (repec.org); Investor.gov (investor.gov). Retrieved 12 November 2026.