%  Creates Figures 11.3 and 11.4.

load capm.txt ;
data = capm ;
clear 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) ;
t = (1:n)' ;

Cl = Close_sp500 ;

% Cl = Close_msft ;


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

R_sort = sort(new_returns) ;
R_sort = R_sort(1:100) ;
n=length(R_sort) 

fit =linregress(log(-R_sort),log((1:n)./n)') ;
fit.beta


figure(2)
clf
fsize=14 ;
p = loglog(-R_sort,(1:n)./n ,'.' ,-R_sort,exp(fit.yhat)) ;
set(gca,'ylim',[10^(-2.2) 1.5])
set(gca,'xlim',[min(-R_sort)-.001 max(-R_sort)+.005])
set(p(2),'linewidth',3)
xlabel('-x','fontsize',fsize) 
ylabel('P(return < -x)','fontsize',fsize) 
set(gca,'xtick',[.03 .05 .1 .15])
set(gca,'fontsize',fsize)

print var_sp500_tail.ps -deps ;


figure(1)
clf
alpha = linspace(.00025,.1,301) ;

varest = 178.*(.1./alpha).^(.262) ;
varestB = 178.*(.1./alpha).^(.228) ;

mu = mean(new_returns) ;
sig = std(new_returns) ;
VaRParam = -10000*(mu + sig*norminv(alpha)) ;
VaRParam2 = -10000*(mu + sig*norminv([.005 .01 .025 .05 ]))


plot(alpha,varest,alpha,VaRParam,'--' ) ;
xlabel('\alpha','fontsize',18) 
ylabel('VaR(\alpha)','fontsize',18) 
set(gca,'fontsize',fsize)
set(gca,'xtick',[ .01 .025 .05 .1])

varest2 = interp1(alpha,varest,[.005 .01 .025 .05 ])
varest2B = interp1(alpha,varestB,[.005 .01 .025 .05 ])

set(gca,'ylim',[100 800])

line([.01 .01],[100 varest2(2)])
line([.025 .025],[100 varest2(3)])
line([.05 .05],[100 varest2(4)])
line([.005 .005],[100 varest2(1)])

line([0 .005],[varest2(1) varest2(1)])
line([0 .01],[varest2(2) varest2(2)])
line([0 .025],[varest2(3) varest2(3)])
line([0 .05],[varest2(4) varest2(4)])

set(gca,'ytick',[fliplr(roundd(varest2,1)) 600 800] )
print var_sp500_est.ps -deps ;

mu = mean(new_returns) ;
sig = std(new_returns) ;
VaRParam = -10000*(mu + sig*norminv([.005 .01 .025 .05 ]))