1

I am trying to convert multiple xts objects in the Global environment to be multiple data.frames of the same name. I am trying to create a array of data.frames that can be feed into a program.

My code creates the xts objects OK but I would have to go back an manually convert each xts object for example (LMT <- as.data.frame(LMT)). I am looking to do a 100 or stocks at a time so this would be a great time saver. I was able to create its stock its objects for the example below in the list for tickers.

My code is as follows

require(quantmod)
require(xts)
tickers <- c("REGN", "LMT", "ZN", "OXY", "PG", "WBA", "EXC")     

FromDate = "2011-01-01"
ToDate = "2015-08-07" #Set one day ahead 
getSymbols(tickers, from = FromDate, to = ToDate,  src="yahoo")
###Convert to Data Frame
stocks[ticker] <- as.data.frame (c("REGN", "LMT", "ZN", "OXY", "PG", "WBA", "EXC")

Any suggestions would be helpful.

Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
Dan
  • 11
  • 1

2 Answers2

1

Instead of having getSymbols create objects in the global environment, create a new environment and tell getSymbols to create objects there.

require(quantmod)
tickers <- c("REGN", "LMT", "ZN", "OXY", "PG", "WBA", "EXC")     
dataEnv <- new.env()
getSymbols(tickers, from="2011-01-01", to="2015-08-07",  env=dataEnv)

Then you can use eapply to loop over all the objects in the new environment and apply a function to them, returning a list.

stocks <- eapply(dataEnv, as.data.frame)
Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
1

You might consider the tidyquant package to solve this problem. You can supply the tickers to the tq_get() function, which will return one data frame with all the prices in. You can do this with as many stock symbols as you would like.

library(tidyquant)
tickers <- c("REGN", "LMT", "ZN", "OXY", "PG", "WBA", "EXC")
tickers %>%
    tq_get(get  = "stock.prices",
           from = "2011-01-01",
           to   = "2015-08-07")

If you'd like to perform with an index or exchange, tidyquant has tq_index() and tq_exchange() which can be piped (%>%) to tq_get. For example, you could do this to get all of the stocks in the S&P500:

tq_index("SP500") %>%
    tq_get(get  = "stock.prices"
           from = "2011-01-01",
           to   = "2015-08-07")
Matt Dancho
  • 6,840
  • 3
  • 35
  • 26
  • I tried this and got error. tq_exchange("NYSE") %>% tq_get(get = "stock.prices", from = "2011-01-01", to = "2015-08-07") The error message is: Column `Symbol` doesn't exist. – Steve Feb 21 '21 at 03:54
  • NASDAQ changed their site. I haven't had time to make (yet another) update, but there is a solution forthcoming. https://github.com/business-science/tidyquant/issues/190 – Matt Dancho Feb 23 '21 at 21:32
  • Thanks! I followed the github link you provided. For now will use the json solution. Until tq_exchange() is updated. – Steve Feb 24 '21 at 11:49