Building and Evaluating a Market-Neutral Pairs Trading Strategy on Indian Equities

Shant Tandon, leveraging a robust academic framework and practical industry experience, has meticulously developed and rigorously evaluated a market-neutral pairs trading strategy specifically designed for the Indian equity market. This initiative, presented as a capstone project, aims to address common pitfalls in algorithmic trading by emphasizing statistical robustness, avoiding look-ahead bias, and incorporating explicit transaction costs. The strategy focuses on identifying and exploiting temporary price divergences between highly correlated large-cap stocks across key sectors of the National Stock Exchange (NSE).
Project Genesis and Strategic Motivation
The core motivation behind this project stems from a desire to create a "clean, defendable academic implementation" of a pairs trading strategy. Pairs trading, a well-established statistical arbitrage technique, seeks to profit from the tendency of two historically correlated assets to revert to their mean relationship. Tandon’s approach is particularly geared towards the Indian market, analyzing data from January 1, 2015, to June 30, 2025.
A significant driver for this research is the need to mitigate prevalent issues in algorithmic trading. These include:
- Look-ahead bias: Using future information to make trading decisions, which artificially inflates performance.
- Incomplete Profit and Loss (PnL) calculations: Failing to account for all relevant costs, such as commissions and slippage.
- Inadequate multiple testing controls: When testing many hypotheses (pairs), the probability of finding spurious relationships increases, leading to false positives.
By meticulously addressing these challenges, Tandon aims to provide a blueprint for a more realistic and potentially profitable trading strategy.
Methodology: Technical Breakdown of the Strategy
The strategy’s implementation is built upon a rolling walk-forward methodology. This involves a cyclical process of training a model on historical data and then testing its performance on subsequent, unseen data. The parameters for this process are defined as follows:
- Training Window: 252 trading days (approximately one year of trading data).
- Test Step: 21 trading days (a short period to capture recent market dynamics).
Pair Selection and Cointegration Testing
The initial and arguably most critical step is identifying suitable pairs of stocks that exhibit a strong, statistically significant cointegrating relationship. This process involves several layers of statistical rigor:

- Hedge Ratio Estimation: During the training phase, the "hedge ratio" (often denoted as beta, denoted by $beta$) between two stock prices is estimated using Ordinary Least Squares (OLS). This ratio quantifies how much of one stock should be traded for every unit of the other to maintain a market-neutral position.
- Residual Stationarity Test: The core of cointegration testing lies in examining the residuals of the OLS regression. If the residuals are stationary, it implies that the spread between the two stock prices tends to revert to a mean. Tandon specifically employs the Augmented Dickey-Fuller (ADF) test, focusing on the ADF(0) variant, to assess this stationarity. The MacKinnon p-value, which provides a critical value adjusted for sample size, is used to determine statistical significance.
- False Discovery Rate (FDR) Control: To manage the risk of selecting pairs that appear cointegrated purely by chance (false positives), the Benjamini-Hochberg FDR procedure is applied at a 5% significance level. This is crucial when testing numerous potential pairs, as it controls the expected proportion of rejected null hypotheses that are, in fact, true null hypotheses.
Through this rigorous process, three highly cointegrated pairs emerged from the initial universe of 25 NSE large-cap stocks across the Banking, IT, Pharma, Cement, and Auto sectors:
- HDFCBANK.NS vs. KOTAKBANK.NS (Banking Sector)
- HEROMOTOCO.NS vs. ULTRACEMCO.NS (Auto and Cement Sectors, respectively – demonstrating cross-sector correlation potential)
- HCLTECH.NS vs. ICICIBANK.NS (IT and Banking Sectors, again highlighting potential cross-sector relationships)
Signal Generation Logic and Execution
Once a cointegrated pair is identified, the strategy moves to generating trading signals and executing trades. This phase is meticulously designed to prevent look-ahead bias:
- Preventing Look-Ahead Bias: To ensure that decisions are made solely on past data, rolling variables such as the mean and standard deviation of the spread are strictly shifted by one day. This means that the calculation of the spread’s mean and volatility at any given point in time uses data only up to the previous trading day.
- Z-Score Calculation: The normalized deviation of the current spread from its historical mean is calculated as a z-score. The formula is: $z_t = frac(St – mut-1)sigma_t-1$, where $St$ is the spread at time $t$, $mut-1$ is the rolling mean of the spread up to time $t-1$, and $sigma_t-1$ is the rolling standard deviation of the spread up to time $t-1$.
- Trading Signals:
- Entry: A long position in the pair is initiated when the absolute z-score exceeds 1.5 (specifically, when $zt < -1.5$ for a long entry or $zt > 1.5$ for a short entry). This indicates a significant deviation from the mean.
- Exit: Trades are exited when the z-score crosses back to zero or reverses direction. This is typically signaled by the product of the previous day’s z-score and the current day’s z-score being less than or equal to zero $(zt-1 times zt le 0)$.
The strategy explicitly defines parameters for capital allocation and transaction costs:
- Capital per Active Pair: INR 5,00,000 (approximately $6,000 USD, subject to exchange rates).
- Transaction Costs: 5 basis points (0.05%) per leg, per side. This accounts for brokerage fees and potential slippage.
Portfolio and Risk Management
While not detailed extensively in the provided abstract, robust portfolio and risk management are implied as crucial components. This would typically involve:
- Position Sizing: Ensuring that the capital allocated to each pair is managed effectively.
- Stop-Loss Mechanisms: Implementing rules to exit a trade if it moves significantly against the position, limiting potential losses.
- Portfolio-Level Risk Metrics: Monitoring overall portfolio volatility, drawdown, and other risk indicators.
A conceptual Python snippet illustrating the core logic of signal generation highlights the technical implementation:
import pandas as pd
import statsmodels.api as sm
def calculate_signals(train_data, test_data, stock_a, stock_b):
# 1. Estimate Hedge Ratio (Beta) using OLS on Training Window
# Ensure train_data has both stock_a and stock_b columns
model = sm.OLS(train_data[stock_a], train_data[stock_b]).fit()
beta = model.params[0] # Assuming stock_b is the explanatory variable
# 2. Calculate Out-of-Sample Spread
# Spread formula: S_t = A_t - beta * B_t
spread = test_data[stock_a] - (beta * test_data[stock_b])
# 3. Calculate Z-Score strictly avoiding look-ahead bias
# z_t = (S_t - mu_t-1) / sigma_t-1
# Use rolling window of 30 days for mean and std dev, shifted by 1 day
rolling_mean = spread.rolling(window=30).mean().shift(1)
rolling_std = spread.rolling(window=30).std().shift(1)
z_score = (spread - rolling_mean) / rolling_std
# 4. Generate Trading Signals based on Z-Score Thresholds
# Enter when absolute z-score > 1.5, Exit when it crosses 0
# Long entry when z_score < -1.5 (stock_a undervalued relative to stock_b)
long_entry = z_score < -1.5
# Short entry when z_score > 1.5 (stock_a overvalued relative to stock_b)
short_entry = z_score > 1.5
# Exit signal when the z_score crosses the zero line from either side
# This happens when the product of consecutive z-scores is non-positive
exit_signal = (z_score.shift(1) * z_score <= 0) & (z_score.shift(1).notna()) # Ensure we have a previous z_score
return z_score, long_entry, short_entry, exit_signal
Key Findings and Portfolio Performance
The out-of-sample backtest, conducted over the period from January 11, 2016, to June 27, 2025, revealed the following performance metrics for the three-pair portfolio:
| Metric | Value |
|---|---|
| Capital Base | INR 15,00,000 |
| Pairs Traded | 3 |
| Backtest Period | Jan 11, 2016 – Jun 27, 2025 |
| Total Trades | 271 |
| Win Ratio | 63.47% |
| Total PnL | INR 1,65,544.97 |
| PnL / Capital | 11.04% |
| Annualized Return | 0.30% |
| Annualized Volatility | 13.34% |
| Sharpe Ratio | 0.089 |
| Max Drawdown | -34.31% |
Analysis of Performance:
The results indicate a strategy that generates a positive, albeit modest, net profit over the backtest period. The win ratio of 63.47% suggests that the strategy successfully identifies profitable trades more often than not. However, several key metrics warrant closer examination and highlight areas for improvement.
- Low Annualized Return: An annualized return of 0.30% is quite low, especially considering the potential risks involved in trading. This suggests that while the strategy is profitable, its efficiency in generating returns relative to the capital deployed is limited.
- High Maximum Drawdown: A maximum drawdown of -34.31% is substantial. This indicates periods where the portfolio lost a significant portion of its value. This level of drawdown is a critical concern for risk-averse investors and suggests that the strategy may not be adequately protected against adverse market events or breakdowns in cointegration.
- Low Sharpe Ratio: The Sharpe ratio of 0.089, which measures risk-adjusted return, is also quite low. A higher Sharpe ratio indicates better performance for the level of risk taken. This low value reinforces the observation that the returns generated are not significantly compensating for the volatility experienced.
The project abstract notes the participation of Shant Tandon, who brings a diverse background in financial markets analysis, consulting, and entrepreneurship. His academic credentials include a Bachelor’s in Commerce with a focus on Financial Markets from Narsee Monjee College of Commerce and Economics and a High School Diploma in Business/Commerce from Mayo College, Ajmer. Professionally, Tandon has accumulated analytical experience through internships at Teach For India and KPMG in Mumbai, followed by a role as an Analyst at PwC, demonstrating a solid foundation for undertaking such a complex quantitative project.
Challenges and Limitations
While the project presents a well-structured and academically sound approach, inherent challenges and limitations exist:
- Survivorship Bias: The selection of a fixed 25-stock universe can lead to survivorship bias. If a stock that was part of the universe historically but has since delisted or significantly underperformed is excluded from the analysis, the historical performance might be artificially inflated. A more realistic approach would involve using a dynamic index constituent list.
- Transaction Cost Sensitivity: Pairs trading strategies can be sensitive to transaction costs. While 5 bps per leg is explicitly accounted for, higher-than-expected slippage or increased trading frequency could erode profitability.
- Regime Changes: Cointegration relationships are not permanent. Market shocks, economic policy changes, or shifts in industry dynamics can cause cointegrated pairs to diverge permanently, leading to significant losses if not managed with robust stop-loss mechanisms.
- Limited Pair Universe: The strategy currently focuses on only 25 large-cap stocks and identifies just three pairs. This limits diversification and exposes the portfolio to the risk of any single pair’s cointegration breaking down.
- Stationarity Test Limitations: While ADF is a standard test, it has its own statistical limitations and may not always perfectly capture all nuances of cointegration, especially in volatile or non-linear market conditions.
Next Steps: Enhancing Strategy Performance
Tandon’s project outline thoughtfully identifies several avenues for future improvement, aiming to enhance the strategy’s risk-adjusted returns and real-world applicability:
- Optimized ADF Lag Selection: Moving beyond the ADF(0) shortcut, employing information criteria like the Akaike Information Criterion (AIC) or Bayesian Information Criterion (BIC) to select optimal lag lengths for the ADF test can lead to more precise and reliable cointegration detection, reducing spurious relationships.
- Expanded Universe and Diversified Pairs: Broadening the stock universe beyond the initial 25 large-cap stocks to include mid-cap NSE stocks across more sectors (e.g., Energy, FMCG, Metals) would increase the pool of potential cointegrated candidates. This diversification is crucial for reducing portfolio concentration risk and mitigating the impact of individual pair breakdowns.
- Dynamic Position Sizing: Implementing volatility-scaled position sizing (e.g., inverse volatility or Kelly criterion) would allocate more capital to pairs with stronger mean-reversion signals and tighter spreads. This adaptive approach can significantly boost the Sharpe ratio and reduce drawdowns by emphasizing more robust trading opportunities.
- Adaptive Entry/Exit Thresholds: The current static z-score thresholds ($pm 1.5$ for entry, 0 for exit) could be made dynamic. Calibrating these thresholds based on a pair’s rolling volatility or market regime classification (trending vs. mean-reverting) can improve signal quality, filter out noise, and potentially enhance the win ratio beyond the current 63.47%.
- Incorporating Stop-Loss Rules: To address the significant maximum drawdown of -34.31%, pair-level stop-loss rules are essential. Examples include exiting a trade when the z-score breaches a higher threshold (e.g., $pm 3.0$) or when an unrealized loss exceeds a predefined percentage of the allocated capital. Such measures are vital for capping downside risk during adverse events.
- Addressing Survivorship Bias: A critical step for realistic performance estimation is to mitigate survivorship bias. This involves using a rolling universe based on actual historical index constituents (e.g., Nifty 50 or Nifty 100 at specific points in time) rather than a fixed list. This ensures that the backtest reflects the market conditions and available opportunities as they truly were.
Pathways for Continuous Learning
The project serves as an excellent case study for individuals interested in statistical arbitrage, cointegration testing, and mean-reversion strategies. QuantInsti, an organization supporting quantitative trading education, offers several resources to build upon these concepts:
- Foundational Courses: "Python for Trading Basics" and Dr. Ernest P. Chan’s "Mean Reversion Trading Strategy" provide essential guidance on building and evaluating statistical models in financial contexts.
- Advanced Strategies: The "Advanced Algorithmic Trading Strategies" learning track delves into more complex quantitative techniques, while "Factor Based Investing" offers insights into adaptive strategies.
- Portfolio and Backtesting: Courses like "Quantitative Portfolio Management" and "Backtesting Trading Strategies" focus on critical aspects of modeling, evaluation, and risk management, directly relevant to the project’s findings.
- Hands-on Learning: The "Quantitative Trading" and "Artificial Intelligence in Trading" learning tracks offer comprehensive training from data handling to model deployment, guided by industry professionals.
- Comprehensive Program: For those inspired by Tandon’s end-to-end project approach, the Executive Programme in Algorithmic Trading (EPAT) provides a full curriculum covering Python, statistics, machine learning, backtesting, and real-world trading applications.
Disclaimer: The information presented in this project is based on the student’s knowledge and is intended for informational purposes only. Recommendations are made without guarantee, and neither the student nor QuantInsti® disclaim any liability in connection with the use of this information. The guidance provided does not guarantee specific profit outcomes.







