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 int
to C++ int
, Python float
to C++ double
, even Python int
to C++ double
if needed) but others are not.
In your case, the C++ function takes two doubles, but x
and y
are numpy types (you can check this with a print(type(x))
or print(type(x))
). y
comes from np.arange(0, 2, 0.1)
and is of type np.float64
, which can converts to float
and then C++ double
. x
, instead, comes from np.arange(535, 750, 1)
and is of type np.int64
which doesn't convert automatically to float
, hence the error.
One way to make this work is to cast the variable explicitly, that is,
black_var_surface.blackVol(y, float(x))
Another is to use
plot_strikes = np.arange(535.0, 750.0, 1.0)
which generates an array of np.float64
instead of np.int64
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.