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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM