Skip to content

Extension API

What a plugin imports from pymetrix besides the names above: the extension API (pymetrix.extension) and the stable modules it names (pymetrix.extension.STABLE), each name under the module it is imported from. Plugins describes how a plugin is made.

Classes

pymetrix.commands.AddFactors dataclass

AddFactors(equations: Annotated[str, Widget('object', source=MODEL_PARTS, multiple=True, help='the model: fitted equations and identities, or a model read (FRB/US XML)')], data: Annotated[str, Widget('object', source='Dataset', help='the data to track: every variable of the model')] = 'data', start: Annotated[str, Widget('period', group='Span', help='the first period; empty = from where they can be computed')] = '', end: Annotated[str, Widget('period', group='Span', help='the last period; empty = to the end of the data')] = '', name: str = 'add_factors', params: Annotated[str, Widget('text', advanced=True, help='values for the parameters of equations not estimated, e.g. b=0.99')] = '')

Bases: Command

Tracking add factors: each equation's residual at the data in each period of a span, as EViews's addinit sets them. Solved with them (Model > Solution > Solve model, Scenario, Add factors) the model reproduces the data exactly, under any solver, so a scenario's other changes read as deviations from that baseline.

Over a projection's span (a baseline such as the Fed's LONGBASE), the add factors make the model track it; over a historical span, they are the equations' historical errors, by period, which a stochastic simulation can resample (Model > Solution > Solve model, Advanced, Error draws: The data's residuals). Every variable of the model needs values in the span; an equation's add factor is missing where its lags reach before the data.

pymetrix.commands.AddToDataset dataclass

AddToDataset(source: Annotated[str, Widget('object', source='FittedEquation,FittedVAR,FittedVECM,FittedStateSpace,FittedPCA,FittedFactorModel,Dataset', help='a fit, a forecast, principal components or a factor analysis, or another dataset')], item: Annotated[str, Widget('item', depends_on='source', help='residuals, fitted values, volatility, or a column')], data: Annotated[str, Widget('object', source='Dataset', help='the dataset to add the series to (it is replaced by the extended one)')] = 'data', series_name: Annotated[str, Widget('text', help="name of the new series; empty = the source's name and the item's")] = '', replace: Annotated[bool, Widget('checkbox', help='replace a series of the same name, if there is one')] = False)

Bases: Command

Add residuals, fitted values, volatilities, forecast columns, components or factor scores to a dataset as new series.

Choose the source object and the item to add. The dataset is replaced by an extended copy; give the new series a name or accept source_item.

pymetrix.commands.AdjustRound dataclass

AdjustRound(round: Annotated[str, Widget('object', source='ForecastRound', help='the round to adjust; the path before judgement is kept')], variable: Annotated[str, Widget('text', help="one of the round's variables; only its path changes, not others linked to it")], changes: Annotated[str, Widget('text', help='period=value, ... e.g. 2026Q4=-0.3, 2027Q1=-0.1')], reason: Annotated[str, Widget('text', help="why: part of the forecast's record")], how: Annotated[Literal['add', 'set'], Widget('choice', help='add to the path, or set it')] = 'add')

Bases: Command

Judgement: change a round's path of one variable in some periods, with the reason.

Write the changes as period=value, separated by commas (2026Q4=-0.3, 2027Q1=-0.1). Add adds them to the path; Set replaces it. Every change is logged with the path before it.

pymetrix.commands.AggregateEntities dataclass

AggregateEntities(data: Annotated[str, Widget('object', source='Dataset', help='the panel (or any dataset) to aggregate')] = 'data', by: Annotated[str, Widget('level', depends_on='data', multiple=True, help='what to keep: the time axis for a total per period; add a category (region) for one per group')] = '', how: Annotated[Literal['', 'sum', 'mean', 'first', 'last'], Widget('choice', help="how the rows combine: sum, average, first or last; by measure, as each series' metadata says")] = '', name: str = 'aggregated', rules: Annotated[str, Widget('text', advanced=True, show_if=('how', ('',)), label='Series rules', help='rules for some series, overriding their measure: gdp=sum, rate=mean (sum, mean, first, last, min, max or median)')] = '')

Bases: Command

Add up (or average) a panel over its entities: the countries' GDP summed into a world total, period by period.

Keep the axes or categories under By: the time axis gives one total per period; a category such as region as well gives one per region and period. Every other row is combined: by measure, flows, counts and stocks are summed, rates, indices and ratios averaged (an unweighted average: for a weighted one, derive the weighted series first). A series without a measure needs a rule (Advanced) or one choice for all.

pymetrix.commands.BalancePanel dataclass

BalancePanel(data: Annotated[str, Widget('object', source='Dataset')] = 'data', series: Annotated[str, Widget('series', depends_on='data', multiple=True, help='series that must be present; empty = all')] = '', keep: Annotated[Literal['periods', 'entities'], Widget('choice', help='periods: drop periods with gaps; entities: drop entities with gaps')] = 'periods', name: str = 'balanced')

Bases: _OnData

Make a balanced panel: keep the periods in which every entity has data on the chosen series, or the entities that have data in every period. Use Panel statistics (coverage) to see what is missing first.

Some estimators and tests need a balanced panel, but balancing throws data away, and the choice of which matters: dropping periods shortens every series, dropping entities narrows the cross-section. If whether an entity has gaps is related to the outcome (a firm leaving because it is doing badly), the balanced panel is a selected sample and estimates on it can be biased. Choose only the series the analysis uses, so that gaps in other series do not cost observations. A missing entity-period counts as a gap even when the row is absent altogether.

pymetrix.commands.BinaryForecastScores dataclass

BinaryForecastScores(probabilities: Annotated[str, Widget('series', depends_on='data', help='the forecast probabilities of the event, between 0 and 1')], outcomes: Annotated[str, Widget('series', depends_on='data', help='what happened: 1 for the event, 0 otherwise')], data: Annotated[str, Widget('object', source='Dataset', help='the dataset holding both series; its active sample applies')] = 'data', threshold: Annotated[float, Widget('number', min=0.01, max=0.99, step=0.05, help='forecast the event when the probability is at least this (hit and false-alarm rates)')] = 0.5, name: str = 'binary_scores_result')

Bases: Command

Scores of probability forecasts of a 0/1 event (a recession, a default): the Brier score and the base rate's, the log score, the area under the ROC curve, and the hit rate, false-alarm rate and Kuipers score of forecasting the event when the probability reaches a threshold.

Both series are in one dataset: the forecast probabilities (between 0 and 1) and what happened (0 or 1), over its active sample; periods missing either are dropped. The Brier score is lower for better forecasts; compare it with the base rate's (always forecasting the share of events), which a useful forecast must beat. The ROC area is the chance that an event got a higher probability than a non-event: 0.5 is no skill. The hit and false-alarm rates depend on the threshold, and the Kuipers score is their difference.

pymetrix.commands.CalendarRegressors dataclass

CalendarRegressors(data: Annotated[str, Widget('object', source='Dataset')] = 'data', trading_days: Annotated[Literal['six', 'one', 'none'], Widget('choice', help='six contrasts, one weekday contrast, or none')] = 'six', easter: Annotated[int, Widget('number', min=0, max=25, help='days before Easter in the window; 0 = no Easter regressor')] = 8, leap_year: Annotated[bool, Widget('checkbox', help='add a regressor for the extra day in February of leap years (monthly and quarterly data)')] = True)

Bases: Command

Add trading-day, Easter and leap-year regressors (X-13ARIMA-SEATS definitions) for use in equations.

Six trading-day contrasts (td_mon ... td_sat: each weekday's count less Sundays), or one (td_weekdays: weekdays less 5/2 of weekend days); easter_w, the share of the w days before Easter in the period; leap_year.

pymetrix.commands.Calibrate dataclass

Calibrate(equations: Annotated[str, Widget('object', source='FittedEquation,Equation', multiple=True, help="the model's equations and identities; their calibrated parameters can be free")], targets: Annotated[str, Widget('text', help='expressions of the variables and their values, separated by ; e.g. k/y = 10; c/y = 0.75')], free: Annotated[str, Widget('text', help='one parameter for each target, e.g. beta, delta')], params: Annotated[str, Widget('text', help="values of the model's parameters, e.g. alpha=0.33, beta=0.99, delta=0.025")] = '', growth: Annotated[bool, Widget('checkbox', help='a trending model: targets on its balanced growth path')] = False, name: str = 'calibration')

Bases: Command

Choose parameters so that the model's steady state hits targets: levels, ratios or spreads of its variables.

Give one target for each free parameter, e.g. targets "k/y = 10; c/y = 0.75" with free parameters "beta, delta". Tick growth for a trending model (the targets then apply on its balanced growth path). The result holds the model with the parameters found, its steady state, and each target with the value reached.

Calibration makes the model match the chosen long-run facts exactly; it does not test them, and it says nothing about the model's dynamics. Pick targets that each free parameter clearly drives (the capital-output ratio for the depreciation rate, say): targets that depend on the same combination of parameters cannot be met separately, and the search fails. Only calibrated parameters can be free; estimated coefficients stay as they are.

pymetrix.commands.CheckModel dataclass

CheckModel(equations: Annotated[str, Widget('object', source='FittedEquation,Equation,Model,Template,DynareModel,EViewsXmlModel', multiple=True, help='fitted equations and identities, or a model, however it was made (imported from IRIS, Dynare, EViews or built)')], data: Annotated[str, Widget('object', source='Dataset')] = 'data', start: Annotated[str, Widget('period', group='Solution period', help='optional: check the data cover it')] = '', end: Annotated[str, Widget('period', group='Solution period', help='with Start, the solution period the data must cover')] = '', shocks: Annotated[str, Widget('text', help='random exogenous variables of a forward-looking model, e.g. ey, epi')] = '', params: Annotated[str, Widget('text', help='values for the parameters of equations not estimated, e.g. b=0.99, k=0.1')] = '', name: str = 'model_check', steady: Annotated[bool | None, Widget('choice', advanced=True, help='check the steady state too: automatic (when the model has one), yes or no')] = None)

Bases: Command

Check a model before solving it: every equation contains the variable it determines, the simultaneous blocks, the parameters, the timing of lags, leads and shocks, and, given a period, whether the data supply the starting values and exogenous paths. For a forward-looking model, also the steady state and the Blanchard-Kahn conditions. The model can be a whole one however it was made (imported from an IRIS, Dynare or EViews file, or built): an imported model is checked with its own shocks and steady-state guesses, unless Shocks are given.

Run it before solving: most failures to solve come from an equation that does not determine its variable, a parameter with no value, a missing exogenous path or a shock listed with the wrong timing. The Blanchard-Kahn conditions compare the stable roots with the predetermined variables: too few stable roots means no stable solution (often a sign error or a policy rule that responds too strongly), too many means the solution is not unique (indeterminacy, e.g. a Taylor rule responding less than one for one to inflation).

to_code

to_code() -> str

The code without a session: as if the chosen dataset were there (none chosen, data="": no data). The dialog and the recorded step build it from the session instead, leaving out a dataset it does not have.

pymetrix.commands.ChooseKMeansClusters dataclass

ChooseKMeansClusters(series: Annotated[str, Widget('series', depends_on='data', multiple=True, help='the series clustered on (two or more)')], data: Annotated[str, Widget('object', source='Dataset')] = 'data', smallest: Annotated[int, Widget('number', min=2, max=50, help='the fewest clusters tried')] = 2, largest: Annotated[int, Widget('number', min=2, max=50, help='the most clusters tried')] = 8, by: Annotated[Literal['observations', 'series'], Widget('choice', help='cluster the dates or the series')] = 'observations', standardize: Annotated[bool, Widget('checkbox', help='scale each series to mean 0 and standard deviation 1 first')] = True, starts: Annotated[int, Widget('number', min=1, max=1000, help='k-means++ starts for each k; the best is kept')] = 10, seed: Annotated[int, Widget('number', min=0, max=2 ** 31 - 1, advanced=True, help='random seed for the starts')] = 0, start: Annotated[str, Widget('period', group='Sample')] = '', end: Annotated[str, Widget('period', group='Sample')] = '', name: str = 'cluster_choice')

Bases: Command

How many k-means clusters: the fit for each number of clusters, to choose one.

For each k from the smallest to the largest, the within-cluster sum of squares (it always falls as k rises: look for the elbow, where it stops falling steeply) and the mean silhouette (higher is better: the clusters are compact and apart). The window shows both by k and marks the k with the highest silhouette; then make the clusters with K-means clusters… and that k.

pymetrix.commands.CoefficientPlot dataclass

CoefficientPlot(results: Annotated[str, Widget('object', source='FittedEquation', multiple=True, help='estimated equations; several are compared coefficient by coefficient')], terms: Annotated[str, Widget('text', help='the coefficients to show, in order, e.g. dlog(y), dlog(c)[-1] (empty: all)')] = '', alpha: Annotated[Literal['0.1', '0.05', '0.01'], Widget('choice', help="the intervals' size: 0.05 for 95% intervals, the conventional; 0.1 gives narrower (90%) intervals at less confidence")] = '0.05', title: Annotated[str, Widget('text', help='a title for the figure (optional)')] = '', name: str = 'coefficients')

Bases: Command

Plot estimated coefficients with their confidence intervals: a marker at each estimate and a line across its interval, one row per coefficient, with a dashed line at zero. Tick several equations to compare them side by side, coefficient by coefficient (each in its own colour, named as in the workspace). Bayesian estimates show their posterior intervals.

For classical estimates the intervals come from each equation's own standard errors, so they are only as reliable as its covariance choice (classic, robust, HAC or clustered): re-estimate with a robust covariance where heteroskedasticity or serial correlation is likely. An interval that excludes zero corresponds to a coefficient significant at one minus the chosen level, one coefficient at a time; it says nothing about joint significance. Coefficients are comparable across rows only if the regressors share units, so standardise or choose comparable terms first. Overlapping intervals of two equations do not imply that the coefficients are not significantly different.

pymetrix.commands.CombineForecasts dataclass

CombineForecasts(backtests: Annotated[str, Widget('object', source='Backtest', multiple=True, help='two or more backtests over the same origins and variables; only common forecasts are combined')], method: Annotated[Literal['equal', 'inverse_mse', 'regression'], Widget('choice', help='equal (robust, hard to beat), inverse MSE, or regression weights (can be negative; noisy if few outcomes)')] = 'equal', min_history: Annotated[int, Widget('number', min=1, max=200, advanced=True, help='equal weights until this many outcomes are known')] = 4, name: str = 'combination')

Bases: Command

Combine the forecasts of several backtests, and evaluate the combination as a backtest of its own.

Equal weights (the simple average, hard to beat), weights in proportion to 1 / MSE, or regression weights that sum to one. Weights are estimated in real time: at each origin only from the outcomes known by then.

pymetrix.commands.CombineNowcasts dataclass

CombineNowcasts(models: Annotated[str, Widget('object', source='FittedBridge,FittedDynamicFactor', multiple=True, help='fitted bridge equations and dynamic factor models')], variable: Annotated[str, Widget('text', help='dynamic factor models: the series to nowcast, e.g. gy')] = '', low: Annotated[str, Widget('object', source='Dataset', help='bridge equations: the quarterly data', empty='no bridge equation')] = '', high: Annotated[str, Widget('object', source='Dataset', help='bridge equations: the monthly indicators, as known on the day')] = 'data', weights: Annotated[str, Widget('text', help='model=weight, e.g. bridge=2, dfm=1; empty = equal weights')] = '', name: str = 'combined', through: Annotated[str, Widget('period', advanced=True, help='nowcast through this quarter, e.g. 2025Q2; empty = the quarter of the latest month')] = '')

Bases: Command

Average the nowcasts of several models: bridge equations and dynamic factor models.

Each model makes its nowcast as its own window does: a bridge equation from the quarterly and monthly data given here (as known on the day, Estimate → Mixed frequency → Data as known on a day…), a dynamic factor model for the series named, from the data it was fitted to. The combination is a weighted average, period by period (equal weights unless given; they are scaled to add up to one); a period is left out unless every model nowcasts it. Inverse mean squared errors from a backtest are a common choice of weights.

pymetrix.commands.CommandInfo dataclass

CommandInfo(cls: type[Command], menu: str | None, id: str = '', plugin: str = '', plugin_version: str = '')

pymetrix.commands.CompareBacktests dataclass

CompareBacktests(first: Annotated[str, Widget('object', source='Backtest', help='the first backtest (for Clark-West, the smaller, nested model)')], second: Annotated[str, Widget('object', source='Backtest', help='the backtest to compare it with')], variable: Annotated[str, Widget('text', help='the variable both forecast')], horizon: Annotated[int, Widget('number', min=1, max=40, help='which horizon to compare; both backtests must have forecast this far ahead')] = 1, test: Annotated[Literal['diebold-mariano', 'giacomini-white', 'clark-west', 'encompassing'], Widget('choice', help='equal accuracy, conditional ability, nested models, or does the first encompass the second')] = 'diebold-mariano', loss: Annotated[_LOSS, Widget('choice', help='not used by Clark-West and encompassing; CRPS and log score need density forecasts')] = 'squared', tau: Annotated[float, _TAU] = 0.5, linex_a: Annotated[float, _LINEX] = 1.0, name: str = 'comparison')

Bases: Command

Test whether two backtests' forecasts of a variable are equally accurate at one horizon.

Diebold-Mariano (equal expected loss), Giacomini-White (equal predictive ability given what was known when forecasting), Clark-West (the first model is nested in the second: does the larger model forecast better?), or encompassing (does the first forecast hold all the information in the second?). Losses: squared or absolute errors, or for density forecasts the CRPS or the log score.

The tests use the forecasts of both backtests for the same targets, so run them over the same origins. For Diebold-Mariano the loss differential is the first backtest's loss less the second's: a negative statistic favours the first. It treats the forecasts as given, which suits comparing forecasts, not population models; for nested models it is undersized, which is what Clark-West corrects. Long-horizon forecasts overlap, so their losses are serially correlated; the tests allow for this, but with few origins they have little power, and failing to reject is not evidence that the forecasts are equally good.

pymetrix.commands.CompareManyForecasts dataclass

CompareManyForecasts(backtests: Annotated[str, Widget('object', source='Backtest', multiple=True, help='the competing backtests; their common forecast targets are compared')], variable: Annotated[str, Widget('text', help='the variable they all forecast')], horizon: Annotated[int, Widget('number', min=1, max=40, help='which horizon to compare; also the shortest default bootstrap block')] = 1, loss: Annotated[_LOSS, Widget('choice', help='the loss to compare; CRPS and log score need density forecasts')] = 'squared', tau: Annotated[float, _TAU] = 0.5, linex_a: Annotated[float, _LINEX] = 1.0, alpha: Annotated[float, Widget('number', min=0.01, max=0.5, step=0.05, help='the set holds the best model with probability 1 - alpha')] = 0.1, name: str = 'confidence_set', draws: Annotated[int, Widget('number', min=100, max=100000, step=100, advanced=True, help='bootstrap resamples for the p-values; 1000 is usual, more steadies p-values near alpha')] = 1000, block: Annotated[int | None, Widget('number', min=1, max=200, advanced=True, help="the stationary bootstrap's mean block length; empty = automatic")] = None, seed: Annotated[int, Widget('number', min=0, max=2 ** 31 - 1, advanced=True, help='random seed for the bootstrap')] = 0)

Bases: Command

The model confidence set (Hansen, Lunde and Nason): which of several backtests' forecasts could be the best, at one horizon, with a stationary bootstrap. Needs the arch package.

Starting from all the models, the procedure drops the worst until the remaining ones cannot be told apart, so the set contains the best model with probability 1 - alpha (it uses the range statistic). A large set means the data cannot separate the forecasts, not that they are equally good; a model outside the set is significantly worse. The table gives each model's average loss and its MCS p-value: a model is in the set when its p-value exceeds alpha. Losses are serially correlated at longer horizons, which the block bootstrap allows for; the default mean block length is the larger of the horizon and n^(1/3).

pymetrix.commands.CompareRounds dataclass

CompareRounds(old: Annotated[str, Widget('text', help='name of the earlier round in the store; revisions are measured from it')], new: Annotated[str, Widget('text', help="name of the later round; each revision is this round's value less the earlier one's")], folder: Annotated[str, Widget('text', help='the forecast store holding both rounds, as given when they were saved')] = 'forecasts', variables: Annotated[str, Widget('text', help='variables; empty = all both rounds have')] = '', name: str = 'revisions')

Bases: Command

Two rounds from a store side by side, with the revisions between them.

For each variable the table shows both rounds' paths and the revision (new less old), period by period. Revisions are the record of how the forecast changed: separate those that come from new data (the later round's last data period is later) from those that come from judgement or a changed model, which the rounds' notes and adjustment logs explain. Persistent revisions in one direction can be a sign that a model or assumption is biased.

pymetrix.commands.ConditionalForecast dataclass

ConditionalForecast(fit: Annotated[str, Widget('object', source='FittedVAR', help='the estimated VAR or Bayesian VAR')], start: Annotated[str, Widget('period', help='the first forecast period')], end: Annotated[str, Widget('period', help='the last forecast period; conditions may cover all of the horizon or part')], conditions: Annotated[str, Widget('text', help='r=2.0 holds r every period; r[2025Q1:2025Q4]=2.0 some periods; pi=3..4 a range; pi>=3 or pi<=4 one side; several, separated by commas')], data: Annotated[str, Widget('object', source='Dataset', help='the data the forecast starts from')] = 'data', coverage: Annotated[float, Widget('number', min=0.5, max=0.999, step=0.05, advanced=True, help='interval coverage, e.g. 0.95')] = 0.95, name: str = 'conditional', draws: Annotated[int | None, Widget('number', min=1, max=100000, step=100, advanced=True, help='Bayesian VARs: posterior draws used; VARs with ranges: simulated paths; empty = the default')] = None, seed: Annotated[int, Widget('number', min=0, max=2 ** 31 - 1, advanced=True, help='random seed of the simulated paths and of the bootstrap')] = 0, shocks: Annotated[str, Widget('text', advanced=True, group='Structural scenario', help='the identified shocks that may move to meet the conditions, e.g. r; empty = all')] = '', shock_conditions: Annotated[str, Widget('text', advanced=True, group='Structural scenario', help='conditions on the shocks themselves, written as the conditions, e.g. y=0 or y[2025Q1:2025Q2]>=0')] = '', update_posterior: Annotated[bool, Widget('checkbox', advanced=True, help='Bayesian VARs: let the conditions inform the parameters too (Waggoner-Zha Gibbs sampler; slower)')] = False, bootstrap_kind: Annotated[Literal['none', 'residual', 'wild', 'block', 'parametric', 'pairs'], Widget('choice', advanced=True, group='Bootstrap', help='none (intervals from the shocks only, as before), or the VAR estimated again on each bootstrap draw, one path meeting the conditions under each: residual, wild (heteroskedastic errors), block (dependent errors), parametric (Gaussian) or pairs')] = 'none', bootstrap_draws: Annotated[int, Widget('number', min=1, max=100000, step=100, advanced=True, group='Bootstrap', show_if=('bootstrap_kind', ('residual', 'wild', 'block', 'parametric', 'pairs')), help='bootstrap draws: the VAR estimated again this many times, one path under each')] = 500, block_length: Annotated[int, Widget('number', min=0, max=400, advanced=True, group='Bootstrap', show_if=('bootstrap_kind', ('block',)), help='block bootstrap: periods in a block; 0 = automatic (5.03 T^(1/4))')] = 0, wild_dist: Annotated[Literal['rademacher', 'mammen', 'normal'], Widget('choice', advanced=True, group='Bootstrap', show_if=('bootstrap_kind', ('wild',)), help="wild bootstrap: the multipliers, Rademacher (plus or minus one), Mammen's or normal")] = 'rademacher', bias_correct: Annotated[bool, Widget('checkbox', advanced=True, group='Bootstrap', help="Kilian's bias correction of the VAR's coefficients before and in the bootstrap (VARs)")] = False, bootstrap_design: Annotated[Literal['recursive', 'fixed'], Widget('choice', advanced=True, group='Bootstrap', help='recursive rebuilds each series from its first values; fixed keeps the lagged data (VARs)')] = 'recursive')

Bases: Command

Forecast from a VAR given conditions on some of its variables: an assumed policy-rate path, or a range such as inflation between 3 and 4%.

Write a condition as r=2.0 (every period), r[2025Q1:2025Q4]=2.0 (some periods), pi[2026Q1]=3..4 (a range), pi>=3 or pi[2026Q1:2026Q4]<=4 (one-sided); several, separated by commas. With exact conditions, the other variables follow their expected paths given the conditions (Waggoner and Zha 1999): the most likely shocks that meet them, so the result does not depend on how shocks are identified. A range is met in every simulated path, drawn from the forecast distribution truncated to it. Name the identified shocks that may move to meet the conditions for a structural scenario (the others keep their usual distribution); conditions on the shocks themselves (e.g. y=0: no demand shocks) are written the same way. For a Bayesian VAR this is done for each posterior draw, so the intervals include parameter uncertainty; tick Update posterior to let the conditions inform the parameters too.

A VAR's intervals reflect the shocks only, unless the Bootstrap group (Advanced) names a kind: the VAR is then estimated again on each of Bootstrap draws bootstrap samples (residual, wild, block, parametric or pairs, with Kilian's bias correction or the fixed design as options) and one path meeting the conditions is drawn under each, so the intervals (percentile) include parameter uncertainty too; Seed seeds both.

pymetrix.commands.ConvertFrequency dataclass

ConvertFrequency(data: Annotated[str, Widget('object', source='Dataset', help='the dataset to convert (it is kept as it is)')] = 'data', freq: Annotated[Literal['Q', 'Y', 'Y-JUN', 'M', 'W'], Widget('choice', label='New frequency', help="Q quarterly, Y annual, Y-JUN a July-June fiscal year, M monthly, W weekly; lower than the data's")] = 'Q', how: Annotated[Literal['', 'sum', 'mean', 'first', 'last'], Widget('choice', help="how the periods of each new period combine: sum for flows, average for rates and indices, first or last for stocks; by measure, as each series' metadata says")] = '', name: str = 'converted', rules: Annotated[str, Widget('text', advanced=True, show_if=('how', ('',)), label='Series rules', help='rules for some series, overriding their measure: ip=sum, emp=last, pmi=mean (sum, mean, first, last, min, max or median)')] = '')

Bases: Command

Convert a dataset to a lower frequency: monthly to quarterly, quarterly to annual (or a July-June fiscal year).

Each new period combines the old ones it contains: their sum (flows such as GDP or sales), their average (rates, indices, prices), or the first or last value (stocks such as the money supply at the end of the quarter). By measure (the default) each series is combined as its metadata says: flows and counts summed, stocks the last value, rates, indices and ratios averaged; a series without a measure needs a rule (Advanced) or one choice for all. A period with a sub-period missing (a quarter with two of its months) is left missing, not computed from part of the data. Panels are converted entity by entity.

To a higher frequency there is nothing to add up: Data → Transform → Temporal disaggregation spreads annual or quarterly totals over the quarters or months, guided by indicators.

pymetrix.commands.Correlogram dataclass

Correlogram(source: Annotated[str, Widget('object', source='Dataset,FittedEquation', help='a dataset, or a fitted equation for its residuals')], variable: Annotated[str, Widget('series', depends_on='source', help='for a dataset: the series to examine')] = '', lags: Annotated[int, Widget('number', min=1, max=500, help='autocorrelations shown and tested jointly; about ln(T), or a few seasonal cycles for seasonal data')] = 20, squared: bool = False, name: str = 'correlogram')

Bases: Command

Autocorrelations, partial autocorrelations and Q-statistics of a series or of residuals.

Choose a dataset and series, or a fitted equation to examine its residuals. Tick Squared to look for volatility clustering.

Each Q-statistic (Ljung-Box) tests that all autocorrelations up to its lag are zero; a small p-value means serial correlation remains. For residuals of an equation with ARMA terms, the p-values take those terms off the degrees of freedom; after ARMA or GARCH the residuals are standardised. The band in the notes (1.96/sqrt(T)) is a guide for single lags only: among 20 lags one may fall outside by chance. Autocorrelations that die out very slowly suggest a unit root (Test > Run test); a partial autocorrelation that cuts off after p lags suggests an AR(p). With Squared, significant Q-statistics point to ARCH effects.

pymetrix.commands.DataAsOf dataclass

DataAsOf(when: Annotated[str, Widget('text', label='On the day', help='a date, e.g. 2025-02-15')], data: Annotated[str, Widget('object', source='Dataset', help='the data with publication lags (Variable.release_lag)')] = 'data', name: str = 'known', release_lags: Annotated[str, Widget('text', advanced=True, help=_RELEASE_LAGS_HELP)] = '')

Bases: Command

The data as they were known on a day: every value published later removed, so a nowcast can be made (or checked) with only what was known then.

A value counts as published on the last day of its period plus the series' publication lag (from its metadata, or given under Advanced). Run a nowcast on data as of a sequence of days to see how it would have moved as the figures came out, a pseudo-real-time evaluation. Values are only removed, not revised: earlier vintages of revised data come from the provider (File → Load from connector…, Vintage).

Apply the as-of date to the raw data before adjusting. Series kept up to date (a seasonal adjustment or filter with Keep updated, a derived series) are recomputed here from the values known on the day, so later data cannot revise the earlier adjusted values. A frozen adjusted series cannot be recomputed: adjust the data as known on the day, or load the adjusted series as it was published (a historical vintage).

pymetrix.commands.DateBusinessCycles dataclass

DateBusinessCycles(series: Annotated[str, Widget('series', depends_on='data', help='the series to date: a level (100*log of GDP) or a gap')], data: Annotated[str, Widget('object', source='Dataset', help='the dataset holding it (a panel: each entity dated on its own)')] = 'data', method: Annotated[Literal['auto', 'bbq', 'bry_boschan'], Widget('choice', help='BBQ (Harding and Pagan, quarterly) or Bry and Boschan (monthly); automatic: Bry-Boschan for monthly data, BBQ otherwise')] = 'auto', detrend: Annotated[Literal['none', 'hp', 'hamilton', 'baxter_king', 'christiano_fitzgerald'], Widget('choice', help='none: the classical cycle of the level; a filter: the growth cycle, the deviation from its trend')] = 'none', add_phases: Annotated[bool, Widget('checkbox', label='Add phases to the dataset', help='add {series}_recession, 1 in recession and 0 in expansion')] = False, name: str = 'cycle_dating', k: Annotated[int, Widget('number', min=0, max=24, advanced=True, label='Window (k)', help='a peak is higher than the k periods on either side; 0 = the published rule (2 quarters, 5 months)')] = 0, min_phase: Annotated[int, Widget('number', min=0, max=60, advanced=True, label='Shortest phase', help='periods from peak to trough or trough to peak; 0 = the published rule (2 quarters, 5 months)')] = 0, min_cycle: Annotated[int, Widget('number', min=0, max=120, advanced=True, label='Shortest cycle', help='periods from peak to peak or trough to trough; 0 = the published rule (5 quarters, 15 months)')] = 0)

Bases: Command

Date the business cycle of a series: its peaks and troughs, when its recessions began and ended, and how long and deep its expansions and recessions were.

Quarterly series are dated by Harding and Pagan's BBQ: a peak is higher than the two quarters on either side of it, a trough lower; peaks and troughs alternate, phases last at least 2 quarters and cycles at least 5. Monthly series are dated by Bry and Boschan's procedure, which finds the turning points in smoothed versions of the series and traces them back to the series itself, with phases of at least 5 months and cycles of at least 15. Date the level of a series (100 times its log, so that amplitudes are per cent) for the classical cycle, or choose a filter under Detrend to date the growth cycle, the deviation from trend. A recession runs from the period after a peak through the trough. The phases are saved as a 0/1 recession series, which can shade a graph or be the events of Evaluate early-warning signals. In a panel each entity is dated on its own.

pymetrix.commands.DefineEquation dataclass

DefineEquation(formula: Annotated[str, Widget('formula', help='e.g. c ~ y + c[-1]   (use = for identities)')], params: Annotated[str, Widget('text', help='comma-separated parameter names; empty for the linear form')] = '', name: str = 'eq', label: Annotated[str, Widget('text', advanced=True, help="the equation's name in a model, e.g. IS; empty = none")] = '', starts: Annotated[str, Widget('text', advanced=True, help="the parameters' starting values, e.g. rho=0.5, beta=0.9")] = '', bounds: Annotated[str, Widget('text', advanced=True, help="the parameters' bounds, e.g. rho=(0, 1); beta=(0, 0.999)")] = '', priors: Annotated[str, Widget('text', advanced=True, help='priors for estimation in a model, e.g. rho=Beta(0.8, 0.1): mean and standard deviation')] = '')

Bases: Command

Define an equation or identity without estimating it, for use in a model.

Write ~ for a stochastic equation and = for an identity. Lags are written x[-1]. For an explicit (nonlinear) form, name every parameter under Params.

pymetrix.commands.DefineMatrix dataclass

DefineMatrix(expression: Annotated[str, Widget('text', help='e.g. (X.T @ X).inv() @ X.T @ y, Matrix.cov(fit), V.chol(upper=True), A.svd()')], name: str = 'M')

Bases: Command

A named matrix from an expression in pymetrix's matrix syntax, using the session's objects by name: (X.T @ X).inv() @ X.T @ y, Matrix.cov(fit), V.chol(upper=True), A.kron(Matrix.identity(3)), A.svd() (a decomposition, shown as a table for each factor).

The expression may use Matrix, np and the session's objects; the usual functions are methods (A.inv(), A.pinv(), A.power(2), A.det()) or Matrix's (Matrix.lyapunov(F, Q), Matrix.hcat(A, B)). It is checked before it runs: one expression of names, calls, operators, indexing and literals; imports, lambda, attributes starting with _ and anything that reads or writes files are refused. The step records name = expression and is recomputed when the objects it uses change.

pymetrix.commands.DeriveEach dataclass

DeriveEach(name: Annotated[str, Widget('text', help='name template for the new series, e.g. d{s}')], formula: Annotated[str, Widget('text', help='formula template, e.g. dlog({s}) or {s} / y * 100')], data: Annotated[str, Widget('object', source='Dataset')] = 'data', series: Annotated[str, Widget('series', depends_on='data', multiple=True, help=_SERIES_HELP)] = '', selection: Annotated[str, Widget('object', source='Selection', help=_SELECTION_HELP)] = '', keep_updated: Annotated[bool, Widget('checkbox', help='keep the formulas, so the series follow their inputs')] = True, replace: Annotated[bool, Widget('checkbox', help='replace a series of the same name, if there is one')] = False)

Bases: _Loop, Command

Add a series for each selected series, from templates: d{s} = dlog({s}) gives dc, di, dg.

Tick the series here, or choose a selection made with Data > Select series. With Keep updated (the default) they are derived series that follow their inputs; otherwise their values are computed once.

pymetrix.commands.DeriveSeries dataclass

DeriveSeries(series: Annotated[str, Widget('text', help='name of the new series, e.g. dly')], formula: Annotated[str, Widget('formula', help='e.g. dlog(y), c / y * 100, (y - y[-4]) / y[-4]')], data: Annotated[str, Widget('object', source='Dataset')] = 'data', replace: Annotated[bool, Widget('checkbox', help='replace a series of the same name, if there is one')] = False)

Bases: Command

Add a series defined by a formula that stays up to date, such as dlog(y) or c / y * 100.

Unlike a plain series, it keeps its formula: when a series it uses changes, it is recomputed, and so is anything derived from it in turn. The formula uses the same expression language as equations (x[-1] for lags, log, dlog, d and other functions). Its values are fixed only if you freeze it in code (data.freeze("name")) or take a subset of the dataset.

pymetrix.commands.Disaggregate dataclass

Disaggregate(formula: Annotated[str, Widget('formula', help='e.g. gdp ~ ip, or gdp ~ 1 with no indicator')], low: Annotated[str, Widget('object', source='Dataset', help='the low-frequency data (e.g. annual)')], high: Annotated[str, Widget('object', source='Dataset', help='the high-frequency data with the indicators (e.g. quarterly)')] = 'data', method: Annotated[Literal['chow-lin', 'chow-lin-minrss', 'fernandez', 'litterman', 'litterman-minrss', 'denton', 'denton-additive'], Widget('choice', help='Chow-Lin (AR(1) residual), Fernandez (random walk), Litterman (random walk with AR(1) steps), or Denton')] = 'chow-lin', conversion: Annotated[Literal['sum', 'average', 'first', 'last'], Widget('choice', help='sum for flows, average for rates, first or last for stocks')] = 'sum', add_to_high: Annotated[bool, Widget('checkbox', help='add the series to the high-frequency data')] = True, name: str = 'disaggregation', rho: Annotated[float | None, Widget('number', min=-0.999, max=0.999, step=0.01, advanced=True, show_if=('method', _RHO_METHODS), help='Chow-Lin and Litterman: fix rho; empty = estimated')] = None, rho_bounds: Annotated[str, Widget('text', advanced=True, show_if=('method', _RHO_METHODS), help='Chow-Lin and Litterman: the range rho is estimated in, low, high; the default 0, 0.999 keeps it non-negative, -0.999, 0.999 allows negative rho')] = '0, 0.999', differences: Annotated[Literal['first', 'seasonal'], Widget('choice', show_if=('method', ('denton', 'denton-additive')), help="Denton: seasonal differences (lag 4 or 12) keep the indicator's seasonal pattern")] = 'first', level_penalty: Annotated[float | None, Widget('number', min=0, step=0.001, advanced=True, show_if=('differences', ('seasonal',)), help='seasonal Denton: the weight on first differences that pins the pattern; empty = 0.001')] = None, soft: Annotated[float | None, Widget('number', min=0, advanced=True, help="soft constraints: the standard deviation of the low-frequency values' error, in their units; empty = met exactly")] = None, aggregation: Annotated[str, Widget('object', source='Matrix,Dataset', advanced=True, empty='none: use the conversion', help="an aggregation matrix instead of the conversion: a matrix (rows named as the low-frequency data's, columns as the high-frequency periods) or a high-frequency dataset of weights, one series per low-frequency value")] = '', aggregation_file: Annotated[str, Widget('file', source='Tables (*.csv *.xlsx *.xls *.parquet);;All files (*)', advanced=True, help='the aggregation matrix from a file: a first column of row names, a header of high-frequency periods')] = '')

Bases: Command

Make a quarterly or monthly series consistent with annual (or quarterly) data, from indicators.

Write the low-frequency series on its high-frequency indicators (gdp ~ ip + emp), or on 1 for none. Chow-Lin, Fernandez and Litterman estimate the relation and spread the rest; Denton moves the indicator (or a constant) as little as possible, in first or seasonal differences. The result adds up to the low-frequency data (sums for flows, averages for rates, first or last values for stocks, or the weighted sums of an aggregation matrix, such as calendar- and fiscal-year totals together), exactly unless soft constraints let it miss them, and extends to the end of the indicators. Chow-Lin's and Litterman's rho is estimated between 0 and 0.999 unless its range is widened; an estimate at an end of the range is noted in the summary.

pymetrix.commands.DropSeries dataclass

DropSeries(data: Annotated[str, _DATA], series: Annotated[str, Widget('text', help='comma-separated series to remove')])

Bases: Command

Remove series from a dataset.

pymetrix.commands.EditData dataclass

EditData(data: Annotated[str, _DATA], edits: Annotated[str, Widget('text', help='JSON list of [series, row key parts, value or null], e.g. [["c", ["2020Q1"], 1.2]]')])

Bases: Command

Values typed or pasted into the spreadsheet editor.

pymetrix.commands.EnterMatrix dataclass

EnterMatrix(values: Annotated[str, Widget('multiline', help='the numbers: a row per line, cells separated by tabs, commas or spaces')], rows: Annotated[str, Widget('text', help='row names, separated by commas; empty: numbered 1, 2, ...')] = '', cols: Annotated[str, Widget('text', help='column names, separated by commas; empty: numbered 1, 2, ...')] = '', name: str = 'M')

Bases: Command

A named matrix from numbers typed or pasted into a grid (from Excel, or text with tabs, semicolons, commas or spaces between the cells), with names for its rows and columns.

Model > Matrix > Enter values opens the grid: set the numbers of rows and columns, type or paste the numbers (Ctrl+V; a first row or column of names is read as the names), and double-click a row or column header to rename it. Recorded as the matrix written out, M = Matrix([[1, 0.5], [0.5, 1]], rows=['a', 'b'], cols=['a', 'b']).

pymetrix.commands.EquationLagSearch dataclass

EquationLagSearch(formula: Annotated[str, Widget('formula', help='the equation without the lags searched, e.g. dlog(c) ~ dlog(y)')], of: Annotated[str, Widget('text', help='the variables whose lags are added, comma-separated; empty = the left-hand side')] = '', max_lags: Annotated[int, Widget('number', min=1, max=24, help='longest lag tried; the common sample starts after it, so a large maximum costs observations')] = 8, data: Annotated[str, Widget('object', source='Dataset')] = 'data', name: str = 'lag_search')

Bases: Command

Choose how many lags an equation takes.

Lags 1 to p of the variables searched (by default the left-hand side as written) are added for p = 0 up to the maximum, each fitted on the same sample, and compared by AIC, BIC and Hannan-Quinn.

BIC is consistent and picks short lags; AIC picks longer ones and suits forecasting. Whichever you choose, check the chosen equation's residuals for remaining autocorrelation (Test > Correlogram): too few lags leave dynamics in the errors and bias the other coefficients when a lagged dependent variable is present. A criterion at its minimum at the largest lag tried suggests trying a larger maximum.

pymetrix.commands.EstimateModel dataclass

EstimateModel(source: Annotated[str, Widget('object', source='Template, DynareModel', help='a template, IRIS or Dynare model (Model > Template model, Import IRIS file, Import Dynare file)')], data: Annotated[str, Widget('object', source='Dataset', empty="empty: a Dynare file's own datafile", help="data with the model's observed series; leave empty for a Dynare file's own datafile")] = 'data', estimate: Annotated[str, Widget('text', help='parameters and shock sizes to estimate, e.g. kappa, rho, sd_ei; empty = all (a Dynare file: its estimated_params)')] = '', priors: Annotated[str, Widget('text', help='e.g. kappa=Gamma(0.3, 0.1); rho=Beta(0.8, 0.1): mean and standard deviation; empty = none (a Dynare file: its own)')] = '', start: Annotated[str, Widget('period', group='Sample')] = '', end: Annotated[str, Widget('period', group='Sample')] = '', starts: Annotated[int, Widget('number', min=1, max=64, advanced=True, help='optimise from this many points (the starting values, then draws from the priors) and keep the best')] = 1, name: str = 'estimated', seed: Annotated[int, Widget('number', min=0, max=2 ** 31 - 1, advanced=True, help='random seed of the draws from the priors (several starts)')] = 0, workers: Annotated[int | None, Widget('number', min=1, max=64, advanced=True, help='starts run at once in other processes; empty = automatic')] = None, initial: Annotated[Literal['default', 'auto', 'stationary', 'diffuse', 'scaled'], Widget('choice', advanced=True, group='Kalman filter', help="the filter's start: stationary, diffuse, scaled (variance 10 I) or auto; default = auto (a Dynare file: its lik_init)")] = 'default', presample: Annotated[int | None, Widget('number', min=0, max=400, advanced=True, group='Kalman filter', help='periods filtered but left out of the likelihood; empty = none (a Dynare file: its presample)')] = None, max_iter: Annotated[int, Widget('number', min=10, max=100000, step=100, advanced=True, help="the optimiser's iterations")] = 2000, bounds: Annotated[str, Widget('text', advanced=True, help='parameter bounds, e.g. kappa=(0.01, 5); rho=(0, 0.99)')] = '', growth: Annotated[bool, Widget('checkbox', advanced=True, help='a balanced-growth steady state (variables trend at constant rates)')] = False, occbin: Annotated[bool, Widget('checkbox', advanced=True, group='Kalman filter', help='the likelihood of the OccBin filter, for a model with occasionally binding constraints (its max or min, such as a lower bound on the policy rate); slower')] = False, regimes: Annotated[str, Widget('text', advanced=True, group='Regimes', help='parameters that change at known dates in the sample, e.g. 2009Q1: phi_pi=1.2; each value is estimated as name@period (phi_pi@2009Q1), which estimate, priors and bounds can name')] = '', order: Annotated[Literal[1, 2], Widget('choice', advanced=True, group='Particle filter', help="the solution's order: 1 (linear, Kalman filter) or 2 (second order, pruned, estimated with the particle filter; every observed series needs a measurement error)")] = 1, filter: Annotated[Literal['default', 'kalman', 'particle', 'guided'], Widget('choice', advanced=True, group='Particle filter', help="the likelihood's filter: Kalman, particle (bootstrap) or guided particle filter; default = Kalman at order 1, particle at order 2")] = 'default', particles: Annotated[int, Widget('number', min=10, max=1000000, step=500, advanced=True, group='Particle filter', help='particles of the particle filter (its seed: the seed above, with common random numbers)')] = 2000, smooth_paths: Annotated[int, Widget('number', min=0, max=100000, step=50, advanced=True, group='Particle filter', help='paths the particle smoother draws for the smoothed variables (backward simulation); 0 = filtered means instead')] = 100, gradient: Annotated[Literal['auto', 'analytic', 'numerical'], Widget('choice', advanced=True, group='Kalman filter', help="the optimiser's gradient: analytic (the Kalman filter's score) where it applies with auto, or central differences (numerical)")] = 'auto', diffuse_terms: Annotated[Literal['include', 'exclude'], Widget('choice', advanced=True, group='Kalman filter', help="with diffuse states, the log likelihood's diffuse periods: included (the exact diffuse likelihood, Durbin and Koopman) or left out (as statsmodels reports it)")] = 'include')

Bases: Command

Estimate a model's parameters and shock sizes from data, by maximum likelihood with the Kalman filter: a template model, an IRIS model, or a Dynare file imported with Model > Import > Dynare file.

The model is linearised and solved at each trial value and fitted to the observed series of its measurement equations. List the parameters to estimate (and shock sizes, sd_<shock>), or leave the list empty for every calibrated parameter and shock size. With priors (e.g. kappa=Gamma(0.3, 0.1); rho=Beta(0.8, 0.1); sd_ei=InvGamma1(0.2, inf), each given by its mean and standard deviation, as in Dynare; also Normal and Uniform(low, high)) the estimate is the posterior mode; then Model > Metropolis-Hastings draws from the whole posterior.

A Dynare file brings its own estimation: leave the data, parameters and priors empty to use its datafile, estimated_params and options (presample, lik_init...), as Dynare's estimation command would. Medium-sized models can have more than one mode: Starts (under Advanced) also optimises from draws from the priors, keeps the best, and says in the results where the others stopped.

pymetrix.commands.EvaluateEarlyWarning dataclass

EvaluateEarlyWarning(indicators: Annotated[str, Widget('series', depends_on='data', multiple=True, help="the candidate indicators, or a model's fitted probability")], events: Annotated[str, Widget('series', depends_on='data', help='the events: 1 in every period of a crisis, 0 otherwise')], data: Annotated[str, Widget('object', source='Dataset', help='the dataset holding them (a panel: windows per entity)')] = 'data', horizon: Annotated[int, Widget('number', min=0, max=120, label='Horizon (periods)', help='an event starting within this many periods is the target (8 quarters, 24 months); 0 = the events themselves')] = 8, post: Annotated[int, Widget('number', min=0, max=120, label='Post-event periods left out', help='periods after each event left out of the evaluation (the post-crisis bias)')] = 0, direction: Annotated[Literal['auto', 'above', 'below'], Widget('choice', help='whether high or low values signal; automatic: whichever gives an AUROC above 0.5')] = 'auto', below: Annotated[str, Widget('series', depends_on='data', multiple=True, label='Low values signal for', help='indicators that signal when low (reserves, the current account), whatever Direction says')] = '', criterion: Annotated[Literal['usefulness', 'youden', 'noise_to_signal'], Widget('choice', label='Threshold by', help="the policymaker's loss, the Youden index (hit rate less false-alarm rate) or KLR's noise-to-signal ratio")] = 'usefulness', mu: Annotated[float, Widget('number', min=0.0, max=1.0, step=0.05, label='Weight on missed events (mu)', help="the policymaker's weight on missing an event against a false alarm; with rare events signals are useful only when it is high")] = 0.5, alpha: Annotated[float, Widget('number', min=0.001, max=0.5, step=0.01, help='AUROC intervals at 1 - alpha')] = 0.05, method: Annotated[Literal['delong', 'bootstrap'], Widget('choice', label='AUROC interval', help="DeLong's variance, or the bootstrap's percentiles")] = 'delong', name: str = 'early_warning_result', min_signals: Annotated[float, Widget('number', min=0.0, max=100000, step=0.05, advanced=True, label='Fewest signals', help='thresholds must give at least this many signals (a share of the observations if below 1); 0 = automatic: a tenth for the noise-to-signal ratio, none otherwise')] = 0.0, loss: Annotated[Literal['sarlin', 'alessi_detken'], Widget('choice', advanced=True, label='Usefulness', help="Sarlin's weighting by the shares of events and calm periods, or Alessi and Detken's unweighted loss")] = 'sarlin', resample: Annotated[Literal['stratified', 'cluster', 'block'], Widget('choice', advanced=True, show_if=('method', ('bootstrap',)), help='what the bootstrap resamples: events and non-events separately, whole entities, or blocks of consecutive periods')] = 'stratified', draws: Annotated[int, Widget('number', min=100, max=100000, step=100, advanced=True, show_if=('method', ('bootstrap',)), help='bootstrap resamples')] = 2000, seed: Annotated[int, Widget('number', min=0, max=2 ** 31 - 1, advanced=True, show_if=('method', ('bootstrap',)), help='random seed for the bootstrap')] = 0, threshold_by: Annotated[Literal['pooled', 'entity'], Widget('choice', advanced=True, label='Thresholds', help="one threshold for all, or (a panel) each country's own: the same percentile of its own distribution of the indicator (Kaminsky, Lizondo and Reinhart)")] = 'pooled', model: Annotated[Literal['none', 'logit', 'probit'], Widget('choice', advanced=True, group='Model', label='Early-warning model', help='also fit a logit or probit of the pre-event target on indicators and rank its probability as one more indicator')] = 'none', model_indicators: Annotated[str, Widget('series', depends_on='data', multiple=True, advanced=True, group='Model', show_if=('model', ('logit', 'probit')), label="Model's indicators", help="the model's regressors (empty = all the indicators)")] = '', scheme: Annotated[Literal['none', 'recursive', 'rolling'], Widget('choice', advanced=True, group='Out of sample', label='Out of sample', help='also judge each indicator out of sample: each period scored with the threshold (and model) chosen from the data before it, outcomes used only once their window has passed; recursive: all the data so far, rolling: the last Window periods')] = 'none', start: Annotated[str, Widget('period', advanced=True, group='Out of sample', show_if=('scheme', ('recursive', 'rolling')), help='the first period scored out of sample (empty = the first with enough events known)')] = '', end: Annotated[str, Widget('period', advanced=True, group='Out of sample', show_if=('scheme', ('recursive', 'rolling')), help='the last period scored (empty = the last)')] = '', window: Annotated[int, Widget('number', min=1, max=10000, advanced=True, group='Out of sample', show_if=('scheme', ('rolling',)), label='Window (periods)', help='periods of resolved outcomes each rolling estimate uses')] = 40, min_events: Annotated[int, Widget('number', min=0, max=1000, advanced=True, group='Out of sample', show_if=('scheme', ('recursive', 'rolling')), label='Fewest events known', help="a period is scored only once this many events' pre-event windows are known")] = 1)

Bases: Command

How well do indicators (or a model's probability) signal coming events, such as banking crises, recessions or debt distress? Each candidate is judged by its power to signal the events against its false alarms, and ranked.

Events is a 0/1 series, 1 in every period of an event. The target is an event starting within the Horizon (8: in the next 8 periods); the events' own periods are left out, and the Post-event periods after each one, when indicators behave as neither calm nor pre-crisis (Bussiere and Fratzscher's post-crisis bias). In a panel the windows are per country. For each indicator: the direction it signals in (high values, low values, or whichever discriminates), the area under its ROC curve (AUROC: 0.5 is no skill, 1 perfect) with a DeLong or bootstrap interval and DeLong's test against the best, the threshold that maximises the policymaker's usefulness (Sarlin 2013; Weight on missed events, mu, against false alarms), the Youden index or minimises the noise-to-signal ratio (Kaminsky, Lizondo and Reinhart), its hit and false-alarm rates there, the share of events it called, and how many periods ahead its first signal came. The window shows the ranking, the ROC curves of the two best with their thresholds, the best indicator over time with its threshold and the events, and its trade-off by threshold.

