Python 挥发性表面的三维绘图
我试图绘制一个隐含波动率的三维表面。但我一直收到BS函数的错误消息:Python 挥发性表面的三维绘图,python,python-3.x,numpy,3d,finance,Python,Python 3.x,Numpy,3d,Finance,我试图绘制一个隐含波动率的三维表面。但我一直收到BS函数的错误消息: line 29, in _amin return umr_minimum(a, axis, None, out, keepdims) TypeError:“@Mr.T很抱歉,我现在编辑了完整的回溯。好吧,因为这一行单独使用numpy数组-也许X或Y不是numpy数组?你检查过这个了吗?或者您必须使用np.min和np.max作为您给定的输入?感谢这解决了问题:)直接导致我在BS公式第29行中遇到一个新问题,in _amin
line 29, in _amin
return umr_minimum(a, axis, None, out, keepdims)
TypeError:“@Mr.T很抱歉,我现在编辑了完整的回溯。好吧,因为这一行单独使用numpy数组-也许X或Y不是numpy数组?你检查过这个了吗?或者您必须使用np.min和np.max作为您给定的输入?感谢这解决了问题:)直接导致我在BS公式第29行中遇到一个新问题,in _aminreturn umr_minimum(a,axis,None,out,keepdims)TypeError:“'在评论中,没有人能听到您的提问”-您应该就此提出一个新问题。
def CND(X):
return float(norm.cdf(X))
def BlackScholes(v=0.8,CallPutFlag = 'c',S = 110.,X = 100.,T = 1.,r = 0.01):
try:
d1 = (log(S/X)+(r+v*v/2.)*T)/(v*sqrt(T))
d2 = d1-v*sqrt(T)
if CallPutFlag=='c':
return S*CND(d1)-X*exp(-r*T)*CND(d2)
else:
return X*exp(-r*T)*CND(-d2)-S*CND(-d1)
except: return 0
def calc_impl_vol(price = 5., right = 'c', underlying = 110., strike = 100., time = 1., rf = 0.005, inc = 0.001):
f = lambda x: BlackScholes(x,CallPutFlag=right,S=underlying,X=strike,T=time,r=rf)-price
return optimize.brentq(f,0.,5.)
def mesh_plot2(X,Y,Z):
fig = plt.figure()
ax = Axes3D(fig, azim = -29, elev = 50)
XX,YY,ZZ = make_surf(X,Y,Z)
ax.plot_surface(XX,YY,ZZ, color = 'white')
ax.contour(XX,YY,ZZ)
plt.xlabel("expiry")
plt.ylabel("strike")
def make_surf(X,Y,Z):
XX,YY = np.meshgrid(np.linspace(min(X),max(X),230),np.linspace(min(Y),max(Y),230))
ZZ = griddata(np.array([X,Y]).T,np.array(Z),(XX,YY), method='linear')
return XX,YY,ZZ
F=pd.read_excel('test_data.xlsx')
def get_surf(F):
q=F
q.reset_index(inplace=True)
vals = []
for index, row in q.iterrows():
if row['Type'] == 'c':
underlying = float(row['Underlying_Price'])
price = (float(row['ask'])+float(row['bid']))/2.0
expd = (row['exp'])
exp1 = (expd) / (365)
try:
impl = calc_impl_vol(price, 'c', underlying, float(row['Strike']), exp1)
vals.append([exp,float(row['Strike']),impl])
except:
pass
vals = np.array(vals).T
mesh_plot2(vals[0],vals[1],vals[2])
surf=get_surf(F)