Skip to content

Instantly share code, notes, and snippets.

@wilsonfreitas
Last active August 29, 2015 13:57
Show Gist options
  • Save wilsonfreitas/9835012 to your computer and use it in GitHub Desktop.
Save wilsonfreitas/9835012 to your computer and use it in GitHub Desktop.
Computting implied volatility massively.
implied.vol <- function(theo_price, eps=.Machine$double.eps, max.iter=1000) {
.implied.vol <- function(S, K, Time, r, spot_price, sig=0.2, min.sig=1e-6, max.sig=1) {
sig <- sig*rep(1, length(S))
sig.up <- max.sig*rep(1, length(S))
sig.down <- min.sig*rep(1, length(S))
iter <- 0
comp.err <- function(sig) theo_price(S, K, Time, r, sig) - spot_price
err <- comp.err(sig)
## repeat until error is sufficiently small or `iter` hits max.iter
while (all(abs(err) > eps) && iter < max.iter) {
idx.err <- err < 0
sig.down[idx.err] <- sig[idx.err]
sig[idx.err] <- (sig.up[idx.err] + sig[idx.err])/2
idx.err <- !idx.err
sig.up[idx.err] <- sig[idx.err]
sig[idx.err] <- (sig.down[idx.err] + sig[idx.err])/2
err <- comp.err(sig)
iter <- iter + 1
}
sig
}
.implied.vol
}

This code uses R's vectorization features to execute a sort of parallel bisection for computing implied volatility. I used this code to compute implied volatility of a bunch of options (~ 200 thoudands). A loop with uniroot would take several minutes which I reduced to few seconds.

The example below uses GBSOption function from package fOptions.

bs.opt <- function(S, K, T, r, sig) GBSOption('c', S, K, T, r, r, sig)@price

impvol <- implied.vol(bs.opt)

impliedVol <- impvol(UnderlyingPrice, Strike, BusinessDays/252, RiskFreeRate, Premium)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment