I'm trying to backtest a simple strategy that purchases ATM SPXW Calls 5 minutes prior to close and holds into expiry but I am having some difficulties navigating the API with options.
So far I have just pieced together this code with the other examples of weekly options on the forum and with the options API example in the Learning Center Articles but it seems to not actually purchase any options.
From the learning center https://www.quantconnect.com/learning/articles/introduction-to-options/quantconnect-options-api. When I add this block of code for purchasing contracts after sorting for ATM contracts in the OnData method I get a continue not used properly in loop error.
if len(contracts) == 0: continue
# trade the contracts with the farthest expiration
symbol = contracts[0].Symbol
self.MarketOrder(symbol, 1)
self.MarketOnCloseOrder(symbol, -1)
Without the loop I would still expect that one contract would be purchased within my single backtest day however none are ever purchased.
The full code looks like this
def Initialize(self):
self.SetStartDate(2023, 7, 14) # Set Start Date
self.SetCash(100000) # Set Strategy Cash
underlying = self.AddIndex("SPX", Resolution.Minute)
options = self.AddIndexOption(underlying.Symbol, "SPXW", Resolution.Minute)
options.SetFilter(lambda u: u.WeeklysOnly().Strikes(-1,1).Expiration(0,1))
self.symbol = options.Symbol
def OnData(self, data: Slice):
chain = slice.OptionChains.get(self.symbol)
if chain:
#self.log(f"underlying price: {chain.Underlying.Price}")
#df=pd.DataFrame([[x.Right,x.Strike,x.Expiry,x.BidPrice,x.AskPrice] for x in chain],
# index=[x.Symbol.Value for x in chain],
# columns=['type)call 0, put1)', 'strike', 'expiry', 'ask price', 'bid price'])
#self.Log(str(df))
call = [x for x in chain if x.Right == OptionRight.Call]
put = [x for x in chain if x.Right == OptionRight.Put]
#Choos ATM Call contracts
contracts = sorted(chain, key = lambda x: abs(x.UnderlyingLastPrice - x.Strike))[0]
#if len(contracts) == 0: continue
# trade the contracts with the farthest expiration
symbol = contracts[0].Symbol
self.MarketOrder(symbol, 1)
def OnOrderEvent(self, orderEvent):
self.log()
I am still getting used to using Quant Connect so I'm sure it is something really obvious that I am doing wrong. Appreciate any advice!
Mia Alissi
Based on the information provided in the extracts, it seems like you're trying to trade options on the SPX index. However, as mentioned in the forum discussion here, QuantConnect currently does not fully support index options like SPX. Instead, it is recommended to use SPY as an equity-option proxy for the SPX index-options.
Regarding the error you're encountering, it seems to be related to the use of the
continue
statement outside of a loop. Thecontinue
statement is used to skip the rest of the code inside a loop for the current iteration only. This means it should be used inside a loop, such as afor
orwhile
loop. In your code, it appears that thecontinue
statement is not inside a loop, hence the error.As for the issue of no contracts being purchased, it could be due to the fact that the conditions for purchasing a contract are not being met. It's hard to say without more information, but you might want to check the conditions you've set for purchasing a contract.
Here's a corrected version of your code:
This code uses SPY instead of SPX and removes the
continue
statement. It also checks if there are any contracts before trying to access the first one. Please note that this is a basic example and might need further adjustments to fit your strategy.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.
Mitchell Kothleitner
Thanks Mia, I did see in the forum that SPXW options are not supported but all from posts pre 2020. I also so a post here from April of this year of a user being able to retrieve SPXW options data. Are you able to confirm that SPXW options data is not currently available? The strategy calls for the cash settlement of the SPX options and this is why SPY will not work for this case.
Thanks again!
Mia Alissi
Based on the information provided in the extracts, it seems that SPX data is available, but the modeling for index options like SPXW might not be fully set up yet. This information was mentioned in a forum discussion from June 2017. However, there is no updated information in the extracts about the current status of SPXW options data.
Regarding the code you provided, the error you're encountering is likely due to the use of
continue
outside of a loop. Thecontinue
statement is used to skip the rest of the code inside a loop for the current iteration only. In your code, it seemscontinue
is not inside a loop, hence the error.Also, in your code, you're trying to access the first element of
contracts
even when it might be empty. This could potentially lead to an error. You should check ifcontracts
is not empty before trying to access its elements.Here's a corrected version of your code:
In this version, the
MarketOrder
is only placed if there are contracts available.Please note that this information is based on the provided extracts and might not fully solve your problem. For more detailed assistance, you might want to refer to the QuantConnect documentation or ask for help in the QuantConnect forum.
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.
Mitchell Kothleitner
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!