Installation
Install the pure-Python package directly from PyPI:
pip install back-trader-python
Note: back-trader-python is the PyPI distribution name; the import name remains backtrader (import backtrader as bt).
For the pybind11-accelerated C++ wheel (order-of-magnitude faster backtests):
pip install back-trader-cpp
https://pypi.org/project/back-trader-python/ · https://pypi.org/project/back-trader-cpp/
Both support Python 3.8+ (the C++ wheel covers 3.8-3.14) on macOS, Windows, and Linux.
C++ and pybind11 Performance Highlights
- 117 strategy benchmark cases, with the C++ version reaching 117/117 success and 0 metric mismatches;
- C++ total-time median speedup: 128.82x;
- C++ run-time median speedup: 235.78x;
- pybind11 total-time median speedup: 43.39x;
- pybind11 run-time median speedup: 57.60x.
📋 Table of Contents
⚡ Performance Snapshot
The active dev branch carries the optimization work originally developed on the
development branch. Running the full 1,271-strategy regression suite
(tests/functional/strategies, -n 8) against the installed engine, dev
completes in about half the time of master.
📊 Benchmark Results (full strategy suite)
| Metric |
Master Branch |
Dev Branch |
Improvement |
| Total Execution Time |
438.96s (7m18s) |
236.36s (3m56s) |
-46.2% |
| Speedup |
1.00x |
1.86x |
✓ |
| Strategies Tested |
1,271 |
1,271 |
✓ |
| Test Pass Rate |
100% (1271 passed) |
100% (1271 passed) |
✓ |
Benchmark: pytest tests/functional/strategies -n 8 on identical hardware
(macOS, Python 3.11, 8 parallel xdist workers). Master measured via
--use-installed-backtrader against the master build.
An earlier internal benchmark on a smaller 119-strategy sample showed a
comparable ~45% reduction (553.12s → 305.36s).
📈 Performance by Strategy Type
| Strategy Category |
Avg Speedup |
Example |
| Simple MA Cross |
40-45% |
test_03_two_ma: 2.6s → 1.5s |
| Multi-Indicator |
45-50% |
test_09_dual_thrust: 59.2s → 26.9s |
| Multi-Data |
42-48% |
test_02_multi_extend_data: 23.5s → 12.6s |
| Complex Strategies |
38-42% |
test_08_kelter_strategy: 36.9s → 11.3s |
🎯 Introduction
Backtrader is a powerful and flexible Python framework for backtesting trading strategies.
This project is based on backtrader with extensive
optimizations and feature enhancements, supporting low-frequency, mid-frequency, and
high-frequency strategy development, backtesting, and live trading.
Why Choose Backtrader?
| Comparison |
Backtrader |
Other Frameworks |
| Learning Curve |
⭐⭐ Gentle |
⭐⭐⭐⭐ Steep |
| Development Efficiency |
⭐⭐⭐⭐⭐ Very High |
⭐⭐⭐ Average |
| Built-in Indicators |
50+ |
10-30 |
| Data Source Support |
20+ |
5-10 |
| Community Activity |
⭐⭐⭐⭐ Active |
⭐⭐ Average |
| Documentation |
⭐⭐⭐⭐⭐ Complete |
⭐⭐⭐ Average |
Project Branches
master: Original Backtrader baseline; only original-baseline bug, compatibility, and
security hotfixes belong here
dev: Daily development entry for routine features, fixes, tests, documentation, and
refactors
development: Improved and optimized release branch; controlled dev promotions and
CI/CD run here
🌐 Project Ecosystem
The CloudQuant Backtrader ecosystem spans the core engine plus five companion
projects — AI-assisted strategy development (skills, MCP, agent), a web-based
research & trading platform, and a quantitative analytics library:
| Project |
Description |
cloudQuant/backtrader |
Core engine (this repository) — high-performance Python framework for backtesting and live trading across all frequencies. |
cloudQuant/backtrader-skills |
Offline author/review/test skills for AI agents — turns registered local datasets and typed StrategySpec v1 specs into pytest strategies or three-file bundles, reviews candidates without importing them, and runs approved candidates in isolated child processes. |
cloudQuant/backtrader-mcp |
Local-first MCP server — typed tools, resources, and prompts for building and running reproducible strategies: immutable datasets, private drafts, and bounded subprocess runs with durable status and reports. |
cloudQuant/backtrader-agent |
Offline-first strategy-authoring agent runtime — canonical strategy specifications, static review, hash-bound approvals, fixed child-process execution, and recoverable session provenance. |
cloudQuant/backtrader_web |
"AI for Investor" — Vue 3 + FastAPI web platform for the full strategy lifecycle: research, strategy generation, backtesting, paper trading, live execution, and market-data management. |
cloudQuant/fincore |
Quantitative performance & risk analytics library — 150+ financial metrics, portfolio optimization, Monte Carlo simulation, and performance attribution. |
The three AI products (skills, MCP, agent) implement the same end-to-end
strategy workflow through different host integration surfaces; none requires
either of the other two. Install, test, release, and contribute to each product
in its own repository — the Backtrader core repository neither vendors nor
initializes those products.
Backtrader's scope is the strategy and backtesting runtime plus its Backtrader-side integration code. The other products in this table, along with bt_api_py, venue adapters, and server-side services, are maintained and delivered separately. This repository does not bundle or start them; the ecosystem list describes project boundaries and optional integrations, not a turnkey deployment or live-trading acceptance.
✨ Key Features
🚀 High-Performance Multi-Frequency Backtesting Engine
Three backtesting modes supported:
├── runonce (Vectorized) - Batch computation, optimal performance
├── runnext (Event-driven) - Bar-by-bar, suitable for complex logic
└── Tick-level backtesting - Tick data support with tick+bar mixed mode
Trading frequency spectrum:
├── Low-frequency - Daily/weekly bars, position trading
├── Mid-frequency - Minute/hour bars, intraday trading
└── High-frequency - Tick-level data, market microstructure
📊 Rich Visualization
- Plotly Interactive Charts: Supports 100k+ data points with zoom, pan, hover
- Bokeh Real-time Charts: Real-time data updates and multi-tab support
- Matplotlib Static Charts: Classic plotting for papers and reports
📈 Professional Reports
One-click generation of professional reports including:
- Equity curves and drawdown charts
- Sharpe ratio, Calmar ratio, SQN rating
- Detailed trade statistics and P&L analysis
- Export to HTML, PDF, JSON formats
🔧 50+ Built-in Technical Indicators
Covering moving averages, momentum, volatility, trend indicators, and more.
🔄 Tick-Level & Mixed-Frequency Trading
- Tick-level backtesting: Process individual tick data for high-frequency strategy research
- Tick + Bar mixed mode: Combine tick and bar data in the same strategy
- Seamless live trading: Same strategy code works for backtesting and live trading
- Full spectrum coverage: Low-frequency (daily), mid-frequency (minute), and high-frequency (tick) — all unified
📝 TradeLogger - Real-time Trade Logging
Comprehensive observer for real-time logging during backtests:
- Real-time file writing: Logs are appended on every bar (not just at the end)
current_position.json: Updated after each bar with the latest holdings
- Strategy indicators: Optionally log strategy-calculated indicators in data files
- Configurable format: Tab-separated
.log (default) or standard .csv
- MySQL persistence: Order/trade/position logs saved to MySQL (
bt_order, bt_trade, bt_position)
- Generic in-memory report:
snapshot() provides a detached real-time status view and
final_report() returns the immutable report frozen after the strategy stops. It works with
any Backtrader broker, store, feed, or strategy and does not require file or MySQL logging.
Core brokers expose cached cash, value, and positions through a local-only report-state API,
so a snapshot does not trigger a live account request. This guarantee covers the in-memory
report API; enabled legacy file sinks retain their own broker-read behavior.
cerebro.addobserver(
bt.observers.TradeLogger,
obsname='trade_logger',
log_dir='logs',
log_indicators=True,
file_format='log', # 'log' or 'csv'
# mysql_enabled=True, # optional MySQL persistence
# mysql_database='backtrder_web',
)
# Inside a strategy: self.stats.trade_logger.snapshot()
# After cerebro.run(): strategies[0].stats.trade_logger.final_report()
📦 Modular Architecture
Strategies, indicators, analyzers, and data sources can be independently extended.
🌍 20+ Data Source Support
CSV, Pandas, Yahoo Finance, Interactive Brokers, CCXT cryptocurrency, CTP futures, and more.
📥 Quick Installation
Requirements
- Python: 3.8+ (3.11 recommended for ~15% performance boost)
- OS: Windows / macOS / Linux
- RAM: 4GB+ recommended
From PyPI (Primary)
pip install back-trader-python
Then import backtrader as bt — the distribution name is back-trader-python, the import name stays backtrader.
For the C++/pybind11-accelerated wheel: pip install back-trader-cpp.
From Source (Developers)
git clone https://github.com/cloudQuant/backtrader.git
cd backtrader
pip install -r requirements.txt
pip install -U .
Verify Installation
import backtrader as bt
print(f"Backtrader version: {bt.__version__}")
# Output: Backtrader version: 1.4.0
Run Tests
pytest tests -n 4
🎓 5-Minute Quickstart
Step 1: Understand the Workflow
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Prepare │ -> │ Write │ -> │ Run │
│ Data │ │ Strategy │ │ Backtest │
└─────────────┘ └─────────────┘ └─────────────┘
│ │ │
v v v
CSV/Pandas/API Extend Strategy cerebro.run()
Implement next()
Step 2: Write Your First Strategy