Pedro Gomes
Pedro Gomes

Reputation: 161

Problem with implementing unitroot function in R

I am new to programming, and I have been exposed to the basic of R and Python. I have been trying to implement the volatility smile function using a unit root function(a traditional procedure) but I am running into problems. Here is the code I am writing:

BlackScholesFormulaBach  <- function (spot,timetomat,strike,r, q=0, sigma)
{ 
  
  d1<-(spot-strike)/(sigma*sqrt(timetomat))
  d2<-(spot-strike)/(sigma*sqrt(timetomat))
  
  
  result<-(spot-strike)*pnorm(d1)+sigma*sqrt(timetomat)*dnorm(d1)
  
  
  BlackScholesFormulaBach<-result
  
}

BlackScholesImpVol  <- function (obsprice,spot,timetomat,strike,r, q=0)
  
{ difference<- function(sigBS, obsprice,spot,timetomat,strike,r,q)
{BlackScholesFormulaBach(spot,timetomat,strike,r,q,sigBS)-obsprice
}

uniroot(difference, c(-1,1),obsprice=obsprice,spot=spot,timetomat=timetomat,strike=strike,r=r,q=q)$root

}

S_0<-100
cap_T<-1
sigma_1<-15
N<-1000

BlackScholesImpVol(S_0,cap_T,1,0,0,15)

Every time I run the code I get:

Error in c(-1, 1) : unused argument (1)

If I change the interval I get the same error. I have been checking the code but it seems right. I have consulted other people and none finds the problem. According to R the problem is on the unitroot function, but I fail to see where.

Question:

Can someone help me solve this implementation problem?

Thanks in Advnace

Upvotes: 0

Views: 87

Answers (2)

John Coleman
John Coleman

Reputation: 52008

The only way you get that error is if you have accidentally shadowed the R function c.

For example,

uniroot(sin,c(-1,1))

is unproblematic. But

c <- function(x) x^2
uniroot(sin(c(-1,1))

leads to exactly the same error that you have. The solution is to, in the console, first evaluate

rm(c)

and then your function should work (or at the very least not throw the same error). If you actually need this function c, you of course might want to assign it to a different name before removing it.

Upvotes: 1

tester
tester

Reputation: 1692

Let the function return a result, and you'll get a result. You can rewrite your other functions just like the one below and they should work.

BlackScholesFormulaBach  <-
  function (spot, timetomat, strike, r, q = 0, sigma) {
    d1 <- (spot - strike) / (sigma * sqrt(timetomat))
    d2 <- (spot - strike) / (sigma * sqrt(timetomat))
    result <-
      (spot - strike) * pnorm(d1) + sigma * sqrt(timetomat) * dnorm(d1)
    return(result)
  }

S_0 <- 100
cap_T <- 1
sigma_1 <- 15
N <- 1000

> BlackScholesFormulaBach(S_0, cap_T, 1, 0, 0, 15)
[1] 99

Upvotes: 1

Related Questions