liveBook · Manning

Monte Carlo simulation

As explained in Investing for Programmers

A Monte Carlo simulation is a computational technique that uses repeated random sampling to estimate outcomes or explore possible solutions.

Monte Carlo simulation estimates uncertain outcomes by repeatedly drawing random samples. In financial analysis, it turns historical returns into many possible future prices or portfolio results, helping quantify risk when a single forecast is inadequate. section 7.2.1

A practical financial workflow typically:

  • Loads historical prices and calculates percentage returns. section 7.2.1
  • Estimates average return and volatility from those observations. section 7.2.1
  • Samples many possible returns, then converts them into simulated prices or portfolio outcomes. section 7.2.1 section 7.6.1
  • Summarizes the distribution with a percentile, such as a 95% Value at Risk estimate. section 7.2.1

Apple one-day VaR

Using one year of Apple prices, estimate return mean and volatility, generate 10,000 normally sampled returns, and compare simulated prices with the latest price. The 5th percentile of simulated losses provides a 95% VaR estimate; the example indicates losses above $5.50 occurred in roughly 5% of simulations. Historical assumptions do not capture unpredictable Black Swan events. section 7.2.1 section 7.7

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

Inspect the executable Python pattern for downloading Apple data, sampling returns, calculating the percentile threshold, and plotting simulated losses. section 7.2.1

How Investing for Programmers covers it

How deep it goes
Explains sampling inputs, simulated outcomes, percentiles, and portfolio selection, but stops short of modeling Black Swan events.
Examples
Uses Apple price simulations, 95% VaR, 10,000 random portfolios, efficient-frontier plots, and portfolio weights.
What it assumes
Assumes historical price data and basic return, mean, volatility, confidence-level, and portfolio-risk concepts.
What you can do after
Build it from scratch to estimate stock VaR or compare randomly generated portfolios using historical returns.
How it connects
Connects Monte Carlo simulation with Value at Risk, historical data, volatility, correlation, Sharpe ratio, and efficient portfolios.

Also explained in

Compare how 8 books explain Monte Carlo simulation →

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.