2013-03-31 2 views
8

이 스크립트는 quantmod의 함수를 통해 yahoo 데이터를 가져온 다음 RGA 라이브러리가있는 3D 그래프를 게시하기 위해 데이터를 마사지합니다. 첨부 된 ggplot은 내가 시도하는 데이터를 표시합니다. 별도의 라인 기하 구조로 표면을 생성합니다. 문제는 3D 그래프가 매우 못 생겼고 앞쪽 만기에 제한된 양의 포인트 때문에자를 수 있다는 것입니다. 아무도 내가 여기에 무슨 일이 일어나는지 말할 수 없으며이 문제를 해결하기 위해 할 수있는 일은 .. 부드럽게 할 필요가 있습니까? 각 만료 라인은 다음 보간 .... volsurface http://img15.imageshack.us/img15/7338/surface.png ggplot2_smile http://img402.imageshack.us/img402/1272/volatilitysmilegoog.pngR 프로그래밍에서 변동성 표면 그래프에 고정 보간

library(RQuantLib) 
library(quantmod) 
library(rgl) 
library(akima) 
library(ggplot2) 
library(plyr) 

GetIV <- function(type, value, 
        underlying, strike,dividendYield, riskFreeRate, maturity, volatility, 
        timeSteps=150, gridPoints=151) { 

    AmericanOptionImpliedVolatility(type, value, 
            underlying, strike,dividendYield, riskFreeRate, maturity, volatility, 
            timeSteps=150, gridPoints=151)$impliedVol 
} 


GetDelta <- function(type, underlying, strike, 
        dividendYield, riskFreeRate, maturity, volatility, 
        timeSteps=150, gridPoints=149, engine="CrankNicolson") { 

    AmericanOption(type,underlying, strike, dividendYield, riskFreeRate, maturity, volatility, 
        timeSteps=150, gridPoints=149, engine="CrankNicolson")$delta 
} 
# set what symbol you want vol surface for 
underlying <- 'GOOG' 
# set what your volatility forcast or assumption is 
volforcast <- .25 
# Get symbols current price 
underlying.price <- getQuote(underlying,what=yahooQF("Last Trade (Price Only)"))$Last 

OC <- getOptionChain(underlying, NULL) 
#check data 
head(OC) 
lputs <- lapply(OC, FUN = function(x) x$puts[grep("[A-Z]\\d{6}[CP]\\d{8}$", rownames(x$puts)), ]) 
head(lputs) #check for NA values, yahoo returns all NA values sometimes 
puts <- do.call('rbind', lputs) 
#check data 
head(puts,5) 

symbols <- as.vector(unlist(lapply(lputs, rownames))) 
expiries <- unlist(lapply(symbols, FUN = function(x) regmatches(x=x, regexpr('[0-9]{6}', x)))) 
puts$maturity <- as.numeric((as.Date(expiries, "%y%m%d") - Sys.Date())/365) 

puts$IV <- mapply(GetIV, value = puts$Ask, strike = puts$Strike, maturity = puts$maturity, 
        MoreArgs= list(type='put', underlying= underlying.price, 
           dividendYield=0, riskFreeRate = 0.01, 
           volatility = volforcast), SIMPLIFY=TRUE) 

puts$delta <- mapply(GetDelta, strike = puts$Strike, volatility = puts$IV, 
        maturity = puts$maturity, MoreArgs= list(type='put', 
                   underlying=underlying.price, dividendYield=0, 
                   riskFreeRate = 0.01), SIMPLIFY=TRUE) 

# subset out itm puts 
puts <- subset(puts, delta < -.09 & delta > -.5) 

expiries.formated <- format(as.Date(levels(factor(expiries)), format = '%y%m%d'), "%B %d, %Y") 

fractionofyear.levels <- levels(factor(puts$maturity)) 

xyz <- with(puts, interp(x=maturity, y=delta*100, z=IV*100, 
         xo=sort(unique(maturity)), extrap=FALSE)) 

with(xyz, persp3d(x,y,z, col=heat.colors(length(z))[rank(z)], xlab='maturity', 
        ylab='delta', zlab='IV', main='IV Surface')) 

putsplot <- ggplot(puts, aes(delta, IV, group = factor(maturity), color = factor(maturity))) + 
    labs(x = "Delta", y = "Implied Volatilty", title="Volatility Smile", color = "GooG \nExpiration") + 
    scale_colour_discrete(breaks=c(fractionofyear.levels), 
          labels=c(expiries.formated)) + 
    geom_line() + 
    geom_point() 

putsplot 
+0

이에 아무런 도움 : 여기에 그 모습 것이 무엇입니까? – cdcaveman

+0

누구나 앞에서 보간을 고치는 법을 아십니까? – cdcaveman

+0

포인트를 일종의 라인 오브젝트로 바꾸고 모든 라인을 보간하면 점 대신에 – cdcaveman

답변

3

akima 패키지 정확히 당신이 필요로하는 것입니다,하지만 난 당신이 감소 당신의 y 축에 보간 점의 수, delta 변수에 필요가 있다고 생각합니다. 지금 설정 한 방법은 기본 40 포인트 그리드를 사용합니다.

# No interpolation on x-axis, but uses the default 40 point grid on the y-axis 
xyz <- with(puts, interp(x=maturity, y=delta*100, z=IV*100, 
      xo=sort(unique(maturity)), extrap=FALSE)) 
# By setting to use less points, it will "stretch" the surface over those points. 
xyz <- with(puts, interp(x=maturity, y=delta*100, z=IV*100, 
      xo=sort(unique(maturity)), 
      yo=seq(min(delta*100), max(delta*100), length = 15), extrap=FALSE)) 

Surface smoothed by y-axis

당신은 seq 기능의 길이 변수로 재생할 수 있습니다

은 부드러움의 수준을 다른 얻을 수 있습니다.


난 아직도 완전히 당신이 원하는 것을 이해하지 못하는,하지만 어쩌면 당신이 maturity에 의해 부드럽게하려면?

# This smooths just by x. 
xyz <- with(puts, interp(x=maturity, y=delta*100, z=IV*100, 
      xo=seq(min(maturity), max(maturity), length = 5), 
      , extrap=FALSE)) 

with(xyz, persp3d(x,y,z, col=heat.colors(length(z))[rank(z)], xlab='maturity', 
        ylab='delta', zlab='IV', main='IV Surface')) 

enter image description here

+0

예. . 나는 정말로 각 만료의 델타 값을 자아로만 희화시키고 싶지만 만기 사이에는 그렇지 않다. – cdcaveman

+0

@cdcaveman 흠, 나는 당신의 특정 도메인에 익숙하지 않다. '델타', '성숙', 'IV'의 관점에서 부드럽게하고 싶지 않은 것을 설명해 주시겠습니까? 나는 어느 것이 "만료"인지 정말로 얻지 않는다. 또한 델타 만이 여기에서 부드럽게 다루어지고 있다고 생각합니다. – nograpes

+0

거기에 이산 maturities ..... 델타 값은 특정 파업 가격에 옵션의 가격에서 파생됩니다 .. 그래서 나는 자신의 만료에 걸쳐 델타 옵션을 부드럽게하고 싶습니다 ... 아이디어는 델타에 의해 성숙 사이의 가격을 차별화 .. 그래서 당신은 성숙 사이에 부드럽게하고 싶지 않아 .. 난 단지 다른 만기가 아닌 각 만기 델타 값을 부드럽게하고 싶습니다 .. 델타에 의해 캘린더 위험을 볼 수있는 이런 식으로 .. 않습니다 감각? – cdcaveman