我想使用R将多家公司的历史股票价格导出到Excel文档。我遇到了如何导出不同列中的所有价格的问题。
例如,我可以将Apple的调整后价格导出到Excel表格,但不知道如何将另一家公司添加到下一栏(依此类推)。代码如下:
library(quantmod)
library(xlsx)
getSymbols("AAPL", from="2014-01-01", to ="2017-01-01")
write.xlsx(AAPL[,6], file.choose(), row.names=TRUE)
有人有解决方案吗?
答案 0 :(得分:0)
这将做你想要的。
# assumes codes are known beforehand
codes <- c("MSFT","SBUX","S","AAPL","ADT")
urls <- paste0("https://www.google.com/finance/historical?q=",codes,"&output=csv")
paths <- paste0(codes,"csv")
missing <- !(paths %in% dir(".", full.name = TRUE))
missing
# simple error handling in case file doesn't exists
downloadFile <- function(url, path, ...) {
# remove file if exists already
if(file.exists(path)) file.remove(path)
# download file
tryCatch(
download.file(url, path, ...), error = function(c) {
# remove file if error
if(file.exists(path)) file.remove(path)
# create error message
c$message <- paste(substr(path, 1, 4),"failed")
message(c$message)
}
)
}
# wrapper of mapply
Map(downloadFile, urls[missing], paths[missing])
如果你有空闲时间,请检查一下。
https://gist.github.com/jaehyeon-kim/356cf62b61248193db25#file-downloadstockdata
答案 1 :(得分:0)