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

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__}")
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
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)
print(fullDatesStrDict)
print(dates)
print(fullDatesDayDict)
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
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)
expiryDateOfInt = [i for i in fullDatesAtTimeOfCalcDatetime
          if i > timeOfCalcDatetime + relativedelta(days=x)][0]
expiryDateOfInt
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
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')
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
_RefDailyImpVolDf = historical_pricing.events.Definition(
  instrument, fields=['IMP_VOLT'], count=2000).get_data()
_RefDailyImpVolDf.data.df.head()
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()
_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.:
_optnMrktPrice.head()
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:
- 4am to 8pm ET for OPRA and
- typically 7:30am to 22:00 CET at the Eurex Exchange (EUREX)
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
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
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... |
_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
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": {
      "buySell": "Buy",
      "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": {
      "buySell": "Buy",
      "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()
  headers_name = [h['name'] for h in response3.data.raw['headers']]
Â
  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)
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:
    ATheaders_name = [h['name'] for h in ATresponse3.data.raw['headers']]
  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)
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.
IPADf.index, ATIPADf.index = dfLocalTimeZone.index, ATdfLocalTimeZone.index
IPADf.columns.name = dfLocalTimeZone.columns.name
ATIPADf.columns.name = ATdfLocalTimeZone.columns.name
IPADf.rename(columns={"Volatility": 'ImpliedVolatility'}, inplace=True)
ATIPADf.rename(columns={"Volatility": 'ImpliedVolatility'}, inplace=True)
IPADf
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 |
ATIPADf
|
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 |
With out-of-trading hours
From now on we will not show AT dataframe equivalents because it is... equivalent!
display(searchDf2.iloc[(searchDf2['StrikePrice']-currentUnderlyingPrc).abs().argsort()[:1]])
Â
IPADfGraph = IPADf[['ImpliedVolatility', 'MarketValueInDealCcy',
          '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.update_layout(yaxis=IPADf.index[0::10])
Â
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.add_trace(go.Scatter(x=IPADf.index, y=IPADf.ImpliedVolatility, name='Op Imp Volatility'), row=1, col=1)
fig.add_trace(go.Scatter(x=IPADf.index, y=IPADf.MarketValueInDealCcy, name='Op Mk Pr'), row=2, col=1)
fig.add_trace(go.Scatter(x=IPADf.index, y=IPADf.UnderlyingPrice, name=underlying+' Undrlyg Pr'), row=3, col=1)
Â
Â
fig.update(layout_xaxis_rangeslider_visible=False)
fig.update_layout(title=IPADf.columns.name)
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]])
ATIPADfSimpleGraph = ATIPADf[['ImpliedVolatility']]
Â
fig, axes = plt.subplots(ncols=1)
Â
ax = axes
ax.plot(ATIPADfSimpleGraph.ImpliedVolatility, '.-')
# 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] |
ATIPADfSimpleGraph
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()
Â
  if AtOptionTradeOnly:
    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')
Â
  if AtOptionTradeOnly:
    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))]
Â
  if AtOptionTradeOnly:
    universeL = [
      {
       "instrumentType": "Option",
       "instrumentDefinition": {
        "buySell": "Buy",
        "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": {
        "buySell": "Buy",
        "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()
    headers_name = [h['name'] for h in response2.data.raw['headers']]
    _IPADf = pd.DataFrame(data=response2.data.raw['data'], columns=headers_name)
    if i == 0: IPADf = _IPADf
    else: IPADf = IPADf.append(_IPADf, ignore_index=True)
Â
  if AtOptionTradeOnly:
    IPADf.index = ATdf.index
    IPADf.columns.name = ATdf.columns.name
  else:
    IPADf.index = df.index
    IPADf.columns.name = df.columns.name
  IPADf.rename(columns={"Volatility": 'ImpliedVolatility'}, inplace=True)
Â
  # 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]])
    IPADfSimpleGraph = IPADf[['ImpliedVolatility']]
    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]])
Â
    IPADfGraph = IPADf[
      ['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:
        IPADfGraph = IPADfGraph[
          ["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(
        x=IPADf.index, y=IPADfGraph.ImpliedVolatility,
        name='Op Imp Volatility'), row=1, col=1)
      fig.add_trace(go.Scatter(
        x=IPADf.index, y=IPADfGraph.MarketValueInDealCcy,
        name='Op Mk Pr'), row=2, col=1)
      fig.add_trace(go.Scatter(
        x=IPADf.index, y=IPADfGraph.UnderlyingPrice,
        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,
  AtOptionTradeOnly=True)
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
Making your code faster: Cython and parallel processing in the Jupyter Notebook