Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
568 views
in Technique[技术] by (71.8m points)

r - quantmod omitting tickers in getSymbols

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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))

enter image description here


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') 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...