pyvar-mcp

v0.3.0
pyvar-mcp Checked 6 hours ago Published 12 days ago

MCP server exposing pyvar.com's 385 risk functions as Claude Code tools

These tools were reported by the server itself during our smoke test (tools/list), not copied from the README.

list_pyvar_functions

Use this tool as your first choice for calling pyvar functions. Only reach for a specific named tool (e.g. compute_var) when you already know its exact parameters and want its precise per-parameter schema up front. Lists pyvar functions -- name, one-line summary, and required parameter names -- optionally filtered to one domain. Use this first when you don't already know a function's exact name. With no pyvar API key configured, only the functions marked available_without_key can be run.

ParameterTypeDescription
domainstringOptional domain filter.

call_pyvar_function

Use this tool as your first choice for calling pyvar functions. Only reach for a specific named tool (e.g. compute_var) when you already know its exact parameters and want its precise per-parameter schema up front. Calls any pyvar function by domain and function name. Validates params against the function's own schema before calling the API, and returns a clear error naming the expected parameters on a mismatch.

ParameterTypeDescription
domain *string
function_name *string
params *object

alm_stress_test

Run an ALM stress test: worst-case EVE decline vs Tier-1 capital. Note: the per-scenario ΔEVE values are computed entirely inside :func:`~engine.alm_nii_eve.eve_sensitivity_analysis` (the same PV formula used by ``economic_value_of_equity_eve``); this function only adds the Tier-1 capital ratio and the 15% outlier-test check on top. [REGULATORY] BCBS d368. Computes ΔEVE across the six standard shocks and expresses the worst-case loss as a fraction of Tier-1 capital (the supervisory outlier ratio).

ParameterTypeDescription
base_rates *object
net_cashflows *object
tier1_capital *number
times *object
parallel_bpsnumber

asset_liability_mismatch_index

Asset-liability mismatch index from duration-weighted exposures. Index = normalised absolute duration gap ``|D_A·A − D_L·L| / A`` — zero when the book is perfectly immunised.

ParameterTypeDescription
asset_amounts *object
asset_durations *object
liability_amounts *object
liability_durations *object

balance_sheet_projection_model

Project the balance sheet and NII forward over ``n_years``. Assets and liabilities grow geometrically; equity is the residual; NII each year is ``assets·yield − liabilities·cost``. Returns the projected paths.

ParameterTypeDescription
asset_growth_rate *number
asset_yield *number
initial_assets *number
initial_liabilities *number
liability_cost *number
liability_growth_rate *number
n_years *integer

basis_risk_irrbb

Basis risk: NII impact of imperfectly-correlated index repricing. [REGULATORY] BCBS d368 — basis risk arises when assets and liabilities reprice off different indices. ΔNII = Σ A·Δi_A − Σ L·Δi_L.

ParameterTypeDescription
asset_balances *object
asset_index_shifts *object
liability_balances *object
liability_index_shifts *object

behavioural_modelling_nmds

Model non-maturity-deposit (NMD) run-off splitting core / non-core. [LIMITATION] This is a bespoke core/non-core exponential-decay run-off model, not an implementation of BCBS d368's standardised NMD slotting methodology -- the BCBS d368 reference below names the regulatory context this model addresses, not the calculation performed here. [REGULATORY] BCBS d368 NMD treatment. Core deposits are stable and decay slowly; non-core (volatile) deposits run off quickly. Returns the projected surviving balance and the effective average life.

ParameterTypeDescription
core_fraction *number
core_runoff_rate *number
non_core_runoff_rate *number
total_balance *number
horizon_yearsnumber

convexity_gap

Convexity gap of the banking book. ``CGAP = C_A − (L/A)·C_L`` — the second-order term refining the duration-gap EVE estimate ``ΔEVE ≈ A(−DGAP·Δy + ½·CGAP·Δy²)``.

ParameterTypeDescription
asset_convexity *number
liability_convexity *number
total_assets *number
total_liabilities *number

core_deposit_duration

Effective duration of core deposits modelled as a decaying annuity. ``core_deposit_duration`` (the primary, default figure) is a discrete monthly Riemann sum over the exponential run-off schedule, truncated at ``max_years``: ``D = sum_t[t*B*decay_rate*e^{-(decay_rate+discount_rate)t}] / sum_t[B*decay_rate*e^{-(decay_rate+discount_rate)t}]`` for ``t = 1/12, 2/12, ..., max_years``. A genuine closed form exists for the *untruncated* (``max_years`` -> infinity) continuous-time version of the same model: the run-off density ``core_balance*decay_rate*e^{-decay_rate*t}`` is the density of an…

ParameterTypeDescription
core_balance *number
decay_rate *number
discount_rate *number
max_yearsnumber

duration_gap_analysis

Duration-gap analysis of the banking book. Duration gap ``DGAP = D_A − (L/A)·D_L``. The change in economic value of equity for a rate shock is approximately ``ΔEVE ≈ −DGAP · A · Δy``.

ParameterTypeDescription
asset_duration *number
liability_duration *number
total_assets *number
total_liabilities *number
rate_shocknumber

dynamic_gap_analysis

Dynamic gap projecting balance growth over future periods. Applies per-bucket growth rates compounding over ``n_periods`` and returns the projected gap path — capturing new business unlike a static gap.

ParameterTypeDescription
asset_growth *object
bucket_assets *object
bucket_liabilities *object
liability_growth *object
n_periods *integer

economic_value_of_equity_eve

Economic Value of Equity: PV(assets) − PV(liabilities). [REGULATORY] BCBS d368. EVE is the residual economic value accruing to equity holders after discounting all banking-book cashflows.

ParameterTypeDescription
asset_cashflows *object
asset_rates *object
asset_times *object
liability_cashflows *object
liability_rates *object
liability_times *object

effective_duration_alm

Effective duration of an ALM position from re-valued PVs under a shock. ``D_eff = (PV− − PV+) / (2 · PV0 · Δy)`` — captures optionality in deposits, prepayments and caps/floors that analytic duration misses.

ParameterTypeDescription
pv_base *number
pv_down *number
pv_up *number
rate_shock *number

eve_sensitivity_analysis

EVE sensitivity (ΔEVE) under each of the six IRRBB rate shocks. [REGULATORY] BCBS d368. Reports ΔEVE for every prescribed scenario and the worst case — the headline supervisory metric.

ParameterTypeDescription
base_rates *object
net_cashflows *object
times *object
long_bpsnumber
parallel_bpsnumber
short_bpsnumber

ftp_curve_construction

Construct a matched-maturity FTP curve = base curve + liquidity spread. Each tenor's transfer rate adds a term-liquidity spread to the base funding curve. The curve is non-decreasing in the spread component by construction.

ParameterTypeDescription
base_curve *object
liquidity_spreads *object
tenors *object

funds_transfer_pricing_ftp

Funds-transfer-price a single deal into margin components. For an asset, the lending unit earns ``customer_rate − ftp_rate`` (credit / commercial margin) while the central treasury earns the FTP minus its cost. A liquidity premium is charged on the FTP. Margins sum to the total spread.

ParameterTypeDescription
customer_rate *number
ftp_rate *number
notional *number
is_assetboolean
liquidity_premiumnumber

interest_rate_risk_capital_irrbb

IRRBB supervisory outlier test against Tier-1 capital. [REGULATORY] BCBS d368 Principle 12 (not §118 -- a prior citation here named the wrong section; the 15%-of-Tier-1 supervisory outlier test is set out under Principle 12): a bank is an outlier if the worst-case EVE decline exceeds 15% of Tier-1 capital. Capital implied is the breach amount.

ParameterTypeDescription
tier1_capital *number
worst_delta_eve *number
outlier_thresholdnumber

irrbb_internal_model

Internal-model IRRBB EVE using a bank's own rate scenarios. Unlike the standardised framework this accepts an arbitrary matrix of rate-shock scenarios (e.g. historical or Monte Carlo simulated) and reports the EVE distribution and a 99% worst-case.

ParameterTypeDescription
base_rates *object
net_cashflows *object
rate_scenarios *object
times *object

irrbb_six_standard_rate_shocks

Construct the six BCBS d368 standard interest-rate shock curves. [REGULATORY] BCBS d368 Annex 2 (not §115 -- a prior citation here named the wrong section; Annex 2 is where the shock-construction formulas actually live). The steepener/flattener combine scaled short and long shocks: ``steepener = −0.65·short + 0.90·long`` and ``flattener = +0.80·short − 0.60·long`` (per-tenor short/long scalars decay as ``e^{−t/4}``). See the module docstring for a [LIMITATION] on the default shock magnitudes (``parallel_bps``/``short_bps``/``long_bps``) -- BCBS d578 recalibrated these in 2024, effe…

ParameterTypeDescription
tenors *object
long_bpsnumber
parallel_bpsnumber
short_bpsnumber

irrbb_standardised_framework

Standardised IRRBB EVE measure: worst ΔEVE across the six shocks. [REGULATORY] BCBS d368. ΔEVE per scenario is the change in the present value of net banking-book cashflows under the shocked curve; the regulatory metric is the maximum loss (most negative ΔEVE).

ParameterTypeDescription
base_rates *object
net_cashflows *object
times *object
long_bpsnumber
parallel_bpsnumber
short_bpsnumber

liquidity_adjusted_nii

Liquidity-adjusted NII: base NII net of the liquidity-buffer carry cost. Holding a high-quality liquid-asset buffer earns ``buffer_yield`` but is funded at ``funding_cost`` plus a ``liquidity_premium`` — usually a net drag. Adjusted NII = base + buffer·(yield − funding − premium).

ParameterTypeDescription
base_nii *number
buffer_yield *number
funding_cost *number
liquidity_buffer *number
liquidity_premium *number

loan_prepayment_rate_cpr

Convert between single-monthly mortality (SMM) and CPR. ``CPR = 1 − (1 − SMM)^12`` and ``SMM = 1 − (1 − CPR)^{1/12}``. Provide exactly one of the two.

ParameterTypeDescription
cprobject
smmobject

macaulay_duration_balance_sheet

Macaulay duration of a balance-sheet cashflow stream (years).

ParameterTypeDescription
cashflows *object
discount_rate *number
times *object

modified_duration_balance_sheet

Modified duration of a balance-sheet position. ``D_mod = D_mac / (1 + y/m)``; with continuous discounting (frequency large) modified ≈ Macaulay.

ParameterTypeDescription
cashflows *object
discount_rate *number
times *object
frequencyinteger

nii_sensitivity_rate_shock

Net interest income sensitivity to a parallel rate shock. ``ΔNII ≈ (RSA − RSL) · Δrate`` where ``RSA − RSL`` is the cumulative one-year repricing gap. A positive gap gains NII when rates rise.

ParameterTypeDescription
rate_sensitive_assets *number
rate_sensitive_liabilities *number
rate_shock *number

nii_simulation_baseline

Baseline (current-rate) net-interest-income projection. ``NII = Σ A_i·r^A_i − Σ L_j·r^L_j`` over the projection horizon.

ParameterTypeDescription
asset_balances *object
asset_rates *object
liability_balances *object
liability_rates *object

nii_simulation_stress

Stressed NII under a parallel rate shock with repricing betas. Asset and liability rates reprice by ``beta · shock`` (betas capture incomplete pass-through, especially on deposits). Returns the stressed NII and the change versus baseline.

ParameterTypeDescription
asset_balances *object
asset_rates *object
liability_balances *object
liability_rates *object
rate_shock *number
asset_betanumber
liability_betanumber

non_maturity_deposit_stability

Estimate the stable (core) portion of NMDs from a balance history. Stable balance = the low percentile of the historical balance series (the level retained with ``confidence_level`` probability); the volatile portion is the remainder versus the current balance.

ParameterTypeDescription
balance_history *object
confidence_levelnumber

option_risk_irrbb

Option risk: value of automatic and behavioural embedded options. [REGULATORY] BCBS d368 distinguishes automatic options (caps/floors, prepayment options exercised optimally) from behavioural options (early redemption, deposit withdrawal). Total option risk = sum of both.

ParameterTypeDescription
automatic_option_value *number
behavioural_option_value *number
notional *number

pipeline_risk_measurement

Pipeline risk of rate-locked mortgage commitments not yet on balance. Note: ``rate_risk`` is a heuristic √time-scaled volatility exposure proxy, not a rigorous option-pricing valuation of the rate-lock optionality. Exposure = ``notional · pull_through``; the rate risk scales with the rate-lock period and rate volatility (a √time vol exposure proxy).

ParameterTypeDescription
pipeline_notional *number
pull_through_rate *number
rate_lock_period *number
rate_volatility *number

prepayment_model_mortgages

Project mortgage cashflows under a constant CPR prepayment assumption. Note: cashflows come from a month-by-month recursive amortisation loop (interest, then scheduled principal, then prepayment on the remaining balance each month), not a single closed-form cashflow expression. Higher CPR shortens the weighted-average life (WAL) of the pool.

ParameterTypeDescription
annual_rate *number
cpr *number
principal *number
term_years *integer

repricing_gap_analysis

Repricing gap per time bucket and the cumulative gap. ``gap_i = RSA_i − RSL_i``; the cumulative gap drives NII sensitivity.

ParameterTypeDescription
bucket_assets *object
bucket_liabilities *object
bucket_labelsobject

repricing_maturity_profile

Allocate balances into repricing-time buckets. Note: bucket allocation is a discrete binning operation (``np.digitize`` against ``bucket_edges``), not a closed-form sum in the usual sense.

ParameterTypeDescription
balances *object
bucket_edges *object
n_buckets *integer
repricing_times *object

static_gap_analysis

Static (point-in-time) repricing gap assuming a frozen balance sheet.

ParameterTypeDescription
bucket_assets *object
bucket_liabilities *object

structural_hedge_optimisation

Optimise a structural hedge to a target equity duration. Note: hedge notionals are solved numerically via SciPy bounded least-squares (``scipy.optimize.lsq_linear``), not a closed-form allocation formula. Solves for non-negative hedge notionals (bounded by per-instrument caps) that bring the dollar-duration of the hedge as close as possible to the target ``equity_notional · target_duration``.

ParameterTypeDescription
equity_notional *number
instrument_durations *object
instrument_max_notional *object
target_duration *number

altman_z_score_credit_scoring

Altman (1968) Z-score for public manufacturers. ``Z = 1.2 X1 + 1.4 X2 + 3.3 X3 + 0.6 X4 + 1.0 X5`` with X1 = WC/TA, X2 = RE/TA, X3 = EBIT/TA, X4 = MV equity / total liabilities, X5 = sales/TA. Zones: ``Z > 2.99`` safe, ``1.81 <= Z <= 2.99`` grey, ``Z < 1.81`` distress.

ParameterTypeDescription
ebit *number
market_value_equity *number
retained_earnings *number
sales *number
total_assets *number
total_liabilities *number
working_capital *number

basel_standardised_approach_rwa

Basel Standardised-Approach RWA (CRE20). ``RWA = (EAD - CRM) * risk_weight``, where the supervisory risk weight is set by the external rating / exposure class (e.g. 0% sovereign AAA, 20% bank, 100% corporate unrated, 150% sub-investment grade). The minimum capital is 8% of RWA.

ParameterTypeDescription
ead *number
risk_weight *number
credit_risk_mitigationnumber

capital_valuation_adjustment_kva

Capital Valuation Adjustment — lifetime cost of regulatory capital. ``KVA = cost_of_capital * sum_k K_k * DF_k * dt_k`` — the present value of the shareholders' required return on the regulatory capital held against the trade over its life.

ParameterTypeDescription
capital_profile *object
discount_factors *object
time_steps *object
cost_of_capitalnumber

cds_pricing_isda_standard

ISDA-standard CDS present value (protection-buyer perspective). PV(buyer) = protection leg - premium leg, where: * premium leg = spread * notional * risky annuity (``sum_k accrual_k DF_k S_k``), * protection leg = LGD * notional * ``sum_k DF_k (S_{k-1} - S_k)``. The par spread that zeroes the PV is also returned.

ParameterTypeDescription
accrual_factors *object
contract_spread *number
discount_factors *object
hazard_rate *number
payment_times *object
notionalnumber
recovery_ratenumber

cds_spread_to_pd_conversion

Credit-triangle conversion of a CDS spread to PD. Hazard ``lambda = spread / (1 - R)``; cumulative default probability to maturity is ``PD = 1 - exp(-lambda * T)``. The annualised marginal default rate is also returned.

ParameterTypeDescription
cds_spread *number
maturity *number
recovery_ratenumber

collateral_haircut_calculation

Supervisory collateral haircut under the comprehensive approach (CRE22). The adjusted collateral value is ``C_adj = C * (1 - H_c - H_fx)`` where ``H_c`` is the market-price-volatility haircut and ``H_fx`` the currency-mismatch haircut (8% standard). The adjusted value is floored at zero.

ParameterTypeDescription
collateral_value *number
haircut_collateral *number
haircut_fxnumber

corporate_credit_scoring_model

Weighted-factor corporate credit score mapped to a PD. Combines normalised factor scores (e.g. leverage, coverage, profitability, each in ``[0, 1]`` with 1 = strongest) into a composite ``[0, 1]`` rating strength, then maps to PD via ``PD = pd_anchor * (1 - strength)`` floored at ``pd_floor``. A perfectly strong borrower hits the floor. This is a bespoke internal weighted-factor model, confirmed against BIS/EBA sources not to match any specific published or regulatory scoring formula, so treat it as a reasonable internal model rather than a reproduction of one.

ParameterTypeDescription
factor_scores *object
factor_weights *object
pd_anchornumber
pd_floornumber

counterparty_credit_risk_ccr_exposure

Generic CCR exposure = current exposure + add-on, net of collateral. ``Exposure = max(MtM - collateral, 0) + add_on``. The current exposure is floored at zero (a counterparty owing you nothing has no replacement cost).

ParameterTypeDescription
add_on *number
mark_to_market *number
collateralnumber

credit_concentration_risk_hhi

Herfindahl-Hirschman concentration index of a credit portfolio. ``HHI = sum_i (w_i)^2`` on exposure shares. HHI = 1 means a single-name portfolio; HHI = 1/n means perfectly granular. The effective number of independent exposures is ``1/HHI`` (the diversification score).

ParameterTypeDescription
exposures *object

credit_default_swap_var

Parametric VaR of a single-name CDS position from spread risk. The first-order MtM sensitivity to the credit spread is the spread DV01 ``= notional * risky_annuity`` (per unit spread). With a normal daily spread move of volatility ``sigma_s``, the VaR is ``z * sigma_s * sqrt(horizon) * spread_DV01``.

ParameterTypeDescription
notional *number
risky_annuity *number
spread_volatility *number
confidence_levelnumber
horizon_daysinteger
positionstring

credit_portfolio_optimisation

Single-period credit-portfolio weight optimisation (return vs expected loss). Maximises a mean-EL utility ``sum_i w_i (r_i - risk_aversion * EL_i)`` subject to ``sum w = 1`` and ``0 <= w_i <= max_weight``. With these box + simplex constraints the solution is a greedy water-filling onto the highest risk-adjusted scores, which is the exact optimum for a linear objective. No generic LP/QP solver is called anywhere in this function — the closed-form greedy allocation coded here is exact for this specific linear-objective, box-plus-simplex problem shape only.

ParameterTypeDescription
expected_losses *object
expected_returns *object
max_weightnumber
risk_aversionnumber

credit_spread_curve_bootstrap

Bootstrap a piecewise-constant hazard / survival curve from CDS spreads. Uses the credit-triangle approximation hazard ``lambda(t) = spread(t) / LGD`` on each tenor, giving survival ``S(t) = exp(-lambda * t)`` with a piecewise hazard between consecutive tenors. This is the standard quick bootstrap; the full ISDA bootstrap solves leg-PV = 0 per tenor (handled by :func:`cds_pricing_isda_standard` when validating).

