Overall Statistics
Total Trades
3
Average Win
0%
Average Loss
-1.27%
Compounding Annual Return
2.893%
Drawdown
7.200%
Expectancy
-1
Net Profit
5.884%
Sharpe Ratio
0.6
Loss Rate
100%
Win Rate
0%
Profit-Loss Ratio
0
Alpha
0.014
Beta
0.255
Annual Standard Deviation
0.05
Annual Variance
0.002
Information Ratio
-0.242
Tracking Error
0.137
Treynor Ratio
0.117
Total Fees
$3.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 = 'IBM'
        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)