0% found this document useful (0 votes)
5 views3 pages

Stress Testing and Scenario Analysis

The document outlines a Python script that analyzes historical stock data for a portfolio of four companies (AAPL, MSFT, AMZN, TSLA) using Yahoo Finance. It computes daily returns, portfolio returns, and performs a stress test to evaluate potential losses under market shocks, calculating Value-at-Risk (VaR) and Expected Shortfall (ES) at a 95% confidence level. Additionally, it conducts Monte Carlo simulations to estimate VaR and ES under hypothetical market conditions, visualizing the results with plots.

Uploaded by

arjitdutta100
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views3 pages

Stress Testing and Scenario Analysis

The document outlines a Python script that analyzes historical stock data for a portfolio of four companies (AAPL, MSFT, AMZN, TSLA) using Yahoo Finance. It computes daily returns, portfolio returns, and performs a stress test to evaluate potential losses under market shocks, calculating Value-at-Risk (VaR) and Expected Shortfall (ES) at a 95% confidence level. Additionally, it conducts Monte Carlo simulations to estimate VaR and ES under hypothetical market conditions, visualizing the results with plots.

Uploaded by

arjitdutta100
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

import numpy as np

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.stats import norm

# Load historical data from Yahoo Finance


import yfinance as yf
tickers=['AAPL', 'MSFT', 'AMZN', 'TSLA']
weights = np.array([0.25, 0.25, 0.25, 0.25])
data = yf.download(tickers, start="2010-01-01", end="2024-01-01")['Close']

[*********************100%***********************] 4 of 4 completed

data.head()

Ticker AAPL AMZN MSFT TSLA

Date

2010-01-04 6.440331 6.6950 23.254044 NaN

2010-01-05 6.451464 6.7345 23.261562 NaN

2010-01-06 6.348848 6.6125 23.118807 NaN

2010-01-07 6.337110 6.5000 22.878382 NaN

2010-01-08 6.379242 6.6760 23.036165 NaN

Next steps: Generate code with data toggle_off View recommended plots New interactive sheet

# Compute daily returns


returns = data.pct_change().dropna()

# Portfolio returns
portfolio_returns = returns.dot(weights)

# Plot portfolio returns


plt.figure(figsize=(12,5))
plt.plot(portfolio_returns, label="Portfolio Returns")
plt.axhline(y=0, color='r', linestyle='dashed')
plt.title("Portfolio Returns Over Time")
plt.legend()
plt.show()

# Define market shock (Hypothetical Stress Test)


stress_shock = np.array([-0.5, -0.5, -0.5, 0.1]) # Stocks crash 50%, bonds rise 10%

# Compute stressed portfolio return


stressed_return = np.dot(weights, stress_shock)
print(f"Portfolio return under stress: {stressed_return*100:.2f}%")
Portfolio return under stress: -35.00%

# Compute historical VaR at 95% confidence


confidence_level = 0.95
VaR_95 = -np.percentile(portfolio_returns, (1-confidence_level)*100)

# Compute Expected Shortfall (Conditional VaR)


ES_95 = -portfolio_returns[portfolio_returns < -VaR_95].mean()

print(f"95% Value-at-Risk (VaR): {VaR_95:.4f}")


print(f"95% Expected Shortfall (ES): {ES_95:.4f}")

95% Value-at-Risk (VaR): 0.0269


95% Expected Shortfall (ES): 0.0390

num_simulations = 1000
simulated_shocks = np.random.normal(-0.05, 0.02, (num_simulations, len(tickers))) # Mean drop 5%, StdDev 2%
stressed_returns = simulated_shocks.dot(weights)

#Monte Carlo VaR & ES


VaR_MC = -np.percentile(stressed_returns, (1-confidence_level)*100)
ES_MC = -stressed_returns[stressed_returns < -VaR_MC].mean()

print(f"Monte Carlo 95% VaR: {VaR_MC:.4f}")


print(f"Monte Carlo 95% ES: {ES_MC:.4f}")

Monte Carlo 95% VaR: 0.0662


Monte Carlo 95% ES: 0.0704

# Plot
sns.histplot(stressed_returns, kde=True, bins=50, color="blue")
plt.axvline(-VaR_MC, color='red', linestyle="--", label="95% VaR")
plt.axvline(-ES_MC, color='green', linestyle="--", label="95% Expected Shortfall")
plt.legend()
plt.title("Monte Carlo Simulation of Market Stress Scenarios")
plt.show()

Start coding or generate with AI.

You might also like