python - 将变量从类中的另一个函数传递到池
问题描述
下面的代码模拟股票价格并计算其收益。我正在尝试使用多处理来加速模拟。问题是在CallUpAndOut
我拥有的地方pool.map
,我不知道如何total
从simulations
我已经尝试了几件事,例如self.Simulations.Total
orself.total
但它不起作用。
import numpy as np
from multiprocessing import Pool
import time
class PricingSimulatedBarrierOption:
def __init__(self, spot, strike, barrier, rate, sigma, time, sims, steps):
self.spot = spot
self.strike = strike
self.barrier = barrier
self.rate = rate
self.sigma = sigma
self.time = time
self.sims = sims
self.steps = steps
self.dt = self.time / self.steps
def Simulations(self):
total = np.zeros((self.sims,self.steps+1),float)
pathwiseS= np.zeros((self.steps+1),float)
for j in range(self.sims):
pathwiseS[0] =self.spot
total[j,0] = self.spot
for i in range(1,self.steps+1):
phi = np.random.normal()
pathwiseS[i] = pathwiseS[i-1]*(1+self.rate*self.dt+self.sigma*phi*np.sqrt(self.dt))
total[j,i]= pathwiseS[i]
return total.reshape(self.sims, self.steps+1)
def CallUpAndOut(self):
start_time = time.time()
p = Pool()
getpayoff = p.map(self.Simulations(),self.total) ###How to pass total here?
p.close()
p.join()
end_time = time.time()-start_time
print(end_time)
# getpayoff = self.Simulations()
callpayoff = np.zeros((self.sims),float)
for j in range(self.sims):
if max(getpayoff[j,])>=self.barrier:
callpayoff[j] = 0
else:
callpayoff[j] = max(getpayoff[j,self.steps-1]-self.strike,0)
return np.exp(-self.rate*self.time)*np.average(callpayoff)
c = PricingSimulatedBarrierOption(100,100,170,0.05,0.2,1,10000,252)
print(c.CallUpAndOut())
解决方案
在函数定义中添加参数见下面的例子:
def CallUpAndOut(self, total):
并在 map 中传递总值数组,请参见下面的示例:
total = [1,2,3]
getpayoff = p.map(self.Simulations,total)
推荐阅读
- express - 如何建立具有多个页面和单页面应用程序的网站?
- python - 如何使用 python3 将更改的模式 json 插入到 mysql 中?
- android - Unity 使用 DirectX 还是 OpenGL?
- c - 如何将十进制数字转换为二进制,将二进制数字保存在数组中?
- bash - 将文件从 node1.html 重命名为 node001.html
- c# - 使用 ASP.NET core Identity 时,最好扩展 User 类或编写与之相关的单独实体
- typescript - 使用 TypeScript 进行依赖注入
- react-native - 调度登录操作时,firebase.auth 不是函数
- android - 改造 2 不填充 RecyclerView
- typescript - 扩展:为自定义脚本语言提供代码导航支持