I'm focused on the user's need: a Python-based Monte Carlo simulation for pricing options. Currently, I'm identifying the underlying mathematical model, specifically the Black-Scholes framework, as a foundation. This will inform the subsequent simulation steps.
Analyzing the Components
Now, I'm breaking down the simulation process. I'm focusing on the GBM and its discretized solution for stock price generation. The core logic involves simulating multiple paths, computing payoffs for each, and then averaging the discounted results, tailored for both call and put options. This framework will be the base for coding.
Developing the Code Structure
I'm now outlining the code's structure, focusing on a clear function signature to encapsulate the simulation logic. It will take key parameters like initial stock price, strike price, and volatility. Inside, the implementation will vectorize calculations using NumPy for efficiency. I'm also preparing for potential visualizations to enhance results.
Optimizing Code and Structure
I'm now diving deep into the code's efficiency. Vectorization with NumPy is essential, and I'm ensuring all calculations leverage its power. The function signature is set, ready to take key parameters and return the option price. I'm focusing on the single-step simulation for speed and supplementing it with a multi-step simulation for better understanding, specifically path visualization.
Finalizing the Strategy
I'm solidifying the code output, readying a structure that clearly outlines the inputs and the Python implementation. I am confirming variable names for clarity, and incorporating a plot of price paths for enhanced understanding. I have set a random seed for reproducible results, crucial for user confidence.
Here is a complete implementation of a Monte Carlo simulation for pricing European Call and Put options using Python and NumPy.
I will provide the mathematical logic, the vectorized code (for speed), a comparison against the Black-Scholes analytical formula (for accuracy), and a visualization of the price paths.
1. The Mathematical Model
We assume the stock price follows Geometric Brownian Motion (GBM):
ST=S0⋅exp((r−2
Where:
ST = Price at maturity
S0 = Current price
r = Risk-free interest rate
= Volatility
2. Python Implementation
You will need numpy and scipy installed (pip install numpy scipy matplotlib).
python
import numpy as np
import scipy.stats as si
import matplotlib.pyplot as plt
def monte_carlo_option_price(S0, K, T, r, sigma, option_type='call', num_simulations=100000):
"""
Calculates the price of a European option using Monte Carlo Simulation.
Parameters:
S0 (float): Current stock price
K (float): Strike price
T (float): Time to maturity (in years)
r (float): Risk-free interest rate (decimal, e.g., 0.05 for 5%)
sigma (float): Volatility (decimal, e.g., 0.2 for 20%)
option_type (str): 'call' or 'put'
num_simulations (int): Number of paths to simulate
Returns:
float: Estimated option price
"""
# 1. Generate Random Variables (Z)
# We generate 'num_simulations' random variables from Standard Normal Distribution
np.random.seed(42) # Set seed for reproducibility
Z = np.random.standard_normal(num_simulations)
# 2. Calculate Stock Price at Maturity (S_T)
# Using the geometric Brownian motion formula
drift = (r - 0.5 * sigma**2) * T
diffusion = sigma * np.sqrt(T) * Z
S_T = S0 * np.exp(drift + diffusion)
# 3. Calculate Payoffs
if option_type == 'call':
payoffs = np.maximum(S_T - K, 0)
elif option_type == 'put':
payoffs = np.maximum(K - S_T, 0)
else:
raise ValueError("Option type must be 'call' or 'put'")
# 4. Discount Payoffs to Present Value
# The Monte Carlo estimator is the average of the discounted payoffs
option_price = np.exp(-r * T) * np.mean(payoffs)
return option_price
# --- Verification Function (Black-Scholes Analytical Model) ---
def black_scholes_price(S0, K, T, r, sigma, option_type='call'):
d1 = (np.log(S0 / K) + (r + 0.5 * sigma ** 2) * T) / (sigma * np.sqrt(T))
d2 = (np.log(S0 / K) + (r - 0.5 * sigma ** 2) * T) / (sigma * np.sqrt(T))
if option_type == 'call':
price = (S0 * si.norm.cdf(d1, 0.0, 1.0) - K * np.exp(-r * T) * si.norm.cdf(d2, 0.0, 1.0))
elif option_type == 'put':
price = (K * np.exp(-r * T) * si.norm.cdf(-d2, 0.0, 1.0) - S0 * si.norm.cdf(-d1, 0.0, 1.0))
return price
# --- RUNNING THE SIMULATION ---
# Parameters
S0 = 100 # Current price
K = 100 # Strike price
T = 1.0 # 1 year to maturity
r = 0.05 # 5% risk free rate
sigma = 0.2 # 20% volatility
sims = 1000000 # 1 million simulations
# Calculate Prices
mc_price = monte_carlo_option_price(S0, K, T, r, sigma, 'call', sims)
bs_price = black_scholes_price(S0, K, T, r, sigma, 'call')
print(f"Parameters: S0={S0}, K={K}, T={T}, r={r}, sigma={sigma}")
print("-" * 40)
print(f"Black-Scholes Price (Exact): ${bs_price:.4f}")
print(f"Monte Carlo Price ({sims:,} sims): ${mc_price:.4f}")
print(f"Difference: ${abs(bs_price - mc_price):.4f}")
3. Visualizing the Paths
While the previous code calculated the price efficiently by jumping straight to the final time T, visualizing the paths requires simulating time steps between 0 and T.
Here is how to visualize the random walk of the asset prices:
Vectorization: Notice we do not use Python for loops to calculate the 1,000,000 simulations. We use NumPy arrays. S_T - K subtracts K from every item in the array instantly. This makes the simulation complete in milliseconds rather than minutes.
Standard Error: As you increase num_simulations (N), the accuracy improves by a factor of 1/N. To double the accuracy, you need 4 times the simulations.
Risk-Neutral Pricing: We use the risk-free rate () for the drift of the stock, not the expected real-world return of the stock. This is a fundamental tenet of option pricing theory (simulating in the Q-measure).
1
σ2
)
T
+
σ
T
Z
)
σ
T = Time to maturity (in years)
Z = Random variable from a standard normal distribution N(0,1)