Skip to main content

API Reference

Core: data and configuration

The dataset that passes between steps, configuration, and the registries every component joins.

ENTRY_POINT_GROUP
FINGERPRINT_FORMAT
STEP_NUMBERS
Config

Base class of every configuration: YAML on disk, JSON Schema for tools.

Dataset

A frame of series with their metadata, scenarios and a log of changes.

LogEntry

One change made to the data, with its reason and what it touched.

Registry

Components of one kind, looked up by the key configuration names them by.

SeriesMeta

Metadata of one series (one column of Dataset.frame).

Dataset Methods

Methods for the Dataset class

Dataset.__setattr__()
Dataset.frame

A copy of the data: changing it does not change the dataset.

Dataset.series

Read-only mapping from column name to SeriesMeta, in column order.

Dataset.scenarios

A copy of the scenarios frame, or None.

Dataset.severity

Scenario labels from mildest to most severe; empty without scenarios.

Dataset.log

Every change made to the data, oldest first.

Dataset.columns
Dataset.is_panel

True when indexed by (segment, period).

Dataset.segments

Segment labels in order of appearance; empty for a single-segment dataset.

Dataset.targets
Dataset.drivers
Dataset.fingerprint()

SHA-256 (lowercase hex) of the canonical form of the frame, metadata and scenarios.

Dataset.__repr__()
Dataset.with_frame()

A dataset with new data; metadata is kept for columns still present.

Dataset.with_series()

A dataset with one column’s metadata fields changed.

Dataset.with_scenarios()

A dataset with other scenarios (or none, when scenarios is None).

Dataset.with_log()

A dataset with entry appended to the log.

Dataset.select()

A dataset with only columns, in that order, and their metadata.

Registry Methods

Methods for the Registry class

Registry.kind
Registry.protocol
Registry.register()

Decorator: register the decorated class or function under key.

Registry.add()

Register obj under key; a taken key is refused.

Registry.get()

The component registered under key; UnknownKeyError lists the known keys.

Registry.keys()

Every registered key, sorted.

Registry.__contains__()
Registry.__iter__()
Registry.__len__()
Registry.__repr__()

Core: results, gates and findings

What every step returns: its checks, gate, overrides and finding.

Check

One test: observed <op> threshold passes.

Comparison
Finding

One or two sentences stating a step’s result.

Gate

The checks that end a step. It passes when every check passes or is overridden.

Override

Accepts a failed check, with the reason written in configuration.

StepResult

The shared fields of a step’s result; each step subclasses it with typed values.

Core: artefacts

Tables and figures as data, with stable identifiers.

Artefact
ArtefactIds

The identifiers of one step’s artefacts, fixed by name, not by creation order.

Column

One table column: its key, its plain-language label, its unit and the kind of value.

Figure

A chart for a document, as data: x values, layers, labelled axes, a caption and a source.

Layer

One thing drawn on a figure, against the figure’s shared x values.

Source

Where an artefact’s numbers come from: the run, the data and the date.

Table

A table for a document: labelled columns, rows of plain values, a caption and a source.

Core: errors

Every error dazflow raises is a DazflowError.

ArtefactError

A Table, Figure, Source, Section, Document or artefact identifier is not valid.

BuildError

Candidate models cannot be built as configured (unknown drivers or forms, no data).

CheckError

A data-quality check cannot be evaluated as configured, such as a downturn that cannot be read.

CleanError

The clean step cannot treat the data as configured, such as a treatment naming an unknown period.

ConfigError

A configuration could not be read, parsed or validated.

DatasetError

A Dataset or its metadata is not valid.

DazflowError

Base class of every error raised by dazflow.

DiagnoseError

The chosen model cannot be diagnosed as configured (no model, a back-test, a break).

DuplicateKeyError

A key is already taken in a registry.

EvaluationError

A splitter, metric or rolling-origin evaluation cannot run as configured.

ExploreError

The explore step cannot profile, test or screen the series as configured.

