Overall Statistics
Total Trades
52
Average Win
0%
Average Loss
-0.34%
Compounding Annual Return
-61.919%
Drawdown
5.100%
Expectancy
-1
Net Profit
-5.069%
Sharpe Ratio
-2.537
Probabilistic Sharpe Ratio
15.431%
Loss Rate
100%
Win Rate
0%
Profit-Loss Ratio
0
Alpha
-0.767
Beta
0.23
Annual Standard Deviation
0.226
Annual Variance
0.051
Information Ratio
-5.162
Tracking Error
0.275
Treynor Ratio
-2.49
Total Fees
$192.00
import decimal as d
import numpy as np
import pandas as pd
import math
import datetime
from QuantConnect.Orders import *
from datetime import datetime

import json
from clr import AddReference
AddReference("System")
AddReference("QuantConnect.Common")
AddReference("QuantConnect.Algorithm")
AddReference("QuantConnect.Algorithm.Framework")
import pytz, datetime

from QuantConnect import *
from QuantConnect.Algorithm import *
from QuantConnect.Algorithm.Framework import *
from QuantConnect.Algorithm.Framework.Portfolio import PortfolioTarget
from QuantConnect.Algorithm.Framework.Risk import RiskManagementModel


       
        
class DropboxBaseDataUniverseSelectionAlgorithm(QCAlgorithm):
    
    def Initialize(self):
        
        self.SetStartDate(2020,5,10)
        self.SetEndDate(2020,5,29)
        self.sl = 20
        self.tp = 40
        self.tomorrow = {}
        self.SetCash(100000)
        
        # add equity tickers to the universe (before the market open of each trading day)
        self.UniverseSettings.Resolution = Resolution.Minute;
        self.AddUniverse(StockDataSource, "my-stock-data-source", self.stockDataSource)
        self.UniverseSettings.DataNormalizationMode = DataNormalizationMode.Raw
        self.SetWarmUp(4000)
        self.thesymbols = [] 
        self.buyorsells = []
        self.strikes = []
        self.putorcalls = []
        self.symbols = []
        self.expiries = []
        self.items = {}
        # set schedule to liquidate at 10 minutes prior to the market close of each trading day
        #spy.SetDataNormalizationMode(DataNormalizationMode.Raw)
        self.SetRiskManagement(TrailingStopRiskManagementModel(1))

        self.SetRiskManagement(MaximumUnrealizedProfitPercentPerSecurity(0.5))
        self.SetRiskManagement(MaximumDrawdownPercentPerSecurity(0.2))
        self.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage)

    def stockDataSource(self, data): # This will grab for each date the different tickers in the csv and add them to the universe
        
        list = []
        try:
            #self.Debug(data)
            for item in data:
                if ' ' not in item['Symbols']:
                    list.append(item['Symbols'])
                    self.symbols.append(item['Symbols'])
                    self.items[item['Symbols']] = item
            #self.Debug(str(list))
        except:
            abc=123
        return list


        
        
    def OnData(self, data):
        option_invested = [x.Key for x in self.Portfolio if x.Value.Invested and x.Value.Type==SecurityType.Option]
        option_price = {}
        yesterday = (self.UtcTime.date() - timedelta(days=1))
        if yesterday in list(self.tomorrow.keys()):
            for symbol2 in self.tomorrow[yesterday]:
                if symbol2 not in self.symbols:
                    self.symbols.append(symbol2)
        print(self.symbols)
        for symbol in data.Keys:
            if symbol.Value in self.symbols:
                # Add newly invested securities
                if symbol in option_invested and symbol.Value.split(' ')[0] not in self.thesymbols:
                    self.symbols.remove(symbol.Value.split(' ')[0])
                    self.thesymbols.append(symbol.Value.split(' ')[0])
                    #self.Debug(self.thesymbols)
                    #self.Debug(symbol.Value.split(' ')[0])
                    #self.Debug(self.UtcTime)
                if symbol.SecurityType == 1: #Selecting only stocks
    
                    invested = [option for option in option_invested if option.Underlying == symbol]
                    #if len(invested) > 0: 
                        #self.Debug("Already invested in "+ str(symbol))
                        #continue
                        ## 'return' would skip the rest of the assets in the current OnData slice. The strategy wants to skip the
                        ## statements below and moves the control to the next asset. So, 'return' should be changed to 'continue'
                        #return 
                    
                    if symbol.Value not in self.thesymbols and symbol.Value in self.symbols:
                        
                        #self.Debug(self.Time.time())
                        #self.Debug(symbol.Value)
                        #self.Log(self.Time.time())
                        #self.Log(symbol)
                        #self.SetHoldings(key, 0.1)   
                        symsym = symbol.Value
                        if ' ' not in symsym:
                                
                            stk = self.AddEquity(symsym, Resolution.Minute)
                            stk.SetDataNormalizationMode(DataNormalizationMode.Raw)
 
                            contracts = self.OptionChainProvider.GetOptionContractList(symbol, self.Time.date()) # Get list of strikes and expiries
                            self.TradeOptions(contracts, symsym) # Select the right strikes/expiries and trade

    def TradeOptions(self, contracts, ticker):
            #self.Debug(ticker)
        # run CoarseSelection method and get a list of contracts expire within 15 days from now on
        # and the strike price between rank -1 to rank 1, rank being the step of the contract
            exp = datetime.datetime.strptime(self.items[ticker]['Expiries'] + '/2020', "%m/%d/%Y")
            exp = exp.date()
            
            today = self.UtcTime.date()
            future = exp
            diff = future - today
            #self.Debug(diff.days)
            buyorsell = self.items[ticker]['BuyorSell']
            putorcall = self.items[ticker]['PutorCall']
            filtered_contracts = self.CoarseSelection(ticker, contracts, -1, 1, diff.days, diff.days+1) # set min_expiry as 1 would avoid trading the contract that expires on the same day
            #if ticker == 'SE' or ticker == 'WYNN' or ticker == 'GILD':
                #self.Debug(ticker)
                #self.Debug(str(diff.days))
                #self.Debug(filtered_contracts)
            if len(filtered_contracts) >0:
                    
                expiry = sorted(filtered_contracts,key = lambda x: x.ID.Date, reverse=False)[0].ID.Date # Take the closest expiry
                
                # filter the call options from the contracts expire on that date
                call = [i for i in filtered_contracts if i.ID.Date == expiry and i.ID.OptionRight == 0]
                # sorted the contracts according to their strike prices
                call_contracts = sorted(call,key = lambda x: x.ID.StrikePrice)

                self.call = call_contracts[0]
                for i in filtered_contracts:
                    if i.ID.Date == expiry and i.ID.OptionRight == 1 and i.ID.StrikePrice ==call_contracts[0].ID.StrikePrice:
                        self.put = i
                        
                ''' Before trading the specific contract, you need to add this option contract
                    AddOptionContract starts a subscription for the requested contract symbol '''
            
                # self.call is the symbol of a contract 
                
                callContract = self.AddOptionContract(self.call, Resolution.Minute)
                putContract = self.AddOptionContract(self.put, Resolution.Minute)
                



                if putorcall == 'C':
                    
                    amt2 = self.Securities[self.call].Price
                    if amt2 != 0:
                        self.Debug(ticker + ' amt2: ' + str(amt2) + ', portfolio ' + str(self.Portfolio.MarginRemaining) + ', amt: ' + str( ( self.Portfolio.MarginRemaining / 10000 ) / amt2) + ' value: ' + str(self.Portfolio.MarginRemaining / 10000))
                    
                        amt = (self.Portfolio.MarginRemaining / 10000) / amt2
                        amt = int(amt)
                        if buyorsell == 'sell':
                            amt = amt * -1
                        if self.call.Value.split(' ')[0]  not in self.thesymbols and  self.call.Value.split(' ')[0] in self.symbols:
                            o = self.MarketOrder(self.call.Value, amt)
                            self.Debug(amt * amt2)
                            #o2 = self.LimitOrder(self.call.Value, -1 * amt, self.Securities[self.call].Price * (1.40))
                            #o3 = self.StopMarketOrder(self.call.Value, -1 * amt, self.Securities[self.call].Price / (1.2))
                            self.thesymbols.append(self.call.Value.split(' ')[0])
                            self.symbols.remove(self.call.Value.split(' ')[0])
                            if (self.UtcTime.date()) not in list(self.tomorrow.keys()):
                                self.tomorrow[(self.UtcTime.date())] = []
                            self.tomorrow[(self.UtcTime.date())].append(self.call.Value.split(' ')[0])
                            self.Debug(o)
                            #self.Debug(self.UtcTime)
                            #self.Debug(self.call.Value)
                            #self.Debug("Call Strike Price : "+str(self.call.ID.StrikePrice))
                            #self.Debug("Put Strike Price (for reference): "+str(self.call.ID.StrikePrice))
                            #self.Debug("Security Price : "+str(self.Securities[self.call].Price))
                    else:
                        self.Debug(self.UtcTime)
                        self.Debug('no price to discover for ' + ticker)
                        #self.symbols.remove(ticker)
                        #self.thesymbols.append(ticker)        
                if putorcall == 'P':
                    amt2 = self.Securities[self.put].Price * -1
                    if amt2 != 0:
                        amt = (self.Portfolio.MarginRemaining / 10000) / amt2
                        amt = int(amt)
                        if buyorsell == 'sell':
                            amt = amt * -1
                        if self.put.Value.split(' ')[0]  not in self.thesymbols and  self.put.Value.split(' ')[0] in self.symbols:
                            o = self.MarketOrder(self.put.Value, amt)
                            self.Debug(amt * amt2)
                            #o2 = self.LimitOrder(self.put.Value, -1 * amt, self.Securities[self.put].Price / (1.4))
                            #o3 = self.StopMarketOrder(self.put.Value, -1 * amt, self.Securities[self.put].Price * (1.2))
                            if (self.UtcTime.date()) not in list(self.tomorrow.keys()):
                                self.tomorrow[(self.UtcTime.date())] = []
                            self.tomorrow[(self.UtcTime.date())].append(self.put.Value.split(' ')[0])
                            self.thesymbols.append(self.put.Value.split(' ')[0])
                            self.symbols.remove(self.put.Value.split(' ')[0])
                            self.Debug(o)
                            #self.Debug(self.UtcTime)
                            #self.Debug("Call Strike Price : "+str(self.call.ID.StrikePrice))
                            #self.Debug("Put Strike Price (for reference): "+str(self.call.ID.StrikePrice))
                            #self.Debug("Security Price : "+str(self.Securities[self.call].Price))
                    else:
                        self.Debug(self.UtcTime)
                        self.Debug('no price to discover for ' + ticker)
                        #self.symbols.remove(ticker)
                        #self.thesymbols.append(ticker)
                #if len(call)>0:
                    # Some Logging 
                    #self.Debug("Call Strike Price : "+str(self.call.ID.StrikePrice))
                    #self.Debug("Put Strike Price (for reference): "+str(self.call.ID.StrikePrice))
                    #self.Debug("Security Price : "+str(self.Securities[self.call].Price))
                    
                    #self.Debug("IV : "+str(self.call.ImpliedVolatility))
                
            else:
                self.Debug('no good contracts for ' + ticker + ' skipping...')
                self.symbols.remove(ticker)
                self.thesymbols.append(ticker)

                
    def CoarseSelection(self, underlyingsymbol, symbol_list, min_strike_rank, max_strike_rank, min_expiry, max_expiry):
        ''' This method implements the coarse selection of option contracts
            according to the range of strike price and the expiration date,
            this function will help you better choose the options of different moneyness '''
        
        # filter 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]
        #if underlyingsymbol == 'SE' or underlyingsymbol == 'WYNN' or underlyingsymbol == 'GILD':
             #self.Debug("Ticker Und : " + str(underlyingsymbol))
             #self.Debug("Nb of contract found : " + str(len(contract_list)))
             #self.Debug("Underlying price : "+str(self.Securities[underlyingsymbol].Price))
        
        # find the strike price of ATM option
        # It seems like sometimes OptionChainProvider.GetOptionContractList is bugging and returns nothing, so let's try/except
    
        min_strike = float(self.items[underlyingsymbol]['Strikes'])
        max_strike = min_strike

        # filter the contracts based on the range of the strike price rank
        availstrikes = [i.ID.StrikePrice for i in contract_list]
        
        
        #self.Debug(str(min_strike))
        min_c = [i for i in contract_list if i.ID.StrikePrice >= min_strike]
        max_c = [i for i in contract_list if i.ID.StrikePrice <= max_strike]
        if len(min_c) == 0:
            self.Debug(self.UtcTime)
            self.Debug(min_strike)
            self.Debug(underlyingsymbol)
            self.Debug('min_c')
        if len(min_c) == 0:
            self.Debug(self.UtcTime)
            self.Debug(min_strike)
            self.Debug(underlyingsymbol)
            self.Debug('max_c')

        filtered_contracts = [i for i in contract_list if i.ID.StrikePrice >= min_strike and i.ID.StrikePrice <= max_strike]
        return filtered_contracts 
    
class StockDataSource(PythonData):
    
    def GetSource(self, config, date, isLiveMode):
        url = "https://www.dropbox.com/s/eh1v7arvvojee3d/test_replaced.csv?dl=1"
            
            
            
        #livemode:
        #https://docs.google.com/spreadsheets/d/1bLLZFPklkKDFRJ_lRvjVXYxKdDYDq5HVqeksYwKidGs/gviz/tq?tqx=out:csv&sheet={sheet1}
        #backtesting:   
        #"https://www.dropbox.com/s/eh1v7arvvojee3d/test_replaced.csv?dl=1"

        return SubscriptionDataSource(url, SubscriptionTransportMedium.RemoteFile)
    
    def Reader(self, config, line, date, isLiveMode):
        #if not (line.strip() and line[0].isdigit()): return None
        stocks = StockDataSource()
        stocks.Symbol = config.Symbol
        csv = line.split(',') # rstrip is essential because quantconnect throws an empty element error (extra commas at the end of the csv)
   
        stocks.Time = datetime.datetime.strptime(csv[0].replace('"','').replace('"',''), "%Y-%m-%d %H:%M:%S")
        stocks["Symbols"] = csv[3]
        stocks["BuyorSell"] = csv[1]
        stocks["PutorCall"] = csv[2]
        stocks["Expiries"] = csv[6]
        stocks["Strikes"] = csv[4]
        return stocks