Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 views
in Technique[技术] by (71.8m points)

finance - Downloading Yahoo stock prices in R

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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=".")])
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...