循环将 xts 转换为数据帧

Loop to transform xts into dataframe

我正在使用包 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 个。

任何人都可以建议修改代码以实现此目的吗?

首先,我建议您使用 R 包附带的 help() 函数(如果您还没有这样做的话)。我在 help(getSymbols) 中注意到您需要将 env=NULL 设置为实际 return 数据。有了它,我还制作了一个列表对象,这样您就可以按照您的要求将数据存储为 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 

我个人会这样做:

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