Can the function getSymbols() take a variable instead of the ticker itself?

StackOverflow https://stackoverflow.com/questions/19374184

  •  30-06-2022
  •  | 
  •  

Domanda

I want to loop through a CSV of some companies tickers and download their respective ticker data.

So far I have defined the variable 'ticker' as follows:

ticker <- companyList[1, 'Symbol']

when I print 'ticker' to the screen, it shows the 1st stocks ticker perfectly fine, but when I try to pass the ticker variable into quantmod's getSymbols function, I get an error.

getSymbols(ticker)
Error in do.call(paste("getSymbols.", symbol.source, sep = ""), list(Symbols =   current.symbols;  : 
 could not find function "getSymbols.940"

Is there an error in my syntax? Is there another way to go about doing this? Any book reccomendations?

È stato utile?

Soluzione

The easiest way is to specify an environment, for example assuming you have an vector with tickers, than you can do the following:

# tickers example
tik <- c("MMM", "ABT", "ABBV", "ANF", "ACT")

# new environment
stockData <- new.env() 

# download data
getSymbols(tik, env = stockData)

Than you can index to access the stocks: eg:

stockData$MMM

           MMM.Open MMM.High MMM.Low MMM.Close MMM.Volume MMM.Adjusted
# 2007-01-03    77.53    78.85   77.38     78.26    3781500        65.42
# 2007-01-04    78.40    78.41   77.45     77.95    2968400        65.16
# 2007-01-05    77.89    77.90   77.01     77.42    2765200        64.72
# 2007-01-08    77.42    78.04   76.97     77.59    2434500        64.86
# 2007-01-09    78.00    78.23   77.44     77.68    1896800        64.93
# 2007-01-10    77.31    77.96   77.04     77.85    1787500        65.07

same for all other stocks.

See also here: Quantmod

hth

EDIT:

for exporting you can use something like this:

# this will export 
lapply(stockData, function(x){
  write.csv(x, file=paste0(gsub(".Open", "", names(x)[1]), ".csv"))
    })

# the data can be found in the folder (execute the function!!!)
getwd()
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top