Repository navigation
Releases
v6.6.0
Full Changelog: v6.5.0...v6.6.0
v6.5.0
puremacro 6.4.0: own-data fiscal brief, connector freshness, LP contracts, and correctness fixes
puremacro 6.4.0 adds reusable own-data quarterly fiscal policy briefs, bounded connector provenance and freshness reporting, local-projection chronological and specification contracts with two-way fixed-effects panel IV, and eleven numerical and data-provenance correctness fixes across DSGE, sovereign DSA, weak-IV, SMC, proxy-SVAR, and trade.
- Reusable own-data quarterly fiscal policy brief (
examples.first_brief_fiscal:FiscalBriefConfig,prepare_fiscal_data,parse_quarterly_index, and CLI flags) supporting custom CSV/DataFrame inputs, Gordon–Krenn scaling, explicit external-instrument vs opt-in Blanchard–Perotti identification, lagged state regimes, short-sample/short-regime guards, and portable bilingual (en/es) SHA-256 output bundles while preserving exact reproduction of Ramey–Zubairy (2018). - Bounded connector provenance and freshness reporting (
fetch.freshness:connector_freshness_report,write_freshness_report,RateBudget, andpython -m puremacro.fetch.freshness) acrosscache,recorded, and rate-budgetedlivemodes with domain-identity checks (LF = E + Uon BLS LAUS, nominal/real/deflator consistency on OECD QNA, and[0, 100]%non-fixture share bounds on energy transition), plus ten registered cross-country panel builders infetch.registry. - Local-projection contracts across
lp_hac,lp_iv,estimate_distributional_lp, andestimate_quantile_lpenforcing chronological regularity on date indices, rejecting±np.infand conflicting canonical/alias arguments, recording specification provenance and weak-IV warnings, and estimating genuine horizon-matched two-way fixed-effects 2SLS with structural residuals and entity-clustered standard errors inpanel_lp_iv. - Eleven wrong-number or silent-substitution conditions fixed and documented in the correctness advisories: deterministic
.modspace-separated signed shock lists,var.identify.sign_zeroorientation and joint restriction verification, BLS LAUS measure codes04/06, explicit failure/warning instead of fixture substitution infetch.energy, third-order Sylvester(1, 1, 2)mixed real/complex Schur blocks, quarterly compounding insovereign.dsa.simulate_stochastic_dsa, multivariate Kleibergen–PaaprkWald$F$ and FWL-consistentweak_iv_summary, exact[lb, ub]-truncated SMC priors, Jentsch–Lunsford (2019, 2022) centered moving-block bootstrap inproxy_svar, baseline-anchored Geary–Khamis welfare accounting intrade.optimal_tariffs, and non-fallback live snapshot accounting inconnector_health. - Lazy module loading in
inferenceandmodelsdecouplingimport puremacro.lpfrom DSGE and trade graphs, plusarch>=9.0lowercaseLiteralcompatibility across GARCH wrappers.
Install with python -m pip install puremacro==6.4.0 on Python 3.11 or later. Read the fiscal brief guide https://jalonso1979.github.io/puremacro/docs/first_brief_fiscal/, connector freshness guide https://jalonso1979.github.io/puremacro/docs/CONNECTOR_HEALTH/, local-projections guide https://jalonso1979.github.io/puremacro/docs/lp/, correctness advisories https://jalonso1979.github.io/puremacro/docs/ADVISORY/, and full changelog https://github.com/jalonso1979/puremacro/blob/v6.4.0/CHANGELOG.md.
Own-data fiscal estimates require user-supplied causal identification; opt-in shock_mode="blanchard_perotti" imposes recursive within-quarter timing and should be defended explicitly for the application. Short samples (< 120 effective quarters) and small state regimes (< 40 observations) emit explicit asymptotic warnings rather than blocking estimation. Connector freshness reports inspect bounded metadata, cached series, recorded wire fixtures, or rate-budgeted live probes and do not certify permanent upstream API stability. Previously saved BLS LAUS panels, energy-transition tables, third-order complex-root DSGE solutions, and quarterly stochastic DSA paths produced with versions up to 6.3.0 should be rebuilt or re-run per docs/ADVISORY.md.
Validation on 4be8a2ffc3cb8be447453916bdf971c0921e40d9: 24,044 local tests passed, 89 skipped, and all seven local release gates passed. The main CI matrix https://github.com/jalonso1979/puremacro/actions/runs/43270156065 and tag release workflow https://github.com/jalonso1979/puremacro/actions/runs/43293497320 passed, including nine OS/Python targets, native and Windows typing on Python 3.11/3.12 (arch 9.0.0, mypy 2.4.1), strict documentation builds, 134 opt-in slow/reference/replication tests (19 skipped), and installed-wheel examples. The real Pyodide 0.28.3 kernel passed 121 smoke tests. Downloaded PyPI artifact hashes and all 1,052 packaged wheel files (1,058 entries including .dist-info) and 1,588 repository sdist files were verified byte-for-byte against v6.4.0, followed by a fresh --no-cache PyPI installation and isolated execution of the four base workflows, own-data fiscal brief CLI, and 9-connector freshness CLI. These cohorts overlap. See the attached release-validation.json for artifact hashes and scope.
The examples gallery retains the documented Romer–Romer (2010) published t-statistic rounding mismatch; it is not relabeled as passing. Timing checks use the repository's CI scale of 10 and do not certify unscaled wall-clock deadlines.
The pinned course edition keeps its own package version and validation record. This library release does not upgrade or requalify those course environments.
Español. puremacro 6.4.0 incorpora informes fiscales trimestrales reutilizables con datos propios (examples.first_brief_fiscal), informes acotados de procedencia y frescura de conectores (fetch.freshness), contratos cronológicos y de especificación en proyecciones locales con IV de panel de efectos fijos bidireccionales (lp.panel_lp_iv), y once correcciones numéricas y de procedencia de datos documentadas en los avisos de corrección. Consulte la guía del informe fiscal https://jalonso1979.github.io/puremacro/docs/es/first_brief_fiscal/, la salud de conectores https://jalonso1979.github.io/puremacro/docs/es/CONNECTOR_HEALTH/, proyecciones locales https://jalonso1979.github.io/puremacro/docs/es/lp/ y los avisos de corrección https://jalonso1979.github.io/puremacro/docs/es/ADVISORY/.
Las estimaciones fiscales con datos propios requieren justificar explícitamente la identificación causal, y las muestras cortas emiten advertencias asintóticas explícitas. Los paneles BLS LAUS, tablas de transición energética, soluciones DSGE de tercer orden con raíces complejas y trayectorias DSA trimestrales generadas con versiones hasta 6.3.0 deben recalcularse según docs/es/ADVISORY.md. La galería de ejemplos conserva la discrepancia de redondeo publicada de Romer–Romer (2010) sin reclasificarla, y la edición fija del curso mantiene su entorno y validación independientes.
puremacro 6.3.0: research APIs and second-order HANK
puremacro 6.3.0 adds research APIs for solving equilibria, accounting for simulation uncertainty, and auditing policy models. It merges #232 and #233 while preserving existing entry points and their approximation orders.
- Equilibrium derivatives, reusable dense factorizations, and pseudo-arclength continuation with explicit fold and failure diagnostics.
- Reproducible simulation-aware SMM, separate sampling/simulation uncertainty, and identification-robust tests and confidence sets within documented model classes.
- Bounded research models for trade reallocation, heterogeneous expectations, sovereign banking, and sovereign adaptation.
- Real-Schur HANK solution and experimental second-order full-basis one-asset policies, anticipated-risk terms, pruned simulation, and independent nonlinear audits.
- Shared validation and ownership contracts, immutable retained arrays, public API snapshots, and executable English/Spanish guides.
- The bilingual NUTS example now uses four chains and 1,000 retained draws per chain, with the same convergence and divergence checks.
Install with python -m pip install puremacro==6.3.0 on Python 3.11 or later. Read the research API guide, second-order HANK guide, and full changelog.
The new economic models remain experimental. The second-order HANK benchmark accepts 22 of 24 signed-amplitude cases: the 20-asset negative shocks -0.001 and -0.0005 fail the unchanged distribution audit. Eight of ten finite nonlinear reference solves meet their tolerance; two coarse-grid failures remain recorded. This evidence does not establish household-grid convergence, infinite-horizon/global accuracy, welfare, or reduced-basis/two-asset/capital support. Inspect each returned audit before interpreting a path. The model modules have separate economic closures; combining their outputs requires an explicitly specified joint model.
Validation on bf3e2d320e024e832b11a4b32b8d649c78a1e481: 23,902 local tests passed, 91 skipped, and all seven local release gates passed. The main CI matrix and tag release workflow passed, including nine OS/Python targets, typing/docs, and installed-wheel examples. The opt-in and showcase run passed: 134 opt-in tests, 19 skipped, plus the complete showcase notebook execution. The real Pyodide kernel passed 120 smoke tests. Installed-package checks covered eight new research CLI entry points, four numerical research examples, the second-order HANK guide, and four base workflows. These cohorts overlap. Downloaded PyPI artifact hashes and all 1,051 packaged files were verified against the tagged source, followed by a fresh PyPI installation and executed examples. See the attached release-validation.json for the artifact hashes and scope.
The examples gallery retains the documented Romer–Romer (2010) published t-statistic rounding mismatch; it is not relabeled as passing. Timing checks use the repository's CI scale of 10 and do not certify unscaled wall-clock deadlines.
The pinned course edition keeps its own package version and validation record. This library release does not upgrade or requalify those course environments.
Español. puremacro 6.3.0 incorpora derivadas y continuación de equilibrios, SMM con incertidumbre de simulación, inferencia robusta a identificación y modelos acotados de reasignación comercial, expectativas heterogéneas, banca soberana y adaptación. Incluye HANK experimental de segundo orden con un activo y bases completas, simulación podada y auditorías no lineales. Las API existentes conservan su orden de aproximación. Consulte las API de investigación y la guía HANK.
Los límites numéricos se conservan: 22/24 casos de amplitud HANK superan la auditoría y 8/10 referencias no lineales convergen a la tolerancia declarada. Los casos rechazados no se reclasifican como éxitos. No se certifican convergencia de malla, exactitud global o de horizonte infinito, bienestar ni modelos de dos activos. La edición fija del curso mantiene su entorno y sus comprobaciones independientes.
puremacro 6.2.0
Fiscal rules & debt-sustainability analysis, state-dependent LP & weak-IV HAC diagnostics, sequence-space optimal policy, SVAR identification, GIV, and investment-research workflows.
Added
- Experimental investment-research kernels in
asset_pricing: lagged,
self-financing long-only backtests with cash, costs, eligibility and JSON replay;
Ledoit–Wolf covariance, bounded mean/minimum-variance allocation and frontier;
causal technical indicators, momentum policies and a block-bootstrap max test;
availability-dated fundamentals, financial ratios, FCFF/FCFE/dividend valuation
and sensitivity; Brock–Hommes affine-belief dynamics with explicit fitness timing.
No new runtime dependencies or bundled market data. Bilingual guides and
executed notebooks document numerical checks, timing and unsupported extensions. -
cumulative=Trueonlp_ivandlp_state_dep_ivestimates integral
multipliers directly: the outcome and the endogenous regressor become
window sums over0..h, the instrument stays dated att. Results carry
the flagis_cumulativeand "(cumulative)" method labels. Window sums need
a regular index, so an irregular date or period index raises an error.
(#217) -
python -m puremacro.examples.first_brief_fiscal [--lang es]writes a
bilingual fiscal policy brief on the Ramey-Zubairy historical data, with
the pagesdocs/first_brief_fiscal.mdanddocs/es/first_brief_fiscal.md.
It reports linear and slack/no-slack cumulative spending multipliers at 2
and 4 years, quotes weak cells by Anderson-Rubin sets, runs the
experiment without WWII under the RZ rule and reports a concentration
diagnostic. The page numbers come from a frozen record, refreshed with
tools/reference_validation/refresh_fiscal_brief.pyand checked by the tests. -
RZ_CONTROLSis public in the Ramey-Zubairy example;_CTLstays as an
alias. -
olea_pflueger_f,anderson_rubin_test, andmsw_bandsin
puremacro.inference.weak_ivacceptlags: int | None = Nonefor
Bartlett-HAC long-run covariance estimation (matchinglp_ivwhen
lags=h+1), andolea_pflueger_facceptscontrolsso rawxandzcan
be residualized inside the helper. (#217) -
instrument_influence(z, controls=None, weights=None)in
puremacro.inference.weak_iv(also re-exported frompuremacro.inference)
computes per-observation shares of residualized instrument variation
$\tilde{z}_t^2 / \sum_s \tilde{z}_s^2$ , effective sample size
$1 / \sum_t w_t^2$ , and max share / top indices to flag outlier-driven first
stages. (#217) -
lp_state_dep,lp_state_dep_iv, andlp_garch_stateaccept
state_lag: int = 0to shift the regime state column bystate_lagperiods
before evaluating transition weights$F(s_{t-\text{state_lag}})$ .
lp_state_dep_ivalso reports Sanderson–Windmeijer (2016) conditional
first-stage F statistics (cond_f_H,cond_f_L) and uses them for
first_stage_f_H/first_stage_f_Lwhentransition="logistic".
(#217) - Archived Arellano (2008) calibration: grid convergence established.
check_arellano_grids --calibration archivekeeps the author's exclusion
timing, Fortran default-real literals and midpoint-refined 200-node grid.
Under the public ladder's pre-registered tolerances and precision rule, 797 to
6,369 debt nodes and 321/641 income states pass both final refinements. The
standard design left one bound unclassified (debt/output, income direction);
it is kept in the record. On converged grids spread volatility is about
2.9 pp against the published 6.36, and the trade-balance–spread correlation
about 0.82 against 0.43. Spread volatility still falls along the income
direction: extrapolation places its limit 0.07–0.14 pp lower. Nothing is
recalibrated. Record:tests/fixtures/arellano_2008/archive_grid_convergence.json;
guide. -
puremacro.sovereign.FiscalRuleandsolve_fiscal_sovereign_default(rule=...):
debt ceilings, deficit limits, escape clauses and soft (penalty) rules,
priced by lenders. Ceilings, escapes and penalties use the certified
monotone search; deficit limits use the newpolicy_search="exhaustive"
(or"dense"). States a hard rule leaves without an admissible choice raise
ValueErrornaming them, or default for sure withinfeasible="default". - Predictions about the rules were registered before any rule solve
(tests/fixtures/sovereign_fiscal/rule_predictions_protocol.json) and
measured on a coarse 401 x 21 grid by
tools/reference_validation/check_fiscal_rule_predictions.py; the guide
reports each verdict, including the one that did not hold. - Debt-sustainability analysis (
puremacro.sovereign):
simulate_stochastic_dsa(reduced-form debt fan charts with a
FiscalReactionFunction),estimate_fiscal_reaction_functionand
fit_stochastic_dsa_from_data(Bohn-style reaction estimates feeding the
simulation), andsimulate_fiscal_dsa/compare_fiscal_rules_dsa
(transitions of solved fiscal models from high initial debt, with common
random numbers across rules).StochasticDSAResultand
FiscalReactionEstimateResultfollow the result-object conventions. The
structural trajectories are illustrative 401 × 21 calculations, not
grid-converged. -
calibrate_fiscal_sovereign_smm(SovereignSMMResult): simulated method of
moments for the fiscal sovereign model throughstructural.fit_structural,
withstructural.ags_sensitivity(AGSSensitivityResult) for
Andrews–Gentzkow–Shapiro sensitivity. Local inference is withheld, with a
warning, when the moment Jacobian is rank-deficient or a parameter sits on a
bound. - Sequence-space policy (
puremacro.dsge):ssj_ramsey,ssj_osrand
ssj_welfare_decomposition(linear-quadratic Ramsey and optimal simple rules
on supplied sequence-space Jacobians);solve_risky_steady_stateand
solve_precautionary_obc(Coeurdacier–Rey–Winant risky steady state and a
precautionary occasionally binding constraint). - Policy counterfactuals (
puremacro.lp):mckay_wolf_counterfactualand
barnichon_mesters_opp, from estimated policy-shock impulse responses. - SVAR identification (
puremacro.var):svar_heteroskedastic,
svar_non_gaussian,svar_proxyandsvar_sign_narrative(SVARResult),
andestimate_functional_var(FunctionalVARResult) for yield curves and
distributions. -
puremacro.inference.estimate_giv(GIVResult): granular instrumental
variables. -
puremacro.portfolio: covariance shrinkage, mean-variance and target-return
optimization, efficient frontiers, hierarchical risk parity, Black–Litterman,
macro-quadrant classification and an all-weather allocation, factor
attribution, rebalancing backtests with transaction costs and Monte Carlo
wealth glidepaths. - Bilingual guides for these additions and showcase notebook 76
(notebooks/76_bilingual_macro_showcase.pyand_es.py).
Changed
lp_state_depandlp_state_dep_ivtakeinteract={"all", "intercept", "none"}, default"all": the constant and every control (lags and
contemporaneous controls) are interacted with the regime weight, as in
Ramey–Zubairy (2018, eq. 2) and the direct projections of
Auerbach–Gorodnichenko (2013). With a threshold transition the point
estimates equal one regression per regime. Behaviour change: 6.1.0 and
earlier pooled the intercept and the control coefficients across regimes;
interact="none"reproduces those results (relative difference below
1e-9 on the bundled Ramey–Zubairy snapshot).lp_garch_stateinherits the
new default. (#217)- Both functions also return
diff_HL,se_diff_HLandp_diff_HL(HAC test
of β_H = β_L) and the effective regime sizesn_eff_H,n_eff_L. - The Ramey-Zubairy example: the headline is now at h = 7 and 15 (the 8- and
16-quarter integrals), which reproduce Table 1. The state layer is one-step
lp_state_dep_iv, with standard errors. Weak-IV diagnostics use the HAC
effective F and the HAC Anderson-Rubin set, so the example no longer uses
the non-HAC helpers ofinference.weak_iv. Teaching assertions that did not hold under HAC statistics were
replaced: the slack F does not collapse at long horizons (55.9 at h = 20),
and the robust set is wider than the conventional band in the no-slack
regime (1.28 times at h = 7), not in the slack regime (1.02). The figure is
regenerated. The linear and no-slack headlines, whose instrument is weak
(effective F 16.0 / 12.0 and 7.3 / 10.8), are reported with their
Anderson-Rubin 90% sets. Compatibility: scripts that read
run_rz_replication()'s output must be updated. Therobustdict's keys
are nowh,regime,beta,se,conv_lo,conv_hi,ar_lo,ar_hi,
ar_set_typeandf_eff;msw_lo,msw_hi,beta_2sls,se_2sls,
n_slack,ar_at_pointandar_at_zeroare gone.ar_horizonnow
defaults to 7, in the no-slack regime (it was 12, in the slack regime).
linearis now anLPResultindexed by h. New keys:state_dep(the
lp_state_dep_ivresult) andexpansion_iv(lp_ivon the no-slack
quarters, with Anderson-Rubin sets).
Fixed
- Pooled controls biased the regime coefficients. On the bundled
Ramey–Zubairy snapshot,lp_state_dep_iverased the slack/no-slack gap once
World War II is excluded (0.70/0.69 against 1.07/0.49 with everything
interacted) and returned explosive estimates on the post-1947 sample
(+2538 at 16 quarters). lp_state_dep_ivandlp_smooth_transition_irfno longer swallow estimation
errors: a horizon that cannot be estimated emits aRuntimeWarningnaming
the horizon...
puremacro 6.1.0 — sovereign grid convergence and certified monotone search
6.1.0 (2026-11-03)
Reliability & Scale Release: Sovereign grid convergence (25,601x1,281), certified fast Arellano monotone solver, HANK with productive capital & matrix-free Newton-GMRES, DSGE solution workbench, and household trade adjustment.
This release establishes full sovereign grid convergence through 25,601 × 1,281
uniform nodes and curved grid refinements, provides an exhaustively certified
monotone search solver for Arellano models, introduces the immutable DSGE
solution workbench with .mod replay, adds matrix-free Newton-GMRES and
productive capital to two-asset HANK, and delivers empirical household trade
incidence analysis on Mexican ENIGH 2022 microdata.
Added
-
solve_sovereign_default(debt_grid=...)accepts explicit nonuniform debt
coordinates with an exact zero. Default-grid equilibria and random paths
retain pinned legacy parity; supplied coordinates survive maturity
restructuring, and their price tangents use nonuniform PCHIP weights.
A separate fixed-support curved-grid experiment evaluates the high-reentry
brief scenario with unchanged simulation design and moment tolerances. -
Bounded the short-term monotone policy search's workspace by batching
independent income columns. Values, choices, equilibrium metadata and random
paths retain exact parity with the pinned original algorithm. Extended
sovereign grid convergence studies through 25,601 × 1,281 uniform nodes and
curved grid refinements (tests/fixtures/sovereign_brief/sensitive_grid_convergence.json
andcurved_grid_convergence.json), retaining all failed crossed refinements
through 12,801 × 1,281 without relaxing moment tolerances or rewriting
historical source provenance. -
DSGE workbench with immutable experiments, explicit
.modreplay, Python/HTML
export, unit/timing-aware comparisons and separate accuracy evidence. The IRF
widget clears stale curves and exports after failed or unapplied edits, reports
actionable failures and supports batched changes with Apply mode. Deterministic
Krylov runs expose cooperative cancellation and accepted-path recovery.
Guide. -
Reduced household marginal-value controls join distribution compression, so
Jacobians and Schur systems are built directly in reduced coordinates.
Full-grid audits expose omitted equations and insufficient ranks. Conditional
nonlinear corrections re-solve after each observed shock and separately
check horizon and branching refinements. Productive-capital two-asset HANK
adds investment, installation costs and endogenous returns with independent
market/resource accounts and an author-code capital-block reference. These
remain local/finite-tree research solvers, with household grid errors reported
separately. Reduction,
continuation,
capital. -
Solved local stochastic HANK policies with constraint- and market-moment-
preserving distribution reduction, Schur determinacy checks and held-out
full-distribution audits. Nonlinear finite trees can use that solved
first-order stochastic terminal policy. A two-asset consol economy clears
both asset markets and accounts for coupons, capital gains and portfolio
adjustment resources. Failed compression audits remain visible; these are
local solutions, not global or second-order aggregate-risk calculations.
Guide. -
HANKEquilibriumWorkspaceandsolve_hank_equilibrium: matrix-free
Newton-GMRES solves the coupled one-asset finite-history household and market
equations with analytic EGM/distribution tangents, a reusable sparse
preconditioner and explicit warm starts. Numerical failures retain the last
feasible iterate; the dense reference remains unchanged. This extends the
computational backend, not the model's terminal or stochastic closure.
Guide. -
Observed ENIGH 2022 household policy studies retain source hashes, survey
weights, zero-spending exclusions and household-level welfare. Explicit
budget-neutral compensation supports signed per-household transfers.
Robust policy comparisons report dominance and minimax regret over complete
assumption grids, with no implicit probabilities or failed-cell deletion. -
Conditional dynamic CES sourcing accounts for procurement and quadratic
adjustment resources. Finite household consumption paths report CES/CRRA
consumption equivalents under explicit financing. These are conditional
incidence experiments, not national dynamic GE or causal tariff estimates. -
Finite-tree aggregate-risk HANK solves household choices before future shocks
are revealed, with one distribution per history and explicit firm valuation
and terminal closures. Deterministic paths reduce to the existing published
one-asset model; this does not certify stationary stochastic HANK. -
calibrate_one_asset_hankandsolve_one_asset_hank: the published ABRS
one-asset equilibrium with endogenous labor, debt revaluation, asset/labor
clearing and nonlinear Phillips curve. Independent author-code fixtures
check the published 500×7 calibration and both shock signs. A fixed-tolerance
study extends income refinement to 31 states and checks assets and horizons;
failed intermediate refinements remain visible. The existing reduced HANK
API keeps its original closure. Guide. -
Added
puremacro.inference.gmm, a public generic GMM engine: user moment
functions, two-step, iterated, identity or user weighting, Bartlett HAC
long-run covariance (package default bandwidth), analytic or numerical
Jacobians, sandwich standard errors, Hansen J and Wald tests. Returns
GMMFitResult. Linear IV estimates, standard errors and J match
linearmodelsIV2SLS/IVGMMandinference.hansen_jto 1e-8.
Optimizer stopping is invariant to common changes of moment units, and a
rank check rejects unidentified parameter combinations before inference. -
Added
puremacro.asset_pricing(macro-finance):to_returns,
excess_returns,compoundand annualization helpers;risk_summary
(Sharpe ratio with a Lo 2002 HAC standard error, Sortino, moments,
drawdowns);value_at_risk/expected_shortfall(historical, normal,
filtered GARCH) andvar_backtest(Kupiec, Christoffersen);
time_series_test(GRS and HAC Wald);fama_macbeth(Fama-MacBeth,
Shanken and Newey-West se);sdf_gmmandhj_distance(Jagannathan-Wang
p-value);ccapm(Hansen-Singleton) with FRED helpers
fred_consumption_growthandfred_risk_free. Inputs are refused when they
contain NaN/inf, look percent-scaled or mix frequencies. Estimates match
statsmodels and linearmodels to 1e-8 where definitions coincide; the
remaining differences are documented. Multi-period historical VaR/ES compound
simple returns; SDF/HJ reject rank-deficient systems before inference. Bilingual guidedocs/asset_pricing.md. -
Added
puremacro.fetch.kenfrench_factors.fetchfor the Fama-French three-
and five-factor, momentum and 25 size/book-to-market files. Data are
downloaded into the user cache and never bundled (registry entry
kenfrench.factors, not redistributable). A network test reproduces the
Fama and French (2015) GRS of the three-factor model on the 25 portfolios
(3.57 against the published 3.62). -
puremacro.sovereign.solve_fiscal_sovereign_default: a fiscal block on the
short-term Arellano solver. A fixed tax sharetaufunds public spending
g = tau*y - b + q(b', y) b', valued aspsi * v(g)next to private
consumption(1 - tau) y.FiscalSovereignResultadds spending,
primary-balance and debt-to-output policies, private consumption, and a
simulate()built on a vectorized path engine with common random numbers.
The certified monotone search is the default. Withtau=1and private
consumption off the solver is bit-identical tosolve_sovereign_default.
tauandpsihave no defaults;tau=0.2, psi=1is an illustrative
calibration, not fitted to any target. Guide:
fiscal block. -
check_arellano_grids.paired_comparisonaccepts atolerancesmapping;
its default is unchanged. -
A bilingual sovereign-risk policy brief,
docs/brief_sovereign_risk.md(Spanish:
docs/es/brief_sovereign_risk.md). It shows how the market-reentry
probability, income volatility and income persistence move average debt,
spreads, default frequency and the value of market access in the validated
short-term Arellano model. These are illustrative comparative statics of the
public calibration, not a claim about any country. Every number is shown with
its 95% interval across 16 seeds and its paired 3,201 -> 6,401 grid change.
The original frozen sweep,tests/fixtures/sovereign_brief/sweep.json,
retains two scenarios that fail its grid criterion; the brief reports their
further refinements separately. Quarterly-income debt ratios divide by four
when expressed relative to approximate annual GDP. -
puremacro.sovereign.ergodic_moments(result, *, periods=500_000, seeds=range(1979, 1995), burn=1_000): raw ergodic debt (% of mean quarterly
income), mean spread,
annual default-entry frequency and spread SD, per seed and with 95%
t-intervals. It reproducesSovereignDefaultResult.simulatedraw for draw
and runs 16 x 500,000 quarters in seconds. Continuing exclusion is not counted
as default. -
puremacro.sovereign.value_of_market_access(result): the
consumption-equivalent value (in %) of market access at zero debt, compared
with permanent autarky without a default cost. -
Example
python -m puremacro.examples.first_brief_sovereign:
--scenario theta=0.15(one scenario on the baseline's 6,401 x 641 grid),
--sweep --coarse(all seven scenarios at 801 x 161 in minutes, with a
coarse-grid caveat)...
Puremacro 5.7.1 — nonlinear DSGE workflows and bilingual solver guides
Puremacro 5.7.1
Puremacro 5.7 lets a supported .mod file or Python equilibrium callback define
one nonlinear model for steady states, local stochastic approximations,
deterministic transitions and explicitly mapped global policy problems.
Loading no longer requires a local solution: read_mod compiles the model;
the caller chooses the solution method.
The 5.7.0 tag was not published to PyPI: its release gate exposed a course-test
bootstrap mismatch. This patch fixes the test environment selection, preserves
the frozen 5.5.0 course edition, and refreshes the eight updated notebook pins.
The numerical solver implementation is unchanged from the 5.7.0 source tag.
Models, transitions and policy accuracy
- Ordered deterministic
.modexecution preserves initialization, history,
terminal values, steady-state solves, dated shocks and repeated setup/solver
snapshots. Unsupported commands and options fail explicitly. - Nonlinear transitions add adaptive continuation, economic domains and scaling,
analytic derivatives, explicit announcement dates, terminal policies and
complementarity mappings, with finite solve and horizon budgets. - Global time iteration supports explicit state/control mappings, Chebyshev,
Smolyak and linear interpolation, quadrature and constrained policies.
Independent off-grid Euler/KKT, feasibility and domain-exit audits allow
comparisons with perturbation orders 1–3 and controlled policy refinement. - The one-asset EGM compiler now validates its affine budget contract
structurally; unsupported nonlinear budgets cannot pass just because they
happen to agree at grid nodes.
This release also includes the 5.6.0 development work, which was not published
separately to PyPI: DP .mod files, reproducible study archives, editable HANK aggregate
equations, rank-normalized MCMC diagnostics, additional result audits and
explicit experimental dependence-bootstrap references. See the
complete changelog
for their assumptions and limits.
Documentation and MAV notebooks
Four English/Spanish guide pairs explain mathematical timing and array shapes,
method selection, compatibility, diagnostics and reproducibility, with 29
Python examples per language:
- Choose a DSGE workflow
- Nonlinear models and ordered commands
- Transitions and announcements
- Global policies and local accuracy
T02_A–D in both languages now pin code, helpers and models to v5.7.1.
All eight completed a fresh local execution: 120 code cells and 72 figures.
The stochastic Euler equations retain future marginal utility inside the
expectation. The original course-2026A-5.5.0 edition and its evidence remain
unchanged. Follow the notebook setup
and execution record.
Scope
Dynare compatibility is a documented subset. Global policies require explicit
states, controls and domains. Passing finite residual/refinement checks does
not establish global existence or uniqueness. Krylov currently rejects MCP and
terminal-policy callbacks. Course evidence covers local Python; the Pyodide
smoke tests do not certify every browser, Colab or Juno notebook session.
Known higher-order accuracy issue
The existing higher-order Sylvester solver rounds its LU-cache keys to 12
decimal places. Distinct Schur products can therefore reuse a factorization.
In a determinate test with roots near 0.9999998, the second- and third-order
policy coefficients differ from their analytic values by up to approximately
3.8e-7 in relative terms. The existing near-unit-root warning does not quantify
this coefficient error. The attached near_unit_sylvester_reproducer.py uses
the public model API and an analytic reference. This predates the 5.7 changes;
exact cache keys and independent operator checks are targeted for 5.7.2, not
included here. There is no general drop-in public-API workaround: validate
affected coefficients against an independent analytic/dense reference rather
than assuming full floating-point precision near unit roots. This example is
not evidence of a general unit-invariance failure.
The library supports Python 3.11+; the MAV notebooks use Python 3.12+.
python -m pip install "puremacro==5.7.1"Verification of the published release
- The exact-tag release workflow
passed all nine Linux/macOS/Windows and Python 3.11–3.13 combinations, the
opt-in suite (130 passed, 19 skipped), artifact checks and trusted PyPI publishing. - All six local release gates passed: 21,255 tests passed, 85 skipped and
223 deselected. The stored gallery retained its documented Romer–Romer 2010
rounding difference; there were no new gallery failures. - The actual PyPI wheel and source archive were downloaded and checked against
PyPI's SHA-256 values. An isolated PyPI installation matched all 871 runtime
source files in the accepted notebook record and executed seven examples
from the nonlinear/global guides. - The clean local wheel passed 61 Pyodide 0.28.3 smoke tests. This is separate
from the eight local notebook runs and does not certify full browser sessions.
The attached puremacro-5.7.1-validation.json records the commit, workflow,
artifact hashes and validation scope. The release's wheel and source archive
assets are the distributions downloaded from PyPI, not rebuilt substitutes.
Puremacro 5.5.0 — model inspection, result audits, and verified course edition
Puremacro 5.5.0 adds model compatibility inspection and numerical result audits, corrects steady-state trajectory references, and consolidates the reviewed development backlog.
- Inspect a
.modfile withpuremacro.dsge.inspect_modorpuremacro-dynare inspectbefore solving it. Reports preserve source locations, macro/include provenance and unsupported commands. - Opt into ordered execution for the supported fixed-calibration command subset. Repeated simulations, smoothers and decompositions retain separate options and results; unsupported programs fail preflight. The legacy runner remains the default.
- Audit supported household, first-order DSGE and dynamic-trade results with
puremacro.validation.audit_result. Convergence, equations, Euler/KKT residuals, distribution checks and explicit refinement experiments are separate evidence. Unsupported or unchecked cases are named explicitly. - Correct
STEADY_STATE()references in nonlinear trajectories and derivatives, retain literal terminal assignments unless a terminal equilibrium is requested, and reject exogenous variables inside the operator. Parsed initial/terminal declarations now agree across model-loading, builder and command-dispatch routes; explicit Python overrides retain precedence. Re-run affected nonlinear calculations; see the correctness advisory. - Recognize supported two-asset household budgets structurally. Safely migrate flat caches, improve quarterly projection and repeated bootstrap/keyword work, preserve seeded results, and improve keyboard and CSV accessibility.
The release includes the features previously shipped in 5.4.2, including supported two-asset DP bridges and analytic DSGE likelihood scores. Tags 5.3.0, 5.4.0 and 5.4.1 did not publish packages to PyPI; their status is documented in the changelog.
Compatibility inspection is not a numerical certificate. Audit tolerances apply to individual checks; solver convergence does not establish grid accuracy or economic validity. Ordered execution and household adapters have explicit supported scopes. The documented RR2010 published-statistic discrepancy remains unchanged.
Complete changelog · Inspection guide · Result audits
Validation at source 2db695c passed 20,672 local baseline tests and all six release gates, Python 3.11 and Windows-target typing, strict documentation, clean package checks, and all 37 real-Pyodide tests. The examples gate found 84 passing examples, 8 intentional skips, and the unchanged documented RR2010 mismatch. The 72 course notebooks executed 1,020 code cells against candidate wheel SHA-256 148a8892070509773c930efb9b18be6ca9795a2e39215bf096778b9b50676576; all 544 frozen inputs were preserved, required DP/text sections ran, and no network attempts or language-model cache misses occurred. All 49 integrated course regression tests also passed.
Get the bilingual 2026A course edition, which pins puremacro==5.5.0 and requires Python 3.12 or later. Its notebooks and execution record are versioned in the separate course-2026A-5.5.0 tag; the library itself continues to support Python 3.11+.
The exact-tag release workflow passed all nine platform targets, the extended suite (129 passed, 19 skipped), package checks, and trusted PyPI publishing. The course CI also passed all nine targets; its merged tree is identical to the validated revision.
The official PyPI 5.5.0 wheel has SHA-256 7b88efd5bac614c2640c031ecbc2742a7247cf39935d0e5c54c048b3629d78cb. A fresh no-cache installation from official PyPI verified all 912 installed runtime files against the tagged source, two ordered invocations, equation/Jacobian audits, and CLI inspection. The attached content-equivalence evidence records complete runtime-file and dependency-metadata equality between the public wheel and the candidate used for the course execution. The archives have different ZIP hashes; this is content equivalence, not a claim that the public archive was separately used to rerun the notebooks.
puremacro 5.2.0
puremacro.trade is back. 5.0 and 5.1 shipped without it; this release brings the multi-country, multi-sector trade library back with consistent producer/purchaser accounting as its only accounting, a new bundled OECD table built by a script that ships with it, and no built-in defaults for the table: every dimension, country and sector comes from the table or from an argument. Code written for the 4.x trade API needs the changes listed under "Removed relative to 4.8.1" and "Changed relative to 4.8.1".
Added
puremacro.tradewith the static model (calibrate_trade_model,solve_trade_equilibrium,solve_equilibrium,TariffScenario,run_scenario,run_scenario_batch, Geary-Khamis PPP), Hicksian welfare (compute_hicksian_welfare), audited policy recovery (solve_policy_equilibrium), optimal tariffs and Nash tariff games (optimal_tariffs,game), Caliendo-Parro (2015) exact hat algebra (CaliendoParroModel), the flexible CGE (solve_flexible_trade_equilibrium: nested CES technology, Stone-Geary demand, Armington sourcing, Atkeson-Burstein markups, capacity margins), policy analytics, the exact nested-CES block Newton (ces_newton), household demand systems and distributional incidence (household,distributional), audited parameter continuation (continuation), the reduced local-stability diagnostic (stability, experimental), native MRIO tables (mrio), the condensed one-factor Leontief tariff model (condensed), the perfect-foresight dynamic MRIO (dynamic, experimental), plots and the optional torch/MLX solvers (gpu).models.TradePolicySimulatorreturns with it.- A bundled table,
puremacro/trade/_datafiles/icio_oecd2023_2019_isic_g20.npz: the OECD Inter-Country Input-Output tables, 2023 edition, reference year 2019, summed into the 19 G20 member countries plus a rest of the world and the 20 sections of ISIC Rev.4 (shape 403 x 460).load_icio_data()reads it by default (source="oecd_isic") and labels it with the table's own codes.puremacro/trade/_datafiles/SOURCES.mdgives the OECD citation, the terms of use, the concordance and the checksums of the source and of the bundled file. If you publish results computed from it, cite the OECD. tools/build_icio_isic.pyrebuilds that table byte for byte from the OECD file;--downloadfetches the OECD's2016-2020_SML.zip(about 85 MB) once into~/.cache/puremacro/oecd_icio(or$PUREMACRO_OECD_ICIO_DIR).tools/reference_validation/validate_oecd.pytakes the same option.puremacro.trade.data.synthetic_icio_table(nc, ns, *, nfd=3, seed=0)builds a seeded synthetic table of any size in the library's layout, with nonnegative final-use shares and positive investment for every seed, andsynthetic_codes(nc, ns)gives its labels (C01...,S01...). The tests run on it instead of a real table.- Docs (EN/ES):
trade_accounting,trade_welfare,trade_policy,trade_continuation,trade_stability,trade_household,trade_distributional,trade_ces_newton,trade_condensed,trade_mrio,trade_dynamic,trade_gpu; the trade sections ofspatial_and_trade_ge,policy_simulators,STRUCTURAL_VALIDATION_STATUSandADVISORY. Notebooks 55 and 61-65 (EN/ES), the examplepuremacro/examples/distributional_trade_ge.py, the OECD/accounting/welfare/Hicksian validators intools/reference_validation/and three trade cases in the validation gallery.
Removed relative to 4.8.1
- The legacy accounting.
accounting="legacy"(the 4.x default),tariff_revenue_mode="legacy_national"and the precedence and compatibility switches that went with it are gone from every entry point,gpuincluded; consistent accounting is the only one, so the same call can give different numbers than in 4.x.accounting="legacy"raisesValueErrorsaying so; a removed keyword raisesTypeErrornaming it. - Named scenarios and the scenario registry (
SCENARIOS, the canonical-scenario constants and lookup functions,ExtendedTariffScenario,run_tariff_scenario).run_scenario,solve_keller_pacandpolicy_analyticstake aTariffScenarioor explicit tariff arrays; a string raisesTypeError("named scenarios were removed; build a TariffScenario"). - The 4.x bundled table, the bundled reference solutions and results workbook, their loaders and constants (the reference-solution and workbook loaders,
available_reference_scenarios,bundled_icio_path,bundled_reference_path,bundled_workbook_path,load_raw_45sector_icio,BUNDLED_ICIO_PROVENANCE,OECD2020_ICIO_PROVENANCE), and that table's code lists (CANONICAL_COUNTRY_CODES,CANONICAL_SECTOR_CODES,CANONICAL_SECTOR_NAMES,get_country_codes,get_sector_codes,get_sector_names).load_icio_data(source="legacy")raisesValueErrornaming the bundled source andsynthetic_icio_table. - The real-world tariff benchmark (and its re-export in
game), the analysis stubs and result classes built on the named scenarios (among themEVDecompositionResult), the twoScenarioBatchResulttable renderers for the named scenarios,plot.plot_country_impactsandplot.plot_tariff_escalation_curve, the"harberger"welfare metric (it now gives the "Unknown welfare metric"ValueError), andflexible.compute_homothetic_final_demand. - In
mrioandcondensed: the coarse tariff rules (coarse_tariff_rates,CoarseTariffResult), the sector concordance of the 4.x table and its code and name constants, the numbered model labels,condensed.measures.aggregation_gapsand thew_<code>alias. puremacro.trade.extensions(scenario extensions built on the named scenarios) andpuremacro.trade.tables(LaTeX tables of the named scenarios) do not return.
Changed relative to 4.8.1
- No paper defaults. Dimensions are read from the table (any number of countries, sectors and final-use categories); the fiscal-recycling and capacity branches of
solve_trade_equilibriumandsolve_flexible_trade_equilibriumneed their country and sector named and raiseTypeErrornaming the missing argument;compute_unilateral_optimal_tariffandcompute_welfare_payoff_matrixtake their countries as required arguments, andsolve_multilateral_nash_tariffsandevaluate_national_welfareraiseTypeErrorwithout them; the Geary-Khamis numeraire is a country argument, andGearyKhamisResult's summary has no fixed-country PPP row.ICIODataneeds its country and sector codes. - Renamed without aliases: the fold helpers are
solve_fold_continuationandsolve_fold_continuation_step(they take the stiff coordinate as an argument; the info key isidx_stiff), andCondensedMeasuresResult.headline()iskey_measures(). solve_flexible_trade_equilibriumis rebuilt on the consistent accounting; at default settings its equations are those ofsolve_trade_equilibrium.method="quasi_condensed"onsolve_trade_equilibriumraisesNotImplementedErrorpointing to the flexible solver.gpu:BatchedJacobianEvaluator(calib, tau_a, taufd_a, ...)evaluates the consistent-accounting residuals and no longer takes the national tariff-rate vectors;solve_homotopy_continuationhas no national-rate targets.get_country_coderaisesIndexErrorfor a position outside the table instead of inventing a code.solve_fold_continuation_stepraisesValueErrorfor anidx_stiffoutside[0, nc); it used to warn and use country 0.- The condensed path of
solve_flexible_trade_equilibriumkeepsiterationswithinmax_iter: Newton stops when its line search finds no decrease (metadata["newton_stalled"]). Before, a solve that could not converge ran Newton up to 21 times with the fullmax_itereach and could report more iterations thanmax_iter. - In that condensed path, the tariff homotopy runs only on the iteration budget the direct attempt leaves unused; with fewer iterations left than homotopy steps it is not tried.
- When that condensed solve fails,
iterationscounts the homotopy stages as well as the direct attempt (metadata["tariff_homotopy_steps"]is 0 when a homotopy was tried and did not converge). TradePolicySimulator.from_icio(year, *, tables=None, ...)calibrates to the table ofyear(fromtables, or the bundled 2019 table) and raisesValueErrorlisting the available years for any other year.
Fixed
CaliendoParroModelmapped the codes USA, CHN and DEU (and ROW) to positions 0-2 whatever the model's own country order, andmanuf/servto sectors 0-1. Countries and sectors are now found by their own codes (exact, then case-insensitive) or by position; an unknown code raisesKeyError.TradePolicySimulator.from_icio(year)ignoredyearand returned thenafta_chinapreset.condensed.table.infer_merchandise_maskcounted utilities (ISIC D and E) as merchandise, and accepted composite sector labels whose content is not documented; those now need an explicitmerchandise_mask.
puremacro 5.1.0
First 5.x final release. puremacro.dp simulates panels of individual histories and reports exact inequality statistics, and it is now the stable way to declare dynamic-programming models; vfi.Model is deprecated and will be removed in 6.0. It also carries everything in the 5.0 pre-releases below: the research material is no longer part of the package (4.8.1 is the last release that contains it), puremacro.llm, and the review-defect fixes.
Added
DPSolution.simulate(n_agents, periods, seed=..., init=..., burn_in=..., record=...)simulates individual histories from apuremacro.dpsolution (discrete VFI and EGM, infinite horizon and life cycle, with or without a discrete choice and taste shocks) and returns adp.Panel. One seeded PCG64 generator draws, each period, the discrete-choice uniforms, then the shock uniforms, then the survival uniforms, so the same seed gives a bit-identical panel. Infinite-horizon panels start in the stationary distribution by default; life-cycle panels start with newborns and apply the declared survival (panel.alive).n_agents * periodsabove 5e8 raisesValueErrorwith the memory it would need. Continuous-time (HJB) and Krusell-Smith solutions raiseNotImplementedError.dp.Panel, a container for simulated histories:to_frame,to_microframe,cross_section,path, andmean,quantile,gini,top_shareandsummarypooled over periods or groupedby="t"orby="age". Dead agents keep their rows and are left out of every statistic.- Exact statistics on the solved distribution:
DPSolution.gini,top_share,quantileandlorenz. The Gini is the standard weighted Gini on the Lorenz curve,1 - sum_i w_i (L_i + L_{i-1}), the same function asMicroFrame.gini(negative values allowed, NaN when the total is not positive). In a life cycle,age=juses one cohort andage="all"returns one value per age. Krusell-Smith solutions raiseValueError(they have no stationary distribution). DPSolution.population_shares()gives each age's population share in a life cycle with survival applied.sol.distributionstill gives every cohort mass 1; the pooled statistics weight cohorts by these shares.docs/dp.md(EN/ES) has two new sections, "Panels and inequality" and "Porting from vfi.Model".dpmoves from Experimental to Stable inARCHITECTURE.md.
Fixed
vfi.simulate_panelraisesTypeErrorfor a policy that is not an integer array of grid indices. It used to cast a float policy (for example a continuous EGM policy in asset levels) withastype(np.intp), which silently truncated it to wrong indices. UseDPSolution.simulatefor such solutions.
Deprecated
vfi.Modelissues aDeprecationWarningwhen constructed and will be removed in 6.0. Declare the model withpuremacro.dp;docs/dp.md, "Porting from vfi.Model", shows the translation, and thedpversion of notebook 21's model picks the same policy on every grid node.
Changed
- The deprecated
puremacro.lp.garch_utilsmodule andpuremacro.sigma.sigma_numpy.SigmaObjectannounced removal in 5.0.0; they now name 6.0.0, together withvfi.Model, so a minor release removes nothing. - Notebook 21 (EN/ES) declares its precautionary-savings model with
puremacro.dpinstead ofvfi.Model. It now prints mean assets 6.5733 and a wealth Gini of 0.3494, the exact values of the stationary distribution. It used to print 6.6767 and 0.3924, which came from a 2000-household, 100-period simulation; that Gini was computed after subtracting the minimum asset holding, so it was not the standard Gini. The notebook adds a simulated panel whose cross-sectional Gini converges to the exact value, and its text no longer claims vectorised Bellman updates or pluggable Numba/MLX/CuPy backends.