Search code examples
rquantmod

Error using getSymbols() in quantmod


I'm trying to randomly select 50 stocks from the New York Stock Exchange, and then get the symbols for them. This code:

 require(quantmod)
 NYstocks<-stockSymbols(exchange="NYSE")
 NYsymbols<-NYstocks[["Symbol"]]
 my_portfolio<-sample(NYsymbols, 50, replace = FALSE)
 date_begin <- as.Date("2014-02-18")
 date_end <- as.Date("2016-02-18")
 tickers <- getSymbols(my_portfolio, from = date_begin, to = date_end)

gets the error

Error in read.table(file = file, header = header, sep = sep, quote = quote, : more columns than column names

my_portfolio is a character vector, so I'm having a hard time figuring out what it means about columns and column names. I've tried using src="google" and got

Error in colnames<-(*tmp*, value = c("AIW.Open", "AIW.High", "AIW.Low", : length of 'dimnames' [2] not equal to array extent

Thanks for any help!


Solution

  • As the Note in ?stockSymbols says:

    The symbols returned by stockSymbols may not be in the format necessary to retrieve data using getYahooData.

    And note that TTR::getYahooData downloads data from Yahoo Finance, just like getSymbols.yahoo.

    You should also use set.seed when using functions that use the random number generator (i.e. sample) so your example will be reproducible.

    A couple other things to keep in mind:

    1. Yahoo Finance, Google Finance, etc do not necessarily provide historical data for all instruments.
    2. Instruments returned by stockSymbols are not necessarily equities. They could be tickers for an ETF, ETN, etc.

    There are other question/answers about how to use try or tryCatch to trap errors that may occur because a site doesn't provide historical data.