Of course! Here is a comprehensive implementation of the Black-Scholes formulas in Python, covering both high-precision numerical methods with mpmath and symbolic manipulation with sympy.
1. The Black-Scholes Formulas
First, let's state the formulas we are implementing. The Black-Scholes model prices European-style options.
Key Variables:
S: Current price of the underlying asset (e.g., stock price)
K: Strike price of the option
T: Time to expiration (in years)
r: Risk-free interest rate (annual)
σ (sigma): Volatility of the underlying asset's returns (annual)
q: Continuous dividend yield (annual)
Core Formulas:
The d1 and d2 terms are calculated first:
d1=σTln(S/K)+(r−q+d2=d1−σT
Where N(x) is the Cumulative Distribution Function (CDF) of the standard normal distribution.
Call Option Price (C):C=Se−qTN(d1)−
Put Option Price (P):P=Ke−rTN(−d2)−
2. Setup
First, ensure you have the required libraries installed.
pip install mpmath sympy
3. Numerical Implementation with mpmath
The mpmath library is excellent for numerical calculations because it provides arbitrary-precision arithmetic and includes special mathematical functions like the normal CDF (ncdf), which are crucial for accuracy in financial models.
Why mpmath?
High Precision: Avoids floating-point errors that can occur with standard Python floats, especially with extreme values or long-dated options.
Built-in Functions: Provides numerically stable implementations of functions like log, exp, sqrt, and ncdf.
Implementation:
import mpmath
def black_scholes_mpmath(S, K, T, r, sigma, q=0, option_type='call'):
"""
Calculates the Black-Scholes option price using the mpmath library for high precision.
Args:
S (float): Current stock price
K (float): Option strike price
T (float): Time to maturity in years
r (float): Risk-free interest rate (annual)
sigma (float): Volatility of the stock (annual)
q (float): Continuous dividend yield (default is 0)
option_type (str): 'call' or 'put'
Returns:
mpmath.mpf: The price of the option.
"""
# Set precision for mpmath calculations
mpmath.mp.dps = 50 # dps = decimal places
# Convert inputs to mpmath floats for precision
S, K, T, r, sigma, q = map(mpmath.mpf, [S, K, T, r, sigma, q])
# Calculate d1 and d2
d1 = (mpmath.log(S / K) + (r - q + 0.5 * sigma**2) * T) / (sigma * mpmath.sqrt(T))
d2 = d1 - sigma * mpmath.sqrt(T)
if option_type.lower() == 'call':
# Calculate call price using the formula: S*e^(-qT)*N(d1) - K*e^(-rT)*N(d2)
price = S * mpmath.exp(-q * T) * mpmath.ncdf(d1) - K * mpmath.exp(-r * T) * mpmath.ncdf(d2)
elif option_type.lower() == 'put':
# Calculate put price using the formula: K*e^(-rT)*N(-d2) - S*e^(-qT)*N(-d1)
price = K * mpmath.exp(-r * T) * mpmath.ncdf(-d2) - S * mpmath.exp(-q * T) * mpmath.ncdf(-d1)
else:
raise ValueError("Invalid option type. Choose 'call' or 'put'.")
return price
# --- Example Usage ---
print("--- Numerical Calculation with mpmath ---")
# Parameters
stock_price = 100
strike_price = 105
time_to_expiry = 1.0 # 1 year
risk_free_rate = 0.05 # 5%
volatility = 0.20 # 20%
dividend_yield = 0.01 # 1%
# Calculate Call and Put prices
call_price_numerical = black_scholes_mpmath(
S=stock_price, K=strike_price, T=time_to_expiry, r=risk_free_rate, sigma=volatility, q=dividend_yield, option_type='call'
)
put_price_numerical = black_scholes_mpmath(
S=stock_price, K=strike_price, T=time_to_expiry, r=risk_free_rate, sigma=volatility, q=dividend_yield, option_type='put'
)
print(f"Stock Price: ${stock_price}")
print(f"Strike Price: ${strike_price}")
print(f"Time to Expiry: {time_to_expiry} years")
print(f"Risk-Free Rate: {risk_free_rate:.2%}")
print(f"Volatility: {volatility:.2%}")
print("-" * 20)
print(f"Call Option Price: ${call_price_numerical:.4f}")
print(f"Put Option Price: ${put_price_numerical:.4f}")
4. Symbolic Implementation with sympy
The sympy library is used for symbolic mathematics. Instead of calculating a numerical answer, it manipulates the formulas themselves. This is incredibly powerful for deriving formulas, understanding their structure, and calculating derivatives (the "Greeks").
Why sympy?
Formula Derivation: See the exact mathematical form of the price.
Analytical Derivatives: Calculate the Greeks (Delta, Gamma, Vega, Theta, Rho) by differentiating the symbolic price formula.
Educational Tool: Helps in understanding the mathematical relationships between variables.
Implementation:
import sympy
from sympy import Symbol, exp, log, sqrt, pi, erf
# To display formulas nicely in environments like Jupyter notebooks
sympy.init_printing(use_unicode=True)
def black_scholes_sympy():
"""
Constructs the Black-Scholes formulas symbolically using the sympy library.
Returns:
(sympy.Expr, sympy.Expr): A tuple containing the symbolic formulas for
the call price and the put price.
"""
# Define symbols for the variables. We assume they are positive real numbers.
S, K, T, r, sigma, q = sympy.symbols('S K T r sigma q', real=True, positive=True)
# Define the Standard Normal CDF N(x) using the error function (erf)
# N(x) = 1/2 * (1 + erf(x / sqrt(2)))
def N(x):
return (1 + erf(x / sqrt(2))) / 2
# Define d1 and d2 symbolically
d1 = (log(S / K) + (r - q + sigma**2 / 2) * T) / (sigma * sqrt(T))
d2 = d1 - sigma * sqrt(T)
# Define the call and put price formulas symbolically
call_price_formula = S * exp(-q * T) * N(d1) - K * exp(-r * T) * N(d2)
put_price_formula = K * exp(-r * T) * N(-d2) - S * exp(-q * T) * N(-d1)
return call_price_formula, put_price_formula
# --- Example Usage ---
print("\n\n--- Symbolic Calculation with sympy ---")
# Get the symbolic formulas
call_formula, put_formula = black_scholes_sympy()
print("Symbolic Call Price Formula:")
sympy.pprint(call_formula)
print("\nSymbolic Put Price Formula:")
sympy.pprint(put_formula)
# --- 1. Evaluate the symbolic formula with numerical values ---
# We can substitute our numerical values into the symbolic expression
print("\n--- Evaluating the symbolic formula ---")
# Define the symbols again for substitution mapping
S, K, T, r, sigma, q = sympy.symbols('S K T r sigma q')
# Create a dictionary of values
values = {
S: 100, K: 105, T: 1.0, r: 0.05, sigma: 0.20, q: 0.01
}
# Substitute values and evaluate to a float
call_price_from_symbolic = call_formula.subs(values).evalf()
put_price_from_symbolic = put_formula.subs(values).evalf()
print(f"Evaluated Call Price: ${float(call_price_from_symbolic):.4f}")
print(f"Evaluated Put Price: ${float(put_price_from_symbolic):.4f}")
# --- 2. Derive a 'Greek' - Delta (the derivative with respect to S) ---
print("\n--- Deriving a Greek (Delta) symbolically ---")
# Delta is the first derivative of the option price with respect to the stock price S
call_delta_formula = sympy.diff(call_formula, S)
print("Symbolic Call Delta Formula:")
# Simplify the expression for better readability
simplified_delta = sympy.simplify(call_delta_formula)
sympy.pprint(simplified_delta)
# Evaluate the Delta formula
call_delta_value = simplified_delta.subs(values).evalf()
print(f"\nEvaluated Call Delta: {float(call_delta_value):.4f}")
5. Summary: mpmath vs. sympy
Feature
mpmath (Numerical)
sympy (Symbolic)
Primary Use
Calculating precise numerical values.
Manipulating and analyzing mathematical formulas.
Output
A high-precision number (e.g., mpmath.mpf).
A symbolic expression (e.g., sympy.Expr).
Speed
Generally faster for pure numerical evaluation.
Slower for evaluation, but invaluable for derivation.
Key Advantage
Accuracy and avoidance of floating-point errors.
Ability to perform calculus (derivatives, integrals).