具有星图的多处理池无法正常工作

时间:2019-07-03 14:21:00

标签: python multiprocessing

我正在尝试将多个参数传递给一个函数

我已阅读并尝试过以下解决方案:Python multiprocessing behavior of Pool / starmap 这是Python multiprocessing pool.map for multiple arguments

,但两者似乎都不起作用。

这是我的代码:

args = [
(1.42,'c',297.39,296,0.0192,0.019,d1,d0),(1.42,'c',297.39,290,0.0192,0.019,d1,d0)
]

with multiprocessing.Pool(processes=2) as pool:
    result = pool.starmap(greeks,args)

这似乎适用于第一组args,但随后出现此错误:

Exception in thread Thread-3:
Traceback (most recent call last):
  File "/anaconda3/envs/py37/lib/python3.7/threading.py", line 917, in _bootstrap_inner
    self.run()
  File "/anaconda3/envs/py37/lib/python3.7/threading.py", line 865, in run
    self._target(*self._args, **self._kwargs)
  File "/anaconda3/envs/py37/lib/python3.7/multiprocessing/pool.py", line 496, in _handle_results
    task = get()
  File "/anaconda3/envs/py37/lib/python3.7/multiprocessing/connection.py", line 251, in recv
    return _ForkingPickler.loads(buf.getbuffer())
TypeError: __init__() takes 1 positional argument but 2 were given

我什至不知道为什么会有Thread-3,因为我只传递了2组args。 我希望最终可以为大约10-15套args工作

编辑:完整代码:

import py_vollib.black_scholes_merton.implied_volatility as BSM
from datetime import date
import quantsbin.derivativepricing as qbdp

def greeks(target_value, flag, S, K, r, div,t1,t0):
    if flag == 'c':
        call_put = 'Call'
    else:
        call_put = "Put"

    delta = t1-t0
    delta_annual = delta.days / 365
    d0s = t0.strftime('%Y%m%d')
    d1s = t1.strftime('%Y%m%d')

    sigma = BSM.implied_volatility(target_value, S, K, delta_annual, r, div, flag)

    risk_parameters = {'delta_spot': 0.02, 'delta_vol': 0.02, 'delta_rf_rate': 0.02,
                       'delta_time': 1}  # TODO Fix with next quantsbin release


    equity_o = qbdp.EqOption(option_type=call_put, strike=K, expiry_date=d1s, expiry_type='American')
    engine = equity_o.engine(model="Binomial", spot0=S, pricing_date=d0s,
                             rf_rate=r, yield_div=div, volatility=sigma)

    greeks = engine.risk_parameters(**risk_parameters)
    greeks['IV'] = sigma
    return greeks


d0 = date.today()
d1 = date(2019, 7, 5)


cpu=multiprocessing.cpu_count()-1

t1 = time.time()

args = [(1.42,'c',297.39,296,0.0192,0.019,d1,d0),(1.42,'c',297.39,290,0.0192,0.019,d1,d0)]

with multiprocessing.Pool(processes=cpu) as pool:
     result = pool.starmap(greeks,args)

t2= time.time()

print(result,'{:0.4}'.format(t2-t1))

编辑2:

print(greeks(1.42,'c',297.39,296,0.0192,0.019,d1,d0))

这有效并返回:

{'delta': 0.6168499226002772, 'gamma': 0.12714118324230908, 'theta': -0.025340261170400336, 'vega': 2.8379233244261832, 'rho': 1.3659174375347853, 'IV': 0.04311625476862159}

def g(a,b,c):
    return [a+b+c,a-b-c,a+b-c]

a = [(1,5,7),(4,7,2),(7,7,7)]

with multiprocessing.Pool(processes=cpu) as pool:
    result = pool.starmap(g,a)

也可以按预期工作。

0 个答案:

没有答案