R/impvol.R

impvol <-
function(){
  my.draw <- function(panel) {
    
    
    
    
    blackscholesvalue <- function(S,K,r,t,sigma,div,opttype){
      
      
      
      
      d1 = (log(S/K) + (r +  sigma^2/2)*t)/(sigma*sqrt(t))
      d2 = d1 - sigma*sqrt(t)
      Nd1 = pnorm(d1)
      Nd2 = pnorm(d2)
      
      
      if (opttype == "Call"){
        price = S*Nd1*exp(-div*t) - K*exp(-r*t)*Nd2  
      }
      else{
        price =   K*exp(-r*t)*(1-Nd2) -  S*(1-Nd1)*exp(-div*t) 
      }
      
      return(price)
    }
    
    S <-as.numeric(panel$S)
    K <-as.numeric(panel$K)
    r <-as.numeric(panel$r)
    t <-as.numeric(panel$t)
    #   sigma <-as.numeric(panel$sigma)
    div <-as.numeric(panel$div)
    opttype <- panel$opttype
    market <-as.numeric(panel$market)
    
    vol <- 0.20
    vol.hi <- 1
    vol.lo <- 0.001
    count <- 0
    err <- blackscholesvalue(S,K,r,t,sigma=vol,div,opttype) - market 
    
    ## repeat until error is very small or iterations are max
    maxiter = 100
    while(abs(err) > 0.0001 && count < maxiter){
      if(err < 0){
        vol.lo <- vol
        vol <- (vol.hi + vol)/2
      }else{
        vol.hi <- vol
        vol <- (vol.lo + vol)/2
      }
      err <- blackscholesvalue(S, K, r, t, vol, div, opttype) - market
      count <- count + 1
    }
    
    
    
    plot(1:20, 1:20, type="n", xlab="", ylab="",
         axes=FALSE, frame = TRUE)
    text(10, 10, paste("Imp. Vol = ", round(vol,3), sep=""),cex=1.5)
    
    panel
  }
  
  my.redraw <- function(panel) {
    rp.tkrreplot(panel, my.tkrplot)
    panel
  }
  
  my.panel <- rp.control(title = "Implied Volatility")
  rp.textentry(panel=my.panel,variable=S,labels="Spot:            ",action=my.redraw,initval=100)
  rp.textentry(panel=my.panel,variable=K,labels="Strike:          ",action=my.redraw,initval=110)
  rp.textentry(panel=my.panel,variable=r,labels="Risk free:     ",action=my.redraw,initval=0.05)
  rp.textentry(panel=my.panel,variable=t,labels="Maturity:     ",action=my.redraw,initval=0.5)
  #   rp.textentry(panel=my.panel,variable=sigma,labels="Sigma:         ",action=my.redraw,initval=0.30)
  rp.textentry(panel=my.panel,variable=div,labels="Div yield:     ",action=my.redraw,initval=0.0)
  rp.textentry(panel=my.panel,variable=market,labels="Mkt Price:   ",action=my.redraw,initval=3)
  rp.radiogroup(panel = my.panel, variable= opttype, vals = c("Call", "Put"), 
                action = my.redraw, title = "Type of Option",initval="Call")
  #   rp.button(panel=my.panel,title="calculate", action=my.redraw)
  rp.tkrplot(panel = my.panel, name = my.tkrplot, plotfun = my.draw)
  
  #rp.do(my.panel, my.draw)
  
  
}

Try the GUIDE package in your browser

Any scripts or data that you put into this service are public.

GUIDE documentation built on May 2, 2019, 9:32 a.m.