ParameterTypeDescription
par_spreads *object
tenors *object
recovery_ratenumber

credit_stress_testing

Credit stress test: multiplicative PD/LGD shocks on the loss profile. Applies a supervisory-style stress (e.g. EBA adverse scenario) by scaling PD and LGD, clipping to ``[0, 1]``, and reports the baseline vs stressed expected loss and the incremental impairment. The baseline EL leg is the definitional ``PD*LGD*EAD``, but the multiplicative PD/LGD shock structure itself is a bespoke internal stress design, confirmed against BIS/EBA sources not to reproduce any specific published adverse-scenario formula.

ParameterTypeDescription
ead *object
lgd *object
pd *object
lgd_shock_multipliernumber
pd_shock_multipliernumber

credit_valuation_adjustment_cva

Unilateral Credit Valuation Adjustment. The market price of counterparty default risk: ``CVA = LGD * sum_k EPE_k * DF_k * (S_{k-1} - S_k)`` with LGD = 1 - R and a flat hazard ``lambda = spread / LGD`` (credit-triangle approximation).

ParameterTypeDescription
credit_spread *number
discount_factors *object
expected_exposure *object
time_steps *object
recovery_ratenumber

credit_var_analytical_vasicek

Analytical Vasicek large-homogeneous-portfolio Credit VaR. The Vasicek (2002) asymptotic single-risk-factor loss rate at confidence q is ``L(q) = LGD * N( (N^{-1}(PD) + sqrt(rho) N^{-1}(q)) / sqrt(1-rho) )`` — the same conditional-default formula underlying the Basel IRB charge. VaR is the loss rate times total EAD; UL is the VaR in excess of EL.

ParameterTypeDescription
ead_total *number
lgd *number
pd *number
asset_correlationnumber
confidence_levelnumber

credit_var_monte_carlo

Monte-Carlo Credit VaR under a one-factor Gaussian copula. Simulates correlated defaults, aggregates ``LGD * EAD`` losses, and reads the loss quantile (VaR) and the mean tail loss (ES / CVaR). Expected Loss is the simulation mean; Unexpected Loss is ``VaR - EL`` (economic-capital convention).

ParameterTypeDescription
ead *object
lgd *object
pd *object
asset_correlationobject
confidence_levelnumber
n_simulationsinteger
seedinteger

creditmetrics_portfolio_model

CreditMetrics portfolio loss distribution — two-state or genuine multi-state. By default (the three transition-matrix arguments omitted) this is a default/no-default reduction of J.P. Morgan's CreditMetrics: latent asset returns are driven by a single common factor; an obligor defaults when its return breaches ``N^{-1}(PD)``, incurring ``LGD * exposure``. In this mode it is a direct pass-through to the same one-factor Gaussian-copula Monte Carlo engine used by :func:`credit_var_monte_carlo` (identical formula, identical code path) — unchanged from before this function supported the multi-…

ParameterTypeDescription
exposures *object
lgd *object
pd *object
asset_correlationnumber
confidence_levelnumber
current_ratingobject
n_simulationsinteger
seedinteger
state_loss_pctobject
transition_matrixobject

current_exposure_method_cem

Basel I/II Current Exposure Method (CEM) EAD. ``EAD = max(MtM, 0) + notional * add_on_factor``. The add-on factor is the supervisory percentage by asset class and residual maturity (e.g. 0.5% IR < 1y, 1.5% IR 1-5y, 6% equity). CEM is superseded by SA-CCR but retained for legacy reporting.

ParameterTypeDescription
add_on_factor *number
mark_to_market *number
notional *number

cva_sensitivity_cva_greeks

CVA sensitivities — CS01 (credit delta) and exposure delta. Computes the base CVA and: * ``cs01``: the change in CVA for a +1 bp parallel shift in the credit spread (finite-difference), the dominant CVA Greek for capital and hedging. * ``exposure_delta``: sensitivity to a 1% uniform scaling of the EPE profile (linear, so exact = CVA * 0.01).

ParameterTypeDescription
credit_spread *number
discount_factors *object
expected_exposure *object
time_steps *object
recovery_ratenumber
spread_bumpnumber

debt_valuation_adjustment_dva

Debit Valuation Adjustment — the symmetric own-default benefit. DVA mirrors CVA using the *negative* expected exposure (the amount the bank owes) and the bank's *own* credit spread. It is a gain to the reporting entity (own default extinguishes a liability). Under the hood this simply calls :func:`credit_valuation_adjustment_cva` on the negative-exposure profile with the bank's own spread and recovery substituted in, rather than a separately derived formula.

ParameterTypeDescription
discount_factors *object
expected_negative_exposure *object
own_credit_spread *number
time_steps *object
own_recovery_ratenumber

default_correlation_matrix

Pairwise default correlation from asset correlations (Gaussian copula). The default correlation between two obligors is ``rho_D = (P(both default) - PD_i PD_j) / sqrt(PD_i(1-PD_i) PD_j(1-PD_j))`` where the joint default probability is the bivariate normal CDF ``Phi_2(N^{-1}(PD_i), N^{-1}(PD_j); rho_A)`` with asset correlation rho_A.

ParameterTypeDescription
asset_correlation *object
pd *object

downturn_lgd_adjustment

Basel downturn-LGD adjustment of a long-run average LGD. CRR Art. 181 requires LGD to reflect economic-downturn conditions when these are more conservative than the long-run average. Two scaling methods are available: - ``"multiplicative"`` (default, backward-compatible): a transparent multiplicative scaling, ``LGD_LR * multiplier``, clipped to ``[floor, 1]`` so the result never under-states the long-run LGD. Calibrate ``downturn_multiplier`` to your own downturn analysis — this is not itself a formula prescribed by CRR Art. 181 or EBA GL. - ``"additive"``: the EBA/GL/2019/03 super…

ParameterTypeDescription
lgd_long_run *number
downturn_multipliernumber
floornumber
methodstring

effective_epe_regulatory

Basel Effective EPE (EEPE) with the non-decreasing Effective EE profile. The Effective Expected Exposure is the running maximum of EE ``EEE(t) = max(EEE(t-1), EE(t))`` (it never decreases, capturing roll-over risk). EEPE is the time-weighted average of EEE over the first year (CRE53). EAD = alpha * EEPE downstream.

ParameterTypeDescription
expected_exposure *object
time_steps *object

expected_loss_el_computation

Expected Loss ``EL = PD * LGD * EAD``.

ParameterTypeDescription
ead *number
lgd *number
pd *number

expected_positive_exposure_epe

Expected Positive Exposure — time-weighted average expected exposure. EPE is the time-average of the expected-exposure profile over the horizon (CRE53): ``EPE = (1/T) * integral_0^T EE(t) dt`` approximated by the trapezoidal rule on the supplied grid.

ParameterTypeDescription
expected_exposure *object
time_steps *object

exposure_at_default_ead_calculator

EAD for a revolving / committed facility via the CCF method. ``EAD = drawn + CCF * undrawn``. The CCF (a.k.a. credit-conversion factor) captures the share of the currently undrawn commitment expected to be drawn by the time of default. Basel F-IRB uses 0.75 for unconditionally cancellable commitments unless otherwise specified.

ParameterTypeDescription
drawn *number
undrawn *number
credit_conversion_factornumber

funding_valuation_adjustment_fva

Funding Valuation Adjustment — cost of funding uncollateralised exposure. Note: when ``survival_probability`` is omitted it defaults to 1 at every bucket, i.e. the FVA is computed with no counterparty-default conditioning applied. ``FVA = funding_spread * sum_k EPE_k * DF_k * S_k * dt_k`` — the present value of the funding-spread carry on the expected exposure over each interval, conditional on counterparty survival.

ParameterTypeDescription
discount_factors *object
expected_exposure *object
funding_spread *number
time_steps *object
survival_probabilityobject

ifrs_9_12_month_ecl_stage_1

IFRS 9 Stage 1 (12-month) Expected Credit Loss. For Stage 1 exposures ECL uses the 12-month PD: ``ECL = PD_12m * LGD * EAD * DF``.

ParameterTypeDescription
ead *number
lgd *number
pd_12m *number
discount_factornumber

ifrs_9_lifetime_ecl_stage_2_3

IFRS 9 Stage 2/3 lifetime Expected Credit Loss. Lifetime ECL sums discounted expected loss across all future periods using the *marginal* (per-period) PD term structure: ``ECL = sum_t marginal_PD_t * LGD_t * EAD_t * DF_t``. For Stage 3 the PD is effectively 1 in the first period (already defaulted); callers pass the appropriate marginal-PD vector.

ParameterTypeDescription
discount_factors *object
ead *object
lgd *object
marginal_pd *object
stageinteger

ifrs_9_scenario_weighted_ecl

Probability-weighted ECL across forward-looking macro scenarios. IFRS 9 requires ECL to reflect an unbiased probability-weighted amount over multiple scenarios (base / upside / downside): ``ECL = sum_s weight_s * ECL_s`` with weights summing to 1.

ParameterTypeDescription
scenario_ecls *object
scenario_weights *object

ifrs_9_stage_classification_pd_threshold

IFRS 9 stage classification by the PD-threshold SICR rule. Stage 3 if credit-impaired (90+ days past due, the IFRS 9 rebuttable default presumption). Otherwise Stage 2 if a significant increase in credit risk has occurred — either the lifetime PD has risen by at least ``sicr_relative_threshold`` times origination, OR the absolute PD increase exceeds ``sicr_absolute_threshold``. Else Stage 1.

ParameterTypeDescription
pd_current *number
pd_origination *number
days_past_dueinteger
sicr_absolute_thresholdnumber
sicr_relative_thresholdnumber

ifrs_9_staging_criteria_assessment

Full IFRS 9 staging assessment combining quantitative and qualitative SICR. Extends the PD-threshold rule with qualitative backstops required by IFRS 9: forbearance and internal watchlist status force at least Stage 2, while 90+ days past due forces Stage 3. The final stage is the most severe of all triggered criteria. The quantitative leg reuses :func:`ifrs_9_stage_classification_pd_threshold`'s PD-threshold rule directly (including its ``sicr_relative_threshold`` parameter) rather than an independently coded SICR test.

ParameterTypeDescription
pd_current *number
pd_origination *number
days_past_dueinteger
forbearanceboolean
sicr_relative_thresholdnumber
watchlistboolean

irb_advanced_approach_capital

Basel IRB Advanced-Approach capital (CRE31). Note: when ``correlation`` is not supplied it defaults to the Basel corporate correlation function of PD, the same formula F-IRB always uses. Under A-IRB the bank supplies its own PD, LGD, EAD and effective maturity. The risk-weight function is identical to F-IRB; only the parameter sources differ.

ParameterTypeDescription
ead *number
lgd *number
pd *number
correlationobject
maturitynumber

irb_foundation_approach_capital

Basel IRB Foundation-Approach capital (CRE31). Note: unlike :func:`irb_advanced_approach_capital`, F-IRB exposes no override at all for the asset correlation R — it is always the Basel corporate correlation function of PD. Under F-IRB the bank supplies its own PD but uses *supervisory* LGD: 45% for senior unsecured and 75% for subordinated claims (CRE32). EAD and maturity are also supervisory (M defaults to 2.5 years).

ParameterTypeDescription
ead *number
pd *number
lgdnumber
maturitynumber
senioritystring

kmv_merton_distance_to_default

Merton / KMV distance-to-default and implied PD. Note: when ``asset_drift`` is omitted, the asset drift mu used in the distance-to-default formula defaults to ``risk_free_rate`` (a risk-neutral assumption), not an estimate of the firm's actual expected asset return. In the structural Merton model the firm defaults at horizon T if asset value falls below the debt face value. The distance-to-default is ``DD = (ln(V/D) + (mu - 0.5 sigma^2) T) / (sigma sqrt(T))`` and the model PD (expected default frequency) is ``N(-DD)``.

ParameterTypeDescription
asset_value *number
asset_volatility *number
debt_face_value *number
asset_driftobject
horizonnumber
risk_free_ratenumber

logistic_regression_pd_model

Fit a logistic-regression PD model by Newton-Raphson (IRLS) MLE. Estimates ``PD = sigmoid(b0 + x·b)`` from a default indicator. A small ridge term stabilises the Hessian on separable / collinear data. An intercept is added automatically. Coefficients are found by iterative Newton-Raphson (IRLS) convergence to the maximum-likelihood estimate, not a closed-form solution.

ParameterTypeDescription
defaults *object
features *object
max_iterinteger
ridgenumber
tolnumber

loss_given_default_lgd_model

Workout LGD as one minus the recovery rate, net of workout costs. ``LGD = 1 - (recoveries - costs) / EAD``, exposure-weighted across the facility sample and clipped to ``[0, 1]``.

ParameterTypeDescription
exposure_amounts *object
recovery_amounts *object
workout_cost_ratenumber

machine_learning_pd_calibration

Platt-scaling calibration of raw ML scores into well-calibrated PDs. Many ML classifiers (gradient boosting, random forests) emit uncalibrated scores. Platt scaling fits a one-dimensional logistic map ``PD = sigmoid(a * score + b)`` so the output is a true probability. The fit reuses the Newton-Raphson logistic solver on the single score feature. No scikit-learn or other ML library is involved anywhere in this module — the calibration is a hand-rolled fit on top of this file's own solver.

ParameterTypeDescription
defaults *object
raw_scores *object
max_iterinteger
tolnumber

macroeconomic_overlays_ecl

Apply forward-looking macroeconomic overlays to a base ECL. Adjusts ECL for projected macro deviations via a multiplicative factor ``adj = 1 + sum_j sensitivity_j * factor_j`` (clamped at 0), then adds a discretionary management overlay. Captures the IFRS 9 requirement to incorporate forward-looking information not in the through-the-cycle model. This multiplicative overlay structure is a bespoke internal design choice, confirmed against BIS/EBA sources not to reproduce a specific published or regulatory ECL-overlay formula.

ParameterTypeDescription
base_ecl *number
macro_factors *object
sensitivities *object
management_overlaynumber

margin_valuation_adjustment_mva

Margin Valuation Adjustment — funding cost of posted initial margin. ``MVA = spread * sum_k IM_k * DF_k * dt_k`` — present value of the carry on posting (and funding) initial margin that earns less than the bank's funding cost over the trade's life.

ParameterTypeDescription
discount_factors *object
initial_margin_profile *object
margin_funding_spread *number
time_steps *object

maturity_adjustment_basel_irb

Basel IRB maturity adjustment (CRE31.6). ``b(PD) = (0.11852 - 0.05478 ln PD)^2`` and ``MA = (1 + (M - 2.5) b) / (1 - 1.5 b)``. At M = 2.5 the adjustment is exactly 1.0 by construction.

ParameterTypeDescription
maturity *number
pd *number

point_in_time_pd_estimation

Derive a point-in-time PD from a TTC PD and a macro factor. Inverse of the TTC transform: shifts the probit-domain TTC score by a sensitivity-scaled standardised macro index ``z`` (negative ``z`` = adverse conditions raise the PD): ``score_PIT = N^{-1}(PD_TTC) - sensitivity * z``.

ParameterTypeDescription
macro_index *number
ttc_pd *number
sensitivitynumber

potential_future_exposure_pfe

Potential Future Exposure profile via Monte-Carlo (arithmetic BM proxy). Simulates the netting-set value as ``V_t = V_0 + drift*t + sigma*sqrt(t)*Z`` and reports the per-step PFE (high quantile of positive exposure) and the peak PFE. Randomness is pre-drawn in pure Python (RULE 3). PFE at each time step is the empirical quantile of the simulated exposure distribution rather than a closed-form expression, so results carry Monte Carlo sampling noise that varies with ``n_paths`` and ``seed``.

ParameterTypeDescription
initial_value *number
time_steps *object
volatility *number
driftnumber
n_pathsinteger
quantilenumber
seedinteger

probability_of_default_pd_estimation

Estimate PD from observed default cohorts (cohort / frequency method). Computes the per-cohort default frequency and the obligor-weighted pooled PD, then applies the Basel regulatory floor (3 bps for non-defaulted exposures under CRR Art. 160/163).

ParameterTypeDescription
n_defaults *object
n_obligors *object
floornumber

ratings_migration_matrix

Estimate a row-stochastic ratings-migration matrix (cohort method). Counts observed transitions and normalises each row to a probability distribution. Empty rows (no obligors observed in that state) are set to the identity (a self-transition), keeping the matrix row-stochastic. This identity substitution for empty rows is a modelling convention, not an observed transition — it exists purely so the returned matrix stays row-stochastic and is safe to chain into further calculations.

ParameterTypeDescription
from_rating *object
n_states *integer
to_rating *object

recovery_rate_estimation

Estimate the recovery rate (1 - LGD) from a defaulted-facility sample. Supports optional present-valuing of recoveries via per-facility discount factors (workout recoveries are received some time after default).

ParameterTypeDescription
exposure_amounts *object
recovery_amounts *object
discount_factorsobject

retail_scorecard_pd_model

Retail scorecard: additive points to a PD via the points-to-double-odds map. A scorecard sums attribute points into a score; the score relates to odds by ``odds = base_odds * 2^{(score - base_score)/pdo}`` (PDO = points to double the odds). PD = ``1 / (1 + odds)``.

ParameterTypeDescription
base_points *number
feature_values *object
points_per_feature *object
base_oddsnumber
base_scorenumber
pdonumber

sector_default_rate_analysis

Per-sector default-rate analysis with a concentration of distress. Computes each sector's default rate, the obligor-weighted overall rate and each sector's relative risk versus the portfolio average (lift > 1 means the sector defaults more than average).

ParameterTypeDescription
sector_defaults *object
sector_obligors *object
sector_namesobject

sme_correlation_factor_basel

Basel SME firm-size correlation adjustment (CRE31.10). For SME corporate exposures (sales €5m-€50m) the asset correlation is reduced by a size term: ``R_SME = R_corp - 0.04 * (1 - (S - 5)/45)`` with S clamped to ``[5, 50]``. This lowers the capital charge for smaller, more idiosyncratic borrowers.

ParameterTypeDescription
annual_sales_millions *number
pd *number

sovereign_credit_risk_assessment

Composite sovereign credit-risk score from macro-fiscal indicators. Maps standard sovereign indicators into a ``[0, 100]`` creditworthiness score (higher = stronger): high debt/GDP and twin deficits reduce the score; larger FX reserves and stronger governance raise it. The score is mapped to an indicative PD via a logistic transform. This is a bespoke internal composite-indicator model, confirmed against BIS/EBA sources not to match any specific published sovereign-risk methodology (e.g. a rating-agency or IMF framework).

ParameterTypeDescription
current_account_pct *number
debt_to_gdp *number
fiscal_balance_pct *number
fx_reserves_months *number
governance_score *number

standardised_approach_ccr_sa_ccr

Basel SA-CCR EAD (CRE52). ``EAD = alpha * (RC + PFE)`` where the replacement cost is ``RC = max(MtM - collateral, 0)`` (unmargined) and ``PFE = multiplier * AddOn_aggregate`` with the regulatory recognition-of-excess-collateral multiplier ``multiplier = min(1, 0.05 + 0.95 * exp((MtM - C)/(1.9 * AddOn)))``. The supervisory ``alpha`` is 1.4.

ParameterTypeDescription
add_on_aggregate *number
collateral *number
mark_to_market *number
alphanumber

through_the_cycle_pd_adjustment

Convert a point-in-time PD to a through-the-cycle PD. TTC PDs dampen the macro cycle for stable regulatory capital. A convex blend in the Gaussian-score (probit) domain is used so the result stays a valid probability: ``score_TTC = (1-w) score_PIT + w score_LRA`` with ``w = cyclicality`` and ``score = N^{-1}(PD)``.

ParameterTypeDescription
long_run_average_pd *number
pit_pd *number
cyclicalitynumber

unexpected_loss_ul_computation

