For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/

Filtering candles from multiple data feeds



  • I have a strategy with multiple data feeds. I would like to access only candles inside the strategy with datetimes existing in all data feeds.

    An example of Python implementation would be:

    def gen(datas):
    for dt in data[0].datetime:
    allTrue = True
    for data in datas:
    if not dt in data.datetime: allTrue = False
    if allTrue: yield dt

    Where to apply similar filter inside the backtrader code?



  • Check out Docs - Filters, maybe it will help or at least give a direction to search.



  • The problem with filters is that they can access only one data feed but for this purpose all data feeds are needed to be accessed.



  • I cannot edit my initial post so here I repost the generator code properly formatted:

    def gen(datas):
        for dt in data[0].datetime:
            allTrue = True
            for data in datas:
                if not dt in data.datetime: allTrue = False
            if allTrue: yield dt
    


  • I gained some new insight to this problem.

    Let's suppose I have two data feeds with same timeframe. First data starts earlier than the second one.

    When I plot candle datetimes in the next method of my strategy:

    class St(bt.Strategy):
        def next(self):
            print(bt.num2date(self.datas[0].datetime[0]),
                  bt.num2date(self.datas[1].datetime[0]))
    

    those two datetimes are equal which means there must be already some mechanism implemented.

    However, when I plot candle datetimes in the next method of my indicator:

    class ind(bt.Indicator):
        lines = ('values',)
        params = dict(period=None)
        def __init__(self):
            self.addminperiod(self.p.period)
        def next(self):
            print(bt.num2date(self.datas[0].datetime[0]),
                  bt.num2date(self.datas[1].datetime[0]))
    
    class St(bt.Strategy):
        def __init__(self):
            self.ind = ind(self.dnames['name1'],
                           self.dnames['name2'],
                           period=100)
    

    they are not equal.

    So my question is:

    How to pass candles to the indicator with same datetimes?



  • Strategy's next() is called when all data feeds and indicators within the strategy deliver the values. If you want to have the same behavior in the indicator, than on each next() call check if all data feeds delivered values. If no, then skip the next(), otherwise proceed with your logic.



  • @ab_trader that seems like a simple and elegant solution.

    Another solution is proposed here. It is more complex and error-prone. I built a custom class (called DataSynchronizer) that handles data feeds on the same principle (feel free to fork).


Log in to reply
 

});