Skip to main content

Implementing Black-Scholes in Python from Scratch: A Complete 2026 Guide

If you’ve ever traded options, used a retail broker’s analytics dashboard, or worked in quantitative finance, you’ve used the Black-Scholes (Black-Scholes-Merton) model—whether you knew it or not. First published in 1973, this mathematical framework remains the global baseline for pricing European-style options, and implementing it from scratch in Python is a rite of passage for every quant developer, data scientist, and active options trader.

Beyond being a foundational skill, building your own Black-Scholes implementation lets you validate broker quotes, calibrate custom volatility surfaces, and integrate options pricing into trading algorithms without relying on closed-source tools. In this guide, we’ll build a full, production-ready implementation, including option Greeks, implied volatility calculation, and best practices to avoid costly mistakes.

Tom Roberts

By · Editor, Quantopia

Published · Updated

Table of Contents#

  1. Core Concepts of the Black-Scholes Model
  2. Pre-Requisites for Python Implementation
  3. Step 1: Build the Black-Scholes Pricing Function
  4. Step 2: Implement Option Greeks in Python
  5. Step 3: Calculate Implied Volatility with the Newton-Raphson Method
  6. Common Pitfalls & Best Practices
  7. How Black-Scholes Compares to Alternative Pricing Models
  8. 2026 Trends in Option Pricing Built on Black-Scholes
  9. Conclusion & Next Steps
  10. References

Core Concepts of the Black-Scholes Model#

The Black-Scholes model is a mathematical framework for pricing European options (contracts that can only be exercised at their expiration date) under the following core assumptions:

  • The underlying asset price follows geometric Brownian motion (GBM) with constant drift and volatility
  • Markets are frictionless (no transaction costs, no restrictions on short selling)
  • The risk-free interest rate is constant
  • The underlying asset pays no dividends (adjustable for dividend-paying assets, as we’ll cover later)

Pricing Formulas#

For a non-dividend paying asset, the model calculates call and put option prices as follows:

Call Option Price (CC)#

C=S0N(d1)−Ke−rTN(d2)C = S_0 N(d_1) - K e^{-rT} N(d_2)

Put Option Price (PP)#

P=Ke−rTN(−d2)−S0N(−d1)P = K e^{-rT} N(-d_2) - S_0 N(-d_1)

For dividend-paying assets, apply the Merton adjustment by replacing S0S_0 with S0e−qTS_0 e^{-qT}, where qq is the annualized continuous dividend yield.

Where:

VariableDefinition
S0S_0Current spot price of the underlying asset
KKStrike price (price the asset can be bought/sold at expiry)
rrAnnualized continuously compounded risk-free interest rate
TTTime to maturity, measured in years
σ\sigmaAnnualized volatility of the underlying asset's log returns
qqAnnualized continuous dividend yield of the underlying asset
N(x)N(x)Cumulative distribution function (CDF) of the standard normal distribution N(0,1)\mathcal{N}(0,1)
n(x)n(x)Probability density function (PDF) of the standard normal distribution N(0,1)\mathcal{N}(0,1)

The terms d1d_1 and d2d_2 are calculated as: d1=ln⁡(S0/K)+(r+σ22)TσTd_1 = \frac{\ln(S_0 / K) + \left(r + \frac{\sigma^2}{2}\right)T}{\sigma \sqrt{T}} d2=d1−σTd_2 = d_1 - \sigma \sqrt{T}


Pre-Requisites for Python Implementation#

We’ll use two core Python libraries for this implementation:

  • numpy for fast vectorized mathematical operations
  • scipy for the standard normal CDF and PDF functions

Install them via pip if you haven’t already:

pip install numpy scipy

Import them at the top of your script:

import numpy as np
from scipy.stats import norm

Step 1: Build the Black-Scholes Pricing Function#

We’ll first write a flexible pricing function that supports both call and put options, with optional adjustments for dividend-paying assets.

Full Implementation Code#

def black_scholes(
    S0: float,
    K: float,
    r: float,
    T: float,
    sigma: float,
    option_type: str = "call",
    include_dividend: bool = False,
    q: float = 0.0
) -> float:
    """
    Calculate Black-Scholes price for a European option.
    
    Args:
        S0: Current spot price of underlying asset
        K: Strike price
        r: Annualized risk-free rate (decimal, e.g. 0.045 = 4.5%)
        T: Time to maturity in years
        sigma: Annualized volatility of underlying (decimal, e.g. 0.25 = 25%)
        option_type: "call" or "put", defaults to "call"
        include_dividend: If True, apply Merton dividend adjustment
        q: Annualized continuous dividend yield, required if include_dividend=True
    
    Returns:
        float: Option price
    """
    # Input validation for edge cases
    if T <= 0:
        # Return intrinsic value at expiry
        if option_type == "call":
            return max(S0 - K, 0)
        else:
            return max(K - S0, 0)
    if sigma <= 0:
        raise ValueError("Volatility (sigma) must be greater than 0")
    if option_type not in ["call", "put"]:
        raise ValueError("option_type must be either 'call' or 'put'")
    
    # Apply dividend adjustment if enabled
    S = S0 * np.exp(-q * T) if include_dividend else S0
    
    # Calculate d1 and d2
    sqrt_T = np.sqrt(T)
    d1 = (np.log(S / K) + (r + 0.5 * sigma ** 2) * T) / (sigma * sqrt_T)
    d2 = d1 - sigma * sqrt_T
    
    # Calculate option price
    discount_factor = np.exp(-r * T)
    if option_type == "call":
        price = S * norm.cdf(d1) - K * discount_factor * norm.cdf(d2)
    else:
        price = K * discount_factor * norm.cdf(-d2) - S * norm.cdf(-d1)
    
    return price