Under Advanced settings: Thresholds by country (each country's own percentile, KLR); an Early-warning model (a logit or probit of the pre-event target, its probability ranked as one more indicator); and Out of sample, where each period is scored with the threshold and model chosen from the data before it, an outcome used only once its window has passed, recursively (all the data so far) or in a rolling window, and compared with the in-sample figures (Alessi and Detken 2011; Holopainen and Sarlin 2017).

pymetrix.commands.ExportModel dataclass

ExportModel(source: Annotated[str, Widget('object', source='Template,DynareModel,Model', help='a template, a Dynare model or a Model')], syntax: Annotated[Literal['pymetrix', 'dynare', 'iris', 'eviews'], Widget('choice', help='the language to write it in')] = 'dynare', form: Annotated[Literal['program', 'text'], Widget('choice', show_if=('syntax', ('eviews',)), help="program: a .prg (model m, m.append lines and the values); text: the model's text alone, its values in a comment")] = 'program', name: str = 'translation', origin: Annotated[str, Widget('text', advanced=True, help='where the model came from, said in the first comment line')] = '')

Bases: Command

Write a model in another syntax: pymetrix's, Dynare's (.mod), IRIS's (.model) or EViews's (a program, or the model's text). The result has the text, notes on what did not carry across (priors IRIS keeps elsewhere, regimes Dynare has no place for, names EViews would read differently) and a check: the text is read back in and solved, and its responses to each shock and its steady state compared with the original's.

The text is generated from the model, not from any text it was read from: it means the same, but comments, layout, loops and model-local variables are not reproduced. Copy it from the Text tab, or open it in Model > Model editor to change it. The editor's Write as button does the same from the text being edited.

pymetrix.commands.FillEdge dataclass

FillEdge(data: Annotated[str, Widget('object', source='Dataset', help='the indicators, ending in different periods')] = 'data', lags: Annotated[int, Widget('number', min=1, max=12, help="lags of each series' autoregression; 2 is usual for monthly data")] = 2, through: Annotated[str, Widget('period', help='fill to this period, e.g. 2025-03 (the end of the quarter); empty = the last period of any series')] = '', series: Annotated[str, Widget('series', depends_on='data', multiple=True, help='the series to fill; empty = all')] = '', name: str = 'filled')

Bases: Command

Fill the missing values at the end of each series with forecasts from an autoregression of the series.

Each series' AR model (a constant and Lags lags) is estimated on its own history and run forward from its last observation to Through (by default the last period of any series), the way bridge equations complete the current quarter's months. Values already there are kept. The forecasts carry little information beyond the series' own momentum, so the more months are filled, the less the nowcast says.

pymetrix.commands.Filter dataclass

Filter(variables: Annotated[str, Widget('series', depends_on='data', multiple=True, help='series to filter, e.g. log GDP')], data: Annotated[str, Widget('object', source='Dataset')] = 'data', method: Annotated[str, Widget('extension', source='filters', help='HP, one-sided HP, band-pass (Baxter-King, Christiano-Fitzgerald), Hamilton or moving average; each defines the cycle differently')] = 'HP', settings: Annotated[str, Widget('options', depends_on='method', source='filters', group='Filter settings')] = '', keep_updated: Annotated[bool, Widget('checkbox', help='recompute the trend and cycle whenever the series changes')] = True, name: Annotated[str, Widget('text', help='a new dataset for the result; empty = add to the dataset itself')] = '')

Bases: Command

Split series into trend and cycle with a filter (HP, band-pass, Hamilton...).

Tick the series and choose the filter; its settings appear below it, defaulting to values suited to the data's frequency. <series>_trend and <series>_cycle are added to the dataset (or to a new one, if you name it).

With Keep updated (the default) they are derived series: when the filtered series changes, they are recomputed. A two-sided filter then revises its whole history, as it would with a new data release.

The cycle is defined by the filter, not found in the data: HP removes a smooth trend whose smoothness the smoothing parameter sets; Baxter-King and Christiano-Fitzgerald keep cycles of 1.5 to 8 years by default; Hamilton takes the error in forecasting the series two years ahead. Two-sided filters use future values, so the last few years of the cycle are revised as data arrive and are unreliable in real time; Baxter-King loses points at both ends instead. Compare two filters before drawing conclusions about the latest output gap.

pymetrix.commands.FitARDL dataclass

FitARDL(formula: Annotated[str, Widget('formula', help='dependent variable on the regressors, in levels (often logs), e.g. lc ~ ly + lw')], data: Annotated[str, Widget('object', source='Dataset')] = 'data', select: Annotated[Literal['', 'aic', 'bic', 'hqic'], Widget('choice', help='choose the lags by a criterion; empty = use the lags below')] = '', lags: Annotated[int, Widget('number', min=1, max=24, help='lags of the dependent variable; enough to leave serially uncorrelated residuals')] = 1, order: Annotated[int, Widget('number', min=0, max=24, help='lags of each regressor; 0 = the current value only, which still allows a long-run effect')] = 1, trend: Annotated[Literal['n', 'c', 'ct'], Widget('choice', help="deterministic terms: none, constant, or constant and trend; the bounds test's critical values depend on it")] = 'c', start: Annotated[str, Widget('period', group='Sample')] = '', end: Annotated[str, Widget('period', group='Sample')] = '', name: str = 'ardl', max_lags: Annotated[int, Widget('number', min=1, max=24, advanced=True, help='longest lag of the dependent variable and of each regressor the criterion may choose')] = 4)

Bases: Command

An autoregressive distributed lag model, with the Pesaran-Shin-Smith bounds test for a level relationship.

Write the dependent variable on the regressors (lc ~ ly + lw). Give the lags of each, or let an information criterion choose them up to the maximums. The result shows the long-run multipliers, the bounds test and the error-correction form, whether the series are I(0) or I(1).

The bounds test asks whether there is a level (long-run) relationship without first deciding whether each series is I(0) or I(1): a statistic above the upper bound rejects "no level relationship" whatever the mix, one below the lower bound does not reject, and one between them is inconclusive. It is not valid if any series is I(2). The long-run multipliers are the regressors' summed coefficients divided by one minus the sum of the dependent variable's lag coefficients; they are meaningful only if a level relationship exists. The error-correction coefficient should be negative and between -1 and 0: it is the share of a deviation from the long run corrected each period. Enough lags to leave white-noise residuals matter for the test's validity.

pymetrix.commands.FitBMA dataclass

FitBMA(outcome: Annotated[str, Widget('text', help='the series to explain or forecast, e.g. dlog(gdp)')], candidates: Annotated[str, Widget('text', help='candidate regressors, separated by commas, e.g. spread[-1], pmi[-1]')], data: Annotated[str, Widget('object', source='Dataset')] = 'data', always: Annotated[str, Widget('text', advanced=True, help='regressors in every model besides the intercept, separated by commas')] = '', g: Annotated[float, Widget('number', min=0, max=1000000000.0, advanced=True, help='prior scale: larger g shrinks coefficients less but penalises larger models more; 0 = max(n, K^2)')] = 0.0, start: Annotated[str, Widget('period', group='Sample', help='first period of the sample (empty = the first available)')] = '', end: Annotated[str, Widget('period', group='Sample', help='last period of the sample (empty = the last available)')] = '', name: str = 'bma')

Bases: Command

Bayesian model averaging: weigh every regression on a subset of the candidate regressors by its posterior probability (Zellner's g-prior, equal prior probabilities).

Reports each candidate's posterior inclusion probability, the model-averaged coefficients and the most probable models; forecasts average the models' forecasts. Up to 15 candidates (32,768 models).

pymetrix.commands.FitBridge dataclass

FitBridge(formula: Annotated[str, Widget('formula', help='e.g. gy ~ gr + pmi (quarterly and monthly series names)')], low: Annotated[str, Widget('object', source='Dataset', help='the dataset with the quarterly series in the formula; its last figure sets where the nowcast starts')], high: Annotated[str, Widget('object', source='Dataset', help='the dataset with the monthly indicators; they may end in different months (a ragged edge)')] = 'data', how: Annotated[Literal['mean', 'sum', 'last'], Widget('choice', help='how three months make a quarter: mean for rates and indices, sum for flows, last for stocks')] = 'mean', fill_lags: Annotated[int, Widget('number', min=1, max=12, advanced=True, help="lags of the autoregressions that forecast each indicator's missing months to complete the quarter")] = 2, name: str = 'bridge', mask: Annotated[str, Widget('text', advanced=True, help='periods left out of the estimation sample, e.g. 2020-03 to 2021-06; ranges and periods separated by semicolons; empty = none')] = '')

Bases: Command

Regress a quarterly series on monthly indicators averaged within each quarter (a bridge equation).

The formula names the quarterly series and the indicators, e.g. gy ~ gr + pmi. To nowcast, the current quarter's missing months are forecast by an autoregression of each indicator, then averaged: the result's nowcast(quarterly, monthly) gives the quarters after the last quarterly figure.

A bridge equation is a plain regression, so it is easy to read and to explain, but each indicator enters only as a quarterly aggregate: what it says about the current quarter depends on how many of its months are already out, and the months filled in by autoregressions carry little information. Choose the aggregation to match the quarterly series: the mean for rates and indices, the sum for flows measured monthly, the last month for end-of-period stocks. Use stationary series (growth rates, survey balances) on both sides, and evaluate the nowcast out of sample, as the in-sample fit says little about real-time accuracy.

Masked periods (under Advanced) leave those quarters out of the estimation sample, e.g. 2020-03 to 2021-06 for the pandemic (a quarter is masked when any of its months is): ranges and single periods separated by semicolons. Their values are still used as lags.

pymetrix.commands.FitDynamicFactor dataclass

FitDynamicFactor(monthly: Annotated[str, Widget('text', help='monthly series, e.g. gr, gip, gemp, pmi')], high: Annotated[str, Widget('object', source='Dataset', help='the dataset with the monthly series; each may end in a different month')] = 'data', quarterly: Annotated[str, Widget('text', help='quarterly series to nowcast, e.g. gy')] = '', low: Annotated[str, Widget('object', source='Dataset', help='the quarterly data (if any quarterly series)')] = '', factors: Annotated[int, Widget('number', min=1, max=5, help='number of common factors; one often captures the business cycle, more fit better but are harder to read')] = 1, factor_order: Annotated[int, Widget('number', min=1, max=6, help='lags in the VAR the factors follow; more lags give richer dynamics at the cost of parameters')] = 2, name: str = 'dfm', blocks: Annotated[str, Widget('text', help='block: series; block: series, e.g. Global: gr, gip, gemp, pmi, gy; Real: gr, gip, gemp, gy; Soft: pmi. Each block is a factor loading on the series listed; empty = Factors common factors')] = '', full_sample: Annotated[bool, Widget('checkbox', advanced=True, help='start the sample in the first month any series has data, the months before the others start treated as missing')] = False, mask: Annotated[str, Widget('text', advanced=True, help='periods set to missing for estimation, e.g. 2020-03 to 2021-06; ranges and periods separated by semicolons; empty = none')] = '', outliers: Annotated[float, Widget('number', advanced=True, min=0, help="values more than this many interquartile ranges from each series' median set to missing (e.g. 10); 0 = none")] = 0.0)

Bases: Command

A dynamic factor model of monthly indicators and quarterly series, estimated by EM with the Kalman filter, so series that end in different months (the ragged edge) are used as they are.

Series must be stationary: growth rates or surveys (make them with Data > Generate series). The result's nowcast("gy") gives the quarters after the last quarterly figure, and nowcast_density("gy") the same with its standard error and a 90% interval; update() puts newer data through the same model, and news() shows how each new figure moved the nowcast.

Factors are common to every series. Factor blocks give a block structure instead, as central banks' nowcasting models have: each block is a factor that loads on the series listed after it, e.g. Global: gr, gip, gemp, pmi, gy; Real: gr, gip, gemp, gy; Soft: pmi (a global factor, and one each for the hard data and the survey). Every series must be in at least one block; with blocks, Factors is not used.

The sample starts in the first month every monthly series has data. Tick Keep each series' full history (under Advanced) for series that start at very different dates: the sample then starts with the earliest, and the months before the others start are treated as missing.

Masked periods (under Advanced) are set to missing for estimation, for every series: ranges and single periods separated by semicolons, e.g. 2020-03 to 2021-06 for the pandemic (a quarter is masked when any of its months is). Outliers sets values more than that many interquartile ranges from each series' median to missing too (0: none); the model's window lists what was masked.

pymetrix.commands.FitEach dataclass

FitEach(formula: Annotated[str, Widget('formula', help=_TEMPLATE_HELP)], data: Annotated[str, Widget('object', source='Dataset')] = 'data', series: Annotated[str, Widget('series', depends_on='data', multiple=True, help=_SERIES_HELP)] = '', selection: Annotated[str, Widget('object', source='Selection', help=_SELECTION_HELP)] = '', method: Annotated[str, Widget('extension', source='methods', help='estimation method for every equation')] = 'OLS', cov: Annotated[Literal['classic', 'white', 'hac'], Widget('choice')] = 'classic', start: Annotated[str, Widget('period')] = '', end: Annotated[str, Widget('period')] = '', name: str = 'fits', method_settings: Annotated[str, Widget('options', depends_on='method', source='methods', exclude=('endog', 'instruments', 'cov', 'hac_lags'), group='Method settings')] = '', keep_going: Annotated[bool, Widget('checkbox', advanced=True, help='if one equation fails, estimate the rest and list the failure')] = False)

Bases: _Loop, Command

Estimate the same equation for each selected series, with {s} standing for the series.

For example d{s} ~ d{s}[-1] + dlog(y) estimates one equation per series. Tick the series here, or choose a selection made with Data > Select series. The result shows the coefficients side by side, with rows lined up across series (d{s}[-1]), and the fit statistics.

pymetrix.commands.FitEquation dataclass

FitEquation(formula: Annotated[str, Widget('formula')], params: Annotated[str, Widget('text')] = '', data: Annotated[str, Widget('object', source='Dataset')] = 'data', method: Annotated[str, Widget('extension', source='methods', help='estimation methods whose libraries are installed')] = 'OLS', family: Annotated[Literal['gaussian', 'logit', 'probit', 'poisson', 'negative binomial', 'zero-inflated poisson', 'ordered logit', 'ordered probit', 'multinomial logit', 'tobit', 'cloglog', 'ordered cloglog'], Widget('choice', show_if=('method', _kind('ml', 'bayes')), help='logit, probit, complementary log-log for 0/1 outcomes; poisson, negative binomial, zero-inflated for counts; ordered, multinomial for choices; tobit if censored')] = 'gaussian', censor_left: Annotated[str, Widget('text', show_if=('family', ('tobit',)), help='the lower limit (empty: none)')] = '0', censor_right: Annotated[str, Widget('text', show_if=('family', ('tobit',)), help='the upper limit (empty: none)')] = '', inflate: Annotated[str, Widget('text', show_if=('family', ('zero-inflated poisson',)), help='regressors of the probability of a structural zero, e.g. age + kids (empty: a constant)')] = '', endog: Annotated[str, Widget('series', depends_on='data', multiple=True, show_if=('method', _kind('iv')), group='Instrumental variables')] = '', instruments: Annotated[str, Widget('text', show_if=('method', _kind('iv')), group='Instrumental variables')] = '', ar: Annotated[str, Widget('text', help='AR order, e.g. 2, or lags 1, 4 (Bayes: an order)', show_if=('method', _kind('ml', 'bayes')), group='Error model')] = '', ma: Annotated[str, Widget('text', help='MA order, e.g. 1, or lags 1, 4; overlapping observations (h-step changes) give MA(h-1) errors', show_if=('method', _kind('ml', 'bayes')), group='Error model')] = '', variance: Annotated[str, Widget('extension', source='variances', show_if=('method', _kind('ml')), group='Error model', help='conditional variance: constant, or a GARCH-type model')] = 'constant', dist: Annotated[Literal['normal', 't', 'skewt', 'ged'], Widget('choice', show_if=('variance', _with_variance), group='Error model')] = 'normal', variance_settings: Annotated[str, Widget('options', depends_on='variance', source='variances', exclude=('dist',), show_if=('variance', _with_variance), group='Variance settings')] = '', cov: Annotated[Literal['classic', 'white', 'hc0', 'hc2', 'hc3', 'hc4', 'hc5', 'hac', 'cluster'], Widget('choice', group='Sample and covariance', help="white is HC1, as Stata's vce(robust); HC3 is R's vcovHC default; HC2 to HC5 for OLS only, HC0 for OLS and IV")] = 'classic', cluster: Annotated[str, Widget('series', depends_on='data', multiple=True, show_if=('cov', ('cluster',)), group='Sample and covariance', help='one or two grouping series or axes')] = '', start: Annotated[str, Widget('period', group='Sample and covariance')] = '', end: Annotated[str, Widget('period', group='Sample and covariance')] = '', name: str = 'fit', method_settings: Annotated[str, Widget('options', depends_on='method', source='methods', exclude=_MAIN_METHOD_FIELDS, group='Method settings')] = '', hac_lags: Annotated[int, Widget('number', min=0, max=100, advanced=True, group='Covariance', show_if=('cov', ('hac',)), help='Newey-West truncation lag; 0 = automatic, 4(n/100)^(2/9); more for persistent errors')] = 0, hac_correction: Annotated[bool, Widget('checkbox', advanced=True, group='Covariance', show_if=('cov', ('hac',)), help="multiply HAC by n / (n - k), as EViews and Stata's newey; untick for statsmodels' default")] = True, weights: Annotated[str, Widget('series', depends_on='data', advanced=True, group='Sample', help='weighted least squares: weights proportional to 1 / error variance; empty = none')] = '', missing: Annotated[Literal['drop', 'raise'], Widget('choice', advanced=True, group='Sample')] = 'drop', where: Annotated[str, Widget('text', advanced=True, group='Sample', help='a condition on the rows, e.g. recession == 0 or year >= 1990; empty = all rows')] = '')

Bases: Command

Estimate a single equation by least squares, instrumental variables or maximum likelihood.

Write the equation with ~, e.g. dlog(c) ~ dlog(y) + c[-1]; a constant is included unless you write - 1. Lags are x[-1]; fe(id) adds fixed effects and C(region) categorical dummies. seasonal() adds seasonal dummies (one per quarter or month, less one with a constant: seasonal[Q2] ...), and C(quarter) or C(month) takes the quarter or month from the dates. For a nonlinear equation write its explicit form and list its parameters under Params.

Choose the Method, then its settings below it. Instrumental-variable methods ask for the endogenous regressors and the excluded instruments. Maximum likelihood (ML) covers logit, probit and Poisson families, ARMA errors and GARCH-type variance models; the variance model's own settings appear under Variance settings. Bayes takes AR and MA orders too, sampling the errors' partial autocorrelations by MCMC on the exact likelihood. Covariance sets how standard errors are computed; the sample is limited by Start and End.

pymetrix.commands.FitExponentialSmoothing dataclass

FitExponentialSmoothing(series: Annotated[str, Widget('series', depends_on='data', help='the series to forecast, in levels; multiplicative options need it positive')], data: Annotated[str, Widget('object', source='Dataset')] = 'data', trend: Annotated[Literal['none', 'add', 'mul'], Widget('choice', help='none (simple smoothing), additive (Holt) or multiplicative')] = 'none', damped: Annotated[bool, Widget('checkbox', help='damp the trend towards flat (needs a trend)')] = False, seasonal: Annotated[Literal['none', 'add', 'mul'], Widget('choice', help='seasonal factors: none, additive or multiplicative (Holt-Winters)')] = 'none', error: Annotated[Literal['add', 'mul'], Widget('choice', advanced=True, help='additive or multiplicative errors (positive series)')] = 'add', start: Annotated[str, Widget('period', group='Sample', help='first period of the sample (empty = the first available)')] = '', end: Annotated[str, Widget('period', group='Sample', help='last period of the sample (empty = the last available)')] = '', name: str = 'ets')

Bases: Command

Exponential smoothing (ETS): forecast a series from a level, an optional trend (damped or not) and optional seasonal factors, each updated by a share of the latest forecast error.

No trend and no season is simple exponential smoothing; an additive trend is Holt's method; adding seasons gives Holt-Winters. Parameters and initial states are estimated by maximum likelihood (statsmodels). Forecast from the result with Forecast, or evaluate it with Forecast → Backtest.

pymetrix.commands.FitFactorModel dataclass

FitFactorModel(variables: Annotated[str, Widget('series', depends_on='data', multiple=True, help='the series to analyse (three or more)')], data: Annotated[str, Widget('object', source='Dataset')] = 'data', factors: Annotated[int, Widget('number', min=1, max=50, help='number of common factors; the test in the window says whether it is enough')] = 1, rotation: Annotated[Literal['none', 'varimax', 'promax'], Widget('choice', help='varimax: uncorrelated factors, loadings near 0 or large; promax: correlated factors (oblique)')] = 'none', start: Annotated[str, Widget('period', group='Sample')] = '', end: Annotated[str, Widget('period', group='Sample')] = '', name: str = 'fa')

Bases: Command

Maximum-likelihood factor analysis: each series a combination of a few common factors plus a part of its own.

Unlike principal components, the model separates what the series share (their communalities) from what is particular to each (its uniqueness), and tests whether the number of factors is enough: a small p-value says more are needed. Rotation makes the loadings easier to read without changing the fit: varimax keeps the factors uncorrelated, promax lets them correlate (their correlations are shown). The window shows the loadings, uniquenesses, the test and regression scores; Next ▸ adds regression or Bartlett scores to a dataset. A uniqueness at its lower bound (0.005) is a Heywood case: a series the factors explain entirely, often a sign of too many factors. The results match R's factanal.

pymetrix.commands.FitFAVAR dataclass

FitFAVAR(panel: Annotated[str, Widget('series', depends_on='data', multiple=True, help='the panel the factors come from')], observed: Annotated[str, Widget('series', depends_on='data', multiple=True, help='observed variables in the VAR, e.g. the policy rate')], factors: Annotated[str, Widget('text', help='a number, or icp1, icp2, icp3 (Bai and Ng)')] = '3', lags: Annotated[str, Widget('text', help='a number, or aic, bic, hq, fpe')] = '2', data: Annotated[str, Widget('object', source='Dataset')] = 'data', name: str = 'fv', slow: Annotated[str, Widget('series', depends_on='data', multiple=True, advanced=True, help='slow-moving series of the panel, for the purge (optional)')] = '', max_factors: Annotated[int, Widget('number', min=1, max=30, advanced=True, help='most factors the criterion considers')] = 8, max_lags: Annotated[int, Widget('number', min=1, max=24, advanced=True, help='most lags the criterion considers')] = 8)

Bases: Command

Estimate a factor-augmented VAR (Bernanke, Boivin and Eliasz).

Factors are the principal components of a panel of many series, in a VAR with the observed variables (ordered last, so a recursive ordering puts policy last). Factors can be a number or Bai and Ng's icp1, icp2 or icp3; lags a number or aic, bic, hq or fpe. Slow-moving series (output, prices) purge the factors of the observed variables.

pymetrix.commands.FitKMeans dataclass

FitKMeans(series: Annotated[str, Widget('series', depends_on='data', multiple=True, help='the series clustered on (two or more)')], data: Annotated[str, Widget('object', source='Dataset')] = 'data', k: Annotated[int, Widget('number', min=2, max=50, label='Number of clusters', help='how many clusters; Number of clusters (k-means)… helps choose')] = 3, by: Annotated[Literal['observations', 'series'], Widget('choice', help='cluster the dates (regimes over time) or the series (which move together)')] = 'observations', standardize: Annotated[bool, Widget('checkbox', help='scale each series to mean 0 and standard deviation 1 first, so each counts equally')] = True, starts: Annotated[int, Widget('number', min=1, max=1000, help='k-means++ starts; the best is kept')] = 10, seed: Annotated[int, Widget('number', min=0, max=2 ** 31 - 1, advanced=True, help='random seed for the starts: the same seed, the same clusters')] = 0, start: Annotated[str, Widget('period', group='Sample')] = '', end: Annotated[str, Widget('period', group='Sample')] = '', max_iter: Annotated[int, Widget('number', min=1, max=100000, advanced=True, help="rounds of Lloyd's algorithm at most, per start")] = 300, missing: Annotated[Literal['drop', 'refuse'], Widget('choice', advanced=True, help='dates with a missing value: left out, or stop with a message')] = 'drop', name: str = 'clusters')

Bases: Command

K-means cluster analysis: dates grouped into regimes, or series grouped by how they move.

By observations, each date is a point whose coordinates are the series, and k-means puts dates with similar readings in the same cluster: regimes over time (expansion, slowdown, stress). By series, each series is a point whose coordinates are its standardised path, and series that move together share a cluster. Standardised (the default), each series counts equally whatever its units. The best of several k-means++ starts is kept, drawn with the seed, so the clusters are the same each time. The window shows each cluster's size, spread and centre, the cluster of each date with its silhouette (near 1: clearly in its cluster; near 0: between two), and the centres as a heatmap; Next ▸ draws the clusters as a band above a surveillance heatmap. Dates with a missing value are left out. Number of clusters (k-means)… helps choose k.

pymetrix.commands.FitLocalProjection dataclass

FitLocalProjection(response: Annotated[str, Widget('text', help='the response, e.g. 100*log(gdp) or infl')], shock: Annotated[str, Widget('text', help='the shock, e.g. an identified monetary surprise or the policy rate')], data: Annotated[str, Widget('object', source='Dataset')] = 'data', horizons: Annotated[int, Widget('number', min=0, max=60, help="longest horizon traced; a few years of the data's frequency, as long horizons lose observations and precision")] = 12, lags: Annotated[int, Widget('number', min=0, max=24, help='lags of the response, the shock and the controls')] = 4, controls: Annotated[str, Widget('series', depends_on='data', multiple=True, help='variables whose lags are controlled for, to absorb predictable movements in the shock and response')] = '', contemporaneous: Annotated[str, Widget('series', depends_on='data', multiple=True, help='controls dated at the time of the shock (ordered before it)')] = '', long_difference: Annotated[bool, Widget('checkbox', help='response y[t+h] - y[t-1], for variables in log levels')] = False, cov: Annotated[Literal['hac', 'white'], Widget('choice', show_if=('smooth', (False,)), help='hac: Newey-West with h+1 lags; white: lag-augmented robust')] = 'hac', start: Annotated[str, Widget('period', group='Sample')] = '', end: Annotated[str, Widget('period', group='Sample')] = '', name: str = 'lp', state: Annotated[str, Widget('text', advanced=True, help='state indicator series (0 to 1), dated t-1; empty = none')] = '', scale: Annotated[float, Widget('number', min=1e-06, max=1000000.0, advanced=True, help='size of the shock the responses are scaled to')] = 1.0, instruments: Annotated[str, Widget('series', depends_on='data', multiple=True, advanced=True, help='external instruments for the shock (LP-IV); empty = none')] = '', smooth: Annotated[bool, Widget('checkbox', advanced=True, help='a smooth response: a penalised spline in the horizon, the penalty by cross-validation')] = False, coverage: Annotated[float, Widget('number', min=0.5, max=0.99, step=0.01, advanced=True, help="the wide bands' coverage, e.g. 0.9 for 90% (68% bands are drawn too)")] = 0.9, penalty: Annotated[float | None, Widget('number', min=0.0, max=100000000.0, step=1, advanced=True, show_if=('smooth', (True,)), help='the smoothing penalty; empty = by cross-validation')] = None, order: Annotated[int, Widget('number', min=1, max=4, advanced=True, show_if=('smooth', (True,)), help="the penalty's order: 2 shrinks towards a straight line, 1 towards a constant")] = 2, folds: Annotated[int, Widget('number', min=2, max=20, advanced=True, show_if=('smooth', (True,)), help='blocks of consecutive periods for the cross-validation that sets the smoothing penalty')] = 5, bootstrap_kind: Annotated[Literal['analytic', 'wild', 'block', 'pairs', 'residual'], Widget('choice', advanced=True, group='Bootstrap', help='how the bands are made: analytic (from the standard errors, as before), or a bootstrap of all horizons together: wild (heteroskedastic errors; with the lag-augmented robust form), block (the overlapping errors), pairs (blocks of periods of the data) or residual (iid)')] = 'analytic', draws: Annotated[int, Widget('number', min=1, max=100000, step=100, advanced=True, group='Bootstrap', show_if=('bootstrap_kind', ('wild', 'block', 'pairs', 'residual')), help='bootstrap draws for the bands')] = 999, seed: Annotated[int, Widget('number', min=0, max=2 ** 31 - 1, advanced=True, group='Bootstrap', show_if=('bootstrap_kind', ('wild', 'block', 'pairs', 'residual')), help='random seed for the bootstrap')] = 0, block_length: Annotated[int, Widget('number', min=0, max=400, advanced=True, group='Bootstrap', show_if=('bootstrap_kind', ('block', 'pairs')), help='block and pairs bootstraps: periods in a block; 0 = automatic (5.03 T^(1/4))')] = 0, block_type: Annotated[Literal['moving', 'stationary'], Widget('choice', advanced=True, group='Bootstrap', show_if=('bootstrap_kind', ('block', 'pairs')), help='moving blocks of a fixed length, or stationary blocks of random length')] = 'moving', wild_dist: Annotated[Literal['rademacher', 'mammen', 'normal'], Widget('choice', advanced=True, group='Bootstrap', show_if=('bootstrap_kind', ('wild',)), help="wild bootstrap: the multipliers, Rademacher (plus or minus one), Mammen's or normal")] = 'rademacher', band_type: Annotated[Literal['percentile', 'hall', 'studentized'], Widget('choice', advanced=True, group='Bootstrap', show_if=('bootstrap_kind', ('wild', 'block', 'pairs', 'residual')), help="percentile bands, Hall's (reflected about the estimate) or studentized (from each draw's t statistic)")] = 'percentile')

Bases: Command

Impulse responses by local projection: one regression of the response at each horizon on the shock.

The response and shock can be series or expressions (100*log(gdp)). Lags of the response, the shock and the controls are included; controls dated at the time of the shock put them before it in a recursive ordering. Tick Long difference for variables in log levels. Standard errors allow for the overlap between horizons (Newey-West with h+1 lags), or use the lag-augmented robust form. A state indicator (0 to 1) gives separate responses in each state, with a test of their difference. External instruments for the shock make each horizon's regression two-stage least squares (LP-IV), with each horizon's first-stage F.

The responses are causal only if the shock is: an identified shock series, or a variable made exogenous by the controls and the recursive ordering. Local projections are robust to misspecified dynamics, as each horizon has its own regression, but they are less efficient than a VAR, so the responses are noisier and become erratic at long horizons where the sample per regression also shrinks. Smoothing trades a little bias for much less noise. Read the bands (68% and the wider level) horizon by horizon; they are not joint bands for the whole path. With LP-IV, a first-stage F well above 10 at each horizon guards against weak instruments.

pymetrix.commands.FitMarkovSwitching dataclass

FitMarkovSwitching(formula: Annotated[str, Widget('formula', help='dependent variable on the regressors whose coefficients switch; growth ~ 1 switches only the mean')], data: Annotated[str, Widget('object', source='Dataset')] = 'data', regimes: Annotated[int, Widget('number', min=2, max=5, help='number of regimes; two (e.g. expansion and recession) is usual, more need a long sample')] = 2, ar: Annotated[int, Widget('number', min=0, max=12, help='autoregressive lags whose coefficients also switch between regimes; 0 = none')] = 0, switching_variance: Annotated[bool, Widget('checkbox', help='let the error variance differ between regimes')] = False, start: Annotated[str, Widget('period', group='Sample')] = '', end: Annotated[str, Widget('period', group='Sample')] = '', name: str = 'ms', search: Annotated[int, Widget('number', min=0, max=500, advanced=True, help='random starting values tried besides the default; more guards against a local maximum')] = 20, seed: Annotated[int, Widget('number', min=0, max=2 ** 31 - 1, advanced=True)] = 0)

Bases: Command

A regression whose intercept and coefficients switch between unobserved regimes (Hamilton 1989).

Write the dependent variable on the regressors (growth ~ 1 for a switching mean). The regimes follow a Markov chain; the result shows each regime's coefficients, the transition probabilities, the expected duration of each regime and the probability of each regime in each period.

The regimes are unlabelled: read them from their estimates (a low-mean regime may be recessions). The smoothed probabilities use the whole sample and are the ones to date regimes with; a regime that is rarely visited, or a transition probability near 1 that makes a regime last for the whole sample, suggests too many regimes. The likelihood often has several local maxima, so the fit tries random starting values; if results change with the seed, raise the number tried. Standard tests of the number of regimes are not valid (a parameter is unidentified under the null), so do not compare a two-regime model with a linear one by a likelihood-ratio test.

pymetrix.commands.FitMIDAS dataclass

FitMIDAS(formula: Annotated[str, Widget('formula', help='e.g. gdp ~ ip + sales (high-frequency series names)')], low: Annotated[str, Widget('object', source='Dataset', help='the low-frequency data (e.g. quarterly)')], high: Annotated[str, Widget('object', source='Dataset', help='the high-frequency data (e.g. monthly)')] = 'data', lags: Annotated[int, Widget('number', min=2, max=60, help='high-frequency lags of each indicator, e.g. 12 months; with unrestricted weights each costs a parameter')] = 12, weights: Annotated[Literal['exp_almon', 'beta', 'unrestricted'], Widget('choice', help='lag weights: exp_almon or beta (two parameters each, smooth) or unrestricted (one per lag)')] = 'exp_almon', ar: Annotated[int, Widget('number', min=0, max=8, help='lags of the low-frequency dependent variable, for persistence; 0 = none')] = 0, high_lag: Annotated[int, Widget('number', min=0, max=24, advanced=True, help='high-frequency periods missing at the end (nowcasting)')] = 0, name: str = 'midas', mask: Annotated[str, Widget('text', advanced=True, help='periods left out of the estimation sample, e.g. 2020-03 to 2021-06; ranges and periods separated by semicolons; empty = none')] = '')

Bases: Command

Regress a low-frequency series (quarterly GDP) on high-frequency indicators (monthly), through lag weights.

Exponential Almon and Beta weights describe many monthly lags with two parameters each; unrestricted estimates every lag. Data short at the end lets you build a nowcast as the quarter's months arrive. The result's nowcast() gives the series for every quarter the indicators cover.

The weighting scheme is the main modelling choice. Exponential Almon and Beta weights let many lags enter with few parameters, which keeps the model parsimonious when the low-frequency sample is short, but impose a smooth lag shape; unrestricted MIDAS estimates every lag freely and suits a small frequency gap (monthly to quarterly) and few lags. Inspect the estimated lag weights: they show which months carry the information. Series should be stationary (growth rates). Evaluate nowcasts out of sample with the high-frequency lag set to mimic the data available at the time.

Masked periods (under Advanced) leave those quarters out of the estimation sample, e.g. 2020-03 to 2021-06 for the pandemic (a quarter is masked when any of its months is): ranges and single periods separated by semicolons. Their values are still used as lags.

pymetrix.commands.FitPanelMeanGroup dataclass

FitPanelMeanGroup(outcome: Annotated[str, Widget('series', depends_on='data', help='the dependent series')], regressors: Annotated[str, Widget('series', depends_on='data', multiple=True, help='the regressors')], data: Annotated[str, Widget('object', source='Dataset', help='a panel with long time series: an entity and a time axis')] = 'data', method: Annotated[Literal['mean group', 'cce mean group', 'cce pooled', 'pooled mean group'], Widget('choice', help='unit-by-unit slopes averaged; with cross-section averages (CCE), averaged or pooled; or a common long run (pooled mean group)')] = 'mean group', trend: Annotated[bool, Widget('checkbox', show_if=('method', ('mean group',)), help="a linear trend in each unit's regression")] = False, lags: Annotated[int, Widget('number', min=1, max=12, show_if=('method', ('pooled mean group',)), help='lags of the ARDL (the short run in differences has one fewer)')] = 1, name: str = 'panel_mg')

Bases: Command

Heterogeneous panels with long time series: the mean group, common correlated effects (mean group or pooled) and the pooled mean group estimators.

Mean group (Pesaran and Smith) fits least squares unit by unit and averages the coefficients, with standard errors from their spread across units: consistent when the slopes differ by unit, where pooled estimators are not. CCE (Pesaran 2006) adds the cross-section averages of the dependent variable and the regressors to each unit's regression, absorbing unobserved common factors whatever their loadings; its mean group averages the units' slopes, its pooled version pools them. The pooled mean group (Pesaran, Shin and Smith) estimates an error-correction ARDL with a common long run and unit-specific adjustment and short-run dynamics, by maximum likelihood; its window has the Hausman test of the common long run against the mean group of the units' own long runs (a small p-value rejects the common long run).

Each unit needs more periods than coefficients. The data must be a panel (an entity axis and a time axis).

pymetrix.commands.FitPCA dataclass

FitPCA(variables: Annotated[str, Widget('series', depends_on='data', multiple=True, help='the series to summarise (two or more)')], data: Annotated[str, Widget('object', source='Dataset')] = 'data', n: Annotated[int, Widget('number', min=0, max=100, label='Components kept', help="how many components to keep; 0 = all (the window's criteria help choose)")] = 0, standardize: Annotated[bool, Widget('checkbox', help='scale each series to unit variance first (the correlation matrix): do so unless the series share units')] = True, start: Annotated[str, Widget('period', group='Sample')] = '', end: Annotated[str, Widget('period', group='Sample')] = '', name: str = 'pca')

Bases: Command

Principal components: the weighted averages of a set of series that explain most of their variance.

The first component is the combination that varies most; each later one varies most among those uncorrelated with the ones before. Standardized (the default), each series counts equally whatever its units (the correlation matrix); otherwise series with larger variances dominate (the covariance matrix). The window shows the loadings, the variance each component explains, Bai and Ng's criteria for the number of factors, and the components period by period; Next ▸ adds them to a dataset, for a regression or a bridge equation on factors. Only periods where every series is observed are used: for missing values and mixed frequencies, use the dynamic factor model (Estimate → Mixed frequency).

pymetrix.commands.FitRolling dataclass

FitRolling(formula: Annotated[str, Widget('formula', help='the equation re-estimated in every window, e.g. c ~ y + c[-1]')], params: Annotated[str, Widget('text', help='comma-separated parameter names; empty for the linear form')] = '', data: Annotated[str, Widget('object', source='Dataset')] = 'data', window: Annotated[int, Widget('number', help='moving-window length in periods; 0 = expanding (recursive)', min=0, max=10000)] = 0, min_obs: Annotated[int, Widget('number', advanced=True, help='recursive: periods in the first window; 0 = parameters + 1', min=0, max=10000)] = 0, cov: Annotated[Literal['classic', 'white', 'hac'], Widget('', help='classic, white (robust) or hac (Newey-West): the bands around the coefficient paths')] = 'classic', start: Annotated[str, Widget('period')] = '', end: Annotated[str, Widget('period')] = '', name: str = 'rolling', step: Annotated[int, Widget('number', min=1, max=1000, advanced=True, help='estimate every step-th window')] = 1, hac_lags: Annotated[int, Widget('number', min=0, max=100, advanced=True, show_if=('cov', ('hac',)), help='Newey-West truncation lag; 0 = automatic, 4(n/100)^(2/9)')] = 0)

Bases: Command

Estimate an equation over moving or expanding windows, with recursive residuals and CUSUM tests.

Window 0 gives recursive (expanding-window) estimation, starting from Min obs periods; a positive window gives rolling estimates. Results include coefficient paths and pseudo out-of-sample forecasts.

Read the coefficient paths against their two-standard-error bands: a coefficient that drifts well outside its earlier bands points to a structural break or an omitted variable, which the CUSUM tests (Test > Run test, on the full-sample fit) check formally. A rolling window tracks change faster but each estimate is noisier; a short window also widens the bands, so apparent movement may be sampling noise. The pseudo out-of-sample forecasts use only data up to each window's end, a fairer test of forecasting ability than the in-sample fit.

pymetrix.commands.FitStateSpace dataclass

FitStateSpace(states: Annotated[str, Widget('text', help='the unobserved states, e.g. trend, cycle')], transition: Annotated[str, Widget('multiline', help='one equation per state: state = ... lagged states and shocks')], measurement: Annotated[str, Widget('multiline', help='one per observed series: series = ... current or lagged states')], shocks: Annotated[str, Widget('text', help="each shock's standard deviation: e_trend = sd_trend, u_y = 0.1")], params: Annotated[str, Widget('text', help='parameters to declare, e.g. phi1, phi2, sd_trend')] = '', stationary: Annotated[str, Widget('text', help='states that are stationary (cycles, gaps)')] = '', data: Annotated[str, Widget('object', source='Dataset')] = 'data', fixed: Annotated[str, Widget('text', advanced=True, help='calibrated values instead of estimates, e.g. sd_slope = 0')] = '', start: Annotated[str, Widget('period', group='Sample')] = '', end: Annotated[str, Widget('period', group='Sample')] = '', name: str = 'ssm', cov: Annotated[Literal['classic', 'none'], Widget('choice', advanced=True, help='standard errors from the Hessian (classic), or none (faster)')] = 'classic', max_iter: Annotated[int, Widget('number', min=10, max=100000, step=100, advanced=True, help='most iterations of the likelihood optimiser; raise it if the fit does not converge')] = 2000, diffuse_terms: Annotated[Literal['include', 'exclude'], Widget('choice', advanced=True, help="the log likelihood's diffuse periods (the first ones, until the non-stationary states are pinned down): included (the exact diffuse likelihood, Durbin and Koopman) or left out (as statsmodels reports it); only the level of the log likelihood, AIC and BIC changes")] = 'include')

Bases: Command

Estimate a state-space model written as equations, with the Kalman filter.

One equation per line. Transition equations give each state from lagged states and shocks (cycle = phi1*cycle[-1] + phi2*cycle[-2] + e_cycle); measurement equations link observed series to the states (y = trend + cycle + u_y). Each shock has a standard deviation, a parameter or a number (e_cycle = sd_cycle, u_y = 0.1). Declare every parameter; states listed as stationary (cycles, gaps) start from their stationary distribution. Fixed values calibrate parameters instead of estimating them.

pymetrix.commands.FitSystem dataclass

FitSystem(equations: Annotated[str, Widget('object', source='Equation', multiple=True, help='equations to estimate, and identities')], method: Annotated[str, Widget('extension', source='systems', help='SUR for errors correlated across equations; 2SLS or 3SLS when regressors are endogenous')] = 'sur', method_settings: Annotated[str, Widget('options', depends_on='method', source='systems', group='Method settings')] = '', data: Annotated[str, Widget('object', source='Dataset')] = 'data', instruments: Annotated[str, Widget('text', help='extra instruments for 2SLS and 3SLS, e.g. g, r[-1]')] = '', restrictions: Annotated[str, Widget('text', help='linear restrictions imposed in estimation, within or across equations, e.g. c.y = i.y, a + b = 1')] = '', start: Annotated[str, Widget('period', group='Sample')] = '', end: Annotated[str, Widget('period', group='Sample')] = '', name: str = 'sys', endogenous: Annotated[str, Widget('text', advanced=True, help='further endogenous variables, besides the left-hand sides')] = '')

Bases: Command

Estimate several equations together: SUR for errors correlated across equations, 3SLS when regressors are also endogenous.

Choose the equations (define them first with Model > Define equation). Identities are not estimated, but their left-hand sides count as endogenous. For 2SLS and 3SLS, the instruments are the constant and every regressor that does not involve the current value of an endogenous variable, plus those you add. Restrictions refer to linear-form coefficients as equation.coefficient (c.y), and to explicit-form parameters by name.

SUR gains efficiency over equation-by-equation OLS when the errors are correlated across equations and the equations have different regressors; with identical regressors and no restrictions it reproduces OLS. 3SLS is consistent when regressors are endogenous and efficient when every equation is correctly specified, but a misspecified equation contaminates the others' estimates, whereas 2SLS keeps the damage to that equation. Compare 2SLS and 3SLS estimates as an informal check. Each equation must be identified: at least as many instruments as endogenous regressors on its right-hand side.

pymetrix.commands.FitThresholdAR dataclass

FitThresholdAR(series: Annotated[str, Widget('series', depends_on='data', help='the series, e.g. GDP growth')], data: Annotated[str, Widget('object', source='Dataset')] = 'data', lags: Annotated[int, Widget('number', min=1, max=12, help='the autoregressive order in each regime')] = 1, delay: Annotated[int, Widget('number', min=0, max=12, help='the lag that switches regimes; 0 = choose')] = 0, trim: Annotated[float, Widget('number', min=0.05, max=0.4, step=0.05, advanced=True, help='least share of observations in each regime; keeps thresholds that leave too little data from being chosen')] = 0.15, start: Annotated[str, Widget('period', group='Sample', help='first period of the sample (empty = the first available)')] = '', end: Annotated[str, Widget('period', group='Sample', help='last period of the sample (empty = the last available)')] = '', name: str = 'tar')

Bases: Command

A two-regime threshold autoregression (SETAR): the series follows one AR when its own lagged value is at or below a threshold, another above it.

The threshold and the delay (which lag switches regimes) are chosen by least squares. The result's Tests tab has Hansen's threshold test and Teräsvirta's test against smooth transition; forecasts are simulated, so multi-step forecasts reflect the regimes.

pymetrix.commands.FitTransferFunction dataclass

FitTransferFunction(series: Annotated[str, Widget('series', depends_on='data', help='the series whose response is modelled')], inputs: Annotated[str, Widget('text', help='interventions or input series, separated by commas, e.g. step("2011Q1"), pulse("2011Q1")')], data: Annotated[str, Widget('object', source='Dataset')] = 'data', decay: Annotated[str, Widget('text', help='the inputs (as written above) whose effect decays: a first-order delta (den = 1)')] = '', order: Annotated[str, Widget('text', help='p, d, q of the disturbance')] = '1, 0, 0', seasonal_order: Annotated[str, Widget('text', advanced=True, help='P, D, Q of the disturbance')] = '0, 0, 0', trend: Annotated[Literal['auto', 'n', 'c', 't', 'ct'], Widget('choice', help='auto: a constant without differencing, none with it')] = 'auto', start: Annotated[str, Widget('period', group='Sample', help='first period of the sample (empty = the first available)')] = '', end: Annotated[str, Widget('period', group='Sample', help='last period of the sample (empty = the last available)')] = '', name: str = 'tf')

Bases: Command

The effect of an intervention or an input series with dynamics: rational transfer functions with ARIMA errors.

Each input is an intervention, written from its date: step("2011Q1") from that period on, pulse("2011Q1") for one period, ramp, temporary(date, decay=d) or seasonal_pulse, or a series of the data. Its effect is omega / (1 - delta L) applied to it when it decays (Decay inputs), omega alone otherwise: a pulse that decays is a temporary effect, a step that decays builds up gradually to its long-run level omega / (1 - delta). The disturbance is an ARIMA(p, d, q)(P, D, Q). Everything is estimated by exact maximum likelihood.

The result gives the effect path (permanent and temporary parts, cumulative), the counterfactual (the series without the interventions), and forecasts that carry the effects as they unwind.

pymetrix.commands.FitUnobservedComponents dataclass

FitUnobservedComponents(series: Annotated[str, Widget('series', depends_on='data', help='the series to decompose, e.g. 100*log of real GDP')], data: Annotated[str, Widget('object', source='Dataset')] = 'data', trend: Annotated[Literal['local level', 'random walk with drift', 'local linear trend', 'smooth trend'], Widget('choice', help='how the trend moves: smooth trend gives an HP-like trend')] = 'local linear trend', cycle: Annotated[int, Widget('number', min=0, max=4, help='order of the autoregressive cycle; 0 = no cycle')] = 2, irregular: Annotated[bool, Widget('checkbox', help='include a white-noise irregular component')] = True, start: Annotated[str, Widget('period', group='Sample')] = '', end: Annotated[str, Widget('period', group='Sample')] = '', name: str = 'uc', diffuse_terms: Annotated[Literal['include', 'exclude'], Widget('choice', advanced=True, help="the log likelihood's diffuse periods (the first ones, until the trend is pinned down): included (the exact diffuse likelihood, Durbin and Koopman) or left out (as statsmodels reports it); only the level of the log likelihood, AIC and BIC changes")] = 'include')

Bases: Command

Split a series into trend, cycle and irregular, estimated with the Kalman filter.

Choose how the trend moves and the order of the autoregressive cycle. The smoothed trend and cycle use all the data (two-sided); the filtered ones use only the data up to each period (real-time), which is what a policymaker would have seen. Add either to the dataset with Data → Add results to dataset.

pymetrix.commands.FitVAR dataclass

FitVAR(variables: Annotated[str, Widget('series', depends_on='data', multiple=True, help="the VAR's series, in the list's order: the default Cholesky ordering")], lags: Annotated[str, Widget('text', help='a number, or aic / bic / hq / fpe to choose')] = '2', max_lags: Annotated[int, Widget('number', advanced=True, help='searched when lags is a criterion', min=1, max=24)] = 8, exog: Annotated[str, Widget('text', help='exogenous expressions (optional)', advanced=True)] = '', trend: Literal['c', 'ct', 'n'] = 'c', data: Annotated[str, Widget('object', source='Dataset')] = 'data', start: Annotated[str, Widget('period')] = '', end: Annotated[str, Widget('period')] = '', name: str = 'var', bayesian: Annotated[bool, Widget('checkbox', help='a Bayesian VAR with a Minnesota prior', group='Bayesian')] = False, tightness: Annotated[float, Widget('number', min=0.0001, max=10, step=0.05, help='overall tightness; smaller shrinks more', show_if=('bayesian', (True,)), group='Bayesian')] = 0.2, own_mean: Annotated[float, Widget('number', min=-2, max=2, step=0.1, help='prior mean of own first lag: 1 for levels, 0 for growth rates', show_if=('bayesian', (True,)), group='Bayesian')] = 1.0, sum_of_coefficients: Annotated[str, Widget('text', advanced=True, help='sum-of-coefficients prior, e.g. 1; empty = none', show_if=('bayesian', (True,)), group='Bayesian')] = '', initial_observation: Annotated[str, Widget('text', advanced=True, help='single-unit-root prior, e.g. 1; empty = none', show_if=('bayesian', (True,)), group='Bayesian')] = '', optimize: Annotated[bool, Widget('checkbox', advanced=True, help='choose the hyperparameters by marginal likelihood', show_if=('bayesian', (True,)), group='Bayesian')] = False, draws: Annotated[int, Widget('number', min=100, max=100000, step=500, advanced=True, help='posterior draws (Bayesian)')] = 5000, seed: Annotated[int, Widget('number', min=0, max=2 ** 31 - 1, advanced=True, help='random seed for posterior draws (Bayesian)')] = 0, independent: Annotated[bool, Widget('checkbox', advanced=True, help="the independent normal-Wishart form, sampled by Gibbs (hyperparameter search by Chib's marginal likelihood)", show_if=('bayesian', (True,)), group='Bayesian')] = False, cross_tightness: Annotated[float, Widget('number', advanced=True, min=0.0001, max=1, step=0.05, help="other variables' lags relative to own (independent prior)", show_if=('independent', (True,)), group='Bayesian')] = 0.5, zeros: Annotated[str, Widget('text', advanced=True, group='Restrictions', help='regressors left out of equations, e.g. pi: r; b: a[-2], const')] = '', block_exogenous: Annotated[str, Widget('text', advanced=True, group='Restrictions', help="variables whose equations leave out the others' lags, e.g. oil")] = '', iterate: Annotated[bool, Widget('checkbox', advanced=True, group='Restrictions', help='iterate the feasible GLS to maximum likelihood')] = False, hierarchical: Annotated[bool, Widget('checkbox', advanced=True, show_if=('bayesian', (True,)), group='Bayesian', help='Giannone-Lenza-Primiceri: hyperpriors on the tightness, the dummy-observation priors and the scales, estimated (the tightness and dummy fields above are then not used)')] = False, hyper_mcmc: Annotated[bool, Widget('checkbox', advanced=True, show_if=('hierarchical', (True,)), group='Bayesian', help='integrate over the hyperparameters by MCMC, rather than fix them at their posterior mode')] = False, hyper_decay: Annotated[bool, Widget('checkbox', advanced=True, show_if=('hierarchical', (True,)), group='Bayesian', help="estimate the lag decay too, with a gamma hyperprior (else: fixed, GLP's 1)")] = False)

Bases: Command

Estimate a vector autoregression, by least squares or with a Bayesian (Minnesota) prior.

Tick the series: they enter in the list's order, which is the order used for Cholesky identification (Impulse responses can reorder them). Lags is a number, or a criterion (aic, bic, hq, fpe) to choose it up to Max lags. Tick Bayesian to shrink the coefficients towards random walks (own mean 1; 0 for growth rates): smaller tightness shrinks more, and the sum-of-coefficients and initial-observation priors pull towards unit roots. Choose hyperparameters lets the marginal likelihood pick them. Independent prior samples the independent normal-Wishart form by Gibbs, which can shrink other variables' lags harder (cross tightness).

pymetrix.commands.FitVECM dataclass

FitVECM(variables: Annotated[str, Widget('series', depends_on='data', multiple=True, help='levels of the (cointegrated) series')], lags: Annotated[int, Widget('number', min=0, max=24, help='lags in first differences')] = 1, rank: Annotated[str, Widget('text', help='a number, or trace / maxeig to choose by Johansen tests')] = 'trace', deterministic: Case = 'unrestricted constant (case 3)', data: Annotated[str, Widget('object', source='Dataset')] = 'data', start: Annotated[str, Widget('period')] = '', end: Annotated[str, Widget('period')] = '', name: str = 'vecm', exog: Annotated[str, Widget('text', advanced=True, help='unrestricted exogenous expressions')] = '', exog_coint: Annotated[str, Widget('text', advanced=True, help='exogenous expressions inside the cointegrating relations')] = '', seasons: Annotated[int, Widget('number', min=0, max=52, advanced=True, help='seasonal dummies: 4 quarterly, 12 monthly; 0 = none')] = 0, first_season: Annotated[int, Widget('number', min=0, max=51, advanced=True, help="season of the sample's first period, counting from 0: 2 for data starting in Q3 or March")] = 0, signif: Annotated[Literal[0.05, 0.1, 0.01], Widget('choice', advanced=True, help='significance level for choosing the rank')] = 0.05)

Bases: Command

Estimate a vector error-correction model for cointegrated series.

Give the series in levels. The cointegrating rank can be fixed or chosen by Johansen's trace or maximum- eigenvalue test; choose where the constant and trend enter.

The rank is the number of long-run (cointegrating) relations. If the tests find rank 0 the series are not cointegrated and a VAR in differences is the model; full rank means the series look stationary, so a VAR in levels is; both stop with a message. The deterministic case changes both the rank tests and the meaning of the relations: case 2 puts the constant only inside them (no drift in the levels), case 3, the usual choice for trending macro series, lets the levels drift. Check that the estimated adjustment coefficients have the signs that pull the variables back towards the relation; normalisation and the signs of the cointegrating vector decide which.

pymetrix.commands.FreezeSeries dataclass

FreezeSeries(data: Annotated[str, _DATA], series: Annotated[str, Widget('text', help='comma-separated derived series to freeze')])

Bases: Command

Keep a derived series' values but drop its recipe, so it can be edited.

pymetrix.commands.GeneralToSpecific dataclass

GeneralToSpecific(fit: Annotated[str, Widget('object', source='FittedEquation', help='the general unrestricted model (GUM), fitted by least squares')], data: Annotated[str, Widget('object', source='Dataset', help='the data the GUM was fitted to')] = 'data', t_pval: Annotated[float, Widget('number', min=0.0001, max=0.5, help='target size: the t-test level for deleting a term (0.05, 0.01...)')] = 0.05, diagnostics: Annotated[str, Widget('text', help='checks each reduced model must pass: autocorrelation, arch, normality, white, breusch_pagan, reset (empty: none)')] = 'autocorrelation, arch', diag_pval: Annotated[float, Widget('number', min=0.0001, max=0.5, help='the level of the diagnostic checks')] = 0.025, keep: Annotated[str, Widget('text', help='terms never deleted, separated by commas (const: the constant)')] = 'const', ic: Annotated[Literal['bic', 'aic', 'hq'], Widget('choice', help='the criterion that chooses among the terminal models')] = 'bic', max_paths: Annotated[int, Widget('spin', min=0, max=1000, advanced=True, help='most search paths; 0 = one for each insignificant term')] = 0, name: str = 'selection')

Bases: _Selection

General-to-specific model selection from a general unrestricted model (GUM), as Autometrics and R's gets.

Start from a fitted equation with plenty of lags of the dependent variable and the regressors (the GUM). Each insignificant term starts a search path; along a path the least significant term is deleted, one at a time, while the smaller model still passes the encompassing test against the GUM and the diagnostic checks. A deletion that fails a check is undone (backtracking) and the term stays on that path. The terminal models of the paths are compared by an information criterion, and the best is the final model.

The target size (t_pval) is the share of irrelevant terms expected to be kept by chance: 0.05 keeps about one in twenty, 0.01 one in a hundred. Diagnostics the GUM itself fails are left out of the search, with a warning. The record shows each path's deletions and the test that allowed or blocked each one.

pymetrix.commands.GenerateSeries dataclass

GenerateSeries(series: Annotated[str, Widget('text', help='name of the new series: a plain name, e.g. ly or growth; with For each, a template such as {x}_g or dl_{x}')], formula: Annotated[str, Widget('formula', help='expression of existing series, e.g. log(y), c / y * 100, y[-1]; computed over all periods; with For each, a template such as 100*d(log({x}))')], data: Annotated[str, Widget('object', source='Dataset')] = 'data', keep_updated: Annotated[bool, Widget('checkbox', help='keep the formula, so the series follows its inputs (a derived series)')] = False, replace: Annotated[bool, Widget('checkbox', help='replace a series of the same name, if there is one')] = False, for_each: Annotated[str, Widget('text', group='For each', help='make one series for each of these: names (gdp cons inv), wildcards (*_sa, ip_*) or both; empty: just one series')] = '', within: Annotated[str, Widget('object', source='Sample', advanced=True, group='Within', help="assign only the rows of this named sample and keep the others' values; empty: every row, or the periods below")] = '', start: Annotated[str, Widget('period', advanced=True, group='Within', help="assign from this period only (with End: EViews' smpl before y = ...)")] = '', end: Annotated[str, Widget('period', advanced=True, group='Within', help='assign up to this period only')] = '')

Bases: Command

Add a series computed once from a formula; its values stay as computed (like EViews' genr).

For a series that keeps following its inputs, tick Keep updated (a derived series). To make one for each of several series, fill in For each: a list (gdp cons inv), wildcards (*_sa, ip_*) or the series picked in the dataset's series browser (Generate for each…). Series and Formula are then templates: {x} is each series, {1}, {2}... the parts a wildcard matched (ip_* with {1}_growth). The preview lists every new series before it is made, and the step records them all, written out, in one call.

Within (under Advanced) assigns only the periods or rows of a sample, a named one or a first and last period, and keeps the other values (missing in a new series): EViews' smpl, then y = .... A formula that uses the series it assigns is then computed one period at a time, so y[-1]*1.02 grows y through the sample.

preview

preview(session: Session) -> Any

What For each would make (pymetrix.data.each.preview_each): a row per new series, checked.

preview_rows

preview_rows(session: Session) -> dict[str, Any] | None

The dialog's preview table (None: nothing to preview, a single series): headings, rows (new series, formula, note), marks per row ("error", "warning" or ""), a summary and whether it can run (ok).

formulas

formulas(session: Session | None = None) -> dict[str, str]

New name -> formula: the one series, or with For each each series it stands for in the dataset.

pymetrix.commands.GregoryHansenTest dataclass

GregoryHansenTest(outcome: Annotated[str, Widget('series', depends_on='data', help='the dependent series, in levels')], regressors: Annotated[str, Widget('series', depends_on='data', multiple=True, help='the regressors, in levels (up to four for the asymptotic values)')], data: Annotated[str, Widget('object', source='Dataset', help='time series in levels, I(1)')] = 'data', model: Annotated[Literal['level', 'trend', 'regime'], Widget('choice', help='what breaks: the level, the level with a trend, or the level and the slopes')] = 'level', lags: Annotated[int, Widget('number', min=0, max=24, help='lagged differences in the ADF regression of the residuals')] = 1, name: str = 'gregory_hansen_test', trim: Annotated[float, Widget('number', min=0.05, max=0.45, step=0.05, advanced=True, help='the share of the sample at each end where no break is considered')] = 0.15, draws: Annotated[int, Widget('number', min=50, max=100000, step=100, advanced=True, help='random-walk replications for the p-value and critical values')] = 500, seed: Annotated[int, Widget('number', min=0, max=2 ** 31 - 1, advanced=True, help='random seed of the replications')] = 0, start: Annotated[str, Widget('period', advanced=True)] = '', end: Annotated[str, Widget('period', advanced=True)] = '')

Bases: Command

Gregory and Hansen's test of no cointegration against cointegration with one break at an unknown date.

For each candidate break date (all but the trimmed ends of the sample) the cointegrating regression is fitted with a level shift, a level shift and a trend, or a regime shift (level and slopes), and the ADF statistic of its residuals computed; the test takes the smallest. Its p-value and critical values are simulated from independent random walks of the same length (Replications); the asymptotic ones of Gregory and Hansen (1996) are in the details for up to four regressors. The date of the smallest statistic is reported as the break, but the test is not a reliable way to date it. Rejecting does not show that there was a break: a relation without one rejects too, so run the usual Engle-Granger or Johansen test as well.

pymetrix.commands.Hausman dataclass

Hausman(consistent: Annotated[str, Widget('object', source='FittedEquation', help='e.g. the fixed-effects fit')], efficient: Annotated[str, Widget('object', source='FittedEquation', help='e.g. the random-effects fit')], name: str = 'hausman', sigma: Annotated[Literal['efficient', 'separate'], Widget('choice', advanced=True, help="efficient: both covariances use the efficient fit's error variance (Stata's sigmamore)")] = 'efficient')

Bases: Command

Hausman test comparing a consistent and an efficient estimate (e.g. fixed against random effects).

The efficient estimate must be consistent under the null; the test asks whether the two differ systematically.

For fixed against random effects, a small p-value means the individual effects are correlated with the regressors, so random effects is inconsistent and fixed effects is preferred. A large p-value does not prove random effects right: the test may lack power. The classic test assumes the efficient estimator is fully efficient, which fails with heteroskedastic or clustered errors; then use a robust alternative, such as the Mundlak (correlated random effects) approach.

pymetrix.commands.HistoricalDecomposition dataclass

HistoricalDecomposition(var: Annotated[str, Widget('object', source='FittedVAR,FittedVECM,FittedPanelVAR,ProxySVAR,FittedBVARSV,FittedMSVAR')], scheme: Annotated[Literal['Cholesky', 'LongRun', 'SignRestrictions', 'MaxShare', 'News'], Widget('', help=_SCHEME_HELP_HD)] = 'Cholesky', ordering: Annotated[str, Widget('text', help='Cholesky order, most exogenous first; empty = VAR order', show_if=('scheme', ('Cholesky',)))] = '', signs: Annotated[str, Widget('text', help='each shock and the signs of its responses: supply: gy+, pi-; demand: gy+, pi+', show_if=('scheme', ('SignRestrictions',)))] = '', sign_horizon: Annotated[int, Widget('number', min=0, max=40, help='the signs hold on impact and for this many periods after', show_if=('scheme', ('SignRestrictions',)))] = 0, zeros: Annotated[str, Widget('text', help='zero restrictions on impact: each shock and the variables it does not move, e.g. monetary: gy, pi', show_if=('scheme', ('SignRestrictions',)))] = '', long_run_zeros: Annotated[str, Widget('text', advanced=True, show_if=('scheme', ('SignRestrictions',)), help='zero restrictions in the long run (cumulated responses), e.g. demand: gy')] = '', share_variable: Annotated[str, Widget('text', show_if=('scheme', ('MaxShare', 'News')), help='the variable whose forecast-error variance the shock explains most of, e.g. tfp')] = '', share_horizon: Annotated[int, Widget('number', min=0, max=400, show_if=('scheme', ('MaxShare', 'News')), help='the share is of the forecast-error variance up to this horizon, e.g. 40 quarters')] = 40, share_start: Annotated[int, Widget('number', min=0, max=400, advanced=True, show_if=('scheme', ('MaxShare', 'News')), help='max share: the first horizon counted (0: impact)')] = 0, name: str = 'hd', draws: Annotated[int, Widget('number', advanced=True, min=0, max=10000, step=100, help="bands: posterior draws of a Bayesian VAR, rotations of a sign-identified set, a VAR's bootstrap, a panel VAR's coefficient draws, a proxy SVAR's block bootstrap or parameter draws of a Markov-switching VAR; 0 = none")] = 0, entity: Annotated[str, Widget('text', help='panel VARs: the entity the window shows; empty = the first')] = '', coverage: Annotated[float, Widget('number', min=0.5, max=0.999, step=0.05, advanced=True, help='probability the bands cover; 0.68 is also common')] = 0.95, seed: Annotated[int, Widget('number', min=0, max=2 ** 31 - 1, advanced=True, help='seed of the rotations drawn for the bands')] = 0, rotations: Annotated[int, Widget('number', min=10, max=100000, step=100, advanced=True, show_if=('scheme', ('SignRestrictions',)), help='sign restrictions: rotations accepted')] = 1000, max_tries: Annotated[int, Widget('number', min=1000, max=10000000, step=10000, advanced=True, show_if=('scheme', ('SignRestrictions',)), help='sign restrictions: rotations tried before giving up')] = 200000, sign_seed: Annotated[int, Widget('number', min=0, max=2 ** 31 - 1, advanced=True, show_if=('scheme', ('SignRestrictions',)), help='sign restrictions: random seed of the rotations')] = 0, narrative_signs: Annotated[str, Widget('text', advanced=True, show_if=('scheme', ('SignRestrictions',)), help="narrative restrictions: the shock's sign in named periods, e.g. monetary: 1979M10+, 1990M12-")] = '', narrative_major: Annotated[str, Widget('text', advanced=True, show_if=('scheme', ('SignRestrictions',)), help='narrative restrictions: the variable the shock moved most, e.g. monetary: 1979M10 ff')] = '', bootstrap_kind: Annotated[Literal['model default', 'residual', 'wild', 'block', 'parametric', 'pairs'], Widget('choice', advanced=True, group='Bootstrap', help="how the bands' draws are made: model default (a VAR's parametric bootstrap, a VECM's residual one), residual, wild (heteroskedastic errors), block (dependent errors), parametric (Gaussian) or pairs (VARs; a panel VAR's only bootstrap: whole entities resampled)")] = 'model default', block_length: Annotated[int, Widget('number', min=0, max=400, advanced=True, group='Bootstrap', show_if=('bootstrap_kind', ('block',)), help='block bootstrap: periods in a block; 0 = automatic (5.03 T^(1/4))')] = 0, wild_dist: Annotated[Literal['rademacher', 'mammen', 'normal'], Widget('choice', advanced=True, group='Bootstrap', show_if=('bootstrap_kind', ('wild',)), help="wild bootstrap: the multipliers, Rademacher (plus or minus one), Mammen's or normal")] = 'rademacher', bias_correct: Annotated[bool, Widget('checkbox', advanced=True, group='Bootstrap', help="Kilian's bias correction of the VAR's coefficients before and in the bootstrap (VARs)")] = False, bootstrap_design: Annotated[Literal['recursive', 'fixed'], Widget('choice', advanced=True, group='Bootstrap', help='recursive rebuilds each series from its first values; fixed keeps the lagged data (VARs)')] = 'recursive', band_type: Annotated[Literal['percentile', 'hall'], Widget('choice', advanced=True, group='Bootstrap', help="percentile bands, or Hall's (the draws reflected about the estimate)")] = 'percentile')

Bases: Command

Historical decomposition of a VAR, VECM, panel VAR or proxy SVAR.

Each variable over the estimation sample, split into the contributions of the identified shocks and the baseline (deterministic terms and initial conditions); the parts add up to the data.

It answers which shocks drove a variable away from its baseline in a given episode, such as how much of a recession was monetary. The split depends on the identification, as impulse responses do; under sign restrictions one member of the identified set is used. Early in the sample the baseline carries most of the movement, because few past shocks have accumulated; read the decomposition from a few years in.

Draws adds bands to each contribution: quantiles over a Bayesian VAR's posterior draws, over the identified set under sign (or zero and sign) restrictions, or over a point-identified VAR's parametric bootstrap (as its impulse responses' bands); the point decomposition stays as it is. Under MaxShare or News only the first shock is identified: the others' contributions are one way of splitting the rest.

A panel VAR is decomposed entity by entity, its baseline starting from the entity's first lags with its fixed effect; Entity picks the one the window shows (hd.select(entity) another), and its bands come from draws of the coefficients (or, with Bootstrap kind pairs, from re-estimates on resampled entities). A proxy SVAR splits each variable into its identified shock, the other shocks together and the baseline, with bands from its moving-block bootstrap; its shock is identified by the proxy, so leave the scheme at Cholesky with no ordering.

A Bayesian VAR with stochastic volatility is decomposed draw by draw, each period's shocks through that period's impact matrix: the point is the mean over the posterior draws (the first Draws of them; 0: all), with Coverage bands. A Markov-switching VAR is decomposed along its most likely regime path (the regime with the highest smoothed probability each period supplies the intercepts, dynamics and impact), its intercepts in the baseline; Draws gives Coverage bands over draws of its parameters from the estimates' asymptotic normal distribution, the regime path held fixed (the bands leave out the uncertainty about the regimes). Both are recursive in the VAR's order (Cholesky, Ordering empty), and their parts add up to the data exactly.

The Bootstrap group (Advanced) replaces a point-identified VAR's parametric bootstrap by a residual, wild, block or pairs bootstrap, with Kilian's bias correction, the fixed design or Hall's bands as options; and a panel VAR's coefficient draws by the pairs bootstrap of its entities (whole entities resampled, the panel VAR estimated again on each draw), with percentile or Hall's bands.

pymetrix.commands.ImportEViewsStateSpace dataclass

ImportEViewsStateSpace(path: Annotated[str, Widget('file', source='EViews programs (*.prg);;All files (*)', help="a .prg holding the sspace object's lines")], params: Annotated[str, Widget('text', help="starting values, e.g. c_1=0.3, c_2=0.8 (or c(1)=0.3), over the file's")] = '', name: str = 'sspace')

Bases: Command

Read an EViews state-space object (sspace: @signal, @state, @ename, @evar; bare lines or after ss.append) as a state-space model ready to estimate with Estimate > Time series > State space.

Signals become measurement equations (terms in data series moved to the left, the observed side), states transition equations, and an error's variance written as a coefficient squared (c(2)^2) the shock's standard deviation, the parameter c_2. Coefficients c(i) become parameters c_i, with starting values from c(i) = ... lines or given here. What does not map is refused with its line and column: covariances of errors, variances not of that form, terms mixing data and states, data in state equations, and EViews's programming language.

pymetrix.commands.ImportFRBUS dataclass

ImportFRBUS(path: Annotated[str, Widget('file', source='XML model files (*.xml);;All files (*)', help='the model file, e.g. mods/model.xml of the FRB/US package')], mce: Annotated[str, Widget('text', help='model-consistent expectations: all, or the groups to use them for, e.g. mcap, mcwp; empty = VAR expectations throughout')] = '', name: str = 'frbus')

Bases: Command

Read an XML model file in the format of the Federal Reserve's FRB/US package (mods/model.xml): its equations, coefficients and each variable's kind, sector, definition and stochastic type, as a model ready to solve.

The equations are EViews's, read by the EViews reader; coefficients such as y_x(1) become parameters y_x_1. Variables with model-consistent-expectations versions use the standard (VAR-expectations) equations unless MCE names their groups (e.g. mcap, mcwp) or is all. The result lists the variables; solve it with Model > Solution > Solve model (its name among the equations), make it track the data with Model > Solution > Add factors, and control it with Model > Policy > Optimal control. The package itself is the Fed's and is not shipped with pymetrix.

pymetrix.commands.ImpulseResponse dataclass

ImpulseResponse(var: Annotated[str, Widget('object', source='FittedVAR,FittedVECM,FittedPanelVAR,FittedBVARSV,FittedMSVAR,FittedQuantileVAR')], periods: Annotated[int, Widget('number', min=1, max=400, help="periods after the shock to trace; several years of the data's frequency to see responses die out")] = 20, scheme: Annotated[Literal['Cholesky', 'LongRun', 'SignRestrictions', 'MaxShare', 'News', 'Heteroskedasticity', 'Generalised'], Widget('', help=_SCHEME_HELP + '; or Generalised (Pesaran-Shin, ordering-free)')] = 'Cholesky', ordering: Annotated[str, Widget('text', help='Cholesky order, most exogenous first; empty = VAR order', show_if=('scheme', ('Cholesky',)))] = '', signs: Annotated[str, Widget('text', help='each shock and the signs of its responses: supply: gy+, pi-; demand: gy+, pi+', show_if=('scheme', ('SignRestrictions',)))] = '', sign_horizon: Annotated[int, Widget('number', min=0, max=40, help='the signs hold on impact and for this many periods after', show_if=('scheme', ('SignRestrictions',)))] = 0, zeros: Annotated[str, Widget('text', help='zero restrictions on impact: each shock and the variables it does not move, e.g. monetary: gy, pi', show_if=('scheme', ('SignRestrictions',)))] = '', long_run_zeros: Annotated[str, Widget('text', advanced=True, show_if=('scheme', ('SignRestrictions',)), help='zero restrictions in the long run (cumulated responses), e.g. demand: gy')] = '', share_variable: Annotated[str, Widget('text', show_if=('scheme', ('MaxShare', 'News')), help='the variable whose forecast-error variance the shock explains most of, e.g. tfp')] = '', share_horizon: Annotated[int, Widget('number', min=0, max=400, show_if=('scheme', ('MaxShare', 'News')), help='the share is of the forecast-error variance up to this horizon, e.g. 40 quarters')] = 40, share_start: Annotated[int, Widget('number', min=0, max=400, advanced=True, show_if=('scheme', ('MaxShare', 'News')), help='max share: the first horizon counted (0: impact)')] = 0, breaks: Annotated[str, Widget('text', show_if=('scheme', ('Heteroskedasticity',)), help='the first period of each new variance regime, e.g. 1984Q1 (two dates: three regimes)')] = '', cumulative: bool = False, draws: Annotated[int, Widget('number', advanced=True, help='bootstrap replications (or posterior draws for a Bayesian VAR) for bands; 0 = none', min=0, max=10000, step=100)] = 500, name: str = 'irf', orthogonal: Annotated[bool, Widget('checkbox', advanced=True, help='untick for responses to unit reduced-form shocks')] = True, coverage: Annotated[float, Widget('number', min=0.5, max=0.999, step=0.05, advanced=True, help='probability the bands cover; 0.68 (one standard error) is also common for responses')] = 0.95, seed: Annotated[int, Widget('number', min=0, max=2 ** 31 - 1, advanced=True, help='seed of the bootstrap or posterior draws; bands that move with it need more draws')] = 0, rotations: Annotated[int, Widget('number', min=10, max=100000, step=100, advanced=True, show_if=('scheme', ('SignRestrictions',)), help='sign restrictions: rotations accepted')] = 1000, max_tries: Annotated[int, Widget('number', min=1000, max=10000000, step=10000, advanced=True, show_if=('scheme', ('SignRestrictions',)), help='sign restrictions: rotations tried before giving up')] = 200000, sign_seed: Annotated[int, Widget('number', min=0, max=2 ** 31 - 1, advanced=True, show_if=('scheme', ('SignRestrictions',)), help='sign restrictions: random seed of the rotations')] = 0, narrative_signs: Annotated[str, Widget('text', advanced=True, show_if=('scheme', ('SignRestrictions',)), help="narrative restrictions: the shock's sign in named periods, e.g. monetary: 1979M10+, 1990M12-")] = '', narrative_major: Annotated[str, Widget('text', advanced=True, show_if=('scheme', ('SignRestrictions',)), help='narrative restrictions: the variable the shock moved most, e.g. monetary: 1979M10 ff')] = '', period: Annotated[str, Widget('period', advanced=True, group='BVAR-SV and MS-VAR', help='BVAR with stochastic volatility: the period whose volatilities size the shocks (empty: the last)')] = '', regime: Annotated[int, Widget('number', min=0, max=9, advanced=True, group='BVAR-SV and MS-VAR', help='Markov-switching VAR: the regime whose dynamics and covariance give the responses (0: the first)')] = 0, bootstrap_kind: Annotated[Literal['model default', 'residual', 'wild', 'block', 'parametric', 'pairs'], Widget('choice', advanced=True, group='Bootstrap', help="how the bands' draws are made: model default (a VAR's parametric bootstrap, a VECM's residual one), residual, wild (heteroskedastic errors), block (dependent errors), parametric (Gaussian) or pairs (VARs; a panel VAR's only bootstrap: whole entities resampled)")] = 'model default', block_length: Annotated[int, Widget('number', min=0, max=400, advanced=True, group='Bootstrap', show_if=('bootstrap_kind', ('block',)), help='block bootstrap: periods in a block; 0 = automatic (5.03 T^(1/4))')] = 0, wild_dist: Annotated[Literal['rademacher', 'mammen', 'normal'], Widget('choice', advanced=True, group='Bootstrap', show_if=('bootstrap_kind', ('wild',)), help="wild bootstrap: the multipliers, Rademacher (plus or minus one), Mammen's or normal")] = 'rademacher', bias_correct: Annotated[bool, Widget('checkbox', advanced=True, group='Bootstrap', help="Kilian's bias correction of the VAR's coefficients before and in the bootstrap (VARs)")] = False, bootstrap_design: Annotated[Literal['recursive', 'fixed'], Widget('choice', advanced=True, group='Bootstrap', help='recursive rebuilds each series from its first values; fixed keeps the lagged data (VARs)')] = 'recursive', band_type: Annotated[Literal['percentile', 'hall'], Widget('choice', advanced=True, group='Bootstrap', help="percentile bands, or Hall's (the draws reflected about the estimate)")] = 'percentile')

Bases: Command

Impulse responses of a VAR or VECM, with bootstrap bands.

Choose the identification scheme: Cholesky orders shocks as the variables are ordered; LongRun imposes Blanchard-Quah long-run restrictions; SignRestrictions names shocks by the signs of their responses (supply: gy+, pi-; demand: gy+, pi+), holding on impact and for the periods after given; Zeros adds the variables a shock does not move on impact (monetary: gy, pi), with the signs or alone (Arias, Rubio-Ramírez and Waggoner's zero and sign restrictions). MaxShare identifies one shock as the one explaining most of a variable's forecast-error variance up to a horizon (Uhlig; Francis et al.), News the same with no effect on that variable on impact (Barsky and Sims); Heteroskedasticity identifies every shock by the change in their variances at the Breaks (Rigobon; no bands); Generalised gives Pesaran and Shin's ordering-free responses. Bayesian VARs with stochastic volatility, Markov-switching and quantile VARs give their own recursive responses (Cholesky, in their order): at Period's volatilities, in Regime, or at the quantile fitted (a Markov-switching VAR's bands: Draws draws of its parameters from the estimates' asymptotic normal distribution). Tick Cumulative for variables in differences.

Cholesky responses depend on the ordering: the first variable responds on impact to its own shock only, the last to all of them. Try other plausible orderings; conclusions that change with it rest on the ordering, not the data. Responses are to one-standard-deviation shocks unless Orthogonal is unticked. Bands are percentile bands: a parametric bootstrap for a VAR, a residual bootstrap for a VECM, posterior draws for a Bayesian VAR. Under sign restrictions the response shown is the pointwise median of the accepted rotations, which need not come from any single one, and the bands describe the identified set as well as sampling uncertainty. A stationary VAR's responses die out; a VECM's responses are of levels, and permanent shocks have lasting effects.

The Bootstrap group (Advanced) chooses another bootstrap for a VAR's or VECM's bands: residual, wild (for heteroskedastic errors), block (for dependent errors), parametric or, for VARs, pairs; Kilian's bias correction and the fixed design for VARs; percentile or Hall's bands. A VECM is rebuilt with its rank held. A panel VAR's bands come from draws of its coefficients; its one bootstrap is pairs: whole entities resampled and the panel VAR estimated again on each draw, with percentile or Hall's bands (fit with as many instrument lags as lags). The result's Bootstrap tab gives the procedure, the draws used and any failures.

pymetrix.commands.InstrumentTests dataclass

InstrumentTests(fit: Annotated[str, Widget('object', source='FittedEquation', help='an equation estimated by IV or GMM: its equation, instruments and sample are used')], test: Annotated[_IV_TESTS, Widget('choice', help='Anderson-Rubin test or confidence set (IV or GMM fits); Stock-Wright S and the C test (GMM fits)')] = 'anderson_rubin', data: Annotated[str, Widget('object', source='Dataset', help='the data the equation was fitted to')] = 'data', endog: Annotated[str, Widget('text', show_if=('test', _AR), help="the endogenous regressor whose coefficient is tested; empty = the fit's first")] = '', value: Annotated[float, Widget('number', min=-1000000.0, max=1000000.0, step=0.01, show_if=('test', ('anderson_rubin',)), help="the coefficient's value under the null")] = 0.0, grid: Annotated[str, Widget('text', advanced=True, show_if=('test', ('anderson_rubin_set',)), help='values to test: low, high, points (e.g. -1, 1, 81), or a list of more than three')] = '-1, 1, 81', alpha: Annotated[float, Widget('number', min=0.001, max=0.5, step=0.01, show_if=('test', ('anderson_rubin_set',)), help='significance level: the set has coverage 1 - alpha')] = 0.05, cov: Annotated[Literal['classic', 'white'], Widget('choice', show_if=('test', _AR), help='classic: the exact F test; white: robust to heteroskedasticity')] = 'classic', values: Annotated[str, Widget('text', show_if=('test', ('stock_wright',)), help="every parameter's value under the null, e.g. const=4, educ=0.1, exper=0.04")] = '', suspect: Annotated[str, Widget('text', show_if=('test', ('c_test',)), help="the instruments whose validity is tested, among the fit's, e.g. nearc2")] = '', name: str = 'iv_test', instruments: Annotated[str, Widget('text', advanced=True, help="Anderson-Rubin: the excluded instruments; empty = the fit's")] = '', start: Annotated[str, Widget('period', advanced=True, help="first period; empty = the fit's sample")] = '', end: Annotated[str, Widget('period', advanced=True, help="last period; empty = the fit's sample")] = '')

Bases: Command

Tests for instrumental-variable equations that stay valid however weak the instruments: Anderson-Rubin and Stock-Wright; and the C test of whether some of the instruments are valid.

Choose an equation estimated by IV or GMM (Estimate > Equation, method IV, LIML or GMM) and the data it was fitted to; the test uses its equation, its instruments and its sample.

Anderson-Rubin tests that the coefficient on one endogenous regressor takes a given value, by regressing y - value * regressor on the other regressors and the excluded instruments: an F test (or, with robust errors, a Wald test) that the instruments' coefficients are zero. Its size is right whatever the instruments' strength, where the 2SLS t test over-rejects with weak instruments. Inverting it over a grid of values gives the Anderson-Rubin confidence set: the values not rejected. With weak instruments it can be wide, unbounded or empty (empty means the over-identifying restrictions fail), which is the honest answer.

Stock and Wright's S tests that every parameter of a GMM equation takes the given values: the continuously updated GMM objective there, chi-squared with as many degrees of freedom as instruments, again whatever their strength.

The C (difference-in-Sargan) test asks whether the suspect instruments are valid, given that the others are: Hansen's J with all the instruments less J without the suspect ones (GMM fits), chi-squared with as many degrees of freedom as suspect instruments. A small p-value says the suspect ones are correlated with the error.

pymetrix.commands.Johansen dataclass

Johansen(variables: Annotated[str, Widget('series', depends_on='data', multiple=True)], lags: Annotated[int, Widget('number', min=0, max=24, help='lags in first differences')] = 1, trend: Annotated[Literal['none', 'constant', 'linear trend'], Widget('', help='deterministic terms: none, a constant, or a linear trend; match how the series trend')] = 'constant', data: Annotated[str, Widget('object', source='Dataset')] = 'data', name: str = 'johansen_result', signif: Annotated[Literal[0.05, 0.1, 0.01], Widget('choice', advanced=True, help='significance level of the sequential tests that suggest the rank')] = 0.05, start: Annotated[str, Widget('period', advanced=True)] = '', end: Annotated[str, Widget('period', advanced=True)] = '')

Bases: Command

Johansen cointegration tests: trace and maximum-eigenvalue statistics for each rank.

Tick the series in levels and choose the lags (in differences) and deterministic terms.

Read the tests in sequence from r0 = 0: the suggested rank is the first r0 at which the statistic falls below its critical value. Rank 0 means no cointegration (model the differences), full rank that the series look stationary; anything between is the number of long-run relations a VECM should have. Trace and maximum- eigenvalue tests can disagree, and both tend to over-reject in small samples. The critical values depend on the deterministic terms and the lags, so settle those first (VECM lag selection).

pymetrix.commands.KalmanFilter dataclass

KalmanFilter(system: Annotated[str, Widget('object', source='StateSpaceSystem', help='a model in state-space form (Model > Analysis > State-space form)')], data: Annotated[str, Widget('object', source='Dataset')] = 'data', start: Annotated[str, Widget('period', group='Sample')] = '', end: Annotated[str, Widget('period', group='Sample')] = '', name: str = 'filtered')

Bases: Command

Estimate a model's variables from data with the Kalman smoother: e.g. the output gap behind observed inflation and interest rates. The result has every model variable in levels and each observed series as the model fits it.

The parameters are those of the state-space form, calibrated or estimated earlier; nothing is estimated here. The smoother uses the whole sample, so estimates near its end rest on fewer later observations and are revised as new data arrive, as the output gap is in practice. Compare each <series>_fitted with the data: the gaps are the measurement errors, and large, persistent ones mean the model or its measurement equation fits that series poorly. The estimates depend on the shock and measurement-error sizes: bigger measurement errors let the filter follow the data less closely.

pymetrix.commands.LoadData dataclass

LoadData(path: Annotated[str, Widget('file', source='Data files (*.parquet *.csv *.xlsx *.xls);;All files (*)', help="a Parquet, CSV or Excel file; PyMetrix's Parquet files keep their axes and metadata")], time: Annotated[str, Widget('column', depends_on='path', help='column of dates or periods (not needed for our Parquet files)')] = '', entity: Annotated[str, Widget('column', depends_on='path', help='column identifying countries, firms, households... (panels, cross-sections)')] = '', freq: Annotated[Literal['', 'Y', 'Y-JUN', 'Q', 'M', 'W', 'D'], Widget('choice', help='period frequency of the time column; Y-JUN = July-June fiscal year')] = '', name: str = 'data', columns: Annotated[str, Widget('column', depends_on='path', multiple=True, show_if=('path', _LargeParquet()), group='Part of a large file', label='Columns', help='the series to read (none ticked: all); the time and entity columns are always read')] = '', where: Annotated[str, Widget('text', show_if=('path', _LargeParquet()), group='Part of a large file', label='Rows where', help="read only these rows, e.g. country in ['DEU', 'FRA'] and year >= 2000; row groups the condition rules out are not read")] = '', start: Annotated[str, Widget('text', show_if=('path', _LargeParquet()), group='Part of a large file', label='From', help='the first period to read, e.g. 2000Q1 (empty: from the start)')] = '', end: Annotated[str, Widget('text', show_if=('path', _LargeParquet()), group='Part of a large file', label='To', help='the last period to read, included (empty: to the end)')] = '', embed: Annotated[bool, Widget('checkbox', show_if=('path', _LargeParquet()), group='Part of a large file', label='Keep a copy in the project', help="off: the project keeps the file's path and fingerprint, reads it again on opening, and refuses if it has changed")] = True, first_period: Annotated[str, Widget('text', help="a file with no dates: its first row's period, e.g. 1990Q1, with the frequency above; the rows follow one period each; empty = the file's own dates")] = '')

Bases: Command

Read a data file into the workspace as a dataset.

Parquet files written by PyMetrix carry their own axes and metadata. For CSV and Excel files, name the column of dates or periods (Time) and, for panels and cross-sections, the column identifying entities (Entity), and choose the frequency. A file with no dates, one row per period in order, is dated from its first period (Dates start at) at the frequency chosen, as R's ts(x, start = c(1990, 1), frequency = 4).

The time column and frequency matter beyond labels: they fix what a lag such as x[-1] means, the defaults that follow the frequency (the HP smoothing parameter, band-pass cycle lengths) and the periods forecasts are dated in. Check the dataset's overview after loading: a frequency read wrongly, or a fiscal year taken for a calendar year, shifts every date without raising an error.

For a Parquet file larger than 100 MB, the dialog also offers Part of a large file: the columns to read, a row condition and a span of periods. pyarrow then reads only those columns, and skips the row groups the condition and span rule out; the dataset holds only the rows and columns selected, and projects keep that selection, not the whole file. Untick Keep a copy in the project to keep only the file's path and fingerprint instead.

pymetrix.commands.LoadExample dataclass

LoadExample(dataset: Annotated[str, Widget('dataset', help='sample_macro (a quarterly economy), or a cross-section or panel example; the simulated ones have known effects')] = 'sample_macro', name: str = 'data')

Bases: Command

Load an example dataset installed with PyMetrix, such as the simulated quarterly economy used in the course labs.

Each example suits particular methods: sample_macro and sample_monthly for time series, VARs and nowcasting; mroz, card, randhie and anes96 for limited-dependent-variable and IV models; wage_panel, grunfeld and jobtraining for panels. The simulated policy_panel, rd_sample and synth_panel have known true effects (2.0, 1.5 and -3.0), so you can check that an estimator recovers them. Plugins can add examples of their own; the dataset's notes say where real data come from.

pymetrix.commands.LoadFromConnector dataclass

LoadFromConnector(provider: Annotated[str, Widget('named', source='connectors', help="the data service: fred, worldbank, sdmx, or a plugin's (each reads addresses provider://codes)")] = 'fred', codes: Annotated[str, Widget('text', help='FRED: series IDs, e.g. GDPC1,UNRATE; World Bank: indicators, e.g. NY.GDP.MKTP.CD; SDMX: PROVIDER/FLOW/KEY, e.g. ECB/EXR/M.USD.EUR.SP00.A')] = '', start: Annotated[str, Widget('period', group='Periods', show_if=('provider', _with_start), help='first period, e.g. 1990Q1 or 1990-01 (World Bank: a year); empty = from the start')] = '', end: Annotated[str, Widget('period', group='Periods', show_if=('provider', _with_end), help='last period; empty = to the latest')] = '', vintage: Annotated[str, Widget('text', show_if=('provider', _with_vintages), help='a date, e.g. 2020-01-30: the data as published that day (ALFRED for FRED); empty = the latest')] = '', name: str = 'data', options: Annotated[str, Widget('text', advanced=True, help='other parameters of the address, as the connector takes them, e.g. country=WSM;TON (World Bank) or entity=REF_AREA (SDMX); several separated by &')] = '')

Bases: Command

Read series from a data service: FRED, the World Bank, SDMX providers (the ECB, Eurostat, the OECD, the IMF, the BIS, or an institution's own service) and those plugins add.

Give the provider and the series codes as the provider writes them: FRED IDs (GDPC1,UNRATE), World Bank indicators (NY.GDP.MKTP.CD, a panel by country), or an SDMX PROVIDER/FLOW/KEY (ECB/EXR/M.USD.EUR.SP00.A). The dialog writes the connector's address, the same text File → Load data… accepts as its path (fred://GDPC1?start=1990Q1), so the step can be repeated, or edited, in code. Where the provider keeps vintages (FRED, through ALFRED) a date gives the data as published that day, for real-time analysis; empty gives the latest. File → Browse series… finds codes by searching or browsing the provider, and fills them in here. A project keeps the data as read, so it opens with the same numbers whatever the provider holds by then; File → Refresh data… reads it again.

address

address() -> str

The connector's address the dialog reads: provider://codes?start=...&end=...&options.

pymetrix.commands.LoadTemplate dataclass

LoadTemplate(template: Annotated[Literal['new_keynesian', 'rbc', 'gap_model', 'qpm'], Widget('choice', help="new_keynesian (three-equation NK), rbc (stochastic growth), gap_model (semi-structural, unobserved output gap) or qpm (Berg, Karam and Laxton's quarterly projection model, small open economy)")] = 'new_keynesian', params: Annotated[str, Widget('text', help='parameters to change, e.g. phi_pi=1.2')] = '', name: str = 'template', shock_sd: Annotated[str, Widget('text', advanced=True, help="shock standard deviations, e.g. ey=0.5, ei=0.2; empty = the template's")] = '')

Bases: Command

Load a template model: a small standard model with calibrated parameters, shocks and measurement equations.

new_keynesian is the three-equation New Keynesian model; rbc the stochastic growth model; gap_model a small semi-structural projection model with an unobserved output gap; qpm the quarterly projection model of Berg, Karam and Laxton (2006) for a small open economy, with trends and levels (GDP, the CPI and the exchange rate in 100*log), open=0 in Parameters for the closed economy. Solve it, check it, take it to data with Model > Analysis > State-space form and Model > Analysis > Kalman filter, or copy its equations to start your own.

pymetrix.commands.MakeRound dataclass

MakeRound(forecast: Annotated[str, Widget('object', source='Dataset,Solution', help='a forecast (from Estimate > Forecast) or a model solution')], round_name: Annotated[str, Widget('text', help='how the round is known in the store, e.g. 2026Q3 baseline; one name per round')], data: Annotated[str, Widget('object', source='Dataset', help='the data the forecast used (sets the last data period)')] = 'data', variables: Annotated[str, Widget('text', help="variables to keep; empty = all the forecast's")] = '', as_name: Annotated[str, Widget('text', help="for an equation's forecast: the variable it forecasts")] = '', notes: Annotated[str, Widget('multiline', help='assumptions, story, sign-off')] = '', name: str = 'forecast_round')

Bases: Command

Make a forecast round from a forecast: an equation's, a VAR's or a model solution's.

A round records the forecast paths with when they were made, the last period of data used, and notes. For an equation's forecast, name the variable it forecasts. For a model solution, list the variables to keep.

pymetrix.commands.MakeSurveillanceHeatmap dataclass

MakeSurveillanceHeatmap(series: Annotated[str, Widget('series', depends_on='data', multiple=True, help='the indicators, in the order to show them')], data: Annotated[str, Widget('object', source='Dataset')] = 'data', normalise: Annotated[Literal['zscore', 'robust_zscore', 'pctrank', 'level', 'gap'], Widget('choice', help='how unusual each reading is: its z-score, robust z-score, percentile rank (0 to 100), its level, or its gap from a trend')] = 'zscore', window: Annotated[int, Widget('number', min=0, max=1000, help='periods each reading is compared with; 0 = every period up to it')] = 0, higher_is_better: Annotated[str, Widget('text', help='the series where a high reading is good (growth, surveys), flipped so red means worse; e.g. gip, pmi')] = '', groups: Annotated[str, Widget('text', help='name: series for each group, e.g. activity: gip gr; labour: gemp; adds group averages and a composite')] = '', order: Annotated[Literal['given', 'group', 'cluster'], Widget('choice', help='rows as listed, by group, or by clustering their correlations (series that move together side by side)')] = 'given', thresholds: Annotated[str, Widget('text', help='cut-offs that colour by bands, e.g. 10, 25, 75, 90 for percentile ranks; empty = a continuous scale')] = '', last: Annotated[int, Widget('number', min=0, max=10000, help='show only the last n periods; 0 = all (the normalising still uses the whole history)')] = 0, clusters: Annotated[str, Widget('object', source='KMeansClusters', help='k-means clusters of the dates, drawn as a band above them')] = '', regime_series: Annotated[str, Widget('text', help='series drawn as bands above the dates, e.g. a recession dummy')] = '', more_data: Annotated[str, Widget('object', source='Dataset', help='a dataset of another frequency (quarterly beside monthly)')] = '', start: Annotated[str, Widget('period', group='Sample')] = '', end: Annotated[str, Widget('period', group='Sample')] = '', reference_start: Annotated[str, Widget('period', group='Reference period', help="normalise against this period's readings instead of a window")] = '', reference_end: Annotated[str, Widget('period', group='Reference period', help="the reference period's last date")] = '', composite: Annotated[Literal['auto', 'equal', 'pca', 'none'], Widget('choice', advanced=True, help='the composite row: the average of the groups, weighted by the first principal component, or none; automatic: an average when there are groups')] = 'auto', gap_filter: Annotated[Literal['hp', 'hamilton', 'mean'], Widget('choice', advanced=True, help='the trend a gap is measured from')] = 'hp', frequency: Annotated[str, Widget('text', advanced=True, help='the calendar: M, Q; empty = the highest frequency of the data')] = '', fill: Annotated[Literal['repeat', 'once', 'latest'], Widget('choice', advanced=True, help='a lower-frequency reading on the calendar: in each period of its own, in its last only, or from its release until the next')] = 'repeat', changes: Annotated[str, Widget('text', advanced=True, help='periods over which the latest table shows changes')] = '3, 6, 12', annotate: Annotated[bool, Widget('checkbox', advanced=True, help='write each value in its cell (small heatmaps)')] = False, date_format: Annotated[str, Widget('text', advanced=True, help='how dates are written under the cells, e.g. %b %y; empty = as periods')] = '', title: Annotated[str, Widget('text', advanced=True, help="the heatmap's title; empty = Surveillance heatmap")] = '', name: str = 'heatmap', calendar: Annotated[str, Widget('object', source='ReleaseCalendar', advanced=True, empty='fixed publication lags', help="with Fill latest: each lower-frequency reading from its actual release day (Release calendar from a table…); empty = each series' fixed publication lag")] = '')

Bases: Command

A surveillance heatmap: indicators down the side, dates across, each reading coloured by how unusual it is.

Each series is normalised over its own history: a z-score, a robust z-score (median and median absolute deviation), a percentile rank (0 to 100), its level, or its gap from a trend; over a rolling window, every period up to each date (Window: 0), or a fixed reference period. Higher is better for flips the series where a high reading is good (growth, surveys), so red means worse on every row. Groups (activity: gip gr; labour: gemp) add each group's average and a composite row, the average of the groups or weighted by the first principal component. Thresholds (10, 25, 75, 90) colour by bands instead of a continuous scale. Order by clustering puts series that move together next to each other. Data of another frequency puts quarterly series on the monthly calendar (or monthly on a quarterly one). K-means clusters, or regime series such as a recession dummy, are drawn as bands above the dates. The window shows the heatmap, each indicator's latest reading with its change over 3, 6 and 12 periods, the tables of normalised values and readings (exported to Excel, Word and HTML with coloured cells), and the composite's weights. The settings are kept: refreshing the data draws the same heatmap on the new figures.

pymetrix.commands.MatrixFrom dataclass

MatrixFrom(source: Annotated[Literal['coefficients', 'covariance', 'lag matrix', 'error covariance', 'series', 'design'], Widget('choice', label='Matrix of', help='what the matrix holds')] = 'coefficients', result: Annotated[str, Widget('object', source=RESULTS, help='a fitted equation, system, VAR or model', show_if=('source', ('coefficients', 'covariance')))] = '', var: Annotated[str, Widget('object', source=VARS, label='VAR', help='a fitted VAR or VECM', show_if=('source', ('lag matrix', 'error covariance')))] = '', lag: Annotated[int, Widget('number', min=1, max=48, help="which lag's coefficients: 1 for the first", show_if=('source', ('lag matrix',)))] = 1, data: Annotated[str, Widget('object', source='Dataset', show_if=('source', ('series', 'design')))] = 'data', series: Annotated[str, Widget('series', depends_on='data', multiple=True, help='the columns, in this order; none: every series', show_if=('source', ('series',)))] = '', formula: Annotated[str, Widget('formula', help='e.g. c ~ y + c[-1]: the regressors X and the dependent variable y', show_if=('source', ('design',)))] = '', start: Annotated[str, Widget('period', show_if=('source', ('series', 'design')))] = '', end: Annotated[str, Widget('period', show_if=('source', ('series', 'design')))] = '', name: str = 'M', dependent: Annotated[str, Widget('text', label='Name of y', help="the dependent variable's matrix (Save as names the regressors')", show_if=('source', ('design',)))] = 'y')

Bases: Command

A named matrix from a result or a dataset: a fit's coefficients (a column) or the covariance matrix of its estimates, a VAR's lag matrix or the covariance matrix of its errors, a dataset's series over a span (rows named by period), or a formula's regressors X and dependent variable y on a dataset (two matrices).

Recorded as the line that makes it, e.g. V = Matrix.cov(fit), A1 = Matrix.var_lag(var, 1), Y = Matrix.from_dataset(data, ['c', 'y'], span=('2000Q1', '2019Q4')) or X, y = Matrix.design('c ~ y', data), and recomputed when the result or the data changes.

expression

expression() -> str

The expression the step runs, and records after name =.

to_call

to_call() -> Any

The recorded call (a matrix expression); the design matrices, two results from one line, are recorded as their code only.

pymetrix.commands.NonNestedTest dataclass

NonNestedTest(first: Annotated[str, Widget('object', source='FittedEquation', help='the equation under the null: is it right?')], second: Annotated[str, Widget('object', source='FittedEquation', help='the alternative: a linear equation for the same dependent variable, not nested in the first')], test: Annotated[Literal['j', 'cox'], Widget('choice', help="Davidson-MacKinnon's J (a t test) or the Cox test (Pesaran's form)")] = 'j', data: Annotated[str, Widget('object', source='Dataset', help='the data both were fitted to')] = 'data', name: str = 'nonnested', start: Annotated[str, Widget('period', advanced=True, help="first period; empty = the first fit's sample")] = '', end: Annotated[str, Widget('period', advanced=True, help="last period; empty = the first fit's sample")] = '')

Bases: Command

Test one linear equation against another that does not nest it, for the same dependent variable: Davidson and MacKinnon's J test or the Cox test (Pesaran's form).

The null is that the first equation is right. The J test adds the second equation's fitted values to the first and tests their coefficient (a t test); the Cox test compares the two equations' error variances with what the first predicts for the second (standard normal; large negative values reject). Run the test both ways: both may reject (neither is adequate) or neither (the data cannot choose). Both equations use the observations they share.

pymetrix.commands.OmittedVariablesTest dataclass

OmittedVariablesTest(fit: Annotated[str, Widget('object', source='FittedEquation', help='a linear-form equation: its equation, method, weights and sample are used')], add: Annotated[str, Widget('text', help='the regressors to add, separated by commas, e.g. x2, x3[-1], log(z)')], data: Annotated[str, Widget('object', source='Dataset', help='the data the equation was fitted to')] = 'data', name: str = 'omitted', start: Annotated[str, Widget('period', advanced=True, help="first period; empty = the fit's sample")] = '', end: Annotated[str, Widget('period', advanced=True, help="last period; empty = the fit's sample")] = '')

Bases: Command

Test whether regressors left out of a fitted equation belong in it (EViews' testadd): the equation is fitted again with them added, on the same observations, and their coefficients tested jointly.

The F form of the Wald test is the headline (with the fit's own kind of standard errors: robust, HAC or clustered if it used one); the details give the Wald chi-squared, the likelihood-ratio test (twice the gain in log likelihood) and, for unweighted least squares, the LM test (n R-squared of the residuals on all the regressors). A small p-value says the added regressors matter. They must have values on every observation of the fit.

pymetrix.commands.OpenResult dataclass

OpenResult(path: Annotated[str, Widget('file', source='pymetrix results (*.pymxr);;All files (*)', help='a .pymxr file written by File > Save result... or save_result in code')], name: str = 'result')

Bases: Command

Open a result saved to a file (File → Save result…, or save_result in code): its tables, figures, summary and provenance as they were saved. It can be read and copied, not estimated again. Projects keep a copy of the file.

The provenance records how the result was produced: the data and their vintages, the sample, the settings and the package version. When a re-run gives different numbers, compare the provenance first: a revised data vintage or a different sample is the usual reason.

pymetrix.commands.OptimalControlCommand dataclass

OptimalControlCommand(equations: Annotated[str, Widget('object', source=MODEL_PARTS, multiple=True, help='the model: fitted equations and identities, or a model read (FRB/US XML)')], start: Annotated[str, Widget('period', help='the first period of the loss and of the solution')], end: Annotated[str, Widget('period', help='the last period of the loss and of the solution')], instruments: Annotated[str, Widget('text', help='exogenous series moved optimally, e.g. rfftay_aerr')], loss: Annotated[str, Widget('text', help="weights of the loss, e.g. ugap=1, pic4=1, delrff=1 (penalise the instrument's moves too)")], data: Annotated[str, Widget('object', source='Dataset')] = 'data', desired: Annotated[str, Widget('text', help='desired values, e.g. pic4=2; the others zero')] = '', discount: Annotated[float, Widget('number', advanced=True, min=0.0001, max=1.0, step=0.01, help='discount factor of the loss; 1 = none')] = 1.0, name: str = 'control', control_start: Annotated[str, Widget('period', advanced=True, group='Control', help="the first period the instruments move; empty = the span's")] = '', control_end: Annotated[str, Widget('period', advanced=True, group='Control', help="the last period the instruments move; empty = the span's")] = '', adjust: Annotated[str, Widget('object', source='dict', advanced=True, empty='empty: none', help='add factors (Model > Add factors) added to the equations, so the baseline tracks the data')] = '', solver: Annotated[Literal['Newton', 'GaussSeidel'], Widget('choice', advanced=True, help='how the model is solved each period')] = 'Newton', params: Annotated[str, Widget('text', advanced=True, help='values for the parameters of equations not estimated, e.g. b=0.99')] = '', tol: Annotated[float, Widget('number', min=1e-12, max=0.1, advanced=True, help='stop when the gradient falls below this share of its size at the start')] = 1e-06, max_iter: Annotated[int, Widget('number', min=1, max=1000, advanced=True, help='Gauss-Newton iterations at most')] = 20)

Bases: Command

The paths of some exogenous instruments that minimise a discounted quadratic loss over a span, with a backward-looking model solved as the constraint: the optimal-control simulation of the Federal Reserve's ocpolicy.prg on FRB/US, where the instrument is an add factor on the policy rule (rfftay_aerr).

The loss is the sum, over the span's periods t (counted from 0) and the variables v named, of discount^t * weight_v * (v(t) - desired_v)^2; desired values are zero unless given. The instruments move in each period of the control span (the whole span by default), and the policymaker commits to the whole path at the start. Penalise the instrument's changes (e.g. delrff=1) or the path may be implausibly aggressive. The model is solved period by period (Newton or Gauss-Seidel); a model with leads (model-consistent expectations) is not controlled here. Add factors (Model > Add factors) make the baseline track the data first. The result shows the loss with and without the moves, the moves, and the paths of the loss's variables.

pymetrix.commands.PanelStatistics dataclass

PanelStatistics(data: Annotated[str, Widget('object', source='Dataset')] = 'data', series: Annotated[str, Widget('series', depends_on='data', multiple=True, help='series to describe; empty = all')] = '', show: Annotated[Literal['coverage', 'variation'], Widget('choice', help='coverage: who has data when; variation: between and within')] = 'coverage', name: str = 'panel_stats', by: Annotated[str, Widget('text', advanced=True, show_if=('show', ('variation',)), help='variation: the entity axis, for panels with several (e.g. country); empty = the only one')] = '')

Bases: _OnData

Describe a panel: coverage (each entity's first and last periods, observations and gaps), or overall, between-entity and within-entity variation of each series.

Coverage shows, for each entity, the first and last periods with data, the observations and the gaps, and says whether the panel is balanced. Variation splits each series' spread: the between standard deviation is that of the entity means, the within standard deviation that of the deviations from them (plus the overall mean, so the within rows read on the series' scale). Fixed effects estimators use only the within variation, so a regressor that varies mostly between entities is poorly identified by them; random effects and pooled estimators use both. N is the observations, n the entities and T the average periods per entity.

pymetrix.commands.PivotTable dataclass

PivotTable(data: Annotated[str, Widget('object', source='Dataset')] = 'data', rows: Annotated[str, Widget('level', depends_on='data', multiple=True, help='axes or categories down the side, e.g. region, country')] = '', columns: Annotated[str, Widget('level', depends_on='data', multiple=True, help='axes or categories across the top, e.g. time; empty = none')] = '', values: Annotated[str, Widget('series', depends_on='data', multiple=True, help='series to summarise; empty = all')] = '', agg: Annotated[str, Widget('text', help='mean, sum, count, min, max, median, std, first, last; several separated by commas')] = 'mean', margins: Annotated[bool, Widget('checkbox', advanced=True, help='add a Total row and column, each computed with the same summary over all the data')] = False, start: Annotated[str, Widget('period', group='Sample')] = '', end: Annotated[str, Widget('period', group='Sample')] = '', name: str = 'pivot', fill: Annotated[str, Widget('text', advanced=True, help='value for empty cells, e.g. 0; empty = leave them blank')] = '')

Bases: _OnData

Summarise series by the values of axes or categories: a pivot table, as in a spreadsheet.

Rows and columns can be axes (country, time) or series of categories (region). Choose the series to summarise and how: mean, sum, count, min, max, median, std, first or last, or several separated by commas. Totals adds a Total row and column. The table can be copied into Excel.

pymetrix.commands.PlotSeries dataclass

PlotSeries(series: Annotated[str, Widget('series', depends_on='data', multiple=True, help='the series to plot (x first for a scatter plot)')], data: Annotated[str, Widget('object', source='Dataset')] = 'data', kind: Annotated[Literal['line', 'step', 'bar', 'barh', 'area', 'scatter', 'histogram', 'box', 'contributions', 'fan', 'vintages', 'correlation', 'ecdf', 'hist2d', 'violin', 'hexbin', 'surface'], Widget('choice', help='chart type: line for time series, bar for contributions, scatter for relations, histogram for distributions')] = 'line', total: Annotated[str, Widget('series', depends_on='data', show_if=('kind', ('contributions',)), help='the series the parts add up to (empty: their sum)')] = '', bins: Annotated[str, Widget('text', show_if=('kind', ('histogram', 'hist2d', 'hexbin')), help='the number of bins, or hexagons across (empty: 30)')] = '', coverages: Annotated[str, Widget('text', show_if=('kind', ('fan',)), help="the bands' coverages in %, e.g. 30, 60, 90 (empty: those in the data)")] = '', layout: Annotated[Literal['one', 'each'], Widget('choice', help='all series in one panel, or one panel each')] = 'one', stacked: Annotated[bool, Widget('checkbox', show_if=('kind', ('bar', 'barh', 'area')), help='stack the series (negative values below zero), e.g. contributions')] = False, transform: Annotated[Literal['none', 'index', 'change', 'growth', 'yoy', 'log'], Widget('choice', help='plot each series as it is, or transformed')] = 'none', shade: Annotated[str, Widget('text', advanced=True, help='periods to shade, e.g. 2008Q3:2009Q2, 2020Q1:2020Q2 (a label after =); nber or cepr for US or euro-area recessions; or a 0/1 series such as recession')] = '', events: Annotated[str, Widget('text', advanced=True, help='dates to mark with a labelled line, e.g. 2016Q2=Brexit vote, 2020Q1=COVID')] = '', reference: Annotated[str, Widget('text', advanced=True, help='values to mark with a labelled line, e.g. 2=inflation target')] = '', bar_labels: Annotated[bool, Widget('checkbox', advanced=True, show_if=('kind', ('bar', 'barh')), help="write each bar's value on it")] = False, line_labels: Annotated[bool, Widget('checkbox', advanced=True, show_if=('kind', ('line', 'step')), help='name each line at its end, in its colour, instead of in a legend')] = False, same_scale: Annotated[bool, Widget('checkbox', show_if=('layout', ('each',)), help='one value scale for every panel')] = False, log_scale: Annotated[bool, Widget('checkbox', advanced=True, help='a log scale for the values (positive series only)')] = False, lowest: Annotated[str, Widget('text', advanced=True, help='the lowest value shown (empty: automatic)')] = '', highest: Annotated[str, Widget('text', advanced=True, help='the highest value shown (empty: automatic)')] = '', split_values: Annotated[str, Widget('text', advanced=True, help='values to leave out, splitting the value axis in two, e.g. 6:12 for a spike that squashes the rest (empty: none)')] = '', split_dates: Annotated[str, Widget('text', advanced=True, help='periods to leave out, splitting the time axis in two, e.g. 1986Q1:2004Q4 (empty: none)')] = '', right: Annotated[str, Widget('series', depends_on='data', multiple=True, advanced=True, show_if=('kind', ('line', 'step', 'bar', 'area')), help='series to draw against a second scale on the right')] = '', start: Annotated[str, Widget('period', group='Sample')] = '', end: Annotated[str, Widget('period', group='Sample')] = '', title: Annotated[str, Widget('text', help='a title for the figure (optional)')] = '', subtitle: Annotated[str, Widget('text', advanced=True, help='a line under the title (optional)')] = '', footnote: Annotated[str, Widget('text', advanced=True, help='a note under the figure, e.g. the source (optional)')] = '', name: str = 'figure', entity: Annotated[str, Widget('text', advanced=True, help='for a panel dataset: the entity to plot')] = '')

Bases: Command

Plot series as lines, steps, bars (side by side or stacked, upright or across), areas, a scatter plot, histograms or box plots, in one panel or one each; or as a macro chart: contributions (the series as stacked parts of a total, drawn as a line), a fan (each series with its bands, from its _lo90/_hi90 or _se columns) or vintages (each series a release of the same data, oldest first); or the series' correlations as a heatmap. For distributions: histograms (with a number of bins), empirical distributions (ecdf, every series in one panel), two-dimensional histograms (hist2d: tick the x series first, then y), violin plots (each series' density, drawn as box plots are) and hexagonal bins (hexbin, for many observations: x first, then y). A surface draws the series side by side along x and the dates along y, each value a height, in 3-D: a yield curve over time, with its maturities ticked in order.

Stacked bars and areas put negative values below zero, as contributions to growth do. Series named under Right axis are drawn against a second scale on the right. A transform plots each series as an index (first period shown = 100), its change, its growth on the previous period or on a year earlier, or its log. Shade marks periods such as recessions: give them (2008Q3:2009Q2, 2020Q1:2020Q2) or a 0/1 series. Events mark dates and reference lines mark values (an inflation target), each with an optional label after =. Values can be written on bars, panels can share one scale, and Advanced settings have a log scale and fixed limits. For a scatter plot, tick the x series first. For a panel dataset, name an entity, or plot one series to get a line per entity; a cross-section's entities label its bars. The figure opens in its own window, where it can be copied as an image, saved as PNG, SVG or PDF, or its data copied. Results have figures of their own in their windows' Graph tabs.

pymetrix.commands.QuantileProcessPlot dataclass

QuantileProcessPlot(fit: Annotated[str, Widget('object', source='FittedEquation', help='a quantile regression (or any linear equation): its equation and sample are used')], data: Annotated[str, Widget('object', source='Dataset', help='the data it was fitted to')] = 'data', quantiles: Annotated[str, Widget('text', help='the quantiles, between 0 and 1, separated by commas')] = '0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9', vcov: Annotated[Literal['robust', 'iid'], Widget('choice', help='standard errors: robust (kernel sandwich) or assuming iid errors')] = 'robust', alpha: Annotated[float, Widget('number', min=0.01, max=0.5, step=0.05, help='the bands cover 1 - alpha')] = 0.1, name: str = 'quantile_process_result', start: Annotated[str, Widget('period', advanced=True, help="first period; empty = the fit's sample")] = '', end: Annotated[str, Widget('period', advanced=True, help="last period; empty = the fit's sample")] = '')

Bases: Command

A quantile regression's coefficients across quantiles, each with its confidence band and the least-squares estimate as a dashed line.

Choose a fitted equation (a quantile regression, or any linear one): its equation and sample are re-estimated by quantile regression at each of the quantiles listed, and by least squares for comparison. A coefficient that changes across quantiles means the regressor moves the spread or the shape of the distribution of the dependent variable, not only its centre; one whose band covers the least-squares line at every quantile is consistent with a pure location shift. The bands are pointwise, so do not read them as a joint test.

pymetrix.commands.RaggedEdge dataclass

RaggedEdge(data: Annotated[str, Widget('object', source='Dataset', help='the indicators (monthly, as a rule), each with its publication lag')] = 'data', when: Annotated[str, Widget('text', label='On the day', help='a date, e.g. 2025-02-15: the edge as it stood then; empty = the data as they are')] = '', name: str = 'edge', release_lags: Annotated[str, Widget('text', advanced=True, help=_RELEASE_LAGS_HELP)] = '')

Bases: Command

Show where each series ends: its last observation, its publication lag and the day that value came out.

Indicators are published with different delays (a survey days after the month, industrial production six weeks later), so on any day they end in different months: the ragged edge. With a day, the table also says how many periods each series is behind the most recent one, as it stood that day. Publication lags come from each series' metadata (Variable.release_lag); give others to check what difference they make.

pymetrix.commands.RealignEdge dataclass

RealignEdge(data: Annotated[str, Widget('object', source='Dataset', help='the indicators, ending in different periods')] = 'data', name: str = 'realigned')

Bases: Command

Vertical realignment: shift each series on so that its last value falls in the latest period any series has.

A series one month behind is moved one month on, so its latest figure is treated as current: the data end together, with no forecasts (Altissimo et al. 2010). The series' timing changes, so a model estimated on the realigned data should be used with data realigned the same way, the same days after each month.

pymetrix.commands.Reconcile dataclass

Reconcile(components: Annotated[str, Widget('series', depends_on='data', multiple=True, help='the series that should add up to the total')], total: Annotated[str, Widget('series', depends_on='data', help='their high-frequency total')], data: Annotated[str, Widget('object', source='Dataset', help='the high-frequency data with the components and the total')] = 'data', low: Annotated[str, Widget('object', source='Dataset', empty='none: only the total', help='low-frequency data with a series for each component whose totals must hold')] = '', fixed: Annotated[str, Widget('series', depends_on='data', multiple=True, help='components left as they are')] = '', method: Annotated[Literal['denton', 'denton-additive', 'least-squares', 'weighted'], Widget('choice', help='Denton: smooth adjustments (proportional or additive); least squares: in proportion to the values; weighted: in proportion to the weights')] = 'denton', conversion: Annotated[Literal['sum', 'average', 'first', 'last'], Widget('choice', help='how the low-frequency values add up')] = 'sum', weights: Annotated[str, Widget('text', advanced=True, help='how much each component moves, e.g. cons=1, inv=4 (larger moves more; empty = equally)')] = '', replace: Annotated[bool, Widget('checkbox', help='replace the components in the data with the reconciled series')] = True, name: str = 'reconciliation')

Bases: Command

Make components (often disaggregated series) add up to their high-frequency total, keeping their own totals.

Each period the components are moved, as little as the method allows, until they add up to the total; each component with a series of the same name in the low-frequency data still adds up to it; fixed components are not moved. Denton moves the components' first differences as little as possible, in proportion to their size or in their units (Di Fonzo and Marini's multivariate Denton); least squares spreads each period's gap in proportion to the values; weighted spreads it in proportion to the components' weights, whatever their levels and signs. The summary lists the size of each component's adjustment and the gaps before and after.

to_call

to_call() -> Any

The reconcile call (replacing the components in the data, when asked, is a second line of the script).

pymetrix.commands.RenameSeries dataclass

RenameSeries(data: Annotated[str, _DATA], old: Annotated[str, Widget('text', help='the series to rename')], new: Annotated[str, Widget('text', help='its new name')])

Bases: Command

Rename a series; recipes of derived series that use it follow.

pymetrix.commands.RunBacktest dataclass

RunBacktest(fit: Annotated[str, Widget('object', source='FittedEquation,FittedVAR,FittedExponentialSmoothing,FittedSARIMA,FittedTheta,FittedSTLForecast,FittedBMA,FittedThresholdAR,FittedLearner', help='the estimate to re-estimate at each origin')], start: Annotated[str, Widget('period', help='first period at which the model is re-estimated and forecasts made; leave enough data before it')], end: Annotated[str, Widget('period', help='last forecast origin; forecasts whose targets lie beyond the data have no error')], data: Annotated[str, Widget('object', source='Dataset')] = 'data', horizon: Annotated[int, Widget('number', min=1, max=40, help='longest horizon forecast at each origin; every horizon from 1 up to it is kept')] = 8, window: Annotated[int, Widget('number', min=0, max=1000, advanced=True, help='estimate on the last N periods to each origin (a rolling window); 0 = all of them (expanding)')] = 0, name: str = 'backtest_result', vintages: Annotated[str, Widget('text', advanced=True, help='real time: origin=dataset for every origin, e.g. 2015Q1=v2015q1, 2015Q2=v2015q2 (the data as they were then); empty = the latest data throughout')] = '')

Bases: Command

Evaluate a forecasting model out of sample: re-estimate it at each origin and forecast ahead.

Choose a fitted equation, VAR or exponential smoothing model: it is re-estimated on the data up to each origin (Start to End) and forecast Horizon periods ahead, and the forecasts are compared with what happened.

This pseudo out-of-sample exercise mimics real-time forecasting, so it is a fairer guide to forecast accuracy than the in-sample fit; but it uses the latest data release throughout, not the data as first published, and so tends to flatter them. Forecasts at every horizon from 1 to Horizon are kept, and the accuracy table gives the RMSE, MAE and mean error by variable and horizon; a mean error far from zero signals bias. An expanding window uses all data to each origin; a rolling window adapts to structural change at the cost of noisier estimates. Use enough origins (a few dozen) for the comparisons and tests to mean much.

For a real-time backtest, give Vintages: for each origin, the dataset as it was then (origin=dataset, separated by commas, one for every origin from Start to End). The model is then re-estimated and forecast from the data available at each origin, while the errors are still measured against the latest release (Data).

A logit or probit equation's forecasts are probabilities of the event, from its regressors in each target period (lag them for genuine forecasts): the result adds their Brier and log scores, a calibration table and a reliability diagram.

pymetrix.commands.RunCode dataclass

RunCode(code: Annotated[str, Widget('text', help='Python code')], source: Annotated[Literal['immediate', 'editor', 'script'], Widget('choice', help='where the code was run from')] = 'immediate')

Bases: Command

Python typed in the Immediate window or run from the Code window.

reads

reads(session: Session, versions: dict[str, int]) -> set[str]

Workspace objects the code uses: names it reads (or, for IPython syntax, mentions).

pymetrix.commands.RunTest dataclass

RunTest(source: Annotated[str, Widget('object', source='FittedEquation,FittedVAR,FittedVECM,Dataset', help='the object to examine: a fit, a VAR or VECM, or a dataset')], test: Annotated[str, Widget('test', depends_on='source')], options: Annotated[str, Widget('options', depends_on='test', group='Test settings')] = '', name: str = 'test')

Bases: Command

Run a specification or diagnostic test on a fit, a VAR or VECM, or a dataset.

The list shows only tests that apply to the chosen object; the test's settings appear below it.

pymetrix.commands.SaturateIndicators dataclass

SaturateIndicators(fit: Annotated[str, Widget('object', source='FittedEquation', help='the equation to saturate, fitted by least squares; its terms are kept')], data: Annotated[str, Widget('object', source='Dataset', help='the data the equation was fitted to')] = 'data', iis: Annotated[bool, Widget('checkbox', help='impulse indicators: an outlier in one period')] = True, sis: Annotated[bool, Widget('checkbox', help='step indicators: a shift in the level from a date on')] = False, t_pval: Annotated[float, Widget('number', min=1e-05, max=0.2, help='target size: the share of indicators kept by chance; about 1/T')] = 0.001, blocks: Annotated[int, Widget('spin', min=1, max=20, help='blocks of indicators searched in turn (2: split-half)')] = 2, name: str = 'saturation')

Bases: _Selection

Indicator saturation: find outliers and breaks by adding an indicator for every date and selecting by GETS.

Impulse-indicator saturation (IIS) adds a dummy for every observation, step-indicator saturation (SIS) a step from every date on, more indicators than observations. They are searched in blocks (two: split-half), GETS selecting within each block with the equation's own terms kept, then across the indicators the blocks retained. Under no outliers or breaks about t_pval of the indicators are kept by chance (the gauge): choose t_pval near 1 / T.

The result lists the retained indicators, the detected outliers (impulses) and breaks (steps) with their dates and sizes, and the final equation has them as terms, pulse("date") and step("date"), so it can be forecast and tested as any other.

pymetrix.commands.SaveRound dataclass

SaveRound(round: Annotated[str, Widget('object', source='ForecastRound', help='the round to save, under its own name')], folder: Annotated[str, Widget('text', help="the store's folder, e.g. forecasts; keep one per forecast process so rounds stay comparable")] = 'forecasts', overwrite: Annotated[bool, Widget('checkbox', help='replace a different round saved under the same name; its earlier record is lost')] = False)

Bases: Command

Save a round in a forecast store: a folder that keeps every round, for comparison and evaluation.

Each round is written as a Parquet file of its paths and a JSON record of when it was made, the last period of data used, its notes and every judgemental adjustment. Keeping each round unchanged is what lets you later compare rounds, chart how forecasts of a variable evolved, and judge the forecasts against what happened. Saving the same round again does nothing; a different round under an existing name is refused unless Overwrite is ticked, which loses the earlier record.

pymetrix.commands.SeasonalAdjust dataclass

SeasonalAdjust(variables: Annotated[str, Widget('series', depends_on='data', multiple=True, help='monthly or quarterly series to adjust')], data: Annotated[str, Widget('object', source='Dataset')] = 'data', method: Annotated[str, Widget('extension', source='seasonal', help='STL, X-13ARIMA-SEATS or classical')] = 'STL', settings: Annotated[str, Widget('options', depends_on='method', source='seasonal', group='Method settings')] = '', keep_updated: Annotated[bool, Widget('checkbox', help='recompute when the series changes, so a new release also revises the adjusted history')] = True, name: Annotated[str, Widget('text', help='a new dataset for the result; empty = add to the dataset itself')] = '')

Bases: Command

Seasonally adjust monthly or quarterly series with STL, X-13ARIMA-SEATS or classical decomposition.

<series>_sa (adjusted) and <series>_seasonal (the seasonal factor, or component for additive adjustment) are added to the dataset. Positive series are adjusted multiplicatively unless you choose otherwise. With Keep updated they are derived series, recomputed when the original changes (a new release revises the adjustment). X-13ARIMA-SEATS and TRAMO-SEATS come with the pymetrix-seasonal plugin, and need the Census Bureau's x13as program and Java with JDemetra+ respectively.

pymetrix.commands.SelectOrder dataclass

SelectOrder(variable: Annotated[str, Widget('series', depends_on='data')], data: Annotated[str, Widget('object', source='Dataset')] = 'data', max_ar: Annotated[int, Widget('number', min=0, max=12, help='largest AR order p tried; widen it if the best order is at the edge')] = 4, max_ma: Annotated[int, Widget('number', min=0, max=12, help='largest MA order q tried; every p is crossed with every q, so the grid grows fast')] = 2, exog: Annotated[str, Widget('series', depends_on='data', multiple=True, help="regressors in every candidate: the orders then describe the regression's errors")] = '', name: str = 'orders', intercept: Annotated[bool, Widget('checkbox', advanced=True, help='include a constant in every candidate')] = True)

Bases: Command

Compare ARMA orders for a series by AIC, BIC and Hannan-Quinn.

Every combination up to the largest AR and MA orders is estimated on the same sample; the table marks the best by each criterion.

Each candidate is fitted by exact Gaussian maximum likelihood on the same observations, so the criteria are comparable. BIC penalises parameters most and picks the smallest models, AIC the largest; when they disagree, fit both and compare their residual correlograms. Differences of one or two units are small, and the more parsimonious model usually forecasts as well. Orders that fail to converge are left blank, often a sign of near-cancelling AR and MA roots. Make a trending series stationary first (difference it, or add a trend series under Exogenous series).

pymetrix.commands.SelectSeries dataclass

SelectSeries(series: Annotated[str, Widget('series', depends_on='data', multiple=True, help='series to include by name; added to any that match the patterns')] = '', patterns: Annotated[str, Widget('text', help='comma-separated name patterns, e.g. *_cycle, d*')] = '', data: Annotated[str, Widget('object', source='Dataset')] = 'data', name: Annotated[str, Widget('text', help='name of the selection in the workspace')] = 'selection')

Bases: Command

Select series by name, pattern or both, to derive, estimate or test each of them in one step.

Tick series, give patterns (*_cycle for every cycle, d* for every series starting with d), or both. In code, series can also be selected by metadata: data.series(units="USD bn").

pymetrix.commands.SeriesInfo dataclass

SeriesInfo(data: Annotated[str, _DATA], series: Annotated[str, Widget('text', help='the series to describe')], info: Annotated[str, Widget('text', help='JSON object of the fields to set, e.g. {"units": "USD bn"}')])

Bases: Command

A series' description: label, units, description, source and how it is measured.

pymetrix.commands.ShockDecomposition dataclass

ShockDecomposition(source: Annotated[str, Widget('object', source='FittedModel', help='an estimated model (Model > Estimate model)')], start: Annotated[Literal['first', 'presample'], Widget('choice', help="first: the first period's state is the starting point; presample: decompose from the second period, the first period's shocks going to the shocks")] = 'first', name: str = 'shock_decomposition', occbin: Annotated[bool | None, Widget('choice', advanced=True, help='decompose the OccBin-smoothed path, regimes held at the smoothed ones; empty = when the model was estimated with the OccBin filter')] = None)

Bases: Command

Split an estimated model's Kalman-smoothed history into the contributions of each shock and of the starting point: which shocks drove output, inflation or the policy rate in each period? The parts add up exactly to the smoothed path (in deviations from the steady state).

Start (first period) counts the first period's state, its shocks included, as the starting point; Start (presample) takes the first period as the state before the sample and decomposes from the next, so that period's shocks go to the shocks. Early in the sample the starting point carries much of the movement, as in a VAR's historical decomposition; read the decomposition from a few years in.

A model estimated with the OccBin filter (Model > Estimate model, Advanced, OccBin) is decomposed along its OccBin-smoothed path, with the regimes held at the smoothed ones: the binding constraints' constants (a rate held at its floor) are a part of their own, and the parts still add up. OccBin decompositions start from the first period. A model estimated with known-date regimes is decomposed through the regimes' time-varying rules, their constants a part of their own ("regimes"). With correlated shocks, the parts are of the shocks orthogonalised by Cholesky in the model's order, as impulse responses are.

pymetrix.commands.Slice dataclass

Slice(data: Annotated[str, Widget('object', source='Dataset')] = 'data', entity: Annotated[str, Widget('entity', depends_on='data', help='one entity, e.g. WSM: its time series')] = '', period: Annotated[str, Widget('period', help='or one period, e.g. 2020Q1: the cross-section')] = '', name: str = 'panel_slice')

Bases: _OnData

Take one entity's time series out of a panel, or the cross-section of all entities in one period.

The result is an ordinary dataset: an entity's slice is a time series, so time-series tools (unit-root tests, ARIMA, VARs) apply to it; a period's slice is a cross-section for regressions across entities at one date. Use it to look at one unit in detail, but remember that conclusions from one entity or one period need not hold for the panel as a whole. Choose either an entity or a period, not both.

pymetrix.commands.SolveModel dataclass

SolveModel(equations: Annotated[str, Widget('object', source='FittedEquation,Equation,Model,EViewsXmlModel', multiple=True, help='fitted equations and identities, or a model read (FRB/US XML)')], start: Annotated[str, Widget('period', help='the first period solved; earlier values, the lags, come from the data', empty="the sample's first period")], end: Annotated[str, Widget('period', help='the last period solved; exogenous series need values up to it', empty="the sample's last period")], data: Annotated[str, Widget('object', source='Dataset')] = 'data', solver: Annotated[str, Widget('extension', source='solvers', help='Newton solves all equations jointly; Gauss-Seidel one at a time')] = 'Newton', solver_settings: Annotated[str, Widget('options', depends_on='solver', source='solvers', group='Solver settings')] = '', ordering: Annotated[Literal['joint', 'blocks'], Widget('choice', advanced=True, group='Solver settings', help='joint: the solver takes all the equations each period; blocks: recursive equations solved once, in order, the solver only on the simultaneous blocks (Newton, Gauss-Seidel)')] = 'joint', fallback: Annotated[bool, Widget('checkbox', advanced=True, group='Solver settings', help='a period the solver cannot solve is tried again with damped Gauss-Seidel (damping 0.5, 400 iterations), then Newton with a line search (Newton, Gauss-Seidel)')] = False, params: Annotated[str, Widget('text', help='values for the parameters of equations not estimated, e.g. b=0.99, k=0.1')] = '', shift: Annotated[str, Widget('text', group='Scenario', help='add to exogenous series, e.g. g=5 (every period) or g[2025Q1:2025Q4]=5')] = '', set_to: Annotated[str, Widget('text', group='Scenario', help='replace exogenous series, e.g. rate=2.5 or ey[2025Q1]=-1')] = '', hold: Annotated[str, Widget('text', group='Scenario', help='hold endogenous variables (exogenize), e.g. i[2025Q1:2025Q4]=0.5')] = '', free: Annotated[str, Widget('text', group='Scenario', help='one shock or exogenous variable per held variable, in order, solved to hold it (endogenize); more free shocks than holds: a least-norm plan (first-order solver)')] = '', unanticipated: Annotated[str, Widget('text', advanced=True, group='Scenario', help='shocks that are surprises (first-order solver); others are known in advance')] = '', hold_sd: Annotated[str, Widget('text', advanced=True, group='Scenario', help='soft holds (first-order solver): a standard deviation, e.g. y[2025Q4]=0.25 or y=0.25; empty or 0 = exact')] = '', free_sd: Annotated[str, Widget('text', advanced=True, group='Scenario', help="least-norm plan (first-order solver): the free shocks' sizes, e.g. ei=0.2, ey=0.5; the smallest shocks in these units that meet the holds")] = '', name: str = 'solution', draws: Annotated[int, Widget('number', min=0, max=100000, step=100, advanced=True, group='Stochastic simulation', help='draws of a stochastic simulation (the fan, quantiles); 0 = none')] = 0, seed: Annotated[int, Widget('number', min=0, max=2 ** 31 - 1, advanced=True, group='Stochastic simulation', help='random seed of the simulation; the same seed gives the same quantiles')] = 0, errors: Annotated[Literal['normal', 'bootstrap', 'sample'], Widget('choice', advanced=True, group='Stochastic simulation', help="fitted equations' errors: normal with their standard errors and correlations, or their residuals resampled; sample: a sample of residuals given (below) resampled, a period at a time")] = 'normal', shock_sd: Annotated[str, Widget('text', advanced=True, group='Stochastic simulation', help='standard deviations: by equation (e.g. cons=0.5), or by shock with the first-order solver (e.g. ey=0.5, ei=0.2)')] = '', coefficients: Annotated[bool, Widget('checkbox', advanced=True, group='Stochastic simulation', help="draw the fitted equations' coefficients too (parameter uncertainty)")] = False, over: Annotated[str, Widget('text', advanced=True, group='Panel', help="a panel's entity axis (country...): the model solved for each entity on its own series")] = '', links: Annotated[str, Widget('text', advanced=True, group='Panel', help='variables each entity takes from the others, solved jointly: ys = trade @ y (trade: a matrix of weights, a row per entity; one row for an aggregate)')] = '', regimes: Annotated[str, Widget('text', advanced=True, group='Regimes', help='first-order solver or perfect foresight: parameters that change at known dates, known in advance, e.g. 2025Q1..2026Q4: rho=1, phi_pi=0 (a while) or 2027Q1: phi_pi=2 (for good); 2027Q1 surprise: phi_pi=2 is unknown until it starts')] = '', hold_lower: Annotated[str, Widget('text', advanced=True, group='Scenario', help='ranges (first-order solver): keep a variable at or above, e.g. pi[2025Q1:2025Q4]=1.5; the free shocks move only as far as needed')] = '', hold_upper: Annotated[str, Widget('text', advanced=True, group='Scenario', help='ranges (first-order solver): keep a variable at or below, e.g. pi=3')] = '', residuals: Annotated[str, Widget('object', source='Dataset,dict', advanced=True, group='Stochastic simulation', empty='empty: none', show_if=('errors', ('sample',)), help='errors: sample: residuals by equation, a series named after each equation shocked (a dataset), or add factors over a historical span (Model > Add factors)')] = '', residual_series: Annotated[str, Widget('series', depends_on='residuals', multiple=True, advanced=True, group='Stochastic simulation', show_if=('errors', ('sample',)), help="the dataset's series to resample, each named after an equation; empty = all")] = '', residual_start: Annotated[str, Widget('period', advanced=True, group='Stochastic simulation', show_if=('errors', ('sample',)), help="the dataset's periods to resample from: first (empty = its active sample's)")] = '', residual_end: Annotated[str, Widget('period', advanced=True, group='Stochastic simulation', show_if=('errors', ('sample',)), help="the dataset's periods to resample from: last")] = '', error_scale: Annotated[str, Widget('text', advanced=True, group='Stochastic simulation', help='multiply the errors drawn in some periods, e.g. 2026Q2=0.5 (a backward-looking model)')] = '', workers: Annotated[int, Widget('number', min=1, max=256, advanced=True, group='Stochastic simulation', help='processes solving the draws (a backward-looking model); 1 = this one; the draws are the same for any number')] = 1, adjust: Annotated[str, Widget('object', source='dict', advanced=True, group='Scenario', empty='empty: none', help='add factors (Model > Add factors) added to the equations, so the model tracks the data')] = '', partial: Annotated[bool, Widget('checkbox', advanced=True, group='Scenario', help="hold only in the periods given a value; elsewhere the variable's equation determines it and its free variable keeps its data (Newton, Gauss-Seidel)")] = False)

Bases: Command

Solve a model of fitted equations and identities over a period range.

Choose the equations and the solution period; values before the period come from the data. Choose the solver and, if needed, its settings. In the scenario, targets hold endogenous variables, each with one free shock (exogenize and endogenize). With the first-order solver, shocks are known in advance unless listed as unanticipated. With Hold only where given (advanced), a hold applies only in the periods it gives a value: elsewhere the variable's equation determines it as usual and its free variable keeps its data.

The result's Convergence view shows, period by period, the solver's iterations and the largest residual left and its equation (Newton, Gauss-Seidel, perfect foresight). Before solving, Model.missing_inputs (or Model.check with data and a span) lists the inputs each equation lacks in each period. The solver's settings choose its convergence test (the residual, or the scaled step, which does not depend on the equations' units), Newton's line search and how often it evaluates the Jacobian; under Advanced, Fallback retries a period the solver cannot solve, and Ordering: blocks solves recursive equations once and iterates only on the simultaneous blocks.

Solved over a historical period with no scenario, the solution is a dynamic simulation: compare it with the data to see how far the model drifts when its errors are left out. A policy experiment is best read as the difference between a scenario and a baseline solved over the same period, which removes the model's own tracking error. With draws, the stochastic simulation adds the equations' errors (and, with Coefficients, parameter uncertainty), so its quantiles show the uncertainty around the path; a model with expectations needs the first-order solver for that.

pymetrix.commands.SpecificationSensitivity dataclass

SpecificationSensitivity(fit: Annotated[str, Widget('object', source='FittedEquation,FittedVAR,FittedVECM,FittedLocalProjection', help='the base specification: a fitted equation, VAR, VECM or local projection')], data: Annotated[str, Widget('object', source='Dataset', help='the data it was fitted to')] = 'data', quantity: Annotated[Literal['coefficient', 'response at a horizon', 'response path', 'long-run effect', 'forecast'], Widget('choice', help='what each specification is reduced to')] = 'coefficient', variable: Annotated[str, Widget('text', help="the coefficient, the responding variable, the variable whose long-run effect (an equation's regressor) or forecast is compared")] = '', shock: Annotated[str, Widget('text', help="the shock (a VAR's or VECM's variable or shock; empty for a local projection's own)")] = '', horizon: Annotated[int, Widget('number', min=0, max=200, help="the response's horizon; for a path, the last horizon")] = 8, at: Annotated[str, Widget('period', help="the forecast's date")] = '', lags: Annotated[str, Widget('text', group='Choices', help='lags to try, e.g. 1, 2, 4, bic')] = '', samples: Annotated[str, Widget('text', group='Choices', help='spans separated by semicolons, e.g. 2000Q1:2019Q4; 2005Q1:')] = '', windows: Annotated[Literal['none', 'rolling', 'recursive'], Widget('choice', group='Choices', help="windows over the base's sample, instead of spans")] = 'none', window: Annotated[int, Widget('number', min=2, max=10000, group='Choices', show_if=('windows', ('rolling', 'recursive')), help="the window's length in periods (recursive: the first window's)")] = 40, window_step: Annotated[int, Widget('number', min=1, max=1000, group='Choices', show_if=('windows', ('rolling', 'recursive')), help='periods between one window and the next')] = 4, deterministic: Annotated[str, Widget('text', group='Choices', help="e.g. c, ct (an equation's or VAR's n, c, ct, cs, cts; a VECM's n, ci, co, coli, colo)")] = '', ranks: Annotated[str, Widget('text', group='Choices', help="a VECM's cointegration ranks, e.g. 1, 2")] = '', orderings: Annotated[str, Widget('text', group='Choices', help='Cholesky orderings separated by semicolons, e.g. y, pi, r; pi, y, r')] = '', controls: Annotated[str, Widget('text', group='Choices', help="sets of extra regressors separated by semicolons, none for the base's own, e.g. none; oil; oil, fx")] = '', methods: Annotated[str, Widget('text', group='Choices', help="estimators, e.g. ols, hac (white; a local projection's hac, white)")] = '', draws: Annotated[int, Widget('number', min=0, max=10000, advanced=True, help="bootstrap draws for a VAR's or VECM's response interval; 0 = none")] = 0, alpha: Annotated[float, Widget('number', min=0.001, max=0.5, step=0.01, advanced=True, help="1 - the intervals' coverage, e.g. 0.05 for 95%")] = 0.05, criterion: Annotated[Literal['bic', 'aic'], Widget('choice', advanced=True, help='the information criterion marked')] = 'bic', workers: Annotated[int, Widget('number', min=1, max=64, advanced=True, help='parallel processes; each starts by importing pymetrix, so more pays for slow fits')] = 1, name: str = 'sensitivity')

Bases: Command

Does the result survive other specifications? Fit the model again for every combination of the choices given, and compare one number (or one response path) across them.

Start from a fitted equation, VAR, VECM or local projection: it is the base specification, and each choice changes one thing about it. Lags: numbers, or aic or bic to let the criterion choose. Samples: spans such as 2000Q1:2019Q4 or 2005Q1: (open at the end), separated by semicolons, or rolling or recursive windows over the base's sample. Deterministic terms: an equation's or VAR's n, c, ct, cs or cts (none, constant, trend, seasonals), a VECM's n, ci, co, coli or colo. Ranks: a VECM's cointegration ranks. Orderings: Cholesky orderings of a VAR or VECM, separated by semicolons. Controls: sets of extra regressors (a VAR's exogenous terms), separated by semicolons, none for the base's own. Estimators: ols, white or hac (a local projection's hac or white).

The quantity is a coefficient, an impulse response at a horizon or its whole path, a long-run effect (an equation's long-run multiplier; a VAR's long-run response), or a forecast at a date. The result gives each specification's estimate with its interval, information criteria and diagnostics; the specification curve (the estimates sorted, with the choices each one makes below); the shares with the base's sign and significant; and which choice moves the estimate most. The lowest-criterion specification is marked as one among the others, not as the answer.

vary

vary() -> dict[str, Any]

The choices, as specification_grid takes them.

pymetrix.commands.StateSpaceForm dataclass

StateSpaceForm(source: Annotated[str, Widget('object', source='Template,LinearSolution', help='a template model or a rational-expectations solution')], measurement: Annotated[str, Widget('multiline', help="one per line: observed = expression in model variables; empty = the template's")] = '', measurement_params: Annotated[str, Widget('text', help='values for parameters in the measurement equations, e.g. pi_ss=2')] = '', shock_sd: Annotated[str, Widget('text', help="shock standard deviations, e.g. ey=0.5, ei=0.2; empty = the template's (or 1)")] = '', errors: Annotated[str, Widget('text', help='measurement-error standard deviations, e.g. growth=0.5')] = '', name: str = 'system', transforms: Annotated[str, Widget('text', advanced=True, group='Raw data', help='observed series made from raw data, rebuilt into it in forecasts: growth = 400*dlog(gdp); infl = 400*dlog(cpi)')] = '', reported: Annotated[str, Widget('multiline', advanced=True, group='Reported series', help='one per line: name = expression in model variables, reported with the smoothed history and forecasts but not fitted (e.g. gap = 100*y)')] = '')

Bases: Command

Put a solved forward-looking model in state-space form, linked to data by measurement equations.

Choose a template model (its measurement equations are used unless you write others) or a rational-expectations solution. Measurement equations give each observed series as an expression in the model's variables and their lags, one per line, e.g. infl = 2 + 4pi or growth = 2 + 4(y - y[-1]). Shock sizes and measurement errors are standard deviations.

pymetrix.commands.SuperiorPredictiveAbility dataclass

SuperiorPredictiveAbility(benchmark: Annotated[str, Widget('object', source='Backtest', help='the backtest to beat, e.g. a random walk or the current model')], models: Annotated[str, Widget('object', source='Backtest', multiple=True, help='the competing backtests, over the same origins')], variable: Annotated[str, Widget('text', help='the variable they all forecast')], horizon: Annotated[int, Widget('number', min=1, max=40, help='which horizon to compare; also the shortest default bootstrap block')] = 1, loss: Annotated[_LOSS, Widget('choice', help='the loss to compare; CRPS and log score need density forecasts')] = 'squared', tau: Annotated[float, _TAU] = 0.5, linex_a: Annotated[float, _LINEX] = 1.0, name: str = 'spa_test', draws: Annotated[int, Widget('number', min=100, max=100000, step=100, advanced=True, help='bootstrap resamples for the p-value')] = 1000, block: Annotated[int | None, Widget('number', min=1, max=200, advanced=True, help="the stationary bootstrap's mean block length; empty = automatic")] = None, seed: Annotated[int, Widget('number', min=0, max=2 ** 31 - 1, advanced=True, help='random seed for the bootstrap')] = 0)

Bases: Command

Hansen's test for superior predictive ability: does any of several backtests forecast better than a benchmark? Needs the arch package.

The null is that no model has lower expected loss than the benchmark, at the horizon chosen, on the targets all the backtests forecast. The p-value is Hansen's consistent one, from a stationary bootstrap of the loss differentials; the lower and upper bounds are in the details (the upper is White's Reality Check, which a poor model in the set makes conservative, the problem Hansen's version corrects). A small p-value says at least one model beats the benchmark; it does not say which: the details name the one with the lowest average loss, and Compare many forecasts (the model confidence set) separates them. Losses are serially correlated at longer horizons, which the block bootstrap allows for; the default mean block length is the larger of the horizon and n^(1/3).

pymetrix.commands.TableHeatmap dataclass

TableHeatmap(source: Annotated[str, Widget('text', help='the result whose table to show')], table: Annotated[str, Widget('text', help='the table: the tab it is on')] = 'Results', label: Annotated[str, Widget('text', help='what the colours measure, for the colour bar (optional)')] = '', scale: Annotated[Literal['auto', 'table', 'column'], Widget('choice', help='auto: each column its own scale when the columns differ in units or size; table: one scale; column: each column its own')] = 'auto', name: Annotated[str, Widget('text', help='save as (empty: <source>_heatmap)')] = '')

Bases: Command

Show a result's table as a heatmap: each number a coloured cell, with a colour bar (Granger p-values, correlations, responses by horizon...). The table's numeric columns are used, less a posterior table's sampling diagnostics (R-hat, effective draws), which describe the sampler rather than the posterior. Values of both signs get a scale symmetric about zero. The scale is chosen by the columns (auto): one for the table, or each column its own where the columns are in different units, such as a posterior's means beside its effective draws. Recorded as heatmap_figure(granger, view='Results', scale='auto', diagnostics=False).

pymetrix.commands.TestEach dataclass

TestEach(test: Annotated[str, Widget('test', depends_on='data')], data: Annotated[str, Widget('object', source='Dataset')] = 'data', series: Annotated[str, Widget('series', depends_on='data', multiple=True, help=_SERIES_HELP)] = '', selection: Annotated[str, Widget('object', source='Selection', help=_SELECTION_HELP)] = '', options: Annotated[str, Widget('options', depends_on='test', exclude=('variable',), group='Test settings')] = '', name: str = 'tests')

Bases: _Loop, Command

Run the same test on each selected series, e.g. a unit-root test, with the results in one table. Tick the series here, or choose a selection made with Data > Select series.

The table gives each series' statistic, p-value and decision at 5%, under the null hypothesis stated below it. The same test settings (lags, deterministic terms) apply to every series, so choose settings that suit them all, or test series that need different settings separately. With many series, some will reject at 5% by chance even when the null is true for all of them (about one in twenty), so read the decisions as a screen, not as separate findings; a multiple-testing correction or a panel test is the way to draw a joint conclusion.

pymetrix.commands.ToLong dataclass

ToLong(data: Annotated[str, Widget('object', source='Dataset')] = 'data', entity: Annotated[str, Widget('text', help='name of the new axis, e.g. country')] = 'country', layout: Annotated[Literal['series_entity', 'one_series'], Widget('choice', help='series_entity: columns y_AUS, c_AUS...; one_series: a column per entity')] = 'series_entity', stubs: Annotated[str, Widget('text', help='series_entity: the series names, e.g. y, c; empty = found from the columns')] = '', series_name: Annotated[str, Widget('text', help='one_series: the name of the series, e.g. gdp')] = '', name: str = 'panel', sep: Annotated[str, Widget('text', advanced=True, help='between the series name and the entity')] = '_')

Bases: _OnData

Make a panel from one column per series and entity (y_AUS, c_AUS, y_NZL...), or from one column per entity of a single series (a sheet with a column per country).

The series names are what comes before the last separator, when two or more columns share it; give them under Series to be exact. Columns that match none are kept, the same for every entity (e.g. a world price).

pymetrix.commands.ToWide dataclass

ToWide(data: Annotated[str, Widget('object', source='Dataset')] = 'data', series: Annotated[str, Widget('series', depends_on='data', multiple=True, help='series to spread; empty = all')] = '', name: str = 'wide', sep: Annotated[str, Widget('text', advanced=True, help='between the series name and the entity')] = '_')

Bases: _OnData

One series per entity: y becomes y_AUS, y_NZL... and the panel becomes a set of time series.

Useful for graphs comparing countries, for exporting to a spreadsheet, and for methods that need time series.

pymetrix.commands.UseHouseStyle dataclass

UseHouseStyle(source: Annotated[str, Widget('text', help='the figure whose style to use, or the result whose figure it is')] = '', tab: Annotated[str, Widget('text', advanced=True, help='for a result: the tab its figure is on')] = 'Graph', notes: Annotated[bool, Widget('checkbox', help='its notes, text, lines and bands too')] = False, stop: Annotated[bool, Widget('checkbox', help='stop using a house style')] = False)

Bases: Command

Make this figure's recorded style the house style: every figure drawn from now on starts from it, where its calls apply (a series' call where that series is drawn, a panel's where the panel is), with the figure's own calls after it. Notes, text, lines and bands stay with this figure unless copied too. Tick stop to draw figures without a house style again. Recorded as set_house_style(figure_of(chart)); open windows show it when they are drawn again.

pymetrix.commands.VarianceDecomposition dataclass

VarianceDecomposition(var: Annotated[str, Widget('object', source='FittedVAR,FittedVECM,FittedBVARSV,FittedMSVAR,FittedQuantileVAR')], periods: Annotated[int, Widget('number', min=1, max=400, help='forecast horizons decomposed, 1 to this; long enough for the shares to settle')] = 20, scheme: Annotated[Literal['Cholesky', 'LongRun', 'SignRestrictions', 'MaxShare', 'News', 'Heteroskedasticity'], Widget('', help=_SCHEME_HELP)] = 'Cholesky', ordering: Annotated[str, Widget('text', help='Cholesky order, most exogenous first; empty = VAR order', show_if=('scheme', ('Cholesky',)))] = '', signs: Annotated[str, Widget('text', help='each shock and the signs of its responses: supply: gy+, pi-; demand: gy+, pi+', show_if=('scheme', ('SignRestrictions',)))] = '', sign_horizon: Annotated[int, Widget('number', min=0, max=40, help='the signs hold on impact and for this many periods after', show_if=('scheme', ('SignRestrictions',)))] = 0, zeros: Annotated[str, Widget('text', help='zero restrictions on impact: each shock and the variables it does not move, e.g. monetary: gy, pi', show_if=('scheme', ('SignRestrictions',)))] = '', long_run_zeros: Annotated[str, Widget('text', advanced=True, show_if=('scheme', ('SignRestrictions',)), help='zero restrictions in the long run (cumulated responses), e.g. demand: gy')] = '', share_variable: Annotated[str, Widget('text', show_if=('scheme', ('MaxShare', 'News')), help='the variable whose forecast-error variance the shock explains most of, e.g. tfp')] = '', share_horizon: Annotated[int, Widget('number', min=0, max=400, show_if=('scheme', ('MaxShare', 'News')), help='the share is of the forecast-error variance up to this horizon, e.g. 40 quarters')] = 40, share_start: Annotated[int, Widget('number', min=0, max=400, advanced=True, show_if=('scheme', ('MaxShare', 'News')), help='max share: the first horizon counted (0: impact)')] = 0, breaks: Annotated[str, Widget('text', show_if=('scheme', ('Heteroskedasticity',)), help='the first period of each new variance regime, e.g. 1984Q1 (two dates: three regimes)')] = '', name: str = 'fevd', rotations: Annotated[int, Widget('number', min=10, max=100000, step=100, advanced=True, show_if=('scheme', ('SignRestrictions',)), help='sign restrictions: rotations accepted')] = 1000, max_tries: Annotated[int, Widget('number', min=1000, max=10000000, step=10000, advanced=True, show_if=('scheme', ('SignRestrictions',)), help='sign restrictions: rotations tried before giving up')] = 200000, sign_seed: Annotated[int, Widget('number', min=0, max=2 ** 31 - 1, advanced=True, show_if=('scheme', ('SignRestrictions',)), help='sign restrictions: random seed of the rotations')] = 0, narrative_signs: Annotated[str, Widget('text', advanced=True, show_if=('scheme', ('SignRestrictions',)), help="narrative restrictions: the shock's sign in named periods, e.g. monetary: 1979M10+, 1990M12-")] = '', narrative_major: Annotated[str, Widget('text', advanced=True, show_if=('scheme', ('SignRestrictions',)), help='narrative restrictions: the variable the shock moved most, e.g. monetary: 1979M10 ff')] = '', period: Annotated[str, Widget('period', advanced=True, group='BVAR-SV and MS-VAR', help='BVAR with stochastic volatility: the period whose volatilities size the shocks (empty: the last)')] = '', coverage: Annotated[float, Widget('number', min=0.5, max=0.999, step=0.05, advanced=True, group='BVAR-SV and MS-VAR', help='BVAR with stochastic volatility or Markov-switching VAR: probability the bands cover')] = 0.68, regime: Annotated[int, Widget('number', min=0, max=9, advanced=True, group='BVAR-SV and MS-VAR', help='Markov-switching VAR: the regime held fixed over the horizon (0: the first)')] = 0, draws: Annotated[int, Widget('number', min=0, max=10000, step=100, advanced=True, group='BVAR-SV and MS-VAR', help='Markov-switching VAR: draws of the parameters for bands; 0 = none')] = 0, seed: Annotated[int, Widget('number', min=0, max=2 ** 31 - 1, advanced=True, group='BVAR-SV and MS-VAR', help='Markov-switching VAR: seed of the parameter draws')] = 0, generalised: Annotated[bool, Widget('checkbox', advanced=True, group='Quantile VAR', help="quantile VAR: Pesaran and Shin's generalised decomposition, free of the order (Ando, Greenwood-Nimmo and Shin), rather than Cholesky")] = False, bootstrap_kind: Annotated[Literal['model default', 'residual', 'wild', 'block', 'parametric', 'pairs'], Widget('choice', advanced=True, group='Bootstrap', help="how the bands' draws are made: model default (a VAR's parametric bootstrap, a VECM's residual one; for a VAR's shares, choose a kind for bands: Draws (0: 500) and Coverage), residual, wild (heteroskedastic errors), block (dependent errors), parametric (Gaussian) or pairs (VARs)")] = 'model default', block_length: Annotated[int, Widget('number', min=0, max=400, advanced=True, group='Bootstrap', show_if=('bootstrap_kind', ('block',)), help='block bootstrap: periods in a block; 0 = automatic (5.03 T^(1/4))')] = 0, wild_dist: Annotated[Literal['rademacher', 'mammen', 'normal'], Widget('choice', advanced=True, group='Bootstrap', show_if=('bootstrap_kind', ('wild',)), help="wild bootstrap: the multipliers, Rademacher (plus or minus one), Mammen's or normal")] = 'rademacher', bias_correct: Annotated[bool, Widget('checkbox', advanced=True, group='Bootstrap', help="Kilian's bias correction of the VAR's coefficients before and in the bootstrap (VARs)")] = False, bootstrap_design: Annotated[Literal['recursive', 'fixed'], Widget('choice', advanced=True, group='Bootstrap', help='recursive rebuilds each series from its first values; fixed keeps the lagged data (VARs)')] = 'recursive', band_type: Annotated[Literal['percentile', 'hall'], Widget('choice', advanced=True, group='Bootstrap', help="percentile bands, or Hall's (the draws reflected about the estimate)")] = 'percentile')

Bases: Command

Forecast-error variance decomposition of a VAR or VECM.

The share of each variable's forecast-error variance due to each identified shock, by horizon.

The shares, in per cent, add up to 100 for every variable at each horizon. Short horizons show what moves a variable now, long ones what drives its fluctuations; for a stationary VAR the shares settle as the horizon grows. The shares depend on the identification as much as the responses do: under Cholesky the first variable's own shock explains all of its variance on impact by construction. A shock that explains little of a variable's variance can still have a significant response; the two answer different questions.

Under MaxShare or News the first shock is the one identified (its share of the chosen variable is as large as any shock's can be over those horizons) and the others only complete the decomposition; under Heteroskedasticity the shares are those of the first variance regime, where every shock has unit variance.

A Bayesian VAR with stochastic volatility gives the shares with the volatilities of Period (empty: the last), posterior means with Coverage bands over the draws; a Markov-switching VAR those of Regime, held fixed over the horizon, with Coverage bands over Draws draws of its parameters from the estimates' asymptotic normal distribution (0: none); a quantile VAR those of its quantile system with the covariance of its quantile residuals (Ando, Greenwood-Nimmo and Shin's quantile connectedness, orthogonalised). All three are recursive in the VAR's order: choose Cholesky with Ordering empty.

A point-identified VAR's shares get Coverage bands from a bootstrap when the Bootstrap group (Advanced) names a kind: residual, wild, block, parametric or pairs, with Draws draws (0: 500) and Seed.

pymetrix.commands.VARLagOrder dataclass

VARLagOrder(variables: Annotated[str, Widget('series', depends_on='data', multiple=True)], max_lags: Annotated[int, Widget('number', min=1, max=24, help='longest lag compared; all lengths use the sample this allows, so it costs observations')] = 8, exog: Annotated[str, Widget('text', help='exogenous expressions (optional)', advanced=True)] = '', trend: Literal['c', 'ct', 'n'] = 'c', data: Annotated[str, Widget('object', source='Dataset')] = 'data', name: str = 'lag_order', by: Annotated[str, Widget('text', advanced=True, help="a panel's entity axis, for a panel VAR (Andrews and Lu's criteria)")] = '')

Bases: Command

Information criteria for choosing a VAR's lag length.

All lag lengths up to the maximum are compared on the same sample. For a panel VAR give its entity axis (under Advanced): Andrews and Lu's MBIC, MAIC and MQIC from Hansen's J, with the same instruments for every lag length.

The criteria often disagree: BIC and HQ choose fewer lags than AIC and FPE, and in VARs with several variables a few extra lags cost many parameters. Short lags may leave serial correlation in the residuals (check it with a portmanteau test on the fitted VAR, Test > Run test); long lags make impulse responses noisy. For quarterly data, four lags is a common check on whatever the criteria choose.

pymetrix.commands.VECMLagOrder dataclass

VECMLagOrder(variables: Annotated[str, Widget('series', depends_on='data', multiple=True)], max_lags: Annotated[int, Widget('number', min=1, max=24, help='most lagged differences compared; all lengths use the sample this allows')] = 8, deterministic: Case = 'unrestricted constant (case 3)', data: Annotated[str, Widget('object', source='Dataset')] = 'data', name: str = 'vecm_lags', exog: Annotated[str, Widget('text', advanced=True)] = '', exog_coint: Annotated[str, Widget('text', advanced=True)] = '', seasons: Annotated[int, Widget('number', min=0, max=52, advanced=True)] = 0)

Bases: Command

Information criteria for choosing a VECM's lag length (in differences).

Lag lengths 0 to the maximum are compared on the same observations by AIC, BIC, Hannan-Quinn and FPE, in the deterministic case chosen here. The lags counted are those of the differences, so p lags in a VAR in levels correspond to p - 1 here. Choose the lags before the cointegrating rank: Johansen's tests depend on them, and too few lags leave serial correlation that distorts the tests. BIC tends to pick fewer lags than AIC; check the chosen model's residuals.

pymetrix.extension.Actor dataclass

Actor(kind: str = 'person', name: str = '', via: str = 'python')

Who took a step: kind "person" or "agent"; name, the person's login or the agent's client as it names itself (blank if unknown); via, the interface: "app", "python" (scripts and notebooks) or "mcp".

pymetrix.extension.AppInterface dataclass

AppInterface(_session: Callable[[], Any], _selected: Callable[[], str | None], _open_dialog: Callable[[type, Any], Any], _run: Callable[[Any], Any], _status: Callable[[str], None], _listeners: list[Callable[[], None]] = list(), _open_demo: Callable[[str], None] | None = None, _closed: bool = False)

The desktop app as a plugin's panel sees it.

session property

session: Any

The open session (it changes when another project opens: read it each time).

selected

selected() -> str | None

The name of the object selected in the Objects panel, if any.

open_dialog

open_dialog(command_cls: type, initial: Any = None) -> Any

Open a command's dialog, filled in from initial (a command); the user runs it, or not.

run

run(command: Any) -> Any

Run a step as the app does: recorded, in the background with progress and Cancel, undoable, and refused while another step runs. Returns its result; raises its error.

status

status(message: str) -> None

A message in the status bar.

open_demo

open_demo(name: str) -> None

Open the demo project name (pymetrix.demos()) as it first was, as File → Open demo project does: the app asks to save unsaved work first, and nothing changes if the user cancels (extension API 1.7).

Raises NotFoundError (with the demos there are) for an unknown name, and NotSupportedError from an interface made without a way to open demos; a panel written for 1.5 too checks for the method, or catches it.

on_history_changed

on_history_changed(callback: Callable[[], None]) -> None

Call callback whenever a step is run, undone or the session replaced. A method of a Qt object (a panel's refresh) is called while that object lives: once it is deleted it is dropped, not called.

pymetrix.extension.AppPanel dataclass

AppPanel(title: str, create: Callable[[AppInterface], Any], area: str = 'right', label: str = '')

A docked panel: its title, create(app) -> QWidget and where it docks first (left, right or bottom).

pymetrix.extension.Command

Base class for commands. Subclasses are dataclasses registered with @command.

pymetrix.extension.ExampleDataset dataclass

ExampleDataset(name: str, description: str, path: Any)

An example dataset a plugin ships: Dataset.example(name) reads the Parquet file at path. path may be any path-like object; os.fspath is called on it only when the dataset is loaded, so it can download data the plugin may not redistribute into a cache on first use.

pymetrix.extension.MCPPolicy dataclass

Policy(root: Path = cwd(), allow_code: bool = False, allow_writes: bool = False, allow_network: bool = False)

What the server may do beyond estimation: run Python code, write files, fetch network data, and where files may be read or written (root and below).

refusal

refusal(command: str) -> str | None

Why command is disabled, or None when it may run.

path

path(value: str, writing: bool = False) -> str

value resolved inside the root folder (absolute), or a network address when those are allowed.

pymetrix.extension.MenuLayout dataclass

MenuLayout(top: str, entries: Sequence[Any] = (), label: str = '')

The order of a plugin's own top menu: command class names, None for a separator, and (title, [entries]) for a submenu, as pymetrix.commands.menus.MENU_LAYOUT. A plugin's dialogs in the core menus go at their end.

pymetrix.extension.Ref dataclass

Ref(name: str)

A reference to an object by its name in a session (a dataset, a fitted equation...), not a copy of it.

pymetrix.extension.ReportNote dataclass

ReportNote(name: str, heading: str, note: Callable[[Any, str], str | None])

A line about each result a report exports (extension API 1.6): note(session, name) returns the line for the result called name, or None for none. The lines go under heading, before the appendix.

pymetrix.extension.SessionEvent dataclass

SessionEvent(kind: str, session: Any, records: tuple[Any, ...] = (), code: str = '', path: str = '', during: str = 'work', detail: Mapping[str, Any] = dict(), time: datetime = (lambda: now(utc))(), actor: Actor = Actor())

Something that happened to a session's history (see the module docstring for the kinds).

pymetrix.extension.SessionObserver dataclass

SessionObserver(name: str, handle: Callable[[SessionEvent], None], records: bool = True)

A plugin's observer of sessions: handle(event) is called for every SessionEvent.

records=True (the default) says it keeps a record of the work, such as a lab book: projects note, at each save, which such observers were active, so a verifier can tell work done without them.

pymetrix.extension.TranslationOutcome dataclass

Outcome(statement: Any, status: str, reason: str = '', ops: list[Any] = list(), file: str = '', kind: str = '', children: list[Any] = list(), orelse: list[Any] = list(), else_outcome: Any = None, closer: Any = None)

One statement translated: its status, reason and ops; a block's also its body (children), its else branch (orelse, after else_outcome) and its end (closer); file the included program it is in ('' for the main one); kind "include" for an included program or "subroutine" for a function defined above.

pymetrix.extension.TranslationPanelSpec dataclass

PanelSpec(language: str, translations: Callable[[Any], list[tuple[Any, Any]]], dialog: Any, menu: str, what: str, noun: str = 'program', prefix: str = 'translation')

What a front end's panel shows: language ("EViews": the column of the program's text, and the words of the tooltips), translations(session) (the session's translations, [(step, Translation)], oldest first: from its History's translate steps, say), dialog (the translate dialog's command class, opened by Translate…), menu (where that dialog is, as the help writes it: "File → Translate EViews program…"), what ("an EViews program"), noun ("program") and prefix, the start of its widgets' object names ("eviews": eviews-report, eviews-source).

pymetrix.extension.TranslationReport dataclass

TranslationReport(rows: tuple[ReportRow, ...], program: str = '', language: str = '')

One row per line of the program that has text (blank lines have none), in order; program is its name and language the name of its language, the heading of the column of its text ("EViews", "R").

counts

counts() -> dict[str, int]

How many lines have each status, every status listed.

line

line(number: int, file: str | None = None) -> ReportRow

The row of a line (from 1) of the program, or of an included one (file, as the report names it).

summary

summary() -> Any

The report as a Table: line, status, the program's text (headed by its language), Python and reason, with the counts as notes.

files

files() -> list[str]

The program's name and the included programs', in the order their rows come.

to_text

to_text(rows: Any = None) -> str

The report (or some of its rows) as plain text, a line per row; an included program's rows under a line naming it.

pymetrix.extension.Widget dataclass

Widget(kind: str, source: str | None = None, help: str = '', label: str = '', depends_on: str | None = None, multiple: bool = False, show_if: tuple[str, Any] | None = None, group: str = '', min: float | None = None, max: float | None = None, step: float | None = None, advanced: bool = False, exclude: tuple[str, ...] = (), empty: str = '')

How a field appears in a form.

kind: "text", "multiline" (several lines, e.g. one equation per line), "formula", "hidden" (not in forms: set in code only), "period", "file", "choice", "number", "checkbox", "object" (a workspace object of the types in source), "series" (series of the dataset named by field depends_on), "level" (axes and series of that dataset: what to group or pivot by), "entity" (the values of that dataset's entity axis, e.g. its countries), "test" (tests valid for the object named by field depends_on), "method" (estimation methods whose library is installed), "file" (a path with a Browse button; source is the file-type filter), "savefile" (the same, for a file to write: Browse opens a Save dialog), "column" (columns of the file named by field depends_on, plus a blank choice), "item" (results that can be added to a dataset from the object named by depends_on), "shock" (the shocks of the model or solution named by field depends_on), "layer" (the series a figure draws, as "gdp (line)", from the figure or result named by depends_on), "figurepart" (those series and the figure's panels, "panel 0: title (axes)", for the property editor), "axesmethod" (the matplotlib Axes methods that fig.call records), "stylestep" (the style calls recorded on the figure named by field depends_on), "dataset" (the example datasets installed with pymetrix and its plugins), "named" (the names pymetrix knows now of the kind in source: "report_templates", the built-in templates and plugins'; "themes", the built-in themes and those added at runtime), "extension" (the available extensions of the registry group in source, e.g. "variances"; the field's default is always offered too), "options" (a sub-form for the settings of the extension named by field depends_on; source is its registry group: "tests" (the default), "methods", "variances", "filters"...; fields named in exclude are set by the main form and left out). advanced fields go in the dialog's collapsed Advanced settings section (with a sub-form's own advanced settings).

pymetrix.extension.Workspace dataclass

Workspace(key: str, title: str, menus: tuple[str, ...] | None, docks: tuple[str, ...] | None, tools: tuple[str, ...], tip: str)

A stage of the work on the app's stage bar: its menus, panels and tool shortcuts.

pymetrix.translation.Arg dataclass

Arg(name: str, value: Any, how: str = 'kw')

One argument of a Step: the parameter's name, its value, and how it is given: "pos" by position in the script (by name to make_call), "star" a tuple spread over *name, "kw" by name, "varkw" a mapping spread over **name.

pymetrix.translation.Attr dataclass

Attr(base: str, attr: str)

An attribute of a variable's value: m.model.

pymetrix.translation.Cmd dataclass

Cmd(command: Any, uses: tuple[str, ...] = (), fields: Any = None, script: str = '')

Bases: Op

A recorded command that is not a call: command (an AddToDataset, say), whose to_code() is its line of the script, and the variables it uses.

pymetrix.translation.Code dataclass

Code(code: str, names: tuple[Any, ...] = ())

Bases: Op

Python that is not a step (a scalar, a string, a matrix): code sets names (a Text for a name made when the program runs).

pymetrix.translation.Def dataclass

Def(name: str, params: tuple[str, ...], returns: tuple[str, ...] = (), shared: tuple[str, ...] = (), local: bool = False, body: tuple[Any, ...] = (), result: str = '')

Bases: Op

A function: its parameters; returns, the parameters it assigns, given back to the caller's variables (as EViews passes arguments by reference); or result, Python for the one value it returns (an R function's last expression or return(x)), worked out in the function's own variables when it ends or reaches a return; shared, the names it assigns at the program's level (global); local, whether it sees none of the program's names. A function has returns or a result, not both.

returned property

returned: tuple[str, ...]

What its return gives back, as Python: the result, or the parameters it assigns.

pymetrix.translation.For dataclass

For(var: str, iterable: str, body: tuple[Any, ...] = ())

Bases: Op

for var in iterable: (range(1, n + 1), ["a", "b"], names.split()).

pymetrix.translation.If dataclass

If(cond: str, body: tuple[Any, ...] = (), orelse: tuple[Any, ...] = ())

Bases: Op

if cond: ... else: ..., decided when it runs.

pymetrix.translation.Invoke dataclass

Invoke(name: str, args: tuple[str, ...] = (), targets: tuple[Any, ...] = ())

Bases: Op

A call of a Def (EViews's call f(...)): the arguments as Python, and targets: for each parameter the function assigns, the caller's variable that takes its value back (None where the argument is not a variable); for a function with a result, the one variable that takes it (or none).

pymetrix.translation.Jump dataclass

Jump(kind: str)

Bases: Op

exitloop (break), return and stop (the program ends).

pymetrix.translation.New dataclass

New(callee: str, args: tuple[Any, ...] = ())

A pymetrix object made from its arguments: callee is its class or function as the script names it (Equation, OLS, Scenario), found in pymetrix; args as a Step's.

pymetrix.translation.Op

What a statement becomes.

pymetrix.translation.Py dataclass

Py(code: str)

A Python expression worked out when the step runs (main.sample), with the program's variables and the session's objects; the script has it as it is.

pymetrix.translation.RefTo dataclass

RefTo(name: Any)

An object of the session by its name, recorded by reference (Ref), as the script names it (a Text for a name made when the program runs).

pymetrix.translation.SampleSpec dataclass

SampleSpec(start: str | None = None, end: str | None = None, where: Text | None = None)

A Sample to make: its ends (pymetrix periods, None for an open end) and its condition.

pymetrix.translation.Source dataclass

Source(source: str, lines: tuple[str, ...], statements: tuple[Any, ...], comments: dict[int, str] = dict())

A program read: its source text, its lines, its statements (each with text, line and last_line) and each line's comments (the comment's text, by line number), which the script keeps.

pymetrix.translation.Spread dataclass

Spread(name: str)

The words of a string variable, spread over a list (*names.split()), as EViews's group g {%names}.

pymetrix.translation.Statement dataclass

Statement(text: str, line: int, last_line: int)

One statement of a program: its text (comments out, continued lines joined), on lines line to last_line (from 1). A front end's own statements may carry more (the EViews plugin's carry the command word, its options and offsets); these three are what the report and the script read.

pymetrix.translation.Step dataclass

Step(function: str, receiver: Any, output: Any, callee: str, args: tuple[Arg, ...] = ())

Bases: Op

A call of pymetrix's API, recorded in steps mode: function (its stable ID, pymetrix:dataset.with_series) on the variable receiver (None for a class method), making output; callee is how the script calls it (data.with_series, Dataset.read). A value is plain (text, a number, a tuple), a Text, a SampleSpec or a Var (a Python variable's value: a named sample).

names property

names: tuple[str, ...]

The Python variables the step's values use.

pymetrix.translation.Var dataclass

Var(name: str)

A Python variable's value inside a Text.

pymetrix.translation.While dataclass

While(cond: str, body: tuple[Any, ...] = ())

Bases: Op

while cond:; steps mode stops after a number of passes the user can change.

Functions

pymetrix.commands.form_spec

form_spec(cls: type) -> list[FieldSpec]

Form fields for a command, or for any dataclass of settings (tests, methods).

pymetrix.commands.load_project

load_project(path: str | Path, trust: bool | None = None, changed_data: str = 'refuse') -> Session

Open a project: restore its data and replay its steps.

trust: None (default) runs the typed code only if it is trusted; True runs it and trusts it from now on; False never runs it. Code that is not run is kept in the history, marked as not run, and saved again with the project.

changed_data: a dataset kept as a reference to its file (Dataset.read(..., embed=False)) is read from the file again; "refuse" (the default) raises DataError if the file's fingerprint differs from the one saved, "read" reads it as it is now.

pymetrix.commands.option_string

option_string(specs: list[FieldSpec], values: dict[str, Any]) -> str

"lags=4, squared=True" for the entries that differ from their defaults.

Text typed into a field that is not a plain string (float | None, int | Sequence[int]...) is passed as written, so 0.5 stays a number.

