pandas 对于给定的回报分布,计算风险价值或“最可能的损失”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30878265/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 23:28:33  来源:igfitidea点击:

Calculating Value At Risk or "most probable loss", for a given distribution of returns

pythonpandasstatisticsscipyquantitative-finance

提问by Just another wombat

Given historical daily returns, how can I calculate the portfolio allocation for a single stock position, based on not losing more than 10% of the starting portfolio value over 21 days? (with 95% confidence.)

给定历史每日回报,基于 21 天内不超过初始投资组合价值的 10%,我如何计算单个股票头寸的投资组合分配?(有 95% 的置信度。)

Based on some starting code of e.g.

基于例如的一些起始代码

import numpy as np
from scipy.stats import norm

returns = [-0.01, -0.02, -0.01, 0.04, 0.02, 0.01, -0.03]
mu = np.mean(returns)
std = np.std(returns)
valueAtRisk = norm.ppf(0.05, mu, sigma)

However, the above only tells me my risk for 1 day. My question goes in the other direction; what can I allocate given the distribution of returns, assuming that I don't want to lose more than 10% over 21 days.

但是,以上仅告诉我我 1 天的风险。我的问题是另一个方向;假设我不想在 21 天内损失超过 10%,考虑到回报的分布,我可以分配什么。

I would prefer an answer that can be computed directly, but a Monte Carlo answer would be acceptable.

我更喜欢可以直接计算的答案,但蒙特卡罗答案是可以接受的。

Thanking you kindly for your help.

衷心感谢您的帮助。

回答by Jianxun Li

import numpy as np

returns = np.random.randn(1000)

Assuming returns are independently and identically distributed (i.i.d.), then the volatility of T days equals to the product of sqrt(T) times one-day-volatility.

假设收益独立同分布(iid),那么T天的波动率等于sqrt(T)乘以一天波动率的乘积。

# one-way 5% quantile, critical value is 1.64
VaR_21 = returns.std() * np.sqrt(21) * 1.645
VaR_21
Out[72]: 7.4161618430166989

Alternatively, you can do bootstraps. That's randomly select 21 days from historical dataset, calculate the return over this randomly drawed 21 days. Plot the histogram and get the 5% quantile.

或者,您可以进行引导。那是从历史数据集中随机选择 21 天,计算这个随机抽取的 21 天的回报。绘制直方图并得到 5% 的分位数。

def generate_random_index(n=21):
    # could set replace to False as well
    return np.random.choice(np.arange(1000), size=n, replace=False)  

VaR_simulated_21 = []
n_bootstrap = 10000
for _ in range(n_bootstrap):
    VaR = returns[generate_random_index(21)].sum()
    VaR_simulated_21.append(VaR)

plt.hist(VaR_simulated_21)
np.percentile(VaR_simulated_21, q=5)
Out[108]: -8.0686958215041216

enter image description here

在此处输入图片说明