Coverage for features/sector_map.py: 100%
18 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
1"""Ticker -> sector-neutral-ranking bucket (V5.1 Phase 0, Problems.md #75).
3Pure, dependency-light, imported by BOTH train.py (torch-bound) and main.py
4(the Lean runtime, which cannot import train.py) - the same train/inference
5parity convention every other module in features/ follows. This module
6existed only inside train.py before V5.1; train.py::load_sector_mapping()
7is now a thin delegate to load_sector_mapping() here so both callers share
8one implementation instead of main.py duplicating the file-read/strip logic.
9"""
11from __future__ import annotations
13import json
14from pathlib import Path
15from typing import Any
17UNKNOWN_SECTOR_LABEL = "Unknown"
19# Mirrors train.py::SECTOR_MAPPING_PATH (DATA_DIR / "reference" / "sector_mapping.json") -
20# this file lives at <repo_root>/features/sector_map.py, so .parent.parent is <repo_root>.
21DEFAULT_SECTOR_MAPPING_PATH = Path(__file__).resolve().parent.parent / "data" / "reference" / "sector_mapping.json"
24def load_sector_mapping(config: dict[str, Any], *, default_path: Path = DEFAULT_SECTOR_MAPPING_PATH) -> dict[str, str]:
25 """Ticker -> sector bucket, from the checked-in data/reference/sector_mapping.json
26 (or an override path via config phase1.target.ranking.sector_neutral.mapping_path).
28 Same defensive posture as every other reference-file loader in this
29 codebase: returns {} (never raises) when the file is missing or
30 unparseable, so a caller degrades to every ticker resolving to
31 UNKNOWN_SECTOR_LABEL rather than crashing over a missing reference file.
32 `_`-prefixed keys are comments and are stripped.
33 """
34 mapping_path_str = (
35 config.get("phase1", {}).get("target", {}).get("ranking", {}).get("sector_neutral", {}).get("mapping_path")
36 )
37 mapping_path = Path(mapping_path_str) if mapping_path_str else default_path
38 if not mapping_path.exists():
39 return {}
41 try:
42 raw = json.loads(mapping_path.read_text(encoding="utf-8"))
43 except (json.JSONDecodeError, OSError):
44 return {}
46 return {ticker: sector for ticker, sector in raw.items() if not ticker.startswith("_")}
49def resolve_sector(ticker: str, sector_by_ticker: dict[str, str]) -> str:
50 """sector_by_ticker.get(ticker, UNKNOWN_SECTOR_LABEL) - the one-line
51 lookup every caller (book_neutrality.py, rank_book_simulator.py,
52 train.py's residual-rank sector dummies) needs, kept in one place so
53 the UNKNOWN_SECTOR_LABEL default can never drift between callers."""
54 return sector_by_ticker.get(ticker, UNKNOWN_SECTOR_LABEL)