openclaw-stock-analysis 0.2.2 → 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/LICENSE +21 -0
- package/README.md +2 -2
- package/dist/index.js +228 -30
- package/index.ts +246 -33
- package/openclaw.plugin.json +13 -1
- package/package.json +1 -1
- package/schemas/report_schema.json +3 -3
- package/scripts/ci-resolve-llm-host.mjs +29 -0
- package/scripts/setup-python.mjs +11 -13
- 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 +8 -0
- package/skills/growth-quality/SKILL.md +8 -0
- package/skills/hot-theme/SKILL.md +3 -2
- package/skills/stock-analysis/SKILL.md +31 -3
- package/skills/stock-screener/SKILL.md +21 -1
- package/skills/strategy-backtest/SKILL.md +15 -5
- package/skills/wisburg-research/SKILL.md +2 -0
- 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/templates/stock_analysis/brief.md.j2 +4 -1
- package/templates/stock_analysis/full.md.j2 +6 -3
- package/tools/_cache.py +61 -0
- package/tools/_subproc.py +49 -0
- package/tools/alert_rules.py +51 -13
- package/tools/anomaly_detect.py +24 -35
- package/tools/backtest.py +202 -104
- package/tools/capabilities.py +16 -5
- package/tools/diagnostics.py +12 -6
- package/tools/gather.py +33 -19
- package/tools/import_parser.py +2 -5
- package/tools/lixinger.py +100 -0
- package/tools/market_regime.py +34 -38
- package/tools/market_review.py +57 -9
- package/tools/name_resolver.py +2 -5
- package/tools/pattern.py +2 -5
- package/tools/position_context.py +22 -7
- package/tools/report_renderer.py +12 -6
- package/tools/requirements.txt +2 -1
- package/tools/risk_screening.py +73 -39
- package/tools/screener.py +90 -20
- package/tools/search_intel.py +5 -13
- package/tools/sec_edgar.py +346 -0
- package/tools/sec_holders.py +263 -0
- package/tools/signal_tracker.py +144 -25
- package/tools/stock_data.py +600 -186
- package/tools/technical.py +152 -42
- package/tools/trading_calendar.py +78 -18
- package/tools/value_data.py +1527 -0
- package/tools/volume_analysis.py +2 -5
- package/tools/watchlist.py +26 -6
- package/tools/watchlist_context.py +9 -8
|
@@ -26,7 +26,8 @@ entry:
|
|
|
26
26
|
exit:
|
|
27
27
|
conditions:
|
|
28
28
|
- indicator: "ma_diff"
|
|
29
|
-
|
|
29
|
+
fast_period: 5
|
|
30
|
+
slow_period: 10
|
|
30
31
|
operator: "cross_below"
|
|
31
32
|
value: 0
|
|
32
33
|
- indicator: "rsi"
|
|
@@ -37,6 +38,11 @@ exit:
|
|
|
37
38
|
stop_loss: "{stop_loss}"
|
|
38
39
|
take_profit: "{take_profit}"
|
|
39
40
|
|
|
41
|
+
simulation:
|
|
42
|
+
slippage: 0.001 # 滑点(买卖双边)
|
|
43
|
+
commission: 0.00025 # 佣金(买卖双边,A股常见万2.5)
|
|
44
|
+
stamp_tax: 0.0005 # 印花税(A股卖出单边;其他市场按当下实际费率,无则删除本行)
|
|
45
|
+
|
|
40
46
|
position:
|
|
41
47
|
size: 0.8
|
|
42
48
|
max_positions: 1
|
|
@@ -7,11 +7,14 @@
|
|
|
7
7
|
{% if risk_screening and risk_screening.veto_buy %}
|
|
8
8
|
⚠️ **一票否决** — 风险筛查触发,建议谨慎。
|
|
9
9
|
{% endif %}
|
|
10
|
+
{% if risk_screening and (risk_screening.data_complete is sameas false or risk_screening.risk_level == 'unknown') %}
|
|
11
|
+
⚠️ **数据不完整** — 当前风险筛查不能判定为低风险。
|
|
12
|
+
{% endif %}
|
|
10
13
|
|
|
11
14
|
{% set dp = data_perspective or {} -%}
|
|
12
15
|
{% set pp = dp.price_position or {} -%}
|
|
13
16
|
{% set ts = dp.trend_status or {} -%}
|
|
14
|
-
- 📈 **趋势:** {{ ts.ma_alignment or '-' }}{% if ts.is_bullish is
|
|
17
|
+
- 📈 **趋势:** {{ ts.ma_alignment or '-' }}{% if ts.is_bullish is boolean %}({{ '看多' if ts.is_bullish else '看空' }}){% endif %}
|
|
15
18
|
- 💰 **价位:** 现价 {{ m.fmt_num(pp.current_price) }} | 支撑 {{ m.fmt_num(pp.support_level) }} | 压力 {{ m.fmt_num(pp.resistance_level) }}
|
|
16
19
|
|
|
17
20
|
{% set bp = battle_plan or {} -%}
|
|
@@ -26,12 +26,15 @@
|
|
|
26
26
|
## 风险筛查
|
|
27
27
|
|
|
28
28
|
{% if risk_screening -%}
|
|
29
|
-
- **风险等级:** {{ m.risk_emoji(risk_screening.risk_level) }} {{ risk_screening.risk_level or '-' }} | **风险分:** {{ risk_screening.risk_score }}/100
|
|
29
|
+
- **风险等级:** {{ m.risk_emoji(risk_screening.risk_level) }} {{ risk_screening.risk_level or '-' }} | **风险分:** {{ m.fmt_num(risk_screening.risk_score, 0) }}/100
|
|
30
|
+
{% if risk_screening.data_complete is sameas false or risk_screening.risk_level == 'unknown' -%}
|
|
31
|
+
- **数据不完整:** {{ risk_screening.warnings | join(';') }},当前结果不能判定为低风险。
|
|
32
|
+
{% endif %}
|
|
30
33
|
{% if risk_screening.flags -%}
|
|
31
34
|
- **风险标记:**
|
|
32
35
|
{% for f in risk_screening.flags %} - [{{ f.severity }}] {{ f.category }}:{{ f.description }}
|
|
33
36
|
{% endfor %}
|
|
34
|
-
{%-
|
|
37
|
+
{%- elif risk_screening.data_complete is not sameas false and risk_screening.risk_level != 'unknown' -%}
|
|
35
38
|
- **风险标记:** 无显著风险标记
|
|
36
39
|
{%- endif %}
|
|
37
40
|
{%- else -%}
|
|
@@ -45,7 +48,7 @@
|
|
|
45
48
|
{% set pp = dp.price_position or {} -%}
|
|
46
49
|
{% set vol = dp.volume_analysis or {} -%}
|
|
47
50
|
{% set chip = dp.chip_structure or {} -%}
|
|
48
|
-
- **趋势:** {{ ts.ma_alignment or '-' }}{% if ts.is_bullish is
|
|
51
|
+
- **趋势:** {{ ts.ma_alignment or '-' }}{% if ts.is_bullish is boolean %}({{ '看多' if ts.is_bullish else '看空' }}){% endif %}{% if ts.trend_score is not none %} 趋势分 {{ m.fmt_num(ts.trend_score) }}{% endif %}
|
|
49
52
|
- **价格结构:** 现价 {{ m.fmt_num(pp.current_price) }} | 偏离 MA5 {{ m.change_pct(pp.bias_ma5) }} | 支撑 {{ m.fmt_num(pp.support_level) }} | 压力 {{ m.fmt_num(pp.resistance_level) }}
|
|
50
53
|
- **量价:** 量比 {{ m.fmt_num(vol.volume_ratio) }}{% if vol.volume_status %}({{ vol.volume_status }}){% endif %}{% if vol.turnover_rate is not none %} | 换手率 {{ m.change_pct(vol.turnover_rate) }}{% endif %}
|
|
51
54
|
{% if chip and (chip.profit_ratio is not none or chip.avg_cost is not none) -%}
|
package/tools/_cache.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""TTL cache for slow public datasets; live quotes and errors are never stored."""
|
|
2
|
+
|
|
3
|
+
import contextlib
|
|
4
|
+
import hashlib
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import tempfile
|
|
8
|
+
import time
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
CACHE_DIR = Path.home() / ".stock-analysis" / "cache"
|
|
12
|
+
DAY = 86400
|
|
13
|
+
WEEK = 7 * DAY
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _namespace_prefix(namespace):
|
|
17
|
+
return hashlib.sha256(namespace.encode()).hexdigest()[:12]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _read(path, ttl):
|
|
21
|
+
try:
|
|
22
|
+
entry = json.loads(path.read_text(encoding="utf-8"))
|
|
23
|
+
if 0 <= time.time() - entry["fetched_at"] < ttl:
|
|
24
|
+
return entry
|
|
25
|
+
except (OSError, ValueError, KeyError, TypeError):
|
|
26
|
+
pass
|
|
27
|
+
return None
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def cached_values(namespace, ttl):
|
|
31
|
+
for path in CACHE_DIR.glob(f"{_namespace_prefix(namespace)}-*.json"):
|
|
32
|
+
entry = _read(path, ttl)
|
|
33
|
+
if entry and str(entry.get("key", "")).startswith(namespace + ":"):
|
|
34
|
+
yield entry.get("data")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def cached(key: str, ttl: int, fetch):
|
|
38
|
+
path = CACHE_DIR / f"{_namespace_prefix(key.partition(':')[0])}-{hashlib.sha256(key.encode()).hexdigest()}.json"
|
|
39
|
+
entry = _read(path, ttl)
|
|
40
|
+
if entry and "data" in entry:
|
|
41
|
+
return entry["data"]
|
|
42
|
+
result = fetch()
|
|
43
|
+
rows = result if isinstance(result, list) else [result]
|
|
44
|
+
if not result or any(isinstance(row, dict) and (row.get("error") or row.get("warnings")) for row in rows):
|
|
45
|
+
return result
|
|
46
|
+
tmp = None
|
|
47
|
+
try:
|
|
48
|
+
CACHE_DIR.mkdir(parents=True, exist_ok=True)
|
|
49
|
+
with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=CACHE_DIR, delete=False) as stream:
|
|
50
|
+
tmp = stream.name
|
|
51
|
+
json.dump(
|
|
52
|
+
{"key": key, "fetched_at": time.time(), "data": result}, stream, ensure_ascii=False, allow_nan=False
|
|
53
|
+
)
|
|
54
|
+
os.replace(tmp, path)
|
|
55
|
+
except (OSError, ValueError, TypeError):
|
|
56
|
+
pass
|
|
57
|
+
finally:
|
|
58
|
+
if tmp:
|
|
59
|
+
with contextlib.suppress(OSError):
|
|
60
|
+
Path(tmp).unlink(missing_ok=True)
|
|
61
|
+
return result
|
package/tools/_subproc.py
CHANGED
|
@@ -6,8 +6,12 @@ so this resolves both when a tool runs as a script (sys.path[0] = tools/) and wh
|
|
|
6
6
|
pytest imports it as tools.*.
|
|
7
7
|
"""
|
|
8
8
|
|
|
9
|
+
import contextlib
|
|
9
10
|
import json
|
|
11
|
+
import math
|
|
10
12
|
import os
|
|
13
|
+
import re
|
|
14
|
+
import socket
|
|
11
15
|
import subprocess
|
|
12
16
|
import sys
|
|
13
17
|
|
|
@@ -44,3 +48,48 @@ def run_tool(script: str, args: list, timeout: int = 30, parse_json: bool = True
|
|
|
44
48
|
except Exception:
|
|
45
49
|
pass
|
|
46
50
|
return None
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def utf8_stdio() -> None:
|
|
54
|
+
"""Force UTF-8 stdio. Windows defaults stdio to a legacy code page (cp1252)
|
|
55
|
+
that cannot encode the Chinese text these tools emit — call at CLI entry."""
|
|
56
|
+
for s in (sys.stdout, sys.stderr):
|
|
57
|
+
if hasattr(s, "reconfigure"):
|
|
58
|
+
s.reconfigure(encoding="utf-8")
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@contextlib.contextmanager
|
|
62
|
+
def socket_timeout(seconds: float):
|
|
63
|
+
"""Bound every blocking socket op for the wrapped chain's duration: akshare/efinance
|
|
64
|
+
leave requests timeout-less, so on a blackholed network a leg hangs until the kernel
|
|
65
|
+
TCP timeout (~2min) and the chain would overrun the caller's subprocess budget before
|
|
66
|
+
ever reaching the plain-HTTPS legs. try/finally always restores the previous default
|
|
67
|
+
(no global-state leak); explicit per-request timeouts (tencent/sina legs) still win."""
|
|
68
|
+
old_timeout = socket.getdefaulttimeout()
|
|
69
|
+
socket.setdefaulttimeout(seconds)
|
|
70
|
+
try:
|
|
71
|
+
yield
|
|
72
|
+
finally:
|
|
73
|
+
socket.setdefaulttimeout(old_timeout)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
_SECRET_PARAM_RE = re.compile(r"(?i)((?:api[_-]?key|token|secret|access[_-]?token)=)[^&\s]+")
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def scrub_secrets(msg: str) -> str:
|
|
80
|
+
"""Error text may embed request URLs (requests connection errors) — never leak keys
|
|
81
|
+
into stdout JSON."""
|
|
82
|
+
return _SECRET_PARAM_RE.sub(r"\1***", msg)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def json_safe(obj):
|
|
86
|
+
"""Replace non-finite floats (inf/-inf/nan, e.g. an all-flat P&L profit_loss_ratio)
|
|
87
|
+
with None so json.dumps never emits the non-standard Infinity/NaN tokens that
|
|
88
|
+
break strict JSON.parse hosts."""
|
|
89
|
+
if isinstance(obj, float):
|
|
90
|
+
return obj if math.isfinite(obj) else None
|
|
91
|
+
if isinstance(obj, dict):
|
|
92
|
+
return {k: json_safe(v) for k, v in obj.items()}
|
|
93
|
+
if isinstance(obj, list):
|
|
94
|
+
return [json_safe(v) for v in obj]
|
|
95
|
+
return obj
|
package/tools/alert_rules.py
CHANGED
|
@@ -6,12 +6,15 @@ Does NOT store history, does NOT push, does NOT schedule. Host agent decides whe
|
|
|
6
6
|
|
|
7
7
|
import argparse
|
|
8
8
|
import json
|
|
9
|
+
import math
|
|
9
10
|
import sys
|
|
11
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
10
12
|
from datetime import datetime, timezone
|
|
11
13
|
from pathlib import Path
|
|
12
14
|
|
|
13
15
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
14
16
|
from _subproc import run_tool as _run_json # noqa: E402
|
|
17
|
+
from _subproc import utf8_stdio
|
|
15
18
|
from stock_data import detect_market # noqa: E402
|
|
16
19
|
|
|
17
20
|
RULE_TYPES = {
|
|
@@ -29,8 +32,14 @@ RULE_TYPES = {
|
|
|
29
32
|
def _check_rule(rule: dict, quote: dict, tech: dict, anom: dict, risk: dict) -> dict | None:
|
|
30
33
|
rtype = rule.get("type")
|
|
31
34
|
value = rule.get("value")
|
|
32
|
-
if rtype not in RULE_TYPES:
|
|
35
|
+
if not isinstance(rtype, str) or rtype not in RULE_TYPES:
|
|
33
36
|
return {"rule": rtype, "triggered": False, "error": f"unknown rule type: {rtype}"}
|
|
37
|
+
if rtype in ("price_below", "price_above", "change_pct_above", "change_pct_below", "volume_ratio_above"):
|
|
38
|
+
try:
|
|
39
|
+
if isinstance(value, bool) or not math.isfinite(float(value)):
|
|
40
|
+
raise ValueError
|
|
41
|
+
except (ValueError, TypeError):
|
|
42
|
+
return {"rule": rtype, "triggered": False, "error": "Rule value must be a finite number"}
|
|
34
43
|
|
|
35
44
|
price = quote.get("price")
|
|
36
45
|
change_pct = quote.get("change_pct")
|
|
@@ -88,6 +97,8 @@ def _check_rule(rule: dict, quote: dict, tech: dict, anom: dict, risk: dict) ->
|
|
|
88
97
|
"message": f"量比 {ratio} 超过 {value}",
|
|
89
98
|
}
|
|
90
99
|
elif rtype == "anomaly":
|
|
100
|
+
if not isinstance(value, str) or not value:
|
|
101
|
+
return {"rule": rtype, "triggered": False, "error": "Anomaly type must be a nonempty string"}
|
|
91
102
|
# value is an anomaly type string, e.g. "macd_golden_cross"
|
|
92
103
|
anomalies = (anom or {}).get("anomalies", [])
|
|
93
104
|
for a in anomalies:
|
|
@@ -104,6 +115,8 @@ def _check_rule(rule: dict, quote: dict, tech: dict, anom: dict, risk: dict) ->
|
|
|
104
115
|
return {"rule": rtype, "triggered": True, "severity": "high", "message": "风险筛查触发一票否决"}
|
|
105
116
|
elif rtype == "risk_level_at_least":
|
|
106
117
|
order = {"low": 0, "medium": 1, "high": 2}
|
|
118
|
+
if not isinstance(value, str) or value not in order:
|
|
119
|
+
return {"rule": rtype, "triggered": False, "error": "Risk threshold must be low/medium/high"}
|
|
107
120
|
cur = order.get((risk or {}).get("risk_level"))
|
|
108
121
|
want = order.get(value)
|
|
109
122
|
if cur is not None and want is not None and cur >= want:
|
|
@@ -120,17 +133,32 @@ def _check_rule(rule: dict, quote: dict, tech: dict, anom: dict, risk: dict) ->
|
|
|
120
133
|
|
|
121
134
|
|
|
122
135
|
def check_rules(symbol: str, rules: list[dict]) -> dict:
|
|
123
|
-
if not rules:
|
|
136
|
+
if not isinstance(rules, list) or not rules or any(not isinstance(rule, dict) for rule in rules):
|
|
124
137
|
return {"symbol": symbol, "error": "no rules provided"}
|
|
125
138
|
|
|
126
139
|
needs_tech = any(r.get("type") == "volume_ratio_above" for r in rules)
|
|
127
140
|
needs_anom = any(r.get("type") == "anomaly" for r in rules)
|
|
128
141
|
needs_risk = any(r.get("type") in ("risk_veto", "risk_level_at_least") for r in rules)
|
|
129
142
|
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
143
|
+
# the fetches are independent subprocesses — fan out concurrently (same
|
|
144
|
+
# ThreadPoolExecutor pattern as gather._run_all), then read back in fixed order
|
|
145
|
+
jobs = {"quote": ("stock_data.py", ["quote", symbol])}
|
|
146
|
+
if needs_tech:
|
|
147
|
+
jobs["tech"] = ("technical.py", ["analyze", symbol, "--period", "daily", "--count", "60"])
|
|
148
|
+
if needs_anom:
|
|
149
|
+
jobs["anom"] = ("anomaly_detect.py", ["detect", symbol])
|
|
150
|
+
if needs_risk:
|
|
151
|
+
jobs["risk"] = ("risk_screening.py", ["screen", symbol])
|
|
152
|
+
with ThreadPoolExecutor(max_workers=len(jobs)) as pool:
|
|
153
|
+
futures = {key: pool.submit(_run_json, script, args) for key, (script, args) in jobs.items()}
|
|
154
|
+
fetched = {key: future.result() for key, future in futures.items()}
|
|
155
|
+
fetched = {
|
|
156
|
+
key: value if isinstance(value, dict) and "error" not in value else None for key, value in fetched.items()
|
|
157
|
+
}
|
|
158
|
+
quote = fetched["quote"] or {}
|
|
159
|
+
tech = fetched.get("tech")
|
|
160
|
+
anom = fetched.get("anom")
|
|
161
|
+
risk = fetched.get("risk")
|
|
134
162
|
|
|
135
163
|
warnings = []
|
|
136
164
|
if not quote or quote.get("price") is None:
|
|
@@ -139,13 +167,25 @@ def check_rules(symbol: str, rules: list[dict]) -> dict:
|
|
|
139
167
|
warnings.append("technical analysis fetch failed — volume_ratio rules cannot fire")
|
|
140
168
|
if needs_anom and not anom:
|
|
141
169
|
warnings.append("anomaly fetch failed — anomaly rules cannot fire")
|
|
142
|
-
if needs_risk and not risk:
|
|
170
|
+
if needs_risk and (not risk or risk.get("data_complete") is False or risk.get("risk_level") == "unknown"):
|
|
143
171
|
warnings.append("risk screening fetch failed — risk rules cannot fire")
|
|
144
172
|
|
|
145
173
|
hits = []
|
|
146
174
|
evaluated = []
|
|
147
175
|
for rule in rules:
|
|
148
|
-
|
|
176
|
+
rtype = rule.get("type")
|
|
177
|
+
missing = (
|
|
178
|
+
(rtype in ("price_below", "price_above") and quote.get("price") is None)
|
|
179
|
+
or (rtype in ("change_pct_below", "change_pct_above") and quote.get("change_pct") is None)
|
|
180
|
+
or (rtype == "volume_ratio_above" and (tech or {}).get("volume", {}).get("volume_ratio") is None)
|
|
181
|
+
or (rtype == "anomaly" and not isinstance((anom or {}).get("anomalies"), list))
|
|
182
|
+
or (rtype == "risk_veto" and (risk or {}).get("veto_buy") is None)
|
|
183
|
+
or (rtype == "risk_level_at_least" and (risk or {}).get("risk_level") not in ("low", "medium", "high"))
|
|
184
|
+
)
|
|
185
|
+
if missing:
|
|
186
|
+
result = {"rule": rtype, "triggered": False, "error": "Required source data unavailable"}
|
|
187
|
+
else:
|
|
188
|
+
result = _check_rule(rule, quote, tech, anom, risk)
|
|
149
189
|
if result is None:
|
|
150
190
|
evaluated.append({"rule": rule.get("type"), "triggered": False})
|
|
151
191
|
else:
|
|
@@ -200,12 +240,10 @@ def main():
|
|
|
200
240
|
result = check_rules(args.symbol, rules)
|
|
201
241
|
json.dump(result, sys.stdout, ensure_ascii=False, indent=2, default=str)
|
|
202
242
|
print()
|
|
243
|
+
if "error" in result:
|
|
244
|
+
sys.exit(1)
|
|
203
245
|
|
|
204
246
|
|
|
205
247
|
if __name__ == "__main__":
|
|
206
|
-
|
|
207
|
-
# Chinese text these tools emit — force UTF-8 so stdout never crashes there.
|
|
208
|
-
for _s in (sys.stdout, sys.stderr):
|
|
209
|
-
if hasattr(_s, "reconfigure"):
|
|
210
|
-
_s.reconfigure(encoding="utf-8")
|
|
248
|
+
utf8_stdio()
|
|
211
249
|
main()
|
package/tools/anomaly_detect.py
CHANGED
|
@@ -12,8 +12,17 @@ import pandas as pd
|
|
|
12
12
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
13
13
|
|
|
14
14
|
from _subproc import run_tool as _run_tool
|
|
15
|
-
from
|
|
16
|
-
from
|
|
15
|
+
from _subproc import utf8_stdio
|
|
16
|
+
from stock_data import calc_limit_price, detect_market, normalize_stock_code
|
|
17
|
+
from technical import (
|
|
18
|
+
bollinger_series,
|
|
19
|
+
fetch_kline,
|
|
20
|
+
kdj_series,
|
|
21
|
+
ma_series,
|
|
22
|
+
macd_series,
|
|
23
|
+
rsi_series,
|
|
24
|
+
to_dataframe,
|
|
25
|
+
)
|
|
17
26
|
|
|
18
27
|
|
|
19
28
|
def _anomaly(type_: str, severity: str, direction: str, description: str, **extra) -> dict:
|
|
@@ -33,10 +42,7 @@ def _anomaly(type_: str, severity: str, direction: str, description: str, **extr
|
|
|
33
42
|
def detect_macd_cross(close: pd.Series) -> list:
|
|
34
43
|
if len(close) < 30:
|
|
35
44
|
return []
|
|
36
|
-
|
|
37
|
-
ema26 = close.ewm(span=26, adjust=False).mean()
|
|
38
|
-
dif = ema12 - ema26
|
|
39
|
-
dea = dif.ewm(span=9, adjust=False).mean()
|
|
45
|
+
dif, dea, _ = macd_series(close)
|
|
40
46
|
|
|
41
47
|
prev_diff = float(dif.iloc[-2] - dea.iloc[-2])
|
|
42
48
|
curr_diff = float(dif.iloc[-1] - dea.iloc[-1])
|
|
@@ -58,11 +64,7 @@ def detect_macd_cross(close: pd.Series) -> list:
|
|
|
58
64
|
def detect_rsi_extreme(close: pd.Series) -> list:
|
|
59
65
|
if len(close) < 10:
|
|
60
66
|
return []
|
|
61
|
-
|
|
62
|
-
gain = delta.where(delta > 0, 0.0).rolling(6).mean()
|
|
63
|
-
loss = (-delta.where(delta < 0, 0.0)).rolling(6).mean()
|
|
64
|
-
rs = gain / loss.replace(0, np.nan)
|
|
65
|
-
rsi = 100 - 100 / (1 + rs)
|
|
67
|
+
rsi = rsi_series(close, 6)
|
|
66
68
|
|
|
67
69
|
if len(rsi.dropna()) < 2:
|
|
68
70
|
return []
|
|
@@ -166,10 +168,7 @@ def detect_volume_spike(volume: pd.Series) -> list:
|
|
|
166
168
|
def detect_bollinger_breakout(close: pd.Series) -> list:
|
|
167
169
|
if len(close) < 21:
|
|
168
170
|
return []
|
|
169
|
-
|
|
170
|
-
std = close.rolling(20).std()
|
|
171
|
-
upper = mid + 2 * std
|
|
172
|
-
lower = mid - 2 * std
|
|
171
|
+
upper, _, lower = bollinger_series(close)
|
|
173
172
|
|
|
174
173
|
curr_price = float(close.iloc[-1])
|
|
175
174
|
prev_price = float(close.iloc[-2])
|
|
@@ -205,13 +204,7 @@ def detect_bollinger_breakout(close: pd.Series) -> list:
|
|
|
205
204
|
def detect_kdj_extreme(high: pd.Series, low: pd.Series, close: pd.Series) -> list:
|
|
206
205
|
if len(close) < 10:
|
|
207
206
|
return []
|
|
208
|
-
|
|
209
|
-
high_n = high.rolling(9).max()
|
|
210
|
-
rsv = (close - low_n) / (high_n - low_n).replace(0, np.nan) * 100
|
|
211
|
-
rsv = rsv.fillna(50)
|
|
212
|
-
k = rsv.ewm(com=2, adjust=False).mean()
|
|
213
|
-
d = k.ewm(com=2, adjust=False).mean()
|
|
214
|
-
j = 3 * k - 2 * d
|
|
207
|
+
_, _, j = kdj_series(high, low, close)
|
|
215
208
|
|
|
216
209
|
if len(j.dropna()) < 2:
|
|
217
210
|
return []
|
|
@@ -315,8 +308,10 @@ def detect_limit_hit(symbol: str, quote: dict) -> list:
|
|
|
315
308
|
|
|
316
309
|
prev_close = float(prev_close)
|
|
317
310
|
price = float(price)
|
|
318
|
-
|
|
319
|
-
|
|
311
|
+
# Exchange rounding (floor(x*100+0.5)/100), same as stock_data's market_stats,
|
|
312
|
+
# so both tools reach the same limit-up/down conclusion for a given quote.
|
|
313
|
+
limit_up_price = calc_limit_price(prev_close, limit_pct, "up")
|
|
314
|
+
limit_down_price = calc_limit_price(prev_close, limit_pct, "down")
|
|
320
315
|
|
|
321
316
|
anomalies = []
|
|
322
317
|
if abs(price - limit_up_price) < 0.02:
|
|
@@ -383,9 +378,7 @@ def detect_divergence(df: pd.DataFrame) -> list:
|
|
|
383
378
|
if len(df) < 30:
|
|
384
379
|
return []
|
|
385
380
|
close = df["close"]
|
|
386
|
-
|
|
387
|
-
ema26 = close.ewm(span=26, adjust=False).mean()
|
|
388
|
-
dif = ema12 - ema26
|
|
381
|
+
dif, _, _ = macd_series(close)
|
|
389
382
|
|
|
390
383
|
window = min(20, len(df) - 10)
|
|
391
384
|
recent_close = close.iloc[-window:]
|
|
@@ -421,9 +414,9 @@ def detect_divergence(df: pd.DataFrame) -> list:
|
|
|
421
414
|
def detect_ma_cross(close: pd.Series) -> list:
|
|
422
415
|
if len(close) < 21:
|
|
423
416
|
return []
|
|
424
|
-
ma5 = close
|
|
425
|
-
ma10 = close
|
|
426
|
-
ma20 = close
|
|
417
|
+
ma5 = ma_series(close, 5)
|
|
418
|
+
ma10 = ma_series(close, 10)
|
|
419
|
+
ma20 = ma_series(close, 20)
|
|
427
420
|
|
|
428
421
|
anomalies = []
|
|
429
422
|
|
|
@@ -553,9 +546,5 @@ def main():
|
|
|
553
546
|
|
|
554
547
|
|
|
555
548
|
if __name__ == "__main__":
|
|
556
|
-
|
|
557
|
-
# Chinese text these tools emit — force UTF-8 so stdout never crashes there.
|
|
558
|
-
for _s in (sys.stdout, sys.stderr):
|
|
559
|
-
if hasattr(_s, "reconfigure"):
|
|
560
|
-
_s.reconfigure(encoding="utf-8")
|
|
549
|
+
utf8_stdio()
|
|
561
550
|
main()
|