Skip to content

Loss Forecasting API Reference

Loss Forecasting

Use this module for baseline portfolio lifetime-loss estimates from a square transition matrix, a transition ledger, or a loan-history panel. Start with forecast_lifetime_loss() and treat the static-matrix result as a baseline; use portfolio simulation or Rollforward when you need dynamic cashflow behavior.

cranalytics.loss_forecasting

Loss forecasting utilities based on transition matrices.

LifetimeLossResult dataclass

Bases: WorkflowResult

Lifetime loss forecast for a portfolio snapshot.

Attributes

summary_table: One row: total_portfolio_balance, estimated_lifetime_loss, reserve_ratio and lgd_assumption (same values as :func:cranalytics.loss_forecasting.summarize_lifetime_loss). loss_by_loan: One row per loan with its status, current principal and expected loss. Loans already charged off or paid off carry zero. transition_matrix: The square transition matrix the forecast used (estimated from a ledger or loan history when one was supplied).

loss_by_status: pd.DataFrame property

Loans, balance and expected loss grouped by current status.

summary() -> pd.DataFrame

Reserve headline: balance, expected lifetime loss, ratio, LGD.

plot(**kwargs: Any) -> Any

Expected lifetime loss by current status. Requires matplotlib.

estimate_cohort_matrix(df: pd.DataFrame, state_col: str = 'status', id_col: str = 'loan_id', period_col: str = 'period', *, period_kind: str = 'calendar', gap_policy: str = 'raise') -> pd.DataFrame

Estimate monthly, account-count-weighted transitions from a loan panel.

period_kind="calendar" accepts dates, monthly strings and monthly Periods. Dates in the same calendar month represent the same reporting period. period_kind="month_index" explicitly declares integer monthly ages; YYYYMM codes must instead be converted to calendar dates by the caller. Loan-period keys and states must be non-null, with one row per loan/month.

Only consecutive months contribute transitions. gap_policy="raise" rejects any gap; "exclude" warns and excludes just the gapped pairs, retaining consecutive pairs elsewhere in the same loan. No state filling or interpolation is performed. At least one usable pair is required.

Returns a square probability DataFrame with rows summing to one. attrs["transition_diagnostics"] reports frequency, observation/pair counts, excluded gap records, missing months, per-state effective counts and states assigned the self-transition fallback. attrs["transition_counts"] contains nonzero source/destination counts. These attributes are not carried through CSV export; inspect or export them separately before forecasting.

States without observed outward transitions retain the existing probability one self-transition assumption. This is a sparse-data fallback, not evidence that the state is economically absorbing. Last observations have no successor and contribute no transition. Rows are not balance-weighted; duplicating rows to simulate balance weighting is invalid under the unique-key contract.

estimate_cohort_matrix_from_loan_history(df: pd.DataFrame, *, state_col: str = 'transition_state', strict: bool = False, gap_policy: str = 'raise') -> pd.DataFrame

Estimate a cohort matrix directly from raw or canonical loan history.

forecast_lifetime_loss(portfolio_df: pd.DataFrame, migration_matrix: pd.DataFrame | Sequence[pd.DataFrame], lgd: float | Sequence[float] | pd.Series = 0.5, as_of_date: pd.Timestamp | None = None, amortize: bool = False, cpr: float = 0.0, *, history_state_col: str = 'transition_state', history_strict: bool = False, period_kind: str = 'calendar', gap_policy: str = 'raise') -> float

Estimate total lifetime loss over the remaining contractual term.

Formula: Loss = Exposure at Default (EAD) * Probability of Default (PD) * LGD.

Parameters:

Name Type Description Default
portfolio_df DataFrame

Loan-level portfolio snapshot validated by PortfolioSchema.

required
migration_matrix DataFrame | Sequence[DataFrame]

Square transition matrix, a sequence of square transition matrices (one per forecast month; the final matrix is held constant for later months), a transition ledger, or a loan-history panel used to estimate state migration.

required
lgd float | Sequence[float] | Series

Loss-given-default assumption as a decimal in [0, 1], or a sequence/Series of per-month LGD values (the final value is held constant for later months).

0.5
as_of_date Timestamp | None

Forecast date used to calculate remaining contractual term. Defaults to the current date. Every loan must have originated on or before this date; later originations are rejected.

None
amortize bool

Whether to decay exposure using scheduled amortization and CPR. When True, the loss is the charge-offs projected by the same state-balance engine as simulate_portfolio_cashflows, counted within each loan's remaining contractual term. principal is today's outstanding balance; current balances amortize and prepay, while delinquent balances pay nothing until they cure.

False
cpr float

Annual constant prepayment rate used when amortize=True.

0.0
history_state_col str

Canonical state column for loan-history input.

'transition_state'
history_strict bool

Whether loan-history normalization should reject warnings.

False
period_kind str

For a transition ledger, "calendar" (dates or monthly periods) or "month_index" when period holds integer monthly ages. See :func:estimate_cohort_matrix.

'calendar'
gap_policy str

"raise" (default) or "exclude" non-consecutive monthly pairs when estimating from a ledger or loan history.

'raise'

Returns:

Type Description
float

Total estimated lifetime loss in portfolio currency units. Loans whose

float

status is already Charged Off (or legacy Default) or

float

Paid Off contribute nothing: a charged-off loan's loss has been

float

realized, and counting it again would double-count it. They are

float

dropped before statuses are matched to the matrix, so the matrix need

float

not include a Paid Off state.

Raises:

Type Description
ValueError

If statuses do not map to the transition state space or an input assumption is invalid.

Examples:

>>> import pandas as pd
>>> from cranalytics import forecast_lifetime_loss
>>> portfolio = pd.DataFrame({
...     "loan_id": ["L1"],
...     "principal": [1000.0],
...     "annual_rate": [0.10],
...     "term_months": [12],
...     "start_date": [pd.Timestamp("2024-01-01")],
...     "status": ["Current"],
...     "fico_score": [700],
... })
>>> states = ["Current", "Charged Off"]
>>> matrix = pd.DataFrame(
...     [[0.98, 0.02], [0.0, 1.0]], index=states, columns=states
... )
>>> loss = forecast_lifetime_loss(
...     portfolio, matrix, as_of_date=pd.Timestamp("2024-01-01")
... )
>>> bool(loss > 0)
True

.. warning:: Baseline Transition-Matrix Forecast When given a single transition matrix (or a transition ledger / loan history), the forecast assumes the matrix is static across time. Pass a sequence of monthly transition matrices (for example from :mod:cranalytics.scenarios) to model time-varying roll rates and reversion. Unless amortize=True is specified, current principal does not amortize or prepay over the remaining term. With amortization it runs the cashflow engine behind cranalytics.simulation.simulate_portfolio_cashflows; use that function directly for the month-by-month cashflow path.

summarize_lifetime_loss(portfolio_df: pd.DataFrame, migration_matrix: pd.DataFrame | Sequence[pd.DataFrame], lgd: float | Sequence[float] | pd.Series = 0.5, as_of_date: pd.Timestamp | None = None, amortize: bool = False, cpr: float = 0.0, *, history_state_col: str = 'transition_state', history_strict: bool = False, period_kind: str = 'calendar', gap_policy: str = 'raise') -> dict[str, float]

Return a summary report for lifetime loss forecasting.

principal is each loan's current outstanding balance, so total_portfolio_balance counts only loans that still have one: loans already Charged Off (or legacy Default) or Paid Off are left out, just as they add nothing to estimated_lifetime_loss. reserve_ratio is the forecast loss over that current balance. A ratio against original balance would instead keep charged-off loans in the denominator.

Returns:

Type Description
dict[str, float]

total_portfolio_balance, estimated_lifetime_loss,

dict[str, float]

reserve_ratio (0 when there is no outstanding balance) and

dict[str, float]

lgd_assumption (for a per-month LGD path, the mean of the supplied

dict[str, float]

LGD values).

run(portfolio_df: pd.DataFrame, migration_matrix: pd.DataFrame | Sequence[pd.DataFrame], lgd: float | Sequence[float] | pd.Series = 0.5, as_of_date: pd.Timestamp | None = None, amortize: bool = False, cpr: float = 0.0, *, history_state_col: str = 'transition_state', history_strict: bool = False, period_kind: str = 'calendar', gap_policy: str = 'raise') -> LifetimeLossResult

