@weaxs/openclaw-stock-analysis 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 +1 -1
- package/dist/index.js +322 -21
- package/index.ts +257 -16
- package/openclaw.plugin.json +11 -1
- package/package.json +1 -1
- 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
|
@@ -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
|
@@ -10,6 +10,7 @@ tmp_path).
|
|
|
10
10
|
|
|
11
11
|
import argparse
|
|
12
12
|
import json
|
|
13
|
+
import math
|
|
13
14
|
import os
|
|
14
15
|
import sys
|
|
15
16
|
from concurrent.futures import ThreadPoolExecutor
|
|
@@ -17,9 +18,14 @@ from pathlib import Path
|
|
|
17
18
|
|
|
18
19
|
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
|
19
20
|
|
|
21
|
+
from _subproc import command_timeout, utf8_stdio
|
|
20
22
|
from _subproc import run_tool as _run_tool
|
|
21
|
-
from
|
|
22
|
-
|
|
23
|
+
from signal_tracker import _append_record, _load_records, _store_lock
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _index_change(row):
|
|
27
|
+
value = row.get("change_pct") if isinstance(row, dict) else None
|
|
28
|
+
return value if isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) else None
|
|
23
29
|
|
|
24
30
|
|
|
25
31
|
def calc_temperature(stats: dict, indices: list) -> dict:
|
|
@@ -37,7 +43,7 @@ def calc_temperature(stats: dict, indices: list) -> dict:
|
|
|
37
43
|
weights.append(0.45)
|
|
38
44
|
|
|
39
45
|
if indices and isinstance(indices, list):
|
|
40
|
-
changes = [
|
|
46
|
+
changes = [value for row in indices if (value := _index_change(row)) is not None]
|
|
41
47
|
if changes:
|
|
42
48
|
avg_change = sum(changes) / len(changes)
|
|
43
49
|
index_score = max(0, min(100, 50 + avg_change * 12))
|
|
@@ -54,7 +60,7 @@ def calc_temperature(stats: dict, indices: list) -> dict:
|
|
|
54
60
|
weights.append(0.20)
|
|
55
61
|
|
|
56
62
|
if not scores:
|
|
57
|
-
return {"score":
|
|
63
|
+
return {"score": None, "level": "unknown", "signal": "unknown"}
|
|
58
64
|
|
|
59
65
|
total_weight = sum(weights)
|
|
60
66
|
temperature = sum(s * w for s, w in zip(scores, weights)) / total_weight
|
|
@@ -69,8 +75,8 @@ def calc_temperature(stats: dict, indices: list) -> dict:
|
|
|
69
75
|
return {"score": round(temperature, 1), "level": level, "signal": signal}
|
|
70
76
|
|
|
71
77
|
|
|
72
|
-
def _signal_to_stance(signal: str) -> str:
|
|
73
|
-
return {"green": "offensive", "yellow": "balanced", "red": "defensive"}.get(signal
|
|
78
|
+
def _signal_to_stance(signal: str) -> str | None:
|
|
79
|
+
return {"green": "offensive", "yellow": "balanced", "red": "defensive"}.get(signal)
|
|
74
80
|
|
|
75
81
|
|
|
76
82
|
def review_market(market: str = "A") -> dict:
|
|
@@ -100,10 +106,7 @@ def review_market(market: str = "A") -> dict:
|
|
|
100
106
|
results = {}
|
|
101
107
|
with ThreadPoolExecutor(max_workers=5) as executor:
|
|
102
108
|
futures = {
|
|
103
|
-
|
|
104
|
-
# (screener.fetch_snapshot); the default 30s would silently degrade the
|
|
105
|
-
# temperature to the neutral 50 fallback on a weak network.
|
|
106
|
-
key: executor.submit(_run_tool, script, args, 240 if key == "stats" else 30)
|
|
109
|
+
key: executor.submit(_run_tool, script, args, command_timeout(script, args))
|
|
107
110
|
for key, (script, args) in tasks.items()
|
|
108
111
|
}
|
|
109
112
|
for key, future in futures.items():
|
|
@@ -113,6 +116,22 @@ def review_market(market: str = "A") -> dict:
|
|
|
113
116
|
results[key] = None
|
|
114
117
|
|
|
115
118
|
temperature = calc_temperature(results.get("stats"), results.get("indices"))
|
|
119
|
+
warnings = [
|
|
120
|
+
f"{key} data unavailable"
|
|
121
|
+
for key, value in results.items()
|
|
122
|
+
if not value
|
|
123
|
+
or (isinstance(value, dict) and "error" in value)
|
|
124
|
+
or (key == "indices" and isinstance(value, list) and any(_index_change(row) is None for row in value))
|
|
125
|
+
or (key == "sectors" and isinstance(value, dict) and not value.get("top") and not value.get("bottom"))
|
|
126
|
+
or (
|
|
127
|
+
isinstance(value, list)
|
|
128
|
+
and any(
|
|
129
|
+
isinstance(row, dict) and ("error" in row or row.get("note") == "data unavailable") for row in value
|
|
130
|
+
)
|
|
131
|
+
)
|
|
132
|
+
]
|
|
133
|
+
if temperature["score"] is None:
|
|
134
|
+
warnings.append("Insufficient market data to determine temperature or strategy stance")
|
|
116
135
|
|
|
117
136
|
output = {
|
|
118
137
|
"market": market,
|
|
@@ -124,6 +143,8 @@ def review_market(market: str = "A") -> dict:
|
|
|
124
143
|
"regime": results.get("regime"),
|
|
125
144
|
"temperature": temperature,
|
|
126
145
|
"strategy_stance": _signal_to_stance(temperature["signal"]),
|
|
146
|
+
"warnings": warnings,
|
|
147
|
+
"data_quality": {"flags": ["partial_data"] if warnings else [], "limitations": warnings},
|
|
127
148
|
}
|
|
128
149
|
return output
|
|
129
150
|
|
|
@@ -145,10 +166,9 @@ def save_review(report: dict, store: Path | None = None) -> dict:
|
|
|
145
166
|
"""Append one review report object to the JSONL archive (side effect of render --save)."""
|
|
146
167
|
store = store or _default_store()
|
|
147
168
|
try:
|
|
148
|
-
store
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
except OSError as e:
|
|
169
|
+
with _store_lock(store):
|
|
170
|
+
_append_record(store, report)
|
|
171
|
+
except (OSError, ValueError) as e:
|
|
152
172
|
return {"error": str(e)}
|
|
153
173
|
return {"saved": True, "date": report.get("review_date") or report.get("date")}
|
|
154
174
|
|
|
@@ -156,7 +176,9 @@ def save_review(report: dict, store: Path | None = None) -> dict:
|
|
|
156
176
|
def cmd_history(args) -> dict:
|
|
157
177
|
"""Recent archived reviews, newest first. Empty store -> clean empty list."""
|
|
158
178
|
try:
|
|
159
|
-
|
|
179
|
+
store = Path(args.store) if args.store else _default_store()
|
|
180
|
+
with _store_lock(store):
|
|
181
|
+
records = _load_records(store)
|
|
160
182
|
except (OSError, UnicodeDecodeError) as e:
|
|
161
183
|
# store is a directory / not UTF-8 — same clean-error contract as save_review
|
|
162
184
|
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__":
|