Skip to content

Instantly share code, notes, and snippets.

@Foxtrod89
Forked from addiversitas/ivCalculation.R
Created August 6, 2021 16:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Foxtrod89/4da61c7ab23b6130a556b49f2150232c to your computer and use it in GitHub Desktop.
Save Foxtrod89/4da61c7ab23b6130a556b49f2150232c to your computer and use it in GitHub Desktop.
iv calculation for APPL calls and puts
#generalized black scholes merton model
gBSM <- function(S, X, sigma, r, q, ttm, type){
#S = stock price
#X = strike price
#sigma = volatility
#r = risk free interest rate
#q = dividend yield
#ttm = time to maturity in days
#type = option type
b <- r - q
t <- ttm/365.25
d1 <- (log(S / X) + (b + sigma^2 / 2) * t) / (sigma * sqrt(t))
d2 <- d1 - sigma * sqrt(t)
if(type == "call"){
price <- S * exp((b - r) * t) * pnorm(d1) - X * exp(-r * t) * pnorm(d2)
}else if (type == "put"){
price <- (X * exp(-r * t) * pnorm(-d2) - S * exp((b - r) * t) * pnorm(-d1))
}
return(price)
}
#objective function
volOptimFun <- function(sigma, price, S, K, r, q, ttm, type){
abs(price - gBSM(S, K, sigma, r, q, ttm, type))
}
#wrapper for the optimization function so it can be used with apply
getIV <- function(x, S, r, q, type){
res <- optimize(volOptimFun, interval = c(0, 2), price = as.numeric(x["ask"]), S = S, K = as.numeric(x["strike"]), r = r, q = q, ttm = as.numeric(x["ttm"]), type = type)
return(res$minimum)
}
#calculating IV
calls$iv <- apply(calls, 1, getIV, S = lastPrice, r = 0.0011, q = 0, type = "call")
puts$iv <- apply(puts, 1, getIV, S = lastPrice, r = 0.0011, q = 0, type = "put")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment