Matlab Calculating mean of distribution quantile in a for-loop

175 views Asked by At

I am trying to calculate portfolio cVaR (conditional value at risk) levels from my simulated data for various portfolios.

I am able to do that for one single portfolio using the following code:

% Without a for-loop for series 1

test2 = test(:,1)

VaR_Calib_EVT   = 100 * quantile(test2, VarLevel_Calib);
help1           = sum(test2(:) <VaR_Calib_EVT/100);
cVaR_Calib_EVT  = sum(test2(test2 <VaR_Calib_EVT/100)/help1); 

However, when putting a for-loop around (see following code), the output values in cVaR_Calib_EVT are wrong except for the value in in cell (1,1).

VarLevel_Calib           = 0.05;
test                     = trnd(3,780,16); 
nIndices                 = 16;

for i=1:nIndices
    VaR_Calib_EVT  (:,i) = 100 * quantile(test(:,i), VarLevel_Calib);
    help1          (:,i) = sum(test(:,i)<(VaR_Calib_EVT(:,i)/100));
    cVaR_Calib_EVT (:,i) = sum(test(test(:,i) <VaR_Calib_EVT(:,i)/100)/help1(:,i)); 
end

What am I doing wrong?

Best, Carolin

1

There are 1 answers

0
xenoclast On BEST ANSWER

Your test variable is a three-dimensional variable, so when you do

test2 = test(:,1);

and then

test2(:) <VaR_Calib_EVT/100

it's not the same as in your second example when you do

test(:,i)<(VaR_Calib_EVT(:,i)/100)

To replicate the results of your first example you could explicitly do the test2 assignment inside the loop, which should perform as expected.

However note that using only two indices to specify parts of a 3-dimensional matrix will probably behave in unexpected ways and the long-term solution would be to explicitly specify exactly which members of the test matrix you want to include. If you do this you will be able to safely expand your single example into the loop.