Stand-alone Unexpected Loss per exposure and the un-diversified sum. For a Bernoulli default with deterministic LGD, the stand-alone UL of one exposure is ``EAD * LGD * sqrt(PD(1-PD))`` — the loss standard deviation. The portfolio UL reported here is the *sum* of stand-alone ULs (i.e. the fully-correlated upper bound); correlation-aware UL is handled by the Vasicek / CreditMetrics models in :mod:`engine.credit_var`.

ParameterTypeDescription
ead *object
lgd *object
pd *object

wrong_way_risk_adjustment

Wrong-way-risk (WWR) multiplicative adjustment to CVA. When exposure rises as the counterparty's credit deteriorates (positive correlation), CVA is understated. A first-order alpha multiplier ``alpha = 1 + correlation * exposure_volatility`` (clamped >= 0) scales the base CVA; negative correlation gives right-way risk (alpha < 1). This is a first-order proxy multiplier, confirmed against the WWR literature (Hull & White 2012; Gregory, *The xVA Challenge*) not to reproduce a specific published WWR model — treat it as a reasonable internal approximation.

ParameterTypeDescription
base_cva *number
correlation *number
exposure_volatilitynumber

xva_aggregation

Aggregate the XVA components into a total valuation adjustment. Sign convention (cost to the bank is positive, reducing the trade value): ``total_xva = CVA - DVA + FVA + KVA + MVA``. DVA is a benefit and so enters negatively. The adjusted price is ``risk_free_price - total_xva`` downstream.

ParameterTypeDescription
cva *number
dvanumber
fvanumber
kvanumber
mvanumber

american_option_lsm

American option price via Longstaff-Schwartz Monte Carlo (LSM). Allows early exercise at every time step. The price must be >= the European price of the same option. Note: the continuation value at each exercise date is fit by quadratic OLS regression on in-the-money paths rather than evaluated from a closed-form formula, and the opt-in Greeks use a spot bump roughly 30x larger than this module's smooth-payoff pricers because that regression-based exercise decision is discontinuous in spot. Deliberately has no qmc option (task #15 Phase 2 evaluated and rejected it for this function specific…

ParameterTypeDescription
rate *number
sigma *number
spot *number
strike *number
tau *number
div_yieldnumber
greeksboolean
n_simulationsinteger
n_stepsinteger
option_typestring
seedinteger

asian_option_pricer

Arithmetic-average Asian option price via Monte Carlo. The averaging reduces volatility, so an Asian option is worth less than the corresponding vanilla European option.

ParameterTypeDescription
rate *number
sigma *number
spot *number
strike *number
tau *number
average_typestring
div_yieldnumber
greeksboolean
n_simulationsinteger
n_stepsinteger
option_typestring
qmcboolean
seedinteger

asset_swap_spread

Par-par asset-swap spread. The spread equating the bond's net present value to an annuity of the swap's fixed-leg PV01: ``ASW = (PV_bond − reference_price) / annuity``, expressed in basis points. By default (``use_market_price=False``), ``reference_price`` is ``face_value`` (par) — this reproduces the function's original, par-referenced behaviour exactly and is unchanged for any existing caller. Set ``use_market_price=True`` to use the bond's actual dirty price instead, matching the standard market convention (O'Kane, 2000, "Introduction to Asset Swaps", Lehman Brothers): the spread is o…

ParameterTypeDescription
bond_price *number
cashflows *object
swap_rates *object
times *object
face_valuenumber
frequencyinteger
use_market_priceboolean

barrier_option_pricer

Single-barrier option price (Reiner-Rubinstein closed form), with a modelled rebate leg. Uses the in-out parity ``knock-in + knock-out = vanilla`` for the *pure* (no-rebate) option legs, so any of the four standard combinations is supported. A nonzero ``rebate`` adds the standard Reiner-Rubinstein cash rebate term on top of that pure leg: for a knock-in, the rebate is paid at expiry if the barrier is never touched (the "E" term below); for a knock-out, the rebate is paid at the moment the barrier is touched (the "F" term below) -- the standard two rebate conventions (Haug, *The Complete Guid…

ParameterTypeDescription
barrier *number
rate *number
sigma *number
spot *number
strike *number
tau *number
barrier_typestring
div_yieldnumber
option_typestring
rebatenumber

basket_option_pricer

Basket option price via Monte Carlo on a weighted sum of assets. Diversification means the basket option is worth no more than the weighted sum of single-asset options.

ParameterTypeDescription
correlation *object
rate *number
sigmas *object
spots *object
strike *number
tau *number
weights *object
greeksboolean
n_simulationsinteger
option_typestring
seedinteger

bermudan_option_pricer

Bermudan option price via LSM with discrete exercise dates. Early exercise is allowed only on an evenly-spaced subset of the time grid. Price lies between the European and American values. Note: uses the same Longstaff-Schwartz regression-based exercise decision as ``american_option_lsm`` (no closed form), restricted to an evenly-spaced subset of roughly ``n_steps / exercise_dates`` grid points.

ParameterTypeDescription
rate *number
sigma *number
spot *number
strike *number
tau *number
div_yieldnumber
exercise_datesinteger
greeksboolean
n_simulationsinteger
n_stepsinteger
option_typestring
seedinteger

binomial_tree_option_pricer

Cox-Ross-Rubinstein binomial tree option price. Handles European and American exercise. European prices converge to Black-Scholes as ``n_steps`` grows.

ParameterTypeDescription
rate *number
sigma *number
spot *number
strike *number
tau *number
div_yieldnumber
n_stepsinteger
option_typestring
stylestring

black_scholes_european_option

Black-Scholes-Merton price of a European option. ``Call = S e^{-qτ} N(d1) − K e^{-rτ} N(d2)``; the put follows by parity. When ``tau == 0`` the intrinsic value is returned (zero-time limit) and when ``sigma == 0`` the discounted-forward intrinsic value is returned.

ParameterTypeDescription
rate *number
sigma *number
spot *number
strike *number
tau *number
div_yieldnumber
option_typestring

black_scholes_greeks

Closed-form Black-Scholes first-order Greeks. Returns delta, gamma, vega, theta (per year) and rho. Gamma and vega are identical for calls and puts.

ParameterTypeDescription
rate *number
sigma *number
spot *number
strike *number
tau *number
div_yieldnumber
option_typestring

bond_pricer_fixed_coupon

Price a fixed-coupon bond by discounting its cashflows at a flat yield. Price falls as yield rises (inverse relationship), and equals par when the coupon rate equals the yield.

ParameterTypeDescription
coupon_rate *number
face_value *number
maturity *number
yield_rate *number
frequencyinteger

bond_pricer_floating_rate

Price a floating-rate note (FRN) from projected forward rates. Each coupon is ``(reference_rate + spread) / frequency · face``. On a reset date with discount rates equal to the reference rates, an FRN prices near par plus the PV of the spread. The coupon schedule actually priced is derived from ``len(reference_rates)`` (``discount_rates`` must match that length). ``maturity`` must be consistent with ``len(reference_rates) / frequency`` — a caller-supplied ``maturity`` that implies a different number of periods is rejected rather than silently ignored.

ParameterTypeDescription
discount_rates *object
face_value *number
maturity *number
reference_rates *object
spread *number
frequencyinteger

bootstrap_yield_curve

Bootstrap zero (spot) rates from par-coupon bond rates. Sequentially solves for each discount factor so each par bond prices to par, then converts discount factors to continuously-compounded zero rates.

ParameterTypeDescription
maturities *object
par_rates *object
face_valuenumber
frequencyinteger

callable_bond_pricer

Price a callable bond (issuer's option) on a short-rate binomial tree. A callable bond is worth no more than the equivalent straight bond — the embedded call belongs to the issuer. Note: the short-rate tree is a simplified multiplicative lattice with fixed 0.5/0.5 branch probabilities, not a Black-Derman-Toy tree calibrated to an initial term structure, and the coupon is added at every node on every step.

ParameterTypeDescription
call_price *number
coupon_rate *number
face_value *number
maturity *number
rate_vol *number
short_rate *number
frequencyinteger

cap_floor_pricer

Price an interest-rate cap/floor as a strip of caplets/floorlets.

ParameterTypeDescription
accruals *object
discount_factors *object
expiries *object
forward_rates *object
notional *number
strike *number
vols *object
option_typestring

caplet_floorlet_pricer_black

Price a single caplet/floorlet under the Black (lognormal) model. A caplet is a call on the forward rate; a floorlet is a put. Caplet + floorlet (same strike) replicate a payer FRA (put-call parity).

ParameterTypeDescription
accrual *number
discount_factor *number
expiry *number
forward_rate *number
notional *number
strike *number
vol *number
option_typestring

chooser_option_pricer

Simple chooser option price (closed form). At ``tau_choose`` the holder picks call or put (same strike/expiry). By put-call parity the value is a call plus a put on a reduced-maturity underlying: ``C(S,K,T) + P(S, K e^{-r(T-t)}·..., t)``. Worth at least the more valuable of the embedded call and put.

ParameterTypeDescription
rate *number
sigma *number
spot *number
strike *number
tau_choose *number
tau_expiry *number
div_yieldnumber

compound_option_pricer

Compound option (option-on-option) price via the Geske (1979) closed form. Supports the four standard compound types (call/put on call/put). See ``_geske_compound_price`` for the exact d-term algebra and its citation.

ParameterTypeDescription
rate *number
sigma *number
spot *number
strike_compound *number
strike_underlying *number
tau_compound *number
tau_underlying *number
compound_typestring
div_yieldnumber
greeksboolean
n_simulationsinteger
seedinteger

convertible_bond_pricer

Price a convertible bond via the bond-floor + conversion-value maximum. Value = max(straight bond floor, conversion value), a simple but standard lower-bound decomposition. The convertible is always worth at least its conversion value and at least its bond floor. Note: this lower-bound decomposition does not model conversion optionality, equity volatility, or embedded call/put features of a real convertible bond.

ParameterTypeDescription
conversion_ratio *number
coupon_rate *number
face_value *number
maturity *number
stock_price *number
yield_rate *number
frequencyinteger

convexity

Bond convexity — the second-order yield sensitivity (always >= 0 for option-free bonds). ``C = Σ cf_k · t_k(t_k + 1/m) · (1+y/m)^{-(m t_k + 2)} / P``.

ParameterTypeDescription
cashflows *object
times *object
yield_rate *number
frequencyinteger

cox_ingersoll_ross_model

CIR model: closed-form ZCB price + simulated (non-negative) short rate. ``dr = κ(θ−r)dt + σ√r dW``. The square-root diffusion keeps ``r >= 0``. The Feller condition ``2κθ ≥ σ²`` guarantees strict positivity. The Monte Carlo path uses the exact non-central chi-squared CIR transition distribution (Broadie-Kaya / Glasserman §3.4; ``_cir_paths_exact_terminal``), not an Euler discretisation -- there is no discretisation bias here at any ``n_steps``, unlike the (retained, non-production) full-truncation Euler scheme in ``_cir_paths_euler``.

ParameterTypeDescription
kappa *number
maturity *number
r0 *number
sigma *number
theta *number
n_simulationsinteger
n_stepsinteger
seedinteger

credit_default_swap_cds_pricer

Price a CDS via a flat-hazard-rate reduced-form model with accrual-midpoint default settlement. Survival ``Q(t)=e^{−λt}``. Default losses -- and the accrued premium a protection buyer owes if default falls inside a coupon period -- are both settled at each period's ACCRUAL MIDPOINT ``t_mid,i = (t_{i−1}+t_i)/2``, discounted at ``DF(t_mid,i)``, following the standard ISDA/JPMorgan reduced-form CDS convention also implemented by QuantLib's ``MidPointCdsEngine`` (which settles the same way by default: ``settlesAccrual=True``, ``paysAtDefaultTime=True`` -- confirmed by inspecting its NPV dec…

ParameterTypeDescription
discount_rate *number
hazard_rate *number
maturity *number
notional *number
recovery_rate *number
spread *number
frequencyinteger

cross_currency_swap_pricer

Price a fixed-fixed cross-currency swap (with notional exchange). Values each leg in its own currency (coupons + final notional), converts the foreign leg at the FX spot, and nets. Pay-domestic = pay the domestic leg, receive the foreign leg.

ParameterTypeDescription
accruals *object
df_dom *object
df_for *object
fixed_rate_dom *number
fixed_rate_for *number
fx_spot *number
notional_dom *number
notional_for *number
pay_domesticboolean

digital_option_pricer

Cash-or-nothing digital (binary) option price. ``Call = payout · e^{-rτ} N(d2)``, ``Put = payout · e^{-rτ} N(-d2)``.

ParameterTypeDescription
rate *number
sigma *number
spot *number
strike *number
tau *number
div_yieldnumber
option_typestring
payoutnumber

displaced_diffusion_model

Displaced-diffusion (shifted lognormal) European option price. Prices ``(S + a)`` as a lognormal with vol scaled by ``S/(S+a)`` — a simple way to interpolate between lognormal (a=0) and normal-like dynamics. Reduces exactly to Black-Scholes when ``displacement == 0``.

ParameterTypeDescription
displacement *number
rate *number
sigma *number
spot *number
strike *number
tau *number
div_yieldnumber
option_typestring

duration_macaulay

Macaulay duration — PV-weighted average time to cashflows (in years).

ParameterTypeDescription
cashflows *object
times *object
yield_rate *number
frequencyinteger

dv01_pvbp

DV01 / PVBP — price change for a 1 basis-point yield move. Computed by central difference of the price function at ±0.5bp.

ParameterTypeDescription
cashflows *object
times *object
yield_rate *number
frequencyinteger

effective_duration

Effective duration from re-priced bond values under a parallel shock. ``D_eff = (P− − P+) / (2 · P0 · Δy)`` — model-agnostic, so it captures embedded optionality (callable/puttable) that analytic duration misses.

ParameterTypeDescription
price_base *number
price_down *number
price_up *number
yield_shock *number

equity_swap_pricer

Value an equity swap leg (equity return vs funding). ``notional · (equity_return − funding·τ) · DF`` to the equity receiver.

ParameterTypeDescription
accrual *number
discount_factor *number
equity_return *number
funding_rate *number
notional *number
receive_equityboolean

forward_rate_agreement_fra

Mark-to-market value of a forward rate agreement (long = pay fixed). ``Value = notional · (forward − fra_rate) · accrual · DF(end)``. Zero value when the contracted FRA rate equals the projected forward.

ParameterTypeDescription
discount_factor *number
end *number
forward_rate *number
fra_rate *number
notional *number
start *number

fx_forward_pricer

FX forward rate and mark-to-market via covered interest-rate parity. ``F = S · e^{(r_dom − r_for)·τ}``. If a contracted forward is supplied, the MtM value (domestic ccy) of a long-foreign position is ``notional · (F − contracted) · e^{−r_dom·τ}``.

ParameterTypeDescription
rate_domestic *number
rate_foreign *number
spot *number
tau *number
contracted_forwardobject
notionalnumber

fx_option_pricer_garman_kohlhagen

Garman-Kohlhagen FX option price. Black-Scholes with the foreign rate acting as a continuous dividend yield: ``Call = S e^{−r_for τ} N(d1) − K e^{−r_dom τ} N(d2)``. Satisfies FX put-call parity ``C − P = S e^{−r_for τ} − K e^{−r_dom τ}``.

ParameterTypeDescription
rate_domestic *number
rate_foreign *number
sigma *number
spot *number
strike *number
tau *number
notionalnumber
option_typestring

heston_stochastic_volatility_model

Heston stochastic-volatility European option price (semi-analytic). Prices via the single-integral representation using the characteristic function. As ``sigma`` (vol-of-vol) → 0 with ``v0 = theta`` the price tends to Black-Scholes with constant vol ``sqrt(theta)``.

ParameterTypeDescription
kappa *number
rate *number
rho *number
sigma *number
spot *number
strike *number
tau *number
theta *number
v0 *number
option_typestring

hull_white_short_rate_model

Hull-White one-factor model with a constant mean-reversion level. ``dr = κ(θ−r)dt + σ dW`` — the extended-Vasicek form; with a constant θ the closed-form ZCB price coincides with Vasicek. Returns the analytic bond price and a Monte Carlo cross-check. Note: with ``theta_const`` held constant this function literally delegates to ``vasicek_interest_rate_model`` — it is not a genuine time-dependent Hull-White model calibrated to fit an observed market forward curve.

ParameterTypeDescription
kappa *number
maturity *number
r0 *number
sigma *number
n_simulationsinteger
n_stepsinteger
seedinteger
theta_constnumber

inflation_linked_bond_pricer

Price an inflation-linked (real) bond with index-uplifted principal. Coupons and principal accrete with cumulative inflation; the resulting nominal cashflows are discounted at the real yield (the standard real-cashflow / real-yield convention).

ParameterTypeDescription
face_value *number
inflation_rate *number
maturity *number
real_coupon_rate *number
real_yield *number
frequencyinteger

interest_rate_swap_irs_pricer

Price a vanilla fixed-vs-float interest-rate swap. Float leg PV = ``notional · Σ fwd_i · τ_i · DF_i``; fixed leg PV = ``notional · fixed · Σ τ_i · DF_i``. Swap value to the payer is ``float − fixed``. The par (break-even) fixed rate is also returned.

ParameterTypeDescription
accruals *object
discount_factors *object
fixed_rate *number
forward_rates *object
notional *number
pay_fixedboolean

lmm_bgm_rate_model

LIBOR Market Model (BGM) forward-rate Monte Carlo simulation. Evolves a vector of forward LIBOR rates under the spot measure with the standard log-normal BGM drift, discretised via the Glasserman-Zhao predictor-corrector Euler scheme (see ``_lmm_terminal_rates_predictor_corrector``). Returns the mean terminal forward curve; rates stay positive (log-normal dynamics). The drift for rate ``i`` sums over ``j = 0..i`` inclusive (including rate ``i`` itself), evaluated from a single consistent rate vector at each of the predictor and corrector stages -- not a sequential same-step overwrite (see ``…

ParameterTypeDescription
forward_rates *object
horizon *number
tenor *number
vols *object
n_simulationsinteger
n_stepsinteger
seedinteger

local_volatility_dupire_model

Dupire local volatility surface from a call-price surface. Uses finite differences of the Dupire equation ``σ_loc² = (∂C/∂T + r K ∂C/∂K) / (½ K² ∂²C/∂K²)`` on the supplied grid, covering the FULL grid: central differences in strike at interior points, one-sided (forward/backward) 2nd-order-accurate differences at the two strike boundaries (exact non-uniform-grid Fornberg-style 3-point stencils -- exact for any quadratic, verified against hand-differentiated polynomials), and a forward/backward difference in maturity at the first/last maturity respectively (interior maturitie…

ParameterTypeDescription
call_surface *object
maturities *object
rate *number
spot *number
strikes *object

lookback_option_pricer

Lookback option price via Monte Carlo. Floating-strike: call pays ``S_T − min`` (>= 0), put pays ``max − S_T``. Fixed-strike: call pays ``max − K``, put pays ``K − min``. Always >= the corresponding vanilla payoff.

ParameterTypeDescription
rate *number
sigma *number
spot *number
strike *number
tau *number
div_yieldnumber
greeksboolean
n_simulationsinteger
n_stepsinteger
option_typestring
qmcboolean
seedinteger
strike_typestring

modified_duration

Modified duration = Macaulay duration / (1 + y/m). Approximates the percentage price change for a 1-unit yield move: ``ΔP/P ≈ −D_mod · Δy``.

ParameterTypeDescription
cashflows *object
times *object
yield_rate *number
frequencyinteger

monte_carlo_option_pricer

Monte Carlo price of a European option (terminal GBM payoff). Randoms are pre-drawn in pure Python (CLAUDE.md §3.1 RULE 3); the JIT kernel only consumes the pre-drawn standard-normal array.

ParameterTypeDescription
rate *number
sigma *number
spot *number
strike *number
tau *number
div_yieldnumber
n_simulationsinteger
option_typestring
seedinteger

nelson_siegel_curve_fit

Fit a Nelson-Siegel curve to observed yields. Parameters: ``beta0`` (level), ``beta1`` (slope), ``beta2`` (curvature), ``tau`` (decay). ``beta0 + beta1`` is the instantaneous short rate and ``beta0`` is the asymptotic long rate.

ParameterTypeDescription
maturities *object
yields *object
tau_initnumber

nelson_siegel_svensson_curve

Fit the Nelson-Siegel-Svensson (six-parameter) curve. Adds a second curvature hump (``beta3``, ``tau2``) to Nelson-Siegel, giving a closer fit to longer/more complex term structures.

ParameterTypeDescription
maturities *object
yields *object
tau1_initnumber
tau2_initnumber

normal_inverse_gaussian_model

Normal Inverse Gaussian European option price via Monte Carlo. NIG is Brownian motion subordinated by an inverse-Gaussian process. The drift is corrected so the discounted spot is a martingale.

ParameterTypeDescription
rate *number
spot *number
strike *number
tau *number
alphanumber
betanumber
deltanumber
greeksboolean
n_simulationsinteger
option_typestring
seedinteger

oas_option_adjusted_spread

Option-adjusted spread of a callable bond. Finds the constant spread added to the short rate on the pricing tree that reprices the callable bond to its market price — stripping out the embedded option so spreads are comparable across bonds. Note: the spread is root-found (Brent's method) against ``callable_bond_pricer``'s tree price rather than expressed in closed form — the equation above is the condition the solver satisfies, not an explicit OAS formula.

ParameterTypeDescription
call_price *number
coupon_rate *number
face_value *number
market_price *number
maturity *number
rate_vol *number
short_rate *number
frequencyinteger

ois_curve_sonia_sofr

Build an OIS (SONIA/SOFR) discount curve from quoted OIS swap rates. OIS swaps pay annually against compounded overnight; the discount curve is bootstrapped exactly as for par swaps (single-curve OIS-discounting).

ParameterTypeDescription
maturities *object
ois_rates *object
frequencyinteger

overnight_index_swap_ois

Value a single-period overnight index swap. Net cashflow = ``notional · (compounded_overnight − fixed) · accrual``, discounted. Zero value when the compounded rate equals the fixed rate.

ParameterTypeDescription
accrual *number
compounded_rate *number
discount_factor *number
fixed_rate *number
notional *number
pay_fixedboolean

puttable_bond_pricer

Price a puttable bond (holder's option) on a short-rate binomial tree. A puttable bond is worth at least the equivalent straight bond — the embedded put belongs to the holder. Note: uses the same simplified multiplicative short-rate lattice as ``callable_bond_pricer`` — fixed 0.5/0.5 branch probabilities, not calibrated to a market curve.

ParameterTypeDescription
coupon_rate *number
face_value *number
maturity *number
put_price *number
rate_vol *number
short_rate *number
frequencyinteger

rainbow_option_pricer

Rainbow (best-of / worst-of) option price via Monte Carlo. Payoff references the max (best-of) or min (worst-of) of the terminal asset prices against the strike.

ParameterTypeDescription
correlation *object
rate *number
sigmas *object
spots *object
strike *number
tau *number
greeksboolean
n_simulationsinteger
option_typestring
rainbow_typestring
seedinteger

rough_volatility_rbergomi_model

Rough Bergomi (rBergomi) European option price via Monte Carlo. A rough-volatility model with Hurst exponent ``H < 0.5``. Randoms are pre-drawn in pure Python (CLAUDE.md §3.1 RULE 3). Three independent numerical-correctness bugs were fixed here (task #18, found via the Tier 3 #2 test-reference audit and its follow-up verification -- see _rbergomi_volterra_driver, _rbergomi_discrete_variance and _rbergomi_paths' docstrings/comments for each in detail): 1. The fractional driver froze each increment's weight at the moment it was drawn instead of recomputing it (as a gap to the current time…

ParameterTypeDescription
rate *number
spot *number
strike *number
tau *number
control_variateboolean
etanumber
greeksboolean
hurstnumber
n_simulationsinteger
n_stepsinteger
option_typestring
rhonumber
seedinteger
xinumber

sabr_volatility_model

SABR implied (lognormal/Black) volatility via Hagan's expansion. Returns the Black implied volatility for the given strike under the SABR dynamics. At-the-money it reduces to the well-known ATM SABR vol.

ParameterTypeDescription
alpha *number
beta *number
forward *number
nu *number
rho *number
strike *number
tau *number

spread_option_kirk_approximation

Spread option price via Kirk's approximation. Prices an option on ``S1 − S2`` by reducing it to a Black-76 option on the ratio with an effective volatility. Exact when ``strike == 0`` (Margrabe). Inputs are treated as forwards (Black-76); the value is discounted once.

ParameterTypeDescription
rate *number
rho *number
sigma1 *number
sigma2 *number
spot1 *number
spot2 *number
strike *number
tau *number
option_typestring

swap_rate_curve

Par swap rates implied by a discount-factor curve. For each tenor, ``swap_rate = (1 − DF(T)) / (Σ τ · DF)`` — the fixed rate that makes a par swap have zero value.

ParameterTypeDescription
discount_factors *object
maturities *object
frequencyinteger

swaption_pricer_black

Price a European swaption under the Black model. ``Price = annuity · Black(forward_swap_rate, strike, vol, expiry)``. A payer swaption is a call on the swap rate; a receiver swaption is a put.

ParameterTypeDescription
annuity *number
expiry *number
forward_swap_rate *number
notional *number
strike *number
vol *number
option_typestring

swaption_pricer_sabr

Price a swaption using a SABR-implied Black volatility. Computes the SABR lognormal vol for the (forward, strike, expiry) point via Hagan's expansion, then plugs it into the Black swaption formula.

ParameterTypeDescription
alpha *number
annuity *number
beta *number
expiry *number
forward_swap_rate *number
notional *number
nu *number
rho *number
strike *number
option_typestring

total_return_swap_trs

Value a total-return swap leg. The total-return receiver gets the asset's total return and pays a financing rate (e.g. SOFR + spread): ``notional · (asset_return − financing·τ) · DF``.

ParameterTypeDescription
accrual *number
asset_return *number
discount_factor *number
financing_rate *number
notional *number
receive_total_returnboolean

trinomial_tree_option_pricer

Boyle trinomial tree option price. Up/middle/down branching converges to Black-Scholes for European options. Handles American exercise.

ParameterTypeDescription
rate *number
sigma *number
spot *number
strike *number
tau *number
div_yieldnumber
n_stepsinteger
option_typestring
stylestring

variance_gamma_model

Variance Gamma European option price via Monte Carlo. Note: the ``theta`` parameter here is the VG skew parameter (subordinated-drift), unrelated to the Greek theta (time decay) optionally returned when ``greeks=True``. Time-changes Brownian motion by a Gamma subordinator (mean 1, variance ``nu``). The martingale drift correction ``omega`` is computed in closed form so the discounted spot is a martingale.

ParameterTypeDescription
rate *number
spot *number
strike *number
tau *number
greeksboolean
n_simulationsinteger
nunumber
option_typestring
seedinteger
sigmanumber
thetanumber

vasicek_interest_rate_model

Vasicek model: closed-form zero-coupon bond price + simulated short rate. ``dr = κ(θ−r)dt + σ dW``. The affine ZCB price is ``P = A·e^{−B·r0}``. The short rate is Gaussian (can go negative).

ParameterTypeDescription
kappa *number
maturity *number
r0 *number
sigma *number
theta *number
n_simulationsinteger
n_stepsinteger
seedinteger

yield_to_call

Yield to call — yield assuming redemption at the first call date. Builds the cashflow stream truncated at ``call_date`` with redemption at ``call_price`` and solves for the yield.

ParameterTypeDescription
call_date *number
call_price *number
coupon_rate *number
face_value *number
price *number
frequencyinteger

yield_to_maturity

Yield to maturity — the flat rate that discounts cashflows to ``price``. Solved by Brent root-finding. Recovers the input yield exactly when ``price`` was produced by :func:`engine.deriv_bonds.bond_pricer_fixed_coupon`.

ParameterTypeDescription
cashflows *object
price *number
times *object
frequencyinteger

z_spread_calculator

Z-spread — constant spread over the zero curve that reprices the bond. Solves for ``z`` such that ``Σ cf_k (1 + (zero_k + z)/m)^{-m t_k} = price``.

ParameterTypeDescription
cashflows *object
price *number
times *object
zero_rates *object
frequencyinteger

zero_coupon_bond_pricer

Price a zero-coupon bond: ``face / (1 + y/m)^{m·T}``.

ParameterTypeDescription
face_value *number
maturity *number
yield_rate *number
frequencyinteger

asset_encumbrance_ratio

Asset encumbrance ratio (EBA reporting). ``encumbrance = encumbered assets / total assets``. High encumbrance reduces the unencumbered asset pool available to monetise in stress.

ParameterTypeDescription
encumbered_assets *number
total_assets *number

available_stable_funding_asf_calc

Available Stable Funding for the NSFR numerator. ASF is the weighted sum of funding sources by their ASF factor. Basel III assigns higher factors to more stable funding (e.g. capital and >1y funding = 100%, stable retail deposits = 95%, less-stable = 90%, wholesale <1y typically 50% or 0%).

ParameterTypeDescription
asf_factors *object
funding_amounts *object

cash_flow_ladder_1_year

One-year bucketed contractual cash-flow ladder. Aggregates inflows and outflows into the standard maturity buckets and computes the per-bucket and cumulative liquidity gap.

ParameterTypeDescription
bucket_inflows *object
bucket_outflows *object
bucketsobject
opening_balancenumber

cash_flow_ladder_30_day

30-day daily contractual cash-flow ladder. Projects the daily net and cumulative liquidity position over a 30-day horizon. The minimum cumulative balance (including the opening balance) is the tightest liquidity point — if negative the institution faces a funding shortfall on that day.

ParameterTypeDescription
daily_inflows *object
daily_outflows *object
opening_balancenumber

central_bank_facility_eligibility

Central-bank facility collateral eligibility and borrowing capacity. Filters assets meeting the central bank's minimum credit rating (encoded as an ordinal where higher = better) and computes the post-central-bank-haircut borrowing capacity from eligible assets.

ParameterTypeDescription
asset_ratings *object
asset_values *object
cb_haircuts *object
min_rating *integer

collateral_availability_analysis

Collateral availability — post-haircut monetisable value. Computes the net realisable collateral value after haircuts and netting off already-pledged amounts — the counterbalancing capacity available to raise secured funding.

ParameterTypeDescription
collateral_values *object
haircuts *object
already_pledgedobject

combined_stress_scenario

Combined idiosyncratic + market-wide stress scenario. By default (the two retail-category arguments omitted) this is NOT the BCBS 238 reference combined scenario: BCBS 238's own combined idiosyncratic + market-wide scenario (§II paras 19-20) runs off the LCR's own regulator-set retail run-off categories (stable/less-stable deposit stability buckets, each with its own national-discretion minimum rate), whereas this function's default applies a single flat 15% retail / 100% wholesale run-off convention instead -- a structural gap a single scalar ``retail_runoff`` rate cannot close, since BCBS…

ParameterTypeDescription
hqla_by_level *object
market_haircuts *object
retail_deposits *number
wholesale_funding *number
inflowsnumber
retail_deposits_by_categoryobject
retail_runoffnumber
retail_runoff_ratesobject
wholesale_runoffnumber

contingency_funding_plan_trigger

Evaluate Contingency Funding Plan (CFP) activation triggers. Compares current early-warning metrics against their activation thresholds. A metric breaches when its value falls *below* the threshold (lower = worse; e.g. LCR, survival days). Returns the list of breached triggers and the CFP activation decision. This is a logical breach test, not an arithmetic formula, so it is shown on the Try-it panel as an indicator function of the comparison rather than a computed expression.

ParameterTypeDescription
metrics *object
thresholds *object

contingent_liquidity_risk

Contingent liquidity risk from undrawn commitments and guarantees. When ``ccf`` is not supplied it defaults to 1.0 for every commitment, i.e. full drawdown of each commitment is assumed in the expected-outflow calculation unless a lower conversion factor is explicitly passed. Estimates the expected contingent outflow as ``commitment * draw_probability * credit-conversion-factor`` — the liquidity that off-balance-sheet commitments (undrawn lines, guarantees) could absorb in stress.

ParameterTypeDescription
commitment_amounts *object
draw_probabilities *object
ccfobject

cross_currency_liquidity_bridge

Cross-currency liquidity bridge via FX swap. Sizes the FX swap needed to fund a shortfall in one currency using surplus in another. ``fx_rate`` converts one unit of the surplus currency into the shortfall currency; a ``swap_haircut`` reduces the usable surplus to reflect swap-market stress.

ParameterTypeDescription
fx_rate *number
shortfall_amount *number
shortfall_ccy *string
surplus_amount *number
surplus_ccy *string
swap_haircutnumber

deposit_stability_classification

Classify deposits as stable vs less-stable from a stability score. Each deposit carries a stability score in [0, 1] (e.g. derived from insurance coverage, transactional relationship, tenor). Deposits at or above ``stable_threshold`` are classified stable (lower LCR run-off), the rest less-stable.

ParameterTypeDescription
deposit_features *object
stable_thresholdnumber

early_warning_indicator_liquidity

Liquidity early-warning indicator (EWI) dashboard. Evaluates each EWI against its threshold and a per-indicator direction (``"higher_breach"`` means a value above threshold is a warning, e.g. funding spread; ``"lower_breach"`` means below threshold is a warning, e.g. LCR). The aggregate signal escalates with the number of triggered indicators. This is a direction-dependent logical breach test per indicator, not a single arithmetic formula, and the aggregate signal buckets are exact: normal (0 triggers), watch (1-2) and alert (3 or more).

ParameterTypeDescription
indicators *object
thresholds *object
directionsobject

funding_cost_analysis

Weighted-average funding cost. Computes the amount-weighted average cost of the funding base and the total annual funding cost in currency terms.

ParameterTypeDescription
funding_amounts *object
funding_rates *object

funding_tenor_analysis

Weighted-average funding tenor and short-term reliance. Computes the amount-weighted average tenor of the funding base and the proportion of funding maturing within 90 days — a core ILAAP structural metric (longer WAL == more stable funding).

ParameterTypeDescription
funding_amounts *object
tenors_days *object

fx_liquidity_risk_by_currency

FX liquidity risk — net position per significant currency. Computes the net liquidity gap in each currency (inflows - outflows). A significant negative position signals reliance on FX swap markets to fund the shortfall — a key vulnerability if swap markets seize.

ParameterTypeDescription
inflows_by_ccy *object
outflows_by_ccy *object

hqla_level_1_asset_classifier

Classify and value Level 1 HQLA. When ``haircuts`` is not supplied it defaults to all zeros, i.e. no haircut is applied and every asset is valued at full market value. Level 1 assets (cash, central-bank reserves, 0%-risk-weight sovereign debt) receive a 0% haircut by default and have no composition cap (BCBS 238 §50).

ParameterTypeDescription
asset_values *object
haircutsobject

hqla_level_2a_asset_classifier

Classify and value Level 2A HQLA. Unlike Level 1's zero-by-default haircut array, ``haircut`` here is a single scalar applied uniformly to every asset in ``asset_values``, and the function enforces a minimum of 15%. Level 2A assets (20%-risk-weight sovereigns, certain covered bonds, high- grade corporates) carry a minimum 15% haircut (BCBS 238 §52).

ParameterTypeDescription
asset_values *object
haircutnumber

hqla_level_2b_asset_classifier

Classify and value Level 2B HQLA. As with Level 2A, ``haircut`` is a single scalar applied uniformly to every asset in ``asset_values`` rather than a per-asset array; the function enforces a minimum of 25% (pass 0.50 for the lower-grade corporate/equity sub-bucket). Level 2B assets (RMBS 25% haircut, lower-grade corporates and qualifying equities 50% haircut) carry a minimum 25% haircut (BCBS 238 §54).

ParameterTypeDescription
asset_values *object
haircutnumber

idiosyncratic_stress_scenario

Idiosyncratic (name-specific) stress scenario. Models a firm-specific crisis (e.g. rating downgrade): partial retail deposit flight and complete loss of wholesale funding rollover. Wholesale run-off defaults to 100% — the hallmark of a name-specific shock.

ParameterTypeDescription
hqla *number
retail_deposits *number
wholesale_funding *number
retail_runoffnumber
wholesale_runoffnumber

ilaap_internal_liquidity_metric

ILAAP internal liquidity adequacy metric. Combines the institution's own counterbalancing-capacity coverage ratio (CBC / stressed outflow) with the survival-horizon adequacy versus the internal minimum (commonly 90 days). Both must hold for internal adequacy.

ParameterTypeDescription
counterbalancing_capacity *number
stressed_net_outflow *number
survival_days *number
minimum_survival_daysnumber

ilaap_stress_testing_framework

ILAAP stress-testing framework aggregator. Aggregates the outcomes of multiple named liquidity stress scenarios into an ILAAP-style summary: the binding (worst) scenario, the count of scenarios breached, and overall adequacy. Each scenario value must expose a ``surplus_deficit`` figure (as produced by the scenario functions above). SD_k in the rendered formula denotes the ``surplus_deficit`` field each named scenario dict must already carry — this function only aggregates pre-computed values and performs no cash-flow arithmetic itself.

ParameterTypeDescription
scenarios *object

intraday_liquidity_monitor

Intraday liquidity monitor (BCBS 248). Of the two figures reported, only ``net_debit_peak`` (the largest negative cumulative position) is the genuine BCBS 248 "largest net debit position" monitoring tool — ``max_usage`` is this codebase's own additional metric, not one of BCBS 248's own monitoring tools. Tracks the intraday liquidity position from time-stamped net payment flows and reports the peak usage (largest negative intraday position relative to the opening balance) and the largest net debit position.

ParameterTypeDescription
net_flows *object
opening_balance *number
timestamps *object

intraday_liquidity_stress_test

Intraday liquidity stress test (BCBS 248 stress scenarios). This is this codebase's own internal stress design — delaying a fraction of positive intraday inflows — set in the context of BCBS 248's intraday- liquidity monitoring framework; it is not BCBS 248's own prescribed stress design. Stresses the intraday profile by delaying a fraction of *inflows* (positive flows): a ``delay_factor`` of expected inflows is removed from the intraday path, sharpening the peak liquidity requirement. Reports the stressed peak usage and whether the opening buffer plus any additional shock survives.

ParameterTypeDescription
net_flows *object
opening_balance *number
delay_factornumber
inflow_delay_shocknumber

intragroup_liquidity_flow

Intragroup liquidity flow netting. Nets bilateral liquidity positions across group entities to derive each entity's net provider/receiver status and the total internal liquidity transferred. Positive = net provider of liquidity to the group.

ParameterTypeDescription
entity_positions *object

liquidity_buffer_sizing

Size the liquidity buffer to the peak cumulative stressed outflow. The required buffer equals the maximum cumulative net outflow over the stress horizon (the deepest point of the cash-flow trough), optionally uplifted by a management ``confidence_buffer`` margin.

ParameterTypeDescription
stressed_net_outflows *object
confidence_buffernumber

liquidity_coverage_ratio_lcr

Basel III Liquidity Coverage Ratio. ``LCR = HQLA / net 30-day outflows`` where net outflows are gross outflows minus *capped* inflows. Recognised inflows are floored at ``inflow_cap`` of gross outflows (default 75%), guaranteeing net outflows never fall below 25% of gross — the BCBS 238 §69 cap.

ParameterTypeDescription
gross_inflows *number
gross_outflows *number
hqla *number
inflow_capnumber

liquidity_gap_analysis

Maturity-bucket liquidity gap (assets vs liabilities). Computes the structural maturity mismatch: ``gap_i = assets_i - liabilities_i`` per bucket, plus the cumulative gap. A positive cumulative gap means more assets than liabilities mature by that point (a funding surplus); a negative gap signals a refinancing need. Like the two cash-flow-ladder functions above, an optional opening balance is added to every cumulative-gap entry — the starting cash / HQLA position carried into the first bucket. It defaults to 0.0, so existing callers see no change in behaviour.

ParameterTypeDescription
asset_maturities *object
liability_maturities *object
bucketsobject

liquidity_risk_appetite_threshold

Map a liquidity metric to a RAG (red/amber/green) risk-appetite zone. For ``higher_is_better`` metrics (LCR, NSFR, survival days) green is at or above ``green_threshold`` and red below ``amber_threshold``. For lower-is-better metrics (e.g. funding concentration) the comparison inverts. This is a piecewise categorical rule rather than a continuous formula, and the Try-it panel's rendered formula shows only the higher-is-better direction; the comparison flips (green <= amber <= metric) when ``higher_is_better`` is False.

ParameterTypeDescription
amber_threshold *number
green_threshold *number
metric_value *number
higher_is_betterboolean

liquidity_scorecard_aggregation

Weighted liquidity scorecard aggregation. Combines individual liquidity metric scores (each typically 0-100) into a single weighted composite score and maps it to a RAG rating.

ParameterTypeDescription
scores *object
weights *object

liquidity_stress_scenario

Generic single liquidity stress scenario. Applies category-specific run-off rates to funding balances to derive stressed outflows, nets inflows, and tests whether HQLA covers the net stressed outflow.

ParameterTypeDescription
balances *object
hqla *number
runoff_rates *object
inflowsnumber

liquidity_transfer_pricing

Liquidity Transfer Pricing (LTP) charge for a funding position. The FTP charge passes the cost of liquidity to business lines: the all-in transfer rate is ``base_rate + term liquidity premium + contingent liquidity premium``. The annual charge is that rate applied to notional; the lifetime charge multiplies by tenor.

ParameterTypeDescription
base_rate *number
liquidity_spread *number
notional *number
tenor_years *number
contingent_spreadnumber

liquidity_var_liqvar

Liquidity VaR (LiqVaR) by Monte Carlo simulation of stressed net outflows. Simulates the distribution of stressed net cash outflows as ``base_outflow * (1 + vol * Z)`` and reads the loss quantile at the confidence level. LiqVaR is the outflow level not exceeded with the given confidence — the liquidity analogue of market VaR. Per CLAUDE.md §3.1 RULE 3 the N(0,1) shocks are pre-drawn in pure Python and passed to the JIT kernel; an analytic normal quantile is also returned for validation. ``liqvar`` is a simulated order statistic of this floored-at-zero normal-shock model, cross-validated…

ParameterTypeDescription
base_outflow *number
outflow_vol *number
confidence_levelnumber
n_simulationsinteger
seedobject

market_wide_stress_scenario

Market-wide stress scenario. Models a system-wide crisis where HQLA monetisation value falls due to widened market haircuts (flight to quality, fire-sale discounts). Outflows are met from the haircut-reduced HQLA value.

ParameterTypeDescription
hqla_by_level *object
market_haircuts *object
outflow *number

net_stable_funding_ratio_nsfr

Basel III Net Stable Funding Ratio. ``NSFR = ASF / RSF`` and must be >= 100% (BCBS 295). Measures the proportion of long-term assets funded by stable funding sources over a one-year horizon.

ParameterTypeDescription
available_stable_funding *number
required_stable_funding *number

repo_market_stress_haircut

Repo market stress — incremental margin call from widened haircuts. Under stress, repo haircuts widen by a multiplier. The incremental margin requirement is the extra collateral (or cash) the institution must post to maintain the same secured borrowing.

ParameterTypeDescription
base_haircuts *object
collateral_values *object
stress_multipliers *object

required_stable_funding_rsf_calc

Required Stable Funding for the NSFR denominator. RSF is the weighted sum of assets by their RSF factor. More liquid / shorter assets attract lower factors (Level 1 HQLA = 5%, Level 2A = 15%, loans = 50- 85%, illiquid assets = 100%).

ParameterTypeDescription
asset_amounts *object
rsf_factors *object

retail_deposit_runoff_rate

Aggregate retail deposit run-off (Basel LCR categories). Computes the blended run-off rate across retail deposit categories (e.g. stable 5%, less-stable 10%, non-operational higher) and the total expected 30-day run-off amount.

ParameterTypeDescription
deposit_balances *object
runoff_rates *object

secured_funding_rollover_risk

Secured funding (repo) rollover risk. Estimates the funding gap from secured transactions that fail to roll: the non-rolled portion of each maturing tranche must be replaced or repaid.

ParameterTypeDescription
maturing_amounts *object
rollover_rates *object

survival_horizon_calculator

Survival horizon — days until cumulative net outflow exhausts HQLA. Walks forward through the daily net-outflow path subtracting from the HQLA counterbalancing capacity. The survival horizon is the last day on which the remaining buffer is still non-negative. ``survival_days`` is the 0-indexed day on which cumulative outflow first drives the buffer negative, so it equals the count of full days survived before breach (0 if the very first day breaches).

ParameterTypeDescription
daily_net_outflows *object
hqla *number

wholesale_funding_concentration

Wholesale funding concentration via the Herfindahl-Hirschman Index. Computes the HHI of funding shares across counterparties (sum of squared shares, in [1/n, 1]) plus the largest single-counterparty share. Higher HHI means more concentrated, less diversified funding.

ParameterTypeDescription
counterparty_amounts *object

basel_capital_addon_multiplier

Basel capital add-on multiplier from the backtest breach count. Green zone (< 5 breaches) → 3.0; yellow zone (5-9) → the BCBS graduated schedule (3.40 .. 3.85); red zone (>= 10) → 4.0. These values are set by the Basel Committee (CLAUDE.md §4.3).

ParameterTypeDescription
n_breaches *integer

charm_delta_decay

Charm — sensitivity of delta to time to maturity (∂Δ/∂τ). Computed in the time-to-maturity convention so that a finite-difference of delta with respect to τ reproduces this value. Note the sign: this is +∂Δ/∂τ (time-to-maturity), the opposite sign from the calendar-time charm convention −∂Δ/∂t (decay per day of calendar time elapsed) more commonly quoted on trading desks and in textbooks — do not assume the calendar-time sign without checking which convention a comparison source uses.

ParameterTypeDescription
rate *number
sigma *number
spot *number
strike *number
tau *number
div_yieldnumber
option_typestring

christoffersen_independence_test

Christoffersen independence (clustering) test. Likelihood-ratio test that breaches are serially independent (no clustering), via a first-order Markov transition model. Chi-squared with 1 dof at the 95% critical value. The four transition counts (n00, n01, n10, n11) that drive the likelihood ratio are derived internally from the ``breaches`` sequence itself, not supplied as separate arguments.

ParameterTypeDescription
breaches *object

combined_backtesting

Combined (conditional coverage) backtest: Kupiec + Christoffersen. The Christoffersen conditional-coverage statistic ``LR_cc = LR_POF + LR_ind`` is chi-squared with 2 dof, tested at the 95% critical value. It rejects a model that either mis-counts or clusters its breaches.

ParameterTypeDescription
breaches *object
confidence_levelnumber

component_var

Component VaR via Euler allocation. Allocates total VaR to each position as ``w_i * marginal_i``. Because VaR is homogeneous of degree 1 in the weights, the components sum exactly to the total VaR (Euler's theorem) — the property regulators require for a coherent risk decomposition.

ParameterTypeDescription
cov_matrix *object
portfolio_value *number
weights *object
confidence_levelnumber

compute_breaches

Backtesting: count days where actual loss exceeded VaR estimate. Basel traffic-light zones: Green < 5 breaches / 250 days Yellow 5-9 breaches Red >= 10 breaches

ParameterTypeDescription
actual_returns *object
var_estimates *object

compute_cvar

Conditional VaR (Expected Shortfall) — mean of losses beyond VaR threshold. Regulatory standard under Basel III / FRTB for market risk capital.

ParameterTypeDescription
confidence_level *number
sorted_losses *object

compute_loss_percentiles

Returns a dict of {percentile_label: loss_value} for fan chart display. Default percentiles cover the standard regulatory range.

ParameterTypeDescription
sorted_losses *object
percentilesobject

compute_rolling_var

Parametric (Gaussian) rolling VaR using a fixed-length trailing window. At each point, mean and volatility are estimated from only the most recent `window` observations (returns[i - window : i]), not an expanding window that grows from the start of the series. Fast approximation for backtesting — not the full Monte Carlo. Uses scipy.stats.norm for the quantile function. Returns array of VaR estimates, same length as returns (NaN for first window obs).

ParameterTypeDescription
returns *object
confidence_levelnumber
windowinteger

conditional_var_es

Conditional VaR (Expected Shortfall) from a return series. The FRTB IMA capital metric is ES at 97.5% (hence the default). ES is the mean loss conditional on exceeding the VaR threshold and is always >= VaR.

ParameterTypeDescription
portfolio_value *number
returns *object
confidence_levelnumber

contagion_stress_scenario

Propagate an initial shock through a contagion (spillover) network. Each round, the current shock spills to connected nodes via the contagion matrix C; the cumulative shock is ``shock + C·shock + C²·shock + ...`` over the requested rounds — a truncated Neumann series of the spillover operator.

ParameterTypeDescription
contagion_matrix *object
initial_shock *object
roundsinteger

cornish_fisher_var

Cornish-Fisher (modified) VaR. Expands the Gaussian quantile with the third and fourth moments so the VaR reflects skewness and fat tails. When skewness and excess kurtosis are both zero it collapses exactly to the parametric delta-normal VaR.

ParameterTypeDescription
portfolio_value *number
returns *object
confidence_levelnumber
excess_kurtosisobject
skewnessobject

correlation_matrix_historical

Historical (Pearson) correlation matrix of asset returns.

ParameterTypeDescription
returns_matrix *object

credit_pnl_attribution

Credit P&L attribution by issuer / curve. Total credit P&L = Σ cs01_i · dspread_bp_i, additive across credit names.

ParameterTypeDescription
cs01_sensitivities *object
spread_moves_bp *object
name_labelsobject

cs01_credit_spread

CS01 — sensitivity of a risky cashflow stream to a +1bp credit spread move. Cashflows are discounted at ``r + s``; CS01 is ``Σ cf_k · t_k · e^{-(r+s) t_k} · 1e-4`` — the price drop for a 1bp widening of the credit spread.

ParameterTypeDescription
cashflows *object
credit_spread *number
risk_free_rate *number
times *object

cvar_decomposition_euler

Euler decomposition of Gaussian Expected Shortfall. Under the normal model ES = sigma_p * φ(z) / (1 − α). ES is homogeneous of degree 1 in the weights, so component ES_i = w_i * (Σ w)_i / sigma_p * φ(z)/(1 − α) and the components sum exactly to total ES (Euler's theorem).

ParameterTypeDescription
cov_matrix *object
portfolio_value *number
weights *object
confidence_levelnumber

dcc_garch_dynamic_correlation

DCC-GARCH dynamic conditional correlation (Engle 2002), terminal R_T. Standardises each series, then evolves the quasi-correlation ``Q_t = (1−a−b) Q̄ + a z_{t-1} z_{t-1}' + b Q_{t-1}`` and normalises to a correlation matrix. With ``a = b = 0`` it collapses to the constant unconditional correlation Q̄.

ParameterTypeDescription
returns_matrix *object
anumber
bnumber

dv01_pv01_bucketed

Tenor-bucketed DV01 / PV01 of a fixed cashflow stream. For continuously-discounted cashflows ``PV = Σ cf_k e^{-y t_k}`` the DV01 of each cashflow (price change for a +1bp yield move) is ``cf_k · t_k · e^{-y t_k} · 1e-4``. Cashflows are summed into tenor buckets; the bucket DV01s sum exactly to the total.

ParameterTypeDescription
bucket_indices *object
cashflows *object
flat_yield *number
n_buckets *integer
times *object

egarch_volatility_model

EGARCH(1,1) asymmetric volatility model (Nelson 1991). Models log-variance, so conditional variance is positive for any parameters. The leverage term ``gamma`` makes negative shocks raise volatility more than positive shocks of equal size (when ``gamma < 0``).

ParameterTypeDescription
returns *object
alphanumber
betanumber
gammanumber
omeganumber

es_at_multiple_confidence_levels

Expected Shortfall evaluated at several confidence levels at once. Useful for limit dashboards that report internal (95%), FRTB (97.5%) and Basel (99%) ES side by side. ES is monotone non-decreasing in confidence.

ParameterTypeDescription
portfolio_value *number
returns *object
confidence_levelsarray

expected_shortfall_contribution

Per-asset ES contribution by conditional expectation in the tail. Each asset's ES contribution is its average loss across exactly the scenarios where the *portfolio* breaches VaR. By construction the contributions sum to total ES (the additive allocation FRTB expects).

ParameterTypeDescription
asset_returns *object
portfolio_value *number
weights *object
confidence_levelnumber

extreme_value_theory_var

Extreme Value Theory VaR via Peaks-Over-Threshold (Generalised Pareto). Fits a Generalised Pareto Distribution to losses exceeding a high threshold u and reads the tail quantile:: VaR_p = u + (β/ξ) · [ ((n/N_u)(1−p))^{−ξ} − 1 ] capturing tail behaviour beyond the empirical sample range.

ParameterTypeDescription
returns *object
confidence_levelnumber
threshold_quantilenumber

filtered_historical_simulation_var

Filtered Historical Simulation VaR (Barone-Adesi & Giannopoulos). Standardises returns by their EWMA conditional volatility, then re-scales the standardised residuals by the *current* volatility forecast before taking the empirical quantile. This captures volatility clustering that plain historical simulation ignores.

ParameterTypeDescription
portfolio_value *number
returns *object
confidence_levelnumber
lambda_decaynumber

frtb_ima_aggregate_capital_charge

FRTB IMA aggregate capital charge. Combines the internally-modelled capital charge (IMCC, from ES), the non-modellable SES add-on, and the default risk charge (MAR33.43): ``ACC = IMCC + SES + DRC``.

ParameterTypeDescription
imcc *number
ses *number
default_risk_chargenumber

frtb_ima_expected_shortfall

FRTB IMA Expected Shortfall (the regulatory ES at 97.5%). ES is the mean loss beyond the VaR threshold at the FRTB confidence of 97.5% (CLAUDE.md §4.2) and is always >= VaR.

ParameterTypeDescription
returns *object
confidence_levelnumber

frtb_ima_non_modellable_risk_factors

FRTB IMA non-modellable risk factor (NMRF) capital — aggregate SES. Aggregates per-factor stressed capital add-ons (ISES) as ``SES = sqrt( (ρ·Σ ISES)² + (1−ρ²)·Σ ISES² )`` (MAR33.16). With ρ = 0 this is the Euclidean sum; with ρ = 1 it is the linear (fully correlated) sum.

ParameterTypeDescription
individual_ses *object
rhonumber

frtb_ima_stressed_period_finder

Locate the FRTB IMA stressed period — the worst 250-day ES window. FRTB calibrates the stressed ES to the historical window of greatest stress. This slides a 250-day window and returns the start index whose Expected Shortfall is largest.

ParameterTypeDescription
returns *object
confidence_levelnumber
windowinteger

frtb_sa_default_risk_charge

FRTB SA Default Risk Charge (DRC) with the hedge-benefit ratio. Net jump-to-default per issuer is risk-weighted; the gross short charge is scaled by the Weighted-to-Short (hedge benefit) ratio ``WtS = Σ netLong / (Σ netLong + Σ|netShort|)`` (MAR22). DRC is floored at 0.

ParameterTypeDescription
jtd_long *object
jtd_short *object
risk_weights *object

frtb_sa_residual_risk_addon

FRTB SA Residual Risk Add-On (RRAO). A simple notional-based add-on for instruments with residual risks not captured by the SBM: ``RRAO = Σ notional_i · weight_i`` (MAR23, e.g. 1.0% on exotic underlyings, 0.1% otherwise).

ParameterTypeDescription
notionals *object
rrao_weights *object

frtb_sa_sensitivity_based_method

FRTB SA Sensitivities-Based Method (delta) risk charge. Within each bucket the risk position is ``Kb = sqrt(Σ WS_i² + Σ_{i≠j} ρ·WS_i·WS_j)``; the charge aggregates buckets as ``sqrt(Σ Kb² + Σ_{b≠c} γ·S_b·S_c)`` with ``S_b = Σ_i WS_i`` (MAR21). Both the per-bucket ``Kb²`` term and the aggregate sum under the final square root are floored at 0 before the square root is taken, guarding against a negative value under extreme correlation inputs — a safeguard not shown in the MAR21 formula above.

ParameterTypeDescription
bucket_weighted_sensitivities *array
inter_bucket_corr *number
intra_bucket_corr *number

fx_pnl_attribution

FX P&L attribution across currency pairs. Total FX P&L = Σ fx_delta_i · dFX_i, additive across currencies.

ParameterTypeDescription
fx_deltas *object
fx_moves *object
currency_namesobject

gamma_cross_gamma_matrix

Assemble the portfolio gamma / cross-gamma matrix. The diagonal holds each underlying's net gamma (∂²V/∂S_i²); off-diagonals hold cross-gammas (∂²V/∂S_i∂S_j). The matrix is symmetric (Schwarz's theorem) — gamma P&L for a shock vector ds is ``0.5 · ds' G ds``.

ParameterTypeDescription
own_gammas *object
cross_gammasobject

gamma_pnl_attribution

Gamma (convexity) P&L component: ``½ · Γ · dS²``.

ParameterTypeDescription
gamma *number
spot_move *number

garch_11_volatility_forecast

GARCH(1,1) conditional-volatility filter and multi-step forecast. Filters the conditional variance and projects it forward. The h-step forecast mean-reverts to the long-run variance ``ω/(1−α−β)`` at rate ``(α+β)`` — the defining property of a stationary GARCH(1,1). If ``omega`` is not supplied it is set by variance targeting, ``ω = (1−α−β)·Var(returns)``.

ParameterTypeDescription
returns *object
alphanumber
betanumber
horizoninteger
omegaobject

gjr_garch_asymmetric_model

GJR-GARCH(1,1) asymmetric volatility model (Glosten-Jagannathan-Runkle). A leverage indicator adds ``gamma`` to the ARCH coefficient when the prior shock was negative, so (for ``gamma > 0``) downside shocks raise volatility more. The long-run variance is ``ω/(1 − α − β − γ/2)``.

ParameterTypeDescription
returns *object
alphanumber
betanumber
gammanumber
omegaobject

greeks_based_pnl_explain

Second-order Greeks P&L explain. Predicted P&L = Δ·dS + ½Γ·dS² + ν·dσ + Θ·dt + ρ·dr. The unexplained residual is ``actual_pnl − predicted`` — the quantity the FRTB PAT scrutinises.

ParameterTypeDescription
actual_pnl *number
delta *number
gamma *number
rate_move *number
rho *number
spot_move *number
theta *number
time_step *number
vega *number
vol_move *number

historical_expected_shortfall

Non-parametric historical Expected Shortfall. Identical tail-mean definition as :func:`conditional_var_es` but framed as the historical-simulation ES: no distributional assumption, the empirical tail is averaged directly.

ParameterTypeDescription
portfolio_value *number
returns *object
confidence_levelnumber

historical_scenario_replay

Replay historical factor moves against the current portfolio. Applies each historical day's factor returns to the current exposures and reports the resulting P&L path, identifying the single worst day.

ParameterTypeDescription
exposures *object
historical_factor_returns *object

historical_simulation_var

Non-parametric Historical Simulation VaR. Re-prices the portfolio under each observed historical return and reads the empirical loss quantile — making no distributional assumption.

ParameterTypeDescription
portfolio_value *number
returns *object
confidence_levelnumber

hypothetical_multi_factor_scenario

P&L under a single hypothetical multi-factor shock. First-order P&L = Σ exposure_i * shock_i. Used for ad-hoc "what if" scenarios such as a simultaneous equity sell-off and rates spike.

ParameterTypeDescription
exposures *object
shocks *object

incremental_var

Incremental VaR of a single position. The exact (non-marginal) effect of a position on portfolio VaR: ``VaR(full) − VaR(portfolio with position i removed)``.

ParameterTypeDescription
cov_matrix *object
portfolio_value *number
position_index *integer
weights *object
confidence_levelnumber

kupiec_pof_test

Kupiec Proportion-of-Failures (POF) unconditional coverage test. Likelihood-ratio test that the observed breach rate matches the expected ``p = 1 − confidence_level``. The statistic is chi-squared with 1 dof; rejection uses the 95% critical value. At the boundary cases ``x = 0`` or ``x = n`` (zero or 100% observed breach rate) the likelihood ratio is computed with a simplified one-sided form to avoid ``ln(0)``; the general two-sided expression applies for ``0 < x < n``.

ParameterTypeDescription
n_breaches *integer
n_observations *integer
confidence_levelnumber

liquidity_adjusted_es

Liquidity-adjusted Expected Shortfall (FRTB IMA, MAR33.12). Scales the base-horizon ES up for risk factors that take longer than the base liquidity horizon T to unwind:: ES = sqrt( ES_base^2 + Σ_{j>=2} ( ES_j * sqrt((LH_j − LH_{j-1}) / T) )^2 ) where ``ES_base`` is the whole-portfolio ES at horizon T, and ``ES_j`` is the ES with respect to factors in liquidity bucket j and longer.

ParameterTypeDescription
es_base *number
liquidity_horizons *array
partial_es *array
base_horizonnumber

macro_scenario_generator

Generate correlated macro factor scenarios via the Cholesky factor. Draws standard-normal innovations in pure Python (CLAUDE.md §3.1 RULE 3) and colours them with the Cholesky factor of the supplied covariance so the generated scenarios reproduce the target factor correlation structure.

ParameterTypeDescription
factor_cov *object
n_scenariosinteger
seedobject

marginal_var

Marginal VaR — sensitivity of portfolio VaR to each position weight. For the delta-normal model VaR = z * sqrt(w' Σ w), the marginal VaR is the gradient ``∂VaR/∂w_i = z * (Σ w)_i / sigma_p``.

ParameterTypeDescription
cov_matrix *object
weights *object
confidence_levelnumber

monte_carlo_expected_shortfall

Monte Carlo Expected Shortfall. Runs the parametric-normal Monte Carlo engine and reads the ES (CVaR) from the simulated loss distribution. Deterministic for a fixed seed. Internally this delegates to ``engine.montecarlo.run_monte_carlo_var`` and returns its ``cvar_pct``/``cvar_abs`` fields; the simulation's mean and volatility (mu, sigma) are fitted directly from the ``returns`` argument, not supplied as separate distribution parameters.

ParameterTypeDescription
portfolio_value *number
returns *object
confidence_levelnumber
horizon_daysinteger
n_simulationsinteger
seedobject

parametric_delta_normal_var

Variance-covariance (delta-normal) VaR. Assumes asset returns are jointly normal so portfolio loss is normal with standard deviation ``sqrt(w' Σ w)``. VaR is the scaled normal quantile.

ParameterTypeDescription
cov_matrix *object
portfolio_value *number
weights *object
confidence_levelnumber
horizon_daysinteger

pnl_attribution_test_frtb_pat

FRTB P&L Attribution Test (PAT) — Spearman correlation and ratio test. Jointly evaluates the Spearman rank correlation between risk-theoretical P&L (RTPL) and hypothetical P&L (HPL) and the volatility ratio ``std(RTPL)/std(HPL)``, assigning the Basel traffic-light zone. These thresholds are set by the Basel Committee and are not parameterised.

ParameterTypeDescription
hypothetical_pnl *object
risk_theoretical_pnl *object

portfolio_delta_aggregated

Aggregate per-position deltas into a net portfolio delta. Net delta = Σ delta_i * quantity_i. When spot prices are supplied the cash (dollar) delta Σ delta_i * quantity_i * spot_i is also returned.

ParameterTypeDescription
deltas *object
quantities *object
spot_pricesobject

rates_pnl_attribution

Interest-rate P&L attribution by key-rate tenor. Total rates P&L = Σ sensitivity_t · dyield_bp_t, where each sensitivity is P&L per +1bp move at that tenor. Additive across the key-rate ladder.

ParameterTypeDescription
key_rate_sensitivities *object
yield_moves_bp *object
tenor_namesobject

realised_volatility

Realised volatility from a block of (typically high-frequency) returns. Realised variance is the sum of squared returns; realised volatility is its square root, and the annualised figure scales by ``sqrt(annualisation_factor)``.

ParameterTypeDescription
returns *object
annualisation_factorinteger

residual_pnl_unexplained

Unexplained (residual) P&L. Residual = actual P&L − Σ explained components. The residual plus the sum of explained components reconstructs the actual P&L exactly; a large residual relative to actual P&L flags model incompleteness (an FRTB PAT concern).

ParameterTypeDescription
actual_pnl *number
explained_components *object

reverse_stress_testing

Reverse stress test — find the most plausible scenario causing a target loss. Among all factor shocks producing the given loss, the most plausible (lowest Mahalanobis magnitude under the factor covariance) lies along ``-Σ e``. The closed-form solution for loss L is ``s* = -(L / e'Σe) · Σ e`` with magnitude ``m = L / sqrt(e'Σe)``.

ParameterTypeDescription
exposures *object
factor_cov *object
target_loss *number

rho_interest_rate

Black-Scholes Rho — option value sensitivity to the interest rate. ``Rho_call = K τ e^{-rτ} N(d2)``; ``Rho_put = -K τ e^{-rτ} N(-d2)``.

ParameterTypeDescription
rate *number
sigma *number
spot *number
strike *number
tau *number
div_yieldnumber
option_typestring

risk_factor_pca_decomposition

Principal-component decomposition of the risk-factor covariance. Eigen-decomposes the factor covariance matrix and orders components by descending variance. The explained-variance ratios sum to 1 (over all components) and the eigenvalues are non-negative (covariance is PSD).

ParameterTypeDescription
returns_matrix *object
n_componentsobject

rolling_var_backtest

Rolling-window VaR backtest over the Basel 250-day window. Estimates parametric VaR on each trailing window and counts breaches of the realised next-day return, returning the Basel traffic-light zone.

ParameterTypeDescription
returns *object
confidence_levelnumber
windowinteger

sector_stress_scenario

Sector-level stress scenario. Applies a shock to each sector's net exposure and aggregates. Total P&L is the exact sum of per-sector P&L (additivity by construction).

ParameterTypeDescription
sector_exposures *object
sector_shocks *object
sector_namesobject

sensitivity_stress_profile

One-factor sensitivity stress profile. Sweeps a single risk factor across a grid of shocks (holding others flat) and returns the P&L profile — the building block of a stress "ladder".

ParameterTypeDescription
exposures *object
factor_index *integer
shock_grid *object

spectral_risk_measure

Spectral risk measure with an exponential risk-aversion spectrum. A coherent risk measure that integrates the loss quantile against a decreasing risk-spectrum ``φ(p) = k·e^{−k(1−p)} / (1−e^{−k})``, placing more weight on the tail as the risk aversion k rises. SRM >= the mean loss and is increasing in k.

ParameterTypeDescription
returns *object
risk_aversionnumber

stressed_expected_shortfall

Stressed Expected Shortfall (FRTB IMA). FRTB requires ES to be calibrated to a historical period of significant financial stress. This computes ES over the supplied stressed window ``returns[stress_start:stress_end]`` only.

ParameterTypeDescription
portfolio_value *number
returns *object
stress_end *integer
stress_start *integer
confidence_levelnumber

theta_carry_attribution

Theta / carry attribution. Isolates the deterministic time-decay (carry) component of P&L, ``theta · dt``, optionally net of a funding cost over the same period.

ParameterTypeDescription
theta *number
time_step *number
funding_costnumber

theta_time_decay

Black-Scholes Theta — calendar time decay (∂V/∂calendar = −∂V/∂τ), per year.

ParameterTypeDescription
rate *number
sigma *number
spot *number
strike *number
tau *number
div_yieldnumber
option_typestring

traffic_light_backtesting

Basel traffic-light backtest over the 250-day window. Counts VaR breaches and assigns the Basel zone: green (< 5 breaches), yellow (5-9), red (>= 10). These boundaries are set by the Basel Committee.

ParameterTypeDescription
actual_returns *object
var_estimates *object

vanna_delta_vega_cross

Vanna — cross sensitivity ∂vega/∂S = ∂Δ/∂σ. ``Vanna = −e^{-qτ} · φ(d1) · d2 / σ``. Identical for calls and puts. It measures how delta drifts as volatility moves (and vice versa).

ParameterTypeDescription
rate *number
sigma *number
spot *number
strike *number
tau *number
div_yieldnumber

var_breach_cluster_analysis

Analyse the clustering of VaR breaches. Reports the number of breach clusters (maximal runs of consecutive breaches), the longest run, and the mean run length — diagnostics for the independence assumption that the Christoffersen test formalises. This is an algorithmic run-length computation over the breach sequence, not a closed-form statistic.

ParameterTypeDescription
breaches *object

var_by_risk_factor

Decompose VaR across systematic risk factors (Euler allocation). Identical Euler decomposition to :func:`component_var` but expressed in risk-factor space: given portfolio factor exposures ``b`` and factor covariance ``F``, the factor contribution is ``z * b_i * (F b)_i / sigma_p`` and contributions sum to the total VaR.

ParameterTypeDescription
factor_cov *object
factor_exposures *object
portfolio_value *number
confidence_levelnumber
factor_namesobject

var_fan_chart

VaR fan chart — parametric VaR bands across confidence levels and horizons. Produces, for each confidence level, the VaR projected over 1..H days using square-root-of-time volatility scaling — the standard visualisation of how the loss envelope widens with the holding period.

ParameterTypeDescription
portfolio_value *number
returns *object
confidence_levelsarray
horizon_daysinteger

vega_pnl_attribution

Vega P&L component: ``ν · dσ``.

ParameterTypeDescription
vega *number
vol_move *number

vega_surface_bucketed

Aggregate option vegas onto a bucketed (expiry × strike) surface. Each option's vega is summed into its (expiry, strike) bucket. Total vega is conserved — the surface sum equals the input vega sum.

ParameterTypeDescription
expiry_buckets *object
n_expiry *integer
n_strike *integer
strike_buckets *object
vegas *object

volatility_surface_implied_vol

Back out the implied-volatility surface from market option prices. For each quoted option the Black-Scholes equation is inverted for implied volatility by bisection. Round-tripping (pricing at the recovered IV) reproduces the input price.

ParameterTypeDescription
expiries *object
market_prices *object
rate *number
spot *number
strikes *object
option_typestring

volga_vega_convexity

Volga (vomma) — convexity of value in volatility (∂²V/∂σ² = ∂vega/∂σ). ``Volga = vega · d1 · d2 / σ``. Identical for calls and puts. Positive volga means the position is long volatility-of-volatility.

ParameterTypeDescription
rate *number
sigma *number
spot *number
strike *number
tau *number
div_yieldnumber

advanced_measurement_approach_ama

Advanced Measurement Approach (AMA) capital charge — retired under Basel III/IV. Superseded by the Standardised Measurement Approach for Basel III/IV regulatory capital (see ``basel_standardised_measurement_sma``); retained here for economic-capital, internal scenario analysis, and jurisdictions still on earlier timelines only. The AMA permits the LDA internal model. Under Basel II §669(b), if a bank can demonstrate that expected loss (EL) is already captured in its provisioning / pricing, capital may be set to unexpected loss only (OpVaR − EL); otherwise capital equals the full OpVaR.…

ParameterTypeDescription
annual_event_counts *object
loss_amounts *object
confidence_levelnumber
expected_loss_coveredboolean
n_yearsinteger
seedobject

audit_finding_risk_scorer

Score an outstanding audit finding by severity, likelihood and ageing. Base score is severity × likelihood on the 5×5 scale; overdue remediation escalates the score (each 30-day block adds an uplift), capped at 25.

ParameterTypeDescription
likelihood *integer
overdue_days *number
severity *integer

basel_standardised_measurement_sma

Basel III Standardised Measurement Approach (SMA) capital. SMA capital = BIC × ILM, where the Business Indicator Component (BIC) is a piecewise-linear function of the Business Indicator (12%/15%/18% marginal coefficients across the three buckets) and the Internal Loss Multiplier (ILM) scales by the bank's historical loss experience: ``ILM = ln(e − 1 + (LC / BIC)^0.8)``. Bucket-1 banks may set ILM = 1. The ILM = 1.0 case (``use_ilm=False``, bucket-1 BI, or non-positive BIC) is an explicit override in code rather than a value the log formula itself produces.

ParameterTypeDescription
business_indicator *number
loss_componentnumber
use_ilmboolean

business_continuity_risk_score

Business-continuity risk from RTO/RPO versus tolerance and BCP maturity. Flags where the recovery time objective (RTO) exceeds the maximum tolerable downtime (MTD) and discounts the residual risk by BCP maturity. A breach of either recovery objective is the dominant driver. By default (``rpo_target_hours`` omitted) this is byte-identical to the original RTO-only scoring: ``rpo_hours`` is still range-validated but does not affect ``bc_risk_score``, since RPO risk has nothing to be measured against without a target to compare it to. Pass ``rpo_target_hours`` (the maximum tolerable period of da…

ParameterTypeDescription
bcp_maturity *number
max_tolerable_downtime *number
rpo_hours *number
rto_hours *number
rpo_target_hoursobject

business_environment_factor_bei

Business Environment Indicator (BEI) capital adjustment multiplier. Translates forward-looking business-environment factor scores (e.g. on a 1-5 scale where higher = riskier) into a capital multiplier around 1.0: scores above the baseline increase capital, below decrease it. Part of the BEICF overlay permitted under the AMA.

ParameterTypeDescription
factor_scores *object
baselinenumber
sensitivitynumber

compound_loss_distribution

Simulate the compound (aggregate) annual loss distribution. The classic frequency ⊗ severity convolution: for each simulated year draw a Poisson(lambda) number of events, then that many lognormal(mu, sigma) severities, and sum. Per RULE 3 all randomness is pre-drawn in pure Python; the per-year aggregation runs in the JIT kernel.

ParameterTypeDescription
frequency_lambda *number
severity_mu *number
severity_sigma *number
n_yearsinteger
seedobject

conduct_risk_metric

Composite conduct-risk metric from complaints and redress intensity. Combines the complaints-per-1000-customers rate and the redress-to-revenue ratio into a normalised 0-100 conduct-risk index (higher = worse) with a RAG band.

ParameterTypeDescription
complaints *number
customers *number
redress_paid *number
revenue *number

control_testing_effectiveness

Control testing pass rate and effectiveness conclusion. The empirical pass rate from control testing samples; an exception rate above a supervisory tolerance (default >5% failures) downgrades the conclusion.

ParameterTypeDescription
tests_passed *integer
tests_total *integer

cyber_risk_loss_estimation

Estimate expected and worst-case cyber loss. Worst-case (given a breach) = ``records_exposed × cost_per_record + business_interruption_cost``; expected loss multiplies by the annual breach probability — a FAIR-style single-loss-expectancy estimate.

ParameterTypeDescription
breach_probability *number
cost_per_record *number
records_exposed *number
business_interruption_costnumber

diversification_benefit_oprisk

Diversification benefit across OpRisk cells under a single correlation. Compares the simple sum of standalone capitals (perfect-correlation, no diversification) with the correlated aggregate ``sqrt(sum_i sum_j rho_ij K_i K_j)`` using a uniform pairwise correlation. The benefit is the reduction from imperfect correlation.

ParameterTypeDescription
standalone_capitals *object
correlationnumber

escalation_threshold_calculation

Determine the escalation level for a loss against tiered thresholds. Maps a loss amount to the highest governance tier whose threshold it meets or exceeds (e.g. ``{"team": 1e3, "head": 1e4, "exco": 1e5, "board": 1e6}``). This is a rule-based lookup: it selects the triggered tier with the numerically largest threshold value, not necessarily the dict's declared "highest" tier by name or insertion order, so it relies on ``thresholds`` being ordered monotonically with severity.

ParameterTypeDescription
loss_amount *number
thresholds *object

external_loss_data_integration

Integrate scaled external loss data with internal data. External (consortium / public) losses are scaled to the firm's size by a ``scaling_factor`` (e.g. ratio of revenues) before being pooled with internal losses — the standard approach for enriching a sparse internal tail.

ParameterTypeDescription
external_losses *object
internal_losses *object
scaling_factor *number

frequency_distribution_fitting

Fit a Poisson frequency distribution to annual loss-event counts. The Poisson MLE for lambda is the sample mean of annual counts. Also reports the variance-to-mean ratio (dispersion) — a value far above 1 signals over-dispersion and a possible negative-binomial alternative.

ParameterTypeDescription
annual_event_counts *object

insurance_offset_calculation

Insurance mitigation offset for an operational loss. Recoverable amount = ``min(max(gross_loss − deductible, 0), policy_limit)`` reduced by a supervisory haircut (Basel caps total insurance recognition at 20% of capital and applies haircuts for residual term and payment uncertainty; the cap is applied by the caller).

ParameterTypeDescription
deductible *number
gross_loss *number
policy_limit *number
haircutnumber

internal_control_factor_icf

Internal Control Factor (ICF) capital adjustment multiplier. Stronger internal controls (higher average effectiveness in [0, 1]) reduce the capital multiplier below 1.0; weaker controls increase it. The BEICF counterpart to :func:`business_environment_factor_bei`.

ParameterTypeDescription
control_scores *object
baselinenumber
sensitivitynumber

it_risk_scoring

IT operational-risk score from availability, incidents and patching. Blends system availability (fraction), incident frequency and patch compliance (fraction) into a 0-100 IT-risk score (higher = worse) with a RAG band.

ParameterTypeDescription
availability *number
incident_count *number
patch_compliance *number

key_risk_indicator_kri_library

Validate and index a KRI library. Each KRI definition must carry a ``name``, a numeric ``amber_threshold`` and ``red_threshold``, and a ``direction`` (``"higher_breach"`` or ``"lower_breach"``). Returns a validated registry keyed by name. This is a pure validation/indexing pass — it checks required keys and builds the keyed registry, with no numeric computation involved.

ParameterTypeDescription
kri_definitions *array

kri_threshold_breach_detection

Classify a KRI value into a green/amber/red status. For ``higher_breach`` KRIs (higher = worse, e.g. failed trades) the value crosses amber then red as it rises; for ``lower_breach`` KRIs (lower = worse, e.g. staffing level) it crosses as it falls. For ``lower_breach`` every inequality above is reversed (red at or below the red threshold, amber between red and amber, green above amber).

ParameterTypeDescription
amber_threshold *number
red_threshold *number
value *number
directionstring

kri_trend_analysis

Linear-trend analysis of a KRI time series. Fits an OLS slope to the observation series and classifies the trend as ``"deteriorating"``, ``"improving"`` or ``"stable"`` based on the slope sign and the metric direction. "Stable" is a scale-relative rule (``|slope| < 1e-4 * mean(|observations|)``), not a fixed absolute tolerance, and the deteriorating/improving call flips with ``higher_is_worse``.

ParameterTypeDescription
observations *object
higher_is_worseboolean

loss_data_collection_framework

Internal loss-data collection above a reporting threshold. Filters loss events at or above the firm's de-minimis reporting threshold and summarises count and total — the internal loss dataset feeding the LDA.

ParameterTypeDescription
loss_events *array
reporting_threshold *number

loss_distribution_approach_lda

End-to-end Loss Distribution Approach capital estimate. Fits the frequency (Poisson) and severity (lognormal) distributions from historical data, simulates the compound distribution and reads OpVaR / capital at the regulatory confidence — the full LDA pipeline in one call. This is a composed pipeline, not a single closed-form equation; ``n_years`` and ``seed`` only control the internal Monte Carlo simulation, not the capital figure itself.

ParameterTypeDescription
annual_event_counts *object
loss_amounts *object
confidence_levelnumber
n_yearsinteger
seedobject

loss_event_classification_basel

Classify a loss event into a Basel II Level-1 event-type category. Validates the event type against the seven Basel II Level-1 categories (BCBS 128, Annex 9) and returns its ordinal index for downstream bucketing. This is a membership lookup against the fixed seven Basel II categories, not a numeric equation.

ParameterTypeDescription
event_type *string

model_risk_assessment

Model risk tier from materiality, complexity, and validation quality. Combines model materiality and complexity (1-5 each) into an inherent score, then discounts by validation quality (in [0, 1]) to a residual model-risk tier (SR 11-7 / PRA SS1/23 style). SR 11-7 / PRA SS1/23 are named only for the general materiality x complexity tiering style this follows; the specific 1-5 scale, multiplication, and RAG thresholds are pyvar's own, not values prescribed by either document.

ParameterTypeDescription
complexity *integer
materiality *integer
validation_score *number

monte_carlo_oprisk_capital

Monte Carlo OpRisk regulatory capital (OpVaR + expected shortfall). Builds the compound loss distribution and reads the loss quantile at the regulatory confidence (Basel AMA uses 99.9% over a one-year horizon). Capital is the unexpected loss = OpVaR minus expected loss.

ParameterTypeDescription
frequency_lambda *number
severity_mu *number
severity_sigma *number
confidence_levelnumber
n_yearsinteger
seedobject

near_miss_capture_framework

Summarise captured near-miss events. A near-miss is an event with zero actual loss but a non-zero potential loss. Validates events and summarises the count and aggregate potential loss — a leading indicator of control weakness. This is a rule-based filter/count over ``events``; ``actual_loss`` and ``potential_loss`` are per-event dict keys rather than top-level function parameters.

ParameterTypeDescription
events *array

operational_var_opvar

Operational VaR from an empirical aggregate-loss sample. Reads the loss quantile at the confidence level directly from a supplied (e.g. simulated or historical) annual-loss array — the generic OpVaR reader.

ParameterTypeDescription
annual_losses *object
confidence_levelnumber

oprisk_capital_allocation

Allocate total OpRisk capital across business lines (pro-rata by risk). Distributes the firm-wide capital to business lines in proportion to their standalone risk contributions, so the allocations sum exactly to the total — a coherent (additive) allocation.

ParameterTypeDescription
business_line_risks *object
total_capital *number

oprisk_economic_capital

OpRisk economic capital (unexpected loss net of mitigants). Economic capital is the unexpected loss (OpVaR − expected loss) reduced by recognised risk mitigants (insurance recoveries and diversification), floored at zero.

ParameterTypeDescription
expected_loss *number
opvar *number
diversification_benefitnumber
insurance_offsetnumber

oprisk_heat_map_generator

Generate a 5×5 OpRisk heat-map distribution. Buckets each (likelihood, impact) risk into the 5×5 grid and computes the score (likelihood × impact) and RAG band for each, plus a count matrix of risks per cell.

ParameterTypeDescription
impacts *object
likelihoods *object

oprisk_stress_testing

OpRisk stress-testing capital projection. Projects stressed capital by scaling the base capital for shocks to event frequency and severity. Because aggregate loss scales (approximately) multiplicatively in both drivers, stressed capital = ``base × (1 + freq_shock) × (1 + sev_shock)``.

ParameterTypeDescription
base_capital *number
frequency_shock *number
severity_shock *number

rcsa_control_effectiveness

Composite control effectiveness from design and operating effectiveness. Combines design effectiveness (is the control well-designed?) and operating effectiveness (does it operate as intended?) into a single [0, 1] score via a weighted average.

ParameterTypeDescription
design_score *number
operating_score *number
design_weightnumber

rcsa_inherent_risk_scoring

Inherent risk score on the 5×5 RCSA heat map. Inherent risk is the gross exposure before controls: ``likelihood × impact`` on the 1-5 scale, giving a 1-25 score mapped to a RAG band.

ParameterTypeDescription
impact *integer
likelihood *integer

rcsa_residual_risk_scoring

Residual risk after control mitigation. Residual = ``inherent × (1 − control_effectiveness)``: effective controls reduce the inherent score toward zero. The residual is mapped to a RAG band.

ParameterTypeDescription
control_effectiveness *number
inherent_score *number

rcsa_risk_identification

Validate and summarise an RCSA risk register. Checks each risk entry exposes a ``risk_id`` and a Basel ``category`` and summarises counts by category — the identification step of the RCSA cycle. This is validation plus a count-by-category aggregation, not a numeric formula; ``category`` is a per-entry dict key rather than a top-level function parameter.

ParameterTypeDescription
risk_register *array

regulatory_compliance_score

Weighted regulatory-compliance score. Computes the weighted fraction of regulatory requirements met (each 0 = not met, 1 = met, or a partial value in between) as a 0-100 compliance score with a RAG band.

ParameterTypeDescription
requirements_met *object
weightsobject

risk_appetite_statement_oprisk

Assess an OpRisk metric against appetite and tolerance limits. Maps a metric to ``within_appetite`` / ``within_tolerance`` / ``breach`` against a two-tier limit structure: appetite (the desired ceiling) and tolerance (the absolute maximum before escalation). When ``higher_is_worse=False`` every inequality is reversed and utilisation is computed as ``tolerance_limit / current_metric`` rather than the ``current_metric / tolerance_limit`` used in the higher-is-worse case.

ParameterTypeDescription
appetite_limit *number
current_metric *number
tolerance_limit *number
higher_is_worseboolean

root_cause_analysis_template

Aggregate root-cause contributions into a normalised attribution. Normalises the supplied causal-factor weights (e.g. people, process, systems, external) to sum to 1 and identifies the dominant root cause — the quantitative backbone of an RCA template.

ParameterTypeDescription
causal_factors *object

scenario_analysis_oprisk

Scenario-based OpRisk capital via a compound Monte Carlo. Builds a single scenario's aggregate annual loss distribution from its calibrated frequency and lognormal severity and reads the loss quantile — the scenario's contribution to capital. Per RULE 3 randomness is pre-drawn in pure Python.

ParameterTypeDescription
frequency_lambda *number
severity_mu *number
severity_sigma *number
confidence_levelnumber
n_yearsinteger
seedobject

scenario_expert_elicitation_model

Aggregate expert loss estimates into a consensus with dispersion. Combines multiple experts' point estimates into a weighted consensus and reports the dispersion (weighted standard deviation) as a confidence proxy — wide disagreement signals an unreliable scenario.

ParameterTypeDescription
expert_estimates *object
expert_weightsobject

scenario_frequency_estimation

Estimate a scenario's annual frequency (Poisson lambda). Uses the expert's expected events per year directly, or — if historical occurrence data is supplied — the empirical rate ``occurrences / observation_years``. The result is the Poisson lambda feeding the scenario's compound loss.

ParameterTypeDescription
expected_events_per_year *number
observation_yearsobject
occurrencesobject

scenario_severity_estimation

Calibrate a lognormal severity from expert typical / worst-case losses. Treats ``typical_loss`` as the lognormal median (so ``mu = ln(typical)``) and solves for ``sigma`` from the worst-case percentile: ``sigma = (ln(worst) − mu) / z_p``. This is the standard two-point expert calibration for scenario severities.

ParameterTypeDescription
typical_loss *number
worst_case_loss *number
worst_case_percentilenumber

severity_distribution_fitting

Fit a severity distribution to individual loss amounts. Supports four standard OpRisk severity families, all fit by maximum likelihood with the location parameter pinned at zero (severities are strictly positive, so a free location would let the MLE drift away from the actual support): - ``"lognormal"`` (default, the OpRisk industry standard): closed-form MLE of the log-loss mean/sigma, i.e. ``scipy.stats.lognorm.fit(x, floc=0)`` reparameterised as ``mu = log(scale)``, ``sigma = shape``. - ``"gamma"``: ``scipy.stats.gamma.fit(x, floc=0)`` — shape ``a`` and ``scale``; commonly used fo…

ParameterTypeDescription
loss_amounts *object
distributionstring

tail_risk_scenario_oprisk

Tail-risk scenario capital uplift for OpRisk. Stresses the extreme tail by scaling losses beyond the tail quantile by a ``severity_multiplier`` (e.g. a "perfect-storm" amplification) and re-reading the stressed tail expectation. Reports the uplift over the unstressed tail.

ParameterTypeDescription
annual_losses *object
severity_multipliernumber
tail_confidencenumber

third_party_vendor_risk

Third-party / vendor risk score. Weighted index of vendor criticality (1-5), inverse financial health, concentration and inverse substitutability — all normalised to a 0-100 score (higher = worse).

ParameterTypeDescription
concentration *number
criticality *integer
financial_health *number
substitutability *number

active_share

Active share — fraction of holdings differing from the benchmark. ``0.5 * sum(|w_i - b_i|)``; 0 means identical to benchmark, 1 means fully differentiated (Cremers & Petajisto).

ParameterTypeDescription
benchmark_weights *object
weights *object

average_drawdown

Average drawdown — mean of the drawdown series magnitude.

ParameterTypeDescription
returns *object
is_equity_curveboolean

black_litterman_model

Black-Litterman posterior expected returns and weights. Combines the CAPM-implied equilibrium returns ``Π = λ Σ w_mkt`` with investor views ``P E[r] = Q`` to produce posterior expected returns and the corresponding mean-variance weights.

ParameterTypeDescription
cov_matrix *object
market_weights *object
p_matrix *object
q_views *object
omegaobject
risk_aversionnumber
taunumber

calmar_ratio

Calmar ratio — annualised return over maximum drawdown.

ParameterTypeDescription
returns *object
periods_per_yearinteger

carbon_footprint_attribution

Carbon footprint attribution (WACI and financed emissions). Computes the Weighted Average Carbon Intensity (WACI) -- this leg matches TCFD's WACI definition regardless of mode. By default (``company_total_emissions``/``company_value`` omitted, unchanged prior behaviour) ``total_financed_emissions`` scales revenue-intensity by invested value per holding, which does NOT match the ownership-share method used by the TCFD/PCAF financed-emissions standards. Supplying BOTH ``company_total_emissions`` (each holding's investee company's total absolute Scope 1+2 emissions, tCO2e) and ``company_value`…

ParameterTypeDescription
carbon_intensities *object
portfolio_value *number
weights *object
asset_namesobject
company_total_emissionsobject
company_valueobject

carhart_4_factor_model

Carhart 4-factor regression (MKT, SMB, HML, MOM). Extends Fama-French 3-factor with the momentum (WML/MOM) factor.

ParameterTypeDescription
excess_returns *object
factors *object

concentration_risk_hhi

Concentration risk via the Herfindahl-Hirschman Index (HHI). ``HHI = sum(w_i^2)`` on absolute weights normalised to sum to 1. Ranges from ``1/n`` (equal weight) to 1 (single holding). The effective number of holdings is ``1/HHI``.

ParameterTypeDescription
weights *object

conditional_drawdown_at_risk

Conditional Drawdown at Risk (CDaR). The mean of the worst ``(1 - confidence_level)`` fraction of drawdowns — the drawdown analogue of Expected Shortfall (Chekhlov, Uryasev, Zabarankin).

ParameterTypeDescription
returns *object
confidence_levelnumber
is_equity_curveboolean

correlation_clustering

Correlation-based clustering of assets. Builds the correlation distance ``sqrt(2(1 - rho))`` and performs single-linkage agglomerative clustering down to ``n_clusters`` groups — grouping assets that co-move. The merge itself is delegated to ``scipy.cluster.hierarchy.linkage`` (``method='single'``) followed by ``fcluster(..., criterion='maxclust')`` rather than a hand-rolled merge loop; this is the same single-linkage algorithm (repeatedly merge the two clusters whose minimum pairwise distance is smallest), just computed by SciPy's tested implementation. Cluster *membership* is therefore id…

ParameterTypeDescription
returns_matrix *object
n_clustersinteger

correlation_matrix_portfolio

Correlation matrix and average pairwise correlation of asset returns.

ParameterTypeDescription
returns_matrix *object

currency_attribution

Currency attribution -- naive geometric split, or genuine Karnosky-Singer. By default (``local_risk_free``/``base_risk_free`` omitted, unchanged prior behaviour) this splits the base-currency return into a local-market component and a currency (FX) component per holding, weighted by exposure, via the geometric identity ``base = (1+local)(1+fx)-1`` with currency as the residual. This naive split is NOT Karnosky-Singer -- see Bacon, C. (2008), "Practical Portfolio Performance Measurement and Attribution", 2nd ed., Ch. 6, which presents it as the baseline before introducing Karnosky-Singer. Sup…

ParameterTypeDescription
fx_returns *object
local_returns *object
weights *object
base_risk_freeobject
currency_namesobject
local_risk_freeobject

cvar_constrained_optimisation

CVaR-constrained portfolio optimisation (Rockafellar-Uryasev). Maximises expected return subject to the portfolio CVaR (at ``confidence_level``) not exceeding ``cvar_limit``, long-only and fully invested. CVaR is computed empirically over the supplied scenarios. Solved via Rockafellar & Uryasev's (2000) original auxiliary-variable linear-programming reformulation, not a direct nonlinear CVaR constraint. Introduce an auxiliary VaR estimate ``zeta`` and one non-negative excess-loss variable ``u_s`` per scenario, then solve the convex LP minimize -mu^T w subject to sum(w) = 1, 0 <…

ParameterTypeDescription
scenario_returns *object
confidence_levelnumber
cvar_limitnumber
mean_returnsobject
periods_per_yearinteger

diversification_ratio

Diversification ratio — weighted average vol over portfolio vol. ``(w' σ) / sqrt(w' Σ w)`` where ``σ`` is the vector of asset volatilities. Always >= 1; higher means more diversification benefit (Choueifaty).

ParameterTypeDescription
cov_matrix *object
weights *object

drawdown_duration

Drawdown duration — longest and current underwater run lengths. Counts consecutive periods spent below the prior peak.

ParameterTypeDescription
returns *object
is_equity_curveboolean

equal_weight_portfolio

Equal-weight (1/N) portfolio.

ParameterTypeDescription
n_assets *integer
cov_matrixobject
mean_returnsobject
periods_per_yearinteger
risk_freenumber

esg_score_integration

ESG score integration — weighted score and optional ESG-constrained tilt. Computes the weighted-average portfolio ESG score. If ``min_esg_score`` and a covariance matrix are supplied, solves a minimum-variance long-only portfolio subject to the weighted ESG score meeting the floor.

ParameterTypeDescription
esg_scores *object
weights *object
cov_matrixobject
min_esg_scoreobject

factor_based_optimisation

Factor-based minimum-risk optimisation. Builds the asset covariance from a factor model ``Σ = B F Bᵀ + diag(specific_var)`` and finds the long-only fully-invested minimum-variance portfolio, optionally matching ``target_exposures`` to the factors via an equality constraint.

ParameterTypeDescription
factor_cov *object
factor_exposures *object
specific_var *object
periods_per_yearinteger
target_exposuresobject

factor_exposure_analysis_barra

Barra-style portfolio factor exposure. Aggregates per-asset factor loadings into portfolio-level exposures ``Bᵀ w`` — the active/absolute factor tilts of the portfolio.

ParameterTypeDescription
asset_exposures *object
weights *object
factor_namesobject

factor_return_attribution

Factor return attribution. Decomposes the realised portfolio return into per-factor contributions ``exposure_i * factor_return_i`` plus a specific (idiosyncratic) component.

ParameterTypeDescription
factor_exposures *object
factor_returns *object
specific_return *number
factor_namesobject

fama_french_3_factor_model

Fama-French 3-factor regression (MKT, SMB, HML). Regresses portfolio excess returns on the market, size (SMB) and value (HML) factors. The intercept is the factor alpha.

ParameterTypeDescription
excess_returns *object
factors *object

fama_french_5_factor_model

Fama-French 5-factor regression (MKT, SMB, HML, RMW, CMA). Adds profitability (RMW) and investment (CMA) factors to the 3-factor model.

ParameterTypeDescription
excess_returns *object
factors *object

gics_sector_exposure

GICS sector exposure aggregation. Aggregates position weights into GICS sector buckets and reports each sector's share of the portfolio. Shares sum to the total invested weight.

ParameterTypeDescription
sector_codes *array
weights *object

information_ratio

Information ratio — active return over tracking error.

ParameterTypeDescription
benchmark_returns *object
returns *object
periods_per_yearinteger

jensens_alpha

Jensen's alpha from the CAPM single-factor regression. ``alpha = mean(r - rf) - beta * mean(b - rf)`` per period; annualised by multiplication by ``periods_per_year``.

ParameterTypeDescription
benchmark_returns *object
returns *object
periods_per_yearinteger
risk_freenumber

liquidity_adjusted_portfolio_var

Liquidity-adjusted parametric VaR (LVaR). Adds a liquidity cost term equal to half the weighted bid-ask spread to the parametric delta-normal VaR (Bangia-Diebold-Schuermann simplified add-on), capturing the cost of unwinding positions.

ParameterTypeDescription
bid_ask_spreads *object
cov_matrix *object
portfolio_value *number
weights *object
confidence_levelnumber
horizon_daysinteger

marginal_contribution_to_risk

Marginal and component contribution to portfolio volatility risk. Marginal contribution ``(Σw)_i / sigma_p``; component ``w_i * marginal_i``. Component contributions sum exactly to the portfolio volatility (Euler).

ParameterTypeDescription
cov_matrix *object
weights *object

maximum_drawdown

Maximum drawdown — largest peak-to-trough decline.

ParameterTypeDescription
returns *object
is_equity_curveboolean

maximum_sharpe_ratio_portfolio

Maximum Sharpe ratio (tangency) portfolio. Maximises the annualised Sharpe ratio subject to weights summing to 1.

ParameterTypeDescription
cov_matrix *object
mean_returns *object
allow_shortboolean
periods_per_yearinteger
risk_freenumber

mean_variance_optimisation

Mean-variance (Markowitz) optimisation. Maximises ``w'μ - 0.5 * λ * w'Σw`` subject to weights summing to 1, with an optional long-only constraint.

ParameterTypeDescription
cov_matrix *object
mean_returns *object
allow_shortboolean
periods_per_yearinteger
risk_aversionnumber
risk_freenumber

minimum_variance_portfolio

Global minimum-variance portfolio. Minimises ``w'Σw`` subject to weights summing to 1. With shorting allowed the closed-form solution ``Σ⁻¹1 / (1'Σ⁻¹1)`` is used; long-only uses SLSQP.

ParameterTypeDescription
cov_matrix *object
allow_shortboolean
mean_returnsobject
periods_per_yearinteger
risk_freenumber

monte_carlo_portfolio_simulation

Monte Carlo portfolio simulation of terminal P&L. Draws correlated multivariate-normal asset returns (RULE 3: pre-drawn in pure Python via Cholesky), compounds them over the horizon in a JIT kernel, and reports the simulated VaR / ES of terminal P&L.

ParameterTypeDescription
cov_matrix *object
mean_returns *object
weights *object
confidence_levelnumber
horizoninteger
n_simulationsinteger
portfolio_valuenumber
seedinteger

omega_ratio

Omega ratio — probability-weighted gains over losses about a threshold. ``Omega = sum(max(r - threshold, 0)) / sum(max(threshold - r, 0))``.

ParameterTypeDescription
returns *object
thresholdnumber

portfolio_beta

Portfolio beta — sensitivity of portfolio returns to the benchmark. ``beta = cov(r, b) / var(b)``.

ParameterTypeDescription
benchmark_returns *object
returns *object

portfolio_turnover

Portfolio turnover — one-way traded fraction between two weight vectors. ``0.5 * sum(|w_after - w_before|)`` (one-way convention).

ParameterTypeDescription
weights_after *object
weights_before *object

principal_component_analysis

Principal Component Analysis of an asset return matrix. Eigendecomposes the covariance matrix to extract orthogonal principal components ordered by explained variance.

ParameterTypeDescription
returns_matrix *object
n_componentsobject

rebalancing_optimiser

Rebalancing optimiser with a no-trade band. Computes the trades to move from current to target weights, suppressing trades within a no-trade band to avoid churn, and reports turnover and total transaction cost. By default ``no_trade_band`` is a single user-supplied absolute weight threshold applied uniformly to every asset (unchanged prior behaviour). Supplying both ``asset_volatility`` and ``risk_aversion`` instead *derives* a per-asset band from the classic Constantinides (1986) / Davis & Norman (1990) asymptotic no-trade-region half-width — the closed-form cube-root result that Leland's…

ParameterTypeDescription
cost_bps *object
current_weights *object
target_weights *object
asset_volatilityobject
no_trade_bandnumber
risk_aversionobject

regime_detection_hmm

Two-state Gaussian regime detection via EM. Note: despite the name, this fits a stationary 2-component Gaussian mixture (EM, i.i.d. weights) — there is no transition matrix, so it does not model true HMM regime persistence/switching dynamics. Fits a two-component Gaussian mixture by EM and labels each observation by its most likely regime. The higher-variance component is reported as the "stress" regime — the standard calm/turbulent market characterisation.

ParameterTypeDescription
returns *object
n_iterinteger

resampled_efficient_frontier

Resampled efficient frontier (Michaud) minimum-variance point. Bootstraps return samples from the estimated multivariate-normal, solves the minimum-variance long-only portfolio on each resample, and averages the weights — reducing estimation-error sensitivity. All randomness is pre-drawn in pure Python (RULE 3).

ParameterTypeDescription
cov_matrix *object
mean_returns *object
n_obsinteger
n_resamplesinteger
seedinteger

residual_risk

Residual (idiosyncratic) risk — volatility of single-factor regression residuals. Regresses portfolio returns on the benchmark (CAPM) and reports the standard deviation of the residuals — the risk not explained by beta.

ParameterTypeDescription
benchmark_returns *object
returns *object
periods_per_yearinteger

return_attribution_brinson

Brinson-Hood-Beebower return attribution. Decomposes the active return into allocation, selection and interaction effects per segment. The three effects sum exactly to the total active return — the reconciliation property required for performance reporting.

ParameterTypeDescription
benchmark_returns *object
benchmark_weights *object
portfolio_returns *object
portfolio_weights *object
segment_namesobject

risk_parity_portfolio

Equal risk contribution (risk parity) portfolio. Finds long-only weights so each asset contributes equally to portfolio variance, by minimising the dispersion of risk contributions. Dispersion is measured as the sum of squared pairwise differences between all assets' risk contributions rather than each asset's deviation from the mean contribution -- a stronger gradient signal for SLSQP that converges to the same equal-risk-contribution solution.

ParameterTypeDescription
cov_matrix *object
mean_returnsobject
periods_per_yearinteger
risk_freenumber

robust_portfolio_optimisation

Robust mean-variance optimisation with a box uncertainty set on means. Uses the worst-case expected return ``μ - κ·diag(Σ)^{1/2}`` within an ellipsoidal/box uncertainty set (Tütüncü-Koenig style), then solves the standard mean-variance problem — producing more conservative weights.

ParameterTypeDescription
cov_matrix *object
mean_returns *object
periods_per_yearinteger
risk_aversionnumber
uncertaintynumber

sector_attribution

Sector attribution — Brinson allocation/selection grouped by sector. A thin specialisation of :func:`return_attribution_brinson` where segments are GICS sectors. Allocation+selection+interaction reconcile to the active return.

ParameterTypeDescription
benchmark_returns *object
benchmark_weights *object
portfolio_returns *object
portfolio_weights *object
sector_namesobject

sharpe_ratio

Annualised Sharpe ratio. Mean excess return divided by return volatility, annualised by ``sqrt(periods_per_year)``. By default (``ddof=0``, unchanged from prior behaviour) volatility is the *population* standard deviation (divide by n) of per-period excess returns. Pass ``ddof=1`` to use the *sample* standard deviation (divide by n-1) instead — the usual unbiased-estimator convention when ``returns`` is treated as a sample drawn from a larger population. The ``n``-vs-``n-1`` divisor only matters materially for small samples; for the sample sizes typical of return series (hundreds+ of obser…

ParameterTypeDescription
returns *object
ddofinteger
periods_per_yearinteger
risk_freenumber

sortino_ratio

Annualised Sortino ratio. Like Sharpe but penalises only downside deviation below ``target``, so upside volatility is not treated as risk. The numerator's excess return is measured against ``risk_free`` while the downside-deviation denominator measures shortfalls of the raw (not risk-free-adjusted) returns below the separate ``target``, so when ``target != risk_free`` the two are distinct reference rates by construction.

ParameterTypeDescription
returns *object
periods_per_yearinteger
risk_freenumber
targetnumber

tail_ratio

Tail ratio — magnitude of the right tail relative to the left tail. ``|quantile(1 - tail)| / |quantile(tail)|``. A value above 1 indicates the right (gain) tail is larger than the left (loss) tail.

ParameterTypeDescription
returns *object
tailnumber

tracking_error

Tracking error — volatility of active (portfolio minus benchmark) return.

ParameterTypeDescription
benchmark_returns *object
returns *object
periods_per_yearinteger

transaction_cost_analysis

Transaction Cost Analysis (TCA) — implementation shortfall vs benchmark. Computes per-trade slippage against an arrival/VWAP benchmark and the quantity-weighted average slippage in basis points. ``side`` is +1 for buys (paying above benchmark is a cost) and -1 for sells. By default (``decision_price`` omitted, unchanged prior behaviour) this is narrower than Perold's (1988) full implementation-shortfall decomposition -- it measures only execution slippage against the ``benchmark_prices`` (arrival/VWAP), with no delay-cost leg. Passing ``decision_price`` -- the price at the instant the inv…

ParameterTypeDescription
benchmark_prices *object
trade_prices *object
trade_quantities *object
cancellation_priceobject
decision_priceobject
sideinteger
unexecuted_quantityobject

treynor_ratio

Treynor ratio — annualised excess return per unit of systematic risk (beta).

ParameterTypeDescription
benchmark_returns *object
returns *object
periods_per_yearinteger
risk_freenumber

ulcer_index

Ulcer Index — root-mean-square of percentage drawdowns from peak. A depth-and-duration-sensitive risk measure: deeper, longer drawdowns are penalised quadratically.

ParameterTypeDescription
returns *object
is_equity_curveboolean

aifmd_risk_metrics

AIFMD Annex IV risk metrics — leverage and (optional) VaR. "Substantially leveraged" here is a simple threshold flag (commitment leverage > 3x NAV), not AIFMD's full leverage-calculation methodology. Computes leverage under the gross method and the commitment method (each as a multiple of NAV) per Delegated Regulation 231/2013 Art. 7-8. A fund is "substantially leveraged" when commitment leverage exceeds 3x NAV.

ParameterTypeDescription
commitment_exposure *number
gross_exposure *number
net_asset_value *number
var_pctobject

basel_iii_cet1_ratio

Basel III Common Equity Tier 1 (CET1) ratio. ``CET1 ratio = CET1 capital / RWA``; minimum 4.5% (Basel III §50).

ParameterTypeDescription
cet1_capital *number
risk_weighted_assets *number

basel_iii_leverage_ratio

Basel III leverage ratio. ``Leverage ratio = Tier 1 capital / total exposure measure``; minimum 3.0%. The exposure measure is non-risk-weighted (on + off balance sheet).

ParameterTypeDescription
tier1_capital *number
total_exposure *number

basel_iii_tier1_ratio

Basel III Tier 1 capital ratio. ``Tier 1 ratio = Tier 1 capital / RWA``; minimum 6.0% (Basel III §50).

ParameterTypeDescription
risk_weighted_assets *number
tier1_capital *number

basel_iii_total_capital_ratio

Basel III Total capital ratio. ``Total ratio = (Tier 1 + Tier 2) / RWA``; minimum 8.0% (Basel III §50).

ParameterTypeDescription
risk_weighted_assets *number
total_capital *number

basel_iv_output_floor

Basel IV output floor. Floored RWA = ``max(internal_model_rwa, floor_factor * standardised_rwa)``. The floor factor is 72.5% (Basel III finalisation) — do not relax.

ParameterTypeDescription
internal_model_rwa *number
standardised_rwa *number
floor_factornumber

capital_conservation_buffer

Capital Conservation Buffer (CCoB) and distribution constraint. The 2.5% CET1 buffer above the 4.5% minimum. Breaching the buffer triggers Maximum Distributable Amount (MDA) restrictions on dividends/bonuses.

ParameterTypeDescription
cet1_ratio *number
risk_weighted_assets *number
buffer_rationumber

combined_buffer_requirement

Combined Buffer Requirement (CBR). The max(G-SII, O-SII, SyRB) selection is expected to already be resolved by the caller into ``systemic_buffer_ratio``; this function itself performs only a straight sum of the three supplied buffer ratios. ``CBR = CCoB + CCyB + max(G-SII, O-SII, SyRB)`` per CRD IV. Sums the buffer ratios and (optionally) the capital amount on the supplied RWA.

ParameterTypeDescription
capital_conservation_buffer_rationumber
countercyclical_buffer_rationumber
risk_weighted_assetsnumber
systemic_buffer_rationumber

countercyclical_capital_buffer

Institution-specific Countercyclical Capital Buffer (CCyB). The CCyB rate is the exposure-weighted average of the national CCyB rates applied to the bank's private-sector credit exposures (CRD IV Art. 140).

ParameterTypeDescription
country_ccyb_rates *object
exposure_amounts *object
risk_weighted_assets *number

crr2_large_exposure_limit

CRR2 large exposure limit (Art. 395). A single client / group exposure must not exceed 25% of Tier 1 capital, or — where the counterparty is an institution (or a group of connected clients including one) — the HIGHER of 25% of Tier 1 capital or EUR 150m (``CRR2_INSTITUTION_ABSOLUTE_LIMIT_EUR``), per Art. 395(1)'s institution alternative. ``exposure_value``/``tier1_capital`` are assumed EUR-denominated, matching Art. 395(1)'s own absolute figure — this function does not itself perform currency conversion. Note: Art. 395(1)'s EUR 150m alternative additionally requires that the institutio…

ParameterTypeDescription
exposure_value *number
tier1_capital *number
is_institutionboolean

emir_clearing_obligation_check

EMIR clearing obligation check (Art. 4 / Art. 4a / Art. 10 / clearing thresholds). [REGULATORY] EMIR REFIT (Regulation (EU) 2019/834) Art. 4a(1): a Financial Counterparty (FC) that breaches its clearing threshold in ANY ONE OTC derivative asset class becomes subject to the clearing obligation for ALL asset classes it has positions in, not just the one that breached. Art. 10(1) evaluates a Non-Financial Counterparty above threshold (NFC+) per-asset-class instead -- only the classes where ITS OWN threshold is breached become subject to clearing. A prior version of this function applied FC's pe…

ParameterTypeDescription
clearing_thresholds *object
counterparty_category *string
notionals *object

emir_margin_requirement

EMIR (Art. 11) uncleared-derivatives margin requirement. Computes the Initial Margin (IM) from the rate and the net margin call after applying the Minimum Transfer Amount (MTA) to the variation margin.

ParameterTypeDescription
initial_margin_rate *number
portfolio_value *number
variation_margin *number
minimum_transfer_amountnumber

emir_trade_repository_report

EMIR trade repository report builder/validator. This validates a representative core subset of 6 fields, not full-schema coverage of EMIR REFIT's roughly 200 reportable fields. Validates the core EMIR reporting fields (counterparty LEIs, UTI, notional, asset class) and echoes a normalised report.

ParameterTypeDescription
trade *object

frtb_ima_market_risk_capital

FRTB Internal Models Approach total market-risk capital. The IMA charge combines the multiplier-scaled, stressed-scaled Expected Shortfall (the "IMCC" proxy) with the non-modellable risk factor capital (SES) and the Default Risk Charge (BCBS d457 §189). The multiplier is floored at 1.5.

ParameterTypeDescription
expected_shortfall *number
multiplier *number
stressed_es_ratio *number
default_risk_chargenumber
non_modellable_sesnumber

frtb_pl_attribution_test

FRTB P&L Attribution Test (PAT) — Spearman correlation + variance ratio. The green/amber/red zone is assigned by a fixed-threshold lookup on the correlation and ratio values below, not a single closed-form equation. Jointly evaluates the Spearman rank correlation between risk-theoretical P&L (RTPL) and hypothetical P&L (HPL) and the volatility ratio ``std(RTPL)/std(HPL)``, assigning the Basel traffic-light zone. The thresholds are mandated by BCBS d457 and CLAUDE.md §4.4: green ``|corr|>=0.80 AND 0.8<=ratio<=1.2``; amber ``|corr|>=0.70 AND 0.6<=ratio<=1.5``; otherwise red (IMA loss).

ParameterTypeDescription
hypothetical_pnl *object
risk_theoretical_pnl *object

frtb_sa_market_risk_capital

FRTB Standardised Approach total market-risk capital. The SA capital is the simple sum of the Sensitivities-Based Method charge (already aggregated across delta/vega/curvature and the three correlation scenarios), the Default Risk Charge (DRC) and the Residual Risk Add-On (RRAO) (BCBS d457 §2).

ParameterTypeDescription
default_risk_charge *number
residual_risk_addon *number
sensitivities_charge *number

frtb_trading_desk_aggregation

FRTB trading-desk capital aggregation. Aggregates per-desk capital: IMA-eligible desks contribute their IMA charge, non-eligible (PAT-red / backtest-failed) desks fall back to the SA charge. The total firm-wide market-risk capital is the sum across desks (BCBS d457 treats the firm charge as the sum of approved-desk IMA plus SA for the rest).

ParameterTypeDescription
desk_ima_charges *object
desk_ima_eligible *object
desk_sa_charges *object

icaap_capital_assessment

ICAAP internal capital adequacy assessment. Aggregates Pillar 1 capital with internally-assessed risk components (credit concentration, IRRBB, etc.) and compares to available capital.

ParameterTypeDescription
available_capital *number
pillar1_capital *number
risk_capital_components *object

mifid_ii_algorithm_documentation

MiFID II RTS 6 algorithmic-trading documentation completeness check. The 6-item checklist below is this codebase's own internal choice, not a checklist published by RTS 6 itself. Verifies that the mandatory governance and control documentation items for an algorithmic trading strategy are present.

ParameterTypeDescription
documentation *object

mifid_ii_best_execution_metric

MiFID II best-execution TCA metric -- internal, NOT an RTS 27/28 figure. This is an internal TCA (transaction cost analysis) metric only; neither RTS 27 nor RTS 28 defines a prescribed quantitative figure that this function reproduces. Computes the quantity-weighted price improvement (or slippage) of executions versus a reference (e.g. EBBO) price, in basis points. Positive means price improvement for the client. This does not correspond to any specific RTS 27/28 field: RTS 27 (Commission Delegated Regulation (EU) 2017/575) requires simple-average and volume-weighted transaction prices/spre…

ParameterTypeDescription
benchmark_prices *object
executed_prices *object
quantities *object
sideinteger

mifid_ii_post_trade_transparency

MiFID II post-trade transparency / deferred-publication assessment. Trades above the size threshold (or in illiquid instruments) may benefit from deferred publication; otherwise publication is near real-time.

ParameterTypeDescription
delayed_publication_threshold *number
trade_size *number
is_liquidboolean

mifid_ii_pre_trade_transparency

MiFID II pre-trade transparency / LIS waiver assessment. Determines whether an order qualifies for the Large-in-Scale (LIS) waiver from pre-trade transparency (illiquid instruments and orders above the LIS threshold may be waived).

ParameterTypeDescription
instrument_type *string
large_in_scale_threshold *number
order_size *number
is_liquidboolean

mifid_ii_transaction_report_validator

MiFID II / RTS 22 transaction report field validator. This checks a representative core subset of 9 fields, not full-schema coverage of RTS 22's roughly 65 mandatory transaction-report fields. Checks the presence and basic validity of the mandatory transaction-report fields (LEI length, ISIN length, positive price/quantity).

ParameterTypeDescription
report *object

pillar_2a_capital

Pillar 2A capital — sum of individual risk add-ons. Pillar 2A covers risks not (fully) captured in Pillar 1: e.g. credit concentration, IRRBB, pension, operational. Sums the component charges.

ParameterTypeDescription
risk_addons *object
risk_weighted_assets *number

pillar_2b_stress_buffer

Pillar 2B stress buffer (PRA buffer / capital guidance). The forward-looking buffer to absorb the peak capital depletion projected under the supervisory stress scenario.

ParameterTypeDescription
risk_weighted_assets *number
stressed_capital_depletion *number

sftr_securities_finance_report

SFTR securities-financing transaction report builder/validator. This validates a representative core subset of 6 fields, not full-schema coverage of SFTR's complete field set. Validates the core SFTR fields for an SFT (repo, securities lending, buy- sell back, margin lending): counterparties, UTI, collateral and the SFT type.

ParameterTypeDescription
transaction *object

solvency_ii_scr_credit_risk

Solvency II SCR counterparty default (credit) risk — Type 1 exposures. The sigma used here is the intra-counterparty (independent-Bernoulli) variance term only; Delegated Regulation (EU) 2015/35 Art. 201's inter-counterparty correlation term is not implemented, so the true Art. 201 variance (and SCR) is at least as large as what this function returns. [REGULATORY] Delegated Regulation (EU) 2015/35 Art. 200(1)-(3) fixes the capital charge as a TIERED multiplier on the standard deviation (sigma) of the loss distribution, not a flat 3x: SCR = 3*sigma while sigma <= 7% of total LGD; SCR = 5*si…

ParameterTypeDescription
default_probabilities *object
exposures *object
loss_given_default *object

solvency_ii_scr_market_risk

Solvency II SCR Market risk — standard-formula modular aggregation. Aggregates the market sub-module capital charges (interest rate, equity, property, spread, currency, concentration) using the prescribed correlation matrix and the square-root formula ``SCR = sqrt(s' Corr s)`` (Delegated Regulation 2015/35 Art. 164).

ParameterTypeDescription
correlation_matrix *object
sub_module_charges *object
sub_module_namesobject

srep_capital_add_on

SREP (Supervisory Review and Evaluation Process) capital add-on. Translates the supervisory Pillar 2A add-on ratio into a capital amount and the Total SREP Capital Requirement (TSCR).

ParameterTypeDescription
pillar1_requirement *number
pillar2a_addon_ratio *number
risk_weighted_assets *number

ucits_kiid_risk_indicator

UCITS KIID Synthetic Risk and Reward Indicator (SRRI), 1-7. The SRRI class itself is a bucket lookup of the annualised volatility against fixed CESR volatility bands, not a closed-form equation. Maps the annualised volatility of (weekly by default) returns to the SRRI bucket per CESR 10-673: class 1 (< 0.5%) up to class 7 (>= 25%).

ParameterTypeDescription
returns *object
periods_per_yearinteger