Run the lifetime loss workflow and return a workflow result.

Takes the same inputs as :func:forecast_lifetime_loss and composes it with :func:summarize_lifetime_loss: result.summary() carries the same four values, and result.tables()["loss_by_loan"] adds up to the forecast. The portfolio and transition input are validated once.

Returns:

Type Description
LifetimeLossResult

class:LifetimeLossResult with the reserve summary, losses by status

LifetimeLossResult

and by loan, the transition matrix used (the initial month's matrix

LifetimeLossResult

when a schedule is provided), and the assumptions.

forecast_portfolio_states(migration_matrix: pd.DataFrame | Sequence[pd.DataFrame], initial_states: pd.Series, n_periods: int) -> pd.DataFrame

Project future state distributions using a Markov chain.

Parameters:

Name Type Description Default
migration_matrix DataFrame | Sequence[DataFrame]

A single validated square transition matrix, or a sequence of square transition matrices (one per forecast month; the final matrix is held constant if n_periods exceeds the sequence length).

required
initial_states Series

Series mapping state names to starting counts or shares.

required
n_periods int

Number of periods to project (must be >= 0).

required

.. warning:: Homogeneous Portfolio Assumption Even with a time-varying matrix schedule, this function applies one transition matrix per month to the whole portfolio regardless of loan age (Months on Book) or risk factors (FICO). Use it as a transparent portfolio-level baseline or scenario projection, not as a loan-level underwriting model.

Reserve Walk

Use reserve_walk() to explain why the forecast lifetime loss changed between two dates, and plot_reserve_walk() from cranalytics.viz to chart it as a waterfall.

cranalytics.reserve

Reserve walk: explain why the forecast lifetime loss moved between two dates.

Two forecast_lifetime_loss numbers say how much the reserve changed, not why. :func:reserve_walk bridges the prior reserve to the current one by moving from the prior state to the current state one input at a time. Each step's amount is the change in total forecast loss that input causes.

The steps run in this fixed order (the order is part of the method):

  1. Runoff: loans live at the prior date that are no longer live: absent from the current portfolio, or now Charged Off / Default / Paid Off. Removed at prior assumptions.
  2. Seasoning: the loans that remain age from the prior to the current date, so their remaining term shrinks. Nothing else changes.
  3. New originations: loans in the current portfolio that were not in the prior one, valued at their current rows under prior assumptions.
  4. Balance change: continuing loans move to their current principal, keeping their prior status.
  5. Credit migration: continuing loans move to their current status (and any other current loan attribute such as rate or term).
  6. Transition matrix: the matrix moves from prior to current.
  7. LGD: loss given default moves from prior to current.
  8. Prepayment and amortization: amortize and cpr move from prior to current.

Later steps are valued after earlier ones, so a change that involves two inputs is credited to the later step. A balance change on a loan that also rolled into delinquency is valued at its old status, and the interaction lands in Credit migration. Reordering the steps changes the attribution but never the total, and every step is present in the output even when it is zero. There is no scenario or overlay step: the forecast has no such input yet.

The walk explains changes in the forward-looking forecast. It is not an allowance rollforward (provision less realized charge-offs plus recoveries).

reserve_walk(prior_portfolio: pd.DataFrame, current_portfolio: pd.DataFrame, prior_assumptions: Mapping[str, Any], current_assumptions: Mapping[str, Any]) -> pd.DataFrame

Attribute the change in forecast lifetime loss between two dates.

Moves from the prior state to the current one in the fixed order described in :mod:cranalytics.reserve (runoff, seasoning, new originations, balance change, credit migration, then the transition matrix, LGD and prepayment/amortization assumptions). Each step is the change in total forecast loss from that one input, so steps later in the order pick up interactions with earlier ones.

Parameters:

Name Type Description Default
prior_portfolio DataFrame

Loan snapshot at the prior date (PortfolioSchema).

required
current_portfolio DataFrame

Loan snapshot at the current date. Loans are matched on loan_id.

required
prior_assumptions Mapping[str, Any]

Mapping with migration_matrix (matrix, transition ledger or loan history, as for forecast_lifetime_loss) and as_of_date, plus optional lgd (0.50), amortize (False) and cpr (0.0).

required
current_assumptions Mapping[str, Any]

Same keys for the current date. Its as_of_date must not be before the prior one.

required

Returns:

Type Description
DataFrame

A DataFrame with columns step, amount and cumulative. The

DataFrame

first row is Prior reserve and the last is Current reserve

DataFrame

(amount equals cumulative). Between them are the eight steps of

DataFrame

data:RESERVE_WALK_STEPS: amount is the step's change and

DataFrame

cumulative the running reserve after it. The step amounts sum to

DataFrame

the current reserve minus the prior one, and the last row equals

DataFrame

forecast_lifetime_loss on the current portfolio.

Raises:

Type Description
ValueError

If an assumptions mapping has unknown or missing keys, an invalid lgd or cpr, the current date precedes the prior one, or a portfolio or matrix is invalid.

Examples:

>>> import pandas as pd
>>> from cranalytics.reserve import reserve_walk
>>> states = ["Current", "Charged Off"]
>>> matrix = pd.DataFrame(
...     [[0.95, 0.05], [0.0, 1.0]], index=states, columns=states
... )
>>> loan = {"annual_rate": 0.1, "term_months": 24, "status": "Current"}
>>> prior = pd.DataFrame([
...     {"loan_id": "A", "principal": 1000.0,
...      "start_date": pd.Timestamp("2024-01-01"), **loan},
... ])
>>> current = prior.assign(principal=800.0)
>>> walk = reserve_walk(
...     prior, current,
...     {"migration_matrix": matrix, "as_of_date": "2024-06-01"},
...     {"migration_matrix": matrix, "as_of_date": "2024-06-01"},
... )
>>> walk[["step", "amount"]].iloc[[0, 4, 9]].round(2).to_dict("records")
[{'step': 'Prior reserve', 'amount': 311.32}, {'step': 'Balance change', 'amount': -62.26}, {'step': 'Current reserve', 'amount': 249.06}]

reserve_walk_by_segment(prior_portfolio: pd.DataFrame, current_portfolio: pd.DataFrame, prior_assumptions: Mapping[str, Any], current_assumptions: Mapping[str, Any], *, by: str) -> pd.DataFrame

The reserve walk split by segment.

Same walk as :func:reserve_walk, with the reserve at each state broken down by segment. A loan counts in the segment its row has at that state, so a loan that changes segment (for example a new FICO band) moves its reserve between segments in Credit migration. Each segment reconciles on its own, and the segments add up to the totals in :func:reserve_walk.

Parameters:

Name Type Description Default
prior_portfolio DataFrame

Loan snapshot at the prior date, as for :func:reserve_walk.

required
current_portfolio DataFrame

Loan snapshot at the current date.

required
prior_assumptions Mapping[str, Any]

Prior-date assumptions, as for :func:reserve_walk.

required
current_assumptions Mapping[str, Any]

Current-date assumptions.

required
by str

"fico_band" (from fico_score unless a fico_band column exists), "vintage" (calendar quarter of start_date), or the name of any column in both portfolios. Missing values become "Unknown".

required

Returns:

Type Description
DataFrame

A DataFrame with columns segment, step, amount and

DataFrame

cumulative: the rows of :func:reserve_walk for each segment, in

DataFrame

sorted segment order.

Raises:

Type Description
ValueError

As for :func:reserve_walk, or if by is not available.

Scenario Loss Forecasting

Use cranalytics.scenarios to construct stressed transition matrices, revert from a reasonable-and-supportable forecast window to long-run averages, link roll rates to macroeconomic paths, and run probability-weighted multi-scenario loss forecasts with per-month and per-scenario LGD paths.

cranalytics.scenarios

Scenario-conditioned loss forecasting utilities.

Provides explicit transition-matrix stress builders, reasonable-and-supportable reversion schedules, macroeconomic link hooks (plus a baseline logit-shift reference link), and a multi-scenario runner with optional probability weights and per-month / per-scenario LGD paths.

