stock-analysis-plugin 0.1.10
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 +498 -0
- package/package.json +88 -0
- package/pi/index.ts +1142 -0
- package/schemas/market_review_schema.json +176 -0
- package/schemas/report_schema.json +131 -0
- package/scripts/setup-python.mjs +57 -0
- package/scripts/sync-version.sh +56 -0
- package/scripts/venv-python.mjs +20 -0
- package/skills/bottom-volume/SKILL.md +63 -0
- package/skills/bottom-volume/scripts/gather.py +22 -0
- package/skills/box-oscillation/SKILL.md +72 -0
- package/skills/box-oscillation/scripts/gather.py +22 -0
- package/skills/bull-trend/SKILL.md +60 -0
- package/skills/bull-trend/scripts/gather.py +22 -0
- package/skills/chan-theory/SKILL.md +71 -0
- package/skills/chan-theory/scripts/gather.py +22 -0
- package/skills/dragon-head/SKILL.md +69 -0
- package/skills/dragon-head/scripts/gather.py +22 -0
- package/skills/emotion-cycle/SKILL.md +65 -0
- package/skills/emotion-cycle/scripts/gather.py +22 -0
- package/skills/event-driven/SKILL.md +73 -0
- package/skills/event-driven/scripts/gather.py +22 -0
- package/skills/expectation-repricing/SKILL.md +72 -0
- package/skills/expectation-repricing/scripts/gather.py +22 -0
- package/skills/growth-quality/SKILL.md +74 -0
- package/skills/growth-quality/scripts/gather.py +22 -0
- package/skills/hot-theme/SKILL.md +74 -0
- package/skills/hot-theme/scripts/gather.py +22 -0
- package/skills/ma-crossover/SKILL.md +63 -0
- package/skills/ma-crossover/scripts/gather.py +22 -0
- package/skills/market-review/SKILL.md +70 -0
- package/skills/market-review/scripts/gather.py +23 -0
- package/skills/one-yang-three-yin/SKILL.md +74 -0
- package/skills/one-yang-three-yin/scripts/gather.py +22 -0
- package/skills/shrink-pullback/SKILL.md +59 -0
- package/skills/shrink-pullback/scripts/gather.py +22 -0
- package/skills/stock-analysis/SKILL.md +134 -0
- package/skills/stock-analysis/scripts/gather.py +22 -0
- package/skills/stock-screener/SKILL.md +68 -0
- package/skills/stock-screener/scripts/gather.py +22 -0
- package/skills/strategy-backtest/SKILL.md +129 -0
- package/skills/strategy-backtest/scripts/gather.py +23 -0
- package/skills/volume-breakout/SKILL.md +58 -0
- package/skills/volume-breakout/scripts/gather.py +22 -0
- package/skills/wave-theory/SKILL.md +67 -0
- package/skills/wave-theory/scripts/gather.py +22 -0
- package/skills/wisburg-research/SKILL.md +119 -0
- package/strategies/examples/bottom_volume.yaml +47 -0
- package/strategies/examples/box_oscillation.yaml +41 -0
- package/strategies/examples/bull_trend.yaml +42 -0
- package/strategies/examples/dragon_head.yaml +45 -0
- package/strategies/examples/emotion_cycle.yaml +43 -0
- package/strategies/examples/ma_crossover.yaml +34 -0
- package/strategies/examples/rsi_oversold.yaml +35 -0
- package/strategies/examples/shrink_pullback.yaml +45 -0
- package/strategies/examples/volume_breakout.yaml +42 -0
- package/templates/_macros.j2 +90 -0
- package/templates/market_review/full.md.j2 +103 -0
- package/templates/stock_analysis/brief.md.j2 +28 -0
- package/templates/stock_analysis/full.md.j2 +108 -0
- package/tools/__init__.py +0 -0
- package/tools/alert_rules.py +243 -0
- package/tools/anomaly_detect.py +575 -0
- package/tools/backtest.py +764 -0
- package/tools/capabilities.py +108 -0
- package/tools/diagnostics.py +146 -0
- package/tools/gather.py +157 -0
- package/tools/import_parser.py +279 -0
- package/tools/market_regime.py +252 -0
- package/tools/market_review.py +155 -0
- package/tools/name_resolver.py +136 -0
- package/tools/pattern.py +515 -0
- package/tools/position_context.py +161 -0
- package/tools/report_renderer.py +116 -0
- package/tools/requirements.txt +15 -0
- package/tools/risk_screening.py +323 -0
- package/tools/screener.py +219 -0
- package/tools/search_intel.py +504 -0
- package/tools/stock_data.py +1721 -0
- package/tools/technical.py +642 -0
- package/tools/trading_calendar.py +226 -0
- package/tools/volume_analysis.py +178 -0
- package/tools/watchlist.py +66 -0
- package/tools/watchlist_context.py +185 -0
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Report renderer — turn structured stock/market JSON into markdown via existing j2 templates.
|
|
3
|
+
|
|
4
|
+
No side effects: does not save, push, or upload. Just returns markdown.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import argparse
|
|
8
|
+
import json
|
|
9
|
+
import sys
|
|
10
|
+
from datetime import datetime, timezone
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
try:
|
|
14
|
+
from jinja2 import Environment, FileSystemLoader, select_autoescape
|
|
15
|
+
except ImportError:
|
|
16
|
+
print(json.dumps({"error": "jinja2 not installed. pip install jinja2"}, ensure_ascii=False))
|
|
17
|
+
sys.exit(1)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
PROJECT_ROOT = Path(__file__).resolve().parent.parent
|
|
21
|
+
TEMPLATES_ROOT = PROJECT_ROOT / "templates"
|
|
22
|
+
|
|
23
|
+
TEMPLATE_MAP = {
|
|
24
|
+
"stock": {
|
|
25
|
+
"brief": "stock_analysis/brief.md.j2",
|
|
26
|
+
"full": "stock_analysis/full.md.j2",
|
|
27
|
+
},
|
|
28
|
+
"market": {
|
|
29
|
+
"full": "market_review/full.md.j2",
|
|
30
|
+
},
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _env() -> Environment:
|
|
35
|
+
return Environment(
|
|
36
|
+
loader=FileSystemLoader(str(TEMPLATES_ROOT)),
|
|
37
|
+
autoescape=select_autoescape(disabled_extensions=("j2", "md")),
|
|
38
|
+
trim_blocks=True,
|
|
39
|
+
lstrip_blocks=True,
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def render(kind: str, template: str, report: dict) -> dict:
|
|
44
|
+
if kind not in TEMPLATE_MAP:
|
|
45
|
+
return {"error": f"unknown kind: {kind}. valid: {list(TEMPLATE_MAP)}"}
|
|
46
|
+
if template not in TEMPLATE_MAP[kind]:
|
|
47
|
+
return {"error": f"unknown template '{template}' for {kind}. valid: {list(TEMPLATE_MAP[kind])}"}
|
|
48
|
+
|
|
49
|
+
tpl_path = TEMPLATE_MAP[kind][template]
|
|
50
|
+
try:
|
|
51
|
+
tpl = _env().get_template(tpl_path)
|
|
52
|
+
except Exception as e:
|
|
53
|
+
return {"error": f"failed to load template {tpl_path}: {e}"}
|
|
54
|
+
|
|
55
|
+
try:
|
|
56
|
+
content = tpl.render(**report)
|
|
57
|
+
except Exception as e:
|
|
58
|
+
return {"error": f"render failed: {e}", "template": tpl_path}
|
|
59
|
+
|
|
60
|
+
return {
|
|
61
|
+
"meta": {
|
|
62
|
+
"provider": "renderer",
|
|
63
|
+
"template": tpl_path,
|
|
64
|
+
"fetched_at": datetime.now(timezone.utc).isoformat(),
|
|
65
|
+
"freshness": "instant",
|
|
66
|
+
"fallback_used": False,
|
|
67
|
+
"warnings": [],
|
|
68
|
+
},
|
|
69
|
+
"format": "markdown",
|
|
70
|
+
"content": content,
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _load_input(path: str | None, b64: str | None) -> dict:
|
|
75
|
+
if b64:
|
|
76
|
+
import base64
|
|
77
|
+
|
|
78
|
+
return json.loads(base64.b64decode(b64).decode("utf-8"))
|
|
79
|
+
if path and path != "-":
|
|
80
|
+
with open(path, encoding="utf-8") as f:
|
|
81
|
+
return json.load(f)
|
|
82
|
+
return json.load(sys.stdin)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def main():
|
|
86
|
+
parser = argparse.ArgumentParser(description="Render stock/market report from structured JSON")
|
|
87
|
+
sub = parser.add_subparsers(dest="command")
|
|
88
|
+
|
|
89
|
+
p = sub.add_parser("stock", help="Render a stock analysis report")
|
|
90
|
+
p.add_argument("--template", default="full", choices=["brief", "full"])
|
|
91
|
+
p.add_argument("--input", "-i", default="-", help="JSON file path or '-' for stdin")
|
|
92
|
+
p.add_argument("--input-b64", help="Base64-encoded JSON (avoids shell escaping)")
|
|
93
|
+
|
|
94
|
+
p2 = sub.add_parser("market", help="Render a market review report")
|
|
95
|
+
p2.add_argument("--template", default="full", choices=["full"])
|
|
96
|
+
p2.add_argument("--input", "-i", default="-", help="JSON file path or '-' for stdin")
|
|
97
|
+
p2.add_argument("--input-b64", help="Base64-encoded JSON (avoids shell escaping)")
|
|
98
|
+
|
|
99
|
+
args = parser.parse_args()
|
|
100
|
+
if not args.command:
|
|
101
|
+
parser.print_help()
|
|
102
|
+
sys.exit(1)
|
|
103
|
+
|
|
104
|
+
report = _load_input(args.input, getattr(args, "input_b64", None))
|
|
105
|
+
result = render(args.command, args.template, report)
|
|
106
|
+
json.dump(result, sys.stdout, ensure_ascii=False, indent=2, default=str)
|
|
107
|
+
print()
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
if __name__ == "__main__":
|
|
111
|
+
# Windows defaults stdio to a legacy code page (cp1252) that cannot encode the
|
|
112
|
+
# Chinese text these tools emit — force UTF-8 so stdout never crashes there.
|
|
113
|
+
for _s in (sys.stdout, sys.stderr):
|
|
114
|
+
if hasattr(_s, "reconfigure"):
|
|
115
|
+
_s.reconfigure(encoding="utf-8")
|
|
116
|
+
main()
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
akshare>=1.14.0
|
|
2
|
+
yfinance>=0.2.36
|
|
3
|
+
pandas>=2.0.0
|
|
4
|
+
numpy>=1.24.0
|
|
5
|
+
pyyaml>=6.0
|
|
6
|
+
pypinyin>=0.50.0
|
|
7
|
+
requests>=2.31.0
|
|
8
|
+
exchange-calendars>=4.5.0
|
|
9
|
+
newspaper4k>=0.9.0
|
|
10
|
+
efinance>=0.5.0
|
|
11
|
+
baostock>=0.8.8
|
|
12
|
+
pytdx>=1.72
|
|
13
|
+
longport>=1.0.0
|
|
14
|
+
finnhub-python>=2.4.0
|
|
15
|
+
jinja2>=3.1.0
|
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Risk screening — 7-dimension risk checker for A-share stocks."""
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import subprocess
|
|
8
|
+
import sys
|
|
9
|
+
from datetime import datetime, timedelta
|
|
10
|
+
|
|
11
|
+
TOOLS_DIR = os.path.dirname(os.path.abspath(__file__))
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _run_tool(script: str, args: str) -> dict:
|
|
15
|
+
cmd = f"python3 {TOOLS_DIR}/{script} {args}"
|
|
16
|
+
try:
|
|
17
|
+
r = subprocess.run(cmd, shell=True, capture_output=True, text=True, encoding="utf-8", timeout=30)
|
|
18
|
+
if r.returncode == 0 and r.stdout.strip():
|
|
19
|
+
return json.loads(r.stdout)
|
|
20
|
+
except Exception:
|
|
21
|
+
pass
|
|
22
|
+
return {}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _safe_float(val) -> float | None:
|
|
26
|
+
if val is None:
|
|
27
|
+
return None
|
|
28
|
+
try:
|
|
29
|
+
v = float(val)
|
|
30
|
+
return v if v == v else None # NaN check
|
|
31
|
+
except (ValueError, TypeError):
|
|
32
|
+
return None
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
# --------------- Check 1: Valuation ---------------
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def check_valuation(symbol: str) -> dict:
|
|
39
|
+
quote = _run_tool("stock_data.py", f"quote {symbol}")
|
|
40
|
+
pe = _safe_float(quote.get("pe"))
|
|
41
|
+
pb = _safe_float(quote.get("pb"))
|
|
42
|
+
result = {"pe": pe, "pb": pb, "status": "normal", "flags": []}
|
|
43
|
+
|
|
44
|
+
if pe is not None:
|
|
45
|
+
if pe < 0:
|
|
46
|
+
result["flags"].append(
|
|
47
|
+
{"category": "valuation", "severity": "medium", "description": "PE为负,公司亏损", "source": "data"}
|
|
48
|
+
)
|
|
49
|
+
result["status"] = "warning"
|
|
50
|
+
elif pe > 200:
|
|
51
|
+
result["flags"].append(
|
|
52
|
+
{
|
|
53
|
+
"category": "valuation",
|
|
54
|
+
"severity": "high",
|
|
55
|
+
"description": f"PE={pe:.1f},估值极端偏高",
|
|
56
|
+
"source": "data",
|
|
57
|
+
}
|
|
58
|
+
)
|
|
59
|
+
result["status"] = "extreme"
|
|
60
|
+
elif pe > 100:
|
|
61
|
+
result["flags"].append(
|
|
62
|
+
{
|
|
63
|
+
"category": "valuation",
|
|
64
|
+
"severity": "medium",
|
|
65
|
+
"description": f"PE={pe:.1f},估值偏高",
|
|
66
|
+
"source": "data",
|
|
67
|
+
}
|
|
68
|
+
)
|
|
69
|
+
result["status"] = "warning"
|
|
70
|
+
|
|
71
|
+
if pb is not None:
|
|
72
|
+
if pb > 15:
|
|
73
|
+
result["flags"].append(
|
|
74
|
+
{
|
|
75
|
+
"category": "valuation",
|
|
76
|
+
"severity": "high",
|
|
77
|
+
"description": f"PB={pb:.1f},市净率极端",
|
|
78
|
+
"source": "data",
|
|
79
|
+
}
|
|
80
|
+
)
|
|
81
|
+
result["status"] = "extreme"
|
|
82
|
+
elif pb > 10:
|
|
83
|
+
result["flags"].append(
|
|
84
|
+
{
|
|
85
|
+
"category": "valuation",
|
|
86
|
+
"severity": "medium",
|
|
87
|
+
"description": f"PB={pb:.1f},市净率偏高",
|
|
88
|
+
"source": "data",
|
|
89
|
+
}
|
|
90
|
+
)
|
|
91
|
+
if result["status"] == "normal":
|
|
92
|
+
result["status"] = "warning"
|
|
93
|
+
|
|
94
|
+
return result
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
# --------------- Check 2: Technical Warning ---------------
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def check_technical(symbol: str) -> dict:
|
|
101
|
+
ta = _run_tool("technical.py", f"analyze {symbol}")
|
|
102
|
+
result = {"flags": []}
|
|
103
|
+
|
|
104
|
+
if not ta or "error" in ta:
|
|
105
|
+
return result
|
|
106
|
+
|
|
107
|
+
signal = ta.get("buy_signal", "")
|
|
108
|
+
score = _safe_float(ta.get("signal_score"))
|
|
109
|
+
trend = ta.get("trend", {}).get("overall", "")
|
|
110
|
+
|
|
111
|
+
if signal in ("STRONG_SELL",):
|
|
112
|
+
result["flags"].append(
|
|
113
|
+
{
|
|
114
|
+
"category": "technical",
|
|
115
|
+
"severity": "high",
|
|
116
|
+
"description": f"技术信号: {signal},评分 {score}",
|
|
117
|
+
"source": "data",
|
|
118
|
+
}
|
|
119
|
+
)
|
|
120
|
+
elif signal in ("SELL",):
|
|
121
|
+
result["flags"].append(
|
|
122
|
+
{
|
|
123
|
+
"category": "technical",
|
|
124
|
+
"severity": "medium",
|
|
125
|
+
"description": f"技术信号: {signal},评分 {score}",
|
|
126
|
+
"source": "data",
|
|
127
|
+
}
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
if trend == "bearish" and score is not None and score < 20:
|
|
131
|
+
result["flags"].append(
|
|
132
|
+
{
|
|
133
|
+
"category": "technical",
|
|
134
|
+
"severity": "high",
|
|
135
|
+
"description": "技术面全面走弱(趋势空头+评分<20)",
|
|
136
|
+
"source": "data",
|
|
137
|
+
}
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
macd = ta.get("macd", {})
|
|
141
|
+
if macd.get("signal") == "death_cross":
|
|
142
|
+
result["flags"].append(
|
|
143
|
+
{"category": "technical", "severity": "medium", "description": "MACD死叉", "source": "data"}
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
result["buy_signal"] = signal
|
|
147
|
+
result["signal_score"] = score
|
|
148
|
+
result["trend"] = trend
|
|
149
|
+
return result
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
# --------------- Check 3: Lock-up Expiry ---------------
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def check_lockup(symbol: str) -> dict:
|
|
156
|
+
result = {"upcoming_30d": [], "flags": []}
|
|
157
|
+
try:
|
|
158
|
+
import akshare as ak
|
|
159
|
+
|
|
160
|
+
df = ak.stock_restricted_release_queue_em(symbol=symbol)
|
|
161
|
+
if df is None or df.empty:
|
|
162
|
+
return result
|
|
163
|
+
|
|
164
|
+
now = datetime.now()
|
|
165
|
+
cutoff = now + timedelta(days=30)
|
|
166
|
+
|
|
167
|
+
date_col = None
|
|
168
|
+
for c in df.columns:
|
|
169
|
+
if "日期" in str(c) or "解禁" in str(c):
|
|
170
|
+
date_col = c
|
|
171
|
+
break
|
|
172
|
+
if date_col is None and len(df.columns) > 0:
|
|
173
|
+
date_col = df.columns[0]
|
|
174
|
+
|
|
175
|
+
if date_col:
|
|
176
|
+
import pandas as pd
|
|
177
|
+
|
|
178
|
+
df[date_col] = pd.to_datetime(df[date_col], errors="coerce")
|
|
179
|
+
upcoming = df[(df[date_col] >= now) & (df[date_col] <= cutoff)]
|
|
180
|
+
if not upcoming.empty:
|
|
181
|
+
result["upcoming_30d"] = [str(d.date()) for d in upcoming[date_col].dropna()]
|
|
182
|
+
result["flags"].append(
|
|
183
|
+
{
|
|
184
|
+
"category": "lockup",
|
|
185
|
+
"severity": "medium",
|
|
186
|
+
"description": f"未来30天有{len(upcoming)}批限售股解禁",
|
|
187
|
+
"source": "data",
|
|
188
|
+
}
|
|
189
|
+
)
|
|
190
|
+
except Exception:
|
|
191
|
+
pass
|
|
192
|
+
return result
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
# --------------- Check 4-7: News-based risks ---------------
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def check_news_risks(symbol: str, name: str = "") -> dict:
|
|
199
|
+
search_name = name if name else symbol
|
|
200
|
+
categories = {
|
|
201
|
+
"insider": f"{search_name} 减持 股东减持",
|
|
202
|
+
"earnings": f"{search_name} 业绩预告 亏损 下降",
|
|
203
|
+
"regulatory": f"{search_name} 处罚 违规 监管 立案",
|
|
204
|
+
"industry": f"{search_name} 行业政策 监管 限制",
|
|
205
|
+
}
|
|
206
|
+
result = {"flags": []}
|
|
207
|
+
for cat, query in categories.items():
|
|
208
|
+
data = _run_tool("search_intel.py", f'search "{query}" --max 3')
|
|
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
|
+
)
|
|
225
|
+
return result
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _cat_cn(cat: str) -> str:
|
|
229
|
+
return {"insider": "内部人减持", "earnings": "业绩预警", "regulatory": "监管处罚", "industry": "行业政策"}.get(
|
|
230
|
+
cat, cat
|
|
231
|
+
)
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
# --------------- Scoring ---------------
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def compute_risk(flags: list) -> dict:
|
|
238
|
+
score = 0
|
|
239
|
+
for f in flags:
|
|
240
|
+
sev = f.get("severity", "low")
|
|
241
|
+
if sev == "high":
|
|
242
|
+
score += 30
|
|
243
|
+
elif sev == "medium":
|
|
244
|
+
score += 15
|
|
245
|
+
else:
|
|
246
|
+
score += 5
|
|
247
|
+
score = min(score, 100)
|
|
248
|
+
|
|
249
|
+
if score >= 60:
|
|
250
|
+
risk_level = "high"
|
|
251
|
+
elif score >= 30:
|
|
252
|
+
risk_level = "medium"
|
|
253
|
+
else:
|
|
254
|
+
risk_level = "low"
|
|
255
|
+
|
|
256
|
+
veto_buy = any(f.get("severity") == "high" for f in flags)
|
|
257
|
+
return {"risk_score": score, "risk_level": risk_level, "veto_buy": veto_buy}
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
# --------------- Main entry ---------------
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def screen_risk(symbol: str, name: str = "") -> dict:
|
|
264
|
+
all_flags = []
|
|
265
|
+
checks = {}
|
|
266
|
+
|
|
267
|
+
val = check_valuation(symbol)
|
|
268
|
+
checks["valuation"] = {"pe": val["pe"], "pb": val["pb"], "status": val["status"]}
|
|
269
|
+
all_flags.extend(val["flags"])
|
|
270
|
+
|
|
271
|
+
tech = check_technical(symbol)
|
|
272
|
+
checks["technical"] = {
|
|
273
|
+
"buy_signal": tech.get("buy_signal"),
|
|
274
|
+
"signal_score": tech.get("signal_score"),
|
|
275
|
+
"trend": tech.get("trend"),
|
|
276
|
+
}
|
|
277
|
+
all_flags.extend(tech["flags"])
|
|
278
|
+
|
|
279
|
+
lockup = check_lockup(symbol)
|
|
280
|
+
checks["lockup"] = {"upcoming_30d": lockup["upcoming_30d"]}
|
|
281
|
+
all_flags.extend(lockup["flags"])
|
|
282
|
+
|
|
283
|
+
news = check_news_risks(symbol, name)
|
|
284
|
+
checks["news_risks"] = {k: v for k, v in news.items() if k != "flags"}
|
|
285
|
+
all_flags.extend(news["flags"])
|
|
286
|
+
|
|
287
|
+
risk = compute_risk(all_flags)
|
|
288
|
+
return {
|
|
289
|
+
"symbol": symbol,
|
|
290
|
+
"name": name,
|
|
291
|
+
"risk_level": risk["risk_level"],
|
|
292
|
+
"risk_score": risk["risk_score"],
|
|
293
|
+
"veto_buy": risk["veto_buy"],
|
|
294
|
+
"flags": all_flags,
|
|
295
|
+
"checks": checks,
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def main():
|
|
300
|
+
parser = argparse.ArgumentParser(description="Risk screening tool")
|
|
301
|
+
sub = parser.add_subparsers(dest="command")
|
|
302
|
+
|
|
303
|
+
p_screen = sub.add_parser("screen")
|
|
304
|
+
p_screen.add_argument("symbol")
|
|
305
|
+
p_screen.add_argument("--name", default="")
|
|
306
|
+
|
|
307
|
+
args = parser.parse_args()
|
|
308
|
+
if not args.command:
|
|
309
|
+
parser.print_help()
|
|
310
|
+
sys.exit(1)
|
|
311
|
+
|
|
312
|
+
if args.command == "screen":
|
|
313
|
+
result = screen_risk(args.symbol, args.name)
|
|
314
|
+
print(json.dumps(result, ensure_ascii=False, default=str))
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
if __name__ == "__main__":
|
|
318
|
+
# Windows defaults stdio to a legacy code page (cp1252) that cannot encode the
|
|
319
|
+
# Chinese text these tools emit — force UTF-8 so stdout never crashes there.
|
|
320
|
+
for _s in (sys.stdout, sys.stderr):
|
|
321
|
+
if hasattr(_s, "reconfigure"):
|
|
322
|
+
_s.reconfigure(encoding="utf-8")
|
|
323
|
+
main()
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""AlphaSift L1 — multi-factor stock screener with hard filter + scoring."""
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import subprocess
|
|
8
|
+
import sys
|
|
9
|
+
|
|
10
|
+
import numpy as np
|
|
11
|
+
import pandas as pd
|
|
12
|
+
import yaml
|
|
13
|
+
|
|
14
|
+
DEFAULT_FILTERS = {
|
|
15
|
+
"pe_min": 0,
|
|
16
|
+
"pe_max": 100,
|
|
17
|
+
"pb_min": 0,
|
|
18
|
+
"pb_max": 20,
|
|
19
|
+
"market_cap_min": 5e9,
|
|
20
|
+
"turnover_rate_min": 0.5,
|
|
21
|
+
"turnover_rate_max": 20,
|
|
22
|
+
"change_pct_min": -5,
|
|
23
|
+
"change_pct_max": 9.9,
|
|
24
|
+
"volume_ratio_min": 0.5,
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def fetch_snapshot(market: str) -> list:
|
|
29
|
+
script = os.path.join(os.path.dirname(os.path.abspath(__file__)), "stock_data.py")
|
|
30
|
+
r = subprocess.run(
|
|
31
|
+
[sys.executable, script, "market_snapshot", "--market", market],
|
|
32
|
+
capture_output=True,
|
|
33
|
+
text=True,
|
|
34
|
+
encoding="utf-8",
|
|
35
|
+
)
|
|
36
|
+
return json.loads(r.stdout)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def load_config(path: str) -> dict:
|
|
40
|
+
with open(path, encoding="utf-8") as f:
|
|
41
|
+
return yaml.safe_load(f)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def merge_filters(config: dict | None) -> dict:
|
|
45
|
+
filters = dict(DEFAULT_FILTERS)
|
|
46
|
+
if config and "filters" in config:
|
|
47
|
+
filters.update(config["filters"])
|
|
48
|
+
return filters
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def apply_filters(df: pd.DataFrame, filters: dict) -> pd.DataFrame:
|
|
52
|
+
conditions = []
|
|
53
|
+
if "pe" in df.columns:
|
|
54
|
+
conditions.append(df["pe"] >= filters["pe_min"])
|
|
55
|
+
conditions.append(df["pe"] <= filters["pe_max"])
|
|
56
|
+
if "pb" in df.columns:
|
|
57
|
+
conditions.append(df["pb"] >= filters["pb_min"])
|
|
58
|
+
conditions.append(df["pb"] <= filters["pb_max"])
|
|
59
|
+
if "market_cap" in df.columns:
|
|
60
|
+
conditions.append(df["market_cap"] >= filters["market_cap_min"])
|
|
61
|
+
if "turnover_rate" in df.columns:
|
|
62
|
+
conditions.append(df["turnover_rate"] >= filters["turnover_rate_min"])
|
|
63
|
+
conditions.append(df["turnover_rate"] <= filters["turnover_rate_max"])
|
|
64
|
+
if "change_pct" in df.columns:
|
|
65
|
+
conditions.append(df["change_pct"] >= filters["change_pct_min"])
|
|
66
|
+
conditions.append(df["change_pct"] <= filters["change_pct_max"])
|
|
67
|
+
if "volume_ratio" in df.columns:
|
|
68
|
+
conditions.append(df["volume_ratio"] >= filters["volume_ratio_min"])
|
|
69
|
+
|
|
70
|
+
if conditions:
|
|
71
|
+
mask = conditions[0]
|
|
72
|
+
for c in conditions[1:]:
|
|
73
|
+
mask = mask & c
|
|
74
|
+
return df[mask].copy()
|
|
75
|
+
return df.copy()
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _minmax(s: pd.Series) -> pd.Series:
|
|
79
|
+
mn, mx = s.min(), s.max()
|
|
80
|
+
if mx == mn:
|
|
81
|
+
return pd.Series(50.0, index=s.index)
|
|
82
|
+
return ((s - mn) / (mx - mn) * 100).clip(0, 100)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def compute_scores(df: pd.DataFrame) -> pd.DataFrame:
|
|
86
|
+
# Value: lower PE/PB → higher score (inverted)
|
|
87
|
+
value_parts = []
|
|
88
|
+
if "pe" in df.columns:
|
|
89
|
+
value_parts.append(100 - _minmax(df["pe"]))
|
|
90
|
+
if "pb" in df.columns:
|
|
91
|
+
value_parts.append(100 - _minmax(df["pb"]))
|
|
92
|
+
df["value_score"] = sum(value_parts) / max(len(value_parts), 1)
|
|
93
|
+
|
|
94
|
+
# Momentum: higher change_pct and volume_ratio → higher score
|
|
95
|
+
mom_parts = []
|
|
96
|
+
if "change_pct" in df.columns:
|
|
97
|
+
mom_parts.append(_minmax(df["change_pct"]))
|
|
98
|
+
if "volume_ratio" in df.columns:
|
|
99
|
+
mom_parts.append(_minmax(df["volume_ratio"]))
|
|
100
|
+
df["momentum_score"] = sum(mom_parts) / max(len(mom_parts), 1)
|
|
101
|
+
|
|
102
|
+
# Liquidity: higher turnover_rate and volume → higher score
|
|
103
|
+
liq_parts = []
|
|
104
|
+
if "turnover_rate" in df.columns:
|
|
105
|
+
liq_parts.append(_minmax(df["turnover_rate"]))
|
|
106
|
+
if "volume" in df.columns:
|
|
107
|
+
liq_parts.append(_minmax(df["volume"].astype(float)))
|
|
108
|
+
df["liquidity_score"] = sum(liq_parts) / max(len(liq_parts), 1)
|
|
109
|
+
|
|
110
|
+
df["composite_score"] = 0.4 * df["value_score"] + 0.3 * df["momentum_score"] + 0.3 * df["liquidity_score"]
|
|
111
|
+
return df
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def screen(market: str, top: int, config: dict | None) -> dict:
|
|
115
|
+
raw = fetch_snapshot(market)
|
|
116
|
+
if isinstance(raw, dict) and "error" in raw:
|
|
117
|
+
return raw
|
|
118
|
+
|
|
119
|
+
df = pd.DataFrame(raw)
|
|
120
|
+
total = len(df)
|
|
121
|
+
|
|
122
|
+
for c in ["price", "change_pct", "volume", "turnover", "pe", "pb", "market_cap", "turnover_rate", "volume_ratio"]:
|
|
123
|
+
if c in df.columns:
|
|
124
|
+
df[c] = pd.to_numeric(df[c], errors="coerce")
|
|
125
|
+
|
|
126
|
+
critical = ["price", "pe", "pb"]
|
|
127
|
+
existing = [c for c in critical if c in df.columns]
|
|
128
|
+
if existing:
|
|
129
|
+
df = df.dropna(subset=existing)
|
|
130
|
+
|
|
131
|
+
filters = merge_filters(config)
|
|
132
|
+
df = apply_filters(df, filters)
|
|
133
|
+
filtered_count = len(df)
|
|
134
|
+
|
|
135
|
+
if df.empty:
|
|
136
|
+
return {
|
|
137
|
+
"market": market,
|
|
138
|
+
"total_stocks": total,
|
|
139
|
+
"filtered_count": 0,
|
|
140
|
+
"returned_count": 0,
|
|
141
|
+
"filters_applied": filters,
|
|
142
|
+
"candidates": [],
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
df = compute_scores(df)
|
|
146
|
+
|
|
147
|
+
sort_by = config.get("sort_by", "composite_score") if config else "composite_score"
|
|
148
|
+
sort_order = config.get("sort_order", "desc") if config else "desc"
|
|
149
|
+
ascending = sort_order == "asc"
|
|
150
|
+
|
|
151
|
+
if sort_by in df.columns:
|
|
152
|
+
df = df.sort_values(sort_by, ascending=ascending)
|
|
153
|
+
else:
|
|
154
|
+
df = df.sort_values("composite_score", ascending=False)
|
|
155
|
+
|
|
156
|
+
df = df.head(top)
|
|
157
|
+
|
|
158
|
+
candidates = []
|
|
159
|
+
for rank, (_, row) in enumerate(df.iterrows(), 1):
|
|
160
|
+
entry = {"rank": rank}
|
|
161
|
+
for field in [
|
|
162
|
+
"symbol",
|
|
163
|
+
"name",
|
|
164
|
+
"price",
|
|
165
|
+
"change_pct",
|
|
166
|
+
"volume",
|
|
167
|
+
"turnover_rate",
|
|
168
|
+
"pe",
|
|
169
|
+
"pb",
|
|
170
|
+
"market_cap",
|
|
171
|
+
"volume_ratio",
|
|
172
|
+
]:
|
|
173
|
+
v = row.get(field)
|
|
174
|
+
if v is not None and not (isinstance(v, float) and np.isnan(v)):
|
|
175
|
+
entry[field] = round(float(v), 2) if isinstance(v, (float, np.floating)) else v
|
|
176
|
+
entry["scores"] = {
|
|
177
|
+
"value": round(float(row.get("value_score", 0)), 1),
|
|
178
|
+
"momentum": round(float(row.get("momentum_score", 0)), 1),
|
|
179
|
+
"liquidity": round(float(row.get("liquidity_score", 0)), 1),
|
|
180
|
+
"composite": round(float(row.get("composite_score", 0)), 1),
|
|
181
|
+
}
|
|
182
|
+
candidates.append(entry)
|
|
183
|
+
|
|
184
|
+
return {
|
|
185
|
+
"market": market,
|
|
186
|
+
"total_stocks": total,
|
|
187
|
+
"filtered_count": filtered_count,
|
|
188
|
+
"returned_count": len(candidates),
|
|
189
|
+
"filters_applied": filters,
|
|
190
|
+
"candidates": candidates,
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def main():
|
|
195
|
+
parser = argparse.ArgumentParser(description="AlphaSift L1 stock screener")
|
|
196
|
+
sub = parser.add_subparsers(dest="command")
|
|
197
|
+
|
|
198
|
+
p = sub.add_parser("screen")
|
|
199
|
+
p.add_argument("--market", default="A", choices=["A", "HK", "US"])
|
|
200
|
+
p.add_argument("--top", type=int, default=20)
|
|
201
|
+
p.add_argument("--config", help="Path to YAML config file")
|
|
202
|
+
|
|
203
|
+
args = parser.parse_args()
|
|
204
|
+
if not args.command:
|
|
205
|
+
parser.print_help()
|
|
206
|
+
sys.exit(1)
|
|
207
|
+
|
|
208
|
+
config = load_config(args.config) if args.config else None
|
|
209
|
+
result = screen(args.market, args.top, config)
|
|
210
|
+
print(json.dumps(result, ensure_ascii=False, default=str))
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
if __name__ == "__main__":
|
|
214
|
+
# Windows defaults stdio to a legacy code page (cp1252) that cannot encode the
|
|
215
|
+
# Chinese text these tools emit — force UTF-8 so stdout never crashes there.
|
|
216
|
+
for _s in (sys.stdout, sys.stderr):
|
|
217
|
+
if hasattr(_s, "reconfigure"):
|
|
218
|
+
_s.reconfigure(encoding="utf-8")
|
|
219
|
+
main()
|