Rajandran R Creator of OpenAlgo - OpenSource Algo Trading framework for Indian Traders. 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. Strongly believe that market understanding and robust trading frameworks are the key to the trading success. Building Algo Platforms, Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in

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

2 min read

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 seamlessly for both call and put options and is ideal for building option dashboards, risk models, or trading signals.

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

  • 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

What This Script Does

  • 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)

Closing Thoughts

This example bridges real-time market data from OpenAlgo with the simplicity of Python and the power of options analytics via Mibian. You’re now equipped to incorporate Greeks into your trading decisions.

Rajandran R Creator of OpenAlgo - OpenSource Algo Trading framework for Indian Traders. 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. Strongly believe that market understanding and robust trading frameworks are the key to the trading success. Building Algo Platforms, Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in

Leave a Reply

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