Created
October 18, 2020 15:46
-
-
Save addiversitas/3a0a695b4019eb9d87bd1da9461d779a to your computer and use it in GitHub Desktop.
interpolation example for calls
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
#get coordinates of NAs in grid | |
toInterpolate <- which(is.na(ivGridCalls)) | |
coords <- cbind(toInterpolate%%dim(ivGridCalls)[1], toInterpolate%/%dim(ivGridCalls)[1] + 1) | |
coords[coords[,1] == 0, 2] <- coords[coords[,1] == 0, 2] - 1 | |
coords[coords[,1] == 0, 1] <- dim(ivGridCalls)[1] | |
#loop through NAs and interpolate | |
for(i in 1:nrow(coords)){ | |
#get the coordinates of a 10x10 area around the missing value | |
x1 <- max(coords[i,1] - 10, 1) | |
x2 <- min(coords[i,1] + 10, dim(ivGridCalls)[1]) | |
y1 <- max(coords[i,2] - 10, 1) | |
y2 <- min(coords[i,2] + 10, dim(ivGridCalls)[2]) | |
#get the moneyness/time to mat combination of the missing value | |
x0 <- as.numeric(rownames(ivGridCalls)[coords[i,1]]) | |
y0 <- as.numeric(colnames(ivGridCalls)[coords[i,2]]) | |
#get the part of the grid that is used to interpolate and remove all missing values that are present | |
interpGrid <- ivGridCalls[x1:x2,y1:y2] | |
interpGrid <- melt(interpGrid) | |
interpGrid <- na.omit(interpGrid) | |
#interpolate linearly | |
interpVal <- interp(x = interpGrid$Var1, y = interpGrid$Var2, z = interpGrid$value, | |
xo = x0, yo = y0, | |
linear = TRUE, extrap = TRUE)$z[1,1] | |
#if linear interpolation doesnt yield a result, use spline interpolation | |
if(is.na(interpVal)){ | |
interpVal <- interp(x = interpGrid$Var1, y = interpGrid$Var2, z = interpGrid$value, | |
xo = x0, yo = y0, | |
linear = FALSE, extrap = TRUE)$z[1,1] | |
} | |
#if the resulting value is clearly wrong, e.g. negative or way outside the values that are used to interpolate, | |
#leave it as NA | |
if(interpVal < 0 | interpVal > max(interpGrid$value * 1.5)){ | |
interpVal <- NA | |
} | |
#replace the value with the result of the interpolation | |
ivGridCalls[coords[i,1],coords[i,2]] <- interpVal | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment