Data & connectors¶
The classes and functions of the row "Data & connectors" 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: Data connectors, Real-time data: masks, release calendars and vintages, Changing frequency and aggregating, Working with panel data, Samples, Distribution functions and moments, Selections and loops, Large Parquet data, Nowcasting and the ragged edge, MIDAS: mixed-frequency regression, Matrices with names.
How do I: Load data with Browse series (FRED, IMF, ECB, Eurostat, World Bank), Seasonally adjust a series, Reconcile national accounts components to a total.
From a plugin: pymetrix-eviews has more for this area.
From a plugin: pymetrix-psets has more for this area.
Classes¶
Dataset
dataclass
¶
Dataset(frame: DataFrame, axes: tuple[Axis, ...], variables: Mapping[str, Variable] = dict(), flags: DataFrame | None = None, meta: DatasetMeta = DatasetMeta())
sample
property
¶
The active sample (a Sample), or None for all rows: what estimation, tests, statistics and graphs
use when no other sample is given.
from_frame
classmethod
¶
from_frame(df: DataFrame, *, time: str | None = None, entity: str | Sequence[str] | None = None, freq: str | None = None, variables: Mapping[str, Variable] | None = None, meta: DatasetMeta | None = None, source: str | None = None, start: str | None = None) -> Dataset
Build a Dataset from a DataFrame, naming its time and entity columns.
A frame that already has a PeriodIndex needs no arguments. A frame with no dates (row numbers, or a plain
integer index, which is dropped) is dated from start at frequency freq, one period per row in order,
on a time axis named time: Dataset.from_frame(df, start="1990Q1", freq="Q") is R's
ts(x, start = c(1990, 1), frequency = 4). For a NumPy array, make the frame first:
pd.DataFrame(array, columns=["y", "x"]). source (e.g. "user:pandas") is recorded on every series
that does not already say where it came from.
example
classmethod
¶
example(name: str = 'sample_macro') -> Dataset
An example dataset shipped with pymetrix (see pymetrix.datasets.available()).
empty
classmethod
¶
empty(freq: str, start: str, end: str) -> Dataset
A time series dataset with no series yet: every period of frequency freq ("Y", "Q", "M",
"W", "D"; "Y-JUN" for a July-June year; "A" is read as "Y") from start to end, both
included, on a time axis named time (EViews' wfcreate q 1990q1 2030q4). Add series with with_series:
Dataset.empty("Q", "1990Q1", "2030Q4").with_series(t="1", y=None).
read
classmethod
¶
read(source: str, vintage: str = 'latest', *, columns: Sequence[str] | str | None = None, where: str | None = None, span: Span | str | None = None, embed: bool = True, **kw: Any) -> Dataset
Read a file (by its extension) or a connector's address (fred://GDPC1).
vintage is which release of a connector's data to ask for: "latest" (the default, written out in
generated code) or a date ("2020-01-30", the data as published then, where the provider keeps
vintages). The request is kept in meta.vintage and in the provenance of every result from the data.
For a Parquet file, or a folder of them (partitioned as year=2010/...), columns, where (a row
condition, as in select) and span ((start, end) on the time axis) read only part of it: pyarrow
skips the columns not named and the folders and row groups the condition rules out, and the condition is then
applied exactly (pymetrix.io.selection). What was read is kept in meta.extra["loads"].
embed=False asks projects to keep only a reference to the file (its path, the selection, and a fingerprint
of its contents) instead of a copy of the data read; opening the project reads the file again, and refuses if
the file has changed. For data too large to copy into every project.
values_of
¶
A column, or the values of an index level, or a calendar field of the time axis (quarter, month,
and seasonal(), the period of the year: the quarter of quarterly data, the month of monthly data), aligned
to the rows. A column of that name comes first.
calendar_names
¶
The calendar fields values_of derives from the time axis for this frequency (quarter, month).
lagged
¶
name shifted by lag periods (negative = past), always within entity.
with_series
¶
with_series(*, within: Any = None, **exprs: str | Series | None) -> Dataset
Add or replace series, from expressions or from aligned Series; None makes a series of missing values
(EViews' series y).
The values are fixed (like EViews' genr); use derive for series that
follow their inputs. Derived series that depend on a replaced series are
recomputed; a derived series replaced here becomes a plain one. A replaced series keeps
its label, description and units, but not its source, vintage, retrieval time or external
reference: those described the old values.
within (a Sample, a (start, end) span or "start:end") assigns only the rows it selects and
keeps the others' values, missing for a new series: EViews' smpl 2000q1 2010q4 then y = .... Lags
still reach outside it. A formula that uses the series it assigns is then computed one period at a time,
each period seeing the values just assigned before it, as EViews does: y="y[-1]*1.02" grows y by 2%
a period through the sample. Without within every row is assigned and a formula sees the values as they
were before the call. A series named within is added with add_series.
series
¶
A Selection of series: named, by pattern ("*_cycle"), by metadata (units="USD bn",
adjustment="sa", derived=True) or by a test on each Variable (where=).
derive
¶
derive(**recipes: Any) -> Dataset
Add series that keep their recipe and follow their inputs.
A value is an expression (dly="dlog(y)") or a recipe from
pymetrix.data.derived (Filtered("y", HP(), "trend")). When a
series they use is replaced (with_series), they are recomputed.
with_each
¶
with_each(series: Any, name: str, formula: str, derived: bool = False, replace: bool = False, within: Any = None) -> Dataset
A new series for each of series (names separated by spaces or commas, wildcards such as "ip_*", a
list or a Selection), named by the template name and computed by the template formula:
data.with_each("gdp cons inv", "{x}_g", "100*d(log({x}))"). {x} is the series; {1}, {2}... the
parts a wildcard's * or ? matched ("ip_*" with "{1}_growth"). With derived they are derived
series (derive); otherwise their values are computed once (with_series). Series that exist already
are an error unless replace. within assigns only a sample's rows, as with_series does (not with
derived).
Recorded and scripted as the one with_series (or derive) call it makes, with every new series written
out, so a script replays exactly whatever series are added later. pymetrix.data.each.preview_each shows
the rows without making them.
recompute
¶
recompute(*names: str) -> Dataset
Recompute derived series (all, or those named, with what depends on them).
freeze
¶
freeze(*names: str) -> Dataset
Keep the values of derived series (all, or those named) but drop their recipes.
row_key
¶
An index label from a row key as written in code: "2020Q1" (time series),
"FRA" (cross-section) or ("FRA", "2020Q1") (panel, in axis order).
flag
¶
The status of each observation of name (Status values; empty = normal).
edit
¶
edit(values: Mapping[str, Mapping[Any, Any]]) -> Dataset
Change observations by hand: {"c": {"2020Q1": 1.2}}; None makes a value missing.
Edited cells are flagged edited; the series' vintage stays as released. Derived
series that depend on an edited series are recomputed. Derived series themselves
cannot be edited: freeze them first.
rename
¶
rename(**names: str) -> Dataset
Rename series (old="new"); recipes that use them are updated to the new names.
keep
¶
keep(*names: str) -> Dataset
Only these series, in this order (the others removed, as drop would).
drop
¶
drop(*names: str) -> Dataset
Remove series. A series that a remaining derived series uses cannot be removed.
with_info
¶
with_info(name: str, **info: Any) -> Dataset
Change a series' description: label, units, description, source, measure,
adjustment, prices, scale, symbol...
over
¶
over(sample: Any = None, **kw: Any) -> Dataset
The same data over a sample, for chains: data.over("1990Q1:2019Q4").fit(Equation("c ~ y")).
with_sample under a shorter name: the sample becomes the dataset's active one, so it is in the code and
in every result's provenance.
fit
¶
Estimate spec (an Equation, VAR, System... anything with fit(data, ...)) on this
data: data.over("1990Q1:2019Q4").fit(Equation("c ~ y"), method=OLS(cov="hac")) is
Equation("c ~ y").fit(data.over("1990Q1:2019Q4"), method=OLS(cov="hac")).
with_sample
¶
with_sample(sample: Any = None, **kw: Any) -> Dataset
The same data with an active sample (EViews' smpl): a Sample, a (start, end) span, or the
arguments of one (with_sample(end="2007Q4", country=["DEU"])); None for all rows again. Lags and
transformations still use all the data; the sample chooses the rows commands use.
to_frame
¶
The series names (default all) on the sample's rows (None: the active sample, as commands use;
"all"; or a span or Sample), with this dataset's index; missing: keep, drop or raise.
to_pandas
¶
The series as a plain pandas DataFrame (default: every series, every row), with this dataset's index and
no metadata: the way out to pandas. sample=None uses the active sample; a span or Sample selects rows.
to_numpy
¶
to_frame(...) as a float array (rows by series).
design
¶
design(y: str, x: Any = (), sample: Any = None, add_constant: bool = True, missing: str = 'drop', where: str | None = None) -> tuple[Series, DataFrame]
(y, X) for statsmodels, SciPy or scikit-learn, labelled, on the rows pymetrix's own estimators would use;
names or formula expressions (log(c), c[-1]). See pymetrix.interop.design.
add_series
¶
add_series(name: str, values: Any, source: str | None = None, overwrite: bool = False, label: str = '', units: str = '') -> Dataset
A copy with series name from a pandas Series or an array; an existing name only with overwrite; the
source (default user:pandas or user:numpy) is recorded.
apply_np
¶
apply_np(name: str, func: Any, series: Any, *, source_expr: str | None = None, overwrite: bool = False) -> Dataset
Add name = func(arrays of series...), recorded as user code (see pymetrix.interop.apply_np).
apply_pd
¶
apply_pd(name: str, func: Any, series: Any, *, source_expr: str | None = None, overwrite: bool = False) -> Dataset
Add name = func(pandas series...), recorded as user code (see pymetrix.interop.apply_pd).
transform_each
¶
transform_each(selection: Any, func: Any, prefix: str = '', suffix: str = '', source_expr: str | None = None, overwrite: bool = False) -> Dataset
Add prefix + s + suffix = func(s) for each series of selection.
sample_record
¶
sample_record(span: Any = None, where: str | None = None, **levels: Any) -> tuple[str, dict[str, Any] | None]
Which rule sample_mask would follow for these arguments, and that rule in full, for provenance:
("explicit", {...}), ("active sample of the dataset", sample.to_dict()) or ("all observations", None).
A result then records how its rows were chosen, not only its first and last period.
sample_mask
¶
The rows a command uses: those of span (a (start, end) pair or a Sample), where and
levels when any is given; otherwise the active sample's (all rows without one).
select
¶
select(where: str | None = None, span: Span | None = None, **levels: Any) -> Dataset
Some of the periods or rows: a condition (where="year > 2000"), a span, or entity levels.
to_freq
¶
to_freq(freq: str, how: str | Mapping[str, str] | None = None) -> Dataset
Convert to a lower frequency ("Q", "Y", "Y-JUN"...). Periods with missing sub-periods become NaN.
how is sum, mean, first, last (or another pandas aggregation), for every series or as a mapping by
series; series it does not cover follow their Variable.measure (flows and counts summed, stocks the last
value, rates, indices and ratios averaged). To a higher frequency, use TemporalDisaggregation.
aggregate
¶
aggregate(by: str | Sequence[str], how: str | Mapping[str, str] | None = None) -> Dataset
Aggregate over everything except by (axis names or columns): aggregate("year") adds up a panel's
entities period by period. how as for to_freq; by measure, stocks are summed across entities.
pivot
¶
pivot(rows: str | Sequence[str], columns: str | Sequence[str] | None = None, values: str | Sequence[str] | None = None, agg: str | Sequence[str] | Mapping[str, str] = 'mean', margins: bool = False, fill: float | None = None, span: Span | None = None, where: str | None = None) -> Table
A pivot table (pandas pivot_table): values summarised by rows and columns.
Rows and columns are axes (country, time) or series of categories (region);
agg is one or more of mean, sum, count, min, max, median, std, first, last, or a
mapping from series to aggregation. margins adds totals.
wide
¶
wide(*names: str, by: str | None = None, sep: str = '_') -> Dataset
One column per series and entity (y_AUS, y_NZL), dropping the entity axis: a panel
becomes a set of time series. The inverse of long.
long
¶
long(entity: str = 'entity', stubs: Sequence[str] | None = None, name: str | None = None, sep: str = '_') -> Dataset
From one column per series and entity (y_AUS, c_AUS, y_NZL...) to a panel with
an entity axis; the inverse of wide. stubs names the series (default: what comes
before the last sep, when two or more columns share it); name instead treats every
column as one entity of a single series (a sheet with a column per country). Columns that
match no stub are kept, the same for every entity (e.g. a world price).
xs
¶
xs(**levels: Any) -> Dataset
One value of some axes, dropping them: xs(country="FJI") is Fiji's time series,
xs(time="2020Q1") a cross-section.
entity
¶
entity(value: Any, by: str | None = None) -> Dataset
One entity's data, without the entity axis (for a panel: its time series).
cross_section
¶
cross_section(period: Any) -> Dataset
All entities in one period, without the time axis.
as_of
¶
as_of(when: Any, lags: Mapping[str, int] | None = None, calendar: Any = None) -> Dataset
The data as known on when: values not yet published (period end plus each series' release_lag
days, or the release dates of a ReleaseCalendar) removed. See pymetrix.nowcast.
ragged_edge
¶
ragged_edge(when: Any = None, lags: Mapping[str, int] | None = None) -> Table
Each series' last observation, publication lag and publication day. See pymetrix.nowcast.
fill_edge
¶
fill_edge(lags: int = 2, through: Any = None, names: Sequence[str] | None = None) -> Dataset
Missing values at the end of each series (or of names) forecast by an AR(lags) of the series, up to
through (default: the last period of any series). See pymetrix.nowcast.fill_edge.
realign
¶
realign() -> Dataset
Vertical realignment: each series shifted on so that its last value falls in the latest period any series
has. See pymetrix.nowcast.realign.
coverage
¶
coverage(*names: str) -> Table
For each entity: the first and last periods with data (on every series named; default all), the observations, and the gaps between them.
balance
¶
balance(*names: str, keep: Literal['periods', 'entities'] = 'periods', by: str | None = None) -> Dataset
A balanced panel: keep the periods in which every entity has data on the series named
(default all), or the entities that have data in every period.
complete
¶
complete() -> Dataset
Add the missing rows (as missing values) so that every entity has every period from the first to the last.
describe_panel
¶
describe_panel(*names: str, by: str | None = None) -> Table
Overall, between-entity and within-entity variation of each series: mean, standard deviation, minimum and maximum, with observations (N), entities (n) and average periods (T).
validate
¶
Check the data before using them: duplicate rows, missing periods, infinite values, text among numbers
(errors); missing values inside a series, constant series, outliers (warnings); missing units or vintages and
ragged edges (notes). A Validation; strict raises DataError if there are errors.
in_sample
¶
The rows of the active sample (all rows without one): what tables and graphs show by default.
describe
¶
describe(names: str | Sequence[str] | None = None, percentiles: Sequence[float] = (0.25, 0.5, 0.75)) -> Table
Count, mean, standard deviation, minimum, percentiles (default the quartiles; the median is always
shown), maximum, skewness and excess kurtosis of each series (default every numeric one), over the active
sample. Skewness and kurtosis are the bias-corrected sample statistics (pandas' skew and kurt,
scipy's skew and kurtosis with bias=False); kurtosis is in excess of the normal's 3.
corr
¶
corr(names: Sequence[str] | None = None, method: Literal['pearson', 'spearman', 'kendall'] = 'pearson') -> Table
Correlations between series (default every numeric one) over the active sample, each pair over the
periods both have: pearson (linear), spearman (of ranks) or kendall (tau-b, of concordant pairs).
cov
¶
cov(names: Sequence[str] | None = None) -> Table
Covariances between series (default every numeric one) over the active sample, each pair over the periods both have, with the n - 1 denominator.
partial_corr
¶
partial_corr(names: Sequence[str], given: str | Sequence[str] = ()) -> Table
Partial correlations between names holding the series given constant: the correlations of their
residuals from least-squares regressions on a constant and given, over the periods all of them have.
coskewness
¶
coskewness(names: str | Sequence[str] | None = None, standardized: bool = True, form: Literal['matrix', 'pairs'] = 'matrix') -> Table
Co-skewness of series (default every numeric one) over the periods every one has in the active sample.
With e the deviations from the means divided by the standard deviations (both with the T denominator),
the co-skewness of i, j and k is S_ijk = mean(e_i e_j e_k). form="matrix" gives every S_ijk as the
n x n² matrix M3 = E[e (e ⊗ e)'] (row i, column "j,k"), as in portfolio choice with higher moments;
form="pairs" the n x n table of S_iij = mean(e_i² e_j) (row i, column j), the co-skewness usually reported
for two assets. The diagonal is each series' skewness with the T denominator (scipy's skew); describe
shows the bias-corrected skewness, G1 = g1 √(T(T-1))/(T-2). standardized=False gives the co-moments of
the deviations themselves, mean((x_i - x̄_i)(x_j - x̄_j)(x_k - x̄_k)).
cokurtosis
¶
cokurtosis(names: str | Sequence[str] | None = None, standardized: bool = True, form: Literal['matrix', 'pairs'] = 'matrix') -> Table
Co-kurtosis of series (default every numeric one) over the periods every one has in the active sample.
With e the standardized deviations (T denominator), the co-kurtosis of i, j, k and l is
K_ijkl = mean(e_i e_j e_k e_l). form="matrix" gives the n x n³ matrix M4 = E[e (e ⊗ e ⊗ e)'] (row i,
column "j,k,l"); form="pairs" the n x n table of K_iiij = mean(e_i³ e_j) (row i, column j). The diagonal is
each series' kurtosis with the T denominator and not in excess (3 for a normal; scipy's kurtosis with
fisher=False); describe shows bias-corrected excess kurtosis, G2 = ((T+1)(b2 - 3) + 6)(T-1)/((T-2)(T-3)) for b2 this kurtosis.
standardized=False gives the fourth co-moments of the deviations themselves.
systematic_comoments
¶
systematic_comoments(names: str | Sequence[str], market: str) -> Table
Each series' beta, co-skewness and co-kurtosis with a market series, over the periods all have in the active sample (moments with the T denominator; d the deviations from the means):
- beta = mean(d_i d_m) / mean(d_m²);
- co-skewness = mean(d_i d_m²) / (σ_i σ_m²) and co-kurtosis = mean(d_i d_m³) / (σ_i σ_m³), standardized;
- co-skewness beta = mean(d_i d_m²) / mean(d_m³) and co-kurtosis beta = mean(d_i d_m³) / mean(d_m⁴), the series' share of the market's skewness and kurtosis (Kraus and Litzenberger 1976; Fang and Lai 1997).
A negative co-skewness means the series does badly when the market makes large moves; investors averse to that demand a higher return (Harvey and Siddique 2000).
crosscorrelogram
¶
crosscorrelogram(x: str, y: str, lags: int = 12) -> Table
Cross-correlations corr(x(t), y(t+k)) for k = -lags ... lags, over the periods both series have: a large value at k > 0 means x moves ahead of y. Each uses the full-sample means and standard deviations, with the sum divided by T (as the autocorrelations of a correlogram are), so the table is a proper correlation function; the 95% band for no correlation is ±1.96/√T.
autocov
¶
autocov(name: str, lags: int = 20) -> Table
Autocovariances of one series at lags 0 ... lags (the sum divided by T, as for the autocorrelations of
a correlogram), with the autocorrelations they give.
filter
¶
filter(names: str | Sequence[str], method: Any, derived: bool = True) -> Dataset
Add {name}_trend and {name}_cycle from a trend-cycle filter (HP, BaxterKing, ...).
By default they are derived series, recomputed when name changes;
derived=False stores plain values.
seasonal_adjust
¶
seasonal_adjust(names: str | Sequence[str], method: Any = None, derived: bool = True) -> Dataset
Add {name}_sa (seasonally adjusted) and {name}_seasonal (the seasonal factor, or
component when additive), by method: STL() (the default), X13(), TramoSeats() or Classical().
By default they are derived series, recomputed when name changes.
calendar
¶
calendar(trading_days: str = 'six', easter: int | None = 8, leap_year: bool = True) -> Dataset
Add calendar regressors for monthly or quarterly data: trading days ("six" contrasts
td_mon ... td_sat, "one" weekday contrast td_weekdays, or "none"), easter_{w}
and leap_year, as defined by X-13ARIMA-SEATS.
correlogram
¶
correlogram(name: str, lags: int = 20) -> Table
Autocorrelations, partial autocorrelations and Ljung-Box Q statistics of one series.
select_order
¶
select_order(name: str, max_ar: int = 4, max_ma: int = 2, exog: Sequence[str] = (), intercept: bool = True, span: Span | None = None) -> Any
Compare ARMA(p, q) models for name by AIC, BIC and Hannan-Quinn.
johansen
¶
johansen(variables: Sequence[str], lags: int = 1, det_order: Literal[-1, 0, 1] = 0, signif: float = 0.05, span: Span | None = None) -> Any
Johansen cointegration tests (trace and maximum eigenvalue) for variables.
plot
¶
plot(names: str | Sequence[str] | None = None, kind: str = 'line', layout: str = 'one', span: Span | None = None, entity: Any = None, title: str = '', stacked: bool = False, right: str | Sequence[str] = (), transform: str = 'none', shade: Any = (), total: str | None = None, coverages: Sequence[float] | None = None, bins: int | None = None, **options: Any) -> Figure
A figure of series.
kind: line, step, bar (side by side), barh (horizontal bars), area, scatter (x first, then y), histogram,
box, contributions (the series as stacked parts; total names the series they add up to, else their sum is
drawn), fan (each series with its bands from {name}_lo90/{name}_hi90 or {name}_se columns, at
coverages such as (0.3, 0.6, 0.9)), vintages (each series a release of the same data, oldest first),
correlation (a heatmap of the series' correlations), ecdf (each series' empirical distribution, in one panel),
hist2d (a two-dimensional histogram of y against x, x first), violin (each series' density, as box plots),
hexbin (hexagonal bins of y against x, x first) or surface (the series side by side along x, the dates along y,
the values as heights, in 3-D: a yield curve over time). bins: for histogram and hist2d, or the hexagons
across for hexbin. layout: one panel, or each series in its own. stacked stacks bars or areas (negative values below
zero, as contributions do). right names series to draw against a right-hand axis. transform: none,
index (first period shown = 100), change, growth (% on the previous period), yoy (% on a year earlier) or log.
shade shades periods: "2008Q3:2009Q2, 2020Q1:2020Q2" (a label after =), or the name of a 0/1 series
such as recession dates. Other keywords are the figure's options (see Figure.with_options): events
("2016Q2=Brexit vote"), reference ("2=inflation target"), log, ylim, sharey,
bar_labels, subtitle, footnote, theme and others. For a panel dataset, choose an entity, or plot one series with a line per entity; a cross-section's
entities label its bars. Forecasts (with intervals) are drawn as such.
Matrix
dataclass
¶
A two-dimensional array of numbers with names for its rows and columns.
from_frame
classmethod
¶
from_frame(frame: DataFrame | Series, title: str = '') -> Matrix
A matrix from a pandas table (or a series, as a column), named by its index and columns.
identity
classmethod
¶
identity(names: int | Sequence[str]) -> Matrix
The identity matrix, of size n or with these names for both its rows and columns.
from_dataset
classmethod
¶
from_dataset(data: Any, names: str | Sequence[str] | None = None, span: Any = None, title: str = '') -> Matrix
Series of a dataset as the columns of a matrix, its rows named by period (None: every series; span:
the active sample when None, as commands use, or "all" or a span). Missing values stay missing.
coef
classmethod
¶
coef(result: Any) -> Matrix
A result's estimates as a column vector, its rows named by the parameters.
cov
classmethod
¶
cov(result: Any) -> Matrix
A result's covariance matrix of the estimates, rows and columns named by the parameters.
var_lag
classmethod
¶
var_lag(result: Any, lag: int) -> Matrix
A VAR's coefficient matrix at lag (1 = the first): rows are the equations, columns the variables.
design
classmethod
¶
The regressors X and the dependent variable y of a formula on the data's sample, rows named by period.
to_frame
¶
The matrix as a pandas table (or one of its window's views by name, as for every result).
to_dataset
¶
A matrix whose rows are periods (as from_dataset and design name them) as a Dataset, a series for
each column.
to_latex
¶
The matrix as LaTeX: a plain bmatrix (amsmath) of its numbers, or with names=True a tabular
with the column names on top and the row names down the left (underscores and the like escaped), for a
matrix whose names matter. Numbers to digits significant digits; complex ones as a+bi.
set
¶
set(rows: Any, cols: Any, value: Any) -> Matrix
A new matrix with an element or a block replaced (m.set("y", "c", 0.5), m.set(["a", "b"], :, B)
with slice(None) for every column). A named block must have the names of the rows and columns it goes
into; a number fills the block.
hcat
classmethod
¶
hcat(*parts: Any) -> Matrix
Matrices side by side: their rows must meet, and their columns may not share a name.
vcat
classmethod
¶
vcat(*parts: Any) -> Matrix
Matrices one above the other: their columns must meet, and their rows may not share a name.
power
¶
power(n: int) -> Matrix
The matrix power of a square matrix: A.power(2) is A @ A, A.power(0) the identity and
A.power(-2) is A.inv().power(2) (numpy.linalg.matrix_power). A negative power is named as the
inverse is (rows by the columns, columns by the rows).
named
¶
named(rows: Sequence[str] | None = None, cols: Sequence[str] | None = None) -> Matrix
The same numbers with other names.
chol
¶
chol(upper: bool = False) -> Matrix
The lower triangular L with L @ L.T equal to the matrix (symmetric and positive definite), or with
upper=True the upper triangular R with R.T @ R equal to it (MATLAB's chol). Named as the matrix.
eig
¶
Eigenvalues (a column eigenvalue, rows λ1, λ2, ..., largest first in size) and eigenvectors (columns
λ1, λ2, ..., rows named as the matrix's rows), so that A @ v = λ v. symmetric=None (the default)
uses numpy.linalg.eigh for a symmetric matrix (real values, orthonormal vectors) and
numpy.linalg.eig otherwise; True insists on a symmetric matrix, False uses the general method.
The general method's results are real when every imaginary part is below 1e-12 (relative to the largest
eigenvalue) and complex otherwise; a conjugate pair keeps NumPy's order.
eigh
¶
The eigenvalues and orthonormal eigenvectors of a symmetric matrix (eig(symmetric=True)).
svd
¶
The thin singular value decomposition A = U diag(s) V': U (rows: A's rows), s (a column,
largest first) and V (rows: A's columns), all named s1, s2, ... for the k = min(m, n) singular values.
qr
¶
The thin QR decomposition A = Q R: Q's rows are A's rows, R's columns A's columns, both named q1, q2,
... between.
lu
¶
A = P L U with partial pivoting (scipy.linalg.lu). P's rows are A's rows and its columns the same
names in pivot order, which name L's rows; L's columns and U's rows are l1, l2, ...; U's columns are A's.
schur
¶
The Schur decomposition A = Q T Q' (scipy.linalg.schur): real, with 2 x 2 blocks on T's diagonal
for complex pairs, or complex=True for triangular T. Q's rows are A's rows; T and Q's columns are u1, u2,
... (the Schur vectors).
qz
¶
The generalized Schur (QZ) decomposition of the pencil (A, B) (scipy.linalg.qz, real):
A = Q AA Z' and B = Q BB Z'. B must have A's names (or none); Q's rows are their rows, Z's rows
their columns, and AA and BB have rows q1, ... and columns z1, ....
expm
¶
expm() -> Matrix
The matrix exponential (scipy.linalg.expm), named as the matrix (as A.power(2) is).
logm
¶
logm() -> Matrix
The principal matrix logarithm (scipy.linalg.logm): real when it has a real value, complex otherwise.
sqrtm
¶
sqrtm() -> Matrix
The principal square root S with S @ S = A (scipy.linalg.sqrtm): real when it has a real value.
norm
¶
A matrix norm: "fro" (Frobenius, the default), "nuc" (nuclear), 1 and "inf" (the largest
column and row sums of absolute values), 2 (the largest singular value), as numpy.linalg.norm.
cond
¶
The condition number in a norm (the 2-norm by default: largest over smallest singular value).
null
¶
null(rcond: float | None = None) -> Matrix
An orthonormal basis of the null space (x with A @ x = 0): rows named by A's columns, columns null1,
null2, .... rcond: singular values below it times the largest count as zero (default as SciPy's).
orth
¶
orth(rcond: float | None = None) -> Matrix
An orthonormal basis of the column space: rows named by A's rows, columns orth1, orth2, ....
perp
¶
perp(rcond: float | None = None) -> Matrix
The orthogonal complement A⊥ of an m x r matrix of rank r: m x (m - r), with A⊥' A = 0 and
[A A⊥] of full rank m, as for a VECM's alpha-perp and beta-perp. Normalised to orthonormal columns
(A⊥' A⊥ = I), the left null space from the SVD, as MATLAB's null(A'); Johansen (1995) defines A⊥ only
up to an invertible r x r factor, which cancels in the expressions it enters (such as the long-run impact
β⊥ (α⊥' Γ β⊥)^-1 α⊥'). Rows are A's rows; columns perp1, perp2, ....
sum
¶
The sum of everything (a number), of each column (axis=0: a row named sum) or of each row
(axis=1: a column named sum).
mean
¶
The mean of everything, of each column (axis=0) or of each row (axis=1), named mean.
outer
¶
outer(other: Any) -> Matrix
The outer product a b' of two vectors: rows named by a's names, columns by b's.
inner
¶
The inner product a' b of two vectors with the same names, or the sum of the element-by-element
products (trace(A' B)) of two matrices with the same names. Not conjugated.
vech
¶
vech() -> Matrix
The lower triangle (with the diagonal) of a square matrix, column by column, into one column; each row named "row,column".
unvech
classmethod
¶
unvech(v: Any, names: Sequence[str] | None = None) -> Matrix
The symmetric matrix whose vech is v (n(n+1)/2 numbers). Named by names, or by the names in v's
rows when v came from vech of a matrix with the same row and column names, or numbered.
commutation
classmethod
¶
commutation(m: int | Sequence[str], n: int | Sequence[str]) -> Matrix
The commutation matrix K (mn x mn) with K @ A.vec() = A.T.vec() for an m x n matrix A. Given names
(A's rows and columns) instead of sizes, K is named so that the product's names meet: columns as
A.vec()'s rows, rows as A.T.vec()'s.
duplication
classmethod
¶
duplication(n: int | Sequence[str]) -> Matrix
The duplication matrix D (n² x n(n+1)/2) with D @ A.vech() = A.vec() for a symmetric n x n A. Given
A's names instead of n, its columns are named as vech's rows and its rows as vec's.
elimination
classmethod
¶
elimination(n: int | Sequence[str]) -> Matrix
The elimination matrix L (n(n+1)/2 x n²) with L @ A.vec() = A.vech() for any n x n A; named, given
names, as the transpose of duplication.
lyapunov
classmethod
¶
lyapunov(A: Any, Q: Any, continuous: bool = False) -> Matrix
X with X = A X A' + Q (discrete, the default; e.g. the unconditional variance of y = A y[-1] + e
with var(e) = Q, by scipy.linalg.solve_discrete_lyapunov), or with A X + X A' + Q = 0
(continuous=True). X is named as Q. A's rows must meet Q's; its columns are taken to be the same
variables (a VAR's lag matrix has columns such as y[-1]). Explosive A is not refused: X then solves the
equation but is no variance.
sylvester
classmethod
¶
sylvester(A: Any, B: Any, C: Any) -> Matrix
X with A X + X B = C (scipy.linalg.solve_sylvester), named as C. C's rows must meet A's rows and
C's columns B's columns; A's columns and B's rows are taken to be the same names (A X and X B add up).
riccati
classmethod
¶
riccati(A: Any, B: Any, Q: Any, R: Any) -> Matrix
The stabilising X of the discrete algebraic Riccati equation
X = A' X A - A' X B (R + B' X B)^-1 B' X A + Q (scipy.linalg.solve_discrete_are): the cost-to-go of
the linear-quadratic regulator, or, with A = T', B = Z', Q = R Q R' and R = H, the
steady-state prediction covariance of the Kalman filter. A (n x n), B (n x k), Q (n x n), R (k x k); B's
rows must meet A's rows, Q's A's, and R's B's columns. X is named as Q.
pymetrix.extension.EViewsBinary
dataclass
¶
left op right: an arithmetic operator (+ - * / ^) or a comparison (< > <= >= <> =).
pymetrix.extension.EViewsCall
dataclass
¶
A function call: fn as written in lower case ("dlog", "@pch") and its argument nodes.
pymetrix.extension.EViewsCoefficient
dataclass
¶
A coefficient vector(index), such as c(2).
pymetrix.extension.EViewsName
dataclass
¶
A series or scalar name (lower case) at lag (negative: a lag, positive: a lead), spanning length
characters from at.
pymetrix.extension.EViewsNumber
dataclass
¶
A number as written (text), at offset at.
ReleaseCalendar
dataclass
¶
ReleaseCalendar(table: DataFrame, releases: Mapping[str, tuple[str, ...]] = dict(), source: str = '')
When each figure was published: table has a row per series and period (series, period as text,
date, release: the release it came out in, the series' own name when it is in none). releases lists
each release's series. source says how the calendar was made.
from_table
classmethod
¶
from_table(table: Any, releases: Mapping[str, Sequence[str]] | None = None) -> ReleaseCalendar
From a table (a CSV file or a DataFrame) with a series or a release column, a period (2025-01,
2025Q1) and a release date. A row naming a release in releases stands for each of its series; a row
with both a series and a release puts the series in that release.
from_lags
classmethod
¶
from_lags(*data: Dataset, lags: Mapping[str, int] | None = None, releases: Mapping[str, Sequence[str]] | None = None) -> ReleaseCalendar
Each period of each series of data published its period's last day plus the series' publication lag
(Variable.release_lag, or lags; none: on the period's last day): the fixed-lag rule as_of uses.
from_vintages
classmethod
¶
from_vintages(vintages: Any, releases: Mapping[str, Sequence[str]] | None = None) -> ReleaseCalendar
From vintage tables (read_vintages; one, or a dict from series to each): each period's release date is
the first vintage in which it has a value. With ALFRED's vintages (each release date of the series), that is the
day the figure first came out.
merge
¶
merge(other: ReleaseCalendar) -> ReleaseCalendar
This calendar with other's rows added (other wins where both list a series and period).
release_of
¶
The release series is published in (its own name when it is in none).
release_date
¶
The day series' value for period was published (NaT when the calendar does not say).
published
¶
For each period of index, the day series' value was published: the calendar's date, or the period's
last day plus fallback days where it has none (NaT without a fallback).
for_data
¶
for_data(data: Dataset) -> ReleaseCalendar
The calendar with rows for data's series made from others (with_series) that it does not list: each
period published on the latest day of the series its formula names, in their release (the last one's).
between
¶
The figures published from first to last (both included): date, release, series and period.
upcoming
¶
The next n release days after after: date, release and the series and periods it publishes.
release_days
¶
The days on which anything was published (between first and last).
to_frame
¶
The release dates (series, period, date, release), or the table of the window's view.
plot
¶
Days from each period's end to its release, by series: how the delay moves around.
Sample
¶
Sample(span: tuple[Any, Any] | None = None, *, start: Any = None, end: Any = None, where: str | None = None, windows: Mapping[str, tuple[Any, Any]] | None = None, **levels: Any)
A selection of periods, entities and rows: see the module docstring.
Selection
dataclass
¶
Bases: Sequence[str]
An ordered set of series names.
format
¶
format(template: str) -> Selection
New names from a template: s.format("d{s}") -> dc, di, dg.
formulas
¶
{new name: formula} for each series, for derive or with_series:
data.derive(**s.formulas("d{s}", "dlog({s})")).
map
¶
map(fn: Callable[[str], Any], errors: str = 'raise') -> Results
fn(series) for each series. errors="collect" keeps going and records failures.
fit
¶
Estimate the equation formula (with {s}) for each series: s.fit("{s} ~ {s}[-1]", data).
Options (method=, span=...) go to Equation.fit.
Functions¶
as_dataset (also dataset)
¶
value as a Dataset: a Dataset unchanged; a DataFrame with a PeriodIndex, with dates that have a
frequency, or with a MultiIndex of entities and one period level, converted (each series recorded as coming
from user:pandas). Anything else is refused with a message saying how to make a dataset.
as_selection
¶
Series names as a Selection: a Selection unchanged; a list or tuple of names; one name; or, with data,
a pattern such as "*_cycle". A string is one name (or a pattern if it has * or ?), never split
at commas.
eviews_series
¶
data with the series the EViews reader made of @trend, @elem and @seas (the exogenous variables
of model, a Model or a template, named trend_<base>, trend_start, <x>_at_<date> and seas_<n>),
worked out from the data's dates: @trend(base) the periods since the base (60:1 in the data's own
frequency), @trend alone from the data's first period, @elem(x, date) x's value at that date in every
period, @seas(n) 1 in the n-th period of the year. Series the data already has are kept as they are.
fit_each
¶
fit_each(names: SelectionLike, formula: str, data: Dataset, errors: str = 'raise', **fit_options: Any) -> Results
Selection.fit for any list of names: fit_each(["c", "i"], "d{s} ~ d{s}[-1]", data).
pymetrix.extension.eviews_blank_comments
¶
Comments (' to the end of the line, outside double quotes) replaced by spaces: positions stay.
pymetrix.extension.eviews_statements
¶
Each statement and its offset; a line ending in _ continues on the next (same length: offsets stay).
pymetrix.extension.parse_eviews_expression
¶
One EViews expression as a tree of nodes whose offsets are base plus the text's own; vectors are the
coefficient vectors ({"c"} at least); comparison lets the whole be a comparison. _Refused where it does
not read.
pymetrix.extension.render_eviews_expression
¶
_render(node: Any, scalars: tuple[str, ...] = (), frequency: str | None = None, *, data: bool = False, seeds: Callable[[], int] | None = None) -> str
A parsed expression (_parse) as pymetrix's text, as convert_expression writes it; _Refused (with
the place) where it does not translate. Public as pymetrix.extension.render_eviews_expression. data: an
expression for data work (the data's calendar, cumulative and by-group statistics read; a model refuses them);
seeds: called for each random draw's seed (without it, random draws are refused).
pymetrix.extension.walk_eviews_expression
¶
A tree's nodes, the root first, then each child's in order.
read_eviews
¶
read_eviews(source: str | Path, params: Mapping[str, float] | None = None, data: Any = None, span: Any = None, name: str | None = None, frequency: str | None = None) -> Any
Read an EViews model's text or program (a path to a .prg or .txt file, or the text) into a Template:
see the module docstring. params gives coefficient and scalar values ({"c_1": 0.5} or {"c(1)": 0.5}),
winning over the text's; data (a Dataset) fits the equation eq.ls specifications by least squares, on their
smpl or span. frequency ("Q", "M", "A") is the data's, for @pchy and the like, when neither the
text (wfcreate, a dated smpl) nor data says it. Series that @trend, @elem and @seas stand for
are made from a dataset's dates by eviews_series. Refused, with the first problems and their places, when the
text has errors.
read_tcodes
¶
The transformation codes of a FRED-MD or FRED-QD file: the row whose first cell is "Transform:", by column.
read_vintages
¶
read_vintages(series: str, vintages: Sequence[Any] | None = None, start: Any = None, end: Any = None, api_key: str | None = None) -> VintageTable
Every ALFRED vintage of FRED series series (e.g. "GDPC1"), or the data as they stood on each day of
vintages: a VintageTable with a row per period and a column per vintage date. start and end
(periods) keep the periods between them. Needs a FRED API key (FRED_API_KEY, set_api_key, or api_key,
which is used for the request only and never kept).
recession_series
¶
1 in recession periods and 0 otherwise, for the periods of data (a dated dataset, Series or PeriodIndex),
named <source>_recession; periods before the committee's first date are 0.
recessions
¶
The recessions as (first period, last period, label) at freq: from the period after each peak through the
trough. Monthly and quarterly use the committee's own dates at that frequency where it publishes them; other
frequencies (and a frequency it does not date at) cover the same span of time.
register_sdmx_provider
¶
Add an SDMX web service, e.g. an institution's own: url has {flow} and {key} placeholders
and returns SDMX-CSV or SDMX-ML structure-specific data. structure_url, the service's REST root (where
/dataflow/{agency} answers), makes its dataflows searchable in the Series browser; agency is the
maintenance agency to list ("all" for every one).
revision_analysis
¶
revision_analysis(vintages: VintageTable, releases: int = 4, final: Any = 'latest', periods: tuple[Any, Any] | None = None) -> RevisionAnalysis
Revisions of a series from its vintages: from the first release to releases 2 ... releases and to the
final value ("latest" or a release number), over the periods between periods (first, last); and Mankiw
and Shapiro's news and noise regressions of the total revision (first release to final).
test_each
¶
test_each(names: SelectionLike, data: Dataset, test: str, *args: Any, errors: str = 'raise', **options: Any) -> Results
Selection.test for any list of names: test_each(["c", "i"], data, "adf", lags=4).
Results¶
Results
¶
Bases: Mapping[str, Any]
Results by series (or by any name), in order, with side-by-side tables.
RevisionAnalysis
dataclass
¶
RevisionAnalysis(variable: str, by_release: DataFrame, tests: DataFrame, revisions: DataFrame, vintages: VintageTable, final: str = 'latest', provenance: Any = None)
How a series' figures were revised: by_release (from the first release to each later one and to the final
value: n, mean, standard deviation, mean absolute revision, the noise-to-signal ratio and the t statistic of the
mean), and tests (Mankiw and Shapiro's news and noise regressions of the total revision).
VintageTable
dataclass
¶
A series' vintages: values has a row per reference period (a period index) and a column per vintage date
(the day that vintage was published), each column the series as it stood from that day to the next vintage.
source says where it came from; retrieved when.
from_datasets
classmethod
¶
from_datasets(vintages: Mapping[Any, Dataset], variable: str, source: str = 'datasets') -> VintageTable
From datasets of the same series as published on several days: {vintage date: dataset}.
vintage_on
¶
The date of the vintage in force on when (the latest published on or before it); None if none was.
as_of
¶
The series as it stood on when: the latest vintage published on or before that day (all missing if none
was).
release
¶
Each period's k-th release (1: the first): its value in the k-th vintage that has a value for it.
first_release_dates
¶
The day each period's first value was published (the first vintage that has it).
triangle
¶
The revision triangle: a row per period, a column per release number (1: first, 2: second...), each the
period's value in that vintage that has it. releases: the most to keep.
revisions
¶
Each period's total revision: its final value ("latest", or a release number) less its first release.
transform
¶
transform(how: str, scale: float | None = None) -> VintageTable
Each vintage transformed alike, within the vintage: "dlog" (log difference), "pch" (percent change),
"d" (difference), or "400*dlog"-style with a factor in front; scale multiplies the result.
to_frame
¶
The vintages (rows: periods; columns: vintage dates as text), or the table of the window's view.
to_dataset
¶
to_dataset(when: Any = None) -> Dataset
The series as a dataset: as of when (default: the latest vintage).
plot
¶
The revision triangle of the last periods periods: each release less the first, by release number.
Other names¶
CodeList
dataclass
¶
pymetrix.extension.EViewsExpressionError
¶
Bases: SpecificationError
Text the reader refuses: why, and where (an offset in the document, and how many characters).