Is it possible to download stock-symbols of a particular country using quantmod package for R?

rstudio

#1

Let's say, I want historical price data from the Indian Stock market.
All Indian stock symbols ends with .NS or .BO
So, is there a way to download stock-symbols or tickers of a particular country using quantmod package for R ?
Thanks !


#2

Here's an approach using an online source for the stock symbols. The code below downloads the first 20 symbols from the data source. Unfortunately, getSymbols throws and error and stops running if it tries a symbol that doesn't match anything at Yahoo Finance, so with this method you'd need to add some logic to skip over symbols that throw an error.

library(tidyverse)
library(quantmod)

stocks = read_csv("https://www.nseindia.com/content/equities/EQUITY_L.csv")

getSymbols(paste0(stocks$SYMBOL,".NS")[1:20])

The BatchGetSymbols package builds in some additional logic to make it easier to do batch data downloads with more graceful error handling. Here's an example adapted from the package introduction. l.out is a list. The second element of the list is a data frame with data for all of the stock symbols for which data is available.

library(BatchGetSymbols)

# set date range
first.date <- Sys.Date() - 60
last.date <- Sys.Date()

# set tickers
tickers <- paste0(stocks$SYMBOL[1:20], ".NS")

l.out <- BatchGetSymbols(tickers = tickers, 
                         first.date = first.date,
                         last.date = last.date, 
                         cache.folder = file.path(tempdir(), 
                                                  'BGS_Cache') ) # cache in tempdir()

head(l.out[["df.tickers"]])
>   price.open price.high price.low price.close volume price.adjusted   ref.date       ticker
> 1      35.35      36.85     35.35       36.00  33065          36.00 2018-07-02 20MICRONS.NS
> 2      35.50      37.00     35.50       35.80  29266          35.80 2018-07-03 20MICRONS.NS
> 3      36.85      36.85     34.95       35.55  23427          35.55 2018-07-04 20MICRONS.NS
> 4      35.45      36.20     35.00       35.10  27984          35.10 2018-07-05 20MICRONS.NS
> 5      35.05      36.10     34.80       35.50  23174          35.50 2018-07-06 20MICRONS.NS
> 6      36.00      36.70     35.60       35.80  21189          35.80 2018-07-09 20MICRONS.NS
>   ret.adjusted.prices ret.closing.prices
> 1                  NA                 NA
> 2        -0.005555583       -0.005555583
> 3        -0.006983240       -0.006983240
> 4        -0.012658256       -0.012658256
> 5         0.011396069        0.011396069
> 6         0.008450676        0.008450676