Skip to content

pymetrix-fiscal

A plugin: a separate package

pymetrix-fiscal is a first-party plugin, installed on its own (not yet on PyPI: from a clone of the repository):

python -m pip install -e packages/pymetrix-fiscal

Fiscal analysis for pymetrix: debt sustainability analysis (the debt-dynamics identity, its decompositions, gross financing needs, the debt-stabilising primary balance and stress tests), with provenance.

The names pymetrix_fiscal exports (its __all__), with their full documentation. Import them from the plugin: from pymetrix_fiscal import .... The plugin's README says more.

Public names

Assumptions dataclass

Assumptions(frame: DataFrame, sources: dict[str, str] = dict(), notes: dict[str, str] = dict(), name: str = '')

Projected paths by year, in the layout's columns and units (pymetrix_fiscal.layout): growth, inflation, the interest rates, the exchange rate (or its depreciation), the foreign-currency and short-term shares, the primary balance, other flows, amortisation and foreign inflation. sources says where each column came from and notes why; both are kept in every result's provenance, as a forecast round keeps its judgement.

from_frame classmethod

from_frame(frame: DataFrame, *, source: str = 'user', notes: dict[str, str] | None = None, name: str = '') -> Assumptions

Assumptions from a frame indexed by year (or with a year column), in the layout's columns.

from_data classmethod

from_data(data: Any, *, after: str | None = None, span: Any = None, source: str = '', **mapping: str) -> Assumptions

The projection years of an annual Dataset: its rows after after (the last year of history; by default the last year with debt, when the data have a debt column) or in span, with the layout's columns found by name, or as mapping names them (growth="ngdp_rpch").

read classmethod

read(path: str, *, sheet: Any = None) -> Assumptions

The projection years of a CSV or Excel file in the documented layout: the rows after the last year with debt.

from_round classmethod

from_round(round: Any, *, span: Any = None, **mapping: str) -> Assumptions

Assumptions from a ForecastRound: its paths (annual) for the layout's columns, found by name or as mapping names them (growth="dly"); its judgemental adjustments' reasons become the notes.

historical classmethod

historical(profile: Any, years: Any, *, window: int = 10) -> Assumptions

Every driver at its average over the last window years of the profile's history, for the projection years (a span of years or a count after the last year of history): the Debt Dynamics Tool's historical scenario (section VI.A), here as a set of assumptions. The average residual is added to other flows.

with_paths

with_paths(*, source: str = 'user', note: str = '', **paths: Any) -> Assumptions

New assumptions with some columns replaced: with_paths(primary_balance={"2027": 1.0, "2028": 1.5}) sets those years (a scalar sets every year).

record

record() -> dict[str, Any]

What provenance keeps: each column's path by year, source and note.

ConstantPrimaryBalance dataclass

ConstantPrimaryBalance(name: str = 'Constant primary balance', start: int = 2)

Bases: StressTest

The primary balance from projection year start on held at its value in the year before; the rest as in the baseline (DDT section VI.B).

Custom dataclass

Custom(name: str = 'Custom', values: dict[str, dict[str, float]] = dict(), changes: dict[str, dict[str, float]] = dict())

Bases: StressTest

A scenario of the user's: values sets inputs in given years ({"growth": {"2027": -3.0}}) and changes adds to them ({"other_flows": {"2027": 5.0}}: a one-off rise in debt of 5 points of GDP, such as a contingent liability called). Years are calendar years.

CyclicalAdjustment dataclass

CyclicalAdjustment(name: str, method: str, scaling: str, frame: DataFrame, elasticities: dict[str, float], sources: dict[str, str], adjusted: DataFrame | None = None, gap_source: str = '', notes: tuple[str, ...] = (), provenance: Any = None)

A cyclically adjusted (and structural) budget balance, by period, from cyclically_adjusted_balance.

frame holds, in per cent: gap (of potential output), potential (potential real output, when real GDP was given), balance and primary_balance (of actual GDP), balance_scaled (the balance over the scaling GDP: potential GDP with scaling="potential"), cyclical and cab (which add up to balance_scaled), cyclical_primary and capb, interest and one_offs (over the scaling GDP), structural (the CAB less one-offs), structural_primary (plus interest), stance (its change: positive, a tightening) and fiscal_impulse (minus the stance). adjusted holds each item's adjusted ratio ("imf", "oecd"). elasticities and sources give each elasticity used and where it came from.

cab property

cab: Series

The cyclically adjusted balance, per cent of potential GDP ("eu": of GDP, as the Commission).

cyclical property

