A high-performance Geometric Brownian Motion (GBM) stock price simulator with Monte Carlo analysis, featuring a modern HFT-style web interface built with Flask and interactive Plotly visualizations.
- Overview
- Mathematical Model
- Features
- Architecture
- Installation
- Usage
- API Reference
- Project Structure
- Performance
- License
Stock prices are stochastic processes influenced by market forces, investor behavior, and random shocks. Exact prediction is impossible, but probabilistic forecasting via Monte Carlo simulation provides critical insights for risk management, portfolio optimization, and derivatives pricing.
This simulator models stock price evolution using Geometric Brownian Motion (the standard model in quantitative finance) and generates thousands of possible future paths via Monte Carlo methods to compute statistics like expected price, volatility, and Value at Risk (VaR).
The continuous-time stochastic differential equation (SDE) governing stock price evolution:
dS_t = mu * S_t * dt + sigma * S_t * dW_t
Where:
| Symbol | Description | Typical Value |
|---|---|---|
S_t |
Stock price at time t | Variable |
mu |
Drift (expected annual return) | 0.05 (5%) |
sigma |
Volatility (annual standard deviation) | 0.20 (20%) |
dt |
Time increment | T / steps |
dW_t |
Wiener process increment (Brownian motion) | N(0, dt) |
Key properties of GBM:
- Non-negative prices: Prices cannot go below zero (exponential form ensures this)
- Log-normal returns: The logarithm of price ratios follows a normal distribution
- Markov property: Future prices depend only on the current price, not the path
- Independent increments: Price changes over non-overlapping intervals are independent
For numerical simulation, we discretize the SDE using the Euler-Maruyama method with an exponential solution:
S_{t+dt} = S_t * exp[(mu - 0.5 * sigma^2) * dt + sigma * sqrt(dt) * Z]
Where Z ~ N(0, 1) is a standard normal random variable.
The mu - 0.5 * sigma^2 term is the Ito correction -- it accounts for the fact that the expected value of the exponential of a random variable is not simply the exponential of its mean. This correction ensures that the expected stock price grows at rate mu:
E[S_t] = S_0 * exp(mu * t)
To generate standard normal random variables Z from uniform random numbers, we use the Box-Muller transform:
Given U1, U2 ~ Uniform(0, 1):
Z1 = sqrt(-2 * ln(U1)) * cos(2 * pi * U2)
Z2 = sqrt(-2 * ln(U1)) * sin(2 * pi * U2)
Both Z1 and Z2 are independent standard normal variables N(0, 1).
Implementation uses:
random_devicefor hardware/OS entropymt19937Mersenne Twister for high-quality pseudo-random numbersuniform_real_distributionfor uniform samples- Box-Muller for normal conversion
Monte Carlo is a numerical method that uses repeated random sampling to obtain numerical results. For stock pricing:
Algorithm:
- Initialize parameters:
S0,mu,sigma,T,steps,simulations - For each simulation
ifrom 1 toN:- Generate a complete price path using GBM discretization
- Record the final price
S_T
- Compute statistics over all
Nfinal prices:- Mean:
E[S_T] = (1/N) * sum(S_T_i) - Standard deviation:
std = sqrt(E[S_T^2] - E[S_T]^2) - Percentiles for VaR calculations
- Mean:
Convergence: By the Law of Large Numbers, Monte Carlo estimates converge to the true expected values as N -> infinity. The standard error decreases as 1/sqrt(N).
VaR measures the maximum potential loss at a given confidence level. The 95% VaR is the 5th percentile of the final price distribution:
VaR_95 = Percentile(final_prices, 5%)
This means there is a 5% probability that the final price will be below this value.
- Geometric Brownian Motion model for realistic stochastic price simulation
- Monte Carlo Simulation engine for probabilistic forecasting
- HFT Terminal Web Dashboard with dark theme, monospace fonts, neon accents
- Interactive Plotly Charts with zoom, pan, and hover tooltips
- Real-time Parameter Adjustment with live validation
- C++17 Backend for high-performance computation
- Python/NumPy Fallback for systems without C++ compiler access
- Flask REST API for clean separation of concerns
- CSV Export for all simulation results and price paths
- Docker Support for containerized deployment
- Comprehensive Statistics: Mean, Std Dev, Min/Max, Median, Quartiles, VaR
+------------------+ +------------------+ +------------------+
| Web Browser | <----> | Flask Server | <----> | Simulation Core |
| (Plotly.js UI) | HTTP | (Python API) | JSON | (C++ / NumPy) |
+------------------+ +------------------+ +------------------+
| | |
| | |
v v v
User inputs REST endpoints GBM engine
parameters /api/simulate Monte Carlo
views plots /api/download/* Statistics
Technology Stack:
| Layer | Technology | Purpose |
|---|---|---|
| Frontend | HTML5, CSS3, Plotly.js | Interactive charts, HFT terminal UI |
| Backend API | Flask 3.0, Flask-CORS | REST API, static file serving |
| Simulation Engine | C++17 / NumPy | GBM path generation, Monte Carlo |
| Data Analysis | Pandas, Matplotlib, Seaborn | Statistics, static plots |
| Visualization | Plotly (Python + JS) | Interactive distribution and path charts |
- Python 3.8 or higher
- pip (Python package manager)
- C++17 compiler (optional, for native speed)
# If using git
git clone <repository-url>
cd stock_simulator_project
# Or extract the ZIP archive
unzip stock_simulator_project.zip
cd stock_simulator_projectLinux/macOS:
python3 -m venv venv
source venv/bin/activateWindows (PowerShell):
python -m venv venv
.\venv\Scripts\Activate.ps1Windows (CMD):
python -m venv venv
venv\Scripts\activate.batpip install --upgrade pip
pip install -r requirements.txtDependencies installed:
flask>= 3.0.0 -- Web frameworknumpy>= 1.24.0 -- Vectorized numerical computingpandas>= 2.0.0 -- Data manipulationmatplotlib>= 3.7.0 -- Static plottingplotly>= 5.18.0 -- Interactive chartsscipy>= 1.11.0 -- Statistical functionsseaborn>= 0.13.0 -- Statistical visualizationflask-cors>= 4.0.0 -- Cross-origin support
Linux/macOS:
makeWindows (with MinGW):
g++ -std=c++17 -O3 -pthread src\stock_simulator.cpp src\gbm_simulation.cpp src\monte_carlo.cpp src\utils.cpp -o bin\stock_simulator.exeIf the C++ build fails, the system automatically falls back to the Python/NumPy engine, which is equally accurate and often faster for large simulation counts due to vectorization.
# Activate virtual environment first
source venv/bin/activate # Linux/macOS
# OR
.\venv\Scripts\Activate.ps1 # Windows PowerShell
# Start the Flask server
python python_interface/flask_app.pyOpen your browser and navigate to: http://localhost:5000
Interface features:
- Adjust all 6 parameters in the left panel
- Click "Execute Simulation" to run
- View live statistics cards (8 metrics)
- Interact with Plotly distribution histogram
- Explore simulated price paths with zoom/pan
- Download results as CSV
Python simulator (works everywhere):
python bin/stock_simulator.py [S0] [mu] [sigma] [T] [steps] [simulations]
# Example
python bin/stock_simulator.py 150.0 0.08 0.25 2.0 504 5000C++ simulator (if compiled):
./bin/stock_simulator 150.0 0.08 0.25 2.0 504 5000python python_interface/stock_simulator_gui.pydocker-compose up --buildAccess at http://localhost:5000
Run a new Monte Carlo simulation.
Request Body:
{
"S0": 100.0,
"mu": 0.05,
"sigma": 0.2,
"T": 1.0,
"steps": 252,
"simulations": 1000
}Response:
{
"success": true,
"stats": {
"mean": 105.23,
"std": 20.45,
"min": 55.12,
"max": 185.67,
"median": 103.89,
"q1": 91.23,
"q3": 118.45,
"var95": 72.34,
"var99": 58.91,
"count": 1000
},
"console_output": "...",
"plotly_distribution": "{...}",
"plotly_paths": "{...}"
}Returns the distribution histogram as PNG image.
Returns the price paths plot as PNG image.
Downloads simulation_results.csv containing all final prices.
Downloads price_paths.csv containing up to 100 complete price paths.
stock_simulator_project/
|
|-- src/ # C++17 source code
| |-- stock_simulator.cpp # Main entry point
| |-- stock_simulator.h # Headers and structs
| |-- gbm_simulation.cpp # Core GBM logic (Box-Muller)
| |-- monte_carlo.cpp # Monte Carlo engine & statistics
| |-- utils.cpp # Utility functions
|
|-- python_interface/ # Python web interface
| |-- flask_app.py # Flask REST API and web server
| |-- data_analyzer.py # Plotly charts & data analysis
| |-- stock_simulator_gui.py # Tkinter desktop GUI
| |-- requirements.txt # Python dependencies
|
|-- templates/
| |-- index.html # HFT-style web dashboard
|
|-- static/
| |-- css/
| | |-- style.css # Terminal aesthetic stylesheet
| |-- js/
| |-- app.js # Frontend JavaScript
|
|-- tests/ # Unit tests
| |-- test_gbm.cpp # GBM component tests
| |-- test_monte_carlo.cpp # Monte Carlo tests
| |-- test_data.csv # Test dataset
|
|-- data/ # Sample datasets
| |-- original_stock_data.csv
| |-- historical_prices.csv
| |-- stock_metadata.json
|
|-- output/ # Simulation outputs
| |-- simulation_results.csv
| |-- price_paths.csv
| |-- plots/
| |-- distribution.png
| |-- price_paths.png
|
|-- scripts/ # Helper scripts
| |-- run_simulation.py # Runner with analysis
| |-- analyze_results.py # Standalone analysis
| |-- generate_report.py # HTML report generator
|
|-- docs/ # Documentation
| |-- README.md # This file
| |-- INSTALL.md # Installation guide
| |-- API.md # API documentation
|
|-- bin/ # Compiled executables
| |-- stock_simulator.py # Python fallback engine
|
|-- Makefile # C++ build automation
|-- CMakeLists.txt # CMake configuration
|-- Dockerfile # Docker container definition
|-- docker-compose.yml # Docker Compose setup
|-- requirements.txt # Python dependencies (flexible versions)
|-- run.sh # Linux/macOS runner script
|-- setup.ps1 # Windows PowerShell setup
|-- setup.bat # Windows CMD setup
|-- run_web.ps1 # Windows web launcher
|-- WINDOWS_SETUP.md # Windows-specific instructions
|-- .gitignore # Git ignore rules
| Simulations | C++ Time | Python/NumPy Time | Notes |
|---|---|---|---|
| 1,000 | ~10 ms | ~15 ms | Negligible difference |
| 10,000 | ~80 ms | ~60 ms | NumPy vectorization wins |
| 100,000 | ~700 ms | ~400 ms | NumPy significantly faster |
| 1,000,000 | ~7 s | ~3 s | NumPy optimal for large N |
Key insight: While C++ has lower per-iteration overhead, NumPy's vectorized operations (operating on entire arrays at once in C under the hood) outperform naive C++ loops for large simulation counts. The Python engine is the recommended default.
MIT License
Copyright (c) 2024 Stock Simulator Contributors
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- Geometric Brownian Motion -- Paul Samuelson (1965), foundational work in financial mathematics
- Monte Carlo Methods -- Stanislaw Ulam and John von Neumann (1940s)
- Box-Muller Transform -- George Box and Mervin Muller (1958)
- Ito Calculus -- Kiyoshi Ito (1940s), stochastic calculus foundations