Skip to main content

Black-Scholes option Greeks made easy - comprehensive Greek calculations for European options

Project description

greeks-package

Black-Scholes option Greeks made easy

Python 3.9+ License: MIT

A comprehensive Python package for calculating first-, second-, and third-order Greeks for European options using pure NumPy/SciPy implementations. No external Greeks library required – just clean, fast calculations with integrated option chain downloading from Yahoo Finance.

Features

  • Complete Greeks Suite: Delta, Gamma, Vega, Theta, Rho, Vanna, Volga, Charm, Veta, Color, Speed, Ultima, Zomma
  • Multi-Ticker Download: Download options for multiple stocks simultaneously with multi_download()
  • Enhanced Data Integration: Download calls, puts, or both together from Yahoo Finance
  • Flexible Usage: Calculate individual Greeks or all at once with convenient wrapper functions
  • Interactive Visualization: 3D plotting of Greeks surfaces using Plotly
  • Strategy Analysis: Multi-leg options strategy builder and analyzer
  • American Option Pricing (FDM): Crank–Nicolson + PSOR finite difference pricing for American calls and puts — scalar (gp.FDM) and vectorized row-level (gp.fdm_row) interfaces. Supports explicit FDM and European mode via cn / psor flags
  • Delta-Hedge Backtesting: Simulate delta hedging on a GBM path with full P&L decomposition, transaction costs, and built-in visualizations (gp.run_backtest, gp.plot_backtest, gp.plot_greeks)
  • Production Ready: Comprehensive error handling, type hints, and full documentation

Quick Start

import greeks_package as gp

# Download Apple call options within 30 days, ±5% moneyness
opts = gp.download_options("AAPL", opt_type="c", max_days=30)

# Calculate all Greeks in one line
all_greeks = opts.apply(gp.greeks, axis=1, ticker="AAPL")

# Combine with original data
full_data = opts.join(all_greeks)
print(full_data[['strike', 'lastPrice', 'Delta', 'Gamma', 'Vega', 'Theta']].head())

Installation

# From PyPI (when published)
pip install greeks-package

# From source (development)
git clone https://github.com/JRCon1/greeks-package.git
cd greeks-package
pip install -e .

Requirements: Python ≥ 3.9, NumPy, Pandas, SciPy, yfinance, Plotly, Matplotlib

Usage Examples

Multi-Ticker Download

import greeks_package as gp

# Download options for multiple tickers at once
tickers = ['AAPL', 'MSFT', 'GOOGL', 'TSLA']
multi_opts = gp.multi_download(
    ticker_symbols=tickers,
    opt_type="c",
    max_days=30,
    price=True  # Include stock prices
)

print(f"Downloaded {len(multi_opts)} options across {len(tickers)} tickers")

Calls and Puts Together

# Download both calls and puts simultaneously
opts = gp.download_options("TSLA", opt_type="all", max_days=60)

# Separate calls and puts
calls = opts[~opts['contractSymbol'].str.contains('P')]
puts = opts[opts['contractSymbol'].str.contains('P')]

print(f"Downloaded {len(calls)} calls and {len(puts)} puts")

Individual Greeks Calculation

opts = gp.download_options("MSFT", max_days=45)

# Calculate specific Greeks
opts['Delta'] = opts.apply(gp.delta, axis=1, ticker="MSFT")
opts['Gamma'] = opts.apply(gp.gamma, axis=1, ticker="MSFT")
opts['Vanna'] = opts.apply(gp.vanna, axis=1, ticker="MSFT")

Interactive Visualization

# 3D plots
gp.surf_scatter(opts, "AAPL", z="delta")      # Delta scatter plot
gp.surface_plot(opts, "AAPL", z="gamma")      # Gamma surface plot

gp.greek_plot(opts, greek_col="Delta")        # Greek vs time with strike selection
gp.iv_plot(opts, "AAPL")                      # Implied volatility term structure
gp.oi_plot(opts, "AAPL")                      # Open interest analysis
gp.vol_curve(opts, "AAPL")                    # Volatility smile/skew curves

Greek Orders Analysis

# Calculate Greeks by order
first_order = opts.apply(gp.first_order, axis=1, ticker="NVDA")    # Δ, Vega, Θ, Rho
second_order = opts.apply(gp.second_order, axis=1, ticker="NVDA")  # Γ, Vanna, Volga, Veta, Charm
third_order = opts.apply(gp.third_order, axis=1, ticker="NVDA")    # Color, Speed, Ultima, Zomma

# Combine all data
full_analysis = gp.comb(opts, first_order, second_order, third_order)

American Option Pricing (FDM)

# Scalar solver — one option per call, full result object
res = gp.FDM(685.74, 685.0, 0.1743, 0.0402, 321/365)                    # call (default)
res = gp.FDM(685.74, 685.0, 0.1743, 0.0402, 321/365, option_type="put")  # put
print(res.price, res.delta, res.gamma, res.theta_day)

