Overall Statistics
# region imports
from AlgorithmImports import *
# endregion

class AlertFluorescentYellowChinchilla(QCAlgorithm):

    def initialize(self):
        self.set_start_date(2023, 1, 2)
        self.set_end_date(2023, 1, 3)
        self.set_cash(100000)
        
        self.rebalanceTime = self.Time
        self.AddUniverse(self.CoarseFilter, self.FineFilter)
        self.UniverseSettings.Resolution = Resolution.Minute
        self.final_universe_size = 10

    def CoarseFilter(self, coarse):
            # Rebalancing monthly
            if self.Time <= self.rebalanceTime:
                return self.Universe.Unchanged
            self.rebalanceTime = self.Time + timedelta(days=360)
            
            sortedByDollarVolume = sorted(coarse, key=lambda x: x.DollarVolume, reverse=True)
            return [x.Symbol for x in sortedByDollarVolume if x.HasFundamentalData][:1000]
        
    def FineFilter(self, fine):
        sortedbyVolume = sorted(fine, key=lambda x: x.DollarVolume, reverse=True ) 
        fine_output = [x.Symbol for x in sortedbyVolume if x.MarketCap > 0][:self.final_universe_size]

        return fine_output

    def OnSecuritiesChanged(self, changes):
        # region removed securities
        for x in changes.RemovedSecurities:
            self.Liquidate(x.Symbol)
            if x.Symbol in self.activeStocks:
                self.activeStocks.remove(x.Symbol)

        for x in changes.AddedSecurities:
            self.activeStocks.add(x.Symbol)

    def on_data(self, data: Slice):
        for x in self.activeStocks:
            if data.ContainsKey(x) and data[x] != None:
                self.SetHoldings(x, .2)