This is a comprehensive request for implementing Monte Carlo simulation for option pricing. Let me break it down:
Here's a comprehensive implementation with vectorization, convergence analysis, and Black-Scholes comparison:
python Copy code
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
from scipy.optimize import minimize_scalar
import time
class EuropeanOptionPricer:
"""Price European options using Monte Carlo and Black-Scholes."""
def __init__(self, S0, K, T, r, sigma, seed=42):
"""
Parameters:
-----------
S0 : float - Initial stock price
K : float - Strike price
T : float - Time to maturity (years)
r : float - Risk-free rate
sigma : float - Volatility (annualized)
seed : int - Random seed for reproducibility
"""
self.S0 = S0
self.K = K
self.T = T
self.r = r
self.sigma = sigma
self.seed = seed
np.random.seed(seed)
# ==================== BLACK-SCHOLES ====================
def black_scholes_call(self):
"""Analytical Black-Scholes call option price."""
d1 = (np.log(self.S0 / self.K) +
(self.r + 0.5 * self.sigma**2) * self.T) / \
(self.sigma * np.sqrt(self.T))
d2 = d1 - self.sigma * np.sqrt(self.T)
call_price = (self.S0 * norm.cdf(d1) -
self.K * np.exp(-self.r * self.T) * norm.cdf(d2))
return call_price
def black_scholes_put(self):
"""Analytical Black-Scholes put option price."""
d1 = (np.log(self.S0 / self.K) +
(self.r + 0.5 * self.sigma**2) * self.T) / \
(self.sigma * np.sqrt(self.T))
d2 = d1 - self.sigma * np.sqrt(self.T)
put_price = (self.K * np.exp(-self.r * self.T) * norm.cdf(-d2) -
self.S0 * norm.cdf(-d1))
return put_price
def black_scholes_greeks(self):
"""Calculate Black-Scholes Greeks."""
d1 = (np.log(self.S0 / self.K) +
(self.r + 0.5 * self.sigma**2) * self.T) / \
(self.sigma * np.sqrt(self.T))
d2 = d1 - self.sigma * np.sqrt(self.T)
delta = norm.cdf(d1)
gamma = norm.pdf(d1) / (self.S0 * self.sigma * np.sqrt(self.T))
vega = self.S0 * norm.pdf(d1) * np.sqrt(self.T) / 100
theta = (-self.S0 * norm.pdf(d1) * self.sigma / (2 * np.sqrt(self.T)) -
self.r * self.K * np.exp(-self.r * self.T) * norm.cdf(d2)) / 365
rho = self.K * self.T * np.exp(-self.r * self.T) * norm.cdf(d2) / 100
return {'delta': delta, 'gamma': gamma, 'vega': vega,
'theta': theta, 'rho': rho}
# ==================== MONTE CARLO ====================
def simulate_gbm_paths(self, n_paths, n_steps):
"""
Simulate GBM paths using vectorized approach.
dS = μ*S*dt + σ*S*dW
Parameters:
-----------
n_paths : int - Number of simulation paths
n_steps : int - Number of time steps
Returns:
--------
S : ndarray of shape (n_steps+1, n_paths) - Stock price paths
"""
dt = self.T / n_steps
# Initialize price matrix
S = np.zeros((n_steps + 1, n_paths))
S[0] = self.S0
# Pre-generate all random numbers
Z = np.random.standard_normal((n_steps, n_paths))
# Vectorized simulation
for t in range(1, n_steps + 1):
S[t] = S[t-1] * np.exp(
(self.r - 0.5 * self.sigma**2) * dt +
self.sigma * np.sqrt(dt) * Z[t-1]
)
return S
def simulate_gbm_terminal(self, n_paths):
"""
Faster method: only simulate terminal prices.
S(T) = S0 * exp((μ - σ²/2)*T + σ*√T*Z)
"""
Z = np.random.standard_normal(n_paths)
ST = self.S0 * np.exp(
(self.r - 0.5 * self.sigma**2) * self.T +
self.sigma * np.sqrt(self.T) * Z
)
return ST
def monte_carlo_call(self, n_paths=100000, method='terminal'):
"""
Price European call using Monte Carlo.
Parameters:
-----------
n_paths : int - Number of simulation paths
method : str - 'terminal' (fast) or 'full' (tracks paths)
Returns:
--------
price : float - Option price
se : float - Standard error
"""
if method == 'terminal':
ST = self.simulate_gbm_terminal(n_paths)
else:
S = self.simulate_gbm_paths(n_paths, 252)
ST = S[-1]
# Terminal payoff
payoff = np.maximum(ST - self.K, 0)
# Discounted expected value
price = np.exp(-self.r * self.T) * np.mean(payoff)
# Standard error
se = np.std(payoff) / np.sqrt(n_paths) * np.exp(-self.r * self.T)
return price, se
def monte_carlo_put(self, n_paths=100000):
"""Price European put using Monte Carlo."""
ST = self.simulate_gbm_terminal(n_paths)
payoff = np.maximum(self.K - ST, 0)
price = np.exp(-self.r * self.T) * np.mean(payoff)
se = np.std(payoff) / np.sqrt(n_paths) * np.exp(-self.r * self.T)
return price, se
def monte_carlo_greeks(self, n_paths=100000, bump_size=0.01):
"""Calculate Greeks using finite differences."""
price_base, _ = self.monte_carlo_call(n_paths)
# Delta: dPrice/dS
original_S0 = self.S0
self.S0 = original_S0 + bump_size
price_up, _ = self.monte_carlo_call(n_paths)
self.S0 = original_S0 - bump_size
price_down, _ = self.monte_carlo_call(n_paths)
self.S0 = original_S0
delta = (price_up - price_down) / (2 * bump_size)
gamma = (price_up - 2*price_base + price_down) / bump_size**2
# Vega: dPrice/dSigma
original_sigma = self.sigma
self.sigma = original_sigma + bump_size
price_vega_up, _ = self.monte_carlo_call(n_paths)
self.sigma = original_sigma - bump_size
price_vega_down, _ = self.monte_carlo_call(n_paths)
self.sigma = original_sigma
vega = (price_vega_up - price_vega_down) / (2 * bump_size) / 100
# Theta: dPrice/dT
original_T = self.T
self.T = original_T - 1/365
price_theta, _ = self.monte_carlo_call(n_paths)
self.T = original_T
theta = (price_theta - price_base) / (1/365)
return {'delta': delta, 'gamma': gamma, 'vega': vega, 'theta': theta}
# ==================== CONVERGENCE ANALYSIS ====================
def convergence_analysis(self, path_counts=None):
"""
Analyze convergence of Monte Carlo estimate.
Returns:
--------
dict with convergence data
"""
if path_counts is None:
path_counts = np.logspace(2, 5, 20).astype(int)
bs_price = self.black_scholes_call()
mc_prices = []
mc_errors = []
std_errors = []
for n_paths in path_counts:
mc_price, se = self.monte_carlo_call(n_paths)
mc_prices.append(mc_price)
error = abs(mc_price - bs_price)
mc_errors.append(error)
std_errors.append(se)
return {
'path_counts': path_counts,
'mc_prices': np.array(mc_prices),
'mc_errors': np.array(mc_errors),
'std_errors': np.array(std_errors),
'bs_price': bs_price
}
# ==================== DEMONSTRATION ====================
def main():
# Parameters
S0 = 100 # Initial stock price
K = 105 # Strike price
T = 1.0 # 1 year to maturity
r = 0.05 # 5% risk-free rate
sigma = 0.2 # 20% volatility
print("=" * 70)
print("EUROPEAN OPTION PRICING: MONTE CARLO vs BLACK-SCHOLES")
print("=" * 70)
print(f"\nParameters:")
print(f" Initial Stock Price (S0): ${S0}")
print(f" Strike Price (K): ${K}")
print(f" Time to Maturity (T): {T} year")
print(f" Risk-free Rate (r): {r*100}%")
print(f" Volatility (σ): {sigma*100}%")
pricer = EuropeanOptionPricer(S0, K, T, r, sigma)
# ==================== 1. PRICE COMPARISON ====================
print("\n" + "=" * 70)
print("1. OPTION PRICE COMPARISON (100,000 paths)")
print("=" * 70)
bs_call = pricer.black_scholes_call()
bs_put = pricer.black_scholes_put()
mc_call, se_call = pricer.monte_carlo_call(n_paths=100000)
mc_put, se_put = pricer.monte_carlo_put(n_paths=100000)
print(f"\nCALL OPTION:")
print(f" Black-Scholes: ${bs_call:.4f}")
print(f" Monte Carlo: ${mc_call:.4f} ± ${se_call:.4f}")
print(f" Error: ${abs(mc_call - bs_call):.4f}")
print(f" Error (% of price): {abs(mc_call - bs_call)/bs_call*100:.2f}%")
print(f"\nPUT OPTION:")
print(f" Black-Scholes: ${bs_put:.4f}")
print(f" Monte Carlo: ${mc_put:.4f} ± ${se_put:.4f}")
print(f" Error: ${abs(mc_put - bs_put):.4f}")
print(f" Error (% of price): {abs(mc_put - bs_put)/bs_put*100:.2f}%")
# ==================== 2. GREEKS COMPARISON ====================
print("\n" + "=" * 70)
print("2. GREEKS COMPARISON")
print("=" * 70)
bs_greeks = pricer.black_scholes_greeks()
mc_greeks = pricer.monte_carlo_greeks(n_paths=100000)
greek_names = {'delta': 'Delta (∂C/∂S)', 'gamma': 'Gamma (∂²C/∂S²)',
'vega': 'Vega (∂C/∂σ)', 'theta': 'Theta (∂C/∂T)'}
for greek, label in greek_names.items():
bs_val = bs_greeks[greek]
mc_val = mc_greeks[greek]
print(f"\n{label}:")
print(f" Black-Scholes: {bs_val:8.4f}")
print(f" Monte Carlo: {mc_val:8.4f}")
print(f" Difference: {abs(bs_val - mc_val):8.4f}")
# ==================== 3. GBM PATH VISUALIZATION ====================
print("\n" + "=" * 70)
print("3. GENERATING GBM PATHS VISUALIZATION...")
print("=" * 70)
np.random.seed(42)
S_paths = pricer.simulate_gbm_paths(n_paths=1000, n_steps=252)
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
# Plot 1: Sample paths
ax = axes[0, 0]
time_grid = np.linspace(0, T, S_paths.shape[0])
ax.plot(time_grid, S_paths[:, :100], alpha=0.3, linewidth=0.5)
ax.axhline(y=K, color='r', linestyle='--', linewidth=2, label='Strike Price')
ax.set_xlabel('Time (Years)')
ax.set_ylabel('Stock Price ($)')
ax.set_title(f'1,000 GBM Paths (100 shown)')
ax.legend()
ax.grid(True, alpha=0.3)
# Plot 2: Terminal price distribution
ax = axes[0, 1]
terminal_prices = S_paths[-1, :]
ax.hist(terminal_prices, bins=50, density=True, alpha=0.7, edgecolor='black')
ax.axvline(x=K, color='r', linestyle='--', linewidth=2, label='Strike')
ax.axvline(x=S0, color='g', linestyle='--', linewidth=2, label='Initial Price')
ax.set_xlabel('Terminal Stock Price ($)')
ax.set_ylabel('Density')
ax.set_title('Distribution of Terminal Prices')
ax.legend()
ax.grid(True, alpha=0.3)
# Plot 3: Payoff diagram
ax = axes[1, 0]
ST_range = np.linspace(50, 150, 100)
call_payoff = np.maximum(ST_range - K, 0)
put_payoff = np.maximum(K - ST_range, 0)
ax.plot(ST_range, call_payoff, 'b-', linewidth=2, label='Call Payoff')
ax.plot(ST_range, put_payoff, 'r-', linewidth=2, label='Put Payoff')
ax.axvline(x=K, color='gray', linestyle='--', alpha=0.5, label='Strike')
ax.axvline(x=S0, color='green', linestyle='--', alpha=0.5, label='Initial Price')
ax.set_xlabel('Terminal Stock Price ($)')
ax.set_ylabel('Payoff ($)')
ax.set_title('Option Payoff Diagrams')
ax.legend()
ax.grid(True, alpha=0.3)
# Plot 4: Price convergence
ax = axes[1, 1]
conv_data = pricer.convergence_analysis()
ax.semilogx(conv_data['path_counts'], conv_data['mc_prices'],
'b.-', linewidth=2, markersize=8, label='MC Price')
ax.axhline(y=bs_call, color='r', linestyle='--', linewidth=2,
label='Black-Scholes')
ax.fill_between(conv_data['path_counts'],
conv_data['mc_prices'] - 1.96*np.array(conv_data['std_errors']),
conv_data['mc_prices'] + 1.96*np.array(conv_data['std_errors']),
alpha=0.2, label='95% CI')
ax.set_xlabel('Number of Paths')
ax.set_ylabel('Call Price ($)')
ax.set_title('Monte Carlo Convergence')
ax.legend()
ax.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig('option_pricing.png', dpi=300, bbox_inches='tight')
print("✓ Saved: option_pricing.png")
# ==================== 4. CONVERGENCE ANALYSIS ====================
print("\n" + "=" * 70)
print("4. CONVERGENCE ANALYSIS")
print("=" * 70)
conv_data = pricer.convergence_analysis()
print(f"\n{'Paths':<10} {'MC Price':<12} {'Error':<12} {'Std Error':<12}")
print("-" * 46)
for i in [0, 5, 10, 15, -1]:
n = conv_data['path_counts'][i]
price = conv_data['mc_prices'][i]
error = conv_data['mc_errors'][i]
se = conv_data['std_errors'][i]
print(f"{n:<10.0f} ${price:<11.4f} ${error:<11.4f} ${se:<11.4f}")
# Plot convergence vs O(1/√N)
fig, ax = plt.subplots(figsize=(10, 6))
ax.loglog(conv_data['path_counts'], conv_data['mc_errors'],
'b.-', linewidth=2, markersize=8, label='MC Error')
# Theoretical O(1/√N) convergence
N_theory = np.logspace(2, 5, 100)
error_theory = 0.1 / np.sqrt(N_theory)
ax.loglog(N_theory, error_theory, 'r--', linewidth=2, label='O(1/√N)')
ax.set_xlabel('Number of Paths', fontsize=12)
ax.set_ylabel('Error (|MC - BS|)', fontsize=12)
ax.set_title('Convergence Rate: Monte Carlo Option Pricing', fontsize=14)
ax.legend(fontsize=11)
ax.grid(True, which='both', alpha=0.3)
plt.tight_layout()
plt.savefig('convergence_analysis.png', dpi=300, bbox_inches='tight')
print("✓ Saved: convergence_analysis.png")
# ==================== 5. PERFORMANCE BENCHMARK ====================
print("\n" + "=" * 70)
print("5. PERFORMANCE BENCHMARK")
print("=" * 70)
path_counts = [10000, 50000, 100000, 500000]
print(f"\n{'Method':<20} {'Paths':<10} {'Time (ms)':<12} {'Price':<10}")
print("-" * 52)
for n_paths in path_counts:
# Terminal only
start = time.time()
price_term, _ = pricer.monte_carlo_call(n_paths, method='terminal')
time_term = (time.time() - start) * 1000
print(f"{'Terminal':<20} {n_paths:<10} {time_term:<12.2f} ${price_term:<9.4f}")
# ==================== 6. SENSITIVITY ANALYSIS ====================
print("\n" + "=" * 70)
print("6. SENSITIVITY ANALYSIS - PRICE vs VOLATILITY")
print("=" * 70)
sigmas = np.linspace(0.05, 0.5, 10)
prices_bs = []
prices_mc = []
print(f"\n{'Volatility':<15} {'BS Price':<12} {'MC Price':<12} {'Difference':<12}")
print("-" * 51)
for sigma in sigmas:
pricer.sigma = sigma
bs_p = pricer.black_scholes_call()
mc_p, _ = pricer.monte_carlo_call(n_paths=10000)
prices_bs.append(bs_p)
prices_mc.append(mc_p)
print(f"{sigma:<15.2%} ${bs_p:<11.4f} ${mc_p:<11.4f} ${abs(bs_p-mc_p):<11.4f}")
# Plot sensitivity
fig, ax = plt.subplots(figsize=(10, 6))
ax.plot(sigmas * 100, prices_bs, 'b-o', linewidth=2, markersize=8,
label='Black-Scholes')
ax.plot(sigmas * 100, prices_mc, 'r--s', linewidth=2, markersize=6,
label='Monte Carlo (10k paths)')
ax.set_xlabel('Volatility (%)', fontsize=12)
ax.set_ylabel('Call Option Price ($)', fontsize=12)
ax.set_title('Option Price Sensitivity to Volatility', fontsize=14)
ax.legend(fontsize=11)
ax.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig('sensitivity_analysis.png', dpi=300, bbox_inches='tight')
print("✓ Saved: sensitivity_analysis.png")
# ==================== 7. ANTITHETIC VARIATES ====================
print("\n" + "=" * 70)
print("7. VARIANCE REDUCTION: ANTITHETIC VARIATES")
print("=" * 70)
pricer.sigma = 0.2 # Reset
def monte_carlo_call_antithetic(pricer, n_paths):
"""MC with antithetic variates for variance reduction."""
n_paths_half = n_paths // 2
# Generate random numbers
Z = np.random.standard_normal(n_paths_half)
# Original paths
ST1 = pricer.S0 * np.exp(
(pricer.r - 0.5 * pricer.sigma**2) * pricer.T +
pricer.sigma * np.sqrt(pricer.T) * Z
)
# Antithetic paths (use -Z)
ST2 = pricer.S0 * np.exp(
(pricer.r - 0.5 * pricer.sigma**2) * pricer.T -
pricer.sigma * np.sqrt(pricer.T) * Z
)
# Combine paths
ST = np.concatenate([ST1, ST2])
payoff = np.maximum(ST - pricer.K, 0)
price = np.exp(-pricer.r * pricer.T) * np.mean(payoff)
se = np.std(payoff) / np.sqrt(n_paths) * np.exp(-pricer.r * pricer.T)
return price, se
print(f"\n{'Method':<25} {'Price':<12} {'Std Error':<12} {'Reduction':<12}")
print("-" * 61)
path_tests = [10000, 50000, 100000]
for n_paths in path_tests:
# Standard MC
np.random.seed(42)
price_std, se_std = pricer.monte_carlo_call(n_paths)
var_std = se_std**2
# Antithetic MC
np.random.seed(42)
price_anti, se_anti = monte_carlo_call_antithetic(pricer, n_paths)
var_anti = se_anti**2
reduction = (1 - var_anti/var_std) * 100
print(f"{'Standard MC:':<25} ${price_std:<11.4f} {se_std:<12.6f}")
print(f"{'Antithetic MC:':<25} ${price_anti:<11.4f} {se_anti:<12.6f} {reduction:>10.1f}%")
print()
print("\n" + "=" * 70)
print("ANALYSIS COMPLETE")
print("=" * 70)
if __name__ == "__main__":
main()