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.
from AlgorithmImports import *
# Import necessary libraries for machine learning
from sklearn.ensemble import RandomForestClassifier
import numpy as np
class SPYOptionMLTradingAlgorithm(QCAlgorithm):
"""
This algorithm uses a Random Forest classifier to predict the direction of SPY's price movement and trades options accordingly.
"""
def Initialize(self):
"""
Initializes the algorithm with necessary parameters and settings.
"""
self.SetStartDate(2023, 1, 1)
self.SetEndDate(2023, 12, 31)
self.SetCash(100000)
self.spy = self.AddEquity("SPY", Resolution.Minute)
self.lookback = 30
self.model = RandomForestClassifier(n_estimators=10)
self.training_data = []
self.TrainModelOnStartOfMonth()
# Schedule trading logic to run before market close every day
self.Schedule.On(self.DateRules.EveryDay("SPY"), self.TimeRules.BeforeMarketClose("SPY", 10), self.TradeOptions)
def TrainModelOnStartOfMonth(self):
"""
Schedules the model training to occur at the start of each month.
"""
self.Schedule.On(self.DateRules.MonthStart("SPY"), self.TimeRules.AfterMarketOpen("SPY", 30), self.TrainModel)
def TrainModel(self):
"""
Trains the Random Forest model using historical SPY price data.
"""
history = self.History(self.spy.Symbol, self.lookback + 1, Resolution.Daily)
if history.empty or history.isnull().values.any():
return
# Calculate features and labels for the model
features = np.diff(history['close'])
labels = np.where(features >= 0, 1, 0)[:-1]
features = features.reshape(-1, 1)[:-1]
# Fit the model to the training data
self.model.fit(features, labels)
def TradeOptions(self):
"""
Predicts the direction of SPY's price movement and trades options accordingly.
"""
# Get the current SPY price and calculate the feature for prediction
today_features = np.array([self.spy.Price - self.spy.Close])
# Make a prediction using the trained model
prediction = self.model.predict(today_features.reshape(1, -1))
# Buy a call option if the prediction is positive, otherwise buy a put option
if prediction[0] == 1:
option = self.BuyCallOption()
else:
option = self.BuyPutOption()
# If an option contract is found, place a market order to buy it
if option is not None:
# Check if the option contract exists in the security list before placing an order
if self.Securities.ContainsKey(option):
self.MarketOrder(option, 1)
else:
self.Log("Option contract not found in security list: " + str(option))
# Schedule liquidation of all holdings at 3:55 PM
self.Schedule.On(self.DateRules.Everyday(), self.TimeRules.At(15, 55), lambda: self.Liquidate())
def BuyCallOption(self):
"""
Returns a call option contract with the closest expiration date.
"""
return self.GetOptionContract(True)
def BuyPutOption(self):
"""
Returns a put option contract with the closest expiration date.
"""
return self.GetOptionContract(False)
def GetOptionContract(self, is_call):
"""
Returns an option contract based on the specified option type (call or put) and closest expiration date.
"""
contracts = self.OptionChainProvider.GetOptionContractList(self.spy.Symbol, self.Time)
if is_call:
contracts = [i for i in contracts if i.ID.OptionRight == OptionRight.Call]
else:
contracts = [i for i in contracts if i.ID.OptionRight == OptionRight.Put]
# Sort contracts by expiration date and select the closest one
contracts = sorted(contracts, key=lambda x: abs((x.ID.Date - self.Time).days))
zero_dte_contracts = [i for i in contracts if (i.ID.Date - self.Time).days == 0]
if zero_dte_contracts:
return zero_dte_contracts[0]
else:
return None
Marc Daoust
Roberto - your Schedule code appears correct, for C#. The Python keywords are in lower_case :
I copied your code, cleaned it up a bit, fixed the syntax, and it runs - but no trades are taken.
I found documentation on self.OptionChainProvider.GetOptionContractList(…) by switching my preference to C# code - you are using C# code with self. added as a prefix!?! It's not that simple!
According to the documentation linked below, this is the Python syntax:
self.option_chain_provider.get_option_contract_list(self._symbol, self.time)
Although it now runs, it does not produce any trades - see backtest below.
Overall it's a good start - keep at it. Let us know if you more questions.
I'm interested in knowing what you find.
Regards;
Marc
Roberto Coccaro
The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.
To unlock posting to the community forums please complete at least 30% of Boot Camp.
You can continue your Boot Camp training progress from the terminal. We hope to see you in the community soon!