The tester above takes daily closes for two stocks, one pair of prices per line, and runs the Engle–Granger two-step test: it estimates the hedge ratio between the stocks, builds the spread, tests whether the spread tends to return to its average, and reports how fast it does so and how stretched it is today. This page explains each figure, works through the tester's own sample, shows how traders in India turn a cointegrated pair into two legs they can actually trade, and sets out the ways a test can mislead. A pair that passed on past data can stop working at any time.
What the cointegration tester does
| Part | What it does |
|---|---|
| Input | At least 20 rows of daily closes: stock A, then stock B on each line |
| Hedge ratio | The slope from regressing A's price on B's price: units of B against one unit of A |
| Spread | A − (hedge ratio × B + a constant) for each day |
| ADF statistic | A Dickey–Fuller test on the spread; more negative means more evidence the spread returns to its average |
| Verdict | Compared with the critical values for two series: −3.90 at 1%, −3.34 at 5%, −3.04 at 10% |
| Half-life | The number of days the spread takes, on average, to close half of a gap |
| Current z-score | How far today's spread is from its average, in standard deviations |
A short history of cointegration and pairs trading
The statistics came first. In 1979 David Dickey and Wayne Fuller published a test of whether a series wanders without bound or tends to return to a level, the question at the heart of this tester.1 In 1987 Robert Engle and Clive Granger showed that two series that each wander can still have a combination that does not: such series are cointegrated, and their two-step method of testing it is the one used here.2 They shared the Nobel prize in economics in 2003 for this and related work. In 1991 Søren Johansen published a test that handles more than two series at once, and James MacKinnon published the critical values that tests like this one compare against.34
Pairs trading grew up alongside. In the mid-1980s a group led by Nunzio Tartaglia at Morgan Stanley used computers to find stocks that had moved together and to bet on gaps between them closing. The idea spread to hedge funds through the 1990s. In 2006 Evan Gatev, William Goetzmann and Geert Rouwenhorst published a study of a simple pairs rule on US stocks from 1962 to 2002, showing that it had made money for decades and that the returns had fallen as more traders used the idea.5
In India, pairs traders face a practical limit that shapes the method: short selling in the cash market must be closed the same day for most traders, so a pair held overnight is usually built with stock futures, which exist only for stocks in the F&O segment. Securities lending and borrowing exists as another route, but it is used far less by individual traders.
How the Engle–Granger test works
- Regress A on B. Find the line A = constant + hedge ratio × B that fits the two price series best. The hedge ratio says how many units of B move with one unit of A.
- Build the spread. For each day, spread = A − (hedge ratio × B + constant). If the pair is cointegrated, this series should wander around zero and come back.
- Test the spread. Regress each day's change in the spread on the previous day's spread. A strongly negative slope means gaps tend to close. The t-statistic of that slope is the ADF statistic.
- Compare with critical values. Because the hedge ratio was estimated from the same data, the usual tables are too lenient; the tester uses the values for two series: −3.90 at 1%, −3.34 at 5% and −3.04 at 10%. A statistic below a critical value passes at that level.
- Measure the speed. From the same slope, the half-life is the number of days a gap takes to shrink by half.
- Measure today's gap. The z-score is today's spread divided by the spread's standard deviation.
For a slope close to zero, this is close to −ln(2) ÷ slope, the version often quoted. The tester uses the exact form.
The tester uses the test without extra lags. Statistical software adds lag selection and p-values; for a first screen of a pair, the simple version with critical values gives the same verdict in most cases.
A worked example: the tester's sample
The tester opens with 120 rows of sample daily closes for two made-up stocks, A around ₹2,300 to ₹2,400 and B around ₹1,500 to ₹1,600. The sample was built so that A follows 1.42 times B plus 160, with a gap that shrinks by a quarter each day plus noise. Running the test gives:
| Figure | Result |
|---|---|
| Hedge ratio | 1.372 units of B against one unit of A |
| Constant | 237.96 |
| ADF statistic | −4.17 |
| Verdict | Cointegrated at the 1% level |
| Half-life | 2.3 days |
| Current z-score | 0.49: the spread is near its average |
| Level | Critical value | Result |
|---|---|---|
| 1% | −3.90 | Pass |
| 5% | −3.34 | Pass |
| 10% | −3.04 | Pass |
Two things are worth noticing. The estimated hedge ratio, 1.372, is close to the true 1.42 but not equal to it: 120 days of noisy prices do not pin down the relationship exactly. And the half-life of 2.3 days is close to the true 2.4 days built into the sample, because a gap that shrinks by a quarter each day halves in about two and a half days. On real stocks you never know the true values, which is why the test is a guide, not proof.
Reading the results
| Result | What it suggests |
|---|---|
| Statistic below −3.90 | Strong evidence the spread returns to its average over this period |
| Between −3.90 and −3.34 | Evidence at the 5% level |
| Between −3.34 and −3.04 | Weak: passes at 10% only |
| Above −3.04 | No reliable evidence of cointegration |
| Half-life of a few days to about four weeks | The spread reverts quickly enough to trade |
| Half-life of several months | Reversion may be too slow to be useful |
| z-score beyond ±2 | The spread is stretched |
| z-score near 0 | The spread is near its average |
A pass at 1% with a half-life of a week is the kind of result pairs traders look for. A pass at 10% with a half-life of three months is not much better than no result.
A worked example by hand: from z-score to a trade
Suppose a test on a year of daily closes for two stocks in the same sector gives a hedge ratio of 0.82, an ADF statistic of −3.9, a half-life of 6 trading days and a current z-score of +2.1.
- The statistic passes at the 5% level and is at the edge of the 1% level.
- The half-life says gaps have closed within about a week on average.
- The z-score says A is expensive relative to B by about two standard deviations.
A pairs trader would sell A and buy 0.82 units of B for each unit of A, and plan to close both legs when the z-score returns to zero. A common rule set:6
| Rule | Example setting |
|---|---|
| Entry | z-score above +2: sell A, buy B; below −2: buy A, sell B |
| Exit | z-score back to 0 |
| Stop | z-score beyond ±3.5, or a set rupee loss |
| Time stop | Close after about three half-lives if the gap has not closed |
| Re-test | Every month, on the latest year of data |
The pairs trading guide covers these rules in full. None of the settings above is a recommendation; each one should be tested on data the pair was not chosen on.
Turning a hedge ratio into two legs you can trade
The hedge ratio is in units of stock, but futures come in lots. Suppose the tester gives a hedge ratio of 1.37 units of B per unit of A, and the stock futures have lots of 300 shares for A and 400 for B.
| Leg | Units the ratio asks for | Units in whole lots | Value at A ₹2,339, B ₹1,527 |
|---|---|---|---|
| A, one lot | 300 | 300 | about ₹7.0 lakh |
| B | 300 × 1.37 = 411 | 400, one lot | about ₹6.1 lakh |
One lot each comes within 3% of the ratio, which is close enough. With other lot sizes the nearest match may need two lots of one and three of the other, and a pair whose lots cannot be matched closely is harder to trade than its statistics suggest. Margin is charged on both legs, and the broker may give some benefit for the hedge; check before sizing.
Which pairs to test
The test finds statistical links; it cannot tell you whether a link has a reason behind it. Start with pairs where a business reason ties the two prices together, and use the test to check whether the reason shows up in the data.
| Kind of pair | Why the prices may stay together |
|---|---|
| Two large private banks | Same interest-rate cycle, same credit conditions, similar customers |
| Two IT services companies | Same export markets, same currency effect, similar contracts |
| Two cement or steel makers | Same input costs and demand from construction |
| Two oil marketing companies | Prices and margins set by the same fuel market |
| A holding company and its listed subsidiary | The holding company's value rests largely on its stake |
| A stock and its sector index | The stock is a large part of the index |
Pairs from different industries can pass the test by chance over a year and then drift apart for good. A pair with a reason that has changed, such as one company entering a new business, needs a fresh look whatever the test says.
Checking a pair on data it was not chosen on
A pair that passes the test on the period it was chosen from has passed an easy exam. The harder test is the next period. A simple routine:
- Choose and test the pair on one year of data, the formation period.
- Fix the hedge ratio, the average spread and the standard deviation from that year.
- Apply them, unchanged, to the following six months: compute each day's z-score with the old figures and record where the entry and exit rules would have traded.
- Compare. If the spread kept reverting with a similar half-life, the pair is a candidate. If it drifted away or the trades lost, the first result was likely luck.
This is the same idea as testing any strategy on unseen days. It costs nothing but time, and it removes many pairs that would otherwise be traded on the strength of one good year.
Sizing a pair
Size a pair by the loss you would take at the stop, not by the margin. If one unit of A plus its hedge in B has a spread standard deviation of ₹6, and you enter at a z-score of 2 with a stop at 3.5, the loss at the stop is about 1.5 × ₹6 = ₹9 per unit of A before costs. With 300 units of A in one lot, that is about ₹2,700 a pair. If the most you are willing to lose on one pair trade is ₹5,000, one lot each fits; two lots each would not.
Pairs are often sized larger than single stocks because they look hedged. They are hedged against the market as a whole, not against the two stocks parting ways, which is exactly the risk the stop is for.
Pairs of a stock and an index
A pair need not be two stocks. A stock that makes up a large part of its sector index, or a stock against the broad index, can be tested the same way. The index side is usually more liquid, through index futures, and its lot is easier to match. The economic link is clear, but these pairs often revert more slowly, because a single company can outperform or underperform its index for long stretches. Test them, and watch the half-life before trading them.
Choosing the order of the pair
The Engle–Granger test can give different results depending on which stock is A and which is B, because the regression treats A as the one being explained. Run it both ways by swapping the columns. If one direction passes and the other does not, treat the evidence as weaker. The Johansen test, which handles both directions at once and can test three or more series together, is the usual alternative in statistical software.3
How long a formation period to use
The formation period is the stretch of data the test is run on. Common choices are six months to two years of daily closes.
- Shorter periods reflect the current relationship but contain fewer reversions, so the test has less to go on and passes and failures are noisier.
- Longer periods give the test more data but may include an old relationship that no longer holds after a merger, a change in business mix or a change in how the market values the sector.
A practical habit is to test on one year, then check that the same pair also passes on the year before it. A relationship that holds across two separate years is more likely to be real than one that holds on one.
Pitfalls
- Spurious results. With many pairs tested, some will pass by chance. Testing 100 pairs at the 5% level can produce around five false passes. Prefer pairs with a clear economic link, such as two banks, two cement makers or a parent and its listed subsidiary.
- Relationships break. Mergers, regulation, management changes or business shifts can end a relationship permanently. Re-test regularly and use stops.
- Formation-period bias. A pair chosen because it looks good on one period should be tested on the next period before trading.
- Corporate actions. Splits, bonuses and dividends must be adjusted for, or they will distort the spread.
- Execution. Trading the pair needs both legs at close to the same moment, often through stock futures for overnight shorts in India, with lot sizes that rarely match the hedge ratio exactly.
- Costs. Each round trip pays brokerage, taxes and slippage on two legs. A spread that reverts by a small amount may not cover them.
Correlation vs cointegration
| Correlation | Cointegration | |
|---|---|---|
| Measures | Whether daily returns move together | Whether price levels share a stable relationship |
| Needed for pairs trading | Helpful as a first filter | Essential |
| Can two stocks have one without the other? | Yes | Yes |
Two stocks that both rise every day by slightly different amounts have highly correlated returns, yet the gap between their prices widens without end: correlated, not cointegrated. Two stocks whose daily moves are only loosely related can still be tied together over months by a common business driver: weakly correlated, yet cointegrated. The stock correlation matrix is a useful first screen; this tester is the second step.
A worked example: a pair that broke
Two stocks in the same industry passed the test at the 1% level on a year of data, with a half-life of eight days. A month after a trader entered at a z-score of +2.2, one company announced an acquisition that changed its business. The spread kept widening: the z-score reached +3, then +4.
| Day | z-score | What the rules said |
|---|---|---|
| Entry | +2.2 | Sell A, buy B |
| Day 5 | +2.8 | Hold |
| Day 9 | +3.6 | Stop: close both legs |
| Day 30 | +5.1 | The relationship had changed |
The stop at ±3.5 cut the loss on day 9. Without it, the trade would have kept losing while the statistics from the old year still said the spread should come back. Re-testing the pair on data after the announcement showed it no longer passed. Pairs fail suddenly when the business reason that tied them together changes, and the test, which only looks back, cannot see it coming.
Results days, rollovers and other dates to watch
Some dates move one leg of a pair without the other, and a pairs trader should know them in advance.
- Results. Two companies in the same sector report on different days. The first to report can move sharply while the other waits, which stretches the spread for reasons that may or may not reverse. Many pairs traders close or avoid positions across either company's results.
- Futures expiry. Stock futures expire monthly. A pair held through expiry must be rolled into the next month's contracts, which costs two more round trips and can be done at different spreads on the two legs.
- Dividends and record dates. A dividend lowers a stock's price on the ex-date by roughly the dividend, which shifts the spread unless the series is adjusted.
- Index changes. A stock added to or removed from a major index can see heavy buying or selling unrelated to its partner.
Keep a calendar of these dates for both stocks, and check it before every entry.
Costs and the size of a reversion
Before trading a pair, compare the typical size of a reversion with the cost of a round trip on both legs. If the spread's standard deviation is ₹6 a unit of A and you trade from a z-score of 2 back to 0, the typical gain is about ₹12 a unit of A before costs. With two stock futures legs, the round trip pays brokerage on four orders, STT and exchange charges on both legs, and slippage on each fill. If those add up to ₹4 or ₹5 a unit of A, a third of the expected gain is gone before the trade starts. Pairs with wide spreads and quick reversions survive costs; pairs with narrow spreads and slow reversions usually do not.
Pairs trading with QuantPower
- Testing. Use this tester and the correlation matrix to screen pairs. Both run in your browser on prices you paste.
- Charts. Arth.live charts, free inside QuantPower, show each stock with 201 indicators, so you can watch both legs side by side in a multiple charts layout.
- The legs. An algo can hold up to 6 legs on stocks, stock futures, stock options, index contracts, commodity and currency contracts, so both legs of a pair can sit in one algo and enter together, buy legs first and sell legs after. A quantity multiplier scales both legs.
- The trigger. If you calculate the z-score yourself, in a spreadsheet or your own code, a webhook from that tool can start the pair's algo when the z-score crosses your entry and stop it, squaring off both legs, when it crosses your exit. A webhook needs no tap and acts only on your own algos, within market hours.
- Risk. The daily loss limit refuses new orders once the day's loss reaches it, and Smart Exit squares off every position and stops the algos at your account-wide stop or target.
- Forward test. Run the pair's algo in Forward test on live prices with test money before it trades for real.
The tester is free. A live algo costs 200 tokens per 28 days and a Forward test 100 tokens per algo per 28 days (1 token = ₹1, GST extra).
How to use the tester, step by step
- Choose two stocks with a clear economic link, both in the F&O segment if you plan to hold the pair overnight.
- Download daily closes for the same dates, adjusted for splits, bonuses and dividends.
- Paste them one day per line: stock A's close, then stock B's close.
- Read the verdict against the critical values, then the half-life and the z-score.
- Swap the columns and run again. Trust a pair more if both directions pass.
- Run it on the previous year of data too. A pair that passes on both years is a better candidate.
- Convert the hedge ratio into whole lots and check the cost of a round trip against the size of a typical reversion.
Common mistakes
- Testing hundreds of pairs and trading the best. The best of hundreds is likely to be luck.
- Using correlation instead of cointegration. Correlated returns do not mean the prices stay together.
- Forgetting corporate actions. One unadjusted split ruins the spread.
- Ignoring the half-life. A pair that reverts over six months ties up margin for six months.
- Trading without a stop. The trade that loses most is the one where the relationship has ended.
- Never re-testing. Relationships drift; a test from last year says little about next month.
Where pairs trading is going
Pairs trading has become more crowded since its early days, as the 2006 study found, and simple pairs in large, well-known stocks now revert faster and with smaller gaps than they once did. Traders have moved in three directions: testing baskets of three or more stocks with the Johansen method, using pairs between a stock and its sector index or between related futures, and combining the statistical test with a business reason for the link. The tools have also moved closer to the trader: a test that once needed statistical software now runs in a browser, and the two legs can be placed and managed as one position.
Related guides
- Stock correlation matrix: the first screen for candidate pairs
- Monte Carlo simulation: testing how a rule set behaves across many possible paths
- Avoiding overfitting: why the best result of many tests is often luck
Start with 500 free tokens
Connect your broker, build a strategy and test it on paper before a single live order goes out.
Frequently asked questions
What is a cointegration test?
A statistical test of whether a combination of two price series, such as A minus a multiple of B, tends to return to a stable average.
Why does the tester show critical values instead of a p-value?
The test statistic is compared with the critical values for two series, −3.90, −3.34 and −3.04, which tell you whether it passes at 1%, 5% or 10%. Statistical software can add an exact p-value and lag selection; the verdict is usually the same.
How long should the test period be?
Commonly one to two years of daily data. Longer periods give more data but may include old relationships that no longer hold. Testing two separate years and trading only pairs that pass both is a stricter rule.
Can cointegration change over time?
Yes. Relationships can weaken or break, often suddenly after a merger, a regulatory change or a shift in a company's business, so pairs should be re-tested regularly and traded with stops.
What does the half-life tell me?
How many days the spread takes, on average, to close half of a gap from its average. It sets a sensible time stop: if a gap has not closed after three or four half-lives, the relationship may have changed.
Can I hold a pair overnight in India?
Short positions in the cash market must usually be closed the same day, so overnight pairs are normally built with stock futures, which are available only for stocks in the F&O segment.
References
- David A. Dickey and Wayne A. Fuller, "Distribution of the Estimators for Autoregressive Time Series with a Unit Root", *Journal of the American Statistical Association*, 74(366), 427–431 (1979)
- Robert F. Engle and Clive W. J. Granger, "Co-Integration and Error Correction: Representation, Estimation, and Testing", *Econometrica*, 55(2), 251–276 (1987)
- Søren Johansen, "Estimation and Hypothesis Testing of Cointegration Vectors in Gaussian Vector Autoregressive Models", *Econometrica*, 59(6), 1551–1580 (1991)
- James G. MacKinnon, "Critical Values for Cointegration Tests", in *Long-Run Economic Relationships*, Oxford University Press (1991); revised as Queen's University working paper 1227 (2010)
- Evan Gatev, William N. Goetzmann and K. Geert Rouwenhorst, "Pairs Trading: Performance of a Relative-Value Arbitrage Rule", *Review of Financial Studies*, 19(3), 797–827 (2006)
- Ernest P. Chan, *Algorithmic Trading: Winning Strategies and Their Rationale*, Wiley (2013)