Algo to calculate option prices using Binomial Model
Build a simple computer program in step by step to help you calculate option contract prices using binomial option pricing model.
By Akash MitraIn the last article, I explained the theory behind the binomial option pricing model. Now is the time to do some hands-on coding.
The Simplified Program
So, without any more delay, here is a Python program that uses the binomial option pricing model to calculate the price of a call option:
import numpy as np
def binomial_option_price(S, K, r, sigma, T, N, option_type):
"""
Calculates the price of a call or put option using the binomial option pricing model.
Parameters
----------
S: float
The current price of the underlying asset.
K: float
The strike price of the option.
r: float
The risk-free interest rate.
sigma: float
The volatility of the underlying asset.
T: float
The expiration time of the option, in years.
N: int
The number of steps in the binomial tree.
option_type: str
The type of option, either "call" or "put".
Returns
-------
float
The price of the option.
"""
# Calculate dt and u
dt = T / N
u = np.exp(sigma * np.sqrt(dt))
# Calculate p
p = (np.exp(r * dt) - 1 / u) / (u - 1 / u)
# Create the binomial tree
tree = np.zeros((N + 1, N + 1))
for i in range(N + 1):
for j in range(i + 1):
tree[j, i] = S * (1 / u)**j * (u**(N - i))**(N - j)
# Calculate option values at each node
if option_type == "call":
option_values = np.maximum(tree - K, 0)
elif option_type == "put":
option_values = np.maximum(K - tree, 0)
else:
raise ValueError("Invalid option type")
# Use backward induction to determine option value at time 0
for i in range(N - 1, -1, -1):
for j in range(i + 1):
option_values[j, i] = np.exp(-r * dt) * (p * option_values[j, i + 1] + (1 - p) * option_values[j + 1, i + 1])
return option_values[0, 0]
It is important to understand the above program first as this is the most easiest version of the required calculation.
I have provided ample comments in the program to help you go through it. If you have already read my last article on the theory, and if you read the above program with my comments it should not be difficult to understand.
Using the Program
To use this function, you can pass in the relevant parameters such as the current stock price, the strike price, the risk-free interest rate, the volatility, the expiration time, the number of steps in the binomial tree, and the option type ("call" or "put"). The function will then return the price of the option.
Here is an example of how you might use the function:
S = 100
K = 110
r = 0.05
sigma = 0.2
T = 1
N = 365
option_type = "call"
option_price = binomial_option_price(S, K, r, sigma, T, N, option_type)
print(f"The price of the {option_type} option is {option_price:.2f}")
This would output the following: 1.39