Backtrader中文笔记之Cerebro(大脑)。

This class is the cornerstone of backtrader because it serves as a central point for:

这个类是backteader平台的基石,因为它服务与以下几点

  1. Gathering all inputs (Data Feeds), actors (Stratgegies), spectators (Observers), critics (Analyzers) and documenters (Writers) ensuring the show still goes on at any moment.

  2. 收集所有的inputs (Data Feeds), actors (Stratgegies), spectators (Observers), critics (Analyzers) and documenters (Writers)确保节点在任何时刻都能继续运行
  3. Execute the backtesting/or live data feeding/trading

  4. 执行回测,或实时数据交易
  5. Returning the results

  6. 返回结果
  7. Giving access to the plotting facilities

  8. 提供进入绘图设施的通道

Gathering input

采集输入

  1. Start by creating a cerebro:

  2. 开始创建cerebro实例
cerebro = bt.Cerebro(**kwargs)

 Some **kwargs to control execution are supported, see the reference (the same arguments can be applied later to the run method)

支持一些**kwarg来控制执行,请参阅参考(相同的参数稍后可以应用到run方法)

  • Add Data feeds

  • 添加数据传输

    The most usual pattern is cerebro.adddata(data), where data is a data feed already instantiated. Example:

  • 通常采用cerebro.adddata(data)的模板添加数据,当数据已经是数据传输的实例,比如
  • data = bt.BacktraderCSVData(dataname='mypath.days', timeframe=bt.TimeFrame.Days)
    cerebro.adddata(data)
    

    Resampling and Replaying a data is possible and follows the same pattern:

  • 重新采样和重放数据是可能的,并遵循相同的模式:
    data = bt.BacktraderCSVData(dataname='mypath.min', timeframe=bt.TimeFrame.Minutes)
    cerebro.resampledata(data, timeframe=bt.TimeFrame.Days)
    
  • 或者
    data = bt.BacktraderCSVData(dataname='mypath.min', timeframe=bt.TimeFrame.Minutes)
    cerebro.replaydatadata(data, timeframe=bt.TimeFrame.Days)
    

    The system can accept any number of data feeds, including mixing regular data with resampled and/or replayed data. Of course some of this combinationns will for sure make no sense and a restriction apply in order to be able to combine datas: time aligment. See the Data - Multiple Timeframes, Data Resampling - Resampling` and Data - Replay sections.

  • 系统可以接收任意数量的数据传输,包括常规数据与重采样数据和/或重放数据的混合。当然有些组合将是没有意义的,为了组合数据的应用添加了一个限制规定:时间校准。参考Data - Multiple Timeframes, Data Resampling - Resampling` and Data - Replay部分
  • Add Strategies

  • 添加策略

    Unlike the datas feeds which are already an instance of a class, cerebro takes directly the Strategy class and the arguments to pass to it. The rationale behind: in an optimization scenario the class will be instantiated several times and passed different arguments

  • 与已经实例的数据传输实例不同,cerebro直接受Strategy类和要传递的参数。背后的原理:在优化的场景中,类将被实例化多次并传入不同的参数

    Even if no optimization is run, the pattern still applies:

  • 即使不在优化状态运行,模式任然使用
  • cerebro.optstrategy(MyStrategy, myparam1=range(10, 20))

    Which will run MyStrategy 10 times with myparam1 taking values from 10 to 19 (remember ranges in Python are half-open and 20 will not be reached)

  • 它将运行MyStrategy 10次,myparam1取10到19的值(记住,Python中的范围是半开的「取头不取尾」,不会达到20)
  • Other elements

  • 其他元素
  • There are some other elements which can be added to enhance the backtesting experience. See the appropriate sections for it. The methods are:

  • 还可以添加其他一些元素来增强回溯测试的体验。请参阅相关章节。方法有:
    • addwriter

    • addanalyzer

    • addobserver (or addobservermulti)

  • Changing the broker

  • 改变经济人
  • Cerebro will use the default broker in backtrader, but this can be overriden:

  • Cerebro将使用默认的经济人在框架里,但它是能够被重写的
  • broker = MyBroker()
    cerebro.broker = broker  # property using getbroker/setbroker methods
    
  • Receive notifications

  • 接收通知
  • If data feeds and/or brokers send notifications (or a store provider which creates them) they will be received through the Cerebro.notify_store method. There are three (3) ways to work with these notifications

  • 如果数据传输或经纪人发送了通知(或者提供者创建了它们),它们能通过Cerebro.notify_store的方法接收到信息。有三种方法处理这些通知
    • Add a callback to a cerebro instance via the addnotifycallback(callback) call. The callback has to support this signature:
    • 通过addnotifycallback(callback)调用cerebro实例添加回调。回调必须支持这个签名:
    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.

  • 实际接收的msg、*arg和**kwarg是实现定义的(完全依赖与data/broker/store)但一般来说,应该期望它们可打印输出,便于接收和试验。
    • Override the notify_store method in the Strategy subclass which is added to a cerebro instance.
    • 重写添加到cerebro实例的Strategy子类中的notify_store方法。(这个我已经使用过了)

    The signature: notify_store(self, msg, *args, **kwargs)

  • 签名:notify_store(self, msg, *args, **kwargs)
    • Subclass Cerebro and override notify_store (same signature as in the Strategy)
    • Cerebro的子类,重写notify_store(与Strategy签名一样)

    This should be the least preferred method

  • 这应该不是很好的方法

    Execute the backtesting

  • 执行回测
  •  

    There is a single method to do it, but it supports several options (which can be also specified when instantiating) to decide how to run:

  • 有一个单一的方法来执行它,但它支持几个选项(也可以在实例化的时候指定)来决定如何运行
  • result = cerebro.run(**kwargs)
    

    See the reerence below to understand which arguments are available.

  • 下面,请各位理解哪些参数是可用的。
  • Standard Observers

  • 标准视角
  •  

    cerebro (unless otherwise specified) automatically instantiates three standard observers

  • cerebro(除非另外指定)将自动实例化三个标准观察者
    • A Broker observer which keeps track of cash and value (portfolio)

    • 一个经纪人的观察者,它将跟踪你的现金与价值(皮夹)
    • A Trades observer which should show how effective each trade has been

    • 一个交易观察者,应该显示每笔交易的有效性
    • A Buy/Sell observer which should document when operations are executed

    • 一个买卖观察者,应该记录执行操作

    Should a cleaner plotting be wished just disable them with stdstats=False

  • 如果希望禁用它们,只需要设置stdstats=Fals

    Returning the results

  • 返回结果
  •  

    cerebro returns the instances of the strategies it created during backtesting. This allows to analyze what they did, because all elements in the strategies are accessible:

  • cerebro在创建回测时会返回一个策略的实例。这样就允许分析他们做了什么,因为策略中的所有元素都是可被访问的:
  • result = cerebro.run(**kwargs)
    

    The format of result returned by run will vary depending on whether optimization is used (a strategy was added with optstrategy):

  • 运行返回结果的格式将根据是否使用优化(optstrategy添加了一个策略)而有所不同:
    • All strategies added with addstrategy

    • 所有策略通过addstrategy添加

      result will be a list of the instances run during the backtesting

    • 结果将是在回测期间运行的实例列表
    • 1 or more strategies were added with optstrategy

    • 一个或多个实例通过optstrategy添加

      result will be a list of list. Each internal list will contain the strategies after each optimization run

    • 结果将是列表套列表。每个内部列表将包含每个优化策略运行后的结果。

    Note

    The default behavior for optimization was changed to only return the analyzers present in the system, to make message passing across computer cores lighter.

    优化的默认行为将更改系统的只返回分析器,以使计算机内核之间的消息传递变得更轻。

    If the complete set of strategies is wished as return value, set the parameter optreturn to False

  • 如果希望返回完成的策略集,则将参数optreturn设置为False

    Giving access to the plotting facilities

  • 提供进入绘图设施的通道
  •  

    As an extra an if matplotlib is installed, the strategies can be plotted. With the usual pattern being:

  • 另外,如果安装了matplotlib,则可以绘制策略。通常的模式是:

    cerebro.plot()
    

    See below for the reference and the section Plotting

  • 参见下面的参考和绘图部分
  • Backtesting logic

  • 回测逻辑

    Brief outline of the flow of things:

  • 事件流程简述
    1. Deliver any store notifications

    2. 发送任何店铺通知
    3. Ask data feeds to deliver the next set of ticks/bars

    4. 要求数据传输提供下一个ticks/bars
    5. Versionchanged: Changed in version 1.9.0.99: New Behavior

    6. 版本更改:升级版本1.9.0.99:新功能

      Data Feeds are synchronized by peeking at the datetime which is going to be provided next by available data feeds. Feeds which have not traded in the new period still provide the old data points, whilst data feeds which have new data available offer this one (along with the calculation of indicators)

    7. 数据传输依靠读取时间参数保持同步,并将提供下一个数据传输。新时期未交易的Feeds仍提供旧数据点,有新数据的Feeds提供旧数据点(含指标计算)
    8. Old Behavior (retained when using oldsync=True with Cerebro)

    9. 旧操作(对Cerebro使用oldsync=True时保留)
    10. The 1st data inserted into the system is the datamaster and the system will wait for it to deliver a tick

    11. 插入到系统的第一个数据是数据管理员,系统将等待它发送一个滴答

      The other data feeds are, more or less, slaves to the datamaster and:

    12. 其他的数据馈入,或多或少,来至数据管理员和:
    1.  * If the next tick to deliver is newer (datetime-wise) than the one
         delivered by the `datamaster` it will not be delivered
      
       * May return without delivering a new tick for a number of reasons
      *如果要交付的下一个滴答(从日期上来说)比它更新
      由“数据管理员”交付的数据将不会被交付

      *可能返回没有交付一个新的tick有许多原因

      The logic was designed to easily synchronize multiple data feeds and data feeds with different timeframes

    2. 该逻辑能够方便的同步多个数据传输,并且数据传输在不同的时间框架
    3. Notify the strategy about queued broker notifications of orders, trades and cash/value

    4. 通知策略有关订单,交易和现金/价值经纪人的排队通知
    5. Tell the broker to accept queued orders and execute the pending orders with the new data

    6. 告诉代理接收排队的订单,并使用新数据执行挂起的订单
    7. Call the strategies’ next method to let the strategy evaluate the new data (and maybe issue orders which are queued in the broker)

    8. 告诉策略的next方法,让策略评估新的数据(可能还会在经纪人的队列中发布订单)
    9. Depending on the stage it may be prenext or nextstart before the minimum period requirements of the strategy/indicators are met

    10. 根据所处的阶段,可能在prenext或nextstart之前达到战略/指标的最低期限要求
    11. Internally the strategies will also kick the observers, indicators, analyzers and other active elements

    12. 在内部,这些战略还将剔除观察员、指标、分析者和其他积极因素
    13. Tell any writers to write the data to its target

    14. 告诉任何写入器将数据写入其目标

    Important to take into account:

  • 必须考虑的重要因素:
  • Note

    In step 1 above when the data feeds deliver the new set of bars, those bars are closed. This means the data has already happened.

    在上面的步骤1中,当数据传输交付新的一组柱时,这些柱被关闭。这意味着数据已经发生了。

    As such, orders issued by the strategy in step 4 cannot be executed with the data from step 1.

  • 因此,不能用步骤1的数据执行步骤4中策略发出的订单
  • This means that orders will be executed with the concept of x + 1. Where x is the bar moment at which the order was executed and x + 1 the next one, which is the earliest moment in time for a possible order execution

  • 这意味着订单将以x + 1的概念执行。x是执行订单时的bar,x + 1是下一个,那是可能执行订单的最早时间
  • Reference

  • 参考
  •  

    class backtrader.Cerebro()

    Params:

    • preload (default: True)

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

  • 是否预加载传递给cerebro的用于策略的不同数据
    • 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

  • 以向量化模式运行指标以加速整个系统。策略和观察者将始终以事件为基础运行
    • live (default: False)

    If no data has reported itself as live (via the data’s islive method but the end user still want to run in live mode, this parameter can be set to true

  • 如果没有数据报告自身的live状态(通过数据的islive方法,但最终用户仍然希望在live模式下运行,则可以将此参数设置为true
  • This will simultaneously deactivate preload and runonce. It will have no effect on memory saving schemes.

  • 这将同时禁用预加载和运行一次。它对内存节省方案没有影响。
  • Run Indicators in vectorized mode to speed up the entire system. Strategies and Observers will always be run on an event based basis

  • 以向量化模式运行指示符以加速整个系统。策略和观察者将始终以事件为基础运行
    • maxcpus (default: None -> all available cores)

      How many cores to use simultaneously for optimization

    • 有多少个核心在优化的时候运行,默认有多少运行多少
    • stdstats (default: True)

    If True default Observers will be added: Broker (Cash and Value), Trades and BuySell

  • 如果是真的,将添加默认观察员:Broker(现金和价值),Trades和BuySell
    • oldbuysell (default: False)

    If stdstats is True and observers are getting automatically added, this switch controls the main behavior of the BuySell observer

  • 如果stdstats是真并且观察者自动被添加,这个开关能够控制买卖观察者的主要行为
    • 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

    • False:使用现代行为,即买入/卖出信号分别标注在低/高价格下方/上方,以避免弄乱绘图
    • 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, difficulting the recognition of the plot.

    • 使用不推荐的行为,在这种行为中,买入/卖出信号被标绘在给定时间段内订单执行的平均价格。当然,这将是在一个OHLC酒吧或在Cloe酒吧的一条线上,难以识别的情节。
    • oldtrades (default: False)

    If stdstats is True and observers are getting automatically added, this switch controls the main behavior of the Trades observer

  • 如果stdstats是真并且观察者自动被添加,这个开关能够控制交易观察者的主要行为
    • False: use the modern behavior in which trades for all datas are plotted with different markers

    • False:使用现代行为,其中所有数据的交易都用不同的标记标记
    • True: use the old Trades observer which plots the trades with the same markers, differentiating only if they are positive or 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.
    `True` or `1`:所有的“lines”对象都将内存使用量减少到
    自动计算的最小周期。 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 如果一个简单的移动平均线的周期是30,其底层数据将一直需要30个bars缓存来运行,以允许简单移动平均线的计算 * This setting will deactivate `preload` and `runonce` 此设置将禁用“preload”和“runonce” * Using this setting also deactivates **plotting** 此设置也禁用'plotting' * `-1`: datafreeds 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 比如'RSI'是一个内部使用的指标,'UpDay'用于计算。它的子指标将不会将所有数据保存在内存中 * This allows to keep `plotting` and `preloading` active. 这允许一直激活`plotting` and `preloading` * `runonce` will be deactivated `runonce`被禁止 * `-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 比如'RSI'是一个内部使用的指标,'UpDay'用于计算。它的子指标将不会将所有数据保存在内存中 If in the `__init__` something like `a = self.data.close - self.data.high` is defined, then `a` will not keep all data in memory 比如在`__init__`有初始化的数据像这样`a = self.data.close - self.data.high`定义,然后a的所有数据也将不会
    全部保存在内存 * This allows to keep `plotting` and `preloading` active. 这允许一直激活`plotting` and `preloading` * `runonce` will be deactivate
    `runonce`被禁止
    • objcache (default: False)

    Experimental option to implement a cache of lines objects and reduce the amount of them. Example from UltimateOscillator:

  • 实验选项实现一个高速缓存的lines对象和减少他们的数量。从UltimateOscillator示例:
  • bp = self.data.close - TrueLow(self.data)
    tr = TrueRange(self.data)  # -> creates another TrueLow(self.data)
    

    If this is True the 2nd TrueLow(self.data) inside TrueRange matches the signature of the one in the bp calculation. It will be reused.

  • 如果条件为真:TrueRange内的第二个TrueLow(self.data)将匹配第一个bp计算中的那个,它会被重复使用
  • Corner cases may happen in which this drives a line object off its minimum period and breaks things and it is therefore disabled.

  • 在极端情况下,可能会发生这样的情况:这会使一个line对象脱离其最小周期并破坏一些东西,因此它被禁用。
    • 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)

  • 如果设置为真,将创建一个默认的写入文件,并打印到标准输出。它将被添加到策略中(以及用户代码添加的其他写入器)
    • tradehistory (default: False)

    If set to True, it will activate update event logging in each trade for all strategies. This can also be accomplished on a per strategy basis with the strategy method set_tradehistory

  • 如果设置为True,它将在所有的策略的每个交易中激活更新事件日志。这也可以通过策略方法set_tradehistory在每个策略的基础上完成
    • 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

  • 如果为真, 优化(系统可以预加载和使用runonce,数据预加载将在主进程中只做一次,以节省时间和资源。

    测试显示了从83秒缩短到66秒,有大约20%的加速
    • optreturn (default: True)

    If True the optimization results will not be full Strategy objects (and all datas, indicators, observers …) but and object with the following attributes (same as in Strategy):

  • 如果为真,优化结果将不是完整的策略对象(以及所有数据、指标、观察者……),而是具有以下属性的对象(与策略相同):
  • * `params` (or `p`) the strategy had for the execution
    
    * `analyzers` the strategy has executed
    

    In most occassions, only the analyzers and with which params are the things needed to evaluate a 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.

  • 测试显示执行时间提高了13% - 15%。与optdatas结合,在一次优化运行中,总增益增加到32%的总加速。
    • 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.

  • 从版本1.9.0.99开始,多个不同长度的数据(相同或不同的时间框架)的同步被更改为允许。
  • If the old behavior with data0 as the master of the system is wished, set this parameter to true

  • 如果希望使用data0作为系统的主人的旧操作,则将该参数设置为true
    • 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 been always the standard behavior
    在这种情况下,策略所显示的日期时间将使用UTC,这一直是标准行为 * `pytz` instance. It will be used as such to convert UTC times to the chosen timezone pytz实例,它将用于将UTC时间转换为所选时区 * `string`. Instantiating a `pytz` instance will be attempted. 字符串 实例化一个`pytz`实例将尝试。 * `integer`. Use, for the strategy, the same timezone as the corresponding `data` in the `self.datas` iterable (`0` would use the timezone from `data0`)
    整数 对于策略,使用对应相同的时区。(' 0 '将使用' data0 '的时区)
    • 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 orde which takes into account the indicators of the previous day but uses the open price for stake calculations

    策略的next_open方法被调用。这发生在next之前,在经纪人评估订单之前。这些指标尚未重新计算。

    这允许发布一个订单,该订单考虑了前一天的指标,但使用公开价格计算股份

    For cheat_on_open order execution, it is also necessary to make the call

    对于cheat_on_open的订单执行,还是需要进行调用的

    cerebro.broker.set_coo(True) or instantite 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.

    这些办法可以将cheat_on_open设置为True,第一实例方法设置cerebro.broker.set_coo(True),第二类里面添加参数BackBroker(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

    这将自动调用代理的set_coo方法(True)来激活cheat_on_open执行。只有在cheat_on_open也为真时才会这样做

    • 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)

    经纪人通知将在下一个价格交割之前送达。对于回溯测试,这没有任何影响,但是对于实时代理来说,通知可以在bar交付之前很久发生。当设置为True时,将尽快发送通知(请参阅livefeeds中的qcheck)

    Set to False for compatibility. May be changed to True

    为兼容性设置为False。可以将其设置为True

    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.

    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.

    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

    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

    chaindata(*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 1st 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 1st data will be used

    Any other kwargs will be passed to the RollOver class

    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

    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 which 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 1 element

    backtrader will anyhow try to identify situations like:

    • cerebro.optstrategy(MyStrategy, period=15)

    and will create an internal pseudo-iterable if possible

    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)

    addindicator(indcls, *args, **kwargs)

    Adds an Indicator class to the mix. Instantiation will be done at run time in the passed strategies

    addobserver(obscls, *args, **kwargs)

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

    addobservermulti(obscls, *args, **kwargs)

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

    It will be added once per “data” in the system. A use case is a buy/sell observer which observes individual datas.

    A counter-example is the CashValue, which observes system-wide values

    addanalyzer(ancls, *args, **kwargs)

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

    addwriter(wrtcls, *args, **kwargs)

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

    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 not datas the method will immediately bail out.

    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

    runstop()

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

    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

    plot(plotter=None, numfigs=1, iplot=True, start=None, end=None, width=16, height=9, dpi=300, tight=True, use=None, **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

    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

    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

    add_signal(sigtype, sigcls, *sigargs, **sigkwargs)

    Adds a signal to the system which will be later added to a SignalStrategy

    signal_concurrent(onoff)

    If signals are added to the system and the concurrent value is set to True, concurrent orders will be allowed

    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

    signal_strategy(stratcls, *args, **kwargs)

    Adds a SignalStrategy subclass which can accept signals

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

    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 been always 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)

    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

    • Parameters

      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 indicated things like a timer being called 15 minutes after the session start.

      • repeat which must be a datetime.timedelta instance

        Indicates if after a 1st 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 where 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 1st 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

    notify_timer(timer, when, *args, **kwargs)

    Receives a timer notification where timer is the timer which 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 be able to call the timer before. This value is the timer value and no the system time.

    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 an iterable (with length) with the following sub-elements (2 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 1st 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

原文地址:https://www.cnblogs.com/sidianok/p/13461185.html