Overall Statistics
Total Trades
38
Average Win
1.07%
Average Loss
-0.38%
Compounding Annual Return
2.618%
Drawdown
2.500%
Expectancy
0.602
Net Profit
5.316%
Sharpe Ratio
0.97
Loss Rate
58%
Win Rate
42%
Profit-Loss Ratio
2.81
Alpha
0.011
Beta
0.138
Annual Standard Deviation
0.027
Annual Variance
0.001
Information Ratio
-0.819
Tracking Error
0.099
Treynor Ratio
0.189
Total Fees
$38.00
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)