Overall Statistics
from datetime import timedelta

class OptionsAlgorithm(QCAlgorithm):

    def Initialize(self):
        self.SetStartDate(2015, 11, 1)
        self.SetEndDate(2017, 11, 1)
        self.SetCash(50000)
        self.syl = 'SPY'
        equity = self.AddEquity(self.syl, Resolution.Minute)
        equity.SetDataNormalizationMode(DataNormalizationMode.Raw)
        self.macd = self.MACD(self.syl, 12, 26, 9, MovingAverageType.Exponential, Resolution.Daily)
        self.underlyingsymbol = equity.Symbol
        # use the underlying equity as the benchmark
        self.SetBenchmark(equity.Symbol)
        self.hist = RollingWindow[float](390*22)
        self.contract = None
        
    def OnData(self,slice):
        
        if  not self.MarketOpen() or not slice.ContainsKey(self.syl): return
    
        self.hist.Add(float(slice[self.syl].Close))
     
        if self.macd.IsReady:
            if not self.Portfolio[self.syl].Invested and self.macd.Current.Value > self.macd.Signal.Current.Value:  
                self.MarketOrder(self.syl,100)
            
            # # <1> if there is a MACD short signal, liquidate the stock            
            # elif self.Portfolio[self.syl].Invested and self.macd.Current.Value < self.macd.Signal.Current.Value:
            #     self.Liquidate()
            
            # <2> if today's close < lowest close of last 30 days, liquidate the stock   
            # self.Plot('Stock Plot','stop loss frontier', min(self.hist))
            # self.Plot('Stock Plot','undelying price', self.Securities[self.syl].Price)  
            if self.Portfolio[self.syl].Invested:        
                if self.Securities[self.syl].Price < min(self.hist):
                    self.Liquidate() 
            
            
            # # <3> if there is a MACD short signal, trade the options     
            # elif self.Portfolio[self.syl].Invested and self.macd.Current.Value < self.macd.Signal.Current.Value:
            #     if self.contract is None:
            #         self.SellCall()
            #     elif not self.Portfolio[self.contract].Invested:
            #         self.SellCall() 

    def MarketOpen(self):
        return self.Time.hour != 10 and self.Time.minute == 1
                        

    def SellCall(self):
        contracts = self.OptionChainProvider.GetOptionContractList(self.underlyingsymbol, self.Time.date())
        if len(contracts) == 0: return
        min_expiry = 0
        max_expiry = 40
        
        filtered_contracts = [i for i in contracts if min_expiry <= (i.ID.Date.date() - self.Time.date()).days <= max_expiry]
        call = [x for x in filtered_contracts if x.ID.OptionRight == 0] 
        
        if len(call) == 0: return
        # sorted the contracts according to their expiration dates and choose the ATM options
        self.contract = sorted(sorted(call, key = lambda x: abs(self.Securities[self.syl].Price - x.ID.StrikePrice)), 
                                        key = lambda x: x.ID.Date, reverse=True)[0]
      
        self.AddOptionContract(self.contract, Resolution.Minute)
        self.MarketOrder(self.contract, -1)

        
    def BuyPut(self):
        contracts = self.OptionChainProvider.GetOptionContractList(self.underlyingsymbol, self.Time.date())
        if len(contracts) == 0: return
        min_expiry = 0
        max_expiry = 40
        
        filtered_contracts = [i for i in contracts if min_expiry <= (i.ID.Date.date() - self.Time.date()).days <= max_expiry]
        put = [x for x in filtered_contracts if x.ID.OptionRight == 1] 
        
        if len(put) == 0: return
        # sorted the contracts according to their expiration dates and choose the ATM options
        self.contract = sorted(sorted(put, key = lambda x: abs(self.Securities[self.syl].Price - x.ID.StrikePrice)), 
                                        key = lambda x: x.ID.Date, reverse=True)[0]
      
        self.AddOptionContract(self.contract, Resolution.Minute)
        self.MarketOrder(self.contract, 1)