Skip to content

Commit

Permalink
Merge branch '247_getquote_tiingo'
Browse files Browse the repository at this point in the history
Fixes #247, fixes #250.
  • Loading branch information
joshuaulrich committed Nov 10, 2018
2 parents 8321ee8 + b96afcb commit 8ccf6ee
Showing 1 changed file with 56 additions and 0 deletions.
56 changes: 56 additions & 0 deletions R/getQuote.R
Original file line number Diff line number Diff line change
Expand Up @@ -314,3 +314,59 @@ getQuote.av <- function(Symbols, api.key, ...) {
rownames(output) <- output$Symbol
return(output[, c("Trade Time", "Last", "Volume")])
}

`getQuote.tiingo` <- function(Symbols, api.key, ...) {
# docs: https://api.tiingo.com/docs/iex/realtime
# NULL Symbols will retrieve quotes for all symbols
importDefaults("getQuote.tiingo")
if(!hasArg("api.key")) {
stop("getQuote.tiingo: An API key is required (api.key). ",
"Registration at https://api.tiingo.com/.", call. = FALSE)
}

base.url <- paste0("https://api.tiingo.com/iex/?token=", api.key)
r <- NULL
if(is.null(Symbols)) {
batch.size <- 1L
batch.length <- 1L
} else {
batch.size <- 100L
batch.length <- length(Symbols)
}

for(i in seq(1L, batch.length, batch.size)) {
batch.end <- min(batch.length, i + batch.size - 1L)
if(i > 1L) {
Sys.sleep(0.25)
cat("getQuote.tiingo downloading batch", i, ":", batch.end, "\n")
}

if(is.null(Symbols)) {
batch.url <- base.url
} else {
batch.url <- paste0(base.url, "&tickers=", paste(Symbols[i:batch.end], collapse = ","))
}

batch.result <- jsonlite::fromJSON(batch.url)
# do type conversions for each batch so we don't get issues with rbind
for(cn in colnames(batch.result)) {
if(grepl("timestamp", cn, ignore.case = TRUE)) {
batch.result[, cn] <- as.POSIXct(batch.result[, cn])
}
else if(cn != "ticker") {
batch.result[, cn] <- as.numeric(batch.result[, cn])
}
}
r <- rbind(r, batch.result)
}

colnames(r) <- gsub("(^[[:alpha:]])", "\\U\\1", colnames(r), perl = TRUE)
r[, "Trade Time"] <- r[, "LastSaleTimestamp"]

# merge join to produce empty rows for missing results from AV
# so that return value has the same number of rows and order as the input
if(!is.null(Symbols)) r <- merge(data.frame(Ticker = Symbols), r, by = "Ticker", all.x = TRUE)
rownames(r) <- r$Ticker
std.cols <- c("Trade Time", "Open", "High", "Low", "Last", "Volume")
return(r[, c(std.cols, setdiff(colnames(r), c(std.cols, "Ticker")))])
}

0 comments on commit 8ccf6ee

Please sign in to comment.