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?

#region imports
from AlgorithmImports import *
import numpy as np


class SmallCapInvestmentAlgorithm(QCAlgorithm):

    def Initialize(self):

        self.SetStartDate(2020, 1, 1)
        self.SetEndDate(2020, 5, 1)
        self.SetCash(100000)
        self.count = 10
        self.UniverseSettings.Resolution = Resolution.Daily
        self.AddUniverse(self.CoarseSelectionFunction, self.FineSelectionFunction)
        self.SetBenchmark("SPY")

    def CoarseSelectionFunction(self, coarse):
        ''' Drop stocks which have no fundamental data or have low price '''
        return [x.Symbol for x in coarse if x.HasFundamentalData and x.Price > 5]
 
    def FineSelectionFunction(self, fine): #small cap stocks
        ''' Selects the stocks by lowest market cap '''
        sorted_market_cap = sorted([x for x in fine if x.MarketCap > 1000000000],
            key=lambda x: x.MarketCap)
        return [x.Symbol for x in sorted_market_cap[:self.count]]
        
    def FineSelectionLarge(self,fine): #large caps
        sorted_market_capLarge = sorted([x for x in fine if x.MarketCap > 1000000000],
            key=lambda x: x.MarketCap, reverse=True)
        return [x.Symbol for x in sorted_market_capLarge[:self.count]]

    def OnData(self, data):
        if not self.IsWarmingUp and not self.Portfolio.Invested:
            if X > Y: # Buy LARGE STOCKS
                for Symbol in self.ActiveSecurities.Keys:
                    self.SetHoldings(Symbol, 1/self.count)  
            if X<Y: #BUY SMALL STOCKS
                for Symbol in self.ActiveSecurities.Keys:
                    self.SetHoldings(Symbol, 1/self.count)  
        
            
    def OnSecuritiesChanged(self, changes):
        ''' Liquidate the securities that were removed from the universe '''
        for security in changes.RemovedSecurities:
            symbol = security.Symbol
            if self.Portfolio[symbol].Invested:
                self.Liquidate(symbol, 'Removed from Universe')

 

Author