I am trying to build an algorithm that buys the top 6 gaining stocks at the beginning of stock day and sell it with stop limit trailing order of 1% if it reaches above 5%. I get the below exemption when running backtest.
QuantConnect.Scheduling.ScheduledEventException: In Scheduled Event 'SPY: EveryDay: Every 1 min', ---> System.Exception: AttributeError : 'NoneType' object has no attribute 'Close'
at sellAfter5prcnt in main.py:line 95 :: currentPrice = self.CurrentSlice[symbol].Close
---> Python.Runtime.PythonException: AttributeError : 'NoneType' object has no attribute 'Close'
at Python.Runtime.PyObject.Invoke (Python.Runtime.PyObject[] args) [0x00035] in :0
at QuantConnect.Scheduling.ScheduleManager+<>c__DisplayClass15_0.b__0 (System.String name, System.DateTime time) [0x00011] in :0
at QuantConnect.Scheduling.ScheduledEvent.OnEventFired (System.DateTime triggerTime) [0x00027] in :0
--- End of inner exception stack trace ---
--- End of inner exception stack trace --
Bennat
class CalibratedHorizontalCompensator(QCAlgorithm):
def Initialize(self):
self.SetStartDate(2019, 1, 30) # Set Start Date
self.SetCash(15000) # Set Strategy Cash
# Add SPY to set scheduled events
self.AddEquity("SPY", Resolution.Minute)
# Setting Universe
self.UniverseSettings.Resolution = Resolution.Minute
self.SetUniverseSelection(QC500UniverseSelectionModel())
# Dictionary to keep track of previous close for each symbol
self.previousClose = {}
# Dictionary to keep track of weekly cumulative performance for each symbol
self.performance = {}
# Our Scheduled Events
self.Schedule.On(self.DateRules.EveryDay("SPY"), self.TimeRules.AfterMarketOpen("SPY", 5), self.GetTopPerformers)
self.Schedule.On(self.DateRules.EveryDay("SPY"), self.TimeRules.Every(TimeSpan.FromMinutes(1)),self.sellAfter5prcnt)
self.Schedule.On(self.DateRules.EveryDay("SPY"), self.TimeRules.BeforeMarketClose("SPY", 1), self.OnMarketClose)
#self.Schedule.On(self.DateRules.Every(DayOfWeek.Friday) , self.TimeRules.BeforeMarketClose("SPY", 5), self.GetTopPerformers)
# list for top performers of week
self.top = []
def OnSecuritiesChanged(self, changes):
for security in changes.AddedSecurities:
symbol = security.Symbol
# Make a history call for symbol to get last closing price
if symbol not in self.previousClose:
history = self.History(symbol, 1, Resolution.Daily)
if not history.empty:
history = history.close.unstack(0)[symbol]
if not history.empty:
self.previousClose[symbol] = history[0]
# Remove symbols from previous close as they are removed from the universe
for security in changes.RemovedSecurities:
symbol = security.Symbol
self.previousClose.pop(symbol, None)
def sellAfter5prcnt(self):
# Dictionary to keep track of percent change from last close
percentChange = {}
currentSymbol={}
currentPrice={}
# Populate Dictionary
for symbol, previousClose in self.previousClose.items():
currentSymbol=symbol
if self.CurrentSlice.ContainsKey(symbol):
#Debug(symbol)
currentPrice = self.CurrentSlice[symbol].Close
change = (currentPrice - previousClose)/previousClose
percentChange[symbol] = change
if(change>5):
stopMarketOrder(currentSymbol,Portfolio[currentSymbol].Quantity,0.90*currentPrice)
def Rebalance(self):
# Dictionary to keep track of percent change from last close
percentChange = {}
# Populate Dictionary
for symbol, previousClose in self.previousClose.items():
if self.CurrentSlice.ContainsKey(symbol):
price = self.CurrentSlice[symbol].Close
change = (price - previousClose)/previousClose
percentChange[symbol] = change
# Symbols under consideration
symbols = list(percentChange.keys())
# Sort symbols by percent change
sortedSymbols = sorted(symbols, key=lambda x : percentChange[x], reverse = True)
# Get top 6 symbols
selected = sortedSymbols[:6]
# Set holdings equally to those symbols
for symbol in selected:
self.SetHoldings(symbol, 1 / len(selected))
def OnMarketClose(self):
# Store cumulative performance for symbols in portfolio
for kvp in self.Portfolio:
symbol = kvp.Key
holding = kvp.Value
if holding.Invested:
if symbol not in self.performance:
self.performance[symbol] = holding.UnrealizedProfitPercent
else:
self.performance[symbol] = self.performance[symbol] + holding.UnrealizedProfitPercent
# Liquidate portfolio
self.Liquidate()
# Store new previous close values
for symbol in self.previousClose:
if self.CurrentSlice.ContainsKey(symbol):
self.previousClose[symbol] = self.CurrentSlice[symbol].Close
def GetTopPerformers(self):
# Symbols under consideration
symbols = list(self.performance.keys())
# Symbols sorted by performance
sortedSymbols = sorted(symbols, key=lambda x: self.performance[x], reverse=True)
# Top 10 performers
self.top = sortedSymbols[:6]
#Debug(sortedSymbols[:6])
# Reset performances
self.performance = {}
Shile Wen
Hi Ben J,
Please see my previous post on this issue.
Best,
Shile Wen
Bennat
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!