我有一个股票指数,我需要使用MC模拟计算VaR,并将几何布朗运动模型作为随机过程。这是我的第一次尝试,无视gbm,只是为了熟悉程序和语法:
x=logreturn; %file with 500 returns
mu=mean(x),
sigma=sigma(x),
rand=normrnd(mu,sigma,2000,1); %random normal distr numbers
VaR=quantile(rand,0.05); %95 percent VaR
VaR=-0.045
它是非常基本的并且仅计算一天的VaR,但是我需要计算前250天的VaR,其中mu和sigma的滚动窗口为250天。
根据艾哈迈德的评论,我试图实现arrayfun和cellfun的全部功能:
x=logreturn;
mu=movmean(x,250);
sigma=movstd(x,250);
mydata = normrnd(0,1,1,20000)
muforsample=arrayfun(@(v) mu*250, mu, 'un', false);
sigmaforsample=arrayfun(@(v) sigma*sqrt(250), sigma, 'un', false);
k=arrayfun(@(v) muforsample-(sigmaforsample.^2)/2, muforsample, sigmaforsample, 'un', false); %this line is faulty and gives an error message (too many input arguments)
t=1/504;
sqrtt=sqrt(t);
gbm=k*t+sigmaforsample*sqrtt; %didnt't try to fix this since I don't have a k
VaR=quantile(gbm, 0.05) %unchanged, needs cellfun too, right?
对于k,我基本上需要一个基于相应的muforsample和sigmaforsample的值,这样我就可以计算出gbm
答案 0 :(得分:1)
使用for
循环肯定比cellfun
和arrayfun
更容易。这是我的解决方案:
% file with log returns until t(n-1)
x = logreturns;
t = 1/250;
% mu and sigma based on 250 returns, moving window
mu = movmean(x,250);
sigma = movstd(x,250);
% k for every cell
k = zeros(size(mu));
for i = 1:length(mu);
k(i) = mu(i)*250 - (((sigma(i)*sqrt(250)).^2)/2);
end
% 0.99 or 0.95 VaR, quantiles based on 500,000 values
VaR = zeros(size(mu));
for j = 1:length(mu)
VaR(j) = quantile(normrnd(0,1,1,500000) * sqrt(t) * ...
(sigma(j) * sqrt(250)) + k(j) * t, 0.01);
end
这是顺便说一句的公式: