Overall Statistics
Total Trades
29
Average Win
11.33%
Average Loss
-1.57%
Compounding Annual Return
29.002%
Drawdown
15.700%
Expectancy
5.470
Net Profit
236.692%
Sharpe Ratio
1.393
Probabilistic Sharpe Ratio
75.963%
Loss Rate
21%
Win Rate
79%
Profit-Loss Ratio
7.24
Alpha
0.201
Beta
0.05
Annual Standard Deviation
0.147
Annual Variance
0.022
Information Ratio
0.504
Tracking Error
0.226
Treynor Ratio
4.077
Total Fees
$104.88
Estimated Strategy Capacity
$240000000.00
Lowest Capacity Asset
QQQ RIWIV7K5Z9LX
Portfolio Turnover
1.66%
#region imports
from AlgorithmImports import *
#endregion
import numpy as np
from datetime import datetime
import matplotlib.pyplot as plt
from AlgorithmImports import *
from CPI import CPIData

# -------------------------------------------------------------------------
STK = ['QQQ']; BND = ['TLT']; VOLA = 126; BASE_RET = 85; DAY = 85 ;LEV = 1.00  #855 
LEV = 1.00  #85
LEV = 1.00;  #85
PAIRS = ['SLV', 'GLD', 'XLI', 'XLU', 'DBB', 'UUP'] ; res = Resolution.Daily
# -------------------------------------------------------------------------
class DualMomentumInOut(QCAlgorithm):

    def Initialize(self):
       
        self.SetStartDate(2022,1,1)
       # self.SetEndDate(2019,1,1)
        self.cap = 10000 #Settare il Capitale Iniziale
        self.SetCash(self.cap) 
        self.AddEquity('SPY', res).Symbol 
        self.SetBenchmark('SPY')
        
        self.STK = self.AddEquity('SPY', res).Symbol
        self.BND1 = self.AddEquity('TLT', res).Symbol
        self.BND2 = self.AddEquity('UUP', res).Symbol

        self.ASSETS = [self.STK, self.BND, self.BND2]

        self.SLV = self.AddEquity('SLV', res).Symbol  
        self.GLD = self.AddEquity('GLD', res).Symbol  
        self.XLI = self.AddEquity('XLI', res).Symbol 
        self.XLU = self.AddEquity('XLU', res).Symbol
        self.DBB = self.AddEquity('DBB', res).Symbol  
        self.UUP = self.AddEquity('UUP', res).Symbol
       # self.SPY = self.AddEquity('SPY', res).Symbol
       # self.TLT = self.AddEquity('TLT', res).Symbol
        self.MKT = self.AddEquity('SPY', res).Symbol 
        self.BNCH = self.AddEquity('SPY', res).Symbol
        self.pairs = [self.XLI, self.XLU, self.GLD, self.SLV, self.DBB, self.UUP] #self.TVC, self.TIP
        
        self.bull = 1        
        self.count = 0 
        self.outday = 0        
        self.wt = {}
        self.real_wt = {}
        self.mkt = []
        self.SetWarmUp(timedelta(350))
        

        self.quandlCode = "RATEINF/INFLATION_USA"
        
        
        Quandl.SetAuthCode("hcm-xaeGb6haorprzgnh")
        self.cpi = self.AddData(QuandlCustomColumns, self.quandlCode, Resolution.Daily, TimeZones.NewYork).Symbol

        self.Schedule.On(self.DateRules.EveryDay(), self.TimeRules.AfterMarketOpen('SPY', 100), #100), #1000), #1005 0), #100), #1000), #100100), #100), #1000), #1005 0), #100), #1000), #100
            self.daily_check)
        
        
        symbols = [self.MKT] + self.pairs
        for symbol in symbols:
            self.consolidator = TradeBarConsolidator(timedelta(days=1))
            self.consolidator.DataConsolidated += self.consolidation_handler
            self.SubscriptionManager.AddConsolidator(symbol, self.consolidator)
        
        self.history = self.History(symbols, VOLA + 1, Resolution.Daily)
        if self.history.empty or 'close' not in self.history.columns:
            return
        self.history = self.history['close'].unstack(level=0).dropna()
        
        
    def consolidation_handler(self, sender, consolidated):
        
        self.history.loc[consolidated.EndTime, consolidated.Symbol] = consolidated.Close
        self.history = self.history.iloc[-(VOLA + 1):] 
        

    def daily_check(self):
        current_inflation = self.Securities[self.kei].Price
        vola = self.history[[self.MKT]].pct_change().std() * np.sqrt(252)
        wait_days = int(vola * DAY)*Mwait
        self.Debug('{}'.format(wait_days))
        period = int((1.0 - vola) * BASE_RET)        
        r = self.history.pct_change(period).iloc[-1]
        rGLD = round(((r[self.GLD] - r[self.SLV]) * 50), 100)
        rXLU = round(((r[self.XLU] - r[self.XLI]) * 50), 100)
        rUUP = round(((r[self.UUP] - r[self.DBB]) * 50), 100)
        
        exit =  (r[self.XLI] < r[self.XLU]) and (r[self.SLV] < r[self.GLD]) and  (r[self.DBB] < r[self.UUP]) 

       
        
            
        
        if exit:
            self.bull = False
            self.outday = self.count
        if self.count >= self.outday + wait_days:
            self.bull = True
        self.count += 1

        if current_inflation > 5 :
              self.safe = self.BND2
        else:
            self.safe = self.BND1

        if not self.bull:
            for sec in self.ASSETS:    
                self.wt[sec] = LEV if sec is self.safe else 0 if sec is self.safe else 0
            self.trade() 

        elif self.bull:
            for sec in self.ASSETS:
                self.wt[sec] = LEV if sec is self.STK else 0 
            self.trade()  
        

        
                    
    def trade(self):

        for sec, weight in self.wt.items():
            if weight == 0 and self.Portfolio[sec].IsLong:
                self.Liquidate(sec)
                
            cond1 = weight == 0 and self.Portfolio[sec].IsLong
            cond2 = weight > 0 and not self.Portfolio[sec].Invested
            if cond1 or cond2:
                self.SetHoldings(sec, weight)
        

        
                    
    def trade(self):

        for sec, weight in self.wt.items():
            if weight == 0 and self.Portfolio[sec].IsLong:
                self.Liquidate(sec)
                
            cond1 = weight == 0 and self.Portfolio[sec].IsLong
            cond2 = weight > 0 and not self.Portfolio[sec].Invested
            if cond1 or cond2:
                self.SetHoldings(sec, weight)
            
                    
    def OnEndOfDay(self):
        vola = self.history[[self.MKT]].pct_change().std() * np.sqrt(252)
        period = int((1.0 - vola) * (BASE_RET))
        r = self.history.pct_change(period).iloc[-1]
        
        rGLD = round(((r[self.GLD] - r[self.SLV]) * 50), 100)
        rXLU = round(((r[self.XLU] - r[self.XLI]) * 50), 100)
        rUUP = round(((r[self.UUP] - r[self.DBB]) * 50), 100)
       # rI = round(((r[self.RINF] - r[self.TLT]) * 50), 100)

        
        self.Plot('ROC', 'GOLD/SLV', rGLD)
        self.Plot('ROC', 'XLU/XLI', rXLU)
        self.Plot('ROC', 'UUP/DBB', rUUP)
      #  self.Plot('ROC', 'RINF/TLT', rI)
         
        vola = self.history[[self.MKT]].pct_change().std() * np.sqrt(252)
        wait_days = int(vola * DAY)
        
        self.Plot('Wait_days', 'Days', wait_days)

       # mkt_price = self.Securities[self.BNCH].Close
        #self.mkt.append(mkt_price)
        #mkt_perf = self.mkt[-1] / self.mkt[0] * self.cap
        #self.Plot('Strategy Equity', 'SPY', mkt_perf)
        
        account_leverage = self.Portfolio.TotalHoldingsValue / self.Portfolio.TotalPortfolioValue
        self.Plot('Holdings', 'leverage', round(account_leverage, 1))



        # Crea una istanza della classe CPIData come simbolo personalizzato
 
   
class QuandlCustomColumns(PythonQuandl):
    def __init__(self):
        # Define ValueColumnName: cannot be None, Empty or non-existant column name
        self.ValueColumnName = "Value"        
#region imports
from AlgorithmImports import *
#endregion
import numpy as np
from datetime import datetime
import matplotlib.pyplot as plt
from AlgorithmImports import *


# -------------------------------------------------------------------------
STK = ['QQQ']; BND = ['TLT']; VOLA = 126; BASE_RET = 85; DAY = 85 ;LEV = 1.00  #855 
LEV = 1.00  #85
LEV = 1.00;  #85
PAIRS = ['SLV', 'GLD', 'XLI', 'XLU', 'DBB', 'UUP'] ; res = Resolution.Daily
# -------------------------------------------------------------------------
class DualMomentumInOut(QCAlgorithm):

    def Initialize(self):
       
        self.SetStartDate(2018,7,1)
        #self.SetEndDate(2021,1,1)
        self.cap = 25000 #Settare il Capitale Iniziale
        self.SetCash(self.cap) 
        self.AddEquity('SPY', res).Symbol 
        self.SetBenchmark('SPY')
        
        self.STK = self.AddEquity('QQQ', res).Symbol
        self.BND1 = self.AddEquity('TLT', res).Symbol
        self.BND2 = self.AddEquity('UUP', res).Symbol

        self.ASSETS = [self.STK, self.BND1, self.BND2]

        self.SLV = self.AddEquity('SLV', res).Symbol  
        self.GLD = self.AddEquity('GLD', res).Symbol  
        self.XLI = self.AddEquity('XLI', res).Symbol 
        self.XLU = self.AddEquity('XLU', res).Symbol
        self.DBB = self.AddEquity('DBB', res).Symbol  
        self.UUP = self.AddEquity('UUP', res).Symbol
       # self.SPY = self.AddEquity('SPY', res).Symbol
       # self.TLT = self.AddEquity('TLT', res).Symbol
        self.MKT = self.AddEquity('SPY', res).Symbol 
        self.BNCH = self.AddEquity('SPY', res).Symbol
        self.pairs = [self.XLI, self.XLU, self.GLD, self.SLV, self.DBB, self.UUP] #self.TVC, self.TIP
        
        self.bull = 1        
        self.count = 0 
        self.outday = 0        
        self.wt = {}
        self.real_wt = {}
        self.mkt = []
        self.SetWarmUp(timedelta(350))
        

        self.quandlCode = "RATEINF/INFLATION_USA"
        
        
        Quandl.SetAuthCode("hcm-xaeGb6haorprzgnh")
        self.cpi = self.AddData(QuandlCustomColumns, self.quandlCode, Resolution.Daily, TimeZones.NewYork).Symbol

        self.Schedule.On(self.DateRules.EveryDay(), self.TimeRules.AfterMarketOpen('SPY', 100), #100), #1000), #1005 0), #100), #1000), #100100), #100), #1000), #1005 0), #100), #1000), #100
            self.daily_check)
        
        
        symbols = [self.MKT] + self.pairs
        for symbol in symbols:
            self.consolidator = TradeBarConsolidator(timedelta(days=1))
            self.consolidator.DataConsolidated += self.consolidation_handler
            self.SubscriptionManager.AddConsolidator(symbol, self.consolidator)
        
        self.history = self.History(symbols, VOLA + 1, Resolution.Daily)
        if self.history.empty or 'close' not in self.history.columns:
            return
        self.history = self.history['close'].unstack(level=0).dropna()
        
        
    def consolidation_handler(self, sender, consolidated):
        
        self.history.loc[consolidated.EndTime, consolidated.Symbol] = consolidated.Close
        self.history = self.history.iloc[-(VOLA + 1):] 
        

    def daily_check(self):

        current_inflation = self.Securities[self.cpi].Price
        self.Debug('{}'.format(current_inflation))
        vola = (self.history[[self.MKT]].pct_change().std() * np.sqrt(252))
        wait_days = int(vola * DAY)
        self.Debug('{}'.format(wait_days))
        period = int((1.0 - vola) * BASE_RET)        
        r = self.history.pct_change(period).iloc[-1]
        rGLD = round(((r[self.GLD] - r[self.SLV]) * 50), 100)
        rXLU = round(((r[self.XLU] - r[self.XLI]) * 50), 100)
        rUUP = round(((r[self.UUP] - r[self.DBB]) * 50), 100)
       # self.SetRiskManagement(MaximumDrawdownPercentPerSecurity(0.10))
        
        exit1 =  (r[self.XLI] < r[self.XLU]) and (r[self.SLV] < r[self.GLD])# and  (r[self.DBB] < r[self.UUP]) 
        exit2 =  (r[self.XLI] < r[self.XLU]) and (r[self.SLV] < r[self.GLD]) and  (r[self.DBB] < r[self.UUP]) 
        
        if current_inflation > 5.8 :
              exit = exit1
        else:
              exit = exit2
            
        
        if exit:
            self.bull = False
            self.outday = self.count
        if self.count >= self.outday + wait_days:
            self.bull = True
        self.count += 1

        if current_inflation > 5.8 :
              self.safe = self.BND2
        else:
            self.safe = self.BND1

        if not self.bull:
            for sec in self.ASSETS:    
                self.wt[sec] = LEV if sec is self.safe else 0 if sec is self.safe else 0
            self.trade() 

        elif self.bull:
            for sec in self.ASSETS:
                self.wt[sec] = LEV if sec is self.STK else 0 
            self.trade()  
            
        

        
                    
    def trade(self):

        for sec, weight in self.wt.items():
            if weight == 0 and self.Portfolio[sec].IsLong:
                self.Liquidate(sec)
                
            cond1 = weight == 0 and self.Portfolio[sec].IsLong
            cond2 = weight > 0 and not self.Portfolio[sec].Invested
            if cond1 or cond2:
                self.SetHoldings(sec, weight)
        

        
                    
   
            
                    
    def OnEndOfDay(self):
        vola = self.history[[self.MKT]].pct_change().std() * np.sqrt(252)
        period = int((1.0 - vola) * (BASE_RET))
        r = self.history.pct_change(period).iloc[-1]
        
        rGLD = round(((r[self.GLD] - r[self.SLV]) * 50), 100)
        rXLU = round(((r[self.XLU] - r[self.XLI]) * 50), 100)
        rUUP = round(((r[self.UUP] - r[self.DBB]) * 50), 100)
       # rI = round(((r[self.RINF] - r[self.TLT]) * 50), 100)

        
        self.Plot('ROC', 'GOLD/SLV', rGLD)
        self.Plot('ROC', 'XLU/XLI', rXLU)
        self.Plot('ROC', 'UUP/DBB', rUUP)
      #  self.Plot('ROC', 'RINF/TLT', rI)
         
        vola = self.history[[self.MKT]].pct_change().std() * np.sqrt(252)
        wait_days = int(vola * DAY)
        
        self.Plot('Wait_days', 'Days', wait_days)

       # mkt_price = self.Securities[self.BNCH].Close
        #self.mkt.append(mkt_price)
        #mkt_perf = self.mkt[-1] / self.mkt[0] * self.cap
        #self.Plot('Strategy Equity', 'SPY', mkt_perf)
        
        account_leverage = self.Portfolio.TotalHoldingsValue / self.Portfolio.TotalPortfolioValue
        self.Plot('Holdings', 'leverage', round(account_leverage, 1))



        # Crea una istanza della classe CPIData come simbolo personalizzato
 
   
class QuandlCustomColumns(PythonQuandl):
    def __init__(self):
        # Define ValueColumnName: cannot be None, Empty or non-existant column name
        self.ValueColumnName = "Value"