Skip to content

Latest commit

 

History

2 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

🎲 Monte Carlo Simulation & Risk Engine

An interactive quantitative finance application for simulating uncertain market outcomes, measuring downside risk, and exploring valuation uncertainty through Monte Carlo methods.

Built with Python, NumPy, pandas, Plotly, Streamlit, and yfinance.


Python Streamlit Tests License

Open in Streamlit

This project is designed for quantitative finance research and education. Its simulations depend on simplified models and assumptions and should not be interpreted as forecasts or investment recommendations.


Overview

The Monte Carlo Simulation & Risk Engine explores a central problem in finance:

How can uncertainty be represented as a distribution of possible outcomes rather than a single estimate?

The application approaches this question through two complementary modules.

Market Simulation & Risk

Simulate thousands of possible future asset-price paths using Geometric Brownian Motion (GBM) and analyze the resulting distributions through risk measures including Value at Risk (VaR), Expected Shortfall (ES), drawdowns, and scenario probabilities.

Model parameters can either be specified manually or calibrated from historical market data.

Monte Carlo DCF

Extend the same probabilistic approach to valuation by allowing key DCF assumptions — including free-cash-flow growth, discount rates, and terminal growth — to vary across simulations.

Instead of producing a single deterministic enterprise value, the model generates a distribution of possible valuations.


Simulation Workflow

The market simulation module follows a simple research process:

Model assumptions
        ↓
Manual or historical calibration
        ↓
Geometric Brownian Motion
        ↓
Thousands of simulated price paths
        ↓
Terminal-price distribution
        ↓
Risk and scenario analysis

The DCF module applies the same philosophy to valuation:

Base DCF assumptions
        ↓
Define uncertainty around key inputs
        ↓
Monte Carlo sampling
        ↓
Thousands of DCF valuations
        ↓
Enterprise-value distribution
        ↓
Percentile-based valuation analysis

Application Preview

Market Simulation

Configure the initial price, expected annual return, annualized volatility, simulation horizon, number of paths, and random seed.

Alternatively, calibrate model inputs from historical ticker data.

Monte Carlo simulation setup

Simulated Price Paths

Visualize a sample of possible future asset-price paths generated under Geometric Brownian Motion.

Simulated GBM price paths

Terminal Price Distribution

Analyze the distribution of simulated ending prices together with mean, median, percentiles, loss probabilities, and user-defined scenario thresholds.

Terminal price distribution

Risk Analysis

Measure downside risk using Value at Risk, Expected Shortfall, and simulated maximum-drawdown behavior.

Monte Carlo risk analysis

Monte Carlo DCF

Introduce uncertainty into growth, discount-rate, and terminal-growth assumptions and observe how those uncertainties propagate into enterprise value.

Monte Carlo DCF assumptions

Valuation Distribution

Examine the resulting distribution of simulated enterprise values using summary statistics and valuation percentiles.

Monte Carlo DCF valuation distribution


Features

Geometric Brownian Motion Simulation

The market module models asset prices using Geometric Brownian Motion.

Conceptually:

Current asset price
        ↓
Expected return + volatility
        ↓
Random shocks
        ↓
Simulated price evolution
        ↓
Distribution of possible future prices

The simulator supports:

  • Configurable initial asset price
  • Expected annual return
  • Annualized volatility
  • Flexible simulation horizons
  • Thousands of Monte Carlo paths
  • Reproducible random seeds
  • Manual model assumptions
  • Historical parameter calibration

Historical Calibration

Instead of manually specifying model parameters, users can calibrate the simulation from historical equity data.

The application retrieves market data using yfinance and estimates the inputs required for the GBM simulation from historical observations.

This provides a convenient empirical starting point while keeping the assumptions visible and editable.

Historical estimates are not treated as forecasts of future returns or volatility.


Terminal Price Analysis

After simulation, the engine analyzes the distribution of terminal asset prices.

Reported outputs include:

  • Mean terminal price
  • Median terminal price
  • Distribution percentiles
  • Probability of finishing below the initial price
  • Probability of exceeding a user-defined target
  • Probability of breaching a user-defined downside threshold

