backtrader.cerebro module¶
Cerebro - The main engine of the Backtrader framework.
This module contains the Cerebro class, which is the central orchestrator for backtesting and live trading operations. Cerebro manages data feeds, strategies, brokers, analyzers, observers, and all other components of the trading system.
- Key Features:
Data feed management and synchronization
Strategy instantiation and execution
Broker integration for order execution
Multi-core optimization support
Live trading and backtesting modes
Plotting and analysis capabilities
示例
Basic backtest setup:
import backtrader as bt
cerebro = bt.Cerebro()
data = bt.feeds.GenericCSVData(dataname='data.csv')
cerebro.adddata(data)
cerebro.addstrategy(MyStrategy)
cerebro.broker.setcash(100000)
results = cerebro.run()
cerebro.plot()
- Classes:
OptReturn: Lightweight result object for optimization runs. Cerebro: Main backtesting/trading engine.
- class backtrader.cerebro.OptReturn[源代码]¶
基类:
objectLightweight result container for optimization runs.
This class is defined at module level to make it picklable for multiprocessing. It stores only essential information from strategy runs during optimization to reduce memory usage.
- p¶
Alias for params.
- params¶
Strategy parameters used in this optimization run.
- analyzers¶
Analyzer results (if returned during optimization).
备注
Additional attributes may be set dynamically via kwargs.
- class backtrader.cerebro.Cerebro[源代码]¶
基类:
RegistryMixin,NotificationMixin,RunLifecycleMixin,ChannelMixin,ExecutionMixin,RunNextMixin,RunOnceMixin,PresentationMixin,ParameterizedBaseParams:
preload(default:True)Whether to preload the different
data feedspassed to cerebro for the StrategiesNote: When True (default), data is loaded into memory before backtesting, which uses more memory but significantly improves execution speed.
runonce(default:True)Run Indicators in vectorized mode to speed up the entire system. Strategies and Observers will always be run on an event-based basis
Note: When True, indicators are calculated using vectorized operations for better performance. Strategies and observers still run event-by-event.
live(default:False)If no data has reported itself as live (via the data's
islivemethod but the end user still wants to run inlivemode, this parameter can be set to trueThis will simultaneously deactivate
preloadandrunonce. It will have no effect on memory saving schemes.Note: Setting to True forces live mode behavior, disabling preload and runonce optimizations, which slows down backtesting.
maxcpus(default: None -> all available cores)How many cores to use simultaneously for optimization
Note: Set to number of CPU cores minus 1 to avoid system overload. Use None (default) to use all available cores.
stdstats(default:True)If True, default Observers will be added: Broker (Cash and Value), Trades and BuySell
Note: These observers are used for plotting. Set to False if not needed.
oldbuysell(default:False)If
stdstatsisTrueand observers are getting automatically added, this switch controls the main behavior of theBuySellobserverFalse: use the modern behavior in which the buy / sell signals are plotted below / above the low / high prices respectively to avoid cluttering the plotTrue: use the deprecated behavior in which the buy / sell signals are plotted where the average price of the order executions for the given moment in time is. This will, of course, be on top of an OHLC bar or on a Line on Cloe bar, difficult the recognition of the plot.
Note: False (modern) plots signals outside the price bars for clarity. True (old) plots signals at execution price, overlapping with bars.
oldtrades(default:False)If
stdstatsisTrueand observers are getting automatically added, this switch controls the main behavior of theTradesobserverFalse: use the modern behavior in which trades for all datas are plotted with different markersTrue: use the old Trades observer which plots the trades with the same markers, differentiating only if they are positive or negative
Note: False uses different markers for different trades. True uses same markers, only distinguishing positive/negative.
exactbars(default:False)With the default value, each and every value stored in a line is kept in memory
- Possible values:
Trueor1: all "lines" objects reduce memory usage to the automatically calculated minimum period.If a Simple Moving Average has a period of 30, the underlying data will have always a running buffer of 30 bars to allow the calculation of the Simple Moving Average
This setting will deactivate
preloadandrunonceUsing this setting also deactivates plotting
-1: datafeeds and indicators/operations at strategy level will keep all data in memory.For example: a
RSIinternally uses the indicatorUpDayto make calculations. This subindicator will not keep all data in memoryThis allows keeping
plottingandpreloadingactive.runoncewill be deactivated
-2: data feeds and indicators kept as attributes of the strategy will keep all points in memory.For example: a
RSIinternally uses the indicatorUpDayto make calculations. This subindicator will not keep all data in memoryIf in the
__init__something likea = self.data.close - self.data.highis defined, thenawill not keep all data in memoryThis allows keeping
plottingandpreloadingactive.runoncewill be deactivated
- Note on exactbars values:
True/1: Minimum memory, disables preload/runonce/plotting
-1: Keeps data/indicators but not sub-indicator internals, disables runonce
-2: Keeps strategy-level data/indicators, sub-indicators not using self are discarded
objcache(default:False)Experimental option to implement a cache of lines objects and reduce the amount of them. Example from UltimateOscillator:
bp = self.data.close - TrueLow(self.data) tr = TrueRange(self.data) # -> creates another TrueLow(self.data)
If this is True, the second
TrueLow(self.data)insideTrueRangematches the signature of the one in thebpcalculation. It will be reused.Corner cases may happen in which this drives a line object off its minimum period and breaks things, and it is therefore disabled.
Note: When True, identical indicator calculations are cached and reused to reduce computation. Disabled by default due to edge cases.
writer(default:False)If set to
Truea default WriterFile will be created which will print to stdout. It will be added to the strategy (in addition to any other writers added by the user code)Note: Outputs trading information to stdout. Custom logging in strategy is usually preferred for more control.
tradehistory(default:False)If set to
True, it will activate update event logging in each trade for all strategies. This can also be achieved on a per-strategy basis with the strategy methodset_tradehistoryNote: Enables trade update logging for all strategies. Can also be enabled per-strategy using set_tradehistory method.
optdatas(default:True)If
Trueand optimizing (and the system canpreloadand userunonce, data preloading will be done only once in the main process to save time and resources.The tests show an approximate
20%speed-up moving from a sample execution in83seconds to66Note: When True with preload/runonce, data is preloaded once in the main process and shared across optimization workers (~20% speedup).
optreturn(default:True)If True, the optimization results will not be full
Strategyobjects (and all datas, indicators, observers ...) but object with the following attributes (same as inStrategy):params(orp) the strategy had for the executionanalyzersthe strategy has executed
On most occasions, only the analyzers and with which params are the things needed to evaluate the performance of a strategy. If detailed analysis of the generated values for (for example) indicators is needed, turn this off
The tests show a 13% - 15% improvement in execution time. Combined with optdatas the total gain increases to a total speed-up of 32% in an optimization run.
Note: Returns only params and analyzers during optimization, discarding data/indicators/observers for ~15% speedup (32% combined with optdatas).
oldsync(default:False)Starting with release 1.9.0.99, the synchronization of multiple datas (same or different timeframes) has been changed to allow datas of different lengths.
If the old behavior with data0 as the master of the system is wished, set this parameter to true
Note: False allows data feeds of different lengths. True uses data0 as master (legacy behavior).
tz(default:None)Adds a global timezone for strategies. The argument
tzcan beNone: in this case the datetime displayed by strategies will be in UTC, which has always been the standard behaviorpytzinstance. It will be used as such to convert UTC times to the chosen timezonestring. Instantiating apytzinstance will be attempted.integer. Use, for the strategy, the same timezone as the correspondingdatain theself.datasiterable (0would use the timezone fromdata0)
Note: None=UTC, pytz instance converts from UTC, string creates pytz, integer uses timezone from corresponding data feed index.
cheat_on_open(default:False)The
next_openmethod of strategies will be called. This happens beforenextand before the broker has had a chance to evaluate orders. The indicators have not yet been recalculated. This allows issuing an order which takes into account the indicators of the previous day but uses theopenprice for stake calculationsFor cheat_on_open order execution, it is also necessary to make the call
cerebro.broker.set_coo(True)or instantiate a broker withBackBroker(coo=True)(where coo stands for cheat-on-open) or set thebroker_cooparameter toTrue. Cerebro will do it automatically unless disabled below.Note: Enables using next bar's open price for position sizing. Useful for precise capital allocation. Requires broker_coo=True.
broker_coo(default:True)This will automatically invoke the
set_coomethod of the broker withTrueto activatecheat_on_openexecution. Will only do it ifcheat_on_openis alsoTrueNote: Works together with cheat_on_open parameter.
quicknotify(default:False)Broker notifications are delivered right before the delivery of the next prices. For backtesting, this has no implications, but with live
brokers, a notification can take place long before the bar is
delivered. When set to
Truenotifications will be delivered as soon as possible (seeqcheckin live feeds)Set to
Falsefor compatibility. May be changed toTrueNote: False delays notifications until next bar. True sends immediately. Mainly relevant for live trading.
- preload¶
Advanced parameter descriptor with type checking and validation.
This descriptor replaces the metaclass-based parameter system with a more modern and maintainable approach. It provides:
Automatic type checking and conversion
Value validation
Default value handling
Documentation support
Python 3.6+ __set_name__ support
- runonce¶
Advanced parameter descriptor with type checking and validation.
This descriptor replaces the metaclass-based parameter system with a more modern and maintainable approach. It provides:
Automatic type checking and conversion
Value validation
Default value handling
Documentation support
Python 3.6+ __set_name__ support
- maxcpus¶
Advanced parameter descriptor with type checking and validation.
This descriptor replaces the metaclass-based parameter system with a more modern and maintainable approach. It provides:
Automatic type checking and conversion
Value validation
Default value handling
Documentation support
Python 3.6+ __set_name__ support
- stdstats¶
Advanced parameter descriptor with type checking and validation.
This descriptor replaces the metaclass-based parameter system with a more modern and maintainable approach. It provides:
Automatic type checking and conversion
Value validation
Default value handling
Documentation support
Python 3.6+ __set_name__ support
- oldbuysell¶
Advanced parameter descriptor with type checking and validation.
This descriptor replaces the metaclass-based parameter system with a more modern and maintainable approach. It provides:
Automatic type checking and conversion
Value validation
Default value handling
Documentation support
Python 3.6+ __set_name__ support
- oldtrades¶
Advanced parameter descriptor with type checking and validation.
This descriptor replaces the metaclass-based parameter system with a more modern and maintainable approach. It provides:
Automatic type checking and conversion
Value validation
Default value handling
Documentation support
Python 3.6+ __set_name__ support
- lookahead¶
Advanced parameter descriptor with type checking and validation.
This descriptor replaces the metaclass-based parameter system with a more modern and maintainable approach. It provides:
Automatic type checking and conversion
Value validation
Default value handling
Documentation support
Python 3.6+ __set_name__ support
- exactbars¶
Advanced parameter descriptor with type checking and validation.
This descriptor replaces the metaclass-based parameter system with a more modern and maintainable approach. It provides:
Automatic type checking and conversion
Value validation
Default value handling
Documentation support
Python 3.6+ __set_name__ support
- optdatas¶
Advanced parameter descriptor with type checking and validation.
This descriptor replaces the metaclass-based parameter system with a more modern and maintainable approach. It provides:
Automatic type checking and conversion
Value validation
Default value handling
Documentation support
Python 3.6+ __set_name__ support
- optreturn¶
Advanced parameter descriptor with type checking and validation.
This descriptor replaces the metaclass-based parameter system with a more modern and maintainable approach. It provides:
Automatic type checking and conversion
Value validation
Default value handling
Documentation support
Python 3.6+ __set_name__ support
- objcache¶
Advanced parameter descriptor with type checking and validation.
This descriptor replaces the metaclass-based parameter system with a more modern and maintainable approach. It provides:
Automatic type checking and conversion
Value validation
Default value handling
Documentation support
Python 3.6+ __set_name__ support
- live¶
Advanced parameter descriptor with type checking and validation.
This descriptor replaces the metaclass-based parameter system with a more modern and maintainable approach. It provides:
Automatic type checking and conversion
Value validation
Default value handling
Documentation support
Python 3.6+ __set_name__ support
- writer¶
Advanced parameter descriptor with type checking and validation.
This descriptor replaces the metaclass-based parameter system with a more modern and maintainable approach. It provides:
Automatic type checking and conversion
Value validation
Default value handling
Documentation support
Python 3.6+ __set_name__ support
- tradehistory¶
Advanced parameter descriptor with type checking and validation.
This descriptor replaces the metaclass-based parameter system with a more modern and maintainable approach. It provides:
Automatic type checking and conversion
Value validation
Default value handling
Documentation support
Python 3.6+ __set_name__ support
- oldsync¶
Advanced parameter descriptor with type checking and validation.
This descriptor replaces the metaclass-based parameter system with a more modern and maintainable approach. It provides:
Automatic type checking and conversion
Value validation
Default value handling
Documentation support
Python 3.6+ __set_name__ support
- tz¶
Advanced parameter descriptor with type checking and validation.
This descriptor replaces the metaclass-based parameter system with a more modern and maintainable approach. It provides:
Automatic type checking and conversion
Value validation
Default value handling
Documentation support
Python 3.6+ __set_name__ support
- cheat_on_open¶
Advanced parameter descriptor with type checking and validation.
This descriptor replaces the metaclass-based parameter system with a more modern and maintainable approach. It provides:
Automatic type checking and conversion
Value validation
Default value handling
Documentation support
Python 3.6+ __set_name__ support
- broker_coo¶
Advanced parameter descriptor with type checking and validation.
This descriptor replaces the metaclass-based parameter system with a more modern and maintainable approach. It provides:
Automatic type checking and conversion
Value validation
Default value handling
Documentation support
Python 3.6+ __set_name__ support
- quicknotify¶
Advanced parameter descriptor with type checking and validation.
This descriptor replaces the metaclass-based parameter system with a more modern and maintainable approach. It provides:
Automatic type checking and conversion
Value validation
Default value handling
Documentation support
Python 3.6+ __set_name__ support
- __init__(**kwargs)[源代码]¶
Initialize Cerebro with optional parameter overrides.
- 参数:
**kwargs -- Parameter overrides (preload, runonce, maxcpus, etc.)
- setbroker(broker)[源代码]¶
Sets a specific
brokerinstance for this strategy, replacing the one inherited from cerebro.
- getbroker()[源代码]¶
Returns the broker instance.
This is also available as a
propertyby the namebroker
- __call__(iterstrat)[源代码]¶
Used during optimization to pass the cerebro over the multiprocessing module without complaints
- __getstate__()[源代码]¶
Used during optimization to prevent optimization result runstrats from being pickled to subprocesses
- run(**kwargs)[源代码]¶
The core method to perform backtesting. Any
kwargspassed to it will affect the value of the standard parametersCerebrowas instantiated with.If cerebro has no data and no
channelis given, the method will immediately bail out.Extra keyword arguments¶
- channeliterable or True, optional
When provided the engine runs in channel mode instead of the traditional bar-based mode.
iterable – an
Eventstream (StreamingEventQueue,LiveEventQueue, or any iterable yieldingEventobjects). Events are dispatched to the broker and then to every strategy via theirnotify_*callbacks.True– strategies are instantiated and returned immediately without entering an event loop. This is useful when an external async loop drives the data (e.g. external market-data watchers callingstrategy.notify_tick()directly). Callcerebro.close_channel()from the same thread when that external loop is done to tear down brokers and strategies.
It has different return values:
For No Optimization: a list contanining instances of the Strategy classes added with
addstrategyFor Optimization: a list of lists which contain instances of the Strategy classes added with
addstrategy
- 返回类型:
- property broker¶
Returns the broker instance.
This is also available as a
propertyby the namebroker