1. Home
2. Article Catalog
3. Historical Implied Volatility and Greeks of Index Options 'At The Money' On Update and in the Past using Python Type Hints

Historical Implied Volatility and Greeks of Index Options 'At The Money' On Update and in the Past using Python Type Hints

Authors:
Jonathan Legrand
In the article below, we will (i) automatically find the Option (of choice) closest to At The Money (ATM) and (ii) calculate its Implied Volatility. We focus below on Future (Monthly) Options on the Index .STOXX50E (EURO STOXX 50 EUR PRICE INDEX) ('EUREX') and .SPX (S&P 500 INDEX), although you can apply the logic below for another index. To find the ATM instrument, we simply and efficiently use the Search API. Usually, the calculation of the Black-Scholes-Merton model's Implied Volatility involves numerical techniques, since it is not a closed equation (unless restricting assumptions that log returns follow a standard normal distribution with mean is zero, $\mu$ = 0, and standard deviation is zero, $\sigma$ = 1, are made). If we used these techniques in calculating each Implied Volatility value on our computer, it would take several seconds - if not minutes - for each data point computed. I have chosen to use the Instrument Pricing Analytics (IPA) service in the Refinitiv Data Platform API Family instead, as this service allows me to send model specifications (and variables) and receive several (up to 100) computed Implied Volatility values in one go - in a few seconds. Not only does this save a great deal of time, but also many lines of code!
    	
import refinitiv.data as rdÂ  # This is LSEG's Data and Analytics' API wrapper, called the Refinitiv Data Library for Python.
from refinitiv.data.content import historical_pricingÂ  # We will use this Python Class in rd to show the Implied Volatility data already available before our work.
from refinitiv.data.content import searchÂ  # We will use this Python Class in rd to fid the instrument we are after, closest to At The Money.
Â
import numpy as npÂ  # We need numpy for mathematical and array manipilations.
import pandas as pdÂ  # We need pandas for datafame and array manipilations.
import calendarÂ  # We use calendar to identify holidays and maturity dates of intruments of interest.
import pytzÂ  # We use pytz to manipulate time values aiding calendar library.
import pandas_market_calendars as mcalÂ  # Used to identify holidays. See https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb for info on this market calendar library
from datetime import datetime, timedelta, timezoneÂ  # We use these to manipulate time values
from dateutil.relativedelta import relativedeltaÂ  # We use relativedelta to manipulate time values aiding calendar library.
Â
# plotly is a library used to render interactive graphs:
from plotly.subplots import make_subplots
import plotly.graph_objects as go
import plotly.express as pxÂ  # This is just to see the implied vol graph when that field is available
import matplotlib.pyplot as pltÂ  # We use matplotlib to just in case users do not have an environment suited to plotly.
from IPython.display import clear_outputÂ  # We use clear_output for users who wish to loop graph production on a regular basis.
Â
# Let's authenticate ourseves to LSEG's Data and Analytics service, Refinitiv:
try:Â  # The following libraries are not available in Codebook, thus this try loop
Â  Â  rd.open_session(config_name="C:\\Example.DataLibrary.Python-main\\Example.DataLibrary.Python-main\\Configuration\\refinitiv-data.config.json")
Â  Â  rd.open_session("desktop.workspace")
except:
Â  Â  rd.open_session()




    	
print(f"Here we are using the refinitiv Data Library version {rd.__version__}")



Here we are using the refinitiv Data Library version 1.0.0b24


## EUREX Call OptionsÂ¶

In this article, we will attempt to calculate the Implied Volatility (IV) for Future Options on 2 indexes (.STOXX50E & .SPX) trading 'ATM', meaning that the contract's strike price is at (or near - within x%) parity with (equal to) its current treading price (TRDPRC_1). We are also only looking for such Options expiring within a set time window; allowing for the option 'forever', i.e.: that expire whenever after date of calculation. To do so, we 1st have to find the option in question. To find live Options, we best use the Search API. To find Expired Options we will use functions created in Haykaz's amazing articles "Finding Expired Options and Backtesting a Short Iron Condor Strategy" & "Functions to find Option RICs traded on different exchanges"

### Finding Live Options (using Search API)Â¶

Live Options, in this context, are Options that have not expired at time of computation. To be explicit:

• 'time of calculation' refers here to the time for which the calculation is done, i.e.: if we compute today an IV for an Option as if it was 3 days ago, 'time of calculation' is 3 days ago.
• 'time of computation' refers here to the time when we are computing the values, i.e.: if we compute today an IV for an Option as if it was 3 days ago, 'time of computation' is today.

As aforementioned, to find live Options, we best use the Search API: Here we look for options on .STOXX50E that mature on the 3rd friday of July 2023, 2023-07-21:

    	
response1 = search.Definition(
Â  Â  view = search.Views.SEARCH_ALL, # To see what views are available: help(search.Views) & search.metadata.Definition(view = search.Views.SEARCH_ALL).get_data().data.df.to_excel("SEARCH_ALL.xlsx")
Â  Â  query=".STOXX50E",
Â  Â  select="DocumentTitle, RIC, StrikePrice, ExchangeCode, ExpiryDate, UnderlyingAsset, " +
Â  Â  Â  Â  Â  Â  "UnderlyingAssetName, UnderlyingAssetRIC, ESMAUnderlyingIndexCode, RCSUnderlyingMarket" +
Â  Â  Â  Â  Â  Â  "UnderlyingQuoteName, UnderlyingQuoteRIC",
Â  Â  filter="RCSAssetCategoryLeaf eq 'Option' and RIC eq 'STX*' and DocumentTitle ne '*Weekly*'Â  " +
Â  Â  "and CallPutOption eq 'Call' and ExchangeCode eq 'EUX' and " +
Â  Â  "ExpiryDate ge 2022-07-10 and ExpiryDate lt 2023-07-22",Â  # ge (greater than or equal to), gt (greater than), lt (less than) and le (less than or equal to). These can only be applied to numeric and date properties.
Â  Â  top=100,
).get_data()
searchDf1 = response1.data.df




    	
searchDf1




Let's say the current underlying price is 3331.7EUR, now we can pick the option with strike price closest to that, i.e.: the most 'At The Money'; note that this means that the option can be in or out the money, as long as it is the closest to at the money:

    	
currentUnderlyingPrc =Â  rd.get_history(
Â  Â  universe=[searchDf1.UnderlyingQuoteRIC[0][0]],
Â  Â  fields=["TRDPRC_1"],
Â  Â  interval="tick").iloc[-1][0]




    	
currentUnderlyingPrc



4195.55

    	
searchDf1.iloc[(searchDf1['StrikePrice']-currentUnderlyingPrc).abs().argsort()[:1]]




In this instance, for this Call Option, 'STXE33500G3.EX', the strike price is 3350, higher than the spot price of our underlying which is 3331.7. The holder of this 'STXE33500G3.EX' option has the right (but not the obligation) to buy the underlying for 3350EUR, which, was the price of the underlying to stay the same till expiry (3331.7EUR on 2023-07-21), means a loss of (3350 - 3331.7 =) 18.3EUR. This option in this instance is 'Out-The-Money'.

N.B.: When using the Filter in Search and playing with dates, it is good to read the API Playground Documentation; it mentions that: "Dates are written in ISO datetime format. The time portion is optional, as is the timezone (assumed to be UTC unless otherwise specified). Valid examples include 2012-03-11T17:13:55Z, 2012-03-11T17:13:55, 2012-03-11T12:00-03:30, 2012-03-11.":

#### Function for Expiration daysÂ¶

Most of the time, market agents will be interested in the next expiring Option, unless we are too close to it. We would not be interested, for example, in an option expiring in 1 hour, or even tomorrow, because that is so close (in time) that the information reflected in the Option's trades in the market does not represent future expectations of its underlying, but current expectations of it.

To implement such a logic, we need to know what are the expiry dates of the option that we are interested in. We are looking for a Python function narrowing our search to options expiring on the 3rd Friday of any one month. For info on this function, please read articles "Finding Expired Options and Backtesting a Short Iron Condor Strategy" & "Functions to find Option RICs traded on different exchanges"

    	
def Get_exp_dates(year, days=True, mcal_get_calendar='EUREX'):
Â  Â  '''
Â  Â  Get_exp_dates Version 2.0:
Â
Â  Â  This function gets expiration dates for a year for NDX options, which are the 3rd Fridays of each month.
Â
Â  Â  Changes
Â  Â  ----------------------------------------------
Â  Â  Changed from Version 1.0 to 2.0: Jonathan Legrand changed Haykaz Aramyan's original code to allow
Â  Â  Â  Â  (i) for the function's holiday argument to be changed, and defaulted to 'EUREX' as opposed to 'CBOE_Index_Options' and
Â  Â  Â  Â  (ii) for the function to output full date objects as opposed to just days of the month if agument days=True.
Â
Â  Â  Dependencies
Â  Â  ----------------------------------------------
Â  Â  Python library 'pandas_market_calendars' version 3.2
Â
Â  Â  Parameters
Â  Â  -----------------------------------------------
Â  Â  Input:
Â  Â  Â  Â  year(int): year for which expiration days are requested
Â
Â  Â  Â  Â  mcal_get_calendar(str): String of the calendar for which holidays have to be taken into account. More on this calendar (link to Github chacked 2022-10-11): https://github.com/rsheftel/pandas_market_calendars/blob/177e7922c7df5ad249b0d066b5c9e730a3ee8596/pandas_market_calendars/exchange_calendar_cboe.py
Â  Â  Â  Â  Â  Â  Default: mcal_get_calendar='EUREX'
Â
Â  Â  Â  Â  days(bool): If True, only days of the month is outputed, else it's dataeime objects
Â  Â  Â  Â  Â  Â  Default: days=True
Â
Â  Â  Output:
Â  Â  Â  Â  dates(dict): dictionary of expiration days for each month of a specified year in datetime.date format.
Â  Â  '''
Â
Â  Â  # get CBOE market holidays
Â  Â  EUREXCal = mcal.get_calendar(mcal_get_calendar)
Â  Â  holidays = EUREXCal.holidays().holidays
Â
Â  Â  # set calendar starting from Saturday
Â  Â  c = calendar.Calendar(firstweekday=calendar.SATURDAY)
Â
Â  Â  # get the 3rd Friday of each month
Â  Â  exp_dates = {}
Â  Â  for i in range(1, 13):
Â  Â  Â  Â  monthcal = c.monthdatescalendar(year, i)
Â  Â  Â  Â  date = monthcal[2][-1]
Â  Â  Â  Â  # check if found date is an holiday and get the previous date if it is
Â  Â  Â  Â  if date in holidays:
Â  Â  Â  Â  Â  Â  date = date + timedelta(-1)
Â  Â  Â  Â  # append the date to the dictionary
Â  Â  Â  Â  if year in exp_dates:
Â  Â  Â  Â  Â  Â  ### Changed from original code from here on by Jonathan Legrand on 2022-10-11
Â  Â  Â  Â  Â  Â  if days: exp_dates[year].append(date.day)
Â  Â  Â  Â  Â  Â  else: exp_dates[year].append(date)
Â  Â  Â  Â  else:
Â  Â  Â  Â  Â  Â  if days: exp_dates[year] = [date.day]
Â  Â  Â  Â  Â  Â  else: exp_dates[year] = [date]
Â  Â  return exp_dates




    	
fullDates = Get_exp_dates(2022, days=False)
dates = Get_exp_dates(2022)
fullDatesStrDict = {i: [fullDates[i][j].strftime('%Y-%m-%d')
Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  for j in range(len(fullDates[i]))]
Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  for i in list(fullDates.keys())}
fullDatesDayDict = {i: [fullDates[i][j].day
Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  for j in range(len(fullDates[i]))]
Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  for i in list(fullDates.keys())}




    	
print(fullDates)



{2022: [datetime.date(2022, 1, 21), datetime.date(2022, 2, 18), datetime.date(2022, 3, 18), datetime.date(2022, 4, 14), datetime.date(2022, 5, 20), datetime.date(2022, 6, 17), datetime.date(2022, 7, 15), datetime.date(2022, 8, 19), datetime.date(2022, 9, 16), datetime.date(2022, 10, 21), datetime.date(2022, 11, 18), datetime.date(2022, 12, 16)]}

    	
print(fullDatesStrDict)



{2022: ['2022-01-21', '2022-02-18', '2022-03-18', '2022-04-14', '2022-05-20', '2022-06-17', '2022-07-15', '2022-08-19', '2022-09-16', '2022-10-21', '2022-11-18', '2022-12-16']}

    	
print(dates)



{2022: [21, 18, 18, 14, 20, 17, 15, 19, 16, 21, 18, 16]}

    	
print(fullDatesDayDict)



{2022: [21, 18, 18, 14, 20, 17, 15, 19, 16, 21, 18, 16]}


#### Function to find the next expiring Option outside the next x day windowÂ¶

Most of the time, market agents will be interested in the next expiring Option, unless we are too close to it. We would not be interested, for example, in an option expiring in 1 hour, or even tomorrow, because that is so close (in time) that the information reflected in the Option's trades in the market does not represent future expectations of its underlying, but current expectations of it.

E.g.: I would like to know what is the next Future (Monthly) Option (i) on the Index '.STOXX50E' (ii) closest to ATM (i.e.: with an underlying spot price closest to the option's strike price) (ii) Expiring in more than x days (i.e.: not too close to calculated time 't'), let's say 15 days:

    	
x = 15



    	
timeOfCalcDatetime = datetime.now()  # For now, we will focuss on the use-case where we are calculating values for today; later we will allow for it historically for any day going back a few business days.
timeOfCalcStr = datetime.now().strftime('%Y-%m-%d')
timeOfCalcStr



'2023-01-18'

    	
fullDatesAtTimeOfCalc = Get_exp_dates(timeOfCalcDatetime.year, days=False)Â  # timeOfCalcDatetime.year here is 2023
fullDatesAtTimeOfCalcDatetime = [
Â  Â  datetime(i.year, i.month, i.day)
Â  Â  for i in fullDatesAtTimeOfCalc[list(fullDatesAtTimeOfCalc.keys())[0]]]




    	
print(fullDatesAtTimeOfCalcDatetime)



[datetime.datetime(2023, 1, 20, 0, 0), datetime.datetime(2023, 2, 17, 0, 0), datetime.datetime(2023, 3, 17, 0, 0), datetime.datetime(2023, 4, 21, 0, 0), datetime.datetime(2023, 5, 19, 0, 0), datetime.datetime(2023, 6, 16, 0, 0), datetime.datetime(2023, 7, 21, 0, 0), datetime.datetime(2023, 8, 18, 0, 0), datetime.datetime(2023, 9, 15, 0, 0), datetime.datetime(2023, 10, 20, 0, 0), datetime.datetime(2023, 11, 17, 0, 0), datetime.datetime(2023, 12, 15, 0, 0)]

    	
expiryDateOfInt = [i for i in fullDatesAtTimeOfCalcDatetime
Â  Â  Â  Â  Â  Â  Â  Â  Â  Â if i > timeOfCalcDatetime + relativedelta(days=x)][0]
expiryDateOfInt




datetime.datetime(2023, 2, 17, 0, 0)


Now we can look for the one option we're after:

    	
response2 = search.Definition(
Â  Â  view=search.Views.SEARCH_ALL, # To see what views are available: help(search.Views) & search.metadata.Definition(view = search.Views.SEARCH_ALL).get_data().data.df.to_excel("SEARCH_ALL.xlsx")
Â  Â  query=".STOXX50E",
Â  Â  select="DocumentTitle, RIC, StrikePrice, ExchangeCode, ExpiryDate, UnderlyingAsset, " +
Â  Â  Â  Â  Â  Â  "UnderlyingAssetName, UnderlyingAssetRIC, ESMAUnderlyingIndexCode, RCSUnderlyingMarket" +
Â  Â  Â  Â  Â  Â  "UnderlyingQuoteName, UnderlyingQuoteRIC",
Â  Â  filter="RCSAssetCategoryLeaf eq 'Option' and RIC eq 'STX*' and DocumentTitle ne '*Weekly*' " +
Â  Â  "and CallPutOption eq 'Call' and ExchangeCode eq 'EUX' and " +
Â  Â  f"ExpiryDate ge {(expiryDateOfInt - relativedelta(days=1)).strftime('%Y-%m-%d')} " +
Â  Â  f"and ExpiryDate lt {(expiryDateOfInt + relativedelta(days=1)).strftime('%Y-%m-%d')}",Â  # ge (greater than or equal to), gt (greater than), lt (less than) and le (less than or equal to). These can only be applied to numeric and date properties.
Â  Â  top=10000,
).get_data()
searchDf2 = response2.data.df




    	
searchDf2



 DocumentTitle RIC StrikePrice ExchangeCode ExpiryDate UnderlyingQuoteRIC 0 Eurex Dow Jones EURO STOXX 50 Index Option 400... STXE40000B3.EX 4000 EUX 17/02/2023 [.STOXX50E] 1 Eurex Dow Jones EURO STOXX 50 Index Option 390... STXE39000B3.EX 3900 EUX 17/02/2023 [.STOXX50E] 2 Eurex Dow Jones EURO STOXX 50 Index Option 380... STXE38000B3.EX 3800 EUX 17/02/2023 [.STOXX50E] 3 Eurex Dow Jones EURO STOXX 50 Index Option 395... STXE39500B3.EX 3950 EUX 17/02/2023 [.STOXX50E] 4 Eurex Dow Jones EURO STOXX 50 Index Option 385... STXE38500B3.EX 3850 EUX 17/02/2023 [.STOXX50E] ... ... ... ... ... ... ... 145 Eurex Dow Jones EURO STOXX 50 Index Option 502... STXE50250B3.EX 5025 EUX 17/02/2023 [.STOXX50E] 146 Eurex Dow Jones EURO STOXX 50 Index Option 507... STXE50750B3.EX 5075 EUX 17/02/2023 [.STOXX50E] 147 Eurex Dow Jones EURO STOXX 50 Index Option 505... STXE50500B3.EX 5050 EUX 17/02/2023 [.STOXX50E] 148 Eurex Dow Jones EURO STOXX 50 Index Option 512... STXE51250B3.EX 5125 EUX 17/02/2023 [.STOXX50E] 149 Eurex Dow Jones EURO STOXX 50 Index Option 517... STXE51750B3.EX 5175 EUX 17/02/2023 [.STOXX50E]

And again, we can collect the closest to ATM:

    	
searchDf2.iloc[(searchDf2['StrikePrice']-currentUnderlyingPrc).abs().argsort()[:1]]



 DocumentTitle RIC StrikePrice ExchangeCode ExpiryDate UnderlyingQuoteRIC 19 Eurex Dow Jones EURO STOXX 50 Index Option 420... STXE42000B3.EX 4200 EUX 17/02/2023 [.STOXX50E]

Now we have our instrument:

    	
instrument = searchDf2.iloc[(searchDf2['StrikePrice']-currentUnderlyingPrc).abs().argsort()[:1]].RIC.values[0]
instrument




'STXE42000B3.EX'


## Refinitiv-provided Daily Implied VolatilityÂ¶

Refinitiv provides pre-calculated Implied Volatility values, but they are daily, and we will look into calculating them in higher frequencies:

    	
datetime.now().isoformat(timespec='minutes')



'2023-01-18T15:12'

    	
start = (timeOfCalcDatetime - pd.tseries.offsets.BDay(5)).strftime('%Y-%m-%dT%H:%M:%S.%f')Â  # '2022-10-05T07:30:00.000'
endDateTime = datetime.now()
end = endDateTime.strftime('%Y-%m-%dT%H:%M:%S.%f')Â  #Â  e.g.: '2022-09-09T20:00:00.000'
end




'2023-01-18T15:12:02.823222'

    	
_RefDailyImpVolDf = historical_pricing.events.Definition(
Â  Â  instrument, fields=['IMP_VOLT'], count=2000).get_data()




    	



 STXE42000B3.EX IMP_VOLT Timestamp 54:57.5 20.3118 55:09.8 20.0319 55:10.4 19.7213 55:10.5 19.9746 55:12.7 20.2399
    	
try: RefDailyImpVolDf = _RefDailyImpVolDf.data.df.drop(['EVENT_TYPE'], axis=1)Â  # In codebook, this line is needed
except: RefDailyImpVolDf = _RefDailyImpVolDf.data.df # If outside of codebook
fig = px.line(RefDailyImpVolDf, title = RefDailyImpVolDf.columns.name + " " + RefDailyImpVolDf.columns[0]) # This is just to see the implied vol graph when that field is available
fig.show()





# Option Price

    	
_optnMrktPrice = rd.get_history(
Â  Â  universe=[instrument],
Â  Â  fields=["TRDPRC_1"],
Â  Â  interval="10min",
Â  Â  start=start,Â  # Ought to always start at 4 am for OPRA exchanged Options, more info in the article below
Â  Â  end=end)Â  # Ought to always end at 8 pm for OPRA exchanged Options, more info in the article below





As you can see, there isn't nessesarily a trade every 10 min.:

    	



 STXE42000B3.EX TRDPRC_1 Timestamp 11/01/2023 15:30 47 11/01/2023 15:40 45.5 11/01/2023 15:50 41.8 11/01/2023 16:20 42.9 12/01/2023 08:00 49

However, for the statistical inferences that we will make further in the article, when we will calculate Implied Volatilities and therefore implement the Black Scholes model, we will need 'continuous timeseries' with which to deal. There are several ways to go from discrete time series (like ours, even if we go down to tick data), but for this article, we will 1st focus on making 'buckets' of 10 min. If no trade is made in any 10 min. bucket, we will assume the price to have stayed the same as previously, throughout the exchange's trading hours which are:

thankfully this is simple. Let's stick with the EUREX for now:

    	
optnMrktPrice = _optnMrktPrice.resample('10Min').mean() # get a datapoint every 10 min
optnMrktPrice = optnMrktPrice[optnMrktPrice.index.strftime('%Y-%m-%d').isin([i for i in _optnMrktPrice.index.strftime('%Y-%m-%d').unique()])]Â  # Only keep trading days
optnMrktPrice = optnMrktPrice.loc[(optnMrktPrice.index.strftime('%H:%M:%S') >= '07:30:00') & (optnMrktPrice.index.strftime('%H:%M:%S') <= '22:00:00')]Â  # Only keep trading hours
optnMrktPrice.fillna(method='ffill', inplace=True)Â  # Forward Fill to populate NaN values
print(f"Our dataframe started at {str(optnMrktPrice.index[0])} and went on continuously till {str(optnMrktPrice.index[-1])}, so out of trading hours rows are removed")
optnMrktPrice




Our dataframe started at 2023-01-11 15:30:00 and went on continuously till 2023-01-18 14:00:00, so out of trading hours rows are removed

 STXE42000B3.EX TRDPRC_1 Timestamp 11/01/2023 15:30 47 11/01/2023 15:40 45.5 11/01/2023 15:50 41.8 11/01/2023 16:00 41.8 11/01/2023 16:10 41.8 ... ... 18/01/2023 13:20 66.1 18/01/2023 13:30 67.7 18/01/2023 13:40 67.7 18/01/2023 13:50 67.7 18/01/2023 14:00 67.6

Note also that one may want to only look at 'At Option Trade' datapoints, i.e.: Implied Volatility when a trade is made for the Option, but not when none is made. For this, we will use the 'At Trade' (AT) dataframes:

    	
AToptnMrktPrice = _optnMrktPrice
AToptnMrktPrice




 STXE42250C3.EX TRDPRC_1 Timestamp 27/01/2023 13:40 64.7 27/01/2023 13:50 63 ... ... 03/02/2023 10:40 86.9 03/02/2023 12:10 88.1

## Underlying Asset Price

Now let's get data for the underying, which we need to calculate IV:

    	
underlying = searchDf2.iloc[(searchDf2['StrikePrice']-currentUnderlyingPrc).abs().argsort()[:1]].UnderlyingQuoteRIC.values[0][0]
underlying




'.STOXX50E'


If you are interested in the opening times of any one exchange, you can use the following:

    	
hoursDf = rd.get_data(universe=["EUREX21"],
Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  fields=["ROW80_10"])
display(hoursDf)
hoursDf.iloc[0,1]




 Instrument ROW80_10 EUREX21 OGBL/OGBM/OGBS 07:30-08:00 08:0...
'       OGBL/OGBM/OGBS     07:30-08:00     08:00-19:00     19:00-20:00           '

    	
_underlyingMrktPrice = rd.get_history(
Â  Â  universe=[underlying],
Â  Â  fields=["TRDPRC_1"],
Â  Â  interval="10min",
Â  Â  start=start,
Â  Â  end=end)
_underlyingMrktPrice




 .STOXX50E TRDPRC_1 Timestamp 27/01/2023 13:30 4165.59 27/01/2023 13:40 4162.12 ... ... 03/02/2023 12:10 4225.29 03/02/2023 12:20 4224.7
    	
ATunderlyingMrktPrice = AToptnMrktPrice.join(
Â  Â  _underlyingMrktPrice, lsuffix='_OptPr', rsuffix='_UnderlyingPr', how='inner')
ATunderlyingMrktPrice




 TRDPRC_1_OptPr TRDPRC_1_UnderlyingPr Timestamp 27/01/2023 13:40 64.7 4162.12 27/01/2023 13:50 63 4156.5 â€¦ â€¦ â€¦ 03/02/2023 10:40 86.9 4223.69 03/02/2023 12:10 88.1 4225.29

Let's put it all in one data-frame, df. Some datasets will have data going from the time we sort for start all the way to end. Some won't because no trade happened in the past few minutes/hours. We ought to base ourselves on the dataset with values getting closer to end and ffill for the other column. As a result, the following if loop is needed:

    	
if optnMrktPrice.index[-1] >= _underlyingMrktPrice.index[-1]:
Â  Â  df = optnMrktPrice.copy()
Â  Â  df['underlying ' + underlying + ' TRDPRC_1'] = _underlyingMrktPrice
else:
Â  Â  df = _underlyingMrktPrice.copy()
Â  Â  df.rename(columns={"TRDPRC_1": 'underlying ' + underlying + ' TRDPRC_1'}, inplace=True)
Â  Â  df['TRDPRC_1'] = optnMrktPrice
Â  Â  df.columns.name = optnMrktPrice.columns.name
df.fillna(method='ffill', inplace=True)Â  # Forward Fill to populate NaN values
df = df.dropna()
df





## Strike Price

    	
strikePrice = searchDf2.iloc[
Â  Â  (searchDf2['StrikePrice']-currentUnderlyingPrc).abs().argsort()[:1]].StrikePrice.values[0]
strikePrice




4225


## Risk-Free Interest Rate

    	
_EurRfRate = rd.get_history(
Â  Â  universe=['EURIBOR3MD='],Â  # USD3MFSR=, USDSOFR=
Â  Â  fields=['TR.FIXINGVALUE'],
Â  Â  # Since we will use dropna() as a way to select the rows we are after later on in the code, we need to ask for more risk-free data than needed, just in case we don't have enough:
Â  Â  start=(datetime.strptime(start, '%Y-%m-%dT%H:%M:%S.%f') - timedelta(days=1)).strftime('%Y-%m-%d'),
Â  Â  end=(datetime.strptime(end, '%Y-%m-%dT%H:%M:%S.%f') + timedelta(days=1)).strftime('%Y-%m-%d'))
Â
_EurRfRate




 EURIBOR3MD= Fixing Value Date 03/02/2023 2.545 02/02/2023 2.54 01/02/2023 2.483 31/01/2023 2.512 30/01/2023 2.482 27/01/2023 2.492 26/01/2023 2.468

Euribor values are released daily at 11am CET, and it is published as such on Refinitiv:

    	
EurRfRate = _EurRfRate.resample('10Min').mean().fillna(method='ffill')
df['EurRfRate'] = EurRfRate





You might be running your code after the latest Risk Free Rate published, so the most accurate such value after taht would be the latest value, thus the use of ffill:

    	
df = df.fillna(method='ffill')
df




 STXE42250C3.EX underlying .STOXX50E TRDPRC_1 TRDPRC_1 EurRfRate Timestamp 27/01/2023 13:40 4162.12 64.7 2.492 27/01/2023 13:50 4156.5 63 2.492 ... ... ... ... 03/02/2023 12:10 4225.29 88.1 2.54 03/02/2023 12:20 4224.7 88.1 2.54

Now for the At Trade dataframe:

    	
pd.options.mode.chained_assignment = NoneÂ  # default='warn'
ATunderlyingMrktPrice['EurRfRate'] = [pd.NA for i in ATunderlyingMrktPrice.index]
for i in _EurRfRate.index:
Â  Â  _i = str(i)[:10]
Â  Â  for n, j in enumerate(ATunderlyingMrktPrice.index):
Â  Â  Â  Â  if _i in str(j):
Â  Â  Â  Â  Â  Â  if len(_EurRfRate.loc[i].values) == 2:
Â  Â  Â  Â  Â  Â  Â  Â  ATunderlyingMrktPrice['EurRfRate'].iloc[n] = _EurRfRate.loc[i].values[0][0]
Â  Â  Â  Â  Â  Â  elif len(_EurRfRate.loc[i].values) == 1:
Â  Â  Â  Â  Â  Â  Â  Â  ATunderlyingMrktPrice['EurRfRate'].iloc[n] = _EurRfRate.loc[i].values[0]
ATdf = ATunderlyingMrktPrice.copy()





Again, you might be running your code after the latest Risk Free Rate published, so the most accurate such value after that would be the latest value, thus the use of ffill:

    	
ATdf = ATdf.fillna(method='ffill')
ATdf




 TRDPRC_1_OptPr TRDPRC_1_UnderlyingPr EurRfRate Timestamp 27/01/2023 13:40 64.7 4162.12 2.492 27/01/2023 13:50 63 4156.5 2.492 â€¦ â€¦ â€¦ â€¦ 03/02/2023 10:40 86.9 4223.69 2.545 03/02/2023 12:10 88.1 4225.29 2.545

## Annualized Continuous Dividend Rate

We are going to assume no dividends.

## Calculating IV

On the Developer Portal, one can see documentation about the Instrument Pricing Analytics service that allows access to calculating functions (that use to be called 'AdFin'). This service is accessible via several RESTful endpoints (in a family of endpoints called 'Quantitative Analytics') which can be used via RD.

Data returned this far was time-stamped in the GMT Time Zone, we need to re-calibrate it to the timezone of our machine

    	
dfGMT = df.copy()
dfLocalTimeZone = df.copy()
dfLocalTimeZone.index = [
Â  Â  df.index[i].replace(
Â  Â  Â  Â  tzinfo=pytz.timezone(
Â  Â  Â  Â  Â  Â  'GMT')).astimezone(
Â  Â  Â  Â  tz=datetime.now().astimezone().tzinfo)
Â  Â  for i in range(len(df))]
dfGMT




 STXE42250C3.EX underlying .STOXX50E TRDPRC_1 TRDPRC_1 EurRfRate Timestamp 27/01/2023 13:40 4162.12 64.7 2.492 27/01/2023 13:50 4156.5 63 2.492 27/01/2023 14:00 4160.8 63.2 2.492 ... ... ... ... 03/02/2023 12:00 4224.96 86.9 2.54 03/02/2023 12:10 4225.29 88.1 2.54 03/02/2023 12:20 4224.7 88.1 2.54
    	
dfLocalTimeZone



 STXE42250C3.EX underlying .STOXX50E TRDPRC_1 TRDPRC_1 EurRfRate 2023-01-27 14:40:00+01:00 4162.12 64.7 2.492 2023-01-27 14:50:00+01:00 4156.5 63 2.492 2023-01-27 15:00:00+01:00 4160.8 63.2 2.492 ... ... ... ... 2023-02-03 13:00:00+01:00 4224.96 86.9 2.54 2023-02-03 13:10:00+01:00 4225.29 88.1 2.54 2023-02-03 13:20:00+01:00 4224.7 88.1 2.54

Now for the At Trade dataframe:

    	
ATdfGMT = ATdf.copy()
ATdfLocalTimeZone = ATdf.copy()
ATdfLocalTimeZone.index = [
Â  Â  ATdf.index[i].replace(
Â  Â  Â  Â  tzinfo=pytz.timezone(
Â  Â  Â  Â  Â  Â  'GMT')).astimezone(
Â  Â  Â  Â  tz=datetime.now().astimezone().tzinfo)
Â  Â  for i in range(len(ATdf))]
ATdfGMT




 TRDPRC_1_OptPr TRDPRC_1_UnderlyingPr EurRfRate Timestamp 27/01/2023 13:40 64.7 4162.12 2.492 27/01/2023 13:50 63 4156.5 2.492 â€¦ â€¦ â€¦ â€¦ 03/02/2023 10:40 86.9 4223.69 2.545 03/02/2023 12:10 88.1 4225.29 2.545
    	
ATdfLocalTimeZone



 TRDPRC_1_OptPr TRDPRC_1_UnderlyingPr EurRfRate 2023-01-27 14:40:00+01:00 64.7 4162.12 2.492 2023-01-27 14:50:00+01:00 63 4156.5 2.492 â€¦ â€¦ â€¦ â€¦ 2023-02-03 11:40:00+01:00 86.9 4223.69 2.545 2023-02-03 13:10:00+01:00 88.1 4225.29 2.545
    	
universeL = [
Â  Â  Â  Â  {
Â  Â  Â  Â  Â  "instrumentType": "Option",
Â  Â  Â  Â  Â  "instrumentDefinition": {
Â  Â  Â  Â  Â  Â  "underlyingType": "Eti",
Â  Â  Â  Â  Â  Â  "instrumentCode": instrument,
Â  Â  Â  Â  Â  Â  "strike": str(strikePrice),
Â  Â  Â  Â  Â  },
Â  Â  Â  Â  Â  "pricingParameters": {
Â  Â  Â  Â  Â  Â  "marketValueInDealCcy": str(dfLocalTimeZone['TRDPRC_1'][i]),
Â  Â  Â  Â  Â  Â  "riskFreeRatePercent": str(dfLocalTimeZone['EurRfRate'][i]),
Â  Â  Â  Â  Â  Â  "underlyingPrice": str(dfLocalTimeZone['underlying ' + underlying + ' TRDPRC_1'][i]),
Â  Â  Â  Â  Â  Â  "pricingModelType": "BlackScholes",
Â  Â  Â  Â  Â  Â  "dividendType": "ImpliedYield",
Â  Â  Â  Â  Â  Â  "volatilityType": "Implied",
Â  Â  Â  Â  Â  Â  "underlyingTimeStamp": "Default",
Â  Â  Â  Â  Â  Â  "reportCcy": "EUR"
Â  Â  Â  Â  Â  }
Â  Â  Â  Â  }
Â  Â  Â  for i in range(len(dfLocalTimeZone.index))]




    	
ATuniverseL = [
Â  Â  Â  Â  {
Â  Â  Â  Â  Â  "instrumentType": "Option",
Â  Â  Â  Â  Â  "instrumentDefinition": {
Â  Â  Â  Â  Â  Â  "underlyingType": "Eti",
Â  Â  Â  Â  Â  Â  "instrumentCode": instrument,
Â  Â  Â  Â  Â  Â  "strike": str(strikePrice),
Â  Â  Â  Â  Â  },
Â  Â  Â  Â  Â  "pricingParameters": {
Â  Â  Â  Â  Â  Â  "marketValueInDealCcy": str(ATdfLocalTimeZone['TRDPRC_1_OptPr'][i]),
Â  Â  Â  Â  Â  Â  "riskFreeRatePercent": str(ATdfLocalTimeZone['EurRfRate'][i]),
Â  Â  Â  Â  Â  Â  "underlyingPrice": str(ATdfLocalTimeZone['TRDPRC_1_UnderlyingPr'][i]),
Â  Â  Â  Â  Â  Â  "pricingModelType": "BlackScholes",
Â  Â  Â  Â  Â  Â  "dividendType": "ImpliedYield",
Â  Â  Â  Â  Â  Â  "volatilityType": "Implied",
Â  Â  Â  Â  Â  Â  "underlyingTimeStamp": "Default",
Â  Â  Â  Â  Â  Â  "reportCcy": "EUR"
Â  Â  Â  Â  Â  }
Â  Â  Â  Â  }
Â  Â  Â  for i in range(len(ATdfLocalTimeZone.index))]




    	
def Chunks(lst, n):
Â  Â  """Yield successive n-sized chunks from lst."""
Â  Â  for i in range(0, len(lst), n):
Â  Â  Â  Â  yield lst[i:i + n]




    	
requestFields = [
Â  Â  "MarketValueInDealCcy", "RiskFreeRatePercent",
Â  Â  "UnderlyingPrice", "PricingModelType",
Â  Â  "DividendType", "VolatilityType",
Â  Â  "UnderlyingTimeStamp", "ReportCcy",
Â  Â  "VolatilityType", "Volatility",
Â  Â  "DeltaPercent", "GammaPercent",
Â  Â  "RhoPercent", "ThetaPercent",
Â  Â  "VegaPercent"]




    	
for i, j in enumerate(Chunks(universeL, 100)):
Â  Â  print(f"Batch of (100 or fewer) requests no.: {str(i+1)}/{str(len([i for i in Chunks(universeL, 100)]))}")
Â  Â  # Example request with Body Parameter - Symbology Lookup
Â  Â  request_definition = rd.delivery.endpoint_request.Definition(
Â  Â  Â  Â  method=rd.delivery.endpoint_request.RequestMethod.POST,
Â  Â  Â  Â  url='https://api.refinitiv.com/data/quantitative-analytics/v1/financial-contracts',
Â  Â  Â  Â  body_parameters={"fields": requestFields,
Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â "outputs": ["Data", "Headers"],
Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â "universe": j})
Â
Â  Â  response3 = request_definition.get_data()
Â
Â  Â  if i == 0:
Â  Â  Â  Â  response3df = pd.DataFrame(data=response3.data.raw['data'], columns=headers_name)
Â  Â  else:
Â  Â  Â  Â  _response3df = pd.DataFrame(data=response3.data.raw['data'], columns=headers_name)
Â  Â  Â  Â  response3df = response3df.append(_response3df, ignore_index=True)




Batch of (100 or fewer) requests no.: 1/3
Batch of (100 or fewer) requests no.: 2/3
Batch of (100 or fewer) requests no.: 3/3

    	
response3df



 MarketValueInDealCcy RiskFreeRatePercent UnderlyingPrice PricingModelType DividendType VolatilityType UnderlyingTimeStamp ReportCcy VolatilityType Volatility DeltaPercent GammaPercent RhoPercent ThetaPercent VegaPercent 0 64.7 2.492 4162.12 BlackScholes ImpliedYield Calculated Default EUR Calculated 15.991558 0.409959 0.00172 1.888962 -1.090608 5.4819 1 63 2.492 4156.5 BlackScholes ImpliedYield Calculated Default EUR Calculated 16.097524 0.401092 0.001701 1.845857 -1.089352 5.444814 ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... 256 88.1 2.54 4225.29 BlackScholes ImpliedYield Calculated Default EUR Calculated 14.926027 0.520198 0.001859 2.427816 -1.075951 5.701125 257 88.1 2.54 4224.7 BlackScholes ImpliedYield Calculated Default EUR Calculated 14.979799 0.519102 0.001853 2.422134 -1.079447 5.701135
    	
for i, j in enumerate(Chunks(ATuniverseL, 100)):
Â  Â  print(f"Batch of (100 or fewer) requests no.: {str(i+1)}/{str(len([i for i in Chunks(ATuniverseL, 100)]))}")
Â  Â  # Example request with Body Parameter - Symbology Lookup
Â  Â  ATrequest_definition = rd.delivery.endpoint_request.Definition(
Â  Â  Â  Â  method=rd.delivery.endpoint_request.RequestMethod.POST,
Â  Â  Â  Â  url='https://api.refinitiv.com/data/quantitative-analytics/v1/financial-contracts',
Â  Â  Â  Â  body_parameters={"fields": requestFields,
Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â "outputs": ["Data", "Headers"],
Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â "universe": j})
Â
Â  Â  ATresponse3 = ATrequest_definition.get_data()
Â  Â  try:
Â  Â  except:
Â  Â  Â  Â  print(ATresponse3.errors)
Â
Â  Â  if i == 0:
Â  Â  Â  Â  ATresponse3df = pd.DataFrame(data=ATresponse3.data.raw['data'], columns=ATheaders_name)
Â  Â  else:
Â  Â  Â  Â  _ATresponse3df = pd.DataFrame(data=ATresponse3.data.raw['data'], columns=ATheaders_name)
Â  Â  Â  Â  ATresponse3df = ATresponse3df.append(_ATresponse3df, ignore_index=True)




Batch of (100 or fewer) requests no.: 1/1

    	
ATresponse3df



 MarketValueInDealCcy RiskFreeRatePercent UnderlyingPrice PricingModelType DividendType VolatilityType UnderlyingTimeStamp ReportCcy VolatilityType Volatility DeltaPercent GammaPercent RhoPercent ThetaPercent VegaPercent 0 64.7 2.492 4162.12 BlackScholes ImpliedYield Calculated Default EUR Calculated 15.991558 0.409959 0.00172 1.888962 -1.090608 5.4819 1 63 2.492 4156.5 BlackScholes ImpliedYield Calculated Default EUR Calculated 16.097524 0.401092 0.001701 1.845857 -1.089352 5.444814 ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... 37 86.9 2.545 4223.69 BlackScholes ImpliedYield Calculated Default EUR Calculated 14.85904 0.517257 0.001869 2.413944 -1.071334 5.701031 38 88.1 2.545 4225.29 BlackScholes ImpliedYield Calculated Default EUR Calculated 14.923951 0.520242 0.00186 2.42803 -1.076091 5.701092
    	
IPADf, ATIPADf = response3df.copy(), ATresponse3df.copy()Â  # IPA here stands for the service we used to get all the calculated valuse, Instrument Pricint Analitycs.




    	



 STXE42250C3.EX MarketValueInDealCcy RiskFreeRatePercent UnderlyingPrice PricingModelType DividendType VolatilityType UnderlyingTimeStamp ReportCcy VolatilityType ImpliedVolatility DeltaPercent GammaPercent RhoPercent ThetaPercent VegaPercent 2023-01-27 14:40:00+01:00 64.7 2.492 4162.12 BlackScholes ImpliedYield Calculated Default EUR Calculated 15.991558 0.409959 0.00172 1.888962 -1.090608 5.4819 2023-01-27 14:50:00+01:00 63 2.492 4156.5 BlackScholes ImpliedYield Calculated Default EUR Calculated 16.097524 0.401092 0.001701 1.845857 -1.089352 5.444814 ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... 2023-02-03 13:10:00+01:00 88.1 2.54 4225.29 BlackScholes ImpliedYield Calculated Default EUR Calculated 14.926027 0.520198 0.001859 2.427816 -1.075951 5.701125 2023-02-03 13:20:00+01:00 88.1 2.54 4224.7 BlackScholes ImpliedYield Calculated Default EUR Calculated 14.979799 0.519102 0.001853 2.422134 -1.079447 5.701135
    	



 MarketValueInDealCcy RiskFreeRatePercent UnderlyingPrice PricingModelType DividendType VolatilityType UnderlyingTimeStamp ReportCcy VolatilityType ImpliedVolatility DeltaPercent GammaPercent RhoPercent ThetaPercent VegaPercent 2023-01-27 14:40:00+01:00 64.7 2.492 4162.12 BlackScholes ImpliedYield Calculated Default EUR Calculated 15.991558 0.409959 0.00172 1.888962 -1.090608 5.4819 2023-01-27 14:50:00+01:00 63 2.492 4156.5 BlackScholes ImpliedYield Calculated Default EUR Calculated 16.097524 0.401092 0.001701 1.845857 -1.089352 5.444814 ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... 2023-02-03 11:40:00+01:00 86.9 2.545 4223.69 BlackScholes ImpliedYield Calculated Default EUR Calculated 14.85904 0.517257 0.001869 2.413944 -1.071334 5.701031 2023-02-03 13:10:00+01:00 88.1 2.545 4225.29 BlackScholes ImpliedYield Calculated Default EUR Calculated 14.923951 0.520242 0.00186 2.42803 -1.076091 5.701092

From now on we will not show AT dataframe equivalents because it is... equivalent!

    	
display(searchDf2.iloc[(searchDf2['StrikePrice']-currentUnderlyingPrc).abs().argsort()[:1]])
Â
Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  'RiskFreeRatePercent', 'UnderlyingPrice', 'DeltaPercent',
Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  'GammaPercent', 'RhoPercent', 'ThetaPercent', 'VegaPercent']]
Â
fig = px.line(IPADfGraph)Â  # This is just to see the implied vol graph when that field is available
# fig.layout = dict(xaxis=dict(type="category"))
Â
# Format Graph: https://plotly.com/python/tick-formatting/
fig.update_layout(
Â  Â  title=instrument,
Â  Â  template='plotly_dark')
Â
# Make it so that only one line is shown by default: # https://stackoverflow.com/questions/73384807/plotly-express-plot-subset-of-dataframe-columns-by-default-and-the-rest-as-opt
fig.for_each_trace(
Â  Â  lambda t: t.update(
Â  Â  Â  Â  visible=True if t.name in IPADfGraph.columns[:1] else "legendonly"))
Â
# fig.update_xaxes(autorange=True)
Â
fig.show()




 DocumentTitle RIC StrikePrice ExchangeCode ExpiryDate UnderlyingQuoteRIC 22 Eurex Dow Jones EURO STOXX 50 Index Option 422... STXE42250C3.EX 4225 EUX 17/03/2023 [.STOXX50E]

