Overall Statistics
from datetime import timedelta

class BasicTemplateOptionsAlgorithm(QCAlgorithm):

    def Initialize(self):
        self.SetStartDate(2018, 1, 1)  
        self.SetEndDate(2018, 4, 30)  
        self.SetCash(30000)
        equity = self.AddEquity("SPY", Resolution.Minute)
        option = self.AddOption("SPY", Resolution.Minute)
        self.symbol = option.Symbol
        equity.SetDataNormalizationMode(DataNormalizationMode.Raw)
        option.SetFilter(-30, 30, timedelta(15), timedelta(45))
        self.SetBenchmark(equity.Symbol)
        

    def OnData(self,slice):
        optionchain = slice.OptionChains
        for i in slice.OptionChains:
            if i.Key != self.symbol: continue
            chains = i.Value
            contract_list = [x for x in chains]
        if (slice.OptionChains.Count == 0) or (len(contract_list) == 0): 
            return 
        if not self.Portfolio["SPY"].Quantity == 100: 
            self.TradePuts(optionchain) 
        elif self.Portfolio["SPY"].Quantity == 100:
            self.TradeCalls(optionchain) 
            
    def TradePuts(self,optionchain):
         for i in optionchain:
            if i.Key != self.symbol: continue
            chain = i.Value
            expiry = sorted(chain,key = lambda x: x.Expiry, reverse=True)[0].Expiry
            put = [i for i in chain if i.Expiry == expiry and i.Right == 1 and i.Greeks.Delta <=-30]
            put_contracts = sorted(put,key = lambda x: x.Greeks.Delta)
            if len(put_contracts) == 0: continue
            self.put = put_contracts[0]
            self.Sell(self.put.Symbol ,1)
    
    def TradeCalls(self,optionchain):
         for i in optionchain:
            if i.Key != self.symbol: continue
            chain = i.Value
            expiry = sorted(chain,key = lambda x: x.Expiry, reverse=True)[0].Expiry
            call = [i for i in chain if i.Expiry == expiry and i.Right == 0 and i.Strike == self.Portfolio["SPY"].AvergaePrice]
            if len(call) == 0: continue
            self.call = call[0]
            self.Sell(self.call.Symbol ,1)

    def OnOrderEvent(self, orderEvent):
        self.Log(str(orderEvent))