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

     

    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.

    7. 通过查看下一个可用的数据源提供的日期时间来同步数据。
    8. 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)

    9. 新周期未交易的Feeds仍提供旧数据点,而有新数据的数据源提供这个数据点(以及指标的计算)
    10. Old Behavior (retained when using oldsync=True with Cerebro)

    11. 旧操作(对Cerebro使用oldsync=True时保留)

      The 1st data inserted into the system is the datamaster and the system will wait for it to deliver a tick

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

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

    13. 其他的数据馈入,或多或少,来至数据管理员和:

  •  * If the next tick to deliver is newer (datetime-wise) than the one
       delivered by the `datamaster` it will not be delivered
    *如果要交付的下一个tick(从日期上来说)比“数据管理员”交付的数据更新,它将不会被交付 * 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

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

    2. 通知策略中排队的经纪人,通知有关订单,交易和现金。
    3. Tell the broker to accept queued orders and execute the pending orders with the new data

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

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

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

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

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

    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的bar或在Cloe的bar一条线上,难以识别的情节。
    • 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.
    所有的“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.

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

    The tests show an approximate 20% speed-up moving from a sample execution in 83 seconds to 66

  • 测试显示了从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 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的订单执行,还是需要进行调用的cerebro.broker.set_coo(True),或者broker实例里面添加参数BackBroker(coo=True),或者设置broker_coo参数为True。Cerebro会自动完成,除非下面禁用。

    • 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

    这将自动调用broker的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)

    Broker通知将在下一个价格交割之前送达。对于回溯测试,这没有任何影响,但是对于实时代理来说,通知可以在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

    添加一个回调以获取将由notify_store方法处理的消息

    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.

    接收到的实际消息、*arg和**kwarg是实现定义的(完全取决于数据/代理/存储),但一般来说,人们应该希望它们是可打印的,以便接收和实验。

    notify_store(msg, *args, **kwargs)

    Receive store notifications in cerebro

    在cerebro接收存储的消息

    This method can be overridden in Cerebro subclasses

    这个方法可以被Cerebro的子类覆盖修改

    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.

    接收到的实际消息、*arg和**kwarg是实现定义的(完全取决于数据/代理/存储),但一般来说,人们应该希望它们是可打印的,以便接收和实验。

    adddatacb(callback)

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

    添加一个回调以获取将由notify_data方法处理的消息

    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.

     实际接收到的*arg和**kwarg是实现定义的(完全取决于数据/代理/存储),但一般情况下,应该希望它们是可打印的,以便接收和实验。

    notify_data(data, status, *args, **kwargs)

    Receive data notifications in cerebro

    在cerbro接收数据通知

    This method can be overridden in Cerebro subclasses

    该方法能在Cerebro的子类被覆盖重写

    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.

    实际接收到的*arg和**kwarg是实现定义的(完全取决于数据/代理/存储),但一般情况下,应该希望它们是可打印的,以便接收和实验。

    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不是None,它将被放入data._ name,用于装饰/打印目的。

    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.

    如果name不是None,它将被放入data._ name,用于装饰/打印目的。

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

    另外的一些重采样支持的关键字参数,比如timeframe, compression, todate,都能被传递。

    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.

    如果name不是None,它将被放入data._ name,用于装饰/打印目的。

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

    另外的一些回放支持的关键字参数,比如timeframe, compression, todate,都能被传递

    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.

    如果name作为命名参数传递,而不是None,它将被放入data._name,这是为了装饰/打印的目的。

    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.

    如果name作为命名参数传递,而不是None,它将被放入data._name,这是为了装饰/打印的目的。

    If None, then the name of the 1st data will be used

    如果没有,则使用第一个数据的名称

    Any other kwargs will be passed to the RollOver class

    任何其他的关键字参数都会传递给RollOver类

    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.

    arg和kwarg将在实例化期间传递给策略

    Returns the index with which addition of other objects (like sizers) can be referenced

    返回可以引用添加的其他对象(如sizer)的索引,第一次添加是1,第二次添加是2。

    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.

    arg和kwargs必须是可迭代的,它们保存要检查的值。

    Example: if a Strategy accepts a parameter period, for optimization purposes the call to optstrategy looks like:

    示例:如果策略接受参数周期,则为了优化目的,调用optstrategy如下所示:

    • cerebro.optstrategy(MyStrategy, period=(15, 25))

    This will execute an optimization for values 15 and 25. Whereas

    这将对值15和25执行优化。鉴于

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

    将使用值15->25执行MyStrategy(不包括25,因为在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

    注意,period仍然作为一个iterable…传递,只有1个元素

    backtrader will anyhow try to identify situations like:

    不管怎样,backtrader都会尝试识别以下情况:

    • cerebro.optstrategy(MyStrategy, period=15)

    and will create an internal pseudo-iterable if possible

    如果可能的话,将创建一个内部伪iterable

    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

    一个反例是CashValue,他是观察整个系统的值。

    addanalyzer(ancls, *args, **kwargs)

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

    添加一个分析器的类。在cerebro运行期间实例化

    addwriter(wrtcls, *args, **kwargs)

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

    将Writer类添加到混合中。实例化将在运行时在大脑中完成

    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.

    执行回溯测试的核心方法。传递给它的任何kwargs都会影响实例化的标准参数Cerebro的值。

    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

    • 对于无优化:一个包含添加了addstrategy的策略类实例的列表
    • For Optimization: a list of lists which contain instances of the Strategy classes added with addstrategy

    • 对于优化:包含添加了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.

    为该策略设置一个特定的broker实例,替换从大脑继承的broker

    getbroker()

    Returns the broker instance.

    返回代理实例。

    This is also available as a property by the name broker

    同样也可以通过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

    在cerebro内部绘画策略

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

    如果plotter为None,则创建一个默认的打印实例,并在实例化期间向其传递kwargs。

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

    numfigs将图分成指定数量的图表,如果需要,可减少图表密度

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

    iplot:如果为True并且在笔记本中运行,则图表将以内联方式显示

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

    use:将其设置为所需的matplotlib后端名称。它将优先于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

    start:设置绘图的开始时间

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

    end:设置绘图的结束时间

    width: in inches of the saved figure

    宽度:以保存图形的英寸为单位

    height: in inches of the saved figure

    高度:以保存图形的英寸为单位

    dpi: quality in dots per inches of the saved figure

    dpi:保存图形的每英寸点数质量

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

    tight:只保存实际内容,不保存图形的框架

    addsizer(sizercls, *args, **kwargs)

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

    添加一个Sizer类(和args),它是添加到cerebro的任何策略的默认Sizer

    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

    通过idx添加一个Sizer类。这个idx是一个与addstrategy返回的引用兼容的引用。只有idx引用的策略才会收到这个大小

    针对不同的策略设置不同的Sizer

    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

    如果将信号添加到系统中,并且将并发值设置为True,则允许并发订单

    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

    如果信号被添加到系统中,并且累计值被设置为True,进入市场时已经在市场中,将被允许增加一个头寸

    signal_strategy(stratcls, *args, **kwargs)

    Adds a SignalStrategy subclass which can accept signals

    添加可以接受信号的SignalStrategy子类

    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.

    cal可以是TradingCalendar字符串的实例,也可以是pandas_market_calendar的实例。一个字符串将被实例化为一个pandasmarket_calendar(它需要在系统中安装pandas_market_calendar模块)。

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

    如果传递了TradingCalendarBase的子类(不是实例),那么它将被实例化

    addtz(tz)

    This can also be done with the parameter tz

    这也可以通过参数tz来实现

    Adds a global timezone for strategies. The argument tz can be

    为策略添加全局时区。tz可以是

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

    • None:在这种情况下,策略显示的日期时间将以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)

    • 整数。对于策略,请使用相应数据相同的时区self.datas iterable(0将使用数据0中的时区)

    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

    调度一个计时器来调用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

    接收一个计时器通知,其中timer是由add_timer返回的计时器,when是调用时间。args和kwargs是传递给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

posted @ 2020-08-09 00:15  就是想学习  阅读(1876)  评论(0编辑  收藏  举报