Machine learning¶
The classes and functions of the row "Machine learning" of Analytical tools, with what calls return (the results and their methods: forecasts, impulse responses, tests). Import them from pymetrix (from pymetrix import ...) unless a heading names another module. Parameters and return types are in each signature; the text says what each does.
Help topics: Double/debiased machine learning, Causal forests, Conformal prediction intervals, Principal components and factor analysis, K-means cluster analysis, Surveillance heatmaps, SHAP values, The forecast workflow.
How do I: Make a surveillance heatmap.
Classes¶
Bagging
dataclass
¶
Bagging(critical: Annotated[float, Widget('number', min=0, max=10, step=0.1, help="the pretest's critical |t| (1.96: 5% two-sided)")] = 1.96, reps: Annotated[int, Widget('number', min=10, max=10000, advanced=True, help='bootstrap samples averaged; more reduce the simulation noise in the coefficients')] = 200, block: Annotated[int, Widget('number', min=0, max=100, advanced=True, help='block length of the moving-block bootstrap; 0 = n^(1/3)')] = 0, seed: Annotated[int, Widget('number', min=0, max=2 ** 31 - 1, advanced=True, help='seed of the bootstrap draws: the same seed gives the same coefficients')] = 0)
Bootstrap aggregation of a pretest (Inoue and Kilian 2008), averaging the coefficients over bootstrap samples.
In each moving-block bootstrap sample, keep the regressors whose t-statistic exceeds critical, re-estimate
with them, and average the coefficients (zero when dropped).
A pretest alone (keep only the significant regressors) makes the forecast jump whenever a t-statistic crosses the critical value; averaging the decision over bootstrap samples smooths it and lowers the forecast variance, most usefully when many predictors are individually weak. The moving blocks keep the serial dependence of time series within each sample. The averaged coefficients are a forecasting rule with no standard errors; the notes give how often each regressor was kept.
ElasticNet
dataclass
¶
ElasticNet(alpha: Annotated[float, Widget('number', min=0, max=1000000000.0, help='the penalty (on standardized regressors); 0 = choose by cross-validation')] = 0.0, l1_ratio: Annotated[float, Widget('number', min=0.01, max=1.0, step=0.1, help="the lasso's share of the penalty")] = 0.5, folds: Annotated[int, _FOLDS] = 5, backend_options: Annotated[BackendOptions, Widget('', advanced=True, help='other scikit-learn arguments of the estimator')] = dict())
The elastic net: a mix of the lasso's and ridge's penalties (l1_ratio 1 is the lasso, near 0 ridge).
Shrinkage trades a little bias for less variance, which pays off in forecasting with many correlated or weak
predictors. The coefficients are biased towards zero by design and have no standard errors, so read them as a
forecasting rule, not as effects. The penalty matters most: left at 0 it is chosen by expanding-window
cross-validation, whose path is in fit.extra["cv_path"]; the notes give the penalty used and how many
coefficients are nonzero. The ridge part keeps groups of correlated predictors together where the lasso would
pick one; only the penalty is cross-validated, so l1_ratio is yours to set.
FactorModel
dataclass
¶
FactorModel(variables: Sequence[str], factors: int, dynamics: int = 0, rotation: Literal['none', 'varimax', 'promax'] = 'none')
Maximum-likelihood factor analysis: each series is a combination of factors common factors plus a part of
its own (its uniqueness); rotation makes the loadings easier to read (none, varimax, promax).
dynamics above 0 (factors following a VAR) is the dynamic factor model: use pymetrix.nowcast.DynamicFactor.
fit
¶
fit(data: Any, span: Any = None, method: Any = None) -> FittedFactorModel
The factor model on the periods (or rows) of span where every series is observed.
GradientBoosting
dataclass
¶
GradientBoosting(trees: Annotated[int, Widget('number', min=10, max=5000, help='the number of boosting rounds')] = 300, learning_rate: Annotated[float, Widget('number', min=0.001, max=1.0, step=0.01, help='the shrinkage of each tree (smaller: slower, smoother)')] = 0.05, depth: Annotated[int, Widget('number', min=1, max=10, help='the depth of each tree (1: additive in the regressors)')] = 2, subsample: Annotated[float, Widget('number', min=0.1, max=1.0, step=0.1, advanced=True, help='the share of observations each tree sees')] = 0.8, folds: Annotated[int, _FOLDS] = 5, seed: Annotated[int, Widget('number', min=0, max=2 ** 31 - 1, advanced=True, help='seed of the random draws: the same seed gives the same fit')] = 0, loss: Annotated[Literal['squared_error', 'absolute_error', 'huber', 'quantile'], Widget('choice', help="the loss each tree reduces: squared error, absolute error, Huber, or a quantile's check loss")] = 'squared_error', quantile: Annotated[float, Widget('number', min=0.01, max=0.99, step=0.05, advanced=True, help="the quantile (loss quantile), or Huber's quantile of the errors (loss huber)")] = 0.9, min_leaf: Annotated[int, Widget('number', min=1, max=100, advanced=True, help='the fewest observations in a leaf')] = 1, min_split: Annotated[int, Widget('number', min=2, max=200, advanced=True, help='the fewest observations a node needs to be split')] = 2, max_features: Annotated[float | None, Widget('number', min=0.1, max=1.0, step=0.1, advanced=True, help='the share of regressors tried at each split; empty = all')] = None, stop_after: Annotated[int | None, Widget('number', min=1, max=1000, advanced=True, help='stop when this many rounds do not improve the held-out score; empty = no early stopping')] = None, held_out: Annotated[float, Widget('number', min=0.05, max=0.5, step=0.05, advanced=True, help='the share held out to decide early stopping')] = 0.1, pruning: Annotated[float, Widget('number', min=0, max=1000000.0, step=0.001, advanced=True, help='cost-complexity pruning (ccp_alpha); 0 = none')] = 0.0, backend_options: Annotated[BackendOptions, Widget('', advanced=True, help='other scikit-learn arguments of the estimator')] = dict())
Boosted regression trees: small trees fitted one after another to the errors left by the earlier ones, each scaled by the learning rate.
Unlike a forest, boosting can overfit as rounds are added: the number of trees and the learning rate work together
(a smaller rate needs more trees), and early stopping can choose the rounds. Depth sets the order of
interactions. Like any tree method it extrapolates poorly: forecasts flatten outside the range of the sample.
Flexible learners can fit the sample almost perfectly, so judge them by the cross-validated RMSE and R-squared
in the summary (expanding windows, each tested on later periods), not the in-sample fit; the cross-validated
RMSE is also the forecast standard error. The settings are not tuned automatically: compare the cross-validated
error across them. There are no coefficients; fit.importance() shows how much the fit relies on each
regressor, not a causal effect.
Lasso
dataclass
¶
Lasso(alpha: Annotated[float, Widget('number', min=0, max=1000000000.0, help='the penalty (on standardized regressors); 0 = choose by cross-validation')] = 0.0, folds: Annotated[int, _FOLDS] = 5, backend_options: Annotated[BackendOptions, Widget('', advanced=True, help='other scikit-learn arguments of the estimator')] = dict())
The lasso: least squares with a penalty on the sum of absolute coefficients, which sets some exactly to zero (selection).
Shrinkage trades a little bias for less variance, which pays off in forecasting with many correlated or weak
predictors. The coefficients are biased towards zero by design and have no standard errors, so read them as a
forecasting rule, not as effects. The penalty matters most: left at 0 it is chosen by expanding-window
cross-validation, whose path is in fit.extra["cv_path"]; the notes give the penalty used and how many
coefficients are nonzero. Among highly correlated predictors the lasso tends to keep one and drop the rest,
somewhat arbitrarily, so which regressors survive should not be read as evidence of which matter.
LightGBM
dataclass
¶
LightGBM(trees: Annotated[int, Widget('number', min=10, max=10000, help='the number of boosting rounds')] = 300, learning_rate: Annotated[float, Widget('number', min=0.001, max=1.0, step=0.01, help='the shrinkage of each tree (smaller: slower, smoother)')] = 0.05, leaves: Annotated[int, Widget('number', min=2, max=1024, help='the most leaves in a tree (its size)')] = 15, min_leaf: Annotated[int, Widget('number', min=1, max=500, help='the fewest observations in a leaf (larger: smoother)')] = 10, subsample: Annotated[float, Widget('number', min=0.1, max=1.0, step=0.1, advanced=True, help='the share of observations each tree sees')] = 0.8, folds: Annotated[int, _FOLDS] = 5, seed: Annotated[int, _SEED] = 0, loss: Annotated[Literal['squared_error', 'absolute_error', 'quantile'], _LOSS] = 'squared_error', quantile: Annotated[float, _QUANTILE] = 0.9, max_features: Annotated[float, Widget('number', min=0.1, max=1.0, step=0.1, advanced=True, help='the share of regressors each tree may use')] = 1.0, depth: Annotated[int | None, Widget('number', min=1, max=64, advanced=True, help='the deepest a tree grows; empty = no limit (leaves set the size)')] = None, l1: Annotated[float, Widget('number', min=0, max=1000000.0, step=0.1, advanced=True, help='L1 penalty on the leaf values')] = 0.0, l2: Annotated[float, Widget('number', min=0, max=1000000.0, step=0.1, advanced=True, help='L2 penalty on the leaf values')] = 0.0, min_gain: Annotated[float, Widget('number', min=0, max=1000000.0, step=0.01, advanced=True, help='the smallest fall in the loss that a split must give')] = 0.0, backend_options: Annotated[BackendOptions, _OPTIONS] = dict())
Gradient-boosted trees from LightGBM: trees grown leaf by leaf on binned regressors, each fitted to the errors left by the earlier ones.
Where scikit-learn's boosted trees grow each tree level by level to a fixed depth, LightGBM splits whichever
leaf reduces the loss most, so the number of leaves, not the depth, sets a tree's size; the fewest observations
in a leaf keeps it from chasing single periods, which matters in short macroeconomic samples. As with any
boosting, the number of trees and the learning rate work together (a smaller rate needs more trees), and the
forecasts flatten outside the range of the sample. Judge the fit by the cross-validated RMSE and R-squared in the
summary (expanding windows, each tested on later periods), not the in-sample fit; the cross-validated RMSE is also
the forecast standard error. The settings are not tuned automatically. Loss quantile fits a conditional quantile,
which conformalised quantile regression uses. The fit runs on one thread in LightGBM's deterministic mode, so the
same seed gives the same trees. There are no coefficients; fit.importance() and fit.shap() show how much
the fit relies on each regressor, not a causal effect.
estimator
¶
The library's estimator with these settings (and pymetrix's fixed ones), unfitted: a classifier (for a
propensity score, without the loss) or a regressor; seed replaces the seed (double ML's cross-fitting).
NearestNeighbours
dataclass
¶
NearestNeighbours(k: Annotated[int, Widget('number', min=1, max=200, help='the number of neighbours averaged')] = 10, distance_weighted: Annotated[bool, Widget('checkbox', help='weight closer neighbours more')] = False, folds: Annotated[int, _FOLDS] = 5, power: Annotated[float, Widget('number', min=1, max=10, step=1, advanced=True, help="the Minkowski distance's power: 1 city-block, 2 straight-line (Euclidean)")] = 2.0, backend_options: Annotated[BackendOptions, Widget('', advanced=True, help='other scikit-learn arguments of the estimator')] = dict())
Nearest neighbours: the average of the outcomes in the k most similar periods (a local, kernel-like regression).
k sets the bias-variance trade-off: few neighbours follow the data closely and are noisy, many are smooth but
blur local features. With many regressors no period is truly near another (the curse of dimensionality), so keep
the regressors few. Forecasts are averages of past outcomes and cannot extrapolate. Flexible learners can fit
the sample almost perfectly, so judge them by the cross-validated RMSE and R-squared in the summary (expanding
windows, each tested on later periods), not the in-sample fit; the cross-validated RMSE is also the forecast
standard error. The settings are not tuned automatically: compare the cross-validated error across them. There
are no coefficients; fit.importance() shows how much the fit relies on each regressor, not a causal effect.
NeuralNetwork
dataclass
¶
NeuralNetwork(hidden: Annotated[tuple[int, ...], Widget('text', help='units in each hidden layer, e.g. 8 or 16, 8')] = (8,), penalty: Annotated[float, Widget('number', min=0, max=100, step=0.001, help='weight decay (L2 penalty on the weights)')] = 0.001, folds: Annotated[int, _FOLDS] = 5, seed: Annotated[int, Widget('number', min=0, max=2 ** 31 - 1, advanced=True, help='seed of the random draws: the same seed gives the same fit')] = 0, activation: Annotated[Literal['relu', 'tanh', 'logistic', 'identity'], Widget('choice', help="the hidden units' activation: rectified linear, tanh, logistic, or none (identity)")] = 'relu', solver: Annotated[Literal['adam', 'lbfgs', 'sgd'], Widget('choice', advanced=True, help='the optimiser: Adam, L-BFGS (often best on small samples), stochastic gradient descent')] = 'adam', learning_rate: Annotated[float, Widget('number', min=1e-06, max=1.0, step=0.0005, advanced=True, help='the initial learning rate (adam, sgd)')] = 0.001, batch: Annotated[int | None, Widget('number', min=1, max=100000, advanced=True, help='observations in each minibatch (adam, sgd); empty = automatic')] = None, max_iter: Annotated[int, Widget('number', min=10, max=1000000, advanced=True, help='the most passes (epochs) or iterations')] = 5000, early_stopping: Annotated[bool, Widget('checkbox', advanced=True, help='stop when a held-out 10% stops improving (adam, sgd)')] = False, backend_options: Annotated[BackendOptions, Widget('', advanced=True, help='other scikit-learn arguments of the estimator')] = dict())
A feed-forward neural network (one or more hidden layers): a flexible sieve approximation, on standardized regressors.
With the few hundred observations of most macroeconomic series a network overfits easily: keep the hidden layers
small and use the penalty. The fit depends on the random starting weights, so try other seeds and check that the
cross-validated error is stable. Flexible learners can fit the sample almost perfectly, so judge them by the
cross-validated RMSE and R-squared in the summary (expanding windows, each tested on later periods), not the
in-sample fit; the cross-validated RMSE is also the forecast standard error. The settings are not tuned
automatically: compare the cross-validated error across them. There are no coefficients; fit.importance()
shows how much the fit relies on each regressor, not a causal effect.
PCA
dataclass
¶
Principal components of a set of series: the weighted averages that explain most of their variance.
n keeps the first n components (all by default); standardize (the default) works with the series scaled
to unit variance, so that each counts equally whatever its units.
RandomForest
dataclass
¶
RandomForest(trees: Annotated[int, Widget('number', min=10, max=5000, help='the number of trees')] = 500, min_leaf: Annotated[int, Widget('number', min=1, max=100, help='the fewest observations in a leaf (larger: smoother)')] = 5, max_features: Annotated[float, Widget('number', min=0.1, max=1.0, step=0.1, advanced=True, help='the share of regressors tried at each split')] = 0.5, folds: Annotated[int, _FOLDS] = 5, seed: Annotated[int, Widget('number', min=0, max=2 ** 31 - 1, advanced=True, help='seed of the random draws: the same seed gives the same fit')] = 0, max_depth: Annotated[int | None, Widget('number', min=1, max=100, advanced=True, help='the deepest a tree grows; empty = no limit')] = None, min_split: Annotated[int, Widget('number', min=2, max=200, advanced=True, help='the fewest observations a node needs to be split')] = 2, criterion: Annotated[Literal['squared_error', 'absolute_error', 'friedman_mse', 'poisson'], Widget('choice', advanced=True, help="the split criterion: squared error, absolute error, Friedman's MSE, Poisson deviance")] = 'squared_error', bootstrap: Annotated[bool, Widget('checkbox', advanced=True, help='grow each tree on a bootstrap sample (unticked: on all observations)')] = True, max_samples: Annotated[float | None, Widget('number', min=0.05, max=1.0, step=0.05, advanced=True, help='the share of observations in each bootstrap sample; empty = all')] = None, pruning: Annotated[float, Widget('number', min=0, max=1000000.0, step=0.001, advanced=True, help='cost-complexity pruning (ccp_alpha); 0 = none')] = 0.0, backend_options: Annotated[BackendOptions, Widget('', advanced=True, help='other scikit-learn arguments of the estimator')] = dict())
A random forest: the average of many regression trees, each grown on a bootstrap sample with random subsets of regressors.
Averaging decorrelated trees captures nonlinearities and interactions with little tuning: more trees only reduce
noise, while larger leaves and fewer regressors per split smooth the fit. Trees cannot extrapolate: forecasts
stay within the range of outcomes seen in the sample, which matters for trending series. Flexible learners can
fit the sample almost perfectly, so judge them by the cross-validated RMSE and R-squared in the summary
(expanding windows, each tested on later periods), not the in-sample fit; the cross-validated RMSE is also the
forecast standard error. The settings are not tuned automatically: compare the cross-validated error across
them. There are no coefficients; fit.importance() shows how much the fit relies on each regressor, not a
causal effect.
Ridge
dataclass
¶
Ridge(alpha: Annotated[float, Widget('number', min=0, max=1000000000.0, help='the penalty (on standardized regressors); 0 = choose by cross-validation')] = 0.0, folds: Annotated[int, _FOLDS] = 5, backend_options: Annotated[BackendOptions, Widget('', advanced=True, help='other scikit-learn arguments of the estimator')] = dict())
Ridge regression: least squares with a penalty on the sum of squared coefficients, shrinking them all toward zero.
Shrinkage trades a little bias for less variance, which pays off in forecasting with many correlated or weak
predictors. The coefficients are biased towards zero by design and have no standard errors, so read them as a
forecasting rule, not as effects. The penalty matters most: left at 0 it is chosen by expanding-window
cross-validation, whose path is in fit.extra["cv_path"]; the notes give the penalty used. Ridge keeps every
regressor and spreads weight over correlated ones, so it suits many predictors that each carry a little
information.
XGBoost
dataclass
¶
XGBoost(trees: Annotated[int, Widget('number', min=10, max=10000, help='the number of boosting rounds')] = 300, learning_rate: Annotated[float, Widget('number', min=0.001, max=1.0, step=0.01, help='the shrinkage of each tree (smaller: slower, smoother)')] = 0.05, depth: Annotated[int, Widget('number', min=1, max=20, help='the depth of each tree (1: additive in the regressors)')] = 2, subsample: Annotated[float, Widget('number', min=0.1, max=1.0, step=0.1, advanced=True, help='the share of observations each tree sees')] = 0.8, folds: Annotated[int, _FOLDS] = 5, seed: Annotated[int, _SEED] = 0, loss: Annotated[Literal['squared_error', 'absolute_error', 'quantile'], _LOSS] = 'squared_error', quantile: Annotated[float, _QUANTILE] = 0.9, max_features: Annotated[float, Widget('number', min=0.1, max=1.0, step=0.1, advanced=True, help='the share of regressors each tree may use')] = 1.0, min_child_weight: Annotated[float, Widget('number', min=0, max=1000000.0, step=1, advanced=True, help='the smallest total weight (with squared error, observations) in a leaf')] = 1.0, l1: Annotated[float, Widget('number', min=0, max=1000000.0, step=0.1, advanced=True, help='L1 penalty on the leaf values')] = 0.0, l2: Annotated[float, Widget('number', min=0, max=1000000.0, step=0.1, advanced=True, help='L2 penalty on the leaf values')] = 1.0, min_gain: Annotated[float, Widget('number', min=0, max=1000000.0, step=0.01, advanced=True, help='the smallest fall in the loss that a split must give')] = 0.0, backend_options: Annotated[BackendOptions, _OPTIONS] = dict())
Gradient-boosted trees from XGBoost: trees fitted one after another to the errors left by the earlier ones, with penalties on the leaf values.
XGBoost adds L1 and L2 penalties on the leaves' values and a smallest gain for a split to the boosting of
scikit-learn's boosted trees, which steadies the fit when the sample is short. Depth sets the order of
interactions (2: pairs of regressors), and the number of trees and the learning rate work together (a smaller
rate needs more trees); the forecasts flatten outside the range of the sample. Judge the fit by the
cross-validated RMSE and R-squared in the summary (expanding windows, each tested on later periods), not the
in-sample fit; the cross-validated RMSE is also the forecast standard error. The settings are not tuned
automatically. Loss quantile fits a conditional quantile, which conformalised quantile regression uses. The fit
runs on one thread with the histogram method, so the same seed gives the same trees. There are no coefficients;
fit.importance() and fit.shap() show how much the fit relies on each regressor, not a causal effect.
estimator
¶
The library's estimator with these settings (and pymetrix's fixed ones), unfitted: a classifier (for a
propensity score, without the loss) or a regressor; seed replaces the seed (double ML's cross-fitting).
Functions¶
causal_forest
¶
causal_forest(data: Dataset, outcome: str, treatment: str, controls: Sequence[str], confounders: Sequence[str] = (), trees: int = 2000, min_leaf: int = 5, max_features: int | None = None, sample_fraction: float = 0.5, group_size: int = 2, learner: Any = 'forest', learner_treatment: Any = None, folds: int = 5, cluster: str | None = None, trim: float = 0.01, alpha: float = 0.05, seed: int = 0) -> FittedCausalForest
A causal forest of the effect of treatment on outcome, heterogeneous in controls (X, the effect
modifiers, which also confound), with confounders (W) that confound without modifying it. trees honest
trees in bags of group_size (for the variance), each on a sample_fraction subsample split in halves to grow
and to estimate, leaves of at least min_leaf, max_features variables tried per split (default GRF's
min(sqrt(p) + 20, p)); the outcome's and treatment's conditional means by learner (learner_treatment) with
folds-fold cross-fitting; cluster keeps clusters whole in folds and half-samples and clusters the errors.
conformal
¶
conformal(fit: Any, data: Dataset, span: tuple[Any, Any], alpha: float = 0.1, method: Literal['split', 'cqr', 'aci'] = 'split', calibration: float = 0.25, gamma: float = 0.005, window: int = 0) -> ConformalIntervals
Conformal (1 - alpha) prediction intervals over span for an estimated equation (a learner, shrinkage or least
squares): method "split" (absolute errors), "cqr" (conformalised quantile regression, for boosted
trees, LightGBM and XGBoost) or "aci" (adaptive conformal inference, for series that are not exchangeable,
with step gamma and the latest window scores, 0: as many as the calibration periods). The last
calibration share of the fit's sample calibrates a model estimated again on the periods before it.
dml_sensitivity
¶
dml_sensitivity(fit: FittedDoubleML, cf_y: float = 0.03, cf_d: float = 0.03, rho: float = 1.0, alpha: float = 0.05, null: float = 0.0, benchmark: Sequence[str] | None = None, data: Dataset | None = None) -> DoubleMLSensitivity
Sensitivity of a double ML estimate (partially linear regression, or the interactive model's ATE or ATT) to an
omitted confounder (Chernozhukov, Cinelli, Newey, Sharma and Syrgkanis 2022), as DoubleML's
sensitivity_analysis: the bounds on theta when the confounder explains a share cf_y of the outcome's
residual variation and cf_d of the Riesz representer's, correlated rho, their one-sided confidence bounds
at 1 - alpha and the robustness values for null. benchmark: observed controls to judge the strengths by,
the model refitted on data without each (comma-separated names in one string drop together), with the same
folds and learners (DoubleML's sensitivity_benchmark).
double_ml
¶
double_ml(data: Dataset, outcome: str, treatment: str, controls: Sequence[str], model: Literal['plr', 'pliv', 'irm'] = 'plr', instrument: str | None = None, score: Literal['ATE', 'ATTE', 'partialling out', 'IV-type'] = 'ATE', learner: Any = 'ols', learner_treatment: Any = None, folds: int = 5, repeats: int = 1, cluster: str | Sequence[str] | None = None, trim: float = 0.01, seed: int = 0) -> FittedDoubleML
Double/debiased machine learning of the effect of treatment on outcome given controls: model
"plr" (partially linear), "pliv" (partially linear IV, with instrument) or "irm" (interactive, a
0/1 treatment). score: for the interactive model "ATE" or "ATTE"; for the partially linear models
"partialling out" (the default) or "IV-type". learner learns the outcome's nuisance functions and
learner_treatment (default: the same) the treatment's and instrument's; folds for cross-fitting (1: none),
repeats sample splits aggregated by the median; cluster a series or axis for clustered errors and folds, or
two of them for two-way clustering.
kmeans
¶
kmeans(data: Any, series: Sequence[str], k: int = 3, standardize: bool = True, starts: int = 10, seed: int = 0, max_iter: int = 300, by: Literal['observations', 'series'] = 'observations', span: tuple[Any, Any] | None = None, missing: Literal['drop', 'refuse'] = 'drop') -> KMeansClusters
K-means clusters of the dates (by="observations": regimes) or of the series (by their standardised
paths) of data over span: k clusters, the best of starts k-means++ starts drawn with seed,
each iterated at most max_iter rounds. See pymetrix.clusters.
kmeans_k
¶
kmeans_k(data: Any, series: Sequence[str], k: Sequence[int] = (2, 3, 4, 5, 6, 7, 8), standardize: bool = True, starts: int = 10, seed: int = 0, max_iter: int = 300, by: Literal['observations', 'series'] = 'observations', span: tuple[Any, Any] | None = None, missing: Literal['drop', 'refuse'] = 'drop') -> KMeansChoice
K-means for each number of clusters in k: the within-cluster sum of squares (the elbow) and the mean
silhouette, to choose k; each fit as kmeans makes it with the same seed.
shap_values
¶
shap_values(fit: Any, data: Dataset | None = None, span: tuple[Any, Any] | None = None, explainer: Literal['auto', 'tree', 'exact', 'permutation'] = 'auto', background: int = 100, evaluations: int = 0, seed: int = 0) -> ShapValues
SHAP values of a machine-learning fit (FittedLearner) over its sample, or over span of data.
explainer: "tree" (TreeSHAP, exact, for random forests, boosted trees, LightGBM and XGBoost), "exact"
(every subset of regressors), "permutation" (a seeded sample of orderings), or "auto": tree for tree models,
else exact up to ten regressors and permutation beyond. The model-agnostic explainers draw absent regressors from
background training periods (all when the sample is no larger; otherwise a sample drawn with seed);
evaluations is the permutation explainer's budget per period (0: 500, or 10 (2p + 1) for p regressors if larger).
Results¶
ConformalIntervals
dataclass
¶
ConformalIntervals(frame: DataFrame, method: str, alpha: float, quantile: float, rank: int, scores: Series, training: tuple[str, str] = ('', ''), dependent: str = '', title: str = '', gamma: float | None = None, window: int | None = None, overlap: int = 0, provenance: Any = None)
Conformal prediction intervals over a span: the prediction, its interval, and the outcome where known.
coverage
property
¶
The share of the span's periods with an outcome whose interval covered it.
DoubleMLSensitivity
dataclass
¶
DoubleMLSensitivity(fit: FittedDoubleML, cf_y: float, cf_d: float, rho: float, alpha: float, null: float, bounds: dict[str, float], rv: float, rva: float, benchmark: DataFrame | None = None, provenance: Any = None)
Bounds on a double ML estimate under omitted confounding (Chernozhukov, Cinelli, Newey, Sharma and Syrgkanis
2022, "Long Story Short"): with a confounder that explains a share cf_y of the outcome's residual variation
and raises the Riesz representer's variation by a share cf_d, correlated rho, theta lies within
theta +- |rho| sqrt(cf_y cf_d / (1 - cf_d)) S, S = sqrt(sigma^2 nu^2); with one-sided confidence bounds at
level, and the robustness values RV and RVa: the strength cf_y = cf_d that moves the bound (or its confidence
bound) to null.
grid
¶
grid(cf_y: Sequence[float] | None = None, cf_d: Sequence[float] | None = None, value: Literal['theta', 'ci'] = 'theta') -> DataFrame
The bound nearest the null (or its confidence bound, value="ci") over a grid: cf_y down the rows, cf_d
across the columns; by default from 0 to 0.15, or past the benchmarks.
FittedCausalForest
dataclass
¶
FittedCausalForest(outcome: str, treatment: str, controls: tuple[str, ...], confounders: tuple[str, ...], binary: bool, cate: DataFrame, ate: float = nan, ate_se: float = nan, att: float | None = None, att_se: float | None = None, importance: Series = None, scores: DataFrame = None, learners: dict[str, str] = dict(), nuisance_rmse: dict[str, float] = dict(), trees: int = 0, min_leaf: int = 5, max_features: int = 0, sample_fraction: float = 0.5, group_size: int = 2, folds: int = 5, nobs: int = 0, clusters: int | None = None, cluster: str | None = None, groups: ndarray | None = None, alpha: float = 0.05, forest: Any = None, provenance: Any = None)
A causal forest: each observation's effect with its interval, the average effects, variable importance, and the heterogeneity checks (best linear projection, calibration test).
average_effects
¶
average_effects() -> Table
The ATE (average partial effect for a continuous treatment) and, for a 0/1 treatment, the ATT.
cate_table
¶
Each observation's effect with its standard error and interval (out of bag).
blp
¶
blp(covariates: str | Sequence[str] | None = None) -> Table
The best linear projection of the effect on covariates (default: every modifier): the doubly robust
scores regressed on a constant and them, with HC3 (or clustered) standard errors.
FittedDoubleML
dataclass
¶
FittedDoubleML(model: str, score: str, outcome: str, treatment: str, instrument: str | None, controls: tuple[str, ...], theta: float, se: float, thetas: ndarray, ses: ndarray, learners: dict[str, str], nuisance_rmse: DataFrame, folds: int = 5, repeats: int = 1, nobs: int = 0, clusters: int | None = None, cluster: str | None = None, splits: ndarray = None, alpha: float = 0.05, provenance: Any = None, cluster_counts: tuple[int, ...] = (), sensitivity_elements: dict[str, Any] | None = None, settings: dict[str, Any] | None = None)
A double/debiased machine-learning estimate: the causal parameter, its standard error, and each split's estimate.
sensitivity
¶
sensitivity(cf_y: float = 0.03, cf_d: float = 0.03, rho: float = 1.0, alpha: float = 0.05, null: float = 0.0, benchmark: Sequence[str] | None = None, data: Dataset | None = None) -> DoubleMLSensitivity
Sensitivity of the estimate to omitted confounding (Chernozhukov, Cinelli, Newey, Sharma and Syrgkanis
2022): dml_sensitivity.
FittedFactorModel
dataclass
¶
FittedFactorModel(spec: FactorModel, loadings: DataFrame, uniquenesses: Series, factor_correlation: DataFrame | None, correlation: ndarray, frame: DataFrame, stats: dict[str, Any], provenance: Any = None)
A fitted factor model: loadings, uniquenesses, the factors' correlations (promax), scores and the test that the number of factors is enough.
communalities
property
¶
The share of each series' variance the factors explain: 1 - uniqueness.
explained
property
¶
Each factor's sum of squared loadings, and its share of the total variance.
test
property
¶
The likelihood-ratio test that this many factors are enough (Bartlett's correction), as factanal reports it.
scores
¶
Factor scores for each observation used: regression (Thomson) or Bartlett (weighted least squares).
FittedLearner
dataclass
¶
FittedLearner(equation: Any, method: Any, model: Any, names: list[str] = list(), y: Series = Series(), X: DataFrame = DataFrame(), cv_rmse: float = float('nan'), cv_resid: Series = Series(), provenance: Any = None)
Bases: BackendResult
A machine-learning regression of an equation's target on its regressors: fit, cross-validated error, importance of each regressor, and forecasts.
importance
¶
importance(reps: int = 10, seed: int = 0) -> Table
Permutation importance: how much the in-sample squared error rises when each regressor is shuffled.
shap
¶
shap(data: Dataset | None = None, span: Any = None, **options: Any) -> Any
SHAP values: each regressor's contribution to each prediction (pymetrix.shap_values; needs shap).
conformal
¶
conformal(data: Dataset, span: tuple[Any, Any], alpha: float = 0.1, **options: Any) -> Any
Conformal (1 - alpha) prediction intervals over span (pymetrix.conformal): split, CQR or adaptive.
predict
¶
predict(data: Dataset, span: Any = None, dynamic: bool = False) -> Series
Predictions over span. Static: of the left-hand side, from the regressors as observed. Dynamic: of the
target series, period by period, with later periods' regressors and left-hand side using the earlier
predictions (a transformed left-hand side such as dlog(c) is solved for c).
forecast
¶
forecast(data: Dataset, span: tuple[Any, Any], dynamic: bool = False, coverage: float = 0.95) -> Any
Forecasts over span with a (coverage) interval from the cross-validated RMSE. Static forecasts are of the
left-hand side; dynamic ones of the target series (as for equations). Dynamic forecasts that feed on themselves
(lags of the target among the regressors, or in a transformed left-hand side) have the interval one step ahead
only: later steps compound errors, and their standard error is left missing.
FittedPCA
dataclass
¶
FittedPCA(spec: PCA, mean: Series, scale: Series, loadings: DataFrame, eigenvalues: Series, _scores: ndarray, _index: Any, _columns: list[str], provenance: Any = None)
scores
property
¶
The components in each period of the sample: one column per component (pc1, pc2, ...).
transform
¶
The components for (other) data, with this fit's means, scales and loadings.
factor_criteria
¶
factor_criteria(kmax: int | None = None) -> Table
Bai and Ng's (2002) information criteria for the number of factors: IC_p1, IC_p2 and IC_p3 for k = 1 to
kmax (default min(8, N - 1)), with the k each picks (the smallest value).
V(k) is the average squared residual of the series (as the components see them: standardized or demeaned) after their projection on the first k components; IC = ln V(k) + k g(N, T) with the penalties (N + T)/(NT) ln(NT/(N + T)), (N + T)/(NT) ln C^2 and ln(C^2)/C^2, C^2 = min(N, T).
KMeansChoice
dataclass
¶
KMeansChoice(table_frame: DataFrame, fits: dict[int, KMeansClusters], provenance: Any = None)
K-means for each k: table (k, within-cluster sum of squares, its fall from k - 1, mean silhouette), the
best k by silhouette, and fits (each k's clusters).
KMeansClusters
dataclass
¶
KMeansClusters(labels: Series, centroids: DataFrame, centres: DataFrame, within: Series, sizes: Series, silhouette: Series, k: int, by: str, series: tuple[str, ...], standardize: bool, starts: int, seed: int, inertias: tuple[float, ...], iterations: int, converged: bool, dropped: tuple[str, ...] = (), provenance: Any = None)
K-means clusters: labels (each date's or series' cluster, 1 to k), centroids (each cluster's centre in
the units clustered: standardised by default), centres (the same in the series' own units, by observations),
within (each cluster's within-cluster sum of squares; inertia their total), sizes, silhouette
(each observation's) and mean_silhouette; the settings (k, by, standardize, starts, seed);
inertias (every start's), iterations and converged (of the start kept); dropped (dates left out
for missing values).
inertia
property
¶
The within-cluster sum of squares, all clusters together (what the algorithm minimises).
summary
¶
summary() -> Table
Each cluster's size, within-cluster sum of squares, mean silhouette and centre.
to_frame
¶
The cluster of each date (or series) and its silhouette.
regime
¶
The clusters as a series by date, for a regime band (by observations only).
ShapValues
dataclass
¶
ShapValues(values: DataFrame, base: float, features: DataFrame, prediction: Series, explainer: str = 'tree', title: str = '', background: Index | None = None, evaluations: int | None = None, seed: int | None = 0, library: str = '', provenance: Any = None)
SHAP values of a learner's predictions: one contribution per regressor and period, and the base value they add to.
additivity_error
property
¶
The largest gap between base + contributions and the prediction (rounding only, by construction).
mean_abs
property
¶
Mean |SHAP| by regressor, largest first: the average size of each regressor's contribution.
to_frame
¶
The contributions with the base value and the prediction, one row per period.