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 TheVixen(QCAlgorithm):

    def Initialize(self):
        # Set the cash we'd like to use for our backtest
        # This is ignored in live trading 
        self.SetCash(10000)
        
        # Set benchmark
        self.SetBenchmark("XIV")
        
        # Start and end dates for the backtest.
        # These are ignored in live trading.
        self.SetStartDate(2016,1,1)
        self.SetEndDate(2018,1,19)
        
        self.SetBrokerageModel(InteractiveBrokersBrokerageModel())
        
        #Assets predetermined
        self.vxx = self.AddEquity("UVXY", Resolution.Minute).Symbol
        self.xiv = self.AddEquity("XIV", Resolution.Minute).Symbol
        self.spy = self.AddEquity("SPY", Resolution.Hour).Symbol
        
        
        # Indicators
        self.emaBig = self.EMA("XIV", 5*50, Resolution.Minute)        
        self.emaSmall = self.EMA("XIV", 2*35, Resolution.Minute)
        
        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(hours=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.8)
                            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.8)
                                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.5)
                        elif self.Portfolio['UVXY'].Quantity > 0:
                            if self.emaBig < self.emaSmall:
                                self.SetHoldings(self.xiv, 0.8)
                                
                                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.8)
                                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, 1)
                        elif self.Portfolio['UVXY'].Quantity > 0:
                            if self.emaBig < self.emaSmall:
                                self.SetHoldings(self.xiv, 1)
                                self.SetHoldings(self.vxx, 0)
        
        
        
    
    
    # This function runs every 10 minutes
    def LiquidateUnrealizedLosses(self):

        if self.t == 0:
            # Curent Equity
            E  = self.Portfolio.TotalPortfolioValue
            
            # Unrealized gains/losses
            Un = self.Portfolio.TotalUnrealizedProfit
            
            # New Equity
            NE = E - Un
            
            # Increase
            I = NE - E
            
            # Percent Increase
            PI = I/E
            
            self.pi += PI
                
#            self.Log("pi = {}".format(self.pi))
            # If percent increase is less than 10%, sell all positions
            if PI <= -0.8:
                self.Log("Liqidating. Percent Increase: {} at {}".format(PI, self.Time))
                self.Liquidate(self.xiv, "Liquidating. Percent Increase: {} at {}".format(PI, self.Time))
                self.Liquidate(self.vxx, "Liquidating. Percent Increase: {} at {}".format(PI, self.Time))
                self.t = 1
                #self.Notify.Sms('8064704027', 'Lost too much. Out of all positions for the rest of the day.')
        
    # 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