0

我正在尝试检索 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)
4

1 回答 1

1

为我工作。另请注意,getSymbols默认情况下返回 xts 对象(不是 zoo 对象);并且由于您将mergewithx作为第一个参数调用,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 
于 2013-05-07T15:52:46.310 回答