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[源代码]

基类:object

Lightweight 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.

__init__(params, **kwargs)[源代码]

Initialize the OptReturn object.

参数:
  • params -- Strategy parameters used in this optimization run.

  • **kwargs -- Additional keyword arguments to set as attributes.

class backtrader.cerebro.Cerebro[源代码]

基类:RegistryMixin, NotificationMixin, RunLifecycleMixin, ChannelMixin, ExecutionMixin, RunNextMixin, RunOnceMixin, PresentationMixin, ParameterizedBase

Params:

  • preload (default: True)

    Whether to preload the different data feeds passed to cerebro for the Strategies

    Note: 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 islive method but the end user still wants to run in live mode, this parameter can be set to true

    This will simultaneously deactivate preload and runonce. 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 stdstats is True and observers are getting automatically added, this switch controls the main behavior of the BuySell observer

    • False: use the modern behavior in which the buy / sell signals are plotted below / above the low / high prices respectively to avoid cluttering the plot

    • True: 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 stdstats is True and observers are getting automatically added, this switch controls the main behavior of the Trades observer

    • False: use the modern behavior in which trades for all datas are plotted with different markers

    • True: 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:
    • True or 1: 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 preload and runonce

      • Using this setting also deactivates plotting

    • -1: datafeeds and indicators/operations at strategy level will keep all data in memory.

      For example: a RSI internally uses the indicator UpDay to make calculations. This subindicator will not keep all data in memory

      • This allows keeping plotting and preloading active.

      • runonce will be deactivated

    • -2: data feeds and indicators kept as attributes of the strategy will keep all points in memory.

      For example: a RSI internally uses the indicator UpDay to make calculations. This subindicator will not keep all data in memory

      If in the __init__ something like a = self.data.close - self.data.high is defined, then a will not keep all data in memory

      • This allows keeping plotting and preloading active.

      • runonce will 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) inside TrueRange matches the signature of the one in the bp calculation. 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 True a 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 method set_tradehistory

    Note: Enables trade update logging for all strategies. Can also be enabled per-strategy using set_tradehistory method.

  • optdatas (default: True)

    If True and optimizing (and the system can preload and use runonce, 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 in 83 seconds to 66

    Note: 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 Strategy objects (and all datas, indicators, observers ...) but object with the following attributes (same as in Strategy):

    • params (or p) the strategy had for the execution

    • analyzers the 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 tz can be

    • None: in this case the datetime displayed by strategies will be in UTC, which has always been the standard behavior

    • pytz instance. It will be used as such to convert UTC times to the chosen timezone

    • string. Instantiating a pytz instance will be attempted.

    • integer. Use, for the strategy, the same timezone as the corresponding data in the self.datas iterable (0 would use the timezone from data0)

    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_open method of strategies will be called. This happens before next and 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 the open price for stake calculations

    For cheat_on_open order execution, it is also necessary to make the call cerebro.broker.set_coo(True) or instantiate a broker with BackBroker(coo=True) (where coo stands for cheat-on-open) or set the broker_coo parameter to True. 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_coo method of the broker with True to activate cheat_on_open execution. Will only do it if cheat_on_open is also True

    Note: 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 True notifications will be delivered as soon as possible (see qcheck in live feeds)

    Set to False for compatibility. May be changed to True

    Note: 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 broker instance for this strategy, replacing the one inherited from cerebro.

getbroker()[源代码]

Returns the broker instance.

This is also available as a property by the name broker

__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

__setstate__(state)[源代码]

Restore process-local run-stop state after multiprocessing pickle.

run(**kwargs)[源代码]

The core method to perform backtesting. Any kwargs passed to it will affect the value of the standard parameters Cerebro was instantiated with.

If cerebro has no data and no channel is 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 Event stream (StreamingEventQueue, LiveEventQueue, or any iterable yielding Event objects). Events are dispatched to the broker and then to every strategy via their notify_* 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 calling strategy.notify_tick() directly). Call cerebro.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 addstrategy

  • For Optimization: a list of lists which contain instances of the Strategy classes added with addstrategy

返回类型:

list

property broker

Returns the broker instance.

This is also available as a property by the name broker