Google News
logo
Python Program to Implement Binomial Tree
In the following example of a Python program that implements a binomial tree :
Program :
import math

def binomial_tree(S, K, r, sigma, T, N):
    # Calculate the parameters of the binomial tree
    dt = T / N
    u = math.exp(sigma * math.sqrt(dt))
    d = 1 / u
    p = (math.exp(r * dt) - d) / (u - d)
    q = 1 - p

    # Initialize the stock price and option value arrays
    stock_prices = [[0 for j in range(i+1)] for i in range(N+1)]
    option_values = [[0 for j in range(i+1)] for i in range(N+1)]

    # Set the final stock prices and option values
    for j in range(N+1):
        stock_prices[N][j] = S * u**(N-j) * d**j
        option_values[N][j] = max(stock_prices[N][j] - K, 0)

    # Calculate the option values at earlier time steps
    for i in range(N-1, -1, -1):
        for j in range(i+1):
            stock_prices[i][j] = S * u**(i-j) * d**j
            option_values[i][j] = math.exp(-r * dt) * (p * option_values[i+1][j] + q * option_values[i+1][j+1])

    # Return the option value at time 0
    return option_values[0][0]

# Example usage
S = 100  # Initial stock price
K = 105  # Strike price
r = 0.05  # Risk-free rate
sigma = 0.2  # Volatility
T = 1  # Time to maturity
N = 100  # Number of time steps

option_value = binomial_tree(S, K, r, sigma, T, N)
print(f"The option value is {option_value:.2f}")
Output :
The option value is 8.03
In this example, the `binomial_tree()` function calculates the option value using a binomial tree with the specified parameters. The `dt`, `u`, `d`, `p`, and `q` variables represent the time step size, up and down factors, and probabilities of up and down movements, respectively.

The `stock_prices` and `option_values` arrays represent the stock prices and option values at each node of the tree.

The function first sets the final stock prices and option values at the last time step (`N`). It then iterates backward through the tree, calculating the option value at each earlier time step using the formula for the risk-neutral probability and the expected option value at the next time step.

The example usage at the bottom of the program demonstrates how to call the function and print the resulting option value. Note that the option value is calculated using the risk-neutral valuation principle, which assumes that the stock price follows a lognormal distribution and that investors are risk-neutral.