Search code examples
rcurrency

How to get currency exchange rates in R


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"))

Solution

  • 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.