binomialCost.R

nate — Jul 1, 2014, 9:24 PM

binomialCost <- function(S, K, sigma, r, delta, h, T=1) {
  if(T!=1) {
    r = r*T
    h = h*T
    delta = delta*T
    sigma = sigma*sqrt(T)
  }

  u = exp((r-delta)/h + sigma*sqrt(1/h))
  d = exp((r-delta)/h - sigma*sqrt(1/h))
  p = (exp((r-delta)/h) - d)/(u-d)

  cost <- function(node) {
    if(length(node)==h) {
      return(max(0,Sundn(node) - K))
    } else {
      return(max(exp(-(r-delta)/h)*(p*cost(nodes(node)[1,]) + (1-p)*cost(nodes(node)[2,])),0))
    }
  }

  nodes <- function(v) {
    if(isOuter(v) == FALSE) {
      nodes = c(c(v,1),c(v,0))
      return(matrix(nodes,nrow=2,ncol=length(nodes)/2, byrow=TRUE))
    } else {
      return(v)
    }
  }

  Sundn <- function(node) {
    un = sum(node)
    dn = length(node) - un
    S*(exp((r-delta)/h + sigma*sqrt(1/h))^un*exp((r-delta)/h - sigma*sqrt(1/h))^(dn))
  }

  isOuter <- function(node) {
    if(length(node) < h) {
      return(FALSE)    
    } else {
      return(TRUE)
    }
  }

  cost(numeric(0))
}

print(binomialCost(S=41,K=40,sigma=0.3,r=0.08,delta=0,h=1,T=2))
[1] 10.74
# compare blackScholes and binomial for h = 15
print(binomialCost(S=41,K=40,sigma=0.3,r=0.08,delta=0,h=15,T=1))
[1] 6.966
#### BLACK-SCHOLES METHOD ####
S = 41.00 # stock price
K = 40.00 # strike price
sigma = 0.3 # volatility
r = 0.08 # continuously compound interest rate
delta = 0 # annualized dividend rate
h = 15 # number of subdivisions per period
T = 1 # number of periods

d1 = 1/(sigma*sqrt(T)) * (log(S/K) + (r + sigma^2/2)*(T))
d2 = d1 - sigma*sqrt(T)
C = pnorm(d1)*S - pnorm(d2)*K*exp(-r*T)
print(C)
[1] 6.961