Calibration of the Vasicek Model to Historical Data with Python Code – Quant Next (2024)

January 29, 2024

We present here two methods for calibrating the Vasicek model to historical data:

  1. Least Squares
  2. Maximum Likelihood Estimation

The Python code is available below.

Calibration-of-the-Vasicek-Model-to-Historical-Data-with-Python-CodeDownload

Python Code

Import Libraries

import matplotlib.pyplot as pltplt.style.use('ggplot')import mathimport numpy as npimport pandas as pdfrom scipy.stats import norm%matplotlib inlinefrom sklearn.linear_model import LinearRegression

Simulation Vasicek Process with Euler-Maruyama Discretisation

def vasicek(r0, a, b, sigma, T, num_steps, num_paths): dt = T / num_steps rates = np.zeros((num_steps + 1, num_paths)) rates[0] = r0 for t in range(1, num_steps + 1): dW = np.random.normal(0, 1, num_paths) rates[t] = rates[t - 1] + a * (b - rates[t - 1]) * dt + sigma * np.sqrt(dt) * dW return rates
# Model parametersr0 = 0.02 # Initial short ratea = 0.5 # Mean reversion speedb = 0.03 # Long-term meansigma = 0.01 # VolatilityT = 10 # Time horizonnum_steps = 10000 # Number of stepsnum_paths = 20 # Number of paths# Simulate Vasicek modelsimulated_rates = vasicek(r0, a, b, sigma, T, num_steps, num_paths)# Time axistime_axis = np.linspace(0, T, num_steps + 1)#average valueaverage_rates = [r0 * np.exp(-a * t) + b * (1 - np.exp(-a * t)) for t in time_axis]# standard deviationstd_dev = [(sigma**2 / (2 * a) * (1 - np.exp(-2 * a * t)))**.5 for t in time_axis]# Calculate upper and lower bounds (±2 sigma)upper_bound = [average_rates[i] + 2 * std_dev[i] for i in range(len(time_axis))]lower_bound = [average_rates[i] - 2 * std_dev[i] for i in range(len(time_axis))]# Plotting multiple paths with time on x-axisplt.figure(figsize=(10, 6))plt.title('Vasicek Model - Simulated Interest Rate Paths')plt.xlabel('Time (years)')plt.ylabel('Interest Rate')for i in range(num_paths): plt.plot(time_axis, simulated_rates[:, i]) plt.plot(time_axis, average_rates, color='black',linestyle='--', label ='Average', linewidth = 3)plt.plot(time_axis, upper_bound, color='grey', linestyle='--', label='Upper Bound (2Σ)', linewidth = 3)plt.plot(time_axis, lower_bound, color='grey', linestyle='--', label='Lower Bound (2Σ)', linewidth = 3)plt.legend()plt.show()

Real Parameters

# Model parameters we want to estimatea = .5 # Mean reversion speedb = 0.03 # Long-term meansigma = 0.01 # Volatility

Simulation one path

r0 = 0.03 # Initial short rateT = 10 # Time horizonnum_steps = 10000 # Number of stepsnum_paths = 1 # Number of paths# Simulate Vasicek modelsimulated_rates = vasicek(r0, a, b, sigma, T, num_steps, num_paths)# Time axistime_axis = np.linspace(0, T, num_steps + 1)# Plotting multiple paths with time on x-axisplt.figure(figsize=(10, 6))plt.title('Simulation Interest Rates with Vasicek Model')plt.xlabel('Time (years)')plt.ylabel('Interest Rate')for i in range(num_paths): plt.plot(time_axis, simulated_rates[:, i], color='red')plt.show()

Least Squares

def Vasicek_LS(r, dt): #Linear Regression r0 = r[:-1,] r1 = r[1:, 0] reg = LinearRegression().fit(r0, r1) #estimation a and b a_LS = (1 - reg.coef_) / dt b_LS = reg.intercept_ / dt / a_LS #estimation sigma epsilon = r[1:, 0] - r[:-1,0] * reg.coef_ sigma_LS = np.std(epsilon) / dt**.5 return a_LS[0], b_LS[0], sigma_LS
LS_Estimate = Vasicek_LS(simulated_rates, T / num_steps)print("a_est: " + str(np.round(LS_Estimate[0],3)))print("b_est: " + str(np.round(LS_Estimate[1],3)))print("sigma_est: " + str(np.round(LS_Estimate[2],3)))

Maximum Likelihood Estimation

