-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinomial.py
More file actions
43 lines (38 loc) · 1.33 KB
/
binomial.py
File metadata and controls
43 lines (38 loc) · 1.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
"http://algo.scu.edu/~sanjivdas/cython.pdf"
import numpy as np
import math
def binomial(s,k,t,v,rf,cp,am=False,n=100):
"Price option using Jarrow-Rud binomial model"
# s : initial stock price
# k : strike price
# t : expiration time
# v : volatility
# rf : risk-free rate
# cp : +1/-1 for call/put
# am : True/False for American/European
# n = binomial steps
# Basic Calculations
h = float(t/n)
u = math.exp((rf - 0.5 * v ** 2) * h + v * math.sqrt(h))
d = math.exp((rf - 0.5 * v ** 2) * h - v * math.sqrt(h))
drift = math.exp(rf * h)
q = (drift - d) / (u - d)
# Process the terminal stock price
stkval = np.zeros((n+1,n+1))
optval = np.zeros((n+1,n+1))
stkval[0,0] = s
for i in range(1,n+1):
stkval[i,0] = stkval[i-1,0]*u
for j in range(1,i+1):
stkval[i,j] = stkval[i-1,j-1]*d
# Backward recursion for option price
for j in range(n+1):
optval[n,j] = max(0,cp*(stkval[n,j]-k))
for i in range(n-1,-1,-1):
for j in range(i+1):
for j in range(i+1):
optval[i,j] = (q*optval[i+1,j]+(1-q)*optval[i+1,j+1])/drift
if am:
optval[i,j] = max(optval[i,j],cp*(stkval[i,j]-k))
return optval[0,0]
#print binomial(100.0,100.0,1.0,0.3,0.03,-1,True,100)