Overall Statistics
Total Trades
1152
Average Win
1.61%
Average Loss
-0.88%
Compounding Annual Return
33.953%
Drawdown
29.000%
Expectancy
0.687
Net Profit
4385.070%
Sharpe Ratio
1.256
Probabilistic Sharpe Ratio
64.431%
Loss Rate
40%
Win Rate
60%
Profit-Loss Ratio
1.82
Alpha
0.287
Beta
0.252
Annual Standard Deviation
0.248
Annual Variance
0.062
Information Ratio
0.762
Tracking Error
0.281
Treynor Ratio
1.236
Total Fees
$12180.71
'''
Intersection of ROC comparison using OUT_DAY approach by Vladimir v1.1 (diversified static lists)

inspired by Peter Guenther, Tentor Testivis, Dan Whitnable, Thomas Chang.
'''
import numpy as np
# -------------------------------------------------------------------------------------------
BONDS = ['TLT','TLH']; VOLA = 126; BASE_RET = 85; LEV = 0.99; 
# -------------------------------------------------------------------------------------------

class ROC_Comparison_IN_OUT(QCAlgorithm):

    def Initialize(self):

        self.SetStartDate(2008, 1, 1)
        # self.SetEndDate(2021, 1, 1)
        self.cap = 100000  
        
        self.STOCKS = [] # Selected using the universe selection
        self.BONDS = [self.AddEquity(ticker, Resolution.Minute).Symbol for ticker in BONDS]

        self.ASSETS = [self.STOCKS, self.BONDS]

        self.SLV = self.AddEquity('SLV', Resolution.Minute).Symbol  
        self.GLD = self.AddEquity('GLD', Resolution.Minute).Symbol  
        self.XLI = self.AddEquity('XLI', Resolution.Minute).Symbol 
        self.XLU = self.AddEquity('XLU', Resolution.Minute).Symbol
        self.DBB = self.AddEquity('DBB', Resolution.Minute).Symbol  
        self.UUP = self.AddEquity('UUP', Resolution.Minute).Symbol  
        self.MKT = self.AddEquity('SPY', Resolution.Minute).Symbol 

        self.pairs = [self.SLV, self.GLD, self.XLI, self.XLU, self.DBB, self.UUP]
        
        self.SetUniverseSelection(FineFundamentalUniverseSelectionModel(self.coarseSelector, self.fineSelector))
        self.UniverseSettings.Resolution = Resolution.Minute
        
        self.bull = 1        
        self.count = 0 
        self.outday = 0        
        self.wt = {}
        self.real_wt = {}
        self.mkt = []

        self.universeMonth = -1

        self.Schedule.On(self.DateRules.EveryDay(), self.TimeRules.AfterMarketOpen('SPY', 60),
            self.daily_check)
        self.Schedule.On(self.DateRules.EveryDay(), self.TimeRules.AfterMarketOpen('SPY', 120),
            self.trade)    
            
        symbols = [self.MKT] + self.pairs
        for symbol in symbols:
            self.consolidator = TradeBarConsolidator(timedelta(days=1))
            self.consolidator.DataConsolidated += self.consolidation_handler
            self.SubscriptionManager.AddConsolidator(symbol, self.consolidator)
        
        self.history = self.History(symbols, VOLA + 1, Resolution.Daily)
        if self.history.empty or 'close' not in self.history.columns:
            return
        self.history = self.history['close'].unstack(level=0).dropna()
        
        
    def consolidation_handler(self, sender, consolidated):
        self.history.loc[consolidated.EndTime, consolidated.Symbol] = consolidated.Close
        self.history = self.history.iloc[-(VOLA + 1):] 
        

    def daily_check(self):
        
        vola = self.history[[self.MKT]].pct_change().std() * np.sqrt(252)
        wait_days = int(vola * BASE_RET)
        period = int((1.0 - vola) * BASE_RET)        
        r = self.history.pct_change(period).iloc[-1]

        exit = ((r[self.SLV] < r[self.GLD]) and (r[self.XLI] < r[self.XLU]) and (r[self.DBB] < r[self.UUP]))

        if exit:
            self.bull = 0
            self.outday = self.count
        if self.count >= self.outday + wait_days:
            self.bull = 1
        self.count += 1
        
    def trade(self):    
        
        # Delete non-tradable stocks
        for sym in self.STOCKS:
            if self.Securities[sym].IsTradable == False:
                del self.Securities[sym]

        # Set all non-selected stocks as zero
        for pi in self.Portfolio.Values:
            eq = self.Symbol(str(pi.Symbol))
            if eq not in self.STOCKS:
                self.wt[eq] = 0.

        for  sec in self.STOCKS: 
            self.wt[sec] = LEV/len(self.STOCKS) if self.bull else 0;
        for  sec in self.BONDS: 
            self.wt[sec] = 0 if self.bull else LEV/len(self.BONDS);

        for mode in ['sell', 'buy']: # First sell, then buy to make sure there is margin
            for sec, weight in self.wt.items():
                if weight == 0 and self.Portfolio[sec].IsLong:
                    self.Liquidate(sec)
                
                cond1 = weight == 0 and self.Portfolio[sec].IsLong
                cond2 = weight > 0 and not self.Portfolio[sec].Invested
                if cond1 or cond2:
                    currentWeight = (self.Portfolio[sec].Quantity * self.Securities[sec].Price) / self.Portfolio.TotalPortfolioValue
                    if ((mode == 'buy' and weight > currentWeight) or
                        (mode == 'sell' and weight < currentWeight)):
                        self.SetHoldings(sec, weight)
                    
    def NOTINUSE_OnEndOfDay(self): 
        
        mkt_price = self.Securities[self.MKT].Close
        self.mkt.append(mkt_price)
        mkt_perf = self.mkt[-1] / self.mkt[0] * self.cap
        self.Plot('Strategy Equity', 'SPY', mkt_perf)
        
        account_leverage = self.Portfolio.TotalHoldingsValue / self.Portfolio.TotalPortfolioValue
        self.Plot('Holdings', 'leverage', round(account_leverage, 1))
        for sec, weight in self.wt.items(): 
            self.real_wt[sec] = round(self.ActiveSecurities[sec].Holdings.Quantity * self.Securities[sec].Price / self.Portfolio.TotalPortfolioValue,4)
            self.Plot('Holdings', self.Securities[sec].Symbol, round(self.real_wt[sec], 3))
            
    def coarseSelector(self, coarse):
        
        if self.Time.month == self.universeMonth:
            return self.STOCKS

        eqs = [x for x in coarse if (x.HasFundamentalData == True)]
        eqs_volume_sorted = sorted(eqs, key=lambda x: x.DollarVolume, reverse=True)
        
        # Top 1000 in stock volume
        top = eqs_volume_sorted[:1000]
        # self.Debug(f"{self.Time} Coarse: {len(eqs)} => {len(top)}")
        
        top_eqs = [x.Symbol for x in top]
        
        return top_eqs

    def fineSelector(self, fine):

        if self.Time.month == self.universeMonth:
            return self.STOCKS
            
        # No idea what class fine is, len or shape do not work
        fineLen = 0
        for i in fine:
            fineLen += 1
    
        tech = [x for x in fine if x.AssetClassification.MorningstarSectorCode == MorningstarSectorCode.Technology]
        selected_symbols = [str(x.Symbol) for x in tech]
        
        hist = self.History(selected_symbols, 21 * 12, Resolution.Daily)
        o = hist['open'].unstack(level=0)
        
        # Pure Profit
        scores = o.ix[-1] / o.ix[0] - 1.
        
        # Sharpe
        # scores = (o.ix[-1] / o.ix[0] - 1.) / o.std()

        companyCount = 10
        
        top_eqs = scores.sort_values(ascending=False)[:companyCount]
        self.STOCKS = [self.Symbol(str(x)) for x in top_eqs.index]
        # self.Debug(f"{self.Time} Fine: selecting {fineLen} => {scores.shape[0]} => {len(self.STOCKS)}")
        
        self.universeMonth = self.Time.month
        
        return self.STOCKS