diff --git a/docs/ADVANCED_FACTOR_RISK.md b/docs/ADVANCED_FACTOR_RISK.md new file mode 100644 index 0000000..8692f8b --- /dev/null +++ b/docs/ADVANCED_FACTOR_RISK.md @@ -0,0 +1,22 @@ +# 高级因子风险配方契约 + +`risk_model`新增两组可选字段: + +- `exposure_pipeline`:完整的`config`、`descriptor_fields`、`market_cap_field`及 + `industry_field`。描述子与市值字段必须映射到`required_history.fundamentals`, + 行业字段必须映射到`classification`。与旧`exposure_fields`互斥。 +- `estimation`:回归权重、行业约束、因子/特异风险半衰期、风险期限、Newey–West滞后、 + 状态调整窗口/界限、分组特异风险、固定/贝叶斯收缩。旧配方默认空字典。 + +配方层保持无风险引擎依赖,在执行前验证闭合字段、类型、PIT映射、风格组合、行业全集、 +正交化无环图及期限约束。非零HAC滞后必须等于H−1,回看长度必须覆盖滞后及完整状态 +调整窗口。加权/行业估计须声明暴露流水线;行业约束须同时包含市场与行业因子。 + +风险限额可引用流水线中的风格、market及`industry:`列。存在主动风险限额时 +仍须提供权重总和为1的基准。`equal`和`cost_aware`配置继续受原有分配规则约束。 +此契约不认证来源真实性、不自动校准参数、不改变风险限额。 + +完整可用配方及历史接入见 +[A股研究接入](https://github.com/PureSaber/a-share-multifactor/blob/main/docs/ADVANCED_FACTOR_RISK.md), +估计公式及独立校准见 +[风险模型说明](https://github.com/PureSaber/quant-risk-monitor/blob/main/docs/ADVANCED_FACTOR_RISK.md)。 diff --git a/src/quant_lab/research_options.py b/src/quant_lab/research_options.py index 0bed3a0..0980d08 100644 --- a/src/quant_lab/research_options.py +++ b/src/quant_lab/research_options.py @@ -5,6 +5,8 @@ import math import re +from quant_lab.risk_options import validate_estimation, validate_exposure_pipeline + def validate_validation(value: dict) -> dict: fields = { @@ -151,6 +153,8 @@ def validate_risk_model(value, histories): "active_factor_bounds", "benchmark_weights", "max_tracking_error", + "estimation", + "exposure_pipeline", } if not isinstance(value, dict) or set(value) - fields: raise ValueError("Unknown risk_model options") @@ -167,6 +171,7 @@ def validate_risk_model(value, histories): "factor_bounds": {}, "active_factor_bounds": {}, "benchmark_weights": {}, + "estimation": {}, **value, } if result.get("model_kind") not in {"statistical_proxy", "fundamental_style"}: @@ -196,11 +201,36 @@ def validate_risk_model(value, histories): or histories.get(field) not in {"fundamentals", "classification"} ): raise ValueError("Risk exposures require PIT numeric history fields") - if not mappings and ( - not result["market_factor"] or result["model_kind"] == "fundamental_style" + pipeline = result.get("exposure_pipeline") + if ( + not mappings + and pipeline is None + and (not result["market_factor"] or result["model_kind"] == "fundamental_style") ): raise ValueError("Fundamental style model requires real descriptors") factors = set(mappings) | ({"market"} if result["market_factor"] else set()) + validate_estimation(result["estimation"], result["lookback"]) + if pipeline is not None: + if mappings: + raise ValueError("exposure_fields and exposure_pipeline cannot be combined") + factors = validate_exposure_pipeline(pipeline, histories) + if "market_factor" in value and value["market_factor"] != pipeline["config"].get( + "market_factor", True + ): + raise ValueError("market_factor differs from the exposure pipeline") + result["market_factor"] = pipeline["config"].get("market_factor", True) + estimation = result["estimation"] + if ( + estimation.get("regression_weighting", "equal") != "equal" + or estimation.get("industry_constraint", False) + or estimation.get("specific_target", "global") == "industry" + ) and pipeline is None: + raise ValueError("Weighted/industry estimation requires a PIT exposure_pipeline") + if estimation.get("industry_constraint", False) and not ( + pipeline["config"].get("market_factor", True) + and pipeline["config"].get("include_industries", True) + ): + raise ValueError("Industry constraint requires market and industry factors") for key in ("factor_bounds", "active_factor_bounds"): bounds = result[key] if not isinstance(bounds, dict) or set(bounds) - factors: diff --git a/src/quant_lab/risk_options.py b/src/quant_lab/risk_options.py new file mode 100644 index 0000000..6db7452 --- /dev/null +++ b/src/quant_lab/risk_options.py @@ -0,0 +1,211 @@ +"""Dependency-free recipe contracts for advanced factor-risk research.""" + +from __future__ import annotations + +import math + +ESTIMATION_FIELDS = { + "regression_weighting", + "industry_constraint", + "factor_half_life", + "specific_half_life", + "newey_west_lags", + "specific_newey_west_lags", + "risk_horizon", + "regime_window", + "regime_min_periods", + "regime_half_life", + "regime_scale_min", + "regime_scale_max", + "specific_target", + "specific_shrinkage_method", + "specific_prior_dof", + "specific_min_group_assets", + "specific_group_fallback", + "max_condition_number", +} + + +def _number(value): + return type(value) in (int, float) and math.isfinite(value) + + +def validate_estimation(value, lookback): + if not isinstance(value, dict) or set(value) - ESTIMATION_FIELDS: + raise ValueError("Unknown risk estimation options") + choices = { + "regression_weighting": {"equal", "market_cap", "sqrt_market_cap"}, + "specific_target": {"global", "industry"}, + "specific_shrinkage_method": {"fixed", "bayesian"}, + "specific_group_fallback": {"error", "global"}, + } + for name, allowed in choices.items(): + if name in value and value[name] not in allowed: + raise ValueError(f"Invalid risk estimation {name}") + if type(value.get("industry_constraint", False)) is not bool: + raise ValueError("industry_constraint must be boolean") + for name in ("factor_half_life", "specific_half_life", "regime_half_life"): + if value.get(name) is not None and (not _number(value[name]) or value[name] <= 0): + raise ValueError(f"Invalid risk estimation {name}") + for name, minimum in ( + ("newey_west_lags", 0), + ("specific_newey_west_lags", 0), + ("risk_horizon", 1), + ("regime_window", 0), + ("regime_min_periods", 2), + ("specific_min_group_assets", 2), + ): + if name in value and (type(value[name]) is not int or value[name] < minimum): + raise ValueError(f"Invalid risk estimation {name}") + horizon = value.get("risk_horizon", 1) + for name in ("newey_west_lags", "specific_newey_west_lags"): + lag = value.get(name, 0) + if lag not in {0, horizon - 1} or lag >= lookback: + raise ValueError("Newey-West lags must match the horizon and fit the lookback") + window = value.get("regime_window", 0) + if window == 1 or (window and window + value.get("regime_min_periods", 20) > lookback): + raise ValueError("Regime adjustment needs sufficient prior history and window") + for name in ( + "regime_scale_min", + "regime_scale_max", + "specific_prior_dof", + "max_condition_number", + ): + if name in value and (not _number(value[name]) or value[name] <= 0): + raise ValueError(f"Invalid risk estimation {name}") + if value.get("max_condition_number", 1e8) <= 1: + raise ValueError("max_condition_number must exceed one") + if value.get("regime_scale_min", 0.25) > 1 or value.get("regime_scale_max", 4) < 1: + raise ValueError("Regime bounds must contain one") + return value + + +def validate_exposure_pipeline(value, histories): + if not isinstance(value, dict) or set(value) != { + "config", + "descriptor_fields", + "market_cap_field", + "industry_field", + }: + raise ValueError("Complete exposure_pipeline contract required") + config = value["config"] + allowed = { + "styles", + "industry_universe", + "market_factor", + "include_industries", + "standardization_weighting", + "winsor_method", + "winsor_limit", + "missing_policy", + "max_missing_fraction", + "min_industry_observations", + "missing_group_fallback", + "min_assets", + "max_descriptor_age_days", + "max_classification_age_days", + "orthogonalize", + } + if not isinstance(config, dict) or set(config) - allowed: + raise ValueError("Unknown exposure pipeline config") + styles = config.get("styles") + if not isinstance(styles, dict) or not styles: + raise ValueError("Exposure pipeline requires explicit styles") + descriptors = set() + for name, composite in styles.items(): + if ( + not isinstance(name, str) + or not name.strip() + or name == "market" + or name.startswith("industry:") + or not isinstance(composite, dict) + or not composite + ): + raise ValueError("Invalid exposure style composite") + if ( + any( + not isinstance(key, str) or not key.strip() or not _number(weight) + for key, weight in composite.items() + ) + or sum(abs(w) for w in composite.values()) == 0 + ): + raise ValueError("Invalid exposure descriptor weights") + descriptors.update(key for key, weight in composite.items() if weight) + fields = value["descriptor_fields"] + if not isinstance(fields, dict) or set(fields) != descriptors: + raise ValueError("descriptor_fields must exactly cover active composite descriptors") + for field in [value["market_cap_field"], *fields.values()]: + if not isinstance(field, str) or histories.get(field) != "fundamentals": + raise ValueError("Exposure descriptors and market cap require PIT numeric histories") + if ( + not isinstance(value["industry_field"], str) + or histories.get(value["industry_field"]) != "classification" + ): + raise ValueError("Exposure industries require PIT classification history") + industries = config.get("industry_universe") + if ( + not isinstance(industries, (list, tuple)) + or not industries + or any(not isinstance(x, str) or not x.strip() for x in industries) + or len(set(industries)) != len(industries) + ): + raise ValueError("A frozen industry_universe is required") + for key in ("market_factor", "include_industries"): + if type(config.get(key, True)) is not bool: + raise ValueError(f"Invalid exposure {key}") + for key, default, choices in ( + ("standardization_weighting", "market_cap", {"equal", "market_cap", "sqrt_market_cap"}), + ("winsor_method", "mad", {"mad", "quantile", "none"}), + ("missing_policy", "error", {"error", "industry_median"}), + ("missing_group_fallback", "error", {"error", "global"}), + ): + if config.get(key, default) not in choices: + raise ValueError(f"Invalid exposure {key}") + limit = config.get("winsor_limit", 5.0) + method = config.get("winsor_method", "mad") + if ( + not _number(limit) + or (method == "mad" and limit <= 0) + or (method == "quantile" and not 0 < limit < 0.5) + ): + raise ValueError("Invalid exposure winsor_limit") + missing = config.get("max_missing_fraction", 0.2) + if not _number(missing) or not 0 <= missing < 1: + raise ValueError("Invalid exposure missing fraction") + for key in ("min_industry_observations", "min_assets"): + if key in config and (type(config[key]) is not int or config[key] < 2): + raise ValueError(f"Invalid exposure {key}") + for key in ("max_descriptor_age_days", "max_classification_age_days"): + if config.get(key) is not None and (not _number(config[key]) or config[key] < 0): + raise ValueError(f"Invalid exposure {key}") + graph = config.get("orthogonalize", {}) + if not isinstance(graph, dict) or set(graph) - set(styles): + raise ValueError("Invalid exposure orthogonalization graph") + visited, active = set(), set() + + def visit(name): + if name in active: + raise ValueError("Exposure orthogonalization cycle") + if name in visited: + return + parents = graph.get(name, []) + if ( + not isinstance(parents, (list, tuple)) + or any(p not in styles for p in parents) + or len(set(parents)) != len(parents) + ): + raise ValueError("Invalid orthogonalization controls") + active.add(name) + for parent in parents: + visit(parent) + active.remove(name) + visited.add(name) + + for name in styles: + visit(name) + factors = set(styles) + if config.get("market_factor", True): + factors.add("market") + if config.get("include_industries", True): + factors.update("industry:" + name for name in industries) + return factors diff --git a/tests/test_advanced_risk_options.py b/tests/test_advanced_risk_options.py new file mode 100644 index 0000000..8869697 --- /dev/null +++ b/tests/test_advanced_risk_options.py @@ -0,0 +1,123 @@ +from copy import deepcopy + +import pytest + +from quant_lab.research_options import validate_risk_model + + +def recipe(): + return { + "model_kind": "fundamental_style", + "lookback": 60, + "exposure_pipeline": { + "descriptor_fields": {"size": "log_cap", "value": "book_to_price"}, + "market_cap_field": "market_cap", + "industry_field": "sector", + "config": { + "styles": {"size": {"size": 1}, "value": {"value": 1}}, + "industry_universe": ["a", "b"], + "orthogonalize": {"value": ["size"]}, + }, + }, + "estimation": { + "regression_weighting": "sqrt_market_cap", + "industry_constraint": True, + "factor_half_life": 30, + "specific_half_life": 20, + "risk_horizon": 5, + "newey_west_lags": 4, + "specific_newey_west_lags": 4, + "regime_window": 10, + "specific_target": "industry", + "specific_shrinkage_method": "bayesian", + }, + "factor_bounds": {"industry:a": [0, 0.6], "size": [-1, 1]}, + } + + +HISTORIES = { + "log_cap": "fundamentals", + "book_to_price": "fundamentals", + "market_cap": "fundamentals", + "sector": "classification", +} + + +def test_advanced_contract_and_legacy_defaults(): + value = recipe() + before = deepcopy(value) + result = validate_risk_model(value, HISTORIES) + assert result["estimation"]["newey_west_lags"] == 4 + assert value == before + legacy = validate_risk_model({"model_kind": "statistical_proxy"}, {}) + assert legacy["estimation"] == {} + + +@pytest.mark.parametrize( + "change", + [ + {"newey_west_lags": 2}, + {"regime_window": 50}, + {"factor_half_life": 0}, + {"specific_half_life": True}, + {"regression_weighting": "inverse_cap"}, + {"industry_constraint": 1}, + {"specific_target": "unknown"}, + {"specific_shrinkage_method": "unknown"}, + {"specific_prior_dof": -1}, + {"risk_horizon": 0}, + {"regime_window": 1}, + {"regime_scale_max": 0.5}, + {"regime_scale_min": 2}, + {"max_condition_number": 1}, + {"unknown": True}, + ], +) +def test_rejects_invalid_estimation_contract(change): + value = recipe() + value["estimation"].update(change) + with pytest.raises(ValueError): + validate_risk_model(value, HISTORIES) + + +@pytest.mark.parametrize( + "change", + [ + {"styles": {}}, + {"styles": {"market": {"size": 1}}}, + {"styles": {"size": {"size": 0}}}, + {"industry_universe": ["a", "a"]}, + {"market_factor": False}, + {"include_industries": False}, + {"winsor_method": "bad"}, + {"winsor_method": "quantile", "winsor_limit": 1}, + {"max_missing_fraction": 1}, + {"min_assets": True}, + {"max_descriptor_age_days": -1}, + {"orthogonalize": {"value": ["missing"]}}, + {"orthogonalize": {"size": ["value"], "value": ["size"]}}, + {"unknown": True}, + ], +) +def test_rejects_invalid_exposure_contract(change): + value = recipe() + value["exposure_pipeline"]["config"].update(change) + with pytest.raises(ValueError): + validate_risk_model(value, HISTORIES) + + +def test_requires_historical_numeric_fields_and_unambiguous_pipeline(): + value = recipe() + with pytest.raises(ValueError, match="PIT numeric"): + validate_risk_model(value, {**HISTORIES, "market_cap": "classification"}) + with pytest.raises(ValueError, match="classification history"): + validate_risk_model(value, {**HISTORIES, "sector": "fundamentals"}) + value["exposure_fields"] = {"size": "log_cap"} + with pytest.raises(ValueError, match="cannot be combined"): + validate_risk_model(value, HISTORIES) + value = { + "model_kind": "statistical_proxy", + "estimation": {"regression_weighting": "market_cap"}, + } + with pytest.raises(ValueError, match="PIT exposure_pipeline"): + validate_risk_model(value, {})