【发布时间】:2020-04-02 14:09:56
【问题描述】:
我正在尝试创建两个类来为选项定价。第一个类捕获选项的参数,第二个生成路径。我需要将一些变量(基础波动率的起点)从第一类传递到第二类。但是,我指的是头等舱的方式有问题。我将不胜感激。
这是代码(我使用的是 VSCode (1.43.2) 和 Python(3.7.3)):
class bsEuroParam(object):
# model parameters of a European option
# pc = put/call
#type = vanila, lookback, asian
def __init__(self,pc,type,So,K,T,Vol,r):
self.pc = pc
self.type = type
self.So = So
self.K = K
self.T = T
self.Vol = Vol
self.r = r
class mcPaths(OptParam):
def __init__(self,numPaths=None,numSteps=None):
***OptParam.__init__(self)***
self.numPaths = numPaths
self.numSteps = numSteps
def paths(self):
dt=self.So/self.numSteps
S=np.zeros((self.numSteps,self.numPaths+1))
S[0]=self.So
for t in range(1,self.numSteps+1):
S[t]=S[t-1]*np.exp((self.r - 0.5 * self.Vol **2) * dt + self.Vol * math.sqrt(dt)*npr.standard_normal(self.numPaths+1))
self.results = np.array(S)
我在类mcPaths 顶部的第三行中做错了。我不太确定引用第一类的正确方法是什么。
在运行代码之前,我收到以下pylint 警告:
未绑定方法调用中的参数“X”没有值” 类 OptParam 中定义的参数。
Pylint 突出显示 mcPaths 类下的行中的 optParam,表明这是错误的根源。
当我运行如下代码时:
myopt = OptParam('c','eur',100,100,1,0.75,0.02)
mySims = mcPaths(10,50)
第一行运行良好。第二行,mySims=mcPaths(10,50),返回:
TypeError Traceback (most recent call last)
filepath\pytest12.py in
----> 9 mySims = mcPaths(10,50)
filepath\pytest12.py in __init__(self, numPaths, numSteps)
30 class mcPaths(OptParam):
31 def __init__(self,numPaths=None,numSteps=None):
---> 32 OptParam.__init__(self)
33 self.numPaths = numPaths
34 self.numSteps = numSteps
TypeError: __init__() missing 7 required positional arguments: 'pc', 'type', 'So', 'K', 'T', 'Vol', and 'r'
----------------基于与 Delena 讨论的代码编辑
Class OptParam(object):
# model parameters of a European option
# pc = put/call
#type = vanila, lookback, asian
def __init__(self,pc,type,So,K,T,Vol,r):
self.pc = pc
self.type = type
self.So = So
self.K = K
self.T = T
self.Vol = Vol
self.r = r
#myopt=bsEuroParam('c','eur',100,100,1,0.75,0.02)
class mcPaths(OptParam):
def __init__(self,numPaths=None,numSteps=None,optPrm_val=None):
#OptParam.__init__(self)
self.numPaths = numPaths
self.numSteps = numSteps
self.So = optPrm_val.So
self.Vol = optPrm_val.Vol
self.r = optPrm_val.r
def paths(self):
dt=self.So/self.numSteps
S=np.zeros((self.numSteps,self.numPaths+1))
S[0]=self.So
for t in range(1,self.numSteps+1):
S[t]=S[t-1]*np.exp((self.r - 0.5 * self.Vol **2) * dt + self.Vol * math.sqrt(dt)*npr.standard_normal(self.numPaths+1))
self.results = np.array(S)
打电话:
myopt=OptParam('c','eur',100,100,1,0.75,0.02)
mysim = mcPaths(10,50,myopt)
错误: 11 mysim = mcPaths(10,50,myopt) init() 接受 1 到 3 个位置参数,但给出了 4 个
【问题讨论】:
-
运行代码时是否报错?
-
感谢@PNX。甚至在运行代码之前,对于所有参数,我都会收到 pylint 警告(“未绑定方法调用中的参数“X”没有值”。运行代码时,调用 mcPaths 时出现以下错误:“TypeError: __init__( ) 缺少 7 个必需的位置参数:'pc'、'type'、'So'、'K'、'T'、'Vol' 和 'r'"
-
您正在尝试创建一个新的
OptParam对象,但没有传递它所需的所有参数。你能解释一下你想用这条线实现什么:OptParam.__init__(self)? -
感谢@DelenaMalan。我正在尝试找到一种方法来传递这些论点……而且我正在努力寻找正确的方法来做到这一点。我认为使用您提到的那一行可以将变量从 OptParam 传递到 mcPaths....但我错了....