Overall Statistics
from QuantConnect.Data.Custom.CBOE import *

class VixAlgo(QCAlgorithm):

    def Initialize(self):
        self.SetStartDate(2020, 1, 2)
        self.SetEndDate(2020, 1, 2) 
        self.SetCash(10000)
        
        self.spy = self.AddEquity("SPY", Resolution.Minute).Symbol
        self.cboeVix = self.AddData(CBOE, "VIX").Symbol
        self.vixPrevious = None
        self.vixLatest = None
        self.pct_change = None
        self.SetWarmup(2, Resolution.Daily)
        
        self.Schedule.On(self.DateRules.EveryDay(), self.TimeRules.AfterMarketOpen(self.spy, 15), Action(self.Buy))
        self.Schedule.On(self.DateRules.EveryDay(), self.TimeRules.AfterMarketOpen(self.spy, 60), Action(self.Sell))


    def OnData(self, data):
        # Update vix data
        if data.ContainsKey(self.cboeVix):
            self.vixPrevious = self.vixLatest
            self.vixLatest = data.Get(CBOE, self.cboeVix).Close
            
        if self.IsWarmingUp:
            return 
        
        if not data.Bars.ContainsKey("SPY"):
            return
        
        if self.vixPrevious != 0:
            self.pct_change = (self.vixLatest - self.vixPrevious) / self.vixPrevious
            
    def Buy(self):
        
        if self.pct_change is not None and self.pct_change > 0.05:
            self.SetHoldings("SPY", 1)
        
    def Sell(self):
        self.SetHoldings("SPY", 0)