$npx -y skills add agiprolabs/claude-trading-skills --skill backtraderEvent-driven backtesting with bar-by-bar execution, complex order types, multiple analyzers, and custom indicators
| 1 | # Backtrader |
| 2 | |
| 3 | Backtrader is a Python event-driven backtesting framework that processes data bar-by-bar, simulating realistic execution with a built-in broker, order management, and position tracking. Unlike vectorized frameworks (vectorbt, pandas), backtrader walks through history one bar at a time, firing callbacks that let you implement complex order logic that depends on previous fills, partial executions, and conditional brackets. |
| 4 | |
| 5 | ## Event-Driven vs Vectorized |
| 6 | |
| 7 | | Aspect | Backtrader (event-driven) | vectorbt (vectorized) | |
| 8 | |---|---|---| |
| 9 | | Execution model | Bar-by-bar callbacks | Whole-array operations | |
| 10 | | Speed | Slower (Python loop) | Fast (NumPy/Numba) | |
| 11 | | Order types | Market, limit, stop, stop-limit, bracket, OCO | Market only (native) | |
| 12 | | Realism | Built-in broker with commission, slippage, margin | Manual slippage modeling | |
| 13 | | Multi-timeframe | Native resampledata | Manual alignment | |
| 14 | | Best for | Complex strategies, bracket orders, portfolio | Fast parameter sweeps, simple signals | |
| 15 | |
| 16 | **Use backtrader when you need:** |
| 17 | - Bracket orders (entry + stop loss + take profit as a unit) |
| 18 | - Stop-limit or trailing stop orders |
| 19 | - Order-dependent logic (scale in after first fill, cancel if not filled in N bars) |
| 20 | - Multi-timeframe strategies (daily signals, hourly execution) |
| 21 | - Realistic commission and slippage modeling |
| 22 | |
| 23 | **Use vectorbt when you need:** |
| 24 | - Fast parameter optimization over thousands of combinations |
| 25 | - Simple long/short signals without complex order management |
| 26 | - Quick prototyping and statistical analysis of results |
| 27 | |
| 28 | --- |
| 29 | |
| 30 | ## Core Concepts |
| 31 | |
| 32 | Backtrader has five core objects that interact through an event loop: |
| 33 | |
| 34 | ### 1. Cerebro (the engine) |
| 35 | |
| 36 | The central orchestrator. You add strategies, data feeds, analyzers, and sizers to Cerebro, then call `run()`. |
| 37 | |
| 38 | ```python |
| 39 | import backtrader as bt |
| 40 | |
| 41 | cerebro = bt.Cerebro() |
| 42 | cerebro.addstrategy(MyStrategy, fast_period=10, slow_period=30) |
| 43 | cerebro.adddata(data_feed) |
| 44 | cerebro.broker.setcash(100_000) |
| 45 | cerebro.broker.setcommission(commission=0.003) # 0.3% |
| 46 | cerebro.addanalyzer(bt.analyzers.SharpeRatio, _name="sharpe") |
| 47 | cerebro.addanalyzer(bt.analyzers.DrawDown, _name="drawdown") |
| 48 | cerebro.run() |
| 49 | ``` |
| 50 | |
| 51 | ### 2. Strategy (your logic) |
| 52 | |
| 53 | A Strategy subclass contains all trading logic. Key methods: |
| 54 | |
| 55 | - `__init__()` — Define indicators. Runs once before backtesting starts. |
| 56 | - `next()` — Called on every bar. Place orders here. |
| 57 | - `notify_order(order)` — Called when order status changes (submitted, accepted, completed, canceled, margin, expired). |
| 58 | - `notify_trade(trade)` — Called when a trade opens or closes. Access P&L here. |
| 59 | |
| 60 | ```python |
| 61 | class EMACrossover(bt.Strategy): |
| 62 | params = ( |
| 63 | ("fast_period", 10), |
| 64 | ("slow_period", 30), |
| 65 | ) |
| 66 | |
| 67 | def __init__(self) -> None: |
| 68 | self.ema_fast = bt.ind.EMA(period=self.p.fast_period) |
| 69 | self.ema_slow = bt.ind.EMA(period=self.p.slow_period) |
| 70 | self.crossover = bt.ind.CrossOver(self.ema_fast, self.ema_slow) |
| 71 | |
| 72 | def next(self) -> None: |
| 73 | if not self.position: |
| 74 | if self.crossover > 0: |
| 75 | self.buy() |
| 76 | elif self.crossover < 0: |
| 77 | self.close() |
| 78 | ``` |
| 79 | |
| 80 | ### 3. Data Feed |
| 81 | |
| 82 | Backtrader data feeds provide OHLCV lines. The most common approach is loading from a pandas DataFrame: |
| 83 | |
| 84 | ```python |
| 85 | import pandas as pd |
| 86 | |
| 87 | df = pd.DataFrame({ |
| 88 | "open": [...], "high": [...], "low": [...], |
| 89 | "close": [...], "volume": [...], |
| 90 | }, index=pd.DatetimeIndex([...])) |
| 91 | |
| 92 | data = bt.feeds.PandasData(dataname=df) |
| 93 | cerebro.adddata(data) |
| 94 | ``` |
| 95 | |
| 96 | For CSV files: |
| 97 | |
| 98 | ```python |
| 99 | data = bt.feeds.GenericCSVData( |
| 100 | dataname="ohlcv.csv", |
| 101 | dtformat="%Y-%m-%d", |
| 102 | openinterest=-1, # no open interest column |
| 103 | ) |
| 104 | ``` |
| 105 | |
| 106 | ### 4. Broker |
| 107 | |
| 108 | The built-in broker simulates order execution with configurable cash, commission, and slippage. |
| 109 | |
| 110 | ```python |
| 111 | cerebro.broker.setcash(100_000) |
| 112 | cerebro.broker.setcommission(commission=0.003) # 0.3% per trade |
| 113 | |
| 114 | # Cheat-on-open: execute at the open of the signal bar (avoids lookahead) |
| 115 | cerebro.broker.set_coo(True) |
| 116 | ``` |
| 117 | |
| 118 | ### 5. Analyzers |
| 119 | |
| 120 | Analyzers compute performance metrics after the backtest completes. |
| 121 | |
| 122 | ```python |
| 123 | cerebro.addanalyzer(bt.analyzers.SharpeRatio, _name="sharpe", |
| 124 | riskfreerate=0.0, annualize=True, timeframe=bt.TimeFrame.Days) |
| 125 | cerebro.addanalyzer(bt.analyzers.DrawDown, _name="drawdown") |
| 126 | cerebro.addanalyzer(bt.analyzers.TradeAnalyzer, _name="trades") |
| 127 | cerebro.addanalyzer(bt.analyzers.Returns, _name="returns") |
| 128 | |
| 129 | results = cerebro.run() |
| 130 | strat = results[0] |
| 131 | |
| 132 | sharpe = strat.analyzers.sharpe.get_analysis() |
| 133 | dd = strat.analyzers.drawdown.get_analysis() |
| 134 | trades = strat.analyzers.trades.get_analysis() |
| 135 | ``` |
| 136 | |
| 137 | --- |
| 138 | |
| 139 | ## Order Types |
| 140 | |
| 141 | Backtrader supports complex order types critical for realistic crypto backtesting. |
| 142 | |
| 143 | ### Market Order |
| 144 | |
| 145 | ```python |
| 146 | self.buy() # market buy |
| 147 | self.sell() # market sell |
| 148 | self.close() # close current position |
| 149 | ``` |
| 150 | |
| 151 | ### Limit Order |
| 152 | |
| 153 | ```python |
| 154 | self.buy |