Automated Trading and Algorithmic Strategies

A Rigorous Pairs Trading Strategy for the Indian Equity Market: An Academic Implementation

Shant Tandon, a professional with a multifaceted background in financial markets, consulting, and entrepreneurship, has developed and rigorously evaluated a market-neutral pairs trading strategy specifically tailored for the Indian equity market. This academic implementation, executed as part of his final project, aims to address common pitfalls in algorithmic trading, such as look-ahead bias and inadequate statistical controls, while offering a clear and defensible methodology. The strategy focuses on 25 large-cap stocks across the Banking, Information Technology (IT), Pharmaceutical, Cement, and Automotive sectors, employing a residual stationarity test for pair selection and a 5% Benjamini-Hochberg False Discovery Rate (FDR) to manage statistical significance.

The project’s motivation stems from the desire to build a robust prototype for pairs trading, a classic statistical arbitrage technique. Pairs trading capitalizes on temporary price divergences between two historically correlated assets, aiming for market neutrality. Tandon’s initiative spans a significant period in the Indian financial landscape, from January 1, 2015, to June 30, 2025, providing a comprehensive dataset for analysis. The core objective was to create a system that minimizes common algorithmic trading errors, ensuring a more realistic and reliable backtest.

Strategy Implementation and Technical Breakdown

The strategy employs a rolling walk-forward methodology, a standard practice in quantitative finance to simulate real-world trading conditions. This involves a 252-trading-day training window, approximately one year of historical data, followed by a 21-day testing step. This iterative process allows the strategy to adapt to changing market dynamics and re-estimate its parameters periodically.

Pair Selection and Cointegration

The foundation of the pairs trading strategy lies in identifying statistically cointegrated assets. Cointegration implies that while the prices of two assets may drift apart in the short term, they tend to revert to a long-term equilibrium relationship. Tandon’s approach to this involves:

  1. Hedge Ratio Estimation: During each training phase, the hedge ratio, denoted by the Greek letter beta (β), is estimated using Ordinary Least Squares (OLS) regression. This ratio quantifies the relative proportion in which the two stocks should be traded to hedge price movements. Specifically, the model is structured as: Stock A = α + β * Stock B + ε, where ε represents the error term. The estimated ‘β’ from this OLS regression becomes the hedge ratio for the subsequent trading period.

  2. Residual Stationarity Test: To confirm the cointegration, the residuals (the difference between the actual spread and its predicted value based on the hedge ratio) are subjected to a stationarity test. Tandon specifically utilizes the Augmented Dickey-Fuller (ADF) test, focusing on the ADF(0) variant. A stationary time series is one whose statistical properties, such as mean and variance, do not change over time, indicating a reversion to a mean. The MacKinnon p-value, derived from the ADF test, is crucial for determining the statistical significance of the stationarity. A low p-value suggests that the residuals are indeed stationary, implying a cointegrated relationship between the two stock prices.

  3. False Discovery Rate Control: Given that multiple pairs are being tested simultaneously, there is an inherent risk of identifying spurious cointegrations purely by chance – a phenomenon known as the multiple testing problem. To mitigate this, Tandon applies the Benjamini-Hochberg False Discovery Rate (FDR) at a 5% threshold. This statistical technique helps to control the proportion of rejected null hypotheses that are actually true null hypotheses (i.e., the proportion of falsely identified cointegrated pairs). By setting the FDR at 5%, Tandon aims to ensure that no more than 5% of the identified pairs are likely to be false positives, thereby enhancing the robustness of the pair selection process.

Through this rigorous selection process, three highly cointegrated pairs emerged from the initial analysis:

  • HDFCBANK.NS vs. KOTAKBANK.NS: Two of India’s leading private sector banks, exhibiting strong correlations due to their similar business models and exposure to the broader economic environment.
  • HEROMOTOCO.NS vs. ULTRACEMCO.NS: A combination of a major two-wheeler manufacturer and a prominent cement producer. While seemingly disparate, their cointegration could stem from broader economic indicators influencing both consumer spending and infrastructure development, or specific market dynamics within their respective sectors.
  • HCLTECH.NS vs. ICICIBANK.NS: An IT services giant and another of India’s premier private sector banks. The correlation here might be influenced by the tech sector’s demand for banking services, the overall health of the Indian economy impacting both IT exports and domestic banking, or capital flows between these sectors.

Signal Generation Logic

Once pairs are identified, the strategy generates trading signals based on the mean-reverting nature of their spread. The core principle is to trade when the spread deviates significantly from its historical mean and to exit when it reverts back.

