Overall Statistics
from System import *
from QuantConnect import *
from QuantConnect.Algorithm import *
from QuantConnect.Data import *
import numpy as np
from datetime import timedelta

"""
I have UVXY set to the variable self.vxx. I was too lazy to 
change all of the variables from self.vxx to self.uvxy.
"""


class BasicTemplateAlgorithm(QCAlgorithm):

    def Initialize(self):
        # Set the cash we'd like to use for our backtest
        # This is ignored in live trading 
        self.SetCash(37000)
        
        # Set benchmark
        self.SetBenchmark("XIV")
        
        # Start and end dates for the backtest.
        # These are ignored in live trading.
        self.SetStartDate(2013,06,8)
        self.SetEndDate(2018,1,19)
        
        #Assets predetermined
        self.vxx = self.AddEquity("UVXY", Resolution.Hour).Symbol
        self.xiv = self.AddEquity("XIV", Resolution.Hour).Symbol
        self.spy = self.AddEquity("SPY", Resolution.Hour).Symbol
        
        
        # Indicators
        self.emaBig = self.EMA("XIV", 5, Resolution.Hour)        
        self.emaSmall = self.EMA("XIV", 2, Resolution.Hour)
        
        self.smaBig = self.SMA("SPY", 200, Resolution.Hour)
        self.smaSmall = self.SMA("SPY", 100, Resolution.Hour)
        self.emaBullBIG = self.EMA("SPY", 50, Resolution.Hour)
        self.emaBullSMALL = self.EMA("SPY", 25, Resolution.Hour)
        
        
        
        # Schedules
        self.Schedule.On(self.DateRules.EveryDay(), self.TimeRules.Every(timedelta(minutes=5)), Action(self.LiquidateUnrealizedLosses))
        self.Schedule.On(self.DateRules.EveryDay("SPY"), self.TimeRules.AfterMarketOpen("SPY", 4), Action(self.EveryDayAfterMarketOpen))
        # schedule an event to fire every trading day for a security the
        # time rule here tells it to fire 10 minutes before SPY's market close
        self.Schedule.On(self.DateRules.EveryDay("SPY"), self.TimeRules.BeforeMarketClose("SPY", 10), Action(self.EveryDayBeforeMarketClose))
        
        # Timer
        self.t = 0
        
        # Unrealized earnings total for each day. Pi stands for percent increase.
        self.pi = 0
        
        # Timer that is switched to 1 if the market is 10 minutes from closing.
        self.closing = 0
        
        # Get warmup data so that the Algorithm can start trading
        self.SetWarmUp(timedelta(200))
        
        
        
    def OnData(self, slice):
        if self.t == 0:
            if self.t == 0:
                
                if self.smaBig < self.smaSmall:
                
                    if not self.Portfolio.Invested:
                         
                        if self.emaBig < self.emaSmall:
                            self.SetHoldings(self.xiv, 0.75)
                            self.SetHoldings(self.vxx, 0)
                            
                    
                    elif self.Portfolio.Invested:    
                        if self.emaBig > self.emaSmall:
                            
                            self.SetHoldings(self.xiv, 0)
                            self.SetHoldings(self.vxx, 0)
                    
                    
                # If the market is detected to be in a downward trend, a whole new set of Indicators are used        
                        
                elif self.smaBig > self.smaSmall:
                    if self.emaBullBIG < self.emaBullSMALL:
                        if not self.Portfolio.Invested:
                         
                            if self.emaBig < self.emaSmall:
                                self.SetHoldings(self.xiv, 0.75)
                                self.SetHoldings(self.vxx, 0)
                                
                        
                        elif self.Portfolio['XIV'].Quantity > 0:
                            if self.emaBig > self.emaSmall:
                                
                                self.SetHoldings(self.xiv, 0)
                                self.SetHoldings(self.vxx, 0.375)
                        elif self.Portfolio['UVXY'].Quantity > 0:
                            if self.emaBig < self.emaSmall:
                                self.SetHoldings(self.xiv, 0.75)
                                
                                self.SetHoldings(self.vxx, 0)
                                
                                
                        
                        
                        
                    
                    elif self.emaBullBIG > self.emaBullSMALL:    
                        if not self.Portfolio.Invested:
                            #Buy XIV if EMA 3 is > EMA 9 
                            if self.emaBig < self.emaSmall:
                                self.SetHoldings(self.xiv, 0.75)
                                self.SetHoldings(self.vxx, 0)
                            
                              
                                
                        elif self.Portfolio['XIV'].Quantity > 0:
                            if self.emaBig > self.emaSmall:
                                self.SetHoldings(self.xiv, 0)
                                self.SetHoldings(self.vxx, 0.75)
                        elif self.Portfolio['UVXY'].Quantity > 0:
                            if self.emaBig < self.emaSmall:
                                self.SetHoldings(self.xiv, 0.75)
                                self.SetHoldings(self.vxx, 0)
        
        
        
    
    
    """
    THIS IS THE FUNCTION THAT IS CHANGIGN RETURNS
    """
    def LiquidateUnrealizedLosses(self):
        pass
        
        
        
        
    # This function sets t back to 0 every day 10 minutes after the market opens
    def EveryDayAfterMarketOpen(self):
        self.t = 0
        self.pi = 0
        self.closing = 0
        
    def EveryDayBeforeMarketClose(self):
        self.closing = 1