关于如何获取 xts 中下一个/上一个元素的基本问题
获取 xts 对象中当前日期特定交易品种的收盘价
closePrice<-as.double(Cl(get(symbol))[currentDate])
我有一个非常基本的问题...假设我可以使用How can I get close Price on the transaction day one day,两天,三天,... ,或者之前/之后n天?
closePriceNDaysBefore<-as.double(Cl(get(symbol))[currentDate - n])
不行...
提前致谢。
亲切的问候, 萨摩。
I have a very basic question... Suppose I can get a closing price for specific symbol for current date in an xts object using
closePrice<-as.double(Cl(get(symbol))[currentDate])
How can I get close price on the trading day one day, two days, three days, ... or n days before/after?
closePriceNDaysBefore<-as.double(Cl(get(symbol))[currentDate - n])
is not ok...
Thanks in advance.
Kind regards,
Samo.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以很容易地做到这一点,具体取决于您所说的“当前日期”的含义。
如果当前日期是最后一个条目(刚刚提取到日期数据),那么最后一个和第一个会有所帮助:
如果您需要当前日期来表示您在此特定循环/上下文中关心的日期,则 子集的 which.i=TRUE 参数将有所帮助 - 因为它采用完全相同的快速 ISO 查找,但返回匹配的位置。也就是说,它不做子集。
You can do this rather easily, depending on what you mean by 'current date'.
If current date is the last entry (just pulled up to date data), then last and first will help:
If instead you need the current date to mean something like the date you care about in this particular loop/context, the which.i=TRUE argument to the subset will help - as it employes the very same fast ISO lookup, but returns the position(s) that match. That is, it doesn't do the subset.
假设您的数据是每日数据并且仅包括交易日,请在子集化之前滞后时间序列。
如果这不起作用,请更具体地说明您的数据结构。
Assuming your data are daily and only include trading days, lag the time series before subsetting.
If that doesn't work, please be more specific about your data structure.
记住,您可以通过获取向量的尾部或头部来向任一方向移动向量,这一点很有用。在您的情况下,请在开头附加 NA,因为第一天没有“昨天”。
It is useful to remember that you can shift a vector either direction by taking its tail or head. In your case, append an NA at the start because the first day does not have a "yesterday".
使用 which() 并将日期字符串与行名匹配。然后结果是数字,可以作为数字索引处理:
感谢 J. Winchester 指出,通过顺序应用 quantmod 中的 getSymbols 和 Cl 函数生成的 xts 对象具有空或 NULL 行名,但 time() 函数可以访问该信息并用作:
which(as.character(time(M))=="2010-11-22")
Use which() and match your date string to rownames. Then the result is numeric and can be handled as a numeric index:
Thanks to J. Winchester for pointing out that xts objects produced by the sequential application of getSymbols and Cl functions from quantmod have empty or NULL rownames but that the time() function can access that information and be used as:
which(as.character(time(M))=="2010-11-22")