
Daily Speculations The Web Site of Victor Niederhoffer & Laurel Kenner Dedicated to the scientific method, free markets, deflating ballyhoo, creating value, and laughter; a forum for us to use our meager abilities to make the world of specinvestments a better place. 
%Market VaR (simulation based)
%Gabe Carbone Aug 2006
%Returns is a 1...N row vector of stock market returns
%WindowRet is a 1...30 row vector; it is a 30 day lookback window of returns
%RetIndex is the index of WindowRet
%RandRetIndex is a randomization of RetIndex
%RandWindowRet is a randomization of WindowRet, created by applying
%WindowRet to RandRetIndex
%RandWindowRetVar is the x percentile of RandWindowRet, this is the one
%realization of the simulationbased VaR
%WindowRetVar is the mean of all 1000 realizations of RandWindowVar. It is
%an N30 row vector.
%define i as the variable for the toplevel loop from 1 to N31
for i=1:(length(Returns(:,1))31)
%define j as the variable for the lookback window
for j=1:30
WindowRet(j,1)=Returns(i+j,1);
end
%calculate RetIndex
RetIndex(:,1)=find(WindowRet(:,1));
%define k as the variable for the number of VaR simulations
for k=1:1000
%calculate randomized RetIndex using the uniform distribution
RandRetIndex(:,1)=unidrnd(RetIndex(:,1));
%calculate RandWindowRet using RandRetIndex as the index for WindowRet
RandWindowRet(:,1)=WindowRet(RandRetIndex(:,1),1);
%calc a realization of the VaR using the percentile function and a 5%
%cutoff
RandWindowRetVar(k,1)=prctile(RandWindowRet(:,1),5);
end
%calc WindowRetVar with each element being an average of all the VaR
%simulations for the corresponding lookback window
WindowRetVar(i,1)=mean(RandWindowRetVar(:,1))
end