test: define reproducible risk snapshot contract
This commit is contained in:
@@ -8,6 +8,7 @@ import pytest
|
||||
|
||||
from quant_engine.risk import (
|
||||
ComponentRiskResult,
|
||||
CovarianceSnapshot,
|
||||
component_var,
|
||||
labeled_component_risk,
|
||||
marginal_risk_contribution,
|
||||
@@ -15,6 +16,54 @@ from quant_engine.risk import (
|
||||
)
|
||||
|
||||
|
||||
def test_covariance_snapshot_is_validated_and_immutable_by_interface() -> None:
|
||||
covariance = pd.DataFrame(
|
||||
[[0.04, 0.01], [0.01, 0.09]],
|
||||
index=["A", "B"],
|
||||
columns=["A", "B"],
|
||||
)
|
||||
snapshot = CovarianceSnapshot(
|
||||
snapshot_id="cov-20260107-v1",
|
||||
as_of_date="2026-01-07",
|
||||
covariance=covariance,
|
||||
return_frequency="1d",
|
||||
periods_per_year=252,
|
||||
)
|
||||
|
||||
covariance.loc["A", "A"] = 999.0
|
||||
leaked_copy = snapshot.covariance
|
||||
leaked_copy.loc["B", "B"] = 999.0
|
||||
|
||||
assert snapshot.as_of_date == pd.Timestamp("2026-01-07").date()
|
||||
assert snapshot.covariance.loc["A", "A"] == pytest.approx(0.04)
|
||||
assert snapshot.covariance.loc["B", "B"] == pytest.approx(0.09)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("kwargs", "message"),
|
||||
[
|
||||
({"snapshot_id": ""}, "snapshot_id"),
|
||||
({"return_frequency": ""}, "return_frequency"),
|
||||
({"periods_per_year": 0}, "periods_per_year"),
|
||||
],
|
||||
)
|
||||
def test_covariance_snapshot_rejects_incomplete_identity(
|
||||
kwargs: dict[str, object],
|
||||
message: str,
|
||||
) -> None:
|
||||
values: dict[str, object] = {
|
||||
"snapshot_id": "cov-20260107-v1",
|
||||
"as_of_date": "2026-01-07",
|
||||
"covariance": pd.DataFrame([[0.04]], index=["A"], columns=["A"]),
|
||||
"return_frequency": "1d",
|
||||
"periods_per_year": 252,
|
||||
}
|
||||
values.update(kwargs)
|
||||
|
||||
with pytest.raises((TypeError, ValueError), match=message):
|
||||
CovarianceSnapshot(**values)
|
||||
|
||||
|
||||
def test_risk_contribution_sums_to_one_for_positive_portfolio_variance() -> None:
|
||||
weights = np.array([0.5, 0.5])
|
||||
covariance = np.diag([1.0, 4.0])
|
||||
|
||||
Reference in New Issue
Block a user