# With Black–Scholes benchmark
res = gp.FDM(685.74, 685.0, 0.1743, 0.0402, 321/365, bs=True)

# Solver modes via cn / psor flags (default: cn=True, psor=True)
res = gp.FDM(..., cn=True,  psor=True)   # Crank–Nicolson + PSOR  (American, default)
res = gp.FDM(..., cn=True,  psor=False)  # Crank–Nicolson + Thomas (European FDM)
res = gp.FDM(..., cn=False, psor=True)   # Explicit + projection   (American explicit)
res = gp.FDM(..., cn=False, psor=False)  # Pure explicit            (European explicit)

# Row-level wrapper — price a DataFrame of options with FDM
fdm_cols = opts.apply(gp.fdm_row, axis=1, ticker="AAPL")
# Returns columns: FDM_Price, FDM_Delta, FDM_Gamma, FDM_Theta
full_data = gp.comb(opts, fdm_cols)

Delta-Hedge Backtesting

# Simulate a delta-hedge strategy on a GBM path
res = gp.run_backtest(
    S0=685.74,      # initial stock price
    K=685.0,        # strike
    sigma=0.1743,   # implied vol (used for FDM repricing)
    r=0.0402,       # risk-free rate
    T=321/365,      # time to expiry (years)
    sigma_real=0.20,  # realized vol for GBM path (optional; tests vol mismatch)
    dt=1/365,         # time step (daily)
    rebal_freq=1,     # rebalance every N steps
    seed=42,
)

print(f"Final P&L: ${res['final_pnl']:.2f}")
print(f"Total transaction costs: ${res['total_costs']:.2f}")

# Visualize results
gp.plot_backtest(res)   # stock price path + repriced option value
gp.plot_greeks(res)     # delta, gamma, theta, hedge shares over time

API Reference

Core Functions

Function Description Returns
download_options() Fetch & filter option chain from Yahoo Finance DataFrame
multi_download() Download options for multiple tickers DataFrame
greeks() Calculate all 13 Greeks at once Series
first_order() Calculate Δ, Vega, Θ, Rho Series
second_order() Calculate Γ, Vanna, Volga, Veta, Charm Series
third_order() Calculate Color, Speed, Ultima, Zomma Series

American Option Pricing (FDM)

Function Description Returns
FDM() Scalar American/European option solver (Crank–Nicolson + PSOR) Result object
fdm_row() Row-level FDM wrapper for use with DataFrame.apply(axis=1) Series

FDM result attributes: price, delta, gamma, theta_day, theta_ann, S_grid, V_grid

Delta-Hedge Backtesting

Function Description Returns
simulate_gbm() Generate a single GBM stock-price path ndarray
run_backtest() Delta-hedge backtest with FDM repricing and P&L decomposition dict
plot_backtest() Plot stock price path and repriced option value Figure
plot_greeks() Plot delta, gamma, theta, and hedge shares over time Figure

Individual Greeks

First Order: delta, vega, theta, rho
Second Order: gamma, vanna, volga, veta, charm
Third Order: color, speed, ultima, zomma

Submodules

Submodule Description
gp.pricing Black–Scholes and Monte Carlo pricing (bsm_price, monte_carlo_price)
gp.plotting All visualization helpers (surf_scatter, surface_plot, greek_plot, iv_plot, etc.)
gp.fdm American/European FDM pricing – gp.FDM (scalar) and gp.fdm_row (row-level)
gp.backtest Delta-hedge backtesting – run_backtest, plot_backtest, plot_greeks

Utilities & Visualization

Function Description
comb() Combine multiple DataFrames with automatic column handling
surf_scatter() Interactive 3D scatter plots
surface_plot() Smooth 3D surface plots
greek_plot() Greek values vs time with strike selection
iv_plot() Implied volatility term structure
oi_plot() Open interest distribution analysis
vol_curve() Volatility smile/skew curves
bsm_price() Black-Scholes theoretical pricing
monte_carlo_price() Monte Carlo option pricing
strategy_builder() Multi-leg options strategy analysis

Function Signatures

All Greek functions follow the same pattern:

function_name(row: pd.Series, ticker: str, option_type: str = 'c', 
              r: float = 0.05, eps: float = 1e-9) -> float

Multi-download signature:

multi_download(ticker_symbols: List[str], opt_type: str = 'c', 
               max_days: int = 60, lower_moneyness: float = 0.95,
               upper_moneyness: float = 1.05, price: bool = False) -> pd.DataFrame

FDM scalar solver signature:

FDM(S0, K, sigma, r, T,
    NAS=200, NTS=2000, S_max_mult=4.0, rannacher=4,
    omega=1.2, tol=1e-8, max_iter=5000,
    bs=False, option_type="call", silent=False,
    cn=True, psor=True)

