Overall Statistics
Total Trades
0
Average Win
0%
Average Loss
0%
Compounding Annual Return
0%
Drawdown
0%
Expectancy
0
Net Profit
0%
Sharpe Ratio
0
Probabilistic Sharpe Ratio
0%
Loss Rate
0%
Win Rate
0%
Profit-Loss Ratio
0
Alpha
0
Beta
0
Annual Standard Deviation
0
Annual Variance
0
Information Ratio
0
Tracking Error
0
Treynor Ratio
0
Total Fees
$0.00
Estimated Strategy Capacity
$0
Lowest Capacity Asset
# region imports
from AlgorithmImports import *
# endregion

class UglyOrangeGuanaco(QCAlgorithm):

    def Initialize(self):
        self.SetStartDate(2020, 1, 2)
        self.SetEndDate(2020, 1, 3)
        self.SetCash(1000)
        self.SetTimeZone('America/New_York')
        
        # Universe Settings & Extended Market Hours
        self.AddUniverse(self.MyCoarseFilterFunction)
        self.UniverseSettings.Resolution = Resolution.Hour
        self.UniverseSettings.ExtendedMarketHours = True
        
        self.spy = self.AddEquity('SPY', Resolution.Hour)

        #schedule event to fire every day 10min after market open to loop through universe
        self.Schedule.On(self.DateRules.EveryDay("SPY"), 
                 self.TimeRules.AfterMarketOpen("SPY", 10),
                 self.EveryDayBeforeMarketClose)
    
    
        self.stateData = { }

    def MyCoarseFilterFunction(self, coarse):
        #copied from https://www.quantconnect.com/docs/algorithm-reference/universes
        #Take 10 stocks above their 200-Day EMA with more than $10 million daily trading volume
        # We are going to use a dictionary to refer the object that will keep the moving averages
        for c in coarse:
            if c.Symbol not in self.stateData:
                self.stateData[c.Symbol] = SelectionData(c.Symbol, 200)

            # Updates the SymbolData object with current EOD price
            avg = self.stateData[c.Symbol]
            avg.update(c.EndTime, c.AdjustedPrice, c.DollarVolume)

        # Filter the values of the dict to those above EMA and more than $10mil vol.
        values = [x for x in self.stateData.values() if x.is_above_ema and x.volume > 10000000]
        
        # sort by the largest in volume.
        values.sort(key=lambda x: x.volume, reverse=True)

        # we need to return only the symbol objects
        return [ x.symbol for x in values[:10] ]

    def OnData(self, data):
        
        
        # Track timestamps of market data being fed in
        if data.ContainsKey( 'SPY' ):
            if not self.Securities['SPY'].Exchange.Hours.IsOpen(self.Time, self.Time + timedelta(hours=1), False):
                self.Log( f'Extended Hours/ {self.Time}')
            else:
                self.Log( f'Market/ {self.Time}')


    def EveryDayAfterMarketOpen(self):
        self.Log("EveryDay.SPY 10 min after open: Fired at: {0}".format(self.Time))
        #Loop through symbols to see which one has increased the most
    
    def EveryDayBeforeMarketClose(self):
        pass


class SelectionData(object):
    def __init__(self, symbol, period):
        self.symbol = symbol
        self.ema = ExponentialMovingAverage(period)
        self.is_above_ema = False
        self.volume = 0

    def update(self, time, price, volume):
        self.volume = volume
        if self.ema.Update(time, price):
            self.is_above_ema = price > ema