Core Engine (Cerebro)
Relevant source files
The following files were used as context for generating this wiki page:
The Cerebro class serves as the central control unit and "brain" of the Backtrader framework. Its primary purpose is to aggregate various components—including data feeds, strategies, brokers, sizers, and analyzers—to execute backtests or live trading operations. It manages the lifecycle of a trading simulation, from initial configuration to data processing and final results visualization.
Cerebro coordinates the flow of information between the data sources and the strategy logic. It is responsible for preloading data, executing the main processing loop, and providing the infrastructure for optimization and performance measurement. By abstracting the complexity of the execution loop, Cerebro allows developers to focus on strategy development while ensuring consistent handling of orders, trades, and portfolio accounting.
Sources: README.rst:41-55, backtest/strategies/strategy_template/strategy_template.py:108-140
System Architecture
The Cerebro engine acts as a coordinator for multiple specialized modules. The architecture follows a plug-and-play model where different components are added to the Cerebro instance before the execution starts.
Key Components
| Component | Description |
|---|---|
| Data Feeds | Sources of market data (CSV, Pandas, Live feeds) added via adddata(). |
| Broker | Simulates the execution of orders and manages cash/leverage via setcash() and setcommission(). |
| Strategy | Contains the trading logic, added via addstrategy() or optstrategy(). |
| Analyzers | Standardized modules to evaluate performance (Sharpe Ratio, Returns, Drawdown) added via addanalyzer(). |
| Observers | Track variables during the run (e.g., Cash, Value) added via addobserver(). |
| Sizers | Determine the quantity of assets to trade (Fixed size, risk-based) added via addsizer(). |
| Sources: README.rst:59-100, backtest/strategies/strategy_template/strategy_template.py:108-124, strategies/utils/init.py:440-449 |
Operational Flow
The following diagram illustrates how Cerebro initializes and processes a backtest:
This diagram shows the sequence from engine instantiation to result visualization.
Sources: Tutorials/quickstart/101.py:18-28, backtest/strategies/strategy_template/strategy_template.py:126-140
Core Methods and Configuration
Cerebro provides a comprehensive API for setting up the trading environment.
Data and Strategy Registration
Developers use cerebro.adddata(data) to attach market information and cerebro.addstrategy(StrategyClass, **kwargs) to register the logic to be executed. For parameter optimization, cerebro.optstrategy() allows passing ranges of parameters to find optimal settings across multiple runs.
Sources: README.rst:48-52, backtest/strategies/strategy_template/strategy_template.py:121-123
Broker Simulation Settings
The engine allows fine-tuning the simulated market environment:
- Initial Capital: Set using
cerebro.broker.setcash(). - Commissions: Configured via
cerebro.broker.setcommission(). - Slippage: Simulated using
cerebro.broker.set_slippage_perc(). - Execution Modes: Supports "Cheat-on-Close" and "Cheat-on-Open" modes for realistic or specialized entry/exit timing.
Sources: README.md:50-60, backtest/strategies/strategy_template/strategy_template.py:113-119
Performance Evaluation
Standard performance metrics are integrated through the analyzer system. Cerebro collects these metrics during the run and returns them in the result object.
# Adding standard analyzers within the Cerebro framework
def add_standard_analyzers(cerebro):
cerebro.addanalyzer(bt.analyzers.SharpeRatio, _name="sharperatio")
cerebro.addanalyzer(bt.analyzers.Returns, _name="returns")
cerebro.addanalyzer(bt.analyzers.DrawDown, _name="drawdown")
cerebro.addanalyzer(bt.analyzers.TradeAnalyzer, _name="trades")
return cerebro
Sources: strategies/utils/init.py:440-449
Execution Lifecycle
The execution loop managed by Cerebro triggers specific hooks within the strategies at each step of the data processing.
This sequence details the interaction between Cerebro and Strategy hooks during a backtest.
Sources: backtest/strategies/strategy_template/strategy_template.py:28-85, backtest/strategies/test_strategy/test_strategy.py:53-73
Strategy Hooks
Cerebro calls these methods during the lifecycle:
start(): Called once at the beginning.prenext(): Called while indicators are still warming up (minimum period not reached).nextstart(): Called exactly once when the minimum period for indicators is first met.next(): The main logic loop called for every bar afternextstart.stop(): Called once at the end of the simulation.
Sources: backtest/strategies/strategy_template/strategy_template.py:28-56
Summary
The Cerebro engine is the foundational component of the project, providing a robust and extensible platform for financial backtesting and trading. It effectively decouples data acquisition, trading logic, and performance analysis, enabling a modular approach to strategy development. Through its comprehensive simulation of brokers, commissions, and slippage, it ensures that backtests provide a realistic approximation of market behavior.
Sources: README.md:10-30, README.rst:41-55