Implied volatility is a measure of the expected fluctuation in the price of a stock or option over a certain period of time. It is derived from the market price of the option and reflects the market's expectations for the stock's future price movements.
I will use Python and MongoDB for this tutorial since I have the stocks and options data stored in mongoDB.
import pymongo
from pymongo import MongoClient
import datetime
import pandas as pd
Let us initiate the mongo DB Connection.
client = MongoClient('mongodb://localhost:27017')
db = client['stocktwits']
At the writing of this tutorial, the date is Jan 6th, 2023. So let us get both the option and stock data from mongoDB.
Let us pick the option contract of strike 100 call expiring Jan 20, 2023
expirationDate = datetime.datetime.strptime("2023-01-20","%Y-%m-%d")
option = list(db.tdameritrade.find({'contractName':'TSLA',\
'strike':100.0,\
'option_type':'call',\
'expirationDate':expirationDate})\
.sort([('added',pymongo.DESCENDING)]).limit(1))
option
[{'_id': ObjectId('63b8383f458ed2075a6d9b74'), 'symbol': 'TSLA_012023C100', 'description': 'TSLA Jan 20 2023 100 Call', 'exchangeName': 'OPR', 'bid': 15.0, 'ask': 15.2, 'last': 15.19, 'mark': 15.1, 'bidSize': 221, 'askSize': 69, 'bidAskSize': '221X69', 'lastSize': 0, 'highPrice': 16.13, 'lowPrice': 7.74, 'openPrice': 0.0, 'closePrice': 13.18, 'totalVolume': 6855, 'tradeDate': None, 'tradeTimeInLong': 1673038767940, 'quoteTimeInLong': 1673038799842, 'netChange': 2.01, 'volatility': 76.836, 'delta': 0.811, 'gamma': 0.016, 'theta': -0.166, 'vega': 0.061, 'rho': 0.031, 'timeValue': 2.13, 'theoreticalOptionValue': 15.124, 'theoreticalVolatility': 29.0, 'optionDeliverablesList': None, 'expirationDate': datetime.datetime(2023, 1, 20, 0, 0), 'daysToExpiration': 14, 'expirationType': 'R', 'multiplier': 100.0, 'settlementType': ' ', 'deliverableNote': '', 'isIndexOption': None, 'percentChange': 15.27, 'markChange': 1.92, 'markPercentChange': 14.58, 'intrinsicValue': 13.06, 'pennyPilot': True, 'inTheMoney': True, 'mini': False, 'nonStandard': False, 'strike': 100.0, 'open_interest': 12856, 'option_type': 'call', 'contractName': 'TSLA', 'lastTradeDate': datetime.datetime(2023, 1, 6, 0, 0), 'price_mult_oi': 205696, 'price_mult_vol': 109680, 'added': datetime.datetime(2023, 1, 6, 16, 0, 3, 8000), 'change_in_open_interest': -12}]
#Let us calculate the market price of the option
price = (option[0]['bid'] + option[0]['ask'])/2.0
print(price)
15.1
Let us look at the Tesla stock price on Jan 6, 2023
list(db.eod_stock_data.find({'ticker':'TSLA'}).sort([('date',pymongo.DESCENDING)]).limit(1))
[{'_id': ObjectId('63b89d2631dc9aead1ea7889'), 'date': datetime.datetime(2023, 1, 6, 0, 0), 'open': 103, 'high': 114.39, 'low': 101.81, 'close': 113.06, 'adjusted_close': 113.06, 'volume': 219981652, 'ticker': 'TSLA', 'perchange': 2.47}]
There are several other ways to calculate the implied volatility of an option in Python, I will use py_vollib.
Using the implied_volatility() function from the py_vollib library: The py_vollib library is a Python library for option pricing that provides a number of functions for calculating option prices and implied volatilities. You can use the implied_volatility() function to calculate the implied volatility of an option as follows:
from py_vollib.black_scholes_merton.implied_volatility import implied_volatility
iv = implied_volatility(price, s, k, t, r, q, flag)
In this example, the input parameters are:
price: The option's market price.
s: The current price of the stock.
k: The option's strike price.
t: The time until expiration, expressed in years.
r: The risk-free interest rate, expressed as a decimal.
q: annualized continuous dividend rate.
flag: A string indicating whether the option is a call option ('c') or a put option ('p').
price = 15.1
s = 113.06
k = 100.0
t = 14/365.0
r = 0.035 #3.5% 10 year treasury rate<br>
q = 0
flag = 'c'
iv = implied_volatility(price, s, k, t, r, q, flag)
print(iv)
0.7799898996788112
There you go, the implied volatility of the option contract is ~78%
Related Notebooks
- Plot Stock Options Vega Implied Volatility Using Python Matplotlib
- Demystifying Stock Options Vega Using Python
- Calculate Stock Options Max Pain Using Data From Yahoo Finance With Python
- Stock Sentiment Analysis Using Autoencoders
- Stock Charts Detection Using Image Classification Model ResNet
- Python IndexError List Index Out of Range
- Stock Tweets Text Analysis Using Pandas NLTK and WordCloud
- A Study of the TextRank Algorithm in Python
- How To Get Measures Of Spread With Python