Package 'trendseries'

Title: Extract Trends from Time Series
Description: Extract trends from monthly and quarterly economic time series. Provides two main functions: augment_trends() for pipe-friendly 'tibble' workflows and extract_trends() for direct time series analysis. Includes established econometric filters such as Hodrick-Prescott (HP), Baxter-King, Christiano-Fitzgerald, and Hamilton, alongside moving averages and smoothing methods. Smart defaults are tuned for common economic frequencies following Ravn and Uhlig (2002) <doi:10.1162/003465302317411604>.
Authors: Vinicius Oike [aut, cre, cph]
Maintainer: Vinicius Oike <[email protected]>
License: MIT + file LICENSE
Version: 1.3.0
Built: 2026-06-07 14:55:32 UTC
Source: https://github.com/viniciusoike/trendseries

Help Index


Daily Arabica Coffee Price

Description

Daily Arabica coffee price data from CEPEA/ESALQ (USP) with inflation adjustment.

Prices are provided in Brazilian reais, with USD values calculated using the daily USD/BRL exchange rate at 16:30. All reported prices include taxes and freight costs.

The data tracks prices for standard 60kg sacks of type 6 Arabica coffee negotiated in São Paulo (SP), representing production from five major regions: Cerrado, Sul de Minas Gerais, Mogiana (SP), Garça (SP), and Northeast Paraná. Regional prices are weighted by production volume to create the final value.

Usage

coffee_arabica

Format

A tibble with daily observations:

date

Date column

spot_rs

Spot price in Brazilian Reais per 60-kg bag

spot_us

Spot price in US Dollars per 60-kg bag

usd_2022

US Dollar price adjusted for inflation (base year 2022)

trend_ma

22-day moving average of inflation-adjusted prices

Source

Center for Advanced Studies in Applied Economics (CEPEA - ESALQ/USP).

See Also

coffee_robusta


Daily Robusta Coffee Price

Description

Daily Robusta coffee price data from CEPEA/ESALQ (USP) with inflation adjustment.

Prices are provided in Brazilian reais, with USD values calculated using the daily USD/BRL exchange rate at 16:30. All reported prices include taxes and freight costs.

The data tracks prices for standard 60kg sacks of type 6 Arabica coffee negotiated in São Paulo (SP), representing production from two major regions: Colatina (ES) and São Gabriel da Palha (ES). The final value is an arithmetic average of the regional prices.

Usage

coffee_robusta

Format

A tibble with daily observations:

date

Date column

spot_rs

Spot price in Brazilian Reais per 60-kg bag

spot_us

Spot price in US Dollars per 60-kg bag

usd_2022

US Dollar price adjusted for inflation (base year 2022)

trend_ma

22-day moving average of inflation-adjusted prices

Source

Center for Advanced Studies in Applied Economics (CEPEA - ESALQ/USP).

See Also

coffee_arabica


Data Format Conversion Utilities

Description

Functions for converting between different time series formats, frequency detection, and data frame manipulation for the trendseries package. These functions handle the interface between tibble/data.frame workflows and time series objects.


Decompose time series into trend, seasonal, and remainder components

Description

Pipe-friendly function that decomposes a time series into its trend, seasonal, and remainder components, adding them as columns to the input data frame. Supports STL decomposition and regression-based decomposition.

Usage

decompose_series(
  data,
  date_col = "date",
  value_col = "value",
  group_cols = NULL,
  methods = "stl",
  trend = "linear",
  transform = "none",
  frequency = NULL,
  seasadj = FALSE,
  params = list(),
  .quiet = FALSE
)

Arguments

data

A data.frame, tibble, or data.table containing the time series data.

date_col

Name of the date column. Defaults to "date". Must be of class Date.

value_col

Name of the value column. Defaults to "value". Must be numeric.

group_cols

Optional grouping variables for multiple time series. A character vector of column names. When provided, decomposition is applied independently to each group.

methods

Decomposition method(s). One or more of "stl", "regression", "classic", "bsm", or "seats". Default is "stl". When several methods are supplied (e.g. c("stl", "classic")), each one contributes its own ⁠trend_*⁠, ⁠seasonal_*⁠, and ⁠remainder_*⁠ columns so decompositions can be compared side by side.

  • "stl": Seasonal-Trend decomposition via Loess (stats::stl()).

  • "regression": joint OLS trend + seasonal-dummy model.

  • "classic": classical decomposition via moving averages (stats::decompose()).

  • "bsm": Basic Structural (state-space) Model via the Kalman smoother (stats::StructTS()).

  • "seats": X-13ARIMA-SEATS decomposition (requires the seasonal package; see Details).

