This class is the cornerstone of backtrader because it serves as a central point for:
這個類是backteader平台的基石,因為它服務與以下幾點
-
Gathering all inputs (Data Feeds), actors (Stratgegies), spectators (Observers), critics (Analyzers) and documenters (Writers) ensuring the show still goes on at any moment.
- 收集所有的inputs (Data Feeds), actors (Stratgegies), spectators (Observers), critics (Analyzers) and documenters (Writers)確保節點在任何時刻都能繼續運行
-
Execute the backtesting/or live data feeding/trading
- 執行回測,或實時數據交易
-
Returning the results
- 返回結果
-
Giving access to the plotting facilities
- 提供進入繪圖設施的通道
Gathering input
采集輸入
-
Start by creating a
cerebro: - 開始創建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), wheredatais 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 feedswhich are already an instance of a class,cerebrotakes directly theStrategyclass 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
MyStrategy10 times withmyparam1taking values from 10 to 19 (remember ranges in Python are half-open and20will 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(oraddobservermulti)
-
-
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_storemethod. There are three (3) ways to work with these notifications - 如果數據傳輸或經紀人發送了通知(或者提供者創建了它們),它們能通過
Cerebro.notify_store的方法接收到信息。有三種方法處理這些通知 -
- Add a callback to a
cerebroinstance via theaddnotifycallback(callback)call. The callback has to support this signature: - 通過addnotifycallback(
callback)調用cerebro實例添加回調。回調必須支持這個簽名:
callback(msg, *args, **kwargs)The actual
msg,*argsand**kwargsreceived 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. - Add a callback to a
- 實際接收的msg、*arg和**kwarg是實現定義的(完全依賴與data/broker/store)但一般來說,應該期望它們可打印輸出,便於接收和試驗。
-
- Override the
notify_storemethod in theStrategysubclass which is added to acerebroinstance. - 重寫添加到cerebro實例的Strategy子類中的notify_store方法。(這個我已經使用過了)
The signature:
notify_store(self, msg, *args, **kwargs) - Override the
- 簽名:
notify_store(self, msg, *args, **kwargs)- Subclass
Cerebroand overridenotify_store(same signature as in theStrategy) Cerebro的子類,重寫notify_store(與Strategy簽名一樣)
This should be the least preferred method
- Subclass
- 這應該不是很好的方法
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
cashandvalue(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=FalseReturning the results
- 返回結果
-
cerebroreturns 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
resultreturned byrunwill vary depending on whether optimization is used (a strategy was added withoptstrategy): - 運行返回結果的格式將根據是否使用優化(optstrategy添加了一個策略)而有所不同:
-
-
All strategies added with
addstrategy - 所有策略通過
addstrategy添加resultwill be alistof the instances run during the backtesting - 結果將是在回測期間運行的實例列表
-
1 or more strategies were added with
optstrategy - 一個或多個實例通過optstrategy添加
resultwill be alistoflist. 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
optreturntoFalse -
- 如果希望返回完成的策略集,則將參數optreturn設置為False
Giving access to the plotting facilities
- 提供進入繪圖設施的通道
-
As an extra an if
matplotlibis 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:
- 事件流程簡述
-
-
Deliver any store notifications
- 發送任何店鋪通知
-
Ask data feeds to deliver the next set of ticks/bars
- 要求數據傳輸提供下一個ticks/bars
-
Versionchanged: Changed in version 1.9.0.99: New Behavior
- 版本更改:升級版本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)
- 新周期未交易的Feeds仍提供舊數據點,而有新數據的數據源提供這個數據點(以及指標的計算)
-
Old Behavior (retained when using
oldsync=Truewith Cerebro) - 舊操作(對Cerebro使用oldsync=True時保留)
The 1st data inserted into the system is the
datamasterand the system will wait for it to deliver a tick -
插入到系統的第一個數據是數據管理員,系統將等待它發送一個tick
The other data feeds are, more or less, slaves to the
datamasterand: - 其他的數據饋入,或多或少,來至數據管理員和:
-
* 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
- 該邏輯能夠方便的同步多個數據傳輸,並且數據傳輸在不同的時間框架
-
-
Notify the strategy about queued broker notifications of orders, trades and cash/value
- 通知策略中排隊的經紀人,通知有關訂單,交易和現金。
-
Tell the broker to accept queued orders and execute the pending orders with the new data
- 告訴經紀人接收排隊的訂單,並使用新數據執行掛起的訂單
-
Call the strategies’
nextmethod to let the strategy evaluate the new data (and maybe issue orders which are queued in the broker) - 告訴策略的next方法,讓策略評估新的數據(可能還會在經紀人的隊列中發布訂單)
-
Depending on the stage it may be
prenextornextstartbefore the minimum period requirements of the strategy/indicators are met - 根據所處的階段,可能在
prenext或nextstart之前達到戰略/指標的最低期限要求 -
Internally the strategies will also kick the
observers,indicators,analyzersand other active elements - 在內部,這些策略還將剔除觀察員、指標、分析者和其他積極因素
-
Tell any
writersto write the data to its target - 告訴任何寫入器將數據寫入其目標
Important to take into account:
-
- 必須考慮的重要因素:
-
Note
In step
1above 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
4cannot be executed with the data from step1. - 因此,不能用步驟1的數據執行步驟4中策略發出的訂單
-
This means that orders will be executed with the concept of
x + 1. Wherexis the bar moment at which the order was executed andx + 1the 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 feedspassed to cerebro for the Strategies - 是否預加載傳遞給cerebro的用於策略的不同數據
-
runonce(default:True)
Run
Indicatorsin 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
islivemethod but the end user still want to run inlivemode, this parameter can be set to true - 如果沒有數據報告自身的live狀態(通過數據的islive方法,但最終用戶仍然希望在live模式下運行,則可以將此參數設置為true
-
This will simultaneously deactivate
preloadandrunonce. It will have no effect on memory saving schemes. - 這將同時禁用預加載和運行一次。它對內存節省方案沒有影響。
-
Run
Indicatorsin 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
stdstatsisTrueand observers are getting automatically added, this switch controls the main behavior of theBuySellobserver - 如果
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
stdstatsisTrueand observers are getting automatically added, this switch controls the main behavior of theTradesobserver -
- 如果
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
Truethe 2ndTrueLow(self.data)insideTrueRangematches the signature of the one in thebpcalculation. 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
Truea 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 methodset_tradehistory - 如果設置為True,它將在所有的策略的每個交易中激活更新事件日志。這也可以通過策略方法set_tradehistory在每個策略的基礎上完成
optdatas(default:True)
If
Trueand optimizing (and the system canpreloadand userunonce, 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 in83seconds to66 - 測試顯示了從83秒縮短到66秒,有大約20%的加速
optreturn(default:True)
If
Truethe optimization results will not be fullStrategyobjects (and all datas, indicators, observers …) but and object with the following attributes (same as inStrategy): - 如果為真,優化結果將不是完整的策略對象(以及所有數據、指標、觀察者……),而是具有以下屬性的對象(與策略相同):
-
* `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 withoptdatasthe total gain increases to a total speed-up of32%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
tzcan 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_openmethod of strategies will be called. This happens beforenextand 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 theopenprice 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 withBackBroker(coo=True)(where coo stands for cheat-on-open) or set thebroker_cooparameter toTrue. 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_coomethod of the broker withTrueto activatecheat_on_openexecution. Will only do it ifcheat_on_openis alsoTrue這將自動調用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
Truenotifications will be delivered as soon as possible (seeqcheckin live feeds)Broker通知將在下一個價格交割之前送達。對於回溯測試,這沒有任何影響,但是對於實時代理來說,通知可以在bar交付之前很久發生。當設置為True時,將盡快發送通知(請參閱livefeeds中的qcheck)
Set to
Falsefor compatibility. May be changed toTrue為兼容性設置為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,*argsand**kwargsreceived 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
Cerebrosubclasses這個方法可以被
Cerebro的子類覆蓋修改The actual
msg,*argsand**kwargsreceived 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
*argsand**kwargsreceived 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
Cerebrosubclasses該方法能在Cerebro的子類被覆蓋重寫
The actual
*argsand**kwargsreceived 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 Feedinstance to the mix.添加數據源的實例
If
nameis not None it will be put intodata._namewhich is meant for decoration/plotting purposes.如果name不是None,它將被放入data._ name,用於裝飾/打印目的。
resampledata(dataname, name=None, **kwargs)
Adds a
Data Feedto be resample by the system添加系統需要的重采集數據源
If
nameis not None it will be put intodata._namewhich is meant for decoration/plotting purposes.如果name不是None,它將被放入data._ name,用於裝飾/打印目的。
Any other kwargs like
timeframe,compression,todatewhich are supported by the resample filter will be passed transparently另外的一些重采樣支持的關鍵字參數,比如
timeframe,compression,todate,都能被傳遞。replaydata(dataname, name=None, **kwargs)
Adds a
Data Feedto be replayed by the system添加系統需要的回放數據源
If
nameis not None it will be put intodata._namewhich is meant for decoration/plotting purposes.如果name不是None,它將被放入data._ name,用於裝飾/打印目的。
Any other kwargs like
timeframe,compression,todatewhich are supported by the replay filter will be passed transparently另外的一些回放支持的關鍵字參數,比如
timeframe,compression,todate,都能被傳遞chaindata(*args, **kwargs)
Chains several data feeds into one
將多個數據源鏈接到一個If
nameis passed as named argument and is not None it will be put intodata._namewhich 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
nameis passed as named argument and is not None it will be put intodata._namewhich 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
Strategyclass to the mix for a single pass run. Instantiation will happen duringruntime.將一個策略類添加到單次傳遞的組合中。實例化將在運行時發生。
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
Strategyclass to the mix for optimization. Instantiation will happen duringruntime.將策略類添加到組合中以進行優化。實例化將在運行時發生。
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 tooptstrategylooks 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
periodvalues 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
periodis still passed as an iterable … of just 1 element注意,period仍然作為一個iterable…傳遞,只有1個元素
backtraderwill 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
Indicatorclass to the mix. Instantiation will be done atruntime in the passed strategies添加指標類類。實例化將在運行時在傳遞的策略中完成
addobserver(obscls, *args, **kwargs)
Adds an
Observerclass to the mix. Instantiation will be done atruntime將觀察者類添加到混合中。實例化將在運行時完成
addobservermulti(obscls, *args, **kwargs)
Adds an
Observerclass to the mix. Instantiation will be done atruntime將觀察者類添加到混合中。實例化將在運行時完成
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
Analyzerclass to the mix. Instantiation will be done atruntime添加一個分析器的類。在cerebro運行期間實例化
addwriter(wrtcls, *args, **kwargs)
Adds an
Writerclass to the mix. Instantiation will be done atruntime in cerebro將Writer類添加到混合中。實例化將在運行時在大腦中完成
run(**kwargs)
The core method to perform backtesting. Any
kwargspassed to it will affect the value of the standard parametersCerebrowas instantiated with.執行回溯測試的核心方法。傳遞給它的任何kwargs都會影響實例化的標准參數Cerebro的值。
If
cerebrohas 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
brokerinstance for this strategy, replacing the one inherited from cerebro.為該策略設置一個特定的
broker實例,替換從大腦繼承的broker。getbroker()
Returns the broker instance.
返回代理實例。
This is also available as a
propertyby the namebroker同樣也可以通過
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
plotteris None a defaultPlotinstance is created andkwargsare passed to it during instantiation.如果plotter為None,則創建一個默認的打印實例,並在實例化期間向其傳遞kwargs。
numfigssplit the plot in the indicated number of charts reducing chart density if wishednumfigs將圖分成指定數量的圖表,如果需要,可減少圖表密度
iplot: ifTrueand running in anotebookthe charts will be displayed inlineiplot:如果為True並且在筆記本中運行,則圖表將以內聯方式顯示
use: set it to the name of the desired matplotlib backend. It will take precedence overiplotuse:將其設置為所需的matplotlib后端名稱。它將優先於iplot
start: An index to the datetime line array of the strategy or adatetime.date,datetime.datetimeinstance indicating the start of the plotstart:設置繪圖的開始時間
end: An index to the datetime line array of the strategy or adatetime.date,datetime.datetimeinstance indicating the end of the plotend:設置繪圖的結束時間
width: in inches of the saved figure寬度:以保存圖形的英寸為單位
height: in inches of the saved figure高度:以保存圖形的英寸為單位
dpi: quality in dots per inches of the saved figuredpi:保存圖形的每英寸點數質量
tight: only save actual content and not the frame of the figuretight:只保存實際內容,不保存圖形的框架
addsizer(sizercls, *args, **kwargs)
Adds a
Sizerclass (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
Sizerclass by idx. This idx is a reference compatible to the one returned byaddstrategy. Only the strategy referenced byidxwill 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
concurrentvalue is set to True, concurrent orders will be allowed如果將信號添加到系統中,並且將並發值設置為True,則允許並發訂單
signal_accumulate(onoff)
If signals are added to the system and the
accumulatevalue 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
向系統添加一個全球交易日歷。單個數據提要可能具有覆蓋全局提要的單獨日歷
calcan be an instance ofTradingCalendara string or an instance ofpandas_market_calendars. A string will be will be instantiated as aPandasMarketCalendar(which needs the modulepandas_market_calendarinstalled 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
tzcan be為策略添加全局時區。tz可以是
-
None: in this case the datetime displayed by strategies will be in UTC, which has been always the standard behavior - None:在這種情況下,策略顯示的日期時間將以UTC表示,這一直是標准行為
-
pytzinstance. It will be used as such to convert UTC times to the chosen timezone - pytz實例。它將用於將UTC時間轉換為所選時區
-
string. Instantiating apytzinstance will be attempted. - 字符串。將嘗試實例化pytz實例。
-
integer. Use, for the strategy, the same timezone as the correspondingdatain theself.datasiterable (0would use the timezone fromdata0) - 整數。對於策略,請使用相應數據相同的時區
self.datasiterable(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.timeinstance (see belowtzdata) -
bt.timer.SESSION_STARTto reference a session start -
bt.timer.SESSION_ENDto reference a session end -
offsetwhich must be adatetime.timedeltainstance
Used to offset the value
when. It has a meaningful use in combination withSESSION_STARTandSESSION_END, to indicated things like a timer being called15 minutesafter the session start.-
repeatwhich must be adatetime.timedeltainstanceIndicates if after a 1st call, further calls will be scheduled within the same session at the scheduled
repeatdeltaOnce 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 invokedIf not specified, the timer will be active on all days
-
weekcarry(default:False). IfTrueand 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 monthIf 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 returnsTrueif the date is allowed for timers or else returnsFalse -
tzdatawhich can be eitherNone(default), apytzinstance or adata feedinstance.None:whenis interpreted at face value (which translates to handling it as if it where UTC even if it’s not)pytzinstance:whenwill be interpreted as being specified in the local time specified by the timezone instance.data feedinstance:whenwill be interpreted as being specified in the local time specified by thetzparameter of the data feed instance.Note
If
whenis eitherSESSION_STARTorSESSION_ENDandtzdataisNone, the 1st data feed in the system (akaself.data0) will be used as the reference to find out the session times. -
strats(default:False) call also thenotify_timerof strategies -
cheat(defaultFalse) ifTruethe 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 tonotify_timer -
**kwargs: any extra kwargs will be passed tonotify_timer
-
Return Value:
- The created timer
notify_timer(timer, when, *args, **kwargs)
Receives a timer notification where
timeris the timer which was returned byadd_timer, andwhenis the calling time.argsandkwargsare any additional arguments passed toadd_timer接收一個計時器通知,其中timer是由add_timer返回的計時器,when是調用時間。args和kwargs是傳遞給add_timer的任何附加參數
The actual
whentime 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:
-
datetimeis a pythondate/datetimeinstance or a string with format YYYY-MM-DD[THH:MM:SS[.us]] where the elements in brackets are optional -
sizeis an integer (positive to buy, negative to sell) -
priceis a float/integer -
dataif 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
Truethe 1st strategy inserted in the system will be notified of the artificial orders created following the information from each order inorders - 如果為真,系統中插入的第一個策略將被通知根據訂單中每個訂單的信息創建的人工訂單
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
