stock-analysis-plugin 0.2.2 → 0.2.3
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/LICENSE +21 -0
- package/README.md +33 -11
- package/package.json +5 -5
- package/pi/index.ts +86 -8
- package/scripts/ci-resolve-llm-host.mjs +29 -0
- package/scripts/setup-python.mjs +7 -9
- package/skills/hot-theme/SKILL.md +3 -2
- package/skills/stock-screener/SKILL.md +1 -1
- package/skills/strategy-backtest/SKILL.md +9 -5
- package/strategies/examples/bottom_volume.yaml +5 -0
- package/strategies/examples/box_oscillation.yaml +5 -0
- package/strategies/examples/bull_trend.yaml +11 -3
- package/strategies/examples/dragon_head.yaml +4 -2
- package/strategies/examples/emotion_cycle.yaml +5 -0
- package/strategies/examples/ma_crossover.yaml +10 -3
- package/strategies/examples/rsi_oversold.yaml +5 -0
- package/strategies/examples/shrink_pullback.yaml +7 -1
- package/strategies/examples/volume_breakout.yaml +7 -1
- package/tools/_subproc.py +49 -0
- package/tools/alert_rules.py +19 -9
- package/tools/anomaly_detect.py +24 -35
- package/tools/backtest.py +180 -100
- package/tools/capabilities.py +4 -5
- package/tools/diagnostics.py +6 -6
- package/tools/gather.py +13 -9
- package/tools/import_parser.py +2 -5
- package/tools/market_regime.py +27 -35
- package/tools/market_review.py +56 -9
- package/tools/name_resolver.py +2 -5
- package/tools/pattern.py +2 -5
- package/tools/position_context.py +2 -5
- package/tools/report_renderer.py +10 -6
- package/tools/requirements.txt +2 -1
- package/tools/risk_screening.py +29 -23
- package/tools/screener.py +26 -16
- package/tools/search_intel.py +5 -13
- package/tools/signal_tracker.py +2 -6
- package/tools/stock_data.py +301 -92
- package/tools/technical.py +136 -40
- package/tools/trading_calendar.py +78 -18
- package/tools/volume_analysis.py +2 -5
- package/tools/watchlist.py +2 -5
- package/tools/watchlist_context.py +2 -5
package/tools/market_regime.py
CHANGED
|
@@ -6,13 +6,17 @@ import json
|
|
|
6
6
|
import os
|
|
7
7
|
import sys
|
|
8
8
|
|
|
9
|
+
import pandas as pd
|
|
10
|
+
|
|
9
11
|
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
|
10
12
|
|
|
11
13
|
from _subproc import run_tool as _run_tool
|
|
14
|
+
from _subproc import utf8_stdio
|
|
15
|
+
from technical import bollinger_series, ma_series, macd_series, rsi_series
|
|
12
16
|
|
|
13
17
|
INDEX_MAP = {
|
|
14
18
|
"A": ("000001", "上证综指"),
|
|
15
|
-
"HK": ("HSI", "恒生指数"),
|
|
19
|
+
"HK": ("^HSI", "恒生指数"),
|
|
16
20
|
"US": ("^GSPC", "标普500"),
|
|
17
21
|
}
|
|
18
22
|
|
|
@@ -54,14 +58,12 @@ def _compute_indicators(klines: list) -> dict:
|
|
|
54
58
|
if len(closes) < 20:
|
|
55
59
|
return {}
|
|
56
60
|
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
ma60 = ma(60) if len(closes) >= 60 else ma(len(closes))
|
|
64
|
-
close = closes[-1]
|
|
61
|
+
close_s = pd.Series(closes)
|
|
62
|
+
ma5 = float(ma_series(close_s, 5).iloc[-1])
|
|
63
|
+
ma10 = float(ma_series(close_s, 10).iloc[-1])
|
|
64
|
+
ma20 = float(ma_series(close_s, 20).iloc[-1])
|
|
65
|
+
ma60 = float(ma_series(close_s, 60).iloc[-1]) if len(closes) >= 60 else float(np.mean(closes))
|
|
66
|
+
close = float(closes[-1])
|
|
65
67
|
|
|
66
68
|
highs = np.array([float(k["high"]) for k in klines if k.get("high") is not None])
|
|
67
69
|
lows = np.array([float(k["low"]) for k in klines if k.get("low") is not None])
|
|
@@ -73,30 +75,24 @@ def _compute_indicators(klines: list) -> dict:
|
|
|
73
75
|
atr = np.mean(tr_values) if tr_values else 0
|
|
74
76
|
atr_ratio = atr / close if close > 0 else 0
|
|
75
77
|
|
|
76
|
-
upper
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
if diff > 0
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
rsi14 = 100 - (100 / (1 + rs))
|
|
91
|
-
|
|
92
|
-
ema12 = np.mean(closes[-12:])
|
|
93
|
-
ema26 = np.mean(closes[-26:]) if len(closes) >= 26 else np.mean(closes)
|
|
94
|
-
macd_diff = ema12 - ema26
|
|
95
|
-
macd_trend = "bullish" if macd_diff > 0 else "bearish"
|
|
78
|
+
upper, mid, lower = bollinger_series(close_s)
|
|
79
|
+
boll_width = float((upper.iloc[-1] - lower.iloc[-1]) / mid.iloc[-1]) if mid.iloc[-1] > 0 else 0
|
|
80
|
+
|
|
81
|
+
# rsi_series leaves NaN when the window has zero losses: 14 straight up bars
|
|
82
|
+
# is RSI 100, but 14 flat bars (no gains either) is undefined — call it neutral.
|
|
83
|
+
rsi_val = rsi_series(close_s, 14).iloc[-1]
|
|
84
|
+
if pd.isna(rsi_val):
|
|
85
|
+
rsi14 = 100.0 if float(close_s.diff().clip(lower=0).iloc[-14:].sum()) > 0 else 50.0
|
|
86
|
+
else:
|
|
87
|
+
rsi14 = float(rsi_val)
|
|
88
|
+
|
|
89
|
+
# Real EMA12-EMA26 (the old code mislabeled an np.mean simple average as EMA).
|
|
90
|
+
dif, _, _ = macd_series(close_s)
|
|
91
|
+
macd_trend = "bullish" if float(dif.iloc[-1]) > 0 else "bearish"
|
|
96
92
|
|
|
97
93
|
ma_spread = abs(ma5 - ma20) / ma20 if ma20 > 0 else 0
|
|
98
94
|
|
|
99
|
-
prev_close = closes[-2] if len(closes) >= 2 else close
|
|
95
|
+
prev_close = float(closes[-2]) if len(closes) >= 2 else close
|
|
100
96
|
change_pct = (close - prev_close) / prev_close * 100 if prev_close > 0 else 0
|
|
101
97
|
|
|
102
98
|
return {
|
|
@@ -233,9 +229,5 @@ def main():
|
|
|
233
229
|
|
|
234
230
|
|
|
235
231
|
if __name__ == "__main__":
|
|
236
|
-
|
|
237
|
-
# Chinese text these tools emit — force UTF-8 so stdout never crashes there.
|
|
238
|
-
for _s in (sys.stdout, sys.stderr):
|
|
239
|
-
if hasattr(_s, "reconfigure"):
|
|
240
|
-
_s.reconfigure(encoding="utf-8")
|
|
232
|
+
utf8_stdio()
|
|
241
233
|
main()
|
package/tools/market_review.py
CHANGED
|
@@ -1,15 +1,25 @@
|
|
|
1
1
|
#!/usr/bin/env python3
|
|
2
|
-
"""Market review — daily market overview with temperature scoring.
|
|
2
|
+
"""Market review — daily market overview with temperature scoring.
|
|
3
|
+
|
|
4
|
+
Review archive: `render_market_report --save` appends the report object to a
|
|
5
|
+
JSONL store so `history` can answer longitudinal questions. Store path:
|
|
6
|
+
$STOCK_REVIEW_STORE, else ~/.stock-analysis/reviews.jsonl (pathlib.Path.home(),
|
|
7
|
+
cross-platform). `history` accepts --store PATH to override (tests point it at
|
|
8
|
+
tmp_path).
|
|
9
|
+
"""
|
|
3
10
|
|
|
4
11
|
import argparse
|
|
5
12
|
import json
|
|
6
13
|
import os
|
|
7
14
|
import sys
|
|
8
15
|
from concurrent.futures import ThreadPoolExecutor
|
|
16
|
+
from pathlib import Path
|
|
9
17
|
|
|
10
18
|
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
|
11
19
|
|
|
12
20
|
from _subproc import run_tool as _run_tool
|
|
21
|
+
from _subproc import utf8_stdio
|
|
22
|
+
from signal_tracker import _load_records
|
|
13
23
|
|
|
14
24
|
|
|
15
25
|
def calc_temperature(stats: dict, indices: list) -> dict:
|
|
@@ -89,10 +99,16 @@ def review_market(market: str = "A") -> dict:
|
|
|
89
99
|
|
|
90
100
|
results = {}
|
|
91
101
|
with ThreadPoolExecutor(max_workers=5) as executor:
|
|
92
|
-
futures = {
|
|
102
|
+
futures = {
|
|
103
|
+
# stats fans out to a full-market snapshot — screener gives the same path 240s
|
|
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)
|
|
107
|
+
for key, (script, args) in tasks.items()
|
|
108
|
+
}
|
|
93
109
|
for key, future in futures.items():
|
|
94
110
|
try:
|
|
95
|
-
results[key] = future.result(timeout=
|
|
111
|
+
results[key] = future.result(timeout=300)
|
|
96
112
|
except Exception:
|
|
97
113
|
results[key] = None
|
|
98
114
|
|
|
@@ -120,6 +136,35 @@ def review_all() -> list:
|
|
|
120
136
|
return results
|
|
121
137
|
|
|
122
138
|
|
|
139
|
+
def _default_store() -> Path:
|
|
140
|
+
env = os.environ.get("STOCK_REVIEW_STORE")
|
|
141
|
+
return Path(env) if env else Path.home() / ".stock-analysis" / "reviews.jsonl"
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def save_review(report: dict, store: Path | None = None) -> dict:
|
|
145
|
+
"""Append one review report object to the JSONL archive (side effect of render --save)."""
|
|
146
|
+
store = store or _default_store()
|
|
147
|
+
try:
|
|
148
|
+
store.parent.mkdir(parents=True, exist_ok=True)
|
|
149
|
+
with store.open("a", encoding="utf-8") as f:
|
|
150
|
+
f.write(json.dumps(report, ensure_ascii=False, default=str) + "\n")
|
|
151
|
+
except OSError as e:
|
|
152
|
+
return {"error": str(e)}
|
|
153
|
+
return {"saved": True, "date": report.get("review_date") or report.get("date")}
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def cmd_history(args) -> dict:
|
|
157
|
+
"""Recent archived reviews, newest first. Empty store -> clean empty list."""
|
|
158
|
+
try:
|
|
159
|
+
records = _load_records(Path(args.store) if args.store else _default_store())
|
|
160
|
+
except (OSError, UnicodeDecodeError) as e:
|
|
161
|
+
# store is a directory / not UTF-8 — same clean-error contract as save_review
|
|
162
|
+
return {"error": str(e)}
|
|
163
|
+
limit = max(args.limit, 0)
|
|
164
|
+
recent = records[-limit:][::-1] if limit else []
|
|
165
|
+
return {"count": len(recent), "records": recent}
|
|
166
|
+
|
|
167
|
+
|
|
123
168
|
def main():
|
|
124
169
|
parser = argparse.ArgumentParser(description="Market review tool")
|
|
125
170
|
sub = parser.add_subparsers(dest="command")
|
|
@@ -127,6 +172,10 @@ def main():
|
|
|
127
172
|
p_review = sub.add_parser("review")
|
|
128
173
|
p_review.add_argument("--market", default="A", choices=["A", "HK", "US", "all"])
|
|
129
174
|
|
|
175
|
+
p_hist = sub.add_parser("history", help="Read archived market reviews (newest first)")
|
|
176
|
+
p_hist.add_argument("--limit", type=int, default=10, help="Max archived entries to return (default 10)")
|
|
177
|
+
p_hist.add_argument("--store", default=None, help="JSONL store path override")
|
|
178
|
+
|
|
130
179
|
args = parser.parse_args()
|
|
131
180
|
if not args.command:
|
|
132
181
|
parser.print_help()
|
|
@@ -134,13 +183,11 @@ def main():
|
|
|
134
183
|
|
|
135
184
|
if args.command == "review":
|
|
136
185
|
result = review_all() if args.market == "all" else review_market(args.market)
|
|
137
|
-
|
|
186
|
+
else: # history
|
|
187
|
+
result = cmd_history(args)
|
|
188
|
+
print(json.dumps(result, ensure_ascii=False, default=str))
|
|
138
189
|
|
|
139
190
|
|
|
140
191
|
if __name__ == "__main__":
|
|
141
|
-
|
|
142
|
-
# Chinese text these tools emit — force UTF-8 so stdout never crashes there.
|
|
143
|
-
for _s in (sys.stdout, sys.stderr):
|
|
144
|
-
if hasattr(_s, "reconfigure"):
|
|
145
|
-
_s.reconfigure(encoding="utf-8")
|
|
192
|
+
utf8_stdio()
|
|
146
193
|
main()
|
package/tools/name_resolver.py
CHANGED
|
@@ -9,6 +9,7 @@ from pathlib import Path
|
|
|
9
9
|
|
|
10
10
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
11
11
|
|
|
12
|
+
from _subproc import utf8_stdio # noqa: E402
|
|
12
13
|
from stock_data import _akshare_retry # noqa: E402
|
|
13
14
|
|
|
14
15
|
_STOCK_MAP_CACHE = None
|
|
@@ -122,9 +123,5 @@ def main():
|
|
|
122
123
|
|
|
123
124
|
|
|
124
125
|
if __name__ == "__main__":
|
|
125
|
-
|
|
126
|
-
# Chinese text these tools emit — force UTF-8 so stdout never crashes there.
|
|
127
|
-
for _s in (sys.stdout, sys.stderr):
|
|
128
|
-
if hasattr(_s, "reconfigure"):
|
|
129
|
-
_s.reconfigure(encoding="utf-8")
|
|
126
|
+
utf8_stdio()
|
|
130
127
|
main()
|
package/tools/pattern.py
CHANGED
|
@@ -11,6 +11,7 @@ import pandas as pd
|
|
|
11
11
|
|
|
12
12
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
13
13
|
|
|
14
|
+
from _subproc import utf8_stdio # noqa: E402
|
|
14
15
|
from technical import fetch_kline, to_dataframe # noqa: E402
|
|
15
16
|
|
|
16
17
|
|
|
@@ -486,9 +487,5 @@ def main():
|
|
|
486
487
|
|
|
487
488
|
|
|
488
489
|
if __name__ == "__main__":
|
|
489
|
-
|
|
490
|
-
# Chinese text these tools emit — force UTF-8 so stdout never crashes there.
|
|
491
|
-
for _s in (sys.stdout, sys.stderr):
|
|
492
|
-
if hasattr(_s, "reconfigure"):
|
|
493
|
-
_s.reconfigure(encoding="utf-8")
|
|
490
|
+
utf8_stdio()
|
|
494
491
|
main()
|
|
@@ -12,6 +12,7 @@ from pathlib import Path
|
|
|
12
12
|
|
|
13
13
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
14
14
|
from _subproc import run_tool as _run_json # noqa: E402
|
|
15
|
+
from _subproc import utf8_stdio
|
|
15
16
|
from stock_data import detect_market # noqa: E402
|
|
16
17
|
|
|
17
18
|
|
|
@@ -135,9 +136,5 @@ def main():
|
|
|
135
136
|
|
|
136
137
|
|
|
137
138
|
if __name__ == "__main__":
|
|
138
|
-
|
|
139
|
-
# Chinese text these tools emit — force UTF-8 so stdout never crashes there.
|
|
140
|
-
for _s in (sys.stdout, sys.stderr):
|
|
141
|
-
if hasattr(_s, "reconfigure"):
|
|
142
|
-
_s.reconfigure(encoding="utf-8")
|
|
139
|
+
utf8_stdio()
|
|
143
140
|
main()
|
package/tools/report_renderer.py
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env python3
|
|
2
2
|
"""Report renderer — turn structured stock/market JSON into markdown via existing j2 templates.
|
|
3
3
|
|
|
4
|
-
|
|
4
|
+
Side effects: none by default. `market --save` additionally appends the input
|
|
5
|
+
report object to the review JSONL archive (see market_review.save_review).
|
|
5
6
|
"""
|
|
6
7
|
|
|
7
8
|
import argparse
|
|
@@ -10,6 +11,10 @@ import sys
|
|
|
10
11
|
from datetime import datetime, timezone
|
|
11
12
|
from pathlib import Path
|
|
12
13
|
|
|
14
|
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
15
|
+
from _subproc import utf8_stdio
|
|
16
|
+
from market_review import save_review
|
|
17
|
+
|
|
13
18
|
try:
|
|
14
19
|
from jinja2 import Environment, FileSystemLoader, select_autoescape
|
|
15
20
|
except ImportError:
|
|
@@ -94,6 +99,7 @@ def main():
|
|
|
94
99
|
p2 = sub.add_parser("market", help="Render a market review report")
|
|
95
100
|
p2.add_argument("--input", "-i", default="-", help="JSON file path or '-' for stdin")
|
|
96
101
|
p2.add_argument("--input-b64", help="Base64-encoded JSON (avoids shell escaping)")
|
|
102
|
+
p2.add_argument("--save", action="store_true", help="Append the report object to the review JSONL archive")
|
|
97
103
|
|
|
98
104
|
args = parser.parse_args()
|
|
99
105
|
if not args.command:
|
|
@@ -102,14 +108,12 @@ def main():
|
|
|
102
108
|
|
|
103
109
|
report = _load_input(args.input, getattr(args, "input_b64", None))
|
|
104
110
|
result = render(args.command, getattr(args, "template", "full"), report)
|
|
111
|
+
if args.command == "market" and args.save and "error" not in result:
|
|
112
|
+
result["archived"] = save_review(report)
|
|
105
113
|
json.dump(result, sys.stdout, ensure_ascii=False, indent=2, default=str)
|
|
106
114
|
print()
|
|
107
115
|
|
|
108
116
|
|
|
109
117
|
if __name__ == "__main__":
|
|
110
|
-
|
|
111
|
-
# Chinese text these tools emit — force UTF-8 so stdout never crashes there.
|
|
112
|
-
for _s in (sys.stdout, sys.stderr):
|
|
113
|
-
if hasattr(_s, "reconfigure"):
|
|
114
|
-
_s.reconfigure(encoding="utf-8")
|
|
118
|
+
utf8_stdio()
|
|
115
119
|
main()
|
package/tools/requirements.txt
CHANGED
package/tools/risk_screening.py
CHANGED
|
@@ -5,11 +5,13 @@ import argparse
|
|
|
5
5
|
import json
|
|
6
6
|
import os
|
|
7
7
|
import sys
|
|
8
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
8
9
|
from datetime import datetime, timedelta
|
|
9
10
|
|
|
10
11
|
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
|
11
12
|
|
|
12
13
|
from _subproc import run_tool as _run_tool
|
|
14
|
+
from _subproc import utf8_stdio
|
|
13
15
|
|
|
14
16
|
|
|
15
17
|
def _safe_float(val) -> float | None:
|
|
@@ -194,24 +196,32 @@ def check_news_risks(symbol: str, name: str = "") -> dict:
|
|
|
194
196
|
"industry": f"{search_name} 行业政策 监管 限制",
|
|
195
197
|
}
|
|
196
198
|
result = {"flags": []}
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
199
|
+
# four independent search_intel subprocesses — fan out concurrently (same
|
|
200
|
+
# ThreadPoolExecutor pattern as gather._run_all); iterating `futures` in
|
|
201
|
+
# declaration order keeps result keys and flags stably ordered
|
|
202
|
+
with ThreadPoolExecutor(max_workers=len(categories)) as pool:
|
|
203
|
+
futures = {
|
|
204
|
+
cat: pool.submit(_run_tool, "search_intel.py", ["search", query, "--count", "3"])
|
|
205
|
+
for cat, query in categories.items()
|
|
206
|
+
}
|
|
207
|
+
for cat, future in futures.items():
|
|
208
|
+
data = future.result()
|
|
209
|
+
items = []
|
|
210
|
+
if isinstance(data, list):
|
|
211
|
+
items = data
|
|
212
|
+
elif isinstance(data, dict) and "results" in data:
|
|
213
|
+
items = data["results"]
|
|
214
|
+
|
|
215
|
+
result[cat] = items
|
|
216
|
+
if items:
|
|
217
|
+
result["flags"].append(
|
|
218
|
+
{
|
|
219
|
+
"category": cat,
|
|
220
|
+
"severity": "medium",
|
|
221
|
+
"description": f"发现{len(items)}条相关{_cat_cn(cat)}信息",
|
|
222
|
+
"source": "news",
|
|
223
|
+
}
|
|
224
|
+
)
|
|
215
225
|
return result
|
|
216
226
|
|
|
217
227
|
|
|
@@ -305,9 +315,5 @@ def main():
|
|
|
305
315
|
|
|
306
316
|
|
|
307
317
|
if __name__ == "__main__":
|
|
308
|
-
|
|
309
|
-
# Chinese text these tools emit — force UTF-8 so stdout never crashes there.
|
|
310
|
-
for _s in (sys.stdout, sys.stderr):
|
|
311
|
-
if hasattr(_s, "reconfigure"):
|
|
312
|
-
_s.reconfigure(encoding="utf-8")
|
|
318
|
+
utf8_stdio()
|
|
313
319
|
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
|
|
21
|
+
from _subproc import run_tool, utf8_stdio
|
|
22
22
|
from market_review import calc_temperature
|
|
23
23
|
from stock_data import compute_market_stats
|
|
24
24
|
|
|
@@ -105,6 +105,15 @@ def _minmax(s: pd.Series) -> pd.Series:
|
|
|
105
105
|
return ((s - mn) / (mx - mn) * 100).clip(0, 100)
|
|
106
106
|
|
|
107
107
|
|
|
108
|
+
def _finite(v):
|
|
109
|
+
"""NaN/±inf → None. An all-empty factor column min-maxes to NaN, and json.dumps
|
|
110
|
+
would emit bare NaN/Infinity tokens that strict parsers in the host adapters
|
|
111
|
+
reject — so non-finite values never reach the output contract."""
|
|
112
|
+
if isinstance(v, (int, float, np.floating)) and not np.isfinite(v):
|
|
113
|
+
return None
|
|
114
|
+
return v
|
|
115
|
+
|
|
116
|
+
|
|
108
117
|
def compute_scores(df: pd.DataFrame) -> pd.DataFrame:
|
|
109
118
|
# Value: lower PE/PB → higher score (inverted)
|
|
110
119
|
value_parts = []
|
|
@@ -277,9 +286,10 @@ def _apply_l2(candidates: list, market: str, multiplier: float) -> None:
|
|
|
277
286
|
groups = factor_scores.get(sym, {})
|
|
278
287
|
c["enriched"] = bool(enrichments.get(sym))
|
|
279
288
|
scores = c["scores"]
|
|
289
|
+
# scores are sanitized to None when non-finite; L2 math needs numbers
|
|
280
290
|
components = {
|
|
281
|
-
"value": scores["value"],
|
|
282
|
-
"liquidity": scores["liquidity"],
|
|
291
|
+
"value": scores["value"] or 0,
|
|
292
|
+
"liquidity": scores["liquidity"] or 0,
|
|
283
293
|
}
|
|
284
294
|
# momentum is L2-only: candidates without kline factors drop the group and renormalize weights.
|
|
285
295
|
components.update(
|
|
@@ -297,6 +307,10 @@ def screen(market: str, top: int, config: dict | None, l2: bool = False) -> dict
|
|
|
297
307
|
raw = fetch_snapshot(market)
|
|
298
308
|
if isinstance(raw, dict) and "error" in raw:
|
|
299
309
|
return raw
|
|
310
|
+
# snapshot legs wrap a total failure as a one-row [{"error": ...}] list — surface it
|
|
311
|
+
# instead of letting the error row walk the scoring pipeline as a ghost candidate
|
|
312
|
+
if isinstance(raw, list) and len(raw) == 1 and isinstance(raw[0], dict) and "error" in raw[0]:
|
|
313
|
+
return {**raw[0], "market": market}
|
|
300
314
|
if raw is None:
|
|
301
315
|
return {"error": "failed to fetch market snapshot", "market": market}
|
|
302
316
|
|
|
@@ -361,16 +375,16 @@ def screen(market: str, top: int, config: dict | None, l2: bool = False) -> dict
|
|
|
361
375
|
"market_cap",
|
|
362
376
|
"volume_ratio",
|
|
363
377
|
]:
|
|
364
|
-
v = row.get(field)
|
|
365
|
-
if v is not None
|
|
378
|
+
v = _finite(row.get(field))
|
|
379
|
+
if v is not None:
|
|
366
380
|
entry[field] = round(float(v), 2) if isinstance(v, (float, np.floating)) else v
|
|
367
|
-
composite = float(row.get("composite_score", 0))
|
|
381
|
+
composite = _finite(float(row.get("composite_score", 0)))
|
|
368
382
|
entry["scores"] = {
|
|
369
|
-
"value": round(float(row.get("value_score", 0)), 1),
|
|
370
|
-
"momentum": round(float(row.get("momentum_score", 0)), 1),
|
|
371
|
-
"liquidity": round(float(row.get("liquidity_score", 0)), 1),
|
|
372
|
-
"composite": round(composite, 1),
|
|
373
|
-
"final": round(composite * multiplier, 1),
|
|
383
|
+
"value": _finite(round(float(row.get("value_score", 0)), 1)),
|
|
384
|
+
"momentum": _finite(round(float(row.get("momentum_score", 0)), 1)),
|
|
385
|
+
"liquidity": _finite(round(float(row.get("liquidity_score", 0)), 1)),
|
|
386
|
+
"composite": None if composite is None else round(composite, 1),
|
|
387
|
+
"final": None if composite is None else round(composite * multiplier, 1),
|
|
374
388
|
}
|
|
375
389
|
candidates.append(entry)
|
|
376
390
|
|
|
@@ -415,9 +429,5 @@ def main():
|
|
|
415
429
|
|
|
416
430
|
|
|
417
431
|
if __name__ == "__main__":
|
|
418
|
-
|
|
419
|
-
# Chinese text these tools emit — force UTF-8 so stdout never crashes there.
|
|
420
|
-
for _s in (sys.stdout, sys.stderr):
|
|
421
|
-
if hasattr(_s, "reconfigure"):
|
|
422
|
-
_s.reconfigure(encoding="utf-8")
|
|
432
|
+
utf8_stdio()
|
|
423
433
|
main()
|
package/tools/search_intel.py
CHANGED
|
@@ -8,14 +8,10 @@ import re
|
|
|
8
8
|
import sys
|
|
9
9
|
import time as _time
|
|
10
10
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
_SECRET_PARAM_RE = re.compile(r"(?i)((?:api[_-]?key|token|secret|access[_-]?token)=)[^&\s]+")
|
|
11
|
+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
|
12
|
+
from _subproc import scrub_secrets, utf8_stdio
|
|
14
13
|
|
|
15
|
-
|
|
16
|
-
def _scrub_secrets(msg: str) -> str:
|
|
17
|
-
"""Error text may embed request URLs (requests connection errors) — never leak keys to stdout JSON."""
|
|
18
|
-
return _SECRET_PARAM_RE.sub(r"\1***", msg)
|
|
14
|
+
# --------------- Web Search ---------------
|
|
19
15
|
|
|
20
16
|
|
|
21
17
|
def _tavily_search(query: str, max_results: int = 5) -> list[dict]:
|
|
@@ -197,7 +193,7 @@ def search_news(query: str, max_results: int = 10) -> dict:
|
|
|
197
193
|
try:
|
|
198
194
|
items = fn(query, max_results)
|
|
199
195
|
except Exception as e:
|
|
200
|
-
engines_errors[name] =
|
|
196
|
+
engines_errors[name] = scrub_secrets(str(e))
|
|
201
197
|
continue
|
|
202
198
|
if items:
|
|
203
199
|
engines_available.append(name)
|
|
@@ -497,9 +493,5 @@ def main():
|
|
|
497
493
|
|
|
498
494
|
|
|
499
495
|
if __name__ == "__main__":
|
|
500
|
-
|
|
501
|
-
# Chinese text these tools emit — force UTF-8 so stdout never crashes there.
|
|
502
|
-
for _s in (sys.stdout, sys.stderr):
|
|
503
|
-
if hasattr(_s, "reconfigure"):
|
|
504
|
-
_s.reconfigure(encoding="utf-8")
|
|
496
|
+
utf8_stdio()
|
|
505
497
|
main()
|
package/tools/signal_tracker.py
CHANGED
|
@@ -18,7 +18,7 @@ from pathlib import Path
|
|
|
18
18
|
from uuid import uuid4
|
|
19
19
|
|
|
20
20
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
21
|
-
from _subproc import run_tool # noqa: E402
|
|
21
|
+
from _subproc import run_tool, utf8_stdio # noqa: E402
|
|
22
22
|
from stock_data import detect_market # noqa: E402
|
|
23
23
|
|
|
24
24
|
|
|
@@ -267,9 +267,5 @@ def main():
|
|
|
267
267
|
|
|
268
268
|
|
|
269
269
|
if __name__ == "__main__":
|
|
270
|
-
|
|
271
|
-
# Chinese text these tools emit — force UTF-8 so stdout never crashes there.
|
|
272
|
-
for _s in (sys.stdout, sys.stderr):
|
|
273
|
-
if hasattr(_s, "reconfigure"):
|
|
274
|
-
_s.reconfigure(encoding="utf-8")
|
|
270
|
+
utf8_stdio()
|
|
275
271
|
main()
|