trend

For methods = "regression" only: the polynomial form of the trend component. One of "linear", "quadratic", or "cubic". Ignored by the other methods. Default is "linear".

transform

Transformation applied to the series before decomposition. One of "none" (default, additive decomposition) or "log". With "log", the series is log-transformed, decomposed additively, and the components are exponentiated back, yielding a multiplicative decomposition.

frequency

The frequency of the series. Supports 4 (quarterly) or 12 (monthly). Will be auto-detected if not specified. All methods require frequency > 1.

seasadj

If TRUE, also add a ⁠seasadj_{method}⁠ column holding the seasonally adjusted series (the series with the seasonal component removed: trend + remainder for additive decompositions, trend * remainder for multiplicative ones). Default FALSE.

params

Optional list of method-specific parameters for fine control. Sensible defaults are provided for all parameters; this argument is only needed for non-standard use cases.

For STL (methods = "stl"):

  • s.window or stl_s_window: seasonal smoothing window. Either "periodic" (default, assumes constant seasonal pattern) or a positive odd integer (larger values allow more slowly evolving seasonality).

  • t.window or stl_t_window: trend smoothing window (odd integer, or NULL to let stats::stl() choose automatically — recommended default).

  • robust or stl_robust: logical. If TRUE, uses robust fitting to reduce the influence of outliers. Default FALSE.

For regression (methods = "regression"):

  • poly_raw: logical. If FALSE (default), uses orthogonal polynomials (numerically stable, recommended). If TRUE, uses raw polynomials (more interpretable coefficients, less stable for degree >= 2).

classic, bsm, and seats take no params. For multiplicative seasonality with any method, use transform = "log".

.quiet

If TRUE, suppress informational messages.

Details

All methods require seasonal data (frequency > 1). For non-seasonal (annual) series, use augment_trends() to extract a trend component only.

STL Decomposition

Uses stats::stl() (Seasonal-Trend decomposition via Loess). The seasonal component is estimated with a loess smoother, the trend with an adaptive moving average, and the remainder is the residual. Default settings (s.window = "periodic", robust = FALSE) are appropriate for most economic series with stable seasonal patterns.

Regression Decomposition

Fits a joint OLS model:

yt=f(t)+s(t)+ϵty_t = f(t) + s(t) + \epsilon_t

where f(t)f(t) is a polynomial in time and s(t)s(t) is captured by period dummy variables (month or quarter indicators). The components are isolated via stats::predict(type = "terms"):

  • Trend: constant + polynomial terms (captures the long-run level and direction).

  • Seasonal: period dummy terms, centred to mean zero over the sample.

  • Remainder: residuals from the full model.

By default, orthogonal polynomials (poly_raw = FALSE) are used for numerical stability. For trend = "cubic", this is especially recommended.

Classical Decomposition

Uses stats::decompose(). The trend is a centred moving average of order equal to the frequency; the seasonal component is the average detrended value for each period; the remainder is the residual. Simple and fast, but shouldn't be used in practice.

Basic Structural Model (BSM)

Uses stats::StructTS(type = "BSM"), a state-space model with stochastic level, slope, and seasonal components estimated by maximum likelihood and extracted with the Kalman smoother (stats::tsSmooth()). Unlike the moving-average methods it produces trend and seasonal estimates for every observation, including the endpoints, and lets both components evolve over time. Fitting relies on numerical optimisation and can occasionally fail to converge on short or irregular series.

X-13ARIMA-SEATS (SEATS)

Uses the seasonal package, which wraps the U.S. Census Bureau's X-13ARIMA-SEATS program. seas() is run with its automatic defaults (model selection, log/level transformation, outlier detection, and calendar adjustment), and the SEATS trend-cycle (s12) and seasonally adjusted series (s11) are mapped to an additive trend/seasonal/remainder so the exact identity holds regardless of the internal transformation. Because X-13 picks its own log/level transformation, seats is best used with the default transform = "none"; an outer log transform is redundant.

Multiplicative Seasonality

When the seasonal amplitude grows with the level of the series (a multiplicative pattern, common in economic data), set transform = "log". The series is log-transformed, decomposed additively, and the components are exponentiated back. This works uniformly for every method and requires strictly positive values.

Value

A tibble with the original columns plus, for each requested method, three new columns (and a fourth when seasadj = TRUE):

  • ⁠trend_{method}⁠: the estimated trend component.

  • ⁠seasonal_{method}⁠: the estimated seasonal component.

  • ⁠remainder_{method}⁠: what remains after removing trend and seasonal.

  • ⁠seasadj_{method}⁠: the seasonally adjusted series (only if seasadj = TRUE).

With transform = "none" the additive identity value = trend + seasonal + remainder holds exactly for every method. With transform = "log" the product identity value = trend * seasonal * remainder holds instead. For "classic" the trend (and hence remainder) is NA for the first and last frequency / 2 observations (the centred moving average has no boundary support).

Output rows are ordered by date within each group; the original row order is not preserved.

Examples

# STL decomposition (default settings work well for most economic series)
gdp_construction |>
  decompose_series(value_col = "index")

# STL with robust fitting (useful when the series has outliers)
gdp_construction |>
  decompose_series(
    value_col = "index",
    params = list(robust = TRUE)
  )

# STL with evolving seasonality (s.window controls how fast it can change)
gdp_construction |>
  decompose_series(
    value_col = "index",
    params = list(s.window = 13)
  )

# Regression with cubic trend
gdp_construction |>
  decompose_series(
    value_col = "index",
    methods = "regression",
    trend = "cubic"
  )

# Classical decomposition via moving averages (boundary trend is NA)
gdp_construction |>
  decompose_series(
    value_col = "index",
    methods = "classic"
  )

# Basic Structural Model (state-space, components for every observation)
gdp_construction |>
  decompose_series(
    value_col = "index",
    methods = "bsm"
  )

# X-13ARIMA-SEATS (requires the 'seasonal' package)
if (requireNamespace("seasonal", quietly = TRUE)) {
  gdp_construction |>
    decompose_series(
      value_col = "index",
      methods = "seats"
    )
}

# Multiplicative decomposition via log transform (works for any method)
oil_derivatives |>
  decompose_series(
    value_col = "production",
    transform = "log"
  )

# Several methods at once for side-by-side comparison
gdp_construction |>
  decompose_series(
    value_col = "index",
    methods   = c("stl", "classic")
  )

# Also return the seasonally adjusted series
gdp_construction |>
  decompose_series(
    value_col = "index",
    seasadj   = TRUE
  )

# Grouped decomposition: one decomposition per electricity sector
electricity |>
  decompose_series(
    group_cols = "name_series"
  )

Seasonally adjust (deseason) a time series

Description

Pipe-friendly convenience wrapper around decompose_series() focused on a single task: removing the seasonal component from a time series. It adds a ⁠seasadj_{method}⁠ column holding the seasonally adjusted (deseasoned) series and, optionally, the underlying trend, seasonal, and remainder components.

Usage

deseason_series(
  data,
  date_col = "date",
  value_col = "value",
  group_cols = NULL,
  methods = "stl",
  transform = "none",
  frequency = NULL,
  components = FALSE,
  params = list(),
  .quiet = FALSE
)

Arguments

data

A data.frame, tibble, or data.table containing the time series data.

date_col

Name of the date column. Defaults to "date". Must be of class Date.

value_col

Name of the value column. Defaults to "value". Must be numeric.

group_cols

Optional grouping variables for multiple time series. A character vector of column names. When provided, decomposition is applied independently to each group.

methods

Seasonal-adjustment method(s). One or more of "stl" (default) or "seats". When both are supplied, each contributes its own ⁠seasadj_{method}⁠ column (and component columns when components = TRUE) so the adjustments can be compared side by side.

  • "stl": Seasonal-Trend decomposition via Loess (stats::stl()).

  • "seats": X-13ARIMA-SEATS decomposition (requires the seasonal package; see decompose_series() for details).

transform

Transformation applied to the series before decomposition. One of "none" (default, additive decomposition) or "log". With "log", the series is log-transformed, decomposed additively, and the components are exponentiated back, yielding a multiplicative decomposition.

frequency

The frequency of the series. Supports 4 (quarterly) or 12 (monthly). Will be auto-detected if not specified. All methods require frequency > 1.

components

If FALSE (default), only the seasonally adjusted ⁠seasadj_{method}⁠ column is added. If TRUE, the ⁠trend_{method}⁠, ⁠seasonal_{method}⁠, and ⁠remainder_{method}⁠ columns are also added (the full decompose_series() output).

params

Optional list of method-specific parameters for fine control. Sensible defaults are provided for all parameters; this argument is only needed for non-standard use cases.

