Skip to content
All library documents

Downloading and Aggregating Stock Data with Quantmod in R

Article Quant Q&A · Author: breezeintopl

Summary

The document describes how to obtain a list of stock symbols, download price histories, skip symbols that fail, and combine adjusted closing prices for analysis in R. The accepted answer outlines a loop that attempts each download, checks for errors, and merges successful results into a time series dataset. It also shows how to resume a long run after an interruption and track progress.

A second answer points to a package designed to retrieve data for many tickers in a single data frame, which may avoid writing a manual loop. The discussion is a practical data collection example rather than a stock selection strategy: it does not specify a performance criterion, evaluate the resulting data, or address survivorship bias, ticker changes, download limits, or the reliability of the cited data source. The sample code reflects the tools and source used in the answer and may need adaptation for current package behavior.

Key ideas

  • A stock symbol list can be used to iterate over candidate securities and retrieve their price histories.
  • Download errors can be caught so that unavailable symbols do not stop a collection run.
  • Adjusted closing prices from successful downloads can be merged into a shared time series dataset.
  • A batch retrieval package is offered as an alternative to managing a manual ticker loop.
  • Ticker coverage, survivorship bias, and data source limitations remain relevant to universe analysis.

Tags

Full text
# how do I loop through all the stocks with quantmod and ttr?


# how do I loop through all the stocks with quantmod and ttr?












I just started with quantmod package. If I want to select stocks based on their recent performance, then I need to loop through all the stocks in, say, NYSE. So I need:

- get all the stock symbols

- select those symbols that do have data

- loop through them one by one(say, each time, download the stock data as $X$, and do some analysis. Then loop to next one, and set it as $X$)

My question is: how can I do these? Here is part of my thought:

- use stockSymbols() function in TTR package: `AllSym <- stockSymbols()`. The first column of `AllSym` are all the potential symbols.

- Use `getSymbols(AllSym[i,1])` to loop all the stock `i`:

Questions here:

- Not all the symbols from TTR have data. Some may have error when using `getSymbols`. I actually do not care about this certain stock. So how can I continue with the loop? [How can I use the `try` function?]

- The `getSymbols` function will automatically make the stock symbols as the variables. How can I copy(or set) it to $X$(instead of something like $APPL$)?

- How can I loop trough the variables with their names saved as strings in a vector? For example, if we do use `getSymbols` function to get data with name as the stock symbol. How can I loop through those stocks?[Note that their variable name are stored in first column `AllSym` as string]

Thank you very much!

## Answer by Rime (score 11, accepted)

https://quant.stackexchange.com/a/18835

Try the following:

```
library(quantmod)  # also loads xts and TTR

# Fetch all Symbols & store only the tickers to retrieve the data
symbols <- stockSymbols()
symbols <- symbols[,1]
```

Next we will specify where to to store data

`dataset<- xts() # Only run once`

The following code is the loop that will download OHLC data to your environment. It will then store the Adjusted Close of the downloaded companies and merge them in `dataset`

```
# cool progress bar to see the % of completion
n <- length(symbols)
pb <- txtProgressBar(min = 0, max = n, style=3)

# Actual loop: 
for(i in 1:length(symbols)) {
  symbols[i]-> symbol
# specify the "from" date to desired start date
  tryit <- try(getSymbols(symbol,from="2014-01-01", src='yahoo'))
  if(inherits(tryit, "try-error")){
    i <- i+1
  } else {
  # specify the "from" date to desired start date
  data <- getSymbols(symbol, from="2014-01-01", src='yahoo')
  dataset <- merge(dataset, Ad(get(symbols[i])))
  rm(symbol)
  }
  setTxtProgressBar(pb, i)
}
```

If the loop breaks, say on the 50th iteration, then just re run the last block of code by changing the following

```
# cool progress bar to see the % of completion
n <- length(symbols)
pb <- txtProgressBar(min = 0, max = n, style=3)

# Actual loop: 
# IF IT BREAKS ON THE 50th ITERATION, it must be skipped, therefore change it to 51
for(i in 51:length(symbols)) { 
  symbols[i]-> symbol
...
```

Keep on doing it until `symbols` is exhausted. Remember that it will download all the data unto your environment & that all the Adjusted Close prices are to be found in `dataset`

## Answer by Ganesh S (score 1)

https://quant.stackexchange.com/a/36795

You may refer this :

use the latest package in CRAN "BatchGetSymbols" for downloading OHLC data for multiple tickers in a single data frame.

You may not need to construct the loop for this.

Refer the following link for more information https://cran.r-project.org/web/packages/BatchGetSymbols/vignettes/BatchGetSymbols-vignette.html

Shown in full with attribution under the source's licence. Licence: CC BY-SA 4.0 (Stack Exchange)

This summary was written by Stratmill's research agent from the original; it is not a copy of the source.