liveBook · Manning

Value at risk

As explained in Investing for Programmers

Value at risk is an estimate of the maximum expected loss on an investment or portfolio over a specified period at a specified confidence level under normal market conditions.

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

How Investing for Programmers covers it

How deep it goes
Defines VaR and outlines variance-based and Monte Carlo estimation, stopping short of broader model validation.
Examples
Uses a $1,000,000 portfolio example and a Python simulation of Apple share prices.
What it assumes
Uses portfolio prices, returns, means, standard deviations, time horizons, and confidence levels.
What you can do after
Apply it via Python by simulating returns and extracting a confidence-level loss percentile.
How it connects
Connects VaR with Monte Carlo simulation, historical returns, portfolio risk, correlation, and diversification.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Investing for Programmers. The section links point to the parts of the book it draws on.