This is a quantitative finance project I built to translate linear algebra and statistics into functional Python code. It explores Modern Portfolio Theory (MPT) by analyzing a basket of 10 diverse assets, mapping out the risk/reward landscape, and mathematically finding the optimal portfolio weights.
Instead of just guessing which stocks to hold, this script calculates the exact percentages needed to maximize the Sharpe Ratio (getting the most return for the least amount of risk).
- Python: Pandas for data manipulation, NumPy for vector/matrix math.
- yfinance: To pull 5 years of historical, split-adjusted market data.
- SciPy: Used the
optimize.minimizefunction (specifically the SLSQP algorithm) for calculus-based optimization. - Matplotlib: To visualize the Efficient Frontier.
- The Data: Fetches daily adjusted closing prices for a diversified portfolio (AAPL, TSLA, KO, GLD, TLT, JNJ, JPM, XOM, WMT, SPY).
- The Math Engine: Converts raw prices into daily percentage returns and calculates the annualized Covariance Matrix to understand how these assets move in relation to one another.
- The Brute Force (Monte Carlo): Generates 100,000 random portfolio weight combinations to visualize the market possibilities and build the Efficient Frontier.
- The Mathematical Optimum: Uses SciPy to mathematically calculate the absolute peak of the curve, finding the exact weights that deliver the highest possible Sharpe Ratio, outperforming the 100,000 random guesses.
By running the optimization, the math engine found a portfolio that significantly outperformed the best random guess:
- Best Simulated Sharpe Ratio (100k random guesses): ~1.81
- Mathematically Optimal Sharpe Ratio (SciPy): ~1.93
(The red star indicates the mathematically optimized maximum Sharpe portfolio)
To get this project up and running on your machine, run the following commands in your terminal:
# 1. Clone the repository
git clone https://github.com/shreyanshyd/Modern-Portfolio-Theory-Markowitz-Optimization.git
# 2. Navigate into the project directory
cd Modern-Portfolio-Theory-Markowitz-Optimization
# 3. Create and activate a virtual environment
python -m venv venv
# On Windows use: venv\Scripts\activate
# On Mac/Linux use: source venv/bin/activate
# 4. Install the required libraries
pip install -r requirements.txt
# 5. Open the Notebook:
# Option A (VS Code): Open the folder in VS Code, click on Portfolio_Optimization.ipynb, select your venv as the kernel, and run the cells.
# Option B (Terminal): Run `jupyter notebook` here to launch the web interface.