How to Backtest a Trading Strategy in Python: A Beginner Guide
This walks through the smallest possible correct backtest — a moving-average crossover on daily data — and, more importantly, the mistakes that make a backtest lie to you.
1. The Strategy
Buy when the 20-day moving average crosses above the 50-day moving average (“golden cross”), exit when it crosses back below.
import pandas as pd
import numpy as np
df = pd.read_csv("nifty_daily.csv", parse_dates=["date"], index_col="date")
df["ma_fast"] = df["close"].rolling(20).mean()
df["ma_slow"] = df["close"].rolling(50).mean()
df["signal"] = np.where(df["ma_fast"] > df["ma_slow"], 1, 0)
2. The Mistake That Breaks Almost Every First Backtest: Lookahead Bias
If you compute today’s return using today’s signal, you’re trading on information (today’s closing price) before it existed. Shift the signal forward by one bar so you only act on yesterday’s confirmed crossover:
df["position"] = df["signal"].shift(1) # act on yesterday's signal, not today's
df["daily_return"] = df["close"].pct_change()
df["strategy_return"] = df["position"] * df["daily_return"]
Skipping this .shift(1) is the single most common reason a beginner’s backtest shows an unrealistically smooth equity curve.
3. Build the Equity Curve
df["equity_curve"] = (1 + df["strategy_return"].fillna(0)).cumprod()
import matplotlib.pyplot as plt
df["equity_curve"].plot(title="Strategy Equity Curve")
plt.show()
4. Account for Costs — Or the Result Is Fiction
TRANSACTION_COST = 0.0005 # 0.05% per trade, adjust for your actual brokerage + STT + slippage
df["trade"] = df["position"].diff().abs() # 1 whenever position changes
df["strategy_return_net"] = df["strategy_return"] - (df["trade"] * TRANSACTION_COST)
df["equity_curve_net"] = (1 + df["strategy_return_net"].fillna(0)).cumprod()
A crossover strategy with frequent whipsaws in a sideways market can look profitable gross of costs and lose money net of costs. Always compare both curves before concluding anything.
5. Basic Performance Metrics
def sharpe_ratio(returns, periods_per_year=252, risk_free_rate=0.0):
excess = returns - risk_free_rate / periods_per_year
return np.sqrt(periods_per_year) * excess.mean() / excess.std()
def max_drawdown(equity_curve):
running_max = equity_curve.cummax()
drawdown = (equity_curve - running_max) / running_max
return drawdown.min()
print(f"Sharpe (net): {sharpe_ratio(df['strategy_return_net'].dropna()):.2f}")
print(f"Max drawdown (net): {max_drawdown(df['equity_curve_net']):.2%}")
A strategy’s Sharpe ratio means little without its max drawdown next to it — a high Sharpe strategy that occasionally loses 40% of capital is not the same risk profile as one that stays within a 10% drawdown band.
6. Checklist Before You Trust Any Backtest
- Signal is shifted forward so you never trade on same-bar information (no lookahead bias)
- Transaction costs and slippage are modeled, not assumed to be zero
- The test period includes at least one bear market or sharp correction, not just a bull run
- Results are checked out-of-sample (a period the strategy wasn’t tuned on), not just in-sample
- Position sizing is applied — see Risk Management Basics — not a flat “1 unit” assumption
Once this is solid, the mean reversion with VectorBT and Ornstein-Uhlenbeck pairs trading articles on this site extend the same framework to more involved strategies.
Important Notice & Educational Purpose: XAlgoPro (xalgopro.com) and its authors/contributors are NOT SEBI registered Research Analysts (RA) or Investment Advisers (IA) under the SEBI (Research Analysts) Regulations, 2014, or SEBI (Investment Advisers) Regulations, 2013.
All content, algorithmic logic, indicators, Pine Script codes, Python scripts, statistical models, mathematical formulas, and backtest results presented on this platform are published strictly for educational, academic, and technological research purposes only. Nothing on this website constitutes investment advice, financial guidance, an offer, recommendation, or solicitation to buy or sell any security, derivative, contract, or financial instrument on the National Stock Exchange (NSE), Bombay Stock Exchange (BSE), or any other global exchange.
SEBI Statutory Risk Disclosure on Derivatives (F&O):As per SEBI study on Intraday & Derivatives trading, 9 out of 10 individual traders in the Equity Futures and Options (F&O) segment incurred net losses, with an average loss of over ₹50,000 per trader. Over and above net trading losses, loss-makers expended an additional 15% to 50% in transaction fees, brokerage, and statutory taxes (STT, GST, Stamp Duty). Trading options and futures involves substantial financial risk, leverage, and potential loss of entire invested capital.
Past algorithmic backtest performance or hypothetical simulations do not guarantee or represent future live trading results. Readers and users must perform their own independent due diligence, test thoroughly in simulated/paper trading environments, and consult an authorized SEBI Registered Financial Advisor before risking actual capital in Indian equity or derivatives markets. You are solely responsible for all trading decisions, capital allocations, and monetary risks undertaken.