stock-analysis-plugin 0.2.5 → 0.2.7
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.
- package/README.md +126 -15
- package/package.json +2 -1
- package/pi/index.ts +918 -72
- package/schemas/market_review_schema.json +12 -5
- package/schemas/report_schema.json +68 -4
- package/scripts/cli-timeout.mjs +27 -0
- package/scripts/json-input.mjs +26 -0
- package/scripts/setup-python.mjs +6 -6
- package/skills/bull-trend/SKILL.md +34 -10
- package/skills/bull-trend/references/fat-tails.md +91 -0
- package/skills/bull-trend/scripts/tail_analysis.py +132 -0
- package/skills/event-driven/SKILL.md +6 -0
- package/skills/growth-quality/SKILL.md +6 -0
- package/skills/market-review/SKILL.md +2 -0
- package/skills/stock-analysis/SKILL.md +25 -5
- package/skills/stock-analysis/references/stateless-analysis.md +66 -0
- package/skills/stock-screener/SKILL.md +7 -1
- package/skills/strategy-backtest/SKILL.md +13 -0
- package/skills/wisburg-research/SKILL.md +2 -0
- package/templates/market_review/full.md.j2 +7 -0
- package/templates/stock_analysis/_evidence.md.j2 +11 -0
- package/templates/stock_analysis/brief.md.j2 +6 -1
- package/templates/stock_analysis/full.md.j2 +8 -3
- package/tools/_subproc.py +66 -11
- package/tools/alert_rules.py +32 -4
- package/tools/backtest.py +95 -18
- package/tools/capabilities.py +11 -0
- package/tools/cli_budgets.json +26 -0
- package/tools/gather.py +24 -16
- package/tools/lixinger.py +100 -0
- package/tools/market_regime.py +7 -3
- package/tools/market_review.py +37 -15
- package/tools/position_context.py +20 -2
- package/tools/report_renderer.py +2 -0
- package/tools/risk_screening.py +45 -17
- package/tools/screener.py +74 -24
- package/tools/sec_edgar.py +346 -0
- package/tools/sec_holders.py +263 -0
- package/tools/signal_tracker.py +218 -24
- package/tools/stateless_analysis.py +630 -0
- package/tools/stock_data.py +170 -32
- package/tools/technical.py +16 -2
- package/tools/value_data.py +159 -0
- package/tools/watchlist.py +24 -1
- package/tools/watchlist_context.py +25 -10
|
@@ -6,6 +6,7 @@ Not a portfolio system. Stateless: user passes cost/quantity/stops each call.
|
|
|
6
6
|
|
|
7
7
|
import argparse
|
|
8
8
|
import json
|
|
9
|
+
import math
|
|
9
10
|
import sys
|
|
10
11
|
from datetime import datetime, timezone
|
|
11
12
|
from pathlib import Path
|
|
@@ -48,13 +49,28 @@ def analyze_position(
|
|
|
48
49
|
stop_loss: float | None = None,
|
|
49
50
|
take_profit: float | None = None,
|
|
50
51
|
) -> dict:
|
|
52
|
+
for field, value in (
|
|
53
|
+
("cost", cost),
|
|
54
|
+
("quantity", quantity),
|
|
55
|
+
("stop_loss", stop_loss),
|
|
56
|
+
("take_profit", take_profit),
|
|
57
|
+
):
|
|
58
|
+
if value is not None and (not isinstance(value, (int, float)) or not math.isfinite(value) or value <= 0):
|
|
59
|
+
return {"symbol": symbol, "error": f"{field} must be finite and positive"}
|
|
51
60
|
quote = _run_json("stock_data.py", ["quote", symbol]) or {}
|
|
52
61
|
tech = _run_json("technical.py", ["analyze", symbol, "--period", "daily", "--count", "60"]) or {}
|
|
53
62
|
|
|
54
|
-
price = quote.get("price")
|
|
63
|
+
price = quote.get("price") if isinstance(quote, dict) and "error" not in quote else None
|
|
55
64
|
if price is None:
|
|
56
65
|
return {"symbol": symbol, "error": "cannot fetch current price"}
|
|
57
|
-
|
|
66
|
+
try:
|
|
67
|
+
price = float(price)
|
|
68
|
+
except (TypeError, ValueError):
|
|
69
|
+
return {"symbol": symbol, "error": "current price must be finite and positive"}
|
|
70
|
+
if not math.isfinite(price) or price <= 0:
|
|
71
|
+
return {"symbol": symbol, "error": "current price must be finite and positive"}
|
|
72
|
+
if not isinstance(tech, dict):
|
|
73
|
+
tech = {}
|
|
58
74
|
|
|
59
75
|
pnl_per_share = price - cost
|
|
60
76
|
pnl_pct = (pnl_per_share / cost * 100) if cost else 0.0
|
|
@@ -133,6 +149,8 @@ def main():
|
|
|
133
149
|
)
|
|
134
150
|
json.dump(result, sys.stdout, ensure_ascii=False, indent=2, default=str)
|
|
135
151
|
print()
|
|
152
|
+
if "error" in result:
|
|
153
|
+
sys.exit(1)
|
|
136
154
|
|
|
137
155
|
|
|
138
156
|
if __name__ == "__main__":
|
package/tools/report_renderer.py
CHANGED
package/tools/risk_screening.py
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
|
|
4
4
|
import argparse
|
|
5
5
|
import json
|
|
6
|
+
import math
|
|
6
7
|
import os
|
|
7
8
|
import sys
|
|
8
9
|
from concurrent.futures import ThreadPoolExecutor
|
|
@@ -19,7 +20,7 @@ def _safe_float(val) -> float | None:
|
|
|
19
20
|
return None
|
|
20
21
|
try:
|
|
21
22
|
v = float(val)
|
|
22
|
-
return v if v
|
|
23
|
+
return v if math.isfinite(v) else None
|
|
23
24
|
except (ValueError, TypeError):
|
|
24
25
|
return None
|
|
25
26
|
|
|
@@ -29,9 +30,12 @@ def _safe_float(val) -> float | None:
|
|
|
29
30
|
|
|
30
31
|
def check_valuation(symbol: str) -> dict:
|
|
31
32
|
quote = _run_tool("stock_data.py", ["quote", symbol]) or {}
|
|
33
|
+
if not isinstance(quote, dict) or "error" in quote:
|
|
34
|
+
quote = {}
|
|
32
35
|
pe = _safe_float(quote.get("pe"))
|
|
33
36
|
pb = _safe_float(quote.get("pb"))
|
|
34
|
-
|
|
37
|
+
available = pe is not None or pb is not None
|
|
38
|
+
result = {"pe": pe, "pb": pb, "status": "normal" if available else "unknown", "flags": [], "available": available}
|
|
35
39
|
|
|
36
40
|
if pe is not None:
|
|
37
41
|
if pe < 0:
|
|
@@ -91,14 +95,15 @@ def check_valuation(symbol: str) -> dict:
|
|
|
91
95
|
|
|
92
96
|
def check_technical(symbol: str) -> dict:
|
|
93
97
|
ta = _run_tool("technical.py", ["analyze", symbol])
|
|
94
|
-
result = {"flags": []}
|
|
98
|
+
result = {"flags": [], "available": False}
|
|
95
99
|
|
|
96
|
-
if not ta or "error" in ta:
|
|
100
|
+
if not isinstance(ta, dict) or not ta or "error" in ta:
|
|
97
101
|
return result
|
|
98
102
|
|
|
99
103
|
signal = ta.get("buy_signal", "")
|
|
100
104
|
score = _safe_float(ta.get("signal_score"))
|
|
101
|
-
|
|
105
|
+
result["available"] = score is not None
|
|
106
|
+
trend = (ta.get("trend") or {}).get("overall", "")
|
|
102
107
|
|
|
103
108
|
if signal in ("STRONG_SELL",):
|
|
104
109
|
result["flags"].append(
|
|
@@ -130,7 +135,7 @@ def check_technical(symbol: str) -> dict:
|
|
|
130
135
|
)
|
|
131
136
|
|
|
132
137
|
macd = ta.get("macd", {})
|
|
133
|
-
if macd.get("
|
|
138
|
+
if macd.get("cross") == "death_cross":
|
|
134
139
|
result["flags"].append(
|
|
135
140
|
{"category": "technical", "severity": "medium", "description": "MACD死叉", "source": "data"}
|
|
136
141
|
)
|
|
@@ -145,15 +150,27 @@ def check_technical(symbol: str) -> dict:
|
|
|
145
150
|
|
|
146
151
|
|
|
147
152
|
def check_lockup(symbol: str) -> dict:
|
|
148
|
-
result =
|
|
153
|
+
result = _run_tool("risk_screening.py", ["lockup", symbol], timeout=25)
|
|
154
|
+
return (
|
|
155
|
+
result
|
|
156
|
+
if isinstance(result, dict) and "error" not in result
|
|
157
|
+
else {"upcoming_30d": [], "flags": [], "available": False}
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _fetch_lockup(symbol: str) -> dict:
|
|
162
|
+
result = {"upcoming_30d": [], "flags": [], "available": False}
|
|
149
163
|
try:
|
|
150
164
|
import akshare as ak
|
|
151
165
|
|
|
152
166
|
df = ak.stock_restricted_release_queue_em(symbol=symbol)
|
|
153
|
-
if df is None
|
|
167
|
+
if df is None:
|
|
168
|
+
return result
|
|
169
|
+
result["available"] = True
|
|
170
|
+
if df.empty:
|
|
154
171
|
return result
|
|
155
172
|
|
|
156
|
-
now = datetime.now()
|
|
173
|
+
now = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
|
|
157
174
|
cutoff = now + timedelta(days=30)
|
|
158
175
|
|
|
159
176
|
date_col = None
|
|
@@ -180,7 +197,7 @@ def check_lockup(symbol: str) -> dict:
|
|
|
180
197
|
}
|
|
181
198
|
)
|
|
182
199
|
except Exception:
|
|
183
|
-
|
|
200
|
+
result["available"] = False
|
|
184
201
|
return result
|
|
185
202
|
|
|
186
203
|
|
|
@@ -195,7 +212,7 @@ def check_news_risks(symbol: str, name: str = "") -> dict:
|
|
|
195
212
|
"regulatory": f"{search_name} 处罚 违规 监管 立案",
|
|
196
213
|
"industry": f"{search_name} 行业政策 监管 限制",
|
|
197
214
|
}
|
|
198
|
-
result = {"flags": []}
|
|
215
|
+
result = {"flags": [], "available": True}
|
|
199
216
|
# four independent search_intel subprocesses — fan out concurrently (same
|
|
200
217
|
# ThreadPoolExecutor pattern as gather._run_all); iterating `futures` in
|
|
201
218
|
# declaration order keeps result keys and flags stably ordered
|
|
@@ -209,8 +226,10 @@ def check_news_risks(symbol: str, name: str = "") -> dict:
|
|
|
209
226
|
items = []
|
|
210
227
|
if isinstance(data, list):
|
|
211
228
|
items = data
|
|
212
|
-
elif isinstance(data, dict) and "
|
|
229
|
+
elif isinstance(data, dict) and "error" not in data and isinstance(data.get("results"), list):
|
|
213
230
|
items = data["results"]
|
|
231
|
+
else:
|
|
232
|
+
result["available"] = False
|
|
214
233
|
|
|
215
234
|
result[cat] = items
|
|
216
235
|
if items:
|
|
@@ -265,7 +284,7 @@ def screen_risk(symbol: str, name: str = "") -> dict:
|
|
|
265
284
|
checks = {}
|
|
266
285
|
|
|
267
286
|
val = check_valuation(symbol)
|
|
268
|
-
checks["valuation"] = {
|
|
287
|
+
checks["valuation"] = {k: val[k] for k in ("pe", "pb", "status", "available")}
|
|
269
288
|
all_flags.extend(val["flags"])
|
|
270
289
|
|
|
271
290
|
tech = check_technical(symbol)
|
|
@@ -273,11 +292,12 @@ def screen_risk(symbol: str, name: str = "") -> dict:
|
|
|
273
292
|
"buy_signal": tech.get("buy_signal"),
|
|
274
293
|
"signal_score": tech.get("signal_score"),
|
|
275
294
|
"trend": tech.get("trend"),
|
|
295
|
+
"available": tech["available"],
|
|
276
296
|
}
|
|
277
297
|
all_flags.extend(tech["flags"])
|
|
278
298
|
|
|
279
299
|
lockup = check_lockup(symbol)
|
|
280
|
-
checks["lockup"] = {"upcoming_30d": lockup["upcoming_30d"]}
|
|
300
|
+
checks["lockup"] = {"upcoming_30d": lockup["upcoming_30d"], "available": lockup["available"]}
|
|
281
301
|
all_flags.extend(lockup["flags"])
|
|
282
302
|
|
|
283
303
|
news = check_news_risks(symbol, name)
|
|
@@ -285,12 +305,16 @@ def screen_risk(symbol: str, name: str = "") -> dict:
|
|
|
285
305
|
all_flags.extend(news["flags"])
|
|
286
306
|
|
|
287
307
|
risk = compute_risk(all_flags)
|
|
308
|
+
missing = [key for key, value in checks.items() if not value.get("available")]
|
|
309
|
+
complete = not missing
|
|
288
310
|
return {
|
|
289
311
|
"symbol": symbol,
|
|
290
312
|
"name": name,
|
|
291
|
-
"risk_level": risk["risk_level"],
|
|
292
|
-
"risk_score": risk["risk_score"],
|
|
293
|
-
"veto_buy": risk["veto_buy"],
|
|
313
|
+
"risk_level": "unknown" if missing and risk["risk_level"] == "low" else risk["risk_level"],
|
|
314
|
+
"risk_score": risk["risk_score"] if all_flags or complete else None,
|
|
315
|
+
"veto_buy": risk["veto_buy"] if risk["veto_buy"] or complete else None,
|
|
316
|
+
"data_complete": complete,
|
|
317
|
+
"warnings": [f"{key} risk data unavailable or incomplete" for key in missing],
|
|
294
318
|
"flags": all_flags,
|
|
295
319
|
"checks": checks,
|
|
296
320
|
}
|
|
@@ -303,6 +327,8 @@ def main():
|
|
|
303
327
|
p_screen = sub.add_parser("screen")
|
|
304
328
|
p_screen.add_argument("symbol")
|
|
305
329
|
p_screen.add_argument("--name", default="")
|
|
330
|
+
p_lockup = sub.add_parser("lockup", help="Internal bounded lockup query")
|
|
331
|
+
p_lockup.add_argument("symbol")
|
|
306
332
|
|
|
307
333
|
args = parser.parse_args()
|
|
308
334
|
if not args.command:
|
|
@@ -312,6 +338,8 @@ def main():
|
|
|
312
338
|
if args.command == "screen":
|
|
313
339
|
result = screen_risk(args.symbol, args.name)
|
|
314
340
|
print(json.dumps(result, ensure_ascii=False, default=str))
|
|
341
|
+
elif args.command == "lockup":
|
|
342
|
+
print(json.dumps(_fetch_lockup(args.symbol), ensure_ascii=False, default=str))
|
|
315
343
|
|
|
316
344
|
|
|
317
345
|
if __name__ == "__main__":
|
package/tools/screener.py
CHANGED
|
@@ -18,7 +18,7 @@ import yaml
|
|
|
18
18
|
|
|
19
19
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
20
20
|
|
|
21
|
-
from _subproc import run_tool, utf8_stdio
|
|
21
|
+
from _subproc import command_timeout, run_tool, utf8_stdio
|
|
22
22
|
from market_review import calc_temperature
|
|
23
23
|
from stock_data import compute_market_stats
|
|
24
24
|
|
|
@@ -35,6 +35,8 @@ DEFAULT_FILTERS = {
|
|
|
35
35
|
"volume_ratio_min": 0.5,
|
|
36
36
|
}
|
|
37
37
|
|
|
38
|
+
L1_WEIGHTS = {"value": 0.4, "momentum": 0.3, "liquidity": 0.3}
|
|
39
|
+
|
|
38
40
|
L2_WEIGHTS = {
|
|
39
41
|
"value": 0.15,
|
|
40
42
|
"quality": 0.20,
|
|
@@ -48,15 +50,17 @@ L2_WEIGHTS = {
|
|
|
48
50
|
_INDEX_REGION = {"A": "cn", "HK": "hk", "US": "us"}
|
|
49
51
|
|
|
50
52
|
|
|
51
|
-
def _fetch_json(args: list[str], timeout: int =
|
|
52
|
-
"""
|
|
53
|
-
return run_tool("stock_data.py", args, timeout=timeout)
|
|
53
|
+
def _fetch_json(args: list[str], timeout: int | None = None) -> dict | list | None:
|
|
54
|
+
"""Fetch JSON with the shared command budget and preserve structured failures."""
|
|
55
|
+
return run_tool("stock_data.py", args, timeout=timeout, preserve_errors=True)
|
|
54
56
|
|
|
55
57
|
|
|
56
58
|
def fetch_snapshot(market: str) -> list:
|
|
57
59
|
# a cold full-market snapshot can exceed 30s (CI runners) — allow longer; with
|
|
58
60
|
# all eastmoney/sina legs timing out, the tencent fallback leg needs ~2min more
|
|
59
|
-
return _fetch_json(
|
|
61
|
+
return _fetch_json(
|
|
62
|
+
["market_snapshot", "--market", market], timeout=command_timeout("stock_data.py", ["market_snapshot"])
|
|
63
|
+
)
|
|
60
64
|
|
|
61
65
|
|
|
62
66
|
def load_config(path: str) -> dict:
|
|
@@ -106,9 +110,10 @@ def apply_filters(df: pd.DataFrame, filters: dict) -> pd.DataFrame:
|
|
|
106
110
|
|
|
107
111
|
|
|
108
112
|
def _minmax(s: pd.Series) -> pd.Series:
|
|
113
|
+
s = s.where(np.isfinite(s))
|
|
109
114
|
mn, mx = s.min(), s.max()
|
|
110
115
|
if mx == mn:
|
|
111
|
-
return pd.Series(50.0, index=s.index)
|
|
116
|
+
return pd.Series(50.0, index=s.index).where(s.notna())
|
|
112
117
|
return ((s - mn) / (mx - mn) * 100).clip(0, 100)
|
|
113
118
|
|
|
114
119
|
|
|
@@ -131,7 +136,7 @@ def compute_scores(df: pd.DataFrame) -> pd.DataFrame:
|
|
|
131
136
|
if "dividend_yield" in df.columns:
|
|
132
137
|
df["dividend_score"] = _minmax(df["dividend_yield"])
|
|
133
138
|
value_parts.append(df["dividend_score"])
|
|
134
|
-
df["value_score"] = pd.concat(value_parts, axis=1).mean(axis=1) if value_parts else
|
|
139
|
+
df["value_score"] = pd.concat(value_parts, axis=1).mean(axis=1) if value_parts else np.nan
|
|
135
140
|
|
|
136
141
|
# Momentum: higher change_pct and volume_ratio → higher score
|
|
137
142
|
mom_parts = []
|
|
@@ -139,7 +144,7 @@ def compute_scores(df: pd.DataFrame) -> pd.DataFrame:
|
|
|
139
144
|
mom_parts.append(_minmax(df["change_pct"]))
|
|
140
145
|
if "volume_ratio" in df.columns:
|
|
141
146
|
mom_parts.append(_minmax(df["volume_ratio"]))
|
|
142
|
-
df["momentum_score"] =
|
|
147
|
+
df["momentum_score"] = pd.concat(mom_parts, axis=1).mean(axis=1) if mom_parts else np.nan
|
|
143
148
|
|
|
144
149
|
# Liquidity: higher turnover_rate and volume → higher score
|
|
145
150
|
liq_parts = []
|
|
@@ -147,9 +152,11 @@ def compute_scores(df: pd.DataFrame) -> pd.DataFrame:
|
|
|
147
152
|
liq_parts.append(_minmax(df["turnover_rate"]))
|
|
148
153
|
if "volume" in df.columns:
|
|
149
154
|
liq_parts.append(_minmax(df["volume"].astype(float)))
|
|
150
|
-
df["liquidity_score"] =
|
|
155
|
+
df["liquidity_score"] = pd.concat(liq_parts, axis=1).mean(axis=1) if liq_parts else np.nan
|
|
151
156
|
|
|
152
|
-
|
|
157
|
+
groups = df[[f"{group}_score" for group in L1_WEIGHTS]].rename(columns=lambda name: name.removesuffix("_score"))
|
|
158
|
+
weights = pd.Series(L1_WEIGHTS)
|
|
159
|
+
df["composite_score"] = groups.mul(weights).sum(axis=1, min_count=1) / groups.notna().mul(weights).sum(axis=1)
|
|
153
160
|
return df
|
|
154
161
|
|
|
155
162
|
|
|
@@ -298,8 +305,9 @@ def _apply_l2(candidates: list, market: str, multiplier: float) -> None:
|
|
|
298
305
|
scores = c["scores"]
|
|
299
306
|
# scores are sanitized to None when non-finite; L2 math needs numbers
|
|
300
307
|
components = {
|
|
301
|
-
|
|
302
|
-
"
|
|
308
|
+
group: scores[group]
|
|
309
|
+
for group in ("value", "liquidity")
|
|
310
|
+
if group in c["factor_coverage"]["available"] and scores[group] is not None
|
|
303
311
|
}
|
|
304
312
|
# momentum is L2-only: candidates without kline factors drop the group and renormalize weights.
|
|
305
313
|
components.update(
|
|
@@ -309,25 +317,35 @@ def _apply_l2(candidates: list, market: str, multiplier: float) -> None:
|
|
|
309
317
|
{g: round(groups[g], 1) for g in ("quality", "growth", "moneyflow", "low_volatility") if g in groups}
|
|
310
318
|
)
|
|
311
319
|
total_weight = sum(L2_WEIGHTS[g] for g in components)
|
|
312
|
-
composite_l2 = sum(L2_WEIGHTS[g] * components[g] for g in components) / total_weight
|
|
313
|
-
scores["final"] = round(composite_l2 * multiplier, 1)
|
|
320
|
+
composite_l2 = sum(L2_WEIGHTS[g] * components[g] for g in components) / total_weight if total_weight else None
|
|
321
|
+
scores["final"] = round(composite_l2 * multiplier, 1) if composite_l2 is not None else None
|
|
322
|
+
c["factor_coverage"] = {
|
|
323
|
+
"available": list(components),
|
|
324
|
+
"missing": [g for g in L2_WEIGHTS if g not in components],
|
|
325
|
+
"ratio": round(total_weight, 4),
|
|
326
|
+
"effective_weights": {g: L2_WEIGHTS[g] / total_weight for g in components},
|
|
327
|
+
"effective_scores": components,
|
|
328
|
+
}
|
|
314
329
|
|
|
315
330
|
|
|
316
331
|
def screen(market: str, top: int, config: dict | None, l2: bool = False) -> dict:
|
|
332
|
+
if isinstance(top, bool) or not isinstance(top, int) or top <= 0:
|
|
333
|
+
return {"error": "top must be a positive integer", "market": market}
|
|
334
|
+
if config is not None and (not isinstance(config, dict) or not isinstance(config.get("filters", {}), dict)):
|
|
335
|
+
return {"error": "config and filters must be objects", "market": market}
|
|
317
336
|
filters = merge_filters(config)
|
|
337
|
+
supported = set(DEFAULT_FILTERS) | {"dividend_yield_min", "dividend_yield_max"}
|
|
338
|
+
for key, value in filters.items():
|
|
339
|
+
if key not in supported:
|
|
340
|
+
return {"error": f"Unsupported filter: {key}", "market": market}
|
|
341
|
+
if isinstance(value, bool) or not isinstance(value, (int, float)) or not np.isfinite(value):
|
|
342
|
+
return {"error": f"{key} must be a finite number", "market": market}
|
|
318
343
|
dividend_requested = any(k.startswith("dividend_yield_") for k in filters) or (config or {}).get("sort_by") in (
|
|
319
344
|
"dividend_yield",
|
|
320
345
|
"dividend_score",
|
|
321
346
|
)
|
|
322
347
|
if dividend_requested and market not in ("A", "HK"):
|
|
323
348
|
return {"error": "dividend screening currently covers A/HK only", "market": market}
|
|
324
|
-
for key in ("dividend_yield_min", "dividend_yield_max"):
|
|
325
|
-
if key in filters and (
|
|
326
|
-
isinstance(filters[key], bool)
|
|
327
|
-
or not isinstance(filters[key], (int, float))
|
|
328
|
-
or not np.isfinite(filters[key])
|
|
329
|
-
):
|
|
330
|
-
return {"error": f"{key} must be a finite number in percent units", "market": market}
|
|
331
349
|
raw = fetch_snapshot(market)
|
|
332
350
|
if isinstance(raw, dict) and "error" in raw:
|
|
333
351
|
return raw
|
|
@@ -378,6 +396,11 @@ def screen(market: str, top: int, config: dict | None, l2: bool = False) -> dict
|
|
|
378
396
|
"error": "dividend data unavailable; requested dividend criterion was not applied",
|
|
379
397
|
"market": market,
|
|
380
398
|
}
|
|
399
|
+
explicit = (config or {}).get("filters") or {}
|
|
400
|
+
missing = [key for key in explicit if key.rsplit("_", 1)[0] not in df]
|
|
401
|
+
if missing:
|
|
402
|
+
return {"error": f"Requested filter data unavailable: {', '.join(missing)}", "market": market}
|
|
403
|
+
applied_filters = {key: value for key, value in filters.items() if key.rsplit("_", 1)[0] in df}
|
|
381
404
|
df = apply_filters(df, filters)
|
|
382
405
|
filtered_count = len(df)
|
|
383
406
|
|
|
@@ -387,7 +410,7 @@ def screen(market: str, top: int, config: dict | None, l2: bool = False) -> dict
|
|
|
387
410
|
"total_stocks": total,
|
|
388
411
|
"filtered_count": 0,
|
|
389
412
|
"returned_count": 0,
|
|
390
|
-
"filters_applied":
|
|
413
|
+
"filters_applied": applied_filters,
|
|
391
414
|
"candidates": [],
|
|
392
415
|
"market_sentiment": sentiment,
|
|
393
416
|
"l2_enabled": l2_enabled,
|
|
@@ -437,11 +460,36 @@ def screen(market: str, top: int, config: dict | None, l2: bool = False) -> dict
|
|
|
437
460
|
}
|
|
438
461
|
if "dividend_score" in row:
|
|
439
462
|
entry["scores"]["dividend"] = _finite(round(float(row["dividend_score"]), 1))
|
|
463
|
+
factor_inputs = {
|
|
464
|
+
"value": ("pe", "pb", "dividend_yield"),
|
|
465
|
+
"momentum": ("change_pct", "volume_ratio"),
|
|
466
|
+
"liquidity": ("turnover_rate", "volume"),
|
|
467
|
+
}
|
|
468
|
+
weights = L1_WEIGHTS
|
|
469
|
+
available = [
|
|
470
|
+
g
|
|
471
|
+
for g, fields in factor_inputs.items()
|
|
472
|
+
if entry["scores"][g] is not None and any(field in entry for field in fields)
|
|
473
|
+
]
|
|
474
|
+
for group in weights:
|
|
475
|
+
if group not in available:
|
|
476
|
+
entry["scores"][group] = None
|
|
477
|
+
if not available:
|
|
478
|
+
entry["scores"]["composite"] = entry["scores"]["final"] = None
|
|
479
|
+
total_weight = sum(weights[g] for g in available)
|
|
480
|
+
entry["factor_coverage"] = {
|
|
481
|
+
"available": available,
|
|
482
|
+
"missing": [g for g in weights if g not in available],
|
|
483
|
+
"ratio": round(total_weight, 4),
|
|
484
|
+
"effective_weights": {g: weights[g] / total_weight for g in available},
|
|
485
|
+
}
|
|
440
486
|
candidates.append(entry)
|
|
441
487
|
|
|
442
488
|
if l2_enabled:
|
|
443
489
|
_apply_l2(candidates, market, multiplier)
|
|
444
|
-
candidates.sort(
|
|
490
|
+
candidates.sort(
|
|
491
|
+
key=lambda c: c["scores"]["final"] if c["scores"]["final"] is not None else -float("inf"), reverse=True
|
|
492
|
+
)
|
|
445
493
|
for rank, entry in enumerate(candidates, 1):
|
|
446
494
|
entry["rank"] = rank
|
|
447
495
|
|
|
@@ -450,7 +498,7 @@ def screen(market: str, top: int, config: dict | None, l2: bool = False) -> dict
|
|
|
450
498
|
"total_stocks": total,
|
|
451
499
|
"filtered_count": filtered_count,
|
|
452
500
|
"returned_count": len(candidates),
|
|
453
|
-
"filters_applied":
|
|
501
|
+
"filters_applied": applied_filters,
|
|
454
502
|
"candidates": candidates,
|
|
455
503
|
"market_sentiment": sentiment,
|
|
456
504
|
"l2_enabled": l2_enabled,
|
|
@@ -478,6 +526,8 @@ def main():
|
|
|
478
526
|
config = load_config(args.config) if args.config else None
|
|
479
527
|
result = screen(args.market, args.top, config, l2=args.l2)
|
|
480
528
|
print(json.dumps(result, ensure_ascii=False, default=str))
|
|
529
|
+
if "error" in result:
|
|
530
|
+
sys.exit(1)
|
|
481
531
|
|
|
482
532
|
|
|
483
533
|
if __name__ == "__main__":
|