## ----include = FALSE----------------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.width = 7,
  fig.height = 4.5,
  fig.align = "center",
  message = FALSE,
  warning = FALSE
)

## ----setup--------------------------------------------------------------------
library(trendseries)
library(dplyr)
library(tidyr)
library(ggplot2)

## ----libs---------------------------------------------------------------------
# library(trendseries)
# library(dplyr)
# library(tidyr)

## ----theme--------------------------------------------------------------------
library(ggplot2)

theme_series <- theme_minimal(paper = "#fefefe") +
  theme(
    legend.position = "bottom",
    panel.grid.minor = element_blank(),
    strip.background = element_rect(fill = "#2c3e50"),
    strip.text = element_text(color = "#fefefe"),
    axis.ticks.x = element_line(color = "gray40", linewidth = 0.5),
    axis.line.x = element_line(color = "gray40", linewidth = 0.5),
    axis.title.x = element_blank(),
    palette.colour.discrete = c(
      "#2c3e50",
      "#e74c3c",
      "#f39c12",
      "#1abc9c",
      "#9b59b6"
    )
  )

## ----ibcbr-plot---------------------------------------------------------------
ggplot(ibcbr, aes(date, index)) +
  geom_line(lwd = 0.7) +
  scale_x_date(date_breaks = "2 years", date_labels = "%Y") +
  labs(
    title = "Brazilian economic activity (IBC-Br)",
    y = "Index (2003 = 100)"
  ) +
  theme_series

## ----ibcbr-detrend------------------------------------------------------------
ibcbr_cycle <- ibcbr |>
  detrend_series(value_col = "index")

ibcbr_cycle

## ----ibcbr-cycle-plot---------------------------------------------------------
ggplot(ibcbr_cycle, aes(date, detrend_hp)) +
  geom_hline(yintercept = 0, color = "gray40", lty = 2) +
  geom_line(lwd = 0.7) +
  scale_x_date(date_breaks = "2 years", date_labels = "%Y") +
  labs(
    title = "Detrended economic activity",
    subtitle = "Deviation from the HP trend",
    y = "Index points"
  ) +
  theme_series

## ----ibcbr-sa-cycle-----------------------------------------------------------
ibcbr_sa_cycle <- ibcbr |>
  deseason_series(value_col = "index") |>
  detrend_series(value_col = "seasadj_stl")

ibcbr_sa_cycle

## ----cycle-compare-data-------------------------------------------------------
cycles <- bind_rows(
  list(
    "Raw series" = ibcbr_cycle,
    "Seasonally adjusted" = ibcbr_sa_cycle
  ),
  .id = "input"
)

cycles <- cycles |>
  rename(cycle = detrend_hp)

## ----cycle-compare-plot-------------------------------------------------------
ggplot(cycles, aes(date, cycle)) +
  geom_hline(yintercept = 0, color = "gray40", lty = 2) +
  geom_line(aes(color = input), lwd = 0.7, show.legend = FALSE) +
  facet_wrap(vars(input), ncol = 1) +
  scale_x_date(date_breaks = "2 years", date_labels = "%Y") +
  labs(
    title = "Detrending before and after seasonal adjustment",
    subtitle = "HP deviations from trend",
    y = "Index points"
  ) +
  theme_series

## ----ibcbr-gap----------------------------------------------------------------
ibcbr_gap <- ibcbr |>
  deseason_series(value_col = "index") |>
  detrend_series(value_col = "seasadj_stl", transform = "log")

## ----ibcbr-gap-plot-----------------------------------------------------------
ggplot(ibcbr_gap, aes(date, detrend_hp)) +
  geom_hline(yintercept = 0, color = "gray40", lty = 2) +
  geom_line(lwd = 0.7) +
  scale_x_date(date_breaks = "2 years", date_labels = "%Y") +
  scale_y_continuous(labels = scales::percent) +
  labs(
    title = "An HP-filter activity gap",
    subtitle = "Log deviation from trend of the seasonally adjusted IBC-Br (x 100)",
    y = "% of trend"
  ) +
  theme_series

## ----methods-detrend----------------------------------------------------------
ibcbr_methods <- ibcbr |>
  deseason_series(value_col = "index") |>
  detrend_series(
    value_col = "seasadj_stl",
    methods = c("hp", "hamilton"),
    transform = "log"
  )

## ----methods-long-------------------------------------------------------------
methods_long <- ibcbr_methods |>
  pivot_longer(
    cols = starts_with("detrend_"),
    names_to = "method",
    names_prefix = "detrend_",
    values_to = "cycle"
  )

## ----methods-plot-------------------------------------------------------------
ggplot(methods_long, aes(date, 100 * cycle)) +
  geom_hline(yintercept = 0, color = "gray40", lty = 2) +
  geom_line(aes(color = method), lwd = 0.7) +
  scale_x_date(date_breaks = "2 years", date_labels = "%Y") +
  labs(
    title = "HP vs Hamilton detrending",
    subtitle = "Log deviation from trend (x 100)",
    y = "% of trend",
    color = NULL
  ) +
  theme_series

## ----bk-example---------------------------------------------------------------
# ibcbr |>
#   deseason_series(value_col = "index") |>
#   detrend_series(
#     value_col = "seasadj_stl",
#     methods = "bk",
#     band = c(18, 96) # periods in months
#   )

## ----components---------------------------------------------------------------
ibcbr_parts <- ibcbr |>
  detrend_series(value_col = "index", components = TRUE)

all.equal(ibcbr_parts$trend_hp + ibcbr_parts$detrend_hp, ibcbr_parts$index)

## ----components-plot----------------------------------------------------------
ggplot(ibcbr_parts, aes(date)) +
  geom_line(aes(y = index, color = "Observed"), lwd = 0.7, alpha = 0.5) +
  geom_line(aes(y = trend_hp, color = "Trend (HP)"), lwd = 1) +
  scale_x_date(date_breaks = "2 years", date_labels = "%Y") +
  labs(
    title = "Economic activity and its HP trend",
    y = "Index (2003 = 100)",
    color = NULL
  ) +
  theme_series

## ----elec-detrend-------------------------------------------------------------
elec_cycles <- electricity |>
  dplyr::filter(date >= as.Date("2003-01-01")) |>
  deseason_series(group_cols = "name_series") |>
  detrend_series(
    value_col = "seasadj_stl",
    group_cols = "name_series",
    transform = "log"
  )

glimpse(elec_cycles)

## ----elec-plot----------------------------------------------------------------
ggplot(elec_cycles, aes(date, detrend_hp)) +
  geom_hline(yintercept = 0, color = "gray40", lty = 2) +
  geom_line(color = "#2c3e50", lwd = 0.7) +
  facet_wrap(vars(name_series), ncol = 1) +
  scale_x_date(date_breaks = "5 years", date_labels = "%Y") +
  scale_y_continuous(labels = scales::percent) +
  labs(
    title = "Electricity consumption cycles by sector",
    subtitle = "Log deviation from HP trend of the seasonally adjusted series (x 100)",
    y = "% of trend"
  ) +
  theme_series

