user8346341
user8346341

Reputation:

How to write a for loop for adjusted close prices on list of stock symbols?

I'm an R beginner, but I'm trying to use quantmod to write a loop to pull adjusted stock prices for a series of dates (current, 6 months ago, 12 months ago, 18 months ago). I want to get a sense of the health of a company over time. However, I've run into error after error so am putting out what I have and hoping someone can help. I haven't been able to use getSymbols to fetch anything, so CompanyTickers is just from a .csv of symbols.

stocks <- (CompanyTickers$Symbol)

## Generate new environment stockEnv for results
stockEnv <- new.env()

##
## This pulls available stock data for the Symbols in the stock variable
## The try function keeps the code from quitting for defunct symbols
##
df <- try(getSymbols(stocks, src ='yahoo', env=stockEnv))


## Runs a loop on the data stored to stockEnv
## One Year ago
for (stock in ls(stockEnv)){
  try(monthlyReturn(xtsTicker, subset='2017-09-18')     
}

Upvotes: 0

Views: 322

Answers (2)

phiver
phiver

Reputation: 23608

Below code will get you started. No need for a separate environment, just store everything in a list and use the apply functions to help you with looping over all the data. The monthlyReturn data needs something specified like I have below like "2017-09-18::" or "2017-09::". The monthly return calculation will take all the data from the month regardless if your starting date is in the middle of the month.

library(quantmod)

# stocklist with 1 bad stock
stocks <- c("MSFT", "MSFT2", "GIS")

# Get the data and name the list objects
stock_data <- lapply(stocks, function(x) try(getSymbols(x, src ='yahoo', auto.assign = FALSE)))
names(stock_data) <- stocks


# Show which stocks don't have any data
which(sapply(stock_data, is.character) == T)
MSFT2 
    2 

# remove stocks that don't return any data.
stock_data <- stock_data[!sapply(stock_data, is.character)]

# One Year ago
monthly_return_data <- lapply(stock_data, function(x) monthlyReturn(x, subset = "2017-09-18::"))

For data quality purposes you might want to check the source tiingo or Alphavantage (API keys needed). yahoo doesn't always have correct data.

Upvotes: 0

Roman Luštrik
Roman Luštrik

Reputation: 70653

You have stored the result into an environment. When you use ls it fetches just the name(s) of the objects in that environment. You can use function get to fetch the object and work on it.

x <- new.env()
x$obj <- 1

for (i in ls(x)) {
  message("Accessing ls() result:")
  print(i)
  message("Properly fetch from environment")
  print(get(i, envir = x))
}

Accessing ls() result:
[1] "obj"
Properly fetch from environment
[1] 1

Upvotes: 0

Related Questions