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

class vixSpyExample(QCAlgorithm):

    def Initialize(self):
        self.SetStartDate(2015,8,20)  #Set Start Date
        self.SetEndDate(2015,8,30)    #Set End Date
        self.SetCash(10000)           #Set Strategy Cash

        # Quandl id    
        self.vix = 'CBOE/VIX'

         # Add Quandl VIX
        self.AddData(QuandlVix, "CBOE/VIX", Resolution.Minute)
        
        # Add SPY options
        option = self.AddOption("SPY", Resolution.Minute)
        option.SetFilter(-10, +10, timedelta(30), timedelta(60))
        
        self.symbol = option.Symbol

    
    def OnData(self, slice):
        optionchain = slice.OptionChains
        for i in slice.OptionChains:
            if i.Key != self.symbol: continue
        
            # Return if holding option contracts
            if self.Portfolio.Invested: return
        
            # Buy OTM call option if the VIX is between 35 and 42
            if self.Securities[self.vix].Price > 35 and self.Securities[self.vix].Price < 42:
                option_contract = self.BuyCall(optionchain)
                self.Buy(option_contract, 2)
    
    def BuyCall(self,optionchain):
        for i in optionchain:
            if i.Key != self.symbol: continue

            # Retrieve option chain
            chain = i.Value
            
            # sorted the optionchain by expiration date and choose the furthest date
            expiry = sorted(chain,key = lambda x: x.Expiry, reverse=True)[0].Expiry
        
            # filter the call options from the contracts expires on that date
            call = [i for i in chain if i.Expiry == expiry and i.Right == 0]

            # sorted the contracts according to their strike prices 
            call_contracts = sorted(call,key = lambda x: x.Strike)
            
            if len(call_contracts) == 0: continue
            
            # choose the deep OTM call option
            self.call = call_contracts[-1]

            return self.call.Symbol
        
    def OnOrderEvent(self, orderEvent):
        ''' Event when the order is filled. Debug log the order fill. :OrderEvent:'''
        self.Log(str(orderEvent))
        order = self.Transactions.GetOrderById(orderEvent.OrderId)
       
        
class QuandlVix(PythonQuandl):
    def __init__(self):
        self.ValueColumnName = "vix Close"