Bhushan
Bhushan

Reputation: 87

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)

This is done in matlab using fzero, I have implemented this in Python using lambda. Want to do same in R.

so far tried following:

> 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

and

> 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'

Also plot(); but no luck!

Please share an idea.

Thank you.

Upvotes: 1

Views: 987

Answers (1)

Federico Manigrasso
Federico Manigrasso

Reputation: 1200

The problem is BS_EC gives back a vector (price,delta,gamma) as result. In order to apply a range of input you have to consider just one result at time. For example for price add [1]

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

The same is true for the optimization, you have to decide what parameter you want to consider Again give back just the price with [1] and you are done

 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))

Upvotes: 1

Related Questions