FindingError

A Finding template could not be filled with its values.

ForecastError

The chosen model cannot be forecast as configured (scenarios, horizon or correction).

GateError

A Check, Gate or Override is not valid, such as an override without a reason.

IngestError

The ingest step cannot put its inputs on one calendar as configured.

MissingExtraError

An optional package is not installed; extra names the dazflow extra that has it.

ModelError

A model form cannot be fitted, predicted or refitted as asked, such as missing values or drivers.

PipelineError

A pipeline cannot be built or run as configured, such as an unknown step or order.

PluginError

A dazflow.plugins entry point failed to load.

ProjectError

A project folder cannot be created, read or written, or its run record is missing.

ReaderError

Data could not be read, or its dates could not be put on a calendar.

RecordError

A run record cannot be read, is of another schema version, or does not match its data.

RegistryError

A component could not be registered or looked up.

RenderError

An artefact could not be rendered in the format asked for.

ReportError

A report cannot be built as configured, such as from something that is not a run record.

ResultError

A StepResult is not valid or could not be rebuilt from its dictionary.

SelectError

Candidates cannot be ranked or chosen as configured (benchmark, choice or scenarios).

TransformError

A transform could not be applied or inverted, such as the log of a value that is not positive.

UnknownKeyError

No component is registered under the key; known lists the keys that are.

Readers

Read input files and frames into a dataset’s calendar.

readers.FREQUENCIES
readers.ReadSpec

What to read and how to put its dates on a calendar.

readers.Reader

A data source. Config holds its own options; read returns a Dataset.

readers.ScenarioInput

A CSV of driver paths in levels: a scenario label column, dates and one column per driver.

readers.from_frame()

A Dataset from a pandas or polars frame or a pyarrow table.

readers.get
readers.read()

Read the data spec names into a Dataset with one column per series.

readers.read_scenarios()

The scenario frame, indexed by (scenario, period), and the severity order, from a CSV.

readers.register
readers.registry
readers.require()

Import an optional module, or raise MissingExtraError naming dazflow[extra].

readers.scenario_cover()

How many consecutive periods after end one scenario’s paths (indexed by period) cover.

Quality checks

The checks clean runs; register your own the same way.

checks.CheckConfig

What every check’s configuration holds: whether it runs, where, and its thresholds.

checks.Context

What a check may need beyond the series itself.

checks.Downturn

A period the history must cover, such as a recession, named in configuration.

checks.Level
checks.Outcome

One check on one series: how many units failed, the level reached and the gate check.

checks.QualityCheck

A data-quality check: its Config and the units it tests on one series.

checks.Test
checks.Units

The periods a check tests (the index of values) and what each value must satisfy.

checks.evaluate()

Run one check on one series with pointblank; the series is not changed.

checks.get
checks.outlier_scores()

Robust z-scores of x’s residuals from an STL decomposition, on its present values.

checks.register
checks.registry

Transforms

Named, invertible transforms recorded as text.

transforms.Transform

What a transform provides. Built-ins and plugins are classes registered by key.

transforms.TransformSpec

One transform of a chain: its registry key and its parameters.

transforms.apply()

A dataset with column transformed by chain, the resolved chain appended to its metadata.

transforms.consumed()

How many leading periods a resolved chain leaves without a value.

transforms.forward()

Apply chain to x, in order.

transforms.get
transforms.inverse()

Undo a resolved chain, giving levels on y’s periods.

transforms.parse()

A TransformSpec from its text form; its parameters validated by the transform’s Config.

transforms.register
transforms.registry

Model forms

The model forms, the protocol a new form follows, and the stored model record.

models.DEFAULT_LEVELS
models.RECORD_FORMAT
models.TREND
models.Design

A candidate’s data: target and drivers transformed, drivers lagged, a trend, a sample.

models.Fitted

What a fitted model provides (design §6).

models.FittedModel

Base class of the built-in fitted models.

models.Forecast

A forecast path: the mean and the prediction interval at each level, by period.

