Skip to content

Instantly share code, notes, and snippets.

@mgei
Created December 27, 2020 17:12
Show Gist options
  • Save mgei/f5cd22848d656d47180db7e68b04048e to your computer and use it in GitHub Desktop.
Save mgei/f5cd22848d656d47180db7e68b04048e to your computer and use it in GitHub Desktop.
library(tidyverse)
library(jsonlite)
get_earnings <- function(symbol, av_key, get = "quarterly", cache_dir = "cache") {
if (!(cache_dir %in% list.dirs(full.names = F, recursive = F))) {
dir.create(cache_dir)
}
if (!(paste0(symbol, ".json") %in% list.files(cache_dir))) {
print("downloading")
url <- paste0("https://www.alphavantage.co/query?function=EARNINGS&symbol=", symbol, "&apikey=", av_key)
download.file(url, dest = paste0(cache_dir, "/", symbol, ".json"))
}
json <- read_json(paste0(cache_dir, "/", symbol, ".json"), simplifyVector = T)
if (get == "quarterly") {
suppressWarnings(
out <- json$quarterlyEarnings %>%
as_tibble() %>%
mutate(fiscalDateEnding = as.Date(fiscalDateEnding),
reportedDate = as.Date(reportedDate)) %>%
mutate_if(is.character, as.double)
)
} else if (get == "annual") {
suppressWarnings(
out <- json$annualEarnings %>%
as_tibble() %>%
mutate(fiscalDateEnding = as.Date(fiscalDateEnding)) %>%
mutate_if(is.character, as.double)
)
} else {
stop("get argument has to be 'quarterly' or 'annual'")
}
return(out)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment