Article 18, Cointegration Pairs Trading on NSE: An Educational Walkthrough

The Engle-Granger cointegration workflow described pedagogically with anonymised placeholders. Methodology only, not a recommendation on any specific pair.

Educational only. Bharath Shiksha is an educational publisher, not a SEBI-registered Investment Adviser or Research Analyst. Nothing here is investment advice or a recommendation on any security. The methodology is described pedagogically with anonymised placeholders. The variable names below (Stock A, Stock B) are illustrative, substitute with any cointegrated pair the reader chooses to study from their own historical data.

The core idea. Two non-stationary price series can have a stationary linear combination (the spread). If the spread reverts to its mean, a pairs-trading framework can in principle profit from the divergence-then-convergence cycle. The methodology below describes the analytical workflow; it is not a recommendation on any specific pair.

The Engle-Granger 2-step procedure

Step 1: OLS regression of one series on the other

import pandas as pd
import numpy as np
import statsmodels.api as sm
from statsmodels.tsa.stattools import adfuller

# Load 5 years of daily closes for any two candidate cointegrated names: Stock A and Stock B
# (Reader supplies historical data for the pair they wish to study)
df = pd.DataFrame({
    "stock_a": stock_a_data["Close"],
    "stock_b": stock_b_data["Close"]
}).dropna()

# Regress Stock A on Stock B
X = sm.add_constant(df["stock_b"])
model = sm.OLS(df["stock_a"], X).fit()
beta = model.params["stock_b"]  # hedge ratio

Step 2: ADF test on residuals

residuals = df["stock_a"] - beta * df["stock_b"] - model.params["const"]
adf_stat, p_value, *_ = adfuller(residuals)
print(f"ADF stat: {adf_stat:.3f}, p-value: {p_value:.3f}")

If p-value < 0.05, the spread is stationary → the pair is cointegrated → the pairs framework is methodologically applicable.

The z-score framework rule

# Compute z-score of spread
residuals = residuals.dropna()
mean = residuals.rolling(60).mean()
std = residuals.rolling(60).std()
z = (residuals - mean) / std

# Framework definition (NOT a trade recommendation):
# When z < -2: the spread is at a historically wide negative deviation.
#   The framework's long-spread leg would be sized as +1 unit Stock A,
#   -beta units Stock B (hedge ratio).
# When z > 2: the spread is at a historically wide positive deviation.
#   The framework's short-spread leg would be the mirror.
# Exit: |z| < 0.5 (mean reversion completed).

These are the framework's mathematical signals, not directions to act on. Whether to deploy capital, and on which specific securities, is the reader's own decision based on their own research, risk tolerance, and SEBI-compliant adviser consultation.

Indian-market-specific constraints

  1. Short selling. Indian retail can't short cash equity overnight. The framework requires stock futures for the short leg.
  2. Hedge ratio and lot size. A computed hedge ratio may not match F&O lot sizes. Round down; adjust size proportionally.
  3. Physical settlement risk on expiry. A pairs methodology held into expiry week is exposed to physical settlement on the equity leg.

Half-life of reversion

# AR(1) of spread
lag_spread = residuals.shift(1).dropna()
aligned = residuals.iloc[1:]
ar1_model = sm.OLS(aligned, sm.add_constant(lag_spread)).fit()
k = ar1_model.params[1] - 1
half_life = -np.log(2) / np.log(1 + k)
print(f"Half-life: {half_life:.1f} days")

A half-life of 10-30 days is typically considered usable for retail-capital horizons. Under 10 days: noise dominated. Over 60 days: capital tied up too long for the expected mean reversion.

Stage 4 Volume 3 connection

Stage 4 Volume 3 (Time-Series Econometrics) covers cointegration with additional pedagogical examples, ARIMA, GARCH for volatility forecasting, and the 8 common time-series mistakes retail quants make. All examples are historical, anonymised, and presented as methodology, not as trade recommendations.

Disclaimer

About Bharath Shiksha. Bharath Shiksha is an educational publisher. All content is for educational purposes only.

Not investment advice. Nothing here constitutes investment advice, a recommendation to buy, sell, or hold any security, a forecast of price action, or a research report under the SEBI (Research Analyst) Regulations, 2014. We are not a SEBI-registered Investment Adviser (IA) or Research Analyst (RA).

Educational scope only. Examples that reference specific securities or sectors are pedagogical illustrations of methodology applied to historical data, not recommendations, predictions, or guidance on current or future market positioning.

Risk warning. Trading involves substantial risk of loss. SEBI's 2024 study found 89-93% of retail F&O traders incurred losses. Past performance is not indicative of future results.

Consult a registered adviser. Before deploying capital, consult a SEBI-registered Investment Adviser or Research Analyst.


Related reading

Ready to go deeper than this article?

Bharath Shiksha is a 30-volume curriculum across 6 stages, from chart reading (Stage 1 at ₹14,999) through capital raising (Stage 6 at ₹59,999), or the full bundle at ₹1,49,999. Every volume has a 14-page companion worksheet, a 10-question gate quiz, and a 7-day money-back guarantee.

See the full curriculum →