Skip to content

Instantly share code, notes, and snippets.

@njtierney
Forked from cpsievert/exchange-rates.R
Last active August 29, 2019 04:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save njtierney/0fe2daa11292e046f83fec7d8e9a8164 to your computer and use it in GitHub Desktop.
Save njtierney/0fe2daa11292e046f83fec7d8e9a8164 to your computer and use it in GitHub Desktop.
Convenience functions for https://openexchangerates.org/
# (1) Get a free plan from https://openexchangerates.org/signup/free
# (2) Tell this function your API key:
# from this section of the site: https://openexchangerates.org/account/app-ids
# Sys.setenv(OER_KEY = "paste-your-very-long-numeric-string-here")
Sys.setenv(OER_KEY = "OER_KEY")
library(glue)
library(tidyverse)
get_day <- function(day) {
u <- glue("https://openexchangerates.org/api/historical/{day}.json?app_id=\\
{Sys.getenv('OER_KEY')}")
res <- jsonlite::fromJSON(u)
# convert timestamp to date object
# http://stackoverflow.com/questions/13456241/convert-unix-epoch-to-date-object-in-r
res$rates$date <- as.POSIXct(
res$timestamp,
origin = "1970-01-01"
)
data.frame(res$rates)
}
get_rates <- function(start = end - 3,
end = Sys.Date()) {
days <- seq(start,
end,
by = "1 day")
map_dfr(days, get_day)
}
data <- get_rates()
data %>%
select(AUD,
NZD,
date)
#> AUD NZD date
#> 1 1.477168 1.566082 2019-08-27 09:59:59
#> 2 1.480451 1.571440 2019-08-28 09:59:59
#> 3 1.483777 1.578108 2019-08-29 09:59:59
#> 4 1.486302 1.584042 2019-08-29 14:00:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment