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

基类: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.)

static iterize(iterable)[源代码]

Convert each element in iterable to be iterable itself.

参数:

iterable -- Input iterable whose elements may not be iterable.

返回:

New list where each element is guaranteed to be iterable.

返回类型:

list

set_fund_history(fund)[源代码]

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:

    • datetime is a python date/datetime instance or a string with format YYYY-MM-DD[THH:MM:SS[.us]] where the elements in brackets are optional

    • share_value is a float/integer

    • net_asset_value is a float/integer

add_order_history(orders, notify=True)[源代码]

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:

    • datetime is a python date/datetime instance or a string with format YYYY-MM-DD[THH:MM:SS[.us]] where the elements in brackets are optional

    • size is an integer (positive to buy, negative to sell)

    • price is a float/integer

    • data if present can take any of the following values

      • None - 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 in orders

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

Receives a timer notification where timer is the timer that was returned by add_timer, and when is the calling time. args and kwargs are any additional arguments passed to add_timer

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

Schedules a timer to invoke notify_timer

参数:

when (-) --

can be

  • datetime.time instance (see below tzdata)

  • bt.timer.SESSION_START to reference a session start

  • bt.timer.SESSION_END to reference a session end

  • offset which must be a datetime.timedelta instance

    Used to offset the value when. It has a meaningful use in combination with SESSION_START and SESSION_END, to indicate things like a timer being called 15 minutes after the session

    starts.

  • repeat which must be a datetime.timedelta instance

    Indicates 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 when

  • weekdays: a sorted iterable with integers indicating on which days (iso codes, Monday is 1, Sunday is 7) the timers can be actually invoked

    If not specified, the timer will be active on all days

  • weekcarry (default: False). If True and 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 month

    If 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 returns True if the date is allowed for timers or else returns False

  • tzdata which can be either None (default), a pytz instance or a data feed instance.

    None: when is interpreted at face value (which translates to handling it as if it is UTC even if it's not)

    pytz instance: when will be interpreted as being specified in the local time specified by the timezone instance.

    data feed instance: when will be interpreted as being specified in the local time specified by the tz parameter of the data feed instance.

    Note: If when is either SESSION_START or

    SESSION_END and tzdata is None, the first data feed in the system (aka self.data0) will be used as the reference to find out the session times.

  • strats (default: False) call also the notify_timer of strategies

  • cheat (default False) if True the 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 to notify_timer

  • **kwargs: any extra kwargs will be passed to notify_timer

Return Value:

  • The created timer

addtz(tz)[源代码]

This can also be done with the parameter tz

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)

addcalendar(cal)[源代码]

Adds a global trading calendar to the system. Individual data feeds may have separate calendars which override the global one

cal can be an instance of TradingCalendar a string or an instance of pandas_market_calendars. A string will be instantiated as a PandasMarketCalendar (which needs the module pandas_market_calendar installed in the system).

If a subclass of TradingCalendarBase is passed (not an instance), it will be instantiated

add_signal(sigtype, sigcls, *sigargs, **sigkwargs)[源代码]

Add a signal to be used with SignalStrategy.

signal_strategy(stratcls, *args, **kwargs)[源代码]

Set a SignalStrategy subclass to receive signals.

signal_concurrent(onoff)[源代码]

Allow concurrent orders when signals are pending.

signal_accumulate(onoff)[源代码]

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

addstore(store)[源代码]

Add a Store instance to the system.

addwriter(wrtcls, *args, **kwargs)[源代码]

Adds an Writer class to the mix. Instantiation will be done at run time in cerebro

addsizer(sizercls, *args, **kwargs)[源代码]

Adds a Sizer class (and args) which is the default sizer for any strategy added to cerebro

addsizer_byidx(idx, sizercls, *args, **kwargs)[源代码]

Adds a Sizer class by idx. This idx is a reference compatible to the one returned by addstrategy. Only the strategy referenced by idx will receive this size

addindicator(indcls, *args, **kwargs)[源代码]

Add an Indicator class to be instantiated at run time.

addanalyzer(ancls, *args, **kwargs)[源代码]

Add an Analyzer class to be instantiated at run time.

参数:

ancls (type)

返回类型:

None

addobserver(obscls, *args, **kwargs)[源代码]

Adds an Observer class to the mix. Instantiation will be done at run time

参数:

obscls (type)

返回类型:

None

addobservermulti(obscls, *args, **kwargs)[源代码]

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

