Created
March 23, 2013 21:39
-
-
Save rbresearch/5229463 to your computer and use it in GitHub Desktop.
Quandl API example for R
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Quandl <- function(Symbols, env=.GlobalEnv, from="2000-01-01", to=Sys.Date(), auth=NULL) { | |
# Function to pull data using the quandl API | |
# Returns an xts object | |
# Input Args | |
# Symbols : character vector of quandl codes of the datasets you want to retrieve | |
# from : character vector of the start date in yyyy-mm-dd | |
# to : character vector of the end date in yyyy-mm-dd | |
# auth : authentication toke for quandl API access www.quandl.com/api | |
# Base url for the quandl api | |
quandl.url <- "http://www.quandl.com/api/v1/datasets/" | |
# remove everything before the "/" for assigning the symbols to variable names | |
sym.names <- gsub(".*/", "", Symbols) | |
print(sym.names) | |
# Loop through the symbols to download the data and assign to the environment | |
for(i in 1:length(Symbols)) { | |
# Create a temporary file | |
tmp <- tempfile() | |
# Paste the url together and download the fle to tmp | |
download.file(paste(quandl.url, Symbols[i], ".csv", | |
"?trim_start=", from, | |
"&trim_end=", to, "&sort_order=asc", | |
"&auth_token=", auth, sep=""), destfile=tmp) | |
# Read the tmp file in as a data.frame | |
fr <- read.csv(tmp, as.is=TRUE) | |
# Delete the temporary file | |
unlink(tmp) | |
# Transform the fr object from data.frame to xts | |
fr <- xts(x=fr[,-1], order.by=as.Date(fr[,1], format="%Y-%m-%d")) | |
# Assign the symbol to the environment | |
assign(sym.names[i], fr, env) | |
# Pause 1 second between requests for more than 5 symbols | |
if (i >= 5 && length(Symbols) > 5) { | |
message("pausing 1 second between requests for more than 5 symbols") | |
Sys.sleep(1) | |
} | |
} | |
} | |
# example to load US GDP, Nymex Crude Oil, and the S&P 500 | |
datasets <- c("FRED/GDP", "OFDP/FUTURE_CL1", "YAHOO/INDEX_GSPC") | |
Quandl(Symbols = datasets) | |
# View the data | |
head(FUTURE_CL1) | |
head(GDP) | |
head(INDEX_GSPC) | |
# The data is downloaded as daily. Easily transform to monthly. This leverages | |
# the xts functions and keeps the Quandl() function simple | |
to.monthly(x=FUTURE_CL1, indexAt="lastof") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment