免责声明:本文由作者参考相关资料,并结合自身实践和思考独立完成,对全文内容的准确性、完整性或可靠性不作任何保证。同时,文中提及的数据仅作为举例使用,不构成推荐;文中所有观点均不构成任何投资建议。请读者仔细阅读本声明,若读者阅读此文章,默认知晓此声明。
1. 源代码
复现三种常见VaR测算方法。
import numpy as np
from scipy.stats import norm
import akshare as ak
import pandas as pd
class VaR_model(object):
@staticmethod
def get_history_data(code, st, et):
'''
获取股票对应的历史收益率数据
----------
code:str,股票代码,例如'000001'
st:str,开始日期,例如'20230301'
et:str,结束日期,例如'20231031'
'''
stock_data = ak.stock_zh_a_hist(symbol=code, period="daily", start_date=st,
end_date=et, adjust="qfq")
return stock_data['涨跌幅'] / 100
def __init__(self, data, T, confidence=None):
'''
data: 历史收益率数据
confidence: 置信度
T:int,测算周期,例如10
'''
self.data = data
self.c = confidence or 0.9
self.T = np.sqrt(T)
self._time = 200 # 蒙特卡洛模拟次数
self.r = 0.02 # 无风险利率
def get_simulate_data(self):
# 获取蒙特卡洛模拟的数据
num = len(self.data) # 确认蒙特卡洛的路径数量
vol = np.std(self.data) * np.sqrt(self._time) # 计算年化波动率
s_path = np.zeros((num + 1, self._time))
r = self.r
s_path[0] = 1
Tt = 1 / num
for i in range(1, num + 1):
N = np.random.standard_normal(self._time) # 标准正态分布随机数
ST = s_path[i - 1] * np.exp((r - 0.5 * vol ** 2) * Tt + vol * np.sqrt(Tt) * N)
# 进行涨跌停的限制
max_st = s_path[i - 1] * 1.1
min_st = s_path[i - 1] * 0.9
new_st = np.where(ST < min_st, min_st, ST)
new_st = np.where(ST > max_st, max_st, new_st)
s_path[i] = new_st
return s_path
def History_model(self):
# 历史数据计算VaR的值
new_confidence = (1 - self.c) * 100 # 置信度转分位值
return np.percentile(self.data, new_confidence) * self.T
def Covariance_model(self):
# 参数法计算VaR的值
mean = self.data.mean() # 计算均值
std = self.data.std() # 计算标准差
Z = norm.ppf(1 - self.c) # 给定概率下的正态分布值
Var = Z * std - mean
return Var * self.T
def Monte_Carlo_model(self):
# 蒙特卡洛模拟计算VaR的值
var_list = []
simulate_data = VaR_model.get_simulate_data(self)
for x in range(simulate_data.shape[1]):
re_data = pd.Series(simulate_data[:, x]).pct_change()[1::] # 收益率序列
new_confidence = (1 - self.c) * 100 # 置信度转分位值
Var = np.percentile(re_data, new_confidence)
var_list.append(Var)
return np.mean(var_list) * self.T
if __name__ == '__main__':
# 传入参数
code = '600519'
st, et = '20210101', '20211231'
T = 10
# 获取数据
data = VaR_model.get_history_data(code, st, et)
# 拟合模型
model = VaR_model(data, T, confidence=0.95)
# 输出相应的结果
hm = model.History_model()
cm = model.Covariance_model()
mm = model.Monte_Carlo_model()
print('历史模拟法', hm)
print('参数法法', cm)
print('蒙卡模拟法', mm)
2. 方法介绍
VaR(Value at Risk)按字面解释就是“在险价值”,其含义指:在市场正常波动下,某一金融资产或证券组合的最大可能损失。更为确切的是指,在一定概率水平(置信度)下,某一金融资产或证券组合价值在未来特定时期内的最大可能损失。
VaR的测算方法主要是历史模拟法,参数法,蒙特卡洛模拟法,其中参数是最为常用的方法。