Spaces:
Sleeping
Sleeping
File size: 10,314 Bytes
72fc0ee | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 | """
Model Risk & Validation Framework.
Validates quantitative models against benchmark values and statistical
acceptance criteria before they are used in production calculations.
Responsibilities:
- Back-test models against known datasets
- Compare to analytical / reference values within tolerance bands
- Run statistical hypothesis tests (t-test, KS-test)
- Produce a ModelValidationReport suitable for a model risk committee
Supported validation types:
- ANALYTICAL : compare to closed-form reference
- MONTE_CARLO : check convergence of MC estimates
- BACKTESTING : compare predictions to realised outcomes
- STRESS : behaviour under extreme inputs
"""
from __future__ import annotations
import logging
import math
from dataclasses import dataclass, field
from datetime import datetime
from enum import Enum
from typing import Any, Callable, Optional
import numpy as np
log = logging.getLogger(__name__)
class ValidationType(str, Enum):
ANALYTICAL = "analytical"
MONTE_CARLO = "monte_carlo"
BACKTESTING = "backtesting"
STRESS = "stress"
class ValidationStatus(str, Enum):
PASSED = "passed"
FAILED = "failed"
CONDITIONAL = "conditional" # passed with caveats / warnings
@dataclass
class ValidationTest:
name: str
validation_type: ValidationType
passed: bool
expected: Optional[float]
actual: Optional[float]
relative_error: Optional[float] # |actual - expected| / |expected|
tolerance: Optional[float]
message: str = ""
@dataclass
class ModelValidationReport:
model_name: str
model_version: str
tests: list[ValidationTest] = field(default_factory=list)
validated_at: datetime = field(default_factory=datetime.utcnow)
@property
def status(self) -> ValidationStatus:
if any(not t.passed for t in self.tests):
return ValidationStatus.FAILED
warnings = [
t for t in self.tests
if t.relative_error is not None
and t.tolerance is not None
and t.relative_error > t.tolerance * 0.8 # within 20% of tolerance
]
if warnings:
return ValidationStatus.CONDITIONAL
return ValidationStatus.PASSED
@property
def is_approved(self) -> bool:
return self.status != ValidationStatus.FAILED
def summary(self) -> str:
n_pass = sum(1 for t in self.tests if t.passed)
n_fail = len(self.tests) - n_pass
return (
f"Model '{self.model_name}' v{self.model_version}: "
f"{self.status.value.upper()} β "
f"{n_pass}/{len(self.tests)} tests passed"
+ (f", {n_fail} FAILED" if n_fail else "")
)
class ModelRiskFramework:
"""
Executes and records model validation tests.
Usage::
mrv = ModelRiskFramework()
report = mrv.validate_black_scholes_call()
if not report.is_approved:
raise RuntimeError(report.summary())
"""
def __init__(self, default_tolerance: float = 0.001) -> None:
self._tolerance = default_tolerance
self._reports: list[ModelValidationReport] = []
# ββ Generic validation ββββββββββββββββββββββββββββββββββββββββββββββββββββ
def compare_to_reference(
self,
model_fn: Callable[..., float],
reference_fn: Callable[..., float],
test_cases: list[dict[str, Any]],
model_name: str,
model_version: str = "0.0.0",
tolerance: Optional[float] = None,
) -> ModelValidationReport:
"""
Run *model_fn* and *reference_fn* on each test case and compare results.
Parameters
----------
model_fn:
The model under test, called with ``**test_case``.
reference_fn:
The reference/benchmark implementation, called with ``**test_case``.
test_cases:
List of parameter dicts.
tolerance:
Maximum acceptable relative error per test (overrides default).
"""
tol = tolerance if tolerance is not None else self._tolerance
report = ModelValidationReport(model_name=model_name, model_version=model_version)
for i, case in enumerate(test_cases):
test_name = f"case_{i+1}"
try:
actual = float(model_fn(**case))
expected = float(reference_fn(**case))
if math.isclose(expected, 0.0, abs_tol=1e-10):
rel_err = abs(actual - expected)
else:
rel_err = abs(actual - expected) / abs(expected)
passed = rel_err <= tol
report.tests.append(
ValidationTest(
name=test_name,
validation_type=ValidationType.ANALYTICAL,
passed=passed,
expected=expected,
actual=actual,
relative_error=rel_err,
tolerance=tol,
message="" if passed else f"Relative error {rel_err:.4%} > tolerance {tol:.4%}",
)
)
except Exception as exc:
report.tests.append(
ValidationTest(
name=test_name,
validation_type=ValidationType.ANALYTICAL,
passed=False,
expected=None,
actual=None,
relative_error=None,
tolerance=tol,
message=f"Exception: {exc}",
)
)
self._reports.append(report)
if report.is_approved:
log.info("%s", report.summary())
else:
log.error("%s", report.summary())
return report
# ββ Monte Carlo convergence check βββββββββββββββββββββββββββββββββββββββββ
def check_mc_convergence(
self,
estimates: list[float],
reference: float,
model_name: str,
model_version: str = "0.0.0",
tolerance: Optional[float] = None,
) -> ModelValidationReport:
"""
Validate that a list of MC estimates converges to the reference value.
Checks:
1. Mean estimate within tolerance of reference.
2. Standard error is decreasing (1/βN rule).
"""
tol = tolerance if tolerance is not None else self._tolerance
report = ModelValidationReport(model_name=model_name, model_version=model_version)
n = len(estimates)
mean_est = float(np.mean(estimates))
std_err = float(np.std(estimates) / math.sqrt(n))
rel_err = abs(mean_est - reference) / abs(reference) if reference != 0 else abs(mean_est)
report.tests.append(
ValidationTest(
name="mc_mean_convergence",
validation_type=ValidationType.MONTE_CARLO,
passed=rel_err <= tol,
expected=reference,
actual=mean_est,
relative_error=rel_err,
tolerance=tol,
message=f"n={n}, std_err={std_err:.6f}",
)
)
expected_std_err = abs(reference) * tol # acceptable noise floor
report.tests.append(
ValidationTest(
name="mc_standard_error",
validation_type=ValidationType.MONTE_CARLO,
passed=std_err < expected_std_err * 2,
expected=expected_std_err,
actual=std_err,
relative_error=None,
tolerance=None,
message=f"Std error {std_err:.6f} vs budget {expected_std_err:.6f}",
)
)
self._reports.append(report)
return report
# ββ Stress testing ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def check_boundary_conditions(
self,
model_fn: Callable[..., float],
stress_cases: list[dict[str, Any]],
model_name: str,
model_version: str = "0.0.0",
) -> ModelValidationReport:
"""
Verify that the model doesn't produce NaN, Inf, or negative values
under extreme inputs.
Each ``stress_case`` dict may include an optional ``expected_finite``
key (bool, default True).
"""
report = ModelValidationReport(model_name=model_name, model_version=model_version)
for i, case in enumerate(stress_cases):
expect_finite = case.pop("expected_finite", True)
label = case.pop("label", f"stress_{i+1}")
try:
actual = float(model_fn(**case))
is_finite = math.isfinite(actual)
passed = is_finite if expect_finite else True
report.tests.append(
ValidationTest(
name=label,
validation_type=ValidationType.STRESS,
passed=passed,
expected=None,
actual=actual,
relative_error=None,
tolerance=None,
message="" if passed else f"Non-finite output: {actual}",
)
)
except Exception as exc:
report.tests.append(
ValidationTest(
name=label,
validation_type=ValidationType.STRESS,
passed=False,
expected=None,
actual=None,
relative_error=None,
tolerance=None,
message=f"Exception under stress: {exc}",
)
)
self._reports.append(report)
return report
def all_reports(self) -> list[ModelValidationReport]:
return list(self._reports)
|