python - ValueError:Series 的真值不明确。在尝试将函数与 pandas df 一起使用时使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()
问题描述
我有以下代码导致以下错误。我认为错误来自循环部分while epsilon > tol:
。我在“IV”列中添加了一个带有所需结果的小 df。
第 1478 行,在非零中 引发 ValueError(ValueError: Series 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。
def d(sigma, S, K, r, q, t):
d1 = 1 / (sigma * np.sqrt(t)) * ( np.log(S/K) + (r - q + sigma**2/2) * t)
d2 = d1 - sigma * np.sqrt(t)
return d1, d2
def call_price(sigma, S, K, r, q, t, d1, d2):
C = norm.cdf(d1) * S * np.exp(-q * t)- norm.cdf(d2) * K * np.exp(-r * t)
return C
# From Put call Prity
def put_price(sigma, S, K, r, q, t, d1, d2):
P = - S * np.exp(-q * t) + K * np.exp(-r * t) + call_price(sigma, S, K, r, q, t, d1, d2)
return P
def calc_put_iv(S,K,t,r,q,P0,tol,epsilon,count,max_iter,vol):
while epsilon > tol:
# Count how many iterations and make sure while loop doesn't run away
count += 1
print(count)
if count >= max_iter:
print('Breaking on count')
break;
# Log the value previously calculated to computer percent change
# between iterations
orig_vol = vol
# Calculate the vale of the call price
d1, d2 = d(vol, S, K, r,q, t)
function_value = put_price(vol, S, K, r, q, t, d1, d2) - P0
# Calculate vega, the derivative of the price with respect to
# volatility
vega = S * norm.pdf(d1) * np.sqrt(t)* np.exp(-q * t)
# Update for value of the volatility
vol = -function_value / vega + vol
# Check the percent change between current and last iteration
epsilon = abs( (vol - orig_vol) / orig_vol )
print(vol)
return vol
# Print out the results
df["IV"] = calc_put_iv(df["Stock Price"], df["Strike"], df["Length / 365"],0.001,df["Div Yield"],df["Premium"],1e-8,1,0,1000,.5)
Strike Stock Price Premium Length Div Yield Length / 365 IV
470 407.339996 65.525 17 0 0.008219178 1.3080322786580916
400 407.339996 14.375 3 0 0.008219178 1.2202688594244515
490 490.649994 17.35 17 0 0.046575342 0.4190594565249461
解决方案
我设法找到了一个解决方案:
list_of_iv = []
# Print out the results
for index, row in df.iterrows():
iv = calc_put_iv(df["Stock Price"].iloc[index], df["Strike"].iloc[index], df["Length/365"].iloc[index],0.001,df["Div Yield"].iloc[index],df["Premium"].iloc[index],1e-8,1,0,1000,.5)
list_of_iv.append(iv)
df['Put IV'] = pd.Series(list_of_iv)
它非常丑陋,而且可能效率不高,尤其是对于较大的数据集,所以如果有人可以改进这一点,我将不胜感激。
推荐阅读
- mysql - Flutter,如何获取对象的数据数组并显示给 ListView.builder?
- javascript - React Portals - 执行引用新窗口 DOM 的函数
- python - 如何使用 selenium python 使用 href 的部分文本进行迭代
- flutter - 如何在颤动中构建一个不遵循颤动中最大项目长度的宽度的下拉菜单
- python - float() 参数必须是字符串或数字,而不是 'Timestamp' ---> 10 scaled_data=scaler.fit_transform(final_dataset)
- python - 在 mod_wsgi 下的 Flask 服务器上加载 tensorflow (keras) 模型
- mysql - 如何更新子查询中的更多行?
- spotfire - Spotfire 交叉表颜色
- php - 获取我刚刚在查询中插入的记录的 ID
- bazel - 外部依赖的不同--compilation_mode