Skip to content

Instantly share code, notes, and snippets.

@Nick3523
Last active January 2, 2020 14:47
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 Nick3523/5b23337e1e0fef38959f69e0a3944c94 to your computer and use it in GitHub Desktop.
Save Nick3523/5b23337e1e0fef38959f69e0a3944c94 to your computer and use it in GitHub Desktop.
import numpy as np
import math
### Parameters ###
sigma = 0.3
T = 200
dt = 1/2000
q = 0. #dividendes rate
r = 0.5 #free-risk rate
S0 = 20
u = math.exp(sigma * math.sqrt(2*dt))
d = 1/u
m = 1
pu = ((math.exp((r-q) * dt/2) - math.exp(-sigma * math.sqrt(dt/2))) /
(math.exp(sigma * math.sqrt(dt/2)) - math.exp(-sigma * math.sqrt(dt/2))))**2
pd = ((math.exp(sigma * math.sqrt(dt/2)) - math.exp((r-q) * dt/2)) /
(math.exp(sigma * math.sqrt(dt/2)) - math.exp(-sigma * math.sqrt(dt/2))))**2
pm = 1 - pu - pd
#Formulas taken from wikipedia, see : https://www.wikiwand.com/en/Trinomial_tree#/Formula
### init_price() est une fonction qui sert à déterminer la valeur de l'actif sous-jacent S, à chaque noeud de l'arbre ###
def init_price(N):
STs = [np.array([S0])]
for i in range(N):
prev_nodes = STs[-1] #At each loop, take the last element of the list
ST = np.concatenate((prev_nodes*u, [prev_nodes[-1]*m, prev_nodes[-1]*d]))
STs.append(ST)
return STs
### payoff_compute() sert à déterminer le prix de l'option, à chaque noeud de l'arbre ###
def payoff_compute(STs,N, K) :
callMatrix = [None] * N #Empty list of size N
putMatrix = [None] * N #Empty list of size N
for i in reversed(range(N)):
if(i == N-1) :
payoffCall = np.maximum(0, max(STs[i]-K)) #The payoff list is sorted, so take the first one
payoffPut = np.maximum(0, max((K-STs[i])))#The payoff list is sorted, so take the first one
else :
payoffCall = math.exp(-(r-q)*dt) * (pu*callMatrix[i+1] + pd*callMatrix[i+1] + pm*callMatrix[i+1])
payoffPut = math.exp(-(r-q)*dt) * (pu*putMatrix[i+1] + pd*putMatrix[i+1] + pm*putMatrix[i+1])
callMatrix.insert(i,payoffCall)
putMatrix.insert(i,payoffPut)
return callMatrix, putMatrix
STs = init_price(20)
c,t = payoff_computer(STs,20, 18)
print("Avec le model trinomial, le prix du put devrait etre", t[0])
print("Avec le model trinomial, le prix du put devrait etre", c[0])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment