将变量从类中的另一个函数传递给Pool

时间:2019-05-06 09:42:15

标签: python python-multiprocessing pool

下面的代码模拟股票价格并计算其收益。我正在尝试使用多处理来加速仿真。问题是在我有say ( $_ * 2 for 3, 9 ); //use topic variables say ( { $^i * 2 } for 3, 9 ); //use placeholder variables 的{​​{1}}中,我不确定如何从CallUpAndOut来访问pool.map

我已经尝试过类似totalsimulations之类的方法,但是它不起作用。

self.Simulations.Total

2 个答案:

答案 0 :(得分:0)

在函数定义中添加参数,请参见以下示例:

def CallUpAndOut(self, total):

然后在地图中传递总值数组,请参见以下示例:

total = [1,2,3]
getpayoff = p.map(self.Simulations,total)

答案 1 :(得分:0)

为此,我不得不将声明移到外面。下面的代码现在可以在Pool函数中接受变量。

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
        self.pathwiseS= np.zeros((self.steps+1),float)

def Simulations(self):

    print("Called")
    total = np.zeros((self.sims,self.steps+1),float)
    self.pathwiseS= np.zeros((self.steps+1),float)
    for j in range(self.sims):
        self.pathwiseS[0] =self.spot
        total[j,0] = self.spot
        for i in range(1,self.steps+1):
            phi = np.random.normal()
            self.pathwiseS[i] = self.pathwiseS[i-1]*(1+self.rate*self.dt+self.sigma*phi*np.sqrt(self.dt))
            total[j,i]= self.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.pathwiseS)
    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)