models.Model

What a model form provides: its Config and fit(y, X) -> Fitted.

models.ModelForm

Base class of the built-in forms: holds the validated Config, checks the data.

models.ModelRecord

A fitted model as stored: specification, parameters, covariance and data fingerprint.

models.ModelSpec

What a fit needs besides the data: the form, its configuration, the series’ names.

models.Sample

The periods a model was fitted on.

models.fingerprint()

The Dataset fingerprint of the target and drivers, as a record stores it.

models.get
models.newey_west_lags()

The Newey-West rule of thumb, floor(4 (n / 100) ** (2 / 9)).

models.refit()

Fit a model again from its stored specification, on the data it was fitted on.

models.register()

Decorator: register a model form under key, which its specifications name it by.

models.registry
models.season_length()

Periods per year of a monthly (12), quarterly (4) or annual (1) index.

Evaluation

Rolling-origin evaluation: splitters, metrics and scores.

evaluation.DEFAULT_METRICS
evaluation.MAE

Mean absolute error, mean |actual - forecast|.

evaluation.MASE

Mean absolute scaled error (Hyndman and Koehler, 2006).

evaluation.RMSE

Root mean squared error, sqrt(mean (actual - forecast)^2).

evaluation.Coverage

Share of actual values within the interval, bounds included.

evaluation.Evaluation

What evaluate returns: the folds, every forecast value and the scores.

evaluation.EvaluationRow

One forecast value: its fold, origin, period and horizon, the actual and the forecast.

evaluation.Expanding

Origins that train on every period up to them, from initial periods on.

evaluation.Fold

One origin: the training and test positions, each (start, stop), stop excluded.

evaluation.Metric

What a metric provides: its Config and score(actual, forecast, ...) -> float.

evaluation.Rolling

Origins that train on the window periods before them.

evaluation.Score

A metric’s value over every forecast (horizon None) or over one horizon.

evaluation.Splitter

What a splitter provides: its Config and split(index) -> folds.

evaluation.evaluate()

Refit model at every origin of splitter and score its forecasts.

evaluation.metrics
evaluation.splitters

Rendering

House-style tables, figures and Word documents.

render.HOUSE_MPLSTYLE
render.SUFFIXES
render.Captions

Caption and source-note templates (jinja2, as findings are).

render.Dates

How date cells and the source note’s date are written (a strftime format).

render.Document

A model document: a title and sections.

render.Figures

Figures: the font matplotlib draws with, the colours, PNG resolution, an extra mplstyle.

render.Fonts

Text in Word and HTML. Word takes its fonts from Word.reference when one is given.

render.Mark

How one check status is marked in a table.

render.Marks

Pass, fail and overridden, marked in place in words and colour.

render.Numbers

How numbers are written: in tables, and in findings’ numeric values.

render.Page

The text width of the page: tables and figures are laid out to it.

render.Renderable
render.Renderer

Writes artefacts in one format.

render.Section

A headed part of a document: paragraphs of text, findings, tables, figures, subsections.

render.Style

Everything that decides how an artefact looks, in one file per organisation.

render.Word

Word output: the organisation’s reference document and its table style.

render.caption_text()

Table T3.1. Caption, from the style’s caption template.

render.finding_text()

The finding’s sentence, with the style’s template for its key and numbers in the style.

render.format_cell()

One table cell as text: numbers, percentages, dates and statuses in the style.

render.format_date()

An ISO date (or a date) in the style’s date format.

render.format_number()

value with the style’s decimals and separators; a value that rounds to zero has no sign.

render.load_style()

The style to render with.

render.render()

obj in format (a renderer key: docx, html, markdown, png, svg), in the style.

render.renderers

Renderers by format, in a registry like every other component (design §6), and render.

render.source_text()

The source note: the note, the run, the dataset fingerprint and the date.

render.to_great_table()

The table as a great-tables GT, its cells already written in the style.

render.write()

Render obj to the file path, the format from its suffix unless format is given.