cyclical: Series

The cyclical component: the balance (over the scaling GDP) less the CAB.

structural property

structural: Series

The structural balance: the CAB less one-off and temporary measures.

structural_primary property

structural_primary: Series

The structural primary balance: the structural balance plus interest.

stance property

stance: Series

The fiscal stance: the change in the structural primary balance (positive: a tightening).

gap property

gap: Series

The output gap used, per cent of potential output.

to_frame

to_frame(view: str | None = None) -> DataFrame

The results by period (frame), or one of the views as a frame (view="Components"...).

components_table

components_table() -> Any

By period: the gap, the balance, its cyclical and cyclically adjusted components, one-offs, the structural and structural primary balances and the stance.

elasticities_table

elasticities_table() -> Any

Each elasticity used and its source.

adjusted_table

adjusted_table() -> Any

Each item, as a ratio to actual GDP and adjusted (to potential GDP).

plot

plot() -> Any

The balance against the cyclically adjusted and structural balances, with the output gap.

plot_components

plot_components() -> Any

The balance as its cyclical and cyclically adjusted parts, as stacked bars.

plot_stance

plot_stance() -> Any

The fiscal stance (the change in the structural primary balance) against the output gap.

cyclically_adjusted_balance

cyclically_adjusted_balance(data: Any, *, method: str = 'imf', revenue: str | None = None, expenditure: str | None = None, balance: str | None = None, interest: str | None = None, one_offs: str | None = None, gdp: str | None = None, gap: str | None = None, gap_form: str = 'percent', real_gdp: str | None = None, potential: str | None = None, filter: Any = None, elasticities: dict[str, float] | None = None, revenue_parts: dict[str, str] | None = None, expenditure_parts: dict[str, str] | None = None, semi_elasticity: Any = None, scaling: str | None = None, span: Any = None, source: str = '', name: str = '') -> CyclicalAdjustment

The cyclically adjusted, structural and structural primary balances, and the fiscal stance, from a dataset's series (a CyclicalAdjustment).

revenue and expenditure (total, interest included) are in per cent of GDP, or levels with gdp (nominal GDP, the same units). interest is the interest paid, part of expenditure: it is never adjusted, and gives the primary balances. one_offs is the effect of one-off and temporary measures on the balance (positive when they improve it): the structural balance is the CAB less them. balance is the overall balance, for "eu" when revenue and expenditure are not given.

The output gap: gap (a series, per cent of potential output, or gap_form="log" for 100 x log(Y/Y*), as the QPM's y_gap); or real_gdp with potential (a series), or with a trend filter on its log (pymetrix.HP(), the default, lambda by frequency; pymetrix.Hamilton()...).

method:

  • "imf": aggregate elasticities, elasticities={"revenue": 1, "expenditure": 0} by default (Fedelino, Ivanova and Horton 2009, p. 6); expenditure's applies to primary expenditure;
  • "oecd": revenue_parts and expenditure_parts (name -> series, in the units of revenue) each with its elasticity in elasticities (required: no defaults are shipped); the rest of revenue and of primary expenditure take elasticities["revenue"] and ["expenditure"] (0 unless given);
  • "eu": semi_elasticity (a number, or "ec2014:XX" for the Commission's 2014 value for country XX, EC2014_SEMI_ELASTICITIES): CAB = b - semi_elasticity x gap.

scaling ("imf" and "oecd"): "potential" (default) puts the balance over potential GDP before taking the CAB from it, so all the parts are ratios to potential GDP (the technical note's Method 2); "actual" leaves the balance over GDP (Method 1). span limits the periods shown (the gap is filtered on the whole sample). source says where user-supplied elasticities came from (kept with the result).

DebtPath dataclass

DebtPath(name: str, kind: str, frame: DataFrame, decompositions: dict[str, DataFrame], financing: DataFrame, style: str = 'srdsf', initial: tuple[str, float] = ('', float('nan')), history: Series | None = None, assumptions: DataFrame | None = None, notes: tuple[str, ...] = (), provenance: Any = None)

A path of the debt ratio and its drivers, by year, in per cent of GDP: a projection (kind="projection", from DSA.project or a stress test) or the identity applied to history (kind="history", from DSA.decompose).

frame holds, by year: debt, its change, the drivers used (growth, inflation, the effective interest rate, depreciation, the foreign-currency share, the primary balance, other flows), gross financing needs and the debt-stabilising primary balance (both definitions). decompositions holds each year's change in debt split two ways, "srdsf" and "mac2013" (engine.contributions): each row adds up to the change exactly, the residual included. financing holds the parts of gross financing needs. history is the profile's debt ratio before the projection, for the charts.

contributions property

contributions: DataFrame

The decomposition in this path's style.

gfn property

gfn: Series

Gross financing needs, per cent of GDP.

stabilising_balance property

stabilising_balance: Series

The primary balance that would hold debt at the previous year's ratio, each year (DDT Appendix IV.A).

decomposition

decomposition(style: str | None = None) -> DataFrame

Each year's change in debt by component, in style ("srdsf" or "mac2013"; this path's by default), with the change itself as the last column.

table

table() -> Any

The path by year: debt, its change, gross financing needs, the balances and the drivers.

plot

plot() -> Any

The debt ratio, history and projection, with the primary balance against the debt-stabilising balance.

plot_decomposition

plot_decomposition(style: str | None = None) -> Any

The contributions as stacked bars, with the change in debt as a line.

residual_table

residual_table() -> Any

The identity's check: each year's change in debt, what the identity explains, and the residual.

DebtProfile dataclass

DebtProfile(frame: DataFrame, name: str = '', coverage: str = 'general government', balance: str = 'primary balance excluding interest revenue and spending', mapping: dict[str, str] = dict(), data: Any = None, provenance: Any = None)

The history of a country's (or a public sector's) debt: its ratio to GDP and composition (currency, short-term share, creditor groups) by year, and the drivers the debt-dynamics identity needs (growth, inflation, effective interest rates, the exchange rate, the primary balance, other flows), in the layout's columns and units (pymetrix_fiscal.layout). coverage says which public sector the debt covers; balance how the primary balance is defined (the SRDSF's excludes interest revenue as well as interest spending: its guidance note, footnote 35).

