我有一个非常基本的问题......假设我可以使用 xts 对象中当前日期的特定交易品种的收盘价
closePrice<-as.double(Cl(get(symbol))[currentDate])
如何获得前一天、两天、三天、……或 n 天前/后交易日的收盘价?
closePriceNDaysBefore<-as.double(Cl(get(symbol))[currentDate - n])
不行……
提前致谢。
亲切的问候,萨摩。
你可以很容易地做到这一点,这取决于你所说的“当前日期”。
如果当前日期是最后一个条目(刚刚提取到最新数据),那么 last 和 first 会有所帮助:
> x <- xts(1:10, Sys.Date()-0:9)
> x <- xts(1:10, Sys.Date()-0:9)
> x
[,1]
2011-02-16 10
2011-02-17 9
2011-02-18 8
2011-02-19 7
2011-02-20 6
2011-02-21 5
2011-02-22 4
2011-02-23 3
2011-02-24 2
2011-02-25 1
# gets the last 3 periods (days here)
> last(x,3) # or last(x, "3 days")
[,1]
2011-02-23 3
2011-02-24 2
2011-02-25 1
# this would get you the 3rd day back from the end
> first(last(x,3),1)
[,1]
2011-02-23 3
相反,如果您需要当前日期来表示您在此特定循环/上下文中关心的日期,则该子集的which.i=TRUE参数将有所帮助 - 因为它使用相同的快速 ISO 查找,但返回位置(s) 匹配。也就是说,它不做子集。
> x[x["2011-02-25", which.i=TRUE] - 0] # today
[,1]
2011-02-25 1
> x[x["2011-02-25", which.i=TRUE] - 1] # yesterday
[,1]
2011-02-24 2
> x[x["2011-02-25", which.i=TRUE] - 2] # 2 days ago...
[,1]
2011-02-23 3
> x[x["2011-02-25", which.i=TRUE] - 3] # you get the idea ;-)
[,1]
2011-02-22 4
> x["2011-02-25", which.i=TRUE]
[1] 10
假设您的数据是每日数据且仅包括交易日,则在子集之前滞后时间序列。
closePriceNDaysBefore <- as.double(lag(Cl(get(symbol)),n)[currentDate])
如果这不起作用,请更具体地说明您的数据结构。
使用 which() 并将您的日期字符串与行名匹配。那么结果是数字的,可以作为数字索引处理:
M <- as.xts(read.table(textConnection(" SPY.Close mavg dn.1 up.1
2010-11-18 119.96 120.713 118.17955 119.99845
2010-11-19 120.29 120.470 118.33112 120.09688
2010-11-22 120.19 120.240 118.47911 120.18489
2010-11-23 118.45 119.924 118.55112 120.20888
2010-11-24 120.20 119.734 118.63565 120.27635
") ) )
> M[which(rownames(M)=="2010-11-22"), "SPY.Close"]
[1] 120.19
> M[which(rownames(M)=="2010-11-22")-1, "SPY.Close"]
[1] 120.29
感谢 J. Winchester 指出由 quantmod 的 getSymbols 和 Cl 函数的顺序应用产生的 xts 对象具有空或 NULL 行名,但 time() 函数可以访问该信息并用作:
which(as.character(time(M))=="2010-11-22")
请记住,您可以通过取其尾部或头部来向任一方向移动矢量,这一点很有用。在您的情况下,请在开始时附加一个 NA,因为第一天没有“昨天”。
M$Prev.Close <- c(NA, head(M$SPY.Close, -1))