Skip to content

Understanding Backtesting - A Complete Beginner's Guide ​

What is Backtesting? ​

Backtesting is like a flight simulator for traders. Just as pilots practice flying in a simulator before flying real planes, traders test their strategies on historical data before risking real money.

In Simple Terms:

  • You write rules for when to buy and sell stocks
  • The computer applies these rules to past market data
  • You see if your strategy would have made or lost money

Why Backtest? ​

1. Risk-Free Learning ​

Test strategies without losing real money. Make all your mistakes in simulation first.

2. Validate Ideas ​

That "brilliant" trading idea might not be so brilliant. Backtesting reveals the truth using actual data.

3. Understand Performance ​

Learn how your strategy performs in different market conditions - bull markets, bear markets, and sideways markets.

4. Build Confidence ​

Seeing your strategy work on years of historical data builds confidence to trade it with real money.

Core Concepts Explained ​

Market Data (OHLCV) ​

Every trading day, stocks generate five key data points:

Open  (O): First trade price of the day ($150.00)
High  (H): Highest price reached ($152.50)
Low   (L): Lowest price reached ($149.25)
Close (C): Last trade price of the day ($151.00)
Volume(V): Number of shares traded (10,000,000)

Visual Example:

     |    <- High ($152.50)
     |
   +-+-+
   | | |  <- Open ($150.00)
   | | |
   +-+-+  <- Close ($151.00)
     |
     |    <- Low ($149.25)

Trading Signals ​

Signals tell you when to buy or sell:

Buy Signal Example:

python
if price > moving_average:
    # Stock is trending up - BUY!

Sell Signal Example:

python
if price < moving_average:
    # Stock is trending down - SELL!

Position ​

Your position is how many shares you own:

  • No position: You own 0 shares
  • Long position: You own shares (betting price will rise)
  • Flat: You sold everything and have no shares

Portfolio ​

Your portfolio is your trading account:

  • Cash: Money available to buy stocks
  • Positions: Stocks you currently own
  • Equity: Total value (cash + stock values)

How Backtesting Works ​

Step-by-Step Process ​

  1. Start with virtual money

    Starting Cash: $10,000
  2. Process each historical day

    Day 1: Check signals → No action
    Day 2: Buy signal → Buy 100 shares at $50
    Day 3: Hold position
    Day 4: Sell signal → Sell 100 shares at $52
  3. Track every trade

    Trade 1: Bought at $50, Sold at $52
    Profit: $200 (100 shares × $2)
  4. Calculate final results

    Ending Cash: $10,200
    Total Return: 2% ($200 / $10,000)

Real Example Walkthrough ​

Let's trace through a simple strategy:

python
def strategy(data_contexts, portfolio, state):
    """Buy when price is low, sell when high"""
    
    aapl = data_contexts['AAPL']
    current_price = aapl.close
    average_price = aapl.sma(20)  # 20-day average
    
    # If price is 5% below average - it's cheap, buy!
    if current_price < average_price * 0.95:
        if portfolio.cash > current_price * 100:
            return {'symbol': 'AAPL', 'action': 'buy', 'quantity': 100}
    
    # If price is 5% above average - it's expensive, sell!
    elif current_price > average_price * 1.05:
        if portfolio.position('AAPL') > 0:
            return {'symbol': 'AAPL', 'action': 'sell', 'quantity': 'all'}
    
    return None

What Happens:

  • Day 1-19: Building up 20-day average (no trades)
  • Day 20: Price=$100, Average=$102 → No signal
  • Day 25: Price=$96, Average=$101 → Below 95% → BUY!
  • Day 30: Price=$107, Average=$102 → Above 105% → SELL!
  • Profit: $11 per share ($107 - $96)

Understanding Results ​

Key Metrics Explained ​

Total Return

How much money you made/lost as a percentage
Example: Started with $10,000, ended with $11,500
Return = 15% profit

Sharpe Ratio

Risk-adjusted returns (Higher is better)
< 0: Losing money
0-1: Okay returns
1-2: Good returns
> 2: Excellent returns

Max Drawdown

Biggest loss from peak to bottom
Example: Portfolio goes $10,000 → $12,000 → $9,000
Max Drawdown = -25% (from $12,000 to $9,000)

Win Rate

Percentage of profitable trades
Example: 6 winning trades, 4 losing trades
Win Rate = 60%

Reading the Equity Curve ​

The equity curve shows your portfolio value over time:

$12,000 |           /\
$11,000 |       /\  /  \
$10,000 | -----/  \/    \
$ 9,000 |                \
        +------------------
         Jan Feb Mar Apr May

What to Look For:

  • Steady upward slope = Good strategy
  • Lots of ups and downs = Volatile strategy
  • Downward slope = Losing strategy

Common Beginner Mistakes ​

1. Overfitting ​

Creating a strategy that works perfectly on past data but fails on new data.

Wrong Approach:

python
# Too specific to historical data
if date == "2021-03-15" and price == 245.67:
    buy()  # This won't work in the future!

Right Approach:

python
# General principle that can work anytime
if rsi < 30:  # Buy when oversold
    buy()

2. Look-Ahead Bias ​

Using information that wouldn't be available at that time.

Wrong:

python
# Can't know tomorrow's price today!
if tomorrow_price > today_price:
    buy()

Right:

python
# Only use past and present data
if yesterday_price < today_price:
    buy()

3. Ignoring Transaction Costs ​

Real trading has costs that eat into profits:

  • Commissions: Fee per trade
  • Spread: Difference between buy/sell price
  • Slippage: Price movement during order execution

4. Survivorship Bias ​

Testing only on stocks that still exist today, ignoring companies that went bankrupt.

Technical Indicators Simplified ​

Moving Average (MA) ​

The average price over N days. Smooths out price noise.

Daily Prices: $10, $12, $11, $13, $12
5-Day Average: $11.60

Usage: Price above MA = Uptrend, Price below MA = Downtrend

RSI (Relative Strength Index) ​

Measures if a stock is overbought or oversold (0-100 scale).

RSI < 30: Oversold (might bounce up)
RSI 30-70: Normal
RSI > 70: Overbought (might drop down)

Volume ​

Number of shares traded. High volume confirms price moves.

Normal Volume: 1 million shares/day
Today's Volume: 3 million shares
Interpretation: Strong interest in the stock

Your Learning Path ​

Week 1: Basics ​

  1. Run the pre-loaded strategy
  2. Change the stock symbol
  3. Adjust the buy/sell quantities
  4. Observe how results change

Week 2: Indicators ​

  1. Learn moving averages
  2. Understand RSI
  3. Combine multiple indicators
  4. Create simple conditions

Week 3: Risk Management ​

  1. Add stop losses
  2. Control position sizes
  3. Limit number of trades
  4. Protect profits

Week 4: Advanced Concepts ​

  1. Trade multiple stocks
  2. Portfolio rebalancing
  3. Market regime detection
  4. Performance optimization

Practice Exercises ​

Exercise 1: Modify the Example ​

Take the pre-loaded strategy and:

  • Change from AAPL to GOOGL
  • Change from 100 shares to 50 shares
  • Run backtest and compare results

Exercise 2: Add a Condition ​

Add RSI to the strategy:

python
# Only buy if RSI < 40 (more oversold)
if sma_20 > sma_50 and rsi < 40:
    buy()

Exercise 3: Risk Management ​

Add a stop loss:

python
# Sell if we lose 5%
if position > 0 and current_price < entry_price * 0.95:
    sell()

Key Takeaways ​

  1. Backtesting is Practice: Test strategies safely on historical data
  2. Data Drives Decisions: Use price, volume, and indicators
  3. Risk Management Matters: Protect your capital with stops
  4. Keep It Simple: Complex doesn't mean better
  5. Past ≠ Future: Good backtest results don't guarantee future profits

Next Steps ​

Ready to dive deeper? Continue with:


Remember: The goal isn't to find a "perfect" strategy, but to understand how markets work and develop disciplined trading approaches.

Test your trading strategies risk-free with professional backtesting.