I'm a complete beginner in R. I want to download historical data about current companies in S&P500 using getSymbols for a few periods. Obviously, some of companies didn't exist in a given period and R stops downloading data for the next tickers. Is there any way to enable getSymbols to simply omit tickers if their data are not existing? It would be much easier to just get the S&P 500 list for that period, but unfortunately it's not free.
You can use try
within sapply
like this:
library(quantmod)
WoW <- new.env()
##
sapply(SiP, function(x){
try(
getSymbols(
x,
from=as.Date("2001-01-01"),
to=as.Date("2007-01-01"),
env=WoW),
silent=TRUE)
})
Errors will be printed to the console (you could probably mitigate this if desired), but the tickers that do not generate errors will still produce data:
R> ls(WoW)
[1] "AA" "AEE" "AEP" "AES" "AP" "ARG" "ATI" "AVY" "BLL" "CF" "CMS" "CNP" "CTL" "D" "DOW" "DTE" "DUK" "ECL" "ED" "EIX"
[21] "EMN" "ETR" "EXC" "FCX" "FE" "FMC" "FTR" "GAS" "IFF" "IP" "LVLT" "MON" "MOS" "MWV" "NEE" "NEM" "NI" "NRG" "NU" "NUE"
[41] "OI" "PCG" "PEG" "PNW" "POM" "PPG" "PPL" "SCG" "SO" "SRE" "T" "TE" "TEG" "VZ" "WEC" "WIN" "XEL"
##
R> length(ls(WoW))
[1] 57
R> length(SiP)
[1] 59
So it looks like there were issues with 2 of the stocks, as sapply(...)
successfully returned data for the other 57.
From here, objects can be accessed within WoW
through your preferred method, e.g.
R> with(WoW, chartSeries(ARG))
Data:
SiP=c('AES','GAS','AEE','AEP','CNP', 'CMS','ED','D',
'DTE','DUK','EIX', 'ETR','EXC','FE','TEG',
'NEE','NI', 'NU','NRG','PCG','POM','PNW','PPL',
'PEG','SCG','SRE','SO','TE','WEC', 'XEL','T',
'CTL','FTR','LVLT','VZ', 'WIN','AP','ARG',
'AA','ATI','AVY', 'BLL','CF','DOW','D',
'EMN','ECL', 'FMC','FCX','IP','IFF','LYB',
'MWV', 'MON','MOS','NEM','NUE','OI','PPG')