Skip to content

Instantly share code, notes, and snippets.

@S0ngyuLi
Created September 19, 2018 00:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save S0ngyuLi/c6d5994716fed7bfffdfad487232ba37 to your computer and use it in GitHub Desktop.
Save S0ngyuLi/c6d5994716fed7bfffdfad487232ba37 to your computer and use it in GitHub Desktop.
import numpy as np
import scipy.stats as ss
import time
def BinomialTree(type,S0, K, r, sigma, T, N=2000):
#calculate delta T
deltaT = np.divide(float(T), N)
# up and down factor will be constant for the tree so we calculate outside the loop
u = np.exp(sigma * np.sqrt(deltaT))
d = np.divide(1.0, u)
# Initialise our f_{i,j} tree with zeros
fs = [[0.0 for j in xrange(i + 1)] for i in xrange(N + 1)]
#store the tree in a triangular matrix
#this is the closest to theory
#no need for the stock tree
#rates are fixed so the probability of up and down are fixed.
#this is used to make sure the drift is the risk free rate
a = np.exp(r * deltaT)
p = np.divide(np.subtract(a, d), np.subtract(u, d) + np.finfo(float).eps)
oneMinusP = 1.0 - p
# Compute the leaves, f_{N, j}
for j in xrange(i+1):
if type =="C":
fs[N][j] = max(S0 * np.power(u, j) * d**(N - j) - K, 0.0)
elif type =="P":
fs[N][j] = max(-S0 * np.power(u, j) * d**(N - j) + K, 0.0)
else:
print("Please select either C fo Call or P for Put.")
return 0
# calculate backward the option prices
for i in xrange(N-1, -1, -1):
for j in xrange(i + 1):
fs[i][j] = np.exp(-r * deltaT) * (p * fs[i + 1][j + 1] + oneMinusP * fs[i + 1][j])
return fs[0][0]
# set up values here
S0 = 37.72 # current value
K = 38 # target value
r= 0.024 # risk-free rate
sigma = 0.1037 # Volatility
expiring_days = 121.0 #remaining trading days
Otype='C'
print "S0\tstock price at time 0:", S0
print "K\tstrike price:", K
print "r\tcontinuously compounded risk-free rate:", r
print "sigma\tvolatility of the stock price per year:", sigma
# print "T\ttime to maturity in trading years:", T
price_result = []
for i in range(4):
T = (expiring_days - 30 * i)/251.0
price_result.append(BinomialTree(Otype,S0, K, r, sigma, T, 1500))
print(price_result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment