Rajandran R Creator of OpenAlgo Sketchmaker, RagZ. Building GenAI Applications. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Now the recent curiosity on building Trading AI Agents.

Computing Option Greeks Using OpenAlgo and Mibian: A Python Guide for Traders

5 min read

To calculate option Greeks in Python, you need four live inputs (spot price, strike, time to expiry and the option’s market price), an implied volatility solver and a pricing model. This guide fetches the prices through OpenAlgo, solves for implied volatility with the Mibian library and returns Delta, Gamma, Theta and Vega for any NSE or BSE option in a few lines of code.

This tutorial demonstrates how to calculate real-time Option Greeks (Delta, Gamma, Theta, Vega, and Implied Volatility) for NIFTY options using Python. By integrating OpenAlgo for live market data and Mibian for Black-Scholes modeling, traders can compute Greeks from any NSE option symbol with minimal setup. The script works for both call and put options and is ideal for building option dashboards, risk models, or trading signals.

Key takeaways
  • Install with pip install openalgo mibian scipy, keep OpenAlgo running and logged in to your broker, and paste your OpenAlgo API key into the script.
  • The script parses an OpenAlgo option symbol, fetches the spot and option LTP, solves for IV and prints the Greeks.
  • Mibian uses Black-Scholes on the spot price; Theta is per calendar day and Vega is per 1 percentage point of volatility.
  • NSE weekly and monthly contracts now expire on Tuesday, so update the example symbol to a live contract before running it.
  • Newer OpenAlgo releases also have a built-in optiongreeks() function that uses the Black-76 model.

This tutorial shows you how to calculate real-time Option Greeks for NIFTY options using:

OpenAlgo: one API for 35+ Indian brokers

FREE AND OPEN SOURCE

OpenAlgo: one API for 35+ Indian brokers

Self-hosted algo trading platform. Send orders from Python, AmiBroker, TradingView, Excel or a no-code flow through one consistent API.

  • Unified REST and WebSocket API
  • Works with AmiBroker, TradingView, ChartInk and Excel
  • Sandbox mode to test before going live
Get OpenAlgo →by Marketcalls
  • OpenAlgo: your broker-connected trading gateway
  • Mibian: a Python library for option pricing models
  • SciPy: used internally by Mibian

Prerequisites

Before diving into code, make sure you’ve completed the following setup:

1. Install Required Libraries

pip install openalgo mibian scipy

Note: mibian requires scipy to function correctly.

2. Set Up OpenAlgo

Ensure that OpenAlgo is:

  • Installed, configured to your broker and running locally
  • Connected to your broker
  • You are logged in

3. Get Your OpenAlgo API Key

  • Visit your OpenAlgo dashboard
  • Click the profile icon and go to API Keys
  • Copy the generated API key
  • Paste it into your Python script
  • Run the Python Application

Full Working Python Script

Here’s the complete code to compute Option Greeks from a symbol like NIFTY24APR2523800CE:

import mibian
import re
from datetime import datetime
from openalgo import api

# Initialize OpenAlgo client globally (adjust API key as needed)
client = api(
    api_key='your-openalgo-apikey',
    host='http://127.0.0.1:5000'
)

# Define index mappings
NSE_INDEX_SYMBOLS = {"NIFTY", "NIFTYNXT50", "FINNIFTY", "BANKNIFTY", "MIDCPNIFTY"}
BSE_INDEX_SYMBOLS = {"SENSEX", "BANKEX", "SENSEX50"}

def parse_option_symbol(symbol: str):
    match = re.match(r"([A-Z]+)(\d{2})([A-Z]{3})(\d{2})(\d+)(CE|PE)", symbol)
    if not match:
        raise ValueError("Invalid symbol format")
    base_symbol, day, month_str, year, strike, opt_type = match.groups()
    month_map = {
        'JAN': 1, 'FEB': 2, 'MAR': 3, 'APR': 4, 'MAY': 5, 'JUN': 6,
        'JUL': 7, 'AUG': 8, 'SEP': 9, 'OCT': 10, 'NOV': 11, 'DEC': 12
    }
    expiry = datetime(int('20' + year), month_map[month_str], int(day), 15, 30)
    return base_symbol, expiry, int(strike), opt_type

