1
votes

When trying to run the getSplits function across all S&P 500 tickers, I receive the following error "Error in open.connection(file, "rt") : HTTP error 404)"

I am able to run the function if I subset the tickers provided and only run a portion of them. Is there a way to write a line of code to bypass any tickers that might cause the HTTP error?

library(tidyverse)
library(BatchGetSymbols)
library(quantmod)

tickers <- GetSP500Stocks()

split_env <- lapply(tickers, function(x) getSplits(x))
2

2 Answers

2
votes

You can use try() to prevent it from breaking:

library(tidyverse)
library(BatchGetSymbols)
library(quantmod)

tickers <- GetSP500Stocks()[1:20,]

split_env = lapply(tickers$Tickers,function(x)try(getSplits(x)))
names(split_env) = tickers$Tickers

And if I am not wrong, you can get the ones without error

head(split_env[sapply(split_env,is.xts)])
$MMM
           MMM.spl
1972-06-16     0.5
1987-06-16     0.5
1994-04-11     0.5
2003-09-30     0.5

$ABT
           ABT.spl
1981-06-01  0.5000
1986-06-02  0.5000
1990-06-01  0.5000
1992-06-01  0.5000
1998-06-01  0.5000
2004-05-03  0.9356
2013-01-02  0.4798

$ABMD
           ABMD.spl
2000-10-02      0.5

$ACN
           ACN.spl
2011-12-30     0.1

$ATVI
            ATVI.spl
2001-11-21 0.6666667
2003-06-09 0.6666667
2004-03-16 0.6666667
2005-03-23 0.7500000
2005-10-25 0.7500000
2008-09-08 0.5000000

$ADBE
           ADBE.spl
1987-03-12      0.5
1988-11-23      0.5
1993-08-11      0.5
1997-07-29      1.0
1997-10-29      1.0
1999-10-27      0.5
2000-10-25      0.5
2005-05-24      0.5
0
votes

Install quantmod v. 0.4.17.2 onwards; CRAN doesn't have this version yet, so install from github directly devtools::install_github("joshuaulrich/quantmod") Because the new version can handle multiple connections & handles (Check this), and you would need this to push multiple requests to yahoo.

The following function uses multiple cores. So you can replace %dopar% with %do% if you want it otherwise.

RawData.Splits <- function(stocks, from)
{
  x <- foreach(ticker = stocks, .combine = bind_rows
               , .errorhandling = "remove", .inorder = F, .multicombine = T
               ) %dopar%
              {
                x <- tryCatch({suppressWarnings(
                                quantmod::getSplits(ticker, from, envir = .GlobalEnv)
                                )},
                              error = function(e) {data.frame()})

            if(xts::is.xts(x))
            {
              names(x) <- c("split.ratio")
              x <- as.data.frame(x) %>% mutate(split.ds = rownames(.), ticker) %>%
                select(ticker, split.ds, split.ratio)
              
              cat(paste0(ticker, "; "))
            }
            else {x <- data.frame()}
            
            rm(ticker)
            return(x)
          }

  if(nrow(x) > 0) 
  { x <- x %>% mutate(split.ds = as.Date(split.ds), updated.on = Sys.Date()) }
  
  rm(stocks, from)
  return(x)
}