Connecting to market data...
4

Level 4 of 7

Strategy Design

Learn to design, code, and evaluate systematic trading strategies for Indian markets.

18 hours4 modules

Learning Objectives

  • Formulate quantitative trading rules and entry/exit logic
  • Implement and interpret technical indicators for signal generation
  • Design robust entry and exit systems with risk management
  • Conduct rigorous backtesting with proper transaction cost modeling
  • Construct and evaluate factor-based investment strategies for Indian equities
  • Implement mean reversion and statistical arbitrage strategies using cointegration
1

Trading Rules

3h · 6 topics

Formalize trading decisions as systematic rules that can be coded and tested.

Signal generationRule formalizationThreshold optimizationLook-ahead biasSignal combinationRule decay

A trading strategy is only as good as the rules that define it. Vague rules like "buy when it looks like a good entry" cannot be backtested or automated. Every quantitative strategy must specify, in precise mathematical terms, exactly when to enter, how much to trade, when to exit, and how to manage risk.

Signal generation starts with a hypothesis about market behavior. Momentum strategies are based on the observation that stocks that have performed well tend to continue performing well over 3-12 month horizons. Mean reversion strategies exploit the tendency for extreme moves to partially reverse. Breakout strategies capture sustained moves after price exceeds a resistance level. Each hypothesis must be converted to a precise, unambiguous rule.

Rule formalization eliminates ambiguity. Instead of "buy when the stock looks strong," a formal rule is: "If the 50-day moving average exceeds the 200-day moving average AND the 14-day RSI is above 50, initiate a long position equivalent to 5% of portfolio equity on the next day's open." This rule is specific, testable, and falsifiable — the essential characteristics of a quantitative strategy.

Threshold optimization is the process of selecting parameter values. For a moving average crossover strategy, what lookback periods work best? Grid searching across thousands of parameter combinations is common, but this creates multiple testing problems. A better approach is to choose thresholds based on economic reasoning — for instance, 20 days equals about 1 month and 200 days equals about 1 year — and test only a few reasonable combinations.

Look-ahead bias is the cardinal sin of backtesting. The most common form is using closing price data to generate signals that would actually trigger at the close — in reality, you would only know the close after the market closes. The correct approach is to use today's signal to trade at tomorrow's open. Other forms include using data that is revised later (like earnings data), using index compositions from the future, or using corporate action data not available on the trade date.

Signal combination is where strategy design gets sophisticated. Rather than relying on a single signal, most robust strategies combine multiple independent signals. A common framework is: combined_signal = w1 x momentum + w2 x mean_reversion + w3 x volume_confirmation. The weights can be equal, based on standalone performance, or dynamically adjusted based on recent signal efficacy. The key is that combined signals are more robust than individual ones.

Signal decay is a persistent challenge. As strategies become known, their edge erodes — this is the efficient market hypothesis in action. A momentum strategy that worked in 2000-2010 may generate lower returns in 2016-2026 as more market participants implement it. Regular monitoring of signal effectiveness and willingness to adapt or retire decaying signals is essential for long-term quant success.

For Indian markets, specific considerations include: adjusting for the higher impact of FII flows on large caps, accounting for the distinct behavior during F&O expiry weeks, incorporating the Friday effect (options expiry on Nifty weekly), and modeling the budget day window (Feb 1) as a separate regime with elevated volatility and potential gap moves.

2

Technical Indicators

3h · 6 topics

Master the mathematical formulation and application of key technical indicators for quant strategies.

Moving averagesRSIMACDBollinger BandsVolume indicatorsMarket breadth

Technical indicators are mathematical transformations of price and volume data designed to extract signals. While technical analysis is sometimes dismissed as unscientific, its quantitative formulation makes many indicators legitimate tools for systematic strategies.

Moving averages are the simplest and most widely used indicators. The simple moving average (SMA) is the arithmetic mean of prices over a window: SMA(n) = (P1 + P2 + ... + Pn)/n. The exponential moving average (EMA) places more weight on recent prices: EMA(t) = a x P(t) + (1-a) x EMA(t-1). In Indian markets, the 50-day and 200-day SMAs are closely watched by institutional traders. When the Nifty 50 trades above its 200-day SMA, the long-term trend is considered bullish. A golden cross (50 crosses above 200) is a major bullish signal.

RSI, developed by J. Welles Wilder, measures momentum on a 0-100 scale: RSI = 100 - 100/(1 + RS), where RS = average gain / average loss over typically 14 periods. Values above 70 suggest overbought conditions (potential sell), and below 30 suggest oversold (potential buy). In trending markets, RSI can remain in overbought/oversold territory for extended periods — the indicator is most useful in ranging markets. For Indian indices, RSI at 70-75 during a strong bull run like 2021-2022 would have triggered premature sell signals.

MACD (Moving Average Convergence Divergence) = EMA(12) - EMA(26). The signal line is EMA(9) of the MACD. A bullish signal occurs when MACD crosses above the signal line; bearish when it crosses below. The MACD histogram (MACD - signal) is useful for identifying momentum changes. In Indian markets, MACD divergence — where the Nifty makes a higher high but MACD makes a lower high — has been a reliable warning signal for trend exhaustion.

Bollinger Bands (developed by John Bollinger) construct volatility envelopes: middle band = 20-day SMA, upper band = +2s, lower band = -2s. Price touching the upper band suggests overextension; price at the lower band suggests undervaluation in mean-reversion terms. The bands widen during high volatility and contract during low volatility. A Bollinger Band squeeze — when bands narrow significantly — often precedes an explosive move, making it a signal for volatility breakout strategies.

Volume indicators confirm price moves. On-balance volume (OBV) accumulates volume on up days and subtracts on down days. If OBV is rising while price is flat, accumulation may be occurring. Delivery volume percentage (delivery trades as a percentage of total volume) in Indian markets is a useful metric — high delivery percentage on up days suggests genuine buying rather than speculative activity.

Market breadth indicators like the advance-decline line (cumulative sum of advancing stocks minus declining stocks) and the percentage of stocks above their 200-day moving average provide a holistic view of market health. A Nifty new high with narrowing breadth (fewer stocks participating) is a classic divergence warning.

For quantitative implementation, indicators should be used as signal inputs rather than standalone decision makers. A robust strategy might combine: trend = (price > 200-day SMA), momentum = (RSI > 50), volatility = (Bollinger Band width > 20-day median). The ensemble of indicators, properly weighted, produces more reliable signals than any single indicator.

3

Entry/Exit Logic

3h · 6 topics

Design precise entry and exit rules with robust risk management for systematic strategies.

Entry triggersExit strategiesStop lossesProfit targetsScaling in/outTime-based exits

Entry and exit logic is the operational layer of a trading strategy — the precise rules that determine when and how trades are executed. A strategy with a great signal but poor execution will underperform, while well-designed entry/exit logic can enhance the performance of even mediocre signals.

Entry triggers must be precise and actionable. A typical entry rule: "Enter long when (1) the 14-day RSI crosses above 30 from below, (2) the stock is trading above its 50-day SMA, and (3) the daily volume exceeds the 20-day average volume." All three conditions must be true simultaneously. This eliminates ambiguity and provides a binary yes/no decision.

Multiple confirmation reduces false signals. Each additional condition lowers the number of potential trades but should improve the quality of those that do trigger. The challenge is balancing selectivity (fewer, higher-probability trades) with opportunity (enough trades to achieve statistical significance and smooth equity curves).

Exit strategies are arguably more important than entries. A trader can enter poorly but exit well and still profit; the reverse is nearly impossible. The four main exit types are:

Target exits: Take profit at a predetermined level. For a momentum strategy, this might be 2x the average true range (ATR). Target exits lock in gains and are essential for strategies with positive skew.

Stop-loss exits: Cut losses at a predetermined level. A fixed rupee stop (Rs 5,000 loss per trade) is simple but doesn't adapt to volatility. A volatility-based stop (2x ATR) adjusts to market conditions. A percentage stop (1% of portfolio per trade) ensures consistent risk per trade.

Trailing stops: The optimal exit technique for trend-following. A common method is the chandelier exit: stop = highest_high_since_entry - 3x ATR. As the stock rallies, the stop rises, locking in gains while allowing room for normal fluctuations.

Time stops: Exit after a fixed holding period regardless of price. This is essential for strategies based on mean reversion or event-driven signals where the edge decays with time. A typical rule: exit after 10 trading days if neither target nor stop is hit.

Scaling in and out is an advanced technique. Instead of entering a full position at once, enter one-third at the initial signal, one-third if the price moves favorably by 0.5 ATR, and one-third if it moves another 0.5 ATR. This reduces the impact of whipsaws and improves average entry prices. Similarly, scaling out — selling one-third at target, one-third at a higher target, and letting the rest run — achieves a balance between locking in profits and capturing trends.

In Indian markets, specific timing considerations apply. The first 30 minutes (9:15-9:45 AM IST) often have elevated volatility due to overnight gap adjustment. The last 30 minutes (3:00-3:30 PM) see FII and institutional flows as they rebalance. The weekly expiry on Thursday creates intraday volatility spikes. A robust entry/exit system should account for these intraday patterns — for instance, avoiding entries during the first 15 minutes and implementing tighter stops near expiry.

State machines are a clean way to formalize entry/exit logic. Each trade follows a defined sequence: IDLE -> SIGNAL_DETECTED -> ENTERING -> IN_POSITION -> EXITING -> IDLE. At each state, specific rules determine transitions. This programmatic approach eliminates emotional decision-making and ensures the strategy can be fully automated.

4

Backtesting Methodology

3h · 6 topics

Learn rigorous backtesting techniques that produce realistic performance estimates.

Walk-forward analysisTransaction costsSurvivorship biasOut-of-sample testingPerformance metricsMonte Carlo simulation

Backtesting is the process of evaluating a trading strategy using historical data. A well-designed backtest is the closest we can come to a controlled experiment in finance. A poorly designed backtest can produce spectacularly misleading results — this is the single most common cause of trading losses for systematic quants.

Walk-forward analysis is the gold standard for backtesting. The process: divide data into overlapping train/test windows. Train (optimize) on years 1-3, test on year 4. Then train on years 2-4, test on year 5. Continue until all data is tested. The out-of-sample test periods generate an equity curve that represents the strategy's realistic performance. This is far more reliable than a single train/test split.

Transaction costs are the most common reason backtest results fail to replicate in live trading. Indian market costs include: STT (0.1% on equity delivery, 0.01-0.05% on derivatives), brokerage (Rs 10-20 per trade for discount brokers, or 0.01-0.03% for percentage-based), stamp duty (0.003% on delivery), SEBI charges (Rs 10 per crore turnover), GST (18% on brokerage), and impact cost (the price deterioration from your own order). A strategy that appears profitable with 0.1% per-trade costs may become unprofitable with 0.3% realistic costs.

Survivorship bias inflates returns by only including stocks that exist today. A backtest of Nifty 50 stocks since 2000 would exclude companies that were once in the index but were replaced — companies like Jaiprakash Associates, Unitech, or Reliance Communications (now delisted/bankrupt). These excluded companies had terrible performance, so ignoring them makes the backtest look better than reality. Always use point-in-time index composition data.

Out-of-sample testing is non-negotiable. The data used for strategy development should be clearly separated from data used for final validation. A common approach: 60% development (further split into train/validate), 20% test (final evaluation), 20% left completely untouched as a garage period for future challenges. If any part of the strategy was influenced by the test data, it is no longer out-of-sample.

Key performance metrics beyond total return: CAGR (compound annual growth rate), Sharpe ratio (risk-adjusted return), Sortino ratio (downside risk only), Calmar ratio (return/max drawdown), max drawdown (largest peak-to-trough decline), win rate (percentage of profitable trades), profit factor (gross profit/gross loss), average holding period, and trade frequency.

Monte Carlo simulation tests robustness. Take the strategy's historical trade list (or return series). Resample them with replacement 10,000 times, each time creating a synthetic equity curve. Analyze the distribution of outcomes — the 5th percentile represents the worst-case scenario, the 50th percentile the median expectation, and the 95th percentile the best case. If the 5th percentile shows a loss, the strategy has meaningful tail risk.

Implementation shortfall is the final reality check. Live trading typically underperforms backtests by 30-50% in the first 6 months due to slippage, market impact, emotional execution errors, and regime differences. Building in a conservatism factor — assuming 70% of backtested returns for projections — is prudent. Only after 12+ months of live trading can you begin to trust that the backtest accurately reflects the strategy's potential.

Ready to Compete?

Apply what you have learned in the QuantX competition. Submit your strategies, climb the leaderboard, and build your Quanta Score.

Enter Competition