Steps

The step registry and the protocol a step follows.

steps.Step

A step module: its configuration, its result type and the function that runs it.

steps.registry

Step: ingest

Read the inputs and put every series on one calendar.

ingest.IDS
ingest.IngestConfig

Configuration of the ingest step.

ingest.IngestResult

What ingest returns. dataset is left out of to_dict(); fingerprint identifies it.

ingest.Input

One input: a file read by a reader, or a frame passed to run under the same name.

ingest.SeriesSpec

One series to take from the inputs, with its metadata and how to align it.

ingest.run()

Read the inputs and put the configured series on one calendar.

Step: clean

Data-quality checks, configured treatments and their log.

clean.IDS
clean.CleanConfig

Configuration of the clean step: one section per check, the treatments, overrides.

clean.CleanResult

What clean returns. dataset is left out of to_dict(); fingerprint identifies it.

clean.Exclude

Exclude periods: their values become missing and no check counts them as missing.

clean.Fill

Fill missing values from the previous or next value, or with a given value.

clean.Interpolate

Fill missing values inside the history linearly between their neighbours.

clean.Replace

Replace values at named periods by value, or linearly from their neighbours.

clean.Treatment
clean.TreatmentRecord

One value changed by a treatment, or a treatment of one series that changed none.

clean.Winsorise

Clip values to the series’ lower and upper quantiles.

clean.run()

Check the data, apply the configured treatments, and check again.

Step: explore

Each series alone, each driver against the target.

explore.IDS
explore.ExploreConfig

Configuration of the explore step.

explore.ExploreResult

What explore returns. dataset (left out of to_dict()) holds the transformed series.

explore.Integration

A series’ order of integration and the levels tested to reach it.

explore.LagProfile

Correlations of the target with a driver lagged 0 to max_lag periods.

explore.Level

The four tests on the series differenced differences times, around trend.

explore.Profile

One series’ profile, on its values from the first to the last present one.

explore.ProfileConfig

How each series is profiled.

explore.Screen

A single-driver regression, target on a constant and the driver at lag.

explore.StationarityConfig

How the four tests are run and read together into an order of integration.

explore.UnitRoot

One test on one level of differencing. stationary reads it at alpha.

explore.driver_checks()

The gate checks of one screened driver, before overrides.

explore.integration_order()

The order of integration of x, from the four tests read together (StationarityConfig).

explore.lag_search()

Correlate y with x lagged 0 to max_lag periods and pick the strongest lag.

explore.newey_west_lags()

The Newey-West (1994) rule of thumb, floor(4 (n / 100)^(2/9)).

explore.profile()

Profile one series: trend and seasonal strength, autocorrelation, volatility, intermittency.

explore.run()

Profile and test every numeric series, transform each, and screen each driver.

explore.says_stationary()

Whether a test’s p-value says stationary at alpha.

explore.screen()

Regress y on a constant and x lagged lag periods, with HAC standard errors.

explore.unit_root()

ADF, DFGLS, Phillips-Perron and KPSS (arch) on x, around a constant or a trend.

Step: build

Candidate models within the declared signs and exclusions.

build.IDS
build.BuildConfig

Configuration of the build step.

build.BuildResult

What build returns: every candidate fitted, and the passing ones.

build.Candidate

One fitted model: its form, drivers, design, stored record and checks.

build.Coefficient

One parameter: estimate, standard error, z and two-sided normal p-value.

build.FormSpec

A model form by registry key, with its configuration (ols or {form: ols, config: ...}).

build.combinations()

Every set of 1 to max_size drivers that holds no excluded pair.

build.run()

Search driver combinations and fit the forms and benchmarks on the series in levels.

build.stepwise()

Forward stepwise search: the sets met adding, each step, the driver that lowers the criterion most.

build.vif()

Variance inflation factors: 1 / (1 - R²) of each column on a constant and the others.

Step: select

Rank the candidates out of sample and propose a default.

select.IDS
select.CandidateEvaluation

A candidate’s rolling-origin evaluation, or why it has none (note).

select.Choice

The modeller’s decision: the proposed candidate confirmed, or another, with a reason.

select.ConfidenceSet

The candidates arch’s MCS keeps at size, in the losses’ column order, and every p-value.

select.MCSConfig

The model confidence set: arch’s MCS on the per-origin losses.

select.OrderingConfig

How projections are compared across scenarios.

select.Ranked

One row of the ranking: scores, set membership and every check select makes.

select.RuleRow

One candidate as the default rule sees it.

select.ScenarioForecast

A candidate’s forecast under one scenario, and its mean path in the target’s levels.

select.SelectConfig

Configuration of the select step.

select.SelectResult

What select returns: the ranking, the confidence set, the scenarios and the choice.

select.confidence_set()

Arch’s model confidence set on losses (one row per origin, one column per model).

select.default_rule()

The default choice (design D38), or None when no passing candidate is in the set.

select.order_check()

The scenario-order check: no pair of successive scenarios out of order.

select.out_of_order()

How many successive scenarios, mildest first, project a less severe target than the one before.

select.read_scenarios()

The scenario frame, indexed by (scenario, period), and the severity order, from a CSV.

select.run()

Score, rank and check every candidate of build, and propose a default.

Step: forecast

The chosen model projected under every scenario.

forecast.IDS
forecast.AnchorConfig

How the gap between observed and fitted at the origin enters the forecast.

forecast.BackTransform

A forecast on the target’s scale and how it got there.

forecast.ForecastConfig

Configuration of the forecast step.

forecast.ForecastResult

What forecast returns: every scenario’s path on the target’s scale, and how it was made.

forecast.ReversionConfig

A linear move towards a long-run level, on the target’s scale.

forecast.ScenarioPath

One scenario: the model’s forecast, anchored, and the forecast on the target’s scale.

forecast.SimulationConfig

The draws of a simulated correction or interval.

forecast.adjustment()

What anchoring adds at horizons 1..h: the gap (carry), gap (1 - decay)^h or nothing.

forecast.back_transform()

forecast (on the model’s scale) on the target’s scale, through the resolved chain.

forecast.revert()

The shift moving path linearly towards level: weight h/periods, full from periods on.

forecast.run()

Forecast select’s chosen model under every scenario, anchored, on the target’s scale.

Step: diagnose

The chosen model tested against its assumptions and against history.

diagnose.IDS
diagnose.Anomaly

An observation outside the interval fitted ± z scale, on the model’s scale.

diagnose.AnomalyConfig

Observations outside the model’s interval.

diagnose.BacktestConfig

Multi-step forecasts from past origins, through dz.evaluation.evaluate.

diagnose.ChowConfig

Chow tests at given break dates, or at fixed fractions of the sample.

diagnose.ChowTest

A Chow test at period: F with df_num and df_denom degrees of freedom.

diagnose.Cusum

The recursive CUSUM (statsmodels RecursiveLS) and its bounds, by period.

diagnose.CusumConfig

The CUSUM tests: the OLS-residual test (a p-value) and the recursive CUSUM’s bounds.

diagnose.DiagnoseConfig

Configuration of the diagnose step.

diagnose.DiagnoseResult

What diagnose returns: every diagnostic, the stability paths, the back-test and the rest.

diagnose.Diagnostic

One diagnostic: its statistic and p-value, what the gate compares, or why it does not apply.

diagnose.LagTest

A p-value test over a number of lags.

diagnose.PValueTest

A test read by its p-value: the check passes when the p-value is at least alpha.

diagnose.ResetConfig

Ramsey’s RESET: powers of the fitted values added to the regression.

diagnose.Rolling

Rolling-window coefficients (statsmodels RollingOLS), by the window’s last period.

diagnose.RollingConfig

Rolling-window coefficients (statsmodels RollingOLS).

diagnose.Sensitivity

