Separate single models from a forecast ledger and forecasts-vs-actuals tracking
Status: proposed (2026-11-29). Becomes accepted when the Slice 1 implementation merges.
Long-lived credit-risk projects need to maintain models across monthly and quarterly cycles, compare forecasts against realized actuals as observation dates arrive, and reconcile loan-level and aggregate-only lenses without duplicating governance plumbing per workflow. We will introduce a lazy-loaded cranalytics.forecasting subpackage that separates stateless single models from an append-only forecast ledger and pure in-process forecasts-vs-actuals tracking.
Slice 1 is the first implementation PR series: the ledger, the store port with its three built-in adapters, tracking, rollup, and the two lens adapters listed under Consequences. Backtests and champion/challenger promotion come after it. Names, arguments and defaults below are the Slice 1 target; the implementation PRs may rename them without reopening this decision, as long as the five commitments hold.
Five commitments anchor the seam:
- Stateless single models. A model is a plain callable
(data, forecast_as_of) -> DataFrame, never a stateful model registry or serialized weights store.ForecastLedger.run()fingerprints input data before calling the model;ForecastLedger.log()records pre-computed or external forecasts through the same contract (with optionalsource_data/data_fingerprint). - Append-only 3-method persistence port for forecasts only.
ForecastStoreexposesappend_run,list_runs, andload_forecastswith no update or delete methods. Realized actuals are passed at tracking time rather than stored in the ledger, so restatements (late charge-offs, cure reversals, data fixes) never create stale truth inside the store. Internal storage uses one canonical long-format schema (metric,predicted, optionaldenominator,scenario, dualtarget_date/mobaxes,tags, optionalparent_run_id) backed by zero-dependency built-in adapters (InMemoryStore, Parquet+JSONLFileStorevia corepyarrow, andSQLiteStorevia stdlibsqlite3with dynamicdimensions_json). Custom DuckDB, SQLAlchemy, or warehouse stores plug into the same port. - Explicit 4-kind metric algebra and leakage guards. Every metric is classified as
flow,balance,rate, orcumulative_rate. Both wide canonicalcranalyticsframes and canonical long frames are accepted at the seam. The canonical long frame is validated by a Pandera schema incranalytics.validation, as AGENTS.md requires of every public entry point; metric kinds are checked against built-in defaults plus explicitmetrics=overrides, raisingUnknownMetricErroron undeclared numeric columns rather than guessing. Rates are stored as dollars, not as ratios. Arateorcumulative_ratemetric is recorded as its numerator inpredicted(dollars or units) and its denominator indenominator, and the kind fixes the denominator's basis: the period's denominator, typically beginning-of-period balance, forrate(such as a monthly charge-off rate), and the cohort's origination balance forcumulative_rate(such as cumulative loss rate by MOB). Wide inputs that carry a rate column must also carry its denominator column, and the seam multiplies them out. Every rate, rollup and A/E is then derived as summed numerators over summed denominators, so no weight can be applied twice or on the wrong basis. A rate supplied without its denominator raises unlessallow_unweighted_rates=Trueis passed; such a rate is stored flagged as unweighted and is never rolled up across grains. A/E ratio is always ratio-of-aggregates, never a mean of cell ratios. Record-time lookahead (allow_in_sample=False) and tracking-timemin_horizon=1are enforced by default, withtarget_datealigned by monthly period (YYYY-MM, optional exact-date mode) and unmatched rows split intopending_futurevs.missing_actual. - Isolated workflow adapters, not a ninth workflow. Built-in
cranalyticslens and actuals adapters live in a lazycranalytics.forecasting.adapterssubmodule. The forecasting core never imports existing workflow modules, preserving lazy package startup and leaving existing workflow interfaces untouched. Forecasting is a seam across workflows, not a workflow of its own: it gets nocranalytics <workflow>CLI command and noca.checkdetection, and the package keeps its eight workflows. Tracking still returns aWorkflowResultsubclass (ForecastTrackingResult) per ADR-0001, and that type joins the ADR-0001 contract test (tests/test_workflow_result_contract.py). - Tracking compares like with like: one scenario and one closed pool per run. Every forecast run carries a
scenariokey (default"baseline") and a fingerprint of the macro assumption path it was run on. A probability-weighted forecast is recorded as one run per scenario plus the weights, never as a single pre-blended run, so tracking can report A/E for each scenario and for the weighted blend. Separating model error from macro error is a rerun of the stateless model on realized macro inputs, recorded as a new run withparent_run_idpointing at the original. Each run also records its population as offorecast_as_of: entity ids at loan grain, or cohort keys with their balances at aggregate grain. Tracking matches actuals for that population only and reports actuals for loans or cohorts booked afterforecast_as_ofasout_of_populationrather than folding them into A/E. Aggregate actuals that cannot separate those later bookings raise unlessallow_open_pool=Trueis passed.
Considered options
- Stateful
Modelbase class + weight registry (MLflow-style). Rejected: forces framework ceremony on custom user code, breaks the DataFrame-first rule inAGENTS.md, and duplicates dedicated MLOps tools.ForecastLedgerandForecastStoreare service objects that hold no domain state of their own; forecasts and runs stay DataFrames. - Storing actuals snapshots inside
ForecastStore. Rejected: actuals restate frequently in lending portfolios; versioning restatements inside the ledger doubles persistence complexity and widens custom DB adapters. Reproducibility comes from fingerprinting the actuals at tracking time instead (see Consequences). - Canonical long-format input only (no wide input support). Rejected: forces every analyst and lens wrapper to write repetitive melt/rename boilerplate when
cranalyticsalready has well-defined metric column names; strictUnknownMetricErrorprevents silent guessing while keeping ergonomics high. - Storing rates with separate weight columns. Rejected: period rates and cumulative rates have different denominators, and a stored ratio plus a weight invites applying the wrong one, such as weighting a cumulative loss rate by current balance, which overweights seasoned cohorts that have already paid down. Storing numerators and denominators makes the right weighting the only one available.
- One pre-blended run for a probability-weighted forecast. Rejected: A/E against a blend mixes model error with the gap between assumed and realized macro conditions, and the blend cannot be taken apart afterwards.
- Tracking against whole-book actuals (open pool). Rejected: actuals that include loans booked after
forecast_as_ofmove A/E with origination volume rather than with forecast accuracy. - Bundling DuckDB or SQLAlchemy as a mandatory dependency. Rejected: keeps core installs lightweight while
pyarrowParquet + stdlibsqlite3cover local files and embedded SQL out of the box andForecastStorestays open for warehouse adapters. - Building a full backtest and champion/challenger framework in Slice 1. Rejected: the ledger + forecasts-vs-actuals seam must soak first;
tagsandparent_run_idreserve the hooks so rolling-origin backtests, champion/challenger promotion, and generalizedreserve_walkrevision attribution layer cleanly on top later.
Consequences
cranalytics.forecastingwill ship four public core names (ForecastLedger,track_forecasts,rollup_forecasts,ForecastStore) and is not added to top-levelcranalytics.__all__in Slice 1.ForecastTrackingResult.assumptions()records a fingerprint of the actuals passed in and a caller-suppliedactuals_as_of, alongside the run fingerprints, so an A/E result can be reproduced after the actuals restate.UnknownMetricErrorand the other forecasting errors adopt whichever shared structured error shape JOS-50 settles on, rather than defining their own.actuals_from_rollforwardandactuals_from_loan_historytake the run's population and return actuals for it, with later bookings split out asout_of_population. Thescenariosmulti-scenario runner's output maps onto one run per scenario.- Loan-to-aggregate rollup supports both record-time
rollup_cols(point-in-time cohort attributes) and evaluation-timeentity_map(retrospective segmentation) withunmapped_policy="raise"by default. - Slice 1 proves both grains and both time axes with two built-in lens adapters (
loss_forecastingloan-level andvintageaggregate-only) and two actuals helpers (actuals_from_loan_history,actuals_from_rollforward), plus one shared parameterized contract test suite acrossInMemoryStore,FileStore, andSQLiteStore. - Out-of-time backtesting stays in
rollforwardfor now: the historical holdout evaluation (JOS-67) and transition-matrix backtests (JOS-75) build on the existingrun_rollforward_backtest_sweepsandselect_rollforward_champion_and_challengers, not on the ledger. Future work can migraterollforward's backtesting/champion selection andvintage's champion selection onto this shared modeling-system seam without breaking existing single-model entry points.