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!
Shile Wen
Hi Ethan,
The error occurs because of Scoping issues, as we try to access stop_prices as if it were a global variable. To fix this, we need to add self. to stop_prices, and I’ve also added self.stop_prices = {} to Initalize. As a side note, wrapping scheduled functions in Actions is no longer necessary. Please see the attached backtest for reference.
Best,
Shile Wen
John Fogel
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!