How can I load multiple closing prices of a stock using getSymbols only into separate xts files?
How can I use getSymbols from quantmod package to do the following:
- Download some stock price stories.
- Select only adjusted close prices - i.e. suppress open / high / low and vol data
- Save each price history as a separate xxt file with dates
I can implement steps 1 and 2, but I am having problems with step 3. StackOverflow has several posts about loading and merging prices for multiple tickers, but I cannot find instructions for loading and saving in separate files.
Here's what I have so far. We would be very grateful for any recommendations on the last step. 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 the solution is splitting the ClosePrices file into separate files, one for each ticker, but I'm not sure how.
source to share
for part 1, see my answer here . Your method will not work for index characters such as ^GSPC
or generally any character starting with special characters (due to automatic assignment).
as for part 3, once you've extracted all your symbols and saved them in myList
as described in the link above, try the following procedure to view the list and export the list items to the 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: combine the two posts as per the first comment.
source to share