FlavioRubensOttaviani commited on
Commit
aaefd93
·
verified ·
1 Parent(s): 81c331e

Upload portfolio_optimization_complete.py

Browse files
Files changed (1) hide show
  1. portfolio_optimization_complete.py +89 -0
portfolio_optimization_complete.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Created on Sat Feb 21 14:28:46 2026
4
+
5
+ @author: ottav
6
+ """
7
+
8
+ # -*- coding: utf-8 -*-
9
+ """
10
+ Script per ottimizzazione di portafoglio con moltiplicatori di Lagrange
11
+ Script for portfolio optimization with Lagrange multipliers
12
+ """
13
+
14
+ import yfinance as yf
15
+ import pandas as pd
16
+ import numpy as np
17
+
18
+ class ottimizzazioneLagrange:
19
+ # optimization of portfolio - Markowitz (Global Minimum Variance)
20
+ # ottimizzazione di portafoglio - Markowitz (Minima Varianza Globale)
21
+ def __init__(self, tickers, period):
22
+ self.tickers = tickers
23
+ self.period = period
24
+
25
+ self.dati_prezzi = None
26
+ self.matrice_covarianza = None
27
+ self.pesi_ottimali = None
28
+
29
+ def downloadData(self):
30
+ print(f"Downloading Data for {self.tickers}....\nDownload Dati per {self.tickers}....")
31
+ dati = yf.download(self.tickers, period=self.period)
32
+
33
+ if isinstance(dati.columns, pd.MultiIndex):
34
+ self.dati_prezzi = dati['Close']
35
+ else:
36
+ self.dati_prezzi = pd.DataFrame(dati['Close'])
37
+ self.dati_prezzi.columns = self.tickers
38
+
39
+ print("Data downloaded successfully!\nDati scaricati con successo!\n")
40
+
41
+ def prepare_matrix(self):
42
+ if self.dati_prezzi is None or self.dati_prezzi.empty:
43
+ raise ValueError("You must download the data first\nDevi prima scaricare i dati")
44
+
45
+ rendimenti = self.dati_prezzi.pct_change().dropna()
46
+ self.matrice_covarianza = rendimenti.cov() * 252
47
+ print("Covariance Matrix in progress...... --> Calculated!\nMatrice Covarianze in progress...... --> Calcolata!\n")
48
+
49
+ def portfolio_optimization(self):
50
+ if self.matrice_covarianza is None:
51
+ raise ValueError("You must fill the matrix first!\nDevi prima riempire la matrice!")
52
+
53
+ n_asset = len(self.tickers)
54
+ vettore1 = np.ones(n_asset)
55
+ cov_inversa = np.linalg.inv(self.matrice_covarianza.values)
56
+ num = cov_inversa @ vettore1
57
+ den = vettore1.T @ num
58
+ self.pesi_ottimali = num / den
59
+ print("Optimization completed!\nOttimizzazione completata!\n")
60
+
61
+ def mostrarisultati(self):
62
+ if self.pesi_ottimali is None:
63
+ raise ValueError("You must calculate the weights first\nDevi prima calcolare i pesi")
64
+
65
+ print('-' * 40)
66
+ print("GLOBAL MINIMUM VARIANCE PORTFOLIO\nPORTAFOGLIO A MINIMA VARIANZA GLOBALE")
67
+ print('-' * 40)
68
+
69
+ for i, ticker in enumerate(self.tickers):
70
+ peso_percentuale = self.pesi_ottimali[i] * 100
71
+ print(f"Asset: {ticker} | Weight: {peso_percentuale:.2f}%")
72
+
73
+ print("-" * 40)
74
+
75
+ #start code
76
+ if __name__ == "__main__":
77
+ # 1. Scegliamo i ticker e il periodo
78
+ tickers_scelti = ["AAPL", "MSFT", "GOOGL"]
79
+
80
+ # 2. Creiamo l'oggetto
81
+ mio_ptf = ottimizzazioneLagrange(tickers=tickers_scelti, period="1y")
82
+
83
+ # 3. Lanciamo i metodi in sequenza
84
+ mio_ptf.downloadData()
85
+ mio_ptf.prepare_matrix()
86
+ mio_ptf.portfolio_optimization()
87
+
88
+ # 4. Stampiamo i risultati a schermo
89
+ mio_ptf.mostrarisultati()