I have a question about indexing with xts. I understand that when I use SPY['2002-10-17/']
, I can get all of the data in my xts object from 2002-10-17 to the last date. This however is not true if I write an ifelse statement and do the same call. Below is code:
library(quantmod)
getSymbols('SPY',from='2002-01-01')
SPY=Cl(SPY) #pull only the closes
returns=(SPY-lag(SPY,1))/(lag(SPY,1)) #returns calculation
head(SPY['2002-10-17/']) #This works and starts at 2002-10-17
head(ifelse(returns>0,1,0)['2002-10-17/']) #this for some odd reason starts at 2002-10-18
Can anyone tell me why this is the case. I am truly befuddled.
As Joshua suggested here is the output from sessionInfo()
> sessionInfo()
R version 3.2.0 (2015-04-16)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1
locale:
[1] LC_COLLATE=English_United States.1252 LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252 LC_NUMERIC=C
[5] LC_TIME=English_United States.1252
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] quantmod_0.4-3 TTR_0.22-0 xts_0.9-7 zoo_1.7-12
loaded via a namespace (and not attached):
[1] tools_3.2.0 grid_3.2.0 lattice_0.20-31
I can confirm this behavior in xts_0.9-7. It's a bug that has been fixed in the development version.
The bug is in the logical operator (>
) dropping the timezone attribute on the xts object. That causes the index to be offset by however many hours your local timezone is offset from UTC. So, the logical operator is essentially changing the interpretation of the index of the object created by the logical operator.
> head((returns > 0)['2002-10-17/'])
SPY.Close
2002-10-18 TRUE
2002-10-21 TRUE
2002-10-22 FALSE
2002-10-23 TRUE
2002-10-24 FALSE
2002-10-25 TRUE
> indexTZ(returns)
[1] "UTC"
> indexTZ(returns > 0)
[1] ""