Overall Statistics
from datetime import timedelta

class BasicTemplateOptionsAlgorithm(QCAlgorithm):

    def Initialize(self):
        self.SetStartDate(2017, 01, 07)
        self.SetEndDate(2017, 02, 01)
        self.SetCash(100000)
        self.symbol = "SPY"

        equity = self.AddEquity(self.symbol, Resolution.Minute)
        option = self.AddOption(self.symbol, Resolution.Minute)
        option.SetFilter(-20, 20, timedelta(30), timedelta(60))

        # use the underlying equity as the benchmark
        self.SetBenchmark(equity.Symbol)
        
    def OnData(self, slice):
        self.TradeOptions(slice)

    def TradeOptions(self, slice):
        if not self.Portfolio.Invested and self.Time.hour != 0 and self.Time.minute != 0: 
        
            shortDelta = .3
            longDelta = .05
            contracts = 1

            shortCall = None
            longCall = None
            shortPut = None
            longPut = None

            for i in slice.OptionChains:
                chain = i.Value
                contract_list = [x for x in chain]
                
                # if there is no optionchain or no contracts in this optionchain, pass the instance
                if (slice.OptionChains.Count == 0) or (len(contract_list) == 0): 
                    return   
    
                # sorted optionchain by expiration date and choose the furthest date
                expiry = sorted(chain, key = lambda x: x.Expiry)[-1].Expiry
                
                # filter call and put options from the contracts
                call = [i for i in chain if i.Right == 0 and i.Expiry == expiry]
                put = [i for i in chain if i.Right == 1 and i.Expiry == expiry]
    
                # sort calls by strike prices in ascending order
                call_contracts = sorted(call, key = lambda x: x.Strike)    
                # sort puts by strike prices in descending order
                put_contracts = sorted(put, key = lambda x: x.Strike, reverse=True)    
                
                if len(call_contracts) == 0 or len(put_contracts) == 0 : 
                    continue
                
                # loop from low strike to high
                for call in call_contracts:
                    self.Log("call=" + str(call.Greeks.Delta))

                    if((shortCall is None) and (call.Greeks.Delta <= shortDelta)):
                        shortCall = call
                    elif((longCall is None) and (call.Greeks.Delta <= longDelta)):
                        longCall = call
                        break # stop for loop

                # loop from high strike to low
                for put in put_contracts:
                    self.Log("put=" + str(put.Greeks.Delta))

                    if((shortPut is None) and (put.Greeks.Delta >= -shortDelta)):
                        shortPut = put
                    elif((longPut is None) and (put.Greeks.Delta >= -longDelta)):
                        longPut = put
                        break # stop for loop

                self.Log(str(longCall.Greeks.Delta))
                self.Log(str(shortCall.Greeks.Delta))
                self.Log(str(shortPut.Greeks.Delta))
                self.Log(str(longPut.Greeks.Delta))

                if((longCall is not None) and (shortCall is not None) and (longPut is not None) and (shortPut is not None)):
                    break

            self.Log(str(longCall.Greeks.Delta))
            self.Log(str(shortCall.Greeks.Delta))
            self.Log(str(shortPut.Greeks.Delta))
            self.Log(str(longPut.Greeks.Delta))

            if((longCall is None) or (shortCall is None) or (longPut is None) or (shortPut is None)):
                return

            # trade the options 
            self.Buy(longCall.Symbol, contracts)
            self.Sell(shortCall.Symbol, contracts)
            self.Sell(shortPut.Symbol, contracts)
            self.Buy(longPut.Symbol, contracts)