@weaxs/openclaw-stock-analysis 0.2.5 → 0.2.6
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/dist/index.js +61 -10
- package/index.ts +65 -10
- package/openclaw.plugin.json +4 -1
- package/package.json +1 -1
- package/schemas/report_schema.json +3 -3
- 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 +2 -0
- package/skills/growth-quality/SKILL.md +2 -0
- package/skills/stock-analysis/SKILL.md +9 -3
- package/skills/stock-screener/SKILL.md +2 -0
- package/skills/strategy-backtest/SKILL.md +4 -0
- package/skills/wisburg-research/SKILL.md +2 -0
- package/templates/stock_analysis/brief.md.j2 +4 -1
- package/templates/stock_analysis/full.md.j2 +6 -3
- package/tools/alert_rules.py +32 -4
- package/tools/backtest.py +22 -4
- package/tools/capabilities.py +3 -0
- package/tools/gather.py +20 -10
- package/tools/lixinger.py +100 -0
- package/tools/market_regime.py +7 -3
- package/tools/market_review.py +7 -6
- 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 +17 -9
- package/tools/sec_edgar.py +346 -0
- package/tools/sec_holders.py +263 -0
- package/tools/signal_tracker.py +142 -19
- package/tools/stock_data.py +80 -17
- package/tools/technical.py +16 -2
- package/tools/value_data.py +159 -0
- package/tools/watchlist.py +24 -1
- package/tools/watchlist_context.py +7 -3
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"""Optional Lixinger HK non-financial datasets (same env token as index data)."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
from datetime import date, timedelta
|
|
5
|
+
|
|
6
|
+
import requests
|
|
7
|
+
from _cache import DAY, cached
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def hk_data(symbol, dataset, metrics):
|
|
11
|
+
code = symbol.split(".")[0].zfill(5)
|
|
12
|
+
end = date.today()
|
|
13
|
+
try:
|
|
14
|
+
start = end.replace(year=end.year - 10)
|
|
15
|
+
except ValueError:
|
|
16
|
+
start = end.replace(year=end.year - 10, day=28) + timedelta(days=1)
|
|
17
|
+
|
|
18
|
+
def fetch():
|
|
19
|
+
response = requests.post(
|
|
20
|
+
f"https://open.lixinger.com/api/hk/company/{dataset}/non_financial",
|
|
21
|
+
json={
|
|
22
|
+
"token": os.environ["LIXINGER_TOKEN"],
|
|
23
|
+
"stockCodes": [code],
|
|
24
|
+
"startDate": start.isoformat(),
|
|
25
|
+
"endDate": end.isoformat(),
|
|
26
|
+
"metricsList": metrics,
|
|
27
|
+
},
|
|
28
|
+
timeout=20,
|
|
29
|
+
)
|
|
30
|
+
response.raise_for_status()
|
|
31
|
+
payload = response.json()
|
|
32
|
+
if payload.get("code") != 1 or not isinstance(payload.get("data"), list) or not payload["data"]:
|
|
33
|
+
raise ValueError("Lixinger HK non-financial data unavailable; check token permissions/company type")
|
|
34
|
+
return payload["data"]
|
|
35
|
+
|
|
36
|
+
return cached(f"lixinger-hk:{dataset}:{code}:{end}:{','.join(metrics)}", DAY, fetch)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def financials_hk(symbol, periods, annual):
|
|
40
|
+
fields = {
|
|
41
|
+
"roe": "m.roe",
|
|
42
|
+
"gross_margin": "ps.gp_m",
|
|
43
|
+
"net_profit_margin": "ps.np_s_r",
|
|
44
|
+
"total_revenue": "ps.toi",
|
|
45
|
+
"net_income": "ps.np",
|
|
46
|
+
"operating_cash_flow": "cfs.ncffoa",
|
|
47
|
+
}
|
|
48
|
+
data = hk_data(symbol, "fs", [f"q.{field}.t" for field in fields.values()])
|
|
49
|
+
history = []
|
|
50
|
+
for row in sorted(data, key=lambda r: r.get("date", ""), reverse=True):
|
|
51
|
+
if annual and row.get("reportType") != "annual_report":
|
|
52
|
+
continue
|
|
53
|
+
if not row.get("date") or row.get("stockCode", symbol.split(".")[0].zfill(5)) != symbol.split(".")[0].zfill(5):
|
|
54
|
+
continue
|
|
55
|
+
entry = {
|
|
56
|
+
"report_date": row["date"][:10],
|
|
57
|
+
"disclosure_date": (row.get("reportDate") or "")[:10] or None,
|
|
58
|
+
"report_type": row.get("reportType"),
|
|
59
|
+
"currency": row.get("currency"),
|
|
60
|
+
"source": "lixinger",
|
|
61
|
+
}
|
|
62
|
+
for key, field in fields.items():
|
|
63
|
+
table, metric = field.split(".")
|
|
64
|
+
value = row.get("q", {}).get(table, {}).get(metric, {}).get("t")
|
|
65
|
+
entry[key] = (
|
|
66
|
+
value * 100 if value is not None and key in ("roe", "gross_margin", "net_profit_margin") else value
|
|
67
|
+
)
|
|
68
|
+
if any(entry.get(key) is not None for key in fields):
|
|
69
|
+
history.append(entry)
|
|
70
|
+
if not history:
|
|
71
|
+
raise ValueError("Lixinger returned no matching financial periods")
|
|
72
|
+
history = history[:periods]
|
|
73
|
+
latest = history[0]
|
|
74
|
+
result = {
|
|
75
|
+
**dict.fromkeys(("name", "market_cap", "pe", "forward_pe", "pb", "debt_to_equity", "dividend_yield")),
|
|
76
|
+
"snapshot_available": False,
|
|
77
|
+
"symbol": symbol,
|
|
78
|
+
"source": "lixinger",
|
|
79
|
+
"report_date": latest["report_date"],
|
|
80
|
+
"currency": latest["currency"],
|
|
81
|
+
"total_revenue": latest["total_revenue"],
|
|
82
|
+
"net_income": latest["net_income"],
|
|
83
|
+
"roe": latest["roe"] / 100 if latest["roe"] is not None else None,
|
|
84
|
+
"profit_margin": latest["net_profit_margin"] / 100 if latest["net_profit_margin"] is not None else None,
|
|
85
|
+
"periods": history,
|
|
86
|
+
"requested_periods": periods,
|
|
87
|
+
"available_periods": len(history),
|
|
88
|
+
"history_units": {
|
|
89
|
+
"roe": "percent",
|
|
90
|
+
"gross_margin": "percent",
|
|
91
|
+
"net_profit_margin": "percent",
|
|
92
|
+
"total_revenue": "reported currency",
|
|
93
|
+
"net_income": "reported currency",
|
|
94
|
+
"operating_cash_flow": "reported currency",
|
|
95
|
+
},
|
|
96
|
+
"accounting_basis": "provider-reported HK financial statements; not normalized to A-share accounting",
|
|
97
|
+
}
|
|
98
|
+
if len(history) < periods:
|
|
99
|
+
result["warnings"] = ["Requested financial history incomplete; only actual available periods returned"]
|
|
100
|
+
return result
|
package/tools/market_regime.py
CHANGED
|
@@ -54,7 +54,9 @@ def _get_index_kline(market: str) -> list:
|
|
|
54
54
|
def _compute_indicators(klines: list) -> dict:
|
|
55
55
|
import numpy as np
|
|
56
56
|
|
|
57
|
-
|
|
57
|
+
df = pd.DataFrame(klines).reindex(columns=["close", "high", "low"]).apply(pd.to_numeric, errors="coerce")
|
|
58
|
+
df = df[np.isfinite(df).all(axis=1) & (df > 0).all(axis=1)]
|
|
59
|
+
closes = df["close"].to_numpy()
|
|
58
60
|
if len(closes) < 20:
|
|
59
61
|
return {}
|
|
60
62
|
|
|
@@ -65,8 +67,8 @@ def _compute_indicators(klines: list) -> dict:
|
|
|
65
67
|
ma60 = float(ma_series(close_s, 60).iloc[-1]) if len(closes) >= 60 else float(np.mean(closes))
|
|
66
68
|
close = float(closes[-1])
|
|
67
69
|
|
|
68
|
-
highs =
|
|
69
|
-
lows =
|
|
70
|
+
highs = df["high"].to_numpy()
|
|
71
|
+
lows = df["low"].to_numpy()
|
|
70
72
|
|
|
71
73
|
tr_values = []
|
|
72
74
|
for i in range(-min(14, len(closes) - 1), 0):
|
|
@@ -226,6 +228,8 @@ def main():
|
|
|
226
228
|
if args.command == "detect":
|
|
227
229
|
result = detect_regime(args.market)
|
|
228
230
|
print(json.dumps(result, ensure_ascii=False, default=str))
|
|
231
|
+
if "error" in result:
|
|
232
|
+
sys.exit(1)
|
|
229
233
|
|
|
230
234
|
|
|
231
235
|
if __name__ == "__main__":
|
package/tools/market_review.py
CHANGED
|
@@ -19,7 +19,7 @@ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
|
|
19
19
|
|
|
20
20
|
from _subproc import run_tool as _run_tool
|
|
21
21
|
from _subproc import utf8_stdio
|
|
22
|
-
from signal_tracker import _load_records
|
|
22
|
+
from signal_tracker import _append_record, _load_records, _store_lock
|
|
23
23
|
|
|
24
24
|
|
|
25
25
|
def calc_temperature(stats: dict, indices: list) -> dict:
|
|
@@ -145,10 +145,9 @@ def save_review(report: dict, store: Path | None = None) -> dict:
|
|
|
145
145
|
"""Append one review report object to the JSONL archive (side effect of render --save)."""
|
|
146
146
|
store = store or _default_store()
|
|
147
147
|
try:
|
|
148
|
-
store
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
except OSError as e:
|
|
148
|
+
with _store_lock(store):
|
|
149
|
+
_append_record(store, report)
|
|
150
|
+
except (OSError, ValueError) as e:
|
|
152
151
|
return {"error": str(e)}
|
|
153
152
|
return {"saved": True, "date": report.get("review_date") or report.get("date")}
|
|
154
153
|
|
|
@@ -156,7 +155,9 @@ def save_review(report: dict, store: Path | None = None) -> dict:
|
|
|
156
155
|
def cmd_history(args) -> dict:
|
|
157
156
|
"""Recent archived reviews, newest first. Empty store -> clean empty list."""
|
|
158
157
|
try:
|
|
159
|
-
|
|
158
|
+
store = Path(args.store) if args.store else _default_store()
|
|
159
|
+
with _store_lock(store):
|
|
160
|
+
records = _load_records(store)
|
|
160
161
|
except (OSError, UnicodeDecodeError) as e:
|
|
161
162
|
# store is a directory / not UTF-8 — same clean-error contract as save_review
|
|
162
163
|
return {"error": str(e)}
|
|
@@ -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
|
@@ -314,20 +314,21 @@ def _apply_l2(candidates: list, market: str, multiplier: float) -> None:
|
|
|
314
314
|
|
|
315
315
|
|
|
316
316
|
def screen(market: str, top: int, config: dict | None, l2: bool = False) -> dict:
|
|
317
|
+
if config is not None and (not isinstance(config, dict) or not isinstance(config.get("filters", {}), dict)):
|
|
318
|
+
return {"error": "config and filters must be objects", "market": market}
|
|
317
319
|
filters = merge_filters(config)
|
|
320
|
+
supported = set(DEFAULT_FILTERS) | {"dividend_yield_min", "dividend_yield_max"}
|
|
321
|
+
for key, value in filters.items():
|
|
322
|
+
if key not in supported:
|
|
323
|
+
return {"error": f"Unsupported filter: {key}", "market": market}
|
|
324
|
+
if isinstance(value, bool) or not isinstance(value, (int, float)) or not np.isfinite(value):
|
|
325
|
+
return {"error": f"{key} must be a finite number", "market": market}
|
|
318
326
|
dividend_requested = any(k.startswith("dividend_yield_") for k in filters) or (config or {}).get("sort_by") in (
|
|
319
327
|
"dividend_yield",
|
|
320
328
|
"dividend_score",
|
|
321
329
|
)
|
|
322
330
|
if dividend_requested and market not in ("A", "HK"):
|
|
323
331
|
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
332
|
raw = fetch_snapshot(market)
|
|
332
333
|
if isinstance(raw, dict) and "error" in raw:
|
|
333
334
|
return raw
|
|
@@ -378,6 +379,11 @@ def screen(market: str, top: int, config: dict | None, l2: bool = False) -> dict
|
|
|
378
379
|
"error": "dividend data unavailable; requested dividend criterion was not applied",
|
|
379
380
|
"market": market,
|
|
380
381
|
}
|
|
382
|
+
explicit = (config or {}).get("filters") or {}
|
|
383
|
+
missing = [key for key in explicit if key.rsplit("_", 1)[0] not in df]
|
|
384
|
+
if missing:
|
|
385
|
+
return {"error": f"Requested filter data unavailable: {', '.join(missing)}", "market": market}
|
|
386
|
+
applied_filters = {key: value for key, value in filters.items() if key.rsplit("_", 1)[0] in df}
|
|
381
387
|
df = apply_filters(df, filters)
|
|
382
388
|
filtered_count = len(df)
|
|
383
389
|
|
|
@@ -387,7 +393,7 @@ def screen(market: str, top: int, config: dict | None, l2: bool = False) -> dict
|
|
|
387
393
|
"total_stocks": total,
|
|
388
394
|
"filtered_count": 0,
|
|
389
395
|
"returned_count": 0,
|
|
390
|
-
"filters_applied":
|
|
396
|
+
"filters_applied": applied_filters,
|
|
391
397
|
"candidates": [],
|
|
392
398
|
"market_sentiment": sentiment,
|
|
393
399
|
"l2_enabled": l2_enabled,
|
|
@@ -450,7 +456,7 @@ def screen(market: str, top: int, config: dict | None, l2: bool = False) -> dict
|
|
|
450
456
|
"total_stocks": total,
|
|
451
457
|
"filtered_count": filtered_count,
|
|
452
458
|
"returned_count": len(candidates),
|
|
453
|
-
"filters_applied":
|
|
459
|
+
"filters_applied": applied_filters,
|
|
454
460
|
"candidates": candidates,
|
|
455
461
|
"market_sentiment": sentiment,
|
|
456
462
|
"l2_enabled": l2_enabled,
|
|
@@ -478,6 +484,8 @@ def main():
|
|
|
478
484
|
config = load_config(args.config) if args.config else None
|
|
479
485
|
result = screen(args.market, args.top, config, l2=args.l2)
|
|
480
486
|
print(json.dumps(result, ensure_ascii=False, default=str))
|
|
487
|
+
if "error" in result:
|
|
488
|
+
sys.exit(1)
|
|
481
489
|
|
|
482
490
|
|
|
483
491
|
if __name__ == "__main__":
|