def get_underlying_exchange(base_symbol: str) -> str:
    if base_symbol in NSE_INDEX_SYMBOLS:
        return "NSE_INDEX"
    elif base_symbol in BSE_INDEX_SYMBOLS:
        return "BSE_INDEX"
    else:
        return "NSE"

def calculate_option_greeks(option_symbol: str):
    base_symbol, expiry, strike, opt_type = parse_option_symbol(option_symbol)
    underlying_exchange = get_underlying_exchange(base_symbol)

    # Fetch spot and option price
    spot_price = client.quotes(symbol=base_symbol, exchange=underlying_exchange)['data']['ltp']
    option_price = client.quotes(symbol=option_symbol, exchange="NFO")['data']['ltp']

    # Time to expiry
    current_time = datetime.now()
    time_to_expiry = (expiry - current_time).total_seconds() / (60 * 60 * 24)

    # Implied Volatility calculation
    if opt_type == 'CE':
        iv_model = mibian.BS([spot_price, strike, 0, time_to_expiry], callPrice=option_price)
    else:
        iv_model = mibian.BS([spot_price, strike, 0, time_to_expiry], putPrice=option_price)

    implied_vol = iv_model.impliedVolatility

    # Greeks
    greek_model = mibian.BS([spot_price, strike, 0, time_to_expiry], implied_vol)

    # Output
    print(f"Base: {base_symbol}, Expiry: {expiry}, Strike: {strike}, Type: {opt_type}")
    print(f"Spot Price: {spot_price}")
    print(f"Option Price: {option_price}\n")
    print(f"Implied Volatility: {implied_vol:.2f}%")
    print(f"Delta: {greek_model.callDelta if opt_type == 'CE' else greek_model.putDelta}")
    print(f"Gamma: {greek_model.gamma}")
    print(f"Theta: {greek_model.callTheta if opt_type == 'CE' else greek_model.putTheta}")
    print(f"Vega: {greek_model.vega}")

# Example usage
calculate_option_greeks("NIFTY24APR2523800CE")
# calculate_option_greeks("RELIANCE24APR252400PE")  # For stock option

Sample Output

Base: NIFTY, Expiry: 2025-04-24 15:30:00, Strike: 23800, Type: CE
Spot Price: 23851.65
Option Price: 218.5

Implied Volatility: 15.21%
Delta: 0.546813421667412
Gamma: 0.0008239758429377188
Theta: -14.861372858158779
Vega: 12.52226125226098

How the script computes option Greeks in Python

Mibian’s Black-Scholes class takes a list of four inputs, [underlying price, strike, interest rate %, days to expiry], plus either a volatility or an observed option price:

  1. Parse the symbol: NIFTY24APR2523800CE becomes NIFTY, expiry 24 April 2025 at 15:30, strike 23800, call.
  2. Fetch prices: the underlying comes from NSE_INDEX or BSE_INDEX for indices and from NSE for stocks; the option comes from NFO.
  3. Time to expiry: measured in fractional calendar days up to 15:30 on expiry day, so the Greeks change through the session.
  4. Implied volatility: passing callPrice or putPrice makes Mibian solve for the volatility that reproduces the market price.
  5. Greeks: the model is rebuilt with that IV and the Greeks are read from it.

Reading the units correctly

GreekUnit in MibianMeaning in the sample output
DeltaChange in option price per ₹1 move in the underlying0.55: the call gains about ₹0.55 for a 1-point rise in NIFTY
GammaChange in Delta per ₹1 move0.00082: Delta rises by about 0.08 for a 100-point rally
ThetaChange in option price per calendar day-14.86: the option loses about ₹14.86 a day from time decay, all else equal
VegaChange in option price per 1 percentage point change in IV12.52: the option gains about ₹12.52 if IV rises from 15.2% to 16.2%

The script passes 0 as the interest rate. That keeps the example simple and has little effect on short-dated index options, but for longer expiries you can pass a risk-free rate such as a 91-day T-bill yield as the third input.


What This Script Does

Updating the example for current NSE contracts

The example symbol NIFTY24APR2523800CE expired in April 2025, so the script will fail on it today. Two exchange changes matter when you pick a live contract:

  • From 1 September 2025, NSE moved the expiry day of its index and stock derivatives to Tuesday (Business Today). The parser still works because it reads the date from the symbol, and it assumes the 15:30 close.
  • Since November 2024, NSE offers weekly options only on NIFTY. BANKNIFTY, FINNIFTY and MIDCPNIFTY now have monthly contracts only (Zerodha Z-Connect).

Use OpenAlgo’s symbol search or expiry API to get a valid contract, then replace the symbol in the last line of the script.

Alternative: OpenAlgo’s built-in optiongreeks() function

Since this tutorial was written, OpenAlgo has added an Option Greeks API. It returns IV, Delta, Gamma, Theta, Vega and Rho in one call, and it uses the Black-76 model on a forward price (a synthetic future for the same expiry where available) instead of Black-Scholes on spot. For index options, Black-76 on the forward is closer to how most professional option chains are quoted. The Python SDK wraps it as client.optiongreeks():

from openalgo import api

client = api(api_key="your-openalgo-apikey", host="http://127.0.0.1:5000")

# Black-76 Greeks and IV calculated by OpenAlgo (needs: pip install py_vollib)
greeks = client.optiongreeks(
    symbol="NIFTY25NOV2526000CE",   # replace with a live contract
    exchange="NFO",
    interest_rate=0.0,              # annualised %, set your own risk-free rate
    underlying_symbol="NIFTY",
    underlying_exchange="NSE_INDEX",
)
print(greeks)

The Mibian script is still the better learning tool, because you see each input and can change the model. For dashboards that scan many strikes, the built-in function (or the batch multioptiongreeks endpoint) is faster to wire up. Note that Mibian’s last release on PyPI was version 0.1.3 in 2016, so expect no further updates to it.

Common mistakes

  • Expired or misspelt symbols: the regex expects the OpenAlgo format BASE + DD + MMM + YY + STRIKE + CE/PE. Anything else raises “Invalid symbol format”.
  • Running after expiry time: once the clock passes 15:30 on expiry day, time to expiry turns negative and the IV solver fails.
  • Illiquid strikes: deep out-of-the-money options with stale LTPs give unrealistic IVs. Use the mid of bid and ask from client.depth() if the LTP is old.
  • Comparing with your broker’s numbers: small differences come from the model (Black-Scholes vs Black-76), the interest rate and whether spot or futures is used as the underlying.
  • Parses option symbols like NIFTY24APR2523800CE
  • Fetches real-time spot and option prices from OpenAlgo
  • Calculates days to expiry
  • Computes implied volatility and Option Greeks using Black-Scholes model
  • Supports both Call (CE) and Put (PE) options

Where You Can Take It From Here

You can now:

  • Extend this script to show full option chain analysis
  • Visualize Greeks in a dashboard.
  • Set up alerts when certain thresholds are breached (e.g., Delta > 0.7)

Next Steps

To see the same Greeks inside your charting platform, try the real-time option Greeks module for Amibroker or first and second order option Greeks in TradingView Pine Script. If IV is new to you, start with the difference between India VIX and implied volatility.

Frequently Asked Questions

Which Python library is best for option Greeks?

Mibian is the simplest for learning. py_vollib is faster and supports Black, Black-Scholes and Black-Scholes-Merton, and it is what OpenAlgo’s built-in Greeks use. For live NSE data without writing the model yourself, OpenAlgo’s optiongreeks() is the quickest route.

Why is my implied volatility different from the broker’s option chain?

Brokers often use futures or a synthetic forward as the underlying and a non-zero interest rate, while this script uses spot and 0%. Expiry time and the option price used (LTP or mid) also change the result.

Is Theta per day in Mibian?

Yes. Mibian divides annual Theta by 365, so the value is the expected change in option price for one calendar day.

Can I calculate option Greeks in Python for stock options?

Yes. Pass a stock option symbol such as RELIANCE with its expiry, strike and CE or PE. The script fetches the underlying from NSE automatically.

Python Elite membership

MEMBERSHIP

Python Elite membership

15 Python, AI and algo trading programs in one plan, including QuantFlow and AI Bootcamp live mentorship.

  • Python from fundamentals to trading apps
  • Backtesting, broker APIs and OpenAlgo
  • Live QuantFlow and AI Bootcamp sessions
View Python Elite →by Marketcalls

Learn by watching: free videos every week

Market Profile, order flow, Python, AI and OpenAlgo tutorials on YouTube.

Rajandran R Creator of OpenAlgo Sketchmaker, RagZ. Building GenAI Applications. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Now the recent curiosity on building Trading AI Agents.

Leave a Reply

Get Notifications, Alerts on Market Updates, Trading Tools, Automation & More