2
votes

This will download dividend data for multiple stocks, each in a separate variable. The R data file names are the name of the stock followed by ".div". I.e., for Microsoft, the file would be "MSFT.div".

require(quantmod)
DJ30_symbols.ls <- c("MSFT", "IBM")
nDiv <- length(DJ30_symbols.ls)
for (i in 1:nDiv) {
  cat("Downloading ", i, " out of ", nDiv, "\n")
  getDividends(DJ30_symbols.ls[i], from = "1970-01-01", to = Sys.Date())
}

When i try to save the individual files as a csv file in my working directory, as follows:

write.zoo(paste(DJ30_symbols.ls[i], ".div", sep=' '),
  file = paste(DJ30_symbols.ls[i], ".csv", sep=''), index.name = "date")

I save files, but the data saved is not the dividends downloaded from Yahoo, but the symbol name (e.g. "MSFT.div"). I get the downloaded dividend information in a csv file if I do:

write.zoo(MSFT.div, file = "MSFT_div.csv", index.name = "date")

Is there any way I can use the variable names to read the data and save the files?

1

1 Answers

0
votes

The code paste(DJ30_symbols.ls[i], ".div", sep=' ') is a character string, not an object that contains the dividend data. You could use get to retrieve the object with that name, but it would be easier if you just had getDividends return the object rather than auto.assign it.

require(quantmod)
DJ30_symbols.ls <- c("MSFT", "IBM")
for (i in seq_along(DJ30_symbols.ls)) {
  cat("Downloading ", i, " out of ", nDiv, "\n")
  obj <- getDividends(DJ30_symbols.ls[i], from="1970-01-01", auto.assign=FALSE)
  write.zoo(obj, paste0(DJ30_symbols.ls[i], ".csv"), index.name="date")
}