How to download multiple closing stock prices only with getSymbols into separate xts files?

自闭症网瘾萝莉.ら 提交于 2019-12-07 15:06:57

问题


How can I use getSymbols from the quantmod package to do the following:

  1. Download multiple stock price histories
  2. Select only the adjusted closing prices--i.e., suppress open/high/low and vol data
  3. Save each price history as a separate xts file, with dates

I can implement steps 1 and 2, but I'm having trouble with step 3. StackOverflow has several posts on downloading and merging prices for multiple tickers, but I can't find instructions for downloading and saving in separate files.

Here's what I have so far. Any advice on implementing the last step would be greatly appreciated. Thanks in advance!

library(quantmod)
symbols = c("GOOG","MSFT","AAPL")
getSymbols(symbols, from="2011-01-01")
ClosePrices <- lapply(symbols, function(x) Ad(get(x)))

I suspect that the solution is separating the ClosePrices file into separate files, one for each ticker, but I'm not sure how to do so.


回答1:


for part 1, see my answer here. Your method won't work for index symbols like ^GSPC or in general any symbol starting with special characters (due to the automatic assignment).

as for part 3, once you fetched all your symbols and stored them into myList as described in the link above, try the following to loop through your list and export elements of the list to your working directory:

require(quantmod)

#Vector of symbols to fetch prices for
symbols <- c('MSFT','SBUX','GOOGL')

#Initialize a list to store the fetched prices
myList <- list()

#Loop through symbols, fetch prices, and store in myList
myList <-lapply(symbols, function(x) {getSymbols(x,auto.assign=FALSE)} )

#Housekeeping
names(myList) <- symbols

#Export to seperate files
quiet <- lapply(1:length(myList), function(x){    #looping through all elements of your list
  write.csv(myList[[x]],     #accessing the xth element of your list
            paste0(names(myList)[x],'.csv'),   #naming the exported element
            row.names=index(myList[[x]])   #include dates in the export
  )  #close write.csv
}  #close function
)  #close lapply

EDIT: Combined the two posts as per the first comment.



来源:https://stackoverflow.com/questions/26980858/how-to-download-multiple-closing-stock-prices-only-with-getsymbols-into-separate

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!