Overall Statistics
Total Trades
135
Average Win
6.01%
Average Loss
-1.84%
Compounding Annual Return
13.788%
Drawdown
21.300%
Expectancy
2.191
Net Profit
1242.364%
Sharpe Ratio
0.942
Probabilistic Sharpe Ratio
29.160%
Loss Rate
25%
Win Rate
75%
Profit-Loss Ratio
3.28
Alpha
0.122
Beta
-0.001
Annual Standard Deviation
0.129
Annual Variance
0.017
Information Ratio
0.206
Tracking Error
0.218
Treynor Ratio
-222.719
Total Fees
$2156.54
"""
Intersection of ROC comparison using OUT_DAY approach by Vladimir

inspired by Peter Guenther, Tentor Testivis, Dan Whitnable, Thomas Chang.
"""
import numpy as np
# ------------------------------------
LEV = 1.0
# ------------------------------------

class DualMomentumInOut(QCAlgorithm):

    def Initialize(self):

        self.SetStartDate(2001, 1, 1) #IN_SAMPLE
        #self.SetEndDate(2010, 1, 1)
        
        #self.SetStartDate(2015, 1, 1) #OUT_SAMPLE
        
        self.cap = 100000
        self.VOLA = 128 #int(self.GetParameter('VOLA'))
        self.BASE_RET = 90 #int(self.GetParameter('BASE_RET'))
       

        
        self.STK = self.AddEquity('SPY', Resolution.Hour).Symbol
        self.BND = self.AddEquity('TLT', Resolution.Hour).Symbol

        self.ASSETS = [self.STK, self.BND]

        self.XLI = self.AddEquity('XLI', Resolution.Daily).Symbol 
        self.XLU = self.AddEquity('XLU', Resolution.Daily).Symbol

        self.MKT = self.AddEquity('SPY', Resolution.Daily).Symbol 

        self.pairs = [self.XLI, self.XLU]
        
        self.bull = 1        
        self.count = 0 
        self.outday = 0        
        self.wt = {}
        self.real_wt = {}
        self.mkt = []
        self.SetWarmUp(timedelta(350))

        self.Schedule.On(self.DateRules.EveryDay(), self.TimeRules.AfterMarketOpen('SPY', 0),
            self.daily_check)
            
        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, self.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[-(self.VOLA + 1):] 
        

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

        exit = (r[self.XLI] < r[self.XLU])

        if exit:
            self.bull = False
            self.outday = self.count
        if self.count >= self.outday + wait_days:
            self.bull = True
        self.count += 1

        if not self.bull:
            for sec in self.ASSETS:    
                self.wt[sec] = LEV if sec is self.BND else 0 
            self.trade() 

        elif self.bull:
            for sec in self.ASSETS:
                self.wt[sec] = LEV if sec is self.STK else 0 
            self.trade()  

                    
    def trade(self):

        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:
                self.SetHoldings(sec, weight)
            
                    
    def 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))