%  Used for Examples 11.1 and 11.2

load capm.txt ;
data = capm ;
Close_tbill = data(:,1) ;
Close_msft = data(:,2) ;
Close_sp500	= data(:,3) ;
Close_ge = data(:,4) ;
Close_ford = data(:,5) ;
day = data(:,6) ;
month = data(:,7) ;
year = data(:,8) ;
n=length(year) ;
data(n,:)
t = (1:n)' ;

Cl = Close_sp500 ;
retn = Cl(2:n) ./ Cl(1:n-1) - 1;
new_n =1000 ;
ind = (n-new_n):n -1;
new_returns = retn(ind) ;

alpha = .05 ;
K = round(alpha*new_n)


new_returns = sort(new_returns) ;
new_returns(K:K+1)
quantile_nonp = new_returns(K)
VaR_nonpar = -20000 * quantile_nonp

mu = mean(new_returns)

sigma = std(new_returns)
quantile_param =(mu + norminv(alpha)*sigma)
VaR_param = -20000 * quantile_param

tic
niter = 50000 ;
VaRboot = zeros(niter,1) ;
VaRbootparam = VaRboot ;
quant = norminv(alpha) ;
for i = 1:niter ;
    bootind = ceil(1000*rand(1000,1)) ;
    sample = sort(new_returns(bootind)) ;
    VaRboot(i) = -20000*sample(K) ;
    VaRbootparam(i) = mean(sample) + quant*std(sample) ;
end ;
VaRboot = sort(VaRboot) ;
gama = .01 ;
ucl = VaRboot((1-gama/2)*niter) 
lpl = VaRboot(gama*niter/2) 

VaRbootparam = sort(VaRbootparam) ;
gama = .01 ;
uclparam = VaRbootparam((1-gama/2)*niter) 
lplparam = VaRbootparam(gama*niter/2) 
toc


