Getting started with backtesting does not need to be intimidating. In the Indian context, a lightweight CSV-based backtester can teach you the core ideas without heavy infrastructure. This article explains a clear, easy-to-follow path: prepare data, implement a simple simulation loop, account for costs and slippage, and evaluate results with practical metrics.
Why build a small backtester?
A small backtester helps you learn how strategies behave on historical data before risking real capital. It is ideal for individual traders testing ideas on NSE or BSE stocks, indices, or ETFs using daily or minute-level CSV files. You will understand execution, order handling, fees, and how to measure performance.
Data format and preparation
Use clean CSV files with these columns: Date, Open, High, Low, Close, Volume. Ensure the Date is in a consistent format (for example YYYY-MM-DD) and values are numeric. For minute data include Time or a timestamp column. Always sort rows in chronological order (oldest first).
Load and sanity-check your CSV
- Confirm there are no missing dates or duplicated timestamps.
- Check for obvious outliers or erroneous prices (zero or negative).
- If you work with multiple tickers, store each CSV separately and align by timestamp for multi-asset testing.
Simple simulation loop (conceptual)
1. Start with initial capital, for example ₹100,000.
2. For each row (time step) in your CSV:
- Calculate signals from your strategy (e.g., moving average crossover).
- Translate signals into orders (market or limit).
- Simulate execution using next available price (e.g., next bar open for market orders).
- Deduct transaction costs and taxes.
- Update positions and account balance.
3. Record trade-level and daily account metrics for analysis.
Example pseudocode (plain language)
- capital = 100000
- position = 0
- for each day:
- signal = compute_signal(prices)
- if signal == buy and position == 0:
- quantity = floor(capital * risk_per_trade / price)
- execute at next_open_price
- capital -= quantity * price + fees
- position = quantity
- if signal == sell and position > 0:
- execute sell at next_open_price
- capital += position * price - fees
- position = 0
- record equity = capital + position * current_close
Transaction costs and Indian specifics
Always model realistic costs: brokerage, exchange transaction charges, GST and securities transaction tax (STT) when applicable, plus slippage. For small retail trades in India, brokerage per order can be a fixed fee or broker-dependent; include a conservative estimate. For instance, if a broker charges approximately ₹20-50 per trade or percentage-based fees, include that amount in each simulated execution. Slippage is often a small percentage of price on liquid instruments and may be modelled as a fixed number of paise or a percent of trade value.
Risk controls and position sizing
Include simple risk rules:
Performance metrics to track
Track basic metrics daily and for the strategy overall:
- Net return and annualised return
- Maximum drawdown and drawdown duration
- Win rate, average win/loss
- Risk-adjusted metrics such as Sharpe ratio (use risk-free rate appropriate to Indian context, e.g., short-term gilt yields)
- Trade-level statistics: average holding period, turnover, total commissions paid
Validation and robustness
Run simple stress tests:
- Walk-forward testing: split history into in-sample and out-of-sample periods.
- Parameter sensitivity: vary lookback lengths or thresholds to see stability.
- Monte Carlo resampling of trade sequences to estimate variability.
Record keeping and reproducibility
Keep each backtest run reproducible: store the CSV snapshots, code version, parameter values, and a summary log. Save trade logs with timestamps, prices, fees and account equity after each trade.
Practical tips
Next steps
Once you understand a simple CSV backtester, you can extend it to multiple instruments, intraday data, limit orders, or integrate with databases and charts. The goal is to learn the feedback loop: strategy → simulation → evaluation → improve. That loop will help you develop more robust methods for the Indian markets.
Why build a small backtester?
A small backtester helps you learn how strategies behave on historical data before risking real capital. It is ideal for individual traders testing ideas on NSE or BSE stocks, indices, or ETFs using daily or minute-level CSV files. You will understand execution, order handling, fees, and how to measure performance.
Data format and preparation
Use clean CSV files with these columns: Date, Open, High, Low, Close, Volume. Ensure the Date is in a consistent format (for example YYYY-MM-DD) and values are numeric. For minute data include Time or a timestamp column. Always sort rows in chronological order (oldest first).
Load and sanity-check your CSV
- Confirm there are no missing dates or duplicated timestamps.
- Check for obvious outliers or erroneous prices (zero or negative).
- If you work with multiple tickers, store each CSV separately and align by timestamp for multi-asset testing.
Simple simulation loop (conceptual)
1. Start with initial capital, for example ₹100,000.
2. For each row (time step) in your CSV:
- Calculate signals from your strategy (e.g., moving average crossover).
- Translate signals into orders (market or limit).
- Simulate execution using next available price (e.g., next bar open for market orders).
- Deduct transaction costs and taxes.
- Update positions and account balance.
3. Record trade-level and daily account metrics for analysis.
Example pseudocode (plain language)
- capital = 100000
- position = 0
- for each day:
- signal = compute_signal(prices)
- if signal == buy and position == 0:
- quantity = floor(capital * risk_per_trade / price)
- execute at next_open_price
- capital -= quantity * price + fees
- position = quantity
- if signal == sell and position > 0:
- execute sell at next_open_price
- capital += position * price - fees
- position = 0
- record equity = capital + position * current_close
Transaction costs and Indian specifics
Always model realistic costs: brokerage, exchange transaction charges, GST and securities transaction tax (STT) when applicable, plus slippage. For small retail trades in India, brokerage per order can be a fixed fee or broker-dependent; include a conservative estimate. For instance, if a broker charges approximately ₹20-50 per trade or percentage-based fees, include that amount in each simulated execution. Slippage is often a small percentage of price on liquid instruments and may be modelled as a fixed number of paise or a percent of trade value.
Risk controls and position sizing
Include simple risk rules:
- Limit exposure per trade (e.g., 2–5% of capital).
- Max drawdown stop: stop trading after a predefined drawdown and review.
Performance metrics to track
Track basic metrics daily and for the strategy overall:
- Net return and annualised return
- Maximum drawdown and drawdown duration
- Win rate, average win/loss
- Risk-adjusted metrics such as Sharpe ratio (use risk-free rate appropriate to Indian context, e.g., short-term gilt yields)
- Trade-level statistics: average holding period, turnover, total commissions paid
Validation and robustness
Run simple stress tests:
- Walk-forward testing: split history into in-sample and out-of-sample periods.
- Parameter sensitivity: vary lookback lengths or thresholds to see stability.
- Monte Carlo resampling of trade sequences to estimate variability.
Record keeping and reproducibility
Keep each backtest run reproducible: store the CSV snapshots, code version, parameter values, and a summary log. Save trade logs with timestamps, prices, fees and account equity after each trade.
Practical tips
Start small and simple. A CSV-based backtester teaches the fundamentals. Add complexity—order types, intraday fills, slippage models—only after your simple model behaves sensibly.
Next steps
Once you understand a simple CSV backtester, you can extend it to multiple instruments, intraday data, limit orders, or integrate with databases and charts. The goal is to learn the feedback loop: strategy → simulation → evaluation → improve. That loop will help you develop more robust methods for the Indian markets.