GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com โ€” GitHub - MaswiliK/simlab: Monte Carlo & Portfolio Risk Simulator built with Flask, NumPy and Matplotlib. Runs 1,000+ GBM simulations, computes VaR/CVaR, and visualizes stochastic paths โ€” the math Wall Street uses, open source.

BranchesTags
Open more actions menu

Latest commit

 

History

1 Commit
1 Commit

Folders and files

NameName
Last commit message
Last commit date
app
app
 
 
.gitignore
.gitignore
 
 
README.md
README.md
 
 
main.py
main.py
 
 
requirements.txt
requirements.txt
 
 

Repository files navigation

๐Ÿš€ SimLab โ€“ Monte Carlo & Portfolio Risk Simulator

SimLab is a Python-based quantitative finance simulation platform built with Flask, NumPy, and Matplotlib. It lets you explore uncertainty, model investment risk, and visualize stochastic processes through Monte Carlo methods โ€” the same techniques used by banks and hedge funds.


๐Ÿง  Features

๐ŸŽฒ Monte Carlo Simulation (/monte-carlo)

  • Geometric Brownian Motion (GBM) random walk engine
  • Configurable drift (ฮผ), volatility (ฯƒ), steps, and paths
  • Renders up to 500 simultaneous stochastic paths
  • Highlights median path against all simulated trajectories
  • Live statistics: Mean, Std, Min, Max, Median, VaR 95%

๐Ÿ“ˆ Portfolio Risk Simulator (/portfolio)

  • Dynamic multi-asset portfolio builder (add/remove assets in the UI)
  • Per-asset configuration:
    • Name
    • Expected annual return (ฮผ)
    • Annual volatility (ฯƒ)
    • Portfolio weight
  • Real-time weight validation (weights must sum to 1.0)
  • Runs up to 10,000 simulations over up to 1,260 trading days
  • Two output charts: trajectory paths + return distribution histogram

๐Ÿ“Š Data Visualization

  • Dark terminal-style charts (GitHub-dark palette)
  • Portfolio trajectory plot โ€” all paths + median + mean overlaid
  • Histogram of final portfolio values with VaR zone highlighted
  • All charts rendered server-side with Matplotlib and returned as base64 PNG

โš ๏ธ Risk Metrics

Metric Description
Mean Average final portfolio value across all simulations
Std Deviation Spread / dispersion of outcomes
VaR 95% Value at Risk โ€” only 5% of outcomes are worse than this
VaR 99% Stricter threshold โ€” only 1% of outcomes fall below
CVaR 95% / 99% Conditional VaR โ€” average of the worst outcomes beyond VaR
Prob. Profit % of simulations that ended in profit
Skewness Whether returns skew positive or negative
Kurtosis Fat-tail risk (how extreme the outliers are)
Min / Max Worst and best single simulation outcome

๐Ÿ—๏ธ Tech Stack

Layer Technology
Web framework Flask 3.x
Forms & validation Flask-WTF, WTForms
Numerical engine NumPy
Statistical analytics SciPy
Data manipulation Pandas
Charting Matplotlib
Language Python 3.11+

๐Ÿ“ Project Structure

simlab/
โ”œโ”€โ”€ main.py                      # App entry point
โ”œโ”€โ”€ requirements.txt
โ””โ”€โ”€ app/
    โ”œโ”€โ”€ __init__.py              # App factory (create_app)
    โ”œโ”€โ”€ config.py                # Environment & simulation defaults
    โ”œโ”€โ”€ models.py                # Asset, Portfolio, SimulationResult dataclasses
    โ”œโ”€โ”€ forms.py                 # WTForms: MonteCarloForm, PortfolioForm
    โ”œโ”€โ”€ views.py                 # Routes: /, /monte-carlo, /portfolio
    โ”œโ”€โ”€ auth.py                  # Auth blueprint (stubs, ready for Flask-Login)
    โ”œโ”€โ”€ services/
    โ”‚   โ”œโ”€โ”€ __init__.py
    โ”‚   โ”œโ”€โ”€ monte_carlo.py       # GBM simulation engine + path chart renderer
    โ”‚   โ”œโ”€โ”€ portfolio.py         # Multi-asset simulator + trajectory & histogram charts
    โ”‚   โ””โ”€โ”€ analytics.py        # VaR, CVaR, Sharpe, Sortino, max drawdown
    โ””โ”€โ”€ templates/
        โ”œโ”€โ”€ layout.html          # Base template (dark terminal UI, Space Mono font)
        โ”œโ”€โ”€ index.html           # Landing page
        โ”œโ”€โ”€ monte_carlo.html     # Monte Carlo simulation page
        โ””โ”€โ”€ portfolio.html       # Portfolio simulator with dynamic asset builder

