I am trying to pass multiple arguments to a function
I have read and tried the solution from this: Python multiprocessing behavior of Pool / starmap and this: Python multiprocessing pool.map for multiple arguments
but both don't seem to work.
This is my code:
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)
It seems to work for the first set of args but then I get this error:
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
I dont even know why there is a Thread-3 since I only passed 2 sets of args. I would like this to eventually work for roughly 10-15 sets of args
Edit: Full Code:
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))
Edit 2:
print(greeks(1.42,'c',297.39,296,0.0192,0.019,d1,d0))
This works and returns:
{'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)
also works as expected.