Overall Statistics
Total Trades
0
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.439
Tracking Error
0.16
Treynor Ratio
0
Total Fees
$0.00
Estimated Strategy Capacity
$0
Lowest Capacity Asset
#region imports
from AlgorithmImports import *
#endregion

class AccelDualMomentum(QCAlgorithm):
    def Initialize(self):
        
        self.SetStartDate(1997, 12, 31)  # Set Start Date
        #self.SetEndDate(datetime.now().date() - timedelta(1)) # Set End Date
        self.SetEndDate(2022,2,28)
        self.SetCash(10000)  # Set Strategy Cash
        
        #self.Portfolio.MarginCallModel = MarginCallModel.Null;
        
        self.aVFINX = self.AddData(VFINX, "VFINX", Resolution.Daily).Symbol
        self.aVINEX = self.AddData(VINEX, "VINEX", Resolution.Daily).Symbol
        self.aVUSTX = self.AddData(VUSTX, "VUSTX", Resolution.Daily).Symbol
        self.aLBMA = self.AddData(LBMA, "LBMA", Resolution.Daily).Symbol
        self.aGLD = self.AddData(GLD, "GLD", Resolution.Daily).Symbol
        self.aVIPSX = self.AddData(VIPSX, "VIPSX", Resolution.Daily).Symbol
        self.aCASH = self.AddData(CASH, "CASH", Resolution.Daily).Symbol
        self.indicator = self.AddData(MOMENTUM, "MOMENTUM", Resolution.Daily).Symbol
        self.LiquidateTickets = {}
        self.EnableAutomaticIndicatorWarmUp = True
        
        #self.Settings.FreePortfolioValuePercentage = 0.5
        
        # Set leverage
        self.leverage = 2
           
        self.trading_day = -1
        
    def OnOrderEvent(self, orderEvent):
        order = self.Transactions.GetOrderById(orderEvent.OrderId)
        if orderEvent.Status == OrderStatus.Filled and order.Symbol in self.LiquidateTickets: 
            self.SetHoldings(order.Symbol , 1*self.leverage)

    def shiftAssets(self, target):
        if not (self.Portfolio[target].Invested):
            for symbol in self.Portfolio.Keys:
                #self.Liquidate(symbol)
                self.LiquidateTickets[symbol] = self.MarketOrder(symbol,-self.Portfolio[symbol].Quantity)

            
    
    def getMonthLastTradingDay(self):
        month_last_day = DateTime(self.Time.year, self.Time.month, DateTime.DaysInMonth(self.Time.year, self.Time.month))
        tradingDays = self.TradingCalendar.GetDaysByType(TradingDayType.BusinessDay, DateTime(self.Time.year, self.Time.month, 1), month_last_day)
        tradingDays = [day.Date.date() for day in tradingDays]
        return tradingDays[0+self.trading_day]
        
        
        # self.Schedule.On(self.DateRules.WeekEnd(tradingfrequency), self.Now,self.trade_in) 

    def OnData(self, data):
        if (self.Time.date() == self.getMonthLastTradingDay()):
        #if (self.Time.date() == date(2019,10,31)):

            if data.ContainsKey(self.indicator):
                ticker = data[self.indicator].GetProperty('Indicator')
                #self.Debug(data[self.indicator].Time.date())
                if (ticker =="VINEX"):
                    #self.Schedule.On(self.Time.date(), self.TimeRules.BeforeMarketClose(self.aVINEX, 30), self.shiftAssets(self.aVINEX))
                    self.shiftAssets(self.aVINEX)
                elif (ticker =="VFINX"):
                    self.shiftAssets(self.aVFINX)
                elif (ticker =="VUSTX"):
                    self.shiftAssets(self.aVUSTX)
                elif (ticker =="LBMA"):
                    self.shiftAssets(self.aLBMA)
                elif (ticker =="VIPSX"):
                    self.shiftAssets(self.aVIPSX)
                elif (ticker =="CASH"):
                    self.shiftAssets(self.aCASH)
                elif (ticker =="GLD"):
                    self.shiftAssets(self.aGLD)
                    
    
                
        #self.Plot("Margin", "Remaining", self.Portfolio.MarginRemaining)
        #self.Plot("Margin", "Used", self.Portfolio.TotalMarginUsed)
        #self.Plot("Cash", "Remaining", self.Portfolio.Cash)
        #self.Plot("Cash", "Remaining", self.Portfolio.TotalHoldingsValue)
        
        self.Plot("VFINX", "Held", self.Portfolio["VFINX"].Quantity)
        self.Plot("VINEX", "Held", self.Portfolio["VINEX"].Quantity)
        self.Plot("VUSTX", "Held", self.Portfolio["VUSTX"].Quantity)
        self.Plot("VIPSX", "Held", self.Portfolio["VIPSX"].Quantity)
        self.Plot("GLD", "Held", self.Portfolio["GLD"].Quantity)
        self.Plot("CASH", "Held", self.Portfolio["CASH"].Quantity)
        
class LBMA(PythonData):
    def GetSource(self, config, date, isLiveMode):
        return SubscriptionDataSource("https://www.dropbox.com/s/81ixmlr8cx1uxgq/LBMA.csv?dl=1", SubscriptionTransportMedium.RemoteFile)
        
    def Reader(self, config, line, date, isLive):
        if not (line.strip() and line[0].isdigit()): 
            return None
        
        index = LBMA()
        index.Symbol = config.Symbol
        
        data = line.split(',')
        index.Time = datetime.strptime(data[0], "%d/%m/%Y")
        index.EndTime = index.Time + timedelta(days=1)
        index.Value = data[1] #Number of values
        index["LBMA"] = float(data[1])
        
        return index

#data missing until 2000 - needs to be excluded from calculations or set momentum is 0        
class VIPSX(PythonData):
    def GetSource(self, config, date, isLiveMode):
        return SubscriptionDataSource("https://www.dropbox.com/s/51npkwxesct345x/VIPSX.csv?dl=1", SubscriptionTransportMedium.RemoteFile)
    def Reader(self, config, line, date, isLive):
        
        if not (line.strip() and line[0].isdigit()): 
            return None
        
        index = VIPSX()
        index.Symbol = config.Symbol
        data = line.split(',')
        index.Time = datetime.strptime(data[0], "%d/%m/%Y")
        index.EndTime = index.Time + timedelta(days=1)
        index.Value = data[4]
        index["Open"] = float(data[1])
        index["High"] = float(data[2])
        index["Low"] = float(data[3])
        index["Close"] = float(data[4])

        return index 
        
class VUSTX(PythonData):
    def GetSource(self, config, date, isLiveMode):
        return SubscriptionDataSource("https://www.dropbox.com/s/hnv2swusm9wra5w/VUSTX.csv?dl=1", SubscriptionTransportMedium.RemoteFile)
    def Reader(self, config, line, date, isLive):
        
        if not (line.strip() and line[0].isdigit()): 
            return None
        
        index = VUSTX()
        index.Symbol = config.Symbol
        data = line.split(',')
        index.Time = datetime.strptime(data[0], "%d/%m/%Y")
        index.EndTime = index.Time + timedelta(days=1)
        index.Value = data[4]
        index["Open"] = float(data[1])
        index["High"] = float(data[2])
        index["Low"] = float(data[3])
        index["Close"] = float(data[4])
        
        return index
        