def Vasicek_MLE(r, dt): r = r[:, 0] n = len(r) #estimation a and b S0 = 0 S1 = 0 S00 = 0 S01 = 0 for i in range(n-1): S0 = S0 + r[i] S1 = S1 + r[i + 1] S00 = S00 + r[i] * r[i] S01 = S01 + r[i] * r[i + 1] S0 = S0 / (n-1) S1 = S1 / (n-1) S00 = S00 / (n-1) S01 = S01 / (n-1) b_MLE = (S1 * S00 - S0 * S01) / (S0 * S1 - S0**2 - S01 + S00) a_MLE = 1 / dt * np.log((S0 - b_MLE) / (S1 - b_MLE)) #estimation sigma beta = 1 / a * (1 - np.exp(-a * dt)) temp = 0 for i in range(n-1): mi = b * a * beta + r[i] * (1 - a * beta) temp = temp + (r[i+1] - mi)**2 sigma_MLE = (1 / ((n - 1) * beta * (1 - .5 * a * beta)) * temp)**.5 return a_MLE, b_MLE, sigma_MLE
MLE_Estimate = Vasicek_MLE(simulated_rates, T / num_steps)print("a_est: " + str(np.round(MLE_Estimate[0],3)))print("b_est: " + str(np.round(MLE_Estimate[1],3)))print("sigma_est: " + str(np.round(MLE_Estimate[2],3)))

Accuracy Estimates

# Model parametersr0 = 0.02 # Initial short ratea = 0.5 # Mean reversion speedb = 0.03 # Long-term meansigma = 0.01 # VolatilityT = 10 # Time horizonnum_steps = 10000 # Number of stepsnum_paths = 100 # Number of pathsa_est = []b_est = []sigma_est = []for i in range(num_paths): simulated_rates = vasicek(r0, a, b, sigma, T, num_steps, 1) LS_Estimate = Vasicek_LS(simulated_rates, T / num_steps) a_est.append(LS_Estimate[0]) b_est.append(LS_Estimate[1]) sigma_est.append(LS_Estimate[2])
plt.figure(figsize=(10, 6))plt.title('Distribution a_estimate')plt.hist(a_est,bins = 10);
plt.figure(figsize=(10, 6))plt.title('Distribution b_estimate')plt.hist(b_est,bins = 10);
plt.figure(figsize=(10, 6))plt.title('Distribution sigma_stimate')plt.hist(sigma_est, bins = 10);

To go further...

Volatility & Derivatives

Why is it Key to Understand Vanna and Volga Risks?

P&L Attribution & Greeks: Vanna and Volga Risks Greeks are used to understand and manage the different dimensions of risk involved when trading options. With

Read More

May 12, 2024

Volatility & Derivatives

How the Parameters of the Heston Model Impact the Implied Volatility Surface

In the Heston model, both the dynamic of the asset price and its instantaneous variance nu are stochastic. The model assumes that the variance follows

Read More

May 10, 2024

Volatility & Derivatives

From Black-Scholes to Heat Equation

The Black-Scholes Model The Black-Scholes model is a pricing model used to determine the theoretical price of options contracts. It was developed by Fischer Black

Read More

April 27, 2024

Calibration of the Vasicek Model to Historical Data with Python Code – Quant Next (2024)

FAQs

How to calibrate the vasicek model? ›

The calibration is done by maximizing the likelihood of zero coupon bond log prices, using mean and covariance functions computed analytically, as well as likelihood derivatives with respect to the parameters. The maximization method used is the conjugate gradients.

What is the Vasicek model simulation in Python? ›

Vasicek one factor model for simulating the evolution of a credit instruments such as a government bonds. The Vasicek model assumes that the process evolves as an Ornstein-Uhlenbeck process. Ornstein-Uhlenbeck is a stochastic process where over time, the process tends to drift towards a long-term mean (mean reverting).

What is the Vasicek interest rate model? ›

The Vasicek Interest Rate Model is a single-factor short-rate model that predicts where interest rates will end up at the end of a given period of time. It outlines an interest rate's evolution as a factor composed of market risk, time, and equilibrium value.

What is the Vasicek one factor model? ›

The Vasicek Interest Rate Model is a mathematical model that tracks and models the evolution of interest rates. It is a one-factor short-rate model and assumes that the movement of interest rates can be modeled based on a single stochastic (or random) factor – the market risk factor.

How do you measure the calibration of a model? ›