## 3 Graphs

    	
fig = plotly.subplots.make_subplots(rows=3, cols=1)
Â
Â
Â
fig.update(layout_xaxis_rangeslider_visible=False)
fig.update_layout(
Â  Â  template='plotly_dark',
Â  Â  autosize=False,
Â  Â  width=1300,
Â  Â  height=500)
fig.show()
searchDf2.iloc[(searchDf2['StrikePrice']-currentUnderlyingPrc).abs().argsort()[:1]]




 DocumentTitle RIC StrikePrice ExchangeCode ExpiryDate UnderlyingQuoteRIC 22 Eurex Dow Jones EURO STOXX 50 Index Option 422... STXE42250C3.EX 4225 EUX 17/03/2023 [.STOXX50E]

## Simple Graph

Certain companies are slow to update libraries, dependencies or Python versions. They/You may thus not have access to plotly (the graph library we used above). Matplotlib is rather light and should work, even on machines with old setups:

    	
display(searchDf2.iloc[(searchDf2['StrikePrice']-currentUnderlyingPrc).abs().argsort()[:1]])
Â
fig, axes = plt.subplots(ncols=1)
Â
ax = axes
# ax.xaxis.set_major_formatter(ticker.FuncFormatter(format_date))
ax.set_title(f"{searchDf2.iloc[(searchDf2['StrikePrice']-currentUnderlyingPrc).abs().argsort()[:1]].RIC.values[0]} Implied Volatility At Trade Only")
fig.autofmt_xdate()
Â
plt.show()




 DocumentTitle RIC StrikePrice ExchangeCode ExpiryDate UnderlyingQuoteRIC 22 Eurex Dow Jones EURO STOXX 50 Index Option 422... STXE42250C3.EX 4225 EUX 17/03/2023 [.STOXX50E]
    	



 ImpliedVolatility 2023-01-27 14:40:00+01:00 15.991558 2023-01-27 14:50:00+01:00 16.097524 â€¦ â€¦ 2023-02-03 11:40:00+01:00 14.85904 2023-02-03 13:10:00+01:00 14.923951

