NbShare
  • Nbshare Notebooks

  • Table of Contents

  • Python Utilities

    • How To Install Jupyter Notebook
    • How to Upgrade Python Pip
    • How To Use Python Pip
  • Python

    • Python Datetime
    • Python Dictionary
    • Python Generators
    • Python Iterators and Generators
    • Python Lambda
    • Python Sort List
    • String And Literal In Python 3
    • Strftime and Strptime In Python
    • Python Tkinter
    • Python Underscore
    • Python Yield
  • Pandas

    • Aggregating and Grouping
    • DataFrame to CSV
    • DF to Numpy Array
    • Drop Columns of DF
    • Handle Json Data
    • Iterate Over Rows of DataFrame
    • Merge and Join DataFrame
    • Pivot Tables
    • Python List to DataFrame
    • Rename Columns of DataFrame
    • Select Rows and Columns Using iloc, loc and ix
    • Sort DataFrame
  • PySpark

    • Data Analysis With Pyspark
    • Read CSV
    • RDD Basics
  • Data Science

    • Confusion Matrix
    • Decision Tree Regression
    • Logistic Regression
    • Regularization Techniques
    • SVM Sklearn
    • Time Series Analysis Using ARIMA
  • Machine Learning

    • How To Code RNN and LSTM Neural Networks in Python
    • PyTorch Beginner Tutorial Tensors
    • Rectified Linear Unit For Artificial Neural Networks Part 1 Regression
    • Stock Sentiment Analysis Using Autoencoders
  • Natural Language
    Processing

    • Opinion Mining Aspect Level Sentiment Analysis
    • Sentiment Analysis using Autoencoders
    • Understanding Autoencoders With Examples
    • Word Embeddings Transformers In SVM Classifier
  • R

    • DataFrame to CSV
    • How to Create DataFrame in R
    • How To Use Grep In R
    • How To Use R Dplyr Package
    • Introduction To R DataFrames
    • Tidy Data In R
  • A.I. News
NbShare Notebooks
  • Publish Your Post On nbshare.io

  • R Python Pandas Data Science Excel NLP Numpy Pyspark Finance

Calculate Implied Volatility of Stock Option Using Python

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.

In [2]:
import pymongo
from pymongo import MongoClient
import datetime
import pandas as pd


Let us initiate the mongo DB Connection.

In [22]:
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

In [43]:
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))
In [44]:
option
Out[44]:
[{'_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}]
In [45]:
#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

In [64]:
list(db.eod_stock_data.find({'ticker':'TSLA'}).sort([('date',pymongo.DESCENDING)]).limit(1))
Out[64]:
[{'_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:

In [57]:
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').

In [52]:
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'
In [59]:
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

Register

User Already registered.


Login

Login

We didn't find you! Please Register

Wrong Password!


Register
    Top Notebooks:
  • Data Analysis With Pyspark Dataframe
  • Strftime and Strptime In Python
  • Python If Not
  • Python Is Integer
  • Dictionaries in Python
  • How To install Python3.9 With Conda
  • String And Literal In Python 3
  • Privacy Policy
©