I wrote a simple algorithm to buy and sell breakout of a 20 day rolling period of highs and lows during those 20 days. Currently I have two issues; first the prices for natural gas are incorrect. The first fill price is around 78$ when in fact the contract traded near 2$ during the start of the backtest. Second, the calculation and fills seem to be off as well. Using a twenty day period there is only 5 trades during the 5 years and I know that the price broke the levels I've set quite a bit more than that. I have attached my code hear and I appreciate all the support. Thank you kindly,
class FocusedRedGoshawk(QCAlgorithm):
def Initialize(self):
self.SetStartDate(2010, 1, 1)
self.SetEndDate(2015,1,1)
self.SetCash(100000)
self.naturalgas = self.AddFuture(Futures.Energies.NaturalGas, Resolution.Daily).Symbol
self.high = self.MAX(self.naturalgas, 20, Resolution.Daily, Field.High)
self.low = self.MIN(self.naturalgas, 20, Resolution.Daily, Field.Low)
self.SetWarmUp(timedelta(days=20))
self.SetBenchmark(self.naturalgas)
def OnData(self, data: Slice):
if not self.high.IsReady:
return
self.Debug(f"Symbol: {self.naturalgas} 20 Day High: {self.high.Current.Value} , Low: {self.low.Current.Value}")
if not self.Portfolio.Invested:
if self.Securities[self.naturalgas].Close > self.high.Current.Value:
self.MarketOrder(self.naturalgas, 1)
if self.Securities[self.naturalgas].Close < self.low.Current.Value:
self.MarketOrder(self.naturalgas,-1)
if self.Portfolio[self.naturalgas].IsLong:
if self.Securities[self.naturalgas].Close < self.low.Current.Value:
self.MarketOrder(self.naturalgas,-2)
if self.Portfolio[self.naturalgas].IsShort:
if self.Securities[self.naturalgas].Close > self.high.Current.Value:
self.MarketOrder(self.naturalgas, 2)