Quickstart & Tutorials
Relevant source files
The following files were used as context for generating this wiki page:
The Backtrader platform provides a robust framework for backtesting and live trading, emphasizing modularity through the use of the Cerebro engine. The Quickstart and Tutorial samples demonstrate the core workflow: defining a strategy, attaching data feeds, configuring the broker, and executing the backtest. These resources show how users can quickly move from a simple Moving Average Crossover to complex multi-indicator systems using a standardized API for order management and performance analysis.
The system is built around the "Strategy" pattern, where users subclass bt.Strategy to implement logic within well-defined lifecycle methods such as __init__, next, and notify_order. This architecture ensures that the execution engine handles data synchronization and broker simulation, allowing the developer to focus on alpha generation and risk management.
Sources: README.rst:45-66, backtrader/strategy.py:126-140
Core Framework Architecture
The primary orchestration component is bt.Cerebro. It serves as the central hub where data feeds, strategies, and brokers are registered. The lifecycle of a backtest follows a structured flow from initialization to final performance reporting.
System Components Overview
| Component | Description | Reference |
|---|---|---|
| Cerebro | The brain of the platform; coordinates data, strategies, and brokers. | bt.Cerebro() |
| Data Feeds | Abstracted price data (CSV, YahooFinance, etc.) converted into "Lines". | bt.feeds |
| Strategy | User-defined logic containing technical indicators and trading rules. | bt.Strategy |
| Broker | Simulation engine managing cash, commissions, and order execution. | cerebro.broker |
| Sizers | Automated logic for determining position sizes per trade. | bt.sizers |
Sources: Tutorials/quickstart/strategy_tester.py:33-55, README.rst:76-118
Execution Flow Diagram
The following diagram illustrates the high-level workflow used in the Quickstart tutorials to set up and run a backtest.
Strategy Development
Strategies are implemented by subclassing bt.Strategy. The framework provides lifecycle hooks to handle different stages of the data processing loop.
Lifecycle Methods
__init__: Used for declaring indicators and pre-calculating static values. Indicators declared here are automatically synchronized with the data.next: Called for every bar in the data feed once the minimum period requirements for indicators are met.notify_order: Handles updates on order status (Submitted, Accepted, Completed, Canceled).notify_trade: Provides updates on closed positions and P&L.start/stop: Execution hooks called at the beginning and end of the backtest.
Sources: backtrader/strategy.py:475-495, strategies/moving_average_crossover.py:186-215, samples/vctest/vctest.py:48-96
Order Lifecycle Management
The interaction between the Strategy and the Broker is managed via order notifications. This sequence diagram shows how an order progresses from creation to execution.
Data Management and Feeds
Tutorials demonstrate different methods of feeding data into the engine. The platform supports standard CSV formats, specialized vendors like Yahoo Finance, and live stores like Interactive Brokers.
Data Synchronization
When multiple data feeds are used (e.g., different symbols or timeframes), Backtrader automatically synchronizes the "clocks" so that next() is called at the appropriate time for the set of datas.
- Resampling: Converting tick data to minute data, or minute to daily.
- Replaying: Simulating the development of a bar using smaller timeframe components.
Sources: samples/vctest/vctest.py:165-195, backtrader/feeds/btcsv.py:35-58
Performance Analysis
The platform uses Analyzers to calculate statistics without interfering with the strategy logic. These are added to Cerebro before running.
Standard Analyzers
Tutorials frequently use the following built-in analyzers:
SharpeRatio: Measures risk-adjusted return.Drawdown: Tracks peak-to-trough declines.TradeAnalyzer: Provides detailed stats on winning/losing trades.Returns: Calculates total and annualized returns.
Sources: strategies/moving_average_crossover.py:530-580, backtrader/strategy.py:388-405
Output and Visualization
Tutorials highlight two main ways to extract data from a run:
- Plotting: Using
cerebro.plot()to generate charts with price bars, indicators, and trade markers. - Writers: Using
bt.WriterFileto output the strategy's internal states, indicator values, and results directly to a CSV or system stream.
Sources: backtrader/writer.py:61-105, Tutorials/quickstart/strategy_tester.py:82-84
Summary
The Quickstart resources establish a reliable blueprint for algorithmic trading. By leveraging the bt.Strategy class and the Cerebro engine, developers can transition from simple script-based testing to comprehensive, multi-analyzer backtests that accurately simulate broker behavior and commission impact.