Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import yfinance as yf
- import numpy as np
- import matplotlib.pyplot as plt
- class PortfolioOptimizer:
- def __init__(self, tickers, start_date, end_date, num_portfolios=10000):
- """
- Inizializza l'ottimizzatore di portafoglio.
- :param tickers: Lista di ticker azionari.
- :param start_date: Data di inizio per i dati storici.
- :param end_date: Data di fine per i dati storici.
- :param num_portfolios: Numero di portafogli da simulare.
- """
- self.tickers = tickers
- self.start_date = start_date
- self.end_date = end_date
- self.num_portfolios = num_portfolios
- self.data = None
- self.returns = None
- self.results = None
- self.weights_record = []
- def fetch_data(self):
- """Scarica i dati storici dei prezzi e calcola i rendimenti."""
- self.data = yf.download(self.tickers, start=self.start_date, end=self.end_date)['Adj Close']
- self.returns = self.data.pct_change(fill_method=None).dropna()
- def simulate_portfolios(self):
- """Simula portafogli casuali e calcola rendimento, volatilità e Sharpe Ratio."""
- num_assets = len(self.tickers)
- self.results = np.zeros((3, self.num_portfolios))
- for i in range(self.num_portfolios):
- weights = np.random.random(num_assets)
- weights /= np.sum(weights)
- self.weights_record.append(weights)
- # Rendimento atteso annualizzato
- portfolio_return = np.sum(weights * self.returns.mean()) * 252
- # Volatilità annualizzata
- portfolio_volatility = np.sqrt(np.dot(weights.T, np.dot(self.returns.cov() * 252, weights)))
- # Sharpe Ratio
- sharpe_ratio = portfolio_return / portfolio_volatility
- self.results[0, i] = portfolio_return
- self.results[1, i] = portfolio_volatility
- self.results[2, i] = sharpe_ratio
- def get_optimal_portfolios(self):
- """
- Trova il portafoglio con il miglior Sharpe Ratio e quello con la minore volatilità.
- :return: Indici e pesi ottimali.
- """
- max_sharpe_idx = np.argmax(self.results[2])
- min_volatility_idx = np.argmin(self.results[1])
- return {
- "max_sharpe_idx": max_sharpe_idx,
- "min_volatility_idx": min_volatility_idx,
- "best_weights": self.weights_record[max_sharpe_idx],
- "min_volatility_weights": self.weights_record[min_volatility_idx],
- }
- def plot_results(self, optimal_portfolios):
- """Visualizza i risultati della simulazione."""
- plt.figure(figsize=(10, 6))
- plt.scatter(self.results[1, :], self.results[0, :], c=self.results[2, :], cmap='YlGnBu', marker='o')
- plt.colorbar(label='Sharpe Ratio')
- plt.scatter(
- self.results[1, optimal_portfolios["max_sharpe_idx"]],
- self.results[0, optimal_portfolios["max_sharpe_idx"]],
- marker='*',
- color='r',
- s=500,
- label='Miglior Sharpe Ratio',
- )
- plt.scatter(
- self.results[1, optimal_portfolios["min_volatility_idx"]],
- self.results[0, optimal_portfolios["min_volatility_idx"]],
- marker='*',
- color='g',
- s=500,
- label='Minima Volatilità',
- )
- plt.title('Simulazione di Portafogli')
- plt.xlabel('Volatilità')
- plt.ylabel('Rendimento Atteso')
- plt.legend()
- plt.show()
- def print_optimal_portfolios(self, optimal_portfolios):
- """Stampa i dettagli dei portafogli ottimali."""
- max_sharpe_idx = optimal_portfolios["max_sharpe_idx"]
- min_volatility_idx = optimal_portfolios["min_volatility_idx"]
- print("Portafoglio con miglior Sharpe Ratio:")
- print(f"Rendimento atteso: {self.results[0, max_sharpe_idx]:.2f}")
- print(f"Volatilità: {self.results[1, max_sharpe_idx]:.2f}")
- print("Pesi:")
- for ticker, weight in zip(self.tickers, optimal_portfolios["best_weights"]):
- print(f"{ticker}: {weight:.2%}")
- print("\nPortafoglio con minima volatilità:")
- print(f"Rendimento atteso: {self.results[0, min_volatility_idx]:.2f}")
- print(f"Volatilità: {self.results[1, min_volatility_idx]:.2f}")
- print("Pesi:")
- for ticker, weight in zip(self.tickers, optimal_portfolios["min_volatility_weights"]):
- print(f"{ticker}: {weight:.2%}")
- # Esempio di utilizzo
- tickers = ['NVDA', 'KO', 'TSLA', 'ENI.MI', 'META', 'BC.MI']
- optimizer = PortfolioOptimizer(tickers, start_date="2023-05-01", end_date="2023-11-01")
- # Passaggi
- optimizer.fetch_data()
- optimizer.simulate_portfolios()
- optimal_portfolios = optimizer.get_optimal_portfolios()
- optimizer.plot_results(optimal_portfolios)
- optimizer.print_optimal_portfolios(optimal_portfolios)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement