QuantsappFaster in the app: live data, alerts, tradingOpen
Log inStart free
Open Backtesting →
Stock F&OPositionalHDFCBANKmedium complexity

Pairs trading (cointegration)

Pairs trading takes two stocks that usually move together and trades the gap between them. This version fits a hedge ratio between HDFCBANK and ICICIBANK from a year of daily closes, re-fits it every month, and only trades when a statistical test says the two prices are cointegrated. When the gap stretches far from its recent average, it buys the cheap leg and sells the rich one.
Trades the gap between two related bank stock futures, HDFCBANK and ICICIBANK, when their price relationship stretches unusually far, betting it returns to normal, but only while the pair passes a cointegration test.
Market viewFades moves (mean reversion)
TradesHDFCBANK and ICICIBANK near-month futures, long one, short other
RiskOpen-ended (loss not capped by the structure)
CapitalFutures margin
SuitsAdvanced
Trades a month0
Typical hold
Profitable months0 of 12
Longest losing run0 trades
Made money inNo evidence: the rules never triggered in the year
Lost money inNo evidence: zero trades to split by condition
Default settings
Symbol
Symbol x
Formation days
Refit step
Z window
Entry z
Exit z
Stop z
Max hold days
Adf pvalue max
Exec time
Roll time
Lots y
Backtest this strategy →Change any setting, pick your own period and run it in the Quantsapp web app. Backtesting is part of the Max plan. Pro+ members can use it now as a free trial.
1

How it trades

What it trades
Universe
HDFCBANK Positional · 1 Oct 25 → 30 Sep 26
Enters
09:16 next session after the spread's z-score closes beyond ±1.5, pair cointegrated
Legs
BUY FUT · Near month (cheap leg of the spread) · Current month · 1 lotSELL FUT · Near month (rich leg, hedge-ratio lots) · Current month · 1 lot
Exits
signal z-score crosses back to 0; closed at 09:16 the next sessionstop z-score stretches to 3.5 or beyondtime Held more than 30 sessionsroll Both legs closed 15:15 on monthly expiry, reopened next session at 09:16
Re-entry
Yes - a fresh signal after the previous pair trade has closed
rule
Formation (walk-forward): every REFIT_STEP sessions, regress log(Y) on log(X) by OLS over the last FORMATION_DAYS daily closes -> beta. Keep trading the pair only while the residual passes an Engle-Granger / ADF test (lag 0, constant) at ADF_PVALUE_MAX (critical t-values -3.90 / -3.34 / -3.04 for 1 / 5 / 10 %). Signal (at a daily close): spread = log(Y) - beta*log(X); z = (spread - mean) / std, mean and std over the Z_WINDOW closes BEFORE it (shifted one bar). z <= -ENTRY_Z -> long spread: buy Y futures, sell X futures z >= +ENTRY_Z -> short spread: sell Y, buy X
Execution
at EXEC_TIME of the next session, both legs in ONE position (tagged long / short spread). Y is LOTS_Y lots; X is the beta-weighted notional, round(beta * notional_Y / notional_X) lots (at least 1). Exits (signal at a close, executed at the next session's EXEC_TIME): z crosses EXIT_Z toward the mean; |z| >= STOP_Z (stop); MAX_HOLD_DAYS sessions held. The open trade keeps the beta it entered with. New entries are skipped while either stock is in the F&O ban.
Roll
futures cannot be held past their monthly expiry - on the expiry day both legs are closed at ROLL_TIME and the trade is re-opened in the new near month at the next session's EXEC_TIME.
2

Results

PRE-BUILT · DEFAULTS
No trades in this periodThe rules never triggered with the default settings in the sample year.
3

Where it made and lost money

There is no evidence to split for this strategy. On default settings it made no trades between 1 Oct 2025 and 30 Sep 2026, so there is no record of how it fared against the NIFTY market backdrop, whether by India VIX level, session type or trend. The reason is the gate before any signal: the pair is only traded while the last hedge-ratio re-fit passes the cointegration test, and HDFCBANK and ICICIBANK never passed it at a re-fit date in this year. Until the strategy produces trades, the market conditions that suit it remain untested here.

The same trades, split by the market conditions around each entry, before costs.
4

About this strategy

  1. Every 21 sessions, counted from the start of the test, regress the log price of HDFCBANK futures on ICICIBANK futures over the last 252 daily closes to get the hedge ratio.
  2. Test the leftover gap (the residual) for stationarity with an ADF test; the pair is tradeable only if it passes at the 5% level, and stays so until the next re-fit.
  3. Each evening, measure the spread's z-score against the previous 30 closes. Below -1.5 means HDFCBANK is cheap; above +1.5 means it is rich.
  4. At 09:16 the next session, buy 1 lot of the cheap leg's future and sell the other; ICICIBANK lots are set by the hedge ratio so both sides carry similar rupee value. Both legs sit in one position.
  5. Close the pair at 09:16 after the z-score crosses back to 0, if it stretches to 3.5 (stop), or after 30 sessions.
  6. On monthly expiry both legs are closed at 15:15 and reopened in the next month at 09:16 the following session.
  7. No new pair is opened while either stock is in the F&O ban.

Why traders use it

Two banks of similar size face the same rates, regulation and credit cycle, so their prices tend to travel together. When one runs ahead of the other without news, pair traders bet the gap closes. Because the trade is long one stock and short the other, a broad market move largely cancels out, leaving the relative move. The cointegration test is meant to filter out pairs whose link has broken, and re-fitting on a rolling window keeps the hedge ratio current without using future data.

Works best whenIn principle, when two stocks share a stable long-run link that passes the cointegration test and short-term gaps open and close within weeks. This test produced no trades, so it gives no evidence either way.
Struggles whenWhen the pair's relationship is not statistically stable, as with HDFCBANK and ICICIBANK at every re-fit in this year: the gate keeps it flat. If a trade were open, a lasting break in the link would push the spread to the stop.

The year in plain words

On default settings, from 1 Oct 2025 to 30 Sep 2026, this strategy made no trades, so there is no profit or loss before or after costs to report. The code only looks for a signal while the latest re-fit passes the 5% cointegration test. Re-fits happen every 21 sessions counted from the start date, and at none of them in this year did the HDFCBANK/ICICIBANK residual pass. A run starting on another date re-fits on different days and could see a different outcome. The honest reading is that the rule set was untested on this pair in this year, not that it worked or failed.

What the settings do

Symbol xThe second stock of the pair, sold when HDFCBANK is bought and vice versa. It should be a closely related name with stock futures.Formation daysHow many daily closes the hedge ratio and the cointegration test use. A shorter window reacts to recent behaviour; a longer one is steadier but slower to notice a broken link.Refit stepSessions between re-fits, counted from the start date. A smaller step tests the pair more often, so a run can switch on as soon as the pair qualifies; a different start date re-fits on different days.Z windowHow many previous closes set the spread's average and spread of values for the z-score. Shorter windows react faster and give more signals.Entry zHow stretched the spread must be to open a trade. Lower values trade more often on smaller gaps.Exit zThe z-score at which the trade is closed on the way back. Zero waits for a full return to the average; a value short of zero takes profit earlier.Stop zCloses the pair if the gap keeps widening to this z-score, on the view that the link may have broken.Max hold daysThe longest a pair trade is held, in sessions, if neither the exit nor the stop is reached.Adf pvalue maxHow strict the cointegration test is: 1%, 5% or 10%. Setting 10% lets more pairs and periods qualify, which loosens the gate that kept this run flat; it says nothing about whether those trades pay.Exec timeThe time next morning at which entries, exits and post-roll re-entries are placed.Roll timeThe time on monthly expiry day at which both legs are closed before reopening in the next month.Lots yLots of HDFCBANK futures per trade; the ICICIBANK lots scale with it through the hedge ratio.

Risks

  • A pair that was cointegrated in the past can decouple after a merger, results surprise or regulatory event, and the spread then keeps widening.
  • Both legs are full stock futures positions; the lots are matched by hedge ratio, but whole-lot rounding leaves some net exposure.
  • Closing and reopening both legs at every monthly expiry adds orders, slippage and an overnight flat gap.
  • Trades can last up to 30 sessions, so margin on two futures positions is tied up for weeks.

Who it suits

Traders interested in market-neutral, statistics-driven ideas who have margin for two stock futures positions at once and can accept long stretches with no trades while the pair fails its test.

5

Questions traders ask

Is HDFCBANK vs ICICIBANK pairs trading profitable?

This test cannot say. With default settings it made zero trades from 1 Oct 2025 to 30 Sep 2026 because the pair never passed the 5% cointegration test at a re-fit date, so there was no profit or loss before or after costs. Looser settings may produce trades, but past results, or their absence, do not guarantee anything about future ones.

What is cointegration in pairs trading?

Two prices are cointegrated when some fixed mix of them, here HDFCBANK minus a hedge ratio times ICICIBANK in log terms, keeps returning to a stable average. Correlation only says they move the same way day to day; cointegration says the gap between them does not drift off. Pairs traders want the second, since the trade bets on the gap closing.

Why use futures instead of shares for a pair trade in India?

The short leg has to be held for days or weeks, and retail traders cannot carry a short position in cash shares overnight. Stock futures allow both a long and a short leg in one account, at the cost of whole-lot sizing and closing and reopening both legs at each monthly expiry.

How do I get this strategy to trade more often?

The gate is the cointegration test. Setting the test level to 10%, changing the formation window or the re-fit step, or choosing a different second stock changes which periods qualify. Lowering the entry z-score adds signals once the pair is tradeable. None of these changes says anything about whether the extra trades would make money.

6

Before you rely on it

ADAPTED FOR TODAY'S NSE RULES- Sources trade cash equities with a free short; NSE retail cannot carry overnight cash shorts, so both legs are near-month stock futures in whole lots (adaptation note). - Defaults: One source 252 / 21 walk-forward, z window 30, entry 1.5, exit 0, plus the source's 3.5 z stop and 30-session time stop (spec interpretation). The ADF uses fixed MacKinnon critical values instead of a p-value (no statsmodels in the sandbox). - The roll leaves the pair flat for one night (expiry close -> next open); holding the next-month future across the roll is not priced correctly by the SDK (see sdk_gaps). - Single pair per backtest; the sources' multi-pair selection with FDR correction is N runs.
WATCH OUTsurvivorship (today's large caps), small trade counts per pair, p-values not corrected across many pairs, highly cost-sensitive (STT on both legs).
Also known asstat arb pairs nseengle-granger pairscointegration pairs trading
Backtests run on historical NSE data with fills at the last traded price. "Before costs" excludes brokerage, taxes and slippage. Quantsapp is not recommending any strategy; it is just a backtesting utility. Past results are not a promise of future returns.

Log in or sign up

Enter your mobile number. New to Quantsapp? The same OTP creates your free account.

+91

By continuing you agree to the Terms of Use and Privacy Policy.