Overall Statistics
Total Trades
62
Average Win
0.83%
Average Loss
-0.23%
Compounding Annual Return
-68.230%
Drawdown
6.900%
Expectancy
-0.700
Net Profit
-5.399%
Sharpe Ratio
-5.042
Probabilistic Sharpe Ratio
0.130%
Loss Rate
94%
Win Rate
6%
Profit-Loss Ratio
3.65
Alpha
-0.765
Beta
0.107
Annual Standard Deviation
0.13
Annual Variance
0.017
Information Ratio
-6.913
Tracking Error
0.242
Treynor Ratio
-6.131
Total Fees
$128.75
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,11)
        self.SetEndDate(2020,5,28)
        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.csvRowsBySymbol = {}
        # 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:
            for item in data:
                if ' ' not in item['Symbols']:
                    list.append(item['Symbols'])
                    self.symbols.append(item['Symbols'])
                    self.csvRowsBySymbol[item['Symbols']] = item
        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)
        
        for symbol in data.Keys:
            if symbol.Value in self.symbols:
                # Add newly invested securities
                first_ticker = symbol.Value.split(' ')[0]
                if symbol in option_invested and first_ticker not in self.thesymbols:                                                                # False
                    self.symbols.remove(first_ticker)
                    self.thesymbols.append(first_ticker)
        
                if symbol.SecurityType == 1: #Selecting only stocks
                    invested = [option for option in option_invested if option.Underlying == symbol] # Get invested option for this underlying symbol   # Empty
        
                    if symbol.Value not in self.thesymbols and symbol.Value in self.symbols:                                                            # True
                        symsym = symbol.Value
                        if ' ' not in symsym:                                                                                                           # True
                            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):
        # 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.csvRowsBySymbol[ticker]['Expiries'] + '/2020', "%m/%d/%Y")
        exp = exp.date()
        
        today = self.UtcTime.date()
        future = exp
        diff = future - today
        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 len(filtered_contracts) == 0:
            self.symbols.remove(ticker)
            self.thesymbols.append(ticker)
            return
            
        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)
        
        buyorsell = self.csvRowsBySymbol[ticker]['BuyorSell']
        putorcall = self.csvRowsBySymbol[ticker]['PutorCall']
        
        if putorcall == 'C':
            
            amt2 = self.Securities[self.call].Price
            if amt2 == 0:
                return
            amt = (self.Portfolio.MarginRemaining / 10000) / amt2
            amt = int(amt)
            if amt == 0:
                return
            if buyorsell == 'sell':
                amt = amt * -1
            callSymbol = self.call.Value.split(' ')[0]
            if callSymbol  not in self.thesymbols and  callSymbol in self.symbols:
                o = self.MarketOrder(self.call.Value, amt)
                self.thesymbols.append(callSymbol)
                self.symbols.remove(callSymbol)
                if (self.UtcTime.date()) not in list(self.tomorrow.keys()):
                    self.tomorrow[(self.UtcTime.date())] = []
                self.tomorrow[(self.UtcTime.date())].append(callSymbol)

        if putorcall == 'P':
            
            amt2 = self.Securities[self.put].Price * -1
            if amt2 == 0:
                return
            amt = (self.Portfolio.MarginRemaining / 10000) / amt2
            amt = int(amt)
            if amt == 0:
                return
            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)
                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])

                
    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]

        # 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.csvRowsBySymbol[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.Log(f"Requested strike available for {underlyingsymbol}: {str(min_strike in availstrikes)}")

        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"
        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