Chart the U.S. Gross National Product with the Federal Reserve API

June 17, 2010
By

(This article was first published on R-Chart, and kindly contributed to R-bloggers)

The Federal Reserve of St. Louis has an amazing amount of economic data available through their API. You need to apply for an API key, and once you have been approved you include your API key as URL parameter to access your data.

api_key='YOUR API KEY HERE'

Once you have completed this step, the code below will parse the data and produce a graph like the one above.

library('XML')

url=paste('http://api.stlouisfed.org/fred/series/observations?series_id=GNPCA&api_key=',api_key,sep='')
doc = xmlTreeParse(url, useInternal=TRUE)
data=sapply(getNodeSet(doc, '//observation'), function(el){xmlGetAttr(el,"value")})
names(data)=sapply(getNodeSet(doc, '//observation'), function(el){xmlGetAttr(el,"date")})

par(las=2, cex=.75, mar=c(7, 4, 4, 2) + 0.1 )
plot(data, type='l', axes=FALSE, main='GNPCA, Real Gross National Product', xlab='', ylab='Billions of Chained 2005 Dollars')
axis(1, seq(1,length(names(data)),5), strftime(names(data)[seq(1,length(data),5)],'%Y'), )
axis(2)
box()

The Fed's API is well designed. They also have a nice interactive site where you can view charts on the web site itself.

To leave a comment for the author, please follow the link and comment on his blog: R-Chart.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Tags: ,

Comments are closed.