Search code examples
rfinance

Black Scholes Option Pricing Model in R


I have herein an attempt to code BS model in R. Mathematically, I think this is pretty good, but the code is returning an error.


price = function(S, K, r, T, sigma, type){

  if(type=="C"){
  d1 <- (log(S/K) + (r + sigma^2/2)*T) / (sigma*sqrt(T))
  d2 <- d1 - sigma*sqrt(T)

  price = S*pnorm(d1) - K*exp(-r*T)*pnorm(d2)
  return(price)}

  if (type=="P"){
  d1 <- (log(S/K) + (r + sigma^2/2)*T) / (sigma*sqrt(T))
  d2 <- d1 - sig*sqrt(T)

  price =  (K*exp(-r*T)*pnorm(-d2) - S*pnorm(-d1))
  return(price)}

I have tried to use if, else if both returned an "Error: Incomplete expression:" - I want the stay away from else, because the option type must either by "C" Call or "P" for Put.

I need your help to check why the code isn't running.

Regards


Solution

  • You need to close the bracket for the function. Also, second if statement has sig rather than sigma. I've changed that which gives:

    price = function(S, K, r, T, sigma, type){
    
      if(type=="C"){
        d1 <- (log(S/K) + (r + sigma^2/2)*T) / (sigma*sqrt(T))
        d2 <- d1 - sigma*sqrt(T)
    
        price = S*pnorm(d1) - K*exp(-r*T)*pnorm(d2)
        return(price)}
    
      if (type=="P"){
        d1 <- (log(S/K) + (r + sigma^2/2)*T) / (sigma*sqrt(T))
        d2 <- d1 - sigma*sqrt(T)
    
        price =  (K*exp(-r*T)*pnorm(-d2) - S*pnorm(-d1))
        return(price)}
    }
    

    This then works:

    price(50,50,0.05,0.5,0.25,'C')
    [1] 4.130008
    
    price(50,50,0.05,0.5,0.25,'P')
    [1] 2.895503