## Binomial & Trinomial Trees – Matlab Code

In this Matlab code, we value European call options using binomial and trinomial trees. These lattice based computational models are very popular in mathematic finance for option pricing.

```% binomial tree

clear all;
clc;
echo off;

% inputs
S = 32; % stock price
K = 30; % strike price
r = 0.05; % risk-free rate
sigma = 0.24; % volatility
T = 0.5; % time to maturity

N = 500; % number of steps
dt = T/N;

c = 0.5 * (exp(-r * dt) + exp((r + sigma^2) * dt));
u = c + sqrt(c^2-1);
d = c - sqrt(c^2-1);
p = (exp(r * dt) - d)/(u - d);

T1 = S * u.^((N:-1:0)').* d.^((0:N)');
T1= max(T1 - K, 0);
Back = p * eye(N+1,N+1) + (1-p) * diag(ones(N,1),1);
for i = N:-1:1
discounted = Back(1 : i, 1 : i + 1) * T1 * exp(-r*dt);
T1 = discounted;
end

Option_Value = T1;
display(Option_Value)

% trinomial tree

% inputs
T = 0.5;
N = 500;
r = 0.05;
K = 30;
S = 32;
sigma = 0.24;

dt = T / N;

RR = exp(r * dt);
Df = exp(-r * dt);
u = 1/d;
d = exp(-sigma * sqrt(3 * dt));
Pu = (r * dt * (1 - d) + (r * dt)^2 + sigma^2 *dt) / ((u-d) * (u - 1));
Pd = (r * dt * (1 - u) + (r * dt)^2 + sigma^2 *dt) / ((u-d) * (1 - d));
Pm = 1 - Pu - Pd;

Value = zeros(N,1);

for i = 0 : (2 * N)
State = i + 1;
Value(State) = max(0, (S * u ^ max(i - N, 0) * d ^ max(N * 2 - N - i, 0) - K));
end

for j = (N - 1): -1 :0
for i = 0 : (j * 2)
State = i + 1;
Value(State) = (Pu * Value(State + 2) + Pm * Value(State + 1) + Pd * Value(State)) * Df;
end
end

Trinomial = Value(1);

echo on;
```