将etf价格数据加载到R中的矩阵中

时间:2015-02-01 02:25:23

标签: r matrix

我是一名新的R程序员,我正试图在白天创建一个ETF价格矩阵。这是我正在使用的代码:

#Download Packages
library(tseries)
library(quantmod)
#Setup list of symbols to download prices
pr=c("vti","vv","vug","vtv","vo")     
#get dates to download data
today=as.Date(Sys.Date())
yday=today-1
#set up matrix to hold data
pri=matrix(nrow=10,ncol=5)
for(i in 1:10){
for(j in 1:5) {
  pri[i,j]=get.hist.quote(instrument=pr[j],start=yday,quote="AdjClose",provider="yahoo",compression="d")
}
yday=yday-1}
  write(pri,"ETFData13115.ods",ncolumns=5,nrows=10,append=TRUE,sep="\t")

以下是我收到的输出和错误消息:

Error in pri[i, j] = get.hist.quote(instrument = pr[j], start = yday,  : 
  number of items to replace is not a multiple of replacement length
>   write(pri,"ETFData13115.ods",ncolumns=5,nrows=10,append=TRUE,sep="\t")
Error in write(pri, "ETFData13115.ods", ncolumns = 5, nrows = 10, append = TRUE,  : 
  unused argument (nrows = 10)
> print(pri)
       [,1] [,2]  [,3]  [,4]   [,5]
 [1,] 103.1 91.6 102.8 81.03 121.08
 [2,]    NA   NA    NA    NA     NA
 [3,]    NA   NA    NA    NA     NA
 [4,]    NA   NA    NA    NA     NA
 [5,]    NA   NA    NA    NA     NA
 [6,]    NA   NA    NA    NA     NA
 [7,]    NA   NA    NA    NA     NA
 [8,]    NA   NA    NA    NA     NA
 [9,]    NA   NA    NA    NA     NA
[10,]    NA   NA    NA    NA     NA

我做错了什么? 有没有更简单的方法来组装我的矩阵?

感谢您的帮助。 罗伯特S

2 个答案:

答案 0 :(得分:0)

您需要使用赋值运算符:

pri[i,j] <- get.hist.quote(...)

更新:

尝试时

a <- get.hist.quote( instrument=pr[j], start=yday,quote="AdjClose",provider="yahoo",compression="d" )

我们可以看到a不是标量:

> dim(a)
[1] 2 1

> a[1,1]
2015-01-29 
    104.52 
> a[2,1]
2015-01-30 
     103.1

因此,您可能需要选择所需的数据或重新设计矩阵以适应这两种数据。

答案 1 :(得分:0)

更新了实际解决方案。

Quantmod已经为你做了很多你在这里做的事情。您主要只需要getSymbols命令。

    #Download Packages
library(tseries)
library(quantmod)

#Your code is commented out line by line

#Setup list of symbols to download prices
    #pr=c("vti","vv","vug","vtv","vo")  

pr <- c("vti", "vv", "vug", "vtv", "vo")  #spaces are your friend

#you do not need to worry about which dates to select... explained in a second 
#get dates to download data
    #today=as.Date(Sys.Date())
    #yday=today-1
#set up matrix to hold data

#you do not need to do this, quantmod does it for you
    #pri=matrix(nrow=10,ncol=5)


#you definitely dont need the uter loop loop!
#for(i in 1:10){
#for(j in 1:5) {
  #get.hist.quote(instrument=pr[j],start=yday,quote="AdjClose",provider="yahoo",#compression="d")
#}

#this command gets all the data you want and assigns them to a data frame with ticker symbol
getSymbols(pr)

print(VTI[1:2]) #print the last 2 trading days of VTI, note this works even if yesterday was a weekend!!!!!!!


#write data to individuals csv files 
#for(j in 1:5) {

write.csv(
    get(toupper(pr[i])), paste(pr[i],"historical-quotes.csv", sep='-'))

}
  write(pri,"ETFData13115.ods",ncolumns=5,nrows=10,append=TRUE,sep="\t")

yday = today-1财务数据的使用情况不佳,因为并非所有天数都是交易日。您应该考虑创建一个可接受交易日的向量,然后从该向量中进行选择。