diff --git a/README.md b/README.md index dea4bee..78aa429 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,8 @@ Shared factor computation library for PureSaber quant research. +[完整因子目录](docs/COMPLETE_CATALOG.md)通过 `quant-factors list --all --json` 汇总公开因子入口、输入要求与缓存边界。原有默认目录保留兼容性。 + ## Install ```bash diff --git a/docs/COMPLETE_CATALOG.md b/docs/COMPLETE_CATALOG.md new file mode 100644 index 0000000..469a48d --- /dev/null +++ b/docs/COMPLETE_CATALOG.md @@ -0,0 +1,20 @@ +# 完整因子目录 + +```text +quant-factors list --all +quant-factors list --all --json +``` + +两种输出来自同一个`factor_catalog()`结果,覆盖core、价量、具名研究、中低频、基本面特征和分钟因子。相同名称合并成一条记录并保留所有来源目录,不能将目录数量相加当成独立因子数。历史`list --json`和计算默认选择保持兼容。 + +机器接口`quant_factors.catalog.factor_catalog()`返回`quant.factor-catalog/v1`: + +- 唯一名称、描述来源、因子家族和历史17个默认组标记。 +- 可调用的日频面板或分钟计算入口及输入要求;日频要求直接复用`expression_requirements`,不另维护一套参数规则。 +- 分钟聚合要求排序后的日内数据;缺少`time`列时保持调用者的原始组内次序。最少bar数只是计算下限,不保证方差、成交量或完整交易日条件满足;不声称PIT认证。 +- 源文件SHA-256和整个目录的规范JSON哈希,识别实际实现和目录内容变化。 +- 缓存真正支持的六个FactorSpec算法及单市场输入、无拟合状态、全表读取边界。 + +持久缓存不通过这个名称目录自动选择算法。名称相近不代表日频函数与显式频率/PIT引擎数值等价,应建立带版本、依赖、日历和as-of的FactorSpec,并分别验证研究用途。 + +兼容语义会显式提示:`turnover_20d`是平均成交量;真实换手率使用`turnover_rate_20d_v2`及对应单位/PIT流通股输入。旧Amihud采用价格乘成交量代理,v2要求实际成交金额。目录不修改任何历史因子结果,也不把公式数量解释为经过验证的有效alpha。 diff --git a/src/quant_factors/catalog.py b/src/quant_factors/catalog.py new file mode 100644 index 0000000..18bc512 --- /dev/null +++ b/src/quant_factors/catalog.py @@ -0,0 +1,147 @@ +"""Complete, deterministic public factor inventory without changing legacy defaults.""" + +from __future__ import annotations + +import hashlib +import json +from pathlib import Path + +from quant_factors.cache import SUPPORTED_ALGORITHMS +from quant_factors.core import DEFAULT_FACTORS, list_factors +from quant_factors.expressions import expression_requirements +from quant_factors.families import factor_families +from quant_factors.fundamental_characteristics import list_fundamental_characteristics +from quant_factors.medium_low import list_medium_low_factors +from quant_factors.price_volume import list_price_volume_factors +from quant_factors.research_factors import MINUTE_FACTORS, list_named_research_factors + + +def factor_catalog() -> dict: + """Return all public named registries, their true dispatch paths and requirements. + + The cache consumes explicit FactorSpec algorithms, not these name registries. + A similarly named algorithm does not establish identical numerical semantics. + """ + groups = { + "core": list_factors(), + "price_volume": list_price_volume_factors(), + "named_research": list_named_research_factors(), + "medium_low": list_medium_low_factors(), + "fundamental_characteristics": list_fundamental_characteristics(), + "minute": dict(MINUTE_FACTORS), + } + daily = {name for group, items in groups.items() if group != "minute" for name in items} + requirements = expression_requirements(sorted(daily)) + rows = [] + for name in sorted(daily | set(MINUTE_FACTORS)): + memberships = [group for group, items in groups.items() if name in items] + interfaces = [] + if name in daily: + interfaces.append( + { + "entrypoint": "quant_factors.expressions.compute_research_factors", + "input_kind": "daily_panel", + "requirements": requirements[name], + } + ) + if name in MINUTE_FACTORS: + interfaces.append( + { + "entrypoint": "quant_factors.research_factors.compute_minute_factors", + "input_kind": "ordered_intraday_bars", + "requirements": { + "columns": ["symbol", "date", "close", "volume"], + "optional_order_column": "time", + "ordering": "Within each symbol/date, chronological bars are caller-provided when time is absent.", + "warmup_sessions": 20 if name == "smart_money_20d" else 1, + "minimum_bars": 4 if name == "minute_return_skew" else 3, + "pit_required": False, + "pit_certified": False, + }, + } + ) + notes = [] + if name == "turnover_20d": + notes.append( + "Legacy mean volume, not a turnover rate. Prefer average_volume_20d for this formula or turnover_rate_20d_v2 with its required units/PIT inputs." + ) + elif name == "amihud_illiq_20d": + notes.append( + "Legacy close-times-volume proxy. amihud_illiq_20d_v2 requires actual traded amount and economic return inputs." + ) + rows.append( + { + "name": name, + "descriptions": {group: groups[group][name] for group in memberships}, + "catalogs": memberships, + "families": list(factor_families(name)), + "historical_default": name in DEFAULT_FACTORS, + "interfaces": interfaces, + "cache_named_dispatch": False, + "notes": notes, + } + ) + source_names = ( + "catalog.py", + "core.py", + "academic.py", + "expressions.py", + "families.py", + "price_volume.py", + "price_volume_catalog.py", + "research_factors.py", + "medium_low.py", + "fundamental_characteristics.py", + "cache.py", + "engine_v2.py", + "contracts_v2.py", + "pit_v2.py", + ) + payload = { + "schema_version": "quant.factor-catalog/v1", + "factors": rows, + "counts": { + "unique_names": len(rows), + "historical_defaults": len(DEFAULT_FACTORS), + "by_catalog": {name: len(items) for name, items in groups.items()}, + }, + "persistent_cache": { + "entrypoint": "quant_factors.cache.FactorCache.compute", + "selection": "Explicit versioned FactorSpec with algorithm, dependency, frequency and as-of; no named-registry auto-dispatch.", + "algorithms": sorted(SUPPORTED_ALGORITHMS), + "constraints": [ + "one market dependency", + "no auxiliary sources or fitted state", + "full-table read/compare/serialize; factor evaluation alone is incremental", + ], + }, + "source_sha256": { + name: hashlib.sha256(Path(__file__).with_name(name).read_bytes()).hexdigest() + for name in source_names + }, + "claims": { + "profitable_alpha_certified": False, + "market_data_certified": False, + "all_named_factors_cache_supported": False, + }, + } + payload["catalog_sha256"] = hashlib.sha256( + json.dumps( + payload, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False + ).encode() + ).hexdigest() + return payload + + +def catalog_text(catalog: dict) -> str: + lines = [f"Factor catalog: {catalog['counts']['unique_names']} unique names"] + for row in catalog["factors"]: + paths = ", ".join(item["input_kind"] for item in row["interfaces"]) + lines.append(f"{row['name']} [{','.join(row['families'])}] ({paths})") + lines.append( + "Persistent cache algorithms: " + ", ".join(catalog["persistent_cache"]["algorithms"]) + ) + lines.append( + "Cache requires explicit FactorSpec; named factors are not dispatched automatically." + ) + return "\n".join(lines) diff --git a/src/quant_factors/cli.py b/src/quant_factors/cli.py index 8972442..3b6928d 100644 --- a/src/quant_factors/cli.py +++ b/src/quant_factors/cli.py @@ -8,6 +8,7 @@ import pandas as pd import yaml +from quant_factors.catalog import catalog_text, factor_catalog from quant_factors.core import list_factors from quant_factors.expressions import compute_research_factors, validate_expressions from quant_factors.families import factor_families @@ -32,6 +33,14 @@ def _print_factor(name: str, description: str, width: int) -> None: def cmd_list(args: argparse.Namespace) -> int: + if args.all: + catalog = factor_catalog() + print( + json.dumps(catalog, indent=2, ensure_ascii=False) + if args.json + else catalog_text(catalog) + ) + return 0 factors = list_factors() if args.json: print(json.dumps(factors, indent=2, ensure_ascii=False)) @@ -133,6 +142,11 @@ def build_parser() -> argparse.ArgumentParser: lst = sub.add_parser("list", help="List built-in factors") lst.add_argument("--json", action="store_true") + lst.add_argument( + "--all", + action="store_true", + help="Complete versioned catalog, including opt-in and minute factors", + ) lst.set_defaults(func=cmd_list) compute = sub.add_parser("compute", help="Compute factors from panel data") diff --git a/tests/test_catalog.py b/tests/test_catalog.py new file mode 100644 index 0000000..90ace75 --- /dev/null +++ b/tests/test_catalog.py @@ -0,0 +1,67 @@ +import hashlib +import json + +from quant_factors.catalog import catalog_text, factor_catalog +from quant_factors.cli import main +from quant_factors.core import DEFAULT_FACTORS, list_factors +from quant_factors.expressions import expression_requirements +from quant_factors.fundamental_characteristics import list_fundamental_characteristics +from quant_factors.medium_low import list_medium_low_factors +from quant_factors.price_volume import list_price_volume_factors +from quant_factors.research_factors import MINUTE_FACTORS, list_named_research_factors + + +def test_complete_catalog_exact_public_registry_union_and_requirements(): + catalog = factor_catalog() + names = set().union( + list_factors(), + list_price_volume_factors(), + list_named_research_factors(), + list_medium_low_factors(), + list_fundamental_characteristics(), + MINUTE_FACTORS, + ) + assert [row["name"] for row in catalog["factors"]] == sorted(names) + assert catalog["counts"]["unique_names"] == len(names) + assert catalog["counts"]["historical_defaults"] == 17 + for row in catalog["factors"]: + assert row["historical_default"] == (row["name"] in DEFAULT_FACTORS) + assert row["families"] + assert row["cache_named_dispatch"] is False + for interface in row["interfaces"]: + if interface["input_kind"] == "daily_panel": + assert ( + interface["requirements"] == expression_requirements([row["name"]])[row["name"]] + ) + else: + assert row["name"] in MINUTE_FACTORS + assert interface["entrypoint"].endswith("compute_minute_factors") + assert not any(catalog["claims"].values()) + assert len(catalog["persistent_cache"]["algorithms"]) == 6 + + +def test_catalog_identity_and_legacy_semantic_notes(): + catalog = factor_catalog() + assert catalog == factor_catalog() + digest = catalog.pop("catalog_sha256") + raw = json.dumps( + catalog, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False + ).encode() + assert hashlib.sha256(raw).hexdigest() == digest + assert all(len(value) == 64 for value in catalog["source_sha256"].values()) + rows = {row["name"]: row for row in catalog["factors"]} + assert "not a turnover rate" in rows["turnover_20d"]["notes"][0] + assert "actual traded amount" in rows["amihud_illiq_20d"]["notes"][0] + assert rows["smart_money_20d"]["interfaces"][0]["requirements"]["warmup_sessions"] == 20 + + +def test_cli_full_text_json_parity_and_legacy_compatibility(capsys): + assert main(["list", "--json"]) == 0 + assert json.loads(capsys.readouterr().out) == list_factors() + assert main(["list", "--all", "--json"]) == 0 + catalog = json.loads(capsys.readouterr().out) + assert main(["list", "--all"]) == 0 + text = capsys.readouterr().out + assert text.strip() == catalog_text(catalog) + for row in catalog["factors"]: + assert row["name"] + " [" in text