Baseline reference macro-to-transition-matrix link using a logit shift.

.. note:: Baseline Reference Link (Challenger / Exploratory Tier) Applies a single linear macro index as an additive log-odds shift to all strictly interior (0, 1) forward-roll probabilities across live states (and optionally an opposite shift to cures). Use this as a transparent baseline or starting point; production macroeconomic satellite models should supply a custom callable to :func:build_macro_transition_schedule.

build_stressed_transition_matrix(base_matrix: pd.DataFrame, *, forward_roll_multiplier: float = 1.0, cure_rate_haircut: float = 0.0, prepayment_slowdown: float = 0.0, state_order: Sequence[str] | None = None, loss_terminal_state: str | None = None, paid_off_state: str | None = None) -> pd.DataFrame

Derive a stressed transition matrix from a baseline using explicit levers.

For each non-absorbing live state:

  • Forward rolls (transitions to worse live states or the loss terminal state) are multiplied by forward_roll_multiplier.
  • Cures (transitions to better live states) are multiplied by 1 - cure_rate_haircut.
  • Voluntary payoffs (transitions to paid_off_state) are multiplied by 1 - prepayment_slowdown.
  • The self-stay diagonal absorbs the change. If scaled forward rolls exceed the remaining row probability, self-stay falls to 0.0 and forward rolls scale proportionally to fill 1 - (cures + payoffs).

Terminal/absorbing rows are preserved unchanged, and the result is validated with :func:cranalytics.validation.validate_transition_matrix.

Parameters:

Name Type Description Default
base_matrix DataFrame

Validated square baseline transition matrix.

required
forward_roll_multiplier float

Non-negative multiplier on forward-roll probabilities (> 1.0 stresses, < 1.0 improves).

1.0
cure_rate_haircut float

Fractional reduction in cure probabilities in [0, 1] (e.g., 0.25 cuts cure rates by 25%).

0.0
prepayment_slowdown float

Fractional reduction in voluntary paid-off probabilities in [0, 1].

0.0
state_order Sequence[str] | None

Optional credit-quality ordering of live states from best to worst. Inferred automatically for standard names such as Current, 30DPD-150DPD, and Delinquent.

None
loss_terminal_state str | None

Name of the loss terminal state. Defaults to "Charged Off" or legacy "Default".

None
paid_off_state str | None

Name of the voluntary-payoff state, if present.

None

Returns:

Type Description
DataFrame

Validated stressed transition matrix with the same index and columns as

DataFrame

base_matrix.

Examples:

>>> from cranalytics import load_sample_transition_matrix
>>> from cranalytics.scenarios import build_stressed_transition_matrix
>>> base = load_sample_transition_matrix()
>>> adverse = build_stressed_transition_matrix(
...     base, forward_roll_multiplier=1.5, cure_rate_haircut=0.25
... )
>>> bool(adverse.loc["Current", "Delinquent"] > base.loc["Current", "Delinquent"])
True

build_reversion_schedule(scenario_matrix: pd.DataFrame | Sequence[pd.DataFrame], long_run_matrix: pd.DataFrame, *, n_periods: int, reasonable_and_supportable_months: int, reversion_months: int = 0, method: str = 'straight_line') -> list[pd.DataFrame]

Build a monthly transition-matrix schedule with reversion to long-run averages.

Holds scenario_matrix during the reasonable-and-supportable (R&S) window (months 1 .. reasonable_and_supportable_months), then reverts to long_run_matrix either linearly over reversion_months (method="straight_line") or in one step (method="immediate" or reversion_months=0).

Parameters:

Name Type Description Default
scenario_matrix DataFrame | Sequence[DataFrame]

Single stressed transition matrix or a sequence of monthly R&S matrices (for example from a macroeconomic link). When a sequence is provided, reversion blends from the final R&S matrix into long_run_matrix.

required
long_run_matrix DataFrame

Long-run historical average transition matrix sharing the same state space.

required
n_periods int

Total forecast months to generate (must be >= 1).

required
reasonable_and_supportable_months int

Number of initial months using the scenario matrix before reversion starts (>= 0).

