Skip to content

Instantly share code, notes, and snippets.

@fsndzomga
Created February 19, 2024 04:42
Show Gist options
  • Save fsndzomga/5899fa1ec0d4b3c04b3cc9fae2bfe171 to your computer and use it in GitHub Desktop.
Save fsndzomga/5899fa1ec0d4b3c04b3cc9fae2bfe171 to your computer and use it in GitHub Desktop.
import yfinance as yf
import numpy as np
import pandas as pd
# Fetch historical data for AAPL and MSFT
tickers = ['AAPL', 'MSFT']
data = yf.download(tickers, start='2022-01-01', end='2023-01-01')['Adj Close']
# Calculate daily returns
daily_returns = data.pct_change().dropna()
# Define weights of AAPL and MSFT in the portfolio
weights = np.array([0.5, 0.5]) # 50% AAPL, 50% MSFT
# Calculate portfolio daily returns
portfolio_returns = daily_returns.dot(weights)
# Calculate the 95% VaR using the historical method
VaR_95 = np.percentile(portfolio_returns, 5)
print(f"95% Value at Risk (VaR): {VaR_95*100:.2f}%")
# Calculate Conditional Value at Risk (CVaR) at the 95% level
CVaR_95 = portfolio_returns[portfolio_returns <= VaR_95].mean()
print(f"95% Conditional Value at Risk (CVaR): {CVaR_95*100:.2f}%")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment