Skip to content

Instantly share code, notes, and snippets.

@joshuaulrich
Last active April 26, 2023 13:02
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save joshuaulrich/ee11ef67b1461df399b84efd3c8f9f67 to your computer and use it in GitHub Desktop.
Save joshuaulrich/ee11ef67b1461df399b84efd3c8f9f67 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"])
}
filename <- "intraday-sp500.rds"
if (file.exists(filename)) {
x <- readRDS(filename)
}
if (!exists("x")) {
x <- NULL
}
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")
if (!is.na(last(Cl(x)))) {
x <- rbind(x, last(x) * NA)
}
saveRDS(x, filename)
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")
price <- last(Cl(x), "2 days")
cs <- chart_Series(price, name = cname)
plot(cs)
}
Sys.sleep(15)
}
x <- x[!duplicated(data.frame(.index(x),x[,4:5])),]
saveRDS(x, filename)
@flare9x
Copy link

flare9x commented Jan 5, 2022

Fun

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment