def Initialize(self): self.SetStartDate(2018, 1, 1) # Set Start Date self.SetEndDate(2020, 8, 26) # Set End Date self.SetCash(100000) # Set Strategy Cash # set the flag for rebalance self.reb = 1 self.AddUniverse(self.CoarseSelectionFunction,self.FineSelectionFunction) self.spy = self.AddEquity("SPY", Resolution.Daily).Symbol self.tlt = self.AddEquity("TLT", Resolution.Daily).Symbol self.Schedule.On(self.DateRules.MonthStart(self.spy), self.TimeRules.AfterMarketOpen(self.spy,5), Action(self.rebalance)) # for stop loss check self.Schedule.On(self.DateRules.EveryDay(self.spy), self.TimeRules.AfterMarketOpen(self.spy,10), Action(self.stoploss)) self.SetSecurityInitializer(self.CustomSecurityInitializer) def stoploss(self): # check for stop loss condition for i in self.Portfolio.Values: hist = self.History(i.Symbol, timedelta(days=3), Resolution.Daily) if "close" in hist.columns: x = (hist["close"][-1] - stop_price[i.Symbol]) / stop_price[i.Symbol] if x <= -10 and i.Invested: self.Liquidate(i.Symbol) self.SetHoldings(self.tlt, 1/self.num_fine) def rebalance(self): long_list = self.long # liquidate all positions at the start of rebalancement for i in self.Portfolio.Values: if i.Invested: self.Liquidate(i.Symbol) # assign each stock equally for i in self.long: self.SetHoldings(i, 1/self.num_fine) # create dictionary to store the stop loss values stop_price = {} # save the stop loss price for i in self.long: stop_price[i] = self.Portfolio[i].AveragePrice self.reb = 1

Hello everyone, I need a little help with a stop loss strategy. 

A summary of my basic momentum strategy with stop loss: 

1) Course universe selection - 500 most liquid stocks

2) Fine universe selection - ranked by momentum 

3) Go long on the top 10 stocks 

4) Rebalance monthly

I currently want to implement a stop loss strategy as such: 

Everyday, I run a price check on my holdings: If their most recent close price is less than the price at which I bought the security at by 10% or more, I will liquidate that position and go into bonds "TLT" 

I have attached my code snippet above. I am currently running into the error which states: 

Runtime Error: In Scheduled Event 'SPY: EveryDay: SPY: 10 min after MarketOpen', NameError : name 'stop_price' is not defined NameError : name 'stop_price' is not defined

and I am not very sure on how to proceed. Any help is appreciated. Thank you! 

Author