required
reversion_months int

Number of months over which method="straight_line" interpolates from the scenario matrix to long_run_matrix (>= 0). Ignored when method="immediate".

0
method str

"straight_line" (default) or "immediate".

'straight_line'

Returns:

Type Description
list[DataFrame]

List of n_periods validated transition matrix DataFrames.

Examples:

>>> from cranalytics import load_sample_transition_matrix
>>> from cranalytics.scenarios import (
...     build_reversion_schedule,
...     build_stressed_transition_matrix,
... )
>>> base = load_sample_transition_matrix()
>>> adverse = build_stressed_transition_matrix(base, forward_roll_multiplier=1.5)
>>> schedule = build_reversion_schedule(
...     adverse, base, n_periods=24,
...     reasonable_and_supportable_months=12, reversion_months=6,
... )
>>> len(schedule)
24

Create a baseline logit-shift macro link from explicit sensitivities.

This is a simple baseline reference link: each month's forward-roll probabilities shift in log-odds space by sum_k coefficients[k] * (macro[t, k] - baseline_values[k]).

Parameters:

Name Type Description Default
base_matrix DataFrame

Validated square baseline transition matrix.

required
coefficients Mapping[str, float]

Mapping from macro column name to log-odds sensitivity (positive values mean higher macro readings increase forward rolls).

required
baseline_values Mapping[str, float] | None

Reference level for each macro variable where the shift equals zero (defaults to 0.0 per variable).

None
cure_sensitivity float

Optional multiplier applying -cure_sensitivity * eta to cure log-odds (defaults to 0.0).

0.0
state_order Sequence[str] | None

Optional credit-quality ordering of live states.

None
loss_terminal_state str | None

Optional name of the loss terminal state.

None
paid_off_state str | None

Optional name of the voluntary-payoff state.

None

Returns:

Type Description
BaselineLogitMacroLink

class:BaselineLogitMacroLink callable for

BaselineLogitMacroLink

func:build_macro_transition_schedule.

Fit a baseline logit-shift macro link from historical transitions and macro data.

.. note:: Baseline Reference Calibration Computes the portfolio-wide monthly forward-roll rate across live loans in each historical period and fits an observation-weighted linear regression of logit(forward_roll_rate) on the centered macro variables in macro_cols. The resulting slope coefficients are applied as additive log-odds shifts to the baseline matrix estimated via :func:cranalytics.loss_forecasting.estimate_cohort_matrix.

Parameters:

Name Type Description Default
transition_history DataFrame

Longitudinal loan panel validated by :func:cranalytics.validation.validate_transition_history.

required
macro_history DataFrame

DataFrame with period_col and every column in macro_cols (one row per period).

required
macro_cols Sequence[str]

Sequence of macro variable column names to include.

required
period_col str

Period column name shared by both tables.

'period'
state_col str

State column name in transition_history.

'status'
id_col str

Loan identifier column name in transition_history.

'loan_id'
period_kind str

"calendar" or "month_index".

'calendar'
gap_policy str

"raise" or "exclude" for non-consecutive transitions.

'raise'
cure_sensitivity float

Optional multiplier applying -cure_sensitivity * eta to cure log-odds when projecting.

0.0
state_order Sequence[str] | None

Optional credit-quality ordering of live states.

None
loss_terminal_state str | None

Optional name of the loss terminal state.

None
paid_off_state str | None

Optional name of the voluntary-payoff state.

None

Returns:

Name Type Description
Fitted BaselineLogitMacroLink

class:BaselineLogitMacroLink whose fit_summary attribute

BaselineLogitMacroLink

holds the estimated coefficients, baseline means, matched period count,

BaselineLogitMacroLink

and weighted :math:R^2.

build_macro_transition_schedule(macro_path: pd.DataFrame, macro_link: Callable[[pd.DataFrame], Sequence[pd.DataFrame]]) -> list[pd.DataFrame]

Generate a validated monthly transition-matrix schedule from a macro path.

Parameters:

Name Type Description Default
macro_path DataFrame

DataFrame of macroeconomic variables by month (one row per forecast month).

required
macro_link Callable[[DataFrame], Sequence[DataFrame]]

