I am trying to use the self.Schedule.On() within the algorithm class Initialize() function. I learn this from the boot camp. Here is the example code:

 

class OpeningRangeBreakout(QCAlgorithm):

openingBar = None

def Initialize(self):
self.SetStartDate(2018, 7, 10)
self.SetEndDate(2019, 6, 30)
self.SetCash(100000)
self.AddEquity("TSLA", Resolution.Minute)
self.Consolidate("TSLA", timedelta(minutes=30), self.OnDataConsolidated)

#3. Create a scheduled event triggered at 13:30 calling the ClosePositions function
self.Schedule.On(self.DateRules.EveryDay("TSLA"), self.TimeRules.At(13, 30), self.ClosePositions)

#1. Create a function named ClosePositions(self)
def ClosePositions(self):
#2. Set self.openingBar to None, and liquidate TSLA
self.openingBar = None
self.Liquidate("TSLA")

 

I try to use it under the suggested Framework like this:

class QuantityTesting_Insight(QCAlgorithm):

def Initialize(self):
self.SetStartDate(2020, 1, 13) # Set Start Date
self.SetEndDate(2020, 1, 18) # Set End Date
self.SetCash(100000) # Set Strategy Cash

# Handle UniverseSettings
self.UniverseSettings.Resolution = Resolution.Minute
symbols = [Symbol.Create("SPY", SecurityType.Equity, Market.USA)]
self.SetUniverseSelection(ManualUniverseSelectionModel(symbols))
self.SetSecurityInitializer(lambda x: x.SetDataNormalizationMode(DataNormalizationMode.Raw))

# Handle Alpha Model
self.SetAlpha(TestingAlpha())

# Handle Portfolio Model
self.SetPortfolioConstruction(EqualWeightingPortfolioConstructionModel())
self.SetExecution(ImmediateExecutionModel())
self.SetRiskManagement(NullRiskManagementModel())


self.Schedule.On(self.DateRules.EveryDay("SPY"), self.TimeRules.At(18, 30), self.ClosePositions)


def ClosePositions(self):
self.Log("Callback ClosePositions()")

I get error message: 

----------------------------------------------------------------------------------

During the algorithm initialization, the following exception has occurred: KeyNotFoundException : SPY not found in portfolio. Request this data when initializing the algorithm.
at QuantConnect.Scheduling.DateRules.GetSecurity (QuantConnect.Symbol symbol) [0x00020] in :0
KeyNotFoundException : SPY not found in portfolio. Request this data when initializing the algorithm.
at QuantConnect.Scheduling.DateRules.GetSecurity (QuantConnect.Symbol symbol) [0x00020] in :0
----------------------------------------------------------------------------------

 

Is that mean I didn't add SPY after calling SetUniverseSelection() ? How to fix it?

Thank you very much.

Author