Overall Statistics
from AlgorithmImports import *

class ExtractAlphaEstimizeAlgorithm(QCAlgorithm):

    def Initialize(self):
        self.SetStartDate(2019, 1, 1)
        self.SetEndDate(2019, 2, 1)
        self.SetCash(100000)
        
        self.time = datetime.min
        
        self.AddUniverse(self.MyCoarseFilterFunction)
        self.UniverseSettings.Resolution = Resolution.Minute
        
    def MyCoarseFilterFunction(self, coarse):
        sorted_by_dollar_volume = sorted([x for x in coarse if x.HasFundamentalData and x.Price > 4], 
                                key=lambda x: x.DollarVolume, reverse=True)
        selected = [x.Symbol for x in sorted_by_dollar_volume[:500]]
        return selected

    def OnData(self, data):
        if self.time > self.Time: return
    
        # Accessing Data
        consensus = data.Get(EstimizeConsensus)
        estimate = data.Get(EstimizeEstimate)
        release = data.Get(EstimizeRelease)
        
        if not estimate: return
        
        sorted_by_eps_estimate = sorted([x for x in estimate.items() if x[1].Eps], key=lambda x: x[1].Eps)
        long_symbols = [x[0].Underlying for x in sorted_by_eps_estimate[-10:]]
        short_symbols = [x[0].Underlying for x in sorted_by_eps_estimate[:10]]
        
        for symbol in [x.Symbol for x in self.Portfolio.Values if x.Invested]:
            if symbol not in long_symbols + short_symbols:
                self.Liquidate(symbol)
        
        long_targets = [PortfolioTarget(symbol, 0.05) for symbol in long_symbols]
        short_targets = [PortfolioTarget(symbol, -0.05) for symbol in short_symbols]
        self.SetHoldings(long_targets + short_targets)
        
        self.time = Expiry.EndOfMonth(self.Time)
        
    def OnSecuritiesChanged(self, changes):
        for security in changes.AddedSecurities:
            # Requesting Data
            estimize_consensus_symbol = self.AddData(EstimizeConsensus, security.Symbol).Symbol
            estimize_estimate_symbol = self.AddData(EstimizeEstimate, security.Symbol).Symbol
            estimize_release_symbol = self.AddData(EstimizeRelease, security.Symbol).Symbol

            # Historical Data
            history = self.History([estimize_consensus_symbol,
                                    estimize_estimate_symbol,
                                    estimize_release_symbol
                                    ], 10, Resolution.Daily)
            self.Debug(f"We got {len(history)} items from our history request")