Adds a callback to get messages which would be handled by the notify_store method

The signature of the callback must support the following:

  • callback(msg, *args, *kwargs)

The actual msg, *args and **kwargs received 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)[源代码]

Receive store notifications in cerebro

This method can be overridden in Cerebro subclasses

The actual msg, *args and **kwargs received 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)[源代码]

Adds a callback to get messages which would be handled by the notify_data method

The signature of the callback must support the following:

  • callback(data, status, *args, *kwargs)

The actual *args and **kwargs received 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)[源代码]

Receive data notifications in cerebro

This method can be overridden in Cerebro subclasses

The actual *args and **kwargs received 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)[源代码]

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.

参数:

event -- Event wrapper with .data and .channel_type attrs.

adddata(data, name=None)[源代码]

Adds a Data Feed instance to the mix.

If name is not None, it will be put into data._name which is meant for decoration/plotting purposes.

参数:

name (str)

chaindata(*args, **kwargs)[源代码]

Chains several data feeds into one

If name is passed as named argument and not None, it will be put into data._name which is meant for decoration/plotting purposes.

If None, then the name of the first data will be used

rolloverdata(*args, **kwargs)[源代码]

Chains several data feeds into one

If name is passed as named argument and is not None, it will be put into data._name which 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)[源代码]

Adds a Data Feed to be replayed by the system

If name is not None, it will be put into data._name which is meant for decoration/plotting purposes.

Any other kwargs like timeframe, compression, todate which are supported by the replay filter will be passed transparently

resampledata(dataname, name=None, **kwargs)[源代码]

Adds a Data Feed to be resample by the system

If name is not None, it will be put into data._name which is meant for decoration/plotting purposes.

Any other kwargs like timeframe, compression, todate which are supported by the resample filter will be passed transparently

optcallback(cb)[源代码]

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

Adds a Strategy class to the mix for optimization. Instantiation will happen during run time.

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 optstrategy looks 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 period values 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

backtrader will anyhow try to identify situations like:

  • cerebro.optstrategy(MyStrategy, period=15)

and will create an internal pseudo-iterable if possible

addstrategy(strategy, *args, **kwargs)[源代码]

Adds a Strategy class to the mix for a single pass run. Instantiation will happen during run time.

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

参数:

strategy (type)

返回类型:

int

setbroker(broker)[源代码]

Sets a specific broker instance for this strategy, replacing the one inherited from cerebro.

返回类型:

None

getbroker()[源代码]

Returns the broker instance.

This is also available as a property by the name broker

property broker

Returns the broker instance.

This is also available as a property by the name broker

plot(plotter=None, numfigs=1, iplot=True, start=None, end=None, width=16, height=9, dpi=300, tight=True, use=None, backend='matplotlib', **kwargs)[源代码]

Plots the strategies inside cerebro

If plotter is None, a default Plot instance is created and kwargs are passed to it during instantiation.

numfigs split the plot in the indicated number of charts reducing chart density if wished

iplot: if True and running in a notebook the charts will be displayed inline

use: set it to the name of the desired matplotlib backend. It will take precedence over iplot

backend: 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 a datetime.date, datetime.datetime instance indicating the start of the plot

end: An index to the datetime line array of the strategy or a datetime.date, datetime.datetime instance indicating the end of the plot

width: in inches of the saved figure

height: in inches of the saved figure

dpi: quality in dots per inches of the saved figure

tight: only save actual content and not the frame of the figure

__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

runstop()[源代码]

If invoked from inside a strategy or anywhere else, including other threads, the execution will stop as soon as possible.

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. ccxt.pro watchers calling strategy.notify_tick() directly). Call cerebro.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 addstrategy

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

返回类型:

list

runstrategies(iterstrat, predata=False)[源代码]

Internal method invoked by run` to run a set of strategies

stop_writers(runstrats)[源代码]

Stop all writers and write final information.

参数:

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

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

参数:

riskfree_rate -- Risk-free rate, default 0.01 (1%)

generate_report(output_path, format='html', template='default', user=None, memo=None, **kwargs)[源代码]

Generate backtest report.

参数:
  • 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

返回:

Output file path

返回类型:

str

抛出:

RuntimeError -- If strategy has not been run yet

示例

cerebro = bt.Cerebro() cerebro.addstrategy(MyStrategy) cerebro.adddata(data) cerebro.run() cerebro.generate_report('report.html')