fdm_row (DataFrame row-level) signature:

fdm_row(row: pd.Series, ticker: str, option_type: str = 'call',
        r: float = 0.05, NAS: int = 200, NTS: int = 2000,
        cn: bool = True, psor: bool = True) -> pd.Series
# Returns: FDM_Price, FDM_Delta, FDM_Gamma, FDM_Theta

run_backtest signature:

run_backtest(S0, K, sigma, r, T,
             sigma_real=None, dt=1/365, rebal_freq=1,
             cost_per_share=0.00003, seed=42,
             cn=True, psor=True,
             fdm_nas=200, fdm_nts=1000,
             verbose=True) -> dict

📊 Comprehensive Examples

See examples.py for complete usage demonstrations including:

  1. Basic Options Greeks Calculation
  2. Calls and Puts Together - Using opt_type="all"
  3. Multi-Ticker Download - Using multi_download()
  4. Multi-Download with Calls & Puts
  5. Individual Greeks Selection
  6. 3D Visualization
  7. Strategy Analysis

Run examples:

python examples.py           # Run all examples
python examples.py 3         # Run multi-download example
python examples.py 2         # Run calls/puts example

📚 Documentation

  • USAGE.md: Detailed function reference and advanced usage patterns
  • examples.py: Complete working examples for all major features
  • Interactive Help: Use gp.help() for in-package documentation

🧮 Greek Formulas

This package implements standard Black-Scholes Greeks:

  • Delta (Δ): ∂V/∂S - Price sensitivity to underlying
  • Gamma (Γ): ∂²V/∂S² - Delta sensitivity to underlying
  • Vega (ν): ∂V/∂σ - Price sensitivity to volatility
  • Theta (Θ): ∂V/∂t - Time decay
  • Rho (ρ): ∂V/∂r - Interest rate sensitivity

Plus advanced second and third-order Greeks for sophisticated risk management.

Performance

  • Vectorized Operations: Efficient NumPy/SciPy implementations
  • Minimal Dependencies: No external Greeks libraries required
  • Memory Efficient: Designed for large option chains
  • Fast Execution: Optimized for production use

🤝 Contributing

Contributions welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

Author

JR Concepcion

Built using NumPy, Pandas, SciPy, yfinance, Plotly, and Matplotlib.


Quick Reference

import greeks_package as gp

# Basic workflow
opts = gp.download_options("AAPL", opt_type="c", max_days=30)
greeks_data = opts.apply(gp.greeks, axis=1, ticker="AAPL")
full_data = opts.join(greeks_data)

# Individual Greeks
opts['Delta'] = opts.apply(gp.delta, axis=1, ticker="AAPL")
opts['Vanna'] = opts.apply(gp.vanna, axis=1, ticker="AAPL")

# Visualization
gp.surf_scatter(opts, "AAPL", z="delta")
gp.surface_plot(opts, "AAPL", z="impliedVolatility")

# American option pricing (FDM – scalar)
res = gp.FDM(685.74, 685.0, 0.1743, 0.0402, 321/365)
print(res.price, res.delta, res.gamma, res.theta_day)

# FDM on a DataFrame (row-level)
fdm_cols = opts.apply(gp.fdm_row, axis=1, ticker="AAPL")
full_data = gp.comb(opts, fdm_cols)

# Delta-hedge backtest
res = gp.run_backtest(685.74, 685.0, 0.1743, 0.0402, 321/365)
gp.plot_backtest(res)
gp.plot_greeks(res)

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

greeks_package-1.2.0.tar.gz (39.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

greeks_package-1.2.0-py3-none-any.whl (36.1 kB view details)

Uploaded Python 3

File details

Details for the file greeks_package-1.2.0.tar.gz.

File metadata

  • Download URL: greeks_package-1.2.0.tar.gz
  • Upload date:
  • Size: 39.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.10

File hashes

Hashes for greeks_package-1.2.0.tar.gz
Algorithm Hash digest
SHA256 9f08f21f01980ffd806d13bed22a7047907da4342765b4a6059d71240ba63f0d
MD5 5bb1b03af6072c633a36179b13d798fc
BLAKE2b-256 e4f3e0d58e9a4bd6b9a9d376f79b7902b078e6194b1789f0a69a0d57c759ce01

See more details on using hashes here.

File details

Details for the file greeks_package-1.2.0-py3-none-any.whl.

File metadata

  • Download URL: greeks_package-1.2.0-py3-none-any.whl
  • Upload date:
  • Size: 36.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.10

File hashes

Hashes for greeks_package-1.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 7c7872341b46b03e56dadaf3835b12fd60bdd91f35ca8d0e0f447f12dfac70d4
MD5 f766cc25d0093d3341d4379e9155c1d7
BLAKE2b-256 f55fdb86e431f3c541cbf0a586f638302053f6d68fe938f35ff143b6ab22a0ee

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page