The user wants to implement a Monte Carlo simulation for option pricing.
Identify the core problem: The goal is to calculate the fair price of a financial option (likely a European-style option) using the Monte Carlo method. This involves simulating the future price paths of the underlying asset and averaging the discounted payoffs.
Determine the mathematical model:
The most common model for stock price dynamics is Geometric Brownian Motion (GBM).
The stochastic differential equation (SDE) is: dSt=rStdt+σStdWt.
The discretized solution (Euler-Maruyama, though for GBM there's a closed-form discretization) is: St+Δt=St, where .
Select the programming language: Python is the standard for this type of financial engineering due to libraries like numpy (vectorization), scipy, and matplotlib (plotting).
Structure the code:
Parameters: Define inputs (Underlying price S, Strike K, Time to maturity T, Risk-free rate r, Volatility σ, Number of simulations N, Number of time steps - though for European options, is sufficient if we just want the final price, but a path approach is more general).
Drafting the Code (Mental or Scratchpad):
Inputs:S=100,K=100,T=1,r=0.05,σ=.
Refining the Python Implementation:
Use numpy for efficiency. Avoid for loops if possible.
Let's build a class or a clean set of functions. A class Option might be overkill for a simple snippet, but structured functions are good. Let's stick to a script with functions for clarity.
Adding the Black-Scholes formula: This is crucial for validation. Without it, the user doesn't know if the simulation is "correct" or just a random number generator.
Step-by-Step Plan for the Output:
Introduction: Briefly explain the concept (GBM, risk-neutral valuation).
Python Code:
Imports.
Black-Scholes function (for benchmark).
Monte Carlo function (vectorized).
Main execution block: Define parameters, run simulation, compare results.
Visualization code (plot a few paths).
Explanation: Walk through the code logic (random shocks, path generation, discounting).
Self-Correction/Edge Cases:
Vectorization vs Loops: A loop over N (simulations) is slow. A loop over M (time steps) is unavoidable if you need the full path for path-dependent options (like Asian or Barrier), but for simple European options, you can jump straight to T.
Decision: I will implement the path-generation version (using time steps). Why? Because "Monte Carlo simulation" usually implies generating paths, and it allows for future extension to Asian/Lookback options easily. If I just simulate the final price, it looks like simple integration.
Antithetic Variates: Should I add variance reduction techniques? It's a nice touch but might complicate the basic explanation. I'll mention it in the text but stick to standard MC for the code to keep it readable. Actually, maybe simple vectorized path generation is best.
Writing the Code (Mental Check):
Z = np.random.standard_normal((N, M))
# Log returns
daily_returns = np.exp(drift + diffusion * Z)
# Paths
S = S0 * daily_returns.cumprod(axis=1) # Wait, cumprod works if daily_returns is multiplier.
# Correct approach for GBM:
# S[t] = S[t-1] * exp(...)
# paths = np.zeros((M+1, N))
# paths[0] = S0
# for t in range(1, M+1):
# paths[t] = paths[t-1] * exp(...)
Actually, using numpy.cumsum on log-returns is the most "numpy" way to do it without a loop.
log(St)=l.
Yes, that is cleaner.
Final Polish: Ensure comments explain the math. Add a convergence chart (Price vs Number of Simulations) to show how MC converges to Black-Scholes. This adds significant value.
Constructing the Final Response:
Theory recap.
Code (Object-oriented approach is often preferred in finance, but functional is easier to read here. I'll go with functional).
Results interpretation.
(Self-Correction during drafting): Make sure to clarify that this is for a European option (exercisable only at maturity). American options (early exercise) require Least Squares Monte Carlo (Longstaff-Schwartz), which is too complex for a "basic" request unless asked. I will stick to European.
Let's write the solution.
Here is a complete Python implementation of a Monte Carlo simulation for pricing European Call and Put options.
This implementation uses Geometric Brownian Motion (GBM) to simulate the stock price paths and assumes a risk-neutral valuation framework.
The Math Behind the Code
Model: We assume the stock price follows a Stochastic Differential Equation (GBM):
dSt=rStdt+σS
Python Implementation
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
def monte_carlo_option_pricing(S0, K, T, r, sigma, num_simulations=100000, option_type='call'):
"""
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)
sigma (float): Volatility (decimal)
num_simulations (int): Number of simulated paths
option_type (str): 'call' or 'put'
Returns:
tuple: (Option Price, Standard Error, Payoff Array)
"""
# 1. Generate random numbers from a standard normal distribution
Z = np.random.standard_normal(num_simulations)
# 2. Calculate the stock price at maturity (S_T) using GBM logic
# This is the "Jump-to-Maturity" approach (analytically exact for European options)
# S_T = S0 * exp((r - 0.5*sigma^2)*T + sigma*sqrt(T)*Z)
drift = (r - 0.5 * sigma**2) * T
diffusion = sigma * np.sqrt(T) * Z
ST = S0 * np.exp(drift + diffusion)
# 3. Calculate the payoff for each simulation
if option_type == 'call':
payoffs = np.maximum(ST - K, 0)
elif option_type == 'put':
payoffs = np.maximum(K - ST, 0)
else:
raise ValueError("Option type must be 'call' or 'put'")
# 4. Discount the average payoff back to present value
discounted_payoff = np.exp(-r * T) * payoffs
option_price = np.mean(discounted_payoff)
# 5. Calculate Standard Error (for confidence interval)
standard_error = np.std(discounted_payoff) / np.sqrt(num_simulations)
return option_price, standard_error, ST
# --- Benchmarking against Black-Scholes ---
def black_scholes(S0, K, T, r, sigma, option_type='call'):
"""Analytical Black-Scholes formula for verification."""
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 * norm.cdf(d1) - K * np.exp(-r * T) * norm.cdf(d2)
else:
price = K * np.exp(-r * T) * norm.cdf(-d2) - S0 * norm.cdf(-d1)
return price
# --- Main Execution Block ---
if __name__ == "__main__":
# Input Parameters
S0 = 100 # Spot Price
K = 105 # Strike Price
T = 1.0 # Time to Maturity (1 year)
r = 0.05 # Risk-free Rate (5%)
sigma = 0.2 # Volatility (20%)
N = 100000 # Number of simulations
print(f"--- Parameters ---")
print(f"Spot: {S0}, Strike: {K}, Time: {T}y, Rate: {r}, Vol: {sigma}")
print(f"Simulations: {N}\n")
# 1. Run Monte Carlo
mc_price, mc_error, final_prices = monte_carlo_option_pricing(S0, K, T, r, sigma, N, 'call')
# 2. Run Black-Scholes for comparison
bs_price = black_scholes(S0, K, T, r, sigma, 'call')
print("--- Call Option Results ---")
print(f"Black-Scholes Price : {bs_price:.4f}")
print(f"Monte Carlo Price : {mc_price:.4f}")
print(f"Standard Error : {mc_error:.4f}")
print(f"95% Confidence Int. : [{mc_price - 1.96*mc_error:.4f}, {mc_price + 1.96*mc_error:.4f}]")
# Optional: Visualizing the distribution of simulated prices
plt.figure(figsize=(10, 6))
plt.hist(final_prices, bins=100, density=True, alpha=0.6, color='blue', label='Simulated $S_T$')
# Plotting vertical lines for Spot and Strike
plt.axvline(S0, color='black', linestyle='--', label=f'Spot Price ({S0})')
plt.axvline(K, color='red', linestyle='--', label=f'Strike Price ({K})')
plt.title(f'Distribution of Simulated Stock Prices at T={T} (N={N})')
plt.xlabel('Stock Price at Maturity')
plt.ylabel('Frequency')
plt.legend()
plt.show()
How it Works
Random Shocks (Z): We generate 100,000 random numbers from a standard normal distribution (mean 0, std dev 1). These represent the randomness of the market.
Propogation: Instead of stepping through every day (which is slow and unnecessary for European options), we use the analytical solution to "jump" directly from Time 0 to Time T.
Payoff Calculation:
For a Call, if the final price ST is greater than Strike , we make . Otherwise, we make 0.
Key Concepts
Standard Error: As you increase num_simulations, the standard error decreases (at a rate of 1/N). This means to get 10x more accuracy, you need 100x more simulations.
Vs Black-Scholes: The Black-Scholes model gives the exact mathematical answer (for European options). The Monte Carlo simulation approximates this answer. As you increase N, the Monte Carlo price will converge toward the Black-Scholes price.
exp
((
r
−
0.5σ2)Δt+
σΔtZ)
Z∼N(0,1)
M
M=1
Simulation Function: Create a function that generates the price paths.
Payoff Function: Define the payoff logic (Call vs. Put).
Pricing Logic: Discount the average payoff back to present value.
Visualization: Plotting the paths helps intuition.
Benchmarking: Compare against the Black-Scholes analytical solution to verify accuracy.
0.2,N=
10000
Random numbers: Need a matrix of size (N,M) of standard normal variables.
Drift & Diffusion:
Drift = (r−0.5σ2)dt
Diffusion = σdtZ
Price Paths: Cumulative sum of log returns? Or iterative multiplication?
Vectorized approach: Calculate all log returns, prepend 0, do cumsum, exponentiate. This gives log prices. Then scale by S0.
Payoff: For a Call: max(ST−K,0). For a Put: max(K−ST,0).
Price:e−rT×mean(Payoffs).
o
g
(
S0
)
+
∑(drift+
diffusion)
t
d
Wt
Discretization: To simulate this on a computer, we discretize the equation over small time steps Δt:
St+Δt=Stexp((r−0.5σ2)Δt+σΔtZ)
Where Z is a random draw from a standard Normal distribution N(0,1).
Pricing: The option price is the discounted expected payoff:
Price=e−rT⋅E[Payoff(ST)]
K
(ST−K)
For a Put, if Strike K is greater than ST, we make (K−ST). Otherwise, 0.
Averaging: We take the average of all these simulated payoffs.
Discounting: Because the payoff happens in the future, we multiply by e−rT to bring it to present value.