【问题标题】:na.omit returns a empty objectna.omit 返回一个空对象
【发布时间】:2013-05-07 23:52:46
【问题描述】:

我正在尝试检索 SP500 中 50000 只股票过去 1 年的收盘价。 SP500 文件来自这里http://blog.quanttrader.org/2011/03/downloading-sp-500-data-to-r/sp500/

我在两个日期之间初始化了一个动物园对象,增量为 1 天。将其与股票收盘价合并时,最终的“z”在某些日期(周末、节假日)给出一个带有 na 的对象。因此,我尝试使用 na.omit 删除 na,它只是返回一个空对象。但是,当股票数量小于 100 时,na.omit 有效。为什么会这样?

library(quantmod);
library(PerformanceAnalytics);
#Get SP500 stocks
symbols <- read.csv("~/Dropbox/R works/sp500.csv",header=F,stringsAsFactors=F)
nrStocks <- length(symbols[,1])
#Past 1 yr returns
to <- Sys.Date()-1
from <-seq(to, length=2, by="-1 year")[2]
dates<- seq(from=from,to=to,by="1 day")
z <- zoo(,dates)

for (i in 1:nrStocks) {
  cat("Downloading ", i, " out of ", nrStocks , "\n")
  x <- try(Cl(getSymbols(symbols[i,],from = from, to = to, auto.assign=FALSE)))
  if (!inherits(x, "try-error") ){
    z<-merge(x,z)
  }
}
z<-na.omit(z)

【问题讨论】:

  • 我认为没有任何行没有至少一个 NA...

标签: r quantmod


【解决方案1】:

为我工作。另请注意,getSymbols 默认返回一个 xts 对象(不是 zoo 对象);并且由于您使用x 作为第一个参数调用merge,因此调度了merge.xts,这意味着z 将是一个xts 对象。

> library(quantmod)
> symbols <- c("IBM","MSFT","AAPL","GE")
> nrStocks <- length(symbols)
> to <- Sys.Date()-1
> from <- seq(to, length=2, by="-1 year")[2]
> dates<- seq(from=from,to=to,by="1 day")
> z <- zoo(,dates)
> 
> for (i in 1:nrStocks) {
+   cat("Downloading ", i, " out of ", nrStocks , "\n")
+   x <- try(Cl(getSymbols(symbols[i],from = from, to = to, auto.assign=FALSE)))
+   if (!inherits(x, "try-error") ){
+     z<-merge(x,z)
+   }
+ }
Downloading  1  out of  4 
Downloading  2  out of  4 
Downloading  3  out of  4 
Downloading  4  out of  4 
> z<-na.omit(z)
> head(z)
           GE.Close AAPL.Close MSFT.Close IBM.Close
2012-05-07    19.32     569.48      30.65    203.75
2012-05-08    19.25     568.18      30.50    201.48
2012-05-09    18.91     569.18      30.76    201.23
2012-05-10    19.09     570.52      30.74    200.60
2012-05-11    19.01     566.71      31.16    201.17
2012-05-14    18.60     558.22      30.68    199.44
> sessionInfo()
R version 2.15.2 (2012-10-26)
Platform: i386-w64-mingw32/i386 (32-bit)

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252   
[3] LC_MONETARY=English_United States.1252 LC_NUMERIC=C                          
[5] LC_TIME=English_United States.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] quantmod_0.4-0 Defaults_1.1-1 TTR_0.22-0     xts_0.9-3      zoo_1.7-10    

loaded via a namespace (and not attached):
[1] grid_2.15.2     lattice_0.20-10 tools_2.15.2 

【讨论】:

    猜你喜欢
    • 2021-03-31
    • 2014-07-15
    • 2018-08-25
    • 2020-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-24
    相关资源
    最近更新 更多