I am new to Python and am trying to optimize the following code:
import sys
import numpy as np
def LSMPut(T, r, sigma, K, S0, TimeSteps, Paths, k):
dt = T/TimeSteps
t = np.arange(0, T+dt, dt).tolist()
z=[np.random.standard_normal() for _ in range(Paths)]
w = (r-sigma**2/2)*T + sigma*np.sqrt(T)*np.array(z)
S = S0*np.exp(np.array(w))
P=np.maximum(K-np.array(S),0)
for i in range(TimeSteps-1, -1, -1):
z=[np.random.standard_normal() for _ in range(Paths)]
w = t[i]*np.array(w)/t[i+1] + sigma*np.sqrt(dt*t[i]/t[i+1])*np.array(z)
S = S0*np.exp(np.array(w))
itmPaths = [index for index,value in enumerate(K-np.array(S)) if value > 0]
itmS = S[itmPaths]
Pt = K - np.array(itmS)
itmDiscP = P[itmPaths]*np.exp(-r*dt)
A = BasisFunct(itmS, k)
beta = np.linalg.lstsq(A,itmDiscP)[0]
C = np.dot(A,beta)
exPaths = [itmPaths[i] for i, value in enumerate(zip(Pt, C)) if value[0] > value[1]]
restPaths = np.setdiff1d(np.arange(0, Paths-1, 1).tolist(), exPaths) # Rest of the paths
P[exPaths] = [Pt[i] for i, value in enumerate(zip(Pt, C)) if value[0] > value[1]]
P[restPaths] = np.array(P[restPaths])*np.exp(-r*dt)
u=np.mean(P*np.exp(-r*dt))
return u
def BasisFunct(X, k):
Ones=[1 for _ in range(len(X))]
if k == 1:
A = np.column_stack((Ones,1 - np.array(X)))
elif k == 2:
A = np.column_stack((Ones,1 - np.array(X),1/2*(2-4*np.array(X) + np.array(X)**2)))
elif k == 3:
A = np.column_stack((Ones,1 - np.array(X),1/2*(2-4*np.array(X) + np.array(X)**2), 1/6*(6-18*np.array(X) + 9*np.array(X)**2-np.array(X)**3)))
elif k == 4:
A = np.column_stack((Ones,1 - np.array(X),1/2*(2-4*np.array(X) + np.array(X)**2), 1/6*(6-18*np.array(X) + 9*np.array(X)**2-np.array(X)**3),1/24*(24 - 96*np.array(X) + 72*np.array(X)**2 - 16*np.array(X)**3 + np.array(X)**4)))
elif k == 5:
A = np.column_stack((Ones,1 - np.array(X),1/2*(2-4*np.array(X) + np.array(X)**2), 1/6*(6-18*np.array(X) + 9*np.array(X)**2-np.array(X)**3),1/24*(24 - 96*np.array(X) + 72*np.array(X)**2 - 16*np.array(X)**3 + np.array(X)**4),1/120*(120-600*np.array(X)+600*np.array(X)**2-200*np.array(X)**3+25*np.array(X)**4-np.array(X)**5)))
else:
sys.exit("Too many basis functions requested")
return A
print(LSMPut(1, 0.06, 0.15, 100, 90, 20, 1000000, 5))
The purpose of the code is to calculate the price of an American put option. The time to execute if Paths > 1,000,000 takes a long time, especially if I perform a sensitivity analysis. I would like to find out if there is any way for me to optimize the code or accelerate the processing time. Thank you.