class VFINX(PythonData):
    def GetSource(self, config, date, isLiveMode):
        return SubscriptionDataSource("https://www.dropbox.com/s/zzh0ydo8t8l5ds4/VFINX.csv?dl=1", SubscriptionTransportMedium.RemoteFile)
    def Reader(self, config, line, date, isLive):
        
        if not (line.strip() and line[0].isdigit()): 
            return None
        
        index = VFINX()
        index.Symbol = config.Symbol
        data = line.split(',')
        index.Time = datetime.strptime(data[0], "%d/%m/%Y")
        index.EndTime = index.Time + timedelta(days=1)
        index.Value = data[4]
        index["Open"] = float(data[1])
        index["High"] = float(data[2])
        index["Low"] = float(data[3])
        index["Close"] = float(data[4])
        
        return index
        
class VINEX(PythonData):
    def GetSource(self, config, date, isLiveMode):
        return SubscriptionDataSource("https://www.dropbox.com/s/3otgob32pyl0hz8/VINEX.csv?dl=1", SubscriptionTransportMedium.RemoteFile)
    def Reader(self, config, line, date, isLive):
        
        if not (line.strip() and line[0].isdigit()): 
            return None
        
        index = VINEX()
        index.Symbol = config.Symbol
        data = line.split(',')
        index.Time = datetime.strptime(data[0], "%d/%m/%Y")
        index.EndTime = index.Time + timedelta(days=1)
        index.Value = data[4]
        index["Open"] = float(data[1])
        index["High"] = float(data[2])
        index["Low"] = float(data[3])
        index["Close"] = float(data[4])
        
        return index
        
class GLD(PythonData):
    def GetSource(self, config, date, isLiveMode):
        return SubscriptionDataSource("https://www.dropbox.com/s/c9asn799ugf8kja/GLD.csv?dl=1", SubscriptionTransportMedium.RemoteFile)
    def Reader(self, config, line, date, isLive):
        
        if not (line.strip() and line[0].isdigit()): 
            return None
        
        index = GLD()
        index.Symbol = config.Symbol
        data = line.split(',')
        index.Time = datetime.strptime(data[0], "%d/%m/%Y")
        index.EndTime = index.Time + timedelta(days=1)
        index.Value = data[4]
        index["Open"] = float(data[1])
        index["High"] = float(data[2])
        index["Low"] = float(data[3])
        index["Close"] = float(data[4])
        
        return index
        
class CASH(PythonData):
    def GetSource(self, config, date, isLiveMode):
        return SubscriptionDataSource("https://www.dropbox.com/s/496wpuy5qrlq9za/CASH.csv?dl=1", SubscriptionTransportMedium.RemoteFile)
    def Reader(self, config, line, date, isLive):
        
        if not (line.strip() and line[0].isdigit()): 
            return None
        
        index = CASH()
        index.Symbol = config.Symbol
        data = line.split(',')
        index.Time = datetime.strptime(data[0], "%d/%m/%Y")
        index.EndTime = index.Time + timedelta(days=1)
        index.Value = data[1] #Number of values
        index["Close"] = float(data[1])
        
        return index
        
class MOMENTUM(PythonData):
    def GetSource(self, config, date, isLiveMode):
        return SubscriptionDataSource("https://www.dropbox.com/s/qh3lfow5yyazveh/Indicator_GLD.csv?dl=1", SubscriptionTransportMedium.RemoteFile)
    def Reader(self, config, line, date, isLive):
        
        if not (line.strip() and line[0].isdigit()): 
            return None
        
        index = MOMENTUM()
        index.Symbol = config.Symbol
        data = line.split(',')
        index.Time = datetime.strptime(data[0], "%d/%m/%Y")
        index.EndTime = index.Time + timedelta(days=1)
        index.SetProperty("Indicator", str(data[1]))

        #index.Value = data[1] #Number of values
        #index["Indicator"] = str(data[1])
        
        return index
        
class CustomFeeModel:
    def GetOrderFee(self, parameters):
        self.margin_rate = 0.1
        fee = 5 + (parameters.Security.Leverage-1)*parameters.Security.Price*parameters.Order.AbsoluteQuantity*(self.margin_rate/12)
        return OrderFee(CashAmount(fee, 'USD'))