---------------------------------------------------------------------- This is the API documentation for the dazflow library. ---------------------------------------------------------------------- ## Core: data and configuration The dataset that passes between steps, configuration, and the registries every component joins. ENTRY_POINT_GROUP str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'. FINGERPRINT_FORMAT str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'. STEP_NUMBERS dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2) Config() -> None Base class of every configuration: YAML on disk, JSON Schema for tools. Subclasses declare fields as pydantic models do. A config is frozen, refuses unknown fields and refuses non-finite floats, so its YAML, its JSON and its schema agree. Validation errors are `ConfigError`. Examples -------- >>> class SelectConfig(Config): ... metric: str = "rmse" ... tolerance: float = 0.05 >>> SelectConfig.from_yaml("tolerance: 0.1\n").to_yaml() 'metric: rmse\ntolerance: 0.1\n' Dataset(frame: 'pd.DataFrame', series: 'Mapping[str, SeriesMeta | Mapping[str, Any]] | None' = None, *, scenarios: 'pd.DataFrame | None' = None, severity: 'Sequence[str | int] | None' = None, log: 'Iterable[LogEntry]' = ()) -> 'None' A frame of series with their metadata, scenarios and a log of changes. Immutable: the constructor copies `frame` and `scenarios`, the `frame` and `scenarios` properties return copies, and every method returns a new `Dataset`. Nothing changes the caller's objects. Parameters ---------- frame One column per series (string names; float, integer, boolean or string values), indexed by a sorted, unique `pd.PeriodIndex`, or for panels by a ``(segment, period)`` MultiIndex. series `SeriesMeta` per column name; a column without one gets ``SeriesMeta()`` (role ``other``). scenarios Optional future paths: a frame indexed by ``(scenario, period)`` whose columns are dataset columns, at the dataset's frequency. severity The scenario labels from mildest to most severe, each once. Defaults to their order of first appearance. log `LogEntry` records of the changes made so far, oldest first. LogEntry(*, action: Annotated[str, MinLen(min_length=1)], reason: str, rows: tuple[str, ...] = (), columns: tuple[str, ...] = ()) -> None One change made to the data, with its reason and what it touched. `rows` holds the labels of the rows affected, as text (``"2020Q1"``, ``"north/2020Q1"``); `columns` the series affected. Registry(kind: 'str', protocol: 'type | None' = None) -> 'None' Components of one kind, looked up by the key configuration names them by. Components are added with the `register` decorator, or by a third-party package through the ``dazflow.plugins`` entry-point group. Each entry point names a module (``name = package.module``, or ``package.module:attr``); loading it imports the module, whose decorators register its components. Entry points are loaded on the registry's first lookup, once. Parameters ---------- kind : str What the registry holds, for messages: ``"model"``, ``"reader"``. protocol : type, optional Optional `typing.Protocol` every component must have the members of. Examples -------- >>> widgets = Registry("widget") >>> @widgets.register("plain") ... class Plain: ... >>> widgets["plain"] is Plain True SeriesMeta(*, role: Literal['target', 'driver', 'other'] = 'other', unit: str | None = None, frequency: str | None = None, source: str | None = None, transforms: tuple[str, ...] = (), expected_sign: Optional[Literal[-1, 0, 1]] = None) -> None Metadata of one series (one column of `Dataset.frame`). `transforms` is the transformation chain applied so far, oldest first. `expected_sign` is the sign a driver's coefficient is expected to have. ## Dataset Methods Methods for the Dataset class __setattr__(self, name: 'str', value: 'Any') -> 'None' frame A copy of the data: changing it does not change the dataset. series Read-only mapping from column name to `SeriesMeta`, in column order. scenarios A copy of the scenarios frame, or None. severity Scenario labels from mildest to most severe; empty without scenarios. log Every change made to the data, oldest first. columns is_panel True when indexed by ``(segment, period)``. segments Segment labels in order of appearance; empty for a single-segment dataset. targets drivers fingerprint(self) -> 'str' SHA-256 (lowercase hex) of the canonical form of the frame, metadata and scenarios. The canonical form is fixed in design §5.1 (format ``dazflow.dataset/1``) and does not depend on the platform, the Python version or the pandas and numpy versions. The log is not part of it. __repr__(self) -> 'str' with_frame(self, frame: 'pd.DataFrame', *, entry: 'LogEntry | None' = None) -> 'Dataset' A dataset with new data; metadata is kept for columns still present. New columns get ``SeriesMeta()``. `entry`, when given, is appended to the log. with_series(self, column: 'str', **changes: 'Any') -> 'Dataset' A dataset with one column's metadata fields changed. with_scenarios(self, scenarios: 'pd.DataFrame | None', severity: 'Sequence[str | int] | None' = None) -> 'Dataset' A dataset with other scenarios (or none, when `scenarios` is None). with_log(self, entry: 'LogEntry') -> 'Dataset' A dataset with `entry` appended to the log. select(self, columns: 'Sequence[str]') -> 'Dataset' A dataset with only `columns`, in that order, and their metadata. Scenarios keep only the selected columns. ## Registry Methods Methods for the Registry class kind protocol register(self, key: 'str') -> 'Callable[[T], T]' Decorator: register the decorated class or function under `key`. add(self, key: 'str', obj: 'Any') -> 'None' Register `obj` under `key`; a taken key is refused. get(self, key: 'str') -> 'Any' The component registered under `key`; `UnknownKeyError` lists the known keys. keys(self) -> 'tuple[str, ...]' Every registered key, sorted. __contains__(self, key: 'object') -> 'bool' __iter__(self) -> 'Iterator[str]' __len__(self) -> 'int' __repr__(self) -> 'str' ## Core: results, gates and findings What every step returns: its checks, gate, overrides and finding. Check(*, name: Annotated[str, MinLen(min_length=1)], observed: float, threshold: Annotated[float, AllowInfNan(allow_inf_nan=False)], op: Literal['<', '<=', '>', '>='], unit: str | None = None, override: dazflow.core.gate.Override | None = None) -> None One test: `observed threshold` passes. A missing (NaN) observed value fails. The threshold must be finite. Literal(*args, **kwargs) Finding(*, template: str, values: dict[str, bool | int | float | str] = , key: str | None = None) -> None One or two sentences stating a step's result. `template` is jinja2 text; `values` fills its fields. The values are booleans, integers, finite floats or strings, so a finding is JSON-safe. The text is rendered, and checked, when the finding is made. `text` shows the values as given; `dazflow.render` formats the numbers in the house style, and a style can replace the template of a finding that has a `key`. Examples -------- >>> Finding(template="{{ n }} of {{ total }} checks pass.", values={"n": 3, "total": 4}).text '3 of 4 checks pass.' Gate(*, checks: tuple[dazflow.core.gate.Check, ...] = ()) -> None The checks that end a step. It passes when every check passes or is overridden. Override(*, check: Annotated[str, MinLen(min_length=1)], reason: str) -> None Accepts a failed check, with the reason written in configuration. A reason is required: an empty or blank one is refused with a `GateError`. StepResult(*, gate: dazflow.core.gate.Gate = , finding: dazflow.core.finding.Finding | None = None, artefacts: dict[str, typing.Annotated[typing.Union[typing.Annotated[dazflow.core.artefact.Table, Tag(tag='table')], typing.Annotated[dazflow.core.artefact.Figure, Tag(tag='figure')], typing.Annotated[dazflow.core.finding.Finding, Tag(tag='finding')]], Discriminator(discriminator=, custom_error_type=None, custom_error_message=None, custom_error_context=None)]] = , config: dazflow.core.config.Config | None = None) -> None The shared fields of a step's result; each step subclasses it with typed values. A subclass narrows `config` to its step's `Config` subclass and adds its own fields. `to_dict()` gives strict JSON (non-finite floats become the strings ``"NaN"``, ``"Infinity"`` and ``"-Infinity"``), and `from_dict()` on the same subclass rebuilds an equal result. ## Core: artefacts Tables and figures as data, with stable identifiers. Annotated(*args, **kwargs) Runtime representation of an annotated type. At its core 'Annotated[t, dec1, dec2, ...]' is an alias for the type 't' with extra annotations. The alias behaves like a normal typing alias. Instantiating is the same as instantiating the underlying type; binding it to types is also the same. The metadata itself is stored in a '__metadata__' attribute as a tuple. ArtefactIds(step: 'str | int', *, tables: 'Mapping[str, int] | None' = None, figures: 'Mapping[str, int] | None' = None, findings: 'Mapping[str, int] | None' = None) -> 'None' The identifiers of one step's artefacts, fixed by name, not by creation order. Each artefact a step can make is declared once with its number, so ``T3.2`` stays the stationarity table on every rerun, whatever order the step builds its artefacts in and whichever of them it builds. Add a new artefact under a new number; never renumber one, or documents written earlier point at the wrong table. Parameters ---------- step A step name from `STEP_NUMBERS` (``"explore"``), or a positive number for a step outside the built-in ones. tables, figures, findings Name to number, each number positive and used once per kind. Examples -------- >>> ids = ArtefactIds("explore", tables={"summary": 1, "stationarity": 2}) >>> ids.table("stationarity") 'T3.2' Column(*, name: Annotated[str, MinLen(min_length=1)], label: Annotated[str, MinLen(min_length=1)], unit: str | None = None, kind: Literal['number', 'integer', 'percent', 'text', 'date', 'status'] = 'number') -> None One table column: its key, its plain-language label, its unit and the kind of value. Kinds: ``number`` (decimals from the style), ``integer``, ``percent`` (a fraction, shown times 100), ``text``, ``date`` (ISO ``YYYY-MM-DD``) and ``status`` (``pass``, ``fail`` or ``overridden``, marked in place). Figure(*, kind: Literal['figure'] = 'figure', id: str, caption: str, x: tuple[typing.Any, ...] = (), layers: tuple[dazflow.core.artefact.Layer, ...], x_label: str = '', y_label: str = '', x_unit: str | None = None, y_unit: str | None = None, aspect: Annotated[float, Ge(ge=0.2), Le(le=2.0)] = 0.5, notes: tuple[str, ...] = (), source: dazflow.core.artefact.Source | None = None) -> None A chart for a document, as data: x values, layers, labelled axes, a caption and a source. `x` holds numbers or labels (periods as ``2024Q1``), shared by every layer. The style draws it at the page width; `aspect` is height over width. Layer(*, kind: Literal['line', 'scatter', 'bar', 'band', 'hline'], y: tuple[typing.Optional[typing.Annotated[float, AllowInfNan(allow_inf_nan=False)]], ...] = (), y_low: tuple[typing.Optional[typing.Annotated[float, AllowInfNan(allow_inf_nan=False)]], ...] = (), y_high: tuple[typing.Optional[typing.Annotated[float, AllowInfNan(allow_inf_nan=False)]], ...] = (), value: Optional[Annotated[float, AllowInfNan(allow_inf_nan=False)]] = None, label: str | None = None) -> None One thing drawn on a figure, against the figure's shared x values. ``line``, ``scatter`` and ``bar`` take `y`; ``band`` takes `y_low` and `y_high` (a shaded interval); ``hline`` takes `value` (a reference line). ``None`` in `y` leaves a gap. Source(*, run_id: Annotated[str, MinLen(min_length=1)], fingerprint: Annotated[str, _PydanticGeneralMetadata(pattern='^[0-9a-f]{64}$')], date: datetime.date, note: str | None = None) -> None Where an artefact's numbers come from: the run, the data and the date. Every source note in a document is written from one of these. Table(*, kind: Literal['table'] = 'table', id: str, caption: str, columns: tuple[dazflow.core.artefact.Column, ...], rows: tuple[tuple[typing.Any, ...], ...] = (), notes: tuple[str, ...] = (), source: dazflow.core.artefact.Source | None = None) -> None A table for a document: labelled columns, rows of plain values, a caption and a source. Values are stored unformatted; the style formats them when the table is rendered, so one style setting changes every table. A missing value is ``None``. A ``status`` column marks pass or fail in place. Examples -------- >>> t = Table(id="T3.1", caption="Means", ... columns=[Column(name="x", label="Mean", unit="pp")], rows=[[1.25]]) >>> t.columns[0].heading 'Mean (pp)' ## Core: errors Every error dazflow raises is a `DazflowError`. ArtefactError(problem: 'str', *, observed: 'str', change: 'str') -> 'None' A `Table`, `Figure`, `Source`, `Section`, `Document` or artefact identifier is not valid. BuildError(problem: 'str', *, observed: 'str', change: 'str') -> 'None' Candidate models cannot be built as configured (unknown drivers or forms, no data). CheckError(problem: 'str', *, observed: 'str', change: 'str') -> 'None' A data-quality check cannot be evaluated as configured, such as a downturn that cannot be read. CleanError(problem: 'str', *, observed: 'str', change: 'str') -> 'None' The clean step cannot treat the data as configured, such as a treatment naming an unknown period. ConfigError(problem: 'str', *, observed: 'str', change: 'str') -> 'None' A configuration could not be read, parsed or validated. DatasetError(problem: 'str', *, observed: 'str', change: 'str') -> 'None' A `Dataset` or its metadata is not valid. DazflowError(problem: 'str', *, observed: 'str', change: 'str') -> 'None' Base class of every error raised by dazflow. Parameters ---------- problem What went wrong, as a lower-case clause. observed The state that was found: the value, the shape, the keys present. change What the caller should change, as an instruction. DiagnoseError(problem: 'str', *, observed: 'str', change: 'str') -> 'None' The chosen model cannot be diagnosed as configured (no model, a back-test, a break). DuplicateKeyError(problem: 'str', *, observed: 'str', change: 'str') -> 'None' A key is already taken in a registry. EvaluationError(problem: 'str', *, observed: 'str', change: 'str') -> 'None' A splitter, metric or rolling-origin evaluation cannot run as configured. ExploreError(problem: 'str', *, observed: 'str', change: 'str') -> 'None' The explore step cannot profile, test or screen the series as configured. FindingError(problem: 'str', *, observed: 'str', change: 'str') -> 'None' A `Finding` template could not be filled with its values. ForecastError(problem: 'str', *, observed: 'str', change: 'str') -> 'None' The chosen model cannot be forecast as configured (scenarios, horizon or correction). GateError(problem: 'str', *, observed: 'str', change: 'str') -> 'None' A `Check`, `Gate` or `Override` is not valid, such as an override without a reason. IngestError(problem: 'str', *, observed: 'str', change: 'str') -> 'None' The ingest step cannot put its inputs on one calendar as configured. MissingExtraError(what: 'str', module: 'str', extra: 'str') -> 'None' An optional package is not installed; `extra` names the ``dazflow`` extra that has it. ModelError(problem: 'str', *, observed: 'str', change: 'str') -> 'None' A model form cannot be fitted, predicted or refitted as asked, such as missing values or drivers. PipelineError(problem: 'str', *, observed: 'str', change: 'str') -> 'None' A pipeline cannot be built or run as configured, such as an unknown step or order. PluginError(problem: 'str', *, observed: 'str', change: 'str') -> 'None' A `dazflow.plugins` entry point failed to load. ProjectError(problem: 'str', *, observed: 'str', change: 'str') -> 'None' A project folder cannot be created, read or written, or its run record is missing. ReaderError(problem: 'str', *, observed: 'str', change: 'str') -> 'None' Data could not be read, or its dates could not be put on a calendar. RecordError(problem: 'str', *, observed: 'str', change: 'str') -> 'None' A run record cannot be read, is of another schema version, or does not match its data. RegistryError(problem: 'str', *, observed: 'str', change: 'str') -> 'None' A component could not be registered or looked up. RenderError(problem: 'str', *, observed: 'str', change: 'str') -> 'None' An artefact could not be rendered in the format asked for. ReportError(problem: 'str', *, observed: 'str', change: 'str') -> 'None' A report cannot be built as configured, such as from something that is not a run record. ResultError(problem: 'str', *, observed: 'str', change: 'str') -> 'None' A `StepResult` is not valid or could not be rebuilt from its dictionary. SelectError(problem: 'str', *, observed: 'str', change: 'str') -> 'None' Candidates cannot be ranked or chosen as configured (benchmark, choice or scenarios). TransformError(problem: 'str', *, observed: 'str', change: 'str', series: 'str | None' = None, period: 'str | None' = None) -> 'None' A transform could not be applied or inverted, such as the log of a value that is not positive. `series` and `period` name the first value outside the transform's domain, when there is one. UnknownKeyError(kind: 'str', key: 'object', known: 'tuple[str, ...]') -> 'None' 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 dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2) ReadSpec(*, reader: str | None = None, path: str | None = None, date: str | None = None, frequency: Optional[Literal['M', 'Q', 'Y']] = None, columns: list[str] | None = None, options: dict[str, str | int | float | bool | None] = ) -> None What to read and how to put its dates on a calendar. The first column holds the dates unless `date` names another (a frame indexed by periods or dates uses its index). Every other column is a series, or only `columns` when given. `options` go to the reader's own `Config` (``sep`` for csv, ``sheet`` for excel). Reader(*args, **kwargs) A data source. `Config` holds its own options; `read` returns a `Dataset`. ScenarioInput(*, path: Annotated[str, MinLen(min_length=1)], scenario: str = 'scenario', date: str | None = None, frequency: Optional[Literal['M', 'Q', 'Y']] = None, severity: list[str] | None = None) -> None A CSV of driver paths in levels: a scenario label column, dates and one column per driver. from_frame(obj: 'Any', *, date: 'str | None' = None, frequency: 'str | None' = None, columns: 'Sequence[str] | None' = None, source: 'str | None' = None) -> 'Dataset' A `Dataset` from a pandas or polars frame or a pyarrow table. Non-pandas input is converted through narwhals. The dates are the `date` column, else the index when it holds periods or dates, else the first column. `source`, when given, is recorded in each series' metadata. get(key: 'str') -> 'Any' The component registered under `key`; `UnknownKeyError` lists the known keys. read(spec: 'ReadSpec | Mapping[str, Any]') -> 'Dataset' Read the data `spec` names into a `Dataset` with one column per series. read_scenarios(spec: 'ScenarioInput', root: 'str | Path | None' = None) -> 'tuple[pd.DataFrame, list]' The scenario frame, indexed by ``(scenario, period)``, and the severity order, from a CSV. A relative path is read from `root` (the working directory by default). A missing file, label column or row is a `ReaderError`. register(key: 'str') -> 'Callable[[T], T]' Decorator: register the decorated class or function under `key`. readers.registry Components of one kind, looked up by the key configuration names them by. Components are added with the `register` decorator, or by a third-party package through the ``dazflow.plugins`` entry-point group. Each entry point names a module (``name = package.module``, or ``package.module:attr``); loading it imports the module, whose decorators register its components. Entry points are loaded on the registry's first lookup, once. Parameters ---------- kind : str What the registry holds, for messages: ``"model"``, ``"reader"``. protocol : type, optional Optional `typing.Protocol` every component must have the members of. Examples -------- >>> widgets = Registry("widget") >>> @widgets.register("plain") ... class Plain: ... >>> widgets["plain"] is Plain True require(module: 'str', what: 'str', extra: 'str' = 'io') -> 'Any' Import an optional `module`, or raise `MissingExtraError` naming ``dazflow[extra]``. scenario_cover(paths: 'pd.DataFrame', end: 'pd.Period') -> 'int' How many consecutive periods after `end` one scenario's `paths` (indexed by period) cover. The count stops at the first missing period. Select, forecast and diagnose forecast every scenario over the smallest cover among them (design §7.6, §7.7, D49). ## Quality checks The checks clean runs; register your own the same way. CheckConfig(*, enabled: bool = True, columns: list[str] | None = None, warning: float | None = None, error: float = 1, critical: float | None = None) -> None What every check's configuration holds: whether it runs, where, and its thresholds. A threshold below 1 is a share of the check's test units, 1 or more a count of them (pointblank's rule); a level is reached when the failing units reach it. The gate check fails at `error`. Context(frequency: 'str | None' = None, role: 'str' = 'other', previous: 'pd.Series | None' = None, excluded: 'frozenset[pd.Period]' = ) -> None What a check may need beyond the series itself. `frequency` is ``"M"``, ``"Q"`` or ``"Y"`` (read from the index when unset); `role` the series' role; `previous` the same series in the previous vintage; `excluded` the periods a treatment excluded, which no check counts against the series. Downturn(*, label: Annotated[str, MinLen(min_length=1)], start: Annotated[str, MinLen(min_length=1)], end: Annotated[str, MinLen(min_length=1)]) -> None A period the history must cover, such as a recession, named in configuration. Literal(*args, **kwargs) Outcome(*, key: str, column: str, measure: str = 'value', units: int = 0, failed: int = 0, share: float = 0.0, level: Literal['none', 'warning', 'error', 'critical'] = 'none', flagged: tuple[str, ...] = (), check: dazflow.core.gate.Check | None = None, reason: str | None = None) -> None One check on one series: how many units failed, the level reached and the gate check. `check` is ``None`` when the check does not apply (`reason` says why). `flagged` lists the failing periods as text (``"2020Q1"``). QualityCheck(*args, **kwargs) A data-quality check: its `Config` and the units it tests on one series. `units` receives the series (a float `pd.Series` on a `PeriodIndex`, named after the column), its validated `Config` and a `Context`. Literal(*args, **kwargs) Units(values: 'pd.Series', test: 'Test' = 'not_null', bound: 'float | None' = None, upper: 'float | None' = None, measure: 'str' = 'value', reason: 'str | None' = None) -> None The periods a check tests (the index of `values`) and what each value must satisfy. `test` is ``not_null``; ``between`` (`bound` and `upper` inclusive; a ``None`` side is open); ``at_most`` (``value <= bound``); or ``above`` (``value > bound``). `measure` says what `values` holds, for the report. When `reason` is set the check does not apply and nothing is tested. evaluate(check: 'str | QualityCheck', x: 'pd.Series', config: 'CheckConfig | Mapping[str, Any] | None' = None, context: 'Context | None' = None) -> 'Outcome' Run one check on one series with pointblank; the series is not changed. `check` is a registry key or a check object. The gate check is named ``:`` and passes while the failing units stay below `error`, counted as periods or, for a threshold below 1, as a share. get(key: 'str') -> 'Any' The component registered under `key`; `UnknownKeyError` lists the known keys. outlier_scores(x: 'pd.Series', frequency: 'str | None' = None, *, z: 'float' = 4.0, seasonal: 'int' = 13, trend: 'int | None' = None, max_iter: 'int' = 20) -> 'pd.Series' Robust z-scores of `x`'s residuals from an STL decomposition, on its present values. Monthly and quarterly series are decomposed by statsmodels' `STL` (seasonal smoother of `seasonal` years, local-constant); annual series, which have no season, by a `lowess` trend over `trend` years (default 21). The residuals are standardised by their median and MAD (1.4826 MAD, the standard deviation for normal residuals). A first, robust fit finds the gross outliers; then each flagged period is replaced by its fitted value and the series decomposed again without robustness weights, until the flagged set is stable, so a spike does not bend the fit around itself (D29). Missing values inside the history are interpolated for the fit and get no score. Raises `CheckError` when the series has fewer than two years from its first to its last value (seven for annual data). register(key: 'str') -> 'Callable[[T], T]' Decorator: register the decorated class or function under `key`. checks.registry Components of one kind, looked up by the key configuration names them by. Components are added with the `register` decorator, or by a third-party package through the ``dazflow.plugins`` entry-point group. Each entry point names a module (``name = package.module``, or ``package.module:attr``); loading it imports the module, whose decorators register its components. Entry points are loaded on the registry's first lookup, once. Parameters ---------- kind : str What the registry holds, for messages: ``"model"``, ``"reader"``. protocol : type, optional Optional `typing.Protocol` every component must have the members of. Examples -------- >>> widgets = Registry("widget") >>> @widgets.register("plain") ... class Plain: ... >>> widgets["plain"] is Plain True ## Transforms Named, invertible transforms recorded as text. Transform(*args, **kwargs) What a transform provides. Built-ins and plugins are classes registered by key. Each method receives the series (a float `pd.Series` on a `PeriodIndex`, named after the column) and the transform's validated `Config`. TransformSpec(*, key: str, params: dict[str, int | float | None] = ) -> None One transform of a chain: its registry key and its parameters. ``str(spec)`` is the text form recorded in `SeriesMeta.transforms`: the key, then the parameters in their declared order, leaving out any that are unset (``None``). apply(dataset: 'Dataset', column: 'str', chain: 'Sequence[str | TransformSpec] | str | TransformSpec') -> 'Dataset' A dataset with `column` transformed by `chain`, the resolved chain appended to its metadata. The change is logged. Invert later with ``inverse(values, dataset.series[column].transforms, history=levels)``. consumed(chain: 'Sequence[str | TransformSpec] | str | TransformSpec') -> 'int' How many leading periods a resolved chain leaves without a value. forward(x: 'pd.Series', chain: 'Sequence[str | TransformSpec] | str | TransformSpec') -> 'tuple[pd.Series, tuple[TransformSpec, ...]]' Apply `chain` to `x`, in order. Returns the transformed series and the chain with every parameter resolved: record that one, it is what `inverse` takes. Missing values stay missing; a value outside a transform's domain raises `TransformError` naming the series and the period. get(key: 'str') -> 'Any' The component registered under `key`; `UnknownKeyError` lists the known keys. inverse(y: 'pd.Series', chain: 'Sequence[str | TransformSpec] | str | TransformSpec', history: 'pd.Series | None' = None) -> 'pd.Series' Undo a resolved `chain`, giving levels on `y`'s periods. `history` is the untransformed series for the periods before (or overlapping) `y`: lagged transforms rebuild each level from the one `lag` periods earlier, taken from `history` where it has a value. For an in-sample round trip it is the first `consumed(chain)` values; for a forecast, the observed series. parse(text: 'str | TransformSpec') -> 'TransformSpec' A `TransformSpec` from its text form; its parameters validated by the transform's `Config`. register(key: 'str') -> 'Callable[[T], T]' Decorator: register the decorated class or function under `key`. transforms.registry Components of one kind, looked up by the key configuration names them by. Components are added with the `register` decorator, or by a third-party package through the ``dazflow.plugins`` entry-point group. Each entry point names a module (``name = package.module``, or ``package.module:attr``); loading it imports the module, whose decorators register its components. Entry points are loaded on the registry's first lookup, once. Parameters ---------- kind : str What the registry holds, for messages: ``"model"``, ``"reader"``. protocol : type, optional Optional `typing.Protocol` every component must have the members of. Examples -------- >>> widgets = Registry("widget") >>> @widgets.register("plain") ... class Plain: ... >>> widgets["plain"] is Plain True ## Model forms The model forms, the protocol a new form follows, and the stored model record. models.DEFAULT_LEVELS Built-in immutable sequence. If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items. If the argument is a tuple, the return value is the same object. models.RECORD_FORMAT int([x]) -> integer int(x, base=10) -> integer Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating-point numbers, this truncates towards zero. If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer iteral. >>> int('0b100', base=0) 4 models.TREND str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'. Design(*, target: str, drivers: tuple[str, ...] = (), lags: dict[str, typing.Annotated[int, FieldInfo(annotation=NoneType, required=True, metadata=[Ge(ge=0)])]] = , chains: dict[str, tuple[str, ...]] = , trend: bool = False, trend_start: str | None = None, start: str, end: str) -> None A candidate's data: target and drivers transformed, drivers lagged, a trend, a sample. `chains` holds each series' resolved transform chain (as explore recorded it in `SeriesMeta.transforms`), applied to the levels by `dazflow.transforms.forward`; a series without one is used as it is. `lags[d]` shifts driver `d` by that many periods. With `trend`, a column ``trend`` counts periods from `trend_start` (1 there), so it extends past the sample unchanged. `start` and `end` are the sample's first and last periods. Fitted(*args, **kwargs) What a fitted model provides (design §6). FittedModel(spec: 'ModelSpec', y: 'pd.Series', X: 'pd.DataFrame | None', *, params: 'pd.Series', cov_params: 'pd.DataFrame', fitted_values: 'pd.Series', notes: 'Sequence[str]' = ()) -> 'None' Base class of the built-in fitted models. Holds the specification, the parameters, their covariance, the in-sample fitted values and residuals (``y - fitted``, on the target's scale) and the data fingerprint. A subclass implements `_predict`. Forecast(*, form: str, frequency: str, periods: tuple[str, ...], mean: tuple[float, ...], levels: tuple[float, ...] = (), lower: tuple[tuple[float, ...], ...] = (), upper: tuple[tuple[float, ...], ...] = ()) -> None A forecast path: the mean and the prediction interval at each level, by period. `lower[i]` and `upper[i]` are the bounds at `levels[i]`, a central interval holding that probability. Periods are written as text (``"2024Q1"``) at `frequency`; `frame()` gives the pandas form. Model(*args, **kwargs) What a model form provides: its `Config` and ``fit(y, X) -> Fitted``. A form is a class built from its configuration, ``Form(config)`` or ``Form(**params)``; `ModelForm` is a base class that does this. ModelForm(config: 'Config | dict[str, Any] | None' = None, /, **params: 'Any') -> 'None' Base class of the built-in forms: holds the validated `Config`, checks the data. A subclass sets `Config`, `drivers` (whether it takes driver series) and `_fit(y, X, spec) -> FittedModel`. ModelRecord(*, kind: Literal['dazflow.model'] = 'dazflow.model', format: Literal[1] = 1, spec: dazflow.models._base.ModelSpec, sample: dazflow.models._base.Sample, data: str, params: dict[str, float], cov_params: tuple[tuple[float, ...], ...]) -> None A fitted model as stored: specification, parameters, covariance and data fingerprint. The format (``kind: dazflow.model``, ``format: 1``) is fixed in design §5.3. `params` keeps the form's order; `cov_params` is the covariance matrix in that order, row by row. `data` is the `Dataset` fingerprint of the target and drivers fitted on (design §5.1.1), checked by `refit`. ModelSpec(*, form: str, config: dict[str, typing.Any] = , target: str, drivers: tuple[str, ...] = ()) -> None What a fit needs besides the data: the form, its configuration, the series' names. `config` holds the form's `Config` with every default filled in, as `model_dump(mode="json")` writes it, so it rebuilds the same form. Sample(*, start: str, end: str, observations: int, frequency: str) -> None The periods a model was fitted on. fingerprint(y: 'pd.Series', X: 'pd.DataFrame | None') -> 'str' The `Dataset` fingerprint of the target and drivers, as a record stores it. get(key: 'str') -> 'Any' The component registered under `key`; `UnknownKeyError` lists the known keys. newey_west_lags(n: 'int') -> 'int' The Newey-West rule of thumb, ``floor(4 (n / 100) ** (2 / 9))``. refit(record: 'ModelRecord | dict[str, Any]', y: 'pd.Series', X: 'pd.DataFrame | None' = None, *, tolerance: 'float | None' = None, registry: 'Registry | None' = None) -> 'Fitted' Fit a model again from its stored specification, on the data it was fitted on. The data must have the record's fingerprint (`ModelError` otherwise). With `tolerance`, the refitted parameters must also be within it of the stored ones, in absolute value. `registry` is where the form is looked up, `dazflow.models.registry` by default. register(key: 'str') -> 'Callable[[T], T]' Decorator: register a model form under `key`, which its specifications name it by. models.registry Components of one kind, looked up by the key configuration names them by. Components are added with the `register` decorator, or by a third-party package through the ``dazflow.plugins`` entry-point group. Each entry point names a module (``name = package.module``, or ``package.module:attr``); loading it imports the module, whose decorators register its components. Entry points are loaded on the registry's first lookup, once. Parameters ---------- kind : str What the registry holds, for messages: ``"model"``, ``"reader"``. protocol : type, optional Optional `typing.Protocol` every component must have the members of. Examples -------- >>> widgets = Registry("widget") >>> @widgets.register("plain") ... class Plain: ... >>> widgets["plain"] is Plain True season_length(index: 'pd.PeriodIndex') -> 'int' Periods per year of a monthly (12), quarterly (4) or annual (1) index. ## Evaluation Rolling-origin evaluation: splitters, metrics and scores. evaluation.DEFAULT_METRICS Built-in immutable sequence. If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items. If the argument is a tuple, the return value is the same object. MAE(config: 'Config | dict[str, Any] | None' = None, /, **params: 'Any') -> 'None' Mean absolute error, ``mean |actual - forecast|``. MASE(config: 'Config | dict[str, Any] | None' = None, /, **params: 'Any') -> 'None' Mean absolute scaled error (Hyndman and Koehler, 2006). Each error is divided by the in-sample mean absolute error of the (seasonal) naive forecast on the training series, ``mean |train[t] - train[t - season]|``. `scale` gives that value, one for all points or one per point (each fold its own); `train` computes it. RMSE(config: 'Config | dict[str, Any] | None' = None, /, **params: 'Any') -> 'None' Root mean squared error, ``sqrt(mean (actual - forecast)^2)``. Coverage(config: 'Config | dict[str, Any] | None' = None, /, **params: 'Any') -> 'None' Share of actual values within the interval, bounds included. Compare it with the interval's `level`: a well-calibrated 95% interval covers about 0.95 of the actual values. Evaluation(*, spec: dazflow.models._base.ModelSpec, splitter: str, splitter_config: dict[str, typing.Any], levels: tuple[float, ...], folds: tuple[dazflow.evaluation._base.Fold, ...], rows: tuple[dazflow.evaluation._rolling.EvaluationRow, ...], scores: tuple[dazflow.evaluation._rolling.Score, ...]) -> None What `evaluate` returns: the folds, every forecast value and the scores. `scores` holds each metric over all rows first (``horizon: null``), then by horizon 1, 2, ... Every value is data; `frame()` gives the rows as a pandas frame. EvaluationRow(*, fold: int, origin: str, period: str, horizon: int, actual: float, forecast: float, lower: tuple[float, ...] = (), upper: tuple[float, ...] = ()) -> None One forecast value: its fold, origin, period and horizon, the actual and the forecast. `lower[i]` and `upper[i]` are the bounds at the evaluation's `levels[i]`. Expanding(config: 'Config | dict[str, Any] | None' = None, /, **params: 'Any') -> 'None' Origins that train on every period up to them, from `initial` periods on. Every fold tests `horizon` periods; the last test period is the last period of the series, and origins are `step` apart. Fold(*, number: int, train: tuple[int, int], test: tuple[int, int]) -> None One origin: the training and test positions, each ``(start, stop)``, stop excluded. `origin` is the last training position, the period a forecast is made from. Metric(*args, **kwargs) What a metric provides: its `Config` and ``score(actual, forecast, ...) -> float``. Keywords a metric does not use are ignored: `scale` (one value, or one per point) or `train` for scaled errors, `lower` and `upper` for interval metrics. Rolling(config: 'Config | dict[str, Any] | None' = None, /, **params: 'Any') -> 'None' Origins that train on the `window` periods before them. Score(*, metric: str, config: dict[str, typing.Any], horizon: int | None, value: float) -> None A metric's value over every forecast (`horizon` None) or over one horizon. Splitter(*args, **kwargs) What a splitter provides: its `Config` and ``split(index) -> folds``. evaluate(model: 'Any', y: 'pd.Series', X: 'pd.DataFrame | None' = None, *, splitter: 'Any' = None, metrics: 'Sequence[Any]' = ('mae', 'rmse', 'mase', 'coverage'), levels: 'Sequence[float]' = (0.8, 0.95)) -> 'Evaluation' Refit `model` at every origin of `splitter` and score its forecasts. Parameters ---------- model A model form (``models.get("ols")()``), its key, or a `ModelSpec`. y, X The target and the drivers, as `fit` takes them. The forecast at each origin uses the drivers' actual values over the test periods. splitter A splitter, or its key; default ``expanding`` with one-step folds. metrics Metrics or their keys. MASE divides each fold's errors by that fold's training scale; coverage scores the interval at its `level`, which must be among `levels`. levels The interval levels forecast at every origin. evaluation.metrics Components of one kind, looked up by the key configuration names them by. Components are added with the `register` decorator, or by a third-party package through the ``dazflow.plugins`` entry-point group. Each entry point names a module (``name = package.module``, or ``package.module:attr``); loading it imports the module, whose decorators register its components. Entry points are loaded on the registry's first lookup, once. Parameters ---------- kind : str What the registry holds, for messages: ``"model"``, ``"reader"``. protocol : type, optional Optional `typing.Protocol` every component must have the members of. Examples -------- >>> widgets = Registry("widget") >>> @widgets.register("plain") ... class Plain: ... >>> widgets["plain"] is Plain True evaluation.splitters Components of one kind, looked up by the key configuration names them by. Components are added with the `register` decorator, or by a third-party package through the ``dazflow.plugins`` entry-point group. Each entry point names a module (``name = package.module``, or ``package.module:attr``); loading it imports the module, whose decorators register its components. Entry points are loaded on the registry's first lookup, once. Parameters ---------- kind : str What the registry holds, for messages: ``"model"``, ``"reader"``. protocol : type, optional Optional `typing.Protocol` every component must have the members of. Examples -------- >>> widgets = Registry("widget") >>> @widgets.register("plain") ... class Plain: ... >>> widgets["plain"] is Plain True ## Rendering House-style tables, figures and Word documents. render.HOUSE_MPLSTYLE str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'. render.SUFFIXES dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2) Captions(*, table: str = 'Table {{ id }}. {{ caption }}', figure: str = 'Figure {{ id }}. {{ caption }}', source: str = 'Source: {% if note %}{{ note }}; {% endif %}run {{ run_id }}, data {{ fingerprint }}, {{ date }}.', fingerprint_digits: Annotated[int, Ge(ge=4), Le(le=64)] = 12) -> None Caption and source-note templates (jinja2, as findings are). Dates(*, format: Annotated[str, MinLen(min_length=1)] = '%Y-%m-%d') -> None How date cells and the source note's date are written (a `strftime` format). Document(*, title: Annotated[str, MinLen(min_length=1)], sections: tuple[dazflow.render.document.Section, ...] = (), source: dazflow.core.artefact.Source | None = None) -> None A model document: a title and sections. `source` fills the source note of every table and figure that has none. Figures(*, font: str = 'DejaVu Sans', font_size: Annotated[float, Gt(gt=0)] = 9.0, dpi: Annotated[int, Ge(ge=50), Le(le=1200)] = 200, palette: Annotated[tuple[str, ...], MinLen(min_length=1)] = ('#1F4E79', '#C55A11', '#548235', '#7F6000', '#7030A0', '#404040'), reference_colour: Annotated[str, _PydanticGeneralMetadata(pattern='^#[0-9A-Fa-f]{6}$')] = '#7F7F7F', mplstyle: pathlib._local.Path | None = None) -> None Figures: the font matplotlib draws with, the colours, PNG resolution, an extra mplstyle. The default font is DejaVu Sans, which matplotlib ships, so a figure is drawn the same on every platform. Fonts(*, body: str = 'Calibri', size: Annotated[float, Gt(gt=0)] = 10.0) -> None Text in Word and HTML. Word takes its fonts from `Word.reference` when one is given. Mark(*, text: Annotated[str, MinLen(min_length=1)], colour: Annotated[str, _PydanticGeneralMetadata(pattern='^#[0-9A-Fa-f]{6}$')], bold: bool = False) -> None How one check status is marked in a table. Marks(*, passed: dazflow.render.style.Mark = Mark(text='Pass', colour='#1B7F3B', bold=False), failed: dazflow.render.style.Mark = Mark(text='Fail', colour='#B00020', bold=True), overridden: dazflow.render.style.Mark = Mark(text='Overridden', colour='#8A5A00', bold=True)) -> None Pass, fail and overridden, marked in place in words and colour. Numbers(*, decimals: Annotated[int, Ge(ge=0), Le(le=12)] = 2, thousands: str = ',', decimal_mark: Annotated[str, MinLen(min_length=1)] = '.', missing: str = '–') -> None How numbers are written: in tables, and in findings' numeric values. Page(*, width_cm: Annotated[float, Gt(gt=0)] = 16.0) -> None The text width of the page: tables and figures are laid out to it. render.Renderable Represent a PEP 604 union type E.g. for int | str Renderer(*args, **kwargs) Writes artefacts in one format. `render` returns text, or bytes when `binary` is true, and raises `RenderError` for a kind of artefact the format cannot hold. Section(*, title: Annotated[str, MinLen(min_length=1)], items: tuple[typing.Annotated[typing.Union[typing.Annotated[str, Tag(tag='text')], typing.Annotated[dazflow.core.finding.Finding, Tag(tag='finding')], typing.Annotated[dazflow.core.artefact.Table, Tag(tag='table')], typing.Annotated[dazflow.core.artefact.Figure, Tag(tag='figure')], typing.Annotated[dazflow.render.document.Section, Tag(tag='section')]], Discriminator(discriminator=, custom_error_type=None, custom_error_message=None, custom_error_context=None)], ...] = ()) -> None A headed part of a document: paragraphs of text, findings, tables, figures, subsections. Style(*, fonts: dazflow.render.style.Fonts = Fonts(body='Calibri', size=10.0), numbers: dazflow.render.style.Numbers = Numbers(decimals=2, thousands=',', decimal_mark='.', missing='–'), dates: dazflow.render.style.Dates = Dates(format='%Y-%m-%d'), page: dazflow.render.style.Page = Page(width_cm=16.0), marks: dazflow.render.style.Marks = Marks(passed=Mark(text='Pass', colour='#1B7F3B', bold=False), failed=Mark(text='Fail', colour='#B00020', bold=True), overridden=Mark(text='Overridden', colour='#8A5A00', bold=True)), captions: dazflow.render.style.Captions = Captions(table='Table {{ id }}. {{ caption }}', figure='Figure {{ id }}. {{ caption }}', source='Source: {% if note %}{{ note }}; {% endif %}run {{ run_id }}, data {{ fingerprint }}, {{ date }}.', fingerprint_digits=12), figures: dazflow.render.style.Figures = Figures(font='DejaVu Sans', font_size=9.0, dpi=200, palette=('#1F4E79', '#C55A11', '#548235', '#7F6000', '#7030A0', '#404040'), reference_colour='#7F7F7F', mplstyle=None), word: dazflow.render.style.Word = Word(reference=None, table_style='Table Grid'), findings: dict[str, str] = ) -> None Everything that decides how an artefact looks, in one file per organisation. `load_style` merges an organisation's partial override onto these defaults. `findings` maps a finding's `key` to a template that replaces the step's own, so rewording a finding needs no code. Word(*, reference: pathlib._local.Path | None = None, table_style: Annotated[str, MinLen(min_length=1)] = 'Table Grid') -> None Word output: the organisation's reference document and its table style. caption_text(artefact: 'Table | Figure', style: 'Style') -> 'str' ``Table T3.1. Caption``, from the style's caption template. finding_text(finding: 'Finding', style: 'Style | None' = None) -> 'str' The finding's sentence, with the style's template for its key and numbers in the style. `style` is a `Style`; ``None`` means the house style (``load_style(None)``). This is the text a report shows and ``dazflow run`` and ``dazflow show`` print; `Finding.text` keeps the numbers as given, for the run record. Floats are written with the style's decimals and separators wherever a template prints them as they are (``{{ x }}``); filters and comparisons see the plain number. Integers, booleans and text are printed as given. format_cell(value: 'Any', kind: 'str', style: 'Style') -> 'str' One table cell as text: numbers, percentages, dates and statuses in the style. format_date(value: 'str | dt.date', style: 'Style') -> 'str' An ISO date (or a `date`) in the style's date format. format_number(value: 'float | int', style: 'Style', *, integer: 'bool' = False) -> 'str' `value` with the style's decimals and separators; a value that rounds to zero has no sign. load_style(source: 'Style | Mapping[str, Any] | str | Path | None' = None) -> 'Style' The style to render with. `source` is ``None`` (the house style), a `Style` (used as it is), a mapping, or the path of a YAML file. A mapping or file is a partial override, merged onto the house style setting by setting; paths in a file are relative to the file. An unknown or invalid setting is a `ConfigError`. render(obj: 'Renderable', format: 'str', *, style: 'Style | Any' = None, source: 'Source | None' = None) -> 'str | bytes' `obj` in `format` (a renderer key: docx, html, markdown, png, svg), in the style. `style` is anything `load_style` takes. `source` fills the source note of every table and figure that has none; a `Document`'s own `source` does the same. render.renderers Components of one kind, looked up by the key configuration names them by. Components are added with the `register` decorator, or by a third-party package through the ``dazflow.plugins`` entry-point group. Each entry point names a module (``name = package.module``, or ``package.module:attr``); loading it imports the module, whose decorators register its components. Entry points are loaded on the registry's first lookup, once. Parameters ---------- kind : str What the registry holds, for messages: ``"model"``, ``"reader"``. protocol : type, optional Optional `typing.Protocol` every component must have the members of. Examples -------- >>> widgets = Registry("widget") >>> @widgets.register("plain") ... class Plain: ... >>> widgets["plain"] is Plain True source_text(source: 'Source', style: 'Style') -> 'str' The source note: the note, the run, the dataset fingerprint and the date. to_great_table(table: 'Table', style: 'Style') -> 'GT' The table as a great-tables `GT`, its cells already written in the style. The id is the artefact's, so the HTML is the same on every render. write(obj: 'Renderable', path: 'str | Path', *, format: 'str | None' = None, style: 'Style | Any' = None, source: 'Source | None' = None) -> 'Path' Render `obj` to the file `path`, the format from its suffix unless `format` is given. Markdown links its figures as ``.svg``; those files are written next to it. ## Steps The step registry and the protocol a step follows. Step(*args, **kwargs) A step module: its configuration, its result type and the function that runs it. steps.registry Components of one kind, looked up by the key configuration names them by. Components are added with the `register` decorator, or by a third-party package through the ``dazflow.plugins`` entry-point group. Each entry point names a module (``name = package.module``, or ``package.module:attr``); loading it imports the module, whose decorators register its components. Entry points are loaded on the registry's first lookup, once. Parameters ---------- kind : str What the registry holds, for messages: ``"model"``, ``"reader"``. protocol : type, optional Optional `typing.Protocol` every component must have the members of. Examples -------- >>> widgets = Registry("widget") >>> @widgets.register("plain") ... class Plain: ... >>> widgets["plain"] is Plain True ## Step: ingest Read the inputs and put every series on one calendar. ingest.IDS The identifiers of one step's artefacts, fixed by name, not by creation order. Each artefact a step can make is declared once with its number, so ``T3.2`` stays the stationarity table on every rerun, whatever order the step builds its artefacts in and whichever of them it builds. Add a new artefact under a new number; never renumber one, or documents written earlier point at the wrong table. Parameters ---------- step A step name from `STEP_NUMBERS` (``"explore"``), or a positive number for a step outside the built-in ones. tables, figures, findings Name to number, each number positive and used once per kind. Examples -------- >>> ids = ArtefactIds("explore", tables={"summary": 1, "stationarity": 2}) >>> ids.table("stationarity") 'T3.2' IngestConfig(*, frequency: Literal['M', 'Q', 'Y'], inputs: Annotated[list[dazflow.steps.ingest.Input], MinLen(min_length=1)], series: Annotated[list[dazflow.steps.ingest.SeriesSpec], MinLen(min_length=1)], min_history: Annotated[int, Ge(ge=1)] = 40, overrides: list[dazflow.core.gate.Override] = ) -> None Configuration of the ingest step. IngestResult(*, gate: dazflow.core.gate.Gate = , finding: dazflow.core.finding.Finding | None = None, artefacts: dict[str, typing.Annotated[typing.Union[typing.Annotated[dazflow.core.artefact.Table, Tag(tag='table')], typing.Annotated[dazflow.core.artefact.Figure, Tag(tag='figure')], typing.Annotated[dazflow.core.finding.Finding, Tag(tag='finding')]], Discriminator(discriminator=, custom_error_type=None, custom_error_message=None, custom_error_context=None)]] = , config: dazflow.steps.ingest.IngestConfig, dataset: dazflow.core.dataset.Dataset | None = None, fingerprint: str | None = None, frequency: Literal['M', 'Q', 'Y'], missing: tuple[str, ...] = (), history: int = 0, sample_start: str | None = None, sample_end: str | None = None) -> None What ingest returns. `dataset` is left out of `to_dict()`; `fingerprint` identifies it. Input(*, reader: str | None = None, path: str | None = None, date: str | None = None, frequency: Optional[Literal['M', 'Q', 'Y']] = None, columns: list[str] | None = None, options: dict[str, str | int | float | bool | None] = , name: Annotated[str, MinLen(min_length=1)]) -> None One input: a file read by a reader, or a frame passed to `run` under the same name. SeriesSpec(*, name: Annotated[str, MinLen(min_length=1)], input: str | None = None, column: str | None = None, role: Literal['target', 'driver', 'other'] = 'driver', unit: str | None = None, source: str | None = None, definition: str | None = None, expected_sign: Optional[Literal[-1, 0, 1]] = None, aggregation: Literal['average', 'end'] = 'average', lag: Annotated[int, Ge(ge=0)] = 0) -> None One series to take from the inputs, with its metadata and how to align it. run(config: 'IngestConfig | Mapping[str, Any]', data: 'Mapping[str, Any] | None' = None, *, root: 'str | Path | None' = None) -> 'IngestResult' Read the inputs and put the configured series on one calendar. `data` maps input names to frames (pandas, polars, pyarrow) used instead of reading a path. `root` is the folder relative paths are read from; each series' source is the path as written, so the dataset is the same wherever the folder is. Prints nothing and writes no files. ## Step: clean Data-quality checks, configured treatments and their log. clean.IDS The identifiers of one step's artefacts, fixed by name, not by creation order. Each artefact a step can make is declared once with its number, so ``T3.2`` stays the stationarity table on every rerun, whatever order the step builds its artefacts in and whichever of them it builds. Add a new artefact under a new number; never renumber one, or documents written earlier point at the wrong table. Parameters ---------- step A step name from `STEP_NUMBERS` (``"explore"``), or a positive number for a step outside the built-in ones. tables, figures, findings Name to number, each number positive and used once per kind. Examples -------- >>> ids = ArtefactIds("explore", tables={"summary": 1, "stationarity": 2}) >>> ids.table("stationarity") 'T3.2' CleanConfig(*, completeness: dazflow.checks._builtin.Completeness.Config = , gaps: dazflow.checks._builtin.Gaps.Config = , duplicates: dazflow.checks._builtin.Duplicates.Config = , range: dazflow.checks._builtin.Range.Config = , revisions: dazflow.checks._builtin.Revisions.Config = , outliers: dazflow.checks._builtin.Outliers.Config = , representativeness: dazflow.checks._builtin.Representativeness.Config = , custom: dict[str, dict[str, typing.Any]] = , treatments: list[typing.Annotated[dazflow.steps.clean.Fill | dazflow.steps.clean.Interpolate | dazflow.steps.clean.Winsorise | dazflow.steps.clean.Replace | dazflow.steps.clean.Exclude, FieldInfo(annotation=NoneType, required=True, discriminator='action')]] = , overrides: list[dazflow.core.gate.Override] = ) -> None Configuration of the clean step: one section per check, the treatments, overrides. CleanResult(*, gate: dazflow.core.gate.Gate = , finding: dazflow.core.finding.Finding | None = None, artefacts: dict[str, typing.Annotated[typing.Union[typing.Annotated[dazflow.core.artefact.Table, Tag(tag='table')], typing.Annotated[dazflow.core.artefact.Figure, Tag(tag='figure')], typing.Annotated[dazflow.core.finding.Finding, Tag(tag='finding')]], Discriminator(discriminator=, custom_error_type=None, custom_error_message=None, custom_error_context=None)]] = , config: dazflow.steps.clean.CleanConfig, dataset: dazflow.core.dataset.Dataset | None = None, fingerprint: str | None = None, input_fingerprint: str | None = None, before: tuple[dazflow.checks._base.Outcome, ...] = (), after: tuple[dazflow.checks._base.Outcome, ...] = (), treatments: tuple[dazflow.steps.clean.TreatmentRecord, ...] = (), flagged: dict[str, tuple[str, ...]] = ) -> None What clean returns. `dataset` is left out of `to_dict()`; `fingerprint` identifies it. `before` and `after` hold every check's outcome on every series, before and after treatment; the gate is built from `after`. `flagged` maps each series to the periods any check flagged before treatment. Exclude(*, reason: str, series: list[str] | None = None, periods: list[str] | None = None, start: str | None = None, end: str | None = None, action: Literal['exclude']) -> None Exclude periods: their values become missing and no check counts them as missing. Fill(*, reason: str, series: list[str] | None = None, periods: list[str] | None = None, start: str | None = None, end: str | None = None, action: Literal['fill'], method: Literal['previous', 'next', 'value'] = 'previous', value: float | None = None) -> None Fill missing values from the previous or next value, or with a given value. Interpolate(*, reason: str, series: list[str] | None = None, periods: list[str] | None = None, start: str | None = None, end: str | None = None, action: Literal['interpolate']) -> None Fill missing values inside the history linearly between their neighbours. Replace(*, reason: str, series: list[str] | None = None, periods: list[str] | None = None, start: str | None = None, end: str | None = None, action: Literal['replace'], value: float | None = None) -> None Replace values at named periods by `value`, or linearly from their neighbours. Annotated(*args, **kwargs) Runtime representation of an annotated type. At its core 'Annotated[t, dec1, dec2, ...]' is an alias for the type 't' with extra annotations. The alias behaves like a normal typing alias. Instantiating is the same as instantiating the underlying type; binding it to types is also the same. The metadata itself is stored in a '__metadata__' attribute as a tuple. TreatmentRecord(*, number: int, action: str, series: str, period: str | None = None, before: float | None = None, after: float | None = None, reason: str) -> None One value changed by a treatment, or a treatment of one series that changed none. `number` is the treatment's place in the configuration, from 1. `period`, `before` and `after` are ``None`` for a treatment that changed nothing in `series`; a missing value is ``None``. Winsorise(*, reason: str, series: list[str] | None = None, periods: list[str] | None = None, start: str | None = None, end: str | None = None, action: Literal['winsorise'], lower: Annotated[float, Ge(ge=0), Le(le=1)] = 0.01, upper: Annotated[float, Ge(ge=0), Le(le=1)] = 0.99) -> None Clip values to the series' `lower` and `upper` quantiles. run(dataset: 'Dataset', config: 'CleanConfig | Mapping[str, Any] | None' = None, *, previous: 'Dataset | None' = None) -> 'CleanResult' Check the data, apply the configured treatments, and check again. `previous` is the previous vintage of the data, for the revisions check. The caller's `dataset` is not changed. Prints nothing and writes no files. ## Step: explore Each series alone, each driver against the target. explore.IDS The identifiers of one step's artefacts, fixed by name, not by creation order. Each artefact a step can make is declared once with its number, so ``T3.2`` stays the stationarity table on every rerun, whatever order the step builds its artefacts in and whichever of them it builds. Add a new artefact under a new number; never renumber one, or documents written earlier point at the wrong table. Parameters ---------- step A step name from `STEP_NUMBERS` (``"explore"``), or a positive number for a step outside the built-in ones. tables, figures, findings Name to number, each number positive and used once per kind. Examples -------- >>> ids = ArtefactIds("explore", tables={"summary": 1, "stationarity": 2}) >>> ids.table("stationarity") 'T3.2' ExploreConfig(*, target: str | None = None, drivers: list[str] | None = None, expected_signs: dict[str, typing.Literal[-1, 0, 1]] = , transforms: dict[str, list[str]] = , profile: dazflow.steps.explore.ProfileConfig = , stationarity: dazflow.steps.explore.StationarityConfig = , max_lag: Annotated[int, Ge(ge=0)] = 4, significance: Annotated[float, Gt(gt=0), Lt(lt=1)] = 0.05, hac_maxlags: Annotated[int | None, Ge(ge=0)] = None, overrides: list[dazflow.core.gate.Override] = ) -> None Configuration of the explore step. ExploreResult(*, gate: dazflow.core.gate.Gate = , finding: dazflow.core.finding.Finding | None = None, artefacts: dict[str, typing.Annotated[typing.Union[typing.Annotated[dazflow.core.artefact.Table, Tag(tag='table')], typing.Annotated[dazflow.core.artefact.Figure, Tag(tag='figure')], typing.Annotated[dazflow.core.finding.Finding, Tag(tag='finding')]], Discriminator(discriminator=, custom_error_type=None, custom_error_message=None, custom_error_context=None)]] = , config: dazflow.steps.explore.ExploreConfig, dataset: dazflow.core.dataset.Dataset | None = None, fingerprint: str | None = None, input_fingerprint: str | None = None, target: str | None = None, drivers: tuple[str, ...] = (), profiles: tuple[dazflow.steps.explore.Profile, ...] = (), integration: tuple[dazflow.steps.explore.Integration, ...] = (), orders: dict[str, int | None] = , chains: dict[str, tuple[str, ...]] = , lag_profiles: tuple[dazflow.steps.explore.LagProfile, ...] = (), lags: dict[str, int] = , screens: tuple[dazflow.steps.explore.Screen, ...] = (), kept: tuple[str, ...] = ()) -> None What explore returns. `dataset` (left out of `to_dict()`) holds the transformed series. `chains` is the chain explore applied to each series (configured transforms, then differences), also appended to its `SeriesMeta.transforms`; `orders` its order of integration; `lags` each driver's lag; `kept` the drivers whose gate checks pass or are overridden, in the configured order. Integration(*, series: str | None = None, order: int | None, kind: Literal['stationary', 'trend-stationary', 'integrated', 'undetermined'], steps: tuple[dazflow.steps.explore.Level, ...], chain: tuple[str, ...] = ()) -> None A series' order of integration and the levels tested to reach it. `kind` is ``stationary`` (order 0), ``trend-stationary`` (order 0 around a trend), ``integrated`` (order 1 or more) or ``undetermined`` (not stationary within `max_order` differences; `order` is ``None``). `chain` holds the differences chosen, as transform text. LagProfile(*, driver: str | None = None, lag: int, correlations: tuple[float | None, ...], observations: int) -> None Correlations of the target with a driver lagged 0 to `max_lag` periods. All lags are measured on one sample, the periods where the target and every lag of the driver are present, so they compare. `lag` has the largest absolute correlation (the smallest such lag on a tie). Level(*, differences: int, trend: Literal['c', 'ct'], tests: tuple[dazflow.steps.explore.UnitRoot, ...], votes: int, stationary: bool) -> None The four tests on the series differenced `differences` times, around `trend`. Profile(*, series: str, observations: int, missing: int, trend_strength: float | None = None, seasonal_strength: float | None = None, acf1: float | None = None, acf_seasonal: float | None = None, volatility: float | None = None, intermittency: float | None = None) -> None One series' profile, on its values from the first to the last present one. Strengths are ``max(0, 1 - Var(R) / Var(T + R))`` for the trend and ``max(0, 1 - Var(R) / Var(S + R))`` for the season, from an STL fit (Wang, Smith and Hyndman 2006); annual series have a lowess trend and no seasonal measure. `acf1` and `acf_seasonal` are sample autocorrelations at lag 1 and at a year; `volatility` is the standard deviation of period-on-period changes; `intermittency` the share of present values that are zero. Missing values inside the history are interpolated for the fit and counted in `missing`. ProfileConfig(*, seasonal: Annotated[int, Ge(ge=3)] = 7, trend_window: Annotated[int, Ge(ge=3)] = 21) -> None How each series is profiled. Screen(*, driver: str | None = None, lag: int, coefficient: float | None = None, std_error: float | None = None, t: float | None = None, pvalue: float | None = None, observations: int, maxlags: int, expected_sign: int | None = None, observed_sign: int | None = None, kept: bool = False) -> None A single-driver regression, target on a constant and the driver at `lag`. Standard errors are HAC (Newey-West, Bartlett kernel, `maxlags`), as statsmodels' ``OLS(...).fit(cov_type="HAC")``. `expected_sign`, `observed_sign` and `kept` are filled by `run`. StationarityConfig(*, alpha: Annotated[float, Gt(gt=0), Lt(lt=1)] = 0.05, votes: Annotated[int, Ge(ge=1), Le(le=4)] = 3, max_order: Annotated[int, Ge(ge=0), Le(le=3)] = 2, lags: Annotated[int | None, Ge(ge=0)] = None, method: Literal['aic', 'bic', 't-stat'] = 'aic', trend_stationary: Literal['difference', 'keep'] = 'difference', min_observations: Annotated[int, Ge(ge=8)] = 20) -> None How the four tests are run and read together into an order of integration. A level of differencing is stationary when at least `votes` of the four tests say so at significance `alpha`: ADF, DFGLS and Phillips-Perron by rejecting their unit-root null, KPSS by not rejecting its stationarity null. Levels are tried in order: the series around a constant, then around a linear trend, then its first, second ... differences around a constant, up to `max_order`. UnitRoot(*, test: Literal['adf', 'dfgls', 'pp', 'kpss'], trend: Literal['c', 'ct'], statistic: float | None = None, pvalue: float | None = None, lags: int | None = None, stationary: bool = False, note: str | None = None) -> None One test on one level of differencing. `stationary` reads it at `alpha`. `statistic`, `pvalue` and `lags` are ``None`` when arch could not run the test (`note` says why); such a test does not say stationary. driver_checks(screen: 'Screen', significance: 'float') -> 'list[Check]' The gate checks of one screened driver, before overrides. ``sign:`` (only when `expected_sign` is -1 or 1) passes when the coefficient times the expected sign is above 0; ``significance:`` passes when the HAC p-value is at most `significance`. A missing coefficient or p-value fails. integration_order(x: 'pd.Series', config: 'StationarityConfig | Mapping[str, Any] | None' = None) -> 'Integration' The order of integration of `x`, from the four tests read together (`StationarityConfig`). Raises `ExploreError` when `x` has fewer than `min_observations` values from its first to its last. lag_search(y: 'pd.Series', x: 'pd.Series', max_lag: 'int') -> 'LagProfile' Correlate `y` with `x` lagged 0 to `max_lag` periods and pick the strongest lag. `y` and `x` share an index (consecutive periods). Raises `ExploreError` when fewer than three periods have the target and every lag present. newey_west_lags(n: 'int') -> 'int' The Newey-West (1994) rule of thumb, floor(4 (n / 100)^(2/9)). profile(x: 'pd.Series', frequency: 'str | None' = None, config: 'ProfileConfig | Mapping[str, Any] | None' = None) -> 'Profile' Profile one series: trend and seasonal strength, autocorrelation, volatility, intermittency. `frequency` is ``"M"``, ``"Q"`` or ``"Y"`` (unset: read from the index). A measure the series is too short for is ``None``. run(dataset: 'Dataset', config: 'ExploreConfig | Mapping[str, Any] | None' = None) -> 'ExploreResult' Profile and test every numeric series, transform each, and screen each driver. The caller's `dataset` is not changed; the result's `dataset` holds the transformed series with their chains recorded. Prints nothing and writes no files. says_stationary(test: 'str', pvalue: 'float', alpha: 'float') -> 'bool' Whether a test's p-value says stationary at `alpha`. ADF, DFGLS and Phillips-Perron test a unit-root null, so they say stationary when ``pvalue < alpha``; KPSS tests a stationarity null, so it says stationary when ``pvalue >= alpha``. A NaN p-value says nothing. screen(y: 'pd.Series', x: 'pd.Series', lag: 'int' = 0, maxlags: 'int | None' = None) -> 'Screen' Regress `y` on a constant and `x` lagged `lag` periods, with HAC standard errors. The sample is every period with both values present; `maxlags` defaults to `newey_west_lags` of its size. A driver with no variation gets no coefficient. unit_root(x: 'pd.Series | Sequence[float]', *, trend: "Literal['c', 'ct']" = 'c', lags: 'int | None' = None, method: "Literal['aic', 'bic', 't-stat']" = 'aic', alpha: 'float' = 0.05) -> 'tuple[UnitRoot, ...]' ADF, DFGLS, Phillips-Perron and KPSS (arch) on `x`, around a constant or a trend. `lags` fixes the lags of ADF and DFGLS and the bandwidth of PP and KPSS; unset, ADF and DFGLS choose by `method` and PP and KPSS take arch's default bandwidth. The lags used are recorded. A unit-root test says stationary when its p-value is below `alpha`; KPSS when its p-value is at least `alpha`. ## Step: build Candidate models within the declared signs and exclusions. build.IDS The identifiers of one step's artefacts, fixed by name, not by creation order. Each artefact a step can make is declared once with its number, so ``T3.2`` stays the stationarity table on every rerun, whatever order the step builds its artefacts in and whichever of them it builds. Add a new artefact under a new number; never renumber one, or documents written earlier point at the wrong table. Parameters ---------- step A step name from `STEP_NUMBERS` (``"explore"``), or a positive number for a step outside the built-in ones. tables, figures, findings Name to number, each number positive and used once per kind. Examples -------- >>> ids = ArtefactIds("explore", tables={"summary": 1, "stationarity": 2}) >>> ids.table("stationarity") 'T3.2' BuildConfig(*, target: str | None = None, drivers: list[str] | None = None, expected_signs: dict[str, typing.Literal[-1, 0, 1]] = , lags: dict[str, typing.Annotated[int, FieldInfo(annotation=NoneType, required=True, metadata=[Ge(ge=0)])]] = , search: Literal['exhaustive', 'stepwise'] = 'exhaustive', max_size: Annotated[int, Ge(ge=1)] = 2, criterion: Literal['aic', 'bic'] = 'aic', exclusions: list[tuple[str, str]] = , forms: list[dazflow.steps.build.FormSpec] = , benchmarks: list[dazflow.steps.build.FormSpec] = , significance: Annotated[float, Gt(gt=0), Lt(lt=1)] = 0.05, max_vif: Annotated[float, Gt(gt=1)] = 10.0, trend: Literal['auto', 'always', 'never'] = 'auto', min_candidates: Annotated[int, Ge(ge=1)] = 1, overrides: list[dazflow.core.gate.Override] = ) -> None Configuration of the build step. BuildResult(*, gate: dazflow.core.gate.Gate = , finding: dazflow.core.finding.Finding | None = None, artefacts: dict[str, typing.Annotated[typing.Union[typing.Annotated[dazflow.core.artefact.Table, Tag(tag='table')], typing.Annotated[dazflow.core.artefact.Figure, Tag(tag='figure')], typing.Annotated[dazflow.core.finding.Finding, Tag(tag='finding')]], Discriminator(discriminator=, custom_error_type=None, custom_error_message=None, custom_error_context=None)]] = , config: dazflow.steps.build.BuildConfig, fingerprint: str | None = None, explore_fingerprint: str | None = None, target: str | None = None, drivers: tuple[str, ...] = (), expected_signs: dict[str, int] = , lags: dict[str, int] = , chains: dict[str, tuple[str, ...]] = , trend_series: tuple[str, ...] = (), sample: dazflow.models._base.Sample | None = None, correlation: dict[str, dict[str, float | None]] = , vif: dict[str, float | None] = , combinations: tuple[tuple[str, ...], ...] = (), candidates: tuple[dazflow.steps.build.Candidate, ...] = (), passing: tuple[str, ...] = ()) -> None What build returns: every candidate fitted, and the passing ones. `fingerprint` is the dataset build ran on (in levels, scenarios left out); `sample` the common periods every candidate was fitted on; `chains` and `lags` how each series was transformed and each driver lagged; `trend_series` the series that call for a trend term. Candidate(*, id: str, role: Literal['benchmark', 'candidate'], form: str, drivers: tuple[str, ...] = (), design: dazflow.models._design.Design, record: dazflow.models._base.ModelRecord | None = None, error: str | None = None, coefficients: tuple[dazflow.steps.build.Coefficient, ...] = (), max_vif: float | None = None, gate: dazflow.core.gate.Gate = , passed: bool = False) -> None One fitted model: its form, drivers, design, stored record and checks. `id` is ``
:+`` (the form key alone for a benchmark). `record` is ``None`` when the fit failed (`error` says why). `gate` holds the candidate's own checks: ``sign:``, ``significance:`` and ``vif``. `passed` is whether they all pass or are overridden. Coefficient(*, term: str, estimate: float, std_error: float | None = None, z: float | None = None, pvalue: float | None = None, expected_sign: int | None = None, gated: bool = False) -> None One parameter: estimate, standard error, z and two-sided normal p-value. `gated` marks a driver's coefficient, which has the sign and significance checks; the constant, the trend and a form's own parameters (``ar.L1``, ``sigma2``) are reported, not gated. FormSpec(*, form: Annotated[str, MinLen(min_length=1)], config: dict[str, typing.Any] = ) -> None A model form by registry key, with its configuration (``ols`` or ``{form: ols, config: ...}``). combinations(drivers: 'Sequence[str]', max_size: 'int', exclusions: 'Sequence[Sequence[str]]' = ()) -> 'tuple[tuple[str, ...], ...]' Every set of 1 to `max_size` drivers that holds no excluded pair. Sets are ordered by size, then as `itertools.combinations` gives them in the order of `drivers`. Without exclusions there are ``sum(comb(n, k) for k in 1..max_size)`` of them. run(dataset: 'Dataset', config: 'BuildConfig | Mapping[str, Any] | None' = None, *, explore: 'Any' = None) -> 'BuildResult' Search driver combinations and fit the forms and benchmarks on the series in levels. `dataset` holds the series in levels, as explore received them; `explore` (its result, optional) gives the target, the kept drivers, their lags and signs, each series' transform chain and which series are trend-stationary. Without it the series are used as they are, at lag 0. The caller's `dataset` is not changed. Prints nothing and writes no files. stepwise(y: 'pd.Series', X: 'pd.DataFrame', max_size: 'int', exclusions: 'Sequence[Sequence[str]]' = (), criterion: "Literal['aic', 'bic']" = 'aic') -> 'tuple[tuple[str, ...], ...]' Forward stepwise search: the sets met adding, each step, the driver that lowers the criterion most. Each step fits OLS on a constant and the current drivers plus one more, skipping a driver that would join an excluded pair, and keeps the one with the lowest AIC (or BIC). The search stops at `max_size` drivers or when no addition lowers the criterion. Drivers are in the order added. vif(X: 'pd.DataFrame') -> 'pd.Series' Variance inflation factors: ``1 / (1 - R²)`` of each column on a constant and the others. R² is centred, as in statsmodels' `variance_inflation_factor` on a design with a constant. A column the others explain exactly has an infinite VIF. ## Step: select Rank the candidates out of sample and propose a default. select.IDS The identifiers of one step's artefacts, fixed by name, not by creation order. Each artefact a step can make is declared once with its number, so ``T3.2`` stays the stationarity table on every rerun, whatever order the step builds its artefacts in and whichever of them it builds. Add a new artefact under a new number; never renumber one, or documents written earlier point at the wrong table. Parameters ---------- step A step name from `STEP_NUMBERS` (``"explore"``), or a positive number for a step outside the built-in ones. tables, figures, findings Name to number, each number positive and used once per kind. Examples -------- >>> ids = ArtefactIds("explore", tables={"summary": 1, "stationarity": 2}) >>> ids.table("stationarity") 'T3.2' CandidateEvaluation(*, candidate: str, evaluation: dazflow.evaluation._rolling.Evaluation | None = None, note: str | None = None) -> None A candidate's rolling-origin evaluation, or why it has none (`note`). Choice(*, candidate: Annotated[str, MinLen(min_length=1)], reason: str) -> None The modeller's decision: the proposed candidate confirmed, or another, with a reason. ConfidenceSet(*, included: tuple[str, ...], pvalues: dict[str, float], size: float, reps: int, block_size: int | None = None, method: str = 'R', bootstrap: str = 'stationary', seed: int = 0, ties: dict[str, str] = ) -> None The candidates arch's MCS keeps at `size`, in the losses' column order, and every p-value. MCSConfig(*, size: Annotated[float, Gt(gt=0), Lt(lt=1)] = 0.1, reps: Annotated[int, Ge(ge=10)] = 1000, block_size: Annotated[int | None, Ge(ge=1)] = None, method: Literal['R', 'max'] = 'R', bootstrap: Literal['stationary', 'circular', 'moving block'] = 'stationary', seed: int | None = None) -> None The model confidence set: arch's `MCS` on the per-origin losses. OrderingConfig(*, statistic: Literal['mean', 'last', 'max', 'min'] = 'mean', direction: Literal[-1, 1] = 1) -> None How projections are compared across scenarios. Ranked(*, rank: int | None = None, candidate: str, role: Literal['benchmark', 'candidate'], form: str, drivers: tuple[str, ...] = (), size: int = 0, scaled_error: float | None = None, in_set: bool = False, pvalue: float | None = None, build_passed: bool = False, beats_benchmark: bool | None = None, statistics: dict[str, float] = , out_of_order: int | None = None, out_of_bounds: int | None = None, eligible: bool = False, note: str | None = None) -> None One row of the ranking: scores, set membership and every check select makes. RuleRow(*, candidate: str, drivers: int, error: float, passed: bool, in_set: bool) -> None One candidate as the default rule sees it. ScenarioForecast(*, candidate: str, scenario: str | int, forecast: dazflow.models._base.Forecast, levels: tuple[float, ...]) -> None A candidate's forecast under one scenario, and its mean path in the target's levels. SelectConfig(*, benchmark: str = 'mean', splitter: str = 'expanding', splitter_config: dict[str, typing.Any] = , loss: Literal['squared', 'absolute'] = 'squared', levels: list[float] = , benchmark_ratio: Annotated[float, Gt(gt=0)] = 1.0, mcs: dazflow.steps.select.MCSConfig = , scenarios: dazflow.readers._scenarios.ScenarioInput | None = None, ordering: dazflow.steps.select.OrderingConfig = , bounds: tuple[float | None, float | None] | None = None, choice: dazflow.steps.select.Choice | None = None, overrides: list[dazflow.core.gate.Override] = ) -> None Configuration of the select step. SelectResult(*, gate: dazflow.core.gate.Gate = , finding: dazflow.core.finding.Finding | None = None, artefacts: dict[str, typing.Annotated[typing.Union[typing.Annotated[dazflow.core.artefact.Table, Tag(tag='table')], typing.Annotated[dazflow.core.artefact.Figure, Tag(tag='figure')], typing.Annotated[dazflow.core.finding.Finding, Tag(tag='finding')]], Discriminator(discriminator=, custom_error_type=None, custom_error_message=None, custom_error_context=None)]] = , config: dazflow.steps.select.SelectConfig, fingerprint: str | None = None, target: str | None = None, benchmark: str | None = None, seed: int = 0, origins: tuple[str, ...] = (), losses: dict[str, tuple[float, ...]] = , evaluations: tuple[dazflow.steps.select.CandidateEvaluation, ...] = (), confidence: dazflow.steps.select.ConfidenceSet | None = None, ranking: tuple[dazflow.steps.select.Ranked, ...] = (), severity: tuple[str | int, ...] = (), scenario_forecasts: tuple[dazflow.steps.select.ScenarioForecast, ...] = (), proposal: str | None = None, chosen: str | None = None, decision: Literal['proposed', 'confirmed', 'overridden', 'none'] = 'none', reason: str | None = None, record: dazflow.models._base.ModelRecord | None = None, design: dazflow.models._design.Design | None = None, drivers: tuple[str, ...] = ()) -> None What select returns: the ranking, the confidence set, the scenarios and the choice. `record` is the chosen candidate's `ModelRecord` (its full-sample fit), `design` how its target and drivers are built from the levels, `drivers` its drivers, and `scenario_forecasts` every candidate under every scenario, which forecast (Stage 9) projects from. `decision` is ``proposed`` (by the default rule, not yet confirmed), ``confirmed``, ``overridden`` or ``none``. confidence_set(losses: 'pd.DataFrame', *, size: 'float' = 0.1, reps: 'int' = 1000, block_size: 'int | None' = None, method: "Literal['R', 'max']" = 'R', bootstrap: 'str' = 'stationary', seed: 'int' = 0) -> 'ConfidenceSet' Arch's model confidence set on `losses` (one row per origin, one column per model). The call is ``arch.bootstrap.MCS(losses, size, reps, block_size, method, bootstrap, seed=seed).compute()``. A single model is its own set. Models whose losses are identical at every origin cannot be told apart, and their loss differential has no variance, so arch's statistic is not finite: the test runs on the first of each tied group, and every other member takes its inclusion and p-value (``ties`` maps it to that first one; design D50). Any other failure of arch's computation is a `SelectError`. default_rule(rows: 'Sequence[RuleRow]') -> 'str | None' The default choice (design D38), or ``None`` when no passing candidate is in the set. Among the rows that pass every check and are in the confidence set: the fewest drivers, then the lowest scaled error, then the first listed. order_check(values: 'Mapping[Any, float]', severity: 'Sequence[Any]', direction: 'int' = 1) -> 'Check' The ``scenario-order`` check: no pair of successive scenarios out of order. out_of_order(values: 'Mapping[Any, float]', severity: 'Sequence[Any]', direction: 'int' = 1) -> 'int' How many successive scenarios, mildest first, project a less severe target than the one before. A more severe scenario should give a higher value (`direction` 1) or a lower one (-1). Equal values are not out of order. read_scenarios(spec: 'ScenarioInput', root: 'str | Path | None' = None) -> 'tuple[pd.DataFrame, list]' The scenario frame, indexed by ``(scenario, period)``, and the severity order, from a CSV. `dazflow.readers.read_scenarios`, whose `ReaderError` becomes a `SelectError`. A relative path is read from `root` (the working directory by default). run(dataset: 'Dataset', config: 'SelectConfig | Mapping[str, Any] | None' = None, *, build: 'Any', seed: 'int | None' = None) -> 'SelectResult' Score, rank and check every candidate of `build`, and propose a default. `dataset` holds the series in levels that build ran on, with any scenarios in `dataset.scenarios` (or read from `config.scenarios`); `build` is build's result. The bootstrap seed is `config.mcs.seed`, else `seed` (project.yaml's), else 0. The caller's `dataset` is not changed. Prints nothing and writes no files. ## Step: forecast The chosen model projected under every scenario. forecast.IDS The identifiers of one step's artefacts, fixed by name, not by creation order. Each artefact a step can make is declared once with its number, so ``T3.2`` stays the stationarity table on every rerun, whatever order the step builds its artefacts in and whichever of them it builds. Add a new artefact under a new number; never renumber one, or documents written earlier point at the wrong table. Parameters ---------- step A step name from `STEP_NUMBERS` (``"explore"``), or a positive number for a step outside the built-in ones. tables, figures, findings Name to number, each number positive and used once per kind. Examples -------- >>> ids = ArtefactIds("explore", tables={"summary": 1, "stationarity": 2}) >>> ids.table("stationarity") 'T3.2' AnchorConfig(*, rule: Literal['carry', 'decay', 'none'] = 'decay', decay: Annotated[float, Gt(gt=0), Le(le=1)] = 0.5) -> None How the gap between observed and fitted at the origin enters the forecast. BackTransform(*, forecast: dazflow.models._base.Forecast, correction: Literal['none', 'smearing', 'simulation'], intervals: Literal['model', 'inverse', 'linear', 'simulated'], draws: int | None = None, seed: int | None = None) -> None A forecast on the target's scale and how it got there. `correction` is the bias correction of the mean; `intervals` how the bounds were mapped: ``model`` (no chain), ``inverse`` (the bounds inverted, exact for a monotone chain without lags), ``linear`` (a linear chain: errors independent across horizons, variances added) or ``simulated`` (quantiles of simulated paths). `draws` and `seed` are set when anything was simulated. ForecastConfig(*, horizon: Annotated[int | None, Ge(ge=1)] = None, levels: Annotated[list[Annotated[float, FieldInfo(annotation=NoneType, required=True, metadata=[Gt(gt=0), Lt(lt=1)])]], MinLen(min_length=1)] = , anchor: dazflow.steps.forecast.AnchorConfig = , reversion: dazflow.steps.forecast.ReversionConfig | None = None, correction: Literal['auto', 'none', 'smearing', 'simulation'] = 'auto', simulation: dazflow.steps.forecast.SimulationConfig = , tolerance: Annotated[float, Ge(ge=0)] = 1e-06, bounds: tuple[float | None, float | None] | None = None, overrides: list[dazflow.core.gate.Override] = ) -> None Configuration of the forecast step. ForecastResult(*, gate: dazflow.core.gate.Gate = , finding: dazflow.core.finding.Finding | None = None, artefacts: dict[str, typing.Annotated[typing.Union[typing.Annotated[dazflow.core.artefact.Table, Tag(tag='table')], typing.Annotated[dazflow.core.artefact.Figure, Tag(tag='figure')], typing.Annotated[dazflow.core.finding.Finding, Tag(tag='finding')]], Discriminator(discriminator=, custom_error_type=None, custom_error_message=None, custom_error_context=None)]] = , config: dazflow.steps.forecast.ForecastConfig, fingerprint: str | None = None, target: str | None = None, chosen: str | None = None, form: str | None = None, record: dazflow.models._base.ModelRecord | None = None, design: dazflow.models._design.Design | None = None, origin: str | None = None, observed: float | None = None, fitted: float | None = None, gap: float | None = None, origin_gap: float | None = None, horizon: int = 0, severity: tuple[str | int, ...] = (), chain: tuple[str, ...] = (), correction: Literal['none', 'smearing', 'simulation'] = 'none', intervals: Literal['model', 'inverse', 'linear', 'simulated'] = 'model', draws: int | None = None, seed: int = 0, adjustments: tuple[float, ...] = (), weights: tuple[float, ...] = (), bounds: tuple[float | None, float | None] | None = None, paths: tuple[dazflow.steps.forecast.ScenarioPath, ...] = ()) -> None What forecast returns: every scenario's path on the target's scale, and how it was made. `paths[i].forecast` is the forecast of scenario `severity[i]`; `record` and `chosen` the model used. `gap` is observed minus fitted at the origin on the model's scale, `origin_gap` the forecast taken back to the origin minus the observed value, in the target's units (the gate's). ReversionConfig(*, level: float, periods: Annotated[int | None, Ge(ge=1)] = None) -> None A linear move towards a long-run level, on the target's scale. ScenarioPath(*, scenario: str | int, raw: dazflow.models._base.Forecast, anchored: dazflow.models._base.Forecast, forecast: dazflow.models._base.Forecast, reversion: tuple[float, ...] = ()) -> None One scenario: the model's forecast, anchored, and the forecast on the target's scale. `raw` is the chosen model's own forecast (model scale), `anchored` it with the anchoring adjustments, `forecast` the result: back-transformed, corrected and reverted. `reversion` is the shift reversion added. SimulationConfig(*, draws: Annotated[int, Ge(ge=100), Le(le=100000)] = 2000, seed: int | None = None) -> None The draws of a simulated correction or interval. adjustment(gap: 'float', h: 'int', rule: 'str' = 'decay', decay: 'float' = 0.5) -> 'np.ndarray' What anchoring adds at horizons 1..h: the gap (carry), ``gap (1 - decay)^h`` or nothing. back_transform(forecast: 'Forecast', chain: 'Sequence[str]', history: 'pd.Series | None' = None, *, residuals: 'Sequence[float] | pd.Series | None' = None, correction: 'str' = 'auto', draws: 'int' = 2000, seed: 'int' = 0) -> 'BackTransform' `forecast` (on the model's scale) on the target's scale, through the resolved `chain`. `history` is the target in levels up to the origin (needed by a chain with a lag). A linear chain (differences) needs no correction: the mean is the inverse of the mean, and the bounds add the horizons' variances, errors taken independent. A chain without lags inverts the bounds; its mean is corrected by ``smearing`` (the inverse averaged over the model's `residuals`; Duan's factor for a log) or ``simulation`` (averaged over `draws` normal errors with the forecast's standard error, from the widest interval, seeded by `seed`). A nonlinear chain with a lag is simulated, its bounds the simulated quantiles. ``auto`` picks none, smearing for a log or Box-Cox, simulation for a logit or a lag. revert(path: 'Sequence[float]', level: 'float', periods: 'int | None' = None) -> 'np.ndarray' The shift moving `path` linearly towards `level`: weight h/periods, full from `periods` on. run(dataset: 'Dataset', config: 'ForecastConfig | Mapping[str, Any] | None' = None, *, select: 'Any', seed: 'int | None' = None) -> 'ForecastResult' Forecast select's chosen model under every scenario, anchored, on the target's scale. `dataset` holds the series in levels select ran on, with any scenarios in `dataset.scenarios`; without them, select's `config.scenarios` file is read (relative to the working directory), so scenarios are declared once. The simulation seed is `config.simulation.seed`, else `seed` (project.yaml's), else 0. The caller's `dataset` is not changed. Prints nothing and writes no files. ## Step: diagnose The chosen model tested against its assumptions and against history. diagnose.IDS The identifiers of one step's artefacts, fixed by name, not by creation order. Each artefact a step can make is declared once with its number, so ``T3.2`` stays the stationarity table on every rerun, whatever order the step builds its artefacts in and whichever of them it builds. Add a new artefact under a new number; never renumber one, or documents written earlier point at the wrong table. Parameters ---------- step A step name from `STEP_NUMBERS` (``"explore"``), or a positive number for a step outside the built-in ones. tables, figures, findings Name to number, each number positive and used once per kind. Examples -------- >>> ids = ArtefactIds("explore", tables={"summary": 1, "stationarity": 2}) >>> ids.table("stationarity") 'T3.2' Anomaly(*, period: str, actual: float, fitted: float, residual: float, lower: float, upper: float, z: float) -> None An observation outside the interval ``fitted ± z scale``, on the model's scale. AnomalyConfig(*, level: Annotated[float, Gt(gt=0), Lt(lt=1)] = 0.99, max_share: Annotated[float, Ge(ge=0), Le(le=1)] = 0.05) -> None Observations outside the model's interval. BacktestConfig(*, splitter: str = 'expanding', splitter_config: dict[str, typing.Any] = , level: Annotated[float, Gt(gt=0), Lt(lt=1)] = 0.95, min_coverage: Annotated[float, Ge(ge=0), Le(le=1)] = 0.8) -> None Multi-step forecasts from past origins, through `dz.evaluation.evaluate`. ChowConfig(*, alpha: Annotated[float, Gt(gt=0), Lt(lt=1)] = 0.05, breaks: list[str] = , candidates: list[typing.Annotated[float, FieldInfo(annotation=NoneType, required=True, metadata=[Gt(gt=0), Lt(lt=1)])]] = ) -> None Chow tests at given break dates, or at fixed fractions of the sample. ChowTest(*, period: str, statistic: float, pvalue: float, df_num: int, df_denom: int) -> None A Chow test at `period`: F with `df_num` and `df_denom` degrees of freedom. Cusum(*, alpha: float, periods: tuple[str, ...], values: tuple[float, ...], lower: tuple[float, ...], upper: tuple[float, ...]) -> None The recursive CUSUM (statsmodels `RecursiveLS`) and its bounds, by period. CusumConfig(*, alpha: float = 0.05, max_crossings: Annotated[int, Ge(ge=0)] = 0) -> None The CUSUM tests: the OLS-residual test (a p-value) and the recursive CUSUM's bounds. DiagnoseConfig(*, ljung_box: dazflow.steps.diagnose.LagTest = , breusch_godfrey: dazflow.steps.diagnose.LagTest = , breusch_pagan: dazflow.steps.diagnose.PValueTest = , white: dazflow.steps.diagnose.PValueTest = , arch: dazflow.steps.diagnose.LagTest = , jarque_bera: dazflow.steps.diagnose.PValueTest = , reset: dazflow.steps.diagnose.ResetConfig = , cusum: dazflow.steps.diagnose.CusumConfig = , chow: dazflow.steps.diagnose.ChowConfig = , rolling: dazflow.steps.diagnose.RollingConfig = , backtest: dazflow.steps.diagnose.BacktestConfig = , sensitivity: dazflow.steps.diagnose.SensitivityConfig = , anomalies: dazflow.steps.diagnose.AnomalyConfig = , overrides: list[dazflow.core.gate.Override] = ) -> None Configuration of the diagnose step. DiagnoseResult(*, gate: dazflow.core.gate.Gate = , finding: dazflow.core.finding.Finding | None = None, artefacts: dict[str, typing.Annotated[typing.Union[typing.Annotated[dazflow.core.artefact.Table, Tag(tag='table')], typing.Annotated[dazflow.core.artefact.Figure, Tag(tag='figure')], typing.Annotated[dazflow.core.finding.Finding, Tag(tag='finding')]], Discriminator(discriminator=, custom_error_type=None, custom_error_message=None, custom_error_context=None)]] = , config: dazflow.steps.diagnose.DiagnoseConfig, fingerprint: str | None = None, target: str | None = None, chosen: str | None = None, form: str | None = None, record: dazflow.models._base.ModelRecord | None = None, design: dazflow.models._design.Design | None = None, lags: int = 0, diagnostics: tuple[dazflow.steps.diagnose.Diagnostic, ...] = (), cusum: dazflow.steps.diagnose.Cusum | None = None, rolling: dazflow.steps.diagnose.Rolling | None = None, backtest: dazflow.evaluation._rolling.Evaluation | None = None, base: str | int | None = None, horizon: int = 0, sensitivity: tuple[dazflow.steps.diagnose.Sensitivity, ...] = (), scale: float | None = None, anomalies: tuple[dazflow.steps.diagnose.Anomaly, ...] = ()) -> None What diagnose returns: every diagnostic, the stability paths, the back-test and the rest. `diagnostics` lists every test in a fixed order, applicable or not; `diagnostic(name)` finds one. `scale` is the standard error behind the anomaly interval, on the model's scale. Diagnostic(*, name: str, group: Literal['residuals', 'stability', 'backtest', 'anomalies'], label: str, statistic: float | None = None, pvalue: float | None = None, observed: float | None = None, threshold: float | None = None, op: Optional[Literal['<', '<=', '>', '>=']] = None, applicable: bool = True, reason: str | None = None) -> None One diagnostic: its statistic and p-value, what the gate compares, or why it does not apply. `observed op threshold` passes. A diagnostic that is not `applicable` has a `reason` and no check. LagTest(*, alpha: Annotated[float, Gt(gt=0), Lt(lt=1)] = 0.05, lags: Annotated[int | None, Ge(ge=1)] = None) -> None A p-value test over a number of lags. PValueTest(*, alpha: Annotated[float, Gt(gt=0), Lt(lt=1)] = 0.05) -> None A test read by its p-value: the check passes when the p-value is at least `alpha`. ResetConfig(*, alpha: Annotated[float, Gt(gt=0), Lt(lt=1)] = 0.05, power: Annotated[int, Ge(ge=2)] = 3) -> None Ramsey's RESET: powers of the fitted values added to the regression. Rolling(*, window: int, periods: tuple[str, ...], params: dict[str, tuple[float, ...]]) -> None Rolling-window coefficients (statsmodels `RollingOLS`), by the window's last period. RollingConfig(*, window: Annotated[int | None, Ge(ge=2)] = None) -> None Rolling-window coefficients (statsmodels `RollingOLS`). Sensitivity(*, kind: Literal['shock', 'scenario'], driver: str, scenario: str | int | None = None, size: float | None = None, response: tuple[float, ...], level_response: tuple[float, ...]) -> None One response: to a shock in a driver, or to one driver's scenario path (``all``: every one). `response` is on the model's scale, horizon by horizon; `level_response` on the target's, through its transform chain without a bias correction. `size` is the shock added to the driver's column. SensitivityConfig(*, shock: float = 1.0, scale: Literal['sd', 'unit'] = 'sd', horizon: Annotated[int | None, Ge(ge=1)] = None, base: str | int | None = None) -> None One-at-a-time sensitivity of the forecast to each driver. anomalies(actual: 'pd.Series', fitted: 'pd.Series', scale: 'float', level: 'float') -> 'tuple[Anomaly, ...]' The periods where `actual` lies outside ``fitted ± z scale``, z the normal `level` quantile. A value on a bound is inside. chow(y: 'pd.Series', X: 'pd.DataFrame | None', period: 'Any', *, constant: 'bool' = True) -> 'ChowTest' Chow's F test of a break at `period`: every coefficient may change from `period` on. F = ((RSS_pooled - RSS_1 - RSS_2) / k) / ((RSS_1 + RSS_2) / (n - 2k)), with k coefficients (the drivers and, with `constant`, an intercept), on F(k, n - 2k). Each part needs more than k observations; otherwise a `DiagnoseError`. default_lags(n: 'int', index: 'pd.PeriodIndex') -> 'int' Twice the seasonal period (10 for annual data), at most a fifth of `n` (Hyndman). residual_tests(fitted: 'Any', y: 'pd.Series', X: 'pd.DataFrame | None', config: 'DiagnoseConfig | Mapping[str, Any] | None' = None) -> 'tuple[Diagnostic, ...]' The residual tests of a fitted model, in a fixed order, each applicable or with its reason. `fitted` is a `dz.models.Fitted`; `y` and `X` the data it was fitted on. Ljung-Box (with the ARMA order as `model_df` for an ARIMAX), ARCH and Jarque-Bera take the model's residuals; Breusch-Godfrey, Breusch-Pagan, White and RESET are tests of an OLS regression and are run on the statsmodels OLS fit of the same data. run(dataset: 'Dataset', config: 'DiagnoseConfig | Mapping[str, Any] | None' = None, *, select: 'Any', forecast: 'Any' = None) -> 'DiagnoseResult' Test select's chosen model: residuals, stability, back-test, sensitivity and anomalies. `dataset` holds the series in levels select ran on, with any scenarios in `dataset.scenarios`; without them, select's `config.scenarios` file is read (relative to the working directory). `forecast`, the forecast step's result for the same model, sets the sensitivity horizon. The caller's `dataset` is not changed. Prints nothing and writes no files. ## Step: report The run as a model document, built from the run record alone. report.IDS The identifiers of one step's artefacts, fixed by name, not by creation order. Each artefact a step can make is declared once with its number, so ``T3.2`` stays the stationarity table on every rerun, whatever order the step builds its artefacts in and whichever of them it builds. Add a new artefact under a new number; never renumber one, or documents written earlier point at the wrong table. Parameters ---------- step A step name from `STEP_NUMBERS` (``"explore"``), or a positive number for a step outside the built-in ones. tables, figures, findings Name to number, each number positive and used once per kind. Examples -------- >>> ids = ArtefactIds("explore", tables={"summary": 1, "stationarity": 2}) >>> ids.table("stationarity") 'T3.2' report.TITLES dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2) ReplayTolerance(*, rtol: Annotated[float, Gt(gt=0), Lt(lt=1)] = 1e-09, atol: Annotated[float, Ge(ge=0)] = 1e-12) -> None How closely a replay must reproduce each recorded float (design D43). ReportConfig(*, title: str | None = None, file: Annotated[str, _PydanticGeneralMetadata(pattern='^[^/\\\\]+\\.docx$')] = 'document.docx', replay: dazflow.steps.report.ReplayTolerance = , overrides: list[dazflow.core.gate.Override] = ) -> None ``config/report.yaml``: the document's title and file, and the replay's tolerance. ReportResult(*, gate: dazflow.core.gate.Gate = , finding: dazflow.core.finding.Finding | None = None, artefacts: dict[str, typing.Annotated[typing.Union[typing.Annotated[dazflow.core.artefact.Table, Tag(tag='table')], typing.Annotated[dazflow.core.artefact.Figure, Tag(tag='figure')], typing.Annotated[dazflow.core.finding.Finding, Tag(tag='finding')]], Discriminator(discriminator=, custom_error_type=None, custom_error_message=None, custom_error_context=None)]] = , config: dazflow.steps.report.ReportConfig, title: str, steps: tuple[str, ...] = (), sections: tuple[str, ...] = (), missing: tuple[str, ...] = (), failed: tuple[str, ...] = (), document: Any = None, script: str | None = None) -> None What report returns: the document and replay script (in memory only) and its tables. `steps` are the steps documented, in pipeline order; `sections` the document's section titles; `missing` the pipeline steps before report that the record lacks; `failed` the documented steps whose gate failed. `document` and `script` are not in `to_dict()`: the record they come from holds everything in them. replay_script(config: 'ReportConfig') -> 'str' The replay script: plain Python that reruns the project from its record and compares. run(record: 'Any', config: 'ReportConfig | Mapping[str, Any] | None' = None) -> 'ReportResult' Build the document, its tables and the replay script from a run record. `record` is a `dazflow.pipeline.RunRecord` or its dictionary (a ``reports/record.json`` read as JSON), holding the steps to report. A result of ``report`` in it is not reported on. Prints nothing and writes no files. ## Pipeline, record and replay Run steps in order, keep the run record, and replay it. pipeline.ATOL Convert a string or number to a floating-point number, if possible. pipeline.DEFAULT_STEPS Built-in immutable sequence. If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items. If the argument is a tuple, the return value is the same object. pipeline.RECORD_KIND str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'. pipeline.RTOL Convert a string or number to a floating-point number, if possible. pipeline.SCHEMA_VERSION int([x]) -> integer int(x, base=10) -> integer Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating-point numbers, this truncates towards zero. If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer iteral. >>> int('0b100', base=0) 4 Callable(*args, **kwargs) DatasetRecord(*, fingerprint: Annotated[str, _PydanticGeneralMetadata(pattern='^[0-9a-f]{64}$')], path: str | None = None) -> None A step's dataset: its fingerprint and, when the project folder holds it, its path. Difference(*, path: str, recorded: Any = None, found: Any = None, note: str | None = None) -> None One recorded value the replay did not reproduce: where it is, and both values. `path` names it in the record (``results.select.ranking[0].mase``); `recorded` is the record's value and `found` the replay's (or the project's current value, for a configuration that changed since the run). Environment(*, python: str, implementation: str, platform: str, machine: str, packages: dict[str, str]) -> None Where the run ran: Python, platform and the versions of dazflow and its dependencies. InputRecord(*, step: Annotated[str, MinLen(min_length=1)], name: Annotated[str, MinLen(min_length=1)], path: str | None = None, kind: Annotated[str, _PydanticGeneralMetadata(pattern='^(file-sha256|dataset)$')], fingerprint: Annotated[str, _PydanticGeneralMetadata(pattern='^[0-9a-f]{64}$')]) -> None One input a run read: a file by the SHA-256 of its bytes, or a frame by its fingerprint. `path` is the path as configured, relative to the project folder when it was. Pipeline(steps: 'Sequence[str]' = ('ingest', 'clean', 'explore', 'build', 'select', 'forecast', 'diagnose', 'report'), *, registry: 'Registry | None' = None, adapters: 'Registry | None' = None) -> 'None' Steps placed by name, run in order, each through its adapter. Steps never see each other: the pipeline passes an earlier result to a later step through the later step's adapter. Parameters ---------- steps Step names in the order they run, each registered in `registry`. Defaults to `DEFAULT_STEPS`. registry Where steps are looked up; `dazflow.steps.registry` by default. adapters How each step is called; `dazflow.pipeline.adapters` by default. A step with no adapter is called as ``run(dataset, config)`` with the latest dataset. Replay(*, record_id: str, steps: tuple[str, ...] = (), rtol: float = 1e-09, atol: float = 1e-12, differences: tuple[dazflow.pipeline._replay.Difference, ...] = (), notes: tuple[str, ...] = (), record: dazflow.pipeline._record.RunRecord | None = None) -> None What a replay found: the steps rerun, the tolerance and every difference. `passed` when there is no difference. `notes` say what differs without counting as a difference, such as another Python or package version. `record` is the replayed run's record, kept in memory only. Run(pipeline: 'tuple[str, ...]', steps: 'tuple[str, ...]', results: 'Mapping[str, StepResult]', configs: 'Mapping[str, Config]', started: 'str', finished: 'str', carried: 'tuple[str, ...]' = (), start: 'str | None' = None, stop: 'str | None' = None, stopped_at: 'str | None' = None, inputs: 'tuple[InputRecord, ...]' = (), carried_record: 'RunRecord | None' = None, environment: 'Environment | None' = None) -> None One pass through a pipeline. Nothing in it has been written anywhere. `results` and `configs` hold every step up to the last run, in pipeline order: those run now (`steps`) and those carried from an earlier record (`carried`). The run stops after a step whose gate fails; that step is `stopped_at`, and the steps after it are not run. RunInfo(*, id: Annotated[str, MinLen(min_length=1)], started: str, finished: str, start: str | None = None, stop: str | None = None, steps: tuple[str, ...] = (), carried: tuple[str, ...] = (), status: Literal['passed', 'gate_failed'], stopped_at: str | None = None) -> None When the run happened, what it ran and how it ended. `steps` were run; `carried` were taken from an earlier record unchanged. `status` is ``passed``, or ``gate_failed`` when the run stopped at `stopped_at` because that step's gate failed. RunRecord(*, schema_version: Literal[1] = 1, kind: Literal['dazflow.record'] = 'dazflow.record', run: dazflow.pipeline._record.RunInfo, project: dict[str, typing.Any] | None = None, pipeline: tuple[str, ...], config: dict[str, dict[str, typing.Any]], results: dict[str, dict[str, typing.Any]], checks: tuple[dict[str, typing.Any], ...] = (), overrides: tuple[dict[str, typing.Any], ...] = (), environment: dazflow.pipeline._record.Environment, inputs: tuple[dazflow.pipeline._adapters.InputRecord, ...] = (), datasets: dict[str, dazflow.pipeline._record.DatasetRecord] = ) -> None The run record, written as ``reports/record.json``. Fields: - `schema_version` and `kind`: the format; `load` refuses another version. - `run`: identifier, times, steps run and carried, status. - `project`: the project configuration as run, defaults filled in (or None). - `pipeline`: the step names in order. - `config`: each step's configuration as run, every default filled in. - `results`: each step's `StepResult.to_dict()`. - `checks`: every gate check of every step, with its step. - `overrides`: every configured gate override, with its step. - `environment`: Python, platform and package versions. - `inputs`: a fingerprint of every input read. - `datasets`: each step's dataset fingerprint and path. StepInputs(step: 'str', results: 'Mapping[str, StepResult]', dataset: 'Dataset | None' = None, root: 'Path | None' = None, data: 'Mapping[str, Any] | None' = None, previous: 'Dataset | None' = None, seed: 'int | None' = None, inputs: 'list[InputRecord]' = , recorder: 'Callable[[], Any] | None' = None, project: 'Any' = None) -> None What a step's adapter has to call the step with. `results` holds the earlier steps' results in pipeline order (run now, or carried from an earlier run's record); `dataset` is the dataset of the latest of them that holds one. `root` is the project folder that relative paths are read from (``None``: as given). `data` holds frames passed in memory, by input name; `previous` the previous data vintage; `seed` the project's seed (``project.yaml: seed``) for a step's random draws. An adapter appends what it read to `inputs`. `record()` gives the run record of the steps before this one, for a step that reports on them. pipeline.adapters Components of one kind, looked up by the key configuration names them by. Components are added with the `register` decorator, or by a third-party package through the ``dazflow.plugins`` entry-point group. Each entry point names a module (``name = package.module``, or ``package.module:attr``); loading it imports the module, whose decorators register its components. Entry points are loaded on the registry's first lookup, once. Parameters ---------- kind : str What the registry holds, for messages: ``"model"``, ``"reader"``. protocol : type, optional Optional `typing.Protocol` every component must have the members of. Examples -------- >>> widgets = Registry("widget") >>> @widgets.register("plain") ... class Plain: ... >>> widgets["plain"] is Plain True compare(recorded: 'Any', found: 'Any', *, rtol: 'float' = 1e-09, atol: 'float' = 1e-12, path: 'str' = '') -> 'list[Difference]' Every difference between two JSON values, by path. Two numbers of which one is a float match when ``|a - b| <= max(rtol * max(|a|, |b|), atol)`` (`math.isclose`); two integers, and everything that is not a number, must be equal and of the same type (``True`` is not ``1``). Dictionaries are compared key by key, lists position by position; a missing key, an extra key or another length is a difference. compare_records(recorded: 'RunRecord', replayed: 'RunRecord', *, rtol: 'float' = 1e-09, atol: 'float' = 1e-12) -> 'tuple[Difference, ...]' The differences between a record and its replay, inputs first, then in pipeline order. Compared: every input's fingerprint, the steps run and the status, each step's dataset fingerprint, and each step's result in full. The configuration is the replay's own input, and the environment is reported by `environment_notes`, not compared. default_adapter(step: 'Any', config: 'Config', inputs: 'StepInputs') -> 'StepResult' ``step.run(dataset, config)`` with the latest dataset: the common case. environment() -> 'Environment' The running environment, with dazflow's installed version and its requirements'. file_sha256(path: 'str | Path') -> 'str' The SHA-256 of a file's bytes; a folder hashes its files' relative paths and bytes. register_adapter(step: 'str') -> 'Callable[[Adapter], Adapter]' Decorator: the function the pipeline calls the step named `step` through. replay(record: 'RunRecord | str | Path', *, root: 'str | Path | None' = None, data: 'Mapping[str, Any] | None' = None, previous: 'Any' = None, rtol: 'float' = 1e-09, atol: 'float' = 1e-12) -> 'Replay' Rerun every step of `record` from its recorded configuration and inputs, and compare. `record` is a `RunRecord` or the path of a ``record.json``. `root` is the folder its relative input paths are read from. A run that read frames in memory needs them again in `data`, by input name; the previous vintage is read from the record's ``project: previous`` unless given here. Prints nothing and writes no files. ## Project folder A project on disk: its configuration, datasets and reports. project.DATASET_FORMAT str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'. project.PROJECT_FILE str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'. project.RECORD_PATH str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'. Project(root: 'str | Path', config: 'ProjectConfig') -> 'None' A project folder: ``project.yaml``, ``config/.yaml``, data and reports. `run()` reads the folder and writes nothing; `write(run)` writes the datasets, each step's artefacts under ``reports//`` and ``reports/record.json``. ProjectConfig(*, name: Annotated[str, MinLen(min_length=1)], description: str | None = None, pipeline: list[str] = , seed: int = 0, style: str | None = None, previous: dazflow.readers._base.ReadSpec | None = None) -> None ``project.yaml``: the project's name, its pipeline and the settings every step shares. commented_yaml(config: 'BaseModel', header: 'str | None' = None) -> 'str' `config` as YAML: every field in declaration order, defaults filled in, described. Loading the text back gives ``config.model_dump(mode="json")``. `header` lines are written first, as comments. init(root: 'str | Path', name: 'str | None' = None) -> 'Project' Create a project in `root` (new or empty) with commented defaults and example data. The example runs as it is: ``dazflow validate`` and ``dazflow run`` pass. load(root: 'str | Path' = '.') -> 'Project' The project in folder `root`. read_dataset(path: 'str | Path', fingerprint: 'str | None' = None) -> 'Dataset' The dataset `write_dataset` wrote to `path`, checked against its fingerprint. `fingerprint`, when given, must also match: the one the run record holds. schema_path(path: 'str | Path') -> 'Path' The schema file next to a dataset CSV: ``ingest.csv`` -> ``ingest.schema.json``. write_dataset(dataset: 'Dataset', path: 'str | Path') -> 'Path' Write `dataset` as ```` (CSV, first column ``period``) and its schema file. The CSV is readable by the csv reader as it is; the schema keeps the series metadata, the log and the fingerprint, which `read_dataset` checks. Panels and scenarios are not written yet. ## Testing The contract suites every component passes. ---------------------------------------------------------------------- This is the User Guide documentation for the package. ---------------------------------------------------------------------- ## Guide ### Get started Building a time-series model means the same steps every time, and much of the effort goes into turning their output into a document. `dazflow` runs the steps from configuration and renders every result in one house style. This page follows one project, the example that `dazflow init` writes, through the main ideas. Every output below is pasted from a real run. ```sh pip install dazflow dazflow init loss-rate ``` ``` created loss-rate (11 files); next: dazflow validate -p loss-rate ``` The folder holds `project.yaml`, one file per step under `config/` with every setting written out at its default, and example data under `data/raw/`: a quarterly loss rate, two drivers (GDP growth and unemployment) and three scenarios for them. ## Run the pipeline ```python import dazflow as dz project = dz.project.load("loss-rate") run = project.run() run.passed, run.steps ``` ``` (True, ('ingest', 'clean', 'explore', 'build', 'select', 'forecast', 'diagnose', 'report')) ``` `project.run()` runs every step in memory and writes nothing. Each step's result is in `run.results`, by step name. ## Gates and findings Every step ends in a gate: checks of its numbers against thresholds set in configuration. Explore's checks that each driver has its expected sign and is significant: ```python ex = run.results["explore"] ex.gate.passed, [c.name for c in ex.gate.checks] ``` ``` (True, ['sign:gdp_growth', 'significance:gdp_growth', 'sign:unemployment', 'significance:unemployment']) ``` A finding is a sentence from a template, filled with the step's numbers; `dz.render.finding_text` writes them in the house style, as the reports and the command line do (`ex.finding.text` keeps them as computed): ```python print(dz.render.finding_text(ex.finding)) ``` ``` 3 series explored; 2 were differenced to stationarity. 2 of 2 drivers are kept, 0 of them by override: each has its expected sign and a p-value of at most 0.05. ``` A failed check is reported, never hidden, and is accepted only with a reason written in configuration. The example's RESET test fails, and `config/diagnose.yaml` overrides it: ```python check = run.results["diagnose"].gate["reset"] check.status, round(check.observed, 3), check.threshold ``` ``` ('overridden', 0.027, 0.05) ``` ```python print(check.override.reason) ``` ``` Example data: RESET rejects the linear form at 5% (p = 0.03). The series were made up for the example; a real model would revisit its functional form before use. ``` ## Tables and figures Tables and figures carry stable identifiers, `T.` and `F.`, that survive reruns, so a document can cite them. ```python sorted(ex.artefacts) ``` ``` ['F3.1', 'S3.1', 'T3.1', 'T3.2', 'T3.3', 'T3.4'] ``` ```python print(dz.render.render(ex.artefacts["T3.3"], "markdown")) ``` ``` Table T3.3. Driver screen | Driver | Lag | Correlation | Coefficient | Standard error (HAC) | t | p-value | Observations | Expected sign | Observed sign | Result | | :--- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | :--- | :--- | :--- | | gdp\_growth | 0 | -0.84 | -0.15 | 0.01 | -18.95 | 0.00 | 119 | negative | negative | Pass | | unemployment | 0 | 0.90 | 0.39 | 0.02 | 21.49 | 0.00 | 119 | positive | positive | Pass | Each driver is regressed alone on the transformed target at the lag of strongest correlation (0 to 4); it is kept with its expected sign and a p-value of at most 0.05. ``` The same table renders to `html` and `docx`, and figures to `svg` and `png`, through `dz.render.render` and `dz.render.write`. ## One step at a time Each step is also one call that takes a dataset and its configuration. A later step takes an earlier one's result as an argument rather than importing it, so any step can run on its own: ```python ds = run.results["clean"].dataset ds.targets, ds.drivers ``` ``` (('loss_rate',), ('gdp_growth', 'unemployment')) ``` ```python again = dz.explore.run(ds, project.step_config("explore")) again.finding.text == ex.finding.text ``` ``` True ``` Select scores every candidate out of sample and proposes one; the proposal stands until it is confirmed in `config/select.yaml`: ```python sel = run.results["select"] sel.chosen, sel.decision ``` ``` ('ols:gdp_growth+unemployment', 'proposed') ``` ## Write, report and replay `project.write(run)` writes the datasets, every step's tables, figures and finding under `reports//`, the Word document, and the run record. ```python record = project.write(run) record.run.status, sorted(p.name for p in (project.root / "reports").iterdir()) ``` ``` ('passed', ['build', 'clean', 'diagnose', 'document', 'explore', 'forecast', 'ingest', 'record.json', 'report', 'select']) ``` ```python sorted(p.name for p in (project.root / "reports" / "document").iterdir()) ``` ``` ['document.docx', 'replay.py'] ``` The document is built from the run record alone: a contents list, a summary, one section per step in pipeline order and the configuration in an appendix. A replay reruns every step from the record and compares every recorded number with what it computes now, floats within a relative 1e-9 and everything else exactly: ```python replay = project.replay() replay.passed, replay.differences ``` ``` (True, ()) ``` ## Score any form Any model form, built in or not, can be scored out of sample by refitting it at successive origins: ```python y = ds.frame["loss_rate"] X = ds.frame[["gdp_growth", "unemployment"]] ev = dz.evaluation.evaluate( dz.models.get("ols")(), y, X, splitter=dz.evaluation.Expanding(initial=80, horizon=4), ) round(ev.score("rmse"), 3), round(ev.score("coverage"), 3) ``` ``` (0.077, 0.919) ``` That is the root mean squared error over the four horizons, and the share of actual values inside the 95% interval. ## Where next [Command line](command-line.qmd) runs the same project from a shell, and [Writing a plugin](writing-a-plugin.qmd) adds a model form of your own. The API reference lists every public name, by layer. ### Command line The `dazflow` command runs a project folder: the same steps, configuration and outputs as `dz.project.load(...).run()` and `.write()`. It is installed with the package; `python -m dazflow` works too. Every output below is pasted from a real run. ```sh $ dazflow --help Usage: dazflow [OPTIONS] COMMAND [ARGS]... A time-series modelling workflow whose every step returns documented artefacts. ╭─ Commands ───────────────────────────────────────────────────────────────────────────╮ │ init Create a project folder with commented defaults and example data. │ │ validate Check the configuration and that every input reads, without running a │ │ step. │ │ run Run the pipeline's steps in order; stop after a step whose gate fails │ │ (exit 2). │ │ replay Rerun every step from reports/record.json and compare; exit 2 on a │ │ difference. │ │ show Print one table or finding of the last run (a figure: its file). │ │ plugins List the registered components of every kind, built in and from plugins. │ │ build Run the build step on the project, from the last run's earlier results; │ │ write reports/build/. │ ... ╰──────────────────────────────────────────────────────────────────────────────────────╯ ``` Every command but `init` works on the project in the current folder, or the one `-p/--project` names. ## A project `dazflow init` writes a project folder: `project.yaml`, one commented file per step under `config/` with every setting at its default, and example data. `validate` reads the configuration and every input without running a step. ```sh $ dazflow init loss-rate created loss-rate (11 files); next: dazflow validate -p loss-rate $ cd loss-rate $ dazflow validate loss-rate: valid; steps ingest, clean, explore, build, select, forecast, diagnose, report; 2 inputs read ``` ## Running steps `dazflow run` runs the pipeline in order and writes each step's tables, figures and finding to `reports//`, its dataset to `data/`, and the run record to `reports/record.json`. `--to` stops after a step: ```sh $ dazflow run --to explore ingest: gate passed; 4 artefacts in reports/ingest/ 3 of 3 configured series were found and put on a quarterly calendar from 1995Q1 to 2024Q4. The targets and drivers overlap on 120 quarters, against a minimum of 40. clean: gate passed; 5 artefacts in reports/clean/ 7 checks on 3 series flagged 1 periods before treatment. 0 treatments changed 0 values. After treatment, 0 of 12 checks fail. explore: gate passed; 6 artefacts in reports/explore/ 3 series explored; 2 were differenced to stationarity. 2 of 2 drivers are kept, 0 of them by override: each has its expected sign and a p-value of at most 0.05. ``` `--from` carries the earlier steps from the last record, their datasets read back and checked against the recorded fingerprints, and runs the rest: ```sh $ dazflow run --from build build: gate passed; 6 artefacts in reports/build/ 3 candidates were fitted on 3 driver combinations of up to 2 drivers, beside 2 benchmarks; 3 pass every check: each driver has its expected sign and a p-value of at most 0.05, and no VIF exceeds 10.00. select: gate passed; 8 artefacts in reports/select/ 5 models were scored at 60 origins, their errors scaled by the mean benchmark's; the model confidence set at 0.10 holds 1 of them, 1 passing every check. ols:gdp_growth+unemployment is proposed: 2 drivers and a scaled error of 0.39. ... report: gate passed; 6 artefacts in reports/report/ The document reports 7 steps, ingest to diagnose, in pipeline order, with 26 tables, 10 figures and 7 findings. Every step's gate passed, 1 check by override with a reason. ``` Each step is also a command of its own: `dazflow select` is `dazflow run --from select --to select`. A step from a plugin gets its command the same way. ## Reading the results `dazflow show` prints one table or finding of the last run by its identifier, or the path of a figure. Tables and findings are written in the project's style, as in `reports//`: ```sh $ dazflow show T6.1 Table T6.1. Ranking of the candidates | Rank | Candidate | Role | Drivers | Scaled error | In the confidence set | MCS p-value | Build checks | Beats the benchmark | Scenarios out of order | Projections out of bounds | Choice | Passes every check | | ---: | :--- | :--- | ---: | ---: | :--- | ---: | :--- | :--- | ---: | ---: | :--- | :--- | | 1 | ols:gdp\_growth+unemployment | candidate | 2 | 0.39 | yes | 1.00 | pass | yes | 0 | 0 | chosen | Pass | | 2 | ols:unemployment | candidate | 1 | 0.49 | no | 0.01 | pass | yes | 0 | 0 | | Pass | | 3 | ols:gdp\_growth | candidate | 1 | 0.54 | no | 0.01 | pass | yes | 0 | 0 | | Pass | | 4 | mean | benchmark | 0 | 1.00 | no | 0.00 | pass | no | 0 | 0 | | **Fail** | | 5 | naive | benchmark | 0 | 1.27 | no | 0.00 | pass | no | 0 | 0 | | **Fail** | Scaled error: the candidate's rolling-origin RMSE over the mean benchmark's; it beats the benchmark below 1. $ dazflow show S6.1 5 models were scored at 60 origins, their errors scaled by the mean benchmark's; the model confidence set at 0.10 holds 1 of them, 1 passing every check. ols:gdp_growth+unemployment is proposed: 2 drivers and a scaled error of 0.39. $ dazflow show F3.1 F3.1: Lag profiles: correlation of each driver with loss_rate, by lag reports/explore/F3.1.svg ``` `--json` on `run`, `validate`, `show`, `replay` and `plugins` prints the result as JSON instead; for `run` it is the run record. ## Gates and exit status `0` when every gate passed, `1` on an error (its message, what was observed and what to change go to stderr), `2` when a gate failed. A failed gate stops the run after that step, which is still written, with the record's status `gate_failed`. The example's RESET test fails and is accepted by an override in `config/diagnose.yaml`; with the override removed: ```sh $ dazflow run --from diagnose diagnose: gate FAILED (reset); 9 artefacts in reports/diagnose/ ols:gdp_growth+unemployment passes 11 of 12 diagnostic checks and fails reset. Back-tested from 57 origins up to 4 periods ahead, its 95% interval covered 0.96 of the actual values, and 1 of 119 observations lie outside its 99% interval. stopped after diagnose: its gate failed $ echo $? 2 ``` An error names what it found and what to change: ```sh $ dazflow validate error: the IngestConfig YAML does not parse observed: duplicate key 'frequency' in "", line 48, column 1: frequency: X ^ change: Correct the YAML syntax at the position given. $ echo $? 1 ``` ## Report and replay The `report` step, last in the default pipeline, writes the Word document and a replay script to `reports/document/`. `dazflow replay` reruns every step from the record and compares each recorded number with what it computes now (floats within a relative 1e-9, the rest exactly), and also checks that `project.yaml` and `config/` still equal the recorded configuration. It exits `0` on a match and `2` on a difference; the script does the same without the command line. ```sh $ dazflow report report: gate passed; 6 artefacts in reports/report/ The document reports 7 steps, ingest to diagnose, in pipeline order, with 26 tables, 10 figures and 7 findings. Every step's gate passed, 1 check by override with a reason. $ dazflow replay replay of run 20261126T005350Z-ff9f2976 (8 steps rerun): matches its record (rtol 1e-09, atol 1e-12) $ python reports/document/replay.py replay of run 20261126T005350Z-ff9f2976 (8 steps rerun): matches its record (rtol 1e-09, atol 1e-12) ``` ## Plugins `dazflow plugins` lists the registered components by kind, built in and from installed plugins (see [Writing a plugin](writing-a-plugin.qmd)): ```sh $ dazflow plugins step: build, clean, diagnose, explore, forecast, ingest, report, select step adapter: build, clean, diagnose, forecast, ingest, report, select reader: csv, excel, parquet check: completeness, duplicates, gaps, outliers, range, representativeness, revisions transform: boxcox, diff, growth, log, logdiff, logit, seasonal_diff renderer: docx, html, markdown, png, svg ``` ### Writing a plugin A model form, quality check, transform, reader or step is registered once under a key, and then named in configuration like a built-in one. This page adds a model form, a random walk with drift, in a package of its own; the other kinds register the same way, through their own `register` decorator. Every output below is pasted from a real run. ## The form A form subclasses `dz.models.ModelForm` and sets its `Config` and `_fit`. `_fit` returns a `dz.models.FittedModel` holding the parameters, their covariance and the fitted values; the fitted model's `_predict` returns the mean and, for each interval level, the lower and upper bounds. `@dz.models.register("drift")` adds it to `dz.models.registry` under the key that configuration names it by. ```python # dazflow_drift.py import numpy as np import pandas as pd from scipy.stats import norm import dazflow as dz class DriftConfig(dz.Config): """The drift form has no parameters of its own.""" class FittedDrift(dz.models.FittedModel): def _predict(self, h, X_future, levels): steps = np.arange(1, h + 1) mean = self._y.iloc[-1] + self.params["drift"] * steps sd = np.sqrt(self.params["sigma2"] * steps) half = [norm.ppf(0.5 + level / 2) * sd for level in levels] return mean, [mean - w for w in half], [mean + w for w in half] @dz.models.register("drift") class Drift(dz.models.ModelForm): """A random walk with drift: y[t] = y[t-1] + drift + e[t].""" Config = DriftConfig def _fit(self, y, X, spec): change = y.diff().dropna() drift = change.mean() sigma2 = ((change - drift) ** 2).mean() n = len(change) names = ["drift", "sigma2"] return FittedDrift( spec, y, None, params=pd.Series([drift, sigma2], index=names), cov_params=pd.DataFrame( np.diag([sigma2 / n, 2 * sigma2**2 / n]), index=names, columns=names ), fitted_values=y.shift(1).iloc[1:] + drift, ) ``` The form takes no drivers (`drivers` is `False` by default), so `fit` refuses any. A form that takes them sets `drivers = True` and receives them as `X`. ## Registering it In a script or a notebook, `import dazflow_drift` runs the decorator and the form is there. For every project to find it without an import, the package declares the module in the `dazflow.plugins` entry-point group: ```toml # pyproject.toml of the plugin's package [project] name = "dazflow-drift" version = "0.1.0" dependencies = ["dazflow"] [project.entry-points."dazflow.plugins"] drift = "dazflow_drift" ``` Once the package is installed, a registry's first lookup imports every module in the group, so the form is found by its key: ```python import dazflow as dz dz.models.registry.keys() ``` ``` ('arimax', 'drift', 'ets', 'glm', 'mean', 'naive', 'ols', 'seasonal_naive') ``` ## Using it The form fits and forecasts like a built-in one. On the example project's loss rate: ```python project = dz.project.load("loss-rate") y = dz.ingest.run(project.step_config("ingest"), root=project.root).dataset.frame["loss_rate"] fit = dz.models.get("drift")().fit(y) fit.params.round(4).to_dict() ``` ``` {'drift': 0.0003, 'sigma2': 0.0098} ``` ```python print(fit.predict(4).frame().round(3)) ``` ``` mean lower_0.8 upper_0.8 lower_0.95 upper_0.95 2025Q1 2.016 1.889 2.143 1.822 2.211 2025Q2 2.017 1.837 2.196 1.742 2.291 2025Q3 2.017 1.797 2.237 1.680 2.354 2025Q4 2.017 1.763 2.271 1.629 2.406 ``` It is scored out of sample against the naive random walk the same way: ```python splitter = dz.evaluation.Expanding(initial=80, horizon=4) { key: round(dz.evaluation.evaluate(dz.models.get(key)(), y, splitter=splitter).score("rmse"), 4) for key in ["naive", "drift"] } ``` ``` {'naive': 0.1487, 'drift': 0.1518} ``` In a project, configuration names it. A form without drivers is a benchmark, so it goes into `config/build.yaml` beside the built-in ones: ```yaml # loss-rate/config/build.yaml benchmarks: - form: naive config: {} - form: mean config: {} - form: drift config: {} ``` ```python run = project.run(stop="build") [(c.id, c.role) for c in run.results["build"].candidates] ``` ``` [('naive', 'benchmark'), ('mean', 'benchmark'), ('drift', 'benchmark'), ('ols:gdp_growth', 'candidate'), ('ols:unemployment', 'candidate'), ('ols:gdp_growth+unemployment', 'candidate')] ``` Select then scores it with the other candidates, and the run record keeps its specification and parameters, so `dazflow replay` refits it. ## The contract `dazflow.testing.ModelContract` holds the tests every form passes, built-in or not: it is found by its key, it is built from its configuration, its fit leaves the data unchanged, its forecast covers the horizon with nested intervals, a refit from the stored record repeats the fit, and drivers are used or refused. A subclass names the key: ```python # tests/test_drift.py from dazflow.testing import ModelContract class TestDrift(ModelContract): key = "drift" ``` ```sh pytest tests/test_drift.py -v ``` ``` tests/test_drift.py::TestDrift::test_key_is_registered PASSED [ 10%] tests/test_drift.py::TestDrift::test_lookup_returns_the_registered_component PASSED [ 20%] tests/test_drift.py::TestDrift::test_component_follows_the_protocol PASSED [ 30%] tests/test_drift.py::TestDrift::test_config_is_a_dazflow_config PASSED [ 40%] tests/test_drift.py::TestDrift::test_form_is_built_from_its_config PASSED [ 50%] tests/test_drift.py::TestDrift::test_fit_returns_a_fitted_model PASSED [ 60%] tests/test_drift.py::TestDrift::test_predict_covers_the_horizon_with_nested_intervals PASSED [ 70%] tests/test_drift.py::TestDrift::test_fit_leaves_its_inputs_unchanged PASSED [ 80%] tests/test_drift.py::TestDrift::test_refit_from_the_stored_record_repeats_the_fit PASSED [ 90%] tests/test_drift.py::TestDrift::test_drivers_are_used_or_refused PASSED [100%] ============================== 10 passed in 2.32s ============================== ``` The contract fits the form on `dazflow.testing.sample_series()`, a quarterly share with two drivers. A subclass can set `config` (the form's parameters under test), `sample()` (other data) and `refit_tolerance`.