2013-05-07 46 views
0

我試圖檢索SP500中500只股票的過去1年收盤價。從這裏SP500文件是http://blog.quanttrader.org/2011/03/downloading-sp-500-data-to-r/sp500/na.omit返回一個空對象

我初始化兩個日期之間的動物園對象,增量爲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) 
+0

我不認爲有任何行至少沒有一個「NA」... – GSee 2013-05-07 16:47:52

回答

1

適合我。另請注意,getSymbols默認返回一個xts對象(不是動物園對象);並且由於您調用mergex作爲第一個參數,因此將調度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