Strategy Test Implementation¶

I am trying to:

  • filter on a universe using coarse + fine (monthly or quarterly)
  • create an indicator to run daily or on minute data on the resulting universe to enter trades
In [ ]:
class CoarseFineFundamentalATRComboAlgorithm(QCAlgorithm):

    def Initialize(self):
        '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''

        self.SetStartDate(2014, 1, 1)  #Set Start Date
        self.SetEndDate(2014, 6, 1)    #Set End Date
        self.SetCash(50000)            #Set Strategy Cash

        # what resolution should the data *added* to the universe be?
        self.UniverseSettings.Resolution = Resolution.Daily
        
        # An indicator(or any rolling window) needs data(updates) to have a value
        self.atr_window = 20
        self.UniverseSettings.MinimumTimeInUniverse = self.atr_window
        self.SetWarmUp(self.atr_window)

        # this add universe method accepts two parameters:
        self.AddUniverse(self.CoarseSelectionFunction, self.FineSelectionFunction)
        
        #self.flag1 = 1  # variable to control the monthly rebalance of coarse and fine selection function
        
        # Set dictionary of indicators
        self.indicators = {}
        
        # Set a list of the selected universe
        self.universe=[]

        self.__numberOfSymbols     = 200
        self.__numberOfSymbolsFine = 10
        
        self.spy = self.AddEquity("SPY", Resolution.Daily).Symbol
        
        #self.Schedule.On(self.DateRules.MonthStart("SPY"), self.TimeRules.AfterMarketOpen("SPY", 10), Action(self.CoarseSelectionFunction))

                        
    # sort the data by daily dollar volume and take the top 'NumberOfSymbols'
    def CoarseSelectionFunction(self, coarse):
        # sort descending by daily dollar volume
        sortedByDollarVolume = sorted(coarse, key=lambda x: x.DollarVolume, reverse=True)

        # return the symbol objects of the top entries from our sorted collection
        return [ x.Symbol for x in sortedByDollarVolume[:self.__numberOfSymbols] ]


    # sort the data by P/E ratio and take the top 'NumberOfSymbolsFine'
    def FineSelectionFunction(self, fine):
        
        # sort descending by P/E ratio
        sortedByPeRatio = sorted(fine, key=lambda x: x.ValuationRatios.FCFYield, reverse=True)
        
        # resulting symbols
        self.universe = [ x.Symbol for x in sortedByPeRatio[:self.__numberOfSymbolsFine] ]

        # take the top entries from our sorted collection
        return self.universe

    def OnData(self, data):
        
        # Return before trying to run a loop on empty list
        if not self.universe:
            return
        
        for symbol in self.universe:
            
            # is symbol iin Slice object? (do we even have data on this step for this asset)
            if not data.ContainsKey(symbol):
                return
            self.indicators[symbol].update_value(self.Time, data[symbol].Price)
            
                #continue
            
            #if data.ContainsKey(symbol):
            #self.indicators[symbol].update_value(self.Time, data[symbol].Price)
            #else:
            #    continue
            
            # new symbol? setup indicator object. Then update
            if symbol not in self.indicators:
                self.indicators[symbol] = SymbolData(symbol, self, self.atr_window)
                
            # update by bar
            #self.indicators[symbol].update_bar(data[symbol])
            #update by value
    
            
            #self.indicators[symbol].update_value(self.Time, data[symbol].Price)
            
            if self.IsWarmingUp: continue
            
            # now you can use logic to trade, random example:
            lowerband = self.indicators[symbol].get_atr()
            upperband = self.indicators[symbol].get_atr2()
            
            # Log the symbol, price & indicators
            self.Log(str(symbol) + " : " + str(self.indicators[symbol].get_atr()))
            self.Log("PRICE : {}".format(str(self.Securities[symbol].Price)))
            self.Log("UPPERBAND : {}".format(str(lowerband)))
            self.Log("LOWERBAND : {}".format(str(lowerband)))


    # this event fires whenever we have changes to our universe
    def OnSecuritiesChanged(self, changes):
        
        # liquidate removed securities
        for security in changes.RemovedSecurities:
            if security.Invested:
                self.Liquidate(security.Symbol)
                
                # clean up
                del self.indicators[security.Symbol]

class SymbolData(object):
    def __init__(self, symbol, context, window):
        self.symbol = symbol
        """
        I had to pass ATR from outside object to get it to work, could pass context and use any indica
        var atr = ATR(Symbol symbol, int period, MovingAverageType type = null, Resolution resolution = null, Func`2[Data.IBaseData,Data.Market.IBaseDataBar] selector = null)
        """
        self.window    = window
        #self.indicator = context.EMA(symbol, self.window)
        #self.indicator = context.BB(symbol, self.window)
        self.indicator = context.BB(symbol,10,2,MovingAverageType.Simple,Resolution.Daily)
        self.indicator2 = context.BB(symbol,20,1,MovingAverageType.Simple,Resolution.Daily)
        self.atr       = 0.0

    """
    Runtime Error: Python.Runtime.PythonException: NotSupportedException : AverageTrueRange does not support Update(DateTime, decimal) method overload. Use Update(IBaseDataBar) instead.
    """
    def update_bar(self, bar):
        self.indicator.Update(bar)
        
    def update_value(self, time, value):
        self.indicator.Update(time, value)
            
    def get_atr(self):
        #return self.indicator.Current.Value
        return self.indicator.LowerBand.Current.Value
        
    def get_atr2(self):
        #return self.indicator.Current.Value
        return self.indicator2.UpperBand.Current.Value