Overall Statistics
Total Trades
905
Average Win
2.05%
Average Loss
-0.75%
Compounding Annual Return
445.358%
Drawdown
34.500%
Expectancy
0.963
Net Profit
1765.419%
Sharpe Ratio
5.253
Probabilistic Sharpe Ratio
99.677%
Loss Rate
47%
Win Rate
53%
Profit-Loss Ratio
2.73
Alpha
2.652
Beta
-0.114
Annual Standard Deviation
0.505
Annual Variance
0.255
Information Ratio
4.951
Tracking Error
0.539
Treynor Ratio
-23.28
Total Fees
$967.96
Estimated Strategy Capacity
$140000.00
Lowest Capacity Asset
BULZ 2T
Portfolio Turnover
43.24%
# This is a conversion of this strategy: https://app.composer.trade/symphony/BVtwgfnVNxNFNbVou8Vl
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 IntelligentSkyRodent(QCAlgorithm):
    def Initialize(self):
        self.cash = 1000
        self.buffer_pct = 0.03
        self.SetStartDate(2022, 1, 1)
        #self.SetEndDate(2023, 1, 31)
        self.SetCash(self.cash)
        self.equities = ['URTY', 'DDM', 'HIBS', 'SRTY', 'SDOW', 'SDS', 'PYPL', 'ADBE', 'NVDA', 'GOOG', 'MSFT', 'AAPL', 'AMZN', 'XLRE', 'XLB', 'BULZ','FNGU','FNGS','SPLV','TMV', 'VCIT', 'XLY', 'HIBL', 'XLK', 'XLP', 'SVXY', 'QID', 'TBF', 'TSLA', 'LQD', 'VTIP', 'EDV', 'STIP', 'SPTL', 'IEI', 'USDU', 'SQQQ', 'VIXM', 'SPXU', 'QQQ', 'BSV', 'TQQQ', 'SPY', 'DBC', 'SHV', 'IAU', 'VEA', 'UTSL', 'UVXY', 'UPRO', 'EFA', 'EEM', 'TLT', 'SHY', 'GLD', 'SLV', 'USO', 'WEAT', 'CORN', 'SH', 'DRN', 'PDBC', 'COMT', 'KOLD', 'BOIL', 'ESPO', 'PEJ', 'UGL', 'URE', 'VXX', 'UUP', 'BND', 'DUST', 'JDST', 'JNUG', 'GUSH', 'DBA', 'DBB', 'COM', 'PALL', 'AGQ', 'BAL', 'WOOD', 'URA', 'SCO', 'UCO', 'DBO', 'TAGS', 'CANE', 'REMX', 'COPX', 'IEF', 'SPDN', 'CHAD', 'DRIP', 'SPUU', 'INDL', 'BRZU', 'ERX', 'ERY', 'CWEB', 'CHAU', 'KORU', 'MEXX', 'EDZ', 'EURL', 'YINN', 'YANG', 'TNA', 'TZA', 'SPXL', 'SPXS', 'MIDU', 'TYD', 'TYO', 'TMF', 'TECL', 'TECS', 'SOXL', 'SOXS', 'LABU', 'LABD', 'RETL', 'DPST', 'DRV', 'PILL', 'CURE', 'FAZ', 'FAS', 'EWA', 'EWGS', 'EWG', 'EWP', 'EWQ', 'EWU', 'EWJ', 'EWI', 'EWN', 'ECC', 'NURE', 'VNQI', 'VNQ', 'VDC', 'VIS', 'VGT', 'VAW', 'VPU', 'VOX', 'VFH', 'VHT', 'VDE', 'SMH', 'DIA', 'UDOW', 'PSQ', 'SOXX', 'VTI', 'COST', 'UNH', 'SPHB', 'BTAL', 'VIXY', 'WEBL', 'WEBS', 'UBT', 'PST', 'TLH', 'QLD', 'SQM', 'SSO', 'SD', 'DGRO', 'SCHD', 'SGOL', 'TIP', 'DUG', 'EWZ', 'TBX', 'VGI', 'XLU', 'XLV', 'EUO', 'YCS', 'MVV', 'USD', 'BIL', 'TMF', 'EPI', 'IYK', 'DIG', 'AGG', 'PUI', 'UDN', 'QQQE', 'VTV', 'VOOG', 'VOOV', 'XLE', 'XLI']

        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.AddEquity('BIL',Resolution.Minute)
        self.Securities['BIL'].SetDataNormalizationMode(DataNormalizationMode.TotalReturn)
       
        self.PT1 = 0.97

        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.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.max()
        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.TQQQOriginal()
        self.ExecuteTrade()

    def TQQQOriginal(self):
        if self.Securities['SPY'].Price > self.SMA('SPY', 200):
            if self.CumReturn('QQQ', 5) < 0:
                self.V1BWCDipBuyStrategy(0.50)
                self.BlackSwanCatcher(0.50)
            else:
                self.BullMarket()
        else:
            self.DipBuyStrategy()

    def V1BWCDipBuyStrategy(self,stock_weight):
        if self.RSI('TQQQ', 2) < 25:
            equities = ["TQQQ", "SOXL", "TECL"]
            returns = {}
            for equity in equities:
                returns[equity] = self.CumReturn(equity, 50)
            sorted_returns = sorted([item for item in returns.items() if item[1] is not None], key=lambda x: x[1], reverse=True)
            t3e = sorted_returns[:3]
            self.AH(t3e[0][0], 1, stock_weight)
        else:
            if self.RSI('SPY', 4) < 25:
                equities = ["UPRO", "URTY", "DDM", "SOXL", "TQQQ", "SVXY"]
                returns = {}
                for equity in equities:
                    returns[equity] = self.CumReturn(equity, 50)
                sorted_returns = sorted([item for item in returns.items() if item[1] is not None], key=lambda x: x[1], reverse=True)
                t3e = sorted_returns[:3]
                self.AH(t3e[0][0], 1, stock_weight/3)
                self.AH(t3e[1][0], 1, stock_weight/3)
                self.AH(t3e[2][0], 1, stock_weight/3)
            else:
                if self.RSI('QQQ', 2) > 95: 
                    self.AH('UVXY', 1, stock_weight/3)

                    equities = ["SQQQ", "SOXS", "TECS"]
                    returns = {}
                    for equity in equities:
                        returns[equity] = self.CumReturn(equity, 50)
                    sorted_returns = sorted([item for item in returns.items() if item[1] is not None], key=lambda x: x[1], reverse=True)
                    t3e = sorted_returns[:3]
                    self.AH(t3e[0][0], 1, stock_weight/3)
                    self.AH(t3e[1][0], 1, stock_weight/3)
                else:
                    if self.RSI('SPY', 3) > 90:
                        self.AH('BTAL', 1, stock_weight/3)

                        equities = ["SDS", "FAZ", "SDOW", "SRTY", "SOXS", "HIBS"]
                        returns = {}
                        for equity in equities:
                            returns[equity] = self.CumReturn(equity, 30)
                        sorted_returns = sorted([item for item in returns.items() if item[1] is not None], key=lambda x: x[1], reverse=True)
                        t3e = sorted_returns[:3]
                        self.AH(t3e[0][0], 1, stock_weight/3)
                        self.AH(t3e[1][0], 1, stock_weight/3)
                    else:
                        if self.RSI('XLRE', 5) < 20:
                            self.AH('DRN', 1, stock_weight)
                        else:
                            if self.RSI('XLRE', 5) > 90:
                                self.AH('DRV', 1, stock_weight)
                            else:
                                if self.RSI('IEI', 5) < 20:
                                    self.AH('TYD', 1, stock_weight)
                                else:
                                    if self.RSI('IEI', 5) > 90:
                                        self.AH('TYO', 1, stock_weight)
                                    else:
                                        self.AH('BIL', 1, stock_weight)

    def BlackSwanCatcher(self,stock_weight):
        if self.RSI('TQQQ', 10) > 79:
            self.AH('SQQQ', 1, stock_weight/2)
            self.AH('SOXS', 1, stock_weight/2)
        else:
            self.HugeVolatility(stock_weight)            

    def HugeVolatility(self,stock_weight):
        if self.CumReturn('TQQQ', 6) < -0.12:
            if self.CumReturn('TQQQ', 1) >0.055:
                self.AH('SQQQ', 1, stock_weight/2)
                self.AH('SOXS', 1, stock_weight/2)
            else:
                self.MeanRevision(stock_weight)
        else:
            self.NormalMarket(stock_weight)

    def NormalMarket(self, stock_weight):
        if self.MaxDD('QQQ',10) > 0.06:
            self.V1BWCSafetyMix(stock_weight)
        else:
            if self.MaxDD('TMF',10) > 0.07:
                self.AH('USDU', 1, stock_weight/3)      
                self.AH('GLD', 1, stock_weight/3)
                self.AH('BTAL', 1, stock_weight/3)
            else:
                if self.Securities['QQQ'].Price > self.SMA('QQQ', 25):
                    self.AH('TQQQ', 1, stock_weight)
                else:
                    if self.RSI('SPY', 60) > 50:
                        self.BondStock(stock_weight)
                    else:
                        self.BondMidTermLong(stock_weight)

    ## Need to stop here
    def BondMidTermLong(self,stock_weight):
        if self.RSI('IEF', 200) < self.RSI('TLT', 200):
            if self.RSI('BND', 45) > self.RSI('SPY', 45):
                self.AH('TQQQ', 1, stock_weight)
            else:
                self.V2SafetyMix(stock_weight)
        else:
            self.V2SafetyMix(stock_weight)

    def V2SafetyMix(self,stock_weight):
        self.AH('USDU', 1, stock_weight/3)      
        self.AH('BTAL', 1, stock_weight/3)
        self.AH('GLD', 1, stock_weight/3)               

    def BondStock(self,stock_weight):
        if self.RSI('BND', 45) > self.RSI('SPY', 45):
            self.AH('TQQQ', 1, stock_weight)
        else:
            self.AH('USDU', 1, stock_weight/3)      
            self.AH('GLD', 1, stock_weight/3)
            self.AH('BTAL', 1, stock_weight/3)

    def V1BWCSafetyMix(self,stock_weight):
        equities = ["XLV", "XLU", "XLP", "XLE", "XLI", "XLB", "XLRE", "GLD", "USDU", "BTAL"]
        returns = {}
        for equity in equities:
            returns[equity] = self.CumReturn(equity, 3)
        sorted_returns = sorted([item for item in returns.items() if item[1] is not None], key=lambda x: x[1], reverse=True)
        t3e = sorted_returns[:3]
        self.AH(t3e[0][0], 1, stock_weight/3)      
        self.AH(t3e[1][0], 1, stock_weight/3)
        self.AH(t3e[2][0], 1, stock_weight/3)

    def MeanRevision(self,stock_weight):
        if self.RSI('TQQQ', 10) < 32:
            self.AH('SOXL', 1, stock_weight)
        else:
            if self.MaxDD('TMF',10) < 0.07:
                self.AH('TQQQ', 1, stock_weight)
            else:
                    equities = ["XLV", "XLU", "XLP", "XLE", "XLI", "XLB", "XLRE", "GLD", "USDU", "BTAL"]
                    returns = {}
                    for equity in equities:
                        returns[equity] = self.CumReturn(equity, 3)
                    sorted_returns = sorted([item for item in returns.items() if item[1] is not None], key=lambda x: x[1], reverse=True)
                    t3e = sorted_returns[:3]
                    self.AH(t3e[0][0], 1, stock_weight/3)      
                    self.AH(t3e[1][0], 1, stock_weight/3)
                    self.AH(t3e[2][0], 1, stock_weight/3)

    def BullMarket(self):
        if self.RSI('QQQ', 10) > 80:
            self.V1BWCDipBuyStrategy(0.50)
            self.BlackSwanCatcher(0.50)
        else:
            if self.CumReturn('SPY', 10) < 0.01:
                self.BlackSwanCatcher(1.0)
            else:
                if self.RSI('SPY', 60) > 60:
                    self.Sort("SMADayRet", ["TMF", "UUP", "VIXY", "XLP", "SPLV"], 15, True, 1, 1)
                else:
                    equities = ["TQQQ", "SOXL", "TECL", "UDOW", "UPRO", "FNGU", "BULZ"]
                    returns = {}
                    for equity in equities:
                        returns[equity] = self.SMADayRet(equity, 14)
                    sorted_returns = sorted([item for item in returns.items() if item[1] is not None], key=lambda x: x[1], reverse=True)
                    t3e = sorted_returns[:3]
                    self.AH(t3e[0][0], 1, 1.0/3)      
                    self.AH(t3e[1][0], 1, 1.0/3)
                    self.AH(t3e[2][0], 1, 1.0/3)
                    # SVXY is not allowed in IRA accounts by IBKR.
                    # Using UPRO as a replacement
                    #self.AH('SVXY', 1, 0.33)
                    #self.AH('UPRO', 1, 0.33)

    def DipBuyStrategy(self):
        if self.RSI('TQQQ', 10) < 28:
            self.AH('TECL', 1, 1)
        else:
            if self.RSI('SMH', 10) < 27:
                self.AH('SOXL', 1, 1)
            else:
                if self.RSI('FNGS', 10) < 27:
                    self.AH('FNGU', 1, 1)
                else:
                    if self.RSI('SPY', 10) < 27:
                        self.AH('UPRO', 1, 1)
                    else:
                        self.BearMarketSidewaysProtection()

    def BearMarketSidewaysProtection(self):
        if self.CumReturn('QQQ', 252) <= -0.2:
            self.NasdaqInCrashTerritoryTimetoDeleverage()
        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', 10) > 0.055:   
                        self.AH('SQQQ', 1, 0.5)
                    else:
                        self.Sort("RSI", ["TQQQ", "SOXL"], 10, True, 1, 0.5)  

        if self.Securities['QQQ'].Price < self.SMA('QQQ', 20):
            if self.CumReturn('QQQ', 60) <= -0.12:
                self.SidewaysMarketDeleverage()
            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:
                self.Sort("RSI", ["QQQ", "SMH"], 10, True, 1, 0.5)

    def NasdaqInCrashTerritoryTimetoDeleverage(self):   

        if self.Securities['QQQ'].Price < self.SMA('QQQ', 20):
            if self.CumReturn('QQQ', 60) <= -0.12:
                self.SidewaysMarketDeleverage2(0.50)
            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.BlackSwanCatcher(0.50)
            else:
                if  self.CumReturn('QQQ', 10) > 0.055:
                    self.BlackSwanCatcher(0.50)
                else:
                    self.BlackSwanCatcher(0.50)

    def SidewaysMarketDeleverage(self):
        stock_weight = 0.25
        if self.Securities['SPY'].Price > self.SMA('SPY', 20):
            self.BuyTech(stock_weight)
        else:
            if self.RSI('TLT', 10) > self.RSI('SQQQ', 10):
               self.BuyTech(stock_weight)
            else:
                self.BlackSwanCatcher(stock_weight)

        if self.RSI('TLT', 10) > self.RSI('SQQQ', 10):
            self.AH('QQQ', 1, 0.25) 
        else:
            self.AH('PSQ', 1, 0.25)

    def BuyTech(self,stock_weight):

        # Top 200d Standard Deviation Return
        equities = ["AMZN", "AAPL", "MSFT", "GOOG", "PYPL", "ADBE", "NVDA"]
        returns = {}
        for equity in equities:
            returns[equity] = self.STD(equity, 200)
        sorted_returns = sorted([item for item in returns.items() if item[1] is not None], key=lambda x: x[1], reverse=True)
        t3e = sorted_returns[:3]
        self.AH(t3e[0][0], 1, stock_weight/3)

        # Bottom 5d Stand Deviation Return
        returns = {}
        for equity in equities:
            returns[equity] = self.STD(equity, 5)
        sorted_returns = sorted([item for item in returns.items() if item[1] is not None], key=lambda x: x[1], reverse=False)
        t3e = sorted_returns[:3]
        self.AH(t3e[0][0], 1, stock_weight/3)

        # Top 200Day Cumulative Return
        returns = {}
        for equity in equities:
            returns[equity] = self.CumReturn(equity, 200)
        sorted_returns = sorted([item for item in returns.items() if item[1] is not None], key=lambda x: x[1], reverse=True)
        t3e = sorted_returns[:3]
        self.AH(t3e[0][0], 1, stock_weight/3)

    def SidewaysMarketDeleverage2(self,stock_weight):
        if self.Securities['SPY'].Price > self.SMA('SPY', 20):
            self.BuyTech(stock_weight/2)
        else:
            if self.RSI('TLT', 10) > self.RSI('SQQQ', 10):
               self.BuyTech(stock_weight/2)
            else:
                self.BlackSwanCatcher(stock_weight/2)

        if self.RSI('TLT', 10) > self.RSI('SQQQ', 10):
            self.BuyTech(stock_weight/2)
        else:
            self.BlackSwanCatcher(stock_weight/2)

    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)
        df = pd.concat([df1, df2])
        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
                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
                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,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)}