Created
July 12, 2015 12:48
-
-
Save mbusigin/8ab0bd5a056c6f75298f to your computer and use it in GitHub Desktop.
R function to retrieve FRED series as xts object
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
## | |
## The quantmod function, getSymbols.FRED(), has been broken by the recent upgrade to FRED to https only. | |
## I've taken that function and tweaked it to work. | |
## | |
fred <- function (Symbols, env, return.class = "xts", ...) | |
{ | |
importDefaults("getSymbols.FRED") | |
this.env <- environment() | |
for (var in names(list(...))) { | |
assign(var, list(...)[[var]], this.env) | |
} | |
if (!hasArg(verbose)) | |
verbose <- FALSE | |
if (!hasArg(auto.assign)) | |
auto.assign <- TRUE | |
FRED.URL <- "https://research.stlouisfed.org/fred2/series" | |
for (i in 1:length(Symbols)) { | |
if (verbose) | |
cat("downloading ", Symbols[[i]], ".....\n\n") | |
tmp <- tempfile() | |
download.file(paste(FRED.URL, "/", Symbols[[i]], "/", | |
"downloaddata/", Symbols[[i]], ".csv", sep = ""), method='curl', | |
destfile = tmp, quiet = !verbose) | |
fr <- read.csv(tmp, na.string = ".") | |
unlink(tmp) | |
if (verbose) | |
cat("done.\n") | |
fr <- xts(as.matrix(fr[, -1]), as.Date(fr[, 1], origin = "1970-01-01"), | |
src = "FRED", updated = Sys.time()) | |
dim(fr) <- c(NROW(fr), 1) | |
colnames(fr) <- as.character(toupper(Symbols[[i]])) | |
fr <- quantmod:::convert.time.series(fr = fr, return.class = return.class) | |
Symbols[[i]] <- toupper(gsub("\\^", "", Symbols[[i]])) | |
if (auto.assign) | |
assign(Symbols[[i]], fr, env) | |
} | |
if (auto.assign) | |
return(Symbols) | |
return(fr) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment