Set the first month of each quarter as the index after applying apply.quarterly()

StackOverflow https://stackoverflow.com/questions/19352828

  •  30-06-2022
  •  | 
  •  

Question

apply.quarterly() only gives the end month of each quarter as the index, see the following example:

library(quantmod)
getSymbols.FRED("CPILFESL")
apply.quarterly(CPILFESL,mean)

        CPILFESL
1957-03-01  28.60000
1957-06-01  28.83333
1957-09-01  29.03333
1957-12-01  29.26667
1958-03-01  29.40000
1958-06-01  29.53333
...

What I really want is:

        CPILFESL
1957-01-01  28.60000
1957-04-01  28.83333
1957-07-01  29.03333
1957-10-01  29.26667
1958-01-01  29.40000
1958-04-01  29.53333
...

So how can I set the first month of each quarter as the index after applying apply.quarterly()?

Thanks

Was it helpful?

Solution

If x is the result of apply.quarterly then:

time(x) <- as.Date(as.yearqtr(time(x)))

as.yearqtr comes from the zoo package which the quantmod package depends on so it should be loaded already.

OTHER TIPS

I have had a bunch of these problems -- typically they have arisen when i'm merging data from a number of sources, and the easiest thing is to change the output in an R aggregate step.

To do this i have a bunch of helper functions. Here's a simple function that changes the months for you.

library(quantmod)
getSymbols("CPILFESL", src = 'FRED')
qd <- apply.quarterly(CPILFESL,mean)

monthSwitch <- function(index, monChng) {
    index_LT <- as.POSIXlt(index)
    index_LT$mon <- index_LT$mon + monChng
    as.Date(index_LT)
}

index(qd) <- monthSwitch(index(qd), -2)

The basic intuition is this: change to POSIXlt, edit the month value directly, and then change back to a simple integer date using as.Date.

One can also edit the xts index vector itself!

library(xts)
library(lubridate)
test_daily <- xts(1:365, Sys.Date()+1:365)
test_monthly <- apply.monthly(test_daily,mean)
index(test_monthly) <- floor_date(index(test_monthly),"month")
test_monthly  

I'm using lubridate to convert the dates but I'm sure there are plenty of other ways to edit the index vector, as well.

Crucially for me, this works even when the xts object is a dataframe.

My reason for doing this is simply to get the axis labels on a plot to land where they intuitively belong.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top