Skip to main content

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.

python-Backtrader SMA crossover strategy
1import backtrader as bt
2
3class SMACross(bt.Strategy):
4 params = (('fast', 20), ('slow', 50),)
5
6 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)
10
11 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()
17
18 def notify_trade(self, trade):
19 if trade.isclosed:
20 print(f"Trade PnL: {trade.pnl:.2f}, Net: {trade.pnlcomm:.2f}")
21
22# Run the backtest
23cerebro = bt.Cerebro()
24cerebro.addstrategy(SMACross, fast=20, slow=50)
25
26data = 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%
34
35results = cerebro.run()
36cerebro.plot()
ArchitectureEvent-driven: processes one bar at a time through strategy callbacks. Mimics live trading execution flow.
StrengthsMaximum flexibility, built-in broker simulation with margin/commission, plotting, multiple data feeds, custom indicators, analyzers for Sharpe/drawdown/trade stats.
WeaknessesSlow for parameter sweeps (Python loop overhead), steep learning curve, limited documentation, development stalled since 2021.
Best forComplex 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.

python-Freqtrade strategy with optimization
1from freqtrade.strategy import IStrategy, DecimalParameter, IntParameter
2import talib.abstract as ta
3
4class OptimizedSMA(IStrategy):
5 INTERFACE_VERSION = 3
6 timeframe = '4h'
7 stoploss = -0.05
8 trailing_stop = True
9 trailing_stop_positive = 0.02
10
11 # Hyperopt parameters
12 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')
15
16 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 dataframe
21
22 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'] = 1
28 return dataframe
29
30 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'] = 1
34 return dataframe
bash-Freqtrade CLI commands
1# Download historical data
2freqtrade download-data --exchange binance --pairs BTC/USDT ETH/USDT --timeframes 4h 1d --timerange 20200101-
3
4# Run backtest
5freqtrade backtesting --strategy OptimizedSMA --timerange 20210101-20240101
6
7# Hyperopt optimization (find best parameters)
8freqtrade hyperopt --strategy OptimizedSMA --hyperopt-loss SharpeHyperOptLoss \
9 --epochs 500 --timerange 20210101-20230101
10
11# Deploy to live trading (paper mode first)
12freqtrade trade --strategy OptimizedSMA --config config.json --dry-run
ArchitectureDataFrame-based: populate indicators as columns, then define entry/exit conditions as column masks. Bridges backtest and live execution.
StrengthsBuilt-in Hyperopt optimization, Telegram bot, web UI, live trading deployment, exchange integrations, community strategies, active development.
WeaknessesOpinionated framework (must follow its structure), backtesting speed moderate, limited multi-asset support, primarily designed for spot and linear futures.
Best forTraders 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.

python-VectorBT parameter sweep
1import vectorbt as vbt
2import numpy as np
3
4# Fetch data
5btc = vbt.YFData.download('BTC-USD', start='2020-01-01').get('Close')
6
7# Test ALL combinations of fast (10-55) and slow (50-195) MAs
8fast_windows = np.arange(10, 56, 5)
9slow_windows = np.arange(50, 196, 5)
10
11fast_ma, slow_ma = vbt.MA.run_combs(
12 btc, window=[fast_windows, slow_windows],
13 r=2, short_names=['fast', 'slow']
14)
15
16entries = fast_ma.ma_crossed_above(slow_ma)
17exits = fast_ma.ma_crossed_below(slow_ma)
18
19portfolio = vbt.Portfolio.from_signals(
20 btc, entries, exits,
21 init_cash=10000, fees=0.001, slippage=0.001
22)
23
24# All metrics for ALL 300+ combinations in one call
25sharpe = portfolio.sharpe_ratio()
26max_dd = portfolio.max_drawdown()
27total_return = portfolio.total_return()
28
29# Find the best by Sharpe
30best_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%}")
python-VectorBT portfolio analysis
1# Detailed analysis of the best strategy
2best_pf = portfolio[best_params]
3
4# Trade statistics
5print(best_pf.stats())
6
7# Equity curve plot
8best_pf.plot().show()
9
10# Drawdown analysis
11drawdowns = best_pf.drawdowns
12print(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")
15
16# Monthly returns heatmap
17best_pf.returns.vbt.returns.monthly().vbt.heatmap().show()
18
19# Parameter surface: Sharpe ratio across all combinations
20sharpe.vbt.heatmap(
21 x_level='fast_window', y_level='slow_window',
22 title='Sharpe Ratio Surface'
23).show()
ArchitectureVectorized: all signals and trades computed as NumPy array operations. No Python loops during simulation.
Strengths100-1000x faster than event-driven frameworks, built-in portfolio analytics, parameter sweep visualization, Monte Carlo, Pandas-native API.
WeaknessesSimplified order simulation (no partial fills, limited order types), memory-intensive for large sweeps, steep NumPy/Pandas prerequisite knowledge.
Best forExploratory research, parameter optimization, strategy screening. Use VectorBT to find promising strategies, then validate with Backtrader or Freqtrade.

Head-to-Head Comparison

Speed (10,000 param combos)

Backtrader: ~30 minutes. Freqtrade: ~15 minutes. VectorBT: ~5 seconds. For exploratory research, this difference is decisive.

Execution realism

Backtrader: best (simulates broker, partial fills, margin). Freqtrade: good (realistic commission, slippage). VectorBT: basic (fixed fees, no partial fills).

Live deployment

Freqtrade: built-in with exchange connectors. Backtrader: possible but requires custom broker adapters. VectorBT: none, research tool only.

Learning curve

Freqtrade: lowest (DataFrame-based, good docs). VectorBT: medium (requires NumPy/Pandas fluency). Backtrader: highest (complex class hierarchy).

Community & maintenance

Freqtrade: most active (GitHub, Discord, regular updates). VectorBT: active development. Backtrader: stalled, but stable and well-tested.

Use the right tool for each phase

The optimal workflow uses multiple frameworks. Start with VectorBT for rapid exploration: screen hundreds of strategy variants in minutes. When you find a promising edge, port it to Backtrader or Freqtrade for realistic simulation with proper order execution, slippage models, and commission schedules. If it survives that validation, deploy via Freqtrade for live trading. Each framework excels at a different phase of the research-to-production pipeline.
Module Quiz

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?

0/5 answered

Put this lesson to work

Free on Thrive, no account needed.