pyvar-mcp
v0.3.0MCP 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.
| Parameter | Type | Description |
|---|---|---|
domain | string | Optional 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.
| Parameter | Type | Description |
|---|---|---|
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).
| Parameter | Type | Description |
|---|---|---|
base_rates * | object | |
net_cashflows * | object | |
tier1_capital * | number | |
times * | object | |
parallel_bps | number |
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
core_fraction * | number | |
core_runoff_rate * | number | |
non_core_runoff_rate * | number | |
total_balance * | number | |
horizon_years | number |
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²)``.
| Parameter | Type | Description |
|---|---|---|
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…
| Parameter | Type | Description |
|---|---|---|
core_balance * | number | |
decay_rate * | number | |
discount_rate * | number | |
max_years | number |
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``.
| Parameter | Type | Description |
|---|---|---|
asset_duration * | number | |
liability_duration * | number | |
total_assets * | number | |
total_liabilities * | number | |
rate_shock | number |
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
base_rates * | object | |
net_cashflows * | object | |
times * | object | |
long_bps | number | |
parallel_bps | number | |
short_bps | number |
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
customer_rate * | number | |
ftp_rate * | number | |
notional * | number | |
is_asset | boolean | |
liquidity_premium | number |
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.
| Parameter | Type | Description |
|---|---|---|
tier1_capital * | number | |
worst_delta_eve * | number | |
outlier_threshold | number |
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.
| Parameter | Type | Description |
|---|---|---|
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…
| Parameter | Type | Description |
|---|---|---|
tenors * | object | |
long_bps | number | |
parallel_bps | number | |
short_bps | number |
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).
| Parameter | Type | Description |
|---|---|---|
base_rates * | object | |
net_cashflows * | object | |
times * | object | |
long_bps | number | |
parallel_bps | number | |
short_bps | number |
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).
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
cpr | object | |
smm | object |
macaulay_duration_balance_sheet
Macaulay duration of a balance-sheet cashflow stream (years).
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
cashflows * | object | |
discount_rate * | number | |
times * | object | |
frequency | integer |
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
asset_balances * | object | |
asset_rates * | object | |
liability_balances * | object | |
liability_rates * | object | |
rate_shock * | number | |
asset_beta | number | |
liability_beta | number |
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.
| Parameter | Type | Description |
|---|---|---|
balance_history * | object | |
confidence_level | number |
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.
| Parameter | Type | Description |
|---|---|---|
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).
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
bucket_assets * | object | |
bucket_liabilities * | object | |
bucket_labels | object |
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
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``.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
ead * | number | |
risk_weight * | number | |
credit_risk_mitigation | number |
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.
| Parameter | Type | Description |
|---|---|---|
capital_profile * | object | |
discount_factors * | object | |
time_steps * | object | |
cost_of_capital | number |
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.
| Parameter | Type | Description |
|---|---|---|
accrual_factors * | object | |
contract_spread * | number | |
discount_factors * | object | |
hazard_rate * | number | |
payment_times * | object | |
notional | number | |
recovery_rate | number |
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.
| Parameter | Type | Description |
|---|---|---|
cds_spread * | number | |
maturity * | number | |
recovery_rate | number |
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.
| Parameter | Type | Description |
|---|---|---|
collateral_value * | number | |
haircut_collateral * | number | |
haircut_fx | number |
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.
| Parameter | Type | Description |
|---|---|---|
factor_scores * | object | |
factor_weights * | object | |
pd_anchor | number | |
pd_floor | number |
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).
| Parameter | Type | Description |
|---|---|---|
add_on * | number | |
mark_to_market * | number | |
collateral | number |
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).
| Parameter | Type | Description |
|---|---|---|
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``.
| Parameter | Type | Description |
|---|---|---|
notional * | number | |
risky_annuity * | number | |
spread_volatility * | number | |
confidence_level | number | |
horizon_days | integer | |
position | string |
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.
| Parameter | Type | Description |
|---|---|---|
expected_losses * | object | |
expected_returns * | object | |
max_weight | number | |
risk_aversion | number |
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).
| Parameter | Type | Description |
|---|---|---|
par_spreads * | object | |
tenors * | object | |
recovery_rate | number |
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.
| Parameter | Type | Description |
|---|---|---|
ead * | object | |
lgd * | object | |
pd * | object | |
lgd_shock_multiplier | number | |
pd_shock_multiplier | number |
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).
| Parameter | Type | Description |
|---|---|---|
credit_spread * | number | |
discount_factors * | object | |
expected_exposure * | object | |
time_steps * | object | |
recovery_rate | number |
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.
| Parameter | Type | Description |
|---|---|---|
ead_total * | number | |
lgd * | number | |
pd * | number | |
asset_correlation | number | |
confidence_level | number |
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).
| Parameter | Type | Description |
|---|---|---|
ead * | object | |
lgd * | object | |
pd * | object | |
asset_correlation | object | |
confidence_level | number | |
n_simulations | integer | |
seed | integer |
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-…
| Parameter | Type | Description |
|---|---|---|
exposures * | object | |
lgd * | object | |
pd * | object | |
asset_correlation | number | |
confidence_level | number | |
current_rating | object | |
n_simulations | integer | |
seed | integer | |
state_loss_pct | object | |
transition_matrix | object |
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.
| Parameter | Type | Description |
|---|---|---|
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).
| Parameter | Type | Description |
|---|---|---|
credit_spread * | number | |
discount_factors * | object | |
expected_exposure * | object | |
time_steps * | object | |
recovery_rate | number | |
spread_bump | number |
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.
| Parameter | Type | Description |
|---|---|---|
discount_factors * | object | |
expected_negative_exposure * | object | |
own_credit_spread * | number | |
time_steps * | object | |
own_recovery_rate | number |
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.
| Parameter | Type | Description |
|---|---|---|
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…
| Parameter | Type | Description |
|---|---|---|
lgd_long_run * | number | |
downturn_multiplier | number | |
floor | number | |
method | string |
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.
| Parameter | Type | Description |
|---|---|---|
expected_exposure * | object | |
time_steps * | object |
expected_loss_el_computation
Expected Loss ``EL = PD * LGD * EAD``.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
drawn * | number | |
undrawn * | number | |
credit_conversion_factor | number |
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.
| Parameter | Type | Description |
|---|---|---|
discount_factors * | object | |
expected_exposure * | object | |
funding_spread * | number | |
time_steps * | object | |
survival_probability | object |
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``.
| Parameter | Type | Description |
|---|---|---|
ead * | number | |
lgd * | number | |
pd_12m * | number | |
discount_factor | number |
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.
| Parameter | Type | Description |
|---|---|---|
discount_factors * | object | |
ead * | object | |
lgd * | object | |
marginal_pd * | object | |
stage | integer |
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
pd_current * | number | |
pd_origination * | number | |
days_past_due | integer | |
sicr_absolute_threshold | number | |
sicr_relative_threshold | number |
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.
| Parameter | Type | Description |
|---|---|---|
pd_current * | number | |
pd_origination * | number | |
days_past_due | integer | |
forbearance | boolean | |
sicr_relative_threshold | number | |
watchlist | boolean |
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.
| Parameter | Type | Description |
|---|---|---|
ead * | number | |
lgd * | number | |
pd * | number | |
correlation | object | |
maturity | number |
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).
| Parameter | Type | Description |
|---|---|---|
ead * | number | |
pd * | number | |
lgd | number | |
maturity | number | |
seniority | string |
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)``.
| Parameter | Type | Description |
|---|---|---|
asset_value * | number | |
asset_volatility * | number | |
debt_face_value * | number | |
asset_drift | object | |
horizon | number | |
risk_free_rate | number |
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.
| Parameter | Type | Description |
|---|---|---|
defaults * | object | |
features * | object | |
max_iter | integer | |
ridge | number | |
tol | number |
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]``.
| Parameter | Type | Description |
|---|---|---|
exposure_amounts * | object | |
recovery_amounts * | object | |
workout_cost_rate | number |
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.
| Parameter | Type | Description |
|---|---|---|
defaults * | object | |
raw_scores * | object | |
max_iter | integer | |
tol | number |
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.
| Parameter | Type | Description |
|---|---|---|
base_ecl * | number | |
macro_factors * | object | |
sensitivities * | object | |
management_overlay | number |
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
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``.
| Parameter | Type | Description |
|---|---|---|
macro_index * | number | |
ttc_pd * | number | |
sensitivity | number |
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``.
| Parameter | Type | Description |
|---|---|---|
initial_value * | number | |
time_steps * | object | |
volatility * | number | |
drift | number | |
n_paths | integer | |
quantile | number | |
seed | integer |
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).
| Parameter | Type | Description |
|---|---|---|
n_defaults * | object | |
n_obligors * | object | |
floor | number |
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.
| Parameter | Type | Description |
|---|---|---|
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).
| Parameter | Type | Description |
|---|---|---|
exposure_amounts * | object | |
recovery_amounts * | object | |
discount_factors | object |
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)``.
| Parameter | Type | Description |
|---|---|---|
base_points * | number | |
feature_values * | object | |
points_per_feature * | object | |
base_odds | number | |
base_score | number | |
pdo | number |
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).
| Parameter | Type | Description |
|---|---|---|
sector_defaults * | object | |
sector_obligors * | object | |
sector_names | object |
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.
| Parameter | Type | Description |
|---|---|---|
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).
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
add_on_aggregate * | number | |
collateral * | number | |
mark_to_market * | number | |
alpha | number |
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)``.
| Parameter | Type | Description |
|---|---|---|
long_run_average_pd * | number | |
pit_pd * | number | |
cyclicality | number |
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`.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
base_cva * | number | |
correlation * | number | |
exposure_volatility | number |
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.
| Parameter | Type | Description |
|---|---|---|
cva * | number | |
dva | number | |
fva | number | |
kva | number | |
mva | number |
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…
| Parameter | Type | Description |
|---|---|---|
rate * | number | |
sigma * | number | |
spot * | number | |
strike * | number | |
tau * | number | |
div_yield | number | |
greeks | boolean | |
n_simulations | integer | |
n_steps | integer | |
option_type | string | |
seed | integer |
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.
| Parameter | Type | Description |
|---|---|---|
rate * | number | |
sigma * | number | |
spot * | number | |
strike * | number | |
tau * | number | |
average_type | string | |
div_yield | number | |
greeks | boolean | |
n_simulations | integer | |
n_steps | integer | |
option_type | string | |
qmc | boolean | |
seed | integer |
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…
| Parameter | Type | Description |
|---|---|---|
bond_price * | number | |
cashflows * | object | |
swap_rates * | object | |
times * | object | |
face_value | number | |
frequency | integer | |
use_market_price | boolean |
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…
| Parameter | Type | Description |
|---|---|---|
barrier * | number | |
rate * | number | |
sigma * | number | |
spot * | number | |
strike * | number | |
tau * | number | |
barrier_type | string | |
div_yield | number | |
option_type | string | |
rebate | number |
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.
| Parameter | Type | Description |
|---|---|---|
correlation * | object | |
rate * | number | |
sigmas * | object | |
spots * | object | |
strike * | number | |
tau * | number | |
weights * | object | |
greeks | boolean | |
n_simulations | integer | |
option_type | string | |
seed | integer |
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.
| Parameter | Type | Description |
|---|---|---|
rate * | number | |
sigma * | number | |
spot * | number | |
strike * | number | |
tau * | number | |
div_yield | number | |
exercise_dates | integer | |
greeks | boolean | |
n_simulations | integer | |
n_steps | integer | |
option_type | string | |
seed | integer |
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.
| Parameter | Type | Description |
|---|---|---|
rate * | number | |
sigma * | number | |
spot * | number | |
strike * | number | |
tau * | number | |
div_yield | number | |
n_steps | integer | |
option_type | string | |
style | string |
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.
| Parameter | Type | Description |
|---|---|---|
rate * | number | |
sigma * | number | |
spot * | number | |
strike * | number | |
tau * | number | |
div_yield | number | |
option_type | string |
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.
| Parameter | Type | Description |
|---|---|---|
rate * | number | |
sigma * | number | |
spot * | number | |
strike * | number | |
tau * | number | |
div_yield | number | |
option_type | string |
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.
| Parameter | Type | Description |
|---|---|---|
coupon_rate * | number | |
face_value * | number | |
maturity * | number | |
yield_rate * | number | |
frequency | integer |
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.
| Parameter | Type | Description |
|---|---|---|
discount_rates * | object | |
face_value * | number | |
maturity * | number | |
reference_rates * | object | |
spread * | number | |
frequency | integer |
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.
| Parameter | Type | Description |
|---|---|---|
maturities * | object | |
par_rates * | object | |
face_value | number | |
frequency | integer |
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.
| Parameter | Type | Description |
|---|---|---|
call_price * | number | |
coupon_rate * | number | |
face_value * | number | |
maturity * | number | |
rate_vol * | number | |
short_rate * | number | |
frequency | integer |
cap_floor_pricer
Price an interest-rate cap/floor as a strip of caplets/floorlets.
| Parameter | Type | Description |
|---|---|---|
accruals * | object | |
discount_factors * | object | |
expiries * | object | |
forward_rates * | object | |
notional * | number | |
strike * | number | |
vols * | object | |
option_type | string |
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).
| Parameter | Type | Description |
|---|---|---|
accrual * | number | |
discount_factor * | number | |
expiry * | number | |
forward_rate * | number | |
notional * | number | |
strike * | number | |
vol * | number | |
option_type | string |
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.
| Parameter | Type | Description |
|---|---|---|
rate * | number | |
sigma * | number | |
spot * | number | |
strike * | number | |
tau_choose * | number | |
tau_expiry * | number | |
div_yield | number |
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.
| Parameter | Type | Description |
|---|---|---|
rate * | number | |
sigma * | number | |
spot * | number | |
strike_compound * | number | |
strike_underlying * | number | |
tau_compound * | number | |
tau_underlying * | number | |
compound_type | string | |
div_yield | number | |
greeks | boolean | |
n_simulations | integer | |
seed | integer |
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.
| Parameter | Type | Description |
|---|---|---|
conversion_ratio * | number | |
coupon_rate * | number | |
face_value * | number | |
maturity * | number | |
stock_price * | number | |
yield_rate * | number | |
frequency | integer |
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``.
| Parameter | Type | Description |
|---|---|---|
cashflows * | object | |
times * | object | |
yield_rate * | number | |
frequency | integer |
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``.
| Parameter | Type | Description |
|---|---|---|
kappa * | number | |
maturity * | number | |
r0 * | number | |
sigma * | number | |
theta * | number | |
n_simulations | integer | |
n_steps | integer | |
seed | integer |
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…
| Parameter | Type | Description |
|---|---|---|
discount_rate * | number | |
hazard_rate * | number | |
maturity * | number | |
notional * | number | |
recovery_rate * | number | |
spread * | number | |
frequency | integer |
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.
| Parameter | Type | Description |
|---|---|---|
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_domestic | boolean |
digital_option_pricer
Cash-or-nothing digital (binary) option price. ``Call = payout · e^{-rτ} N(d2)``, ``Put = payout · e^{-rτ} N(-d2)``.
| Parameter | Type | Description |
|---|---|---|
rate * | number | |
sigma * | number | |
spot * | number | |
strike * | number | |
tau * | number | |
div_yield | number | |
option_type | string | |
payout | number |
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``.
| Parameter | Type | Description |
|---|---|---|
displacement * | number | |
rate * | number | |
sigma * | number | |
spot * | number | |
strike * | number | |
tau * | number | |
div_yield | number | |
option_type | string |
duration_macaulay
Macaulay duration — PV-weighted average time to cashflows (in years).
| Parameter | Type | Description |
|---|---|---|
cashflows * | object | |
times * | object | |
yield_rate * | number | |
frequency | integer |
dv01_pvbp
DV01 / PVBP — price change for a 1 basis-point yield move. Computed by central difference of the price function at ±0.5bp.
| Parameter | Type | Description |
|---|---|---|
cashflows * | object | |
times * | object | |
yield_rate * | number | |
frequency | integer |
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
accrual * | number | |
discount_factor * | number | |
equity_return * | number | |
funding_rate * | number | |
notional * | number | |
receive_equity | boolean |
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.
| Parameter | Type | Description |
|---|---|---|
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·τ}``.
| Parameter | Type | Description |
|---|---|---|
rate_domestic * | number | |
rate_foreign * | number | |
spot * | number | |
tau * | number | |
contracted_forward | object | |
notional | number |
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 τ}``.
| Parameter | Type | Description |
|---|---|---|
rate_domestic * | number | |
rate_foreign * | number | |
sigma * | number | |
spot * | number | |
strike * | number | |
tau * | number | |
notional | number | |
option_type | string |
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)``.
| Parameter | Type | Description |
|---|---|---|
kappa * | number | |
rate * | number | |
rho * | number | |
sigma * | number | |
spot * | number | |
strike * | number | |
tau * | number | |
theta * | number | |
v0 * | number | |
option_type | string |
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.
| Parameter | Type | Description |
|---|---|---|
kappa * | number | |
maturity * | number | |
r0 * | number | |
sigma * | number | |
n_simulations | integer | |
n_steps | integer | |
seed | integer | |
theta_const | number |
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).
| Parameter | Type | Description |
|---|---|---|
face_value * | number | |
inflation_rate * | number | |
maturity * | number | |
real_coupon_rate * | number | |
real_yield * | number | |
frequency | integer |
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.
| Parameter | Type | Description |
|---|---|---|
accruals * | object | |
discount_factors * | object | |
fixed_rate * | number | |
forward_rates * | object | |
notional * | number | |
pay_fixed | boolean |
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 ``…
| Parameter | Type | Description |
|---|---|---|
forward_rates * | object | |
horizon * | number | |
tenor * | number | |
vols * | object | |
n_simulations | integer | |
n_steps | integer | |
seed | integer |
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…
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
rate * | number | |
sigma * | number | |
spot * | number | |
strike * | number | |
tau * | number | |
div_yield | number | |
greeks | boolean | |
n_simulations | integer | |
n_steps | integer | |
option_type | string | |
qmc | boolean | |
seed | integer | |
strike_type | string |
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``.
| Parameter | Type | Description |
|---|---|---|
cashflows * | object | |
times * | object | |
yield_rate * | number | |
frequency | integer |
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.
| Parameter | Type | Description |
|---|---|---|
rate * | number | |
sigma * | number | |
spot * | number | |
strike * | number | |
tau * | number | |
div_yield | number | |
n_simulations | integer | |
option_type | string | |
seed | integer |
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.
| Parameter | Type | Description |
|---|---|---|
maturities * | object | |
yields * | object | |
tau_init | number |
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.
| Parameter | Type | Description |
|---|---|---|
maturities * | object | |
yields * | object | |
tau1_init | number | |
tau2_init | number |
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.
| Parameter | Type | Description |
|---|---|---|
rate * | number | |
spot * | number | |
strike * | number | |
tau * | number | |
alpha | number | |
beta | number | |
delta | number | |
greeks | boolean | |
n_simulations | integer | |
option_type | string | |
seed | integer |
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.
| Parameter | Type | Description |
|---|---|---|
call_price * | number | |
coupon_rate * | number | |
face_value * | number | |
market_price * | number | |
maturity * | number | |
rate_vol * | number | |
short_rate * | number | |
frequency | integer |
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).
| Parameter | Type | Description |
|---|---|---|
maturities * | object | |
ois_rates * | object | |
frequency | integer |
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.
| Parameter | Type | Description |
|---|---|---|
accrual * | number | |
compounded_rate * | number | |
discount_factor * | number | |
fixed_rate * | number | |
notional * | number | |
pay_fixed | boolean |
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.
| Parameter | Type | Description |
|---|---|---|
coupon_rate * | number | |
face_value * | number | |
maturity * | number | |
put_price * | number | |
rate_vol * | number | |
short_rate * | number | |
frequency | integer |
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.
| Parameter | Type | Description |
|---|---|---|
correlation * | object | |
rate * | number | |
sigmas * | object | |
spots * | object | |
strike * | number | |
tau * | number | |
greeks | boolean | |
n_simulations | integer | |
option_type | string | |
rainbow_type | string | |
seed | integer |
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…
| Parameter | Type | Description |
|---|---|---|
rate * | number | |
spot * | number | |
strike * | number | |
tau * | number | |
control_variate | boolean | |
eta | number | |
greeks | boolean | |
hurst | number | |
n_simulations | integer | |
n_steps | integer | |
option_type | string | |
rho | number | |
seed | integer | |
xi | number |
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
rate * | number | |
rho * | number | |
sigma1 * | number | |
sigma2 * | number | |
spot1 * | number | |
spot2 * | number | |
strike * | number | |
tau * | number | |
option_type | string |
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.
| Parameter | Type | Description |
|---|---|---|
discount_factors * | object | |
maturities * | object | |
frequency | integer |
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.
| Parameter | Type | Description |
|---|---|---|
annuity * | number | |
expiry * | number | |
forward_swap_rate * | number | |
notional * | number | |
strike * | number | |
vol * | number | |
option_type | string |
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.
| Parameter | Type | Description |
|---|---|---|
alpha * | number | |
annuity * | number | |
beta * | number | |
expiry * | number | |
forward_swap_rate * | number | |
notional * | number | |
nu * | number | |
rho * | number | |
strike * | number | |
option_type | string |
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``.
| Parameter | Type | Description |
|---|---|---|
accrual * | number | |
asset_return * | number | |
discount_factor * | number | |
financing_rate * | number | |
notional * | number | |
receive_total_return | boolean |
trinomial_tree_option_pricer
Boyle trinomial tree option price. Up/middle/down branching converges to Black-Scholes for European options. Handles American exercise.
| Parameter | Type | Description |
|---|---|---|
rate * | number | |
sigma * | number | |
spot * | number | |
strike * | number | |
tau * | number | |
div_yield | number | |
n_steps | integer | |
option_type | string | |
style | string |
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.
| Parameter | Type | Description |
|---|---|---|
rate * | number | |
spot * | number | |
strike * | number | |
tau * | number | |
greeks | boolean | |
n_simulations | integer | |
nu | number | |
option_type | string | |
seed | integer | |
sigma | number | |
theta | number |
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).
| Parameter | Type | Description |
|---|---|---|
kappa * | number | |
maturity * | number | |
r0 * | number | |
sigma * | number | |
theta * | number | |
n_simulations | integer | |
n_steps | integer | |
seed | integer |
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.
| Parameter | Type | Description |
|---|---|---|
call_date * | number | |
call_price * | number | |
coupon_rate * | number | |
face_value * | number | |
price * | number | |
frequency | integer |
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`.
| Parameter | Type | Description |
|---|---|---|
cashflows * | object | |
price * | number | |
times * | object | |
frequency | integer |
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``.
| Parameter | Type | Description |
|---|---|---|
cashflows * | object | |
price * | number | |
times * | object | |
zero_rates * | object | |
frequency | integer |
zero_coupon_bond_pricer
Price a zero-coupon bond: ``face / (1 + y/m)^{m·T}``.
| Parameter | Type | Description |
|---|---|---|
face_value * | number | |
maturity * | number | |
yield_rate * | number | |
frequency | integer |
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.
| Parameter | Type | Description |
|---|---|---|
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%).
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
bucket_inflows * | object | |
bucket_outflows * | object | |
buckets | object | |
opening_balance | number |
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.
| Parameter | Type | Description |
|---|---|---|
daily_inflows * | object | |
daily_outflows * | object | |
opening_balance | number |
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
collateral_values * | object | |
haircuts * | object | |
already_pledged | object |
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…
| Parameter | Type | Description |
|---|---|---|
hqla_by_level * | object | |
market_haircuts * | object | |
retail_deposits * | number | |
wholesale_funding * | number | |
inflows | number | |
retail_deposits_by_category | object | |
retail_runoff | number | |
retail_runoff_rates | object | |
wholesale_runoff | number |
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
commitment_amounts * | object | |
draw_probabilities * | object | |
ccf | object |
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.
| Parameter | Type | Description |
|---|---|---|
fx_rate * | number | |
shortfall_amount * | number | |
shortfall_ccy * | string | |
surplus_amount * | number | |
surplus_ccy * | string | |
swap_haircut | number |
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.
| Parameter | Type | Description |
|---|---|---|
deposit_features * | object | |
stable_threshold | number |
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).
| Parameter | Type | Description |
|---|---|---|
indicators * | object | |
thresholds * | object | |
directions | object |
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.
| Parameter | Type | Description |
|---|---|---|
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).
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
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).
| Parameter | Type | Description |
|---|---|---|
asset_values * | object | |
haircuts | object |
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).
| Parameter | Type | Description |
|---|---|---|
asset_values * | object | |
haircut | number |
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).
| Parameter | Type | Description |
|---|---|---|
asset_values * | object | |
haircut | number |
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.
| Parameter | Type | Description |
|---|---|---|
hqla * | number | |
retail_deposits * | number | |
wholesale_funding * | number | |
retail_runoff | number | |
wholesale_runoff | number |
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.
| Parameter | Type | Description |
|---|---|---|
counterbalancing_capacity * | number | |
stressed_net_outflow * | number | |
survival_days * | number | |
minimum_survival_days | number |
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
net_flows * | object | |
opening_balance * | number | |
delay_factor | number | |
inflow_delay_shock | number |
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
stressed_net_outflows * | object | |
confidence_buffer | number |
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.
| Parameter | Type | Description |
|---|---|---|
gross_inflows * | number | |
gross_outflows * | number | |
hqla * | number | |
inflow_cap | number |
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.
| Parameter | Type | Description |
|---|---|---|
asset_maturities * | object | |
liability_maturities * | object | |
buckets | object |
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.
| Parameter | Type | Description |
|---|---|---|
amber_threshold * | number | |
green_threshold * | number | |
metric_value * | number | |
higher_is_better | boolean |
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
balances * | object | |
hqla * | number | |
runoff_rates * | object | |
inflows | number |
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.
| Parameter | Type | Description |
|---|---|---|
base_rate * | number | |
liquidity_spread * | number | |
notional * | number | |
tenor_years * | number | |
contingent_spread | number |
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…
| Parameter | Type | Description |
|---|---|---|
base_outflow * | number | |
outflow_vol * | number | |
confidence_level | number | |
n_simulations | integer | |
seed | object |
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
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%).
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
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).
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
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).
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
rate * | number | |
sigma * | number | |
spot * | number | |
strike * | number | |
tau * | number | |
div_yield | number | |
option_type | string |
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
breaches * | object | |
confidence_level | number |
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.
| Parameter | Type | Description |
|---|---|---|
cov_matrix * | object | |
portfolio_value * | number | |
weights * | object | |
confidence_level | number |
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
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
sorted_losses * | object | |
percentiles | object |
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).
| Parameter | Type | Description |
|---|---|---|
returns * | object | |
confidence_level | number | |
window | integer |
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.
| Parameter | Type | Description |
|---|---|---|
portfolio_value * | number | |
returns * | object | |
confidence_level | number |
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.
| Parameter | Type | Description |
|---|---|---|
contagion_matrix * | object | |
initial_shock * | object | |
rounds | integer |
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.
| Parameter | Type | Description |
|---|---|---|
portfolio_value * | number | |
returns * | object | |
confidence_level | number | |
excess_kurtosis | object | |
skewness | object |
correlation_matrix_historical
Historical (Pearson) correlation matrix of asset returns.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
cs01_sensitivities * | object | |
spread_moves_bp * | object | |
name_labels | object |
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.
| Parameter | Type | Description |
|---|---|---|
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).
| Parameter | Type | Description |
|---|---|---|
cov_matrix * | object | |
portfolio_value * | number | |
weights * | object | |
confidence_level | number |
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̄.
| Parameter | Type | Description |
|---|---|---|
returns_matrix * | object | |
a | number | |
b | number |
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.
| Parameter | Type | Description |
|---|---|---|
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``).
| Parameter | Type | Description |
|---|---|---|
returns * | object | |
alpha | number | |
beta | number | |
gamma | number | |
omega | number |
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.
| Parameter | Type | Description |
|---|---|---|
portfolio_value * | number | |
returns * | object | |
confidence_levels | array |
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).
| Parameter | Type | Description |
|---|---|---|
asset_returns * | object | |
portfolio_value * | number | |
weights * | object | |
confidence_level | number |
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.
| Parameter | Type | Description |
|---|---|---|
returns * | object | |
confidence_level | number | |
threshold_quantile | number |
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.
| Parameter | Type | Description |
|---|---|---|
portfolio_value * | number | |
returns * | object | |
confidence_level | number | |
lambda_decay | number |
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``.
| Parameter | Type | Description |
|---|---|---|
imcc * | number | |
ses * | number | |
default_risk_charge | number |
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.
| Parameter | Type | Description |
|---|---|---|
returns * | object | |
confidence_level | number |
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.
| Parameter | Type | Description |
|---|---|---|
individual_ses * | object | |
rho | number |
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.
| Parameter | Type | Description |
|---|---|---|
returns * | object | |
confidence_level | number | |
window | integer |
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.
| Parameter | Type | Description |
|---|---|---|
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).
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
fx_deltas * | object | |
fx_moves * | object | |
currency_names | object |
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``.
| Parameter | Type | Description |
|---|---|---|
own_gammas * | object | |
cross_gammas | object |
gamma_pnl_attribution
Gamma (convexity) P&L component: ``½ · Γ · dS²``.
| Parameter | Type | Description |
|---|---|---|
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)``.
| Parameter | Type | Description |
|---|---|---|
returns * | object | |
alpha | number | |
beta | number | |
horizon | integer | |
omega | object |
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)``.
| Parameter | Type | Description |
|---|---|---|
returns * | object | |
alpha | number | |
beta | number | |
gamma | number | |
omega | object |
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
portfolio_value * | number | |
returns * | object | |
confidence_level | number |
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
portfolio_value * | number | |
returns * | object | |
confidence_level | number |
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.
| Parameter | Type | Description |
|---|---|---|
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)``.
| Parameter | Type | Description |
|---|---|---|
cov_matrix * | object | |
portfolio_value * | number | |
position_index * | integer | |
weights * | object | |
confidence_level | number |
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``.
| Parameter | Type | Description |
|---|---|---|
n_breaches * | integer | |
n_observations * | integer | |
confidence_level | number |
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.
| Parameter | Type | Description |
|---|---|---|
es_base * | number | |
liquidity_horizons * | array | |
partial_es * | array | |
base_horizon | number |
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.
| Parameter | Type | Description |
|---|---|---|
factor_cov * | object | |
n_scenarios | integer | |
seed | object |
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``.
| Parameter | Type | Description |
|---|---|---|
cov_matrix * | object | |
weights * | object | |
confidence_level | number |
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.
| Parameter | Type | Description |
|---|---|---|
portfolio_value * | number | |
returns * | object | |
confidence_level | number | |
horizon_days | integer | |
n_simulations | integer | |
seed | object |
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.
| Parameter | Type | Description |
|---|---|---|
cov_matrix * | object | |
portfolio_value * | number | |
weights * | object | |
confidence_level | number | |
horizon_days | integer |
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
deltas * | object | |
quantities * | object | |
spot_prices | object |
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.
| Parameter | Type | Description |
|---|---|---|
key_rate_sensitivities * | object | |
yield_moves_bp * | object | |
tenor_names | object |
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)``.
| Parameter | Type | Description |
|---|---|---|
returns * | object | |
annualisation_factor | integer |
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).
| Parameter | Type | Description |
|---|---|---|
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)``.
| Parameter | Type | Description |
|---|---|---|
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)``.
| Parameter | Type | Description |
|---|---|---|
rate * | number | |
sigma * | number | |
spot * | number | |
strike * | number | |
tau * | number | |
div_yield | number | |
option_type | string |
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).
| Parameter | Type | Description |
|---|---|---|
returns_matrix * | object | |
n_components | object |
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.
| Parameter | Type | Description |
|---|---|---|
returns * | object | |
confidence_level | number | |
window | integer |
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).
| Parameter | Type | Description |
|---|---|---|
sector_exposures * | object | |
sector_shocks * | object | |
sector_names | object |
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".
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
returns * | object | |
risk_aversion | number |
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.
| Parameter | Type | Description |
|---|---|---|
portfolio_value * | number | |
returns * | object | |
stress_end * | integer | |
stress_start * | integer | |
confidence_level | number |
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.
| Parameter | Type | Description |
|---|---|---|
theta * | number | |
time_step * | number | |
funding_cost | number |
theta_time_decay
Black-Scholes Theta — calendar time decay (∂V/∂calendar = −∂V/∂τ), per year.
| Parameter | Type | Description |
|---|---|---|
rate * | number | |
sigma * | number | |
spot * | number | |
strike * | number | |
tau * | number | |
div_yield | number | |
option_type | string |
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.
| Parameter | Type | Description |
|---|---|---|
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).
| Parameter | Type | Description |
|---|---|---|
rate * | number | |
sigma * | number | |
spot * | number | |
strike * | number | |
tau * | number | |
div_yield | number |
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
factor_cov * | object | |
factor_exposures * | object | |
portfolio_value * | number | |
confidence_level | number | |
factor_names | object |
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.
| Parameter | Type | Description |
|---|---|---|
portfolio_value * | number | |
returns * | object | |
confidence_levels | array | |
horizon_days | integer |
vega_pnl_attribution
Vega P&L component: ``ν · dσ``.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
expiries * | object | |
market_prices * | object | |
rate * | number | |
spot * | number | |
strikes * | object | |
option_type | string |
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.
| Parameter | Type | Description |
|---|---|---|
rate * | number | |
sigma * | number | |
spot * | number | |
strike * | number | |
tau * | number | |
div_yield | number |
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.…
| Parameter | Type | Description |
|---|---|---|
annual_event_counts * | object | |
loss_amounts * | object | |
confidence_level | number | |
expected_loss_covered | boolean | |
n_years | integer | |
seed | object |
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
business_indicator * | number | |
loss_component | number | |
use_ilm | boolean |
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…
| Parameter | Type | Description |
|---|---|---|
bcp_maturity * | number | |
max_tolerable_downtime * | number | |
rpo_hours * | number | |
rto_hours * | number | |
rpo_target_hours | object |
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.
| Parameter | Type | Description |
|---|---|---|
factor_scores * | object | |
baseline | number | |
sensitivity | number |
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.
| Parameter | Type | Description |
|---|---|---|
frequency_lambda * | number | |
severity_mu * | number | |
severity_sigma * | number | |
n_years | integer | |
seed | object |
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
breach_probability * | number | |
cost_per_record * | number | |
records_exposed * | number | |
business_interruption_cost | number |
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.
| Parameter | Type | Description |
|---|---|---|
standalone_capitals * | object | |
correlation | number |
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
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).
| Parameter | Type | Description |
|---|---|---|
deductible * | number | |
gross_loss * | number | |
policy_limit * | number | |
haircut | number |
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`.
| Parameter | Type | Description |
|---|---|---|
control_scores * | object | |
baseline | number | |
sensitivity | number |
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
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).
| Parameter | Type | Description |
|---|---|---|
amber_threshold * | number | |
red_threshold * | number | |
value * | number | |
direction | string |
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``.
| Parameter | Type | Description |
|---|---|---|
observations * | object | |
higher_is_worse | boolean |
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
annual_event_counts * | object | |
loss_amounts * | object | |
confidence_level | number | |
n_years | integer | |
seed | object |
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
frequency_lambda * | number | |
severity_mu * | number | |
severity_sigma * | number | |
confidence_level | number | |
n_years | integer | |
seed | object |
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
annual_losses * | object | |
confidence_level | number |
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
expected_loss * | number | |
opvar * | number | |
diversification_benefit | number | |
insurance_offset | number |
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.
| Parameter | Type | Description |
|---|---|---|
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)``.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
design_score * | number | |
operating_score * | number | |
design_weight | number |
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
requirements_met * | object | |
weights | object |
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.
| Parameter | Type | Description |
|---|---|---|
appetite_limit * | number | |
current_metric * | number | |
tolerance_limit * | number | |
higher_is_worse | boolean |
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
frequency_lambda * | number | |
severity_mu * | number | |
severity_sigma * | number | |
confidence_level | number | |
n_years | integer | |
seed | object |
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.
| Parameter | Type | Description |
|---|---|---|
expert_estimates * | object | |
expert_weights | object |
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.
| Parameter | Type | Description |
|---|---|---|
expected_events_per_year * | number | |
observation_years | object | |
occurrences | object |
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.
| Parameter | Type | Description |
|---|---|---|
typical_loss * | number | |
worst_case_loss * | number | |
worst_case_percentile | number |
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…
| Parameter | Type | Description |
|---|---|---|
loss_amounts * | object | |
distribution | string |
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.
| Parameter | Type | Description |
|---|---|---|
annual_losses * | object | |
severity_multiplier | number | |
tail_confidence | number |
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).
| Parameter | Type | Description |
|---|---|---|
concentration * | number | |
criticality * | integer | |
financial_health * | number | |
substitutability * | number |
average_drawdown
Average drawdown — mean of the drawdown series magnitude.
| Parameter | Type | Description |
|---|---|---|
returns * | object | |
is_equity_curve | boolean |
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.
| Parameter | Type | Description |
|---|---|---|
cov_matrix * | object | |
market_weights * | object | |
p_matrix * | object | |
q_views * | object | |
omega | object | |
risk_aversion | number | |
tau | number |
calmar_ratio
Calmar ratio — annualised return over maximum drawdown.
| Parameter | Type | Description |
|---|---|---|
returns * | object | |
periods_per_year | integer |
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`…
| Parameter | Type | Description |
|---|---|---|
carbon_intensities * | object | |
portfolio_value * | number | |
weights * | object | |
asset_names | object | |
company_total_emissions | object | |
company_value | object |
carhart_4_factor_model
Carhart 4-factor regression (MKT, SMB, HML, MOM). Extends Fama-French 3-factor with the momentum (WML/MOM) factor.
| Parameter | Type | Description |
|---|---|---|
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``.
| Parameter | Type | Description |
|---|---|---|
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).
| Parameter | Type | Description |
|---|---|---|
returns * | object | |
confidence_level | number | |
is_equity_curve | boolean |
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…
| Parameter | Type | Description |
|---|---|---|
returns_matrix * | object | |
n_clusters | integer |
correlation_matrix_portfolio
Correlation matrix and average pairwise correlation of asset returns.
| Parameter | Type | Description |
|---|---|---|
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…
| Parameter | Type | Description |
|---|---|---|
fx_returns * | object | |
local_returns * | object | |
weights * | object | |
base_risk_free | object | |
currency_names | object | |
local_risk_free | object |
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 <…
| Parameter | Type | Description |
|---|---|---|
scenario_returns * | object | |
confidence_level | number | |
cvar_limit | number | |
mean_returns | object | |
periods_per_year | integer |
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).
| Parameter | Type | Description |
|---|---|---|
cov_matrix * | object | |
weights * | object |
drawdown_duration
Drawdown duration — longest and current underwater run lengths. Counts consecutive periods spent below the prior peak.
| Parameter | Type | Description |
|---|---|---|
returns * | object | |
is_equity_curve | boolean |
equal_weight_portfolio
Equal-weight (1/N) portfolio.
| Parameter | Type | Description |
|---|---|---|
n_assets * | integer | |
cov_matrix | object | |
mean_returns | object | |
periods_per_year | integer | |
risk_free | number |
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.
| Parameter | Type | Description |
|---|---|---|
esg_scores * | object | |
weights * | object | |
cov_matrix | object | |
min_esg_score | object |
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.
| Parameter | Type | Description |
|---|---|---|
factor_cov * | object | |
factor_exposures * | object | |
specific_var * | object | |
periods_per_year | integer | |
target_exposures | object |
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.
| Parameter | Type | Description |
|---|---|---|
asset_exposures * | object | |
weights * | object | |
factor_names | object |
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.
| Parameter | Type | Description |
|---|---|---|
factor_exposures * | object | |
factor_returns * | object | |
specific_return * | number | |
factor_names | object |
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
sector_codes * | array | |
weights * | object |
information_ratio
Information ratio — active return over tracking error.
| Parameter | Type | Description |
|---|---|---|
benchmark_returns * | object | |
returns * | object | |
periods_per_year | integer |
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``.
| Parameter | Type | Description |
|---|---|---|
benchmark_returns * | object | |
returns * | object | |
periods_per_year | integer | |
risk_free | number |
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.
| Parameter | Type | Description |
|---|---|---|
bid_ask_spreads * | object | |
cov_matrix * | object | |
portfolio_value * | number | |
weights * | object | |
confidence_level | number | |
horizon_days | integer |
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).
| Parameter | Type | Description |
|---|---|---|
cov_matrix * | object | |
weights * | object |
maximum_drawdown
Maximum drawdown — largest peak-to-trough decline.
| Parameter | Type | Description |
|---|---|---|
returns * | object | |
is_equity_curve | boolean |
maximum_sharpe_ratio_portfolio
Maximum Sharpe ratio (tangency) portfolio. Maximises the annualised Sharpe ratio subject to weights summing to 1.
| Parameter | Type | Description |
|---|---|---|
cov_matrix * | object | |
mean_returns * | object | |
allow_short | boolean | |
periods_per_year | integer | |
risk_free | number |
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.
| Parameter | Type | Description |
|---|---|---|
cov_matrix * | object | |
mean_returns * | object | |
allow_short | boolean | |
periods_per_year | integer | |
risk_aversion | number | |
risk_free | number |
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.
| Parameter | Type | Description |
|---|---|---|
cov_matrix * | object | |
allow_short | boolean | |
mean_returns | object | |
periods_per_year | integer | |
risk_free | number |
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.
| Parameter | Type | Description |
|---|---|---|
cov_matrix * | object | |
mean_returns * | object | |
weights * | object | |
confidence_level | number | |
horizon | integer | |
n_simulations | integer | |
portfolio_value | number | |
seed | integer |
omega_ratio
Omega ratio — probability-weighted gains over losses about a threshold. ``Omega = sum(max(r - threshold, 0)) / sum(max(threshold - r, 0))``.
| Parameter | Type | Description |
|---|---|---|
returns * | object | |
threshold | number |
portfolio_beta
Portfolio beta — sensitivity of portfolio returns to the benchmark. ``beta = cov(r, b) / var(b)``.
| Parameter | Type | Description |
|---|---|---|
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).
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
returns_matrix * | object | |
n_components | object |
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…
| Parameter | Type | Description |
|---|---|---|
cost_bps * | object | |
current_weights * | object | |
target_weights * | object | |
asset_volatility | object | |
no_trade_band | number | |
risk_aversion | object |
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.
| Parameter | Type | Description |
|---|---|---|
returns * | object | |
n_iter | integer |
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).
| Parameter | Type | Description |
|---|---|---|
cov_matrix * | object | |
mean_returns * | object | |
n_obs | integer | |
n_resamples | integer | |
seed | integer |
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.
| Parameter | Type | Description |
|---|---|---|
benchmark_returns * | object | |
returns * | object | |
periods_per_year | integer |
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.
| Parameter | Type | Description |
|---|---|---|
benchmark_returns * | object | |
benchmark_weights * | object | |
portfolio_returns * | object | |
portfolio_weights * | object | |
segment_names | object |
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.
| Parameter | Type | Description |
|---|---|---|
cov_matrix * | object | |
mean_returns | object | |
periods_per_year | integer | |
risk_free | number |
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.
| Parameter | Type | Description |
|---|---|---|
cov_matrix * | object | |
mean_returns * | object | |
periods_per_year | integer | |
risk_aversion | number | |
uncertainty | number |
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.
| Parameter | Type | Description |
|---|---|---|
benchmark_returns * | object | |
benchmark_weights * | object | |
portfolio_returns * | object | |
portfolio_weights * | object | |
sector_names | object |
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…
| Parameter | Type | Description |
|---|---|---|
returns * | object | |
ddof | integer | |
periods_per_year | integer | |
risk_free | number |
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.
| Parameter | Type | Description |
|---|---|---|
returns * | object | |
periods_per_year | integer | |
risk_free | number | |
target | number |
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.
| Parameter | Type | Description |
|---|---|---|
returns * | object | |
tail | number |
tracking_error
Tracking error — volatility of active (portfolio minus benchmark) return.
| Parameter | Type | Description |
|---|---|---|
benchmark_returns * | object | |
returns * | object | |
periods_per_year | integer |
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…
| Parameter | Type | Description |
|---|---|---|
benchmark_prices * | object | |
trade_prices * | object | |
trade_quantities * | object | |
cancellation_price | object | |
decision_price | object | |
side | integer | |
unexecuted_quantity | object |
treynor_ratio
Treynor ratio — annualised excess return per unit of systematic risk (beta).
| Parameter | Type | Description |
|---|---|---|
benchmark_returns * | object | |
returns * | object | |
periods_per_year | integer | |
risk_free | number |
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.
| Parameter | Type | Description |
|---|---|---|
returns * | object | |
is_equity_curve | boolean |
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.
| Parameter | Type | Description |
|---|---|---|
commitment_exposure * | number | |
gross_exposure * | number | |
net_asset_value * | number | |
var_pct | object |
basel_iii_cet1_ratio
Basel III Common Equity Tier 1 (CET1) ratio. ``CET1 ratio = CET1 capital / RWA``; minimum 4.5% (Basel III §50).
| Parameter | Type | Description |
|---|---|---|
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).
| Parameter | Type | Description |
|---|---|---|
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).
| Parameter | Type | Description |
|---|---|---|
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).
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
internal_model_rwa * | number | |
standardised_rwa * | number | |
floor_factor | number |
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.
| Parameter | Type | Description |
|---|---|---|
cet1_ratio * | number | |
risk_weighted_assets * | number | |
buffer_ratio | number |
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.
| Parameter | Type | Description |
|---|---|---|
capital_conservation_buffer_ratio | number | |
countercyclical_buffer_ratio | number | |
risk_weighted_assets | number | |
systemic_buffer_ratio | number |
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).
| Parameter | Type | Description |
|---|---|---|
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…
| Parameter | Type | Description |
|---|---|---|
exposure_value * | number | |
tier1_capital * | number | |
is_institution | boolean |
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…
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
initial_margin_rate * | number | |
portfolio_value * | number | |
variation_margin * | number | |
minimum_transfer_amount | number |
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
expected_shortfall * | number | |
multiplier * | number | |
stressed_es_ratio * | number | |
default_risk_charge | number | |
non_modellable_ses | number |
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).
| Parameter | Type | Description |
|---|---|---|
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).
| Parameter | Type | Description |
|---|---|---|
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).
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
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…
| Parameter | Type | Description |
|---|---|---|
benchmark_prices * | object | |
executed_prices * | object | |
quantities * | object | |
side | integer |
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.
| Parameter | Type | Description |
|---|---|---|
delayed_publication_threshold * | number | |
trade_size * | number | |
is_liquid | boolean |
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).
| Parameter | Type | Description |
|---|---|---|
instrument_type * | string | |
large_in_scale_threshold * | number | |
order_size * | number | |
is_liquid | boolean |
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).
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
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…
| Parameter | Type | Description |
|---|---|---|
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).
| Parameter | Type | Description |
|---|---|---|
correlation_matrix * | object | |
sub_module_charges * | object | |
sub_module_names | object |
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).
| Parameter | Type | Description |
|---|---|---|
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%).
| Parameter | Type | Description |
|---|---|---|
returns * | object | |
periods_per_year | integer |