Overall Statistics
Total Trades
170
Average Win
0.16%
Average Loss
-0.14%
Compounding Annual Return
2.860%
Drawdown
2.800%
Expectancy
0.044
Net Profit
0.472%
Sharpe Ratio
0.433
Probabilistic Sharpe Ratio
39.815%
Loss Rate
52%
Win Rate
48%
Profit-Loss Ratio
1.19
Alpha
0.021
Beta
-0.348
Annual Standard Deviation
0.059
Annual Variance
0.004
Information Ratio
0.227
Tracking Error
0.168
Treynor Ratio
-0.074
Total Fees
$170.00
Estimated Strategy Capacity
$130000000.00
Lowest Capacity Asset
AMZN R735QTJ8XC9X
class LiquidUniverseSelection(QCAlgorithm):
    
    #self.lastDay = -1
    
    filteredByPrice = None
    changes = None
    
    #self.FirstDay = 0
    
    def SellAll(self):
        '''
        #self.MarkerOnCloseOrder.Liquidate()
        
        if self.FirstDay > 0:
            self.Liquidate()
            self.FirstDay = 0
        self.FirstDay = self.FirstDay + 1
        self.Debug(f"self.LastDay = {self.FirstDay} sstop")
        '''
        self.Liquidate()
        
    """
    def OnEndOfDay(self):
        self.Debug(f"self.LastDay = {self.FirstDay} sstop")
        if self.FirstDay > 0:
            self.Liquidate()
            self.FirstDay = 0
        self.FirstDay = self.FirstDay + 1
        # close up shop each day and reset our 'last' value so we start tomorrow fresh
        #self.Liquidate()
        #self.__last = None
    """    
    def __init__(self):
        
        self.FirstDay = 0
        
        #self.lastDay = -1
        #self.mom = []
        
        self.SetWarmUp(10, Resolution.Daily)
        self.SetSecurityInitializer(lambda x: x.SetMarketPrice(self.GetLastKnownPrice(x)))
        
        #self.SetExecution(ImmediateExecutionModel())
        
    def Initialize(self):
        self.SetStartDate(2019, 4, 8)  
        self.SetEndDate(2019, 6, 8) 
        self.SetCash(100000)  
        self.AddUniverse(self.CoarseSelectionFilter)
        self.SetAlpha(MOMAlphaModel())
        #self.AddAlpha(ConstantAlphaModel(InsightType.Price, InsightDirection.Up, timedelta(days=1), None, None))
        #self.SetPortfolioConstruction(InsightWeightingPortfolioConstructionModel())
        
        self.SetPortfolioConstruction( UnEqualWeightingPortfolioConstructionModel() )
        self.SetExecution(AndreExecutionModel())
        
        #self.Schedule.On(self.DateRules.EveryDay(), self.TimeRules.At(23, 59), Action(self.SellAll))
        #self.Schedule.On(self.DateRules.EveryDay(), self.TimeRules.At(10, 30), Action(self.BuyStop))
        #if (Time.TimeOfDay.TotalHours > 15.9) 
        #self.OnEndOfDay(Action(self.SellAll))
                    

        
        
        
        #self.SetPortfolioConstruction()
        
    def CoarseSelectionFilter(self, coarse):
        
        #EquityCountCoarseSelectionFilter = 0
        #self.Debug(f"EquityStartCountCoarseSelectionFilter = {EquityCountCoarseSelectionFilter}")
        
        for cf in coarse:
            symbol = cf.Symbol
            
            #EquityCountCoarseSelectionFilter = EquityCountCoarseSelectionFilter + 1
        #self.Debug(f"EquityEndCountCoarseSelectionFilter = {EquityCountCoarseSelectionFilter}")
        #1. Sort descending by daily dollar volume
        
        self.sortedByDollarVolume = sorted(coarse, key=lambda c: c.DollarVolume, reverse=True)
        
        #2. Select only Symbols 
        
        self.symbols_by_price = [c.Symbol for c in self.sortedByDollarVolume if c.Price > 10]
        
        #3. Return the 100 (3 for now) most liquid Symbols from the filteredByPrice list
        '''
        if len(self.symbols_by_price) < 100:
            self.Top100 = self.symbols_by_price[:len(self.symbols_by_price)]
        else:
            self.Top100 = self.symbols_by_price[:100]
        '''
        self.Top100 = self.symbols_by_price[:2]
        #self.Debug(f"NumberOfEquitiesInTop100 = {len(self.Top100)}")
        #self.Debug(f"TopOneInTop100 = {self.Top100[0]}")
        #self.Debug(f"TopOneInTop100 = {self.Top100[0]}")
        #self.Debug(f"BottemOneInTop100 = {self.Top100[-1]}")
        #self.Debug(f"OnUpdate({self.Time}:: ","ordered (sorted_mom=)",ordered)
        return self.Top100
    
    """    
    from datetime import timedelta
    """
   
   
