尝试用值填充矩阵时,错误是 R 中的 fsolve;寻找解释 and/or 解决方案

Error is fsolve in R when trying to fill a matrix with values; looking for explanation and/or solution

找到解决方案

我正在尝试使用 R 中的 "persp" 绘制波动率曲面。为此,我需要用隐含波动率填充矩阵 z。

我有执行价格、时间和市场价格的数据框。数据仅包含 看涨期权.

    AAPL <- #data
    df <- data.frame(AAPL$Strike.Price,AAPL$Time.Left,AAPL$Market.Price)

我目前有一个矩阵 zz,它的第一列是股票价格,乘以 headers,第 2、3 和 4 列分别是市场价格。它是 重要 注意市场价格的某些值缺失 (NA)。

    zz <- cast(df, df.Strike.Price ~ df.Time.Left)

对于我的 x、y 轴,我定义了向量:

    x0 <- zz$df.Strike.Price  #Strike prices for calculation of imp. vol.
    x <- zz$df.Strike.Price / 153.06  #Axis for plotting
    y <- c(time1, time2, time3) 

现在是绘制隐含波动率的 z 矩阵。我从一个空矩阵开始

    z = matrix(data=NA,nrow=length(x0),ncol=length(y))

然后我尝试填充矩阵,为无法计算的值留下 NA

    for(i in 1:length(x0)){
        for(j in 1:length(y)){
            #Formula for Black-Scholes call option price (no dividends)
            BS = function(X,T,sigma){
                #Parameters
                S=153.06; r=0.05 #Stock value is same for all options, r is arbitrarily selected to be some constant.

                d1 = (log(S/X) + (r + sigma^2/2)*T) / (sigma*sqrt(T))
                d2 = d1 - sigma*sqrt(T)

                #Price for call options
                price = S*pnorm(d1) - X*exp(-r*T)*pnorm(d2)
                return(price)
            }

            #To address NA entries in zz
            if(is.na(zz[i,j+1] == TRUE)){  
                z[i,j] = NA
            }

            #This is the part of the code that causes issues
            else{
                #Function for fsolve, the Black-Scholes price minus the market price.
                A = function(sigma){
                    a = BS(x0[i], y[j], sigma) - zz[i,j+1]
                    return(a)
                }

            V = fsolve(A, 0.5) #Should give me the implied volatility from market data.
            z[i,j] = V
            }
        }
    }

执行这段代码后,我收到错误消息:

if (norm(s, "F") < tol || norm(as.matrix(ynew), "F") < tol) 中断时出错: TRUE/FALSE 需要

的缺失值

我不确定错误是什么。有没有办法克服这个问题或获得隐含波动率的替代方法而不是使用 fsolve?

该错误与函数 fsolve 的 sigma 变化变得太小有关。我找到了另一个可以求解非线性方程的函数并使用了它。

该函数是同名包 nleqslv 中的 nleqslv。