Python implements Historical Simulation to calculate Value at Risk (VaR) (with code)

一,Value at Risk(VaR)

Value at Risk (VaR) is a risk measurement method commonly used in financial risk management, which is used to estimate the maximum possible loss at a given confidence level within a certain period of time. VaR is often used to assess the risk level of a portfolio, asset or liability so that investors or traders can better understand their risk exposure and take appropriate risk management measures.

2. Historical Simulation

The historical simulation method estimates future risks by looking back at historical data, sorting the historical return series in chronological order, and then selecting a certain amount of historical data to calculate the quantile of its return, which is VaR. For example, select the historical data of the past year and calculate the 5th percentile of its return, which is the VaR at the 95% confidence level.

3. Use Python to calculate the Historical Simulation Method to calculate VaR

We will calculate VaR using historical stock price data, which is available through the Yahoo Finance API. To simplify calculations, we will assume that returns follow a normal distribution.

First, we need to import the required libraries and modules, including pandas, numpy, matplotlib, and yfinance:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import yfinance as yf

Next, we need to define some parameters. In this demo, we will use a standard rolling window with a length of 252 trading days, representing the number of trading days in a year. We will also set the VaR confidence level to 95%.

# 设置收益率窗口长度为252个交易日
rolling_window = 252

# 设置VaR置信水平为95%
alpha = 0.05

Then, we need to get historical stock price data. In this demo, we will obtain historical price data for Apple Inc. (AAPL).

# 使用yfinance获取AAPL的历史价格数据
stock_data = yf.download("AAPL", start="2016-01-01", end="2022-03-25")

Next, we need to calculate the rate of return. In this demo, we will calculate the return using daily closing prices and convert it to logarithmic return.

# 计算每日收益率
stock_data["Returns"] = stock_data["Adj Close"].pct_change()

# 将每日收益率转换为对数收益率
stock_data["Log Returns"] = np.log(1 + stock_data["Returns"])

Now we can start calculating VaR. First, we need to use a rolling window to calculate the historical return series for each trading day. We will then use these historical returns to estimate the mean and standard deviation and calculate the corresponding VaR.

# 使用滚动窗口计算历史收益率序列
historical_returns = stock_data["Log Returns"].rolling(window=rolling_window).sum()

# 计算历史收益率序列的均值和标准差
mu = historical_returns.mean()
sigma = historical_returns.std()

# 计算VaR
var = -1 * np.sqrt(rolling_window) * (mu + sigma * np.percentile(historical_returns, 100 * alpha))

 Finally, we can plot the yield versus historical simulated VaR and print out the VaR value.

# 绘制收益率和VaR曲线
fig, ax = plt.subplots()
ax.plot(stock_data.index, historical_returns, label="Historical Returns")
ax.axhline(y=var, color="r", label="VaR")

# 添加图例和标签
ax.legend()
ax.set_xlabel("Date")
ax.set_ylabel("

Guess you like

Origin blog.csdn.net/DonFred/article/details/129821632