Sure! Here's an example of a Python function that can price any European or American payoff under a Black Scholes model with binomial trees:
python
import numpy as np
import math
def binomial_tree_option_price(S0, K, r, T, sigma, N, option_type):
# Calculate parameters
dt = T / N
u = math.exp(sigma * math.sqrt(dt))
d = 1 / u
p = (math.exp(r * dt) - d) / (u - d)
# Initialize stock price tree and option value tree
stock_tree = np.zeros((N+1, N+1))
option_tree = np.zeros((N+1, N+1))
# Fill in stock price tree
for i in range(N+1):
for j in range(i+1):
stock_tree[j, i] = S0 * (u**j) * (d**(i-j))
# Calculate option values at final nodes
for j in range(N+1):
if option_type == 'call':
option_tree[j, N] = max(stock_tree[j, N] - K, 0)
else:
option_tree[j, N] = max(K - stock_tree[j, N], 0)
# Calculate option values at earlier nodes
for i in range(N-1, -1, -1):
for j in range(i+1):
if option_type == 'call':
option_tree[j, i] = max((p * option_tree[j, i+1] + (1-p) * option_tree[j+1, i+1]) / math.exp(r * dt), stock_tree[j, i] - K)
else:
option_tree[j, i] = max((p * option_tree[j, i+1] + (1-p) * option_tree[j+1, i+1]) / math.exp(r * dt), K - stock_tree[j, i])
# Return option price
return option_tree[0, 0]
# Example usage
S0 = 100 # initial stock price
K = 100 # strike price
r = 0.05 # risk-free interest rate
T = 1 # time to maturity (in years)
sigma = 0.2 # volatility
N = 100 # number of time steps
option_type = 'call' # 'call' or 'put'
option_price = binomial_tree_option_price(S0, K, r, T, sigma, N, option_type)
print(f"The price of the {option_type} option is: {option_price:.2f}")
Note that this function assumes a risk-neutral probability of the up movement (p) and calculates the option value at each node by discounting the expected value of the option at the next time step. The function takes in the initial stock price (S0), strike price (K), risk-free interest rate (r), time to maturity (T), volatility (sigma), number of time steps (N), and option type ('call' or 'put'). It returns the price of the option.
Please note that this implementation assumes a constant volatility throughout the time steps and does not account for dividends or transaction costs. It is also worth noting that the accuracy of the option price increases as the number of time steps (N) increases.