% Program to simulate VAR by the monte-carlo method
% 2 correlated stocks
% James Thompson

mu=[0.001 0.002];           % daily mean return
sigma=[0.01 0.03];          % volatility
t=1;                        % number of periods
n=[2000 1000];               % number of shares of each stock you hold
S0=[130 200];                % Beginning stock prices
rho=0.2;                    % The correlation of the two stocks

iter=10000;               % number of monte carlo iterations we wish to run    
conf=0.999;                  % the confidence level we are working at
event_prob=0.005;           %probability of the event 


covar=[1 rho; rho 1];


% To generate the correlated random variables, we use the cholesky decomposition.
C=(chol(covar))';

Z=normrnd(0,1,iter,2);

X=C*Z';



%Simulate the stock price paths
S11= S0(1)*exp((mu(1)-(1/2)*sigma(1)*sigma(1))*t + sigma(1)*sqrt(t)*X(1,:));
S12= S0(2)*exp((mu(2)-(1/2)*sigma(2)*sigma(2))*t + sigma(2)*sqrt(t)*X(2,:));


event=rand(iter,1);
for i=1:iter
if(event(i)<event_prob)
    event(i)=0.5;
else
    event(i)=1;
end;
end;



% calculate weighted portfolio value for each run
values=(n(1)*S11+n(2)*S12).*event';

% sort the price paths and grab the value sitting at the correct location
% given the confidence level we are working with.

m=mean(values);
values=sort(values);

VAR=m-values(int32((iter*(1-conf))))
