Monte Carlo Simulation
Monte Carlo Simulation
1. Identify Key Uncertainties: Pinpoint the variables that truly drive your financial model.
Be granular – not just "stock return," but factors driving stock returns (interest rates,
inflation, sector-specific shocks).
2. Probability Distributions: Choosing Wisely: Log-normal is a starting point, but consider:
– Empirical Distributions: Fit distributions directly from historical data for a more
realistic representation of market behavior (non-normality, fat tails).
– Copulas: Model dependencies between multiple uncertain variables (e.g.,
correlation between stocks and bonds) beyond simple linear correlation.
– Stochastic Volatility Models: Volatility itself is not constant! Models like Heston
capture the time-varying and stochastic nature of volatility, crucial for accurate
option pricing.
– Jump Diffusion Models: Incorporate sudden, unexpected market jumps (black
swan events) that standard GBM misses.
3. Simulation Engine: Power & Efficiency:
– Random Number Generation: Use high-quality pseudo-random number
generators (PRNGs) to ensure statistical accuracy. Consider quasi-Monte Carlo
methods (Sobol sequences) for faster convergence in some applications.
– Variance Reduction Techniques (Advanced): Beyond antithetic and control
variates, explore:
• Importance Sampling: Focus simulations on scenarios that are most
important for your calculation (e.g., in VaR, simulate more tail events).
• Stratified Sampling: Divide the probability space into strata and sample
proportionally from each for better representation.
4. Aggregation & Insight Extraction – Beyond Averages:
– Quantiles & Percentiles: VaR, CVaR, and other risk metrics are derived from
quantiles of the simulated outcome distribution.
– Probability Densities & Histograms: Visualize the full range of outcomes, not
just averages. Identify potential "black swan" scenarios.
– Sensitivity Analysis: Determine which uncertain variables have the biggest
impact on your results. Tornado charts and regression analysis on simulation
outputs are powerful tools.
– Scenario Analysis: Select specific simulated scenarios (e.g., worst-case, best-
case, median) and analyze them in detail to understand the drivers and
consequences.
Step 1: Model Stock Price Paths (GBM, but with Daily Steps)
We still use GBM, but now simulate the stock price daily over the option's life to calculate the
average price.
import numpy as np
import matplotlib.pyplot as plt
plt.tight_layout()
plt.show()
Key Insights:
option_price_optimized = monte_carlo_option_price_numba(S0, K, r,
sigma, T, N)
print(f"Optimized Monte Carlo Price (Numba): $
{option_price_optimized:.2f}")
• Vectorization (NumPy): Always strive for vectorized NumPy operations instead of loops
whenever possible for speed.
• Random Number Seeding: Use np.random.seed(seed_value) for reproducibility
during development and testing. For production, you might remove seeding for true
randomness.
• Code Profiling: Use Python profilers (cProfile, line_profiler) to identify
performance bottlenecks in your MCS code and optimize accordingly.
• Modular Design: Break down complex MCS into modular functions and classes for better
organization, maintainability, and reusability.
4. Case Study 2: Portfolio Credit Risk –
Simulating Credit VaR and Expected Shortfall
Let’s move beyond market risk to credit risk. We'll simulate the 99.9% Credit VaR and Expected
Shortfall (ES) for a portfolio of loans. Credit VaR and ES quantify potential losses due to
borrower defaults.
For each loan, simulate a Bernoulli trial (success/failure) based on its PD. If it defaults, calculate
the loss.
import numpy as np
# Portfolio Parameters
n_loans = 1000
ead = 100_000 # Exposure at Default
lgd = 0.6 # Loss Given Default
pd_min = 0.005 # Minimum PD
pd_max = 0.05 # Maximum PD
N_simulations = 10_000
plt.figure(figsize=(8, 5))
plt.hist(portfolio_losses, bins=50, alpha=0.7, label='Simulated
Portfolio Losses')
plt.axvline(credit_var_99_9, color='red', linestyle='--', linewidth=2,
label=f'99.9% Credit VaR: ${credit_var_99_9:,.2f}')
plt.axvline(credit_es_99_9, color='orange', linestyle='--',
linewidth=2, label=f'99.9% ES: ${credit_es_99_9:,.2f}')
• Correlation in Defaults (Factor Models): Defaults are not independent! Use factor
models (e.g., Merton model, CreditMetrics) to introduce correlation based on
macroeconomic factors. This creates more realistic and systemic risk scenarios.
• Stochastic LGD: Loss Given Default is also uncertain! Model LGD as a random variable
(e.g., Beta distribution) to capture recovery rate uncertainty.
• Time-Varying PDs (Credit Migration): Probability of Default changes over time based on
economic conditions and borrower characteristics. Implement credit migration models
within MCS.
• Stress Testing Credit Portfolios: Design specific macroeconomic stress scenarios
(recessions, interest rate shocks) and use MCS to simulate portfolio losses under these
stressed conditions.
1. Volatility Smile Option Pricing: Implement a local volatility model or stochastic volatility
model (Heston) within your option pricing MCS to capture the volatility smile/skew
observed in real markets.
2. Correlated Asset Portfolio VaR with Copulas: Extend the portfolio VaR example to
include multiple assets (stocks and bonds) with non-linear correlation modeled using a
Gaussian or Student's t-copula.
3. Credit Portfolio Simulation with Factor Model: Implement a single-factor Merton
model to simulate correlated defaults in a credit portfolio, and calculate Credit VaR and
ES under correlated default scenarios.
4. Algorithmic Trading Backtesting with MCS: Develop a simple algorithmic trading
strategy (e.g., moving average crossover) and use MCS to backtest its performance under
thousands of simulated market paths. Optimize strategy parameters using simulation
results.
5. Real Options Valuation for a Project with Uncertainty: Value a simple real option (e.g.,
option to expand) for a hypothetical investment project using MCS, incorporating
uncertainty in key project parameters (demand, costs, commodity prices).