Hi!

I have been working on a strategy, which involves sorting stocks by their Market Cap. Unfortunately I am facing 2 problems which I can't solve. Firstly, when I try to test the strategy from 2017 and invest in smallest 10% stocks, the algo goes Long only 32 companies. If i change startDate from 2018, the list of companies expands to 295. Is it possible that prior to 2018 the list of stocks with MarketCap is incomplete?It would be very strange as in the “Book-to-market Value Anomaly” tutorial, which has a very similar approach, the data used in the test begins in 2004. 
Secondly, In my example, when I try to test my strategy prior to 2017, I receive this notification:

  1. Runtime Error: It is not possible to cast a non-finite floating-point value (NaN) as decimal. Please review math operations and verify the result is valid. (Parameter 'input') in Trading.cs:line 1075

Here is the code which I use:

  1. #region imports
  2. from AlgorithmImports import *
  3. #endregion
  4. # https://quantpedia.com/Screener/Details/26
  5. from QuantConnect.Data.UniverseSelection import *
  6. import math
  7. import numpy as np
  8. class BooktoMarketAnomaly(QCAlgorithm):
  9. def Initialize(self):
  10. self.SetStartDate(2017, 1, 1)
  11. self.SetEndDate(2018, 1, 10)
  12. self.SetCash(1000000)
  13. self.UniverseSettings.Resolution = Resolution.Daily
  14. self.AddEquity("SPY", Resolution.Daily)
  15. self.AddUniverse(self.CoarseSelectionFunctionBottom, self.FineSelectionFunctionBottom)
  16. def CoarseSelectionFunctionBottom(self, coarse):
  17. return [x.Symbol for x in coarse if x.HasFundamentalData and x.Price > 5]
  18. def FineSelectionFunctionBottom(self, fine):
  19. bottom_market_cap = sorted(fine, key = lambda x:x.MarketCap, reverse=False)[:int(len([j for j in fine])*0.1)]
  20. self.sorted_by_mc_bottom = [j.Symbol for j in bottom_market_cap]
  21. total_market_cap_bottom = np.sum([j.MarketCap for j in bottom_market_cap])
  22. self.weights_bottom = {}
  23. for j in bottom_market_cap:
  24. self.weights_bottom[str(j.Symbol)] = j.MarketCap/total_market_cap_bottom
  25. return self.sorted_by_mc_bottom
  26. def OnData(self, data):
  27. if not self.Portfolio.Invested:
  28. for j in self.sorted_by_mc_bottom:
  29. self.SetHoldings(j, self.weights_bottom[str(j)])
  30. self.Log("Otwarcie Small Cap")
+ Expand


 

Author

Sebastian Wozniczka

November 2022