Skip to content

Fourier decomposition

polars_ts.decomposition.fourier_decomposition

fourier_decomposition(df, ts_freq, freqs=('week',), n_fourier_terms=3, id_col='unique_id', time_col='ds', target_col='y', anomaly_threshold=None)

Perform Fourier decomposition on a time series dataset.

Extract trend, seasonal, and residual components. The decomposition is based on Fourier harmonics for various temporal frequencies (e.g., week, month, quarter).

Parameters:

Name Type Description Default
df DataFrame

The input Polars DataFrame containing the time series data.

required
ts_freq int

The number of periods within a seasonal cycle: 52 for weekly data, 4 for quarterly data, 12 for monthly data, etc.

required
freqs Tuple[Literal['week', 'month', 'quarter', 'day_of_week', 'day_of_month', 'day_of_year']]

A tuple of frequencies to use for generating Fourier harmonics. Options include:

  • week (weekly frequency)
  • month (monthly frequency)
  • quarter (quarterly frequency)
  • day_of_week (day of the week, 0-6)
  • day_of_month (day of the month, 1-31)
  • day_of_year (day of the year, 1-365/366)
('week',)
n_fourier_terms int

The number of Fourier terms (harmonics) to generate for each frequency. Higher values allow capturing more complex seasonal patterns.

3
id_col str

The name of the column that uniquely identifies each series (default: unique_id).

'unique_id'
time_col str

The name of the column containing the timestamps or time values. This is used to generate temporal features like "week", "month", etc. Defaults to ds.

'ds'
target_col str

The name of the target variable (column) whose seasonal and trend components are being decomposed. Defaults to y.

'y'
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 following columns:

  • id_col: The original ID column.
  • time_col: The original time column.
  • target_col: The original target variable.
  • trend: The estimated trend component (using moving average).
  • seasonal: The seasonal component (estimated using Fourier harmonics).
  • resid: The residuals, computed as the difference between the original target and the sum of the trend and seasonal components.
  • is_anomaly (optional): Boolean flag when anomaly_threshold is set.