Skip to content

Instantly share code, notes, and snippets.

@msmith01
Forked from joshuaulrich/intraday-sp500.R
Created November 14, 2020 20:37
Show Gist options
  • Select an option

  • Save msmith01/79a62412de2d836dcff2a0e1f90c2b52 to your computer and use it in GitHub Desktop.

Select an option

Save msmith01/79a62412de2d836dcff2a0e1f90c2b52 to your computer and use it in GitHub Desktop.
Track the S&P 500 throughout the trading day
require(quantmod)
do_chart <- function(symbol) {
quote <- getQuote(symbol)
quote$Close <- quote$Last
xts(OHLCV(quote), quote[,"Trade Time"],
pct_change = quote[,"% Change"])
}
x <- readRDS("intraday-sp500.rds")
market_closed <- TRUE
errored <- FALSE
repeat {
now_t <- xts(,Sys.time())
now <- .indexhour(now_t)*100 + .indexmin(now_t)
if (now > 1530) {
cat(format(index(now_t)), "after close;",
"writing data and sleeping for an hour\n")
saveRDS(x, "intraday-sp500.rds")
Sys.sleep(3600)
next
} else if (now < 828) {
if (now < 720) {
cat(format(index(now_t)), "before open; sleeping for an hour\n")
Sys.sleep(3600)
} else if (now > 721 && now < 810) {
cat(format(index(now_t)), "before open; sleeping for 10 minutes\n")
Sys.sleep(600)
} else {
cat("2-20 min before open; sleeping for 1 min\n")
Sys.sleep(60)
}
next
} else if (now > 830 && market_closed) {
cat("market open\n")
market_closed <- FALSE
}
y <- try(do_chart("^GSPC"), silent = TRUE)
if (inherits(y, "try-error")) {
msg <- attr(y, "condition")[["message"]]
cat("Error! ", msg, "\n")
errored <- TRUE
Sys.sleep(15)
next
} else if (errored) {
errored <- FALSE
cat("...recovered\n")
}
x <- rbind(x, y)
if (nrow(x) > 5) {
cname <- paste(Cl(last(x)), attr(y, "pct_change"), sep = "\t")
cs <- chart_Series(Cl(x),
subset = "2020-11-09 07:45/",
name = cname)
plot(cs)
}
Sys.sleep(15)
}
x <- x[!duplicated(data.frame(.index(x),x[,4:5])),]
saveRDS(x, "intraday-sp500.rds")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment