Search code examples
rfor-loopquantmod

Creating arraylist using for loop


I want to create an arraylist of the price data of certain stocks.

First, I selected my basket of stocks using:

tickers <- c("^GSPC","MSFT","INTC","NVDA","AAPL")

Next, I downloaded the price data using a for loop function:

for (i in 1:length(tickers)) {
  getSymbols(tickers[i],
             from = as.Date("2006-01-01"), to = as.Date("2009-12-31"))
}

Now, I want to add each stock data into an arraylist, so I tried something like this:

s <- list()
for (i in 1:length(tickers)) {
  getSymbols(tickers[i],
             from = as.Date("2006-01-01"), to = as.Date("2009-12-31")) %>%
             {. ->> s[[i]]}
}

But the output seems to only give me an arraylist of the name of the stocks:

[[1]] [1] "GSPC"

[[2]] [1] "MSFT"

[[3]] [1] "INTC"

[[4]] [1] "NVDA"

[[5]] [1] "AAPL"

Is there something wrong with the code I gave after the pipe function?


Solution

  • Just use lapply to create your list object and make sure to set the option auto.assign to FALSE.

    library(quantmod)
    
    tickers <- c("^GSPC","MSFT","INTC","NVDA","AAPL")
    
    # Get the ticker data
    s <- lapply(tickers, getSymbols, from = as.Date("2006-01-01"), to = as.Date("2009-12-31"), auto.assign = FALSE)
    
    # name the list objects
    names(s) <- tickers
    
    str(s)
    List of 5
     $ ^GSPC:An ‘xts’ object on 2006-01-03/2009-12-30 containing:
      Data: num [1:1006, 1:6] 1248 1269 1273 1273 1285 ...
     - attr(*, "dimnames")=List of 2
      ..$ : NULL
      ..$ : chr [1:6] "GSPC.Open" "GSPC.High" "GSPC.Low" "GSPC.Close" ...
      Indexed by objects of class: [Date] TZ: UTC
      xts Attributes:  
    List of 2
      ..$ src    : chr "yahoo"
      ..$ updated: POSIXct[1:1], format: "2018-12-07 15:01:48"
     $ MSFT :An ‘xts’ object on 2006-01-03/2009-12-30 containing:
    .....