Reputation: 21
import math
import numpy as np
def ExplicitMethod(S0, K, r, q, T, Sigma, M, N, Option):
M = int(M)
N = int(N)
dt = T / N
K = float(K)
Smax = 2 * K
dS = Smax / N
FGrid = np.zeros(shape=(N+1, M+1))
if Option == 'Call':
FGrid[-1, :] = np.maximum(np.arange(0, M+1) * dS - K, 0)
elif Option == 'Put':
FGrid[-1, :] = np.maximum(K - np.arange(0, M+1) * dS, 0)
A = np.zeros(shape=(M+1, M+1))
A[0,0] = 1
A[-1,-1] = 1
for j in range(1, M-1):
A[j, (j-1,j, j+1)] = \
[0.5 * dt * (Sigma ** 2 * j ** 2 - (r - q) * j ), \
1 - dt * (Sigma ** 2 * j ** 2 + r), \
0.5 * dt * (Sigma **2 * j ** 2 + (r - q) * j)]
for i in range(N):
Fhat = FGrid [i, ]
FGrid[i, :] = np.dot(A , Fhat)
Fhat[0] = 0
Fhat[-1] = Smax - K * math.exp(-r * (N - i) * dt)
k = math.floor(S0 / dS)
V = FGrid[0, k] + (FGrid[0, k] - FGrid[0, k]) / dS * [(S0 - k * dS)]
print (V)
ExplicitMethod (50, 30, 0.1, 0.05, 2, 0.3, 400, 800, Option = 'Call')
And I got this error:
IndexError Traceback (most recent call last) in () 37 print (V) 38 ---> 39 ExplicitMethod (50, 30, 0.1, 0.05, 2, 0.3, 400, 800, Option = 'Call')
in ExplicitMethod(S0, K, r, q, T, Sigma, M, N, Option) 33 k = math.floor(S0 / dS) 34 ---> 35 V = FGrid[0, k] + (FGrid[0, k] - FGrid[0, k]) / dS * [(S0 - k * dS)] 36 37 print (V)
IndexError: index 666 is out of bounds for axis 1 with size 401
And FYI I'm coding Option Pricing Explicit Method:
Please help, thank you!
Upvotes: 1
Views: 1746
Reputation: 231335
You have initialized FGrid
to be (801,401). The tells us that, for some reason, k=666
k = math.floor(S0 / dS)
V = FGrid[0, k] + (FGrid[0, k] - FGrid[0, k]) / dS * [(S0 - k * dS)]
You need to refine how k
is set. Maybe the math is wrong. At the very least you need to ensure that it does not get above 400.
In [200]: S0=50; K=30; N=800
In [201]: dS = 2*K/N
In [202]: dS
Out[202]: 0.075
In [203]: S0/dS
Out[203]: 666.6666666666667
There's your 666
.
Upvotes: 2