Advertisement
Guest User

Untitled

a guest
Mar 9th, 2013
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.46 KB | None | 0 0
  1. library(RQuantLib)
  2. library(quantmod)
  3. library(rgl)
  4. library(akima)
  5.  
  6. GetIV <- function(type, value,
  7. underlying, strike,dividendYield, riskFreeRate, maturity, volatility,
  8. timeSteps=150, gridPoints=151) {
  9.  
  10. AmericanOptionImpliedVolatility(type, value,
  11. underlying, strike,dividendYield, riskFreeRate, maturity, volatility,
  12. timeSteps=150, gridPoints=151)$impliedVol
  13. }
  14.  
  15.  
  16. GetDelta <- function(type, underlying, strike,
  17. dividendYield, riskFreeRate, maturity, volatility,
  18. timeSteps=150, gridPoints=149, engine="CrankNicolson") {
  19.  
  20. AmericanOption(type,underlying, strike, dividendYield, riskFreeRate, maturity, volatility,
  21. timeSteps=150, gridPoints=149, engine="CrankNicolson")$delta
  22. }
  23. # set what symbol you want vol surface for
  24. underlying <- 'AAPL'
  25. # set what your volatility forcast or assumption is
  26. volforcast <- .40
  27. # Get symbols current price
  28. underlying.price <- getQuote(underlying,what=yahooQF("Last Trade (Price Only)"))$Last
  29.  
  30. OC <- getOptionChain(underlying, NULL)
  31. #check data
  32. head(OC)
  33. lputs <- lapply(OC, FUN = function(x) x$puts)
  34. head(lputs) #check for NA values, yahoo returns all NA values sometimes
  35. puts <- do.call('rbind', lputs )
  36. #check data
  37. head(puts,15)
  38.  
  39. symbols <- as.vector(unlist(lapply(lputs, rownames)))
  40. expiries <- unlist(lapply(symbols, FUN = function(x) regmatches(x=x, regexpr('[0-9]{6}', x) )))
  41. puts$maturity <- as.numeric(as.Date(expiries, "%y%m%d") - Sys.Date())/365
  42.  
  43. puts$IV <- mapply(GetIV, value = puts$Ask, strike = puts$Strike, maturity = puts$maturity,
  44. MoreArgs= list(type='put', underlying= underlying.price,
  45. dividendYield=0, riskFreeRate = 0.01,
  46. volatility = volforcast), SIMPLIFY=TRUE)
  47.  
  48. puts$delta <- mapply(GetDelta, strike = puts$Strike, volatility = puts$IV,
  49. maturity = puts$maturity, MoreArgs= list(type='put',
  50. underlying=underlying.price, dividendYield=0,
  51. riskFreeRate = 0.01 ), SIMPLIFY=TRUE)
  52.  
  53. # subset out itm puts
  54. puts <- subset(puts, delta < -.1 & delta > -.5 )
  55.  
  56. xyz <- with(puts, interp(x=maturity, y=delta*100, z=IV*100,
  57. xo=sort(unique(maturity)), extrap=FALSE ))
  58.  
  59. with(xyz, persp3d(x,y,z, col=heat.colors(length(z))[rank(z)], xlab='maturity',
  60. ylab='delta', zlab='IV', main='IV Surface'))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement