如何将日期作为行名提供给来自 quantmod::getSymbols 的数据框?

How can I give dates as rownames to a data frame from quantmod::getSymbols?

如何将 getSymbols 的输出转换为将日期作为行名?到目前为止,这是我的代码。

library("quantmod")
library("coindeskr")
getSymbols("AAPL")
> [1] "AAPL"
row.names(head(Cl(AAPL)))
> NULL
btc <- get_historic_price(start = "2017-01-01")
row.names(head(btc))
> [1] "2017-01-01" "2017-01-02" "2017-01-03" "2017-01-04" "2017-01-05" "2017-01-06"

quantmod 中的股票价格值实际上既不是 data.frames 也不是矩阵,尽管它们是由具有矩阵结构的组件构建的并且它们有点类似于 zoo-objects:

str(AAPL)
#---------
An ‘xts’ object on 2007-01-03/2018-05-01 containing:
  Data: num [1:2852, 1:6] 12.3 12 12.3 12.3 12.3 ...
 - attr(*, "dimnames")=List of 2
  ..$ : NULL
  ..$ : chr [1:6] "AAPL.Open" "AAPL.High" "AAPL.Low" "AAPL.Close" ...
  Indexed by objects of class: [Date] TZ: UTC
  xts Attributes:  
List of 2
 $ src    : chr "yahoo"
 $ updated: POSIXct[1:1], format: "2018-05-02 16:49:23"

所以 AAPL 对象有一个名为 "Data" 的数字矩阵和一个单独的索引 class 日期:

> str( index(AAPL) )
 Date[1:2852], format: "2007-01-03" "2007-01-04" "2007-01-05" "2007-01-08" "2007-01-09" "2007-01-10" "2007-01-11" "2007-01-12" ...
> str( coredata(AAPL) )
 num [1:2852, 1:6] 12.3 12 12.3 12.3 12.3 ...
 - attr(*, "dimnames")=List of 2
  ..$ : NULL
  ..$ : chr [1:6] "AAPL.Open" "AAPL.High" "AAPL.Low" "AAPL.Close" ...

您需要学习干净地访问它们所需的结构和特殊函数。看:

 ?xts
 ?xtsAttributes

我怀疑您可能想尝试对数据框对象进行强制转换:

str( as.data.frame(AAPL) )
#--------
'data.frame':   2852 obs. of  6 variables:
 $ AAPL.Open    : num  12.3 12 12.3 12.3 12.3 ...
 $ AAPL.High    : num  12.4 12.3 12.3 12.4 13.3 ...
 $ AAPL.Low     : num  11.7 12 12.1 12.2 12.2 ...
 $ AAPL.Close   : num  12 12.2 12.2 12.2 13.2 ...
 $ AAPL.Volume  : num  309579900 211815100 208685400 199276700 837324600 ...
 $ AAPL.Adjusted: num  8.1 8.28 8.23 8.27 8.95 ...

row.names( as.data.frame(AAPL) )[:16]
#---------
   [1] "2007-01-03" "2007-01-04" "2007-01-05" "2007-01-08" "2007-01-09" "2007-01-10" "2007-01-11" "2007-01-12"
   [9] "2007-01-16" "2007-01-17" "2007-01-18" "2007-01-19" "2007-01-22" "2007-01-23" "2007-01-24" "2007-01-25"

anomalize 的创建者有另一个您可能会觉得有用的包。它被称为 tidyquant 并且非常适合您想要做的事情。

library(anomalize)
library(tidyquant)
library(tidyverse)   
获取财务数据的整洁方式
aapl <- tq_get("AAPL")
参考您的最终目标,我们可以绘制 AAPL 自 2008 年以来的异常情况。
aapl %>% 
 time_decompose(adjusted) %>%
 anomalize(remainder) %>%
 time_recompose() %>%
 plot_anomalies(time_recomposed = TRUE, ncol = 3, alpha_dots = 0.5)