One response: to a shock in a driver, or to one driver’s scenario path (all: every one).

diagnose.SensitivityConfig

One-at-a-time sensitivity of the forecast to each driver.

diagnose.anomalies()

The periods where actual lies outside fitted ± z scale, z the normal level quantile.

diagnose.chow()

Chow’s F test of a break at period: every coefficient may change from period on.

diagnose.default_lags()

Twice the seasonal period (10 for annual data), at most a fifth of n (Hyndman).

diagnose.residual_tests()

The residual tests of a fitted model, in a fixed order, each applicable or with its reason.

diagnose.run()

Test select’s chosen model: residuals, stability, back-test, sensitivity and anomalies.

Step: report

The run as a model document, built from the run record alone.

report.IDS
report.TITLES
report.ReplayTolerance

How closely a replay must reproduce each recorded float (design D43).

report.ReportConfig

config/report.yaml: the document’s title and file, and the replay’s tolerance.

report.ReportResult

What report returns: the document and replay script (in memory only) and its tables.

report.replay_script()

The replay script: plain Python that reruns the project from its record and compares.

report.run()

Build the document, its tables and the replay script from a run record.

Pipeline, record and replay

Run steps in order, keep the run record, and replay it.

pipeline.ATOL
pipeline.DEFAULT_STEPS
pipeline.RECORD_KIND
pipeline.RTOL
pipeline.SCHEMA_VERSION
pipeline.Adapter
pipeline.DatasetRecord

A step’s dataset: its fingerprint and, when the project folder holds it, its path.

pipeline.Difference

One recorded value the replay did not reproduce: where it is, and both values.

pipeline.Environment

Where the run ran: Python, platform and the versions of dazflow and its dependencies.

pipeline.InputRecord

One input a run read: a file by the SHA-256 of its bytes, or a frame by its fingerprint.

pipeline.Pipeline

Steps placed by name, run in order, each through its adapter.

pipeline.Replay

What a replay found: the steps rerun, the tolerance and every difference.

pipeline.Run

One pass through a pipeline. Nothing in it has been written anywhere.

pipeline.RunInfo

When the run happened, what it ran and how it ended.

pipeline.RunRecord

The run record, written as reports/record.json.

pipeline.StepInputs

What a step’s adapter has to call the step with.

pipeline.adapters
pipeline.compare()

Every difference between two JSON values, by path.

pipeline.compare_records()

The differences between a record and its replay, inputs first, then in pipeline order.

pipeline.default_adapter()

step.run(dataset, config) with the latest dataset: the common case.

pipeline.environment()

The running environment, with dazflow’s installed version and its requirements’.

pipeline.file_sha256()

The SHA-256 of a file’s bytes; a folder hashes its files’ relative paths and bytes.

pipeline.register_adapter()

Decorator: the function the pipeline calls the step named step through.

pipeline.replay()

Rerun every step of record from its recorded configuration and inputs, and compare.

Project folder

A project on disk: its configuration, datasets and reports.

project.DATASET_FORMAT
project.PROJECT_FILE
project.RECORD_PATH
project.Project

A project folder: project.yaml, config/<step>.yaml, data and reports.

project.ProjectConfig

project.yaml: the project’s name, its pipeline and the settings every step shares.

project.commented_yaml()

config as YAML: every field in declaration order, defaults filled in, described.

project.init()

Create a project in root (new or empty) with commented defaults and example data.

project.load()

The project in folder root.

project.read_dataset()

The dataset write_dataset wrote to path, checked against its fingerprint.

project.schema_path()

The schema file next to a dataset CSV: ingest.csv -> ingest.schema.json.

project.write_dataset()

Write dataset as <path> (CSV, first column period) and its schema file.

Testing

The contract suites every component passes.

testing.ComponentContract

Tests every registered component passes, whatever its kind.

testing.ModelContract

Tests every model form passes (design §6, §13).

testing.sample_series()

A quarterly share between 0 and 1 (loss) and two drivers, for the model contract.