Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Creating a dynamic list of xts objects

Going crazy trying to create some type of list/data frame containing xts objects.

I'm trying loop through a vector of strings (each an economic "ticker"), and create an xts object for each (length varies for each "ticker") using the getSymbols function from the quantmod package. Then I want to make each xts object one data point in a data frame. I also plan to have some associated data in the data frame (like, the maximum date in each xts object, and a "title" that I specify elsewhere, etc.), but I can handle that myself.

Just trying to create a list of xts objects is driving me nuts. When I just try something like this, I always wind up getting a list of strings:

test <- list()

for (i in 1:length(fredTickers))
{# import Data from FRED database
    # this creates a list of strings, I'm hoping for list of xts objects...
    test[i] <- getSymbols(fredTickers[i],src="FRED")
    # xts objects are created for each, but not assigned to the list
}

# this creates an xts object named EVANQ. 
# The test2 object is just a string with value "EVANQ".
test2 <- getSymbols("EVANQ",src="FRED")

Handling these xts objects is driving me nuts. I've tried many tricks.

Thank you for your help.

like image 434
ch-pub Avatar asked Mar 22 '23 05:03

ch-pub


1 Answers

It is stated multiple times in the documentation that by default the object is assigned to the global environment, not returned explicitly. Specify auto.assign=FALSE to do the opposite. Also recall the difference between '[' and '[['.

tickers <- c("F", "YHOO")
test <- list()

for (i in 1:length(tickers)) {
  test[[i]] <- getSymbols(tickers[i], src="yahoo", auto.assign=FALSE, return.class="xts")
}

head(test[[1]])
           F.Open F.High F.Low F.Close F.Volume F.Adjusted
2007-01-03   7.56   7.67  7.44    7.51 78652200       7.18
2007-01-04   7.56   7.72  7.43    7.70 63454900       7.36
2007-01-05   7.72   7.75  7.57    7.62 40562100       7.29
2007-01-08   7.63   7.75  7.62    7.73 48938500       7.39
2007-01-09   7.75   7.86  7.73    7.79 56732200       7.45
2007-01-10   7.79   7.79  7.67    7.73 42397100       7.39

class(test[[1]])
[1] "xts" "zoo"
like image 180
tonytonov Avatar answered Mar 29 '23 09:03

tonytonov