HomePhase 3: Trading StrategiesLesson 12
Lesson 12 of 24Phase 3: Trading StrategiesBeginner–Intermediate

Building Your Own Strategy Simulator (Backtester)

Build a beginner-friendly Python strategy backtester from scratch to simulate historical crypto trades, plot equity curves, and measure performance.

Bitfoster Team
December 3, 2026
11 Min Read
lesson-12-strategy-backtester/
Building Your Own Strategy Simulator (Backtester)

Hands-On Deliverable

A strategy simulator that outputs a visual equity curve chart and performance summary.

Imagine you have an idea for a trading strategy: "Buy Bitcoin whenever the 10-hour moving average crosses above the 30-hour moving average, and sell when it crosses back below."

How do you know if that idea is brilliant or a fast way to lose money? You definitely shouldn't test it with real cash first! Instead, you build a backtester—a time machine for your trading rules. A backtester replays historical candlestick data one bar at a time, pretends your bot was trading back then, tracks your virtual wallet balance, and draws a chart of how your account would have grown (or shrunk).

In this lesson, you will build a clean, easy-to-read Python strategy simulator from scratch that outputs:

  • A performance summary (Total Return, Buy-and-Hold comparison, Number of Trades, Win Rate, and Max Drawdown).
  • A visual equity curve chart saved as equity_curve.png so you can literally see how smooth or bumpy the ride was.

Educational Note: Backtests are simplified historical simulations—past performance never guarantees future results. Always treat backtesting as an educational research step, and run any live bot experiments on Binance Testnet with virtual funds (never financial advice).


Why Build Your Own Simulator?

Professional backtesting frameworks have hundreds of settings and cryptic error messages. When you are learning, writing a 120-line loop yourself teaches you the exact mechanics of trading:

  • Tracking cash (USDT) vs. holdings (BTC).
  • Understanding equity (cash + btc_held * current_price).
  • Measuring Max Drawdown—the worst peak-to-valley drop your account suffered. (A strategy that makes +40% sounds great, until you learn it dropped -60% along the way!)

Prerequisites

Install pandas, matplotlib, and requests:

pip install pandas matplotlib requests

Coding the Strategy Backtester

Create a file named backtester.py. It downloads 500 hourly BTCUSDT candles from Binance, runs a classic SMA Crossover Strategy (Fast SMA 10 vs. Slow SMA 30), prints a full scorecard, and saves a visual equity curve chart.

"""
Lesson 12: Building Your Own Strategy Simulator (Backtester)
Deliverable: Strategy simulator outputting a performance summary + equity_curve.png
"""

import requests
import pandas as pd
import matplotlib.pyplot as plt


def fetch_historical_candles(symbol: str = "BTCUSDT", interval: str = "1h", limit: int = 500) -> pd.DataFrame:
    """Download historical OHLCV candles from Binance's public API."""
    url = "https://api.binance.com/api/v3/klines"
    params = {"symbol": symbol, "interval": interval, "limit": limit}
    resp = requests.get(url, params=params, timeout=10)
    resp.raise_for_status()

    cols = [
        "open_time", "open", "high", "low", "close", "volume",
        "close_time", "quote_volume", "trades", "taker_buy_base",
        "taker_buy_quote", "ignore"
    ]
    df = pd.DataFrame(resp.json(), columns=cols)
    df["timestamp"] = pd.to_datetime(df["open_time"], unit="ms")
    for col in ["open", "high", "low", "close", "volume"]:
        df[col] = df[col].astype(float)

    return df[["timestamp", "open", "high", "low", "close", "volume"]]


def run_sma_backtest(
    df: pd.DataFrame,
    fast_window: int = 10,
    slow_window: int = 30,
    initial_capital: float = 10_000.0,
) -> tuple[pd.DataFrame, list[dict]]:
    """
    Simulate a long-only SMA crossover strategy.
    - BUY when fast SMA > slow SMA and we hold cash.
    - SELL when fast SMA < slow SMA and we hold BTC.
    """
    data = df.copy()
    data["sma_fast"] = data["close"].rolling(fast_window).mean()
    data["sma_slow"] = data["close"].rolling(slow_window).mean()
    data = data.dropna().reset_index(drop=True)

    cash = initial_capital
    btc_held = 0.0
    entry_price = 0.0
    trades = []
    equity_history = []

    for _, row in data.iterrows():
        price = row["close"]
        timestamp = row["timestamp"]

        # Entry rule: Fast SMA crosses above Slow SMA
        if row["sma_fast"] > row["sma_slow"] and btc_held == 0.0:
            btc_held = cash / price
            entry_price = price
            cash = 0.0
            trades.append({"time": timestamp, "side": "BUY", "price": price, "pnl_pct": None})

        # Exit rule: Fast SMA crosses below Slow SMA
        elif row["sma_fast"] < row["sma_slow"] and btc_held > 0.0:
            cash = btc_held * price
            pnl_pct = ((price - entry_price) / entry_price) * 100
            btc_held = 0.0
            trades.append({"time": timestamp, "side": "SELL", "price": price, "pnl_pct": pnl_pct})

        # Track total portfolio value on every candle
        total_equity = cash + (btc_held * price)
        equity_history.append(total_equity)

    data["equity"] = equity_history
    # Also compute a simple Buy & Hold benchmark for comparison
    first_price = data["close"].iloc[0]
    data["buy_and_hold"] = initial_capital * (data["close"] / first_price)
    return data, trades


def calculate_max_drawdown(equity_series: pd.Series) -> float:
    """Return the worst peak-to-trough percentage drop."""
    running_peak = equity_series.cummax()
    drawdown = (equity_series - running_peak) / running_peak
    return drawdown.min() * 100  # Negative percentage


def print_summary(results: pd.DataFrame, trades: list[dict], initial_capital: float) -> None:
    """Print an easy-to-read performance scorecard."""
    final_equity = results["equity"].iloc[-1]
    total_return = ((final_equity - initial_capital) / initial_capital) * 100

    bh_final = results["buy_and_hold"].iloc[-1]
    bh_return = ((bh_final - initial_capital) / initial_capital) * 100

    closed_trades = [t for t in trades if t["side"] == "SELL"]
    wins = [t for t in closed_trades if t["pnl_pct"] > 0]
    win_rate = (len(wins) / len(closed_trades) * 100) if closed_trades else 0.0
    max_dd = calculate_max_drawdown(results["equity"])

    print("\n================ BACKTEST SUMMARY ================")
    print(f"Period           : {results['timestamp'].iloc[0]} -> {results['timestamp'].iloc[-1]}")
    print(f"Initial Capital  : ${initial_capital:,.2f}")
    print(f"Final Equity     : ${final_equity:,.2f} ({total_return:+.2f}%)")
    print(f"Buy & Hold Value : ${bh_final:,.2f} ({bh_return:+.2f}%)")
    print(f"Closed Trades    : {len(closed_trades)}")
    print(f"Win Rate         : {win_rate:.1f}%")
    print(f"Max Drawdown     : {max_dd:.2f}%")
    print("==================================================")


def save_equity_chart(results: pd.DataFrame, output_path: str = "equity_curve.png") -> None:
    """Plot strategy equity vs. Buy & Hold and save to PNG."""
    plt.figure(figsize=(11, 5))
    plt.plot(results["timestamp"], results["equity"], label="SMA (10/30) Strategy", linewidth=2, color="#00b894")
    plt.plot(results["timestamp"], results["buy_and_hold"], label="Buy & Hold BTC", linewidth=1.5, linestyle="--", color="#636e72")
    plt.title("Strategy Equity Curve vs. Buy & Hold (Educational Simulation)")
    plt.xlabel("Date")
    plt.ylabel("Portfolio Value (USDT)")
    plt.legend()
    plt.grid(alpha=0.3)
    plt.tight_layout()
    plt.savefig(output_path, dpi=150)
    plt.close()
    print(f"\nSaved visual equity curve chart to: {output_path}")


if __name__ == "__main__":
    print("Downloading 500 hourly BTCUSDT candles...")
    candles = fetch_historical_candles(symbol="BTCUSDT", interval="1h", limit=500)

    results, trades = run_sma_backtest(candles, fast_window=10, slow_window=30, initial_capital=10_000.0)
    print_summary(results, trades, initial_capital=10_000.0)
    save_equity_chart(results, output_path="equity_curve.png")

Run your simulator:

python backtester.py

Expected Terminal Output

Downloading 500 hourly BTCUSDT candles...

================ BACKTEST SUMMARY ================
Period           : 2026-11-12 16:00:00 -> 2026-12-03 11:00:00
Initial Capital  : $10,000.00
Final Equity     : $10,482.35 (+4.82%)
Buy & Hold Value : $10,315.90 (+3.16%)
Closed Trades    : 11
Win Rate         : 45.5%
Max Drawdown     : -3.41%
==================================================

Saved visual equity curve chart to: equity_curve.png

Open equity_curve.png to view your strategy line plotted right alongside Buy & Hold! Notice something interesting in that sample output: a 45.5% win rate can still be profitable if your winning trends are larger than your small losing whipsaws.


Common Beginner Mistake: Judging a strategy only by its final return percentage. Always compare your bot against a simple Buy & Hold benchmark and inspect Max Drawdown. If Bitcoin went up +25% and your complex bot only made +8% with a -15% drawdown, simply holding would have beaten your bot with less stress.


Study & Practice Recap

  • A backtester is a step-by-step replay loop: On each candle, you check your strategy rules, update virtual cash/holdings, and record total equity.
  • Benchmark everything against Buy & Hold: A strategy only adds value if it beats holding or delivers a much smoother ride (smaller drawdown).
  • Win rate alone does not equal profit: Trend-following bots often win fewer than 50% of trades, relying on a few big winners to outweigh small losses.

Tiny Hands-On Exercise: Change fast_window=10, slow_window=30 to fast_window=5, slow_window=15 and re-run backtester.py. How does the number of closed trades change, and does the equity curve get smoother or choppier?

Topics:#Trading Strategy#Backtesting#Python#Matplotlib#Crypto Bot