Skip to content

krish1209/MonteCarloSims

Repository files navigation

Monte Carlo Options Pricing Engine

A comprehensive Monte Carlo simulation framework for pricing various financial options, implementing advanced financial engineering techniques with optimized computation.

Overview

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

Features

Option Types

  • 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

Stochastic Processes

  • 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)

Variance Reduction Techniques

  • 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)

Performance Optimizations

  • 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

Visualization Tools

  • Price path visualization
  • Payoff distribution analysis
  • Greeks visualization (delta, gamma, vega, etc.)
  • Implied volatility surface plotting
  • Performance benchmarking tools

Project Structure

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

Installation

  1. Clone the repository:

    git clone https://github.com/yourusername/monte-carlo-options.git
    cd monte-carlo-options
  2. Create a virtual environment and activate it:

    python -m venv venv
    source venv/bin/activate  # On Windows: venv\Scripts\activate
  3. Install the required packages:

    pip install -r requirements.txt

Usage Examples

Pricing a European Option

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']

Pricing an Asian Option

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)

Visualizing Results

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'])

Running Examples

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

Running Tests

# Run all tests
python -m unittest discover

# Run specific test file
python -m tests.test_black_scholes
python -m tests.test_monte_carlo

Performance Considerations

Optimization Tips

  1. 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)
  2. Use antithetic variates for better accuracy with the same number of simulations:

    mc_engine = MonteCarloEngine(..., use_antithetic=True)
  3. Use parallel execution for large simulations:

    results = mc_engine.run_parallel(num_processes=4)

Benchmarking

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)

Extending the Framework

Adding New Option Types

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
        pass

Adding New Stochastic Processes

To 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

Requirements

  • Python 3.7+
  • NumPy
  • SciPy
  • Matplotlib
  • Numba
  • Plotly (optional, for interactive visualizations)

License

MIT License

Disclaimer

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.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors