python
import numpy as np
def monte_carlo_european_option_price(
S0: float, # Initial stock price
K: float, # Strike price
T: float, # Time to maturity (years)
r: float, # Risk-free rate
sigma: float, # Volatility
N: int = 100000, # Number of simulations
option_type: str = 'call', # 'call' or 'put'
seed: int = None # Random seed for reproducibility
) -> float:
"""
Monte Carlo simulation for pricing a European call or put option
under Black-Scholes assumptions (geometric Brownian motion).
The stock price at maturity is simulated as:
S_T = S0 * exp( (r - 0.5*sigma^2)*T + sigma*sqrt(T)*Z ), Z ~ N(0,1)
Returns the estimated option price.
"""
if seed is not None:
np.random.seed(seed)
# Simulate terminal stock prices
Z = np.random.standard_normal(N)
ST = S0 * np.exp((r - 0.5 * sigma**2) * T + sigma * np.sqrt(T) * Z)
# Compute payoffs
if option_type.lower() == 'call':
payoffs = np.maximum(ST - K, 0)
elif option_type.lower() == 'put':
payoffs = np.maximum(K - ST, 0)
else:
raise ValueError("option_type must be 'call' or 'put'")
# Discounted average payoff
price = np.exp(-r * T) * np.mean(payoffs)
return price
def monte_carlo_with_confidence_interval(
S0: float, K: float, T: float, r: float, sigma: float, N: int = 100000,
option_type: str = 'call', seed: int = None, confidence: float = 0.95
) -> tuple[float, tuple[float, float]]:
"""
Enhanced version with 95% confidence interval (default).
Returns (price, (lower_bound, upper_bound))
"""
if seed is not None:
np.random.seed(seed)
Z = np.random.standard_normal(N)
ST = S0 * np.exp((r - 0.5 * sigma**2) * T + sigma * np.sqrt(T) * Z)
if option_type.lower() == 'call':
payoffs = np.maximum(ST - K, 0)
elif option_type.lower() == 'put':
payoffs = np.maximum(K - ST, 0)
else:
raise ValueError("option_type must be 'call' or 'put'")
discounted_payoffs = np.exp(-r * T) * payoffs
price = np.mean(discounted_payoffs)
std_err = np.std(discounted_payoffs) / np.sqrt(N)
z_score = 1.96 if confidence == 0.95 else -np.log(1 - confidence) # Approx for 95%
ci_lower = price - z_score * std_err
ci_upper = price + z_score * std_err
return price, (ci_lower, ci_upper)
# Example usage
if __name__ == "__main__":
# Standard parameters: at-the-money call, 1 year
S0 = 100
K = 100
T = 1.0
r = 0.05
sigma = 0.2
N = 1000000 # Use more paths for accuracy
print("Monte Carlo European Call Price:")
price = monte_carlo_european_option_price(S0, K, T, r, sigma, N, seed=42)
print(f"Estimated price: {price:.4f}")
print("\nWith 95% Confidence Interval:")
price_ci, ci = monte_carlo_with_confidence_interval(S0, K, T, r, sigma, N, seed=42)
print(f"Estimated price: {price_ci:.4f}")
print(f"95% CI: ({ci[0]:.4f}, {ci[1]:.4f})")
# Theoretical Black-Scholes call price ~10.4506 for comparison
print("\n(Theoretical Black-Scholes: ~10.4506)")