Created
October 18, 2020 13:22
-
-
Save addiversitas/94abae1f5a953cef4f4eeb34190515e3 to your computer and use it in GitHub Desktop.
iv calculation for APPL calls and puts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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