R: expr' 没有计算出长度为 'n' 的对象

R: expr' did not evaluate to an object of length 'n'

require(OptionPricing)
c=BS_EC(K=54, r = 0.07, sigma = 0.3, T = 5/12, S0 = 50)
c[1]
y <- function(y) (BS_EC(K=54, r = 0.07, sigma = y, T = 5/12, S0 = 50)-2.846575)

这是在 matlab 中使用 fzero 完成的,我在 Python 中使用 lambda 实现了它。想在 R 中做同样的事情。

到目前为止已尝试以下操作:

> uniroot(y,c(-1,1))
Error in uniroot(y, c(-1, 1)) : 
  f() values at end points not of opposite sign
In addition: Warning messages:
1: In if (is.na(f.lower)) stop("f.lower = f(lower) is NA") :
  the condition has length > 1 and only the first element will be used
2: In if (is.na(f.upper)) stop("f.upper = f(upper) is NA") :
  the condition has length > 1 and only the first element will be used

> f <- Vectorize(function(y) (BS_EC(K=54, r = 0.07, sigma = y, T = 5/12, S0 = 50)-2.846575))
> curve(f)
Error in curve(f) : 'expr' did not evaluate to an object of length 'n'

还有情节();但运气不好!

请分享想法。

谢谢。

问题是 BS_EC 返回一个向量 (price,delta,gamma) 作为结果。 为了应用一系列输入,您必须一次只考虑一个结果。 例如,价格添加 [1]

 f <- Vectorize(function(y) (BS_EC(K=54, r = 0.07, sigma = y, T = 5/12, S0 = 50)[1]-2.846575))
 curve(f)

优化也是如此,你要决定你要考虑什么参数 再次返回 [1] 的价格,你就完成了

 y <- function(y) (BS_EC(K=54, r = 0.07, sigma = y, T = 5/12, S0 = 50)[1]-2.846575)
uniroot(y,c(-1,1))