Overall Statistics
Total Trades
1395
Average Win
4.06%
Average Loss
-0.48%
Compounding Annual Return
47.511%
Drawdown
18.800%
Expectancy
1.107
Net Profit
4026.749%
Sharpe Ratio
1.492
Probabilistic Sharpe Ratio
80.983%
Loss Rate
78%
Win Rate
22%
Profit-Loss Ratio
8.46
Alpha
0.246
Beta
1.318
Annual Standard Deviation
0.292
Annual Variance
0.085
Information Ratio
1.312
Tracking Error
0.222
Treynor Ratio
0.33
Total Fees
$104380.16
Estimated Strategy Capacity
$23000000.00
Lowest Capacity Asset
TMF UBTUG7D0B7TX
## T. Smith - Reductionist ROC comparison XLI-XLU - Faster trading - Long SPY only - Sharpe >1 since 1999 - Inspired by Vladimir & Peter Guenther

import numpy as np

class DualMomentumInOut(QCAlgorithm):

    def Initialize(self):

        self.SetStartDate(2012, 1, 1) 
        self.cap = 100000
        self.RETURN = 10 
       
        self.STK = self.AddEquity('TQQQ', Resolution.Minute).Symbol
        self.HDG_1 = self.AddEquity('TMF', Resolution.Minute).Symbol
        self.SVXY = self.AddEquity('SVXY',Resolution.Minute).Symbol
        
        self.XLI = self.AddEquity('XLI', Resolution.Hour).Symbol 
        self.XLU = self.AddEquity('XLU', Resolution.Hour).Symbol
        self.MKT = self.AddEquity('SPY', Resolution.Daily).Symbol 

        self.pairs = [self.XLI, self.XLU]
       
        self.wt = {}
        self.real_wt = {}
        self.mkt = []
        self.SetWarmUp(timedelta(350))
        
        self.AddEquity('SVXY',Resolution.Minute)
        res = Resolution.Daily
        self.uvxy = self.AddEquity('UVXY',res).Symbol
        self.bb = self.BB(self.uvxy,10,2,res)
        self.sma = self.SMA(self.uvxy,4,res)
        self.rc = self.RC(self.uvxy,6,0.3,res)
        self.trigger=False
        self.buy=False
        self.hold=False
        self.sell=False

        self.Schedule.On(self.DateRules.EveryDay(), self.TimeRules.Every(TimeSpan.FromMinutes(240)),
            self.daily_check)
            
        symbols = self.pairs
        for symbol in symbols:
            self.consolidator = TradeBarConsolidator(timedelta(hours=1))
            self.consolidator.DataConsolidated += self.consolidation_handler
            self.SubscriptionManager.AddConsolidator(symbol, self.consolidator)
        
        self.history = self.History(symbols, self.RETURN + 1, Resolution.Hour)
        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.RETURN + 1):] 
        
    def OnData(self, data):   
        #vix check
        
        if self.bb.IsReady and data.ContainsKey(self.uvxy) and self.sma.IsReady:
            vix=data[self.uvxy].Close
            if self.rc.UpperChannel.Current.Value<vix:
                self.trigger=True

            if self.trigger and self.sma.Current.Value>vix:
                self.buy=True

            if self.hold and (vix<(self.bb.MiddleBand.Current.Value-self.bb.StandardDeviation.Current.Value)):
                self.sell=True
                
            
        if self.buy and data.ContainsKey('SVXY'):
            self.wt[self.SVXY] = 0.2
            self.wt[self.uvxy] = 0
            self.trigger=False
            self.buy=False
            self.hold=True

        if data.ContainsKey('SVXY') and (self.sell or self.Portfolio['SVXY'].UnrealizedProfitPercent<-0.04):
            self.wt[self.SVXY] = 0
            self.wt[self.uvxy] = 0.2
            self.hold=False
            self.sell=False
            
        self.trade()
    
    def daily_check(self):
            
        #industrial utilities check
        
        r = self.history.pct_change(self.RETURN).iloc[-1]

        if (r[self.XLI] < r[self.XLU]):
            self.wt[self.STK] = 0.2
            self.wt[self.HDG_1] = 0.2
            self.trade()
        else:
            self.wt[self.STK] = 0.5
            self.wt[self.HDG_1] = 0.2
            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)
        
        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))