Overall Statistics
Total Trades
24
Average Win
3.26%
Average Loss
-3.64%
Compounding Annual Return
-77.128%
Drawdown
28.900%
Expectancy
-0.311
Net Profit
-10.580%
Sharpe Ratio
-0.59
Probabilistic Sharpe Ratio
28.241%
Loss Rate
64%
Win Rate
36%
Profit-Loss Ratio
0.89
Alpha
1.109
Beta
2.693
Annual Standard Deviation
0.85
Annual Variance
0.723
Information Ratio
0.143
Tracking Error
0.672
Treynor Ratio
-0.186
Total Fees
$966.59
Estimated Strategy Capacity
$30000.00
Lowest Capacity Asset
USD TPT7KXW4PVMT
Portfolio Turnover
70.35%
from AlgorithmImports import *
import math
import pandas as pd
from cmath import sqrt
from clr import AddReference
AddReference("System")
AddReference("QuantConnect.Algorithm")
AddReference("QuantConnect.Common")

from System import *
from QuantConnect import *
from QuantConnect.Algorithm import *
from QuantConnect.Data.Custom import *
from QuantConnect.Python import PythonData


class IntelligentSkyDoge(QCAlgorithm):
   
    def Initialize(self):

        self.cash = 100000
        self.buffer_pct = 0.03 # CHANGE YOUR THRESHOLD HERE
        self.SetStartDate(2018, 12, 1)
        self.SetEndDate(2018, 12, 28)
        self.SetCash(self.cash)
        self.equities = ['UPRO', 'SPY', 'TQQQ', 'TECL', 'SOXL', 'TECS', 'SOXS', 'SQQQ', 'SPXU', 'ERX', 'EUO', 'YCS', 'EWZ', 'MVV', 'USD', 'DBC', 'UVXY', 'BIL', 'IEF', 'UUP', 'TMF', 'UCO', 'SPXL', 'QLD', 'SHY', 'GLD', 'SPXS', 'EPI', 'TMV', 'IYK', 'QQQ', 'TLT', 'CURE', 'DIG', 'EEM', 'VIXY', 'BSV', 'SPHB', 'AGG', 'XLU', 'EFA']

        self.MKT = self.AddEquity("SPY", Resolution.Daily).Symbol
        self.mkt = []
        for equity in self.equities:
            self.AddEquity(equity, Resolution.Minute)
            self.Securities[equity].SetDataNormalizationMode(DataNormalizationMode.Adjusted)
        
        self.PT1 = 0.94
        self.PT2 = 0.0
        self.PT3 = 0.0

        self.HT1 = {str(i).zfill(2): 0 for i in range(1, 21)}
        self.HTS1 = {str(i).zfill(2): [] for i in range(1, 21)}

        self.Schedule.On(self.DateRules.EveryDay("SPY"),
                self.TimeRules.BeforeMarketClose("SPY", 2),
                self.FunctionBeforeMarketClose)

    def RSI(self, equity, period):
        extension = min(period*5, 250)
        r_w = RollingWindow[float](extension)
        history = self.History(equity, extension - 1, Resolution.Daily)
        for historical_bar in history:
            r_w.Add(historical_bar.Close)
        while r_w.Count < extension:
            current_price = self.Securities[equity].Price
            r_w.Add(current_price)
        if r_w.IsReady:
            average_gain = 0
            average_loss = 0
            gain = 0
            loss = 0
            for i in range(extension - 1, extension - period -1, -1):
                gain += max(r_w[i-1] - r_w[i], 0)
                loss += abs(min(r_w[i-1] - r_w[i], 0))
            average_gain = gain/period
            average_loss = loss/period
            for i in range(extension - period - 1, 0, -1):
                average_gain = (average_gain*(period-1) + max(r_w[i-1] - r_w[i], 0))/period
                average_loss = (average_loss*(period-1) + abs(min(r_w[i-1] - r_w[i], 0)))/period
            if average_loss == 0:
                return 100
            else:
                rsi = 100 - (100/(1 + average_gain / average_loss))
                return rsi
        else:
            return None

    def CumReturn(self, equity, period):
        history = self.History(equity, period, Resolution.Daily)
        closing_prices = pd.Series([bar.Close for bar in history])
        current_price = self.Securities[equity].Price
        closing_prices = closing_prices.append(pd.Series([current_price]))
        first_price = closing_prices.iloc[0]
        if first_price == 0:
            return None
        else:
            return_val = (current_price / first_price) - 1
            return return_val


    def STD(self, equity, period):
        r_w = RollingWindow[float](period + 1)
        r_w_return = RollingWindow[float](period)
        history = self.History(equity, period, Resolution.Daily)
        for historical_bar in history:
            r_w.Add(historical_bar.Close)
        while r_w.Count < period + 1:
            current_price = self.Securities[equity].Price
            r_w.Add(current_price)
        for i in range (period, 0, -1):
            daily_return = (r_w[i-1]/r_w[i] - 1)
            r_w_return.Add(daily_return)
        dfstd = pd.DataFrame({'r_w_return':r_w_return})       
        if r_w.IsReady:
            std = dfstd['r_w_return'].std()
            if std == 0:
                return 0
            else:
                return std
        else:
            return 0

    def MaxDD(self, equity, period):

        history = self.History(equity, period - 1, Resolution.Daily)     
        closing_prices = pd.Series([bar.Close for bar in history])
        current_price = self.Securities[equity].Price
        closing_prices = closing_prices.append(pd.Series([current_price]))
        rolling_max = closing_prices.cummax()
        drawdowns = (rolling_max - closing_prices) / rolling_max
        max_dd = drawdowns.min()
        return max_dd


    def SMA(self, equity, period):
        r_w = RollingWindow[float](period)
        history = self.History(equity, period - 1, Resolution.Daily)
        for historical_bar in history:
            r_w.Add(historical_bar.Close)
        while r_w.Count < period:
            current_price = self.Securities[equity].Price
            r_w.Add(current_price)        
        if r_w.IsReady:
            sma = sum(r_w) / period
            return sma
        else:
            return 0
           
    def IV(self, equity, period):
        r_w = RollingWindow[float](period + 1)
        r_w_return = RollingWindow[float](period)
        history = self.History(equity, period, Resolution.Daily)
        for historical_bar in history:
            r_w.Add(historical_bar.Close)
        while r_w.Count < period + 1:
            current_price = self.Securities[equity].Price
            r_w.Add(current_price)
        for i in range (period, 0, -1):
            if r_w[i] == 0:
                return 0
            else:
                daily_return = (r_w[i-1]/r_w[i] - 1)
                r_w_return.Add(daily_return)
        dfinverse = pd.DataFrame({'r_w_return':r_w_return})       
        if r_w.IsReady:
            STD = dfinverse['r_w_return'].STD()
            if STD == 0:
                return 0
            else:
                inv_vol = 1 / STD
                return inv_vol
        else:
            return 0

    def SMADayRet(self, equity, period):
        r_w = RollingWindow[float](period + 1)
        r_w_return = RollingWindow[float](period)
        history = self.History(equity, period, Resolution.Daily)
        for historical_bar in history:
            r_w.Add(historical_bar.Close)
        while r_w.Count < period + 1:
            current_price = self.Securities[equity].Price
            r_w.Add(current_price)
        for i in range (period, 0, -1):
            if r_w[i] == 0:
                return None
            daily_return = (r_w[i-1]/r_w[i] - 1)
            r_w_return.Add(daily_return)
        if r_w.IsReady:
            smareturn = sum(r_w_return) / period
            return smareturn
        else:
            return 0

    def EMA(self, equity, period):
        extension = period + 50
        r_w = RollingWindow[float](extension)
        history = self.History(equity, extension - 1, Resolution.Daily)
        for historical_bar in history:
            r_w.Add(historical_bar.Close)
        while r_w.Count < extension:
            current_price = self.Securities[equity].Price
            r_w.Add(current_price)
        if r_w.IsReady:
            total_price = 0
            for i in range(extension - 1, extension - period - 2, -1):
                total_price += r_w[i]
            average_price = total_price/period
            for i in range(extension - period - 2, -1, -1):
                average_price = r_w[i]*2/(period+1) + average_price*(1-2/(period+1))

            return average_price
        else:
            return None

    def Sort(self, sort_type, equities, period, reverse, number, multiplier):
        self.PT = getattr(self, f"PT{number}") * multiplier
        returns = {}
        for equity in equities:
            returns[equity] = getattr(self, sort_type)(equity, period)
        s_e = sorted([item for item in returns.items() if item[1] is not None], key = lambda x: x[1], reverse = reverse)
        t3e = s_e[:1]
        ht = getattr(self, f"HT{number}")
        hts = getattr(self, f"HTS{number}")
        for i in ht.keys():
            if ht[i] == 0:
                ht[i] = self.PT
                hts[i].append(t3e[0][0])
                break
        setattr(self, f"HT{number}", ht)
        setattr(self, f"HTS{number}", hts)


    def AppendHolding(self, equity, PTnumber, HTnumber, multiplier):
        HT = getattr(self, f"HT{HTnumber}")
        HTS = getattr(self, f"HTS{HTnumber}")
        PT = getattr(self, f"PT{PTnumber}") * multiplier
        for i in HT.keys():
            if HT[i] == 0:
                HT[i] = PT
                HTS[i].append(equity)
                break

    def OnData (self, data):
        pass
   
    def FunctionBeforeMarketClose(self):

        mkt_price = self.History(self.MKT, 2, Resolution.Daily)['close'].unstack(level= 0).iloc[-1]
        self.mkt.append(mkt_price)
        mkt_perf = self.cash * self.mkt[-1] / self.mkt[0]
        self.Plot('Strategy Equity', self.MKT, mkt_perf)

        self.DereckCustomBetaBaller()
        self.ExecuteTrade()

    def DereckCustomBetaBaller(self):

        if self.SMADayRet('TLT', 350) < self.SMADayRet('TLT', 550):
            if self.Securities['SPY'].Price < self.SMA('SPY', 200):
                self.V320BetaBaller()
            else:
                self.BullStockMarket()
        else:
            self.NewApollo()

    def V320BetaBaller(self):
        if self.RSI('BIL', 8) < 35:
            if self.RSI('TQQQ', 10) > 80:
                self.OverboughtSP()
            else:
                self.AppendHolding('SOXL', 1, 1, 1)

        else:
            if self.RSI('SPY', 6) < 27:
                self.ExtremelyoversoldSP() 
            else:
                self.BearStockMarket()

    def OverboughtSP(self):

        self.Sort("RSI",["UVXY", "VIXY"],13,False, 1, 1)

    def ExtremelyoversoldSP(self):

        if self.RSI('BSV', 7) < self.RSI('SPHB', 7):
            self.Sort("RSI",["SOXS", "SOXS"],7,False, 1, 1)
        else:
           self.Sort("RSI",["SOXL", "TECL"],7,False, 1, 1)
 
    def BearStockMarket(self):

        if self.RSI('BSV', 7) > self.RSI('SHY', 7):
            self.BearStockMarketSTRIPPED331()
        else:
            self.AppendHolding('SOXL', 1, 1, 1)

    def BearStockMarketSTRIPPED331(self):

        if self.RSI('QQQ', 10) < 30:
            self.Sort("SMADayRet",["TQQQ", "SPXL", "SOXL", "UPRO"], 5, True, 1, 1)
        else:
            if self.RSI('SPY', 10) < 30:
                self.AppendHolding('UPRO', 1, 1, 1)
            else:
                if self.Securities['QLD'].Price > self.SMA('QLD', 20):                              
                    self.BearStockMarketSTRIPPED231()
                else:
                    self.BearStockMarketSTRIPPED022()
                    
    def BearStockMarketSTRIPPED231(self):

        if self.RSI('BIL', 7) > self.RSI('IEF', 7):                    
            self.BearStockMarketSTRIPPED141()
        else:
            if self.RSI('SPY', 6) > 75:
                self.AppendHolding('UVXY', 1, 1, 1)
            else:
                self.AppendHolding('SOXL', 1, 1, 1)

    def BearStockMarketSTRIPPED141(self):

        if self.Securities['TLT'].Price < self.SMA('TLT', 21):
            self.BAARiskOffRisingRatesTMV()
        else:
            self.BABRiskOffFallingRatesTMF()

    def BAARiskOffRisingRatesTMV(self):

        if self.EMA('SPY', 210) <= self.SMA('SPY', 360):
            if self.RSI('TQQQ', 10) < 30:
                self.Sort("SMADayRet",["TQQQ", "SOXL", "UPRO"],5,True, 1, 1)
            else:
                if self.CumReturn('SPY', 2) < -0.02:
                    self.Sort("CumReturn",["SPXS", "TECS", "SOXS", "SQQQ", "ERX"],5,False, 1, 1)
                else:
                    if self.CumReturn('SPXU', 6) > self.CumReturn('UPRO', 3):
                        self.Sort("CumReturn",["SOXS", "SQQQ", "EPI"], 5, True, 1, 1)
                    else:
                        self.Sort("SMADayRet",["TECL", "SOXL", "TMV"], 5, False, 1, 1)
        else:
            if self.SMADayRet('SPY', 210) > self.SMADayRet('DBC', 360):                        
                if self.RSI('TQQQ', 11) > 77:
                    self.AppendHolding('UVXY', 1, 1, 1)
                else:
                    if self.CumReturn('TQQQ', 6) < -0.1:
                        if self.CumReturn('TQQQ', 1) > 0.055:   
                            self.AppendHolding('UVXY', 1, 1, 1)
                        else:
                            self.Sort("SMADayRet",["SOXL", "IYK", "TMV"], 5, False, 1, 1)

                    else:
                        if self.RSI('BIL', 7) < self.RSI('IEF', 7):  
                            self.Sort("SMADayRet",["TQQQ", "IYK", "SOXL", "UPRO", "TECL"], 5, True, 1, 1)
                        else:
                            self.Sort("SMADayRet",["SOXL", "IYK", "UPRO"], 22, False, 1, 1)
            else:
                self.Defence()

    def Defence(self):

        if self.STD('DBC', 20) > self.STD('SPY', 20):
            if self.STD('DBC', 10) > 0.03:
                if self.STD('TMV', 5) < self.STD('DBC', 5):
                    self.AppendHolding('TMV', 1, 1, 1)   
                else:
                    self.AppendHolding('DBC', 1, 1, 1)
            else:
                if self.RSI('BIL', 7) < self.RSI('IEF', 7):  
                    self.Sort("SMADayRet",["TMV", "SOXS", "SPXU"], 5, True, 1, 1)

                else:
                    self.Sort("CumReturn",["EFA", "EEM", "SPXS", "SOXS", "UCO", "TMV"], 5, False, 1, 1)
        else:
            if self.RSI('BIL', 7) < self.RSI('IEF', 7):                 
                self.Sort("SMADayRet",["EPI", "SOXL", "UPRO", "IYK"], 5, False, 1, 1)

            else:
                self.Sort("CumReturn",["EWZ", "TECS", "SOXS", "EUO", "YCS", "TMV"], 5, False, 1, 1)
    
    def BABRiskOffFallingRatesTMF(self):

        if self.EMA('SPY', 210) <= self.SMA('SPY', 360):
            if self.CumReturn('SPY', 2) < -0.02:
                self.Sort("SMADayRet",["SPXS", "TECS", "SOXS", "SQQQ"], 5, True, 1, 1)
            else:
                if self.CumReturn('SPXU', 6) > self.CumReturn('UPRO', 3):
                    self.Sort("CumReturn",["BIL", "AGG", "TMF"], 5, False, 1, 1)
                else:
                    self.Sort("SMADayRet",["TECL", "SOXL", "TQQQ", "EWZ", "TMF"], 5, False, 1, 1)
        else:
            if self.SMADayRet('SPY', 210) > self.SMADayRet('DBC', 360): 
                if self.EMA('SPY', 210) > self.EMA('SPY', 360):
                    if self.RSI('TQQQ', 11) > 77:
                        self.AppendHolding('UVXY', 1, 1, 1)
                    else:
                        if self.CumReturn('TQQQ', 6) < -0.1:
                            if self.CumReturn('TQQQ', 1) > 0.055:   
                                self.AppendHolding('UVXY', 1, 1, 1)
                            else:
                                self.Sort("SMADayRet",["TECL", "TQQQ", "SPXL", "EPI", "SOXL", "UPRO", "QLD", "EWZ", "MVV", "XLU", "IYK", "USD", "TMF"], 7, False, 1, 1)
                        if self.RSI('BIL', 7) < self.RSI('IEF', 7):  
                            self.Sort("SMADayRet",["TECL", "SPXL", "EPI", "SOXL", "UPRO", "MVV"], 7, False, 1, 1)
                        else:
                            self.Sort("CumReturn",["SOXS", "TMF"], 5, True, 1, 1)
                else:
                    self.Sort("RSI",["SPXS", "SQQQ", "TECS", "SOXS"], 5, False, 1, 1)
            else:
                self.Defence2()

    def Defence2(self):

        if self.STD('DBC', 20) > self.STD('SPY', 20):
            self.Sort("RSI",["SPXS", "EPI", "TECS", "SOXS", "SQQQ"], 5, False, 1, 1)
        else:
            self.Sort("SMADayRet",["TECL", "TQQQ", "SOXL", "TMF"], 5, True, 1, 1)

    def BearStockMarketSTRIPPED022(self):

        if self.RSI('TQQQ', 9) < 32:
            if self.CumReturn('TQQQ', 2) > self.CumReturn('TQQQ', 5):
                self.FiveandDime11()
            else:
                self.Sort("RSI",["TMF", "UCO", "USD", "SOXL", "SQQQ"], 5, False, 1, 1)

        else:
             self.BearStockMarketSTRIPPED201()

    def FiveandDime11(self):
        self.Substrategy1()
        self.Substrategy2()

    def Substrategy1(self):

        self.Sort("RSI",["TECL", "SOXL", "SHY"], 10, False, 1, 0.5)

    def Substrategy2(self):
        
        self.Sort("RSI",["SHY", "SOXL"], 5, False, 1, 0.5)

    def BearStockMarketSTRIPPED201(self):

        if self.Securities['TLT'].Price > self.SMA('TLT', 200):
            self.ABMediumtermTLT()
        else:
            self.BlongtermTLT()

    def ABMediumtermTLT(self):
        if self.SMADayRet('TLT', 20) < 0:
            self.ABBARiskOffRisingRatesTMV()
        else:
            self.ABBBRiskOffFallingRatesTMF()

    def ABBARiskOffRisingRatesTMV(self):

        if self.EMA('SPY', 210) <= self.SMA('SPY', 360):
            if self.RSI('TQQQ', 10) < 30:
                self.Sort("SMADayRet",["TECL", "TQQQ", "SOXL", "UPRO"], 5, False, 1, 1)
            else:
                if self.CumReturn('SPXU', 6) > self.CumReturn('UPRO', 3):
                    self.Sort("CumReturn",["SOXS", "EUO", "YCS"], 5, True, 1,1)
                else:
                    self.Sort("SMADayRet",["TECL", "SOXL", "TQQQ", "CURE"],5, False,1,1)
        else:               
            if self.RSI('TQQQ', 11) > 77:
                self.AppendHolding('UVXY', 1, 1, 1)
            else:
                self.Sort("SMADayRet",["SOXL", "TECL", "TMV", "TQQQ", "UPRO"],5, False,1,1)

    def ABBBRiskOffFallingRatesTMF(self):

        if self.EMA('SPY', 210) <= self.SMA('SPY', 360):
            if self.RSI('TQQQ', 10) < 30:
                self.Sort("SMADayRet",["TECL", "SOXL", "TQQQ"],5, False,1,1)
            else:
                if self.CumReturn('SPY', 2) < -0.02:
                    self.Sort("CumReturn",["TECS", "SOXS", "SQQQ"],5, True,1,1)
                else:
                    if self.CumReturn('SPXU', 6) > self.CumReturn('UPRO', 3):
                        self.Sort("CumReturn",["ERX", "EUO", "YCS"],5, True,1,1)                       
                    else:
                        self.Sort("SMADayRet",["EWZ", "SOXL", "MVV", "USD"],5, False,1,1)
        else:
            if self.SMADayRet('SPY', 210) > self.SMADayRet('DBC', 360):                        
                if self.RSI('TQQQ', 11) > 77:
                    self.AppendHolding('UVXY', 1, 1, 1)
                else:
                    if self.CumReturn('TQQQ', 6) < -0.1:
                        if self.CumReturn('TQQQ', 1) > 0.055:   
                            self.AppendHolding('UVXY', 1, 1, 1)
                        else:
                            if self.RSI('BIL', 7) < self.RSI('IEF', 7):  
                                self.AppendHolding('SOXL', 1, 1, 1)
                            else:
                                self.Sort("CumReturn",["EWZ", "UUP", "TMF", "UCO"],5, True,1,1)
                    else:
                        if self.RSI('BIL', 7) < self.RSI('IEF', 7):  
                            self.Sort("SMADayRet",["TQQQ", "SPXL", "QLD", "USD", "TECL"],5, False,1,1)
                        else:
                            self.Sort("CumReturn",["EWZ", "EWZ", "TMF"],5, True,1,1)
            else:
                self.Defence3()

    def Defence3(self):

        if self.STD('DBC', 20) > self.STD('SPY', 20):
            self.Sort("RSI",["SHY", "EWZ", "GLD", "SPXS", "TECS", "SOXS", "UCO", "YCS"],5, False,1,1)
        else:
            if self.RSI('BIL', 7) < self.RSI('IEF', 7):  
                self.Sort("SMADayRet",["SOXL", "USD", "TMF"],5, False,1,1)
            else:
                self.Sort("CumReturn",["EWZ", "SPXS", "SOXS", "UCO", "YCS"],5, True,1,1)

    def BlongtermTLT(self):

        if self.SMADayRet('TLT', 20) < 0:
            self.BAARiskOffRisingRatesTMV2()
        else:
            self.BABRiskOffFallingRatesTMF()

    def BAARiskOffRisingRatesTMV2(self):

        if self.EMA('SPY', 210) <= self.SMA('SPY', 360):
            if self.RSI('TQQQ', 10) < 30:
                self.Sort("SMADayRet",["TQQQ", "SOXL", "UPRO"],5, True,1,1)
            else:
                if self.CumReturn('SPY', 2) < -0.02:
                    self.Sort("CumReturn",["SPXS", "TECS", "SOXS", "SQQQ", "ERX"],5,False,1,1)
                else:
                    if self.CumReturn('SPXU', 6) > self.CumReturn('UPRO', 3):
                        self.Sort("CumReturn", ["SOXS", "SQQQ", "EPI"], 5, True, 1, 1)
                    else:
                        self.Sort("SMADayRet", ["TECL", "SOXL", "TMV"], 5, False, 1, 1)
        else:
            if self.SMADayRet('SPY', 210) > self.SMADayRet('DBC', 360):                        
                if self.RSI('TQQQ', 11) > 77:
                    self.AppendHolding('UVXY', 1, 1, 1)
                else:
                    if self.CumReturn('TQQQ', 6) < -0.1:
                        if self.CumReturn('TQQQ', 1) > 0.055:   
                            self.AppendHolding('UVXY', 1, 1, 1)
                        else:
                            self.Sort("SMADayRet",["SOXL", "IYK", "TMV"], 5, False, 1, 1)
                    else:
                        if self.RSI('BIL', 7) < self.RSI('IEF', 7):  
                            self.Sort("SMADayRet", ["TQQQ","SOXL", "IYK", "TMV", "UPRO", "TECL"], 5, True, 1, 1)
                        else:
                            self.Sort("SMADayRet", ["SOXL", "IYK", "UPRO"], 22, False, 1, 1)
            else:
                self.Defence()

    def BullStockMarket(self):

        if self.RSI('SPY', 40) > 75:
            if self.RSI('BIL', 7) < self.RSI('IEF', 7):
                self.AppendHolding('QQQ', 1, 1, 1)
            else:
                self.AppendHolding('UVXY', 1, 1, 1)
        else:
            self.BullStockMarket222()

    def BullStockMarket222(self):

        if self.RSI('BIL', 7) > self.RSI('IEF', 7):
            self.BullStockMarketSTRIPPED1()
        else:
            if self.RSI('SPY', 6) > 75:
                self.AppendHolding('UVXY', 1, 1, 1)
            else:
                self.AppendHolding('SOXL', 1, 1, 1)

    def BullStockMarketSTRIPPED1(self):

        if self.RSI('TQQQ', 14) > 75:
            self.AppendHolding('UVXY', 1, 1, 1)
        else:
            if self.RSI('SPXL', 10) > 80:
                self.AppendHolding('UVXY', 1, 1, 1)
            else:
                self.BullStockMarketSTRIPPED201()

    def BullStockMarketSTRIPPED201(self):

        if self.Securities['TLT'].Price > self.SMA('TLT', 200):                        
            self.ALongTLTtrendingup()
        else:
            self.BLongTLTtrendingdown()

    def ALongTLTtrendingup(self):

        if self.RSI('TLT', 14) < 50:
            self.AAMediumTLTnotOverbought()
        else:
            self.ABMediumTLTmayOverbought2()

    def AAMediumTLTnotOverbought(self):

        if self.Securities['TLT'].Price > self.SMA('TLT', 5):  
            self.AAAShortTLTtrendingup()
        else:
            self.AABShortTLTtrendingdown()

    def AAAShortTLTtrendingup(self):

        if self.EMA('SPY', 210) <= self.SMA('SPY', 360):
            if self.RSI('TQQQ', 10) < 30:
                self.Sort("SMADayRet", ["TQQQ", "SOXL", "UPRO", "TECL", "SPXL"], 5, True, 1, 1)
            else:
                if self.CumReturn('SPXU', 6) > self.CumReturn('UPRO', 3):
                    self.Sort("CumReturn", ["TECS", "SOXS", "SQQQ", "TMF", "SHY"], 5, True, 1, 1)
                else:
                    self.Sort("SMADayRet", ["TECL", "SOXL", "UPRO", "EWZ", "TMF", "TQQQ"], 5, False, 1, 1)
        else:
            if self.CumReturn('TQQQ', 6) < -0.1:
                self.Sort("SMADayRet", ["TECL", "TQQQ", "TMF"], 7, False, 1, 1)
            else:
                self.Sort("SMADayRet", ["SOXL", "TMF"], 7, False, 1, 1)

    def AABShortTLTtrendingdown(self):

        if self.RSI('TLT', 14) < 20:
            self.AppendHolding('SHY', 1, 1, 1)
        else:
            if self.SMADayRet('TLT', 20) < 0:
                self.AABBARiskOffRisingRatesTMV()
            else:
                self.AABBBRiskOffFallingRatesTMF()

    def AAMediumTLTnotOverbought(self):

        if self.Securities['TLT'].Price > self.SMA('TLT', 5):  
            self.AAAShortTLTtrendingup()
        else:
            self.AABShortTLTtrendingdown() 

    def AABBARiskOffRisingRatesTMV(self):

        if self.EMA('SPY', 210) <= self.SMA('SPY', 360):
            if self.CumReturn('SPXU', 6) >= self.CumReturn('UPRO', 3):
                self.Sort("CumReturn", ["SOXS", "ERX", "SHY"], 5, True, 1, 1)
            else:
                self.Sort("SMADayRet", ["TQQQ", "SOXL", "CURE", "EWZ", "SHY"], 5, False, 1, 1)
        else:
            if self.SMA('SPY', 210) > self.SMA('DBC', 360):
                if self.RSI('TQQQ', 11) > 77:
                    self.AppendHolding('UVXY', 1, 1, 1)
                else:
                    if self.CumReturn('TQQQ', 6) < -0.1:
                        if self.CumReturn('TQQQ', 1) > 0.055:
                            self.AppendHolding('UVXY', 1, 1, 1)
                        else:
                            self.Sort("SMADayRet", ["TECL", "TQQQ", "SOXL", "UPRO", "TMV", "SHY"], 5, False, 1, 1)
                    else:
                        self.Sort("SMADayRet", ["TECL", "TQQQ", "SOXL", "UPRO", "TMV", "SHY"], 5, True, 1, 1)
            else:                       
                self.DefenseModified4()

    def DefenseModified4(self):

        if self.STD('DBC', 20) > self.STD('SPY', 20):
            self.Sort("RSI", ["EEM", "TECS", "SOXS", "TMV"], 5, False, 1, 1)
        else:
            self.Sort("RSI", ["EEM", "TECS", "SOXS", "TMV"], 10, False, 1, 1)

    def AABBBRiskOffFallingRatesTMF(self):

        if self.EMA('SPY', 210) <= self.SMA('SPY', 360):
            if self.CumReturn('SPXU', 6) >= self.CumReturn('UPRO', 3):
                self.Sort("SMADayRet", ["TQQQ", "SOXL", "UPRO", "TECL", "TMF"], 5, True, 1, 1)
            else:
                self.Sort("SMADayRet", ["TECL", "TQQQ", "SOXL", "TMF"], 5, False, 1, 1)
        elif self.SMADayRet('SPY', 210) > self.SMADayRet('DBC', 360):
            if self.RSI('TQQQ', 11) > 77:
                self.AppendHolding('UVXY', 1, 1, 1)
            elif self.CumReturn('TQQQ', 6) < -0.1:
                if self.CumReturn('TQQQ', 1) > 0.055:
                    self.AppendHolding('UVXY', 1, 1, 1)
                else:
                    self.Sort("SMADayRet", ["TECL", "TQQQ", "SPXL", "EPI", "SOXL", "UPRO", "QLD", "EWZ", "MVV", "PUI", "IYK", "USD", "TMF"], 7, False, 1, 1)
            else:
                if self.RSI('BIL', 7) < self.RSI('IEF', 7):
                    self.Sort("SMADayRet", ["TECL", "TQQQ", "SOXL", "PUI"], 5, False, 1, 1)
                else:
                    self.Sort("CumReturn", ["SOXS", "SQQQ", "UCO", "DIG"], 5, False, 1, 1)
        else:
            self.Sort("SMADayRet", ["EPI", "UPRO", "SOXL", "TQQQ"], 5, True, 1, 1)

    def ABMediumTLTmayOverbought2(self):

        if self.RSI('TLT', 14) > 80:
            self.ABAMediumtermTLTisoverbought()
        else:
            if self.Securities['TLT'].Price < self.SMA('TLT', 21):
                self.ABBARiskOffRisingRatesTMV()
            else:
                self.ABBBRiskOffFallingRatesTMF()

    def ABAMediumtermTLTisoverbought(self):

        if self.SMADayRet('SPY', 210) > self.SMADayRet('DBC', 360):
            if self.CumReturn('TQQQ', 6) < -0.1:
                if self.CumReturn('TQQQ', 1) > 0.055:
                    self.AppendHolding('UVXY', 1, 1, 1)
                else:
                    self.Sort("SMADayRet", ["TECL", "TQQQ", "SOXL", "UPRO"], 5, False, 1, 1)
            else:
                self.Sort("RSI", ["SQQQ", "TECS", "SOXS", "TMV"], 5, True, 1, 1)
        else:
            self.Sort("SMADayRet", ["EPI", "UPRO", "SOXL", "TQQQ", "TMV"], 5, True, 1, 1)

    def BLongTLTtrendingdown(self):
        if self.Securities['TLT'].Price < self.SMA('TLT', 21):
            self.BAARiskOffRisingRatesTMV2()
        else:
            self.BABRiskOffFallingRatesTMF2()        

    def BABRiskOffFallingRatesTMF2(self):
        if self.EMA('SPY', 210) <= self.SMA('SPY', 360):
            if self.CumReturn('SPY', 2) <= -0.02:
                self.Sort("CumReturn", ["SPXS", "TECS", "SOXS", "SQQQ"], 5, True, 1, 1)
            elif self.CumReturn('SPXU', 6) >= self.CumReturn('UPRO', 3):
                self.Sort("CumReturn", ["BIL", "AGG", "TMF"], 5, False, 1, 1)
            else:
                self.Sort("SMADayRet", ["TECL", "TQQQ", "SOXL", "EWZ", "TMF"], 5, False, 1, 1)
        elif self.SMADayRet('SPY', 210) > self.SMADayRet('DBC', 360):
            if self.EMA('SPY', 210) > self.EMA('SPY', 360):
                if self.RSI('TQQQ', 11) > 77:
                    self.AppendHolding('UVXY', 1, 1, 1)
                elif self.CumReturn('TQQQ', 6) < -0.1:
                    if self.CumReturn('TQQQ', 1) > 0.055:
                        self.AppendHolding('UVXY', 1, 1, 1)
                    else:
                        self.Sort("SMADayRet", ["TECL", "TQQQ", "SPXL", "EPI", "SOXL", "UPRO", "QLD", "EWZ", "MVV", "XLU", "IYK", "USD", "TMF"], 7, False, 1, 1)
                elif self.RSI('BIL', 7) < self.RSI('IEF', 7):
                    self.Sort("SMADayRet", ["TECL", "SPXL", "EPI", "SOXL", "UPRO", "MVV", "UGE"], 7, False, 1, 1)
                else:
                    self.Sort("CumReturn", ["SOXS", "TMF"], 5, True, 1, 1)
            else:
                self.Sort("RSI", ["SPXS", "SQQQ", "TECS", "SOXS"], 5, False, 1, 1)
        else:
            self.Defence2()

    def NewApollo(self):

        if self.Securities['SPY'].Price > self.SMA('SPY', 200):
            if self.RSI('QQQ', 14) > 80:
                self.AppendHolding('UVXY', 1, 1, 1)
            else:
                if self.RSI('SPY', 10) > 80:
                    self.AppendHolding('UVXY', 1, 1, 1)
                else:
                    self.V201ABetterLETFBasketDJKeyholeNoUGEPUI()
        else:
            if self.RSI('TQQQ', 9) < 32:
                if self.CumReturn('TQQQ', 2) >= self.CumReturn('TQQQ', 5):
                    self.FiveandDime11()
                else:
                    if self.RSI('SPY', 10) < 30:
                        self.FiveandBelow12()
                    else:
                        if self.Securities['TQQQ'].Price > self.SMA('TQQQ', 20):
                            if self.RSI('SQQQ', 10) < 31:
                                self.AppendHolding('SQQQ', 1, 1, 1)
                            else:
                                self.AppendHolding('TQQQ', 1, 1, 1)
                        else:
                            self.Sort("RSI", ["TMF", "UCO", "USD", "SOXL", "SQQQ"], 5, False, 1, 1)
            else:
                self.V201ABetterLETFBasketDJKeyholeNoUGEPUI()

    def V201ABetterLETFBasketDJKeyholeNoUGEPUI(self):
        if self.Securities['TLT'].Price > self.SMA('TLT', 200):
            self.AIfLongTermTLTIsTrendingUp2()
        else:
            self.BLongTLTtrendingdown2()

    def AIfLongTermTLTIsTrendingUp2(self):
        if self.RSI('TLT', 14) < 50:
            self.AAIfMediumTermTLTIsNotOverbought2()
        else:
            self.ABMediumTermTLTMayBeOverbought3()

    def AAIfMediumTermTLTIsNotOverbought2(self):
        if self.Securities['TLT'].Price > self.SMA('TLT', 5):
            self.AAAShortTermTLTIsTrendingUpBuy3xLeveragedBullTreasuryBonds2()
        else:
            self.AABIfShortTermTLTIsTrendingDown2()

    def AAAShortTermTLTIsTrendingUpBuy3xLeveragedBullTreasuryBonds2(self):
        if self.EMA('SPY', 210) <= self.SMA('SPY', 360):
            if self.RSI('TQQQ', 10) < 30:
                self.Sort("SMADayRet", ["TECL", "TQQQ", "SOXL", "UPRO"], 5, True, 1, 1)
            else:
                if self.CumReturn('SPXU', 6) >= self.CumReturn('UPRO', 3):
                    self.Sort("CumReturn", ["TECS", "SOXS", "SQQQ", "TMF", "SHY"], 5, True, 1, 1)
                else:
                    self.Sort("SMADayRet", ["TECL", "TQQQ", "SOXL", "UPRO", "EWZ", "TMF"], 5, False, 1, 1)
        else:
            if self.CumReturn('TQQQ', 6) < -0.1:
                self.Sort("SMADayRet", ["TECL", "TQQQ", "TMF"], 7, False, 1, 1)
            else:
                self.Sort("SMADayRet", ["SOXL", "TMF"], 7, False, 1, 1)
    
    def AABIfShortTermTLTIsTrendingDown2(self):

        if self.RSI('TLT', 14) < 20:
            self.AppendHolding('TMF', 1, 1, 1)
        else:
            if self.SMADayRet('TLT', 20) < 0:
                self.AABBARiskOffRisingRatesTMV()
            else:
                self.AABBBRiskOffFallingRatesTMF2()

    def AABBBRiskOffFallingRatesTMF2(self):
        if self.EMA('SPY', 210) <= self.SMA('SPY', 360):
            if self.CumReturn('SPXU', 6) >= self.CumReturn('UPRO', 3):
                self.Sort("SMADayRet", ["TQQQ", "SOXL", "UPRO", "TECL", "TMF"], 5, True, 1, 1)
            else:
                self.Sort("SMADayRet", ["TECL", "TQQQ", "SOXL", "TMF"], 5, False, 1, 1)
        elif self.SMA('SPY', 210) > self.SMA('DBC', 360):
            if self.RSI('TQQQ', 11) > 77:
                self.AppendHolding('UVXY', 1, 1, 1)
            elif self.CumReturn('TQQQ', 6) < -0.1:
                if self.CumReturn('TQQQ', 1) > 0.055:
                    self.AppendHolding('UVXY', 1, 1, 1)
                else:
                    self.Sort("SMADayRet", ["TECL", "TQQQ", "EPI", "SOXL", "UPRO", "QLD", "EWZ", "MVV", "XLU", "USD", "TMF"], 7, False, 1, 1)
            elif self.RSI('BIL', 7) < self.RSI('IEF', 7):
                self.Sort("SMADayRet", ["TECL", "TQQQ", "SOXL", "XLU"], 5, False, 1, 1)
            else:
                self.Sort("CumReturn", ["SOXS", "SQQQ", "UCO", "DIG"], 5, False, 1, 1)
        else:
            self.Sort("SMADayRet", ["EPI", "UPRO", "SOXL", "TQQQ"], 5, True, 1, 1)

    def ABMediumTermTLTMayBeOverbought3(self): 
        if self.RSI('TLT', 14) > 80:
            self.ABAMediumtermTLTisoverbought()
        else:
            self.ABBLeveragedSafety()
        
    def ABBLeveragedSafety(self):
        if self.SMADayRet('TLT', 20) < 0:
            self.ABBARiskOffRisingRatesTMV()
        else:
            self.ABBARiskOffFallingRatesTMF2()
        
    def ABBARiskOffFallingRatesTMF2(self):
        if self.EMA('SPY', 210) <= self.SMA('SPY', 360):
            if self.RSI('TQQQ', 10) < 30:
                self.Sort("SMADayRet", ["TECL", "TQQQ", "SOXL"], 5, False, 1, 1)
            elif self.CumReturn('SPY', 2) <= -0.02:
                self.Sort("CumReturn", ["TECS", "SOXS", "SQQQ"], 5, True, 1, 1)
            elif self.CumReturn('SPXU', 6) >= self.CumReturn('UPRO', 3):
                self.Sort("CumReturn", ["ERX", "EUO", "YCS"], 5, True, 1, 1)
            else:
                self.Sort("SMADayRet", ["SOXL", "EWZ", "MVV", "USD"], 5, False, 1, 1)
        elif self.SMADayRet('SPY', 210) > self.SMADayRet('DBC', 360):
            if self.RSI('TQQQ', 11) > 77:
                self.AppendHolding('UVXY', 1, 1, 1)
            elif self.CumReturn('TQQQ', 6) < -0.1:
                if self.CumReturn('TQQQ', 1) > 0.055:
                    self.AppendHolding('UVXY', 1, 1, 1)
                elif self.RSI('BIL', 7) < self.RSI('IEF', 7):
                    self.AppendHolding('SOXL', 1, 1, 1)
                else:
                    self.Sort("CumReturn", ["EWZ", "UUP", "TMF", "UCO"], 5, True, 1, 1)
            elif self.RSI('BIL', 7) < self.RSI('IEF', 7):
                self.Sort("SMADayRet", ["TECL", "TQQQ", "UPRO", "QLD", "USD"], 5, False, 1, 1)
            else:
                self.Sort("CumReturn", ["EWZ", "UUP", "TMF"], 5, True, 1, 1)
        else:
            self.DefenseModified5()

    def DefenseModified5(self):
        if self.STD('DBC', 20) > self.STD('SPY', 20):
            self.Sort("RSI", ["SHY", "EWZ", "GLD", "SPXU", "TECS", "SOXS", "UCO", "YCS"], 5, False, 1, 1)
        elif self.RSI('BIL', 7) < self.RSI('IEF', 7):
            self.Sort("SMADayRet", ["SOXL", "USD", "TMF"], 5, False, 1, 1)
        else:
            self.Sort("CumReturn", ["EWZ", "SPXU", "SOXS", "UCO", "YCS"], 5, True, 1, 1)

    def BLongTLTtrendingdown2(self):
        if self.Securities['TLT'].Price < self.SMA('TLT', 21):
            self.BAARiskOffRisingRatesTMV3()
        else:
            self.BABRiskOffFallingRatesTMF3()

    def BAARiskOffRisingRatesTMV3(self):
        if self.EMA('SPY', 210) <= self.SMA('SPY', 360):
            if self.RSI('TQQQ', 10) < 30:
                self.Sort("SMADayRet", ["TQQQ", "SOXL", "UPRO"], 5, True, 1, 1)
            else:
                if self.CumReturn('SPY', 2) <= -0.02:
                    self.Sort("CumReturn", ["SPXU", "TECS", "SOXS", "SQQQ", "ERX"], 5, False, 1, 1)
                else:
                    if self.CumReturn('SPXU', 6) >= self.CumReturn('UPRO', 3):
                        self.Sort("CumReturn", ["SOXS", "SQQQ", "EPI"], 5, True, 1, 1)
                    else:
                        self.Sort("SMADayRet", ["TECL", "SOXL", "TMV"], 5, False, 1, 1)
        else:
            if self.SMA('SPY', 210) > self.SMA('DBC', 360):
                if self.RSI('TQQQ', 11) > 77:
                    self.AppendHolding('UVXY', 1, 1, 1)
                else:
                    if self.CumReturn('TQQQ', 6) < -0.1:
                        if self.CumReturn('TQQQ', 1) > 0.055:
                            self.AppendHolding('UVXY', 1, 1, 1)
                        else:
                            self.Sort("SMADayRet", ["SOXL", "IYK", "TMV"], 5, False, 1, 1)
                    else:
                        if self.RSI('BIL', 7) < self.RSI('IEF', 7):
                            self.Sort("SMADayRet", ["TQQQ", "SOXL", "UPRO", "TMV", "TECL"], 5, True, 1, 1)
                        else:
                            self.Sort("SMADayRet", ["SOXL", "UPRO", "IYK"], 22, False, 1, 1)
            else:
                self.DefenseModified6()

    def DefenseModified6(self):
        if self.STD('DBC', 20) > self.STD('SPY', 20):
            if self.STD('DBC', 10) >= 0.03:
                if self.STD('TMV', 5) <= self.STD('DBC', 5):
                    self.AppendHolding('TMV', 1, 1, 1)
                else:
                    self.AppendHolding('DBC', 1, 1, 1)
            else:
                if self.RSI('BIL', 7) < self.RSI('IEF', 7):
                    self.Sort("SMADayRet", ["TMV", "SOXS", "SPXU"], 5, True, 1, 1)
                else:
                    self.Sort("CumReturn", ["EFA", "EEM", "SPXU", "SOXS", "UCO", "TMV"], 5, False, 1, 1)
        else:
            if self.RSI('BIL', 7) < self.RSI('IEF', 7):
                self.Sort("SMADayRet", ["EPI", "SOXL", "UPRO"], 5, False, 1, 1)
            else:
                self.Sort("CumReturn", ["EWZ", "TECS", "SOXS", "EUO", "YCS", "TMV"], 5, True, 1, 1)

    def BABRiskOffFallingRatesTMF3(self):
        if self.EMA('SPY', 210) <= self.SMA('SPY', 360):
            if self.CumReturn('SPY', 2) < -0.02:
                self.Sort("CumReturn", ["SPXU", "TECS", "SOXS", "SQQQ"], 5, True, 1, 1)
            else:
                if self.CumReturn('SPXU', 6) >= self.CumReturn('UPRO', 3):
                    self.Sort("CumReturn", ["BIL", "AGG", "TMF"], 5, False, 1, 1)
                else:
                    self.Sort("CumReturn", ["TECL", "TQQQ", "SOXL", "EWZ", "TMF"], 5, False, 1, 1)
        else:
            if self.SMA('SPY', 210) > self.SMA('DBC', 360):
                if self.EMA('SPY', 210) > self.EMA('SPY', 360):
                    if self.RSI('TQQQ', 11) > 77:
                        self.AppendHolding('UVXY', 1, 1, 1)
                    else:
                        if self.CumReturn('TQQQ', 6) < -0.1:
                            if self.CumReturn('TQQQ', 1) > 0.055:
                                self.AppendHolding('UVXY', 1, 1, 1)
                            else:
                                self.Sort("SMADayRet", ["TECL", "TQQQ", "EPI", "SOXL", "UPRO", "QLD", "EWZ", "MVV", "XLU", "USD", "TMF"], 7, True, 1, 1)
                        else:
                            if self.RSI('BIL', 7) < self.RSI('IEF', 7):
                                self.Sort("SMADayRet", ["TECL", "EPI", "SOXL", "UPRO", "MVV"], 7, False, 1, 1)
                            else:
                                self.Sort("CumReturn", ["SOXS", "TMF"], 5, True, 1, 1)
                else:
                    self.Sort("RSI", ["SPXU", "SQQQ", "TECS", "SOXS"], 5, False, 1, 1)
            else:
                self.DefenseModified7()

    def DefenseModified7(self):
        if self.STD('DBC', 20) > self.STD('SPY', 20):
            self.Sort("RSI", ["SPXU", "EPI", "TECS", "SOXS", "SQQQ"], 5, False, 1, 1)
        else:
            self.Sort("SMADayRet", ["TECL", "TQQQ", "SOXL", "TMF"], 5, True, 1, 1)

    def FiveandBelow12(self):
        self.Sort("SMADayRet", ["TECL", "TQQQ", "SOXL", "UPRO", "QLD"], 5, False, 1, 1)


    def ExecuteTrade(self):
        group = {
            'HTS': [self.HTS1[i][0] if len(self.HTS1[i]) == 1 else self.HTS1[i] for i in self.HTS1],
            'HT': [self.HT1[i] for i in self.HT1]
        }
        df = pd.DataFrame(group)
        df = pd.concat([df])
        df['HTS'] = df['HTS'].astype(str)
        result = df.groupby(['HTS']).sum().reset_index()

        for equity in self.equities:
            if all(not pd.isnull(result.iloc[i, 0]) and not equity == result.iloc[i, 0] for i in range(len(result))):
                if self.Portfolio[equity].HoldStock:
                    self.Liquidate(equity)
        output = "*****"

        for i in range(len(result)):
            if result.iloc[i, 0]:
                percentage = round(result.iloc[i, 1] * 100, 2)
                output += "{}: {}% - ".format(result.iloc[i, 0], percentage)
        output = output.rstrip(" - ")
        self.Log(output)

        for i in range(len(result)):
            if not result.iloc[i, 1] == 0 and not result.iloc[i, 0] == 'BIL':
                percentage_equity = self.Portfolio[result.iloc[i, 0]].HoldingsValue / self.Portfolio.TotalPortfolioValue
                quantity = (result.iloc[i, 1] - percentage_equity) * self.Portfolio.TotalPortfolioValue / self.Securities[result.iloc[i, 0]].Price
                if result.iloc[i, 1] < percentage_equity and abs(result.iloc[i, 1] / percentage_equity - 1) > self.buffer_pct:
                    self.SetHoldings(result.iloc[i, 0], result.iloc[i, 1])
                else:
                    pass

        for i in range(len(result)):
            if not result.iloc[i, 1] == 0 and not result.iloc[i, 0] == 'BIL':
                percentage_equity = self.Portfolio[result.iloc[i, 0]].HoldingsValue / self.Portfolio.TotalPortfolioValue
                quantity = (result.iloc[i, 1] - percentage_equity) * self.Portfolio.TotalPortfolioValue / self.Securities[result.iloc[i, 0]].Price
                if result.iloc[i, 1] > percentage_equity and abs(percentage_equity / result.iloc[i, 1] - 1) > self.buffer_pct:
                    self.SetHoldings(result.iloc[i, 0], result.iloc[i, 1])
                else:
                    pass
    
        self.HT1 = {str(i).zfill(2): 0 for i in range(1, 21)}
        self.HTS1 = {str(i).zfill(2): [] for i in range(1, 21)}