% Generate Brownian paths to simulat stock prices following the B-S model
% and price various options that could be path-dependent. In the following
% a knock-out call is used as an example.
clear
M = input('enter the number of paths: ');
N = input('enter the number of steps: ');

S0 = 100;
strike = 100;
barrier = 120;

sigma = input('enter sigma: ');

r = 0.01;
mu = r - 0.5*sigma^2;
T = 0.5;
dt = T/N;

x = zeros(M,N+1);
w = randn(M,N);
payoff = zeros(M,1);

t = 0:dt:T;

% generate brownian paths:
for k=1:N
    x(:,k+1) = x(:,k) + mu*dt + sigma*sqrt(dt)*w(:,k);
end

% generate geometric brownian paths:
Sprice = S0*exp(x);

for j=1:M
    if max(Sprice(j,:)) > barrier
        payoff(j) = 0;
    else
        payoff(j) = 0.5*(Sprice(j,N+1)-strike + abs(Sprice(j,N+1)-strike));
    end
end

V0 = exp(-r*T)*mean(payoff);

fprintf('MC price is %10.6f\n',V0);
