A comprehensive Monte Carlo simulation framework for pricing various financial options, implementing advanced financial engineering techniques with optimized computation.
This project provides a flexible and efficient Monte Carlo engine for pricing financial derivatives, with a focus on options. The implementation includes:
- Analytical Black-Scholes model for European options (for benchmarking)
- Monte Carlo simulations for various option types
- Multiple stochastic processes to model asset price movements
- Variance reduction techniques for improved accuracy
- Performance optimizations including vectorization, Numba JIT compilation, and parallel execution
- Comprehensive visualization tools for analyzing results
- European Options: Standard call/put options exercisable at expiry
- American Options: Options exercisable anytime before expiry, priced using Least Squares Monte Carlo
- Asian Options: Options with payoff based on average price during the life of the option
- Barrier Options: Options that activate or deactivate when the price crosses a barrier
- Lookback Options: Options with payoff dependent on the maximum or minimum price reached
- Geometric Brownian Motion (GBM): Standard model for stock price movements
- Heston Model: Stochastic volatility model with mean-reverting variance process
- (More processes can be easily added to the framework)
- Antithetic Variates: Reduce variance by including negatively correlated paths
- Control Variates: Use analytical solutions to reduce Monte Carlo error
- Stratified Sampling: (can be implemented as an extension)
- Vectorized Operations: Fast path generation using NumPy
- Numba JIT Compilation: Just-in-time compilation for CPU-intensive calculations
- Parallel Execution: Multi-process simulation to utilize multiple CPU cores
- Price path visualization
- Payoff distribution analysis
- Greeks visualization (delta, gamma, vega, etc.)
- Implied volatility surface plotting
- Performance benchmarking tools
quant_options/
│
├── models/
│ ├── __init__.py
│ ├── black_scholes.py # Analytical models for benchmarking
│ ├── monte_carlo.py # Core Monte Carlo implementation
│ ├── stochastic_processes.py # Different price processes
│ └── option_types.py # Option payoff definitions
│
├── utils/
│ ├── __init__.py
│ ├── market_data.py # Market data handling
│ ├── visualization.py # Plotting and visualization tools
│ └── performance.py # Performance measurement utilities
│
├── tests/
│ ├── __init__.py
│ ├── test_black_scholes.py
│ └── test_monte_carlo.py
│
└── examples/
├── european_option_pricing.py
├── american_option_pricing.py
├── exotic_options.py
└── performance_benchmarking.py
-
Clone the repository:
git clone https://github.com/yourusername/monte-carlo-options.git cd monte-carlo-options -
Create a virtual environment and activate it:
python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate
-
Install the required packages:
pip install -r requirements.txt
from models.black_scholes import BlackScholes
from models.stochastic_processes import GeometricBrownianMotion
from models.option_types import EuropeanOption
from models.monte_carlo import MonteCarloEngine
# Set parameters
spot = 100.0
strike = 100.0
risk_free_rate = 0.05
div_yield = 0.02
volatility = 0.2
expiry = 1.0
drift = risk_free_rate - div_yield
# Create option and process objects
option = EuropeanOption(strike=strike, expiry=expiry, option_type='call')
process = GeometricBrownianMotion(spot=spot, drift=drift, volatility=volatility)
# Create Monte Carlo engine
mc_engine = MonteCarloEngine(
option=option,
process=process,
risk_free_rate=risk_free_rate,
num_paths=10000,
num_steps=252,
random_seed=42,
use_antithetic=True
)
# Run simulation
results = mc_engine.run(verbose=True)
# Access results
price = results['price']
stderr = results['stderr']
conf_interval = results['conf_interval_95']
paths = results['paths']from models.option_types import AsianOption
# Create Asian option
asian_option = AsianOption(
strike=strike,
expiry=expiry,
option_type='call',
averaging_type='arithmetic'
)
# Create Monte Carlo engine
mc_engine = MonteCarloEngine(
option=asian_option,
process=process,
risk_free_rate=risk_free_rate,
num_paths=10000,
num_steps=252,
random_seed=42
)
# Run simulation
results = mc_engine.run(verbose=True)from utils.visualization import plot_price_paths, plot_payoff_distribution
# Plot price paths
plot_price_paths(results['paths'], num_paths=20)
# Plot payoff distribution
plot_payoff_distribution(results['payoffs'])The repository includes several example scripts demonstrating different features:
# Run European option pricing example
python -m examples.european_option_pricing
# Run American option pricing example
python -m examples.american_option_pricing
# Run exotic options example
python -m examples.exotic_options
# Run performance benchmarking
python -m examples.performance_benchmarking# Run all tests
python -m unittest discover
# Run specific test file
python -m tests.test_black_scholes
python -m tests.test_monte_carlo-
Use Numba-optimized functions for best performance with large numbers of paths:
from utils.performance import generate_gbm_paths_numba, european_call_payoff_numba paths = generate_gbm_paths_numba(spot, drift, volatility, num_paths, num_steps, expiry) payoffs = european_call_payoff_numba(paths, strike, discount_factor)
-
Use antithetic variates for better accuracy with the same number of simulations:
mc_engine = MonteCarloEngine(..., use_antithetic=True)
-
Use parallel execution for large simulations:
results = mc_engine.run_parallel(num_processes=4)
The project includes benchmarking tools to measure performance:
from utils.performance import benchmark_simulation_performance, plot_performance_comparison
results = benchmark_simulation_performance(...)
plot_performance_comparison(results)To add a new option type, subclass the Option base class and implement the payoff method:
from models.option_types import Option
class MyNewOption(Option):
def __init__(self, strike, expiry, option_type='call', my_param=None):
super().__init__(strike, expiry, option_type)
self.my_param = my_param
def payoff(self, spot_paths):
# Implement payoff calculation
passTo add a new stochastic process, create a new class with a simulate_paths method:
class MyNewProcess:
def __init__(self, spot, param1, param2):
self.spot = spot
self.param1 = param1
self.param2 = param2
def simulate_paths(self, num_paths, num_steps, time_horizon, random_seed=None):
# Implement path simulation
pass- Python 3.7+
- NumPy
- SciPy
- Matplotlib
- Numba
- Plotly (optional, for interactive visualizations)
MIT License
This software is for educational purposes only. It is not intended for use in actual trading or investment decisions. The implementation may contain bugs or inaccuracies, and the models make simplifying assumptions that may not reflect real market conditions.