Value at risk (VaR) estimates the loss an investment or portfolio could exceed over a specified period at a chosen confidence level under normal market conditions. A one-day VaR of $30,000 at 95% confidence means losses should be $30,000 or less on 95% of days, leaving a 5% chance of a larger loss. section 7.2.1
Estimate VaR by:
- Collect historical prices and calculate returns. section 7.2.1
- Estimate the returns’ mean and standard deviation. section 7.2.1
- Simulate potential outcomes and select the loss percentile matching the confidence level. section 7.2.1
Listing 7.1 Monte Carlo simulation for VaR on Apple
import numpy as np
import yfinance as yf
import matplotlib.pyplot as plt
ticker = "AAPL" #1
confidence_level = 0.95 #1
num_simulations = 10000 #1
time_horizon = 1 #1
stock = yf.Ticker(ticker) #2
hist = stock.history(period="1y") #2
returns = hist['Close'].pct_change().dropna() #2
mu = returns.mean() #3
sigma = returns.std() #3
last_price = hist['Close'].iloc[-1] #4
sim_returns = np.random.normal(mu,
sigma,
num_simulations) #4
sim_prices = last_price * (1 + sim_returns) #4
threshold = np.percentile(sim_prices - last_price,
(1 - confidence_level) * 100) #5
plt.hist(simulated_prices - last_price, bins=50,
alpha=0.75, color="blue", edgecolor="black") #6
plt.axvline(threshold, color="red",
linestyle="dashed", linewidth=2) #6
plt.title(f"Monte Carlo Simulated "
f"P&L Distribution for {ticker}") #6
plt.xlabel("Profit/Loss") #6
plt.ylabel("Frequency") #6
plt.show() #6
print(f"{confidence_level * 100}% Monte Carlo "
f"VaR for {ticker}: ${-var_threshold:.2f}") #6
A Python workflow downloads one year of Apple prices, simulates 10,000 normally distributed returns, and calculates a one-day VaR threshold. section 7.2.1
