在python中导入嵌套类时出错

时间:2017-10-30 23:14:15

标签: python-3.x class option

你好专家,

我正在尝试在Python中创建一个简单的(选项)二项式pricer。

我创建了两个类选项,一个是BinomialEuropeanOption,另一个是StockOption;两者都分别保存为.py。

但是,我收到以下错误消息:AttributeError:'module'对象没有属性'price' 有什么建议?非常感谢!

在我的主模块中,我使用以下代码

import BinomialEuropeanOption as EurOption

@xw.func
def EuropeOption(S0, K, r, T, N):
    EuropeOption = EurOption.price(S0, K, r, T, N)
    return EuropeOption

在EuropeOption中,它被写为下面的类。

import math
import numpy as np
from StockOption import StockOption

class BinomialEuropeanOption(StockOption):
    def setup_parameters__(self):
    #""" Required calculations for the model """
        self.M = self.N + 1 # Number of terminal nodes of tree
        self.u = 1 + self.pu # Expected value in the up state
        self.d = 1 - self.pd # Expected value in the down state
        self.qu = (math.exp((self.r-self.div)*self.dt) - self.d) / (self.u-self.d)
        self.qd = 1-self.qu

    def initialize_stock_price_tree_(self):
        # Initialize terminal price nodes to zeros
        self.STs = np.zeros(self.M)

        # Calculate expected stock prices for each node
        for i in range(self.M):
            self.STs[i] = self.S0*(self.u**(self.N-i))*(self.d**i)
            self.STs[i] = self.S0*(self.u**(self.N-i))*(self.d**i)

    def initialize_payoffs_tree_(self):
        # Get payoffs when the option expires at terminal nodes
        payoffs = np.maximum(0, (self.STs-self.K) if self.is_call else(self.K-self.STs))
        return payoffs

    def traverse_tree_(self, payoffs):
        # Starting from the time the option expires, traverse
        # backwards and calculate discounted payoffs at each node
        for i in range(self.N):
            payoffs = (payoffs[:-1] * self.qu + payoffs[1:] * self.qd) * self.df
        return payoffs

    def _begin_tree_traversal__(self):
        payoffs = self._initialize_payoffs_tree_()
        return self._traverse_tree_(payoffs)

    def price(self):
        #""" The pricing implementation """
        self.__setup_parameters__()
        self._initialize_stock_price_tree_()
        payoffs = self.__begin_tree_traversal__()
        return payoffs[0] # Option value converges to first node

2 个答案:

答案 0 :(得分:1)

不是专家,但你必须实例化该类然后调用方法

def EuropeOption(S0, K, r, T, N):
    return EurOption().price(S0, K, r, T, N)

答案 1 :(得分:0)

尝试以下,

    from BinomialEuropeanOption import BinomialEuropeanOption
    ...
    b = BinomialEuropeanOption()
    result = b.price(...)

如果要在不创建上述对象的情况下调用类的方法,则需要将方法声明为静态。

我假设您的.py文件名为BinomialEuropeanOption.py