na.omit返回一个空对象

时间:2013-05-07 15:05:21

标签: r quantmod

我试图回收SP500中500只股票的过去1年收盘价。 SP500文件来自此处http://blog.quanttrader.org/2011/03/downloading-sp-500-data-to-r/sp500/

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

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)

1 个答案:

答案 0 :(得分:1)

适合我。另请注意,getSymbols默认返回xts对象(不是动物园对象);由于您使用merge作为第一个参数调用x,因此会调度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