在R中下载Yahoo股票价格 [英] Downloading Yahoo stock prices in R

查看:238
本文介绍了在R中下载Yahoo股票价格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是R中的一个新手问题.我正在使用R下载Yahoo财务月度股票价格数据,其中从文本文件中读取了股票代码.我正在使用循环读取代码名称,以下载数据并将其放在列表中.我的问题是某些股票代号名称可能不正确,因此遇到这种情况时我的代码将停止.我想要以下内容.

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. 如果代码名称不正确,请跳过该代码.
  2. 列表中的每个元素都是一个数据框.我希望代码名称可以附加到元素数据帧中的变量名称上.
  3. 我需要一种有效的方法来创建一个以收盘价作为变量的数据框.

这是我的问题的简化版本的示例代码.

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")  
}   

代码在第三个条目处停止,但是我想跳过此代码,转到"MMM".我听说过Trycatch()函数,但不知道如何使用它.

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.

根据问题2,我希望列表的第一个元素的变量名称为"MSFTopen","MSFThigh","MSFTlow"和"MSFTclose".除了使用loop和paste()函数的组合之外,还有其他更好的方法吗?

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.

最后,对于问题3,我需要一个带有三列对应于收盘价的数据框.同样,我试图避免在这里出现循环.

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

谢谢.

推荐答案

您最好的选择是使用Quantmod并将结果存储为时间序列(在本例中为xts):

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

这篇关于在R中下载Yahoo股票价格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