R/BlackScholes.R

#' Black Scholes class
#' 
#' @author elh

BlackScholes <- setClass(
  "BlackScholes",
  
  slots = c(
    spot = "numeric",
    drift = "numeric",
    volatility = "numeric"
  ),
  
  prototype = list(
    spot = 20,
    drift = 0.05,
    volatility = 0.01
  ),
  
  # Inheritance
  contains = "Underlying"
)

setMethod(
  f = "asset",
  signature = "BlackScholes",
  definition = function(this, maturity, timestep)
  {
    today <- tail(this@grid, n=1)
    
    if(length(today)==0)
      today = 0

    # Set the grid with jumps
    this@grid <- seq(from = today, to=today+maturity, by=timestep)
    
    # Brownian increment
    G <- rnorm(maturity/timestep + 1)
    
    # Logarithm of the the underlying path
    X <- vector("numeric", length(this@grid))
    if(length(this@path)==0)
      X[1] <- 0
    else
      X[1] <- log(tail(this@path, n=1)/this@spot)
    
    for(i in 2:length(this@grid))
    {
      delta_t = this@grid[i] - this@grid[i-1]
      X[i] <- X[i-1] + this@drift * delta_t + this@volatility * sqrt(delta_t) * G[i]
    }  
    this@path <- this@spot * exp(X)
    return(this)
  }
)

setMethod(
  f = "phi",
  signature = "BlackScholes",
  definition = function(this, v, maturity)
  {
    return(exp(-this@volatility^2*maturity/2)*(v^2 + complex(imaginary = 1)*v))
  }
)

setGeneric(
  name = "d1",
  def = function(this,...)
  {
    standardGeneric("d1")
  }
)

setGeneric(
  name = "d2",
  def = function(this, ...)
  {
    standardGeneric("d2")
  }
)

setMethod(
  f = "d1",
  signature = "BlackScholes",
  definition = function(this, k, maturity)
  {
    return((log(this@spot) - k + (this@drift + this@volatility^2/2)*maturity) / (this@volatility * sqrt(maturity)))
  }
)

setMethod(
  f = "d2",
  signature = "BlackScholes",
  definition = function(this, k, maturity)
  {
    return((log(this@spot) - k + (this@drift - this@volatility^2/2)*maturity) / (this@volatility * sqrt(maturity)))
  }
)
gaspardcc/jumpyMerton documentation built on May 25, 2019, 5:24 p.m.