Overall Statistics
from Execution.ImmediateExecutionModel import ImmediateExecutionModel
from Portfolio.EqualWeightingPortfolioConstructionModel import EqualWeightingPortfolioConstructionModel

class AlphaFiveEnergyUniverse(QCAlgorithm):

    def Initialize(self):
        #1. Required: Five years of backtest history
        self.SetStartDate(2014, 1, 1) 
        
        #2. Required: Alpha Streams Models:
        self.SetBrokerageModel(BrokerageName.AlphaStreams)
        
        #3. Required: Significant AUM Capacity
        self.SetCash(1000000)
        
        #4. Select Desired ETF Universe
        # See more: https://www.quantconnect.com/docs/algorithm-reference/universes
        self.UniverseSettings.Resolution = Resolution.Hour
        self.SetUniverseSelection(EnergyETFUniverse()) 
        self.universe = { }
        
        #5. Set Relevent Benchmark
        self.reference = "XLE"
        self.AddEquity(self.reference, Resolution.Hour)
        self.SetBenchmark("SPY")

        # Demonstration: Consolidation
        # See more: https://www.quantconnect.com/docs/algorithm-reference/consolidating-data
        self.Consolidate(self.reference, CalendarType.Weekly, self.ConsolidationDemo)
        
        # Demonstration: Scheduled Events
        # See more: https://www.quantconnect.com/docs/algorithm-reference/scheduled-events
        self.Schedule.On(self.DateRules.Every(DayOfWeek.Monday), self.TimeRules.AfterMarketOpen(self.reference, 30), self.ScheduleDemo)
        
        # --------
        # Optional: Framework Algorithm Models
        self.SetPortfolioConstruction(EqualWeightingPortfolioConstructionModel())
        self.SetExecution(ImmediateExecutionModel())
        # --------
        
    def OnData(self, data):
        # Manually update the Indicators
        for symbol in self.universe.keys():
            if data.Bars.ContainsKey(symbol):
                self.universe[symbol].update(data[symbol].EndTime, data[symbol].Close)

    
    def ScheduleDemo(self):
        for symbol, assetData in self.universe.items():
            price = self.ActiveSecurities[symbol].Price
            if assetData.is_ready() and assetData.deviating(price):
                # Demonstration: Ensure to emit Insights to clearly signal intent to fund.
                self.EmitInsights(Insight.Price(symbol, timedelta(3), InsightDirection.Up))
                
    def ConsolidationDemo(self, bar):
        self.Debug(f'{self.Time} :: {bar.Time} {bar.Close}')
            
    # Initializing ETF Universe Securities
    def OnSecuritiesChanged(self, changes):
        for s in changes.AddedSecurities:
            if s.Symbol not in self.universe:
                history = self.History(s.Symbol, 30, Resolution.Hour)
                self.universe[s.Symbol] = AssetData(s.Symbol, history)

# Indicators+Universe Demonstration
class AssetData(object):
    def __init__(self, symbol, history):
        self.std = StandardDeviation(30)
        self.mean = SimpleMovingAverage(7) 
        
        for bar in history.itertuples():
            self.update(bar.Index[1], bar.open)
        
    def is_ready(self):
        return self.std.IsReady
        
    def update(self, time, price):
        self.std.Update(time, price)
        self.mean.Update(time, price)
        
    def deviating(self, price):
        if self.std.Current.Value == 0:
            return False
        return ( (price - self.mean.Current.Value) / self.std.Current.Value ) < -3