quantmod 省略了 getSymbols 中的代码 [英] quantmod omitting tickers in getSymbols

查看:35
本文介绍了quantmod 省略了 getSymbols 中的代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 R 的完全初学者.我想使用 getSymbols 下载 S&P500 中当前公司的历史数据.显然,某些公司在特定时期内并不存在,R 停止下载下一个代码的数据.如果数据不存在,有什么方法可以让 getSymbols 简单地省略股票代码?获得那个时期的标准普尔 500 指数会容易得多,但不幸的是它不是免费的.

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.

推荐答案

您可以像这样在 sapply 中使用 try :

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

所以看起来其中 2 只股票存在问题,因为 sapply(...) 成功返回了另外 57 只股票的数据.

So it looks like there were issues with 2 of the stocks, as sapply(...) successfully returned data for the other 57.

从这里开始,可以通过您喜欢的方法在 WoW 中访问对象,例如

From here, objects can be accessed within WoW through your preferred method, e.g.

R> with(WoW, chartSeries(ARG))

数据:

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

这篇关于quantmod 省略了 getSymbols 中的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