class MOMAlphaModel(AlphaModel): 
    #self.lastDay = -1
    def __init__(self):
        self.mom = {}
        self.lastDay = -1
        #self.DailyMovingAverage
    
    def OnSecuritiesChanged(self, algorithm, changes):
        
    
        
        
        for security in changes.AddedSecurities:
            
           
        
            symbol = security.Symbol
            
            #algorithm.Debug(f"symbol= {symbol}")
            self.last_return = 0
            self.history = algorithm.History([symbol], 1, Resolution.Daily)
            if self.history.empty:
                continue
            algorithm.Debug(f"history.head(1)= {self.history.head(1)} stop_history")
            #algorithm.Debug("time=",self.Time)
            if self.history.iloc[0]["close"]:
                self.last_close = self.history.iloc[0]["close"] 
            else: self.last_close = 1
            #algorithm.Debug(f"self.last_close= {self.last_close} last_close_stop")
            if self.history.iloc[0]["open"]: 
                self.last_open = self.history.iloc[0]["open"] 
            else: self.last_open = 1
            #algorithm.Debug(f"self.last_open= {self.last_open} last_open_stop")
            self.last_return = (self.last_close - self.last_open) / self.last_open
            #algorithm.Debug(f"self.last_return= {self.last_return} last_return_stop")
            #algorithm.Debug(f"self.last_close= {self.last_close} last_close_stop")
            self.mom[symbol] = self.last_return
            algorithm.Debug(f"self.mom[{symbol}]= {self.mom[symbol]} self.mom_stop")
        for security in changes.RemovedSecurities:
            symbol = security.Symbol
            self.mom.pop(symbol, None)
            algorithm.Debug(f"popped= {symbol}")
            
        pass
         
    """ 
    def OnData(self,data):       
        for symbol in self.Data.keys():
            symbolData = self.Data[symbol]
            if symbolData.IsReady() and symbolData.WasJustUpdated(self.Time):
                # print the SMA value for each symbol 
                self.Log(str(symbol) + " SMA " + str(symbolData))    
    """
   
    def Update(self, algorithm, data):
        if algorithm.Time.day == self.lastDay: 
            return []
        
        self.lastDay = algorithm.Time.day

        symbols = self.mom.keys()
        #ordered = sorted(self.mom, key=lambda kv: self.mom[kv], reverse=True) 
        #algorithm.Debug(f"symbols[0]= {symbols[0]} stop_symbols")
        self.groep =[]
        self.total_weight=0
        
        for symbol in symbols:
            #self.history = algorithm.History([symbol], 1, Resolution.Daily)
            self.last_return = 0
            #algorithm.Debug(f"update_symbol= {symbol}_stop_update_symbol")
            self.history = algorithm.History([symbol], 1, Resolution.Daily)
            #algorithm.Debug(f"history.head(2)= {self.history.head(2)} update_stop_history")
            if self.history.empty:
                continue
            if self.history.iloc[0]["close"]: 
            #    pass
                self.last_close = self.history.iloc[0]["close"] 
            else: self.last_close = 1
            #algorithm.Debug(f"self.last_close= {self.last_close} last_close_stop_update")
            if self.history.iloc[0]["open"]: 
                self.last_open = self.history.iloc[0]["open"] 
            else: self.Last_open = 1
            #algorithm.Debug(f"self.last_open= {self.last_open} last_open_stop")
            self.last_return = (self.last_close - self.last_open) / self.last_open
            #algorithm.Debug(f"self.last_return= {self.last_return} _update_last_return_stop")
            #algorithm.Debug(f"self.last_close= {self.last_close} last_close_stop")
            self.mom[symbol] = self.last_return
            #algorithm.Debug(f"self.mom[{symbol}]= {self.mom[symbol]} self.mom_stop")
            direction = InsightDirection.Flat
            magnitude = self.last_return
            algorithm.Debug(f"magnitude= {magnitude} stop_magnitude")
            if magnitude > 0.00001: 
                direction = InsightDirection.Up
                algorithm.Debug(f"Up Up {direction} stop up")
            if magnitude < -0.00001: direction = InsightDirection.Down
            #alpha_magnitude = InsightWeight.magnitude
            #insights.append(Insight.Price(symbol, timedelta(1), direction, magnitude, None))
            self.total_weight = self.total_weight + magnitude
            
            #insight = Insight.Price("IBM", timedelta(minutes = 20), InsightDirection.Up, None, None, None, 0.25)
            visie=Insight.Price(symbol, timedelta(minutes = 2040), direction, None, None, None, magnitude)
            #algorithm.Debug(f"visie= {visie} stop_visie")
            #algorithm.Debug(f"slpha_magnitude= {alpha_magnitude} stop_alpha_magnitude")
            self.groep.append(visie)
            #algorithm.Debug(f"Insight.Groep= {self.groep} stop_insight_groep")
        return Insight.Group(self.groep)
        #self.SetPortfolioConstruction( UnEqualWeightingPortfolioConstructionModel() )
        #self.SetExecution(AndreExecutionModel())        
        
