alphasift 0.3.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. alphasift/__init__.py +52 -0
  2. alphasift/__main__.py +7 -0
  3. alphasift/audit.py +191 -0
  4. alphasift/candidate_context.py +738 -0
  5. alphasift/cli.py +2797 -0
  6. alphasift/config.py +705 -0
  7. alphasift/context.py +672 -0
  8. alphasift/daily.py +1256 -0
  9. alphasift/daily_brief.py +593 -0
  10. alphasift/daily_report.py +1115 -0
  11. alphasift/daily_report_html.py +1257 -0
  12. alphasift/doctor.py +1123 -0
  13. alphasift/dsa.py +302 -0
  14. alphasift/dsa_adapter.py +178 -0
  15. alphasift/dsa_provider.py +192 -0
  16. alphasift/evaluate.py +2418 -0
  17. alphasift/filter.py +517 -0
  18. alphasift/hotspot.py +1713 -0
  19. alphasift/industry.py +959 -0
  20. alphasift/llm_client.py +349 -0
  21. alphasift/market_digest.py +284 -0
  22. alphasift/market_news.py +446 -0
  23. alphasift/market_regime.py +578 -0
  24. alphasift/markets.py +160 -0
  25. alphasift/mcp.py +720 -0
  26. alphasift/models.py +315 -0
  27. alphasift/normalize.py +113 -0
  28. alphasift/notify.py +2608 -0
  29. alphasift/overview.py +225 -0
  30. alphasift/pack.py +1470 -0
  31. alphasift/pack_features.py +431 -0
  32. alphasift/pattern_replay.py +1449 -0
  33. alphasift/patterns/bottom_volume_yang.yaml +32 -0
  34. alphasift/patterns/box_breakout.yaml +36 -0
  35. alphasift/patterns/double_bottom_breakout.yaml +38 -0
  36. alphasift/patterns/ma20_shrink_pullback.yaml +37 -0
  37. alphasift/patterns/shooting_star_confirm.yaml +49 -0
  38. alphasift/patterns/single_yang_hold.yaml +44 -0
  39. alphasift/patterns/steady_trend_breakout.yaml +39 -0
  40. alphasift/patterns/three_white_soldiers.yaml +72 -0
  41. alphasift/patterns/three_white_soldiers_pullback.yaml +91 -0
  42. alphasift/patterns.py +1233 -0
  43. alphasift/performance_history.py +297 -0
  44. alphasift/pipeline.py +1010 -0
  45. alphasift/post_analysis.py +337 -0
  46. alphasift/ranker.py +990 -0
  47. alphasift/report.py +379 -0
  48. alphasift/result_schema.py +179 -0
  49. alphasift/risk.py +452 -0
  50. alphasift/run_history.py +164 -0
  51. alphasift/scorer.py +597 -0
  52. alphasift/server.py +680 -0
  53. alphasift/snapshot.py +1025 -0
  54. alphasift/snapshot_us.py +280 -0
  55. alphasift/snapshot_yahoo.py +358 -0
  56. alphasift/source_guard.py +70 -0
  57. alphasift/source_history.py +306 -0
  58. alphasift/store.py +294 -0
  59. alphasift/strategies/balanced_alpha.yaml +76 -0
  60. alphasift/strategies/blue_chip_income.yaml +87 -0
  61. alphasift/strategies/capital_heat.yaml +74 -0
  62. alphasift/strategies/dual_low.yaml +80 -0
  63. alphasift/strategies/global_value.yaml +65 -0
  64. alphasift/strategies/low_volatility_quality.yaml +95 -0
  65. alphasift/strategies/momentum_quality.yaml +81 -0
  66. alphasift/strategies/oversold_reversal.yaml +75 -0
  67. alphasift/strategies/quality_value.yaml +80 -0
  68. alphasift/strategies/shrink_pullback.yaml +77 -0
  69. alphasift/strategies/us_momentum_quality.yaml +74 -0
  70. alphasift/strategies/volume_breakout.yaml +78 -0
  71. alphasift/strategy.py +1090 -0
  72. alphasift/strategy_cards.py +424 -0
  73. alphasift/strategy_templates.py +291 -0
  74. alphasift/timeutil.py +38 -0
  75. alphasift/valuation_kr.py +149 -0
  76. alphasift/workbench_ui.py +1051 -0
  77. alphasift-0.3.1.data/data/.env.example +151 -0
  78. alphasift-0.3.1.data/data/LICENSE +184 -0
  79. alphasift-0.3.1.data/data/SKILL.md +190 -0
  80. alphasift-0.3.1.data/data/agents/openai.yaml +7 -0
  81. alphasift-0.3.1.dist-info/METADATA +312 -0
  82. alphasift-0.3.1.dist-info/RECORD +86 -0
  83. alphasift-0.3.1.dist-info/WHEEL +5 -0
  84. alphasift-0.3.1.dist-info/entry_points.txt +2 -0
  85. alphasift-0.3.1.dist-info/licenses/LICENSE +184 -0
  86. alphasift-0.3.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,291 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Reusable strategy authoring templates."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from dataclasses import asdict, dataclass
