【问题标题】:Error importing nested class in python在python中导入嵌套类时出错
【发布时间】:2017-10-30 23:14:15
【问题描述】:

各位专家您好,

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

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

但是,我收到以下错误消息:AttributeError: 'module' object has no attribute '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

【问题讨论】:

    标签: python-3.x class option


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      试试下面,

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

      如果你想调用一个类的方法而不像上面那样创建对象,你需要将你的方法声明为静态。

      我假设你的 .py 文件被命名为 BinomialEuropeanOption.py

      【讨论】:

        猜你喜欢
        • 2016-07-30
        • 2014-05-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-20
        • 1970-01-01
        相关资源
        最近更新 更多