Risk API¶
Value at Risk¶
classical_var
¶
Classical VaR and Expected Shortfall implementations.
Provides historical, parametric (Gaussian), and Monte Carlo Value-at-Risk (VaR) and Expected Shortfall (CVaR / ES).
References¶
Jorion, "Value at Risk", 3rd ed., McGraw-Hill (2006). McNeil, Frey, Embrechts, "Quantitative Risk Management", Princeton (2015).
VaRResult
dataclass
¶
historical_var(returns, confidence=0.95, portfolio_value=1.0)
¶
Historical simulation VaR and Expected Shortfall.
Uses the empirical distribution of past returns directly.
Parameters¶
returns : NDArray Historical portfolio returns, shape (T,) or (T, N) with weights summed. confidence : float Confidence level, e.g. 0.95 for 95% VaR. portfolio_value : float Portfolio notional for dollar VaR.
parametric_var(returns, confidence=0.95, portfolio_value=1.0)
¶
Parametric (Gaussian) VaR and Expected Shortfall.
Assumes returns are normally distributed.
Parameters¶
returns : NDArray Historical portfolio returns, shape (T,). confidence : float Confidence level. portfolio_value : float Portfolio notional.
monte_carlo_var(returns, confidence=0.95, n_simulations=100000, horizon=1, portfolio_value=1.0, seed=42)
¶
Monte Carlo VaR and Expected Shortfall.
Simulates future returns from a fitted multivariate normal.
Parameters¶
returns : NDArray Historical returns, shape (T,) for single asset or (T, N). confidence : float Confidence level. n_simulations : int Number of simulated scenarios. horizon : int Holding period in same units as returns. portfolio_value : float Portfolio notional. seed : int or None Random seed.
portfolio_var(returns, weights, confidence=0.95, method='historical', portfolio_value=1.0, **kwargs)
¶
Compute portfolio VaR given asset returns and weights.
Parameters¶
returns : NDArray Asset returns, shape (T, N). weights : NDArray Portfolio weights, shape (N,). confidence : float Confidence level. method : str One of "historical", "parametric", "monte_carlo". portfolio_value : float Portfolio notional.
Conditional VaR¶
cvar
¶
CVaR optimization (Barkoutsos et al., Quantum 4:256, 2020).
Implements CVaR as an objective function for VQE/QAOA, plus ascending CVaR scheduling (Kolotouros & Wallden, PRR 4.023225, 2022).
In variational quantum optimization, the standard objective is the expectation value E[C(x)] of the cost function. CVaR replaces this with the conditional expectation of the alpha-fraction worst outcomes:
CVaR_alpha = E[C(x) | C(x) >= VaR_alpha]
This biases the optimizer toward exploring low-energy (good) solutions, improving convergence on combinatorial optimization problems.
References¶
Barkoutsos, Nannicini, Robert, Tavernelli, Woerner, "Improving Variational Quantum Optimization using CVaR", Quantum 4:256 (2020), arXiv:1907.04769.
Kolotouros & Wallden, "Evolving objective function for improved variational quantum optimization", Physical Review Research 4:023225 (2022), arXiv:2105.11766.
CVaRObjective
dataclass
¶
CVaR objective function for variational optimization.
Parameters¶
alpha : float CVaR confidence parameter in (0, 1]. alpha=1.0 recovers standard expectation. alpha→0 focuses on the single best sample.
evaluate(costs, counts=None)
¶
Compute CVaR_alpha of the given cost samples.
Parameters¶
costs : NDArray Cost values for each measurement outcome, shape (M,). counts : NDArray or None Counts for each outcome (if from a histogram). If None, each cost is counted once.
Returns¶
float CVaR_alpha value (lower is better for minimization).
gradient_weight(costs)
¶
Compute per-sample weights for CVaR gradient estimation.
Returns weights that are 1/alpha for the alpha-fraction best samples and 0 otherwise. Used in parameter-shift gradient estimation.
AscendingCVaR
¶
Ascending CVaR schedule per Kolotouros & Wallden (2105.11766).
Starts with a small alpha (aggressive focus on tail) and gradually increases toward alpha=1 (full expectation) over the optimization.
This avoids the local minima traps of fixed-alpha CVaR while still benefiting from tail-focused exploration early on.
Parameters¶
alpha_start : float Initial alpha (small = aggressive). alpha_end : float Final alpha (1.0 = standard expectation). n_steps : int Total optimization steps. schedule : str Schedule type: "linear", "cosine", or "exponential".
cvar_from_samples(costs, alpha=0.05)
¶
Compute CVaR (Expected Shortfall) from cost samples.
This is the standard risk management CVaR: CVaR_alpha = E[X | X >= VaR_alpha] (for losses)
For portfolio optimization (minimization), we look at the alpha-fraction of LOWEST costs.
Parameters¶
costs : NDArray Sample costs/losses. alpha : float Tail fraction (0.05 = 5% worst cases).
Counterparty Risk¶
counterparty
¶
Counterparty credit risk.
Implements exposure-at-default models and CVA (Credit Valuation Adjustment) computations for OTC derivative counterparty risk.
Also provides stress scenario libraries for historical backtesting.
References¶
Gregory, "Counterparty Credit Risk and Credit Value Adjustment", 2nd ed., Wiley (2012).
Basel III, "The standardised approach for measuring counterparty credit risk exposures" (SA-CCR), BCBS 279 (2014).
CounterpartyExposure
dataclass
¶
Counterparty exposure profile.
Parameters¶
name : str Counterparty name/ID. notional : float Notional amount. pd : float Default probability (annual). lgd : float Loss given default (1 - recovery). exposure_profile : NDArray[np.float64] Expected exposure over time, shape (n_periods,).
compute_cva(exposure, risk_free_rate=0.03, n_periods=None)
¶
Compute unilateral CVA (Credit Valuation Adjustment).
CVA = LGD * sum_t [ DF(t) * EE(t) * PD(t-1, t) ]
where DF is the discount factor, EE is expected exposure, and PD(t-1, t) is the marginal default probability.
Parameters¶
exposure : CounterpartyExposure Counterparty exposure profile. risk_free_rate : float Risk-free discount rate. n_periods : int or None Number of periods. Uses length of exposure profile if None.
compute_ead_sa_ccr(notional, mtm, add_on_factor=0.01, collateral=0.0, alpha=1.4)
¶
Exposure at Default under SA-CCR (Basel III).
EAD = alpha * (RC + PFE)
where RC = max(V - C, 0) is replacement cost, and PFE = multiplier * add-on is potential future exposure.
Parameters¶
notional : float Trade notional. mtm : float Current mark-to-market value (positive = in the money). add_on_factor : float Supervisory add-on factor (depends on asset class). collateral : float Collateral held. alpha : float Supervisory scaling factor (1.4 per Basel III).
portfolio_cva(exposures, risk_free_rate=0.03)
¶
Compute CVA for a portfolio of counterparties.
Returns per-counterparty and total CVA.
Stress Testing¶
stress
¶
Stress testing scenarios: 1987 Black Monday, 2008 GFC, 2020 COVID, 2022 rates.
SCENARIO_LIBRARY = {(s.name): s for s in [BLACK_MONDAY_1987, GFC_2008, COVID_2020, RATES_2022]}
module-attribute
¶
StressScenario
dataclass
¶
A single stress scenario with market-factor shocks.
Parameters¶
name : str Human-readable label (e.g. "Black Monday 1987"). date : str Reference date or period (e.g. "1987-10-19"). equity_shock : float Equity market shock as a fraction (e.g. -0.226 for -22.6%). rates_shock : float Interest-rate shock in basis points (e.g. -50.0). vol_shock : float Implied-volatility shock as a fraction (e.g. 1.50 for +150%). spread_shock : float Credit-spread shock in basis points (e.g. 300.0). description : str Short narrative of the event.
apply_stress(portfolio_value, weights, scenario)
¶
Compute stressed P&L for a portfolio under a single scenario.
The weights array describes the portfolio's sensitivity to each risk factor in the following order:
[equity, rates, volatility, spreads]
Each weight represents the fraction of portfolio_value exposed to that factor. The stressed P&L for each factor is:
equity -> weight * portfolio_value * equity_shock
rates -> weight * portfolio_value * (rates_shock / 10_000)
vol -> weight * portfolio_value * vol_shock
spreads -> weight * portfolio_value * (-spread_shock / 10_000)
Spread widening is treated as a loss (negative P&L).
Parameters¶
portfolio_value : float
Total portfolio market value.
weights : array-like, shape (4,)
Sensitivity weights [equity, rates, vol, spreads].
scenario : StressScenario
The scenario to apply.
Returns¶
dict
scenario name, individual factor P&Ls, total_pnl, and
pct_loss (total P&L as a fraction of portfolio value).
stress_test_suite(portfolio_value, weights, scenarios=None)
¶
Run a suite of stress scenarios and return a summary.
Parameters¶
portfolio_value : float
Total portfolio market value.
weights : array-like, shape (4,)
Sensitivity weights [equity, rates, vol, spreads].
scenarios : sequence of StressScenario, optional
Scenarios to run. Defaults to all entries in
:data:SCENARIO_LIBRARY.
Returns¶
dict
Mapping of scenario name to the result dict produced by
:func:apply_stress.
Quantum Stress Testing¶
quantum_stress
¶
Quantum stress testing with superposition-encoded scenarios.
Encodes multiple stress scenarios as a superposition state where each computational basis state represents a scenario weighted by its probability. A portfolio loss oracle evaluates losses under each scenario, and quantum amplitude estimation (QAE) computes the probability-weighted expected loss across all scenarios simultaneously.
This provides a quadratic speed-up over classical scenario-weighted Monte Carlo for large scenario sets, following the paradigm of Woerner & Egger (1806.06893) applied to stress testing.
References¶
Woerner & Egger, "Quantum Risk Analysis", npj Quantum Information 5:15 (2019). Egger et al., "Credit Risk Analysis using Quantum Computers", IEEE TQE (2021).
QuantumStressTester
¶
Quantum stress testing with superposition-encoded scenarios.
Encodes stress scenarios as a weighted superposition state and uses quantum amplitude estimation to compute the probability-weighted expected portfolio loss across all scenarios simultaneously.
Parameters¶
backend : Backend
Quantum backend for circuit execution.
qae_method : str
QAE algorithm: "iqae", "mlae", or "canonical".
qae_shots : int
Shots per QAE round.
seed : int or None
Random seed for reproducibility.
run(portfolio_value, weights, scenario_specs)
¶
Run quantum stress test.
Parameters¶
portfolio_value : float Total portfolio market value. weights : NDArray, shape (4,) Sensitivity weights [equity, rates, vol, spreads]. scenario_specs : list[StressScenarioSpec] Scenarios with probability weights.
Returns¶
QuantumStressResult Full result with per-scenario and aggregate metrics.
classical_stress_test(portfolio_value, weights, scenario_specs, n_monte_carlo=10000, seed=42)
¶
Classical scenario-weighted Monte Carlo stress test.
Computes expected loss by sampling scenarios according to their probability weights and adding Monte Carlo noise to factor shocks.
Parameters¶
portfolio_value : float Total portfolio market value. weights : NDArray, shape (4,) Sensitivity weights [equity, rates, vol, spreads]. scenario_specs : list[StressScenarioSpec] Scenarios with probability weights. n_monte_carlo : int Number of Monte Carlo samples. seed : int or None Random seed.
Returns¶
QuantumStressResult Result with method="classical".