Overall Statistics |
Total Trades 14 Average Win 7.58% Average Loss -0.72% Compounding Annual Return 273.796% Drawdown 22.100% Expectancy 6.699 Net Profit 64.285% Sharpe Ratio 4.3 Probabilistic Sharpe Ratio 77.382% Loss Rate 33% Win Rate 67% Profit-Loss Ratio 10.55 Alpha 1.452 Beta 3.788 Annual Standard Deviation 0.592 Annual Variance 0.351 Information Ratio 4.693 Tracking Error 0.481 Treynor Ratio 0.672 Total Fees $14.85 Estimated Strategy Capacity $36000.00 Lowest Capacity Asset UTSL WK7PAZG36KIT |
import numpy as np from QuantConnect.Python import PythonQuandl # ------------------------------------------------------------------ STK = ['QQQ']; BND = ['TLT']; VOLA = 126; BASE_RET = 85; LEV = 1.00; PAIRS = ['SLV', 'GLD', 'XLI', 'XLU', 'DBB', 'UUP'] # ------------------------------------------------------------------ class QuandlImporterAlgorithm(QCAlgorithm): def Initialize(self): #self.SetEndDate(2021, 3, 4) self.cap = 10000 self.SetCash(self.cap) self.quandlCode = "OECD/KEI_LOLITOAA_OECDE_ST_M" ## Optional argument - personal token necessary for restricted dataset #Quandl.SetAuthCode("PrzwuZR28Wqegvv1sdJ7") self.SetStartDate(2021, 1, 1) #Set Start Date #self.SetEndDate(2020,1,1) #Set End Date self.SetWarmup(100) self.SetBenchmark("SPY") self.init = True self.kei = self.AddData(QuandlCustomColumns, self.quandlCode, Resolution.Daily, TimeZones.NewYork).Symbol self.sma = self.SMA(self.kei, 1) self.mom = self.MOMP(self.kei, 2) #self.SPY = self.AddEquity('SPY', Resolution.Daily).Symbol self.stock = self.AddEquity('QQQ', Resolution.Hour).Symbol self.bond = self.AddEquity('TLT', Resolution.Hour).Symbol self.STK = self.AddEquity('QQQ', Resolution.Minute).Symbol self.BND = self.AddEquity('TLT', Resolution.Minute).Symbol self.ASSETS = [self.STK, self.BND] self.SLV = self.AddEquity('SLV', Resolution.Daily).Symbol self.GLD = self.AddEquity('GLD', Resolution.Daily).Symbol self.XLI = self.AddEquity('XLI', Resolution.Daily).Symbol self.XLU = self.AddEquity('XLU', Resolution.Daily).Symbol self.DBB = self.AddEquity('DBB', Resolution.Daily).Symbol self.UUP = self.AddEquity('UUP', Resolution.Daily).Symbol self.MKT = self.AddEquity('SPY', Resolution.Daily).Symbol self.pairs = [self.SLV, self.GLD, self.XLI, self.XLU, self.DBB, self.UUP] self.symbols = ['FAS', 'ERX', 'UYM', 'DUSL', 'WANT', 'UGE', 'UTSL', 'TECL', 'CURE', 'TENG', 'XLRE'] #Leverged 3x self.XLF = self.AddEquity('FAS', Resolution.Hour).Symbol self.XLE = self.AddEquity('ERX', Resolution.Hour).Symbol self.XLB = self.AddEquity('UYM', Resolution.Hour).Symbol self.XLI = self.AddEquity('DUSL', Resolution.Hour).Symbol self.XLY = self.AddEquity('WANT', Resolution.Hour).Symbol self.XLP = self.AddEquity('UGE', Resolution.Hour).Symbol self.XLU = self.AddEquity('UTSL', Resolution.Hour).Symbol self.XLK = self.AddEquity('TECL', Resolution.Hour).Symbol self.XLV = self.AddEquity('CURE', Resolution.Hour).Symbol self.XLC = self.AddEquity('TENG', Resolution.Hour).Symbol self.XLRE = self.AddEquity('XLRE', Resolution.Hour).Symbol #self.Schedule.On(self.DateRules.WeekStart(self.stock), self.TimeRules.AfterMarketOpen(self.stock, 31), # self.Rebalance) 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.stock), self.TimeRules.AfterMarketOpen(self.stock, 1), self.Rebalance) self.Schedule.On(self.DateRules.EveryDay(), self.TimeRules.AfterMarketOpen('SPY', 100), 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, 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 = 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)) def Rebalance(self): if self.IsWarmingUp or not self.mom.IsReady or not self.sma.IsReady: return initial_asset = self.stock if self.mom.Current.Value > 0 else self.bond if self.init: self.SetHoldings(initial_asset, 1) self.init = False keihist = self.History([self.kei], 1400) #keihist = keihist['Value'].unstack(level=0).dropna() keihistlowt = np.nanpercentile(keihist, 15) keihistmidt = np.nanpercentile(keihist, 50) keihisthight = np.nanpercentile(keihist, 90) kei = self.sma.Current.Value keimom = self.mom.Current.Value if (keimom < 0 and kei < keihistmidt and kei > keihistlowt) and not (self.Securities[self.XLP].Invested): # DECLINE self.Liquidate() self.SetHoldings(self.XLP, .5) self.SetHoldings(self.XLV, .5) #self.SetHoldings(self.bond, 1) self.Debug("STAPLES {0} >> {1}".format(self.XLP, self.Time)) elif (keimom > 0 and kei < keihistlowt) and not (self.Securities[self.XLB].Invested): # RECOVERY self.Liquidate() self.SetHoldings(self.XLB, .5) self.SetHoldings(self.XLY, .5) self.Debug("MATERIALS {0} >> {1}".format(self.XLB, self.Time)) elif (keimom > 0 and kei > keihistlowt and kei < keihistmidt) and not (self.Securities[self.XLE].Invested): # EARLY self.Liquidate() self.SetHoldings(self.XLE, .33) self.SetHoldings(self.XLF, .33) self.SetHoldings(self.XLI, .33) self.Debug("ENERGY {0} >> {1}".format(self.XLE, self.Time)) elif (keimom > 0 and kei > keihistmidt and kei < keihisthight) and not (self.Securities[self.XLU].Invested): # REBOUND self.Liquidate() self.SetHoldings(self.XLK, .5) self.SetHoldings(self.XLU, .5) self.Debug("UTILITIES {0} >> {1}".format(self.XLU, self.Time)) elif (keimom < 0 and kei < keihisthight and kei > keihistmidt) and not (self.Securities[self.XLK].Invested): # LATE self.Liquidate() self.SetHoldings(self.XLK, .5) self.SetHoldings(self.XLC, .5) self.Debug("INFO TECH {0} >> {1}".format(self.XLK, self.Time)) elif (keimom < 0 and kei < 100 and not self.Securities[self.bond].Invested): self.Liquidate() self.SetHoldings(self.bond, 1) self.Plot("LeadInd", "SMA(LeadInd)", self.sma.Current.Value) self.Plot("LeadInd", "THRESHOLD", 100) self.Plot("MOMP", "MOMP(LeadInd)", self.mom.Current.Value) self.Plot("MOMP", "THRESHOLD", 0) class QuandlCustomColumns(PythonQuandl): def __init__(self): # Define ValueColumnName: cannot be None, Empty or non-existant column name self.ValueColumnName = "Value"