class TrialHighalgorithm(QCAlgorithm):
def Initialize(self):
self.SetStartDate(2020, 11, 1)
#self.SetEndDate(2020, 11, 11)
self.SetCash(10000)
self.numberOfSymbols = 200
self.numberOfSymbolsFine = 10
self.res = Resolution.Minute
self.averages = {}
self.symbols = []
self.sma = {}
self.selectedSymbols = []
self.SPY = self.AddEquity('SPY', self.res).Symbol
self.Securities["SPY"].SetDataNormalizationMode(DataNormalizationMode.Raw)
self.SetTimeZone(TimeZones.HongKong)
self.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Margin)
self.AddUniverse(self.CoarseSelectionFunction, self.FineSelectionFunction)
def CoarseSelectionFunction(self, coarse):
filtered = [ x for x in coarse if (x.HasFundamentalData) & (x.Price > 1) & ( x.Volume > 500000) ]
filtered.sort(key=lambda x: x.DollarVolume, reverse=True)
self.symbols = [ x.Symbol for x in filtered[:self.numberOfSymbols] ]
return self.symbols
def FineSelectionFunction(self, fine):
symbols = [x.Symbol for x in fine]
history = self.History(symbols, 252, Resolution.Daily)
for symbol in symbols:
if str(symbol) in history.index.get_level_values(0):
symbolHistory = history.loc[str(symbol)]
if not symbolHistory.empty:
symbolSMA = SimpleMovingAverage(200)
for tuple in symbolHistory.itertuples():
bar = TradeBar(tuple.Index, symbol, tuple.open, tuple.high, tuple.low, tuple.close, tuple.volume)
symbolSMA.Update(tuple.Index, tuple.close)
self.sma[symbol] = symbolSMA
else:
symbols.pop(symbols.index(symbol))
self.selectedSymbols = [ x for x in symbols if (max(history.loc[str(x)]['high'][:-1]) < history.loc[str(x)]['high'][-1]) & (history.loc[str(x)]['close'][-1] > history.loc[str(x)]['open'][-1])]
return self.selectedSymbols
def OnData(self, data):
if self.selectedSymbols is None: return
for x in self.selectedSymbols:
self.SetHoldings(x, 0.01)
I want to filter 52 weeks high stocks and make sure they close above open yesterday. I know my coding is bad. Is there any easy way to do it in the same way? It is a bit slow.
sometimes it got : max() arg is an empty sequence
Could someone help me, please? Thanks
AK M
Hey Vidal,
There are a couple issues with your algorithm. The algorithm is slow for several reasons. First, the algorithm resolution is set to Minute, however it does not seem that anything significant is being done minutely that cannot be done at a coarser resolution. When the resolution is minutely, your OnData() function is called every minute. Changing to Resolution.Daily may better suite your needs.
Second, it seems like you are calling the FineSelection function unnecessarily. Fine universe selection is used when you want to want to use fundamental data to filter your universe, data such as EPS, Revenue Growth, EBIDTA, Debt, etc. It seems what you require does not require fundamental data at the moment, so moving the logic to the CoarseSelection function is better.
However, the biggest bottleneck is the history call. History calls are slow and in your code, the calls are being made every day (as CoarseSelection is called daily at midnight). A better way to manage historical data would be to cache old values for symbols and update as necessary.
There are some minor things too, like using ‘and’ instead of ‘&’ to short-circuit conditions.
It may be difficult to make all these changes, so I have rewritten your algorithm with them in mind. It may not be perfectly what you want, but hopefully it is a good starting point for you. I've attached it below.
Vidal boreal
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!