This allows the simulation to answer probabilistic questions rather than returning a single projected price.


Risk Analytics

Value at Risk

Value at Risk (VaR) estimates a loss threshold associated with a selected confidence level under the simulated distribution.

The engine calculates VaR from the Monte Carlo outcomes rather than assuming a deterministic future price.

Expected Shortfall

Expected Shortfall (ES) examines the average loss in outcomes beyond the VaR threshold.

This complements VaR by providing information about the severity of losses in the simulated tail rather than only identifying a cutoff.

Maximum Drawdown

Risk is not limited to terminal outcomes.

The engine also calculates maximum drawdown across simulated paths, allowing the user to examine the distribution of peak-to-trough losses that could occur before the simulation horizon ends.

This distinguishes:

Where did the asset finish?

from:

What could the investor have experienced along the way?

Scenario Analysis

The application supports user-defined price scenarios.

Users can specify:

  • An upside target
  • A downside threshold
  • A confidence level

The engine then estimates probabilities such as:

  • Probability of finishing above the target
  • Probability of finishing below the downside threshold
  • Probability of loss

These values describe outcomes within the simulated model and should not be interpreted as objective probabilities of future market events.


Monte Carlo DCF

Traditional discounted cash-flow valuation often produces a single enterprise-value estimate from a single set of assumptions.

The Monte Carlo DCF module instead treats several important assumptions as uncertain.

The simulation varies inputs including:

  • Free-cash-flow growth
  • Discount rate
  • Terminal growth rate

Each simulation produces a separate DCF valuation.

Repeating the process generates a distribution of enterprise values rather than one point estimate.


Valuation Distribution

The DCF module summarizes simulated enterprise values using statistics including:

  • Mean
  • Median
  • 5th percentile
  • 25th percentile
  • 75th percentile
  • 95th percentile

The resulting distribution illustrates how uncertainty in financial assumptions can propagate into uncertainty in valuation.

The goal is not to identify a single "correct" enterprise value, but to explore the sensitivity of valuation to uncertain inputs.


Why Monte Carlo?

Many financial models produce point estimates:

Expected price = X
VaR = Y
Enterprise value = Z

Monte Carlo simulation instead asks:

What range of outcomes can emerge if uncertain inputs evolve differently across repeated scenarios?

This project uses that idea in two different contexts:

  1. Market risk — uncertainty in future asset-price paths
  2. Valuation — uncertainty in the assumptions underlying a DCF

The common theme is representing uncertainty explicitly rather than hiding it behind a single estimate.


Project Structure

monte-carlo-risk-engine/
│
├── app.py
├── README.md
├── requirements.txt
├── LICENSE
├── .gitignore
│
├── src/
│   ├── __init__.py
│   ├── data.py
│   ├── interpretation.py
│   ├── risk.py
│   ├── simulation.py
│   ├── statistics.py
│   └── valuation.py
│
├── tests/
│   ├── test_risk.py
│   ├── test_simulation.py
│   └── test_valuation.py
│
└── assets/
    └── screenshots/
        ├── simulation-setup.png
        ├── simulated-paths.png
        ├── terminal-distribution.png
        ├── risk-analysis.png
        ├── dcf-inputs.png
        └── dcf-distribution.png

---

# Technology Stack

The project is built primarily with:

- **Python**
- **NumPy**
- **pandas**
- **Plotly**
- **Streamlit**
- **yfinance**
- **pytest**

---

# Installation

Clone the repository:

