Even though universal resolution is daily, CoarseSelectionFunction gets executed every second as per below logs
Source Code
UniversalSelection.py
class UniverseSelection:
def __init__(self, algorithm: QCAlgorithm, logger: Logger):
super().__init__()
self.algorithm = algorithm
self.logger = logger
self.logger.log("Starting UniverseSelection initialization...")
self.algorithm.universe_settings.Resolution = Resolution.Daily
# self.algorithm.add_universe(self.CoarseSelectionFunction)
try:
self.history = {}
self.moving_averages_200 = {}
self.moving_averages_20 = {}
self.previous_close = {}
self.atr = {}
self.volatility = {}
self.avg_volatility = {}
self.logger.log("Finished UniverseSelection initialization.")
except BaseException as e:
self.logger.log(f"Error during UniverseSelection initialization: {str(e)}")
raise e
def CreateUniverses(self, algorithm: QCAlgorithm) -> List[Universe]:
# This method must return one or more universes
return [self.algorithm.add_universe(self.CoarseSelectionFunction)]
def CoarseSelectionFunction(self, coarse):
# self.logger.log("CoarseSelectionFunction Started.")
current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
# Track memory usage before selection
process = psutil.Process()
memory_before = process.memory_info().rss / (1024 * 1024) # Convert to MB
self.logger.log(f"{current_time} - Memory Usage Before Selection: {memory_before:.2f} MB")
selected: List[str] = []
for stock in coarse:
if stock.Price > params.PRICE_THRESHOLD and stock.DollarVolume > params.DOLLAR_VOLUME_THRESHOLD:
selected.append(stock.Symbol)
# Initialize the historical data if not already done
if stock.Symbol not in self.history:
self.InitializeIndicators(stock.Symbol)
memory_after = process.memory_info().rss / (1024 * 1024) # Convert to MB
self.logger.log(f"{current_time} - Memory Usage After Selection: {memory_after:.2f} MB , CoarseSelectionFunction Selected {len(selected)} stocks.")
return selected
Main.py
class MainAlgorithm(QCAlgorithm):
def Initialize(self):
self.SetStartDate(2023, 1, 1)
self.SetCash(100000)
self.universe_settings.Resolution = Resolution.DAILY
# Initialize modules
self.Debug("Initializing Logger")
self.Debug("Logger initialized successfully")
self.Debug("Initializing UniverseSelection")
self.logger = Logger(self)
self.add_universe_selection(UniverseSelection(self, self.logger))
self.Debug("UniverseSelection initialized successfully")
self.set_warm_up(10,Resolution.DAILY)
def OnData(self, data):
if self.IsWarmingUp:
return
Logs example
2024-09-02 00:29:01 - Memory Usage After Selection: 4835.48 MB , CoarseSelectionFunction Selected 4673 stocks.
2024-09-02 00:30:19 - Memory Usage After Selection: 8069.66 MB , CoarseSelectionFunction Selected 4814 stocks.
2024-09-02 00:30:27 - Memory Usage After Selection: 8106.60 MB , CoarseSelectionFunction Selected 4649 stocks.
2024-09-02 00:30:30 - Memory Usage After Selection: 8135.48 MB , CoarseSelectionFunction Selected 4663 stocks.
Mia Alissi
Sources: Stateless Coarse Universe Selection Benchmark, Liquidity Effect In Stocks, Coarse Fine Universe Selection Benchmark, Initialization - QuantConnect.com, Stateful Coarse Universe Selection Benchmark
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.
Dharmesh Khalasi
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!