我一直在使用名为getOptionsChain
的quantmod中的函数来拉入选项链。既然有像GOOG,AAPL等股票提供的迷你期权合约,它会在我的代码中引发一个错误。我正在删除符号后面的数字,现在迷你合约通过GOOG7传递所有数据。有什么想法吗?
library(quantmod)
underlying <- 'GOOG'
# set what your volatility forcast or assumption is
volforcast <- .25
# Get symbols current price
yqf <- "Last Trade (Price Only)"
underlying.price <- getQuote(underlying,what=yahooQF(yqf))$Last
OC <- getOptionChain(underlying, NULL)
#check data
head(OC)
lputs <- lapply(OC, FUN = function(x) x$puts)
head(lputs) #check for NA values, yahoo returns all NA values sometimes
puts <- do.call('rbind', lputs )
#check data
head(puts,150)
symbols <- as.vector(unlist(lapply(lputs, rownames)))
expiries <- unlist(lapply(symbols, function(x) {
regmatches(x=x, regexpr('[0-9]{6}', x)) } ))
puts$maturity <- as.numeric((as.Date(expiries, "%y%m%d") - Sys.Date())/365)
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
}
#this is the part that throws the error due to NA values in puts$maturity
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)
#this is the error Error: Date's serial number (-2147442285) outside allowed range [367-109574], i.e. [January 1st, 1901-December 31st, 2199]
我想避免添加puts$maturity
为NA
的行。
答案 0 :(得分:1)
您只想要puts$maturity
不是NA
的行吗?这将实现这一目标:
puts <- puts[!is.na(puts$maturity), ]
另一个选项,@VincentZoonekynd suggested是使用更好的正则表达式。
例如,这会查找以大写字母开头的符号,后跟6位数字,后跟“C”或“P”后跟8位数字,没有别的。它不会在代码之后拾取有7位数的符号。
symbols <- c("GOOG7130420P00695000", "GOOG130426P00720000")
grep("^[A-Z]+\\d{6}[CP]\\d{8}$", symbols, value=TRUE)
#[1] "GOOG130426P00720000"
^[A-Z]+
:以(^
)任意大写字母([A-Z]
)开头,一次或多次(+
)
\\d{6}
:后跟6({6}
)个数字(\\d
)
[CP]
:后跟字母“C”或“P”
\\d{8}$
:以8({8}
)个数字(\\d
)结尾,后面没有任何内容($
)
根据评论中的愿望,这里有一种方法可以在执行任何其他操作之前删除您不想要的行。它只是用你关心的东西重新创建对象。
OC <- lapply(OC, function(x) {
list(calls=x$calls[grep("[A-Z]\\d{6}[CP]\\d{8}$", rownames(x$calls)), ],
puts=x$puts[grep("[A-Z]\\d{6}[CP]\\d{8}$", rownames(x$puts)), ],
symbol=x$symbol)
})
答案 1 :(得分:1)
对于删除'GOOG7'或任何基础安全符号后跟'7'的简洁过滤器,请尝试以下操作:
symbols <- grep(paste("^",underlying,"[0-6,8-9]", sep="", collapse = NULL),
symbols, value = TRUE)