Hi! 

I am trying to create a strategy, in which I would be buying top 10 stocks in terms of Market Cap if condition 1 would be true, and bottom 10 stocks in terms of Market Cap if condition 1 is false. I don't understand however, how to create market orders, which would execute this strategy correctly. The difference between “FineSelectionFunction” and “FineSelectionLarge” is that the list of stocks in the second function is reversed, which means that is sorted from the largest from the smallest companies. I would like to buy Large companies when X > Y and Small stocks when X < Y. Could you please help me with this issue?

  1. #region imports
  2. from AlgorithmImports import *
  3. import numpy as np
  4. class SmallCapInvestmentAlgorithm(QCAlgorithm):
  5. def Initialize(self):
  6. self.SetStartDate(2020, 1, 1)
  7. self.SetEndDate(2020, 5, 1)
  8. self.SetCash(100000)
  9. self.count = 10
  10. self.UniverseSettings.Resolution = Resolution.Daily
  11. self.AddUniverse(self.CoarseSelectionFunction, self.FineSelectionFunction)
  12. self.SetBenchmark("SPY")
  13. def CoarseSelectionFunction(self, coarse):
  14. ''' Drop stocks which have no fundamental data or have low price '''
  15. return [x.Symbol for x in coarse if x.HasFundamentalData and x.Price > 5]
  16. def FineSelectionFunction(self, fine): #small cap stocks
  17. ''' Selects the stocks by lowest market cap '''
  18. sorted_market_cap = sorted([x for x in fine if x.MarketCap > 1000000000],
  19. key=lambda x: x.MarketCap)
  20. return [x.Symbol for x in sorted_market_cap[:self.count]]
  21. def FineSelectionLarge(self,fine): #large caps
  22. sorted_market_capLarge = sorted([x for x in fine if x.MarketCap > 1000000000],
  23. key=lambda x: x.MarketCap, reverse=True)
  24. return [x.Symbol for x in sorted_market_capLarge[:self.count]]
  25. def OnData(self, data):
  26. if not self.IsWarmingUp and not self.Portfolio.Invested:
  27. if X > Y: # Buy LARGE STOCKS
  28. for Symbol in self.ActiveSecurities.Keys:
  29. self.SetHoldings(Symbol, 1/self.count)
  30. if X<Y: #BUY SMALL STOCKS
  31. for Symbol in self.ActiveSecurities.Keys:
  32. self.SetHoldings(Symbol, 1/self.count)
  33. def OnSecuritiesChanged(self, changes):
  34. ''' Liquidate the securities that were removed from the universe '''
  35. for security in changes.RemovedSecurities:
  36. symbol = security.Symbol
  37. if self.Portfolio[symbol].Invested:
  38. self.Liquidate(symbol, 'Removed from Universe')
+ Expand

 

Author

Sebastian Wozniczka

October 2022