Transformations & seasonal adjustment¶
The classes and functions of the row "Transformations & seasonal adjustment" of Analytical tools, with what calls return (the results and their methods: forecasts, impulse responses, tests). Import them from pymetrix (from pymetrix import ...) unless a heading names another module. Parameters and return types are in each signature; the text says what each does.
Help topics: Trend-cycle filters, Seasonal adjustment and calendar effects, Real-time data: masks, release calendars and vintages, Nowcasting and the ragged edge, Changing frequency and aggregating, Selections and loops, Derived series, Generate series for each, Temporal disaggregation, Quantile nowcasts, targeted predictors, weekly data and the mixed-frequency BVAR, Index numbers.
How do I: Test for cointegration in a short annual sample, Reconcile national accounts components to a total, Check whether a result survives other specifications.
From a plugin: pymetrix-seasonal has more for this area.
Classes¶
BaxterKing
dataclass
¶
BaxterKing(low: Annotated[float | None, Widget('text', help='shortest cycle kept, in periods; empty = 1.5 years')] = None, high: Annotated[float | None, Widget('text', help='longest cycle kept, in periods; empty = 8 years')] = None, k: Annotated[int | None, Widget('text', advanced=True, help='lead/lag length (points lost at each end); empty = 3 years')] = None)
Baxter-King band-pass filter: keeps cycles between low and high periods; loses k points at each end.
A symmetric moving average of 2k + 1 terms approximates the ideal filter that keeps only cycles of between
low and high periods (by default the business-cycle band of 1.5 to 8 years); the trend is the remainder.
Its weights sum to zero, so it removes trends, stochastic ones included, and being symmetric it does not shift
the cycle in time. A larger k approximates the ideal filter better but loses more observations at each end, where
the cycle is often of most interest; the Christiano-Fitzgerald filter keeps them.
ChristianoFitzgerald
dataclass
¶
ChristianoFitzgerald(low: Annotated[float | None, Widget('text', help='shortest cycle kept, in periods; empty = 1.5 years')] = None, high: Annotated[float | None, Widget('text', help='longest cycle kept, in periods; empty = 8 years')] = None, drift: Annotated[bool, Widget('checkbox', advanced=True, help="first subtract the straight line from the first to the last value (a random walk's drift)")] = True)
Christiano-Fitzgerald asymmetric band-pass filter (random-walk approximation), full sample.
It approximates the ideal filter that keeps cycles of between low and high periods using every
observation at every date, with asymmetric weights, so no observations are lost at the ends. The weights are
those that are optimal when the series is a random walk (after removing a drift, if asked). Near the ends the
estimates use mostly one side of the data, so they are revised as data arrive, and the asymmetric weights can
shift the cycle in time there.
Classical
dataclass
¶
Classical(log: Annotated[bool | None, _LOG] = None, two_sided: Annotated[bool, Widget('checkbox', advanced=True, help='a centred moving average (unticked: one-sided, past values only)')] = True, extrapolate_trend: Annotated[int, Widget('number', min=0, max=1000, advanced=True, help='extend the trend to the ends by a line through this many points; 0 = leave the ends empty')] = 0)
Classical decomposition: a centred moving-average trend, and the average deviation from it in each season. Simple and transparent, but the seasonal pattern cannot change over time.
Hamilton
dataclass
¶
Hamilton(h: Annotated[int | None, Widget('text', help='horizon in periods: the cycle is what is unpredictable this far ahead; empty = 2 years')] = None, p: Annotated[int | None, Widget('text', advanced=True, help='lags in the regression; empty = one year (at most 12)')] = None)
Hamilton (2018) regression filter: cycle = error in predicting y[t] from y[t-h] .. y[t-h-p+1].
The trend is the fitted value of a least-squares regression of y[t] on a constant and the p values ending h periods earlier; the cycle, the part of the series that could not be predicted h periods ahead. Hamilton proposes it in place of the HP filter, whose cycles can have spurious dynamics. The defaults are his: two years ahead and a year of lags (8 and 4 for quarterly data). The first h + p - 1 periods get no trend or cycle, and as the regression uses the whole sample its coefficients change as data arrive.
HP
dataclass
¶
HP(lamb: Annotated[float | None, Widget('text', help='smoothing parameter lambda: larger, smoother trend; empty = frequency default (1600 quarterly)')] = None, power: Annotated[int, Widget('number', min=1, max=6, advanced=True, help="default lambda = 1600*(f/4)^power: 2 is EViews' rule, 4 Ravn-Uhlig")] = 2, one_sided: Annotated[bool, Widget('checkbox', help='real-time trend: each period uses data up to then only')] = False)
Hodrick-Prescott filter. lamb=None: 1600*(f/4)**power (power 2: EViews' rule; 4: Ravn-Uhlig).
The trend minimises the squared deviations of the series from it plus lambda times the squared changes in its slope; the cycle is the remainder. A larger lambda gives a smoother trend and longer cycles. The two-sided filter uses future data, so its last estimates are the least reliable and are revised as new data arrive. The one-sided version (each period's trend is the end point of the filter run on the data up to then) suits real-time measures such as gaps, but its trend lags turning points. Hamilton (2018) shows that the filter can produce cycles with spurious dynamics, even from a random walk; his regression filter is an alternative.
MovingAverage
dataclass
¶
MovingAverage(window: Annotated[int, Widget('number', min=2, max=1000, help="periods averaged: longer, smoother trend; a year's periods remove stable seasonality")] = 4, centered: Annotated[bool, Widget('checkbox', help='centre the window (otherwise trailing)')] = True)
Moving-average trend.
The trend is the mean of window values, either the last ones (trailing) or those around each period
(centred); the cycle is the remainder. A trailing average uses only past data but lags the series by about half
a window; a centred one does not lag but leaves about half a window missing at each end. With an even window the
centred average reaches one period further back than forward. A window of one year's periods averages out a
stable seasonal pattern.
STL
dataclass
¶
STL(seasonal: Annotated[int, Widget('number', min=3, max=99, step=2, help='seasonal smoother length (odd); larger = more stable seasonal pattern')] = 7, robust: Annotated[bool, Widget('checkbox', help='downweight outliers')] = True, log: Annotated[bool | None, _LOG] = None, trend: Annotated[int | None, Widget('number', min=3, max=999, advanced=True, label='Trend length', help='trend smoother length (odd); empty = automatic')] = None, low_pass: Annotated[int | None, Widget('number', min=3, max=999, advanced=True, help='low-pass filter length (odd, more than the period); empty = the next odd number above it')] = None, seasonal_deg: Annotated[Literal[0, 1], Widget('choice', advanced=True, help='degree of the seasonal LOESS: 0 constant, 1 linear')] = 1, trend_deg: Annotated[Literal[0, 1], Widget('choice', advanced=True, help='degree of the trend LOESS: 0 constant, 1 linear')] = 1, low_pass_deg: Annotated[Literal[0, 1], Widget('choice', advanced=True, help='degree of the low-pass LOESS: 0 constant, 1 linear')] = 1, seasonal_jump: Annotated[int, Widget('number', min=1, max=100, advanced=True, help='fit the seasonal LOESS every this many points and interpolate (faster)')] = 1, trend_jump: Annotated[int, Widget('number', min=1, max=100, advanced=True, help='fit the trend LOESS every this many points')] = 1, low_pass_jump: Annotated[int, Widget('number', min=1, max=100, advanced=True, help='fit the low-pass LOESS every this many points')] = 1, inner_iter: Annotated[int | None, Widget('number', min=1, max=50, advanced=True, help='inner-loop iterations; empty = automatic (2 if robust, else 5)')] = None, outer_iter: Annotated[int | None, Widget('number', min=0, max=50, advanced=True, help='robustness (outer-loop) iterations; empty = automatic (15 if robust, else 0)')] = None)
Seasonal-trend decomposition by LOESS (Cleveland et al. 1990), computed by statsmodels.
TemporalDisaggregation
dataclass
¶
TemporalDisaggregation(formula: str, method: Method = 'chow-lin', conversion: Conversion = 'sum', rho: float | None = None, rho_bounds: tuple[float, float] = (0.0, 0.999), soft: float | tuple[tuple[str, float], ...] | None = None, differences: Differences = 'first', level_penalty: float | None = None)
formula: the low-frequency series on high-frequency indicators (gdp ~ ip + emp; gdp ~ 1 for none).
method: chow-lin (AR(1) residual, rho by maximum likelihood), chow-lin-minrss (rho by minimum residual
sum of squares), fernandez (random walk), litterman and litterman-minrss (random walk with AR(1)
increments, Litterman 1983), denton (proportional) or denton-additive.
conversion: how the low-frequency data aggregate the high-frequency series (sum, average, first, last);
fit(..., aggregation=C) gives any aggregation matrix instead.
rho: Chow-Lin and Litterman: fix rho instead of estimating it.
rho_bounds: the range rho is estimated in, by default [0, 0.999] (tempdisagg's: rho is kept non-negative);
(-0.999, 0.999) allows negative rho. An estimate at an end of the range is reported in the summary's notes.
soft: soft constraints: the standard deviation of the error on the low-frequency values (in their units), one
for all, or {period: sd} (periods not named stay exact; 0 = exact). Regression methods treat it as measurement
error on the aggregates (GLS); Denton adds ((C y - Y) / sd)^2 to its criterion. None (the default): exact.
differences: Denton: first (the default) or seasonal (lag 4 for quarterly, 12 for monthly data), which
keeps the indicator's seasonal pattern; level_penalty: with seasonal differences, the weight on first
differences that pins the pattern seasonal differences leave free (None: 0.001; 0: none, the minimum-norm solution).
fit
¶
fit(low: Dataset, high: Dataset, aggregation: Any = None) -> FittedDisaggregation
Disaggregate low's series with high's indicators.
aggregation: an aggregation matrix C (low × high) in place of conversion, so that C y = Y: a Matrix or
DataFrame with one row per low-frequency value (named as low's rows: periods, or any labels in a
cross-section dataset) and one column per high-frequency period (named as high's), a dataset at the high
frequency with one series of weights per constraint, a CSV, Excel or Parquet file laid out like the Matrix, or
an array matched by position (see aggregation_matrix). Rows whose low-frequency value is missing are
dropped; the rest must be independent and lie within the indicators' sample.
Functions¶
aggregation_matrix
¶
aggregation_matrix(high: Any, periods: Sequence[Any], conversion: Conversion = 'sum') -> Matrix
The aggregation matrix of low-frequency periods of any frequencies over the high-frequency periods of
high (a dataset or a PeriodIndex): one row per period, named by it ('2019', '2020 Y-JUN'), one column per
high-frequency period. Calendar years, fiscal years and quarters can be mixed and can overlap:
C = aggregation_matrix(quarterly, [pd.Period("2018", "Y"), pd.Period("2019", "Y-JUN"), pd.Period("2020", "Y-JUN")])
apply_tcodes
¶
apply_tcodes(data: Dataset, codes: Any, scale: Mapping[str, float] | float | None = None, drop: bool = False) -> Dataset
Each series named in codes (a dict or Series from series to code, or a FRED-MD CSV file whose
"Transform:" row holds them) transformed by its code; scale multiplies the results (one number, or by series).
Series without a code are kept as they are, or left out with drop. Names are matched exactly, then ignoring
case (FRED-MD's INDPRO is indpro once read).
chain_link
¶
chain_link(values: DataFrame | None = None, prices: DataFrame | None = None, *, quantities: DataFrame | None = None, previous_year_prices: DataFrame | None = None, method: ChainMethod = 'annual-overlap', reference: Any = None, year_start: int | str | None = None) -> DataFrame
Chain-linked volumes of an aggregate and its components (IMF QNA Manual 2017, chapter 8), from each component's
current-price values and prices (a price index or deflator; or quantities and prices; or values
and previous_year_prices, its values at the previous year's average prices, which the first year may lack:
its quarters are then spread as its current-price values). method: annual-overlap,
one-period-overlap (the one-quarter overlap of quarterly data, a one-month overlap of monthly data; its
earlier name one-quarter-overlap still works) or over-the-year (the same for annual data). reference:
the year whose annual sum
equals its current-price value (the first complete year by default). year_start: the first month of the
year the links use, for quarterly and monthly data (4 or "april" for an April-March fiscal year; January by
default); the years are then named by the calendar year they end in (2021 is April 2020 to March 2021, as
pandas' Y-MAR), and reference is such a year (2021, "2020/21", or a period in it). Columns: each
component, total, and discrepancy (total less the sum of the components: chain-linked volumes do not add
up); attrs records the method, the reference year, year_start and the period the one-period overlap
links at.
contributions_to_growth
¶
contributions_to_growth(values: DataFrame | None = None, prices: DataFrame | None = None, *, quantities: DataFrame | None = None, previous_year_prices: DataFrame | None = None, method: ContributionMethod = 'fisher', year_start: int | str | None = None, change: Change = 'period') -> DataFrame
Each component's contribution, in percentage points, to the percentage change of a chained aggregate
(total), adding up to it exactly: fisher (a Fisher index chained period to period, the BEA's
contributions), annual-overlap (the annual-overlap chain-linked Laspeyres volume of chain_link) or
laspeyres (a Laspeyres index chained period to period). change: period, the change on the period
before; year, the change on the same period a year before (the four-quarter or 12-month change; for annual
data the two are the same). Inputs, and year_start (the annual overlap's years), as chain_link's.
The year-on-year contributions to the annual-overlap volume are the QNA Manual's (IMF 2017, chapter 8, paragraph 8.88, equation 31): the change at the previous year's annual chain deflators, plus an adjustment for the change in the component's relative deflator between the two years before (none in the year after the first, whose relative deflators are taken as unchanged). For the chained Fisher and Laspeyres indices they are the period-on-period contributions of the year's periods, each weighted by the aggregate's level at the start of its period relative to a year before, which add up because the changes do: Q(t) / Q(t - n) - 1 is sum_k (Q(k - 1) / Q(t - n)) (Q(k) / Q(k - 1) - 1) over the n periods k of the year to t.
deflate
¶
deflate(nominal: Series | DataFrame, price: Series, base: Any = None, value: float = 100.0) -> Series | DataFrame
nominal at constant prices: nominal * value / price, the price index (or deflator) equal to value in
its reference period; with base, the index is rebased to value there first, so the result is in the
prices of base.
implicit_deflator
¶
The implicit price deflator value * nominal / real: the price index a current-price series and its volume
imply (value where they are equal, in the volume's reference year).
link_factor
¶
The factor that links old to new at the overlap at (a period, or a span averaged; the first period
both have by default): mean(new) / mean(old) there, or mean(new) - mean(old) with method="difference".
price_index
¶
price_index(prices: DataFrame, quantities: DataFrame | None = None, *, values: DataFrame | None = None, formula: Formula = 'fisher', chained: bool = False, base: Any = None, value: float = 100.0, weight_period: Any = None) -> Series
A price index of the items in the columns of prices (rows: periods), weighted by their quantities (or
values; columns matched by position): formula Laspeyres, Paasche, Fisher or Törnqvist, each period on the
base (fixed-base) or chained period to period; value on average over base (the first period by
default; a span as base uses each item's unit value and average quantity over it as the reference).
formula="lowe" or "young" weights by a weight_period b other than the price reference period 0
(base): Lowe keeps b's quantities, sum p_t q_b / sum p_0 q_b (b's expenditure shares price-updated to 0,
as price_update_weights does); Young keeps b's expenditure shares, sum s_b p_t / p_0 (ILO et al.,
Consumer Price Index Manual 2020, paragraphs 9.53-9.58). Only the weight period needs quantities or values; the
prices of a span (as base) are averaged.
price_update_weights
¶
price_update_weights(weights: Any, prices: DataFrame, weight_period: Any, base: Any, total: float = 100.0) -> DataFrame
Expenditure weights of the weight period b price-updated to the price reference period 0, as the Consumer
Price Index Manual (2020, Table 9.2, p. 204) does: each item's weights (b's expenditure or its share; a
Series or mapping by item) times its update factor, its price (or price index) averaged over base divided by
its average over weight_period, then normalised to add up to total. The Young index with these weights is
the Lowe index with b's (price_index(formula="lowe")). Columns: weight, factor, updated (weight
times factor) and share (normalised); a row per item.
quantity_index
¶
quantity_index(prices: DataFrame, quantities: DataFrame | None = None, *, values: DataFrame | None = None, formula: Formula = 'fisher', chained: bool = False, base: Any = None, value: float = 100.0) -> Series
A quantity (volume) index of the items, as price_index with the roles of prices and quantities swapped:
Laspeyres weights the quantities by the base period's prices, Paasche by the current period's.
rebase
¶
x (a series, or each column of a frame) scaled to average value over base: a period (2020,
"2020Q1") whose periods of the data are averaged, or a span ("2019:2021", or a pair).
reconcile
¶
reconcile(data: Dataset, components: str | Sequence[str], total: str, low: Dataset | None = None, *, fixed: str | Sequence[str] = (), method: ReconcileMethod = 'denton', conversion: str = 'sum', weights: Mapping[str, float] | None = None) -> Reconciliation
Reconcile components (series of data) with their high-frequency total (a series of data) and,
where low has a series of the same name, with that component's low-frequency values.
fixed: components held as they are. method: denton (proportional first differences, Di Fonzo and
Marini's multivariate Denton), denton-additive, least-squares (each adjustment's variance proportional
to the value), or weighted (minimises sum_c sum_t e_ct^2 / w_c: each component's adjustments have a constant
variance w_c, whatever its level and sign, so with equal weights it is the minimum-norm adjustment).
conversion: how the low-frequency values aggregate (sum, average, first, last). weights:
{component: relative weight}, larger moving more (default 1 each; positive: hold a component with fixed).
splice
¶
splice(old: Series, new: Series, at: Any = None, method: SpliceMethod = 'ratio', backcast: bool = True) -> Series
One series from a discontinued old and its replacement new, linked at the overlap at (a period, or a
span averaged; the first period both have by default). backcast: the new series as it is, and before the
overlap the old series times the link factor (plus it, with method="difference"): the old growth on the new
level. backcast=False: the old series as it is, and after the overlap the new one divided by (less) the factor.
The factor is in the result's attrs["link_factor"].
tcode_transform
¶
One series transformed by FRED-MD code code (1 to 7), times scale.
weekly_to_monthly
¶
weekly_to_monthly(data: Dataset, when: Any = None, names: Sequence[str] | None = None, how: Literal['mean', 'sum', 'last'] = 'mean', partial: Literal['separate', 'fill', 'drop'] = 'separate', lags: Mapping[str, int] | None = None, calendar: Any = None, suffix: str = '_mtd') -> Dataset
Weekly (or daily) series as monthly ones up to the ragged edge, as known on when (default: all the data):
complete months' means and, with partial="separate", a month-to-date series name + suffix (see the module
notes). lags and calendar say when each value was published, as in as_of.
with_chain_linked
¶
with_chain_linked(data: Dataset, name: str, values: str | Sequence[str], prices: str | Sequence[str] = (), *, quantities: str | Sequence[str] = (), previous_year_prices: str | Sequence[str] = (), method: ChainMethod = 'annual-overlap', reference: Any = None, components: bool = False, year_start: int | str | None = None) -> Dataset
data with the chain-linked volume name of the components whose series are named (chain_link), its
{name}_discrepancy (the total less the sum of the chain-linked components) and, with components, each
component's chain-linked volume {name}_{component}. values names the current-price series (or, with
quantities, is left empty). year_start: the first month of the years linked on (chain_link). In a
panel, each entity is chain-linked on its own, to its own reference year (the first complete year it has by
default). The new series are at chained prices (Variable.prices), with the reference year as their
base_period ("2020/21" for a year from April) and the method, year_start and the period linked at in
extra["index"]; they keep the current-price series' units when those all share them.
with_contributions
¶
with_contributions(data: Dataset, name: str, values: str | Sequence[str], prices: str | Sequence[str] = (), *, quantities: str | Sequence[str] = (), previous_year_prices: str | Sequence[str] = (), method: ContributionMethod = 'fisher', year_start: int | str | None = None, change: Change = 'period') -> Dataset
data with the aggregate's percentage change name and each component's contribution to it, in
percentage points, {name}_{component} (contributions_to_growth; year_start for the annual overlap;
change="year" for the change on a year before). In a panel, each entity's own. The series record their units
(percent, percentage points) and the method and change in extra["index"].
with_index
¶
with_index(data: Dataset, name: str, prices: str | Sequence[str], quantities: str | Sequence[str] = (), *, values: str | Sequence[str] = (), kind: Literal['price', 'quantity'] = 'price', formula: Formula = 'fisher', chained: bool = False, base: Any = None, value: float = 100.0, weight_period: Any = None) -> Dataset
data with a price (or quantity, kind) index name of the items whose prices and quantities (or
values) are series of data: price_index or quantity_index on those series (in a panel, each entity's
own, on its own base: the first period it has by default). weight_period: the Lowe and Young indices' (a
price index). The new series records its base (Variable.base_period: the index reference period), and in
extra["index"] the formula, the value at the base and the weight period.
Results¶
FittedDisaggregation
dataclass
¶
FittedDisaggregation(spec: TemporalDisaggregation, series: Series, names: list[str], params: ndarray, cov: ndarray, rho: float, low_index: Index, low_values: ndarray, C: ndarray, info: dict[str, Any] = dict(), provenance: Any = None)
check
property
¶
Largest gap between the low-frequency data and the disaggregated series aggregated (zero, unless soft).
gaps
property
¶
The low-frequency data minus the disaggregated series aggregated, by period (zero, unless soft).
plot
¶
The disaggregated series, with the low-frequency data spread evenly over each period for comparison.
Reconciliation
dataclass
¶
Reconciliation(series: DataFrame, preliminary: DataFrame, total: Series, components: tuple[str, ...], fixed: tuple[str, ...], method: str, conversion: str, low_totals: dict[str, Series] = dict(), C: dict[str, ndarray] = dict(), weights: dict[str, float] = dict(), provenance: Any = None, skipped: tuple[str, ...] = ())
Reconciled components: series (the components, fixed ones included), preliminary (as given),
adjustments (series minus preliminary), total, check (the largest gap from any constraint),
diagnostics() (the size of each component's adjustment and its gaps before and after), skipped (periods
with data left out of the sample, and the low-frequency benchmarks not applied because of them).
check
property
¶
The largest gap from the constraints the reconciled series must meet (zero up to rounding).
total_gaps
¶
The total minus the components' sum, by period (zero once reconciled).
low_gaps
¶
A component's low-frequency values minus its high-frequency values aggregated.