class AndreExecutionModel(ExecutionModel):
    
    def __init__(self):
        '''Initializes a new instance of the ImmediateExecutionModel class'''
        self.targetsCollection = PortfolioTargetCollection()
        self.lastDay = -1
    def Execute(self, algorithm, targets):
        '''Immediately submits orders for the specified portfolio targets.
        Args:
            algorithm: The algorithm instance
            targets: The portfolio targets to be ordered'''
        if algorithm.Time.day == self.lastDay: 
            return []
        
        self.lastDay = algorithm.Time.day
        # for performance we check count value, OrderByMarginImpact and ClearFulfilled are expensive to call
        self.targetsCollection.AddRange(targets)
        if self.targetsCollection.Count > 0:
            for target in self.targetsCollection.OrderByMarginImpact(algorithm):
                # calculate remaining quantity to be ordered
                quantity = OrderSizing.GetUnorderedQuantity(algorithm, target)
                if quantity != 0:
                    #self.MarketOnOpenOrder("IBM", 100)
                    algorithm.MarketOnCloseOrder(target.Symbol, .5*-quantity)
                    algorithm.MarketOnOpenOrder(target.Symbol, .5*quantity)
                    #algorithm.MarketOnCloseOrder(target.Symbol, .5*-quantity)
            self.targetsCollection.ClearFulfilled(algorithm)
            #algorithm.MarketOnCloseOrder.Liquidate()
    pass
    
class UnEqualWeightingPortfolioConstructionModel(PortfolioConstructionModel):
    def __init__(self):
        self.targets = []
        
    def CreateTargets(self, algorithm, insights):
        #target = PortfolioTarget.Percent(algorithm, "IBM", 0.1)
        if len(self.targets)>0:
            return self.targets
        total_weight = 0
        for insight in insights:
            total_weight = total_weight + insight.Weight
        for insight in insights:
            algorithm.Debug(f"insight= {insight} stop insight.")
            algorithm.Debug(f"insight.Symbol= {insight.Symbol} stop insight.Symbol.")
            algorithm.Debug(f"insight.Direction= {insight.Direction} stop insight.Direction.")
            algorithm.Debug(f"insight.Weight= {insight.Weight} stop insight.Weight.")
            #target = PortfolioTarget.Percent(algorithm, "IBM")
            target_weight = insight.Weight  / total_weight
            algorithm.Debug(f"target_weight= {target_weight} stop target_weight.")
            target = PortfolioTarget.Percent(algorithm, insight.Symbol, target_weight)
            if target_weight > 0.05:
                self.targets.append(target)
        return self.targets
        #pass    
    """
            tiepe = type(symbol)
            algorithm.Debug(f"type= {tiepe} stop_type")
            self.history = algorithm.History([symbol], 2, Resolution.Daily)
            algorithm.Debug(f"history_update= {self.history} stop_history_update")
            
            
            self.history = algorithm.History([symbol], 2, Resolution.Daily)
            closewaarde = self.history.iloc[0]["close"] 
            algorithm.Debug(f"symbol_in_update= {closewaarde} update_stop")
            
            symbolData = data[symbol]
            algorithm.Debug(f"symbolData_in_update= {symbolData} stop_symbolData")
        
            algorithm.Debug(f"data = {data} data_stop")
    """