tjbrooks
tjbrooks

Reputation: 91

Get frequency for TS from and XTS for X12

I'm trying to automate some seasonal adjustment with the x12 package. To do this I need a ts object. However, I do not need a simple ts object, but one whose start date and frequency has been set. For any given series I could type that, but I will be feeding a mix of monthly or weekly data in. I can get the data from a quantmod as an xta object, but can't seem to figure out how to extract the frequency from the xts. Here is some sample code that works the the whole way through, but I would like to pull the frequency info from the xts, rather than explicitly set it:

getSymbols("WILACR3URN",src="FRED", from="2000-01-01") # get data as an XTS
lax <- WILACR3URN #shorten name
laxts <- ts(lax$WILACR3URN, start=c(2000,1), frequency=12) #explicitly it works
plot.ts(laxts)
x12out <- x12(laxts,x12path="c:\\x12arima\\x12a.exe",transform="auto", automdl=TRUE)
laxadj  <- as.ts(x12out$d11) # extract seasonally adjusted series

Any suggestions? Or is it not possible and I should determine/feed the frequency explicitly?

Thanks

Upvotes: 3

Views: 1488

Answers (2)

Aran
Aran

Reputation: 145

The xts::periodicity suggestion was helpful to me. I've also found the following approach using xts::convertIndex works well for monthly and quarterly data. It is untested for weekly data.

require("quantmod")
require("dplyr")
getSymbols("WILACR3URN",src="FRED", from="2000-01-01") # get data as an XTS
lax <- WILACR3URN #shorten name
laxts <- lax %>%
  convertIndex("yearmon") %>% # change index of xts object
  as.ts(start = start(.), end = end(.)) # convert to ts
plot.ts(laxts)

Upvotes: 0

Joshua Ulrich
Joshua Ulrich

Reputation: 176648

This is untested for this specific case, but try using xts::periodicity for the frequency:

freq <- switch(periodicity(lax)$scale,
  daily=365,
  weekly=52,
  monthly=12,
  quarterly=4,
  yearly=1)

And use the year and mon elements of POSIXlt objects to calculate the start year and month.

pltStart <- as.POSIXlt(start(lax))
Start <- c(pltStart$year+1900,pltStart$mon+1)
laxts <- ts(lax$WILACR3URN, start=Start, frequency=freq)
plot.ts(laxts)

Upvotes: 4

Related Questions