pymetrix.commands.save_project

save_project(session: Session, path: str | Path, as_copy: bool = False) -> Path

Save the session as a project. as_copy=True writes a copy (an autosave) and leaves the session's own path and unsaved-changes flag as they were.

pymetrix.disclosure.describe_object

describe_object(name: str, obj: Any) -> dict[str, Any]

An object in metadata only: its kind and what is safe to say about its shape (see the module's rules).

pymetrix.disclosure.describe_session

describe_session(session: Any, mode: str = 'metadata_only') -> dict[str, Any]

The project as mode allows: in metadata_only (and local_model), each object (describe_object) and the latest steps, by dialog and what they made, never their code. In full_context, the steps' code as well: the assistant panel shows it to the user, who sends it or not, before each question.

pymetrix.disclosure.to_text

to_text(facts: dict[str, Any]) -> str

The description as compact JSON, for a prompt.

pymetrix.extension.add_help_topic

add_topic(id: str, title: str, text: str, references: tuple[str, ...] = (), see_also: tuple[str, ...] = ()) -> Topic

pymetrix.extension.api

api(id: str | None = None, version: int = 1, show: Callable[[Any], Any] | None = None, as_dataset: bool = True) -> Callable[[Callable[..., Any]], Callable[..., Any]]

Make a public function or method a recorded call (see the module docstring). id defaults to plugin:class.method in lower case (pymetrix:equation.fit). show(arguments) names arguments that generated code writes even at their default (vintage='latest'). as_dataset=False: a data argument given as plain pandas is passed on as it is, for functions that take arrays rather than a Dataset.

pymetrix.extension.blas_threads

blas_threads() -> Iterator[None]

Limit BLAS to get_blas_threads() threads inside the block (nothing changes when that is None). The limit goes through threadpoolctl (OpenBLAS, MKL, BLIS; nothing when it is not installed) and, on macOS 15 or later, Accelerate's own switch.

pymetrix.extension.build_mcp_server

build_server(session: Any = None, policy: Policy | None = None, *, session_of: Any = None, run: Any = None, call: Any = None) -> Any

The MCP server over session (a new Session by default), allowed what policy allows.

For serving a session that lives elsewhere, such as the desktop app's (extension API 1.8, build_mcp_server): session_of() gives the current session each time (the app opens other projects); run(command) runs a step (the app's own runner: in the background, undoable, shown in History); call(fn) runs each tool call and returns its result (the app: on its main thread, since the session and the window live there).

pymetrix.extension.call_migration

call_migration(call_id: str, from_version: int)

Register a function turning a call's arguments saved at from_version into those of the next version.

pymetrix.extension.capture

capture() -> Iterator[list[str]]

Record the warnings raised inside the block (as "Category: message"), then re-issue them.

pymetrix.extension.check_cancelled

check() -> None

Stop the running step here if Cancel was pressed.

pymetrix.extension.command

command(menu: str | None, id: str | None = None)

Register a command class under a menu path such as "Estimate/Equation..." (None: not in the menus, but saved in projects and replayed). id (or the class's command_id) fixes its identifier in projects; the default is plugin:snake_name.

pymetrix.extension.complement

complement(x: Any) -> Any

1 - x, rounded to 12 places so that alpha=0.05 is coverage=0.95 exactly (and back): the conversion between a band's coverage and a test's size. None stays None.

pymetrix.extension.json_schema

json_schema(obj: type | Callable[..., Any]) -> dict[str, Any]

The JSON Schema of a dataclass's fields (a command or settings class) or of a function's arguments.

pymetrix.extension.make_call

make_call(call_id: str, receiver: Any = None, /, *, output: str = '', recorded_by: str = '', **arguments: Any) -> Call

The Call of call_id on receiver (for methods) with arguments, defaults applied, as recording the call would give: how dialogs build the call they run. Name workspace objects with Ref("data"); a Call as the receiver, an argument or a value of a mapping argument is nested in this one (data.series(...).fit(...), nowcast.combine({"bridge": bridge.nowcast(...)})). A *args parameter is given by name, as a tuple.

pymetrix.extension.menu_label

menu_label(menu: str) -> str

A command's own menu label: its menu path less the top menu. Only the first "/" separates them, so a label may hold one: "Model/Import FRB/US XML file..." -> "Import FRB/US XML file...".

pymetrix.extension.migration

migration(command_id: str, from_version: int)

Register a function that turns a step's fields saved at from_version into those of from_version + 1:

@migration("pymetrix:fit_each", 1)
def _(fields):
    fields["selection"] = fields.pop("group")
    return fields

pymetrix.extension.plugin_context

plugin_context(info: PluginInfo) -> Iterator[PluginInfo]

Registrations inside the block belong to info (not those of pymetrix's own modules first imported in it).

pymetrix.extension.random_number_generator

generator(seed: Any = None, name: str | None = None) -> Generator

A NumPy Generator from seed (an integer, a sequence of them, a SeedSequence or None), with the bit generator chosen by set_random_generator (or name). A Generator is returned as it is. With the default "pcg64" this is exactly np.random.default_rng(seed).

pymetrix.extension.register

register(group: str, obj: Any = None, *, name: str | None = None, label: str | None = None, kind: str | None = None, requires: tuple[str, ...] | None = None, preset: Mapping[str, Any] | None = None, plugin: PluginInfo | None = None) -> Any

Register obj in group; usable as a decorator (@register("filters")).

Defaults come from the class: label (else the class name), kind and requires class attributes. name (the short identifier) defaults to the lower-case class name.

pymetrix.extension.register_reader

register_reader(key: str, fn: Reader, connector: Connector | None = None) -> None

key is a URI scheme ("sdmx") or a file extension (".parquet"). A scheme's connector describes its addresses for the Load from connector dialog.

pymetrix.extension.renamed_arguments

renamed_arguments(**renames: Any) -> Callable[[Callable[..., Any]], Callable[..., Any]]

Accept keyword arguments by their old names (old="new"), with a DeprecationWarning; both names at once raise a SpecificationError (also a TypeError). old=("new", convert) also converts the value on the way through (alpha=("coverage", complement): alpha=0.05 is coverage=0.95), and the warning names the conversion. The wrapper records its renames in __renamed__ ({old: new or (new, convert)}, merged with those of a function it wraps). Put it above @api, so the call is recorded under the new names; saved calls with the old names need a call_migration (renamed_call writes one from the same renames). For a settings class, wrap its __init__ and add the old field names to codec.FIELD_ALIASES.

pymetrix.extension.renamed_call

renamed_call(call_id: str, from_version: int, **renames: Any) -> Callable[[dict[str, Any]], dict[str, Any]]

Register the call_migration of a call whose arguments were renamed at from_version + 1, from the same renames as its renamed_arguments (old="new" or old=("new", convert)): a call saved before replays with the new names and converted values. Returns the migration.

pymetrix.extension.renamed_fields

renamed_fields(command_id: str, from_version: int, **renames: Any) -> Migration

Register the migration of a dialog whose fields were renamed at schema from_version + 1: old="new", or old=("new", convert) when the value changes too (level=("alpha", percent_complement)). Steps saved before open under the new names, silently. Returns the migration.

pymetrix.extension.report_progress

report(fraction: float | None = None, message: str = '') -> None

How far the running step is (0 to 1) and, optionally, what it is doing; stops it if Cancel was pressed.

pymetrix.extension.require

require(module: str) -> Any

Import a module, or explain which extra installs it.

pymetrix.extension.sniff_data_file

sniff(source: str, rows: int = 500) -> Sniff

Read the first rows rows of a data file and guess, for Load data, which column holds the periods (and their frequency) and which identifies the units (a column that, with the period, picks out one row). Nothing is loaded; unreadable files give an empty guess.

pymetrix.extension.translation_panel

translation_panel(spec: PanelSpec) -> Callable[[Any], Any]

The create(app) of an AppPanel that shows spec's translations: register("panels", AppPanel("EViews translation", translation_panel(spec), area="bottom")).

pymetrix.translation.allocate_name

allocate_name(source: str, base: str, what: str, taken: MutableMapping[str, str], reserved: Collection[str] = ()) -> tuple[str, str]

A Python variable for the program's object source, from base (already a Python identifier, as the front end makes it): base_v when base is reserved, then _2, _3 ... while the name is taken by something other than what (a description, "series x"). Records it in taken; returns the name and a note for the report when it is not base ('' otherwise).

pymetrix.translation.body_lines

body_lines(body: tuple[Any, ...], indent: int, returns: tuple[str, ...] = ()) -> list[str]

Ops ((line, op, file) entries) as lines of Python, without the program's lines as comments.

pymetrix.translation.error

error(reason: str) -> Untranslated

A statement that does not read, or names what the program has not made: raise it.

pymetrix.translation.flatten

flatten(outcomes: Iterable[Any]) -> list[Any]

Every outcome, a block's body, else branch and end included, in the program's order.

pymetrix.translation.left

left(reason: str) -> Untranslated

A statement left out, with the reason (left_reason adds pymetrix's equivalent): raise it.

pymetrix.translation.left_reason

left_reason(why: str, equivalent: str = '') -> str

A reason as the report gives it: why, then pymetrix's equivalent where there is one.

pymetrix.translation.literal

literal(value: Any) -> str

A value as Python, in the script.

pymetrix.translation.name_code

name_code(name: Any) -> str

A variable's name in the script: as it is, or globals()[f"eq_{c}"] for a name made as the program runs.

pymetrix.translation.op_code

op_code(op: Any, returns: tuple[str, ...] = ()) -> str

One op as Python: a statement, or a block's first line (for i in range(1, 4):).

pymetrix.translation.panel_class

panel_class() -> Any

The panel's Qt class, made on first use (Qt is not imported with pymetrix); an instance is made with (app, spec).

pymetrix.translation.pymetrix_imports

pymetrix_imports(text: str) -> list[str]

pymetrix's names the script's code uses (Equation(, Dataset.read), outside comments and strings: Dataset, Matrix and Sample first, then the rest in order.

pymetrix.translation.quote

quote(text: str) -> str

Text as a Python string literal, in double quotes.

pymetrix.translation.render

render(outcomes: list[Any], functions: list[tuple[Any, Def]], programs: dict[str, Any], top: list[str], comment: Callable[[int, str], str] = source_comment) -> tuple[str, dict[tuple[str, int], int]]

The script's body: top (the arguments), the functions ((outcome, Def)), then the program's outcomes; and the line of the body (from 0) that stands for each line of a program, by (file, line). programs are the programs read (Source), by file ('' the main one); comment(line, text) writes a statement as the comment above what it became.

pymetrix.translation.report_rows

report_rows(program: Any, outcomes: Iterable[Any], name: str, file: str = '', row: type = ReportRow) -> list[Any]

A row (row, a ReportRow class) per line with text of program (a Source; file '' for the main one, named name): a statement's first line with its outcome's status, Python and reason, its other lines as continuing it, a comment line as translated (the script keeps it); after an include outcome, the rows of the included program under its name.

pymetrix.translation.reserved_names

reserved_names(*extra: str) -> set[str]

The names a script's variables must not take: pymetrix's public names, Python's builtins, and extra.

pymetrix.translation.resolved

resolved(value: Any, env: Mapping[str, Any]) -> Any

A value with its variables' values put in: what steps mode passes to make_call.

pymetrix.translation.run_steps

run_steps(translation: Any, session: Any = None, attach: bool = True, *, args: Any = None, while_cap: int | None = None, runner: Any = None) -> dict[str, Any]

Translation.run: the translation's ops run in session, each step through runner (session.run when None).

pymetrix.translation.source_comment

source_comment(line: int, text: str) -> str

A statement of the program as the script's comment above what it became: # 5: series y = x.

pymetrix.translation.step_call

step_call(step: Step, env: Any, recorded_by: str = 'translation') -> Any

The Call of a step, with the program's values (env) put into its expressions; recorded_by is the steps' source (Translation.recorded_by).

pymetrix.translation.step_code

step_code(step: Step) -> str

A step as one line of the script: output = callee(arguments).

Results

pymetrix.commands.AnnotateFigure dataclass

AnnotateFigure(source: Annotated[str, Widget('text', help='the figure, or the result whose figure it is')], tab: Annotated[str, Widget('text', advanced=True, help='for a result: the tab its figure is on')] = 'Graph', what: Annotated[Literal['annotate', 'arrow', 'text', 'textbox', 'axvline', 'axhline', 'axvspan', 'axhspan'], Widget('choice', help='what to add')] = 'annotate', text: Annotated[str, Widget('text', show_if=('what', ('annotate', 'text', 'arrow', 'textbox')), help='the words (for an arrow: optional, at its tail)')] = '', panel: Annotated[str, Widget('text', help='the panel: 0 for the first, or its title')] = '0', x: Annotated[str, Widget('text', show_if=('what', ('annotate', 'text', 'textbox', 'arrow', 'axvline', 'axvspan')), help="the date (a period such as 2008Q3), or a number on an axis without dates; an arrow's head")] = '', y: Annotated[str, Widget('text', show_if=('what', ('annotate', 'text', 'textbox', 'arrow', 'axhline', 'axhspan')), help="the value; an arrow's head")] = '', from_x: Annotated[str, Widget('text', show_if=('what', ('arrow',)), help="the arrow's tail: a date or a number")] = '', from_y: Annotated[str, Widget('text', show_if=('what', ('arrow',)), help="the arrow's tail: a value")] = '', arrowstyle: Annotated[Literal['->', '-|>', '<->', 'fancy', 'wedge', '-'], Widget('choice', advanced=True, show_if=('what', ('arrow',)), help="the arrow's style")] = '->', connection: Annotated[Literal['straight', 'curved'], Widget('choice', advanced=True, show_if=('what', ('arrow',)), help='a straight line, or a curve')] = 'straight', curvature: Annotated[str, Widget('text', advanced=True, show_if=('connection', ('curved',)), help="how much it bends: matplotlib's rad, e.g. 0.3 (negative bends the other way)")] = '0.3', width: Annotated[str, Widget('text', advanced=True, show_if=('what', ('arrow',)), help="the line's width in points (empty: 1)")] = '', head: Annotated[str, Widget('text', advanced=True, show_if=('what', ('arrow',)), help="the head's size (matplotlib's mutation_scale; empty: 10)")] = '', boxstyle: Annotated[Literal['round', 'square', 'sawtooth', 'none'], Widget('choice', advanced=True, show_if=('what', ('textbox',)), help='the box around the words')] = 'round', facecolor: Annotated[str, Widget('text', advanced=True, show_if=('what', ('textbox',)), help="the box's fill colour (empty: white)")] = '', edgecolor: Annotated[str, Widget('text', advanced=True, show_if=('what', ('textbox',)), help="the box's edge colour (empty: grey)")] = '', pad: Annotated[str, Widget('text', advanced=True, show_if=('what', ('textbox',)), help='space inside the box, in font sizes (empty: 0.3)')] = '', ha: Annotated[Literal['left', 'center', 'right'], Widget('choice', advanced=True, show_if=('what', ('textbox',)), help='where the box sits across from the point')] = 'left', va: Annotated[Literal['bottom', 'center', 'top'], Widget('choice', advanced=True, show_if=('what', ('textbox',)), help='where the box sits up and down from the point')] = 'bottom', x2: Annotated[str, Widget('text', show_if=('what', ('axvspan',)), help="the band's last date")] = '', y2: Annotated[str, Widget('text', show_if=('what', ('axhspan',)), help="the band's upper value")] = '', text_x: Annotated[str, Widget('text', show_if=('what', ('annotate',)), advanced=True, help='where the words go: a date (empty: just above and right of the point)')] = '', text_y: Annotated[str, Widget('text', show_if=('what', ('annotate',)), advanced=True, help='where the words go: a value')] = '', arrow: Annotated[bool, Widget('checkbox', show_if=('what', ('annotate',)), help='an arrow from the words to the point')] = True, color: Annotated[str, Widget('text', help="a colour: a name, #RRGGBB, or C0 to C9 (empty: matplotlib's default)")] = '', fontsize: Annotated[str, Widget('text', advanced=True, show_if=('what', ('annotate', 'text', 'textbox', 'arrow')), help="the words' size in points")] = '', linestyle: Annotated[Literal['', 'solid', 'dashed', 'dashdot', 'dotted'], Widget('choice', show_if=('what', ('axvline', 'axhline')), help="the line's style")] = '', alpha: Annotated[str, Widget('text', show_if=('what', ('axvspan', 'axhspan')), help="the band's opacity, 0 to 1")] = '', name: Annotated[str, Widget('text', help='save as (empty: <source>_figure)')] = '')

Bases: Command

Add something to a figure, as matplotlib's Axes would: a note with an arrow (annotate), an arrow from one point to another (with optional words at its tail), text, a text box, a line at a date or a value (axvline, axhline), or a band between dates or values (axvspan, axhspan).

An arrow has a style (->, -|>, <->, fancy, wedge), a straight or curved connection (curvature: matplotlib's rad), a colour, a width and a head size. A text box has a box style (round, square, sawtooth, or none), fill and edge colours, padding, a font size and an alignment. Both are recorded as annotate or text with matplotlib's arrowprops and bbox, so they replay, appear in reports and in the figure's matplotlib code.

Positions are in the data's terms: dates as periods (2008Q3), values as numbers. In the app, click Add a note on the figure, then click where it goes: the panel, date and value are filled in. The step is recorded as the call, e.g. figure_of(fit).annotate('Lehman', xy=('2008Q3', 3.2), xytext=(15, 20), textcoords='offset points', arrowprops={'arrowstyle': '->'}), so it replays at any size.

at classmethod

at(source: str, figure: Any, tab: str = 'Graph', is_figure: bool = False, panel: int = 0, x: Any = '', y: Any = '', what: str = 'annotate', start: Any = None) -> AnnotateFigure

The dialog for a note at a clicked point: the panel, date (or number) and value filled in. what="arrow" with start, the tail's (x, y): an arrow from the first click to the second.

pymetrix.commands.ArrangeStyles dataclass

ArrangeStyles(source: Annotated[str, Widget('text', help='the figure, or the result whose figure it is')], tab: Annotated[str, Widget('text', advanced=True, help='for a result: the tab its figure is on')] = 'Graph', keep: Annotated[str, Widget('text', help='the steps to keep, in order, e.g. 0, 2, 1 (empty: none)')] = '', name: Annotated[str, Widget('text', help='save as (empty: <source>_figure)')] = '', steps: Annotated[int, Widget('hidden', help='how many style calls the figure had (-1: not known)')] = -1)

Bases: Command

Remove or reorder the style calls recorded on a figure. keep lists the steps to keep, in the order they should apply, by their numbers in the figure's list of recorded styles (fig.style_steps()): 0, 2, 1 swaps the last two of three; 0, 2 removes step 1. Recorded as figure_of(fit).without_style(1) or .reorder_style([0, 2, 1]).

pymetrix.commands.CallAxesMethod dataclass

CallAxesMethod(source: Annotated[str, Widget('text', help='the figure, or the result whose figure it is')], tab: Annotated[str, Widget('text', advanced=True, help='for a result: the tab its figure is on')] = 'Graph', method: Annotated[str, Widget('axesmethod', help='the Axes method')] = 'minorticks_on', arguments: Annotated[str, Widget('text', help="positional arguments, e.g. 'equal' (empty: none)")] = '', keywords: Annotated[str, Widget('text', help="keyword arguments, e.g. axis='y', style='sci' (empty: none)")] = '', panel: Annotated[str, Widget('text', help='the panel: 0 for the first, its title, or all')] = '0', side: Annotated[Literal['left', 'right'], Widget('choice', help='the left-hand axes, or the right-hand one')] = 'left', name: Annotated[str, Widget('text', help='save as (empty: <source>_figure)')] = '')

Bases: Command

Call any matplotlib Axes method that styles or annotates a panel, recorded as data: set_aspect, ticklabel_format, minorticks_on, axline, hlines... (methods that plot more data, clear things or need Python objects are not offered). Give its arguments as matplotlib takes them, in Python's notation: positional ('equal') and keyword (axis='y', style='sci', scilimits=(0, 0)). The step is recorded as figure_of(fit).call('ticklabel_format', axis='y', style='sci'), and matplotlib checks the call as it runs.

pymetrix.commands.ChangeStyle dataclass

ChangeStyle(source: Annotated[str, Widget('text', help='the figure, or the result whose figure it is')], tab: Annotated[str, Widget('text', advanced=True, help='for a result: the tab its figure is on')] = 'Graph', step: Annotated[str, Widget('stylestep', depends_on='source', help='the recorded style call to change')] = '', properties: Annotated[str, Widget('text', help="its keyword arguments, e.g. color='C2', linewidth=2")] = '', replace_all: Annotated[bool, Widget('checkbox', help='replace all its keyword arguments with these')] = False, name: Annotated[str, Widget('text', help='save as (empty: <source>_figure)')] = '')

Bases: Command

Change one recorded style call's keyword arguments: its colour, line style, label, position... The call keeps its series, panel and place in the order. Give matplotlib's keyword arguments in Python's notation (color='C2', linewidth=2); with replace all they replace the call's arguments, otherwise they change only those given (None removes one). Recorded as figure_of(fit).restyle(0, color='C2').

for_step classmethod

for_step(source: str, figure: Any, step: int, tab: str = 'Graph', is_figure: bool = False) -> ChangeStyle

The dialog on one step, its current keyword arguments filled in (all of them, so they replace the old).

pymetrix.commands.CommandRecord dataclass

CommandRecord(command: Command, code: str, ok: bool, error: str | None = None, created: datetime = now(), reads: dict[str, int] = dict(), writes: dict[str, int] = dict(), series: dict[str, frozenset[str]] = dict(), skipped: bool = False, seconds: float = 0.0, pruned: bool = False, deferred: bool = False, outputs: tuple[str, ...] = (), cautions: tuple[str, ...] = (), call: Any = None, random_generator: str = (lambda: _current_generator())(), proposed_by: str = '', note: str = '', inputs: dict[str, Any] = dict())

One step of the session: a dialog command or typed code, what it read and what it wrote.

reads and writes map object names to their versions (see Session.versions), so the session can tell when a result was computed from an object that has since changed.

typed property

typed: bool

Code typed in the Immediate or Code window and kept as code (not recognised as API calls).

code_step property

code_step: bool

Typed code: kept as code, or recorded as an API call (a Call step), rather than a dialog.

pymetrix.commands.CopyStyle dataclass

CopyStyle(source: Annotated[str, Widget('text', help='the figure to style, or the result whose figure it is')], tab: Annotated[str, Widget('text', advanced=True, help='for a result: the tab its figure is on')] = 'Graph', style_from: Annotated[str, Widget('text', help='the figure (or result) whose style to copy')] = '', from_tab: Annotated[str, Widget('text', advanced=True, help='for a result: the tab its figure is on')] = 'Graph', notes: Annotated[bool, Widget('checkbox', help='copy its notes, text, lines and bands too')] = False, name: Annotated[str, Widget('text', help='save as (empty: <source>_figure)')] = '')

Bases: Command

Style a figure as another one is: the other figure's recorded style calls are added after this one's own, where they apply. A series' call is copied if this figure draws that series; a panel's, if it has that panel (and the right-hand axis, for one on it). Notes, text, lines and bands mark the other chart's data, so they are copied only if asked. Recorded as figure_of(fit).with_style_of(figure_of(house_chart)).

pymetrix.commands.ExportReport dataclass

ExportReport(objects: Annotated[str, Widget('object', source='Reportable', multiple=True, show_if=('use_outline', (False,)), help='results to include, in order')], path: Annotated[str, Widget('savefile', source='Excel (*.xlsx);;Word (*.docx);;Web page (*.html);;Markdown (*.md)', help='the file to write: .xlsx, .docx, .html or .md')] = 'report.xlsx', title: Annotated[str, Widget('text', help="the heading at the top of the report (and the Word document's title)")] = 'Report', author: Annotated[str, Widget('text', help='the author shown under the title, with the date; empty = none')] = '', template: Annotated[str, Widget('named', source='report_templates', show_if=('use_outline', (False,)), empty='summary and graph', help='which views of each result; empty = summary and graph')] = '', theme: Annotated[str, Widget('named', advanced=True, source='themes', empty="the session's default", help="how figures look and the decimals in tables; empty = the session's default")] = '', start: Annotated[str, Widget('period', group='Dates in figures')] = '', end: Annotated[str, Widget('period', group='Dates in figures')] = '', all_sections: Annotated[bool, Widget('checkbox', advanced=True, show_if=('use_outline', (False,)), help="every tab of each result's window, not just its summary and graph")] = False, provenance: Annotated[bool, Widget('checkbox', advanced=True, help='add the appendix of data vintages and methods')] = True, plugin_notes: Annotated[bool, Widget('checkbox', advanced=True, help="add the plugins' notes on each result, such as the lab book's count of the specifications tried; they come from this session's record, so the recorded script does not write them again")] = False, use_outline: Annotated[bool, Widget('checkbox', help="the report outline (the Report panel's items, headings and text) instead of results")] = False, date: Annotated[str, Widget('text', advanced=True, help='the date printed under the title; empty = today')] = '', figure_width: Annotated[float, Widget('number', min=2.0, max=20.0, step=0.5, advanced=True, help='the width figures are drawn at, in inches (their height keeps their shape)')] = 6.0, outline: Annotated[str, Widget('hidden', help='the report outline, as JSON: taken from the Report panel when it opens this')] = '')

Bases: Command

Write results to a report: Excel (each table on its own sheet), Word, HTML or Markdown (in order).

Each result adds its summary and its graph, under a heading with its name; Sections all adds every tab of its window. A template chooses the views instead: estimation_summary (summary, graph, diagnostics), forecast_round (fan charts, paths, judgement, accuracy) or technical_appendix (everything). The theme sets how figures look and the decimals in tables; the sample limits the dates drawn in figures. An appendix lists where the numbers come from: data vintages, samples, methods and the pymetrix version. Plugins' notes (Advanced) add a line about each result from a plugin, such as the lab book's count of the specifications tried. Word reports need python-docx (pip install pymetrix[report]).

from_outline classmethod

from_outline(session: Session, **fields: Any) -> ExportReport

The dialog on the session's report outline (the Report panel's Export…).

pymetrix.commands.FieldSpec dataclass

FieldSpec(name: str, label: str, kind: str, default: Any, required: bool, choices: tuple[Any, ...] | None = None, source: str | None = None, help: str = '', type: Any = None, depends_on: str | None = None, multiple: bool = False, show_if: tuple[str, Any] | None = None, group: str = '', min: float | None = None, max: float | None = None, step: float | None = None, advanced: bool = False, exclude: tuple[str, ...] = (), empty: str = '', owner: str = '')

dynamic property

dynamic: bool

True when the UI fills the choices from the session (see Session.choices).

scientific property

scientific: bool

Small floats (tolerances) are typed as text such as 1e-10 rather than spun.

radio property

radio: bool

Short fixed choice lists show as radio buttons, longer ones as dropdowns.

display

display(choice: Any) -> str

How a fixed choice is shown in a form: "Constant and trend" for trend 'ct'; the value itself otherwise.

pymetrix.commands.FigureOptions dataclass

FigureOptions(source: Annotated[str, Widget('text', help='the figure, or the result whose figure it is')], tab: Annotated[str, Widget('text', advanced=True, help='for a result: the tab its figure is on')] = 'Graph', title: Annotated[str, Widget('text', help='the title (empty: none)')] = '', subtitle: Annotated[str, Widget('text', help='a line under the title')] = '', footnote: Annotated[str, Widget('text', help='a note under the figure, e.g. the source')] = '', shade: Annotated[str, Widget('text', help='periods to shade, e.g. 2008Q3:2009Q2=GFC, 2020Q1:2020Q2; nber or cepr for US or euro-area recessions; or a 0/1 series of the dataset below')] = '', events: Annotated[str, Widget('text', help='dates to mark with a labelled line, e.g. 2016Q2=Brexit vote')] = '', reference: Annotated[str, Widget('text', help='values to mark with a labelled line, e.g. 2=inflation target')] = '', line_labels: Annotated[bool, Widget('checkbox', help='name each line at its end, in its colour, instead of in a legend')] = False, log_scale: Annotated[bool, Widget('checkbox', help='a log scale for the values (positive series only)')] = False, lowest: Annotated[str, Widget('text', help='the lowest value shown (empty: automatic)')] = '', highest: Annotated[str, Widget('text', help='the highest value shown (empty: automatic)')] = '', data: Annotated[str, Widget('object', source='Dataset', advanced=True, help='the dataset whose 0/1 series Shade may name')] = 'data', name: Annotated[str, Widget('text', help='save as (empty: <source>_figure)')] = '', start: Annotated[str, Widget('period', advanced=True, group='Dates drawn')] = '', end: Annotated[str, Widget('period', advanced=True, group='Dates drawn')] = '', theme: Annotated[str, Widget('named', source='themes', advanced=True, empty="the session's default", help="how the figure looks; empty = the session's default")] = '', columns: Annotated[int | None, Widget('number', min=1, max=6, advanced=True, help='panels side by side; empty = as drawn')] = None, sharey: Annotated[bool, Widget('checkbox', advanced=True, help='one value scale for all panels')] = False, bar_labels: Annotated[bool, Widget('checkbox', advanced=True, help="each bar's value written on it")] = False, house: Annotated[bool, Widget('checkbox', advanced=True, help='drawn with the house style first, where one is set')] = True, split_values: Annotated[str, Widget('text', advanced=True, help='values to leave out, splitting the value axis in two, e.g. 6:12 for a spike that squashes the rest (empty: none)')] = '', split_dates: Annotated[str, Widget('text', advanced=True, help='periods to leave out, splitting the time axis in two, e.g. 1986Q1:2004Q4 (empty: none)')] = '')

Bases: Command

Change how a figure is drawn: its title, subtitle and footnote, shaded periods (such as recessions), labelled lines at dates and at values, and its value scale. The data are unchanged.

It works on any figure: one made by Plot series, or a result's own (an equation's Graph tab, a forecast's fan chart, impulse responses). The figure is kept as a new object, so the result itself is untouched; a figure in the workspace is changed in place.

for_figure classmethod

for_figure(source: str, figure: Any, tab: str = 'Graph', is_figure: bool = False) -> FigureOptions

The dialog filled in with figure's current options, to edit: a workspace figure (is_figure) in place, a result's as <result>_<tab>.

pymetrix.commands.MarkChange dataclass

MarkChange(source: Annotated[str, Widget('text', help='the figure, or the result whose figure it is')], tab: Annotated[str, Widget('text', advanced=True, help='for a result: the tab its figure is on')] = 'Graph', series: Annotated[str, Widget('text', help='the series (its name in the legend)')] = '', start: Annotated[str, Widget('text', help='the first point: a period such as 2019Q4 (a number on an axis without dates)')] = '', end: Annotated[str, Widget('text', help='the second point')] = '', show: Annotated[Literal['both', 'change', 'percent'], Widget('choice', help='what the label says')] = 'both', units: Annotated[Literal['auto', 'pp', '%', 'none'], Widget('choice', help="the change's units: auto is percentage points for a rate or a percentage")] = 'auto', annualise: Annotated[bool, Widget('checkbox', help='add the rate a year (compound, for the percent change)')] = False, style: Annotated[Literal['arrow', 'bracket'], Widget('choice', help='a double-headed arrow or a bracket')] = 'arrow', color: Annotated[str, Widget('text', help='a colour (empty: dark grey)')] = '', panel: Annotated[str, Widget('text', advanced=True, help='the panel: empty for wherever the series is drawn')] = '', name: Annotated[str, Widget('text', help='save as (empty: <source>_figure)')] = '')

Bases: Command

Mark the change in a series between two points: an arrow (or a bracket) from one to the other, labelled with the change, the percent change, or both, and optionally the rate a year. In the app, choose Mark a change on the figure and click two points of a series (each snaps to its nearest data point), or give the periods here.

The change is in percentage points (pp) where the panel's axis is a rate or a percentage, unless units say otherwise. The step is recorded as figure_of(x).change('u', '2019Q4', '2020Q2', show='both'): the values are read from the data each time the figure is drawn, so the label stays right when the data change.

at classmethod

at(source: str, figure: Any, tab: str = 'Graph', is_figure: bool = False, series: str = '', start: Any = '', end: Any = '') -> MarkChange

The dialog for two clicked points of series.

pymetrix.commands.SaveFigure dataclass

SaveFigure(source: Annotated[str, Widget('text', help='the figure, or the result whose figure it is')], tab: Annotated[str, Widget('text', advanced=True, help='for a result: the tab its figure is on')] = 'Graph', path: Annotated[str, Widget('savefile', source='PNG (*.png);;PDF (*.pdf);;SVG (*.svg);;EPS (*.eps)', help='the file to write; its extension sets the format')] = '', size: Annotated[Literal['as drawn', 'column', 'page', 'slide', 'half-a4', 'custom'], Widget('choice', help='column 89 mm, page 183 mm wide (journals), slide 16:9, half an A4 page')] = 'as drawn', width: Annotated[str, Widget('text', show_if=('size', ('custom',)), help='the width, e.g. 120mm, 12cm or 4.7in')] = '', height: Annotated[str, Widget('text', show_if=('size', ('custom',)), help="the height (empty: keep the figure's shape)")] = '', dpi: Annotated[int, Widget('number', min=50, max=1200, help='dots per inch, for PNG (300 for print)')] = 300, transparent: Annotated[bool, Widget('checkbox', help='no background')] = False, editable_text: Annotated[bool, Widget('checkbox', advanced=True, help='SVG: keep text as text, to edit')] = False)

Bases: Command

Save a figure for publication: as PNG, PDF, SVG or EPS (from the file's extension), at a size made for print or slides, at a resolution, with or without a background. PDF and EPS embed their fonts; SVG draws text as outlines unless it is kept editable. Text keeps its size in points. The file records what made it (pymetrix and matplotlib versions, the series, the style calls). Recorded as figure_of(fit).save('fit.pdf', size='column').

pymetrix.commands.Session

Session()

attach_course

attach_course(folder: Any) -> None

Save a folder of course material (notes, notebooks, slides) with this session's project.

of_type

of_type(type_names: str) -> list[str]

Names of objects whose type (or a base type) is one of the comma-separated names.

choices

choices(spec: FieldSpec, values: dict[str, Any], scoped: bool = True) -> list[str]

Options for a session-dependent form field; values holds the form's current entries. An optional single choice (default empty) starts with a blank, so a dropdown does not quietly pick the first option. A dataset's series are those of its working set, if it has one, unless scoped=False.

options_form

options_form(spec: FieldSpec, values: dict[str, Any]) -> list[FieldSpec]

Fields of an "options" sub-form: the settings of the extension chosen in field spec.depends_on (a test, method, variance, filter...), less those the main form sets itself.

cautions

cautions(names: Any) -> list[str]

Warnings about the named results: out of date, frozen while their inputs changed, or not computed.

proposing

proposing(command_cls: type, by: str) -> Iterator[None]

Mark the next command_cls step run inside the block as proposed by by (CommandRecord.proposed_by): an assistant's proposal, opened in its dialog for the user to run (extension API 1.9). Saved with the project, shown in History and noted in the script.

period_choices

period_choices(values: dict[str, Any]) -> list[str]

The periods of the dataset a form works on, for period fields: what their spinners step through.

sample_bounds

sample_bounds(values: dict[str, Any]) -> tuple[str, str] | None

The first and last periods of the active sample of the dataset a form works on (None without one): what empty start and end fields stand for.

run

run(cmd: Command) -> Any

Run a command and record it as a step (with the automatic recalculation after it, in Automatic mode). A dialog step can be undone (undo); typed code cannot, since it may change objects in place.

add

add(cmd: Command, deferred: bool = False, outputs: Any = None) -> Any

Add a step to the session. deferred=False (the default) runs it now, exactly as run does, and returns its result. deferred=True records it without running it, as Manual mode defers a slow step when a project is opened: the step is pending (pending()) until compute() (the app's Compute) runs it in its place; History lists it as not computed, the script marks it, and a saved project keeps it deferred. It returns None.

outputs names the objects the step will make, when they cannot be told from it: a call's output (a dialog's call too) or a dialog's name otherwise; for typed code, the names it assigns. A deferred step is checked as far as it can be without running it (its code, its span, and the objects it uses, unless it uses results of other pending steps), and can be undone. What it uses is told from the command (the objects its fields name, its call's refs, the names typed code reads) and recorded as its reads, as they are now: the steps that make them are not dead ends, and compute runs it against them as they are here, even when a later step makes one of them again.

undo_blocked

undo_blocked() -> str | None

Why the last step cannot be undone, or None if it can.

undo_changes

undo_changes() -> set[str]

The objects Undo would remove or replace (empty if it cannot undo).

undo_label

undo_label() -> str

The step Undo would take back, as its code's first line ("" if none).

undo

undo() -> CommandRecord

Take back the last dialog step: the objects as they were before it, and its record (with the recalculation after it) out of the history. Only while the objects are as the step left them; the last 20 steps.

redo_blocked

redo_blocked() -> str | None

Why the last step undone cannot be run again, or None if it can.

redo_label

redo_label() -> str

The step Redo would run again, as its code's first line ("" if none).

redo

redo() -> CommandRecord

Run the last step undone again, as it was recorded (with the recalculation after it): what Undo took back, in order, while the objects are as Undo left them. A new step clears what can be redone. Observers hear of it as a step, as of any step run.

refreshable

refreshable() -> list[str]

The datasets and models File → Refresh data… can read again: those a load step read from a file or a data service, and those an import step read from a model file.

refresh

refresh(*names: str) -> list[CommandRecord]

Read datasets again from their sources (all those refreshable lists, or the ones named): File → Refresh data…. A project keeps the data as it was read, so opening it gives the same numbers whatever the source holds by then; refreshing takes the source's current data (a load pinned to a vintage reads that vintage again). The same goes for a model imported from a file (a Dynare .mod and the files it includes, an IRIS .model): the project keeps the files as read, and refreshing the model reads them as they are now.

Each load step runs again, recorded as a new step, and so do the later steps that changed the dataset in place (series generated or added to it), in order. What was computed from the dataset is then out of date: Automatic mode recomputes it, Manual mode marks it. Typed code that changed the dataset is not run again: the refresh is refused, naming the step, so the change can be made again by hand after refreshing. Returns the steps run.

restore

restore(cmd: Command, objects: dict[str, Any], seconds: float = 0.0) -> CommandRecord

Record a step whose results are already known (from a project's results cache) without running it.

set_mode

set_mode(mode: str) -> None

"automatic": out-of-date results are recomputed after every step, in dependency order (frozen ones excepted); "manual": they are marked out of date until recompute() (the app's Recalculate).

freeze

freeze(*names: str) -> None

Keep these results as they are: never recomputed, even when their inputs change, until unfrozen.

add_to_report

add_to_report(source: str, tab: str | None = None, caption: str = '') -> dict[str, Any]

Put a result in the report outline: one of its tabs (a figure or a table), or, without tab, its summary and graph. Collecting is not a step: exporting the outline is (the Report panel's Export…).

set_working_set

set_working_set(dataset: str, spec: str | None) -> list[str]

Show only some of a dataset's series in the app: in every dialog's series lists, the spreadsheet and the dataset's window. spec is patterns ("gdp_*, cpi*, u") or the name of a selection; None or "" shows every series again. A view, not a step: commands still record the series they use by name, so scripts run the same. Returns the series it shows.

working_set

working_set(dataset: str) -> list[str] | None

The series a dataset's working set shows (None: no working set, every series).

unfreeze

unfreeze(*names: str) -> None

Let these results (all, without names) be recomputed again.

needed

needed() -> list[bool]

For each step of the history, whether the current objects depend on it. Typed code, steps that write nothing (exports, saved rounds) and deferred steps always count; pruned steps never do.

dead_ends

dead_ends() -> list[CommandRecord]

Steps nothing current depends on: results later replaced or deleted, and the steps only they used.

prune

prune() -> list[CommandRecord]

Remove the dead ends from the history (and so from the script and the saved project).

pending

pending() -> dict[str, CommandRecord]

Results not computed yet (deferred when the project was opened, or added with add(cmd, deferred=True)): name -> the step that makes it.

compute

compute(names: Any = None) -> list[CommandRecord]

Run deferred steps, in history order: all, or those that make (or lead to) the named results. Each runs against the objects it reads as they were at its place (CommandRecord.inputs), as if it had run there.

push

push() -> None

Copy the workspace objects into the code namespace (after a dialog command changed them).

pull

pull() -> None

Take objects created, replaced or deleted by typed code into the workspace.

begin_code

begin_code() -> dict[str, int]

Call before typed code runs elsewhere (the Immediate window); pass the result to end_code.

end_code

end_code(before: dict[str, int], code: str, ok: bool, error: str | None = None, source: str = 'immediate') -> CommandRecord

Record typed code that has already run in self.namespace.

run_code

run_code(code: str, source: str = 'script') -> Any

Run Python in the session's namespace and record it, as the Immediate window does.

resolved_failures

resolved_failures() -> dict[int, int]

Failed dialog steps that a later step of the same dialog on the same target ran successfully: the failed step's place in the history -> the place of the step that resolved it. They stay in the history (greyed) but are no longer problems; nothing else changes (failed steps are never saved or replayed). Undoing the successful step makes the failure count again.

producer

producer(name: str) -> CommandRecord | None

The step that made the current version of name (None for objects placed directly).

stale

stale(frozen: bool = False) -> dict[str, str]

Objects computed from inputs that have changed since: name -> reason. Frozen results count as up to date (so nothing is recomputed because of them); frozen=True lists instead the frozen results whose inputs have changed.

recompute

recompute(names: Any = None) -> list[CommandRecord]

Re-run, in history order, the steps that produced stale objects (all, or those named).

script

script() -> str

Python that reproduces the session's successful commands, importing any plugin classes it uses. Steps run with a random generator other than the default are preceded by set_random_generator(...).

pymetrix.commands.SetProperties dataclass

SetProperties(source: Annotated[str, Widget('text', help='the figure, or the result whose figure it is')], tab: Annotated[str, Widget('text', advanced=True, help='for a result: the tab its figure is on')] = 'Graph', part: Annotated[str, Widget('figurepart', depends_on='source', help='the series or panel whose properties to set')] = '', properties: Annotated[str, Widget('options', depends_on='part', source='figure-properties', help="matplotlib's properties for that part")] = '', name: Annotated[str, Widget('text', help='save as (empty: <source>_figure)')] = '')

Bases: Command

Set any style property matplotlib has for a part of a figure: a series' line, bars or band, or a panel's axes.

The properties are matplotlib's own, listed from its description of each artist (ArtistInspector), with its own note on their valid values; those holding the plotted data or positions are left out. Empty fields are left as they are. The step is recorded as the call that makes it, e.g. figure_of(fit).line('actual', drawstyle='steps-post', markevery=4), and matplotlib checks each value as it runs.

pymetrix.commands.StyleFigure dataclass

StyleFigure(source: Annotated[str, Widget('text', help='the figure, or the result whose figure it is')], tab: Annotated[str, Widget('text', advanced=True, help='for a result: the tab its figure is on')] = 'Graph', series: Annotated[str, Widget('layer', depends_on='source', group='Series', help='the series to style')] = '', color: Annotated[str, Widget('text', group='Series', help="a colour: a name (navy), #RRGGBB, or C0 to C9 (matplotlib's cycle)")] = '', linestyle: Annotated[Literal['', 'solid', 'dashed', 'dashdot', 'dotted'], Widget('choice', group='Series', help="the line's style")] = '', linewidth: Annotated[str, Widget('text', group='Series', help="the line's width in points")] = '', marker: Annotated[Literal['', 'none', 'o', 's', '^', 'D', 'x', '+', '.'], Widget('choice', group='Series', help='a marker at each point')] = '', markersize: Annotated[str, Widget('text', group='Series', help="the markers' size in points")] = '', alpha: Annotated[str, Widget('text', group='Series', help='opacity, 0 (invisible) to 1')] = '', panel: Annotated[str, Widget('text', group='Axes', help='the panel: 0 for the first, its title, or all')] = '0', side: Annotated[Literal['left', 'right'], Widget('choice', group='Axes', help='the left-hand axis, or the right-hand one')] = 'left', yscale: Annotated[Literal['', 'linear', 'log', 'symlog'], Widget('choice', group='Axes', help='the value scale')] = '', ymin: Annotated[str, Widget('text', group='Axes', help='the lowest value shown')] = '', ymax: Annotated[str, Widget('text', group='Axes', help='the highest value shown')] = '', xmin: Annotated[str, Widget('text', group='Axes', help='the first date shown, e.g. 2010Q1')] = '', xmax: Annotated[str, Widget('text', group='Axes', help='the last date shown')] = '', ylabel: Annotated[str, Widget('text', group='Axes', help="the value axis' label")] = '', xlabel: Annotated[str, Widget('text', group='Axes', help="the date axis' label")] = '', tick_format: Annotated[str, Widget('text', group='Axes', help="the value labels' format, e.g. {x:,.0f} or {x:.0%}")] = '', tick_size: Annotated[str, Widget('text', group='Axes', help="the tick labels' size in points")] = '', grid: Annotated[Literal['', 'on', 'off'], Widget('choice', group='Axes', help='grid lines')] = '', hide_spines: Annotated[str, Widget('text', group='Axes', help='sides of the frame to hide, e.g. top, right')] = '', legend_loc: Annotated[Literal['', 'best', 'upper left', 'upper right', 'lower left', 'lower right', 'upper center', 'lower center', 'center left', 'center right', 'center', 'none'], Widget('choice', group='Legend', help='where the legend goes (none: no legend)')] = '', legend_columns: Annotated[str, Widget('text', group='Legend', help='entries side by side')] = '', legend_frame: Annotated[Literal['', 'on', 'off'], Widget('choice', group='Legend', help='a frame around the legend')] = '', legend_size: Annotated[str, Widget('text', group='Legend', help="the legend's text size in points")] = '', width: Annotated[str, Widget('text', group='Layout', help="the figure's width in inches")] = '', height: Annotated[str, Widget('text', group='Layout', help="the figure's height in inches")] = '', name: Annotated[str, Widget('text', help='save as (empty: <source>_figure)')] = '')

Bases: Command

Style a figure in matplotlib's terms: a series' line (colour, line style, width, markers), a panel's axes (scale, limits, labels, tick format, grid, frame), the legend and the figure's size.

Empty fields leave things as they are. Each change is recorded as the matplotlib-style call that makes it, e.g. fig = figure_of(fit).line('actual', color='C3', linestyle='dashed').set(ax=0, yscale='log'), so it replays. Values are checked by matplotlib as the step runs: a colour or line style it does not know is reported here.

for_figure classmethod

for_figure(source: str, figure: Any, tab: str = 'Graph', is_figure: bool = False) -> StyleFigure

The dialog, opened on figure: a workspace figure is styled in place, a result's kept as <result>_<tab>.

pymetrix.extension.Translation dataclass

Translation(script: str, report: TranslationReport, program: str = '', ops: Sequence[Any] = (), functions: Sequence[Any] = (), objects: Mapping[str, Any] = dict(), arguments: Mapping[str, str] = dict(), sources: Mapping[str, str] = dict(), script_lines: Mapping[Any, int] = dict())

A program in another language translated: script, readable Python that uses pymetrix's public API; report, a row per line; and run(session), the same work as recorded steps. All three come from one representation (ops: (line, op, file) entries of the ops in pymetrix.translation.ir), so the script and the steps give equal objects.

functions are the program's functions ((line, Def, file)); objects what was given to the translation, put in the session before the steps run; arguments the program's parameters (name -> value: the script's first lines); sources the text of the program and each included one, by name; script_lines the script's line (from 1) of each (file, line) of a program.

A front end subclasses it to say what it is, in class attributes: language (the report's column), recorded_by (the steps' source, as a dialog's ID is for its steps), attachments (the key under which the script and the report are kept in the project) and while_cap; step_names() gives the names the steps' Python sees besides pymetrix's.

step_names

step_names() -> dict[str, Any]

Names the steps' Python (a condition, a scalar's code) sees besides pymetrix's public names: a module the script imports, say. None by default.

script_line

script_line(line: int, file: str | None = None) -> int | None

The script's line (from 1) of a program's line, or of the nearest one before it with a line of its own; None before the first.

run

run(session: Any = None, attach: bool = True, *, args: Any = None, while_cap: int | None = None, run: Any = None) -> dict[str, Any]

Run the translation as steps (steps mode) in session (a new Session when None): each Step a recorded call (make_call) and each Cmd a recorded command, so History and the session's script hold them as if typed or made in a dialog; loops, if blocks and functions run in Python; Code (scalars, strings, matrices) runs as Python, and the values it makes are returned (name -> value), with the session under "session". With attach, the readable script and the report are kept in the project (session.attachments[attachments]["<program>.py"] and "<program>.txt"). Stops at the first step that fails, raising its error with .line and .file.

args replaces the program's arguments (strings, or one string of words); while_cap is how many passes a while loop may make before it stops with an error (default: the class's); run runs each step instead of session.run (the app's AppInterface.run, which records it and lets it be undone). The objects given to the translation are put in the session when it has none of that name.

pymetrix.translation.ReportRow dataclass

ReportRow(line: int, status: str, source: str, python: str = '', reason: str = '', file: str = '')

One line of the program: its number (from 1), status (one of STATUSES), its text in the program's language (source), the Python it became (empty for a line left out, or a line that continues a statement), the reason, with pymetrix's equivalent where there is one, and file, the program (or included one) it is in.

pymetrix.translation.Text dataclass

Text(parts: tuple[Any, ...])

Text with scalars in it: parts are pieces of text and Var(name) for a Python variable's value.

code

code() -> str

The text as Python: a string literal, or an f-string where it holds variables.

value

value(env: Mapping[str, Any]) -> str

The text with each variable's value, as the f-string gives it.

Other names

pymetrix.commands.CommandError

Bases: PyMetrixError, ValueError

A dialog step whose fields do not validate.

pymetrix.commands.COMMANDS module-attribute

COMMANDS: dict[str, CommandInfo] = {}

pymetrix.disclosure.DEFAULT_MODE module-attribute

DEFAULT_MODE = 'off'

pymetrix.disclosure.MODES module-attribute

MODES = ('off', 'metadata_only', 'full_context', 'local_model')

pymetrix.extension.eviews_functions module-attribute

FUNCTIONS: dict[str, tuple[str, str]] = {'log': ('log(x)', 'the natural logarithm'), '@log': ('@log(x)', 'the natural logarithm'), 'exp': ('exp(x)', 'e to the power x'), '@exp': ('@exp(x)', 'e to the power x'), 'abs': ('abs(x)', 'the absolute value'), '@abs': ('@abs(x)', 'the absolute value'), 'sqr': ('sqr(x)', "the square root (EViews's sqr is the root, not the square)"), '@sqrt': ('@sqrt(x)', 'the square root'), '@inv': ('@inv(x)', '1/x'), 'd': ('d(x[, n[, s]])', 'n first differences (1 by default) and one of span s: d(x) = x - x(-1)'), 'dlog': ('dlog(x[, n[, s]])', 'd of log(x): dlog(x) = log(x) - log(x(-1))'), '@pch': ('@pch(x)', 'the change as a fraction, x/x(-1) - 1'), '@pc': ('@pc(x)', 'the change in percent, 100*@pch(x)'), '@pchy': ('@pchy(x)', "the change over a year as a fraction, x/x(-4) - 1 in quarterly data (the data's frequency)"), '@pcy': ('@pcy(x)', '100*@pchy(x)'), '@pcha': ('@pcha(x)', "the change annualised, (x/x(-1))^4 - 1 in quarterly data (the data's frequency)"), '@pca': ('@pca(x)', '100*@pcha(x)'), '@trend': ('@trend(base)', "the periods since base (1960q1, 60:1, ...): a series pymetrix makes from the data's dates (eviews_series); @trend alone counts from the data's first period"), '@elem': ('@elem(x, "2004q4")', "x's value at that date, a constant (of @trend: the number)"), '@seas': ('@seas(n)', "1 in the n-th period of the year, else 0 (a series from the data's dates)"), '@movav': ('@movav(x, n)', 'the average of x and the n - 1 periods before it'), '@movsum': ('@movsum(x, n)', 'the sum of x and the n - 1 periods before it'), '@movmax': ('@movmax(x, n)', 'the largest of x and the n - 1 periods before it'), '@movmin': ('@movmin(x, n)', 'the smallest of x and the n - 1 periods before it'), '@recode': ('@recode(a > b, a, b)', 'a where the condition holds, else b: read as max(a, b) (or min), its only form here'), '@cnorm': ('@cnorm(x)', 'the standard normal cumulative distribution function'), '@dnorm': ('@dnorm(x)', 'the standard normal density'), '@qnorm': ('@qnorm(p)', 'the standard normal quantile'), '@ctdist': ('@ctdist(x, v)', "Student's t cumulative distribution function"), '@dtdist': ('@dtdist(x, v)', "Student's t density"), '@qtdist': ('@qtdist(p, v)', "Student's t quantile"), '@cchisq': ('@cchisq(x, v)', 'the chi-squared cumulative distribution function'), '@dchisq': ('@dchisq(x, v)', 'the chi-squared density'), '@qchisq': ('@qchisq(p, v)', 'the chi-squared quantile'), '@cfdist': ('@cfdist(x, v1, v2)', 'the F cumulative distribution function'), '@dfdist': ('@dfdist(x, v1, v2)', 'the F density'), '@qfdist': ('@qfdist(p, v1, v2)', 'the F quantile'), '@log10': ('@log10(x)', 'the base-10 logarithm'), '@floor': ('@floor(x)', 'the largest whole number not above x'), '@ceiling': ('@ceiling(x)', 'the smallest whole number not below x'), '@round': ('@round(x)', 'x rounded to the nearest whole number, halves away from zero'), '@isna': ('@isna(x)', '1 where x is NA, else 0'), '@nan': ('@nan(x, v)', 'v where x is NA, else x'), '@iif': ('@iif(condition, a, b)', 'a where the condition holds, b where not (NA where the condition is NA)'), 'na': ('na', 'the missing value'), '@year': ('@year', 'the year of each observation (data only: refused in a model)'), '@quarter': ('@quarter', 'the quarter of each observation (data only: refused in a model)'), '@month': ('@month', "the month of each observation's first day (data only: refused in a model)"), '@day': ('@day', "the day of the month of each observation's first day (data only: refused in a model)"), '@obsnum': ('@obsnum', "the observation's number, from 1 (data only: refused in a model)"), '@obsid': ('@obsid', "the observation's number within its cross-section, from 1 (data only: refused in a model)"), 'nrnd': ('nrnd', 'a standard normal random draw for each observation (data only, seeded: refused in a model)'), '@nrnd': ('@nrnd', 'as nrnd'), '@rnorm': ('@rnorm', 'as nrnd'), 'rnd': ('rnd', 'a uniform random draw on (0, 1) for each observation (data only, seeded: refused in a model)'), '@rnd': ('@rnd', 'as rnd'), '@runif': ('@runif(a, b)', 'a uniform random draw on (a, b) for each observation (data only)'), '@cumsum': ('@cumsum(x)', 'the sum of x up to each observation, NAs skipped (data only)'), '@sumsby': ('@sumsby(x, g)', 'the sum of x over the observations with the same value of the series g (data only)'), '@meansby': ('@meansby(x, g)', 'the mean of x over the observations with the same value of g (data only)'), '@minsby': ('@minsby(x, g)', 'the smallest x among the observations with the same value of g (data only)'), '@maxsby': ('@maxsby(x, g)', 'the largest x among the observations with the same value of g (data only)')}

pymetrix.extension.STABLE module-attribute

STABLE = ('pymetrix', 'pymetrix.extension', 'pymetrix.errors', 'pymetrix.data', 'pymetrix.output', 'pymetrix.figures', 'pymetrix.estimation', 'pymetrix.statespace', 'pymetrix.metadata', 'pymetrix.commands', 'pymetrix.translation', 'pymetrix.disclosure')

pymetrix.translation.COLOURS module-attribute

COLOURS = {'translated': (46, 160, 67, 55), 'translated with a note': (31, 111, 235, 60), 'left out': (191, 135, 0, 75), 'error': (207, 34, 46, 85), 'failed': (207, 34, 46, 150)}

pymetrix.translation.ERROR module-attribute

ERROR = 'error'

pymetrix.translation.LEFT module-attribute

LEFT = 'left out'

pymetrix.translation.NOTE module-attribute

NOTE = 'translated with a note'

pymetrix.translation.STATUSES module-attribute

STATUSES = (TRANSLATED, NOTE, LEFT, ERROR)

pymetrix.translation.StepFailed

StepFailed(message: str, line: int, file: str)

Bases: PyMetrixError

A step that failed in steps mode: line and file (an included program's name, or '') say where.

pymetrix.translation.TRANSLATED module-attribute

TRANSLATED = 'translated'

pymetrix.translation.Untranslated

Untranslated(status: str, reason: str)

Bases: PyMetrixError

A statement that does not translate: its status (left out or error) and the reason.

pymetrix.translation.WHILE_CAP module-attribute

WHILE_CAP = 10000