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
Example
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[source]¶
Bases:
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).
Note
Additional attributes may be set dynamically via kwargs.
- class backtrader.cerebro.Cerebro[source]¶
Bases:
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)[source]¶
Initialize Cerebro with optional parameter overrides.
- Parameters:
**kwargs – Parameter overrides (preload, runonce, maxcpus, etc.)
- static iterize(iterable)[source]¶
Convert each element in iterable to be iterable itself.
- Parameters:
iterable – Input iterable whose elements may not be iterable.
- Returns:
New list where each element is guaranteed to be iterable.
- Return type:
- set_fund_history(fund)[source]¶
Add a history of orders to be directly executed in the broker for performance evaluation
fund: is an iterable (ex: list, tuple, iterator, generator) in which each element will be also iterable (with length) with the following sub-elements (two formats are possible)[datetime, share_value, net asset value]- Note: it must be sorted (or produce sorted elements) by
datetime ascending
where:
datetimeis a pythondate/datetimeinstance or a string with format YYYY-MM-DD[THH:MM:SS[.us]] where the elements in brackets are optionalshare_valueis a float/integernet_asset_valueis a float/integer
- add_order_history(orders, notify=True)[source]¶
Add a history of orders to be directly executed in the broker for performance evaluation
orders: is an iterable (ex: list, tuple, iterator, generator) in which each element will be also iterable (with length) with the following sub-elements (two formats are possible)[datetime, size, price]or[datetime, size, price, data]- Note: it must be sorted (or produce sorted elements) by
datetime ascending
where:
datetimeis a pythondate/datetimeinstance or a string with format YYYY-MM-DD[THH:MM:SS[.us]] where the elements in brackets are optionalsizeis an integer (positive to buy, negative to sell)priceis a float/integerdataif present can take any of the following valuesNone - The 1st data feed will be used as target
integer - The data with that index (insertion order in Cerebro) will be used
string - a data with that name, assigned for example with
cerebro.addata(data, name=value), will be the target
notify(default: True)If
True, the first strategy inserted in the system will be notified of the artificial orders created following the information from each order inorders
- Note: Implicit in the description is the need to add a data feed
which is the target of the orders.This is, for example, needed by analyzers which track, for example, the returns
- notify_timer(timer, when, *args, **kwargs)[source]¶
Receives a timer notification where
timeris the timer that was returned byadd_timer, andwhenis the calling time.argsandkwargsare any additional arguments passed toadd_timerThe actual when time can be later, but the system may have not been able to call the timer before. This value is the timer value and no the system time.
- add_timer(when, offset=datetime.timedelta(0), repeat=datetime.timedelta(0), weekdays=[], weekcarry=False, monthdays=[], monthcarry=True, allow=None, tzdata=None, strats=False, cheat=False, *args, **kwargs)[source]¶
Schedules a timer to invoke
notify_timer- Parameters:
when (-) –
can be
datetime.timeinstance (see belowtzdata)bt.timer.SESSION_STARTto reference a session startbt.timer.SESSION_ENDto reference a session end
offsetwhich must be adatetime.timedeltainstanceUsed to offset the value
when. It has a meaningful use in combination withSESSION_STARTandSESSION_END, to indicate things like a timer being called15 minutesafter the sessionstarts.
repeatwhich must be adatetime.timedeltainstanceIndicates if after a first call, further calls will be scheduled within the same session at the scheduled repeat delta
Once the timer goes over the end of the session, it is reset to the original value for
whenweekdays: a sorted iterable with integers indicating on which days (iso codes, Monday is 1, Sunday is 7) the timers can be actually invokedIf not specified, the timer will be active on all days
weekcarry(default:False). IfTrueand the weekday was not seen (ex: trading holiday), the timer will be executed on the next day (even if in a new week)monthdays: a sorted iterable with integers indicating on which days of the month a timer has to be executed. For example, always on day 15 of the monthIf not specified, the timer will be active on all days
monthcarry(default:True). If the day was not seen (weekend, trading holiday), the timer will be executed on the next available day.allow(default:None). A callback which receives a datetime.date` instance and returnsTrueif the date is allowed for timers or else returnsFalsetzdatawhich can be eitherNone(default), apytzinstance or adata feedinstance.None:whenis interpreted at face value (which translates to handling it as if it is UTC even if it’s not)pytzinstance:whenwill be interpreted as being specified in the local time specified by the timezone instance.data feedinstance:whenwill be interpreted as being specified in the local time specified by thetzparameter of the data feed instance.- Note: If
whenis eitherSESSION_STARTor SESSION_ENDandtzdataisNone, the first data feed in the system (akaself.data0) will be used as the reference to find out the session times.
- Note: If
strats(default:False) call also thenotify_timerof strategiescheat(defaultFalse) ifTruethe timer will be called before the broker has a chance to evaluate the orders. This opens the chance to issue orders based on opening price, for example, right before the session starts*args: any extra args will be passed tonotify_timer**kwargs: any extra kwargs will be passed tonotify_timer
Return Value:
The created timer
- addtz(tz)[source]¶
This can also be done with the parameter
tzAdds 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)
- addcalendar(cal)[source]¶
Adds a global trading calendar to the system. Individual data feeds may have separate calendars which override the global one
calcan be an instance ofTradingCalendara string or an instance ofpandas_market_calendars. A string will be instantiated as aPandasMarketCalendar(which needs the modulepandas_market_calendarinstalled in the system).If a subclass of TradingCalendarBase is passed (not an instance), it will be instantiated
- add_signal(sigtype, sigcls, *sigargs, **sigkwargs)[source]¶
Add a signal to be used with SignalStrategy.
- signal_strategy(stratcls, *args, **kwargs)[source]¶
Set a SignalStrategy subclass to receive signals.
- signal_accumulate(onoff)[source]¶
If signals are added to the system and the accumulate value is set to True, entering the market when already in the market, will be allowed to increase a position
- addwriter(wrtcls, *args, **kwargs)[source]¶
Adds an
Writerclass to the mix. Instantiation will be done atruntime in cerebro
- addsizer(sizercls, *args, **kwargs)[source]¶
Adds a
Sizerclass (and args) which is the default sizer for any strategy added to cerebro
- addsizer_byidx(idx, sizercls, *args, **kwargs)[source]¶
Adds a
Sizerclass by idx. This idx is a reference compatible to the one returned byaddstrategy. Only the strategy referenced byidxwill receive this size
- addindicator(indcls, *args, **kwargs)[source]¶
Add an Indicator class to be instantiated at run time.
- addanalyzer(ancls, *args, **kwargs)[source]¶
Add an Analyzer class to be instantiated at run time.
- Parameters:
ancls (type)
- Return type:
None
- addobserver(obscls, *args, **kwargs)[source]¶
Adds an
Observerclass to the mix. Instantiation will be done atruntime- Parameters:
obscls (type)
- Return type:
None
- addobservermulti(obscls, *args, **kwargs)[source]¶
It will be added once per “data” in the system. A use case is a buy/sell observer that observes individual data.
A counter-example is the CashValue, which observes system-wide values
- addstorecb(callback)[source]¶
Adds a callback to get messages which would be handled by the notify_store method
The signature of the callback must support the following:
The actual
msg,*argsand**kwargsreceived are implementation defined (depend entirely on the data/broker/store) but in general one should expect them to be printable to allow for reception and experimentation.
- notify_store(msg, *args, **kwargs)[source]¶
Receive store notifications in cerebro
This method can be overridden in
CerebrosubclassesThe actual
msg,*argsand**kwargsreceived are implementation defined (depend entirely on the data/broker/store) but in general one should expect them to be printable to allow for reception and experimentation.
- adddatacb(callback)[source]¶
Adds a callback to get messages which would be handled by the notify_data method
The signature of the callback must support the following:
The actual
*argsand**kwargsreceived are implementation defined (depend entirely on the data/broker/store), but in general one should expect them to be printable to allow for reception and experimentation.
- notify_data(data, status, *args, **kwargs)[source]¶
Receive data notifications in cerebro
This method can be overridden in
CerebrosubclassesThe actual
*argsand**kwargsreceived are implementation defined (depend entirely on the data/broker/store), but in general one should expect them to be printable to allow for reception and experimentation.
- dispatch_channel_event(event)[source]¶
Dispatch a channel event to all running strategies.
Routes tick, orderbook, funding, and bar events from the channel system (StreamingEventQueue / LiveEventQueue) to the appropriate
notify_*callbacks on each strategy.- Parameters:
event – Event wrapper with
.dataand.channel_typeattrs.
- adddata(data, name=None)[source]¶
Adds a
Data Feedinstance to the mix.If
nameis not None, it will be put intodata._namewhich is meant for decoration/plotting purposes.- Parameters:
name (str)
- chaindata(*args, **kwargs)[source]¶
Chains several data feeds into one
If
nameis passed as named argument and not None, it will be put intodata._namewhich is meant for decoration/plotting purposes.If None, then the name of the first data will be used
- rolloverdata(*args, **kwargs)[source]¶
Chains several data feeds into one
If
nameis passed as named argument and is not None, it will be put intodata._namewhich is meant for decoration/plotting purposes.If None, then the name of the first data will be used
Any other kwargs will be passed to the RollOver class
- replaydata(dataname, name=None, **kwargs)[source]¶
Adds a
Data Feedto be replayed by the systemIf
nameis not None, it will be put intodata._namewhich is meant for decoration/plotting purposes.Any other kwargs like
timeframe,compression,todatewhich are supported by the replay filter will be passed transparently
- resampledata(dataname, name=None, **kwargs)[source]¶
Adds a
Data Feedto be resample by the systemIf
nameis not None, it will be put intodata._namewhich is meant for decoration/plotting purposes.Any other kwargs like
timeframe,compression,todatewhich are supported by the resample filter will be passed transparently
- optcallback(cb)[source]¶
Adds a callback to the list of callbacks that will be called with the optimizations when each of the strategies has been run
The signature: cb(strategy)
- optstrategy(strategy, *args, **kwargs)[source]¶
Adds a
Strategyclass to the mix for optimization. Instantiation will happen duringruntime.args and kwargs MUST BE iterables that hold the values to check.
Example: if a Strategy accepts a parameter period, for optimization purposes, the call to
optstrategylooks like:cerebro.optstrategy(MyStrategy, period=(15, 25))
This will execute an optimization for values 15 and 25. Whereas
cerebro.optstrategy(MyStrategy, period=range(15, 25))
will execute MyStrategy with
periodvalues 15 -> 25 (25 not included, because ranges are semi-open in Python)If a parameter is passed but shall not be optimized, the call looks like:
cerebro.optstrategy(MyStrategy, period=(15,))
Notice that period is still passed as an iterable … of just one element
backtraderwill anyhow try to identify situations like:cerebro.optstrategy(MyStrategy, period=15)
and will create an internal pseudo-iterable if possible
- addstrategy(strategy, *args, **kwargs)[source]¶
Adds a
Strategyclass to the mix for a single pass run. Instantiation will happen duringruntime.Args and kwargs will be passed to the strategy as they are during instantiation.
Returns the index with which addition of other objects (like sizers) can be referenced
- setbroker(broker)[source]¶
Sets a specific
brokerinstance for this strategy, replacing the one inherited from cerebro.- Return type:
None
- getbroker()[source]¶
Returns the broker instance.
This is also available as a
propertyby the namebroker
- property broker¶
Returns the broker instance.
This is also available as a
propertyby the namebroker
- plot(plotter=None, numfigs=1, iplot=True, start=None, end=None, width=16, height=9, dpi=300, tight=True, use=None, backend='matplotlib', **kwargs)[source]¶
Plots the strategies inside cerebro
If
plotteris None, a defaultPlotinstance is created andkwargsare passed to it during instantiation.numfigssplit the plot in the indicated number of charts reducing chart density if wishediplot: ifTrueand running in anotebookthe charts will be displayed inlineuse: set it to the name of the desired matplotlib backend. It will take precedence overiplotbackend: plotting backend to use. Options:‘matplotlib’: traditional matplotlib plotting (default)
‘plotly’: interactive Plotly charts (better for large data)
start: An index to the datetime line array of the strategy or adatetime.date,datetime.datetimeinstance indicating the start of the plotend: An index to the datetime line array of the strategy or adatetime.date,datetime.datetimeinstance indicating the end of the plotwidth: in inches of the saved figureheight: in inches of the saved figuredpi: quality in dots per inches of the saved figuretight: only save actual content and not the frame of the figure
- __call__(iterstrat)[source]¶
Used during optimization to pass the cerebro over the multiprocessing module without complaints
- __getstate__()[source]¶
Used during optimization to prevent optimization result runstrats from being pickled to subprocesses
- runstop()[source]¶
If invoked from inside a strategy or anywhere else, including other threads, the execution will stop as soon as possible.
- run(**kwargs)[source]¶
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.ccxt.prowatchers callingstrategy.notify_tick()directly). Callcerebro.runstop()when 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
- Return type:
- runstrategies(iterstrat, predata=False)[source]¶
Internal method invoked by
run`to run a set of strategies
- stop_writers(runstrats)[source]¶
Stop all writers and write final information.
- Parameters:
runstrats – List of strategy instances that were run.
Collects information from data feeds and strategies, writes the information to all registered writers, and stops them.
- add_report_analyzers(riskfree_rate=0.01)[source]¶
Automatically add analyzers required for reporting.
Adds the following analyzers: - SharpeRatio: Sharpe ratio - DrawDown: Drawdown analysis - TradeAnalyzer: Trade analysis - SQN: System Quality Number - AnnualReturn: Annual returns
- Parameters:
riskfree_rate – Risk-free rate, default 0.01 (1%)
- generate_report(output_path, format='html', template='default', user=None, memo=None, **kwargs)[source]¶
Generate backtest report.
- Parameters:
output_path – Output file path
format – Report format (‘html’, ‘pdf’, ‘json’)
template – Template name or path (only for HTML/PDF)
user – Username
memo – Remarks/notes
**kwargs – Additional parameters
- Returns:
Output file path
- Return type:
- Raises:
RuntimeError – If strategy has not been run yet
Example
cerebro = bt.Cerebro() cerebro.addstrategy(MyStrategy) cerebro.adddata(data) cerebro.run() cerebro.generate_report(‘report.html’)