Skip to content

Commit

Permalink
Convert quote timestamps to POSIXct
Browse files Browse the repository at this point in the history
These are returned as seconds since the epoch.
  • Loading branch information
joshuaulrich committed Jul 28, 2023
1 parent 5959f98 commit 8eb4378
Showing 1 changed file with 29 additions and 11 deletions.
40 changes: 29 additions & 11 deletions R/getQuote.R
Original file line number Diff line number Diff line change
Expand Up @@ -118,21 +118,38 @@ function(Symbols,what=standardQuote(),session=NULL,...) {
stop(response$quoteResponse$error)
}

# Always return symbol and time (if regularMarketTime is provided)
# milliseconds to seconds
milliFields <- c("firstTradeDateMilliseconds", "gmtOffSetMilliseconds")
for (field in milliFields) {
if (!is.null(sq[[field]])) {
sq[[field]] <- sq[[field]] / 1000
}
}

# Use exchange TZ, if possible. POSIXct must have only one TZ, so times
# from different timezones will be converted to a common TZ
regularMktTime <- sq$regularMarketTime
if (is.null(regularMktTime)) {
Qposix <- .POSIXct(NA)
tz <- sq[["exchangeTimezoneName"]]
if (length(unique(tz)) == 1L) {
tz <- tz[1]
} else {
tz <- sq[, "exchangeTimezoneName"]
if (length(unique(tz)) == 1L) {
Qposix <- .POSIXct(regularMktTime, tz = tz[1L])
} else {
warning("symbols have different timezones; converting to local time")
Qposix <- .POSIXct(regularMktTime, tz = NULL) # force local timezone
warning("symbols have different timezones; converting to local time")
tz <- NULL
}

# timestamps to POSIXct
timeFields <-
c("regularMarketTime", "postMarketTime", "exDividendDate", "dividendDate",
"earningsTimestamp", "earningsTimestampStart", "earningsTimestampEnd",
"firstTradeDateMilliseconds")

for (field in timeFields) {
if (!is.null(sq[[field]])) {
sq[[field]] <- .POSIXct(sq[[field]], tz = tz)
}
}
if (is.null(sq$regularMarketTime)) {
sq$regularMarketTime <- .POSIXct(NA)
}

# Extract user-requested columns. Convert to list to avoid
# 'undefined column' error with data.frame.
Expand All @@ -143,7 +160,8 @@ function(Symbols,what=standardQuote(),session=NULL,...) {
qflist <- lapply(qflist, function(e) if (is.null(e)) pad else e)

# Add the symbols and trade time, and setNames() on other elements
qflist <- c(list(Symbol = sq$symbol, regularMarketTime = Qposix),
# Always return symbol and time
qflist <- c(list(Symbol = sq$symbol, regularMarketTime = sq$regularMarketTime),
setNames(qflist, QF))

df <- data.frame(qflist, stringsAsFactors = FALSE, check.names = FALSE)
Expand Down

0 comments on commit 8eb4378

Please sign in to comment.