CodeForFinance
Quant Concepts

Options Pricing Calculator in Python

Build a Black-Scholes options pricing calculator with Greeks visualisation.

Black-Scholes Formula

import numpy as np
from scipy.stats import norm

def black_scholes(S, K, T, r, sigma, option_type="call"):
    d1 = (np.log(S/K) + (r + sigma**2/2) * T) / (sigma * np.sqrt(T))
    d2 = d1 - sigma * np.sqrt(T)
    
    if option_type == "call":
        price = S * norm.cdf(d1) - K * np.exp(-r * T) * norm.cdf(d2)
    else:
        price = K * np.exp(-r * T) * norm.cdf(-d2) - S * norm.cdf(-d1)
    
    # Greeks
    delta = norm.cdf(d1) if option_type == "call" else norm.cdf(d1) - 1
    gamma = norm.pdf(d1) / (S * sigma * np.sqrt(T))
    theta = -(S * norm.pdf(d1) * sigma) / (2 * np.sqrt(T)) / 365
    vega = S * norm.pdf(d1) * np.sqrt(T) / 100
    
    return {"price": price, "delta": delta, "gamma": gamma, "theta": theta, "vega": vega}

# Example: AAPL call option
result = black_scholes(S=180, K=185, T=0.25, r=0.05, sigma=0.25)
for k, v in result.items():
    print(f"{k:>8}: {v:.4f}")

Developer Essentials

As an Amazon Associate we may earn from qualifying purchases.