尝试将列添加到pandas数据帧中,该数据帧是使用pyvollib(from py_vollib.black.implied_volatility import implied_volatility
)中的implied_volatility()函数计算的。所有输入参数均来自以下df:
In [101]: odf.head()
Out[101]:
Expiry K Type close F texp r
7 2018-01-26 120.5 p 0.015625 122.9375 10 0.012604
10 2018-01-26 121.0 p 0.015625 122.9375 10 0.012604
11 2018-01-26 122.0 p 0.062500 122.9375 10 0.012604
17 2018-01-26 121.5 p 0.015625 122.9375 10 0.012604
19 2018-01-26 122.5 p 0.140625 122.9375 10 0.012604
我正在使用的功能:
odf['iv'] = [implied_volatility(discounted_option_price = odf.close,F=odf.F,K=odf.K,
r=odf.r,t=odf.texp/365,flag=odf.Type)
for rows in odf]
问题似乎是odf.Type列,它是一系列字符串。
我在ipython中获取回溯:
In [102]: odf['iv'] = [implied_volatility(discounted_option_price = odf.close,F=
...: odf.F,K=odf.K,
...: r=odf.r,t=odf.texp/365,flag=odf.Type)
...: for rows in odf]
...:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-102-133149ca6fb0> in <module>()
1 odf['iv'] = [implied_volatility(discounted_option_price = odf.close,F=odf.F,K=odf.K,
2 r=odf.r,t=odf.texp/365,flag=odf.Type)
----> 3 for rows in odf]
<ipython-input-102-133149ca6fb0> in <listcomp>(.0)
1 odf['iv'] = [implied_volatility(discounted_option_price = odf.close,F=odf.F,K=odf.K,
2 r=odf.r,t=odf.texp/365,flag=odf.Type)
----> 3 for rows in odf]
~/miniconda3/lib/python3.6/site-packages/py_vollib/black/implied_volatility.py in implied_volatility_of_discounted_option_price(discounted_option_price, F, K, r, t, flag)
97 K,
98 t,
---> 99 binary_flag[flag]
100 )
101 if sigma_calc == FLOAT_MAX:
~/miniconda3/lib/python3.6/site-packages/pandas/core/generic.py in __hash__(self)
1043 def __hash__(self):
1044 raise TypeError('{0!r} objects are mutable, thus they cannot be'
-> 1045 ' hashed'.format(self.__class__.__name__))
1046
1047 def __iter__(self):
TypeError: 'Series' objects are mutable, thus they cannot be hashed
任何指针如何让这个运行将非常感激。
答案 0 :(得分:1)
我相信你需要apply
:
odf['iv'] = odf.apply(lambda x: implied_volatility(discounted_option_price = x.close,
F=x.F,
K=x.K,
r=x.r,
t=x.texp/365,
flag=x.Type), axis=1)
或者:
odf['iv'] = odf.apply(lambda x: implied_volatility(x.close,
x.F,
x.K,
x.r,
x.texp/365,
x.Type), axis=1)
答案 1 :(得分:-1)
odf['iv'] = [implied_volatility(discounted_option_price = odf.loc[i,'close'],F=odf.loc[i,'F'],K=odf.loc[i,'k'],
r=odf.loc[i,'r'],t=odf.loc[i,'texp']/365,flag=odf.loc[i,'Type'])
for i in odf.index]
使用apply可能有一些更好的方法,但我不知道它如何用于命名参数。