Skip to content

Instantly share code, notes, and snippets.

@ycytai
Last active December 8, 2023 14:10
Show Gist options
  • Save ycytai/753b904e9f316a55c4877df80ea345a0 to your computer and use it in GitHub Desktop.
Save ycytai/753b904e9f316a55c4877df80ea345a0 to your computer and use it in GitHub Desktop.
import scipy.stats as st
import numpy as np
def binomial_tree_pricing_model(
option_type: str,
s: float,
k: float,
r: float,
v: float,
q: float,
t: float,
n: int,
) -> float:
"""
Parameters:
option_type: option type, use 'call' or 'put'
s: spot price
k: strike price
r: interest rate
v: volatility
q: yield rate
t: maturity(year)
n: periods
---
Test1:
binomial_tree_pricing_model(
option_type = 'call', s = 810, k = 800, r = 0.05,
v = 0.2, q = 0.02, t = 6/12, n = 2
)
Output:
53.3947
---
Test2:
binomial_tree_pricing_model(
option_type = 'put', s = 50, k = 50, r = 0.1,
v = 0.4, q = 0, t = 5/12, n = 5
)
Output:
4.3190
"""
delta_t = t / n
u = np.exp(v * np.sqrt(delta_t))
d = np.exp(-v * np.sqrt(delta_t))
p = (np.exp((r - q) * delta_t) - d) / (u - d)
asset_price = [s * (u**j) * (d ** (n - j)) for j in range(n + 1)]
if option == "call":
option_price = [max(s - k, 0) for s in asset_price]
elif option == "put":
option_price = [max(k - s, 0) for s in asset_price]
else:
raise ValueError("Wrong option input.")
option_tree = [[] for _ in range(n)]
option_tree.append(option_price)
for i in range(1, n + 1):
last_level = option_tree[n - i + 1]
for j in range(1, len(last_level)):
down_price = last_level[j - 1]
up_price = last_level[j]
option_tree[n - i].append(
np.exp(-r * delta_t) * (up_price * p + down_price * (1 - p))
)
return option_tree[0][0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment