Indicators

Indicator Universes

Introduction

An indicator universe uses technical indicators to determine the constituents of the universe. Imagine a universe that only contains assets above their 10-day simple moving average. You can incorporate indicators into any of the types of universes in the Universes chapter. To create an indicator universe, define a helper class that contains the indicators and then define a universe that updates the indicators and selects assets.

Define SymbolData Objects

To make it easy to create and update indicators for each security in the universe, move the indicator logic into a class. In the universe definition, you can create an instance of this class for each security in the universe. The indicators you create in this class should be manual indicators so you can ensure they only update during universe selection.

class SymbolData(object):
    def __init__(self, symbol):
        self._symbol = symbol
        self.tolerance = 1.01
        self.fast = ExponentialMovingAverage(100)
        self.slow = ExponentialMovingAverage(300)
        self.is_uptrend = False
        self.scale = 0

    def update(self, time, value):
        if self.fast.update(time, value) and self.slow.update(time, value):
            fast = self.fast.current.value
            slow = self.slow.current.value
            self.is_uptrend = fast > slow * self.tolerance

        if self.is_uptrend:
            self.scale = (fast - slow) / ((fast + slow) / 2.0)
private class SelectionData
{
    public readonly ExponentialMovingAverage Fast;
    public readonly ExponentialMovingAverage Slow;

    public SelectionData()
    {
        Fast = new ExponentialMovingAverage(100);
        Slow = new ExponentialMovingAverage(300);
    }

    public decimal ScaledDelta
    {
        get { return (Fast - Slow)/((Fast + Slow)/2m); }
    }

    public bool Update(DateTime time, decimal value)
    {
        return Fast.Update(time, value) && Slow.Update(time, value);
    }
}

You need to use a SymbolData class instead of assigning the indicators to the Fundamental object because you can't create custom propertiesattributes on Fundamental objects like you can with Security objects.

Define the Universe

You need to define SymbolData objects before you define the universe that selects securities.

When your universe function receives an object that contains all the possible securities, create a SymbolData object for each new security and update the remaining SymbolData objects with their daily price or some other data point. For example, the following universe definition selects US Equities that have the greatest difference between two moving averages.

class EmaCrossUniverseSelectionAlgorithm(QCAlgorithm):

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

        self.set_start_date(2010,1,1)  #Set Start Date
        self.set_end_date(2015,1,1)    #Set End Date
        self.set_cash(100000)           #Set Strategy Cash
        self.universe_settings.asynchronous = True
        self.universe_settings.resolution = Resolution.DAILY
        self.universe_settings.leverage = 2

        self.count = 10
        self.averages = { }

        # this add universe method accepts two parameters:
        # - fundamental selection function: accepts an IEnumerable<Fundamental> and returns an IEnumerable<Symbol>
        self.add_universe(self.fundamental_selection_function)


    # sort the data by daily dollar volume and take the top 'NumberOfSymbols'
    def fundamental_selection_function(self, fundamental: List[Fundamental]) -> List[Symbol]:

        # We are going to use a dictionary to refer the object that will keep the moving averages
        for f in fundamental:
            if f.symbol not in self.averages:
                self.averages[f.symbol] = SymbolData(f.symbol)

            # Updates the SymbolData object with current EOD price
            avg = self.averages[f.symbol]
            avg.update(f.end_time, f.adjusted_price)

        # Filter the values of the dict: we only want up-trending securities
        values = list(filter(lambda x: x.is_uptrend, self.averages.values()))

        # Sorts the values of the dict: we want those with greater difference between the moving averages
        values.sort(key=lambda x: x.scale, reverse=True)

        for x in values[:self.count]:
            self.log('symbol: ' + str(x.symbol.value) + '  scale: ' + str(x.scale))

        # we need to return only the symbol objects
        return [ x.symbol for x in values[:self.count] ]
namespace QuantConnect.Algorithm.CSharp
{
    public class EmaCrossUniverseSelectionAlgorithm : QCAlgorithm
    {
        // tolerance to prevent bouncing
        const decimal Tolerance = 0.01m;
        private const int Count = 10;
        // use Buffer+Count to leave a little in cash
        private const decimal TargetPercent = 0.1m;
        private SecurityChanges _changes = SecurityChanges.None;
        // holds our fundamental indicators by symbol
        private readonly ConcurrentDictionary<Symbol, SelectionData> _averages = new ConcurrentDictionary<Symbol, SelectionData>();
    
        public override void Initialize()
        {
            UniverseSettings.Asynchronous = true;
            UniverseSettings.Leverage = 2.0m;
            UniverseSettings.Resolution = Resolution.Daily;
            SetStartDate(2010, 01, 01);
            SetEndDate(2015, 01, 01);
            SetCash(100*1000);

            AddUniverse(fundamental =>
            {
                return (from f in fundamental
                        // grab th SelectionData instance for this symbol
                        let avg = _averages.GetOrAdd(f.Symbol, sym => new SelectionData())
                        // Update returns true when the indicators are ready, so don't accept until they are
                        where avg.Update(f.EndTime, f.AdjustedPrice)
                        // only pick symbols who have their 50 day ema over their 100 day ema
                        where avg.Fast > avg.Slow*(1 + Tolerance)
                        // prefer symbols with a larger delta by percentage between the two averages
                        orderby avg.ScaledDelta descending
                        // we only need to return the symbol and return 'Count' symbols
                        select f.Symbol).Take(Count);
            });
        }
    }
}

You can also see our Videos. You can also get in touch with us via Discord.

Did you find this page helpful?

Contribute to the documentation: