From course: β€” β€Ί
← Back to Course
Algo Trading Tutorial
⚑

Building a Simple Backtesting Framework in Python

Backtesting is where trading ideas go to survive reality. A simple, robust framework prevents curve-fitting and gives you honest historical results.

PythonBacktestingAutomationStrategy
22 May 2026Algo Trading
5 min read
1 views
0 likes
TradFlakes Insight

Why Backtest?

Without historical testing, a trading strategy is just a hypothesis. Backtesting lets you stress-test an idea against years of market data before risking real capital.

import pandas as pd

def backtest(df, signal_col, stop_pct=0.01, target_pct=0.02):
    trades = []
    for i, row in df.iterrows():
        if row[signal_col] == 1:
            entry = row['close']
            stop  = entry * (1 - stop_pct)
            tp    = entry * (1 + target_pct)
            trades.append({'entry': entry, 'stop': stop, 'tp': tp})
    return pd.DataFrame(trades)

Avoiding Curve-Fitting

The biggest trap in backtesting is optimising parameters until historical results look perfect. This creates a strategy that works on the past but fails on the future.

  • Use out-of-sample data β€” test on data the strategy never saw during development
  • Minimise the number of parameters
  • Accept that live performance will always be below backtest performance
If your backtest looks too good, it probably is.
Finished reading this lesson?
Mark it as complete to track your progress in the course.
← Back to Course
Share
← All Insights
TradFlakes