To strictly avoid look-ahead bias, which occurs when future information is used in historical backtesting, rolling variables for standard deviation and mean are calculated. These are then strictly shifted by one day (shift(1) in Python). This ensures that at any given point in time, the calculation of the trading signal only relies on information available up to the previous trading day.

The Python code snippet illustrates this process:

Cointegrated Pairs Trading Strategy in Indian Equity Market (2015–2025) | EPAT Project
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
    model = sm.OLS(train_data[stock_a], train_data[stock_b]).fit()
    beta = model.params

    # 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
    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 = z_score < -1.5
    short_entry = z_score > 1.5
    exit_signal = (z_score.shift(1) * z_score <= 0) # Exit when spread crosses the mean

    return z_score, long_entry, short_entry, exit_signal

The signal generation logic is as follows:

  • Entry: A long position in the spread (buy Stock A, sell Stock B) is initiated when the z-score falls below -1.5, indicating that Stock A is relatively undervalued compared to Stock B. Conversely, a short position in the spread (sell Stock A, buy Stock B) is initiated when the z-score rises above +1.5, suggesting Stock A is relatively overvalued.
  • Exit: The position is closed when the z-score crosses zero, signifying that the spread has reverted to its historical mean. This is detected by checking if the z-score’s sign changes from the previous period to the current period.

This systematic approach ensures that trading decisions are based on statistically validated relationships and executed without the advantage of future information.

Portfolio and Risk Management

The strategy allocates an equal capital of ₹5,00,000 (approximately $6,000 USD at current exchange rates) to each active pair. This fixed capital allocation per pair simplifies the initial implementation. Comprehensive portfolio-level risk metrics are tracked throughout the backtest, providing insights into the strategy’s overall performance and risk exposure. Transaction costs are explicitly included at 5 basis points (bps) per leg per side, reflecting a realistic trading environment where brokerage fees, taxes, and slippage are accounted for.

Key Findings and Portfolio Performance

The out-of-sample backtest, conducted over the period from January 11, 2016, to June 27, 2025, reveals the strategy’s performance characteristics. Despite the academic nature of the implementation, the strategy generated a total Profit and Loss (PnL) of ₹1,65,544.97 on a capital base of ₹15,00,000 (across three pairs). This translates to a PnL per capital ratio of 11.04%.

Here’s a detailed snapshot of the strategy’s performance:

  • Capital Base: ₹15,00,000
  • Pairs Traded: 3
  • Backtest Period: Jan 11, 2016 – Jun 27, 2025
  • Total Trades: 271
  • Win Ratio: 63.47%
  • Total PnL: ₹1,65,544.97
  • PnL / Capital: 11.04%
  • Annualized Return: 0.30%
  • Annualized Volatility: 13.34%
  • Sharpe Ratio: 0.089
  • Max Drawdown: -34.31%

The annualized return of 0.30% appears modest, especially when compared to the annualized volatility of 13.34%. This results in a low Sharpe Ratio of 0.089, indicating that the risk-adjusted returns were not particularly compelling over the tested period. The most significant concern highlighted by the performance metrics is the substantial maximum drawdown of -34.31%. This suggests that the strategy, in its current form, experienced significant periods of loss, which could be a deterrent for risk-averse investors. The win ratio of 63.47% is respectable, but the profitability of winning trades may not have been sufficient to offset the losses from the remaining 36.53% of trades, or the losing trades may have been larger in magnitude.

The modest annualized return and high drawdown suggest that while the strategy successfully identified cointegrated pairs and traded their mean reversion, the profit generated per trade or the frequency of profitable trades was not substantial enough to overcome the inherent risks and transaction costs over the long term. The low Sharpe ratio further reinforces this observation, indicating inefficient risk-adjusted returns.

Challenges and Limitations

Despite the rigorous methodology, several challenges and limitations are inherent to this academic implementation and pairs trading strategies in general. The concentrated nature of trading only three pairs, while reducing complexity, also limits diversification. If one pair experiences a structural breakdown in its cointegration or a sustained divergence, it can significantly impact overall portfolio performance.

Furthermore, the assumption of stationarity for cointegrated pairs can break down during periods of significant market regime shifts, increased volatility, or specific company-specific news. The fixed entry and exit thresholds (z-score > 1.5 for entry, 0 for exit) might not be optimal across all market conditions. The chosen training window of 252 days and testing step of 21 days are parameters that could be further optimized.

A critical limitation of many historical backtests, including this one unless explicitly addressed, is survivorship bias. If the universe of 25 large-cap stocks is fixed over the entire backtesting period and does not account for companies that were delisted or no longer meet the large-cap criteria at different points in time, the results can be overly optimistic. The strategy’s performance is also sensitive to the accuracy of historical data and the chosen cost structure.