7
+
8
+
9
+ @dataclass(frozen=True)
10
+ class StrategyTemplate:
11
+ name: str
12
+ display_name: str
13
+ description: str
14
+ category: str
15
+ tags: list[str]
16
+ style: dict[str, object]
17
+ data_requirements: list[str]
18
+ notes: list[str]
19
+ yaml_text: str
20
+
21
+
22
+ _TEMPLATES: dict[str, StrategyTemplate] = {
23
+ "defensive_value_quality": StrategyTemplate(
24
+ name="defensive_value_quality",
25
+ display_name="稳健价值质量",
26
+ description="从估值、稳定性和流动性出发的防守型价值质量模板",
27
+ category="value",
28
+ tags=["value", "quality", "defensive"],
29
+ style={
30
+ "risk_profile": "defensive",
31
+ "holding_period": "watchlist",
32
+ "execution_style": "quality_value",
33
+ "market_regime": ["risk_off", "range_bound"],
34
+ "capital_profile": "medium_liquidity",
35
+ "ui_badge": "稳健",
36
+ },
37
+ data_requirements=["snapshot"],
38
+ notes=[
39
+ "适合从 `quality_value` / `dual_low` 延伸出更保守的策略。",
40
+ "默认不依赖日 K,先保证 snapshot 字段覆盖和低降级风险。",
41
+ ],
42
+ yaml_text="""# Defensive value-quality template. Rename before use.
43
+ name: my_defensive_value_quality
44
+ display_name: 我的稳健价值质量
45
+ description: 估值合理、流动性充足、波动不过热的防守型候选
46
+ version: "1.0"
47
+ category: value
48
+ tags: [value, quality, defensive]
49
+ style:
50
+ risk_profile: defensive
51
+ holding_period: watchlist
52
+ execution_style: quality_value
53
+ market_regime: [risk_off, range_bound]
54
+ capital_profile: medium_liquidity
55
+ ui_badge: 稳健
56
+
57
+ screening:
58
+ enabled: true
59
+ market_scope: [cn]
60
+ hard_filters:
61
+ exclude_st: true
62
+ amount_min: 80000000
63
+ price_min: 3
64
+ price_max: 180
65
+ market_cap_min: 10000000000
66
+ pe_ttm_min: 0
67
+ pe_ttm_max: 25
68
+ pb_min: 0
69
+ pb_max: 4.0
70
+ change_pct_min: -3.5
71
+ change_pct_max: 5.0
72
+ tech_weight: 0.15
73
+ factor_weights:
74
+ value: 0.32
75
+ stability: 0.24
76
+ liquidity: 0.18
77
+ momentum: 0.08
78
+ activity: 0.08
79
+ reversal: 0.04
80
+ size: 0.06
81
+ scoring_profile:
82
+ momentum_chase_start_pct: 3.0
83
+ activity_ideal_volume_ratio: 1.4
84
+ activity_ideal_turnover_rate: 2.5
85
+ stability_hot_change_pct: 4.5
86
+ risk_profile:
87
+ chase_change_pct: 5.5
88
+ abnormal_volume_ratio: 4.5
89
+ high_turnover_rate: 10.0
90
+ scorecard_profile:
91
+ value_quality_value_min: 72.0
92
+ value_quality_stability_min: 68.0
93
+ value_quality_bonus: 2.8
94
+ ranking_hints: |
95
+ 优先关注:
96
+ 1. 估值合理且不是依赖单日情绪推动的标的
97
+ 2. 成交额足够、涨跌幅不过热
98
+ 3. 行业地位、现金流质量或经营稳定性更好
99
+ max_output: 5
100
+ """,
101
+ ),
102
+ "momentum_breakout_daily": StrategyTemplate(
103
+ name="momentum_breakout_daily",
104
+ display_name="日K放量突破",
105
+ description="依赖日 K 特征确认放量突破、均线结构和整理形态的进攻型模板",
106
+ category="trend",
107
+ tags=["momentum", "breakout", "daily_k"],
108
+ style={
109
+ "risk_profile": "aggressive",
110
+ "holding_period": "short_term",
111
+ "execution_style": "breakout",
112
+ "market_regime": ["risk_on", "trend", "high_volume"],
113
+ "capital_profile": "high_liquidity",
114
+ "ui_badge": "突破",
115
+ },
116
+ data_requirements=["snapshot", "daily_k", "industry_context"],
117
+ notes=[
118
+ "适合从 `volume_breakout` 延伸,依赖 daily K-line 数据源稳定性。",
119
+ "上线前先运行 `doctor data-sources --strategy <name> --explain` 检查字段覆盖。",
120
+ ],
121
+ yaml_text="""# Momentum breakout template. Rename before use.
122
+ name: my_momentum_breakout
123
+ display_name: 我的放量突破
124
+ description: 成交量放大突破关键阻力位,趋势启动信号
125
+ version: "1.0"
126
+ category: trend
127
+ tags: [momentum, volume, breakout, daily_k]
128
+ style:
129
+ risk_profile: aggressive
130
+ holding_period: short_term
131
+ execution_style: breakout
132
+ market_regime: [risk_on, trend, high_volume]
133
+ capital_profile: high_liquidity
134
+ ui_badge: 突破
135
+
136
+ screening:
137
+ enabled: true
138
+ market_scope: [cn]
139
+ hard_filters:
140
+ exclude_st: true
141
+ amount_min: 100000000
142
+ turnover_rate_min: 3.0
143
+ volume_ratio_min: 2.0
144
+ change_pct_min: 2.0
145
+ change_pct_max: 9.9
146
+ require_price_above_ma20: true
147
+ signal_score_min: 60
148
+ macd_status_whitelist: [bullish, neutral]
149
+ breakout_20d_pct_min: -1.0
150
+ range_20d_pct_max: 35.0
151
+ volume_ratio_20d_min: 1.3
152
+ body_pct_min: 0.5
153
+ consolidation_days_20d_min: 8
154
+ tech_weight: 0.6
155
+ factor_weights:
156
+ momentum: 0.32
157
+ activity: 0.28
158
+ liquidity: 0.22
159
+ theme_heat: 0.08
160
+ stability: 0.10
161
+ scoring_profile:
162
+ momentum_chase_start_pct: 7.0
163
+ activity_ideal_volume_ratio: 3.0
164
+ activity_high_volume_ratio: 9.0
165
+ activity_ideal_turnover_rate: 6.0
166
+ stability_hot_change_pct: 8.8
167
+ risk_profile:
168
+ chase_change_pct: 9.8
169
+ abnormal_volume_ratio: 9.0
170
+ high_turnover_rate: 24.0
171
+ weak_signal_score: 45.0
172
+ scorecard_profile:
173
+ capital_confirmed_bonus: 2.2
174
+ volume_spike_ratio: 9.0
175
+ hot_money_activity_min: 96.0
176
+ hot_money_penalty: 1.4
177
+ ranking_hints: |
178
+ 优先关注:
179
+ 1. 突破前有明显横盘整理
180
+ 2. 量比和换手同步放大,日 K 信号仍健康
181
+ 3. 板块有联动效应更佳
182
+ max_output: 5
183
+ """,
184
+ ),
185
+ "oversold_reversal_snapshot": StrategyTemplate(
186
+ name="oversold_reversal_snapshot",
187
+ display_name="超跌修复",
188
+ description="只依赖 snapshot 的超跌修复模板,用于低数据依赖的反转候选",
189
+ category="reversal",
190
+ tags=["reversal", "oversold", "snapshot_only"],
191
+ style={
192
+ "risk_profile": "balanced",
193
+ "holding_period": "short_term",
194
+ "execution_style": "reversal",
195
+ "market_regime": ["oversold_repair", "range_bound"],
196
+ "capital_profile": "medium_liquidity",
197
+ "ui_badge": "反转",
198
+ },
199
+ data_requirements=["snapshot"],
200
+ notes=[
201
+ "适合数据源不稳定时的低依赖策略起点。",
202
+ "需要靠后续 LLM/scorecard/人工复核确认是否真的出现修复催化。",
203
+ ],
204
+ yaml_text="""# Oversold reversal template. Rename before use.
205
+ name: my_oversold_reversal
206
+ display_name: 我的超跌修复
207
+ description: 跌幅可控、流动性仍在、具备修复观察价值的反转候选
208
+ version: "1.0"
209
+ category: reversal
210
+ tags: [reversal, oversold, snapshot_only]
211
+ style:
212
+ risk_profile: balanced
213
+ holding_period: short_term
214
+ execution_style: reversal
215
+ market_regime: [oversold_repair, range_bound]
216
+ capital_profile: medium_liquidity
217
+ ui_badge: 反转
218
+
219
+ screening:
220
+ enabled: true
221
+ market_scope: [cn]
222
+ hard_filters:
223
+ exclude_st: true
224
+ amount_min: 60000000
225
+ price_min: 3
226
+ price_max: 120
227
+ pe_ttm_min: 0
228
+ pe_ttm_max: 80
229
+ pb_min: 0
230
+ pb_max: 8.0
231
+ turnover_rate_min: 1.0
232
+ change_pct_min: -8.0
233
+ change_pct_max: 1.5
234
+ tech_weight: 0.35
235
+ factor_weights:
236
+ reversal: 0.40
237
+ stability: 0.20
238
+ liquidity: 0.18
239
+ value: 0.16
240
+ activity: 0.06
241
+ scoring_profile:
242
+ reversal_ideal_change_pct: -3.5
243
+ reversal_collapse_start_pct: -8.5
244
+ reversal_chase_start_pct: 2.0
245
+ activity_ideal_turnover_rate: 3.0
246
+ risk_profile:
247
+ breakdown_change_pct: -8.5
248
+ chase_change_pct: 4.0
249
+ abnormal_volume_ratio: 5.5
250
+ scorecard_profile:
251
+ controlled_reversal_min: 72.0
252
+ controlled_reversal_bonus: 2.0
253
+ ranking_hints: |
254
+ 优先关注:
255
+ 1. 跌幅可控,不能是流动性枯竭的连续下跌
256
+ 2. 成交额仍然足够,后续有修复观察价值
257
+ 3. 避免基本面或监管风险明显的标的
258
+ max_output: 5
259
+ """,
260
+ ),
261
+ }
262
+
263
+
264
+ def list_strategy_templates() -> list[dict[str, object]]:
265
+ """Return available authoring templates without the full YAML body."""
266
+ return [
267
+ _template_payload(template, include_yaml=False)
268
+ for template in _TEMPLATES.values()
269
+ ]
270
+
271
+
272
+ def get_strategy_template(name: str, *, include_yaml: bool = True) -> dict[str, object]:
273
+ try:
274
+ template = _TEMPLATES[name]
275
+ except KeyError as exc:
276
+ available = ", ".join(_TEMPLATES)
277
+ raise ValueError(f"Strategy template '{name}' not found; available: {available}") from exc
278
+ return _template_payload(template, include_yaml=include_yaml)
279
+
280
+
281
+ def render_strategy_template(name: str) -> str:
282
+ return str(get_strategy_template(name, include_yaml=True)["yaml"])
283
+
284
+
285
+ def _template_payload(template: StrategyTemplate, *, include_yaml: bool) -> dict[str, object]:
286
+ payload = asdict(template)
287
+ if include_yaml:
288
+ payload["yaml"] = payload.pop("yaml_text")
289
+ else:
290
+ payload.pop("yaml_text", None)
291
+ return payload
alphasift/timeutil.py ADDED
@@ -0,0 +1,38 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Timestamps for saved runs and evaluations.
3
+
4
+ New timestamps carry the UTC offset, so a run created on one machine and
5
+ evaluated on another (or in CI) maps to the same exchange session. Older
6
+ files hold naive local times; those are read as the current machine's local
7
+ time, which is what they meant when written on the same machine.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from datetime import datetime, timezone
13
+
14
+ # Sort sentinel for missing or unparseable timestamps; aware, so it compares
15
+ # with parsed values.
16
+ MIN_TIMESTAMP = datetime.min.replace(tzinfo=timezone.utc)
17
+
18
+
19
+ def now_iso() -> str:
20
+ """Current local time with its UTC offset, e.g. ``2026-11-04T09:12:00+08:00``."""
21
+ return datetime.now().astimezone().isoformat()
22
+
23
+
24
+ def parse_timestamp(value: object) -> datetime | None:
25
+ """Parse an ISO timestamp into an aware datetime; naive values are local time."""
26
+ text = str(value or "").strip()
27
+ if text.endswith(("Z", "z")):
28
+ text = text[:-1] + "+00:00" # Python 3.10 fromisoformat rejects Z
29
+ try:
30
+ parsed = datetime.fromisoformat(text)
31
+ except (TypeError, ValueError):
32
+ return None
33
+ if parsed.tzinfo is None:
34
+ try:
35
+ parsed = parsed.astimezone()
36
+ except (OverflowError, OSError, ValueError):
37
+ parsed = parsed.replace(tzinfo=timezone.utc)
38
+ return parsed
@@ -0,0 +1,149 @@
1
+ # -*- coding: utf-8 -*-
2
+ """PE/PB for South Korean listings from Naver Finance.
3
+
4
+ The Yahoo screener (and Yahoo's per-ticker quote) carries no PE, PB, EPS or
5
+ book value for .KS/.KQ symbols, so valuation strategies could not run on KR.
6
+ Naver's mobile stock API reports trailing PER/PBR per listing and is
7
+ reachable from overseas servers. It is an unofficial endpoint: failures only
8
+ leave PE/PB empty and are reported in ``source_errors``.
9
+
10
+ Set ``ALPHASIFT_KR_VALUATION=0`` to skip it.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import logging
16
+ import os
17
+ import re
18
+ from concurrent.futures import ThreadPoolExecutor, as_completed
19
+ from concurrent.futures import TimeoutError as FuturesTimeout
20
+
21
+ import pandas as pd
22
+ import requests
23
+
24
+ logger = logging.getLogger(__name__)
25
+
26
+ _NAVER_INTEGRATION_URL = "https://m.stock.naver.com/api/stock/{code}/integration"
27
+ _HEADERS = {"User-Agent": "Mozilla/5.0 (alphasift)"}
28
+ # Naver display values: "9.68배", "1,234.5배", "-12.30배", "N/A".
29
+ _NUMBER_RE = re.compile(r"^\s*(-?\d{1,3}(?:,\d{3})*(?:\.\d+)?|-?\d+(?:\.\d+)?)\s*배?\s*$")
30
+ _DEFAULT_WORKERS = 8
31
+ _REQUEST_TIMEOUT = (5, 10)
32
+
33
+
34
+ def kr_valuation_enabled() -> bool:
35
+ return os.getenv("ALPHASIFT_KR_VALUATION", "1").strip().lower() not in {"0", "false", "off", "no"}
36
+
37
+
38
+ def enrich_kr_valuation(
39
+ df: pd.DataFrame,
40
+ *,
41
+ budget_seconds: float | None = 60.0,
42
+ fetch=None,
43
+ max_workers: int = _DEFAULT_WORKERS,
44
+ ) -> tuple[pd.DataFrame, list[str]]:
45
+ """Fill missing ``pe_ratio`` / ``pb_ratio`` on KR rows. Returns (frame, errors)."""
46
+ if df.empty or "code" not in df.columns:
47
+ return df, []
48
+ session = None
49
+ if fetch is None:
50
+ # One pooled session: a cold KR snapshot makes ~250 requests.
51
+ session = requests.Session()
52
+ adapter = requests.adapters.HTTPAdapter(pool_maxsize=max(1, int(max_workers)))
53
+ session.mount("https://", adapter)
54
+
55
+ def fetch(code: str) -> dict[str, float | None]:
56
+ return fetch_naver_valuation(code, session=session)
57
+
58
+ result = df.copy()
59
+ for column in ("pe_ratio", "pb_ratio"):
60
+ if column not in result.columns:
61
+ result[column] = None
62
+ missing = result["pe_ratio"].isna() | result["pb_ratio"].isna()
63
+ codes = [str(code) for code in result.loc[missing, "code"]]
64
+ if not codes:
65
+ result.attrs["valuation_coverage"] = 1.0
66
+ return result, []
67
+
68
+ values: dict[str, dict[str, float | None]] = {}
69
+ failures: list[str] = []
70
+ timed_out = 0
71
+ pool = ThreadPoolExecutor(max_workers=max(1, int(max_workers)))
72
+ futures = {pool.submit(fetch, _naver_code(code)): code for code in codes}
73
+ try:
74
+ for future in as_completed(futures, timeout=budget_seconds):
75
+ code = futures[future]
76
+ try:
77
+ values[code] = future.result()
78
+ except Exception as exc: # noqa: BLE001 - one listing failing is fine
79
+ failures.append(f"{code}: {exc}")
80
+ except FuturesTimeout:
81
+ timed_out = sum(1 for future in futures if not future.done())
82
+ finally:
83
+ # Queued requests are dropped; in-flight ones finish in the background
84
+ # (bounded by the request timeout) without holding up the snapshot.
85
+ pool.shutdown(wait=False, cancel_futures=True)
86
+ if session is not None:
87
+ session.close()
88
+
89
+ filled = 0
90
+ for idx in result.index[missing]:
91
+ item = values.get(str(result.at[idx, "code"]))
92
+ if not item:
93
+ continue
94
+ for column, key in (("pe_ratio", "per"), ("pb_ratio", "pbr")):
95
+ if pd.isna(result.at[idx, column]) and item.get(key) is not None:
96
+ result.at[idx, column] = item[key]
97
+ filled += 1
98
+
99
+ # Coverage counts listings that got a usable ratio, not HTTP successes:
100
+ # a changed payload returning N/A everywhere must not look complete.
101
+ # PBR is present for nearly every listing; PER is absent for losses.
102
+ usable = sum(
103
+ 1 for item in values.values() if item and (item.get("per") is not None or item.get("pbr") is not None)
104
+ )
105
+ result.attrs["valuation_coverage"] = round(usable / len(codes), 4)
106
+
107
+ errors: list[str] = []
108
+ if failures:
109
+ errors.append(
110
+ f"naver_valuation failed for {len(failures)}/{len(codes)} KR listings: "
111
+ + "; ".join(failures[:3])
112
+ )
113
+ if values and not usable:
114
+ errors.append(f"naver_valuation: no PER/PBR in {len(values)} responses (payload format changed?)")
115
+ if timed_out:
116
+ errors.append(f"naver_valuation exceeded {budget_seconds:.0f}s budget; {timed_out} listings left without PE/PB")
117
+ logger.info("Naver valuation: %d/%d KR listings, %d fields filled", len(values), len(codes), filled)
118
+ return result, errors
119
+
120
+
121
+ def fetch_naver_valuation(code: str, *, session: requests.Session | None = None) -> dict[str, float | None]:
122
+ """Trailing PER / PBR for one KRX code (``005930``)."""
123
+ client = session or requests
124
+ response = client.get(
125
+ _NAVER_INTEGRATION_URL.format(code=code), headers=_HEADERS, timeout=_REQUEST_TIMEOUT
126
+ )
127
+ response.raise_for_status()
128
+ payload = response.json()
129
+ infos = payload.get("totalInfos") if isinstance(payload, dict) else None
130
+ if not isinstance(infos, list):
131
+ raise ValueError(f"unexpected Naver payload: {str(payload)[:80]}")
132
+ by_code = {str(item.get("code")): item.get("value") for item in infos if isinstance(item, dict)}
133
+ return {"per": parse_naver_number(by_code.get("per")), "pbr": parse_naver_number(by_code.get("pbr"))}
134
+
135
+
136
+ def parse_naver_number(value: object) -> float | None:
137
+ """Parse Naver display values like ``9.68배`` or ``1,234.5배``.
138
+
139
+ N/A, dashes, anything else and an exact 0 (no ratio) -> None.
140
+ """
141
+ match = _NUMBER_RE.match(str(value or ""))
142
+ if not match:
143
+ return None
144
+ number = float(match.group(1).replace(",", ""))
145
+ return number if number != 0 else None
146
+
147
+
148
+ def _naver_code(symbol: str) -> str:
149
+ return str(symbol).split(".", 1)[0].strip().upper()