A quantitative finance application for portfolio optimization and risk management using Modern Portfolio Theory and Monte Carlo simulations, with an optimized C computational engine.
Portfolio Lab is a comprehensive financial analysis tool that enables users to optimize investment portfolios through statistical methods. The application combines traditional portfolio optimization techniques with Monte Carlo simulations to provide detailed risk assessment and performance forecasting. Core computational functions are implemented in C for performance, with a Python interface for ease of use.
Portfolio Lab employs a multi-layer architecture optimized for both performance and usability
├── app.py # Main Streamlit application
├── portfolio_engine.c # High-performance C computation engine
├── portfolio_interface.py # Python-C bridge interface
├── portfolio_engine.so # Compiled C library (generated)
├── data/
│ └── combined_stocks.csv # Stock ticker dataset
├── requirements.txt # Python dependencies
├── Makefile # Build automation (optional)
└── README.md # Documentation
The computational core (portfolio_engine.c) handles:
- Monte Carlo Simulations: Optimized random number generation with Box-Muller transform
- Matrix Operations: Efficient covariance matrix calculations
- Risk Metrics: VaR, CVaR, and drawdown computations
- Statistical Analysis: Moments calculation (skewness, kurtosis)
- Memory Management: Optimized allocation and cleanup
The portfolio_interface.py module provides:
- C Library Loading: Dynamic linking with compiled C engine
- Data Marshaling: Seamless numpy array ↔ C array conversion
- Type Safety: Robust ctypes interface with error handling
- Memory Safety: Automatic cleanup of C-allocated resources
- Maximum Sharpe Ratio: Optimize for the best risk-adjusted returns
- Minimum Volatility: Minimize portfolio risk while maintaining diversification
- Equal Weight: Benchmark against naive diversification strategy
- High-Speed Monte Carlo: C-optimized simulation engine with OpenMP parallelization
- Risk Metrics: VaR, CVaR, Maximum Drawdown analysis
- Performance Statistics: Sharpe ratio, Skewness, Kurtosis
- Correlation Analysis: Asset correlation matrix visualization
- Portfolio composition pie charts
- Monte Carlo simulation paths
- Final value distribution histograms
- Asset correlation heatmaps
The application implements Harry Markowitz's Modern Portfolio Theory to find optimal asset allocations:
Portfolio Return: μₚ = Σ(wᵢ × μᵢ)
Portfolio Variance: σₚ² = Σ(wᵢ² × σᵢ²) + ΣΣ(wᵢ × wⱼ × σᵢⱼ)
Sharpe Ratio: Sₚ = (μₚ - rₓ) / σₚ
Where:
wᵢ= weight of asset iμᵢ= expected return of asset iσᵢ= standard deviation of asset iσᵢⱼ= covariance between assets i and jrₓ= risk-free rate
Subject to:
- Σwᵢ = 1 (weights sum to 100%)
- wᵢ ≥ 0 (no short selling)
- 0 ≤ wᵢ ≤ 1 (individual weight bounds)
Portfolio value simulation using geometric Brownian motion:
Sₜ = S₀ × exp((μ - σ²/2) × t + σ × √t × Z)
Where:
Sₜ= portfolio value at time tS₀= initial portfolio valueμ= expected daily returnσ= daily volatilityZ= random normal variable N(0,1)
Quantile-based risk measure:
VaR₍α₎ = -Quantile(returns, α)
Expected loss beyond VaR threshold:
CVaR₍α₎ = E[loss | loss > VaR₍α₎]
Peak-to-trough decline:
DD(t) = (Peak_value - Current_value) / Peak_value
Max_DD = min(DD(t)) for all t
Python 3.8+
GCC Compiler (for C engine compilation)Linux/Mac:
sudo apt-get install gcc libomp-dev # Ubuntu/Debian
brew install gcc libomp # macOSWindows:
# Install MinGW or Visual Studio Build Tools
# OpenMP support included with most modern compilersstreamlit>=1.28.0
numpy>=1.24.0
pandas>=2.0.0
plotly>=5.15.0
scipy>=1.10.0
yfinance>=0.2.0
ctypes # Clone repository
git clone https://github.com/real-veersandhu/portfolio-lab.git
cd portfolio-lab
# Install Python dependencies
pip install -r requirements.txt
# Compile C engine with OpenMP support
gcc -O3 -march=native -fopenmp -fPIC -shared -o portfolio_engine.so portfolio_engine.c
# Alternative: Compile without OpenMP
gcc -O3 -march=native -fPIC -shared -o portfolio_engine.so portfolio_engine.c
# Run application
streamlit run app.py- Select 2+ stocks from the dropdown (supports search)
- Choose historical data period (1-5 years)
- Set risk-free rate (default: 4.5%)
- Simulation Years: Forecast horizon (1-20 years)
- Number of Simulations: Monte Carlo iterations (10-10,000)
- Initial Investment: Starting portfolio value
Click "Run Analysis" to:
- Fetch historical price data via Yahoo Finance API
- Calculate daily returns and covariance matrix
- Solve optimization problems using Sequential Least Squares Programming (SLSQP)
- Generate portfolio composition visualizations
Choose from three optimized portfolios:
- Max Sharpe: Highest risk-adjusted returns
- Min Volatility: Lowest portfolio risk
- Equal Weight: Benchmark strategy
- Annual Return: Annualized expected return (252 trading days)
- Annual Volatility: Annualized standard deviation
- Sharpe Ratio: Risk-adjusted return measure
- Max Drawdown: Worst peak-to-trough decline
- VaR (95%/99%): Potential loss at confidence levels
- CVaR: Expected loss beyond VaR threshold
- Skewness: Return distribution asymmetry
- Kurtosis: Tail risk measurement
- Probability of Profit: Chance of positive returns
- Percentile Analysis: 5th, 50th, 95th percentile outcomes
- Path Visualization: Sample simulation trajectories
