Overall Statistics
Total Trades
2378
Average Win
0.15%
Average Loss
-0.27%
Compounding Annual Return
15.421%
Drawdown
10.600%
Expectancy
0.355
Net Profit
730.426%
Sharpe Ratio
1.215
Loss Rate
12%
Win Rate
88%
Profit-Loss Ratio
0.54
Alpha
0.123
Beta
0.007
Annual Standard Deviation
0.101
Annual Variance
0.01
Information Ratio
0.227
Tracking Error
0.193
Treynor Ratio
16.772
Total Fees
$4756.00
from datetime import datetime,timedelta
import pandas as pd
import numpy as np
import sys
from QuantConnect.Algorithm.Framework.Risk import TrailingStopRiskManagementModel
from Execution.StandardDeviationExecutionModel import StandardDeviationExecutionModel

class  MomentumAlgorithm(QCAlgorithm):
    
    def Initialize(self):
        self.SetStartDate(2005,1,1)
        #self.SetEndDate(2012,1,1)
        self.SetCash(100000)
        self.benchmark = "SPY" 
        self.SetRiskManagement(TrailingStopRiskManagementModel(0.017))
        self.spy = self.AddEquity("SPY",Resolution.Minute)
        self.tlt = self.AddEquity("TLT",Resolution.Minute)
        self.gld = self.AddEquity("GLD",Resolution.Minute)
        
        for symbol in self.Securities.Keys:
            self.Securities[symbol].FeeModel = ConstantFeeModel(2.00)

        self.__macd = self.MACD("SPY", 12, 26, 4, MovingAverageType.Exponential, Resolution.Daily)
        self.__mac = self.MACD("TLT", 12, 26, 3, MovingAverageType.Exponential, Resolution.Daily)
        self.__ma = self.MACD("GLD", 12, 26, 3, MovingAverageType.Exponential, Resolution.Daily)
        
        self.__previous = datetime.min

        self.SetWarmUp(TimeSpan.FromDays(30))   
        self.Schedule.On(self.DateRules.WeekStart("SPY"), self.TimeRules.AfterMarketOpen("SPY", 10), self.Rebalance)
        
        self.SetExecution(StandardDeviationExecutionModel(15, 2, Resolution.Daily))

            
    def Rebalance(self):

        time_back = self.History(self.Securities.Keys,timedelta(days=90))
        
        if not self.__macd.IsReady: return


        if self.__previous.date() == self.Time.date(): return
    
        tolerance1 = 0.00024
        tolerance2 = -0.00040
        
        
        signalDeltaPercent = (self.__macd.Current.Value - self.__macd.Signal.Current.Value)/self.__macd.Fast.Current.Value
        
        signalDeltaPercent2 = (self.__mac.Current.Value - self.__mac.Signal.Current.Value)/self.__mac.Fast.Current.Value
        
        signalDeltaPercent3 = (self.__ma.Current.Value - self.__ma.Signal.Current.Value)/self.__ma.Fast.Current.Value
        
        signalDeltaPercent_SLOW = (self.__macd.Current.Value - self.__macd.Signal.Current.Value)/self.__macd.Slow.Current.Value
        
        
        
        if not time_back.empty:
            if not "SPY" in time_back.index:
                self.Log("SPY is not in data stream skipping")
                return                
            look_1 = time_back.loc[self.spy.Symbol.Value]
            if len(look_1) == 0: return
            last_look_1 = look_1["open"].iloc[0]
            if last_look_1 is None: 
                return
        
            if not "TLT" in time_back.index:
                self.Log("TLT is not in data stream skipping")
                return     
            self.Log("got past TLT")
            look_2 = time_back.loc[self.tlt.Symbol.Value]
            if len(look_2) == 0: return               
            last_look_2 = look_2["open"].iloc[0]
            if last_look_2 is None: return
            if not "GLD" in time_back.index:
                self.Log("GLD is not in data stream skipping")
                return    
            self.Log("got past GLD")
         
            look_3 = time_back.loc[self.gld.Symbol.Value]
            if len(look_3) == 0: return               
            last_look_3 = look_3["open"].iloc[0]
            if last_look_3 is None: return         
            try:
                
                self.Log("last_look_1 {}" . format(last_look_1))
                self.Log("last_look_2 {}" . format(last_look_2))
                self.Log("last_look_3 {}" . format(last_look_3))
            except:
                self.Log('An unknown error occurred trying OnData' +  str(sys.exc_info()[0]) )     
                return
                   
            if (float(self.Securities[self.spy.Symbol].Price) == float(0))  or (float(self.Securities[self.tlt.Symbol].Price) == float(0)) \
                or (float(self.Securities[self.tlt.Symbol].Price) == float(0)):
                self.Log("No current price found . skipping ")
                return
            
            GO_1= (float(self.Securities[self.spy.Symbol].Price) - float(last_look_1))/(float(self.Securities[self.spy.Symbol].Price))
            GO_2= (float(self.Securities[self.tlt.Symbol].Price) - float(last_look_2))/(float(self.Securities[self.tlt.Symbol].Price))
            GO_3 = (float(self.Securities[self.tlt.Symbol].Price) - float(last_look_3))/(float(self.Securities[self.tlt.Symbol].Price))
            
            GO_4 = (float(self.Securities[self.gld.Symbol].Price) - float(last_look_3))/(float(self.Securities[self.gld.Symbol].Price))
            
            GO_5= (float(self.Securities[self.spy.Symbol].Price) - float(last_look_1))/(float(self.Securities[self.tlt.Symbol].Price))
            
            GO_6= (float(self.Securities[self.spy.Symbol].Price) - float(last_look_1))/(float(self.Securities[self.gld.Symbol].Price))   
            
            GO_7= (float(self.Securities[self.tlt.Symbol].Price) - float(last_look_1))/(float(self.Securities[self.tlt.Symbol].Price))
            
            GO_8= (float(self.Securities[self.tlt.Symbol].Price) - float(last_look_2))/(float(self.Securities[self.spy.Symbol].Price))
            
            GO_9= (float(self.Securities[self.gld.Symbol].Price) - float(last_look_3))/(float(self.Securities[self.spy.Symbol].Price))
            
            GO_10= (float(self.Securities[self.gld.Symbol].Price) - float(last_look_3))/(float(self.Securities[self.tlt.Symbol].Price))

            first = max(GO_1,GO_2)

            self.Log("SPY {} TLT {} GLD_3 {}" . format(GO_1,GO_2,GO_3))
            if (first <= 0 and signalDeltaPercent < tolerance1):
                self.EmitInsights(Insight.Price("TLT", timedelta(seconds=1), InsightDirection.Flat))
                self.Liquidate(self.tlt.Symbol)                      
                self.EmitInsights(Insight.Price("GLD", timedelta(seconds=1), InsightDirection.Flat))                       
                self.Liquidate(self.gld.Symbol) 
                self.EmitInsights(Insight.Price("SPY", timedelta(1), InsightDirection.Up))    
                self.SetHoldings(self.spy.Symbol,0.25)


            else:

                if(GO_1> GO_2 and GO_1> GO_3 and GO_1 > GO_4 and signalDeltaPercent < -tolerance1 ):
                    if(self.Securities[self.tlt.Symbol].Invested==True):
                        self.EmitInsights(Insight.Price("TLT", timedelta(seconds=1), InsightDirection.Flat))
                        self.Liquidate(self.tlt.Symbol)
                    if(self.Securities[self.gld.Symbol].Invested==True):
                        self.EmitInsights(Insight.Price("GLD", timedelta(seconds=1), InsightDirection.Flat))
                        self.Liquidate(self.gld.Symbol)
                    self.EmitInsights(Insight.Price("SPY", timedelta(1), InsightDirection.Up))    
                    self.SetHoldings(self.spy.Symbol,1.0)
                else:
                
                    if(GO_2 > GO_3 and GO_2 > GO_1 and GO_2 > GO_6 and GO_2 > GO_8 and GO_2 > GO_7 ) :
                        if(self.Securities[self.gld.Symbol].Invested==True):
                            self.EmitInsights(Insight.Price("GLD", timedelta(seconds=1), InsightDirection.Flat))
                            self.Liquidate(self.gld.Symbol)
                        if(self.Securities[self.spy.Symbol].Invested==True):
                            self.EmitInsights(Insight.Price("SPY", timedelta(seconds=1), InsightDirection.Flat))
                            self.Liquidate(self.spy.Symbol) 
                        self.EmitInsights(Insight.Price("TLT", timedelta(1), InsightDirection.Up))    
                        self.SetHoldings(self.tlt.Symbol,1.0)         
                    elif (GO_3 > GO_2 and GO_3 > GO_1 and signalDeltaPercent3 > signalDeltaPercent) :
                        if(self.Securities[self.spy.Symbol].Invested==True):
                            self.EmitInsights(Insight.Price("SPY", timedelta(seconds=1), InsightDirection.Flat))
                            self.Liquidate(self.spy.Symbol)    
                        if(self.Securities[self.tlt.Symbol].Invested==True):
                            self.EmitInsights(Insight.Price("TLT", timedelta(seconds=1), InsightDirection.Flat))
                            self.Liquidate(self.tlt.Symbol)
                        self.EmitInsights(Insight.Price("GLD", timedelta(1), InsightDirection.Up))   
                        self.SetHoldings(self.gld.Symbol,1.0)
                        


    def OnData(self, data):
        pass