Stack Trace:
'DateRules' object has no attribute 'Everyday'
  at TradeOptions
    self.Schedule.On(self.DateRules.Everyday(), self.TimeRules.At(15, 55), lambda: self.Liquidate())
                     ^^^^^^^^^^^^^^^^^^^^^^^
 in main.py: line 66

 

Sorry, but i don't know how to solve this code. I try to modify as “Ask Mia” suggested but continues to give me this error.

Please be patience, i'm a newbie.

  1. from AlgorithmImports import *
  2. # Import necessary libraries for machine learning
  3. from sklearn.ensemble import RandomForestClassifier
  4. import numpy as np
  5. class SPYOptionMLTradingAlgorithm(QCAlgorithm):
  6. """
  7. This algorithm uses a Random Forest classifier to predict the direction of SPY's price movement and trades options accordingly.
  8. """
  9. def Initialize(self):
  10. """
  11. Initializes the algorithm with necessary parameters and settings.
  12. """
  13. self.SetStartDate(2023, 1, 1)
  14. self.SetEndDate(2023, 12, 31)
  15. self.SetCash(100000)
  16. self.spy = self.AddEquity("SPY", Resolution.Minute)
  17. self.lookback = 30
  18. self.model = RandomForestClassifier(n_estimators=10)
  19. self.training_data = []
  20. self.TrainModelOnStartOfMonth()
  21. # Schedule trading logic to run before market close every day
  22. self.Schedule.On(self.DateRules.EveryDay("SPY"), self.TimeRules.BeforeMarketClose("SPY", 10), self.TradeOptions)
  23. def TrainModelOnStartOfMonth(self):
  24. """
  25. Schedules the model training to occur at the start of each month.
  26. """
  27. self.Schedule.On(self.DateRules.MonthStart("SPY"), self.TimeRules.AfterMarketOpen("SPY", 30), self.TrainModel)
  28. def TrainModel(self):
  29. """
  30. Trains the Random Forest model using historical SPY price data.
  31. """
  32. history = self.History(self.spy.Symbol, self.lookback + 1, Resolution.Daily)
  33. if history.empty or history.isnull().values.any():
  34. return
  35. # Calculate features and labels for the model
  36. features = np.diff(history['close'])
  37. labels = np.where(features >= 0, 1, 0)[:-1]
  38. features = features.reshape(-1, 1)[:-1]
  39. # Fit the model to the training data
  40. self.model.fit(features, labels)
  41. def TradeOptions(self):
  42. """
  43. Predicts the direction of SPY's price movement and trades options accordingly.
  44. """
  45. # Get the current SPY price and calculate the feature for prediction
  46. today_features = np.array([self.spy.Price - self.spy.Close])
  47. # Make a prediction using the trained model
  48. prediction = self.model.predict(today_features.reshape(1, -1))
  49. # Buy a call option if the prediction is positive, otherwise buy a put option
  50. if prediction[0] == 1:
  51. option = self.BuyCallOption()
  52. else:
  53. option = self.BuyPutOption()
  54. # If an option contract is found, place a market order to buy it
  55. if option is not None:
  56. # Check if the option contract exists in the security list before placing an order
  57. if self.Securities.ContainsKey(option):
  58. self.MarketOrder(option, 1)
  59. else:
  60. self.Log("Option contract not found in security list: " + str(option))
  61. # Schedule liquidation of all holdings at 3:55 PM
  62. self.Schedule.On(self.DateRules.Everyday(), self.TimeRules.At(15, 55), lambda: self.Liquidate())
  63. def BuyCallOption(self):
  64. """
  65. Returns a call option contract with the closest expiration date.
  66. """
  67. return self.GetOptionContract(True)
  68. def BuyPutOption(self):
  69. """
  70. Returns a put option contract with the closest expiration date.
  71. """
  72. return self.GetOptionContract(False)
  73. def GetOptionContract(self, is_call):
  74. """
  75. Returns an option contract based on the specified option type (call or put) and closest expiration date.
  76. """
  77. contracts = self.OptionChainProvider.GetOptionContractList(self.spy.Symbol, self.Time)
  78. if is_call:
  79. contracts = [i for i in contracts if i.ID.OptionRight == OptionRight.Call]
  80. else:
  81. contracts = [i for i in contracts if i.ID.OptionRight == OptionRight.Put]
  82. # Sort contracts by expiration date and select the closest one
  83. contracts = sorted(contracts, key=lambda x: abs((x.ID.Date - self.Time).days))
  84. zero_dte_contracts = [i for i in contracts if (i.ID.Date - self.Time).days == 0]
  85. if zero_dte_contracts:
  86. return zero_dte_contracts[0]
  87. else:
  88. return None
+ Expand

Author

Roberto Coccaro

June 2024