```bash
git clone https://github.com/enesozs/monte-carlo-risk-engine.git
cd monte-carlo-risk-engine

Create a virtual environment:

python -m venv .venv

Activate it on macOS/Linux:

source .venv/bin/activate

On Windows:

.venv\Scripts\activate

Install dependencies:

pip install -r requirements.txt

Run the application:

python -m streamlit run app.py

Testing

Run the automated test suite with:

python -m pytest

The test suite is intended to cover the core simulation, risk, and valuation calculations independently from the dashboard interface.


Model Assumptions and Limitations

Monte Carlo simulation does not eliminate uncertainty. Its outputs depend directly on the model and assumptions used to generate them.

Geometric Brownian Motion

The market simulator uses Geometric Brownian Motion as a simplified model of asset-price dynamics.

GBM assumes a continuous stochastic process with constant model parameters over the simulation horizon.

Real financial markets can exhibit behavior not represented by this model, including:

  • Time-varying volatility
  • Volatility clustering
  • Jumps and discontinuities
  • Fat-tailed return distributions
  • Changing market regimes
  • Structural breaks

Simulated paths should therefore be interpreted as outcomes generated under the GBM model, not forecasts of actual future prices.

Historical Calibration

Historical return and volatility estimates describe the selected historical sample.

They do not imply that the same parameters will persist in the future.

VaR and Expected Shortfall

VaR and Expected Shortfall are calculated from the simulated outcome distribution.

Their usefulness therefore depends on the assumptions underlying that distribution.

DCF Assumptions

Monte Carlo DCF makes uncertainty more visible, but it does not remove the dependence of valuation on assumptions.

The resulting enterprise-value distribution remains sensitive to:

  • Base free cash flow
  • Growth assumptions
  • Discount-rate assumptions
  • Terminal-growth assumptions
  • The uncertainty assigned to each input

Particular care is required when the discount rate approaches the terminal growth rate because terminal-value estimates can become extremely sensitive.

No Forecasting Claim

The application does not claim to predict future market prices or determine the intrinsic value of a company with certainty.

Its purpose is to explore how modeled uncertainty affects financial outcomes.


Intended Use

This project is intended for:

  • Learning Monte Carlo simulation
  • Studying Geometric Brownian Motion
  • Exploring probabilistic market outcomes
  • Practicing quantitative risk measurement
  • Comparing VaR and Expected Shortfall
  • Studying drawdown risk
  • Exploring scenario probabilities
  • Understanding uncertainty in DCF valuation
  • Experimenting with historical and manually specified assumptions

It is not intended to provide personalized investment advice, price forecasts, or trading recommendations.


Design Philosophy

The project prioritizes:

Distributions over point estimates

Uncertain financial outcomes are better represented as ranges and distributions than as falsely precise single numbers.

Transparent assumptions over black-box outputs

Users can inspect and modify the assumptions driving the simulations.

Risk beyond final outcomes

Terminal prices alone do not describe the path-dependent risk an investor may experience.

Model awareness over false precision

Simulation output is only as meaningful as the assumptions and stochastic model generating it.

Interpretability over unnecessary complexity

The project deliberately uses understandable quantitative methods so that the relationship between assumptions, simulation, and output remains visible.


Future Extensions

Possible extensions include:

  • Multi-asset correlated simulations
  • Portfolio-level Monte Carlo analysis
  • Alternative stochastic processes
  • Time-varying volatility models
  • Additional tail-risk measures
  • Sensitivity analysis for DCF assumptions
  • Correlated DCF input assumptions
  • Equity-value and per-share valuation outputs
  • Additional historical calibration methods

Lessons Learned

This project reinforced concepts including:

  • Monte Carlo simulation
  • Geometric Brownian Motion
  • Stochastic modeling
  • Historical parameter estimation
  • Value at Risk
  • Expected Shortfall
  • Drawdown analysis
  • Scenario analysis
  • Probabilistic valuation
  • DCF sensitivity to uncertain assumptions

It also reinforced an important modeling principle:

A more detailed simulation does not automatically produce a more certain answer.

The value of Monte Carlo analysis lies in making assumptions and uncertainty visible, not in disguising uncertainty with additional computation.


Disclaimer

This software is provided for educational and research purposes only.

Nothing in this repository or application constitutes financial, investment, trading, legal, or tax advice.

Simulated prices, risk measures, scenario probabilities, and valuation distributions depend on simplified assumptions and do not guarantee future outcomes.