For STL (methods = "stl"):

  • s.window or stl_s_window: seasonal smoothing window. Either "periodic" (default, assumes constant seasonal pattern) or a positive odd integer (larger values allow more slowly evolving seasonality).

  • t.window or stl_t_window: trend smoothing window (odd integer, or NULL to let stats::stl() choose automatically — recommended default).

  • robust or stl_robust: logical. If TRUE, uses robust fitting to reduce the influence of outliers. Default FALSE.

For regression (methods = "regression"):

  • poly_raw: logical. If FALSE (default), uses orthogonal polynomials (numerically stable, recommended). If TRUE, uses raw polynomials (more interpretable coefficients, less stable for degree >= 2).

classic, bsm, and seats take no params. For multiplicative seasonality with any method, use transform = "log".

.quiet

If TRUE, suppress informational messages.

Details

deseason_series() is a thin wrapper: it calls decompose_series() with seasadj = TRUE and then keeps only the seasonally adjusted column unless components = TRUE. All seasonal-adjustment behaviour, validation, grouping, and the transform = "log" (multiplicative) path are inherited unchanged from decompose_series(). See its documentation for method internals and the meaning of the params argument.

For a full trend/seasonal/remainder decomposition, or for the regression, classic, and bsm methods, use decompose_series() directly.

Value

A tibble with the original columns plus, for each requested method, a ⁠seasadj_{method}⁠ column holding the seasonally adjusted series. When components = TRUE, the ⁠trend_{method}⁠, ⁠seasonal_{method}⁠, and ⁠remainder_{method}⁠ columns are added as well.

The seasonally adjusted series is the series with the seasonal component removed: trend + remainder for additive decompositions, trend * remainder when transform = "log". Output rows are ordered by date within each group; the original row order is not preserved.

See Also

decompose_series() for the underlying decomposition and the full set of methods; augment_trends() to extract a trend component only.

Examples

# Seasonally adjust a quarterly series (STL, the default)
gdp_construction |>
  deseason_series(value_col = "index")

# Also keep the trend, seasonal, and remainder components
gdp_construction |>
  deseason_series(value_col = "index", components = TRUE)

# Multiplicative adjustment via log transform (seasonal swings grow with level)
gdp_construction |>
  deseason_series(value_col = "index", transform = "log")

# X-13ARIMA-SEATS adjustment (requires the 'seasonal' package)
if (requireNamespace("seasonal", quietly = TRUE)) {
  gdp_construction |>
    deseason_series(value_col = "index", methods = "seats")
}

# Compare STL and SEATS adjustments side by side
if (requireNamespace("seasonal", quietly = TRUE)) {
  gdp_construction |>
    deseason_series(value_col = "index", methods = c("stl", "seats"))
}

# Grouped seasonal adjustment: one adjustment per electricity sector
electricity |>
  deseason_series(group_cols = "name_series")

Convert a data.frame into a time series (ts)

Description

Converts a series, stored in a data.frame or tibble, into a ts object.

Usage

df_to_ts(x, date_col = "date", value_col = "value", frequency = 12)

Arguments

x

A data.frame, tibble or data.table.

date_col

Name of the date column. Defaults to 'date'. Must be of class Date.

value_col

Name of the value column. Defaults to 'value'. Must be numeric.

frequency

The frequency of the series. Can be a shortened string (e.g. "M" for monthly) or a number (e.g. 12).

Value

A ts object

Examples

ibc <- df_to_ts(ibcbr, value_col = "index", frequency = "M")
class(ibc)
plot(ibc)

Electric Consumption Residential

Description

Monthly residential electric consumption in Brazil (GWh).

Usage

electric

Format

A tibble with monthly observations:

date

Date column

consumption

Electric consumption in GWh

Source

Brazilian Central Bank SGS (code 1403)


Electricity Consumption by Sector

Description

Monthly electricity consumption in Brazil by sector (GWh), in long format. Combines residential, commercial, and industrial sub-series from the Brazilian National Electric System Operator (ONS) as reported by the Brazilian Central Bank SGS.

Usage

electricity

Format

A tibble with monthly observations:

date

Date column

name_series

Sector identifier: "electric_residential", "electric_commercial", or "electric_industrial"

value

Electricity consumption in GWh

Source

ONS via Brazilian Central Bank SGS (codes 1403 — residential, 1402 — commercial, 1404 — industrial).

See Also

electric for the residential-only wide-format series.


GDP Construction Index

Description

Quarterly Brazilian GDP construction sector index (Base: average 1995 = 100).

Usage

gdp_construction

Format

A tibble with quarterly observations:

date

Date column

index

Construction index value

Source

DEPEC/GEATI/COACE. Fetched from Brazilian Central Bank SGS (code 22087)


Central Bank Economic Activity Index

Description

Monthly Central Bank Economic Activity Index (IBC-Br). The IBC-Br was built based on proxies for the evolution of agriculture, industry and service-sector products. The proxies are aggregated with weights derived from the tables of supply and use of the Brazilian National Accounts.

Usage

ibcbr

Format

A tibble with monthly observations:

date

Date column

index

Index (2003 = 100)

Source

BACEN. Fetched from Brazilian Central Bank SGS (code 24363).


Series Metadata

Description

Metadata for all economic series included in the package.

Usage

metadata_series

Format

A tibble with metadata:

series_name

Short series identifier

description

Full series description

frequency

Data frequency (D = daily, M = monthly, Q = quarterly)

source

Data source

date_col

Name of the date column in the dataset

value_col

Name of the main value column(s) in the dataset

group_cols

Grouping column(s) for long-format datasets, or NA

date_min

First observation date

date_max

Last observation date

Source

Various (BCB-SGS, ONS, CEPEA/ESALQ)


Oil Derivatives Production

Description

Monthly production of petroleum derivatives in Brazil (thousand barrels/day).

Usage

oil_derivatives

Format

A tibble with monthly observations:

date

Date column

production

Oil derivatives production

Source

ANP. Fetched from Brazilian Central Bank SGS (code 1391).


UK Retail Sales - Automotive Fuel

Description

Chained volume of retail sales for automotive fuel in the UK, non-seasonally adjusted. Index numbers of sales per week (100 = 2023). The monthly period consists of 4 weeks except for March, June, September and December which are 5 weeks. January 2025 is also a 5 week period. The series considers the "All Businesses" specification and covers Great Britain from 1998 to 2025.

Usage

retail_autofuel

Format

A tibble with monthly observations:

date

Date column

value

Retail sales index (chained volume)

name

Series name

frequency

Frequency ("M")

source

Data source ("ONS")

Source

UK Office for National Statistics (ONS). (Table 3M).

See Also

retail_volume


UK Retail Index

Description

Chained volume of retail sales, non-seasonally adjusted, selected sub-series. Index numbers of sales per week (100 = 2023). The monthly period consists of 4 weeks except for March, June, September and December which are 5 weeks. January 2025 is also a 5 week period. The included series consider the "All Businesses" specification and cover Great Britain from 1998 to 2025.

Usage

retail_volume

Format

A tibble with monthly observations:

date

Date column

name_series

Series name derived from the unofficial SIC

value

Retail sales index (chained volume)

Source

UK Office for National Statistics (ONS). (Table 3M).

See Also

retail_autofuel


London Transit - Average Daily Journeys

Description

Average daily journeys on London's bus and tube networks, split by business day and non-business day. Aggregated from daily Transport for London (TfL) network demand data using the UK calendar.

Usage

transit_london_avgs

Format

A tibble with monthly observations:

date_month

First day of each month (Date)

transit_mode

Transit mode: "bus" or "tube"

is_business_day

1 for business days, 0 for weekends/holidays

avg_daily_journeys

Average daily journeys for the given day type

Source

Transport for London (TfL) network demand data.

See Also

transit_london_monthly


London Transit - Monthly Journey Totals

Description

Monthly total journeys on London's bus and tube (underground) networks. Aggregated from daily Transport for London (TfL) network demand data.

Usage

transit_london_monthly

Format

A tibble with monthly observations:

date_month

First day of each month (Date)

transit_mode

Transit mode: "bus" or "tube"

journey_monthly

Total journeys in the month

Source

Transport for London (TfL) network demand data.

See Also

transit_london_avgs


Convert time series to tibble

Description

Convert time series to tibble

Usage

ts_to_df(x, date_col = NULL, value_col = NULL)

Arguments

x

A time series as a ts object

date_col

Optional name for the date column

value_col

Optional name for the value column

Value

a tibble

Examples

# example code
ts_to_df(AirPassengers)

# Using a custom name for the value column
ts_to_df(AirPassengers, value_col = "passengers")

Vehicle Production

Description

Monthly vehicle production in Brazil (units).

Usage

vehicles

Format

A tibble with monthly observations:

date

Date column

production

Vehicle production in absolute units

Source

Anfavea. Fetched from Brazilian Central Bank SGS (code 1378).