Apologies in advance if this is covered elsewhere. I have looked but haven't been able to find a satisfying answer.
To keep things as simple as possible, I have a test strategy that merely prints out the date and name of each instrument and the length of the corresponding data line for each period (days in this case). Using this post as a starting point: https://www.backtrader.com/blog/2019-05-20-momentum-strategy/momentum-strategy/
class TestStrategy(bt.Strategy):
def __init__(self):
# Keep a reference to the "close" line in the data[0] dataseries
# self.dataclose = self.datas[0].close
self.d_with_len = []
def prenext(self):
self.data_list = [d for d in self.datas if len(d)]
self.next()
def nextstart(self):
# This is called exactly ONCE, when next is 1st called and defaults to
# call `next`
self.data_list = self.datas # all data sets fulfill the guarantees now
def next(self):
# Evetually do something cool. But for now show us what you've got.
for d in self.data_list:
print('%s %s %d' % (d.datetime.date(0), d._name, len(d)))
On the assumption that we are trying to model real market conditions as a closely as possible; it seems fair to assume that if an instrument isn't being traded, it shouldn't be visible to us. At the same time we do want to see data for instruments that are being traded.
For test purposes here are two small, overlapping samples:
Given this data and the assumption above, the expect output would be this:
Starting Portfolio Value: 100000.00
2017-03-31 LLOY 1
2017-04-03 LLOY 2
2017-04-04 TSCO 1
2017-04-04 LLOY 3
2017-04-05 TSCO 2
2017-04-05 LLOY 4
2017-04-06 TSCO 3
2017-04-06 LLOY 5
2017-04-07 TSCO 4
2017-04-10 TSCO 5
Final Portfolio Value: 100000.00
But what is actually output is this:
2017-03-31 LLOY 1
2017-04-03 LLOY 2
2017-04-05 TSCO 2
2017-04-05 LLOY 4
2017-04-06 TSCO 3
2017-04-06 LLOY 5
2017-04-07 TSCO 4
2017-04-06 LLOY 5
2017-04-10 TSCO 5
2017-04-06 LLOY 5
It seems to work as expected for the first section. But at the tail the LLOY data is still being displayed. Even after the feed is exhausted.
How is possible to prevent this occurring? And as a wider question is there an established pattern for working with multiple instruments?
Thanks