【问题标题】:How to loop through a Pandas DataFrame or Numpy Arrays with a self made function?如何使用自制函数循环遍历 Pandas DataFrame 或 Numpy 数组?
【发布时间】:2019-04-17 14:55:09
【问题描述】:

对于我的论文,我需要期权的隐含波动率,我已经为它创建了以下函数:

#Implied volatility solver
def Implied_Vol_Solver(s_t,K,t,r_f,option,step_size):
#s_t=Current stock price, K=Strike price, t=time until maturity, r_f=risk-free rate and option=option price,stepsize=is precision in stepsizes
    #sigma set equal to steps to make a step siz equal to the starting point
    sigma=step_size
    while sigma < 1:
        #Regualar BlackScholes formula (current only call option, will also be used to calculate put options)
        d_1=(np.log(s_t/K)+(r_f+(sigma**2)/2)*t)/(sigma*(np.sqrt(t)))
        d_2=d_1-np.square(t)*sigma
        P_implied=s_t*norm.cdf(d_1)-K*np.exp(-r_f*t)*norm.cdf(d_2)
        if option-(P_implied)<step_size:
            #convert stepts to a string to find the decimal point (couldn't be done with a float)
            step_size=str(step_size)
            #rounds sigma equal to the stepsize
            return round(sigma,step_size[::-1].find('.'))
        sigma+=step_size
    return "Could not find the right volatility"

我需要的变量位于 Pandas DataFrame 中,并且我已经为它创建了一个循环,以测试它是否有效(当它正常工作时我将添加其他变量):

for x in df_option_data['Settlement_Price']:
    df_option_data['Implied_Volatility']=Implied_Vol_Solver(100,100,1,0.01,x,0.001)

但是,当我运行这个循环时,我会得到整个 Implied_Voltality 列的 0.539,而且这些数字需要不同,我哪里错了?或者有没有更简单的解决方案?

我还尝试了以下方法:

df_option_data['Implied_Volatility']=Implied_Vol_Solver(100,100,1,0.01,np.array(df_option_data['Settlement_Price']),0.001)

但是我得到以下错误:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

基本上我需要的是以下内容:一个包含 5 列输入变量和 1 列输出变量(隐含波动率)的数据框,由函数计算。

【问题讨论】:

    标签: python pandas function loops


    【解决方案1】:

    您将Implied_Vol_Solver 的结果替换为整列而不是特定单元格。

    尝试以下方法:

    df_option_data['Implied_Volatility'] = df_option_data['Settlement_Price'].apply(lambda x: Implied_Vol_Solver(100,100,1,0.01,x,0.001))
    

    apply 函数可以将函数应用于数据列中的所有元素,这样您就不需要自己执行for 循环。

    【讨论】:

    • 首先感谢您的快速响应,我了解 ATK7474 解决方案,但您的解决方案更易于应用和维护。一个小问题,其他变量也需要改变,我怎样才能用多个参数来做这个 Lambda 函数?目前我只能调整一个变量,但所有五个都需要更改(变量在同一行但不同列)。
    • @10uss 你可以看看:stackoverflow.com/questions/39814416/…
    【解决方案2】:

    您可以传入行(作为一个系列)并从中提取值,而不是将输入变量传递给函数。然后,使用 apply 函数来获取输出帧。这看起来像这样:

    def Implied_Vol_Solver(row):
        s_t = row['s_t']  # or whatever the column is called in the dataframe
        k = row['k']  # and so on and then leave the rest of your logic as is
    

    修改函数后,您可以像这样使用它:

    df_option_data['Implied_Volatility'] = df_option_data.apply(Implied_Vol_Solver, axis=1)
    

    【讨论】:

      猜你喜欢
      • 2023-03-24
      • 1970-01-01
      • 2020-09-23
      • 1970-01-01
      • 1970-01-01
      • 2016-04-25
      • 2012-03-06
      • 2021-04-04
      • 2020-07-28
      相关资源
      最近更新 更多