Skip to content

Latest commit

 

History

20 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Stock Price Simulator

License: MIT Python C++ Flask NumPy Plotly

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.


Table of Contents

  1. Overview
  2. Mathematical Model
  3. Features
  4. Architecture
  5. Installation
  6. Usage
  7. API Reference
  8. Project Structure
  9. Performance
  10. License

Overview

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


Mathematical Model

1. Geometric Brownian Motion (GBM)

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

2. Discrete-Time Euler-Maruyama Approximation

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)

3. Box-Muller Transform

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_device for hardware/OS entropy
  • mt19937 Mersenne Twister for high-quality pseudo-random numbers
  • uniform_real_distribution for uniform samples
  • Box-Muller for normal conversion

4. Monte Carlo Simulation

Monte Carlo is a numerical method that uses repeated random sampling to obtain numerical results. For stock pricing:

Algorithm:

  1. Initialize parameters: S0, mu, sigma, T, steps, simulations
  2. For each simulation i from 1 to N:
    • Generate a complete price path using GBM discretization
    • Record the final price S_T
  3. Compute statistics over all N final 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

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

5. Value at Risk (VaR)

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.


Features

  • 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

Architecture

+------------------+        +------------------+        +------------------+
|   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

Installation

Prerequisites

  • Python 3.8 or higher
  • pip (Python package manager)
  • C++17 compiler (optional, for native speed)

Step 1: Clone or Extract

# If using git
git clone <repository-url>
cd stock_simulator_project

# Or extract the ZIP archive
unzip stock_simulator_project.zip
cd stock_simulator_project

Step 2: Create Virtual Environment (Recommended)

Linux/macOS:

python3 -m venv venv
source venv/bin/activate

Windows (PowerShell):

python -m venv venv
.\venv\Scripts\Activate.ps1

Windows (CMD):

python -m venv venv
venv\Scripts\activate.bat

Step 3: Install Dependencies

pip install --upgrade pip
pip install -r requirements.txt

Dependencies installed:

  • flask >= 3.0.0 -- Web framework
  • numpy >= 1.24.0 -- Vectorized numerical computing
  • pandas >= 2.0.0 -- Data manipulation
  • matplotlib >= 3.7.0 -- Static plotting
  • plotly >= 5.18.0 -- Interactive charts
  • scipy >= 1.11.0 -- Statistical functions
  • seaborn >= 0.13.0 -- Statistical visualization
  • flask-cors >= 4.0.0 -- Cross-origin support

Step 4: Build C++ Engine (Optional)

Linux/macOS:

make

Windows (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.exe

If 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.


Usage

Web Interface (Recommended)

# 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.py

Open 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

Command Line

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 5000

C++ simulator (if compiled):

./bin/stock_simulator 150.0 0.08 0.25 2.0 504 5000

Tkinter GUI (Desktop)

python python_interface/stock_simulator_gui.py

Docker

docker-compose up --build

Access at http://localhost:5000


API Reference

POST /api/simulate

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": "{...}"
}

GET /api/plot/distribution

Returns the distribution histogram as PNG image.

GET /api/plot/paths

Returns the price paths plot as PNG image.

GET /api/download/results

Downloads simulation_results.csv containing all final prices.

GET /api/download/paths

Downloads price_paths.csv containing up to 100 complete price paths.


Project Structure

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

Performance

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.


License

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.


Acknowledgments

  • 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

About

GBM Monte Carlo Stock Price Simulator with Flask web interface. Visualize stock price paths, distribution, and risk metrics.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages