以下是一些意见/建议:
“我有一个包含多个变量的 XTS 对象,我想为每个变量添加自定义属性。”
xts 对象没有“多个变量”。 xts 对象与数据矩阵(通常为数字或字符类型)和时间向量(日期或 POSIXct 类型)基本一致。
“我希望 XTS 对象(或对象列表)中的每个变量对这些属性都有单独的值。我相信不能将 xtsAttributes 分配给 xts 查询”
这对我来说不太有意义,但我推测您可能意味着您想要不同列名的不同属性。如果是这种情况,您可以使列表的名称反映 xts 对象中的列名称。例如
xtsAttributes(a)<-list(Open = "a", Close = list(1:10, rep("A", 3)), Volume = "NYSE")
使用xtsAttributes(a)$Open等访问属性值
xtsAttributes 只是将元数据附加到 xts 对象的一种方式,如果您执行子集(根据时间)xts 对象之类的操作,它不会消失。使用您的示例:
> str(a)
An ‘xts’ object on 2015-01-01/2018-01-01 containing:
Data: int [1:2, 1:2] 1 2 3 4
Indexed by objects of class: [Date] TZ: UTC
xts Attributes:
List of 1
$ myattr: chr "foo"
> b <- a["2015"]
> str(b)
An ‘xts’ object on 2015-01-01/2015-01-01 containing:
Data: int [1, 1:2] 1 3
Indexed by objects of class: [Date] TZ: UTC
xts Attributes:
List of 1
$ myattr: chr "foo"
b 仍然包含元数据foo。
如果您想对元数据进行时间索引,请为此创建一个单独的 xts 对象:
> xx <-xts(matrix(c("Annoucement1", "Announcement2")), as.Date(c("2015-01-01","2018-01-01")))
> xx
[,1]
2015-01-01 "Annoucement1"
2018-01-01 "Announcement2"
# Return all announcements up to 2016
> xx["/2016"]
[,1]
2015-01-01 "Annoucement1"
a) 和 b) 如果不是 xtsAttributes 中的“永恒”元数据,则可能可以通过其他方式更好地解决它们。也许 data.frame 项目列表(其中每个列表项目对应于特定符号)会更好。
c) 听起来有点像(代码的)过早优化...只有在您确定您心目中的扩展类有重复用例时才这样做。
就个人而言,我从未发现需要 xtsAttributes。将此财务数据用例视为解决问题的一种方法:将财务数据的相关数据存储在股票上,或将金融工具存储在另一个相关对象中。例如,R quantstrat 库使用与 xts 对象中股票的时间序列财务数据相关联的 stock 对象(来自 FinancialInstrument 包)。有关更多信息,请参阅 quantstrat 演示。在这种情况下,财务数据(xts 对象)和元数据(在“股票对象”中)之间的“映射”/“键”是股票的名称。
例如:
library(quantmod)
library(FinancialInstrument)
> getSymbols("AAPL")
> head(AAPL)
AAPL.Open AAPL.High AAPL.Low AAPL.Close AAPL.Volume AAPL.Adjusted
2007-01-03 95.539 95.860 90.679 83.80000 309579900 10.81246
2007-01-04 93.059 95.163 92.804 85.66000 211815100 11.05245
2007-01-05 94.964 95.440 93.447 85.04999 208685400 10.97374
2007-01-08 95.174 95.805 94.421 85.47000 199276700 11.02793
2007-01-09 95.716 102.946 94.277 92.57000 837324600 11.94403
2007-01-10 104.906 108.283 103.467 97.00000 738220000 12.51562
currency("USD")
[1] "USD"
# You could add meta data here:
> stock("AAPL", currency = "USD", tick_size = 0.01, identifiers = list("foo" = 1233, "blah" = "text"))
[1] "AAPL"
# Want to get meta data for the `AAPL` xts object
> getInstrument("AAPL")
primary_id :"AAPL"
currency :"USD"
multiplier :1
tick_size :0.01
identifiers:List of 2
..$ foo :1233
..$ blah:"text"
type :"stock"