2017-02-07 42 views
0

我想使用R將多家公司的歷史股票價格導出到Excel文檔中。我遇到了如何導出不同列中所有價格的問題。使用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

'write.xlsx'設計用於處理data.frame,因此可能最容易轉換爲一個。你可能想把rownames變成一個專欄,這樣你就不會失去日期。 – alistaire

回答

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