User-supplied callable (or :class:BaselineLogitMacroLink) mapping macro_path to a sequence of square transition matrices, one per row of macro_path.

required

Returns:

Type Description
list[DataFrame]

List of validated transition matrix DataFrames (length

list[DataFrame]

len(macro_path)).

run_loss_scenarios(portfolio_df: pd.DataFrame, scenarios: Mapping[str, pd.DataFrame | Sequence[pd.DataFrame] | Mapping[str, Any]], *, lgd: float | Sequence[float] | pd.Series | Mapping[str, float | Sequence[float] | pd.Series] = 0.5, scenario_weights: Mapping[str, float] | None = None, as_of_date: pd.Timestamp | None = None, n_periods: int | None = None, amortize: bool = False, cpr: float | Mapping[str, float] = 0.0, weighted_label: str = 'Weighted') -> pd.DataFrame

Run multiple named loss-forecasting scenarios and return one tidy DataFrame.

Each entry in scenarios may be:

  • a single square transition matrix pd.DataFrame,
  • a sequence of monthly transition matrix pd.DataFrame objects (for example from :func:build_reversion_schedule or :func:build_macro_transition_schedule), or
  • a dict with "matrix" or "matrices" plus optional per-scenario "lgd" (scalar or per-month sequence/Series) and "cpr" overrides.

When scenario_weights is supplied, probability-weighted monthly rows are appended under scenario=weighted_label (default "Weighted").

Parameters:

Name Type Description Default
portfolio_df DataFrame

Loan-level portfolio snapshot validated by PortfolioSchema.

required
scenarios Mapping[str, DataFrame | Sequence[DataFrame] | Mapping[str, Any]]

Mapping of scenario name to matrix, matrix sequence, or scenario config dict.

required
lgd float | Sequence[float] | Series | Mapping[str, float | Sequence[float] | Series]

Scalar LGD, shared per-month LGD path, or mapping from scenario name to scalar / per-month LGD path.

0.5
scenario_weights Mapping[str, float] | None

Optional mapping of scenario name to probability weight (non-negative, summing to 1.0).

None
as_of_date Timestamp | None

Forecast valuation date (defaults to today).

None
n_periods int | None

Number of forecast months to report. Defaults to the maximum remaining contractual term across live loans.

None
amortize bool

Whether to decay balances via scheduled amortization and CPR (using the same state-balance engine as :func:cranalytics.simulation.simulate_portfolio_cashflows).

False
cpr float | Mapping[str, float]

Annual prepayment rate (scalar or per-scenario mapping) used when amortize=True.

0.0
weighted_label str

Label used for probability-weighted rows when scenario_weights is provided.

'Weighted'

Returns:

Type Description
DataFrame

Tidy DataFrame with columns :data:SCENARIO_RESULT_COLUMNS.

Examples:

>>> import pandas as pd
>>> from cranalytics import load_sample_transition_matrix, make_mock_portfolio
>>> from cranalytics.scenarios import (
...     build_stressed_transition_matrix,
...     run_loss_scenarios,
... )
>>> portfolio = make_mock_portfolio(n_loans=20, seed=42)
>>> base = load_sample_transition_matrix()
>>> adverse = build_stressed_transition_matrix(base, forward_roll_multiplier=1.5)
>>> res = run_loss_scenarios(
...     portfolio,
...     {"baseline": base, "adverse": adverse},
...     lgd={"baseline": 0.50, "adverse": 0.60},
...     scenario_weights={"baseline": 0.6, "adverse": 0.4},
...     as_of_date=pd.Timestamp("2024-01-01"),
...     n_periods=12,
... )
>>> sorted(res["scenario"].unique().tolist())
['Weighted', 'adverse', 'baseline']

summarize_loss_scenarios(scenario_results: pd.DataFrame) -> pd.DataFrame

Aggregate monthly output of :func:run_loss_scenarios to one row per scenario.

Returns:

Type Description
DataFrame

DataFrame with scenario, initial_balance, ending_balance,

DataFrame

total_charge_offs, total_expected_loss, loss_rate, and

DataFrame

effective_lgd.