if nargin~=9
return
end
2. Use If statement to check whether these parameters are valid (Time, stock
price, maximum stock price K and variance must be more than 0. Matrix
dimensions must be more than 1).
3. Use If statement to check whether we enter the correct type of option pricing.
if T<=0||S<0||K<0||sigma<0||N<1||M<1||Smax<=0
return
end
Otype 1 equates to call option pricing, Otype 2 for put option pricing.
return
end
Step 2: Set up the matrix
In this step, we will be following the use of these formula:
1. According to the first line of the algorithm, we require a matrix of size I,J. This
line of code sets up a matrix of zeroes with I*J dim.
f = zeros(N+1,M+1);
2. Second portion of algorithm requires us to set up the time and stock price
vectors of N+1,M+1 size(since it includes 0). We define it using the linspace
function.
Tvec = linspace(0,T,N+1);
Svec = linspace(0,Smax,M+1);
dt = T/N;
ds = Smax/M;
Step 3: Set up initial values of f
According to the algorithm, we calculate initial values of f with the values calculated
in step 2, and that which is defined with the algorithm given above and below. This
depends also whether it is a call or put option pricing. We use switch function to
funnel the values between the two codes depending on the initial otype the user
keys in.
switch otype
case 0
f(N+1,0+1:M+1) = max(Svec-K,0);
f(:,0+1) = 0;
case 1
f(N+1,0+1:M+1) = max(K-Svec,0);
f(:,0+1) = K*exp(-r*(T-Tvec));
f(0+1:N+1,M+1) = 0;
end
Step 4: Explicit Method
Next, we simply calculate a, b c, for the respective values of j using the algorithm
provided
for j=1:M-1
a(j) = (1/2)*dt*(sigma^2*j^2-r*j);
b(j) = 1-dt*(sigma^2*j^2+r);
c(j) = (1/2)*dt*(sigma^2*j^2+r*j);
end
Step 5
% Built the matrix multiplier A according to matrix notation.
Essentially filling in the diagonals with the a,b,c values in step 4
using diag function.
Step 6
1. Do matrix multiplication for AF. Do transposing so rows of A = columns of F
switch otype
case 0
f(i+1,0+1:M+1) = A*(f(i+1+1,0+1:M+1)');
f(i+1,0+1)=0;
f(i+1,M+1)=Smax - K*exp(-r*(N-i)*dt);
end
case 1
f(i+1,0+1:M+1) = A*(f(i+1+1,0+1:M+1)');
f(i+1,0+1)= K*exp(-r*(N-i)*dt);
f(i+1,M+1)= 0;
end
end
option_price = interp1(Svec,f(0+1,:),S);