绘制波动率表面时的 QuantLib 错误



我正在尝试使用代码 blelow 绘制波动率表面:

plot_years = np.arange(0, 2, 0.1)
plot_strikes = np.arange(535, 750, 1)
fig = plt.figure()
ax = fig.gca(projection='3d')
X, Y = np.meshgrid(plot_strikes, plot_years)
Z = np.array([black_var_surface.blackVol(y, x) 
for xr, yr in zip(X, Y) 
for x, y in zip(xr,yr) ]
).reshape(len(X), len(X[0]))

surf = ax.plot_surface(X,Y,Z, rstride=1, cstride=1, cmap=cm.coolwarm, 
linewidth=0.1)
fig.colorbar(surf, shrink=0.5, aspect=5)

但是我收到此错误:


TypeError                                 Traceback (most recent call last)
<ipython-input-55-8132b1b292ed> in <module>
4 ax = fig.gca(projection='3d')
5 X, Y = np.meshgrid(plot_strikes, plot_years)
----> 6 Z = np.array([black_var_surface.blackVol(y, x) 
7               for xr, yr in zip(X, Y)
8                   for x, y in zip(xr,yr) ]

<ipython-input-55-8132b1b292ed> in <listcomp>(.0)
4 ax = fig.gca(projection='3d')
5 X, Y = np.meshgrid(plot_strikes, plot_years)
----> 6 Z = np.array([black_var_surface.blackVol(y, x) 
7               for xr, yr in zip(X, Y)
8                   for x, y in zip(xr,yr) ]

~anaconda3libsite-packagesQuantLibQuantLib.py in blackVol(self, *args)
7566 
7567     def blackVol(self, *args):
-> 7568         return _QuantLib.BlackVolTermStructure_blackVol(self, *args)
7569 
7570     def blackVariance(self, *args):

TypeError: Wrong number or type of arguments for overloaded function 'BlackVolTermStructure_blackVol'.
Possible C/C++ prototypes are:
BlackVolTermStructure::blackVol(Date const &,Real,bool) const
BlackVolTermStructure::blackVol(Date const &,Real) const
BlackVolTermStructure::blackVol(Time,Real,bool) const
BlackVolTermStructure::blackVol(Time,Real) const

我使用的是旧版本的软件包吗?因为我正在使用Goutham Balaraman在2016年分享的笔记本。

感谢您的帮助!

QuantLib 函数和类方法通过包装器从C++公开,这些包装器执行从 Python 类型到底层C++类型的类型转换。 显而易见的被定义了(Pythonintto C++int,Pythonfloatto C++double,如果需要,甚至 Pythonint到 C++double),但其他的没有。

在您的情况下,C++函数需要两个双精度,但xy是 numpy 类型(您可以使用print(type(x))print(type(x))进行检查)。y来自np.arange(0, 2, 0.1),属于np.float64型,可以转换为float,然后转换为C++double。 相反,x来自np.arange(535, 750, 1),并且属于np.int64类型,不会自动转换为float,因此错误。

完成这项工作的一种方法是显式转换变量,即

black_var_surface.blackVol(y, float(x))

另一种是使用

plot_strikes = np.arange(535.0, 750.0, 1.0)

生成一个np.float64数组而不是np.int64.

最新更新