Overall Statistics
Total Trades
31
Average Win
0.11%
Average Loss
-0.10%
Compounding Annual Return
1537.872%
Drawdown
3.200%
Expectancy
-0.176
Net Profit
3.112%
Sharpe Ratio
53.028
Probabilistic Sharpe Ratio
100.000%
Loss Rate
60%
Win Rate
40%
Profit-Loss Ratio
1.06
Alpha
3.889
Beta
2.928
Annual Standard Deviation
0.113
Annual Variance
0.013
Information Ratio
66.81
Tracking Error
0.079
Treynor Ratio
2.045
Total Fees
$45.72
Estimated Strategy Capacity
$7800000.00
Lowest Capacity Asset
ETHCY R735QTJ8XC9X
class LiquidUniverseSelection(QCAlgorithm):
       
    filteredByPrice = None
    changes = None
    

    
    def SellAll(self):
        
        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 __init__(self):
        
        self.FirstDay = 0

        
        self.SetWarmUp(10, Resolution.Daily)
        self.SetSecurityInitializer(lambda x: x.SetMarketPrice(self.GetLastKnownPrice(x)))
        

    def Initialize(self):
        self.SetStartDate(2019, 1, 8)  
        self.SetEndDate(2019, 1, 12) 
        self.SetCash(100000)  
        self.AddUniverse(self.CoarseSelectionFilter)
        self.SetAlpha(MOMAlphaModel())
        

        
        self.SetPortfolioConstruction( UnEqualWeightingPortfolioConstructionModel() )
        self.SetExecution(AndreExecutionModel())
        
    def CoarseSelectionFilter(self, coarse):
        

        
        for cf in coarse:
            symbol = cf.Symbol
        
        self.sortedByDollarVolume = sorted(coarse, key=lambda c: c.DollarVolume, reverse=True)
        
        
        self.symbols_by_price = [c.Symbol for c in self.sortedByDollarVolume if c.Price > 10]
        
        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]

        return self.Top100
    
  
   
   
class MOMAlphaModel(AlphaModel): 
    #self.lastDay = -1
    def __init__(self):
        self.mom = {}
        self.lastDay = -1
    def OnSecuritiesChanged(self, algorithm, changes):
        
    
        
        
        for security in changes.AddedSecurities:
            symbol = security.Symbol
            self.last_return = 0
            self.history = algorithm.History([symbol], 1, Resolution.Daily)
            if self.history.empty:
                return
            algorithm.Debug(f"history.head(1)= {self.history.head(1)} stop_history")
            if self.history.iloc[0]["close"]:
                self.last_close = self.history.iloc[0]["close"] 
            else: self.last_close = 1
            if self.history.iloc[0]["open"]: 
                self.last_open = self.history.iloc[0]["open"] 
            else: self.last_open = 1
            self.last_return = (self.last_close - self.last_open) / self.last_open
            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
            algorithm.Liquidate(symbol)
            self.mom.pop(symbol, None)
            algorithm.Debug(f"popped= {symbol}")
        pass
    
   
    def Update(self, algorithm, data):
        if algorithm.Time.day == self.lastDay: 
            return []
        
        self.lastDay = algorithm.Time.day

        symbols = self.mom.keys()
        
        self.groep =[]
        self.total_weight=0
        
        for symbol in symbols:
            self.last_return = 0
            self.history = algorithm.History([symbol], 1, Resolution.Daily)
            if self.history.empty:
                continue
            if self.history.iloc[0]["close"]: 
                self.last_close = self.history.iloc[0]["close"] 
            else: self.last_close = 1
            if self.history.iloc[0]["open"]: 
                self.last_open = self.history.iloc[0]["open"] 
            else: self.Last_open = 1
            
            self.last_return = (self.last_close - self.last_open) / self.last_open
            
            self.mom[symbol] = self.last_return
            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
           
            self.total_weight = self.total_weight + magnitude
            
           
            visie=Insight.Price(symbol, timedelta(minutes = 2040), direction, None, None, None, magnitude)
            
            self.groep.append(visie)
           
        return Insight.Group(self.groep)
              
        
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
        self.targetsCollection.AddRange(targets)
        if self.targetsCollection.Count > 0:
            for target in self.targetsCollection.OrderByMarginImpact(algorithm):
                quantity = OrderSizing.GetUnorderedQuantity(algorithm, target)
                if quantity != 0:
                    #self.MarketOnOpenOrder("IBM", 100)
                    algorithm.MarketOnOpenOrder(target.Symbol, quantity)
                    algorithm.MarketOnCloseOrder(target.Symbol, -quantity)
            self.targetsCollection.ClearFulfilled(algorithm)
    pass
    
class UnEqualWeightingPortfolioConstructionModel(PortfolioConstructionModel):
    def __init__(self):
        self.targets = []
        
    def CreateTargets(self, algorithm, insights):
        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