Trying to keep things simple here and coding the trading logic to run base on system time. I am having difficulty saving the open and closing futures as objects to use in trading logic. Code and backtests are below. Any suggestions?

Unable to connect backtest because it is erroring out. Here is the code

  1. import datetime
  2. class ScikitLearnLinearRegressionAlgorithm(QCAlgorithm):
  3. openPeriod = None
  4. closePeriod = None
  5. def Initialize(self):
  6. self.SetTimeZone("America/New_York")
  7. self.SetStartDate(2015, 1, 1)
  8. self.SetEndDate(2021, 12, 31)
  9. self.NQ = self.AddFuture(Futures.Indices.NASDAQ100EMini)
  10. self.NQ.SetFilter(lambda x: x.FrontMonth())
  11. self.Schedule.On(self.DateRules.EveryDay(), self.TimeRules.BeforeMarketClose(self.NQ, 0), self.ClosePositions)
  12. def OnData(self, data):
  13. now = datetime.datetime.now()
  14. if now.hour == 9 and now.minute == 30:
  15. self.closePeriod = self.Securities[self.NQ].Close
  16. if now.hour == 16 and now.minute == 00:
  17. self.openPeriod = self.Securities[self.NQ].Open
  18. if self.closePeriod is None or self.openPeriod is None:
  19. return
  20. change = (self.closePeriod - self.openPeriod) / self.openPeriod
  21. if now.hour == 9 and now.minute == 31 and self.change >= 0:
  22. self.SetHoldings(self.NQ, 1)
  23. elif now.hour == 9 and now.minute == 31 and self.change < 0:
  24. self.SetHoldings(self.NQ, -1)
  25. def ClosePositions(self):
  26. self.Liquidate()
  27. # for chain in data.FutureChains.Values:
  28. # contracts = chain.Contracts
  29. # for contract in contracts.Values:
  30. # history = self.History(contract.Symbol, 30, Resolution.Minute)
  31. # self.Log(history.to_string())
  32. # self.Quit()
  33. # return
+ Expand

Author

James Hawkins

January 2022