last property

last: Period

The last year of history.

from_data classmethod

from_data(data: Any, debt: str, *, gdp: str | None = None, real_gdp: str | None = None, growth: str | None = None, inflation: str | None = None, interest: str | None = None, interest_paid: str | None = None, interest_domestic: str | None = None, interest_foreign: str | None = None, fx_share: str | None = None, short_term_share: str | None = None, exchange_rate: str | None = None, exchange_rate_avg: str | None = None, primary_balance: str | None = None, other_flows: str | None = None, amortisation: str | None = None, foreign_inflation: str | None = None, revenue: str | None = None, creditors: dict[str, str] | None = None, name: str = '', coverage: str = 'general government', span: Any = None) -> DebtProfile

A profile from an annual Dataset, naming the series that hold each part of the layout.

With gdp (nominal GDP, in local currency), debt, primary_balance, other_flows, amortisation and revenue are levels in local currency, divided by GDP here; without it they are already in per cent of GDP. real_gdp gives growth (and, with gdp, the deflator's inflation) when growth and inflation are not named. interest_paid (a level) gives the effective rate, interest paid over last year's debt. creditors maps a group's name to the series of its share of the debt (per cent). Years with the debt ratio are the history; span limits them. The call, with this mapping, is recorded, and the profile's provenance names the data's series and vintages.

read classmethod

read(path: str, *, sheet: Any = None, name: str = '', coverage: str = 'general government') -> DebtProfile

A profile from a CSV or Excel file in the documented layout (layout.COLUMNS; the plugin's docs/data-layout.md): a year column, then the layout's columns by name. The rows with debt are the history; later rows (assumptions) are left for Assumptions.read.

composition

composition() -> DataFrame

The debt by currency, maturity and creditor group, in per cent of GDP, by year (the shares times the ratio).

previous

previous(year: Period) -> Series

The row of the year before year (the history's).

history

history(span: Any = None, exchange: str = 'average') -> tuple[float, Any, DataFrame, list[str]]

(d0, drivers, rows, notes): the drivers of each year of history in span (all years after the first by default), and the debt ratio the year before (fractions).

identity

identity(span: Any = None, style: str = 'srdsf', exchange: str = 'average') -> DataFrame

The identity applied to the history: each year's change in debt split into its contributions (per cent of GDP), with the residual the identity leaves unexplained (style: "srdsf" or "mac2013").

check

check(tolerance: float = 0.5, exchange: str = 'average') -> Any

Whether the identity holds on the history: a Table of each year's change in debt, the change the identity explains and the residual, flagging the years whose residual is above tolerance (percentage points of GDP) in absolute value. Large residuals point to flows missing from other_flows, valuation changes of debt in other currencies, or coverage that differs between the debt and the balance.

history_moments

history_moments(window: int = 10, exchange: str = 'average') -> tuple[Series, Series, DataFrame]

(means, standard deviations, values) of the drivers over the last window years of history, in the layout's units: growth, inflation, interest rates, depreciation, the primary balance, other flows and the identity's residual. Changes (depreciation) and the residual need the year before, so within a window of 10 years they have 9 values, as the Debt Dynamics Tool's 10 years of history give (its section VI, footnotes 14 and 16). Standard deviations are the sample's (n - 1).

DSA dataclass

DSA(profile: DebtProfile, assumptions: Assumptions, span: tuple[str, str] | None = None, style: str = 'srdsf', exchange: str = 'average', name: str = 'baseline')

A deterministic debt sustainability analysis: a DebtProfile (history), Assumptions (projection), the projection's span (all the assumptions' years by default; it must start the year after the history ends), the decomposition style shown by default ("srdsf", the SRDSF guidance note's Box 3, or "mac2013", the 2013 MAC DSA guidance note's Figure 2: results hold both) and how the exchange rate enters (exchange: "average" values foreign-currency interest and the year's flows at the average rate when the data give it, with the stock-flow adjustment that intra-year changes make, as the Debt Dynamics Tool does; "end" uses the end-of-year rate throughout). Frozen, so a recorded step replays it.

inputs

inputs() -> DataFrame

The projection's inputs as the identity uses them, in the layout's units, with the exchange rate as depreciation and the average rate as average_to_end (its ratio to the end-of-year rate).

project

project(name: str | None = None) -> DebtPath

The baseline: the debt ratio by year from the assumptions, with both decompositions of its change, gross financing needs and the debt-stabilising primary balance (a DebtPath).

decompose

decompose(span: Any = None) -> DebtPath

The identity applied to the profile's history (span: some of its years): each year's change in debt by component, with the residual the identity leaves (a DebtPath of kind "history").

stress

stress(tests: StressTests | None = None) -> StressTestResult

The baseline and each of tests (StressTests.ddt2021() by default), each a DebtPath projected with the same identity.

scenario

scenario(name: str, **paths: Any) -> DebtPath

An alternative scenario: the baseline with some assumptions replaced (primary_balance={"2027": 0.5}, or a scalar for every year), projected the same way.

EC2014_SEMI_ELASTICITIES module-attribute

EC2014_SEMI_ELASTICITIES: dict[str, float] = {'BE': 0.61, 'BG': 0.31, 'CZ': 0.43, 'DK': 0.62, 'DE': 0.55, 'EE': 0.44, 'IE': 0.53, 'EL': 0.48, 'ES': 0.54, 'FR': 0.6, 'HR': 0.47, 'IT': 0.54, 'CY': 0.52, 'LV': 0.38, 'LT': 0.41, 'LU': 0.44, 'HU': 0.49, 'MT': 0.46, 'NL': 0.65, 'AT': 0.58, 'PL': 0.52, 'PT': 0.51, 'RO': 0.34, 'SI': 0.48, 'SK': 0.39, 'FI': 0.57, 'SE': 0.59, 'UK': 0.59, 'EU28': 0.5}

HistoricalScenario dataclass

HistoricalScenario(name: str = 'Historical', start: int = 2)

Bases: StressTest

Growth, inflation, the interest rates, depreciation, the primary balance and other flows (with the identity's average residual added, as the DDT does: section VI.A and footnote 16) at their historical averages from the projection year start on; the other inputs as in the baseline.

layout

The documented column layout of a debt profile and its assumptions, and turning those columns into the engine's drivers.

One file (CSV or Excel) holds both, as the Debt Dynamics Tool's input sheet does: a year column, then one column per series below, in the units stated (percentages are written as 5 for 5 per cent). Years with debt filled in are history (the profile); the years after the last of them are the projection (the assumptions). Any column but year and debt may be left out, with the defaults stated; docs/data-layout.md in the plugin's folder and the help topic list them too.

example_file

example_file() -> str

The path of the layout's example file, a CSV of a fictional country (history 2010-2025, assumptions to 2031): a template to copy, and what Dataset.example("dsa_example") holds.

layout_table

layout_table() -> Any

The layout as a Table: column, what it is, unit and default.

read_table

read_table(path: str, sheet: Any = None) -> DataFrame

A CSV or Excel file in the layout, as a frame indexed by annual periods, its column names in lower case.

interest_columns

interest_columns(frame: DataFrame) -> str

Which interest columns the frame gives: "effective" (interest) or "split" (domestic and foreign).

drivers

drivers(rows: DataFrame, previous: Series, exchange: str = 'average', notes: list[str] | None = None) -> Drivers

The engine's drivers for the years rows (canonical columns, in percent), with previous the year before the first (its fx_share, short_term_share and exchange_rate). Missing optional columns take the layout's defaults, each noted in notes.

check_ranges

check_ranges(frame: DataFrame, where: str) -> None

Refuse values that cannot be right: shares outside 0 to 100, exchange rates not above zero, growth or inflation of -100 per cent or less.

Shock dataclass

Shock(name: str = '', variable: str = 'growth', size: float = -1.0, unit: str = 'sd', years: tuple[int, int] = (2, 3))

Bases: StressTest

One driver moved from the baseline in projection years years (from 1, both included): by size historical standard deviations (unit="sd", over the context's window) or by size points ("points"). variable is one of growth, inflation, interest (the effective rate, or both the local- and the foreign- currency rate, each by its own standard deviation), primary_balance, depreciation, other_flows and foreign_inflation. The DDT's shock scenarios are these, one driver at a time (section VI.C).

StressTest dataclass

StressTest(name: str)

A stress test or alternative scenario. Subclasses say what changes (apply) and in words (describe).

StressTestResult dataclass

StressTestResult(paths: dict[str, DebtPath], tests: Any, provenance: Any = None)

The baseline and each stress test's DebtPath (paths, the baseline first), the tests as run, and tables of each indicator by test and year.

indicator

indicator(name: str = 'debt') -> DataFrame

name ("debt", "gfn", "debt_to_revenue" where revenue is given...) by year (rows) and test (columns).

largest

largest() -> DataFrame

For debt and gross financing needs: the test that raises each most above the baseline, by how much, and in which year.

plot

plot() -> Any

Every scenario's debt path (the stress-test fan of scenarios), the baseline drawn heavier.

heatmap

heatmap() -> Any

Each scenario's debt less the baseline's, by year, as a heat map.

StressTests dataclass

StressTests(tests: tuple[StressTest, ...] = (), window: int = 10, name: str = '', source: str = '')

A set of stress tests run together (settings): the tests, in order, and the history window (years) their averages and standard deviations come from. name and source say which preset it is.

Presets: ddt2021(), the deterministic scenarios of the IMF's Debt Dynamics Tool (Acosta-Ormaechea and Martinez 2021, section VI.A-C). Planned, as further presets beside it: lic_dsf_2018() (phase 3a, the 2018 LIC DSF guidance note's standardised and contingent-liability tests, section VI and Tables 8-9) and, later, the 2027 LIC DSF's. The 2013 MAC DSA's macro-fiscal tests (its Table 3) need judgement on their sizes (planned adjustment, overvaluation) and interactions through new borrowing, and are not a preset yet: build them from Shock and Custom.

ddt2021 classmethod

ddt2021(*, primary_balance: float = -1.0, growth: float = -1.0, interest: float = 1.0, depreciation: float = 1.0, years: tuple[int, int] = (2, 3), window: int = 10, historical: bool = True, constant_primary_balance: bool = True) -> StressTests

The Debt Dynamics Tool's deterministic scenarios (Acosta-Ormaechea and Martinez 2021, section VI.A-C): the historical scenario (from the second projection year), the constant primary balance (the first projection year's, from the second on), and four shocks, one driver at a time, of a multiple of its historical standard deviation (10 years; depreciation over the 9 changes they give): the primary balance, real growth, the interest rates (local- and foreign-currency, each by its own) and the depreciation of the exchange rate (the average rate moving with the end-of-year rate). The default sizes (-1, -1, +1, +1 standard deviations) and years (the second and third projection years) are those of the manual's example inputs (p. 16); the manual leaves both to the user.

add

add(*tests: StressTest) -> StressTests

These tests with tests added at the end.

Plugin plumbing

What pymetrix's plugin loader reads (PLUGIN, register) and the plugin's version.

__version__ module-attribute

__version__ = '0.1.0a1'

PLUGIN module-attribute

PLUGIN = PluginInfo(name='pymetrix-fiscal', version=__version__, license='BSD-3-Clause', maintainer='Geoffrey Heenan', description='Fiscal analysis: deterministic debt sustainability analysis (the debt-dynamics identity, its decompositions, gross financing needs, the debt-stabilising primary balance and stress tests) and cyclically adjusted and structural budget balances', install='pip install -e packages/pymetrix-fiscal')

register

register() -> None

The entry point: the help topic, recorded calls, dialogs, views, menu, workspace, report template and example datasets. Importing the package registers them too; a second call does nothing.