Skip to content

Seasonal decomposition

polars_ts.decomposition.seasonal_decomposition

seasonal_decomposition(df, freq, method='additive', id_col='unique_id', target_col='y', time_col='ds', anomaly_threshold=None)

Perform seasonal decomposition of time series data using either an additive or multiplicative method.

  • Additive: Y(t) = T(t) + S(t) + E(t)
  • Multiplicative: Y(t) = T(t) * S(t) * E(t)

Parameters:

Name Type Description Default
df DataFrame

Polars DataFrame containing the time series data.

required
freq int

The seasonal period (e.g., 12 for monthly data with yearly seasonality).

required
method Literal['additive', 'multiplicative']

The decomposition method (additive or multiplicative).

'additive'
id_col str

The column to group by (e.g., for multiple time series). Defaults to unique_id.

'unique_id'
target_col str

The column containing the time series values to decompose. Defaults to y.

'y'
time_col str

The column containing the time values. Defaults to ds.

'ds'
anomaly_threshold float | None

If provided, adds an is_anomaly boolean column that is True when |resid| > threshold * std(resid) per group. Defaults to None (no anomaly column).

None

Returns:

Type Description
DataFrame

A DataFrame with the decomposed components: trend, seasonal component, and residuals.

DataFrame

When anomaly_threshold is set, an additional is_anomaly column is included.

Raises:

Type Description
ValueError

If invalid method is passed.

KeyError

If specified columns do not exist in the DataFrame.

ValueError

If the DataFrame is empty or doesn't have enough data to decompose.