-1

I have the following vector:

USTickers=c("BAC","C","JPM","HBS","WFC","GS","MS","USB","BK","PNC")

Actually this vector of mine is much longer, but I just cut it short. This vector has ticker names of stocks.

I use quantmod to download data of the stocks from yahoo.

Since I do not intend to write function for every specific ticker I want to do a loop. First I want to use a function getSymbols which is not a problem. An object of a specific stock is downloaded.

However I want to make some adjustments of it and save it. Then I have a problem (second line in the for in loop). I want to have a variable name. The name of an object in which it will be saved has to be changing. But I am unable to do that.

for (i in 1:(length(USTickers))) {
  getSymbols.yahoo(paste(USTickers[i]),.GlobalEnv,from=StrtDt,to=EndDt)
  as.symbol(USTickers[i]=data.frame(time(get(USTickers[1])),get(USTickers[1])[,4],row.names=NULL)
}

In addiction:

in every object of a stock that I download, a column name is in this form "AAL.Open" and i want to change it to "AAL". How am I supposed to change column name?

I know it can be done with colnames function, but i don't know how to automate the operation.

Cause the first part "AAL" will be constantly changing, i just want to get rid of the ".Open" part.

Basically I could just be rewriting it with a ticker name, but I do not know how to apply it when the column name will be changing and I am planning to use as a reference my vector USTickers.

Raad
  • 2,675
  • 1
  • 13
  • 26

1 Answers1

0

It is a better idea to turn off auto assignment with the getSymbols function and store the results in a list. The elements can be easily accessed later. See the below for some ideas.

require(quantmod)

# Not going to loop through all
USTickers = c("BAC","C")#,"JPM","HBS","WFC","GS","MS","USB","BK","PNC")

# Initialise empty list
mysymbols <- vector("list", length(USTickers))

# Loop through symbols
for (i in 1:length(USTickers)) {
  # Store in list
  mysymbols[[i]] <- getSymbols.yahoo(paste(USTickers[i]),auto.assign = F)

  # Isolate column of interest and date
  mysymbols[[i]] <- data.frame(time(mysymbols[[i]]), 
                               mysymbols[[i]][,4],
                               row.names = NULL)

  # Change list elements name to symbol
  names(mysymbols)[i] <- USTickers[i]
}

Regarding substituting names, this can be done easily with gsub which can be applied to the colnames. For example:

gsub(".Open", "", "AAL.Open")

However if you just want to make that column name the ticker you can just do that directly in the loop as well colnames(mysymbols[[i]])[2] <- USTickers[i]

Raad
  • 2,675
  • 1
  • 13
  • 26