Overall Statistics
Total Trades
64
Average Win
0.25%
Average Loss
-0.20%
Compounding Annual Return
-8.786%
Drawdown
7.000%
Expectancy
0.291
Net Profit
-1.127%
Sharpe Ratio
-0.294
Loss Rate
42%
Win Rate
58%
Profit-Loss Ratio
1.22
Alpha
-0.047
Beta
-0.401
Annual Standard Deviation
0.203
Annual Variance
0.041
Information Ratio
-0.356
Tracking Error
0.253
Treynor Ratio
0.149
Total Fees
$64.00
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, 2, 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 = 10
        self.UniverseSettings.MinimumTimeInUniverse = self.atr_window
        self.SetWarmUp(self.atr_window)

        # this add universe method accepts two parameters:
        self.AddUniverse(self.CoarseSelectionFunction, self.FineSelectionFunction)
        
        # Set dictionary of indicators
        self.indicators = {}

        self.__numberOfSymbols     = 100
        self.__numberOfSymbolsFine = 10
        
        
    def OnData(self, data):
    
        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):
                continue
            
            # new symbol? setup indicator object. Then update
            if symbol not in self.indicators:
                self.indicators[symbol] = SymbolData(symbol, self, self.atr_window)
            self.indicators[symbol].update(data[symbol])
            
            if self.IsWarmingUp: continue
            
            self.Log(str(symbol) + " : " + str(self.indicators[symbol].get_atr()))
    
            # now you can use logic to trade, random example:
            atr = self.indicators[symbol].get_atr()
            if atr != 0.0: # maybe a new symbol gets added and isnt ready yet?
                if atr >= 3.0:
                    self.SetHoldings(symbol, -0.1)
                else:
                    self.Liquidate(symbol)
            

    # 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.OperationRatios.OperationMargin.Value, reverse=False)
        
        # resulting symbols
        self.universe = [ x.Symbol for x in sortedByPeRatio[:self.__numberOfSymbolsFine] ]

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


    # 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.ATR(symbol, self.window)
        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(self, bar):
        self.indicator.Update(bar)
            
    def get_atr(self):
        return self.indicator.Current.Value