How to get currency exchange rates in R
Asked Answered
H

4

18

Are there are any R packages/functions to get exchange rates in real time, e.g. from Google Finance? Would prefer to avoid RCurl or other parsers if something's already out there.

Specifically, given vectors of "from" and "to" currency symbols, I'd like to know the rates. Something like:

IdealFunction(c("CAD", "JPY", "USD"), c("USD", "USD", "EUR"))
Hatcher answered 1/11, 2014 at 22:45 Comment(2)
Look at the package TFXBoeschen
You may want to visit the packages suggested here (TFX included): thertrader.com/2013/11/08/…Korney
N
30

You can use quantmod to get yahoo quotes. (I'm not sure how delayed yahoo FX quotes are, or how often they're updated.)

library(quantmod)
from <- c("CAD", "JPY", "USD")
to <- c("USD", "USD", "EUR")
getQuote(paste0(from, to, "=X"))
#                  Trade Time   Last Change % Change Open High Low Volume
#CADUSD=X 2014-11-01 08:23:00 0.8875    N/A      N/A  N/A  N/A N/A    N/A
#JPYUSD=X 2014-11-01 08:23:00 0.0089    N/A      N/A  N/A  N/A N/A    N/A
#USDEUR=X 2014-11-01 08:23:00 0.7985    N/A      N/A  N/A  N/A N/A    N/A

Or TFX for real-time, millisecond timestamped quotes if you sign up for a free account. (note you have to use market convention; i.e. USD/JPY instead of JPY/USD)

library(TFX)
pairs <- paste(to, from, sep="/")
QueryTrueFX(ConnectTrueFX(pairs, "validUser", "anytext"))
#   Symbol Bid.Price Ask.Price      High       Low               TimeStamp
#1 USD/CAD   1.12651   1.12665   1.12665   1.12651 2014-10-31 20:45:00.559
#2 USD/JPY 112.34600 112.35900 112.35900 112.34600 2014-10-31 20:45:00.134
#3 EUR/USD   1.25234   1.25253   1.25253   1.25234 2014-10-31 20:45:00.598

Or if you have an Interactive Brokers account, you can use the IBrokers package, or my twsInstrument package (which is basically just wrappers for IBrokers functions)

library(twsInstrument)
getQuote(paste0(to, from), src="IB") # only works when market is open.
Northerly answered 2/11, 2014 at 0:44 Comment(5)
You can actually get by without a TrueFX username: qt <- QueryTrueFX(); qt[qt$Symbol %in% paste(to, from, sep="/"),], but you'd still need to either know whether you need the pair quoted in reverse, or have some logic to see which exists.Northerly
is this quant mod function now defunct? quant mod::getFX("USD/JPY") returns: Error in download.file(oanda.URL, destfile = tmp, quiet = !verbose) : cannot open URL 'oanda.com/currency/historical-rates/…'Botfly
@Botfly it has been fixed in the development version. Alternatively, you can work around like this: options(download.file.method="wget"); getFX("USD/JPY")Northerly
this is why r is the bestNofretete
One question: How to use 'quantmod' to get yahoo quotes for a specific date, say 2019-12-31?Utta
R
7

You could use historical_exchange_rates() from the priceR library.

E.g. to get the daily AUD to USD exchange rate from 2010 to 2020:

# install.packages("priceR")
library(priceR)

cur <- historical_exchange_rates("AUD", to = "USD",
                          start_date = "2010-01-01", end_date = "2020-06-30")
tail(cur)

       date one_AUD_equivalent_to_x_USD
 2020-06-25                    0.688899
 2020-06-26                    0.686340
 2020-06-27                    0.686340
 2020-06-28                    0.685910
 2020-06-29                    0.687335
 2020-06-30                    0.690166

dim(cur)
[1] 3834    2


# Plot USD vs AUD last 10 years
library(ggplot2)
library(tidyverse)

cur %>% 
  tail(365 * 10) %>% 
  rename(aud_to_usd = one_AUD_equivalent_to_x_USD) %>%  
  mutate(date = as.Date(date)) %>% 
  ggplot(aes(x = date, y = aud_to_usd, group = 1)) +
  geom_line() +
  geom_smooth(method = 'loess') + 
  theme(axis.title.x=element_blank(),
        axis.ticks.x=element_blank()) + 
  scale_x_date(date_labels = "%Y", date_breaks = "1 year")

enter image description here

Some more examples can be found here, and here.

Ratan answered 28/7, 2020 at 19:15 Comment(5)
Hello @stevec, I really like priceR but can I ask where the data for priceR originates? The reason I ask is that, if I do an inflation adjustment (say 50 from Jan 2000 to Jan 2019) for US dollars and compare it to an online calculator - then I get really similar results. But for EUR priceR significantly underestimates the correction (~65 vs ~69). For GBP it's ~73 vs ~85 suggested by the Bank of England. I guess because the UK moved to RPI from CPI, but is there a way to get priceR to use (say) RPI instead?Denature
@Denature thanks for letting me know! All inflation data comes directly from the World Bank API. All currency exchange data comes from the European Central Bank (via exchangerate.host). If you confirm there is a bug, please let me know here: github.com/stevecondylios/priceR/issues and I will follow upRatan
@Denature here is the documentation for the World Bank inflation measure adjust_for_inflation() usesRatan
@Denature Unfortunately there's no easy way to use the RPI. The best I could suggest is you could view the code that calculates real prices and try to incorporate RPI instead of CPI. Hope that's some helpRatan
Awesome package! ThanksRomina
H
6

Looks like TFX and quantmod have functions for this (thanks to @RStudent and @KFB for the tips). I preferred quantmod since it didn't require setting up an account, but AFAICT there's no vectorized current-snapshot function like what I'm seeking. This function GetExchangeRates does this:

GetExchangeRates <- function(from_curr, to_curr, dt) {
  require(quantmod)
  exchanges <- paste0(from_curr, "/", to_curr)
  result <- mapply(
    function(from_curr, to_curr) {      
      getFX(paste0(from_curr, "/", to_curr),
        from = dt,
        to = dt,
        src = "yahoo",
        auto.assign = FALSE
      )
    },
    from_curr, to_curr
  )
  names(result) <- exchanges
  return(result)
}

TestExchangeRates <- function() {
  from_curr <- c("CAD", "JPY", "USD")
  to_curr <- c("USD", "USD", "EUR")
  dt <- Sys.Date() -1
  GetExchangeRates(from_curr, to_curr, dt)
}

TestExchangeRates()
#    CAD/USD    JPY/USD    USD/EUR 
# 0.72915600 0.00667232 0.94388600 
Hatcher answered 2/11, 2014 at 0:24 Comment(3)
getFX is nice for historic requests, but it only updates daily.Northerly
However, historical data in only available for the past 180 days. Is there any way to also get older data?Romina
Beware that quantmod::getFX returns mid prices from OANDA (I found this by comparing rates to other sources and using OANDA online feed). The mid prices are something like intraday average... I found really strange effects on these data. Really strange...Disenthrone
L
0

Comparing functions getSymbols and getFX:

  • only the first one changes the date input to -1 day, see below. EDIT: since 2023-10-30 not anymore
  • getSymbols returns several values per day, however, Open, Close, etc are the same
  • The second one has the 180 days limitation.

Regarding Alexey Burkanov comment

"Beware that quantmod::getFX returns mid prices from OANDA"

it seems true, because the average built here is closer to FX than the "Adjusted column" of getSymbol (other tests show same trend, not shown).

from_curr <- c("CAD", "JPY", "USD")
to_curr <- c("USD", "USD", "EUR")

library(quantmod)
# this dates will not work currently see above
res <- GetExchangeRates(from_curr = from_curr, to_curr = to_curr, "2023-05-03", "2023-05-09")

# artificial avg_low_high_this_fun column vs FX:
sum(abs(res$FX - res$avg), na.rm = T)
0.005812667

# Adjusted_Sy == Close == Open ? vs FX:
sum(abs(res$FX - res$Adjusted_Sy), na.rm = T)
0.01492536

enter image description here

# inspired in other answer:
require(quantmod)
require(dplyr)    
require(stringr)
require(rlang)
require(tibble)
GetExchangeRates <- function(from_curr, to_curr, from_date, to_date = from_date) {
  exchanges <- paste0(from_curr, "/", to_curr)

  result_getFX <- mapply(
    function(from_curr, to_curr) {
      ready_name <- paste0(from_curr, ".", to_curr)
      getFX(paste0(from_curr, "/", to_curr),
        from = from_date,
        to = to_date,
        src = "yahoo",
        auto.assign = FALSE
      ) |>
        as.list() |>
        as.data.frame() |>
        rownames_to_column(var = "date") |>
        set_names(~ (.) |> paste0("FX")) |>
        set_names(~ (.) |> str_replace_all(ready_name, ""))
    },
    from_curr, to_curr,
    SIMPLIFY = F
  )
  names(result_getFX) <- exchanges
  result_getFX <- result_getFX |> bind_rows(.id = "exchange")

  result_getSymbols <- try(get_exchange_rates_symbol(from_curr, to_curr, from_date, to_date), silent = TRUE)
  if (inherits(result_getSymbols, "try-error")) {
    warning("getSymbol unavailable for weekends or between two non-dollar currencies")
    return(result_getFX)
  }
  merge(result_getFX, result_getSymbols,
    by.y = c("exchange", "date_input"), by.x = c("exchange", "dateFX"),
    all = TRUE
  )
}

get_exchange_rates_symbol <- function(from_curr, to_curr, from_date, to_date = from_date) {
  exchanges <- paste0(from_curr, "/", to_curr)

  result_getSymbols <- mapply(
    function(from_curr, to_curr) {
      ready_name <- paste0(from_curr, to_curr)
      getSymbols(paste0(ready_name, "=X"),
        src = "yahoo", auto.assign = FALSE,
        from = as.Date(from_date), to = as.Date(to_date)
      ) |>
        as.list() |>
        as.data.frame() |>
        rownames_to_column(var = "date") |>
        set_names(~ (.) |> str_replace_all(".X", "")) |>
        rowwise() |>
        mutate("{ready_name}.avg_low_high_this_fun" := mean(c(
          .data[[paste0(ready_name, ".Low")]],
          .data[[paste0(ready_name, ".High")]]
        ), na.rm = TRUE)) |>
        set_names(~ (.) |> str_replace_all(paste0(ready_name, "."), "")) |>
        set_names(~ (.) |> paste0("_Sy")) |>
        mutate(date_input = ifelse(
          as.Date(date_Sy) < as.Date("2023-10-30"),
          as.character(as.Date(date_Sy) + 1),
          date_Sy
        )) |>
        relocate(date_input, .before = date_Sy) |>
        relocate(avg_low_high_this_fun_Sy, .after = date_input)
    },
    from_curr, to_curr,
    SIMPLIFY = FALSE
  )
  names(result_getSymbols) <- exchanges
  result_getSymbols <- result_getSymbols |>
    bind_rows(.id = "exchange") |>
    as.data.frame()
  result_getSymbols
}
Lyly answered 23/10, 2023 at 17:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.