I have written this piece of code where I am storing the error values as I keep changing the values of three parameters sigma, N and K and then storing the error value for each choice of sigma, K and N
import numpy as np
import scipy.stats as si
from scipy import integrate
import math
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import pandas as pd
import openpyxl
r=0.03
S0=1
T=1
#short maturity
u1=1/4
mu=r
strike=1
deltaK=0.05
K=[]
N=[]
E=[]
d1= (np.log(S0 / strike) + (r + 0.5 * sigma ** 2) * (T)) / (sigma * np.sqrt(T))
d2 = (np.log(S0 /strike) + (r - 0.5 * sigma ** 2) * (T)) / (sigma * np.sqrt(T))
call = (S0 * si.norm.cdf(d1, 0.0, 1.0) - strike * np.exp(-r * (T)) * si.norm.cdf(d2, 0.0, 1.0))
N2=0
#counting number of points in y-axis
for i1 in range(3,31,1):
N2=N2+1
#storing the y-axis values
N=np.zeros(N2)
N[0]=3
for j2 in range(1,N2):
N[j2]=N[j2-1]+1
N3=0
#counting no of points in x-axis
for j1 in range(5,100,5):
N3=N3+1
#storing the x-axis values
K=np.zeros(N3)
K[0]=0.05
for i2 in range(1,N3):
K[i2]=K[i2-1]+0.05
E=np.zeros((130,N2,N3))
for k in range(20,150,1):
sigma=0.01*k+0.01
for l in range(0,N2,1):
N1=3+1*l
for m in range(0,N3,1):
K1=0.05+0.05*m
def f(x):
d= (np.log(x/strike) + (r + 0.5 * sigma ** 2) * (T-u1)) / (sigma * np.sqrt(T-u1))
W1=(si.norm.pdf(d))/(x*sigma*np.sqrt(T-u1))
d11= (np.log(S0/x) + (r + 0.5 * sigma ** 2) * (u1)) / (sigma * np.sqrt(u1))
d22 = (np.log(S0/x) + (r - 0.5 * sigma ** 2) * (u1)) / (sigma * np.sqrt(u1))
call1 = (S0 * si.norm.cdf(d11, 0.0, 1.0) - x* np.exp(-r * (u1)) * si.norm.cdf(d22, 0.0, 1.0))
return W1*call1
hedge=integrate.fixed_quad(f, strike-K1,strike+K1,n=N1)
error=np.log(np.abs(hedge[0]-call))
E[k,l,m]=error
print("The log error for",str(N1),"quadrature points, volatility",str(sigma)," and deltaK=",str(K1)," is:", error)
print("The range of strikes is:", [strike-K1,strike+K1])
I then try to visualise these error values, denoted by E, as a matrix using the following code:
import pandas as pd
df = pd.DataFrame(E,index=N, columns=K)
print(df)
Now, I am trying to visualise the error value as I keep changing the values of K,N as well as sigma and u1. I need to find the optimal value of error for a particular choice of the parameters K,N, sigma and u1. Can someone please suggest me how to do it?
I also wanted to have a separate excel sheet for each choice of sigma and u1. I tried the following:
import pandas as pd
with pd.ExcelWriter('output.xlsx') as writer:
for k in range(20,150,1):
df[k] = pd.DataFrame(E[k],index=N, columns=K)
print("The error for volatility",str( 0.01*k+0.01),"is:")
print(df[k])
df[k].to_excel(writer, sheet_name='Sheet_name_k',)
But it is not working. How do i get a matrix for each choice of sigma? Any help is highly appreciated.