openclaw-stock-analysis 0.2.2 → 0.2.5
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 +2 -2
- package/dist/index.js +170 -23
- package/index.ts +184 -26
- package/openclaw.plugin.json +10 -1
- package/package.json +1 -1
- package/scripts/ci-resolve-llm-host.mjs +29 -0
- package/scripts/setup-python.mjs +7 -9
- package/skills/event-driven/SKILL.md +6 -0
- package/skills/growth-quality/SKILL.md +6 -0
- package/skills/hot-theme/SKILL.md +3 -2
- package/skills/stock-analysis/SKILL.md +22 -0
- package/skills/stock-screener/SKILL.md +19 -1
- package/skills/strategy-backtest/SKILL.md +11 -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/_cache.py +61 -0
- 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 +13 -5
- package/tools/diagnostics.py +12 -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 +80 -18
- package/tools/search_intel.py +5 -13
- package/tools/signal_tracker.py +2 -6
- package/tools/stock_data.py +520 -169
- package/tools/technical.py +136 -40
- package/tools/trading_calendar.py +78 -18
- package/tools/value_data.py +1368 -0
- package/tools/volume_analysis.py +2 -5
- package/tools/watchlist.py +2 -5
- package/tools/watchlist_context.py +2 -5
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
|
|
|
@@ -73,6 +73,13 @@ def merge_filters(config: dict | None) -> dict:
|
|
|
73
73
|
|
|
74
74
|
def apply_filters(df: pd.DataFrame, filters: dict) -> pd.DataFrame:
|
|
75
75
|
conditions = []
|
|
76
|
+
for bound, op in [("dividend_yield_min", "min"), ("dividend_yield_max", "max")]:
|
|
77
|
+
if bound in filters:
|
|
78
|
+
if "dividend_yield" not in df.columns:
|
|
79
|
+
return df.iloc[0:0].copy()
|
|
80
|
+
conditions.append(
|
|
81
|
+
df["dividend_yield"] >= filters[bound] if op == "min" else df["dividend_yield"] <= filters[bound]
|
|
82
|
+
)
|
|
76
83
|
if "pe" in df.columns:
|
|
77
84
|
conditions.append(df["pe"] >= filters["pe_min"])
|
|
78
85
|
conditions.append(df["pe"] <= filters["pe_max"])
|
|
@@ -105,6 +112,15 @@ def _minmax(s: pd.Series) -> pd.Series:
|
|
|
105
112
|
return ((s - mn) / (mx - mn) * 100).clip(0, 100)
|
|
106
113
|
|
|
107
114
|
|
|
115
|
+
def _finite(v):
|
|
116
|
+
"""NaN/±inf → None. An all-empty factor column min-maxes to NaN, and json.dumps
|
|
117
|
+
would emit bare NaN/Infinity tokens that strict parsers in the host adapters
|
|
118
|
+
reject — so non-finite values never reach the output contract."""
|
|
119
|
+
if isinstance(v, (int, float, np.floating)) and not np.isfinite(v):
|
|
120
|
+
return None
|
|
121
|
+
return v
|
|
122
|
+
|
|
123
|
+
|
|
108
124
|
def compute_scores(df: pd.DataFrame) -> pd.DataFrame:
|
|
109
125
|
# Value: lower PE/PB → higher score (inverted)
|
|
110
126
|
value_parts = []
|
|
@@ -112,7 +128,10 @@ def compute_scores(df: pd.DataFrame) -> pd.DataFrame:
|
|
|
112
128
|
value_parts.append(100 - _minmax(df["pe"]))
|
|
113
129
|
if "pb" in df.columns:
|
|
114
130
|
value_parts.append(100 - _minmax(df["pb"]))
|
|
115
|
-
|
|
131
|
+
if "dividend_yield" in df.columns:
|
|
132
|
+
df["dividend_score"] = _minmax(df["dividend_yield"])
|
|
133
|
+
value_parts.append(df["dividend_score"])
|
|
134
|
+
df["value_score"] = pd.concat(value_parts, axis=1).mean(axis=1) if value_parts else 0.0
|
|
116
135
|
|
|
117
136
|
# Momentum: higher change_pct and volume_ratio → higher score
|
|
118
137
|
mom_parts = []
|
|
@@ -277,9 +296,10 @@ def _apply_l2(candidates: list, market: str, multiplier: float) -> None:
|
|
|
277
296
|
groups = factor_scores.get(sym, {})
|
|
278
297
|
c["enriched"] = bool(enrichments.get(sym))
|
|
279
298
|
scores = c["scores"]
|
|
299
|
+
# scores are sanitized to None when non-finite; L2 math needs numbers
|
|
280
300
|
components = {
|
|
281
|
-
"value": scores["value"],
|
|
282
|
-
"liquidity": scores["liquidity"],
|
|
301
|
+
"value": scores["value"] or 0,
|
|
302
|
+
"liquidity": scores["liquidity"] or 0,
|
|
283
303
|
}
|
|
284
304
|
# momentum is L2-only: candidates without kline factors drop the group and renormalize weights.
|
|
285
305
|
components.update(
|
|
@@ -294,9 +314,27 @@ def _apply_l2(candidates: list, market: str, multiplier: float) -> None:
|
|
|
294
314
|
|
|
295
315
|
|
|
296
316
|
def screen(market: str, top: int, config: dict | None, l2: bool = False) -> dict:
|
|
317
|
+
filters = merge_filters(config)
|
|
318
|
+
dividend_requested = any(k.startswith("dividend_yield_") for k in filters) or (config or {}).get("sort_by") in (
|
|
319
|
+
"dividend_yield",
|
|
320
|
+
"dividend_score",
|
|
321
|
+
)
|
|
322
|
+
if dividend_requested and market not in ("A", "HK"):
|
|
323
|
+
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}
|
|
297
331
|
raw = fetch_snapshot(market)
|
|
298
332
|
if isinstance(raw, dict) and "error" in raw:
|
|
299
333
|
return raw
|
|
334
|
+
# snapshot legs wrap a total failure as a one-row [{"error": ...}] list — surface it
|
|
335
|
+
# instead of letting the error row walk the scoring pipeline as a ghost candidate
|
|
336
|
+
if isinstance(raw, list) and len(raw) == 1 and isinstance(raw[0], dict) and "error" in raw[0]:
|
|
337
|
+
return {**raw[0], "market": market}
|
|
300
338
|
if raw is None:
|
|
301
339
|
return {"error": "failed to fetch market snapshot", "market": market}
|
|
302
340
|
|
|
@@ -316,7 +354,30 @@ def screen(market: str, top: int, config: dict | None, l2: bool = False) -> dict
|
|
|
316
354
|
if existing:
|
|
317
355
|
df = df.dropna(subset=existing)
|
|
318
356
|
|
|
319
|
-
|
|
357
|
+
dividend_meta = {}
|
|
358
|
+
if dividend_requested:
|
|
359
|
+
try:
|
|
360
|
+
from value_data import dividend_ranking
|
|
361
|
+
|
|
362
|
+
ranked = dividend_ranking(report_date=(config or {}).get("dividend_report_date", ""), market=market)
|
|
363
|
+
|
|
364
|
+
def dividend_key(symbol):
|
|
365
|
+
return symbol.split(".")[0].lstrip("0") if market == "HK" else symbol
|
|
366
|
+
|
|
367
|
+
yields = {dividend_key(r["symbol"]): r["dividend_yield"] for r in ranked["items"]}
|
|
368
|
+
df["dividend_yield"] = df["symbol"].map(dividend_key).map(yields)
|
|
369
|
+
dividend_meta = {
|
|
370
|
+
"dividend_factor": {
|
|
371
|
+
"report_date": ranked["report_date"],
|
|
372
|
+
"yield_basis": ranked.get("yield_basis", "provider report-period cash dividend yield, percent"),
|
|
373
|
+
"missing": "unknown; excluded by dividend filters",
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
except Exception:
|
|
377
|
+
return {
|
|
378
|
+
"error": "dividend data unavailable; requested dividend criterion was not applied",
|
|
379
|
+
"market": market,
|
|
380
|
+
}
|
|
320
381
|
df = apply_filters(df, filters)
|
|
321
382
|
filtered_count = len(df)
|
|
322
383
|
|
|
@@ -330,6 +391,7 @@ def screen(market: str, top: int, config: dict | None, l2: bool = False) -> dict
|
|
|
330
391
|
"candidates": [],
|
|
331
392
|
"market_sentiment": sentiment,
|
|
332
393
|
"l2_enabled": l2_enabled,
|
|
394
|
+
**dividend_meta,
|
|
333
395
|
}
|
|
334
396
|
|
|
335
397
|
df = compute_scores(df)
|
|
@@ -360,18 +422,21 @@ def screen(market: str, top: int, config: dict | None, l2: bool = False) -> dict
|
|
|
360
422
|
"pb",
|
|
361
423
|
"market_cap",
|
|
362
424
|
"volume_ratio",
|
|
425
|
+
"dividend_yield",
|
|
363
426
|
]:
|
|
364
|
-
v = row.get(field)
|
|
365
|
-
if v is not None
|
|
427
|
+
v = _finite(row.get(field))
|
|
428
|
+
if v is not None:
|
|
366
429
|
entry[field] = round(float(v), 2) if isinstance(v, (float, np.floating)) else v
|
|
367
|
-
composite = float(row.get("composite_score", 0))
|
|
430
|
+
composite = _finite(float(row.get("composite_score", 0)))
|
|
368
431
|
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),
|
|
432
|
+
"value": _finite(round(float(row.get("value_score", 0)), 1)),
|
|
433
|
+
"momentum": _finite(round(float(row.get("momentum_score", 0)), 1)),
|
|
434
|
+
"liquidity": _finite(round(float(row.get("liquidity_score", 0)), 1)),
|
|
435
|
+
"composite": None if composite is None else round(composite, 1),
|
|
436
|
+
"final": None if composite is None else round(composite * multiplier, 1),
|
|
374
437
|
}
|
|
438
|
+
if "dividend_score" in row:
|
|
439
|
+
entry["scores"]["dividend"] = _finite(round(float(row["dividend_score"]), 1))
|
|
375
440
|
candidates.append(entry)
|
|
376
441
|
|
|
377
442
|
if l2_enabled:
|
|
@@ -389,6 +454,7 @@ def screen(market: str, top: int, config: dict | None, l2: bool = False) -> dict
|
|
|
389
454
|
"candidates": candidates,
|
|
390
455
|
"market_sentiment": sentiment,
|
|
391
456
|
"l2_enabled": l2_enabled,
|
|
457
|
+
**dividend_meta,
|
|
392
458
|
}
|
|
393
459
|
|
|
394
460
|
|
|
@@ -415,9 +481,5 @@ def main():
|
|
|
415
481
|
|
|
416
482
|
|
|
417
483
|
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")
|
|
484
|
+
utf8_stdio()
|
|
423
485
|
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()
|