Practical Example#

Let’s test this function with a real-world scenario: AAPL is trading at 190,wewanttopricea3−monthcalloptionwitha190, we want to price a 3-month call option with a 200 strike, 4.5% risk-free rate, and 25% annualized volatility.

# Test the function
call_price = black_scholes(S0=190, K=200, r=0.045, T=0.25, sigma=0.25, option_type="call")
put_price = black_scholes(S0=190, K=200, r=0.045, T=0.25, sigma=0.25, option_type="put")
 
print(f"Call Price: ${call_price:.2f}")
print(f"Put Price: ${put_price:.2f}")

Output:#

Call Price: $6.07
Put Price: $13.84

This means the fair value of the call option is ~6.07,andtheputis 6.07, and the put is ~13.84.


Step 2: Implement Option Greeks in Python#

Option Greeks measure the sensitivity of an option’s price to changes in underlying parameters, and are critical for risk management and hedging. We’ll extend our implementation to return the 5 core Greeks, with full support for dividend adjustments:

GreekDefinitionFormula (dividend-adjusted)
Delta (Δ\Delta)Sensitivity to changes in the underlying spot priceCall: e−qTN(d1)e^{-qT}N(d_1)
Put: e−qT(N(d1)−1)e^{-qT}(N(d_1) - 1)
Gamma (Γ\Gamma)Sensitivity of Delta to changes in spot price (same for calls/puts)e−qTn(d1)S0σT\frac{e^{-qT}n(d_1)}{S_0 \sigma \sqrt{T}} where n(x)n(x) = normal PDF
Vega (ν\nu)Sensitivity to changes in volatility (same for calls/puts)S0e−qTn(d1)TS_0 e^{-qT} n(d_1) \sqrt{T} (typically divided by 100 for 1% vol changes)
Theta (θ\theta)Sensitivity to time decay (time to maturity)Call: −S0e−qTn(d1)σ2T+qS0e−qTN(d1)−rKe−rTN(d2)- \frac{S_0 e^{-qT} n(d_1) \sigma}{2 \sqrt{T}} + q S_0 e^{-qT} N(d_1) - r K e^{-rT} N(d_2) (divided by 252/365 for daily decay)
Put: −S0e−qTn(d1)σ2T−qS0e−qTN(−d1)+rKe−rTN(−d2)- \frac{S_0 e^{-qT} n(d_1) \sigma}{2 \sqrt{T}} - q S_0 e^{-qT} N(-d_1) + r K e^{-rT} N(-d_2) (divided by 252/365 for daily decay)
Rho (ρ\rho)Sensitivity to changes in the risk-free rateCall: KTe−rTN(d2)K T e^{-rT} N(d_2)
Put: −KTe−rTN(−d2)- K T e^{-rT} N(-d_2) (typically divided by 100 for 1% rate changes)

Greek Calculation Function#

def black_scholes_greeks(
    S0: float,
    K: float,
    r: float,
    T: float,
    sigma: float,
    option_type: str = "call",
    include_dividend: bool = False,
    q: float = 0.0,
    annualize_days: int = 252
) -> dict:
    """
    Calculate core dividend-adjusted option Greeks for a European option.
    
    Args:
        annualize_days: Number of days to use for daily theta calculation (252 = trading days, 365 = calendar days)
    """
    # Handle edge case T=0 (expired option)
    if T <= 0:
        delta = 1 if (option_type == "call" and S0 > K) else (-1 if (option_type == "put" and S0 < K) else 0)
        return {"delta": delta, "gamma": 0, "vega": 0, "theta": 0, "rho": 0}
    
    # Input validation
    if sigma <= 0:
        raise ValueError("Volatility (sigma) must be greater than 0")
    if option_type not in ["call", "put"]:
        raise ValueError("option_type must be either 'call' or 'put'")
    
    # Calculate discount factors
    div_discount = np.exp(-q * T) if include_dividend else 1.0
    risk_free_discount = np.exp(-r * T)
    
    # Calculate d1, d2 and normal PDF/CDF values
    S = S0 * div_discount
    sqrt_T = np.sqrt(T)
    d1 = (np.log(S / K) + (r + 0.5 * sigma ** 2) * T) / (sigma * sqrt_T)
    d2 = d1 - sigma * sqrt_T
    pdf_d1 = norm.pdf(d1)
    cdf_d1 = norm.cdf(d1)
    cdf_d2 = norm.cdf(d2)
    
    # Calculate Greeks
    delta = div_discount * cdf_d1 if option_type == "call" else div_discount * (cdf_d1 - 1)
    gamma = (div_discount * pdf_d1) / (S0 * sigma * sqrt_T)
    vega = (S0 * div_discount * pdf_d1 * sqrt_T) / 100  # Scaled for 1% volatility change
    rho = (K * T * risk_free_discount * cdf_d2) / 100 if option_type == "call" else (-K * T * risk_free_discount * norm.cdf(-d2)) / 100  # Scaled for 1% rate change
    
    if option_type == "call":
        theta = (- (S0 * div_discount * pdf_d1 * sigma) / (2 * sqrt_T) + q * S0 * div_discount * cdf_d1 - r * K * risk_free_discount * cdf_d2) / annualize_days
    else:
        theta = (- (S0 * div_discount * pdf_d1 * sigma) / (2 * sqrt_T) - q * S0 * div_discount * norm.cdf(-d1) + r * K * risk_free_discount * norm.cdf(-d2)) / annualize_days
    
    return {
        "delta": round(delta, 4),
        "gamma": round(gamma, 4),
        "vega": round(vega, 4),
        "theta": round(theta, 4),
        "rho": round(rho, 4)
    }

Test the Greeks Function#

Using the same AAPL example as before:

greeks = black_scholes_greeks(S0=190, K=200, r=0.045, T=0.25, sigma=0.25)
print(greeks)

Output:#

{'delta': 0.3867, 'gamma': 0.0213, 'vega': 0.2403, 'theta': -0.0286, 'rho': 0.0846}

This means for every 1increaseinAAPL’sprice,thecallvaluerisesby 1 increase in AAPL’s price, the call value rises by ~0.39, and it loses ~$0.03 in value per day from time decay.


Step 3: Calculate Implied Volatility with the Newton-Raphson Method#

Volatility is the only Black-Scholes input that is not directly observable in the market. Traders calculate implied volatility (IV) by inverting the Black-Scholes formula to match observed market option prices. Since the formula cannot be inverted analytically, we use the iterative Newton-Raphson method, with fallback to bisection for edge cases, and pre-checks for arbitrage bounds:

σn+1=σn+Market Price−Black-Scholes Price(σn)Vega(σn)\sigma_{n+1} = \sigma_n + \frac{\text{Market Price} - \text{Black-Scholes Price}(\sigma_n)}{\text{Vega}(\sigma_n)}

Implied Volatility Implementation#

def implied_volatility(
    market_price: float,
    S0: float,
    K: float,
    r: float,
    T: float,
    option_type: str = "call",
    include_dividend: bool = False,
    q: float = 0.0,
    max_iter: int = 100,
    tol: float = 1e-5,
    initial_guess: float = 0.5
) -> float:
    """
    Calculate implied volatility from market option price using Newton-Raphson method with bisection fallback.
    
    Args:
        market_price: Observed market price of the option
        max_iter: Maximum number of iterations
        tol: Convergence tolerance
        initial_guess: Starting value for sigma (default 0.5 = 50%)
    
    Returns:
        float: Implied volatility (decimal)
    """
    # Input validation
    if T <= 0:
        raise ValueError("Time to maturity (T) must be greater than 0 to calculate IV")
    if market_price <= 0:
        raise ValueError("Market price must be greater than 0")
    if option_type not in ["call", "put"]:
        raise ValueError("option_type must be either 'call' or 'put'")
    
    # Calculate arbitrage bounds to validate market price
    div_discount = np.exp(-q * T) if include_dividend else 1.0
    risk_free_discount = np.exp(-r * T)
    S_adj = S0 * div_discount
    K_adj = K * risk_free_discount
    
    if option_type == "call":
        lower_bound = max(S_adj - K_adj, 0)
        upper_bound = S_adj
    else:
        lower_bound = max(K_adj - S_adj, 0)
        upper_bound = K_adj
    
    if market_price < lower_bound or market_price > upper_bound:
        raise ValueError(f"Market price {market_price:.2f} is outside arbitrage bounds [{lower_bound:.2f}, {upper_bound:.2f}]. No valid IV exists.")
    
    sigma = initial_guess
    for _ in range(max_iter):
        bs_price = black_scholes(S0, K, r, T, sigma, option_type, include_dividend, q)
        vega = black_scholes_greeks(S0, K, r, T, sigma, option_type, include