Hello,
I'm trying to figure out how to backtest trading options near-after EPS reports.
the algo needs to get a list of symbols and dates (the day before the release of the earnings report), to buy ATM options at a specific date, hour and dollar amount and to sell them at the end of the next day (after the earnings report release).
with the help of Alexandre Catarino I got this far (code sample) but the program chooses only one symbol, buys it and then sells it at expiration date.
So how can I:
1) Trade muiltiple symbols from a list with diffrent buying and selling dates.
2) choose the dollar amount of any position.
3) choose the specific dates to sell every position.
import datetime
import matplotlib.pyplot as plt
import pandas as pd
from System import *
from QuantConnect import *
from QuantConnect.Algorithm import *
class BasicTemplateOptionsAlgorithm(QCAlgorithm):
def Initialize(self):
self.SetCash(100000)
def init_option(season_tickets, self):
for ind, row in season_tickets.iterrows():
option = self.AddOption(row[0], Resolution.Minute)
option.SetFilter(-3, 0, timedelta(7), timedelta(14))
self.SetBenchmark(row[0])
self.Schedule.On(
self.DateRules.On(int(row[6]),int(row[5]),int(row[4])),
self.TimeRules.At(10,00),
self.BuyCall)
self.option_symbol = option.Symbol
#download EPS csv file from google drive and creating dataframe
url = "https://www.dropbox.com/s/4vtx2nn6jzty7lc/CND%20EPS%20data.csv?dl=1"
file = self.Download(url).split("\n")
extract_data = [x.split(',') for x in file]
EPS_data = pd.DataFrame(extract_data)
EPS_data.columns = EPS_data.iloc[0]
EPS_data = EPS_data.drop(EPS_data.index[0])
EPS_data = EPS_data.drop(EPS_data.index[len(EPS_data)-1])
self.symbols = []
self.SetStartDate(2018, 4, 1)
self.SetEndDate(2018, 6, 30)
init_option(EPS_data, self)
def BuyCall(self):
if self.Portfolio.Invested: return
for kvp in self.CurrentSlice.OptionChains:
if kvp.Key != self.option_symbol: continue
chain = kvp.Value
# we sort the contracts to find at the money (ATM) contract with farthest expiration
contracts = sorted(sorted(sorted(chain, \
key = lambda x: abs(chain.Underlying.Price - x.Strike)), \
key = lambda x: x.Expiry, reverse=True), \
key = lambda x: x.Right)
# if found, trade it
if len(contracts) == 0: continue
symbol = contracts[0].Symbol
self.MarketOrder(symbol, 1)
#self.MarketOnCloseOrder(symbol, -1)
Alexandre Catarino
Hi Tal Shoham ,
I would suggest the implementation of a dictionary keyed by Option Symbol that would save the information from the dropbox file. I cannot access it to write an example, so here is some steps you can take.
class OptionData: def __init__(self, symbol): self.symbol self.dates = list() def add_eps(self, year, month, day): self.dates.append(datetime(year, month, day)
In Initialize:
self.optionData = dict() option = self.AddOption(row[0], Resolution.Minute) symbol = option.Symbol if symbol not in self.optionData: self.optionData[symbol] = OptionData(symbol) self.optionData[symbol].add_eps(row[6],row[5],row[4])
Then it should only add one schedule event for every day at 10
self.Schedule.On(self.DateRules.EveryDay(), self.TimeRules.At(10,00), self.BuyCall)
Finally, you will loop through self.optionData dictionary and place the order if the current algorithm date is found in OptionData.dates list.
Tal Shoham
Hi Alexandre Catarino,
Where should I put the class OptionData?
I tryied to put it befor the main class but I got syntax error.
Alexandre Catarino
Hi Tal Shoham ,
You can add it before or after the main class. There is a typo in line 7, a missing ")" that is causing the error.
Rahul Chowdhury
Hey Tal,
You can put the OptionData class before or after the BasicTemplateOptionsAlgorithm class. I updated your code with the modifications. However, since the dropbox link has expired, I replaced that section with a sample symbol.
Tal Shoham
The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.
To unlock posting to the community forums please complete at least 30% of Boot Camp.
You can continue your Boot Camp training progress from the terminal. We hope to see you in the community soon!