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

[This article was first published on R-Chart, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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 their blog: R-Chart.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)