@weaxs/openclaw-stock-analysis 0.1.3 → 0.1.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/index.ts +197 -0
- package/openclaw.plugin.json +9 -1
- package/package.json +5 -2
- package/schemas/market_review_schema.json +176 -0
- package/scripts/sync-version.sh +55 -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/alert_rules.py +238 -0
- package/tools/backtest.py +115 -0
- package/tools/capabilities.py +101 -0
- package/tools/diagnostics.py +135 -0
- package/tools/import_parser.py +259 -0
- package/tools/position_context.py +156 -0
- package/tools/report_renderer.py +111 -0
- package/tools/requirements.txt +2 -0
- package/tools/stock_data.py +8 -2
- package/tools/watchlist_context.py +180 -0
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Data source diagnostics — report which providers are usable per market.
|
|
3
|
+
|
|
4
|
+
Checks: (1) python package importable, (2) required env vars present.
|
|
5
|
+
Does NOT hit the network — this is a cheap capability probe, not a health check.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import argparse
|
|
9
|
+
import importlib
|
|
10
|
+
import importlib.util
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import sys
|
|
14
|
+
from datetime import datetime, timezone
|
|
15
|
+
|
|
16
|
+
# provider -> (import_name, required_env_vars, markets, note)
|
|
17
|
+
PROVIDERS = {
|
|
18
|
+
"akshare": ("akshare", [], ["A"], None),
|
|
19
|
+
"tushare": ("tushare", ["TUSHARE_TOKEN"], ["A"], None),
|
|
20
|
+
"efinance": ("efinance", [], ["A"], None),
|
|
21
|
+
"pytdx": ("pytdx", [], ["A"], "connects to public Tencent servers"),
|
|
22
|
+
"yfinance": ("yfinance", [], ["HK", "US"], "quote may be delayed 15-20min"),
|
|
23
|
+
"finnhub": ("finnhub", ["FINNHUB_API_KEY"], ["US"], None),
|
|
24
|
+
"longbridge": (
|
|
25
|
+
"longport.openapi",
|
|
26
|
+
["LONGBRIDGE_APP_KEY", "LONGBRIDGE_APP_SECRET", "LONGBRIDGE_ACCESS_TOKEN"],
|
|
27
|
+
["HK", "US"],
|
|
28
|
+
None,
|
|
29
|
+
),
|
|
30
|
+
"alphavantage": ("requests", ["ALPHAVANTAGE_API_KEY"], ["US"], None),
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _check_provider(name: str) -> dict:
|
|
35
|
+
import_name, env_vars, markets, note = PROVIDERS[name]
|
|
36
|
+
|
|
37
|
+
# find_spec avoids executing the package's top-level code — cheaper and
|
|
38
|
+
# side-effect-free vs import_module. This is a capability probe, not a call.
|
|
39
|
+
try:
|
|
40
|
+
spec = importlib.util.find_spec(import_name)
|
|
41
|
+
pkg_ok = spec is not None
|
|
42
|
+
pkg_err = None if pkg_ok else f"package '{import_name}' not installed"
|
|
43
|
+
except Exception as e:
|
|
44
|
+
pkg_ok = False
|
|
45
|
+
pkg_err = f"package '{import_name}' not installed: {e}"
|
|
46
|
+
|
|
47
|
+
missing_env = [v for v in env_vars if not os.environ.get(v)]
|
|
48
|
+
|
|
49
|
+
available = pkg_ok and not missing_env
|
|
50
|
+
reasons = []
|
|
51
|
+
if not pkg_ok:
|
|
52
|
+
reasons.append(pkg_err)
|
|
53
|
+
if missing_env:
|
|
54
|
+
reasons.append(f"missing env: {', '.join(missing_env)}")
|
|
55
|
+
|
|
56
|
+
entry = {
|
|
57
|
+
"name": name,
|
|
58
|
+
"available": available,
|
|
59
|
+
"markets": markets,
|
|
60
|
+
"reason": "; ".join(reasons) if reasons else None,
|
|
61
|
+
}
|
|
62
|
+
if note:
|
|
63
|
+
entry["note"] = note
|
|
64
|
+
return entry
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def diagnose(market: str = "all") -> dict:
|
|
68
|
+
market = (market or "all").upper()
|
|
69
|
+
all_providers = [_check_provider(p) for p in PROVIDERS]
|
|
70
|
+
|
|
71
|
+
markets_to_report = ["A", "HK", "US"] if market == "ALL" else [market]
|
|
72
|
+
|
|
73
|
+
result = {
|
|
74
|
+
"meta": {
|
|
75
|
+
"provider": "diagnostics",
|
|
76
|
+
"fetched_at": datetime.now(timezone.utc).isoformat(),
|
|
77
|
+
"freshness": "instant",
|
|
78
|
+
"fallback_used": False,
|
|
79
|
+
"warnings": [],
|
|
80
|
+
},
|
|
81
|
+
"markets": [],
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
for m in markets_to_report:
|
|
85
|
+
providers = [p for p in all_providers if m in p["markets"]]
|
|
86
|
+
available = [p for p in providers if p["available"]]
|
|
87
|
+
|
|
88
|
+
warnings = []
|
|
89
|
+
if not available:
|
|
90
|
+
warnings.append(f"no working data source for {m}")
|
|
91
|
+
# market-specific caveats
|
|
92
|
+
if m == "A" and not any(p["name"] == "tushare" and p["available"] for p in providers):
|
|
93
|
+
warnings.append("TUSHARE_TOKEN not set — akshare-only, some deep data unavailable")
|
|
94
|
+
if (
|
|
95
|
+
m in ("HK", "US")
|
|
96
|
+
and not any(p["name"] == "longbridge" and p["available"] for p in providers)
|
|
97
|
+
and not any(p["name"] == "finnhub" and p["available"] for p in providers)
|
|
98
|
+
):
|
|
99
|
+
warnings.append(f"{m} quotes will be delayed (yfinance only)")
|
|
100
|
+
|
|
101
|
+
result["markets"].append(
|
|
102
|
+
{
|
|
103
|
+
"market": m,
|
|
104
|
+
"available": bool(available),
|
|
105
|
+
"providers": providers,
|
|
106
|
+
"warnings": warnings,
|
|
107
|
+
}
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
return result
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def main():
|
|
114
|
+
parser = argparse.ArgumentParser(description="Data source diagnostics")
|
|
115
|
+
sub = parser.add_subparsers(dest="command")
|
|
116
|
+
p = sub.add_parser("check")
|
|
117
|
+
p.add_argument(
|
|
118
|
+
"--market",
|
|
119
|
+
default="ALL",
|
|
120
|
+
type=str.upper,
|
|
121
|
+
choices=["A", "HK", "US", "ALL"],
|
|
122
|
+
help="Market to diagnose (default: ALL)",
|
|
123
|
+
)
|
|
124
|
+
args = parser.parse_args()
|
|
125
|
+
if not args.command:
|
|
126
|
+
parser.print_help()
|
|
127
|
+
sys.exit(1)
|
|
128
|
+
|
|
129
|
+
result = diagnose(args.market)
|
|
130
|
+
json.dump(result, sys.stdout, ensure_ascii=False, indent=2, default=str)
|
|
131
|
+
print()
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
if __name__ == "__main__":
|
|
135
|
+
main()
|
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Parse stock list from freeform text / CSV / markdown.
|
|
3
|
+
|
|
4
|
+
Extracts symbols using regex heuristics + name_resolver for A-share Chinese names.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import argparse
|
|
8
|
+
import json
|
|
9
|
+
import re
|
|
10
|
+
import sys
|
|
11
|
+
from datetime import datetime, timezone
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
15
|
+
from name_resolver import resolve # noqa: E402
|
|
16
|
+
|
|
17
|
+
# regex patterns
|
|
18
|
+
RE_A_CODE = re.compile(r"(?<!\d)(\d{6})(?!\d)")
|
|
19
|
+
RE_HK_CODE = re.compile(r"(?<![A-Za-z0-9])(\d{4,5}\.HK)(?![A-Za-z0-9])", re.IGNORECASE)
|
|
20
|
+
RE_US_TICKER = re.compile(r"(?<![A-Za-z0-9])([A-Z]{1,5})(?![A-Za-z0-9\.])")
|
|
21
|
+
RE_CN_NAME = re.compile(r"[一-鿿][一-鿿\w]{1,7}")
|
|
22
|
+
|
|
23
|
+
# US ticker false-positive filter (common ALL-CAPS words that aren't tickers)
|
|
24
|
+
US_STOPWORDS = {
|
|
25
|
+
"A",
|
|
26
|
+
"I",
|
|
27
|
+
"AM",
|
|
28
|
+
"PM",
|
|
29
|
+
"AN",
|
|
30
|
+
"AS",
|
|
31
|
+
"AT",
|
|
32
|
+
"BE",
|
|
33
|
+
"BY",
|
|
34
|
+
"DO",
|
|
35
|
+
"GO",
|
|
36
|
+
"IF",
|
|
37
|
+
"IN",
|
|
38
|
+
"IS",
|
|
39
|
+
"IT",
|
|
40
|
+
"ME",
|
|
41
|
+
"MY",
|
|
42
|
+
"NO",
|
|
43
|
+
"OF",
|
|
44
|
+
"ON",
|
|
45
|
+
"OR",
|
|
46
|
+
"SO",
|
|
47
|
+
"TO",
|
|
48
|
+
"UP",
|
|
49
|
+
"US",
|
|
50
|
+
"WE",
|
|
51
|
+
"THE",
|
|
52
|
+
"AND",
|
|
53
|
+
"FOR",
|
|
54
|
+
"BUT",
|
|
55
|
+
"NOT",
|
|
56
|
+
"YOU",
|
|
57
|
+
"ALL",
|
|
58
|
+
"CAN",
|
|
59
|
+
"HAD",
|
|
60
|
+
"HAS",
|
|
61
|
+
"HER",
|
|
62
|
+
"WAS",
|
|
63
|
+
"ONE",
|
|
64
|
+
"OUR",
|
|
65
|
+
"OUT",
|
|
66
|
+
"DAY",
|
|
67
|
+
"GET",
|
|
68
|
+
"HIM",
|
|
69
|
+
"HIS",
|
|
70
|
+
"HOW",
|
|
71
|
+
"MAN",
|
|
72
|
+
"NEW",
|
|
73
|
+
"NOW",
|
|
74
|
+
"OLD",
|
|
75
|
+
"SEE",
|
|
76
|
+
"TWO",
|
|
77
|
+
"WAY",
|
|
78
|
+
"WHO",
|
|
79
|
+
"BOY",
|
|
80
|
+
"DID",
|
|
81
|
+
"ITS",
|
|
82
|
+
"LET",
|
|
83
|
+
"PUT",
|
|
84
|
+
"SAY",
|
|
85
|
+
"SHE",
|
|
86
|
+
"TOO",
|
|
87
|
+
"USE",
|
|
88
|
+
"PE",
|
|
89
|
+
"PB",
|
|
90
|
+
"PS",
|
|
91
|
+
"ROE",
|
|
92
|
+
"MA",
|
|
93
|
+
"RSI",
|
|
94
|
+
"MACD",
|
|
95
|
+
"KDJ",
|
|
96
|
+
"BOLL",
|
|
97
|
+
"ETF",
|
|
98
|
+
"IPO",
|
|
99
|
+
"AI",
|
|
100
|
+
"ML",
|
|
101
|
+
"GDP",
|
|
102
|
+
"CPI",
|
|
103
|
+
"PPI",
|
|
104
|
+
"CEO",
|
|
105
|
+
"CFO",
|
|
106
|
+
"CTO",
|
|
107
|
+
"COO",
|
|
108
|
+
"USA",
|
|
109
|
+
"PDF",
|
|
110
|
+
"CSV",
|
|
111
|
+
"API",
|
|
112
|
+
"URL",
|
|
113
|
+
"HTTP",
|
|
114
|
+
"SQL",
|
|
115
|
+
"JSON",
|
|
116
|
+
"XML",
|
|
117
|
+
"HTML",
|
|
118
|
+
"CSS",
|
|
119
|
+
"OK",
|
|
120
|
+
"TV",
|
|
121
|
+
"PC",
|
|
122
|
+
"OS",
|
|
123
|
+
"USD",
|
|
124
|
+
"CNY",
|
|
125
|
+
"HKD",
|
|
126
|
+
"EUR",
|
|
127
|
+
"JPY",
|
|
128
|
+
"GBP",
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _dedupe(items: list[dict]) -> list[dict]:
|
|
133
|
+
seen = set()
|
|
134
|
+
result = []
|
|
135
|
+
for it in items:
|
|
136
|
+
key = it.get("symbol")
|
|
137
|
+
if key and key not in seen:
|
|
138
|
+
seen.add(key)
|
|
139
|
+
result.append(it)
|
|
140
|
+
return result
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def parse(text: str) -> dict:
|
|
144
|
+
text = text.strip()
|
|
145
|
+
items: list[dict] = []
|
|
146
|
+
unresolved: list[str] = []
|
|
147
|
+
seen_symbols: set[str] = set()
|
|
148
|
+
|
|
149
|
+
# 1. HK codes (do first — they contain digits that A-share regex would also match)
|
|
150
|
+
hk_matches: list[str] = []
|
|
151
|
+
for m in RE_HK_CODE.finditer(text):
|
|
152
|
+
code = m.group(1).upper()
|
|
153
|
+
# normalize to 5-digit
|
|
154
|
+
num, suf = code.split(".")
|
|
155
|
+
code = f"{num.zfill(5)}.HK"
|
|
156
|
+
if code not in seen_symbols:
|
|
157
|
+
items.append({"symbol": code, "market": "HK"})
|
|
158
|
+
seen_symbols.add(code)
|
|
159
|
+
hk_matches.append(m.group(1))
|
|
160
|
+
|
|
161
|
+
# strip HK codes so their 4-5 digit part doesn't get picked up as A-share
|
|
162
|
+
text_after_hk = text
|
|
163
|
+
for m in hk_matches:
|
|
164
|
+
text_after_hk = text_after_hk.replace(m, " ")
|
|
165
|
+
|
|
166
|
+
# 2. A-share 6-digit codes
|
|
167
|
+
for m in RE_A_CODE.finditer(text_after_hk):
|
|
168
|
+
code = m.group(1)
|
|
169
|
+
if code not in seen_symbols:
|
|
170
|
+
items.append({"symbol": code, "market": "A"})
|
|
171
|
+
seen_symbols.add(code)
|
|
172
|
+
|
|
173
|
+
# 3. US tickers (1-5 uppercase letters), filtered against stopwords
|
|
174
|
+
for m in RE_US_TICKER.finditer(text):
|
|
175
|
+
tick = m.group(1)
|
|
176
|
+
if tick in US_STOPWORDS:
|
|
177
|
+
continue
|
|
178
|
+
if len(tick) == 1:
|
|
179
|
+
continue # too noisy
|
|
180
|
+
if tick not in seen_symbols:
|
|
181
|
+
items.append({"symbol": tick, "market": "US"})
|
|
182
|
+
seen_symbols.add(tick)
|
|
183
|
+
|
|
184
|
+
# 4. Chinese names → resolve via name_resolver
|
|
185
|
+
cn_names = set(RE_CN_NAME.findall(text))
|
|
186
|
+
# filter obviously non-stock words
|
|
187
|
+
noise = {"成本", "持仓", "买入", "卖出", "止损", "止盈", "股票", "代码", "行情", "分析", "策略"}
|
|
188
|
+
cn_names = {n for n in cn_names if n not in noise and len(n) >= 2}
|
|
189
|
+
|
|
190
|
+
for name in cn_names:
|
|
191
|
+
try:
|
|
192
|
+
hits = resolve(name, top=1)
|
|
193
|
+
except Exception:
|
|
194
|
+
hits = []
|
|
195
|
+
if hits and isinstance(hits, list) and hits[0].get("code"):
|
|
196
|
+
top_hit = hits[0]
|
|
197
|
+
# ponytail: name_resolver returns nearest fuzzy match even for names not in A-share
|
|
198
|
+
# (e.g. "腾讯" → "拓新药业" via pinyin). Reject low-confidence hits.
|
|
199
|
+
score = top_hit.get("score")
|
|
200
|
+
hit_name = top_hit.get("name", "")
|
|
201
|
+
is_exact = (name in hit_name) or (hit_name in name)
|
|
202
|
+
if not is_exact and score is not None and score < 0.85:
|
|
203
|
+
unresolved.append(name)
|
|
204
|
+
continue
|
|
205
|
+
code = top_hit["code"]
|
|
206
|
+
if code not in seen_symbols:
|
|
207
|
+
items.append(
|
|
208
|
+
{
|
|
209
|
+
"symbol": code,
|
|
210
|
+
"market": "A",
|
|
211
|
+
"name": hit_name,
|
|
212
|
+
"resolved_from": name,
|
|
213
|
+
}
|
|
214
|
+
)
|
|
215
|
+
seen_symbols.add(code)
|
|
216
|
+
else:
|
|
217
|
+
unresolved.append(name)
|
|
218
|
+
|
|
219
|
+
return {
|
|
220
|
+
"meta": {
|
|
221
|
+
"provider": "import_parser",
|
|
222
|
+
"fetched_at": datetime.now(timezone.utc).isoformat(),
|
|
223
|
+
"freshness": "instant",
|
|
224
|
+
"fallback_used": False,
|
|
225
|
+
"warnings": [],
|
|
226
|
+
},
|
|
227
|
+
"items": _dedupe(items),
|
|
228
|
+
"unresolved": unresolved,
|
|
229
|
+
"count": len(items),
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def main():
|
|
234
|
+
parser = argparse.ArgumentParser(description="Parse stock list from text")
|
|
235
|
+
sub = parser.add_subparsers(dest="command")
|
|
236
|
+
p = sub.add_parser("parse")
|
|
237
|
+
p.add_argument("--text", help='Text to parse (or "-" for stdin)')
|
|
238
|
+
p.add_argument("--text-b64", help="Base64-encoded text")
|
|
239
|
+
|
|
240
|
+
args = parser.parse_args()
|
|
241
|
+
if not args.command:
|
|
242
|
+
parser.print_help()
|
|
243
|
+
sys.exit(1)
|
|
244
|
+
|
|
245
|
+
if args.text_b64:
|
|
246
|
+
import base64
|
|
247
|
+
|
|
248
|
+
text = base64.b64decode(args.text_b64).decode("utf-8")
|
|
249
|
+
elif not args.text or args.text == "-":
|
|
250
|
+
text = sys.stdin.read()
|
|
251
|
+
else:
|
|
252
|
+
text = args.text
|
|
253
|
+
result = parse(text)
|
|
254
|
+
json.dump(result, sys.stdout, ensure_ascii=False, indent=2, default=str)
|
|
255
|
+
print()
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
if __name__ == "__main__":
|
|
259
|
+
main()
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Position context analyzer — pnl, distance to stop-loss/take-profit, position advice.
|
|
3
|
+
|
|
4
|
+
Not a portfolio system. Stateless: user passes cost/quantity/stops each call.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import argparse
|
|
8
|
+
import json
|
|
9
|
+
import subprocess
|
|
10
|
+
import sys
|
|
11
|
+
from datetime import datetime, timezone
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
15
|
+
from stock_data import detect_market # noqa: E402
|
|
16
|
+
|
|
17
|
+
TOOLS_DIR = Path(__file__).resolve().parent
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _find_python() -> str:
|
|
21
|
+
venv = TOOLS_DIR.parent / ".venv" / "bin" / "python3"
|
|
22
|
+
return str(venv) if venv.exists() else sys.executable
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _run_json(script: str, args: list[str], timeout: int = 30):
|
|
26
|
+
cmd = [_find_python(), str(TOOLS_DIR / script)] + args
|
|
27
|
+
try:
|
|
28
|
+
r = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
|
|
29
|
+
if r.returncode == 0 and r.stdout.strip():
|
|
30
|
+
return json.loads(r.stdout)
|
|
31
|
+
except Exception:
|
|
32
|
+
pass
|
|
33
|
+
return None
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _risk_level(distance_to_stop_pct: float, pnl_pct: float, trend: str) -> str:
|
|
37
|
+
# ponytail: simple 3-bucket heuristic, upgrade to volatility-adjusted if needed
|
|
38
|
+
if distance_to_stop_pct is not None and distance_to_stop_pct < 3:
|
|
39
|
+
return "high"
|
|
40
|
+
if pnl_pct < -5 or trend == "bearish":
|
|
41
|
+
return "high"
|
|
42
|
+
if pnl_pct < 0 or (distance_to_stop_pct is not None and distance_to_stop_pct < 6):
|
|
43
|
+
return "medium"
|
|
44
|
+
return "low"
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _advice(pnl_pct: float, distance_to_stop_pct, distance_to_take_pct, trend: str, stop_loss, cost) -> str:
|
|
48
|
+
if distance_to_stop_pct is not None and distance_to_stop_pct < 3:
|
|
49
|
+
return "接近止损,建议减仓或严守止损位"
|
|
50
|
+
if pnl_pct > 15 and distance_to_take_pct is not None and distance_to_take_pct < 5:
|
|
51
|
+
return "接近目标价,考虑分批止盈"
|
|
52
|
+
if pnl_pct > 8 and stop_loss is not None and stop_loss < cost:
|
|
53
|
+
return "已有盈利,建议将止损上移到成本价或以上"
|
|
54
|
+
if pnl_pct < -5 and trend == "bearish":
|
|
55
|
+
return "浮亏且趋势偏空,控制仓位避免加仓"
|
|
56
|
+
if trend == "bullish" and pnl_pct >= 0:
|
|
57
|
+
return "趋势配合,可持有观察后续量能"
|
|
58
|
+
return "维持现有策略,关注关键位变化"
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def analyze_position(
|
|
62
|
+
symbol: str,
|
|
63
|
+
cost: float,
|
|
64
|
+
quantity: float,
|
|
65
|
+
stop_loss: float | None = None,
|
|
66
|
+
take_profit: float | None = None,
|
|
67
|
+
) -> dict:
|
|
68
|
+
quote = _run_json("stock_data.py", ["quote", symbol]) or {}
|
|
69
|
+
tech = _run_json("technical.py", ["analyze", symbol, "--period", "daily", "--count", "60"]) or {}
|
|
70
|
+
|
|
71
|
+
price = quote.get("price")
|
|
72
|
+
if price is None:
|
|
73
|
+
return {"symbol": symbol, "error": "cannot fetch current price"}
|
|
74
|
+
price = float(price)
|
|
75
|
+
|
|
76
|
+
pnl_per_share = price - cost
|
|
77
|
+
pnl_pct = (pnl_per_share / cost * 100) if cost else 0.0
|
|
78
|
+
market_value = price * quantity
|
|
79
|
+
total_pnl = pnl_per_share * quantity
|
|
80
|
+
|
|
81
|
+
distance_to_stop_pct = None
|
|
82
|
+
if stop_loss is not None:
|
|
83
|
+
distance_to_stop_pct = (price - stop_loss) / price * 100 if price else None
|
|
84
|
+
|
|
85
|
+
distance_to_take_pct = None
|
|
86
|
+
if take_profit is not None:
|
|
87
|
+
distance_to_take_pct = (take_profit - price) / price * 100 if price else None
|
|
88
|
+
|
|
89
|
+
trend = (tech.get("trend") or {}).get("overall", "unknown")
|
|
90
|
+
support = (tech.get("support_resistance") or {}).get("support")
|
|
91
|
+
resistance = (tech.get("support_resistance") or {}).get("resistance")
|
|
92
|
+
|
|
93
|
+
risk_level = _risk_level(distance_to_stop_pct, pnl_pct, trend)
|
|
94
|
+
advice = _advice(pnl_pct, distance_to_stop_pct, distance_to_take_pct, trend, stop_loss, cost)
|
|
95
|
+
|
|
96
|
+
return {
|
|
97
|
+
"meta": {
|
|
98
|
+
"provider": "position_context",
|
|
99
|
+
"fetched_at": datetime.now(timezone.utc).isoformat(),
|
|
100
|
+
"freshness": "realtime_or_latest_trade_day",
|
|
101
|
+
"fallback_used": False,
|
|
102
|
+
"warnings": [],
|
|
103
|
+
},
|
|
104
|
+
"symbol": symbol,
|
|
105
|
+
"market": detect_market(symbol),
|
|
106
|
+
"name": quote.get("name"),
|
|
107
|
+
"position": {
|
|
108
|
+
"cost": cost,
|
|
109
|
+
"quantity": quantity,
|
|
110
|
+
"current_price": price,
|
|
111
|
+
"market_value": round(market_value, 2),
|
|
112
|
+
"total_pnl": round(total_pnl, 2),
|
|
113
|
+
"pnl_pct": round(pnl_pct, 2),
|
|
114
|
+
},
|
|
115
|
+
"levels": {
|
|
116
|
+
"stop_loss": stop_loss,
|
|
117
|
+
"take_profit": take_profit,
|
|
118
|
+
"support": support,
|
|
119
|
+
"resistance": resistance,
|
|
120
|
+
"distance_to_stop_loss_pct": round(distance_to_stop_pct, 2) if distance_to_stop_pct is not None else None,
|
|
121
|
+
"distance_to_take_profit_pct": round(distance_to_take_pct, 2) if distance_to_take_pct is not None else None,
|
|
122
|
+
},
|
|
123
|
+
"trend": trend,
|
|
124
|
+
"risk_level": risk_level,
|
|
125
|
+
"position_advice": advice,
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def main():
|
|
130
|
+
parser = argparse.ArgumentParser(description="Position context analyzer")
|
|
131
|
+
sub = parser.add_subparsers(dest="command")
|
|
132
|
+
p = sub.add_parser("analyze")
|
|
133
|
+
p.add_argument("symbol")
|
|
134
|
+
p.add_argument("--cost", type=float, required=True, help="Cost basis per share")
|
|
135
|
+
p.add_argument("--quantity", type=float, required=True, help="Number of shares held")
|
|
136
|
+
p.add_argument("--stop-loss", type=float, help="Stop loss price")
|
|
137
|
+
p.add_argument("--take-profit", type=float, help="Take profit price")
|
|
138
|
+
|
|
139
|
+
args = parser.parse_args()
|
|
140
|
+
if not args.command:
|
|
141
|
+
parser.print_help()
|
|
142
|
+
sys.exit(1)
|
|
143
|
+
|
|
144
|
+
result = analyze_position(
|
|
145
|
+
args.symbol,
|
|
146
|
+
cost=args.cost,
|
|
147
|
+
quantity=args.quantity,
|
|
148
|
+
stop_loss=args.stop_loss,
|
|
149
|
+
take_profit=args.take_profit,
|
|
150
|
+
)
|
|
151
|
+
json.dump(result, sys.stdout, ensure_ascii=False, indent=2, default=str)
|
|
152
|
+
print()
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
if __name__ == "__main__":
|
|
156
|
+
main()
|
|
@@ -0,0 +1,111 @@
|
|
|
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
|
+
main()
|
package/tools/requirements.txt
CHANGED
package/tools/stock_data.py
CHANGED
|
@@ -128,13 +128,18 @@ def _kline_efinance(symbol: str, period: str, count: int) -> list:
|
|
|
128
128
|
|
|
129
129
|
|
|
130
130
|
def _kline_baostock(symbol: str, period: str, count: int) -> list:
|
|
131
|
+
import io
|
|
132
|
+
|
|
131
133
|
import baostock as bs
|
|
132
134
|
import pandas as pd
|
|
133
135
|
|
|
134
136
|
freq_map = {"daily": "d", "weekly": "w", "monthly": "m"}
|
|
135
137
|
end = datetime.now()
|
|
136
138
|
start = end - timedelta(days=count * 7 if period == "weekly" else count * 31 if period == "monthly" else count * 2)
|
|
137
|
-
|
|
139
|
+
# baostock login/logout print status lines to stdout — silence them so the
|
|
140
|
+
# tool's JSON output on stdout stays clean for the calling host.
|
|
141
|
+
with contextlib.redirect_stdout(io.StringIO()):
|
|
142
|
+
bs.login()
|
|
138
143
|
try:
|
|
139
144
|
rs = bs.query_history_k_data_plus(
|
|
140
145
|
_to_baostock_code(symbol),
|
|
@@ -149,7 +154,8 @@ def _kline_baostock(symbol: str, period: str, count: int) -> list:
|
|
|
149
154
|
rows.append(rs.get_row_data())
|
|
150
155
|
df = pd.DataFrame(rows, columns=rs.fields)
|
|
151
156
|
finally:
|
|
152
|
-
|
|
157
|
+
with contextlib.redirect_stdout(io.StringIO()):
|
|
158
|
+
bs.logout()
|
|
153
159
|
if df.empty:
|
|
154
160
|
raise ValueError("baostock returned empty data")
|
|
155
161
|
col_map = {"amount": "turnover", "pctChg": "change_pct"}
|