The calibration can be measured using the Brier Score. The Brier score is similar to the Mean Squared Error but used slightly in a different context. It takes values from 0 to 1, with 0 meaning perfect calibration, and the lower the Brier Score, the better the model calibration.

How do you calculate Vasicek parameters? ›

Estimates the parameters of the Vasicek model. dr = alpha(beta-r)dt + sigma dW, with market price of risk q(r) = q1+q2 r.

What is the formula for the Vasicek model? ›

Using the Vasicek model equation: dR(t) = a(b – R(t))dt + σdW(t), we can simulate the interest rate path as follows: Step 1: Set initial values: R(0) = 0.05 (initial interest rate) Δt = 1/12 (time step, 1 month)

What is the Vasicek technique? ›

Vasicek's Technique

If β1 is the average beta, across the sample of stocks, in the historical period, then the Vasicek technique involves taking a weighted average of β1, and the historic beta for security j.

What is the Vasicek model credit risk? ›

The Vasicek model uses three inputs to calculate the probability of default (PD) of an asset class. One input is the through-the-cycle PD (TTC_PD) specific for that class. Further inputs are a portfolio common factor, such as an economic index over the interval (0,T) given by S.

Is Vasicek arbitrage free? ›

1 Answer. Short rate models are broadly divided into equilibrium models and no-arbitrage models. The models from Vasicek, Dothan and Cox, Ingersoll and Ross are examples of equilibrium short rate models. The models from Ho-Lee, Hull-White and Black-Karasinski are no-arbitrage models.

What are the advantages of the Vasicek model? ›

Flexibility: One of the key advantages of the Vasicek Model is its flexibility in capturing interest rate movements. The model allows for the estimation of various parameters, such as the mean reversion speed and the volatility of interest rates, which can be adjusted to fit different market conditions.

What are the applications of Vasicek model? ›

The Vasicek model can be used to estimate the expected return and risk of a bond or a bond portfolio under different assumptions of the interest rate process parameters, such as the mean, volatility, and speed of mean reversion.

What is the volatility of the Vasicek model? ›

In the Vasicek specification, volatility is independent of the level of the short rate as in equation (17.1) and is referred to as the normal model. In the normal model, it is possible for negative interest rates to be generated. In the Dothan specification, volatility is proportional to the short rate.

What is the advantage of the CIR model over the Vasicek model? ›

The CIR model is a linear mean reverting stochastic model, which avoids the possibility of negative interest rates experienced in the Vasicek model.

What is the difference between Hull White and Vasicek model? ›

The Hull-White model allows for a time-varying volatility of the short rate, while the Vasicek model assumes a constant volatility. This means that the Hull-White model can capture more complex dynamics of interest rate movements, such as mean reversion, stochastic volatility, and volatility smiles.

How do I calibrate my Garmin? ›

Steps to Manually Trigger a Calibration
  1. Garmin Edge (Touchscreen): Select. ...
  2. Garmin Edge (Button Controlled): Scroll down to Menu > Settings > Sensors > Choose your power meter.
  3. Garmin Edge 130 Series: Press and hold the Top-Right button to access the Menu > Scroll down to select Sensors > Choose your power meter.

How do you calibrate atomos? ›

Unpack the ZIP file and install the Atomos Calibrator software. Connect the 2.5mm jack of the USB to Serial cable to the LANC/Remote port of your Atomos device, and the USB connector into your Windows PC or Mac. On the Ninja, Shogun or Shinobi 7, set the Remote mode in the Input menu to Calibration/LANC.

How do you calibrate a PD model? ›

Calibration of rating scale involves aligning the PDs of the rating scale such that the calibrated portfolio PD matches with the target central tendency. Optimization routine with goal seeking algorithm is one of the most suitable algorithm to carry out such a transformation.

Top Articles
Latest Posts
Article information

Author: Prof. An Powlowski

Last Updated:

Views: 6146

Rating: 4.3 / 5 (44 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Prof. An Powlowski

Birthday: 1992-09-29

Address: Apt. 994 8891 Orval Hill, Brittnyburgh, AZ 41023-0398

Phone: +26417467956738

Job: District Marketing Strategist

Hobby: Embroidery, Bodybuilding, Motor sports, Amateur radio, Wood carving, Whittling, Air sports

Introduction: My name is Prof. An Powlowski, I am a charming, helpful, attractive, good, graceful, thoughtful, vast person who loves writing and wants to share my knowledge and understanding with you.