[R-SIG-Finance] problem subsetting xts object with yearmon time index
Eric Zivot
ezivot at u.washington.edu
Fri Mar 20 18:08:57 CET 2015
I seem to have a problem sub-setting an xts object with a yearmon time index. I have a xts object holding monthly returns where the time index is a yearmon object. When I subset the data for 2014 using “2014” within the xts object I don’t get the data for January. However, if I subset the data using window() I get all of the data for 2014. Below is the example (from Rstudio on windows 8) and output. Why is January missing when I subset using mydata.xts["2014"]????
> options(digits=3, width=70)
> # IntroCompFinR available from R-forge
> # install.packages("IntroCompFinR", repos="http://R-Forge.R-project.org")
> library(IntroCompFinR)
> library(PerformanceAnalytics)
>
> #
> # load data and compute returns - MSFT
> #
>
> data(msftMonthlyPrices)
> msftRetC = na.omit(Return.calculate(msftMonthlyPrices,
+ method="log"))
> head(msftRetC, n=3)
MSFT
Feb 1993 -0.0371
Mar 1993 0.1075
Apr 1993 -0.0809
> tail(msftRetC, n=3)
MSFT
Oct 2014 0.0128
Nov 2014 0.0243
Dec 2014 -0.0289
> class(index(msftRetC))
[1] "yearmon"
> # restric returns to last year
> msftRetC2014 = msftRetC["2014"]
> msftRetC2014
MSFT
Feb 2014 0.0198
Mar 2014 0.0676
Apr 2014 -0.0144
May 2014 0.0204
Jun 2014 0.0183
Jul 2014 0.0344
Aug 2014 0.0576
Sep 2014 0.0201
Oct 2014 0.0128
Nov 2014 0.0243
Dec 2014 -0.0289
> # why is January missing?????
> as.Date(index(msftRetC2014))
[1] "2014-02-01" "2014-03-01" "2014-04-01" "2014-05-01" "2014-06-01"
[6] "2014-07-01" "2014-08-01" "2014-09-01" "2014-10-01" "2014-11-01"
[11] "2014-12-01"
> # I get the right data using window()
> window(msftRetC, start=as.yearmon("Jan 2014"), end=as.yearmon("Dec 2014"))
MSFT
Jan 2014 0.0113
Feb 2014 0.0198
Mar 2014 0.0676
Apr 2014 -0.0144
May 2014 0.0204
Jun 2014 0.0183
Jul 2014 0.0344
Aug 2014 0.0576
Sep 2014 0.0201
Oct 2014 0.0128
Nov 2014 0.0243
Dec 2014 -0.0289
> sessionInfo()
R version 3.1.2 (2014-10-31)
Platform: x86_64-w64-mingw32/x64 (64-bit)
locale:
[1] LC_COLLATE=English_United States.1252
[2] LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C
[5] LC_TIME=English_United States.1252
attached base packages:
[1] stats graphics grDevices utils datasets methods
[7] base
other attached packages:
[1] boot_1.3-13 PerformanceAnalytics_1.4.3541
[3] IntroCompFinR_1.0 xts_0.9-7
[5] zoo_1.7-11
loaded via a namespace (and not attached):
[1] digest_0.6.8 grid_3.1.2 htmltools_0.2.6 lattice_0.20-29
[5] rmarkdown_0.5.1 tools_3.1.2 yaml_2.1.13
Thanks in advance for any insight.
More information about the R-SIG-Finance
mailing list