Downloading Yahoo stock prices in R

user227290 picture user227290 · Aug 18, 2010 · Viewed 60.8k times · Source

This is a newbie question in R. I am downloading yahoo finance monthly stock price data using R where the ticker names are read from a text file. I am using a loop to read the ticker names to download the data and putting them in a list. My problem is some ticker names may not be correct thus my code stops when it encounters this case. I want the following.

  1. skip the ticker name if it is not correct.
  2. Each element in the list is a dataframe. I want the ticker names to be appended to variable names in element dataframes.
  3. I need an efficient way to create a dataframe that has the closing prices as variables.

Here is the sample code for the simplified version of my problem.

library(tseries)  
tckk <- c("MSFT", "C", "VIA/B", "MMM") # ticker names defined  
numtk <- length(tckk);  
ustart <- "2000-12-30";
uend <- "2007-12-30" # start and end date  
all_dat <- list(); # empty list to fill in the data  
for(i in 1:numtk)  
{  
  all_dat[[i]] <- xxx <- get.hist.quote(instrument = tckk[i], start=ustart, end=uend, quote = c("Open", "High", "Low", "Close"), provider = "yahoo", compression = "m")  
}   

The code stops at the third entry but I want to skip this ticker and move on to "MMM". I have heard about Trycatch() function but do not know how to use it.

As per question 2, I want the variable names for the first element of the list to be "MSFTopen", "MSFThigh", "MSFTlow", and "MSFTclose". Is there a better to way to do it apart from using a combination of loop and paste() function.

Finally, for question 3, I need a dataframe with three columns corresponding to closing prices. Again, I am trying to avoid a loop here.

Thank you.

Answer

Shane picture Shane · Aug 18, 2010

Your best bet is to use quantmod and store the results as a time series (in this case, it will be xts):

library(quantmod)
library(plyr)
symbols <- c("MSFT","C","VIA/B","MMM")

#1
l_ply(symbols, function(sym) try(getSymbols(sym))) 
symbols <- symbols[symbols %in% ls()]

#2
sym.list <- llply(symbols, get) 

#3
data <- xts()
for(i in seq_along(symbols)) {
    symbol <- symbols[i]
    data <- merge(data, get(symbol)[,paste(symbol, "Close", sep=".")])
}