这些不再适用于期权数据,因为雅虎改变了它的网站,请使用谷歌金融作为期权数据源,这里是一个示例
示例:getOptionChain('GOOG',3) 表示谷歌期权链的下一个 3 到期日期
library(rjson)
library(plyr)
getOptionChain <- function (symbol,exp) {
# symbol = "WMT"
url <- "https://www.google.com/finance/option_chain?q="
# url <- paste(url, symbol, "&expd=15&expm=01&expy=2016&output=json", sep="")
url <- paste(url, symbol, "&output=json", sep="")
google.options.json <- readLines(url, warn = FALSE)
options.json <- google.options.json
options.json <- gsub("[{]", "{\"", options.json)
options.json <- gsub("[:]", "\":", options.json)
options.json <- gsub("[,] ", "$$$", options.json)
options.json <- gsub("[,]", ",\"", options.json)
options.json <- gsub("[,]\"[{]", ",{", options.json)
options.json <- gsub("[$][$][$]", ", ", options.json)
options.list <- fromJSON(options.json)
#get the options chain without an expiry date and then determine longest option
last.expiration <- length(options.list[["expirations"]])
if ( exp>0 && exp< last.expiration) {
last.expiration <-exp
}
month <- sprintf("%02d", options.list[["expirations"]][[last.expiration]]$m)
day <- sprintf("%02d", options.list[["expirations"]][[last.expiration]]$d )
year <- options.list[["expirations"]][[last.expiration]]$y
#now request option chain for the longest expiry
url <- "https://www.google.com/finance/option_chain?q="
url <- paste(url, symbol, "&expd=", day, "&expm=", month, "&expy=", year, "&output=json", sep="")
google.options.json <- readLines(url, warn = FALSE)
options.json <- google.options.json
options.json <- gsub("[{]", "{\"", options.json)
options.json <- gsub("[:]", "\":", options.json)
options.json <- gsub("[,] ", "$$$", options.json)
options.json <- gsub("[,]", ",\"", options.json)
options.json <- gsub("[,]\"[{]", ",{", options.json)
options.json <- gsub("[$][$][$]", ", ", options.json)
options.list <- fromJSON(options.json)
options <- ldply (options.list[["calls"]], data.frame)
options <- rename(options, c("s" = "contract.name",
"p" = "price",
"b" = "bid",
"a" = "ask",
"c" = "change",
"cp" = "change.percentage",
"oi" = "open.interest",
"vol" = "volume"))
options <- options[c( "contract.name",
"strike",
"price",
"change",
"change.percentage",
"bid",
"ask",
"volume",
"open.interest")]
options$expiry <- paste(options.list[["expiry"]]$m, options.list[["expiry"]]$d, options.list[["expiry"]]$y, sep = "/")
last.expiration <- length(options.list[["expirations"]])
options$longest.available.expiry <- paste(options.list[["expirations"]][[last.expiration]]$m,
options.list[["expirations"]][[last.expiration]]$d,
options.list[["expirations"]][[last.expiration]]$y, sep = "/")
options$underlying.price <- options.list[["underlying_price"]]
return(options)
}