Am I correctly removing trend and seasonality using X-13 in R?

Posted by HairRadiant2114@reddit | learnprogramming | View on Reddit | 2 comments

Hi, I’m working with quarterly macroeconomic data and trying to remove both trend and seasonality using X-13 in R.

Here is my code:

rm(list = ls())

library(seasonal)

library(dplyr)

library(zoo)

dados <- read.table(

file.choose(),

header = TRUE,

sep = "\t",

dec = "."

)

dados <- dados %>% arrange(ano, tri)

n <- nrow(dados)

vars <- c(

"ibc", "ipca", "inpc", "selic", "desocupacao",

"remuneracao_real", "cambio_real",

"commodities_real", "rndb",

"otimo_bom", "regular", "ruim_pessimo"

)

x13_ciclo_safe <- function(x, nome) {

if (any(is.na(x))) {

x <- na.approx(x, na.rm = FALSE)

}

ts_data <- ts(

x,

start = c(dados$ano[1], dados$tri[1]),

frequency = 4

)

ajuste <- try(

seas(ts_data),

silent = TRUE

)

if (inherits(ajuste, "try-error")) {

return(rep(NA, n))

}

dessaz <- final(ajuste)

trend <- trend(ajuste)

ciclo <- dessaz - trend

return(as.numeric(ciclo))

}

base_final <- dados[, c("ano", "tri")]

for (v in vars) {

base_final[[paste(v, "ciclo", sep = "_")]] <-

x13_ciclo_safe(dados[[v]], v)

}

write.csv2(base_final, "base_ciclo_x13.csv", row.names = FALSE)

My understanding is:

- final() removes seasonality

- trend() extracts the trend

so ciclo = final - trend should give me the irregular (cycle) component

My question:

Is this the correct way to remove both trend and seasonality using X-13?

Any feedback on methodology would be really appreciated.