Overall Statistics
Total Trades
2
Average Win
0%
Average Loss
0%
Compounding Annual Return
0%
Drawdown
0%
Expectancy
0
Net Profit
0%
Sharpe 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
$5.06
Estimated Strategy Capacity
$2700000.00
Lowest Capacity Asset
TYH U8JOSZGR4OKL
Portfolio Turnover
36.83%
#region imports
from AlgorithmImports import *
#endregion


# Your New Python File
from indicators import RSI, SMA, CumReturn, AH
from project.main import YellowCatStrat

class TQQQFTLTStrategy(YellowCatStrat):
    def __init__(self, algorithm):
        super().__init__()
        self.algorithm = algorithm
    def Execute(self):
        if self.algorithm.Securities['SPY'].Price > SMA(self.algorithm, 'SPY', 200):
            if RSI(self.algorithm, 'TQQQ', 10) > 78:
                AH(self.algorithm, ['SPXU', 'UVXY', 'SQQQ'], 1, 0.33)
            else:
                if RSI(self.algorithm, 'SPXL', 10) > 79:
                    AH(self.algorithm, ['SPXU', 'UVXY', 'SQQQ'], 1, 0.33)
                else:
                    if CumReturn(self.algorithm, 'TQQQ', 4) > 0.2:
                        if RSI(self.algorithm, 'TQQQ', 10) < 31:
                            AH(self.algorithm, 'TQQQ', 1, 1)
                        else:
                            if RSI(self.algorithm, 'UVXY', 10) > RSI(self.algorithm, 'SQQQ', 10):
                                AH(self.algorithm, ['SPXU', 'UVXY', 'SQQQ'], 1, 0.33)
                            else:
                                AH(self.algorithm, 'SQQQ', 1, 1)
                    else:
                        AH(self.algorithm, 'TQQQ', 1, 1)
        else:
            if RSI(self.algorithm, 'TQQQ', 10) < 31:
                AH(self.algorithm, 'TECL', 1, 1)
            else:
                if RSI(self.algorithm, 'SMH', 10) < 30:
                    AH(self.algorithm, 'SOXL', 1, 1)
                else:
                    if RSI(self.algorithm, 'DIA', 10) < 27:
                        AH(self.algorithm, 'UDOW', 1, 1)
                    else:
                        if RSI(self.algorithm, 'SPY', 14) < 28:
                            AH(self.algorithm, 'UPRO', 1, 1)
                        else:
                            self.Group1()
                            self.Group2()

    def Group1(self):
        if CumReturn(self.algorithm, 'QQQ', 200) < -0.2:
            if self.algorithm.Securities['QQQ'].Price < SMA(self.algorithm, 'QQQ', 20):
                if CumReturn(self.algorithm, 'QQQ', 60) < -0.12:
                    self.algorithm.Group5()
                    self.algorithm.Group6()
                else:
                    if RSI(self.algorithm, 'TLT', 10) > RSI(self.algorithm, 'SQQQ', 10):
                        AH(self.algorithm, 'TQQQ', 1, 0.5)
                    else:
                        AH(self.algorithm, 'SQQQ', 1, 0.5)
            else:
                if RSI(self.algorithm, 'SQQQ', 10) < 31:
                    AH(self.algorithm, 'PSQ', 1, 0.5)
                else:
                    if CumReturn(self.algorithm, 'QQQ', 9) > 0.055:
                        AH(self.algorithm, 'PSQ', 1, 0.5)
                    else:
                        if RSI(self.algorithm, 'TQQQ', 10) > RSI(self.algorithm, 'SOXL', 10):
                            AH(self.algorithm, 'TQQQ', 1, 0.5)
                        else:
                            AH(self.algorithm, 'SOXL', 1, 0.5)

    def Group2(self):
        if self.algorithm.Securities['QQQ'].Price < SMA(self.algorithm, 'QQQ', 20):
            if CumReturn(self.algorithm, 'QQQ', 60) < -0.12:
                self.algorithm.Group3()
                self.algorithm.Group4()
            else:
                if RSI(self.algorithm, 'TLT', 10) > RSI(self.algorithm, 'SQQQ', 10):
                    AH(self.algorithm, 'TQQQ', 1, 0.5)
                else:
                    AH(self.algorithm, 'SQQQ', 1, 0.5)
        else:
            if self.algorithm.RSI('TQQQ', 10) > self.algorithm.RSI('SOXL', 10):
                AH(self.algorithm, 'TQQQ', 1, 0.5)
            else:
                AH(self.algorithm, 'SOXL', 1, 0.5)

    def Group3(self):
        if self.algorithm.Securities['SPY'].Price > SMA(self.algorithm, 'SPY', 20):
            AH(self.algorithm, 'SPY', 1, 0.25)
        else:
            if RSI(self.algorithm, 'TLT', 10) > RSI(self.algorithm, 'SQQQ', 10):
                AH(self.algorithm, 'QQQ', 1, 0.25)
            else:
                AH(self.algorithm, 'PSQ', 1, 0.25)

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

    def Group5(self):
        if self.algorithm.Securities['SPY'].Price > SMA(self.algorithm, 'SPY', 20):
            AH(self.algorithm, 'SPY', 1, 0.25)
        else:
            if RSI(self.algorithm, 'TLT', 10) > RSI(self.algorithm, 'SQQQ', 10):
                AH(self.algorithm, 'QQQ', 1, 0.25)
            else:
                AH(self.algorithm, 'PSQ', 1, 0.25)
    def Group6(self):
        if RSI(self.algorithm, 'TLT', 10) > RSI(self.algorithm, 'SQQQ', 10):
            AH(self.algorithm, 'QQQ', 1, 0.25)
        else:
            AH(self.algorithm, 'PSQ', 1, 0.25)
#region imports
from AlgorithmImports import *
#endregion


# Your New Python File
from indicators import RSI, CumReturn, MaxDD, SMA, STD, IV, SMADayRet, EMA, Sort, AH
from project.main import YellowCatStrat

class TQQQorNotStrategy(YellowCatStrat):
    def __init__(self, algorithm):
        super().__init__()
        self.algorithm = algorithm
    def Execute(self):
        if RSI(self.algorithm,'TQQQ',10) > 78:
            AH(self.algorithm,['SPXU','UVXY','SQQQ'],3,1/3)
        else:
            if CumReturn(self.algorithm,'TQQQ',6) < -0.12:
                if CumReturn(self.algorithm,'TQQQ',1) > 0.055:
                    AH(self.algorithm,['SPXU','UVXY','SQQQ'],3,1/3)
                else:
                    if RSI(self.algorithm,'TQQQ',10) < 32:
                        AH(self.algorithm,'TQQQ',3,1)
                    else:
                        if MaxDD(self.algorithm,'TMF',10)<0.07:
                            AH(self.algorithm,'TQQQ',3,1)
                        else:
                            AH(self.algorithm,'BIL',3,1)
            else:
                if MaxDD(self.algorithm,'QQQ',10)>0.06:
                    AH(self.algorithm,'BIL',3,1)
                else:
                    if MaxDD(self.algorithm,'TMF',10)>0.07:
                        AH(self.algorithm,'BIL',3,1)
                    else:
                        if self.algorithm.Securities['QQQ'].Price > self.algorithm.SMA('QQQ',25):
                            AH(self.algorithm,'TQQQ',3,1)
                        else:
                            if RSI(self.algorithm,'SPY',60) > 50:
                                if RSI(self.algorithm,'BND',45) > RSI(self.algorithm,'SPY',45):
                                    AH(self.algorithm,'TQQQ',3,1)
                                else:
                                    AH(self.algorithm,'BIL',3,1)
                            else:
                                if RSI(self.algorithm,'IEF',200) < RSI(self.algorithm,'TLT',200):
                                    if RSI(self.algorithm,'BND',45) > RSI(self.algorithm,'SPY',45):
                                        AH(self.algorithm,'TQQQ',3,1)
                                    else:
                                        AH(self.algorithm,'BIL',3,1)
                                else:
                                    AH(self.algorithm,'BIL',3,1)
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
def RSI(algorithm,equity,period):
    extension = min(period*5,250)
    r_w = RollingWindow[float](extension)
    history = algorithm.History(equity,extension - 1,Resolution.Daily)
    for historical_bar in history:
        r_w.Add(historical_bar.Close)
    while r_w.Count < extension:
        current_price = algorithm.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(algorithm,equity,period):
    history = algorithm.History(equity,period,Resolution.Daily)
    closing_prices = pd.Series([bar.Close for bar in history])
    current_price = algorithm.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(algorithm,equity,period):
    r_w = RollingWindow[float](period + 1)
    r_w_return = RollingWindow[float](period)
    history = algorithm.History(equity,period,Resolution.Daily)
    for historical_bar in history:
        r_w.Add(historical_bar.Close)
    while r_w.Count < period + 1:
        current_price = algorithm.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(algorithm,equity,period):
    history = algorithm.History(equity,period - 1,Resolution.Daily)
    closing_prices = pd.Series([bar.Close for bar in history])
    current_price = algorithm.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(algorithm,equity,period):
    r_w = RollingWindow[float](period)
    history = algorithm.History(equity,period - 1,Resolution.Daily)
    for historical_bar in history:
        r_w.Add(historical_bar.Close)
    while r_w.Count < period:
        current_price = algorithm.Securities[equity].Price
        r_w.Add(current_price)
    if r_w.IsReady:
        sma = sum(r_w)/period
        return sma
    else:
        return 0
def IV(algorithm,equity,period):
    r_w = RollingWindow[float](period + 1)
    r_w_return = RollingWindow[float](period)
    history = algorithm.History(equity,period,Resolution.Daily)
    for historical_bar in history:
        r_w.Add(historical_bar.Close)
    while r_w.Count < period + 1:
        current_price = algorithm.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(algorithm,equity,period):
    r_w = RollingWindow[float](period + 1)
    r_w_return = RollingWindow[float](period)
    history = algorithm.History(equity,period,Resolution.Daily)
    for historical_bar in history:
        r_w.Add(historical_bar.Close)
    while r_w.Count < period + 1:
        current_price = algorithm.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(algorithm,equity,period):
    extension = period + 50
    r_w = RollingWindow[float](extension)
    history = algorithm.History(equity,extension - 1,Resolution.Daily)
    for historical_bar in history:
        r_w.Add(historical_bar.Close)
    while r_w.Count < extension:
        current_price = algorithm.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(algorithm,sort_type,equities,period,reverse,number,multiplier):
    algorithm.PT = getattr(algorithm,f"PT{number}") * multiplier
    returns = {}
    for equity in equities:
        returns[equity] = getattr(algorithm,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(algorithm,f"HT{number}")
    hts = getattr(algorithm,f"HTS{number}")
    for i in ht.keys():
        if ht[i] == 0:
            ht[i] = algorithm.PT
            hts[i].append(t3e[0][0])
            break
    setattr(algorithm,f"HT{number}",ht)
    setattr(algorithm,f"HTS{number}",hts)
def AH(algorithm,equities,PTnumber,multiplier): #AppendHolding
    if not isinstance(equities,list):
        equities = [equities]
    HT = getattr(algorithm,f"HT{PTnumber}")
    HTS = getattr(algorithm,f"HTS{PTnumber}")
    PT = getattr(algorithm,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
# main.py
from AlgorithmImports import *
from indicators import *

class StrategyPerformanceTracker:
    def __init__(self):
        self.strategyReturns = {}  # {strategyName: [daily returns]}

    def logDailyReturn(self, strategyName, dailyReturn):
        if strategyName not in self.strategyReturns:
            self.strategyReturns[strategyName] = []
        self.strategyReturns[strategyName].append(dailyReturn)

    def calculateReturnsOverPeriod(self, strategyName, days):
        if strategyName in self.strategyReturns:
            return sum(self.strategyReturns[strategyName][-days:])
        return None

    def rankStrategies(self, days, topN):
        performance = {strategy: self.calculateReturnsOverPeriod(strategy, days) 
                       for strategy in self.strategyReturns}
        rankedStrategies = sorted(performance.items(), key=lambda x: x[1], reverse=True)
        return rankedStrategies[:topN]

class YellowCatStrat(QCAlgorithm):
    def Initialize(self):
        
        self.cash = 100000
        self.buffer_pct = 0.02
        self.SetStartDate(2023,10,27)
        self.SetEndDate(2023,10,27)
        self.SetCash(self.cash)
        self.equities = ['XENE','ARCT','CRSP','IMRX','NAMS','BPMC','IMUX','HOWL','AUTL','ETNB','SIMO','IEO','ATXS','SERA','VRTX','PNT','FUSN','PYXS','EXAI','ICVX','IOVA','CRBU','ROIV','XLF','CDTX','TRDA','CRVS','AKBA','EDC','SON','XLE','TWM','RWM','URTY','PBR','OIL','ROST','WMS','AAPD','TSLQ','TSLS','AAPB','ALGN','TPL','COIN','VLO','AA','BITI','HIBS','ACLS','EQT','MOS','AR','MU','CZR','UVIX','ENPH','AMEH','ERIC','GNRC','BULZ','VCIT','UDN','SARK','AMD','FNGU','TSLL','AEHR','MSTR','TARK','XLY','QQQE','VOOG','VOOV','VTV','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','BIL','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','TMV','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','VGIT','VGLT','CCOR','LBAY','NRGD','PHDG','SPHD','COWZ','CTA','DBMF','GDMA','VIGI','AGG','NOBL','FAAR','BITO','FTLS','MORT','FNDX','GLL','NTSX','RWL','VLUE','IJR','SPYG','VXUS','AAL','AEP','AFL','C','CMCSA','DUK','EXC','F','GM','GOOGL','INTC','JNJ','KO','MET','NWE','OXY','PFE','RTX','SNY','SO','T','TMUS','VZ','WFC','WMT','AMZN','MSFT','NVDA','TSM','BA','CB','COKE','FDX','GE','LMT','MRK','NVEC','ORCL','PEP','V','DBE','BRK-B','CRUS','INFY','KMLM','NSYS','SCHG','SGML','SLDP','ARKQ','XLU','XLV','ULTA','AAPL','AMZU','BAD','DDM','IYH','JPM','PM','XOM','EUO','YCS','MVV','USD','TMF','SPXL','EPI','IYK','CURE','DIG','XLU']
        self.MKT = self.AddEquity("QQQ",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)
        from Strategies.TQQQFTLT.version1 import TQQQFTLTStrategy
        self.tqqqftltStrategy = TQQQFTLTStrategy(self)
        from Strategies.TQQQorNot.version1 import TQQQorNotStrategy
        self.tqqqorNotStrategy = TQQQorNotStrategy(self)
        self.PTMaster = 1
        self.PT1 = 0.24*self.PTMaster #TQQQFTLT 
        self.PT3 = 0.13*self.PTMaster #TQQQorNOT
        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.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.Schedule.On(self.DateRules.EveryDay("SPY"),
                self.TimeRules.BeforeMarketClose("SPY",2),
                self.FunctionBeforeMarketClose)
    def __init__(self):
        super().__init__()

    def FunctionBeforeMarketClose(self):
        # End of day trading function
        self.tqqqftltStrategy.Execute()
        self.tqqqorNotStrategy.Execute()
        self.ExecuteTrade()

    def OnData(self, data):
        # This function is called every time new data is received
        pass

    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)
        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)
        df = pd.concat([df1,df3])
        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'}
        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']
        # 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']
        transform_mapping = {'PSQ':'SQQQ','SH':'SPXS','USDU':'UUP','SPXU':'SPXS','UPRO':'SPXL','QLD':'TQQQ','QID':'SQQQ','TSLS':'TSLQ'}
        transform_ratios = {'PSQ':3,'SH':3,'USDU':1,'SPXU':1,'UPRO':1,'QLD':1.5,'QID':1.5,'TSLS':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:
                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):
                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)


        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.HT3 = {str(i).zfill(2): 0 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)}