As if there hasn’t been enough going on this week, silver prices have fallen nearly $10 per ounce. That’s a reduction of over 20%. Jeffrey Ryan’s quantmod package makes it easy to download the latest prices from OANDA’s web site and plot the excitement.
getSymbols() function is at the heart of quantmod’s data retrieval prowess, currently handling Yahoo! Finance, Google Finance, the St. Louis Fed’s FRED, and OANDA sites, in addition to MySQL databases and RData and CSV files.
First a word of warning: if you have a computer science background, you may cringe at the way
getSymbols() returns data. Rather than returning the fetched data as the result of a function call, it populates your R session’s
.GlobalEnv environment (or another one of your choosing via the
env parameter) with
zoo objects containing your data. For example, if you ask for IBM’s stock prices via
getSymbols("IBM"), you will find the data in a new “IBM” object in your
.GlobalEnv. This behavior can be changed by setting
auto.assign=F, but then you can only request one symbol at a time. But this is a minor nit about an incredibly useful package.
There’s even a wrapper function to help retrieve precious metal prices, and we will use this
getMetals() function to retrieve the last year’s worth of prices for gold (XAU) and silver (XAG):
library(quantmod) getMetals(c('XAU', 'XAG'), from=Sys.Date()-365)
Yup — that’s it.
getMetals() lets us know it has created two new objects:
 "XAUUSD" "XAGUSD"
There were also few warning messages complaining about the last line in the downloaded file. I haven’t bothered to dig into it as the data seem fine, including today’s price:
> ls()  "XAGUSD" "XAUUSD" > head(XAGUSD) XAG.USD 2010-05-07 17.6600 2010-05-08 18.4600 2010-05-09 18.4320 2010-05-10 18.4336 2010-05-11 18.5400 2010-05-12 19.3300 > tail(XAGUSD) XAG.USD 2011-05-02 47.9850 2011-05-03 45.2373 2011-05-04 44.0238 2011-05-05 40.9171 2011-05-06 37.9939 2011-05-07 35.0598
And here’s how easy it is to use the package’s built-in graphing facilities:
Yup — that’s quite a shellacking for silver.
Now I tend to be a ggplot2 guy myself, and I have never actually worked with
zoo objects before, but it’s pretty easy to get them into a suitable
silver = data.frame(XAGUSD) silver$date = as.Date(rownames(silver)) colnames(silver) = 'price' library(ggplot2) ggplot(data=silver, aes(x=date, y=price)) + geom_line() + theme_bw()