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}")