QuantConnect – Consolidators介紹

Consolidators(合併器)是回測引擎裡面提供用來將較高頻的資料結合為低頻的資料的工具物件。這在某些指標需要用短期信號結合進行長期分析很有用。Consolidators的使用方式為在Initialize()方法中構造並設置; 這樣可以確保它們僅初始化一次。 創建和註冊合併器有三個關鍵步驟:

  1. 建立consolidator物件
  2. 綁定事件處理程序(當新的bar進來的處理邏輯)
  3. 在訂閱處理中心中訂閱它(Register it with the subscription manager to start receiving data.)
以下是一個使用範例
[python]
from datetime import datetime, timedelta
class DataConsolidationAlgorithm(QCAlgorithm):

    def Initialize(self):
        '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''

        self.SetStartDate(2016,1,1)  #Set Start Date
        self.SetEndDate(datetime.now())   #Set End Date
        # Find more symbols here: http://quantconnect.com/data
        self.AddEquity("SPY", Resolution.Minute)

        # define our 30 minute trade bar consolidator. we can
        # access the 30 minute bar from the DataConsolidated events
        thirtyMinuteConsolidator = TradeBarConsolidator(timedelta(minutes=30))

        # attach our event handler. The event handler is a function that will
        # be called each time we produce a new consolidated piece of data.
        thirtyMinuteConsolidator.DataConsolidated += self.ThirtyMinuteBarHandler

        # this call adds our 30-minute consolidator to
        # the manager to receive updates from the engine
        self.SubscriptionManager.AddConsolidator("SPY", thirtyMinuteConsolidator)

    def ThirtyMinuteBarHandler(self, sender, bar):
        '''This is our event handler for our 30-minute trade bar defined above in Initialize(). So each time the consolidator produces a new 30-minute bar, this function will be called automatically. The sender parameter will be the instance of the IDataConsolidator that invoked the event '''
        self.Debug(str(self.Time) + " " + str(bar))
    def OnData(self, data):
        pass
[/python]

這邊第一步為建立Consolidator物件

[python]
thirtyMinuteConsolidator = TradeBarConsolidator(timedelta(minutes=30))
[/python]

這個物件會將我們接受的bar整合成30分鐘的bar
第二步為建立事件處理程序

[python]
thirtyMinuteConsolidator.DataConsolidated += self.ThirtyMinuteBarHandler
def ThirtyMinuteBarHandler(self, sender, bar):
        '''This is our event handler for our 30-minute trade bar defined above in Initialize(). So each time the consolidator produces a new 30-minute bar, this function will be called automatically. The sender parameter will be the instance of the IDataConsolidator that invoked the event '''
        self.Debug(str(self.Time) + " " + str(bar))
[/python]

這邊的sender為DataConsolidated的instance,bar為整合好的30分鐘bar,我們在這個函數就可以寫怎麼計算想要的指標

最後一步是告訴訂閱中心我們要訂閱這個consolidator

[python]
# this call adds our 30-minute consolidator to
        # the manager to receive updates from the engine
        self.SubscriptionManager.AddConsolidator("SPY", thirtyMinuteConsolidator)
[/python]

Share

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *