I'm trying to plot the volatility surface using the code 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)
But I get this error :
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) ]
~\anaconda3\lib\site-packages\QuantLib\QuantLib.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
am I using an old version of the package? Because I'm working with a notebook that Goutham Balaraman shared in 2016.
Thank you for your help !
The QuantLib functions and class methods are exposed from C++ through wrappers that perform type conversion from Python types to the underlying C++ types. The obvious ones are defined (Python
intto C++int, Pythonfloatto C++double, even Pythonintto C++doubleif needed) but others are not.In your case, the C++ function takes two doubles, but
xandyare numpy types (you can check this with aprint(type(x))orprint(type(x))).ycomes fromnp.arange(0, 2, 0.1)and is of typenp.float64, which can converts tofloatand then C++double.x, instead, comes fromnp.arange(535, 750, 1)and is of typenp.int64which doesn't convert automatically tofloat, hence the error.One way to make this work is to cast the variable explicitly, that is,
Another is to use
which generates an array of
np.float64instead ofnp.int64.