Overall Statistics
Total Orders
11
Average Win
0%
Average Loss
0%
Compounding Annual Return
0%
Drawdown
0%
Expectancy
0
Net Profit
0%
Sharpe Ratio
0
Sortino Ratio
0
Probabilistic Sharpe Ratio
0%
Loss Rate
0%
Win Rate
0%
Profit-Loss Ratio
0
Alpha
0
Beta
0
Annual Standard Deviation
0
Annual Variance
0
Information Ratio
0
Tracking Error
0
Treynor Ratio
0
Total Fees
$14.23
Estimated Strategy Capacity
$280000.00
Lowest Capacity Asset
HIBS X9BLOT91F5UT
Portfolio Turnover
84.30%
from AlgorithmImports import *
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
import csv
import io
import time
import json
class IntelligentSkyRodent(QCAlgorithm):
    def Initialize(self):
        self.cash = 100000
        self.buffer_pct = 0.02
        self.SetStartDate(2023,12,27)
        self.SetEndDate(2023,12,27)
        self.SetCash(self.cash)
        self.equities = ['IBIT','GBTC','BTF','BITI','DFEN','CONL','BITX','DPST','AMZN','MSFT','NVDA','SPLV','ARKK','DRV','VTI','BSV','EWZ','UNH','COST','USDU','IEI','DIA','IWM','AAPB','AAPD','AMD','BULZ','COIN','EDC','EDV','FNGU','HIBL','HIBS','IEO','LQD','OIL','QID','QQQ','QQQE','RWM','SARK','SHV','SPXU','STIP','SVXY','SQQQ','TARK','TBF','TSLA','TSLL','TSLQ','TSLS','UDN','URTY','UVIX','VCIT','VEA','VIXM','VOOG','VOOV','VTIP','VTV','XLE','XLF','XLK','XLP','XLY','AAPL','TQQQ','SPY','DBC','IAU','AGG','BAD','BITO','BTAL','CCOR','COWZ','CTA','CURE','DBMF','DDM','DGRO','DIG','DUK','EPI','EUO','FAAR','FNDX','FTLS','GDMA','GLL','IYH','IYK','KMLM','LBAY','MVV','MORT','NOBL','NRGD','NTSX','PHDG','PST','QLD','RWL','SCHD','SCHG','SGOL','SOXX','SPHB','SPHD','SPXL','SPYG','SSO','TBX','TIP','TLH','TMF','UBT','USD','VGLT','VGIT','VLUE','VXUS','VIXY','WEBL','WEBS','XLU','XLV','YCS','AGQ','BAL','BIL','BND','BOIL','BRZU','CANE','CHAD','CHAU','COPX','CORN','CURE','DBA','DBB','DBO','DRIP','DRN','DUST','ECC','EDZ','EEM','EFA','ERX','ERY','ESPO','EURL','EWA','EWG','EWGS','EWI','EWJ','EWN','EWP','EWQ','EWU','FAZ','FAS','GUSH','GLD','INDL','IEF','JDST','JNUG','KOLD','KORU','LABD','LABU','MEXX','MIDU','NURE','PALL','PDBC','PEJ','PILL','PSQ','REMX','RETL','SCO','SH','SHY','SLV','SMH','SOXL','SOXS','SPDN','SPXL','SPXS','SPUU','TNA','TLT','TMF','TMV','TZA','TAGS','TECL','TECS','TYD','TYO','UCO','UDOW','UGL','UPRO','URE','USO','UTSL','UVXY','UUP','VAW','VDC','VDE','VFH','VGT','VNQ','VNQI','VIS','VPU','VXX','VOX','VHT','WEAT','WOOD','YANG','YINN','SPDN']
        self.MKT = self.AddEquity("QQQ",Resolution.Daily).Symbol
        self.mkt = []
        for equity in self.equities:
            self.AddEquity(equity,Resolution.Minute) #LEVERAGE!!
            self.Securities[equity].SetDataNormalizationMode(DataNormalizationMode.Adjusted)
        self.AddEquity('BIL',Resolution.Minute)
        self.Securities['BIL'].SetDataNormalizationMode(DataNormalizationMode.TotalReturn)

        self.PTMaster = 1.0
        self.SetSecurityInitializer(self.CustomSecurityInitializer)
        self.PT1 = 0.26*self.PTMaster #TQQQFTLT 
        self.PT2 = 0.00*self.PTMaster #SOXX
        self.PT3 = 0.16*self.PTMaster #TQQQorNOT
        self.PT4 = 0.07*self.PTMaster #BB
        self.PT5 = 0.125*self.PTMaster #Best
        self.PT6 = 0.125*self.PTMaster #Best
        self.PT7 = 0.125*self.PTMaster #Best
        self.PT8 = 0.125*self.PTMaster #Best
        self.TA1110 = 1
        self.TA1111 = 0.45
        self.TA1120 = 0.45
        self.TA1121 = 0.15
        self.TA1130 = 0.02
        self.TA1140 = 0.08
        self.TA1210 = 1
        self.TA6 = 1
        self.HT1 = {str(i).zfill(2): 0 for i in range(1,10)}
        self.HTS1 = {str(i).zfill(2): [] for i in range(1,10)}
        self.HT2 = {str(i).zfill(2): 0 for i in range(1,10)}
        self.HTS2 = {str(i).zfill(2): [] for i in range(1,10)}
        self.HT3 = {str(i).zfill(2): 0 for i in range(1,10)}
        self.HTS3 = {str(i).zfill(2): [] for i in range(1,10)}
        self.HT4 = {str(i).zfill(2): 0 for i in range(1,10)}
        self.HTS4 = {str(i).zfill(2): [] for i in range(1,10)}
        self.HT5 = {str(i).zfill(2): 0 for i in range(1,30)}
        self.HTS5 = {str(i).zfill(2): [] for i in range(1,30)}
        self.HT6 = {str(i).zfill(2): 0 for i in range(1,30)}
        self.HTS6 = {str(i).zfill(2): [] for i in range(1,30)}
        self.HT7 = {str(i).zfill(2): 0 for i in range(1,30)}
        self.HTS7 = {str(i).zfill(2): [] for i in range(1,30)}
        self.HT8 = {str(i).zfill(2): 0 for i in range(1,30)}
        self.HTS8 = {str(i).zfill(2): [] for i in range(1,30)}

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

    def CustomSecurityInitializer(self, security): 
        security.SetLeverage(self.PTMaster)

    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 AH(self,equities,PTnumber,multiplier): #AppendHolding
        if not isinstance(equities,list):
            equities = [equities]
        HT = getattr(self,f"HT{PTnumber}")
        HTS = getattr(self,f"HTS{PTnumber}")
        PT = getattr(self,f"PT{PTnumber}") * multiplier
        
        for equity in equities:
            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.TQQQFTLT()
        self.SOXXRSIMachine()
        self.TQQQorNOT()
        self.DereckCustomBetaBaller()
        self.Slowloss()
        self.ExecuteTrade()
        self.PrintStrategy()
    def Slowloss(self):
        response = self.Download('https://drive.google.com/uc?export=download&id=1TljX0Fa6rmZFWvXtW0I6-8dCoVfg-VCY')
        tickers_list = []
        self.new_tickers_list = []
        if response:
            reader = csv.DictReader(io.StringIO(response))
            for row in reader:
                if row['Symphony'] == 'BEST0d' and len(row['Ticker']) <= 5:
                    ticker = row['Ticker']
                    tickers_list.append(ticker)
                    allocation_percent = float(row['Ticker Allocation Percent'])
                    self.AH(ticker,5,allocation_percent/100)
                if row['Symphony'] == 'BEST5d' and len(row['Ticker']) <= 5:
                    ticker = row['Ticker']
                    tickers_list.append(ticker)
                    allocation_percent = float(row['Ticker Allocation Percent'])
                    self.AH(ticker,6,allocation_percent/100)
                if row['Symphony'] == 'BEST10d' and len(row['Ticker']) <= 5:
                    ticker = row['Ticker']
                    tickers_list.append(ticker)
                    allocation_percent = float(row['Ticker Allocation Percent'])
                    self.AH(ticker,7,allocation_percent/100)
                if row['Symphony'] == 'BEST20d' and len(row['Ticker']) <= 5:
                    ticker = row['Ticker']
                    tickers_list.append(ticker)
                    allocation_percent = float(row['Ticker Allocation Percent'])
                    self.AH(ticker,8,allocation_percent/100)
                if row['Symphony'] == 'info':
                    self.Debug('******Data refreshed at: ' + row['Ticker'])
            tickers_list.extend(ticker for ticker in self.equities if ticker not in tickers_list)
            self.new_tickers_list = list(set(tickers_list) - set(self.equities))
            self.Debug("Newly added tickers: " + str(self.new_tickers_list))

    def TQQQFTLT(self):
        if self.Securities['SPY'].Price > self.SMA('SPY',200):
            if self.RSI('TQQQ',10) > 78:
                self.AH(['BIL','UVXY','SQQQ'],1,0.33)
            else:
                if self.RSI('SPXL',10) > 79:
                    self.AH(['BIL','UVXY','SQQQ'],1,0.33)
                else:
                    if self.CumReturn('TQQQ',4) > 0.2:
                        if self.RSI('TQQQ',10) < 31:
                            self.AH('TQQQ',1,1)
                        else:
                            if self.RSI('UVXY',10) > self.RSI('SQQQ',10):
                                self.AH(['BIL','UVXY','SQQQ'],1,0.33)
                            else:
                                self.AH('SQQQ',1,1)
                    else:
                        self.AH('TQQQ',1,1)
        else:
            if self.RSI('TQQQ',10) < 31:
                self.AH('TECL',1,1)
            else:
                if self.RSI('SMH',10) < 30:
                    self.AH('SOXL',1,1)
                else:
                    if self.RSI('DIA',10) < 27:
                        self.AH('UDOW',1,1)
                    else:
                        if self.RSI('SPY',14) < 28:
                            self.AH('UPRO',1,1)
                        else:
                            self.Group1()
                            self.Group2()
    def Group1(self):
        if self.CumReturn('QQQ',200) < -0.2:
            if self.Securities['QQQ'].Price < self.SMA('QQQ',20):
                if self.CumReturn('QQQ',60) < -0.12:
                    self.Group5()
                    self.Group6()
                else:
                    if self.RSI('TLT',10) > self.RSI('SQQQ',10):
                        self.AH('TQQQ',1,0.5)
                    else:
                        self.AH('SQQQ',1,0.5)
            else:
                if self.RSI('SQQQ',10) < 31:
                    self.AH('PSQ',1,0.5)
                else:
                    if self.CumReturn('QQQ',9) > 0.055:
                        self.AH('PSQ',1,0.5)
                    else:
                        if self.RSI('QQQ',10) > self.RSI('SMH',10):
                            self.AH('QQQ',1,0.5)
                        else:
                            self.AH('SMH',1,0.5)
        else:
            if self.Securities['QQQ'].Price < self.SMA('QQQ',20):
                if self.RSI('TLT',10) > self.RSI('SQQQ',10):
                    self.AH('TQQQ',1,0.5)
                else:
                    self.AH('SQQQ',1,0.5)
            else:
                if self.RSI('SQQQ',10) < 31:
                    self.AH('SQQQ',1,0.5)
                else:
                    if self.CumReturn('QQQ',9) > 0.055:
                        self.AH('SQQQ',1,0.5)
                    else:
                        if self.RSI('TQQQ',10) > self.RSI('SOXL',10):
                            self.AH('TQQQ',1,0.5)
                        else:
                            self.AH('SOXL',1,0.5)
    def Group2(self):
        if self.Securities['QQQ'].Price < self.SMA('QQQ',20):
            if self.CumReturn('QQQ',60) < -0.12:
                self.Group3()
                self.Group4()
            else:
                if self.RSI('TLT',10) > self.RSI('SQQQ',10):
                    self.AH('TQQQ',1,0.5)
                else:
                    self.AH('SQQQ',1,0.5)
        else:
            if self.RSI('SQQQ',10) < 31:
                self.AH('SQQQ',1,0.5)
            else:
                if self.CumReturn('QQQ',70) < -0.15:
                    if self.RSI('TQQQ',10) > self.RSI('SOXL',10):
                        self.AH('TQQQ',1,0.5)
                    else:
                        self.AH('SOXL',1,0.5)
                else:
                    self.Sort("CumReturn",["SPY","QQQ","DIA","XLP"],14,True,1,0.5)
    def Group3(self):
        if self.Securities['SPY'].Price > self.SMA('SPY',20):
            self.AH('SPY',1,0.25)
        else:
            if self.RSI('TLT',10) > self.RSI('SQQQ',10):
                self.AH('QQQ',1,0.25)
            else:
                self.AH('PSQ',1,0.25)
    def Group4(self):
        if self.RSI('TLT',10) > self.RSI('SQQQ',10):
            self.AH('QQQ',1,0.25)
        else:
            self.AH('PSQ',1,0.25)
    def Group5(self):
        if self.Securities['SPY'].Price > self.SMA('SPY',20):
            self.AH('SPY',1,0.25)
        else:
            if self.RSI('TLT',10) > self.RSI('SQQQ',10):
                self.AH('QQQ',1,0.25)
            else:
                self.AH('PSQ',1,0.25)
    def Group6(self):
        if self.RSI('TLT',10) > self.RSI('SQQQ',10):
            self.AH('QQQ',1,0.25)
        else:
            self.AH('PSQ',1,0.25)

    def SOXXRSIMachine(self):
        if self.RSI('SOXX',10) > 75:
            self.AH('SOXS',2,self.TA1110)
        else:
            if self.RSI('SOXX',2) < 41:
                if self.RSI('SOXL',10) < 57:
                    self.AH('SOXL',2,self.TA1110)
                else:
                    self.AH('SOXS',2,self.TA1110)
            else:
                self.GainTrainDGAF()
    def GainTrainDGAF(self):
        self.S13()
        self.S12()
        self.O9()
    def S13(self):
        if self.EMA('UUP',42) > self.EMA('UUP',100):
            self.Sort("RSI",["UUP","USDU"],14,False,2,self.TA1111)
        else:
            self.Sort("STD",["BIL","SOXL","DBC"],14,True,2,self.TA1111)

    def S12(self):
        if 50 < self.RSI('IEF',10):
            if self.RSI('SPY',7) > 76:
                self.O8()
            else:
                self.Sort("MaxDD",["SOXL","SMH"],6,True,2,self.TA1120)
        else:
            if self.RSI('SPY',7) < 27:
                self.E7()
            else:
                self.AH(['UGL','SH','PSQ'],2,self.TA1121)
    def O8(self):
        self.AH('UGL',2,self.TA1120)
    def E7(self):
        if self.RSI('SHY',10) < self.RSI('VTI',10):
            self.AH('SOXS',2,self.TA1120)
        else:
            self.AH('SOXL',2,self.TA1120)
    def O9(self):
        self.S10()
        self.S11()
    def S10(self):
        if self.RSI('COST',14) < 69:
            if self.MaxDD('SPY',5) > 0.12:
                self.AH('BIL',2,self.TA1130)
            else:
                self.AH('COST',2,self.TA1130)
        else:
            self.AH('BIL',2,self.TA1130)
    def S11(self):
        if self.RSI('UNH',14) < 79:
            if self.MaxDD('SPY',5) > 0.12:
                self.AH('BIL',2,self.TA1140)
            else:
                self.AH('UNH',2,self.TA1140)
        else:
            self.AH('BIL',2,self.TA1140)
    def TQQQorNOT(self):
        if self.RSI('TQQQ',10) > 78:
            self.AH(['BIL','UVXY','SQQQ'],3,self.TA1210/3)
        else:
            if self.CumReturn('TQQQ',6) < -0.12:
                if self.CumReturn('TQQQ',1) > 0.055:
                    self.AH(['BIL','UVXY','SQQQ'],3,self.TA1210/3)
                else:
                    if self.RSI('TQQQ',10) < 32:
                        self.AH('TQQQ',3,self.TA1210)
                    else:
                        if self.MaxDD('TMF',10)<0.07:
                            self.AH('TQQQ',3,self.TA1210)
                        else:
                            self.AH('BIL',3,self.TA1210)
            else:
                if self.MaxDD('QQQ',10)>0.06:
                    self.AH('BIL',3,self.TA1210)
                else:
                    if self.MaxDD('TMF',10)>0.07:
                        self.AH('BIL',3,self.TA1210)
                    else:
                        if self.Securities['QQQ'].Price > self.SMA('QQQ',25):
                            self.AH('TQQQ',3,self.TA1210)
                        else:
                            if self.RSI('SPY',60) > 50:
                                if self.RSI('BND',45) > self.RSI('SPY',45):
                                    self.AH('TQQQ',3,self.TA1210)
                                else:
                                    self.AH('BIL',3,self.TA1210)
                            else:
                                if self.RSI('IEF',200) < self.RSI('TLT',200):
                                    if self.RSI('BND',45) > self.RSI('SPY',45):
                                        self.AH('TQQQ',3,self.TA1210)
                                    else:
                                        self.AH('BIL',3,self.TA1210)
                                else:
                                    self.AH('BIL',3,self.TA1210)
    def DereckCustomBetaBaller(self):
        if self.SMADayRet('TLT',350) < self.SMADayRet('TLT',550):
            if self.Securities['SPY'].Price < self.SMA('SPY',200):
                self.V1()
            else:
                self.B2()
        else:
            self.N3()
    def V1(self):
        if self.RSI('BIL',8) < 35:
            if self.RSI('TQQQ',10) > 80:
                self.O6()
            else:
                self.AH('SOXL',4,1)
        else:
            if self.RSI('SPY',6) < 27:
                self.E77()
            else:
                self.B5()
    def O6(self):
        self.Sort("RSI",["VIXM","VIXY"],13,False,4,1)

    def E77(self):
        if self.RSI('BSV',7) < self.RSI('SPHB',7):
            self.Sort("RSI",["SOXS","SOXS"],7,False,4,1)
        else:
           self.Sort("RSI",["SOXL","TECL"],7,False,4,1)
    def B5(self):
        if self.RSI('BSV',7) > self.RSI('SHY',7):
            self.B4()
        else:
            self.AH('SOXL',4,1)
    def B4(self):
        if self.RSI('QQQ',10) < 30:
            self.Sort("SMADayRet",["TQQQ","SPXL","SOXL","UPRO"],5,True,4,1)
        else:
            if self.RSI('SPY',10) < 30:
                self.AH('UPRO',4,1)
            else:
                if self.Securities['QLD'].Price > self.SMA('QLD',20):
                    self.B14()
                else:
                    self.A42()
    def B14(self):
        if 50 > self.RSI('IEF',7):
            self.B15()
        else:
            if self.RSI('SPY',6) > 75:
                self.AH(['BIL','UVXY','SQQQ'],4,0.33)
            else:
                self.AH('SOXL',4,1)
    def B15(self):
        if self.Securities['TLT'].Price < self.SMA('TLT',21):
            self.B16()
        else:
            self.B17()
    def B16(self):
        if self.EMA('SPY',210) <= self.SMA('SPY',360):
            if self.RSI('TQQQ',10) < 30:
                self.Sort("SMADayRet",["TQQQ","SOXL","UPRO"],5,True,4,1)
            else:
                if self.CumReturn('SPY',2) < -0.02:
                    self.Sort("CumReturn",["SPXS","TECS","SOXS","SQQQ","ERX"],5,False,4,1)
                else:
                    if self.CumReturn('SPXU',6) > self.CumReturn('UPRO',3):
                        self.Sort("CumReturn",["SOXS","SQQQ","EPI"],5,True,4,1)
                    else:
                        self.Sort("SMADayRet",["TECL","SOXL","TMV"],5,False,4,1)
        else:
            if self.SMADayRet('SPY',210) > self.SMADayRet('DBC',360):
                if self.RSI('TQQQ',11) > 77:
                    self.AH(['BIL','UVXY','SQQQ'],4,0.33)
                else:
                    if self.CumReturn('TQQQ',6) < -0.1:
                        if self.CumReturn('TQQQ',1) > 0.055:
                            self.AH(['BIL','UVXY','SQQQ'],4,0.33)
                        else:
                            self.Sort("SMADayRet",["SOXL","IYK","TMV"],5,False,4,1)
                    else:
                        if 50 < self.RSI('IEF',7):
                            self.Sort("SMADayRet",["TQQQ","IYK","SOXL","UPRO","TECL"],5,True,4,1)
                        else:
                            self.Sort("SMADayRet",["SOXL","IYK","UPRO"],22,False,4,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.AH('TMV',4,1)
                else:
                    self.AH('DBC',4,1)
            else:
                if 50 < self.RSI('IEF',7):
                    self.Sort("SMADayRet",["TMV","SOXS","SPXU"],5,True,4,1)

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

            else:
                self.Sort("CumReturn",["EWZ","TECS","SOXS","EUO","YCS","TMV"],5,False,4,1)
    def B17(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,4,1)
            else:
                if self.CumReturn('SPXU',6) > self.CumReturn('UPRO',3):
                    self.Sort("CumReturn",["BIL","AGG","TMF"],5,False,4,1)
                else:
                    self.Sort("SMADayRet",["TECL","SOXL","TQQQ","EWZ","TMF"],5,False,4,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.AH(['BIL','UVXY','SQQQ'],4,0.33)
                    else:
                        if self.CumReturn('TQQQ',6) < -0.1:
                            if self.CumReturn('TQQQ',1) > 0.055:
                                self.AH(['BIL','UVXY','SQQQ'],4,0.33)
                            else:
                                self.Sort("SMADayRet",["TECL","TQQQ","SPXL","EPI","SOXL","UPRO","QLD","EWZ","MVV","XLU","IYK","USD","TMF"],7,False,4,1)
                        if 50 < self.RSI('IEF',7):
                            self.Sort("SMADayRet",["TECL","SPXL","EPI","SOXL","UPRO","MVV"],7,False,4,1)
                        else:
                            self.Sort("CumReturn",["SOXS","TMF"],5,True,4,1)
                else:
                    self.Sort("RSI",["SPXS","SQQQ","TECS","SOXS"],5,False,4,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,4,1)
        else:
            self.Sort("SMADayRet",["TECL","TQQQ","SOXL","TMF"],5,True,4,1)
    def A42(self):
        if self.RSI('TQQQ',9) < 32:
            if self.CumReturn('TQQQ',2) > self.CumReturn('TQQQ',5):
                self.A41()
            else:
                self.Sort("RSI",["TMF","UCO","USD","SOXL","SQQQ"],5,False,4,1)
        else:
             self.A43()
    def A41(self):
        self.Substrategy1()
        self.Substrategy2()
    def Substrategy1(self):
        self.Sort("RSI",["TECL","SOXL","SHY"],10,False,4,0.5)
    def Substrategy2(self):
        self.Sort("RSI",["SHY","SOXL"],5,False,4,0.5)
    def A43(self):
        if self.Securities['TLT'].Price > self.SMA('TLT',200):
            self.A19()
        else:
            self.B18()
    def A19(self):
        if self.SMADayRet('TLT',20) < 0:
            self.A44()
        else:
            self.A55()
    def A44(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,4,1)
            else:
                if self.CumReturn('SPXU',6) > self.CumReturn('UPRO',3):
                    self.Sort("CumReturn",["SOXS","EUO","YCS"],5,True,4,1)
                else:
                    self.Sort("SMADayRet",["TECL","SOXL","TQQQ","CURE"],5,False,4,1)
        else:
            if self.RSI('TQQQ',11) > 77:
                self.AH(['BIL','UVXY','SQQQ'],4,0.33)
            else:
                self.Sort("SMADayRet",["SOXL","TECL","TMV","TQQQ","UPRO"],5,False,4,1)
    def A55(self):
        if self.EMA('SPY',210) <= self.SMA('SPY',360):
            if self.RSI('TQQQ',10) < 30:
                self.Sort("SMADayRet",["TECL","SOXL","TQQQ"],5,False,4,1)
            else:
                if self.CumReturn('SPY',2) < -0.02:
                    self.Sort("CumReturn",["TECS","SOXS","SQQQ"],5,True,4,1)
                else:
                    if self.CumReturn('SPXU',6) > self.CumReturn('UPRO',3):
                        self.Sort("CumReturn",["ERX","EUO","YCS"],5,True,4,1)
                    else:
                        self.Sort("SMADayRet",["EWZ","SOXL","MVV","USD"],5,False,4,1)
        else:
            if self.SMADayRet('SPY',210) > self.SMADayRet('DBC',360):
                if self.RSI('TQQQ',11) > 77:
                    self.AH(['BIL','UVXY','SQQQ'],4,0.33)
                else:
                    if self.CumReturn('TQQQ',6) < -0.1:
                        if self.CumReturn('TQQQ',1) > 0.055:
                            self.AH(['BIL','UVXY','SQQQ'],4,0.33)
                        else:
                            if 50 < self.RSI('IEF',7):
                                self.AH(['BIL','UVXY','SQQQ'],4,0.33)
                            else:
                                self.Sort("CumReturn",["EWZ","UUP","TMF","UCO"],5,True,4,1)
                    else:
                        if 50 < self.RSI('IEF',7):
                            self.Sort("SMADayRet",["TQQQ","SPXL","QLD","USD","TECL"],5,False,4,1)
                        else:
                            self.Sort("CumReturn",["EWZ","EWZ","TMF"],5,True,4,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,4,1)
        else:
            if 50 < self.RSI('IEF',7):
                self.Sort("SMADayRet",["SOXL","USD","TMF"],5,False,4,1)
            else:
                self.Sort("CumReturn",["EWZ","SPXS","SOXS","UCO","YCS"],5,True,4,1)
    def B18(self):
        if self.SMADayRet('TLT',20) < 0:
            self.A57()
        else:
            self.B17()
    def A57(self):
        if self.EMA('SPY',210) <= self.SMA('SPY',360):
            if self.RSI('TQQQ',10) < 30:
                self.Sort("SMADayRet",["TQQQ","SOXL","UPRO"],5,True,4,1)
            else:
                if self.CumReturn('SPY',2) < -0.02:
                    self.Sort("CumReturn",["SPXS","TECS","SOXS","SQQQ","ERX"],5,False,4,1)
                else:
                    if self.CumReturn('SPXU',6) > self.CumReturn('UPRO',3):
                        self.Sort("CumReturn",["SOXS","SQQQ","EPI"],5,True,4,1)
                    else:
                        self.Sort("SMADayRet",["TECL","SOXL","TMV"],5,False,4,1)
        else:
            if self.SMADayRet('SPY',210) > self.SMADayRet('DBC',360):
                if self.RSI('TQQQ',11) > 77:
                    self.AH(['BIL','UVXY','SQQQ'],4,0.33)
                else:
                    if self.CumReturn('TQQQ',6) < -0.1:
                        if self.CumReturn('TQQQ',1) > 0.055:
                            self.AH(['BIL','UVXY','SQQQ'],4,0.33)
                        else:
                            self.Sort("SMADayRet",["SOXL","IYK","TMV"],5,False,4,1)
                    else:
                        if 50 < self.RSI('IEF',7):
                            self.Sort("SMADayRet",["TQQQ","SOXL","IYK","TMV","UPRO","TECL"],5,True,4,1)
                        else:
                            self.Sort("SMADayRet",["SOXL","IYK","UPRO"],22,False,4,1)
            else:
                self.Defence()
    def B2(self):
        if self.RSI('SPY',40) > 75:
            if 50 < self.RSI('IEF',7):
                self.AH('QQQ',4,1)
            else:
                self.AH(['BIL','UVXY','SQQQ'],4,0.33)
        else:
            self.A54()
    def A54(self):
        if 50 > self.RSI('IEF',7):
            self.A53()
        else:
            if self.RSI('SPY',6) > 75:
                self.AH(['BIL','UVXY','SQQQ'],4,0.33)
            else:
                self.AH('SOXL',4,1)
    def A53(self):
        if self.RSI('TQQQ',14) > 75:
            self.AH(['BIL','UVXY','SQQQ'],4,0.33)
        else:
            if self.RSI('SPXL',10) > 80:
                self.AH(['BIL','UVXY','SQQQ'],4,0.33)
            else:
                self.B23()
    def B23(self):
        if self.Securities['TLT'].Price > self.SMA('TLT',200):
            self.A24()
        else:
            self.A52()
    def A24(self):
        if self.RSI('TLT',14) < 50:
            self.A22()
        else:
            self.A26()
    def A22(self):
        if self.Securities['TLT'].Price > self.SMA('TLT',5):
            self.A25()
        else:
            self.A51()
    def A25(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,4,1)
            else:
                if self.CumReturn('SPXU',6) > self.CumReturn('UPRO',3):
                    self.Sort("CumReturn",["TECS","SOXS","SQQQ","TMF","SHY"],5,True,4,1)
                else:
                    self.Sort("SMADayRet",["TECL","SOXL","UPRO","EWZ","TMF","TQQQ"],5,False,4,1)
        else:
            if self.CumReturn('TQQQ',6) < -0.1:
                self.Sort("SMADayRet",["TECL","TQQQ","TMF"],7,False,4,1)
            else:
                self.Sort("SMADayRet",["SOXL","TMF"],7,False,4,1)
    def A51(self):
        if self.RSI('TLT',14) < 20:
            self.AH('SHY',4,1)
        else:
            if self.SMADayRet('TLT',20) < 0:
                self.A21()
            else:
                self.A50()
    def A21(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,4,1)
            else:
                self.Sort("SMADayRet",["TQQQ","SOXL","CURE","EWZ","SHY"],5,False,4,1)
        else:
            if self.SMA('SPY',210) > self.SMA('DBC',360):
                if self.RSI('TQQQ',11) > 77:
                    self.AH(['BIL','UVXY','SQQQ'],4,0.33)
                else:
                    if self.CumReturn('TQQQ',6) < -0.1:
                        if self.CumReturn('TQQQ',1) > 0.055:
                            self.AH(['BIL','UVXY','SQQQ'],4,0.33)
                        else:
                            self.Sort("SMADayRet",["TECL","TQQQ","SOXL","UPRO","TMV","SHY"],5,False,4,1)
                    else:
                        self.Sort("SMADayRet",["TECL","TQQQ","SOXL","UPRO","TMV","SHY"],5,True,4,1)
            else:
                self.A49()
    def A49(self):
        if self.STD('DBC',20) > self.STD('SPY',20):
            self.Sort("RSI",["EEM","TECS","SOXS","TMV"],5,False,4,1)
        else:
            self.Sort("RSI",["EEM","TECS","SOXS","TMV"],10,False,4,1)
    def A50(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,4,1)
            else:
                self.Sort("SMADayRet",["TECL","TQQQ","SOXL","TMF"],5,False,4,1)
        elif self.SMADayRet('SPY',210) > self.SMADayRet('DBC',360):
            if self.RSI('TQQQ',11) > 77:
                self.AH(['BIL','UVXY','SQQQ'],4,0.33)
            elif self.CumReturn('TQQQ',6) < -0.1:
                if self.CumReturn('TQQQ',1) > 0.055:
                    self.AH(['BIL','UVXY','SQQQ'],4,0.33)
                else:
                    self.Sort("SMADayRet",["TECL","TQQQ","SPXL","EPI","SOXL","UPRO","QLD","EWZ","MVV","PUI","IYK","USD","TMF"],7,False,4,1)
            else:
                if 50 < self.RSI('IEF',7):
                    self.Sort("SMADayRet",["TECL","TQQQ","SOXL","PUI"],5,False,4,1)
                else:
                    self.Sort("CumReturn",["SOXS","SQQQ","UCO","DIG"],5,False,4,1)
        else:
            self.Sort("SMADayRet",["EPI","UPRO","SOXL","TQQQ"],5,True,4,1)
    def A26(self):
        if self.RSI('TLT',14) > 80:
            self.A27()
        else:
            if self.Securities['TLT'].Price < self.SMA('TLT',21):
                self.A44()
            else:
                self.A55()
    def A27(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.AH(['BIL','UVXY','SQQQ'],4,0.33)
                else:
                    self.Sort("SMADayRet",["TECL","TQQQ","SOXL","UPRO"],5,False,4,1)
            else:
                self.Sort("RSI",["SQQQ","TECS","SOXS","TMV"],5,True,4,1)
        else:
            self.Sort("SMADayRet",["EPI","UPRO","SOXL","TQQQ","TMV"],5,True,4,1)
    def A52(self):
        if self.Securities['TLT'].Price < self.SMA('TLT',21):
            self.A57()
        else:
            self.A56()
    def A56(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,4,1)
            elif self.CumReturn('SPXU',6) >= self.CumReturn('UPRO',3):
                self.Sort("CumReturn",["BIL","AGG","TMF"],5,False,4,1)
            else:
                self.Sort("SMADayRet",["TECL","TQQQ","SOXL","EWZ","TMF"],5,False,4,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.AH(['BIL','UVXY','SQQQ'],4,0.33)
                elif self.CumReturn('TQQQ',6) < -0.1:
                    if self.CumReturn('TQQQ',1) > 0.055:
                        self.AH(['BIL','UVXY','SQQQ'],4,0.33)
                    else:
                        self.Sort("SMADayRet",["TECL","TQQQ","SPXL","EPI","SOXL","UPRO","QLD","EWZ","MVV","XLU","IYK","USD","TMF"],7,False,4,1)
                elif 50 < self.RSI('IEF',7):
                    self.Sort("SMADayRet",["TECL","SPXL","EPI","SOXL","UPRO","MVV","UGE"],7,False,4,1)
                else:
                    self.Sort("CumReturn",["SOXS","TMF"],5,True,4,1)
            else:
                self.Sort("RSI",["SPXS","SQQQ","TECS","SOXS"],5,False,4,1)
        else:
            self.Defence2()
    def N3(self):
        if self.Securities['SPY'].Price > self.SMA('SPY',200):
            if self.RSI('QQQ',14) > 80:
                self.AH(['BIL','UVXY','SQQQ'],4,0.33)
            else:
                if self.RSI('SPY',10) > 80:
                    self.AH(['BIL','UVXY','SQQQ'],4,0.33)
                else:
                    self.A31()
        else:
            if self.RSI('TQQQ',9) < 32:
                if self.CumReturn('TQQQ',2) >= self.CumReturn('TQQQ',5):
                    self.A41()
                else:
                    if self.RSI('SPY',10) < 30:
                        self.A40()
                    else:
                        if self.Securities['TQQQ'].Price > self.SMA('TQQQ',20):
                            if self.RSI('SQQQ',10) < 31:
                                self.AH('SQQQ',4,1)
                            else:
                                self.AH('TQQQ',4,1)
                        else:
                            self.Sort("RSI",["TMF","UCO","USD","SOXL","SQQQ"],5,False,4,1)
            else:
                self.A31()
    def A31(self):
        if self.Securities['TLT'].Price > self.SMA('TLT',200):
            self.A30()
        else:
            self.A37()
    def A30(self):
        if self.RSI('TLT',14) < 50:
            self.A29()
        else:
            self.A28()
    def A29(self):
        if self.Securities['TLT'].Price > self.SMA('TLT',5):
            self.A32()
        else:
            self.A33()
    def A32(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,4,1)
            else:
                if self.CumReturn('SPXU',6) >= self.CumReturn('UPRO',3):
                    self.Sort("CumReturn",["TECS","SOXS","SQQQ","TMF","SHY"],5,True,4,1)
                else:
                    self.Sort("SMADayRet",["TECL","TQQQ","SOXL","UPRO","EWZ","TMF"],5,False,4,1)
        else:
            if self.CumReturn('TQQQ',6) < -0.1:
                self.Sort("SMADayRet",["TECL","TQQQ","TMF"],7,False,4,1)
            else:
                self.Sort("SMADayRet",["SOXL","TMF"],7,False,4,1)
    def A33(self):
        if self.RSI('TLT',14) < 20:
            self.AH('TMF',4,1)
        else:
            if self.SMADayRet('TLT',20) < 0:
                self.A21()
            else:
                self.A34()
    def A34(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,4,1)
            else:
                self.Sort("SMADayRet",["TECL","TQQQ","SOXL","TMF"],5,False,4,1)
        elif self.SMA('SPY',210) > self.SMA('DBC',360):
            if self.RSI('TQQQ',11) > 77:
                self.AH(['BIL','UVXY','SQQQ'],4,0.33)
            elif self.CumReturn('TQQQ',6) < -0.1:
                if self.CumReturn('TQQQ',1) > 0.055:
                    self.AH(['BIL','UVXY','SQQQ'],4,0.33)
                else:
                    self.Sort("SMADayRet",["TECL","TQQQ","EPI","SOXL","UPRO","QLD","EWZ","MVV","XLU","USD","TMF"],7,False,4,1)
            elif 50 < self.RSI('IEF',7):
                self.Sort("SMADayRet",["TECL","TQQQ","SOXL","XLU"],5,False,4,1)
            else:
                self.Sort("CumReturn",["SOXS","SQQQ","UCO","DIG"],5,False,4,1)
        else:
            self.Sort("SMADayRet",["EPI","UPRO","SOXL","TQQQ"],5,True,4,1)
    def A28(self):
        if self.RSI('TLT',14) > 80:
            self.A27()
        else:
            self.A35()
    def A35(self):
        if self.SMADayRet('TLT',20) < 0:
            self.A44()
        else:
            self.A36()
    def A36(self):
        if self.EMA('SPY',210) <= self.SMA('SPY',360):
            if self.RSI('TQQQ',10) < 30:
                self.Sort("SMADayRet",["TECL","TQQQ","SOXL"],5,False,4,1)
            elif self.CumReturn('SPY',2) <= -0.02:
                self.Sort("CumReturn",["TECS","SOXS","SQQQ"],5,True,4,1)
            elif self.CumReturn('SPXU',6) >= self.CumReturn('UPRO',3):
                self.Sort("CumReturn",["ERX","EUO","YCS"],5,True,4,1)
            else:
                self.Sort("SMADayRet",["SOXL","EWZ","MVV","USD"],5,False,4,1)
        elif self.SMADayRet('SPY',210) > self.SMADayRet('DBC',360):
            if self.RSI('TQQQ',11) > 77:
                self.AH(['BIL','UVXY','SQQQ'],4,0.33)
            elif self.CumReturn('TQQQ',6) < -0.1:
                if self.CumReturn('TQQQ',1) > 0.055:
                    self.AH(['BIL','UVXY','SQQQ'],4,0.33)
                elif 50 < self.RSI('IEF',7):
                    self.AH('SOXL',4,1)
                else:
                    self.Sort("CumReturn",["EWZ","UUP","TMF","UCO"],5,True,4,1)
            elif 50 < self.RSI('IEF',7):
                self.Sort("SMADayRet",["TECL","TQQQ","UPRO","QLD","USD"],5,False,4,1)
            else:
                self.Sort("CumReturn",["EWZ","UUP","TMF"],5,True,4,1)
        else:
            self.A45()
    def A45(self):
        if self.STD('DBC',20) > self.STD('SPY',20):
            self.Sort("RSI",["SHY","EWZ","GLD","SPXU","TECS","SOXS","UCO","YCS"],5,False,4,1)
        elif 50 < self.RSI('IEF',7):
            self.Sort("SMADayRet",["SOXL","USD","TMF"],5,False,4,1)
        else:
            self.Sort("CumReturn",["EWZ","SPXU","SOXS","UCO","YCS"],5,True,4,1)
    def A37(self):
        if self.Securities['TLT'].Price < self.SMA('TLT',21):
            self.A38()
        else:
            self.A39()
    def A38(self):
        if self.EMA('SPY',210) <= self.SMA('SPY',360):
            if self.RSI('TQQQ',10) < 30:
                self.Sort("SMADayRet",["TQQQ","SOXL","UPRO"],5,True,4,1)
            else:
                if self.CumReturn('SPY',2) <= -0.02:
                    self.Sort("CumReturn",["SPXU","TECS","SOXS","SQQQ","ERX"],5,False,4,1)
                else:
                    if self.CumReturn('SPXU',6) >= self.CumReturn('UPRO',3):
                        self.Sort("CumReturn",["SOXS","SQQQ","EPI"],5,True,4,1)
                    else:
                        self.Sort("SMADayRet",["TECL","SOXL","TMV"],5,False,4,1)
        else:
            if self.SMA('SPY',210) > self.SMA('DBC',360):
                if self.RSI('TQQQ',11) > 77:
                    self.AH(['BIL','UVXY','SQQQ'],4,0.33)
                else:
                    if self.CumReturn('TQQQ',6) < -0.1:
                        if self.CumReturn('TQQQ',1) > 0.055:
                            self.AH(['BIL','UVXY','SQQQ'],4,0.33)
                        else:
                            self.Sort("SMADayRet",["SOXL","IYK","TMV"],5,False,4,1)
                    else:
                        if 50 < self.RSI('IEF',7):
                            self.Sort("SMADayRet",["TQQQ","SOXL","UPRO","TMV","TECL"],5,True,4,1)
                        else:
                            self.Sort("SMADayRet",["SOXL","UPRO","IYK"],22,False,4,1)
            else:
                self.A46()
    def A46(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.AH('TMV',4,1)
                else:
                    self.AH('DBC',4,1)
            else:
                if 50 < self.RSI('IEF',7):
                    self.Sort("SMADayRet",["TMV","SOXS","SPXU"],5,True,4,1)
                else:
                    self.Sort("CumReturn",["EFA","EEM","SPXU","SOXS","UCO","TMV"],5,False,4,1)
        else:
            if 50 < self.RSI('IEF',7):
                self.Sort("SMADayRet",["EPI","SOXL","UPRO"],5,False,4,1)
            else:
                self.Sort("CumReturn",["EWZ","TECS","SOXS","EUO","YCS","TMV"],5,True,4,1)
    def A39(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,4,1)
            else:
                if self.CumReturn('SPXU',6) >= self.CumReturn('UPRO',3):
                    self.Sort("CumReturn",["BIL","AGG","TMF"],5,False,4,1)
                else:
                    self.Sort("CumReturn",["TECL","TQQQ","SOXL","EWZ","TMF"],5,False,4,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.AH(['BIL','UVXY','SQQQ'],4,0.33)
                    else:
                        if self.CumReturn('TQQQ',6) < -0.1:
                            if self.CumReturn('TQQQ',1) > 0.055:
                                self.AH(['BIL','UVXY','SQQQ'],4,0.33)
                            else:
                                self.Sort("SMADayRet",["TECL","TQQQ","EPI","SOXL","UPRO","QLD","EWZ","MVV","XLU","USD","TMF"],7,True,4,1)
                        else:
                            if 50 < self.RSI('IEF',7):
                                self.Sort("SMADayRet",["TECL","EPI","SOXL","UPRO","MVV"],7,False,4,1)
                            else:
                                self.Sort("CumReturn",["SOXS","TMF"],5,True,4,1)
                else:
                    self.Sort("RSI",["SPXU","SQQQ","TECS","SOXS"],5,False,4,1)
            else:
                self.A47()
    def A47(self):
        if self.STD('DBC',20) > self.STD('SPY',20):
            self.Sort("RSI",["SPXU","EPI","TECS","SOXS","SQQQ"],5,False,4,1)
        else:
            self.Sort("SMADayRet",["TECL","TQQQ","SOXL","TMF"],5,True,4,1)
    def A40(self):
        self.Sort("SMADayRet",["TECL","TQQQ","SOXL","UPRO","QLD"],5,False,4,1)
    def ExecuteTrade(self):
        group1 = {
            '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]
        }
        df1 = pd.DataFrame(group1)
        group2 = {
            'HTS': [self.HTS2[i][0] if len(self.HTS2[i]) == 1 else self.HTS2[i] for i in self.HTS2],
            'HT': [self.HT2[i] for i in self.HT2]
        }
        df2 = pd.DataFrame(group2)
        group3 = {
            'HTS': [self.HTS3[i][0] if len(self.HTS3[i]) == 1 else self.HTS3[i] for i in self.HTS3],
            'HT': [self.HT3[i] for i in self.HT3]
        }
        df3 = pd.DataFrame(group3)
        group4 = {
            'HTS': [self.HTS4[i][0] if len(self.HTS4[i]) == 1 else self.HTS4[i] for i in self.HTS4],
            'HT': [self.HT4[i] for i in self.HT4]
        }
        df4 = pd.DataFrame(group4)
        group5 = {
            'HTS': [self.HTS5[i][0] if len(self.HTS5[i]) == 1 else self.HTS5[i] for i in self.HTS5],
            'HT': [self.HT5[i] for i in self.HT5]
        }
        df5 = pd.DataFrame(group5)
        group6 = {
            'HTS': [self.HTS6[i][0] if len(self.HTS6[i]) == 1 else self.HTS6[i] for i in self.HTS6],
            'HT': [self.HT6[i] for i in self.HT6]
        }
        df6 = pd.DataFrame(group6)
        group7 = {
            'HTS': [self.HTS7[i][0] if len(self.HTS7[i]) == 1 else self.HTS7[i] for i in self.HTS7],
            'HT': [self.HT7[i] for i in self.HT7]
        }
        df7 = pd.DataFrame(group7)
        group8 = {
            'HTS': [self.HTS8[i][0] if len(self.HTS8[i]) == 1 else self.HTS8[i] for i in self.HTS8],
            'HT': [self.HT8[i] for i in self.HT8]
        }
        df8 = pd.DataFrame(group8)
        df = pd.concat([df1,df2,df3,df4,df5,df6,df7,df8])
        df['HTS'] = df['HTS'].astype(str)
        result = df.groupby(['HTS']).sum().reset_index()
        # Dictionary with pairs
        pairs_dict = {'SOXL':'SOXS','TQQQ':'SQQQ','SPXL':'SPXS','WEBL':'WEBS','TECL':'TECS','UPRO':'SPXU','QQQ':'PSQ','SPY':'SH','TMV':'TMF','HIBL':'HIBS','BITO':'BITI','TSLA':'TSLS','AAPL':'AAPD','ERX':'ERY','BOIL':'KOLD','LABU':'LABD','JNUG':'JDST','ARKK':'SARK','IBIT':'BITI'}
        pairs_dict.update({v: k for k,v in pairs_dict.items()}) #ensure both directions are covered
        # Track selling and buying
        processed_pairs_selling = set()
        processed_pairs_buying = set()
        liquidated_equities = set()
        # Exclude symbols
        exclude_symbols = ['BIL','BSV','SHV','SHY','IEI','STIP','VCIT','LQD','VTIP','TLT','BND','IEF','TIP','VGIT','IYK']
        # dictionary
        symbol_dict = dict(zip(result.iloc[:,0],result.iloc[:,1]))
        # Log output
        output = "*****"
        for symbol, percentage in symbol_dict.items():
            output += "{}: {}% - ".format(symbol, round(percentage*100, 2))
        output = output.rstrip(" - ")
        self.Log(output)
        # Symbols to be transformed
        transform_symbols = ['PSQ','SH','USDU','SPXU','UPRO','QLD','QID','TSLS','ARKK','FNGU','IBIT']
        transform_mapping = {'PSQ':'SQQQ','SH':'SPXS','USDU':'UUP','SPXU':'SPXS','UPRO':'SPXL','QLD':'TQQQ','QID':'SQQQ','TSLS':'TSLQ','ARKK':'TARK','FNGU':'SOXL','GBTC':'BITO','IBIT':'BITO'}
        transform_ratios = {'PSQ':3,'SH':3,'USDU':1,'SPXU':1,'UPRO':1,'QLD':1.5,'QID':1.5,'TSLS':1,'ARKK':2,'FNGU':1,'GBTC':1,'IBIT':1}
        # Transform symbols
        for symbol in transform_symbols:
            if symbol in symbol_dict:
                new_symbol = transform_mapping[symbol]
                ratio = transform_ratios[symbol]
                new_percentage = symbol_dict[symbol]/ratio 
                # Adjust percentage allocation
                if new_symbol in symbol_dict:
                    new_percentage += symbol_dict[new_symbol]
                symbol_dict[new_symbol] = new_percentage
                # Remove transformed
                symbol_dict.pop(symbol, None)
        # Ensure updated equities list
        updated_equities = set(symbol_dict.keys())
        # Liquidate equities
        for equity in self.equities:
            if equity not in updated_equities and self.Portfolio[equity].HoldStock and equity not in liquidated_equities:
                self.Liquidate(equity)
                liquidated_equities.add(equity)
        # Iterate pairs selling
        for symbol1,symbol2 in pairs_dict.items():
            if symbol1 in symbol_dict and symbol2 in symbol_dict:
                offset_value = abs(symbol_dict[symbol1] - symbol_dict[symbol2])
                if symbol_dict[symbol1] >= symbol_dict[symbol2] and self.Portfolio[symbol2].HoldStock:
                    self.Liquidate(symbol2)
                elif symbol_dict[symbol1] <= symbol_dict[symbol2] and self.Portfolio[symbol1].HoldStock:
                    self.Liquidate(symbol1)
                # Mark processed selling
                processed_pairs_selling.add(symbol1)
                processed_pairs_selling.add(symbol2)
        # Iterate remaining selling
        for symbol,value in symbol_dict.items():
            if symbol not in processed_pairs_selling and not value == 0 and symbol not in exclude_symbols and symbol not in self.new_tickers_list:
                percentage_equity = self.Portfolio[symbol].HoldingsValue/self.Portfolio.TotalPortfolioValue
                if value < percentage_equity and abs(value/percentage_equity - 1) > self.buffer_pct:
                    self.SetHoldings(symbol,value)
        # Iterate pairs buying
        for symbol1,symbol2 in pairs_dict.items():
            if symbol1 in symbol_dict and symbol2 in symbol_dict and symbol1 not in processed_pairs_buying and symbol2 not in processed_pairs_buying:
                offset_value = abs(symbol_dict[symbol1] - symbol_dict[symbol2])
                if offset_value > 0.01:
                    if symbol_dict[symbol1] > symbol_dict[symbol2]:
                        self.SetHoldings(symbol1,offset_value)
                    else:
                        self.SetHoldings(symbol2,offset_value)
                else:
                    if self.Portfolio[symbol1].HoldStock:
                        self.Liquidate(symbol1)
                    if self.Portfolio[symbol2].HoldStock:
                        self.Liquidate(symbol2)
                # Mark as processed buying
                processed_pairs_buying.add(symbol1)
                processed_pairs_buying.add(symbol2)
        # Filter less than 1%
        updated_equities = {symbol for symbol, value in symbol_dict.items() if value >= 0.01}
        # Iterate remaining symbol_dict for buying
        for symbol,value in symbol_dict.items():
            if (symbol in updated_equities and 
                symbol not in processed_pairs_buying and 
                symbol not in exclude_symbols and symbol not in self.new_tickers_list):
                percentage_equity = (self.Portfolio[symbol].HoldingsValue /
                                    self.Portfolio.TotalPortfolioValue)
                if value > percentage_equity and abs(percentage_equity/value - 1) > self.buffer_pct:
                    self.SetHoldings(symbol,value)

    def PrintStrategy(self):
        strategy_dataframes = {
            'TQQQFTLT': {
                '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]
            },
            'SOXXRSIMachine': {
                'HTS': [self.HTS2[i][0] if len(self.HTS2[i]) == 1 else self.HTS2[i] for i in self.HTS2],
                'HT': [self.HT2[i] for i in self.HT2]
            },
            'TQQQorNOT': {
                'HTS': [self.HTS3[i][0] if len(self.HTS3[i]) == 1 else self.HTS3[i] for i in self.HTS3],
                'HT': [self.HT3[i] for i in self.HT3]
            },
            'Beta Baller': {
                'HTS': [self.HTS4[i][0] if len(self.HTS4[i]) == 1 else self.HTS4[i] for i in self.HTS4],
                'HT': [self.HT4[i] for i in self.HT4]
            },
            'BEST0d': {
                'HTS': [self.HTS5[i][0] if len(self.HTS5[i]) == 1 else self.HTS5[i] for i in self.HTS5],
                'HT': [self.HT5[i] for i in self.HT5]
            },
            'BEST5d': {
                'HTS': [self.HTS6[i][0] if len(self.HTS6[i]) == 1 else self.HTS6[i] for i in self.HTS6],
                'HT': [self.HT6[i] for i in self.HT6]
            },
            'BEST10d': {
                'HTS': [self.HTS7[i][0] if len(self.HTS7[i]) == 1 else self.HTS7[i] for i in self.HTS7],
                'HT': [self.HT7[i] for i in self.HT7]
            },
            'BEST20d': {
                'HTS': [self.HTS8[i][0] if len(self.HTS8[i]) == 1 else self.HTS8[i] for i in self.HTS8],
                'HT': [self.HT8[i] for i in self.HT8]
            }
        }
        output_strategies = []
        for strategy_name,data in strategy_dataframes.items():
            df = pd.DataFrame(data)
            df['HTS'] = df['HTS'].astype(str)
            result = df.groupby(['HTS']).sum().reset_index()
            valid_results = result[(result['HTS'] != '[]') & (result['HT'] != 0)]
            strategy_output = f"{strategy_name}: " + ','.join([f"{row['HTS']}({row['HT']*100:.2f}%)" for _,row in valid_results.iterrows()])
            output_strategies.append(strategy_output)
        output = '; '.join(output_strategies)
        self.Log(output)
        self.HT1 = {str(i).zfill(2): 0 for i in range(1,10)}
        self.HTS1 = {str(i).zfill(2): [] for i in range(1,10)}
        self.HT2 = {str(i).zfill(2): 0 for i in range(1,10)}
        self.HTS2 = {str(i).zfill(2): [] for i in range(1,10)}
        self.HT3 = {str(i).zfill(2): 0 for i in range(1,10)}
        self.HTS3 = {str(i).zfill(2): [] for i in range(1,10)}
        self.HT4 = {str(i).zfill(2): 0 for i in range(1,10)}
        self.HTS4 = {str(i).zfill(2): [] for i in range(1,10)}
        self.HT5 = {str(i).zfill(2): 0 for i in range(1,30)}
        self.HTS5 = {str(i).zfill(2): [] for i in range(1,30)}
        self.HT6 = {str(i).zfill(2): 0 for i in range(1,30)}
        self.HTS6 = {str(i).zfill(2): [] for i in range(1,30)}
        self.HT7 = {str(i).zfill(2): 0 for i in range(1,30)}
        self.HTS7 = {str(i).zfill(2): [] for i in range(1,30)}
        self.HT8 = {str(i).zfill(2): 0 for i in range(1,30)}
        self.HTS8 = {str(i).zfill(2): [] for i in range(1,30)}