我的代码:
class ImpliedVol:
def __init__(self, flag, mkt_price, spot_price, strike, time_to_maturity,
lower_bound, upper_bound, risk_free_rate=0, maxiter=1000,
method='f'):
self.flag = flag
self.mkt_price = mkt_price
self.S = spot_price
self.K = strike
self.T = time_to_maturity
self.r = risk_free_rate
self.a = lower_bound
self.b = upper_bound
self.n = maxiter
self.method = method
def func(self, vol):
p = Pricer(self.flag, self.S, self.K, self.T, vol, self.r, self.method)
return p.get_price() - self.mkt_price
def get(self):
implied_vol = brentq(self.func, self.a, self.b, self.n)
return implied_vol
使用某些参数创建类的实例工作正常,同时调用方法func
可以根据需要完美地工作:
obj.func(0.54)
Out[11]:
4.0457814868958174e-05
但是在我的实例上调用方法get
会返回以下错误:
/Users/~/miniconda3/lib/python3.5/site-packages/scipy/optimize/zeros.py in brentq(f, a, b, args, xtol, rtol, maxiter, full_output, disp)
436 if rtol < _rtol:
437 raise ValueError("rtol too small (%g < %g)" % (rtol, _rtol))
--> 438 r = _zeros._brentq(f,a,b,xtol,rtol,maxiter,args,full_output,disp)
439 return results_c(full_output, r)
440
TypeError: func() takes 2 positional arguments but 3 were given
答案 0 :(得分:1)
您正在定义:self.n = maxiter
,并将其作为第4个arg调用brentq
。但是,brentq的签名是:scipy.optimize.brentq(f, a, b, args=(), xtol=1e-12, rtol=4.4408920985006262e-16, maxiter=100, full_output=False, disp=True)
因此,请为其提供所需的位置参数(f
,a
,b
),并将maxiter
作为关键字arg传递。像这样:
brentq(self.func, self.a, self.b, maxiter=self.n)
(另外,帮自己一个忙,不要使用那些单字母变量名)