Backtesting is where trading ideas go to survive reality. A simple, robust framework prevents curve-fitting and gives you honest historical results.
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)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.
If your backtest looks too good, it probably is.