Overall Statistics
Total Trades
13
Average Win
0.17%
Average Loss
0%
Compounding Annual Return
-1.113%
Drawdown
4.900%
Expectancy
0
Net Profit
-0.095%
Sharpe Ratio
-0.048
Probabilistic Sharpe Ratio
38.113%
Loss Rate
0%
Win Rate
100%
Profit-Loss Ratio
0
Alpha
0.089
Beta
0.148
Annual Standard Deviation
0.109
Annual Variance
0.012
Information Ratio
2.459
Tracking Error
0.258
Treynor Ratio
-0.036
Total Fees
$13.00
Estimated Strategy Capacity
$310000.00
from QuantConnect.Securities.Option import OptionPriceModels
from datetime import timedelta
import decimal as d

class LogicalBlackSalamander(QCAlgorithm):

    def Initialize(self):
        self._no_K = 25       # no of strikes around ATM => for uni selection
        self.MIN_EXPIRY = 1 # min num of days to expiration => for uni selection
        self.MAX_EXPIRY = 5 # max num of days to expiration => for uni selection
        self.MAX_DELTA = d.Decimal(0.07) # max delta of contract traded
        self.MIN_DELTA = d.Decimal(0.05) # min delta of contract traded
        self.MIN_PREMIUM = d.Decimal(0.3)
        self.ticker = "SPY"
        self.benchmarkTicker = "SPY"
        self.SetStartDate(2018, 12, 1)
        self.SetEndDate(2018, 12, 31)
        self.SetCash(10000)
        
        self.resolution = Resolution.Minute
        self.call, self.put, self.takeProfitTicket = None, None, None
        
        equity = self.AddEquity(self.ticker, self.resolution)
        equity.SetDataNormalizationMode(DataNormalizationMode.Raw)
        option = self.AddOption(self.ticker, self.resolution)
        option.SetDataNormalizationMode(DataNormalizationMode.Raw)
        self.symbol = option.Symbol
        
        option.SetFilter(self.UniverseFunc)
        
        # for greeks and pricer (needs some warmup) - https://github.com/QuantConnect/Lean/blob/21cd972e99f70f007ce689bdaeeafe3cb4ea9c77/Common/Securities/Option/OptionPriceModels.cs#L81
        option.PriceModel = OptionPriceModels.CrankNicolsonFD()  # both European & American, automatically
        
        # this is needed for Greeks calcs
        self.SetWarmUp(TimeSpan.FromDays(60))    # timedelta(7)

        # use the underlying equity as the benchmark
        # self.SetBenchmark(self.benchmarkTicker)
        self.SetBenchmark(self.benchmarkTicker)

    def OnData(self,slice):
        if (self.IsWarmingUp): return

        option_invested = [x.Key for x in self.Portfolio if x.Value.Invested and x.Value.Type==SecurityType.Option]
        
        if len(option_invested) == 1: return
            
        # If we already have underlying - check if we need to sell covered call
        if self.Portfolio[self.ticker].Invested:
            self.TradeCallOption(slice) 
        else:
            self.TradePutOption(slice) 
 
    def TradePutOption(self,slice):
        for i in slice.OptionChains:
            if i.Key != self.symbol: continue
        
            chain = i.Value
            
            # filter the put options contracts
            puts = [x for x in chain if x.Right == OptionRight.Put and abs(x.Greeks.Delta) > 0 and abs(x.Greeks.Delta) < self.MAX_DELTA and x.BidPrice > self.MIN_PREMIUM] 
            
            # sorted the contracts according to their expiration dates and choose the ATM options
            contracts = sorted(sorted(puts, key = lambda x: x.BidPrice, reverse=True), 
                                            key = lambda x: x.Expiry)
                                            
            if len(contracts) == 0: continue  
        
            self.put = contracts[0].Symbol
            
            # short the call options
            ticket = self.MarketOrder(self.put, -1, asynchronous = False)     
            
            # set Take Profit order
            self.takeProfitTicket = self.LimitOrder(self.put, 1, round(ticket.AverageFillPrice * 0.5, 2))
    
    def TradeCallOption(self,slice):
        for i in slice.OptionChains:
            if i.Key != self.symbol: continue
        
            chain = i.Value
            
            # filter the put options contracts
            calls = [x for x in chain if x.Right == OptionRight.Call and abs(x.Greeks.Delta) > 0 and abs(x.Greeks.Delta) < self.MAX_DELTA and x.BidPrice > self.MIN_PREMIUM] 
            
            # sorted the contracts according to their expiration dates and choose the ATM options
            contracts = sorted(sorted(calls, key = lambda x: x.BidPrice, reverse=True), 
                                             key = lambda x: x.Expiry)

            if len(contracts) == 0: continue  
        
            self.call = contracts[0].Symbol
            
            # short the call options
            ticket = self.MarketOrder(self.call, -1, asynchronous = False)     
            
            # set Take Profit order
            self.takeProfitTicket = self.LimitOrder(self.call, 1, round(ticket.AverageFillPrice * 0.5, 2))
    
 
    def OnOrderEvent(self, orderEvent):
        self.Log(str(orderEvent))
        
    def OnAssignmentOrderEvent(self, assignmentEvent):
        if self.takeProfitTicket != None:
            self.takeProfitTicket.cancel();
            self.takeProfitTicket = None

    def UniverseFunc(self, universe):
        return universe.IncludeWeeklys()\
                        .Strikes(-self._no_K, self._no_K)\
                        .Expiration(timedelta(self.MIN_EXPIRY), timedelta(self.MAX_EXPIRY))
                        
    def OnFrameworkData(self):
        return