James Picerno
James Picerno

Reputation: 490

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

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.

Upvotes: 4

Views: 4783

Answers (1)

Bahae Omid
Bahae Omid

Reputation: 574

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.

Upvotes: 3

Related Questions