Overall Statistics
Total Trades
59
Average Win
0.45%
Average Loss
0%
Compounding Annual Return
34.800%
Drawdown
8.300%
Expectancy
0
Net Profit
7.803%
Sharpe Ratio
1.337
Loss Rate
0%
Win Rate
100%
Profit-Loss Ratio
0
Alpha
0.298
Beta
-2.479
Annual Standard Deviation
0.193
Annual Variance
0.037
Information Ratio
1.254
Tracking Error
0.193
Treynor Ratio
-0.104
Total Fees
$49.00
from QuantConnect.Data.Market import *
from QuantConnect.Data.Consolidators import *
from datetime import *
from System import *
from QuantConnect import *
from QuantConnect.Algorithm import *
from QuantConnect.Indicators import *
from QuantConnect.Securities.Option import OptionPriceModels
import decimal as d 
import operator

class BasicTemplateOptionsAlgorithm(QCAlgorithm):

    def Initialize(self):
        self.SetStartDate(2018, 6, 1)
        self.SetEndDate(2018, 9, 2)
        self.SetCash(200000)
        self.symbols = []
        #self.all_contracts = []
        self.cotracts_ultimate = []
        self.fill_price =dict()
        self.marg = dict()
        self.marg_sp = dict()
        self.invested = 0
        for ticker in [
"CAT", "JD", "ROKU", "XLU", "WFC", "SBUX",
"T", "UUP", "CSCO", "GDX", "DIA", "JPM",
"XOM", "WMT", "ECA", "SNAP", "TWLO", "AAL",
"MRK", "RUT", "CL", "BHGE", "PFE", "VALE",
"TWTR", "BHC", "WYNN", "MS", "GM",
"CTL", "EWW", "XLE", "SLV", "TTWO", "BA",
"EBAY", "KORS", "VZ", "V", "ET", "PYPL",
"FCX", "SLB", "CVS", "KO", "SMH", "TEVA"]:
            option = self.AddOption(ticker)
            self.symbols.append(option.Symbol)
            for symbol in self.symbols:
                self.fill_price[symbol] = 0
            option.SetFilter(-18, -8, timedelta(0), timedelta(90))
            
            #option.PriceModel = OptionPriceModels.CrankNicolsonFD()
            
    def OnData(self,slice):
        self.today_time = self.Time.replace(hour=10, minute=30, second=0)
        if self.Time == self.today_time:
            self.Log("ff")
            self.all_contracts = []
            option_invested = [x.Key for x in self.Portfolio if x.Value.Invested and x.Value.Type==SecurityType.Option]
            for symbol in self.symbols:
                invested = [option for option in option_invested if option.Underlying == symbol.Underlying]
                
                if self.Securities[symbol.Underlying].Invested:
                    self.Log(str(symbol.Underlying))
                    continue
                
                if len(invested) > 0:
                            self.Log(str(invested[0]))
                            if self.fill_price[invested[0]] > self.Securities[invested[0]].AskPrice * d.Decimal(5):
                                self.Liquidate(invested[0])
                                self.invested -= 1
                            if self.fill_price[invested[0]] * d.Decimal(2) < self.Securities[invested[0]].BidPrice:
                                continue
                                self.Liquidate(invested[0])
                                chain = slice.OptionChains.GetValue(symbol)
                                if chain is None:
                                    continue
                                contracts_iv = [x for x in chain if 
                                #x.ImpliedVolatility > d.Decimal(0.4) and
                                x.Right == 1
                                #and d.Decimal(0.05) < x.Greeks.Delta < d.Decimal(0.4)
                                #and x.Strike < chain.Underlying.Price
                                and  x.BidPrice > d.Decimal(2) * self.Securities[invested[0]].AskPrice - (self.fill_price[invested[0]]) 
                                ]
                                """for x in chain:
                                    if x.Right == 1:
                                        self.Log(str(x.Symbol.Value))
                                        self.Log(str(x.BidPrice))
                                        self.Log(str(x.AskPrice))"""
                                contracts = sorted(sorted(contracts_iv, 
                                    key = lambda x: -x.BidPrice *100/(x.BidPrice*100+
                                    max(20*chain.Underlying.Price - ((chain.Underlying.Price - x.Strike)*100), 10*x.Strike))),
                                    key = lambda x: x.Expiry, reverse=True)
                                self.Log(str(len(contracts)))
                                #for x in contracts:
                                #    self.Log(x.Symbol.Value)
                                            
                                if len(contracts) == 0: continue
                                contract_symbol = contracts[0].Symbol
                                #symbol = contracts[0].Symbol
                        
                                ticket=self.MarketOrder(contract_symbol, -1)
                                self.fill_price[contract_symbol] = ticket.AverageFillPrice
                                self.Log(str(contract_symbol)+"  "+str(self.fill_price[contract_symbol]))
                                
                                
                            continue 
                if self.invested > 14: continue
                chain = slice.OptionChains.GetValue(symbol)
                if chain is None:
                    continue
                contracts_iv = [x for x in chain if 
                x.Right == 1
                and x.BidPrice > 0.7
                #and x.Expiry < self.Time + timedelta(days=60)
                ]
                marg_ratio_high = 0
                for x in contracts_iv:
                    marg_ratio = x.BidPrice *100/(x.BidPrice*100+
                        max(20*chain.Underlying.Price - ((chain.Underlying.Price - x.Strike)*100), 10*x.Strike))
                    self.Log(str(x.Symbol.Value))
                    self.Log(str(marg_ratio))
                    self.Log(str(x.BidPrice*100+max(20*chain.Underlying.Price - ((chain.Underlying.Price - x.Strike)*100), 10*x.Strike)))
                    self.marg_sp[x.Symbol] = (x.BidPrice*100+max(20*chain.Underlying.Price - ((chain.Underlying.Price - x.Strike)*100), 10*x.Strike))
                    if marg_ratio > marg_ratio_high:
                        self.Log("marker")
                        self.marg[chain.Symbol] = (x.BidPrice*100+
                        max(20*chain.Underlying.Price - ((chain.Underlying.Price - x.Strike)*100), 10*x.Strike))
                        marg_ratio_high = marg_ratio

                #if len(contracts) == 0: continue
                contracts_new = [x for x in contracts_iv if 
                self.marg[chain.Symbol] == self.marg_sp[x.Symbol]
                        ]
                self.all_contracts += contracts_new
                self.Log(str(len(self.all_contracts)))
            if self.invested < 15: 
                contracts_ultimate = sorted(self.all_contracts, 
                            key = lambda x: -x.BidPrice *100/(x.BidPrice*100+
                            max(20*chain.Underlying.Price - ((chain.Underlying.Price - x.Strike)*100), 10*x.Strike)))
                my_range = min(15, len(contracts_ultimate))
                for g in range(my_range):
                    contract_symbol = contracts_ultimate[g].Symbol
                    factor = d.Decimal(100000/ 15)/ self.marg_sp[contract_symbol]
                    self.Log(str(contract_symbol))
                    self.Log(str(factor))
                    if factor < 1:
                        factor = 1
                    ticket=self.MarketOrder(contract_symbol, -int(factor))
                    self.fill_price[contract_symbol] = ticket.AverageFillPrice
                    self.invested += 1
                    self.Log(str(contract_symbol)+"  "+str(self.fill_price[contract_symbol]))
                    self.Log(str(self.Securities[contract_symbol.Underlying].Price))
                    self.Log("marginremaining"+str(self.Portfolio.MarginRemaining))
                    if self.invested > 14: break