%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% PRICING A DOWN-AND-OUT BARRIER PUT OPTION 
% stock obeys GBM with r=0.1, s=0.4 (time unit = year = 252 days), current 
% price 50. 60 day european put option, with strike 50, but a barrier at 30 
% - below this the option gets knocked out thus reducing risk for seller. 
% daily observation. use "control variable" of a regular european put 

S0=50;
K=50;
r=0.1;
sigma=0.4;
T=60/252;       % up to here usual parameters for a put 
B=30;           % barrier - see what happens when increase to 35 and 40!  

N=60;           % number of observations 
h=T/N; 

% find V_P, value of the vanilla put without the barrier
d_1=(log(S0/K) + (r + sigma^2/2)*T)/sigma/sqrt(T);
d_2=(log(S0/K) + (r - sigma^2/2)*T)/sigma/sqrt(T);
V_P = K*exp(-r*T)*(1-erf(d_2/sqrt(2)))/2 - S0*(1-erf(d_1/sqrt(2)))/2

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% part 1: estimate the correlation of the barrier and vanilla options 

M=5000;       
Z=randn(M,N);    
S=zeros(M,N+1);   

S(:,1)=S0*ones(M,1);
for i=1:N
    S(:,i+1)=S(:,i).*exp( (r-sigma^2/2)*h+sigma*sqrt(h)*Z(:,i));
end 

worst=min(S,[],2); 
payoff=exp(-r*T)*(worst>B).*(S(:,N+1)<K).*(K-S(:,N+1));  
payoff2=exp(-r*T)*(S(:,N+1)<K).*(K-S(:,N+1)); 

q=cov(payoff,payoff2)        % show the covariance matrix
c=-q(1,2)/q(2,2)             % show c 

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% part 2: the real simulation 

M=45000;        % number of replications 
Z=randn(M,N);    
S=zeros(M,N+1);   

S(:,1)=S0*ones(M,1);
for i=1:N
    S(:,i+1)=S(:,i).*exp( (r-sigma^2/2)*h+sigma*sqrt(h)*Z(:,i));
end 

worst=min(S,[],2); 
payoff=exp(-r*T)*(worst>B).*(S(:,N+1)<K).*(K-S(:,N+1)); 
payoff2=exp(-r*T)*(S(:,N+1)<K).*(K-S(:,N+1)); 

corrected=payoff+c*(payoff2-V_P);

controlled = [mean(corrected),std(corrected)/sqrt(M)]   % answers with control variable 
uncontrolled = [mean(payoff),std(payoff)/sqrt(M)]       % answers without control variable 
vanilla = [mean(payoff2),std(payoff2)/sqrt(M)]          % simulated answers for vanilla option
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
