Overall Statistics
Total Trades
0
Average Win
0%
Average Loss
0%
Compounding Annual Return
0%
Drawdown
0%
Expectancy
0
Net Profit
0%
Sharpe Ratio
0
Probabilistic Sharpe Ratio
0%
Loss Rate
0%
Win Rate
0%
Profit-Loss Ratio
0
Alpha
0
Beta
0
Annual Standard Deviation
0
Annual Variance
0
Information Ratio
-0.74
Tracking Error
0.308
Treynor Ratio
0
Total Fees
$0.00
Estimated Strategy Capacity
$0
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
    #TSLAFilledPrice = 1000
    #openingBar = None 
    
    def Initialize(self):
        self.SetStartDate(2020, 1, 1)  
        self.SetEndDate(2021, 3, 5)  
        self.SetCash(100000)
        equity = self.AddEquity('TSLA', Resolution.Minute)
        option = self.AddOption('TSLA', Resolution.Minute)
        equity.SetDataNormalizationMode(DataNormalizationMode.Raw)
        self.underlyingsymbol = equity.Symbol
        
        # In initialize create a consolidator and add its bars to the window
        self.window = RollingWindow[TradeBar](3)
        equitybar=self.Consolidate('TSLA', timedelta(minutes=5), lambda x: self.window.Add(x))
        
        self.contract = None
        
    def OnData(self, data):
        # Portfolio Invested means at least hold one stock, cannot use
        #if  self.Portfolio.Invested:
        #    return
        
        # buy the option if we don't own one
        if self.contract is not None and not self.Portfolio[self.contract].Invested:
            self.Buy(self.contract, 1)
            
        
        # check that we hold no options
        if len([security for security in self.Portfolio.Values if security.Type==SecurityType.Option and not security.Invested])==0 \
            and self.window.IsReady and self.window[2].Close > self.window[2].Open \
            and self.window[1].Close < self.window[1].Open \
            and self.window[0].Close > self.window[0].Open \
            and self.window[0].Close > self.window[1].Open: 
            self.Debug("Call Indicator")
            self.BuyCall()
            
        #elif self.window.IsReady and self.window[2].Close < self.window[2].Open \
        #    and self.window[1].Close > self.window[1].Open \
        #    and self.window[0].Close < self.window[0].Open \
        #    and self.window[0].Close < self.window[1].Open: 
            #self.Debug("Put Indicator")   
            #self.MarketOrder("TSLA",-100) 
    def OnOrderEvent(self, orderEvent):     

        #1. Write code to only act on fills
        if orderEvent.Status == OrderStatus.Filled:
            self.Log(str(orderEvent.Symbol))
            
    def BuyCall(self):
        contracts = self.OptionChainProvider.GetOptionContractList(self.underlyingsymbol, self.Time.date())
        if len(contracts) == 0: return
        filtered_contracts = self.OptionsFilter(self.underlyingsymbol, contracts, -3, 3, 60, 90)
        call = [x for x in filtered_contracts if x.ID.OptionRight == 0] 
        # sorted the contracts according to their expiration dates and choose the ATM options
        contracts = sorted(sorted(call, key = lambda x: abs(self.Securities['TSLA'].Price - x.ID.StrikePrice)), 
                                        key = lambda x: x.ID.Date, reverse=True)
        contract = contracts[0]
        self.Debug("strike price is"  + str(contracts[0].ID.StrikePrice))
        self.contract = self.AddOptionContract(contract, Resolution.Minute).Symbol
        
    def OptionsFilter(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]
        # 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