Skip to content

Instantly share code, notes, and snippets.

@fsndzomga
Created February 19, 2024 04:37
Show Gist options
  • Save fsndzomga/1c6d6f89d3dade38bda826dd9173a063 to your computer and use it in GitHub Desktop.
Save fsndzomga/1c6d6f89d3dade38bda826dd9173a063 to your computer and use it in GitHub Desktop.
import yfinance as yf
import pandas as pd
import numpy as np
# Define the tickers of the stocks in the portfolio
tickers = ['AAPL', 'MSFT', 'AMZN']
# Fetch historical data for these stocks
data = yf.download(tickers, start='2023-01-01', end='2024-01-01')['Adj Close']
# Calculate daily returns
daily_returns = data.pct_change().dropna()
# Define weights for the stocks in the portfolio
weights = np.array([0.4, 0.3, 0.3]) # For example, 40% AAPL, 30% MSFT, 30% AMZN
# Calculate portfolio daily returns
portfolio_daily_returns = daily_returns.dot(weights)
# Portfolio variance
portfolio_variance = np.dot(weights.T, np.dot(daily_returns.cov() * 252, weights))
# Portfolio standard deviation (volatility)
portfolio_std_dev = np.sqrt(portfolio_variance)
# Correlation matrix of the returns
correlation_matrix = daily_returns.corr()
print(f"Portfolio Variance: {portfolio_variance}")
print(f"Portfolio Standard Deviation (Volatility): {portfolio_std_dev}")
print("Correlation Matrix of the Returns:")
print(correlation_matrix)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment