可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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"))
回答1:
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.
回答2:
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, to, dt=Sys.Date()) { require(quantmod) obj.names <- getFX(paste0(from, "/", to), from=dt, to=dt) result <- numeric(length(obj.names)) names(result) <- obj.names for (obj.name in obj.names) { result[obj.name] <- as.numeric(get(obj.name))[1] # Clean up rm(obj.name) } return(result) } TestExchangeRates <- function() { from <- c("CAD", "JPY", "USD") to <- c("USD", "USD", "EUR") GetExchangeRates(from, to) }