Backtesting Frameworks Comparison
Backtrader, Freqtrade, and VectorBT: architecture, pros/cons, when to use which, and implementing the same strategy across all three frameworks.
Choosing the Right Backtesting Framework
A backtest is only as good as the framework running it. The three dominant Python backtesting frameworks each solve different problems: Backtrader is the Swiss Army knife of event-driven backtesting, Freqtrade is a complete bot framework with built-in optimization and deployment, and VectorBT is a speed monster that processes millions of parameter combinations in seconds. Choosing the wrong framework wastes weeks of development time. Choosing the right one accelerates your research by 10x.
Backtrader: Event-Driven Flexibility
Backtrader processes each bar sequentially, triggering callbacks on your strategy class:next() fires on every candle, notify_order() when an order changes state, and notify_trade() when a trade opens or closes. This event-driven architecture mirrors how a live trading system works, making the transition from backtest to production more natural. The downside: it is slow. Each bar requires a Python function call, and testing 10,000 parameter combinations means running the strategy 10,000 times sequentially.
1import backtrader as bt23class SMACross(bt.Strategy):4 params = (('fast', 20), ('slow', 50),)56 def __init__(self):7 fast_ma = bt.ind.SMA(period=self.p.fast)8 slow_ma = bt.ind.SMA(period=self.p.slow)9 self.crossover = bt.ind.CrossOver(fast_ma, slow_ma)1011 def next(self):12 if not self.position:13 if self.crossover > 0:14 self.buy(size=0.01)15 elif self.crossover < 0:16 self.close()1718 def notify_trade(self, trade):19 if trade.isclosed:20 print(f"Trade PnL: {trade.pnl:.2f}, Net: {trade.pnlcomm:.2f}")2122# Run the backtest23cerebro = bt.Cerebro()24cerebro.addstrategy(SMACross, fast=20, slow=50)2526data = bt.feeds.GenericCSVData(27 dataname='btc_daily.csv',28 dtformat='%Y-%m-%d',29 openinterest=-1,30)31cerebro.adddata(data)32cerebro.broker.setcash(10000)33cerebro.broker.setcommission(commission=0.001) # 0.1%3435results = cerebro.run()36cerebro.plot()| Architecture | Event-driven: processes one bar at a time through strategy callbacks. Mimics live trading execution flow. |
| Strengths | Maximum flexibility, built-in broker simulation with margin/commission, plotting, multiple data feeds, custom indicators, analyzers for Sharpe/drawdown/trade stats. |
| Weaknesses | Slow for parameter sweeps (Python loop overhead), steep learning curve, limited documentation, development stalled since 2021. |
| Best for | Complex multi-asset strategies, strategies requiring realistic order simulation (partial fills, slippage models), one-off research. |
Freqtrade: Strategy Framework with Deployment
Freqtrade is not just a backtesting library. It is a full trading bot framework. You write a strategy class, backtest it, optimize with Hyperopt (Bayesian hyperparameter optimization), and deploy the same code to live trading. It has built-in Telegram integration for monitoring, a web UI for real-time status, and supports Binance, Bybit, OKX, and other exchanges out of the box. The strategy interface uses Pandas DataFrames with indicator columns, making it accessible to anyone comfortable with data analysis.
1from freqtrade.strategy import IStrategy, DecimalParameter, IntParameter2import talib.abstract as ta34class OptimizedSMA(IStrategy):5 INTERFACE_VERSION = 36 timeframe = '4h'7 stoploss = -0.058 trailing_stop = True9 trailing_stop_positive = 0.021011 # Hyperopt parameters12 buy_fast = IntParameter(5, 50, default=20, space='buy')13 buy_slow = IntParameter(30, 200, default=50, space='buy')14 buy_rsi = IntParameter(20, 40, default=30, space='buy')1516 def populate_indicators(self, dataframe, metadata):17 for period in range(5, 201):18 dataframe[f'sma_{period}'] = ta.SMA(dataframe, timeperiod=period)19 dataframe['rsi'] = ta.RSI(dataframe, timeperiod=14)20 return dataframe2122 def populate_entry_trend(self, dataframe, metadata):23 dataframe.loc[24 (dataframe[f'sma_{self.buy_fast.value}'] > dataframe[f'sma_{self.buy_slow.value}']) &25 (dataframe['rsi'] < self.buy_rsi.value) &26 (dataframe['volume'] > 0),27 'enter_long'] = 128 return dataframe2930 def populate_exit_trend(self, dataframe, metadata):31 dataframe.loc[32 (dataframe[f'sma_{self.buy_fast.value}'] < dataframe[f'sma_{self.buy_slow.value}']),33 'exit_long'] = 134 return dataframe1# Download historical data2freqtrade download-data --exchange binance --pairs BTC/USDT ETH/USDT --timeframes 4h 1d --timerange 20200101-34# Run backtest5freqtrade backtesting --strategy OptimizedSMA --timerange 20210101-2024010167# Hyperopt optimization (find best parameters)8freqtrade hyperopt --strategy OptimizedSMA --hyperopt-loss SharpeHyperOptLoss \9 --epochs 500 --timerange 20210101-202301011011# Deploy to live trading (paper mode first)12freqtrade trade --strategy OptimizedSMA --config config.json --dry-run| Architecture | DataFrame-based: populate indicators as columns, then define entry/exit conditions as column masks. Bridges backtest and live execution. |
| Strengths | Built-in Hyperopt optimization, Telegram bot, web UI, live trading deployment, exchange integrations, community strategies, active development. |
| Weaknesses | Opinionated framework (must follow its structure), backtesting speed moderate, limited multi-asset support, primarily designed for spot and linear futures. |
| Best for | Traders who want a single tool from research to live deployment. Ideal for systematic strategies on 1h-1d timeframes. |
VectorBT: Vectorized Speed
VectorBT takes a radically different approach: instead of processing bars one at a time, it uses NumPy array operations to compute all signals and simulate all trades simultaneously. A parameter sweep that takes 30 minutes in Backtrader finishes in under 10 seconds with VectorBT. It excels at exploratory research: testing hundreds of indicator combinations, running Monte Carlo simulations, and visualizing multi-dimensional parameter surfaces. The Sharpe ratio, maximum drawdown, and dozens of other metrics are computed as vectorized operations across all parameter combinations simultaneously.
1import vectorbt as vbt2import numpy as np34# Fetch data5btc = vbt.YFData.download('BTC-USD', start='2020-01-01').get('Close')67# Test ALL combinations of fast (10-55) and slow (50-195) MAs8fast_windows = np.arange(10, 56, 5)9slow_windows = np.arange(50, 196, 5)1011fast_ma, slow_ma = vbt.MA.run_combs(12 btc, window=[fast_windows, slow_windows],13 r=2, short_names=['fast', 'slow']14)1516entries = fast_ma.ma_crossed_above(slow_ma)17exits = fast_ma.ma_crossed_below(slow_ma)1819portfolio = vbt.Portfolio.from_signals(20 btc, entries, exits,21 init_cash=10000, fees=0.001, slippage=0.00122)2324# All metrics for ALL 300+ combinations in one call25sharpe = portfolio.sharpe_ratio()26max_dd = portfolio.max_drawdown()27total_return = portfolio.total_return()2829# Find the best by Sharpe30best_params = sharpe.idxmax()31print(f"Best params: Fast={best_params[0]}, Slow={best_params[1]}")32print(f"Sharpe: {sharpe.max():.2f}")33print(f"Return: {total_return[best_params]:.2%}")34print(f"Max DD: {max_dd[best_params]:.2%}")1# Detailed analysis of the best strategy2best_pf = portfolio[best_params]34# Trade statistics5print(best_pf.stats())67# Equity curve plot8best_pf.plot().show()910# Drawdown analysis11drawdowns = best_pf.drawdowns12print(f"Number of drawdowns: {len(drawdowns.records_readable)}")13print(f"Avg drawdown duration: {drawdowns.duration.mean():.0f} bars")14print(f"Max drawdown duration: {drawdowns.duration.max():.0f} bars")1516# Monthly returns heatmap17best_pf.returns.vbt.returns.monthly().vbt.heatmap().show()1819# Parameter surface: Sharpe ratio across all combinations20sharpe.vbt.heatmap(21 x_level='fast_window', y_level='slow_window',22 title='Sharpe Ratio Surface'23).show()| Architecture | Vectorized: all signals and trades computed as NumPy array operations. No Python loops during simulation. |
| Strengths | 100-1000x faster than event-driven frameworks, built-in portfolio analytics, parameter sweep visualization, Monte Carlo, Pandas-native API. |
| Weaknesses | Simplified order simulation (no partial fills, limited order types), memory-intensive for large sweeps, steep NumPy/Pandas prerequisite knowledge. |
| Best for | Exploratory research, parameter optimization, strategy screening. Use VectorBT to find promising strategies, then validate with Backtrader or Freqtrade. |
Head-to-Head Comparison
Backtrader: ~30 minutes. Freqtrade: ~15 minutes. VectorBT: ~5 seconds. For exploratory research, this difference is decisive.
Backtrader: best (simulates broker, partial fills, margin). Freqtrade: good (realistic commission, slippage). VectorBT: basic (fixed fees, no partial fills).
Freqtrade: built-in with exchange connectors. Backtrader: possible but requires custom broker adapters. VectorBT: none, research tool only.
Freqtrade: lowest (DataFrame-based, good docs). VectorBT: medium (requires NumPy/Pandas fluency). Backtrader: highest (complex class hierarchy).
Freqtrade: most active (GitHub, Discord, regular updates). VectorBT: active development. Backtrader: stalled, but stable and well-tested.
Use the right tool for each phase
1.What makes VectorBT 100-1000x faster than Backtrader for parameter sweeps?
2.Which framework is best suited for going from research directly to live trading with minimal code changes?
3.Why is Backtrader's slow speed actually an advantage for certain use cases?
4.What is the recommended multi-framework workflow for strategy development?
5.A VectorBT backtest shows a 3.2 Sharpe ratio, but the same strategy in Freqtrade shows 1.4. What is the most likely explanation?
Put this lesson to work
Free on Thrive, no account needed.