Overall Statistics
Total Trades
570
Average Win
0.24%
Average Loss
-0.21%
Compounding Annual Return
-95.101%
Drawdown
23.300%
Expectancy
-0.432
Net Profit
-23.262%
Sharpe Ratio
-4.985
Probabilistic Sharpe Ratio
0.000%
Loss Rate
73%
Win Rate
27%
Profit-Loss Ratio
1.13
Alpha
-0.89
Beta
-0.212
Annual Standard Deviation
0.185
Annual Variance
0.034
Information Ratio
-4.713
Tracking Error
0.227
Treynor Ratio
4.351
Total Fees
$712.50
from datetime import timedelta

class OptionsAlgorithm(QCAlgorithm):

    # Order ticket for our stop order, Datetime when stop order was last hit
    stopMarketTicket = None
    stopMarketOrderFillTime = datetime.min
    highestSPYPrice = 0
    
    def Initialize(self):
        self.SetStartDate(2015, 11, 1)
        self.SetEndDate(2015, 12, 1)
        self.SetCash(20000)
        self.syl = "SPY"
        self.spy = "SPY"
        equity = self.AddEquity(self.syl, Resolution.Minute)
        equity.SetDataNormalizationMode(DataNormalizationMode.Raw)
        
        # create a XX-period exponential moving average; since this is minute, may have to multiply by 2
        self.fast = self.EMA("SPY", 26, Resolution.Minute);

        # create a XX-period exponential moving average; since this is minute, may have to multiply by 2
        slow_ema_lookback = 97
        self.slow = self.EMA("SPY", slow_ema_lookback, Resolution.Minute);
    
        # 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.SetWarmUp(slow_ema_lookback)
     
        
    def OnData(self,slice):
        
        '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''
        if self.IsWarmingUp:
            return
        
        
        # buying puts; needs to be in a loop; will need to initiate options chain here; may need to incorporate slope
        # will need to check and see if holding any positions self.Portfolio[self.BuyPut()].Quantity == 0 and 
        #self.Securities[self.vix].Price > 30 and not self.buy_spy
        
        if (self.Portfolio.Invested == False) and (self.fast.Current.Value < self.slow.Current.Value) and (self.Securities[self.spy].Price >= (self.fast.Current.Value - 0.05)):
            self.BuyPut()
        
        #if (self.fast.Current.Value > self.slow.Current.Value):
        #    self.Liquidate()
            
        if (self.Securities["SPY"].Close < self.highestSPYPrice) or (self.Securities[self.spy].Price < (self.fast.Current.Value - 0.20)) or (self.Securities[self.spy].Close >= (self.fast.Current.Value + 0.20)):
                
            #2. Save the new high to highestSPYPrice; then update the stop price to 90% of highestSPYPrice 
            self.highestSPYPrice = self.Securities["SPY"].Close
            #updateFields = UpdateOrderFields()
            #updateFields.StopPrice = self.highestSPYPrice * 0.9
            #self.stopMarketTicket.Update(updateFields)
            self.Liquidate()
    
        #buying calls;
        #if (self.fast.Current.Value > self.slow.Current.Value):
        #    self.BuyCall()
            
        # if self.fast.IsReady:
        #    if self.Portfolio[self.syl].Quantity == 0 and self.fast.Current.Value > self.slow.Current.Value:  
        #        self.Buy(self.syl,100)
            
            # # <1> if there is a MACD short signal, liquidate the stock            
            # elif self.Portfolio[self.syl].Quantity > 0 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   
            # history = self.History([self.syl], 30, Resolution.Daily).loc[self.syl]['close']
            # self.Plot('Stock Plot','stop loss frontier', min(history))
            # if self.Portfolio[self.syl].Quantity > 0:        
            #     if self.Securities[self.syl].Price < min(history):
            #         self.Liquidate()
            
            
            # <3> if there is a MACD short signal, trade the options     
        #    elif self.Portfolio[self.syl].Quantity > 0 and self.macd.Current.Value < self.macd.Signal.Current.Value:
        #        try:               
        #            if self.Portfolio[self.syl].Invested and not self.Portfolio[self.contract].Invested \
        #              and self.Time.hour != 0 and self.Time.minute == 1:
        #                self.SellCall() 
        #        except:
        #            if self.Portfolio[self.syl].Invested and self.Time.hour != 0 and self.Time.minute == 1:
        #                self.SellCall() 
                        
                
    def BuyPut(self):
        contracts = self.OptionChainProvider.GetOptionContractList(self.underlyingsymbol, self.Time.date())
        if len(contracts) == 0: return
        filtered_contracts = self.InitialFilter(self.underlyingsymbol, contracts, -1, 1, 0, 14)
        put = [x for x in filtered_contracts if x.ID.OptionRight == OptionRight.Put] 
        
        if len(put) == 0:
            return
        
        # sorted the contracts according to their expiration dates and choose the ATM options
        contracts = sorted(sorted(put, key = lambda x: abs(self.Securities[self.syl].Price - x.ID.StrikePrice)), 
                                        key = lambda x: x.ID.Date, reverse=False)
        self.contract = contracts[0]
        self.AddOptionContract(self.contract, Resolution.Minute)
        self.Buy(self.contract, 5)
    
    # def BuyCall(self):
    #    contracts = self.OptionChainProvider.GetOptionContractList(self.underlyingsymbol, self.Time.date())
    #    if len(contracts) == 0: return
    #    filtered_contracts = self.InitialFilter(self.underlyingsymbol, contracts, -3, 3, 0, 30)
    #    call = [x for x in filtered_contracts if x.ID.OptionRight == 1] 
        # sorted the contracts according to their expiration dates and choose the ATM options
    #    contracts = sorted(sorted(call, key = lambda x: abs(self.Securities[self.syl].Price - x.ID.StrikePrice)), 
    #                                    key = lambda x: x.ID.Date, reverse=True)
    #    self.contract = contracts[0]
    #    self.AddOptionContract(self.contract, Resolution.Minute)
    #    self.Buy(self.contract, 1)
        
    def SellCall(self):
        contracts = self.OptionChainProvider.GetOptionContractList(self.underlyingsymbol, self.Time.date())
        if len(contracts) == 0: return
        filtered_contracts = self.InitialFilter(self.underlyingsymbol, contracts, -3, 3, 0, 30)
        put = [x for x in filtered_contracts if x.ID.OptionRight == OptionRight.Call] 
        
        if len(put) == 0:
            return
        
        # sorted the contracts according to their expiration dates and choose the ATM options
        contracts = sorted(sorted(put, key = lambda x: abs(self.Securities[self.syl].Price - x.ID.StrikePrice)), 
                                        key = lambda x: x.ID.Date, reverse=False)
        self.contract = contracts[0]
        self.AddOptionContract(self.contract, Resolution.Minute)
        self.Sell(self.contract, 1)

    def InitialFilter(self, underlyingsymbol, symbol_list, min_strike_rank, max_strike_rank, min_expiry, max_expiry):
        
        ''' This method is an initial filter of option contracts
            according to the range of strike price and the expiration date '''
            
        if len(symbol_list) == 0 : return
        # fitler the contracts based on the expiry range
        contract_list = [i for i in symbol_list if min_expiry < (i.ID.Date.date() - self.Time.date()).days < max_expiry]
        
        if len(contract_list) == 0:
            return []
        
        # find the strike price of ATM option
        atm_strike = sorted(contract_list,
                            key = lambda x: abs(x.ID.StrikePrice - self.Securities[underlyingsymbol].Price))[0].ID.StrikePrice
        strike_list = sorted(set([i.ID.StrikePrice for i in contract_list]))
        # find the index of ATM strike in the sorted strike list
        atm_strike_rank = strike_list.index(atm_strike)
        try: 
            min_strike = strike_list[atm_strike_rank + min_strike_rank]
            max_strike = strike_list[atm_strike_rank + max_strike_rank]
        except:
            min_strike = strike_list[0]
            max_strike = strike_list[-1]
           
        filtered_contracts = [i for i in contract_list if i.ID.StrikePrice >= min_strike and i.ID.StrikePrice <= max_strike]

        return filtered_contracts