R:expr'没有评估长度为'n'的对象

时间:2017-07-06 13:37:34

标签: r matlab curve-fitting

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)

这是在使用fzero的matlab中完成的,我已经使用lambda在Python中实现了这一点。想在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'

还有plot();但没有运气!

请分享一个想法。

谢谢。

1 个答案:

答案 0 :(得分:1)

问题是BS_EC给出了一个向量(价格,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))