【问题标题】:How to get min and max values with the date of accurance using quantmod如何使用 quantmod 获取精确日期的最小值和最大值
【发布时间】:2015-08-14 16:03:55
【问题描述】:

我想计算以 xts 格式存储的每个变量的最高价和最低价的范围和日期,并将结果存储在数据框中。我寻找的结果是一个数据框,其中将包含变量名称、最大值日期、最大值、最小值日期、最小值。 我使用 quantmod 包导入了两个股票数据,并编写了一个函数来计算范围(但没有最高价和最低价的日期),但没有成功。

d<-getSymbols(c("ZTS","ZX") , src = 'yahoo', from = '2015-01-01', auto.assign = T)
d<-cbind(ZTS,ZX)
head(d)
          ZTS.Open ZTS.High ZTS.Low ZTS.Close ZTS.Volume ZTS.Adjusted ZX.Open ZX.High ZX.Low ZX.Close
2015-01-02    43.46    43.70   43.07     43.31    1784200     43.07725    1.40    1.40   1.21     1.24
2015-01-05    43.25    43.63   42.97     43.05    3112100     42.81864    1.35    1.38   1.24     1.32
2015-01-06    43.15    43.36   42.30     42.63    3977200     42.40090    1.28    1.29   1.22     1.22
2015-01-07    43.00    43.56   42.98     43.51    2481800     43.27617    1.24    1.34   1.24     1.29
2015-01-08    44.75    44.87   44.00     44.18    3121300     43.94257    1.26    1.28   1.17     1.18
2015-01-09    44.06    44.44   43.68     44.25    2993200     44.01220    1.30    1.39   1.22     1.27
           ZX.Volume ZX.Adjusted
2015-01-02     20400        1.24
2015-01-05     43200        1.32
2015-01-06     16700        1.22
2015-01-07      6200        1.29
2015-01-08     17200        1.18
2015-01-09     60200        1.27
s<- for (i in names(d[,-1])) function(x) {max(x);min(x) }
> s
NULL

str(d)
An ‘xts’ object on 2015-01-02/2015-08-13 containing:
  Data: num [1:155, 1:12] 43.5 43.2 43.2 43 44.8 ...
 - attr(*, "dimnames")=List of 2
  ..$ : NULL
  ..$ : chr [1:12] "ZTS.Open" "ZTS.High" "ZTS.Low" "ZTS.Close" ...
  Indexed by objects of class: [Date] TZ: UTC
  xts Attributes:  
List of 2
 $ src    : chr "yahoo"
 $ updated: POSIXct[1:1], format: "2015-08-14 18:35:14"

x

【问题讨论】:

  • 什么是ClosePrices?也不清楚结果应该是什么

标签: r quantmod


【解决方案1】:

我不知道您的日期列是行名还是实际列,但如果日期列在数据框中称为 date,下面的代码应该会产生您的结果。

do.call(rbind, apply(d[,-1], 2, function(col) {
   max_ind <- which.max(col)
   min_ind <- which.min(col)
   list(max=col[max_ind], max_date=d$date[max_ind], min=col[min_ind],
       min_date=d$date[min_ind])
}))

如果日期列是行名

do.call(rbind, apply(d, 2, function(col) {
   max_ind <- which.max(col)
   min_ind <- which.min(col)
   list(max=col[max_ind], max_date=as.character(index(d))[max_ind], min=col[min_ind],
       min_date=as.character(index(d))[min_ind])
}))

代码对列进行应用以找到最大值和最小值的索引,然后返回与这些对应的值和日期。

【讨论】:

  • 感谢@mattdevlin,我尝试了两个代码 sn-ps ,第二个是我正在寻找的,但我得到的日期为 NULLS。实际上,两个代码 sn-ps 都存在max_date 和 min_date 中的 NULLS
  • 我认为这与“d”是一个 xts 对象这一事实有关。我将 str(d) 添加到问题的正文中。
  • 您需要使用index(d)。我已经更新了我的答案。如果您希望它们的类型为 Date 而不是字符,则可以将 max_date 包装在 as.Date
猜你喜欢
  • 2021-12-15
  • 1970-01-01
  • 1970-01-01
  • 2019-11-13
  • 2019-05-31
  • 1970-01-01
  • 2019-11-02
  • 2021-05-30
  • 2013-04-01
相关资源
最近更新 更多