self.data.datetime.date() starting at the last date of my data
-
Hello,
I am having an issue where my strategy starts off at the very end of my data, but then goes back to normal after a while and starts from the beginning and goes to the end just fine. I put a print statement at the beginning of the "next" method of the strategy class that prints out self.data.datetime.date() and it prints out 2022-12-30 (which is the very last day of my data) a bunch of times. Then it proceeds to print dates from 1999-11-18 until 2022-12-30 as normal. Keep in mind that my data starts at 1998-01-03 ... NOT 1999-11-18.
Here is the code for the strategy script:
import backtrader as bt import backtrader.indicators as btind import pandas as pd class MovingAverageCrossover(bt.Strategy): params = ( ('ma_short_length', 50), ('ma_long_length', 200), ) def __init__(self): self.ma_short_dict = {} self.ma_long_dict = {} for data in self.datas: if self.has_sufficient_data(data): self.ma_short_dict[data] = btind.ExponentialMovingAverage(data.close, period=self.params.ma_short_length) self.ma_long_dict[data] = btind.ExponentialMovingAverage(data.close, period=self.params.ma_long_length) def prenext(self): self.next() def next(self): print(self.data.datetime.date()) for data in self.datas: if data in self.ma_short_dict and data in self.ma_long_dict: ma_short = self.ma_short_dict[data] ma_long = self.ma_long_dict[data] if ma_short[0] > ma_long[0] and ma_short[-1] <= ma_long[-1]: self.buy(data=data, size=1) elif ma_short[0] < ma_long[0] and ma_short[-1] >= ma_long[-1]: self.close(data=data, size=1) def has_sufficient_data(self, data): df = pd.read_csv(fr'C:\Users\Z\Desktop\Python\Backtest\Backtrader Stock Data\SP500\
Any ideas?
Thanks,
Zack -
@Z also just noticed that the very first file of my SP500 folder doesn't have data until 1999-11-18. Undoubtedly the issue has something to do with this. I will look again tomorrow, but if anybody has the solution in the meantime I would appreciate it!