How do i use dynamic variables in a loop to execute the command?


I want to download stock prices in a loop. But i have problem with the syntax on how to convert string into command etc.

I have this code:

getSymbols("GME", from = '2010-11-01', to = "2020-11-01")
Stockprices <- GME$GME.Adjusted

And this line of code above works fine.
however, if want the code to download more than stockprices i thought of using a loop to do that.

So i have a variable called "Dataset" with the different tricker-code for the stocks:


So i have tried to create a loop that looks like this:

x = 1
for (x in 1:nrow(Dataset)) {
getSymbols(sprintf("%s", Dataset[x,]), from = '2010-11-01', to = "2020-11-01")
Stockprice = sprintf("%s", Dataset[x,])$sprintf("%s", Dataset[x,]).Adjusted

The first coding line with the "getSymbols..." works fine.
But the last line of code where i want to save the adjusted stock price would not give the stock prices

I have also tried the code below, but that would just return a string of "GME$GME.Adjusted" but would not execute the command to actully give me the stock prices.


So how do i use data.frames or whatever its called to execute the command and not just returning a string.

You can use the get() function to return an object using a string of the object's name.

Your for loop will overwrite StockPrices in each iteration so that only the last value will be stored. I think you want to use a list to store each iteration of the loop.

I have never used the quantmod package but I think this will work.

Dataset <-  c("GME", "AAPL")
StockPrices <- vector(mode = "list", length = length(Dataset))
names(StockPrices) <- Dataset

for (Nm in Dataset) {
  getSymbols(Nm, from = '2010-11-01', to = "2020-11-01")
  StockPrices[[Nm]] <- get(Nm)[[paste0(Nm, ".Adjusted")]]

I see from the documentation that getSymbols accepts a vector of symbols, so this should also work.

Dataset <-  c("GME", "AAPL")
StockPrices <- vector(mode = "list", length = length(Dataset))
names(StockPrices) <- Dataset
getSymbols(Dataset, from = '2010-11-01', to = "2020-11-01")
for (Nm in Dataset) {
  StockPrices[[Nm]] <- get(Nm)[[paste0(Nm, ".Adjusted")]]

Note that getSymbols is unusual in that it assigns its output to an object or objects without explicit assignment by the user. You give it the character "AAPL" and it automatically makes an object named AAPL that stores the function output.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.