Back

Runtime Error: KeyNotFoundException : 'SPY'

Would this error be due to a data problem or a code problem?

 

I cant seem to attatch a backtest here is the code snippet

class SupportAndResistance(QCAlgorithm):
UnderlyingTicker = 'SPY'
openingBar = None;
def Initialize(self):
self.SetStartDate(2020, 1, 1)
self.SetEndDate(2020,1,31)
self.SetCash(100000)
self.SetWarmUp(timedelta(7)) # Warm up 7 days of data.
equity = self.AddEquity(self.UnderlyingTicker, Resolution.Minute)
equity.SetDataNormalizationMode(DataNormalizationMode.Raw)

option = self.AddOption(self.UnderlyingTicker)
self.Consolidate(self.UnderlyingTicker, timedelta(1), self.OnDataConsolidated)

self.option_symbol = option.Symbol

# set our strike/expiry filter for this option chain
option.SetFilter(lambda u: u.IncludeWeeklys().Strikes(0, 10).Expiration(timedelta(0), timedelta(7)))
# option.SetFilter(lambda u: (u.Strikes(-2, +2)
# # Expiration method accepts TimeSpan objects or integer for days.
# # The following statements yield the same filtering criteria
# .Expiration(0, 180)))
# #.Expiration(TimeSpan.Zero, TimeSpan.FromDays(180))))
# self.Schedule.On(self.DateRules.EveryDay(self.UnderlyingTicker), self.TimeRules.At(13, 30), self.ClosePositions)

# use the underlying equity as the benchmark
self.SetBenchmark(equity.Symbol)

def OnData(self,slice):
if self.openingBar == None: return
if not self.Portfolio.Invested:
chain = slice.OptionChains.GetValue(self.option_symbol)
if chain is None:
return

contracts_put = sorted(sorted(sorted(chain, \
key = lambda x: abs(chain.Underlying.Price - x.Strike)), \
key = lambda x: x.Expiry, reverse=False), \
key = lambda x: x.Right, reverse=True)

contracts_call = sorted(sorted(sorted(chain, \
key = lambda x: abs(chain.Underlying.Price - x.Strike)), \
key = lambda x: x.Expiry, reverse=False), \
key = lambda x: x.Right, reverse=False)

if len(contracts_put) == 0: return
self.symbol_put = contracts_put[0].Symbol

if len(contracts_call) == 0: return
self.symbol_call = contracts_call[0].Symbol

if slice[self.UnderlyingTicker].Close >= (self.openingBar.High - .10):
self.MarketOrder(self.symbol_put, 10)

if self.Portfolio.Invested:
option_invested = [x.Key.Value for x in self.Portfolio if x.Value.Invested and x.Value.Type==SecurityType.Option]
# Print to log
for contract in option_invested:
self.c = contract
quantity = self.Portfolio[contract].Quantity
lastPrice = self.Securities[contract].Price
if self.Securities[contract].BidPrice > (self.Securities[contract].Holdings.AveragePrice + .10):
self.Debug('Here')
self.Liquidate(contract)
self.openingBar = None
if self.Securities[contract].Holdings.AveragePrice < self.Securities[contract].BidPrice - .20:
self.Debug('Here')
self.Liquidate(contract)
self.openingBar = None




def OnOrderEvent(self, orderEvent):
self.Log(str(orderEvent))

def OnDataConsolidated(self, bar):
self.openingBar = bar

 

Update Backtest







0

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.


Hi Tom,

Data for a symbol may sometimes be missing for a particular time slice. In order to account for this, we should check whether that data exists in the slice before attempting to access it.

if not slice.ContainsKey(self.UnderlyingTicker):
self.Debug(f"NO {self.UnderlyingTicker} data on {self.Time}")
return

 

1

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.


Update Backtest





0

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.


Loading...

This discussion is closed