SC.
SC.

Reputation: 416

R Optimize Vectorization

I have written a function bs.pp that calculates the Black Scholes value of a Put Option.

bs.pp <- function (Price, Strike, sigma, texp, int) {
  d1=(1 / (sigma*sqrt(texp)))*(log(Price/Strike)+(int+(sigma^2)/2)*texp)
  d2=d1-sigma*sqrt(texp)
  Strike*pnorm(-d2)*exp(-int*texp)-Price*pnorm(-d1)}

Which seems to work well

> bs.pp(1000,1000,.2,1,.02)
[1] 69.35905
> bs.pp(1000,900,.25,1,.02)
[1] 46.15609

With some help with some people here I have also completed my inverse function, that given (Price, Strike, texp, int) and the result of bs.pp will tell you what the missing sigma value should be.

bs.piv <- function(Price, Strike, texp, intr, PutPrice)
{
  optfunc <- function(P, S, sigma, t, i, PP){(bs.pp(Price, Strike, sigma, texp, intr) - PutPrice)^2}
  xmin <- optimize(optfunc, interval = c(0,2), tol = 0.0001, P=Price, S=Strike, t=texp, i=intr, PP=PutPrice)
  xmin$minimum
}

Which also works well

> bs.piv(1000,1000,1,.02,69.35)
[1] 0.1999901
> bs.piv(1000,900,1,.02,30.25)
[1] 0.2000281

The problem is that while the first function, bs.pp is vectorized

> bs_strike <- c(1000,900)
> bs.pp(1000,bs_strike,.2,1,.02)
[1] 69.35905 30.24388

Unfortunately the second inverse function returns errors

> bs_pp_ans <- c(69.35, 30.25)
> bs.piv(1000,bs_strike,1,.02,bs_pp_ans)
Error in optimize(optfunc, interval = c(0, 2), tol = 1e-04, P = Price,  : 
  invalid function value in 'optimize'

Upvotes: 1

Views: 191

Answers (1)

user20650
user20650

Reputation: 25854

Upgrade comment.

I don't think you can vectorise your code due to the optimize() function ... a previous question. However, as an alternative, you can use the Vectorize() function. Rather than a true vectorised solution (in terms of vector in / vector out at a low(ish) level) it is a wrapper for various other functions. (To see the code of Vectorize just enter it into the terminal).

So you can change your code to

Vectorize(bs.piv)(1000,bs_strike,1,.02,bs_pp_ans) 

Upvotes: 2

Related Questions