Quantitative Portfolio Optimization via Lagrange Multipliers ๐
Author: Dr. Ottaviani Flavio Rubens
Finance | Economics | Computer Science | AI/ML
๐ฌ๐ง About the Project
This repository provides a highly efficient, robust Python implementation for finding the Global Minimum Variance Portfolio using the exact mathematical formulation derived from Lagrange multipliers.
Designed for quantitative analysts, data scientists, and finance students, this module automates the entire pipeline: from retrieving historical market data to calculating the optimal asset allocation that minimizes systemic risk.
๐ฎ๐น Informazioni sul Progetto
Questo repository fornisce un'implementazione in Python altamente efficiente e robusta per trovare il Portafoglio a Minima Varianza Globale utilizzando la formulazione matematica esatta derivata dai moltiplicatori di Lagrange.
Progettato per analisti quantitativi, data scientist e studenti di finanza, questo modulo automatizza l'intera pipeline: dal recupero dei dati storici di mercato fino al calcolo dell'allocazione ottimale degli asset che minimizza il rischio sistemico.
๐ฌ๐ง The Financial Framework: Harry Markowitz & MPT
In 1952, Harry Markowitz published a groundbreaking paper that birthed Modern Portfolio Theory (MPT), earning him a Nobel Prize in Economics. Markowitz mathematically demonstrated that an investor shouldn't just look at the expected return of a single stock, but rather how that stock's price movements correlate with the rest of the portfolio.
By diversifying assets, an investor can construct an "Efficient Frontier" of portfolios that offer the maximum possible return for a given level of risk. At the very left edge of this Efficient Frontier lies the Global Minimum Variance Portfolio (GMVP): the specific combination of assets that results in the absolute lowest possible volatility (risk).
To find these exact weights, the code solves the following constrained optimization problem mathematically using Lagrange Multipliers:
Minimize the portfolio variance: Min Var(w) = ฮฃแตข ฮฃโฑผ (wแตข ยท wโฑผ ยท ฯแตขโฑผ)
Subject to the budget constraint (fully invested): ฮฃแตข wแตข = 1
(Where "wแตข" and "wโฑผ" are the weights of assets i and j, "ฯแตขโฑผ" is the covariance between them, and "ฮฃ" is the sum from 1 to N assets).
๐ฎ๐น Il Framework Finanziario: Harry Markowitz & MPT
Nel 1952, Harry Markowitz pubblicรฒ un articolo rivoluzionario che diede vita alla Teoria Moderna di Portafoglio (MPT), facendogli vincere un Premio Nobel per l'Economia. Markowitz dimostrรฒ matematicamente che un investitore non dovrebbe guardare solo al rendimento atteso di una singola azione, ma a come i movimenti di prezzo di quell'azione sono correlati con il resto del portafoglio.
Diversificando gli asset, un investitore puรฒ costruire una "Frontiera Efficiente" di portafogli che offrono il massimo rendimento possibile per un dato livello di rischio. All'estremitร sinistra di questa Frontiera Efficiente si trova il Portafoglio a Minima Varianza Globale (GMVP): la specifica combinazione di asset che genera la volatilitร (rischio) piรน bassa in assoluto.
Per trovare questi pesi esatti, il codice risolve matematicamente il seguente problema di ottimizzazione vincolata utilizzando i Moltiplicatori di Lagrange:
Minimizzare la varianza del portafoglio: Min Var(w) = ฮฃแตข ฮฃโฑผ (wแตข ยท wโฑผ ยท ฯแตขโฑผ)
Soggetto al vincolo di bilancio (tutto il capitale investito): ฮฃแตข wแตข = 1
(Dove "wแตข" e "wโฑผ" sono i pesi degli asset i e j, "ฯแตขโฑผ" รจ la covarianza tra di essi, e "ฮฃ" รจ la sommatoria da 1 a N asset).
๐ฌ๐ง Key Features
- Automated Data Pipeline: Direct integration with
yfinanceto download historical market data. - Covariance Matrix Calculation: Automatically processes daily returns and computes the annualized covariance matrix (252 trading days).
- Exact Mathematical Optimization: Uses NumPy linear algebra (
np.linalg.inv) for high-speed matrix inversion and exact Lagrange multiplier resolution. - Bilingual Output: System messages and results are printed in both English and Italian.
๐ฎ๐น Caratteristiche Principali
- Pipeline Dati Automatica: Integrazione diretta con
yfinanceper il download dei dati storici di mercato. - Calcolo Matrice di Covarianza: Elabora automaticamente i rendimenti giornalieri e calcola la matrice di covarianza annualizzata (252 giorni di trading).
- Ottimizzazione Matematica Esatta: Utilizza l'algebra lineare di NumPy (
np.linalg.inv) per l'inversione rapida delle matrici e la risoluzione esatta con i moltiplicatori di Lagrange. - Output Bilingue: I messaggi di sistema e i risultati vengono stampati sia in inglese che in italiano.
๐ How to Download and Use (Inferenza / Inference)
๐ฌ๐ง EN: To properly register a download and test the code in your local Python environment, run the following script. It uses the official huggingface_hub library to fetch the module directly into your project.
๐ฎ๐น IT: Per registrare correttamente il download ed eseguire il codice nel tuo ambiente Python locale, lancia il seguente script. Utilizza la libreria ufficiale huggingface_hub per scaricare il modulo direttamente nel tuo progetto.
1. Install Requirements / Installa i Requisiti
pip install huggingface_hub yfinance pandas numpy
#INFERENZA/INFERENCE
from huggingface_hub import hf_hub_download
import sys
import os
# Scarica lo script
file_path = hf_hub_download(
repo_id="FlavioRubensOttaviani/Finance-Markowitz-Portfolio-Optimization-Lagrange-Multipliers",
filename="portfolio_optimization.py"
)
sys.path.append(os.path.dirname(file_path))
#Importa la classe
from portfolio_optimization import ottimizzazioneLagrange
#Inizializza e scarica
mio_ptf = ottimizzazioneLagrange(tickers=["AAPL", "MSFT", "GOOGL"], period="1y")
mio_ptf.downloadData()
mio_ptf.prepare_matrix()
mio_ptf.portfolio_optimization()
mio_ptf.mostrarisultati()