Hello.

I've been trying to write this algo but I'm stuck. It's intended to be a long/short equity strategy based on a few fundamentals but I'm not sure how to fire the trades and write the monthly rebalancing function. It doesn't result in equal numbers of long and short equities, but the weight is supposed to be 0.45 if the len(self.longs) > 2, otherwise SetHoldings(self.longs, 0). For the shorts it's the same but the weight is -0.45.

Any help is much appreciated.

from AlgorithmImports import *
from datetime import timedelta
from QuantConnect.Data.UniverseSelection import *
from Selection.FundamentalUniverseSelectionModel import FundamentalUniverseSelectionModel

class LongShortPF(QCAlgorithm):

    def Initialize(self):
        self.UniverseSettings.Resolution = Resolution.Daily
        self.SetStartDate(2015, 1, 1)  
        self.SetEndDate(2022, 1, 1)    
        self.SetCash(1000000)          
        self._changes = None
        self.numb_stocks = 50
        self.AddUniverse(self.CoarseSelection, self.FineSelection)
        self.UniverseSettings.DataNormalizationMode = DataNormalizationMode.Raw
       
        #self.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Cash)
        #self.SetTimeZone(TimeZones.Chicago)    
       
    def CoarseSelection(self, coarse):
        self.filteredStocks = [x.Symbol for x in coarse if x.HasFundamentalData \
            and (float(x.Price)) > 10 \
                and x.DollarVolume > 5000000]

        return self.filteredStocks

         
    def FineSelection(self,fine):
        no_fin = [sec for sec in fine if \
            sec.AssetClassification.MorningstarSectorCode != MorningstarSectorCode.FinancialServices]

        tops = sorted(no_fin, key = lambda sec:sec.ValuationRatios.ForwardPERatio, reverse=True)[:self.numb_stocks]
        bottoms = sorted(no_fin, key = lambda sec:sec.ValuationRatios.ForwardPERatio, reverse=True)[-self.numb_stocks:]


        self.longs = [l.Symbol for l in tops if l.ValuationRatios.PEGRatio < 1]
        self.shorts = [s.Symbol for s in bottoms if s.ValuationRatios.PEGRatio > 1]


        return self.longs + self.shorts


    def OnSecuritiesChanged(self, change):
        pass
   
    def OnData(self, data):

        if not self.Portfolio.Invested:
            if len(self.longs) < 2:
                self.SetHoldings(self.longs, 0)
            else:
                self.SetHoldings(self.longs, 0.45 / len(self.longs))


            if len(self.shorts) < 2:
                self.SetHoldings(self.short, 0)
            else:
                self.SetHolding(self.shorts, -0.45 / len(self.shorts))