Backtrader Documentation¶
Backtrader is a feature-rich Python quantitative trading framework supporting backtesting and live trading, with 50+ technical indicators, multiple data sources, various brokers, and comprehensive analysis tools.
Tip
📖 This documentation is also available in 中文 (Chinese).
✍️ Author’s blog: yunjinqi.blog.csdn.net
Why Backtrader?¶
Gentle learning curve with intuitive API design. Get your first strategy running in 5 minutes.
Vectorized (runonce) and event-driven (runnext)
modes. 45%+ faster than the original.
50+ indicators, 17+ analyzers, 21+ data feeds — everything you need out of the box.
Plotly, Bokeh, and Matplotlib backends with one-click HTML/PDF/JSON reports.
Interactive Brokers, CCXT (crypto), and CTP (Chinese futures) — backtest to live seamlessly.
Custom indicators, analyzers, data feeds, and brokers. Plugin-friendly architecture.
Quick Start¶
git clone https://github.com/cloudQuant/backtrader.git
cd backtrader && pip install -U .
import backtrader as bt
class SmaCross(bt.Strategy):
params = (('pfast', 10), ('pslow', 30))
def __init__(self):
sma_fast = bt.indicators.SMA(period=self.p.pfast)
sma_slow = bt.indicators.SMA(period=self.p.pslow)
self.crossover = bt.indicators.CrossOver(sma_fast, sma_slow)
def next(self):
if not self.position and self.crossover > 0:
self.buy()
elif self.position and self.crossover < 0:
self.close()
cerebro = bt.Cerebro()
data = bt.feeds.GenericCSVData(
dataname='data.csv',
datetime=0, open=1, high=2, low=3,
close=4, volume=5, dtformat='%Y-%m-%d')
cerebro.adddata(data)
cerebro.addstrategy(SmaCross)
cerebro.broker.setcash(100000)
cerebro.broker.setcommission(commission=0.001)
cerebro.addanalyzer(bt.analyzers.SharpeRatio, _name='sharpe')
cerebro.addanalyzer(bt.analyzers.DrawDown, _name='drawdown')
results = cerebro.run()
strat = results[0]
print(f"Sharpe: {strat.analyzers.sharpe.get_analysis()}")
cerebro.plot(backend='plotly')
Source Code¶
Primary repository — issues, pull requests, CI/CD.
Mirror for users in mainland China with faster access.
Getting Started
User Guide
Advanced Topics
- TS (Time Series) Mode Guide
- Ensure preload=True
- Indicators must implement once() for speedup
- Verify TS mode produces same results as standard mode
- CS (Cross-Section) Mode Guide
- Verify CS mode actually helps your specific strategy
- Ensure all data feeds have same datetime index
- Verify ranking is stable
- CS mode shines with 10+ assets
- Multi-Strategy Backtesting
- Performance Optimization
- Performance Analysis and Profiling
- Data Acquisition Guide
- Architecture Overview
- Line System
- Phase System
- Post-Metaclass Design
- CCXT Live Trading Guide
- CCXT Environment Variable Configuration Guide
- WebSocket Real-Time Data Stream Guide
- Funding Rate Strategy Guide
- If a proxy is needed, set it in config
- CTP Live Trading
Tutorials
API Reference
Migration
Developer Guide