Skip to content

Data preparation

Differences of a target series, the reversible target transforms that a Pipeline can fit and invert, and how to put readings taken at irregular times on a regular grid without letting the future in.

differencing is public through timegym.target; import it from that module. It is a standalone pandas transformation, not an automatic Pipeline stage, and it never mutates the supplied object. Row offsets are positional, so a lag of one means the previous row even when timestamps are irregular. The reversible target transforms below are the exception: a Pipeline fits and inverts them on each case. The smoothing, feature, label and fractional-difference helpers of TimeGym 1.4.0 are deprecated, will leave the package in a later release and are no longer documented here; the changelog names what to use instead.

Differences

differencing takes a whole-number order (default 1) and a positive lag (default 1). order counts repeated differences and is not the lag distance: order two is y[t]-2*y[t-lag]+y[t-2*lag]. It trims order*lag rows. Its fractional_coefficients argument serves only the deprecated fractional orders.

Differencing accepts a Series or DataFrame and preserves its type and labels on the retained rows. Orders must be finite and nonnegative, and lag must be a positive integer. Missing observations inside the series propagate; they are not filled with zero. It applies no inverse; use DifferenceTransform below for differences that a pipeline undoes.

Reversible target transforms

LogTransform(), BoxCoxTransform() and DifferenceTransform(order=1, lag=1) implement fit_transform(history), inverse_transform(forecast) and clone_unfitted(). ComposedTransform(transforms) applies bundled members in order and inverts them in reverse order. Each transform is fitted on the history only. Log and Box-Cox require strictly positive finite targets; Box-Cox fits one lambda per target by maximum likelihood, bounded to [-1, 2], and rejects a constant target and transformed forecasts without a preimage. Inversion requires a valid forecast with the fitted target names in the fitted order.

  • Samples and quantiles invert elementwise. Monotone transforms preserve quantile order.
  • After a nonlinear inverse, the point is the mean of the inverted samples, else the inverted 0.5 quantile, else the inverted point read as a median.
  • DifferenceTransform integrates points and samples exactly. It recomputes quantiles from the integrated samples, or omits them when there are none, and assumes the forecast rows immediately follow the history.

A pipeline's saved configuration describes exact bundled classes as builtin and any other object, including a subclass, as external; replay rebuilds bundled transforms only.

Irregular readings

Sensors, logs and sales arrive at irregular times, and a TimeGym history needs one row per step. Put the readings on a regular grid by taking, at each step, the last reading at or before it, never one after it. pandas' default resampling does not do this: readings.resample("1h").last() labels each hour by its start, so a reading taken at 10:50 becomes the value at 10:00, and a forecast made at 10:00 sees 50 minutes of the future. pd.merge_asof with direction="backward" looks only backwards:

import pandas as pd

readings = pd.Series([1.0, 2.0, 3.0, 4.0], name="level", index=pd.to_datetime(
    ["2024-05-01 09:10", "2024-05-01 10:50", "2024-05-01 12:05", "2024-05-01 19:30"]))
grid = pd.date_range("2024-05-01 10:00", "2024-05-01 20:00", freq="1h")
hourly = pd.merge_asof(pd.DataFrame(index=grid), readings.to_frame(),
                       left_index=True, right_index=True,
                       direction="backward",           # the last reading at or before each hour
                       tolerance=pd.Timedelta("6h"))   # older than 6 hours: missing

At 11:00 hourly holds the 10:50 reading, and at 19:00 it is missing, because the last reading, at 12:05, is more than six hours old. Choose the tolerance on purpose: it says how old a reading may be and still count as current.

TimeGym does not fill gaps for you: ForecastTask and cases_from_series refuse a history with missing values. Cut the series at a gap, or fill it in a way you can defend, before you cut it into cases.

Signatures

timegym.target.differencing

differencing(series: _Pandas, order: float = 1, fractional_coefficients: int = 10, *, lag: int = 1) -> _Pandas

Apply repeated lag differences; order is not a lag distance.

order=2 means y[t]-2y[t-lag]+y[t-2lag]. For a seasonal first difference use order=1, lag=period. Order zero returns a copy unchanged. Noninteger orders use the explicitly truncated fractional approximation. Return the same pandas type and labels, trimming order*lag warmup rows for integer orders. Internal missing values propagate. All columns are treated independently without mutation. fractional_coefficients is used only for noninteger orders; lag counts rows, not calendar durations.

timegym.target.LogTransform

Natural logarithm of a strictly positive target, inverted by exp.

Samples and quantiles invert elementwise. exp(mean of logs) is not the original-scale mean, so the inverted point is the mean of exp(samples), else exp of the 0.5 quantile, else exp of the point read as a median.

fit_transform

fit_transform(history: DataFrame) -> pd.DataFrame

Record the target names and return the log of a strictly positive history.

inverse_transform

inverse_transform(forecast: Forecast) -> Forecast

Return a forecast that meets its contract on the original scale.

timegym.target.BoxCoxTransform

Box-Cox transform with one lambda per target, fitted by maximum likelihood on the history.

The lambdas are recomputed for every history and never see future values. Each lies in [-1, 2]: on short histories the unbounded estimate can be so extreme that ordinary forecast noise has no preimage. Inversion follows LogTransform's point rule. A transformed value v with lambda * v + 1 <= 0 has no Box-Cox preimage, and inverting it raises.

fit_transform

fit_transform(history: DataFrame) -> pd.DataFrame

Fit one lambda per target on this history and return the transformed history.

inverse_transform

inverse_transform(forecast: Forecast) -> Forecast

Return a forecast that meets its contract on the original scale.

Raises when a value has no Box-Cox preimage.

timegym.target.DifferenceTransform

DifferenceTransform(order=1, lag=1)

Repeated lag differences that keep the history tail needed to undo them.

order counts repeated differences and lag is their distance, as in differencing: order=1, lag=12 is a monthly seasonal difference. The forecast rows must be the steps that immediately follow the history. Points (means) and samples integrate exactly. Marginal quantiles of differences do not determine quantiles of their sums, so quantiles are recomputed from the integrated samples, or omitted without samples.

params

params() -> dict

Return the constructor arguments that clone_unfitted rebuilds from.

fit_transform

fit_transform(history: DataFrame) -> pd.DataFrame

Keep the history tail needed for inversion and return the differenced history.

inverse_transform

inverse_transform(forecast: Forecast) -> Forecast

Integrate a forecast that meets its contract back to levels.

Quantiles are recomputed from the integrated samples, or omitted without samples.

timegym.target.ComposedTransform

ComposedTransform(transforms)

Apply bundled transforms in order and invert them in reverse order.

Members are LogTransform, BoxCoxTransform or DifferenceTransform instances, copied unfitted so that no instance holds two fitted states.

params

params() -> dict

Return the constructor arguments that clone_unfitted rebuilds from.

fit_transform

fit_transform(history: DataFrame) -> pd.DataFrame

Fit and apply each member in order, each on the previous member's output.

inverse_transform

inverse_transform(forecast: Forecast) -> Forecast

Invert the members in reverse order.