## EUREX, or SPX Call or Put Options

Let's put it all together into a single function. This ImpVolatilityCalcIPA function will allow anyone to:

(I) find the option (i) with the index of your choice (SPX or EUREX) as underlying, (ii) closest to strike price right now (i.e.: At The Money) and (iii) with the next, closest expiry date past x days after today,

(II) calculate the Implied Volatility for that option either (i) only at times when the option itself is traded or (ii) at any time the option or the underlying is being traded.

    	
def ImpVolatilityCalcIPA(x=15,
Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â indexUnderlying=".STOXX50E",
Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â callOrPut='Put',
Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â dateBack=3,
Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â expiryYearOfInterest=datetime.now().year,
Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â riskFreeRate=None, riskFreeRateField=None,
Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â timeZoneInGraph=datetime.now().astimezone(),
Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â maxColwidth=200,
Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â graphStyle='without out of trading hours',Â  # 'with out of trading hours', '3 graphs', 'simple'
Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â simpleGraphLineStyle='.-',Â  # 'o-'
Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â simpleGraphSize=(15, 5),
Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â graphTemplate='plotly_dark',
Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â debug=False,
Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â returnDfGraph=False,
Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â AtOptionTradeOnly=False):
Â
Â
Â  Â  if indexUnderlying == ".STOXX50E":
Â  Â  Â  Â  exchangeC, exchangeRIC, mcalGetCalendar = 'EUX', 'STX', 'EUREX'
Â  Â  elif indexUnderlying == '.SPX':
Â  Â  Â  Â  exchangeC, exchangeRIC, mcalGetCalendar = 'OPQ', 'SPX', 'CBOE_Futures'# 'CBOE_Index_Options'Â  # should be 'CBOE_Index_Options'... CBOT_Equity
Â
Â
Â  Â  def Get_exp_dates(year=expiryYearOfInterest,
Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  days=True,
Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  mcal_get_calendar=mcalGetCalendar):
Â  Â  Â  Â  '''
Â  Â  Â  Â  Get_exp_dates Version 3.0:
Â
Â  Â  Â  Â  This function gets expiration dates for a year for NDX options, which are the 3rd Fridays of each month.
Â
Â  Â  Â  Â  Changes
Â  Â  Â  Â  ----------------------------------------------
Â  Â  Â  Â  Changed from Version 1.0 to 2.0: Jonathan Legrand changed Haykaz Aramyan's original code to allow
Â  Â  Â  Â  Â  Â  (i) for the function's holiday argument to be changed, and defaulted to 'EUREX' as opposed to 'CBOE_Index_Options' and
Â  Â  Â  Â  Â  Â  (ii) for the function to output full date objects as opposed to just days of the month if agument days=True.
Â
Â  Â  Â  Â  Changed from Version 2.0 to 3.0: Jonathan Legrand changed this function to reflec tthe fact that it can be used for indexes other than EUREX.
Â
Â  Â  Â  Â  Dependencies
Â  Â  Â  Â  ----------------------------------------------
Â  Â  Â  Â  Python library 'pandas_market_calendars' version 3.2
Â
Â  Â  Â  Â  Parameters
Â  Â  Â  Â  -----------------------------------------------
Â  Â  Â  Â  Input:
Â  Â  Â  Â  Â  Â  year(int): year for which expiration days are requested
Â
Â  Â  Â  Â  Â  Â  mcal_get_calendar(str): String of the calendar for which holidays have to be taken into account. More on this calendar (link to Github chacked 2022-10-11): https://github.com/rsheftel/pandas_market_calendars/blob/177e7922c7df5ad249b0d066b5c9e730a3ee8596/pandas_market_calendars/exchange_calendar_cboe.py
Â  Â  Â  Â  Â  Â  Â  Â  Default: mcal_get_calendar='EUREX'
Â
Â  Â  Â  Â  Â  Â  days(bool): If True, only days of the month is outputed, else it's dataeime objects
Â  Â  Â  Â  Â  Â  Â  Â  Default: days=True
Â
Â  Â  Â  Â  Output:
Â  Â  Â  Â  Â  Â  dates(dict): dictionary of expiration days for each month of a specified year in datetime.date format.
Â  Â  Â  Â  '''
Â
Â  Â  Â  Â  # get CBOE market holidays
Â  Â  Â  Â  Cal = mcal.get_calendar(mcal_get_calendar)
Â  Â  Â  Â  holidays = Cal.holidays().holidays
Â
Â  Â  Â  Â  # set calendar starting from Saturday
Â  Â  Â  Â  c = calendar.Calendar(firstweekday=calendar.SATURDAY)
Â
Â  Â  Â  Â  # get the 3rd Friday of each month
Â  Â  Â  Â  exp_dates = {}
Â  Â  Â  Â  for i in range(1, 13):
Â  Â  Â  Â  Â  Â  monthcal = c.monthdatescalendar(year, i)
Â  Â  Â  Â  Â  Â  date = monthcal[2][-1]
Â  Â  Â  Â  Â  Â  # check if found date is an holiday and get the previous date if it is
Â  Â  Â  Â  Â  Â  if date in holidays:
Â  Â  Â  Â  Â  Â  Â  Â  date = date + timedelta(-1)
Â  Â  Â  Â  Â  Â  # append the date to the dictionary
Â  Â  Â  Â  Â  Â  if year in exp_dates:
Â  Â  Â  Â  Â  Â  Â  Â  ### Changed from original code from here on by Jonathan Legrand on 2022-10-11
Â  Â  Â  Â  Â  Â  Â  Â  if days: exp_dates[year].append(date.day)
Â  Â  Â  Â  Â  Â  Â  Â  else: exp_dates[year].append(date)
Â  Â  Â  Â  Â  Â  else:
Â  Â  Â  Â  Â  Â  Â  Â  if days: exp_dates[year] = [date.day]
Â  Â  Â  Â  Â  Â  Â  Â  else: exp_dates[year] = [date]
Â  Â  Â  Â  return exp_dates
Â
Â  Â  timeOfCalcDatetime = datetime.now()Â  # For now, we will focuss on the use-case where we are calculating values for today; later we will allow for it historically for any day going back a few business days.
Â  Â  timeOfCalcStr = datetime.now().strftime('%Y-%m-%d')
Â  Â  fullDatesAtTimeOfCalc = Get_exp_dates(timeOfCalcDatetime.year, days=False)Â  # timeOfCalcDatetime.year here is 2023
Â  Â  fullDatesAtTimeOfCalcDatetime = [
Â  Â  Â  Â  datetime(i.year, i.month, i.day)
Â  Â  Â  Â  for i in fullDatesAtTimeOfCalc[list(fullDatesAtTimeOfCalc.keys())[0]]]
Â  Â  expiryDateOfInt = [i for i in fullDatesAtTimeOfCalcDatetime
Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â if i > timeOfCalcDatetime + relativedelta(days=x)][0]
Â
Â  Â  if debug: print(f"expiryDateOfInt: {expiryDateOfInt}")
Â
Â  Â  response = search.Definition(
Â  Â  Â  Â  view = search.Views.SEARCH_ALL, # To see what views are available: help(search.Views) & search.metadata.Definition(view = search.Views.SEARCH_ALL).get_data().data.df.to_excel("SEARCH_ALL.xlsx")
Â  Â  Â  Â  query=indexUnderlying,
Â  Â  Â  Â  select="DocumentTitle, RIC, StrikePrice, ExchangeCode, ExpiryDate, UnderlyingAsset, " +
Â  Â  Â  Â  Â  Â  Â  Â  "UnderlyingAssetName, UnderlyingAssetRIC, ESMAUnderlyingIndexCode, RCSUnderlyingMarket" +
Â  Â  Â  Â  Â  Â  Â  Â  "UnderlyingQuoteName, UnderlyingQuoteRIC",
Â  Â  Â  Â  filter=f"RCSAssetCategoryLeaf eq 'Option' and RIC eq '{exchangeRIC}*' and DocumentTitle ne '*Weekly*' " +
Â  Â  Â  Â  f"and CallPutOption eq '{callOrPut}' and ExchangeCode eq '{exchangeC}' and " +
Â  Â  Â  Â  f"ExpiryDate ge {(expiryDateOfInt - relativedelta(days=1)).strftime('%Y-%m-%d')} " +
Â  Â  Â  Â  f"and ExpiryDate lt {(expiryDateOfInt + relativedelta(days=1)).strftime('%Y-%m-%d')}",Â  # ge (greater than or equal to), gt (greater than), lt (less than) and le (less than or equal to). These can only be applied to numeric and date properties.
Â  Â  Â  Â  top=10000,
Â  Â  ).get_data()
Â  Â  searchDf = response.data.df
Â
Â  Â  if debug: display(searchDf)
Â
Â  Â  try:
Â  Â  Â  Â  underlyingPrice =Â  rd.get_history(
Â  Â  Â  Â  Â  Â  universe=[indexUnderlying],
Â  Â  Â  Â  Â  Â  fields=["TRDPRC_1"],
Â  Â  Â  Â  Â  Â  interval="tick").iloc[-1][0]
Â  Â  except:
Â  Â  Â  Â  print("Function failed at the search strage, returning the following dataframe: ")
Â  Â  Â  Â  display(searchDf)
Â
Â  Â  if debug:
Â  Â  Â  Â  print(f"Underlying {indexUnderlying}'s price recoprded here was {underlyingPrice}")
Â  Â  Â  Â  display(searchDf.iloc[(searchDf['StrikePrice']-underlyingPrice).abs().argsort()[:10]])
Â
Â  Â  instrument = searchDf.iloc[(searchDf['StrikePrice']-underlyingPrice).abs().argsort()[:1]].RIC.values[0]
Â
Â  Â  start = (timeOfCalcDatetime - pd.tseries.offsets.BDay(dateBack)).strftime('%Y-%m-%dT%H:%M:%S.%f')Â  # '2022-10-05T07:30:00.000'
Â  Â  endDateTime = datetime.now()
Â  Â  end = endDateTime.strftime('%Y-%m-%dT%H:%M:%S.%f')Â  #Â  e.g.: '2022-09-09T20:00:00.000'
Â
Â  Â  _optnMrktPrice = rd.get_history(
Â  Â  Â  Â  universe=[instrument],
Â  Â  Â  Â  fields=["TRDPRC_1"],
Â  Â  Â  Â  interval="10min",
Â  Â  Â  Â  start=start,Â  # Ought to always start at 4 am for OPRA exchanged Options, more info in the article below
Â  Â  Â  Â  end=end)Â  # Ought to always end at 8 pm for OPRA exchanged Options, more info in the article below
Â
Â  Â  if debug:
Â  Â  Â  Â  print(instrument)
Â  Â  Â  Â  display(_optnMrktPrice)
Â
Â  Â  ## Data on certain options are stale and do not nessesarily show up on Workspace, in case that happens, we will pick the next ATM Option, which probably will have the same strike, but we will only do so once, any more and we could get too far from strike:
Â  Â  if _optnMrktPrice.empty:
Â  Â  Â  Â  if debug: print(f"No data could be found for {instrument}, so the next ATM Option was chosen")
Â  Â  Â  Â  instrument = searchDf.iloc[(searchDf['StrikePrice']-underlyingPrice).abs().argsort()[1:2]].RIC.values[0]
Â  Â  Â  Â  if debug: print(f"{instrument}")
Â  Â  Â  Â  _optnMrktPrice = rd.get_history(universe=[instrument],
Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  fields=["TRDPRC_1"], interval="10min",
Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  start=start, end=end)
Â  Â  Â  Â  if debug: display(_optnMrktPrice)
Â  Â  if _optnMrktPrice.empty:Â  # Let's try one more time, as is often nessesary
Â  Â  Â  Â  if debug: print(f"No data could be found for {instrument}, so the next ATM Option was chosen")
Â  Â  Â  Â  instrument = searchDf.iloc[(searchDf['StrikePrice']-underlyingPrice).abs().argsort()[2:3]].RIC.values[0]
Â  Â  Â  Â  if debug: print(f"{instrument}")
Â  Â  Â  Â  _optnMrktPrice = rd.get_history(universe=[instrument],
Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  fields=["TRDPRC_1"], interval="10min",
Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  start=start, end=end)
Â  Â  Â  Â  if debug: display(_optnMrktPrice)
Â  Â  if _optnMrktPrice.empty:
Â  Â  Â  Â  print(f"No data could be found for {instrument}, please check it on Refinitiv Workspace")
Â
Â  Â  optnMrktPrice = _optnMrktPrice.resample('10Min').mean() # get a datapoint every 10 min
Â  Â  optnMrktPrice = optnMrktPrice[optnMrktPrice.index.strftime('%Y-%m-%d').isin([i for i in _optnMrktPrice.index.strftime('%Y-%m-%d').unique()])]Â  # Only keep trading days
Â  Â  optnMrktPrice = optnMrktPrice.loc[(optnMrktPrice.index.strftime('%H:%M:%S') >= '07:30:00') & (optnMrktPrice.index.strftime('%H:%M:%S') <= '22:00:00')]Â  # Only keep trading hours
Â  Â  optnMrktPrice.fillna(method='ffill', inplace=True)Â  # Forward Fill to populate NaN values
Â
Â  Â  # Note also that one may want to only look at 'At Option Trade' datapoints,
Â  Â  # i.e.: Implied Volatility when a trade is made for the Option, but not when
Â  Â  # none is made. For this, we will use the 'At Trade' (AT) dataframes:
Â  Â  if AtOptionTradeOnly: AToptnMrktPrice = _optnMrktPrice
Â
Â  Â  underlying = searchDf.iloc[(searchDf['StrikePrice']).abs().argsort()[:1]].UnderlyingQuoteRIC.values[0][0]
Â
Â  Â  _underlyingMrktPrice = rd.get_history(
Â  Â  Â  Â  universe=[underlying],
Â  Â  Â  Â  fields=["TRDPRC_1"],
Â  Â  Â  Â  interval="10min",
Â  Â  Â  Â  start=start,
Â  Â  Â  Â  end=end)
Â  Â  # Let's put it al in one data-frame, df. Some datasets will have data
Â  Â  # going from the time we sert for start all the way to end. Some won't
Â  Â  # because no trade happened in the past few minutes/hours. We ought to base
Â  Â  # ourselves on the dataset with values getting closer to end and ffill
Â  Â  # for the other column. As a result, the following if loop is needed:
Â  Â  if optnMrktPrice.index[-1] >= _underlyingMrktPrice.index[-1]:
Â  Â  Â  Â  df = optnMrktPrice.copy()
Â  Â  Â  Â  df['underlying ' + underlying + ' TRDPRC_1'] = _underlyingMrktPrice
Â  Â  else:
Â  Â  Â  Â  df = _underlyingMrktPrice.copy()
Â  Â  Â  Â  df.rename(
Â  Â  Â  Â  Â  Â  columns={"TRDPRC_1": 'underlying ' + underlying + ' TRDPRC_1'},
Â  Â  Â  Â  Â  Â  inplace=True)
Â  Â  Â  Â  df['TRDPRC_1'] = optnMrktPrice
Â  Â  Â  Â  df.columns.name = optnMrktPrice.columns.name
Â  Â  df.fillna(method='ffill', inplace=True)Â  # Forward Fill to populate NaN values
Â  Â  df = df.dropna()
Â
Â  Â  Â  Â  ATunderlyingMrktPrice = AToptnMrktPrice.join(
Â  Â  Â  Â  Â  Â  _underlyingMrktPrice, lsuffix='_OptPr', rsuffix=' Underlying ' + underlying + ' TRDPRC_1', how='inner')
Â  Â  Â  Â  ATdf = ATunderlyingMrktPrice
Â
Â  Â  strikePrice = searchDf.iloc[(searchDf['StrikePrice']-underlyingPrice).abs().argsort()[:1]].StrikePrice.values[0]
Â
Â  Â  if riskFreeRate is None and indexUnderlying == ".SPX":
Â  Â  Â  Â  _riskFreeRate = 'USDCFCFCTSA3M='
Â  Â  Â  Â  _riskFreeRateField = 'TR.FIXINGVALUE'
Â  Â  elif riskFreeRate is None and indexUnderlying == ".STOXX50E":
Â  Â  Â  Â  _riskFreeRate = 'EURIBOR3MD='
Â  Â  Â  Â  _riskFreeRateField = 'TR.FIXINGVALUE'
Â  Â  else:
Â  Â  Â  Â  _riskFreeRate, _riskFreeRateField = riskFreeRate, riskFreeRateField
Â
Â  Â  _RfRate = rd.get_history(
Â  Â  Â  Â  universe=[_riskFreeRate],Â  # USD3MFSR=, USDSOFR=
Â  Â  Â  Â  fields=[_riskFreeRateField],
Â  Â  Â  Â  # Since we will use dropna() as a way to select the rows we are after later on in the code, we need to ask for more risk-free data than needed, just in case we don't have enough:
Â  Â  Â  Â  start=(datetime.strptime(start, '%Y-%m-%dT%H:%M:%S.%f') - timedelta(days=1)).strftime('%Y-%m-%d'),
Â  Â  Â  Â  end=(datetime.strptime(end, '%Y-%m-%dT%H:%M:%S.%f') + timedelta(days=1)).strftime('%Y-%m-%d'))
Â
Â  Â  RfRate = _RfRate.resample('10Min').mean().fillna(method='ffill')
Â  Â  df['RfRate'] = RfRate
Â  Â  df = df.fillna(method='ffill')
Â
Â  Â  Â  Â  pd.options.mode.chained_assignment = NoneÂ  # default='warn'
Â  Â  Â  Â  ATunderlyingMrktPrice['RfRate'] = [pd.NA for i in ATunderlyingMrktPrice.index]
Â  Â  Â  Â  for i in RfRate.index:
Â  Â  Â  Â  Â  Â  _i = str(i)[:10]
Â  Â  Â  Â  Â  Â  for n, j in enumerate(ATunderlyingMrktPrice.index):
Â  Â  Â  Â  Â  Â  Â  Â  if _i in str(j):
Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  if len(RfRate.loc[i].values) == 2:
Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  ATunderlyingMrktPrice['RfRate'].iloc[n] = RfRate.loc[i].values[0][0]
Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  elif len(RfRate.loc[i].values) == 1:
Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  ATunderlyingMrktPrice['RfRate'].iloc[n] = RfRate.loc[i].values[0]
Â  Â  Â  Â  ATdf = ATunderlyingMrktPrice.copy()
Â  Â  ATdf = ATdf.fillna(method='ffill')Â  # This is in case there were no Risk Free datapoints released after a certain time, but trades on the option still went through.
Â
Â  Â  if timeZoneInGraph != 'GMT':
Â  Â  Â  Â  df.index = [
Â  Â  Â  Â  Â  Â  df.index[i].replace(
Â  Â  Â  Â  Â  Â  Â  Â  tzinfo=pytz.timezone(
Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  'GMT')).astimezone(
Â  Â  Â  Â  Â  Â  Â  Â  tz=timeZoneInGraph.tzinfo)
Â  Â  Â  Â  Â  Â  for i in range(len(df))]
Â  Â  Â  Â  if AtOptionTradeOnly:
Â  Â  Â  Â  Â  Â  ATdf.index = [
Â  Â  Â  Â  Â  Â  Â  Â  ATdf.index[i].replace(
Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  tzinfo=pytz.timezone(
Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  'GMT')).astimezone(
Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  tz=datetime.now().astimezone().tzinfo)
Â  Â  Â  Â  Â  Â  Â  Â  for i in range(len(ATdf))]
Â
Â  Â  Â  Â  universeL = [
Â  Â  Â  Â  Â  Â  {
Â  Â  Â  Â  Â  Â  Â  "instrumentType": "Option",
Â  Â  Â  Â  Â  Â  Â  "instrumentDefinition": {
Â  Â  Â  Â  Â  Â  Â  Â  "underlyingType": "Eti",
Â  Â  Â  Â  Â  Â  Â  Â  "instrumentCode": instrument,
Â  Â  Â  Â  Â  Â  Â  Â  "strike": str(strikePrice),
Â  Â  Â  Â  Â  Â  Â  },
Â  Â  Â  Â  Â  Â  Â  "pricingParameters": {
Â  Â  Â  Â  Â  Â  Â  Â  "marketValueInDealCcy": str(ATdf['TRDPRC_1_OptPr'][i]),
Â  Â  Â  Â  Â  Â  Â  Â  "riskFreeRatePercent": str(ATdf['RfRate'][i]),
Â  Â  Â  Â  Â  Â  Â  Â  "underlyingPrice": str(ATdf['TRDPRC_1 Underlying ' + underlying + ' TRDPRC_1'][i]),
Â  Â  Â  Â  Â  Â  Â  Â  "pricingModelType": "BlackScholes",
Â  Â  Â  Â  Â  Â  Â  Â  "dividendType": "ImpliedYield",
Â  Â  Â  Â  Â  Â  Â  Â  "volatilityType": "Implied",
Â  Â  Â  Â  Â  Â  Â  Â  "underlyingTimeStamp": "Default",
Â  Â  Â  Â  Â  Â  Â  Â  "reportCcy": "EUR"
Â  Â  Â  Â  Â  Â  Â  }
Â  Â  Â  Â  Â  Â  }
Â  Â  Â  Â  Â  Â  for i in range(len(ATdf.index))]
Â  Â  else:
Â  Â  Â  Â  universeL = [
Â  Â  Â  Â  Â  Â  {
Â  Â  Â  Â  Â  Â  Â  "instrumentType": "Option",
Â  Â  Â  Â  Â  Â  Â  "instrumentDefinition": {
Â  Â  Â  Â  Â  Â  Â  Â  "underlyingType": "Eti",
Â  Â  Â  Â  Â  Â  Â  Â  "instrumentCode": instrument,
Â  Â  Â  Â  Â  Â  Â  Â  "strike": str(strikePrice),
Â  Â  Â  Â  Â  Â  Â  },
Â  Â  Â  Â  Â  Â  Â  "pricingParameters": {
Â  Â  Â  Â  Â  Â  Â  Â  "marketValueInDealCcy": str(df['TRDPRC_1'][i]),
Â  Â  Â  Â  Â  Â  Â  Â  "riskFreeRatePercent": str(df['RfRate'][i]),
Â  Â  Â  Â  Â  Â  Â  Â  "underlyingPrice": str(df['underlying ' + underlying + ' TRDPRC_1'][i]),
Â  Â  Â  Â  Â  Â  Â  Â  "pricingModelType": "BlackScholes",
Â  Â  Â  Â  Â  Â  Â  Â  "dividendType": "ImpliedYield",
Â  Â  Â  Â  Â  Â  Â  Â  "volatilityType": "Implied",
Â  Â  Â  Â  Â  Â  Â  Â  "underlyingTimeStamp": "Default",
Â  Â  Â  Â  Â  Â  Â  Â  "reportCcy": "EUR"
Â  Â  Â  Â  Â  Â  Â  }
Â  Â  Â  Â  Â  Â  }
Â  Â  Â  Â  Â  Â  for i in range(len(df.index))]
Â
Â  Â  def Chunks(lst, n):
Â  Â  Â  Â  """Yield successive n-sized chunks from lst."""
Â  Â  Â  Â  for i in range(0, len(lst), n):
Â  Â  Â  Â  Â  Â  yield lst[i:i + n]
Â
Â  Â  requestFields = [
Â  Â  Â  Â  "MarketValueInDealCcy", "RiskFreeRatePercent",
Â  Â  Â  Â  "UnderlyingPrice", "PricingModelType",
Â  Â  Â  Â  "DividendType", "VolatilityType",
Â  Â  Â  Â  "UnderlyingTimeStamp", "ReportCcy",
Â  Â  Â  Â  "VolatilityType", "Volatility",
Â  Â  Â  Â  "DeltaPercent", "GammaPercent",
Â  Â  Â  Â  "RhoPercent", "ThetaPercent", "VegaPercent"]
Â
Â  Â  for i, j in enumerate(Chunks(universeL, 100)):
Â  Â  Â  Â  # Example request with Body Parameter - Symbology Lookup
Â  Â  Â  Â  request_definition = rd.delivery.endpoint_request.Definition(
Â  Â  Â  Â  Â  Â  method=rd.delivery.endpoint_request.RequestMethod.POST,
Â  Â  Â  Â  Â  Â  url='https://api.refinitiv.com/data/quantitative-analytics/v1/financial-contracts',
Â  Â  Â  Â  Â  Â  body_parameters={
Â  Â  Â  Â  Â  Â  Â  Â  "fields": requestFields,
Â  Â  Â  Â  Â  Â  Â  Â  "outputs": ["Data", "Headers"],
Â  Â  Â  Â  Â  Â  Â  Â  "universe": j})
Â  Â  Â  Â  response2 = request_definition.get_data()
Â
Â  Â  Â  Â  IPADf.index = ATdf.index
Â  Â  Â  Â  IPADf.columns.name = ATdf.columns.name
Â  Â  else:
Â  Â  Â  Â  IPADf.index = df.index
Â  Â  Â  Â  IPADf.columns.name = df.columns.name
Â
Â  Â  # We are going to want to show details about data retreived in a dataframe in the output of this function. The one line below allows us to maximise the width (column) length of cells to see all that is written within them.
Â  Â  pd.options.display.max_colwidth = maxColwidth
Â
Â  Â  if graphStyle == 'simple':
Â  Â  Â  Â  display(searchDf.iloc[(searchDf['StrikePrice']-underlyingPrice).abs().argsort()[:1]])
Â  Â  Â  Â  fig, axes = plt.subplots(ncols=1, figsize=simpleGraphSize)
Â  Â  Â  Â  axes.plot(IPADf[['ImpliedVolatility']].ImpliedVolatility, simpleGraphLineStyle)
Â  Â  Â  Â  if AtOptionTradeOnly: axes.set_title(f"{instrument} Implied Volatility At Trade Only")
Â  Â  Â  Â  else: axes.set_title(f"{instrument} Implied Volatility")
Â  Â  Â  Â  plt.show()
Â
Â  Â  else:
Â
Â  Â  Â  Â  display(searchDf.iloc[(searchDf['StrikePrice']-underlyingPrice).abs().argsort()[:1]])
Â
Â  Â  Â  Â  Â  Â  ['ImpliedVolatility', 'MarketValueInDealCcy',
Â  Â  Â  Â  Â  Â  Â 'RiskFreeRatePercent', 'UnderlyingPrice', 'DeltaPercent',
Â  Â  Â  Â  Â  Â  Â 'GammaPercent', 'RhoPercent', 'ThetaPercent', 'VegaPercent']]
Â
Â  Â  Â  Â  if debug: display(IPADfGraph)
Â
Â  Â  Â  Â  try:Â  # This is needed in case there is not enough data to calculate values for all timestamps , see https://stackoverflow.com/questions/67244912/wide-format-csv-with-plotly-express
Â  Â  Â  Â  Â  Â  fig = px.line(IPADfGraph)
Â  Â  Â  Â  except:
Â  Â  Â  Â  Â  Â  if returnDfGraph:
Â  Â  Â  Â  Â  Â  Â  Â  return IPADfGraph
Â  Â  Â  Â  Â  Â  else:
Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  ["ImpliedVolatility", "MarketValueInDealCcy",
Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â "RiskFreeRatePercent", "UnderlyingPrice"]]
Â  Â  Â  Â  Â  Â  Â  Â  fig = px.line(IPADfGraph)
Â
Â  Â  Â  Â  if graphStyle == 'with out of trading hours':
Â  Â  Â  Â  Â  Â  fig.update_layout(
Â  Â  Â  Â  Â  Â  Â  Â  title=instrument,
Â  Â  Â  Â  Â  Â  Â  Â  template=graphTemplate)
Â  Â  Â  Â  Â  Â  fig.for_each_trace(
Â  Â  Â  Â  Â  Â  Â  Â  lambda t: t.update(
Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  visible=True if t.name in IPADfGraph.columns[:1] else "legendonly"))
Â  Â  Â  Â  Â  Â  fig.show()
Â
Â  Â  Â  Â  elif graphStyle == '3 graphs':
Â  Â  Â  Â  Â  Â  fig = plotly.subplots.make_subplots(rows=3, cols=1)
Â
Â  Â  Â  Â  Â  Â  fig.add_trace(go.Scatter(
Â  Â  Â  Â  Â  Â  Â  Â  name='Op Imp Volatility'), row=1, col=1)
Â  Â  Â  Â  Â  Â  fig.add_trace(go.Scatter(
Â  Â  Â  Â  Â  Â  Â  Â  name='Op Mk Pr'), row=2, col=1)
Â  Â  Â  Â  Â  Â  fig.add_trace(go.Scatter(
Â  Â  Â  Â  Â  Â  Â  Â  name=underlying+' Undrlyg Pr'), row=3, col=1)
Â
Â  Â  Â  Â  Â  Â  fig.update(layout_xaxis_rangeslider_visible=False)
Â  Â  Â  Â  Â  Â  fig.update_layout(title=IPADfGraph.columns.name)
Â  Â  Â  Â  Â  Â  fig.update_layout(
Â  Â  Â  Â  Â  Â  Â  Â  title=instrument,
Â  Â  Â  Â  Â  Â  Â  Â  template=graphTemplate,
Â  Â  Â  Â  Â  Â  Â  Â  autosize=False,
Â  Â  Â  Â  Â  Â  Â  Â  width=1300,
Â  Â  Â  Â  Â  Â  Â  Â  height=500)
Â  Â  Â  Â  Â  Â  fig.show()
Â
Â  Â  Â  Â  else:
Â
Â  Â  Â  Â  Â  Â  print("Looks like the agrument graphStyle used is incorrect. Try simple, with out of trading hours or 3 graphs")




    	
ImpVolatilityCalcIPA(Â  # This will pick up 10 min data
Â  Â  x=15,
Â  Â  indexUnderlying=".STOXX50E",Â  # ".SPX" or ".STOXX50E"
Â  Â  callOrPut='Call',Â  # 'Put' or 'Call'
Â  Â  dateBack=3,
Â  Â  expiryYearOfInterest=datetime.now().year,
Â  Â  riskFreeRate=None,
Â  Â  riskFreeRateField=None,Â  # 'TR.FIXINGVALUE'
Â  Â  timeZoneInGraph=datetime.now().astimezone(),
Â  Â  maxColwidth=200,
Â  Â  graphStyle='3 graphs',Â  # 'with out of trading hours', '3 graphs', 'simple'
Â  Â  simpleGraphLineStyle='.-',Â  # 'o-'
Â  Â  simpleGraphSize=(15, 5),
Â  Â  graphTemplate='plotly_dark',
Â  Â  debug=False,
Â  Â  returnDfGraph=False,




 DocumentTitle RIC StrikePrice ExchangeCode ExpiryDate UnderlyingQuoteRIC 22 Eurex Dow Jones EURO STOXX 50 Index Option 4225 Call Mar 2023 , Stock Index Cash Option, Call 4225 EUR 17-Mar-2023, Eurex STXE42250C3.EX 4225 EUX 17/03/2023 [.STOXX50E]

## Creating a class with PEP 3107 (a.k.a.: Type Hints)

Stay tuned! As soon I will update this article using PEP 3107 (and PEP 484) (and some decorators)!

# Conclusion

As you can see, not only can we use IPA to gather large amounts of bespoke, calculated, values, but be can also portray this insight in a simple, quick and relevent way. The last cell in particular loops through our built fundction to give an updated graph every 5 seconds using 'legacy' technologies that would work in most environments (e.g.: Eikon Codebook).

## References

Brilliant: Black-Scholes-Merton

What is the RIC syntax for options in Refinitiv Eikon?

Functions to find Option RICs traded on different exchanges

Eikon Calc Help Page

Making your code faster: Cython and parallel processing in the Jupyter Notebook

## Q&A

RIC nomenclature for expired Options on Futures

Expiration Dates for Expired Options API