Overall Statistics
import numpy as np
from datetime import datetime
import pandas as pd
import math


class VolTrading(QCAlgorithm):

    def __init__(self):
        self.previous = None
        self.position = None
        
        
    def Initialize(self):
        self.SetStartDate(2012,1,1) #Set Start Date
        self.SetEndDate(2018,10,29) #Set End Date
        self.SetCash(10000) #Set Strategy Cash
        self.AddEquity("SPY", Resolution.Minute)
        self.AddEquity("VIXY", Resolution.Minute)
        self.spy_window = RollingWindow[TradeBar](1)
        self.vixy_window = RollingWindow[TradeBar](1)
        self.SetWarmUp(20)


    def OnData(self, data):
        if data.ContainsKey("SPY") == False: return
        if data.ContainsKey("VIXY") == False: return
    
        self.spy_window.Add(data["SPY"])
        self.vixy_window.Add(data["VIXY"])
        
        last_minute_close_s = self.spy_window[0] #of length 2
        last_minute_close_v = self.vixy_window[0] 
        
        self.SPercent = math.log(data["SPY"].Close/last_minute_close_s.Close)
        self.VPercent = math.log(data["VIXY"].Close/last_minute_close_v.Close)
        
        
        if self.IsWarmingUp:
            return
        
        if self.SPercent <= -.01:
            if self.position == None:
                self.SetHoldings("VIXY", 1)
            elif self.position == "SPY":
                self.Liquidate("SPY")
                self.SetHoldings("VIXY", 1)
                self.position = "VIXY"
        
        elif self.VPercent <= -.01:
            if self.position == None:
                self.SetHoldings("SPY", 1)
            elif self.position == "VIXY":
                self.Liquidate("VIXY")
                self.SetHoldings("SPY", 1)
                self.position = "SPY"