How to run the strategy when 2 data feeds have no-overlapping fromdate-todate periods?
-
Hi community,
I'm fairly new to Backtrader. My question is probably simple: Let's say I have 2 stocks: OLD and NEW. The OLD has feed data from 01/01/1996 to 12/31/1996. The NEW has feed data from 01/01/2000 to 12/31/2000. I'd like to run the strategy when either data is available. It seems like the framework will wait until it sees NEW's first data before it begins executing the next() function
Here is sample code:
class TestStrategy(bt.Strategy): # omit unnecessary code... def next(self): print(self.datetime.date()) for data in self.datas: print("Stock: {}, close: {}".format(data._name, data.close[0])) if __name__ == '__main__': cerebro = bt.Cerebro() cerebro.addstrategy(TestStrategy) newData = bt.feeds.YahooFinanceCSVData( dataname = "new-2000.txt", fromdate = datetime.datetime(1990, 1, 1), todate = datetime.datetime(2000, 12, 31), reverse = False ) oldData = bt.feeds.YahooFinanceCSVData( dataname = "old-1996.txt", fromdate = datetime.datetime(1990, 1, 1), todate = datetime.datetime(2000, 12, 31), reverse = False ) cerebro.adddata(newData, name = 'new') cerebro.adddata(oldData, name = 'old') cerebro.run()
When I run it, the next() function will begin printing after 01/01/2000 and the price of OLD is set to the last OLD's price in the year 1996:
2000-01-04 Stock: new, close: 23.95 Stock: old, close: 4.13 2000-01-05 Stock: new, close: 22.68 Stock: old, close: 4.13 2000-01-06 Stock: new, close: 21.35 Stock: old, close: 4.13 2000-01-07 Stock: new, close: 22.99 Stock: old, close: 4.13 2000-01-10 Stock: new, close: 25.74 Stock: old, close: 4.13 2000-01-11 Stock: new, close: 24.99 Stock: old, close: 4.13 2000-01-12 Stock: new, close: 23.49 Stock: old, close: 4.13 2000-01-13 Stock: new, close: 23.36 Stock: old, close: 4.13 2000-01-14 Stock: new, close: 23.75 Stock: old, close: 4.13 2000-01-18 Stock: new, close: 24.74 Stock: old, close: 4.13 ...
My goal is to backtest a basket of stocks that span several decades and obviously all of them don't share the exact same trading period.
-
@vna01 use
prenext()
as well to get data from early periods.