Search code examples
rxtsquantmod

Subset an xts by year into a list. Subset an xts by year and month into a list


im new to R and the stack platforms.

sti <- getSymbols("^STI", src = "yahoo", auto.assign = F, from = "2007-01-01", to = "2017-12-31")
sti_adjusted <- sti[, 6]

I done this in order to subset the data into a list of years.

ls_sti_adjusted <- list(sti_adjusted["2007"], sti_adjusted["2008"], sti_adjusted["2009"], sti_adjusted["2010"], sti_adjusted["2011"], sti_adjusted["2012"], sti_adjusted["2013"], sti_adjusted["2014"], sti_adjusted["2015"], sti_adjusted["2016"], sti_adjusted["2017"])

I'm looking for a more elegant solution, like a for-loop maybe?

ls_sti_adjusted <- list()
for (i in 2007:2017){
ls_sti_adjusted[[]] <- ???
}

The second issue is how can I further subset the elements into months in the year?

so for example: ls_sti_adjusted[[1]][[2]][[3]] returns the 3rd data point of February in 2007. Is this possible?

I hope that I am clear about the problem that I am facing. Thanks folks, plus any tips/tricks to understand loops and lists better would be greatly appreciated.


Solution

  • Combining .indexyear and split(x,f = “months” will give you the desired list.

    lapply(unique(.indexyear(STI)),function(x) split.xts(STI[.indexyear(STI) == x ,],f='months’))
    

    If you only need yearly lists leave out the split part, like so:

    lapply(unique(.indexyear(STI)),function(x) STI[.indexyear(STI) == x ,])
    

    UPDATE: OP’s follow-up question regarding naming of lists

    Assuming you named the list of lists object STIlist you can do the following to name the list by years.( keep in mind that the names are converted to strings! )

    names(STIlist) <- 2007:2018
    

    To get the list of the year 2007:

    > both(STIlist[['2007']])
               STI.Open STI.High STI.Low STI.Close STI.Volume STI.Adjusted
    2007-01-03  3015.74  3037.74 3010.22   3037.74  192739200      3037.74
    2007-01-04  3035.08  3045.18 3008.23   3023.80  198216700      3023.80
    2007-01-05  3031.09  3038.27 3000.50   3029.04  233321400      3029.04
               STI.Open STI.High STI.Low STI.Close STI.Volume STI.Adjusted
    2007-12-27  3469.11  3491.65 3459.97   3477.20   91474200      3477.20
    2007-12-28  3452.18  3463.38 3441.96   3445.82  109442100      3445.82
    2007-12-31  3424.48  3482.30 3424.48   3482.30  205741900      3482.30
    

    If you need need more information about naming lists "Google is your best friend” or post another question :-)