โš™๏ธ Installation

git clone <your-repo>
cd simlab

pip install -r requirements.txt
python main.py

Open http://localhost:5000


๐Ÿงช Usage

Monte Carlo Simulation

  1. Navigate to /monte-carlo
  2. Configure:
    • ฮผ (drift) โ€” expected annual return (e.g. 0.05 = 5%)
    • ฯƒ (volatility) โ€” annual volatility (e.g. 0.20 = 20%)
    • Steps โ€” number of time steps per path (e.g. 252 = 1 trading year)
    • Paths โ€” number of independent simulations (e.g. 50)
    • Initial Value โ€” starting price
  3. Click Run Simulation
  4. Read the path chart and statistics panel

Portfolio Risk Simulator

  1. Navigate to /portfolio
  2. Set your initial capital (e.g. $100,000)
  3. Add assets using the dynamic asset builder:
    • Enter name, ฮผ, ฯƒ, and weight for each asset
    • The weight bar turns green when weights sum to 1.0
  4. Set simulation count and trading days
  5. Click Run Simulation
  6. Analyze:
    • Portfolio trajectory paths (all simulations + median + mean)
    • Return distribution histogram with VaR cutoffs highlighted
    • Full risk metrics table (VaR, CVaR, prob. profit, skewness, kurtosis)

๐Ÿงฎ The Math (Plain English)

Every price path is generated using Geometric Brownian Motion (GBM):

S(t+1) = S(t) ร— exp((ฮผ - ยฝฯƒยฒ)ยทdt + ฯƒยทโˆšdtยทZ)

Where:

  • ฮผ = expected annual return (drift)
  • ฯƒ = annual volatility
  • dt = time increment (1/252 for daily)
  • Z = random shock drawn from a standard normal distribution

Running this equation 1,000 times in parallel gives you 1,000 different futures โ€” the full distribution of possible outcomes.


๐Ÿ”ฅ Future Improvements

  • Real stock price data integration (NSE / Yahoo Finance API)
  • Correlated asset modeling (Cholesky decomposition on covariance matrix)
  • Portfolio optimization โ€” efficient frontier (Markowitz)
  • Streamlit version for fully interactive UI without Flask
  • REST API endpoints for external access
  • User authentication with Flask-Login
  • Export simulation results to CSV / PDF report
  • Backtesting against historical data

๐Ÿง  Concepts Covered

  • Monte Carlo Simulation
  • Geometric Brownian Motion (GBM)
  • Stochastic Processes
  • Value at Risk (VaR) & Conditional VaR (CVaR)
  • Quantitative Risk Modeling
  • Portfolio Theory
  • Probability Distributions
  • Financial Statistics (Skewness, Kurtosis, Sharpe Ratio)

๐Ÿ’ฃ Author

Maswili โ€” Building quantitative systems with Python โšก

"Banks pay quants six figures to run this math. We built it in an afternoon."

About

Monte Carlo & Portfolio Risk Simulator built with Flask, NumPy and Matplotlib. Runs 1,000+ GBM simulations, computes VaR/CVaR, and visualizes stochastic paths โ€” the math Wall Street uses, open source.

Topics

cvarfinancial-simulationfintechflaskgbmgeometric-brownian-motionmatplotlibmonte-carlonumpyportofolio-riskpythonrisk-modellingscipysimulationstochastic-processesvalue-at-risk

Resources

Readme
Activity

Stars

1 star

Watchers

0 watching

Forks

0 forks
Report repository

Releases

Packages

Contributors

Languages

You are visitor 01402775 โ€” GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800ร—600. No cookies required.