root.dir <- "/home/share/CorpCDOs" code.dir <- if(Sys.getenv("CODE_DIR")!="") Sys.getenv("CODE_DIR") else root.dir source(file.path(code.dir, "code", "R", "yieldcurve.R")) source(file.path(code.dir, "code", "R", "optimization.R")) source(file.path(code.dir, "code", "R", "calibration.R"), chdir=TRUE) source(file.path(code.dir, "code", "R", "serenitasdb.R")) source(file.path(code.dir, "code", "R", "creditIndex.R")) source(file.path(code.dir, "code", "R", "tranche_functions.R")) tradedate <- as.Date("2016-08-02") exportYC(tradedate) index <- creditIndex("ig26", "5yr") index <- set.index.desc(index, tradedate) index <- set.singlenamesdata(index, tradedate) index$cs <- couponSchedule(IMMDate(tradedate, noadj=TRUE), index$maturity,"Q", "FIXED", 1, 0, tradedate, IMMDate(tradedate, "prev")) tweakindex <- function(index, refprice){ fixedRate <- couponfromindex(index$name, index$tenor)*1e-4 index$quotes <- data.frame(maturity=index$maturity, refspread=fixedRate, refprice=refprice) index$quotes$spread <- fixedRate index$cs <- couponSchedule(IMMDate(tradedate, noadj=TRUE), index$maturity,"Q", "FIXED", 1, 0, tradedate, IMMDate(tradedate, "prev")) index$quotes$price <- index$quotes$refprice/100 tweak <- tweakcurves(index, index$tradedate) index$portfolio <- NULL index <- c(index, tweak) return( index ) } ref <- 107 newindex <- tweakindex(index, ref) h <- cdshazardrate.flat(1-ref/100, 0.05, index$maturity, 0.3, tradedate) exerciseDates <- c(as.Date("2016-08-17"), as.Date("2016-09-21"), as.Date("2016-10-19")) fp <- c() fp2 <- c() for(i in seq_along(exerciseDates)){ fp <- c(fp, defaultAdjustedForwardIndexPrice(newindex, exerciseDates[i])) fp2 <- c(fp2, forwardflatcds(h, index$cs, tradedate, exerciseDates[i], fixedRate=0.01, R=0.4)) } calib <- function(S0, index, fp, exerciseDate, sigma, quad){ T <- yearFrac(index$tradedate, exerciseDate) S <- S0 * exp(-sigma^2/2*T+sigma*quad$Z*sqrt(T)) values <- unlist(lapply(S, function(s){ snacpv(index$cs, s, index$quotes$refspread, index$recovery, exerciseDate)})) guess <- crossprod(quad$w, values) return( guess - fp ) } option <- function(index, fp, exerciseDate, sigma, strike, quad){ T <- yearFrac(index$tradedate, exerciseDate) S0 <- uniroot(calib, interval=c(0.02, 0.05), index, fp, exerciseDate, sigma, quad)$root S <- S0 * exp(-sigma^2/2*T+sigma*quad$Z*sqrt(T)) v <- matrix(0, length(S), 2) for(i in 1:length(S)){ fw <- snacpv(index$cs, S[i], index$quotes$refspread, index$recovery, exerciseDate) v[i,] <-c(max(fw-strike, 0), max(strike-fw, 0)) } return(crossprod(quad$w, v)) }