Overall Statistics
Total Trades
23
Average Win
4.44%
Average Loss
-4.98%
Compounding Annual Return
220.812%
Drawdown
22.100%
Expectancy
0.547
Net Profit
57.695%
Sharpe Ratio
3.233
Probabilistic Sharpe Ratio
77.247%
Loss Rate
18%
Win Rate
82%
Profit-Loss Ratio
0.89
Alpha
1.035
Beta
2.709
Annual Standard Deviation
0.461
Annual Variance
0.213
Information Ratio
3.514
Tracking Error
0.377
Treynor Ratio
0.551
Total Fees
$505.38
Estimated Strategy Capacity
$7100000.00
Lowest Capacity Asset
TQQQ UK280CGTCB51
Portfolio Turnover
11.61%
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 = 100000
        self.buffer_pct = 0.085
        self.SetStartDate(2023, 1, 1)
        self.SetEndDate(2023, 5, 23)
        self.SetCash(self.cash)
        self.equities = ['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']

        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.PT2 = 0.98 

        self.HT199 = 0
        self.HT299 = 0
        self.HT399 = 0
        self.HT499 = 0
        self.HT599 = 0
        self.HT699 = 0
        self.HT99 = 0
        self.HTS199 = []
        self.HTS299 = []
        self.HTS399 = []
        self.HTS499 = []
        self.HTS599 = []
        self.HTS699 = []
        self.HTS99 = []


        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 CalReturn(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 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.ExecuteTrade()

    def TQQQFTLT(self):
        if self.Securities['SPY'].Price > self.SMA('SPY', 200):
            if self.RSI('TQQQ', 10) > 78:
                self.HT99 =  self.PT2        
                self.HTS99 = "UVXY"
            else:
                if self.RSI('SPXL', 10) > 79:
                    self.HT99 =  self.PT2        
                    self.HTS99 = "UVXY"
                else:
                    if self.CalReturn('TQQQ', 4) > 0.2:
                        if self.RSI('TQQQ', 10) < 31:
                            self.HT99 =  self.PT2        
                            self.HTS99 = "TQQQ"
                        else:
                            if self.RSI('UVXY', 10) > self.RSI('SQQQ', 10):
                                self.HT99 =  self.PT2        
                                self.HTS99 = "UVXY"
                            else:
                                self.HT99 =  self.PT2        
                                self.HTS99 = "SQQQ"
                    else:
                        self.HT99 =  self.PT2        
                        self.HTS99 = "TQQQ"
        else:
            if self.RSI('TQQQ', 10) < 31:
                self.HT99 =  self.PT2        
                self.HTS99 = "TECL"
            else:
                if self.RSI('SMH', 10) < 30:
                    self.HT99 =  self.PT2        
                    self.HTS99 = "SOXL"
                else:
                    if self.RSI('DIA', 10) < 27:
                        self.HT99 =  self.PT2        
                        self.HTS99 = "UDOW"
                    else:
                        if self.RSI('SPY', 14) < 28:
                            self.HT99 =  self.PT2        
                            self.HTS99 = "UPRO"
                        else:
                            self.Group1()
                            self.Group2()

    def Group1(self):
        if self.CalReturn('QQQ', 200) < -0.2:
            if self.Securities['QQQ'].Price < self.SMA('QQQ', 20):
                if self.CalReturn('QQQ', 60) < -0.12:
                    self.Group5()
                    self.Group6()
                else:
                    if self.RSI('TLT', 10) > self.RSI('SQQQ', 10):
                        self.HT199 =  0.5*self.PT2        
                        self.HTS199 = "TQQQ"
                    else:
                        self.HT199 =  0.5*self.PT2        
                        self.HTS199 = "SQQQ"                                      
            else:
                if self.RSI('SQQQ', 10) < 31:
                    self.HT199 =  0.5*self.PT2        
                    self.HTS199 = "PSQ"               
                else:
                    if self.CalReturn('QQQ', 9) > 0.055:
                        self.HT199 =  0.5*self.PT2        
                        self.HTS199 = "PSQ"
                    else:
                        if self.RSI('QQQ', 10) > self.RSI('SMH', 10):
                            self.HT199 =  0.5*self.PT2        
                            self.HTS199 = "QQQ"
                               
                        else:
                            self.HT199 =  0.5*self.PT2        
                            self.HTS199 = "SMH"  
        else:
            if self.Securities['QQQ'].Price < self.SMA('QQQ', 20):
                if self.RSI('TLT', 10) > self.RSI('SQQQ', 10):
                        self.HT199 =  0.5*self.PT2        
                        self.HTS199 = "TQQQ"                               
                else:
                    self.HT199 =  0.5*self.PT2        
                    self.HTS199 = "SQQQ"
                               
            else:
                if self.RSI('SQQQ', 10) < 31:
                    self.HT199 =  0.5*self.PT2        
                    self.HTS199 = "SQQQ"                           
                else:
                    if self.CalReturn('QQQ', 9) > 0.055:
                        self.HT199 =  0.5*self.PT2        
                        self.HTS199 = "SQQQ"                           
                    else:
                        if self.RSI('TQQQ', 10) > self.RSI('SOXL', 10):
                            self.HT199 =  0.5*self.PT2        
                            self.HTS199 = "TQQQ"                               
                        else:
                            self.HT199 =  0.5*self.PT2        
                            self.HTS199 = "SOXL"                                 
    def Group2(self):
        if self.Securities['QQQ'].Price < self.SMA('QQQ', 20):
            if self.CalReturn('QQQ', 60) < -0.12:
                self.Group3()
                self.Group4()
            else:
                if self.RSI('TLT', 10) > self.RSI('SQQQ', 10):
                    self.HT299 =  0.5*self.PT2        
                    self.HTS299 = "TQQQ"
                               
                else:
                    self.HT299 =  0.5*self.PT2        
                    self.HTS299 = "SQQQ"                               
        else:
            if self.RSI('SQQQ', 10) < 31:
                for equity in self.equities:
                    if not equity == "SQQQ" and self.Portfolio[equity].HoldStock:
                        self.Liquidate(equity)  
                self.HT299 =  0.5*self.PT2        
                self.HTS299 = "SQQQ"                           
            else:
                if self.CalReturn('QQQ', 70) < -0.15:
                    if self.RSI('TQQQ', 10) > self.RSI('SOXL', 10):
                        self.HT299 =  0.5*self.PT2        
                        self.HTS299 = "TQQQ"                                   
                    else:
                        self.HT299 =  0.5*self.PT2        
                        self.HTS299 = "SOXL"                                   
                else:
                    equities = ["SPY", "QQQ", "DIA", "XLP"]
                    returns = {}
                    for equity in equities:
                        returns[equity] = self.CalReturn(equity, 14)
                    s_e = sorted([item for item in returns.items() if item[1] is not None], key=lambda x: x[1], reverse=True)
                    top_2_equities = s_e[0]
                    self.HT299 =  0.5*self.PT2        
                    self.HTS299 = top_2_equities[0]                                                           
    def Group3(self):
        if self.Securities['SPY'].Price > self.SMA('SPY', 20): 
            self.HT399 =  0.25*self.PT2
            self.HTS399 = "SPY"
         
        else:
            if self.RSI('TLT', 10) > self.RSI('SQQQ', 10):
                self.HT399 =  0.25*self.PT2        
                self.HTS399 = "QQQ"
                             
            else:
                self.HT399 =  0.25*self.PT2        
                self.HTS399 = "PSQ"
    def Group4(self):
        if self.RSI('TLT', 10) > self.RSI('SQQQ', 10):
            self.HT499 =  0.25*self.PT2        
            self.HTS499 = "QQQ"           
        else:
            self.HT499 =  0.25*self.PT2        
            self.HTS499 = "PSQ"
    def Group5(self):
        if self.Securities['SPY'].Price > self.SMA('SPY', 20):
            self.HT599 =  0.25*self.PT2
            self.HTS599 = "SPY"         
        else:
            if self.RSI('TLT', 10) > self.RSI('SQQQ', 10):
                self.HT599 =  0.25*self.PT2        
                self.HTS599 = "QQQ"                             
            else:
                self.HT599 =  0.25*self.PT2        
                self.HTS599 = "PSQ"
    def Group6(self):
        if self.RSI('TLT', 10) > self.RSI('SQQQ', 10):
            self.HT699 =  0.25*self.PT2        
            self.HTS699 = "QQQ"           
        else:
            self.HT699 =  0.25*self.PT2        
            self.HTS699 = "PSQ"
                    
    def ExecuteTrade(self):

        group99 = {
            'HTS': [self.HTS99, self.HTS199, self.HTS299, self.HTS399, self.HTS499, self.HTS599, self.HTS699],
            'HT': [self.HT99, self.HT199, self.HT299, self.HT399, self.HT499, self.HT599, self.HT699]
        }
        df99 = pd.DataFrame(group99)


        df = pd.concat([df99])
        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.HT199 = 0
        self.HT299 = 0
        self.HT399 = 0
        self.HT499 = 0
        self.HT599 = 0
        self.HT699 = 0
        self.HT99 = 0
        self.HTS199 = []
        self.HTS299 = []
        self.HTS399 = []
        self.HTS499 = []
        self.HTS599 = []
        self.HTS699 = []
        self.HTS99 = []