循环将xts转换为数据帧

时间:2018-12-29 19:44:40

标签: r quantmod

我正在使用Quantmod软件包获取历史股价。

我想创建一个回撤价格的循环,作为循环的一部分,我想为每个份额创建一个数据框。到目前为止,我使用下面的代码未能成功,它可以按预期方式获得股价,但是将其作为xts对象返回,而我需要将信息作为数据框-代码的as.data.frame部分不执行任何操作...

library(quantmod)
shares<-c("BARC.L", "BP.L", "DLG.L")

for(i in 1:length(shares)){

#gets share prices
getSymbols((paste(shares[i])), from = "2018-01-01")

#put the data into a dataframe (doesn't work).
shares[i]<-as.data.frame(shares[i])
}

我想要的最终结果是3个数据帧-每个共享1个。

有人可以建议对代码进行修改以实现此目标吗?

2 个答案:

答案 0 :(得分:2)

我个人会这样:

library(quantmod)
shares<-c("BARC.L", "BP.L", "DLG.L")

my_shares <- lapply(shares, function(x) getSymbols(x, from = "2018-01-01", auto.assign = FALSE))
names(my_shares) <- shares

或者如果您需要日期作为列而不是行名:

my_shares <- lapply(shares, function(x) {
   out <- getSymbols(x, from = "2018-01-01", auto.assign = FALSE)
   out <- data.frame(dates = index(out), coredata(out))
   return(out)
  })

names(my_shares) <- shares

或者如果您需要整洁的数据集中的所有内容:

library(tidyquant)
my_shares <- tq_get(shares)
my_shares

# A tibble: 7,130 x 8
   symbol date        open  high   low close    volume adjusted
   <chr>  <date>     <dbl> <dbl> <dbl> <dbl>     <dbl>    <dbl>
 1 BARC.L 2008-01-02  464.  483.  460.  466.  38104837     344.
 2 BARC.L 2008-01-03  466.  472.  458.  470.  33215781     347.
 3 BARC.L 2008-01-04  466.  476.  447.  449.  42710244     332.
 4 BARC.L 2008-01-07  447.  452.  433.  436.  58213512     322.
 5 BARC.L 2008-01-08  439.  447.  421.  437. 105370539     322.
 6 BARC.L 2008-01-09  432.  434.  420.  424.  71059078     313.
 7 BARC.L 2008-01-10  428.  431.  413.  418.  54763347     309.
 8 BARC.L 2008-01-11  416.  437.  416.  430.  72467229     317.
 9 BARC.L 2008-01-14  430.  448.  427.  444.  56916500     328.
10 BARC.L 2008-01-15  445.  452.  428.  429.  77094907     317.
# ... with 7,120 more rows

答案 1 :(得分:1)

首先,我建议您使用R软件包随附的help()函数(如果尚未这样做)。我在help(getSymbols)中注意到,您需要设置env = NULL才能实际返回数据。这样,我还制作了一个列表对象,因此您可以按照要求将数据存储为data.frames:

library(quantmod)
shares<-c("BARC.L", "BP.L", "DLG.L")

# initialize a list to store your data frames
df_list <- as.list(rep(data.frame(), length(shares))) 

for (i in 1:length(shares)) {
    #gets share prices
    df_list[[i]] <- as.data.frame(getSymbols(shares[i], from = "2018-01-01", env=NULL))
}

# so you can access by name, e.g. df_list$DLG.L
names(df_list) <- shares 
相关问题