Skip to main content
 首页 » 编程设计

Python:针对函数的一个变量进行绘图

2025年05月04日10emanlee

我已经思考了一段时间了:

我有一个函数在求解之前依赖于五 (5) 个变量 (Black-Scholes)。在我解决了这个 BS 实例的价格之后,我想创建一系列不同的输入(比如时间)并将它们与相应的输出(解决方案,所有其他变量保持不变)进行对比。

所以希望我会策划类似的事情

class BS 
 
    def __init__(self, args) 
        self.a = float(args[0]) 
        self.b = float(args[1]) 
        self.c = float(args[2]) 
        self.d = float(args[3]) 
        self.e = float(args[4]) 
    ... 
    ... 
    the math 
    ... 
    ... 

现在,我可以创建该类的一个实例,其中包含一个根据 T 或时间计算价格的方法。

def price(self) 
   'math that only requires T' 
    return price 

所以,我只需要运行 BS.price() 就可以输出类似的东西

t = range(T-200, T+200, 1) 
 
prices = [BS.price() for x in t] 
rhos = [BS.rho() for x in t] 
vegas = [BS.vega() for x in t] 
parities = [BS.parity() for x in t] 
 
 
pylab.plot(prices,t) 
pylab.plot(rhos,t) 
pylab.plot(vegas,t) 
pylab.plot(parities,t) 

如果价格的唯一变量是时间。有没有更好的方法来观察 python 的单变量依赖?我更喜欢 R,但这不取决于我。

感谢您的帮助!

编辑:当时间变量正在进行 math.sqrt() 和 scipy.cdf() 等数学运算时,我不知道如何使用列表理解。有没有办法做到这一点?我知道如何构建依赖于变量 t 的函数,一个 float 。我如何将值列表输入 math.sqrt() 或 scipy.cdf()?感谢您的帮助!

请您参考如下方法:

I don't know how to use list comprehensions when the time variable is undergoing math operations like math.sqrt() and scipy.cdf(). Is there a way to do this? I know how to build the function relying on variable t, a float. How would I input a list of values into math.sqrt() or scipy.cdf()?

有几个选项需要考虑:

  • Python 生成器允许您在遍历集合/值列表时即时生成结果。这是一个很好的讨论:
    http://wiki.python.org/moin/Generators

  • Python 的 map 和 reduce 函数允许您将函数(例如 sqrt)应用于列表中的每个元素,并且使用 reduce 可以将列表中某些操作的每个结果缩减为单个值(检查 2.1“映射列表"):
    http://www.siafoo.net/article/52