Next Steps: Enhancing Strategy Performance

Tandon outlines several avenues for improvement, focusing on enhancing risk-adjusted returns and real-world applicability:

  1. Optimize ADF Lag Selection: Moving beyond the ADF(0) shortcut to employ information criterion-based lag selectors (like AIC or BIC) can lead to more accurate cointegration detection, reducing the risk of spurious relationships and improving the quality of pair selection.

    Cointegrated Pairs Trading Strategy in Indian Equity Market (2015–2025) | EPAT Project
  2. Expand Universe and Diversify Pairs: Increasing the stock universe beyond the current 25 large-cap stocks to include mid-cap NSE stocks and exploring additional sectors such as Energy, Fast-Moving Consumer Goods (FMCG), and Metals can yield a broader range of cointegrated candidates. This diversification would reduce the impact of any single pair’s failure and potentially uncover more robust trading opportunities.

  3. Introduce Dynamic Position Sizing: The current fixed capital allocation of ₹5,00,000 per pair could be replaced with dynamic sizing techniques. Volatility-scaled sizing, such as inverse-volatility weighting or Kelly criterion-based allocation, would allow the strategy to allocate more capital to pairs exhibiting stronger mean-reversion signals and tighter spreads, thereby potentially improving the overall Sharpe ratio and reducing drawdowns.

  4. Refine Entry/Exit Thresholds Adaptively: The static z-score thresholds of ±1.5 for entry and 0 for exit might not be optimal in all market regimes. Developing an adaptive threshold model, where entry and exit levels are calibrated to each pair’s rolling volatility or classified market regime (e.g., trending vs. mean-reverting), can help filter out lower-quality signals and improve the win ratio.

  5. Incorporate Stop-Loss Rules: The significant maximum drawdown suggests a need for robust risk management. Implementing pair-level stop-loss rules, such as exiting a position when the z-score breaches a higher threshold (e.g., ±3.0) or when the unrealized loss exceeds a predefined percentage of allocated capital, would cap downside risk during regime-breaking events and substantially improve the Sharpe ratio.

  6. Address Survivorship Bias: To create more realistic forward-looking performance estimates, the fixed 25-stock universe should be replaced with a rolling universe approach. This would involve using point-in-time NSE Nifty 50 or Nifty 100 constituent lists, accurately reflecting the index composition at each training window, thereby eliminating survivorship bias.

Broader Implications and Continuous Learning

Shant Tandon’s project underscores the critical importance of rigorous methodology and risk management in quantitative trading. The development of a market-neutral strategy like pairs trading, when executed with attention to detail regarding statistical validity and trading costs, offers a valuable alternative to directional betting in financial markets.

The insights gained from this project are highly relevant for aspiring quantitative traders and portfolio managers. The challenges identified, particularly the high drawdown and modest risk-adjusted returns, highlight areas where further research and development are crucial for real-world trading success. The proposed next steps provide a clear roadmap for enhancing the strategy’s robustness and profitability.

For individuals looking to delve deeper into the concepts of statistical arbitrage, cointegration testing, and mean-reversion strategies, a structured learning path is recommended. Foundational courses in "Python for Trading Basics" and "Mean Reversion Trading Strategy" by experts like Dr. Ernest P. Chan can provide a solid grounding. For those aiming for more advanced techniques, learning tracks on "Advanced Algorithmic Trading Strategies," "Factor Based Investing," "Quantitative Portfolio Management," and "Backtesting Trading Strategies" offer comprehensive knowledge.

For hands-on experience, curated learning tracks such as "Quantitative Trading" and "Artificial Intelligence in Trading" are invaluable. These programs cover end-to-end aspects of trading system development, from data handling and feature engineering to model deployment. Aspiring professionals who wish to replicate such end-to-end projects with industry guidance might consider comprehensive programs like the Executive Programme in Algorithmic Trading (EPAT). Such programs equip participants with the essential skills in Python, statistics, machine learning, backtesting, and real-world trading applications, mirroring the comprehensive approach taken in Tandon’s final project.

The disclaimer accompanying the project emphasizes that all information is provided for informational purposes only, and past performance is not indicative of future results. QuantInsti® and the student disclaim any liability in connection with the use of this information, reinforcing the principle that trading inherently involves risk and potential for loss.

This academic exercise by Shant Tandon serves as a compelling case study, demonstrating the potential and the inherent complexities of applying statistical arbitrage strategies in a dynamic market like India’s. The project’s transparent methodology and clear articulation of limitations and future enhancements offer valuable lessons for anyone venturing into the field of algorithmic trading.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button