@weaxs/openclaw-stock-analysis 0.1.15 → 0.2.0
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 +1 -1
- package/dist/index.js +153 -19
- package/index.ts +164 -17
- package/openclaw.plugin.json +7 -0
- package/package.json +1 -1
- package/skills/dragon-head/SKILL.md +3 -1
- package/skills/emotion-cycle/SKILL.md +2 -0
- package/skills/hot-theme/SKILL.md +2 -1
- package/skills/stock-analysis/SKILL.md +9 -1
- package/tools/alert_rules.py +5 -18
- package/tools/backtest.py +4 -4
- package/tools/capabilities.py +8 -0
- package/tools/gather.py +12 -31
- package/tools/market_review.py +1 -1
- package/tools/name_resolver.py +4 -10
- package/tools/pattern.py +3 -24
- package/tools/report_renderer.py +1 -2
- package/tools/screener.py +2 -16
- package/tools/search_intel.py +1 -24
- package/tools/signal_tracker.py +275 -0
- package/tools/stock_data.py +389 -94
- package/tools/trading_calendar.py +92 -7
- package/tools/volume_analysis.py +3 -23
- package/tools/watchlist_context.py +1 -10
- package/scripts/sync-version.sh +0 -56
package/tools/backtest.py
CHANGED
|
@@ -482,7 +482,7 @@ def diagnose_advanced(metrics: dict, trades: list, equity_curve: list, strategy:
|
|
|
482
482
|
trade_count_quality = "sufficient"
|
|
483
483
|
|
|
484
484
|
# main_failure_reason — pick the most impactful weakness
|
|
485
|
-
sell_trades = [t for t in trades if t.get("
|
|
485
|
+
sell_trades = [t for t in trades if t.get("type") == "sell"]
|
|
486
486
|
stop_hits = sum(
|
|
487
487
|
1
|
|
488
488
|
for t in sell_trades
|
|
@@ -509,9 +509,9 @@ def diagnose_advanced(metrics: dict, trades: list, equity_curve: list, strategy:
|
|
|
509
509
|
if len(equity_curve) >= 3:
|
|
510
510
|
# split into halves, compare
|
|
511
511
|
mid = len(equity_curve) // 2
|
|
512
|
-
first = equity_curve[mid][
|
|
513
|
-
last = equity_curve[-1][
|
|
514
|
-
start_v = equity_curve[0][
|
|
512
|
+
first = equity_curve[mid]["equity"]
|
|
513
|
+
last = equity_curve[-1]["equity"]
|
|
514
|
+
start_v = equity_curve[0]["equity"]
|
|
515
515
|
first_half = (first - start_v) / start_v if start_v else 0
|
|
516
516
|
second_half = (last - first) / first if first else 0
|
|
517
517
|
if first_half > 0.05 and second_half > 0.05:
|
package/tools/capabilities.py
CHANGED
|
@@ -39,6 +39,9 @@ TOOL_MATRIX = {
|
|
|
39
39
|
"get_market_stats": {"markets": ["A"], "reason": "A-share only"},
|
|
40
40
|
"get_fundamental_context": {"markets": ["A"], "reason": "A-share only"},
|
|
41
41
|
"resolve_stock_name": {"markets": ["A"], "reason": "A-share name/pinyin index only"},
|
|
42
|
+
"get_limit_up_pool": {"markets": ["A"], "reason": "A-share only"},
|
|
43
|
+
"get_dragon_tiger": {"markets": ["A"], "reason": "A-share only"},
|
|
44
|
+
"get_hot_stocks": {"markets": ["A"], "reason": "A-share only"},
|
|
42
45
|
"get_social_sentiment": {
|
|
43
46
|
"markets": ["A", "HK", "US"],
|
|
44
47
|
"reason": "A-share uses Eastmoney/Xueqiu; HK/US require SENTIMENT_API_KEY",
|
|
@@ -52,6 +55,11 @@ TOOL_MATRIX = {
|
|
|
52
55
|
"search_comprehensive_intel": {"markets": ALL_MARKETS, "reason": None},
|
|
53
56
|
"extract_article": {"markets": ALL_MARKETS, "reason": None},
|
|
54
57
|
"screen_risk": {"markets": ["A"], "reason": "A-share only"},
|
|
58
|
+
# trading phase (session tables) + signal tracking (local JSONL store)
|
|
59
|
+
"get_trading_phase": {"markets": ALL_MARKETS, "reason": None},
|
|
60
|
+
"record_signal": {"markets": ALL_MARKETS, "reason": None},
|
|
61
|
+
"evaluate_signals": {"markets": ALL_MARKETS, "reason": None},
|
|
62
|
+
"get_signal_summary": {"markets": ALL_MARKETS, "reason": None},
|
|
55
63
|
}
|
|
56
64
|
|
|
57
65
|
|
package/tools/gather.py
CHANGED
|
@@ -4,16 +4,15 @@
|
|
|
4
4
|
import argparse
|
|
5
5
|
import json
|
|
6
6
|
import sys
|
|
7
|
-
from concurrent.futures import ThreadPoolExecutor
|
|
7
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
8
8
|
from pathlib import Path
|
|
9
9
|
|
|
10
10
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
11
11
|
from _subproc import run_tool # noqa: E402
|
|
12
12
|
|
|
13
13
|
|
|
14
|
-
# gather fans out the heavier CLIs, so the default timeout stays 60s;
|
|
15
|
-
# is _parse_json's job
|
|
16
|
-
# functools.partial) keeps timeout passable both positionally and by keyword.
|
|
14
|
+
# gather fans out the heavier CLIs, so the default timeout stays 60s; raw stdout
|
|
15
|
+
# wanted here (parsing is _parse_json's job); def keeps timeout kw-passable.
|
|
17
16
|
def _run(script, args, timeout=60):
|
|
18
17
|
return run_tool(script, args, timeout=timeout, parse_json=False)
|
|
19
18
|
|
|
@@ -27,6 +26,12 @@ def _parse_json(raw: str | None):
|
|
|
27
26
|
return raw
|
|
28
27
|
|
|
29
28
|
|
|
29
|
+
def _run_all(tasks: dict) -> dict:
|
|
30
|
+
with ThreadPoolExecutor(max_workers=len(tasks)) as pool:
|
|
31
|
+
futures = {pool.submit(_run, script, args): key for key, (script, args) in tasks.items()}
|
|
32
|
+
return {key: _parse_json(f.result()) for f, key in futures.items()}
|
|
33
|
+
|
|
34
|
+
|
|
30
35
|
def gather_analysis(symbol: str) -> dict:
|
|
31
36
|
tasks = {
|
|
32
37
|
"quote": ("stock_data.py", ["quote", symbol]),
|
|
@@ -38,15 +43,7 @@ def gather_analysis(symbol: str) -> dict:
|
|
|
38
43
|
"risk": ("risk_screening.py", ["screen", symbol]),
|
|
39
44
|
"regime": ("market_regime.py", ["detect"]),
|
|
40
45
|
}
|
|
41
|
-
|
|
42
|
-
results = {}
|
|
43
|
-
with ThreadPoolExecutor(max_workers=8) as pool:
|
|
44
|
-
futures = {pool.submit(_run, script, args): key for key, (script, args) in tasks.items()}
|
|
45
|
-
for future in as_completed(futures):
|
|
46
|
-
key = futures[future]
|
|
47
|
-
results[key] = _parse_json(future.result())
|
|
48
|
-
|
|
49
|
-
return results
|
|
46
|
+
return _run_all(tasks)
|
|
50
47
|
|
|
51
48
|
|
|
52
49
|
def gather_technical(symbol: str, kline_count: int = 120, with_quote: bool = False) -> dict:
|
|
@@ -56,15 +53,7 @@ def gather_technical(symbol: str, kline_count: int = 120, with_quote: bool = Fal
|
|
|
56
53
|
}
|
|
57
54
|
if with_quote:
|
|
58
55
|
tasks["quote"] = ("stock_data.py", ["quote", symbol])
|
|
59
|
-
|
|
60
|
-
results = {}
|
|
61
|
-
with ThreadPoolExecutor(max_workers=4) as pool:
|
|
62
|
-
futures = {pool.submit(_run, script, args): key for key, (script, args) in tasks.items()}
|
|
63
|
-
for future in as_completed(futures):
|
|
64
|
-
key = futures[future]
|
|
65
|
-
results[key] = _parse_json(future.result())
|
|
66
|
-
|
|
67
|
-
return results
|
|
56
|
+
return _run_all(tasks)
|
|
68
57
|
|
|
69
58
|
|
|
70
59
|
def gather_screen(market: str = "A", top: int = 20, config: str | None = None) -> dict:
|
|
@@ -85,15 +74,7 @@ def gather_fundamental(symbol: str) -> dict:
|
|
|
85
74
|
"stock_info": ("stock_data.py", ["stock_info", symbol]),
|
|
86
75
|
"sector_rankings": ("stock_data.py", ["sector_rankings", "--top", "5", "--direction", "both"]),
|
|
87
76
|
}
|
|
88
|
-
|
|
89
|
-
results = {}
|
|
90
|
-
with ThreadPoolExecutor(max_workers=7) as pool:
|
|
91
|
-
futures = {pool.submit(_run, script, args): key for key, (script, args) in tasks.items()}
|
|
92
|
-
for future in as_completed(futures):
|
|
93
|
-
key = futures[future]
|
|
94
|
-
results[key] = _parse_json(future.result())
|
|
95
|
-
|
|
96
|
-
return results
|
|
77
|
+
return _run_all(tasks)
|
|
97
78
|
|
|
98
79
|
|
|
99
80
|
def main():
|
package/tools/market_review.py
CHANGED
|
@@ -71,7 +71,7 @@ def review_market(market: str = "A") -> dict:
|
|
|
71
71
|
|
|
72
72
|
if market == "A":
|
|
73
73
|
tasks["indices"] = ("stock_data.py", ["market_indices", "--region", "cn"])
|
|
74
|
-
tasks["stats"] = ("stock_data.py", ["market_stats"
|
|
74
|
+
tasks["stats"] = ("stock_data.py", ["market_stats"])
|
|
75
75
|
tasks["sectors"] = ("stock_data.py", ["sector_rankings", "--top", "5", "--direction", "both"])
|
|
76
76
|
# query 含空格,必须保持单个 argv 元素
|
|
77
77
|
tasks["news"] = ("search_intel.py", ["search", "A股 今日 市场"])
|
package/tools/name_resolver.py
CHANGED
|
@@ -4,20 +4,14 @@
|
|
|
4
4
|
import argparse
|
|
5
5
|
import json
|
|
6
6
|
import sys
|
|
7
|
-
import time
|
|
8
7
|
from difflib import SequenceMatcher
|
|
8
|
+
from pathlib import Path
|
|
9
9
|
|
|
10
|
-
|
|
10
|
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
11
11
|
|
|
12
|
+
from stock_data import _akshare_retry # noqa: E402
|
|
12
13
|
|
|
13
|
-
|
|
14
|
-
for attempt in range(retries + 1):
|
|
15
|
-
try:
|
|
16
|
-
return fn(*args)
|
|
17
|
-
except Exception:
|
|
18
|
-
if attempt == retries:
|
|
19
|
-
raise
|
|
20
|
-
time.sleep(delay)
|
|
14
|
+
_STOCK_MAP_CACHE = None
|
|
21
15
|
|
|
22
16
|
|
|
23
17
|
def _load_stock_map() -> list[dict]:
|
package/tools/pattern.py
CHANGED
|
@@ -3,34 +3,15 @@
|
|
|
3
3
|
|
|
4
4
|
import argparse
|
|
5
5
|
import json
|
|
6
|
-
import os
|
|
7
|
-
import subprocess
|
|
8
6
|
import sys
|
|
7
|
+
from pathlib import Path
|
|
9
8
|
|
|
10
9
|
import numpy as np
|
|
11
10
|
import pandas as pd
|
|
12
11
|
|
|
12
|
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
13
13
|
|
|
14
|
-
|
|
15
|
-
script = os.path.join(os.path.dirname(os.path.abspath(__file__)), "stock_data.py")
|
|
16
|
-
r = subprocess.run(
|
|
17
|
-
[sys.executable, script, "kline", symbol, "--period", period, "--count", str(count)],
|
|
18
|
-
capture_output=True,
|
|
19
|
-
text=True,
|
|
20
|
-
encoding="utf-8",
|
|
21
|
-
)
|
|
22
|
-
return json.loads(r.stdout)
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
def to_dataframe(records: list) -> pd.DataFrame:
|
|
26
|
-
df = pd.DataFrame(records)
|
|
27
|
-
for c in ["open", "high", "low", "close", "volume"]:
|
|
28
|
-
if c in df.columns:
|
|
29
|
-
df[c] = pd.to_numeric(df[c], errors="coerce")
|
|
30
|
-
if "date" in df.columns:
|
|
31
|
-
df["date"] = pd.to_datetime(df["date"], errors="coerce")
|
|
32
|
-
df = df.sort_values("date").reset_index(drop=True)
|
|
33
|
-
return df
|
|
14
|
+
from technical import fetch_kline, to_dataframe # noqa: E402
|
|
34
15
|
|
|
35
16
|
|
|
36
17
|
def _body(row):
|
|
@@ -403,8 +384,6 @@ PATTERN_STRENGTH = {
|
|
|
403
384
|
"hammer": "中",
|
|
404
385
|
"hanging_man": "中",
|
|
405
386
|
"shooting_star": "中",
|
|
406
|
-
"big_candle_up": "中",
|
|
407
|
-
"big_candle_down": "中",
|
|
408
387
|
"double_bottom": "中",
|
|
409
388
|
"box_oscillation": "中",
|
|
410
389
|
"morning_star": "强",
|
package/tools/report_renderer.py
CHANGED
|
@@ -92,7 +92,6 @@ def main():
|
|
|
92
92
|
p.add_argument("--input-b64", help="Base64-encoded JSON (avoids shell escaping)")
|
|
93
93
|
|
|
94
94
|
p2 = sub.add_parser("market", help="Render a market review report")
|
|
95
|
-
p2.add_argument("--template", default="full", choices=["full"])
|
|
96
95
|
p2.add_argument("--input", "-i", default="-", help="JSON file path or '-' for stdin")
|
|
97
96
|
p2.add_argument("--input-b64", help="Base64-encoded JSON (avoids shell escaping)")
|
|
98
97
|
|
|
@@ -102,7 +101,7 @@ def main():
|
|
|
102
101
|
sys.exit(1)
|
|
103
102
|
|
|
104
103
|
report = _load_input(args.input, getattr(args, "input_b64", None))
|
|
105
|
-
result = render(args.command, args
|
|
104
|
+
result = render(args.command, getattr(args, "template", "full"), report)
|
|
106
105
|
json.dump(result, sys.stdout, ensure_ascii=False, indent=2, default=str)
|
|
107
106
|
print()
|
|
108
107
|
|
package/tools/screener.py
CHANGED
|
@@ -8,8 +8,6 @@ L2 (opt-in via --l2 / config l2: true): per-candidate quality/growth/momentum/vo
|
|
|
8
8
|
|
|
9
9
|
import argparse
|
|
10
10
|
import json
|
|
11
|
-
import os
|
|
12
|
-
import subprocess
|
|
13
11
|
import sys
|
|
14
12
|
from concurrent.futures import ThreadPoolExecutor
|
|
15
13
|
from pathlib import Path
|
|
@@ -20,6 +18,7 @@ import yaml
|
|
|
20
18
|
|
|
21
19
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
22
20
|
|
|
21
|
+
from _subproc import run_tool
|
|
23
22
|
from market_review import calc_temperature
|
|
24
23
|
from stock_data import compute_market_stats
|
|
25
24
|
|
|
@@ -51,20 +50,7 @@ _INDEX_REGION = {"A": "cn", "HK": "hk", "US": "us"}
|
|
|
51
50
|
|
|
52
51
|
def _fetch_json(args: list[str], timeout: int = 30) -> dict | list | None:
|
|
53
52
|
"""Run a stock_data.py CLI command and parse its JSON stdout; None on any failure."""
|
|
54
|
-
|
|
55
|
-
try:
|
|
56
|
-
r = subprocess.run(
|
|
57
|
-
[sys.executable, script, *args],
|
|
58
|
-
capture_output=True,
|
|
59
|
-
text=True,
|
|
60
|
-
encoding="utf-8",
|
|
61
|
-
timeout=timeout,
|
|
62
|
-
)
|
|
63
|
-
if r.returncode == 0 and r.stdout.strip():
|
|
64
|
-
return json.loads(r.stdout)
|
|
65
|
-
except Exception:
|
|
66
|
-
pass
|
|
67
|
-
return None
|
|
53
|
+
return run_tool("stock_data.py", args, timeout=timeout)
|
|
68
54
|
|
|
69
55
|
|
|
70
56
|
def fetch_snapshot(market: str) -> list:
|
package/tools/search_intel.py
CHANGED
|
@@ -8,23 +8,6 @@ import re
|
|
|
8
8
|
import sys
|
|
9
9
|
import time as _time
|
|
10
10
|
|
|
11
|
-
# --------------- TTL Cache ---------------
|
|
12
|
-
|
|
13
|
-
_CACHE = {}
|
|
14
|
-
_CACHE_TTL = 600 # 10 minutes
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
def _cache_get(key: str):
|
|
18
|
-
entry = _CACHE.get(key)
|
|
19
|
-
if entry and (_time.time() - entry["ts"]) < _CACHE_TTL:
|
|
20
|
-
return entry["data"]
|
|
21
|
-
return None
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
def _cache_set(key: str, data):
|
|
25
|
-
_CACHE[key] = {"data": data, "ts": _time.time()}
|
|
26
|
-
|
|
27
|
-
|
|
28
11
|
# --------------- Web Search ---------------
|
|
29
12
|
|
|
30
13
|
_SECRET_PARAM_RE = re.compile(r"(?i)((?:api[_-]?key|token|secret|access[_-]?token)=)[^&\s]+")
|
|
@@ -398,12 +381,7 @@ def get_social_sentiment(symbol: str) -> dict:
|
|
|
398
381
|
|
|
399
382
|
|
|
400
383
|
def get_trending_sentiment() -> dict:
|
|
401
|
-
"""Fetch trending sentiment from Reddit/X/Polymarket.
|
|
402
|
-
cache_key = "trending_sentiment"
|
|
403
|
-
cached = _cache_get(cache_key)
|
|
404
|
-
if cached:
|
|
405
|
-
return cached
|
|
406
|
-
|
|
384
|
+
"""Fetch trending sentiment from Reddit/X/Polymarket."""
|
|
407
385
|
api_url = os.environ.get("SENTIMENT_API_URL", "https://api.adanos.org")
|
|
408
386
|
api_key = os.environ.get("SENTIMENT_API_KEY")
|
|
409
387
|
|
|
@@ -432,7 +410,6 @@ def get_trending_sentiment() -> dict:
|
|
|
432
410
|
"wisburg_mcp": "Use 'list-feed' for latest research feed and 'list-market-daily' for market daily digest.",
|
|
433
411
|
}
|
|
434
412
|
|
|
435
|
-
_cache_set(cache_key, result)
|
|
436
413
|
return result
|
|
437
414
|
|
|
438
415
|
|
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Signal tracker — record/evaluate/summary for AI trade suggestions.
|
|
3
|
+
|
|
4
|
+
The single stateful exception in an otherwise stateless toolset: a small JSONL
|
|
5
|
+
store lets the host agent track the after-the-fact performance of the buy/sell
|
|
6
|
+
suggestions it issues. Store path: $STOCK_SIGNAL_STORE, else
|
|
7
|
+
~/.stock-analysis/signals.jsonl (pathlib.Path.home(), cross-platform). Every
|
|
8
|
+
subcommand accepts --store PATH to override (tests point it at tmp_path). The
|
|
9
|
+
host decides when to record and when to evaluate.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import argparse
|
|
13
|
+
import json
|
|
14
|
+
import os
|
|
15
|
+
import sys
|
|
16
|
+
from datetime import datetime
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from uuid import uuid4
|
|
19
|
+
|
|
20
|
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
21
|
+
from _subproc import run_tool # noqa: E402
|
|
22
|
+
from stock_data import detect_market # noqa: E402
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _default_store() -> Path:
|
|
26
|
+
env = os.environ.get("STOCK_SIGNAL_STORE")
|
|
27
|
+
return Path(env) if env else Path.home() / ".stock-analysis" / "signals.jsonl"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _store_path(args) -> Path:
|
|
31
|
+
return Path(args.store) if args.store else _default_store()
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _load_records(store: Path) -> list:
|
|
35
|
+
if not store.exists():
|
|
36
|
+
return []
|
|
37
|
+
records = []
|
|
38
|
+
for line in store.read_text(encoding="utf-8").splitlines():
|
|
39
|
+
line = line.strip()
|
|
40
|
+
if line:
|
|
41
|
+
try:
|
|
42
|
+
records.append(json.loads(line))
|
|
43
|
+
except json.JSONDecodeError:
|
|
44
|
+
continue
|
|
45
|
+
return records
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _save_records(store: Path, records: list):
|
|
49
|
+
"""Atomic rewrite: write <store>.tmp, then os.replace onto the store."""
|
|
50
|
+
store.parent.mkdir(parents=True, exist_ok=True)
|
|
51
|
+
tmp = store.parent / (store.name + ".tmp")
|
|
52
|
+
tmp.write_text("".join(json.dumps(r, ensure_ascii=False) + "\n" for r in records), encoding="utf-8")
|
|
53
|
+
os.replace(tmp, store)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def cmd_record(args):
|
|
57
|
+
entry_price = args.entry_price
|
|
58
|
+
if entry_price is None:
|
|
59
|
+
quote = run_tool("stock_data.py", ["quote", args.symbol])
|
|
60
|
+
if not isinstance(quote, dict) or "error" in quote or quote.get("price") is None:
|
|
61
|
+
return {"error": f"cannot determine entry price for {args.symbol}: quote unavailable"}
|
|
62
|
+
entry_price = quote["price"]
|
|
63
|
+
date = args.date or datetime.now().strftime("%Y-%m-%d")
|
|
64
|
+
record = {
|
|
65
|
+
"id": f"{date}-{args.symbol}-{uuid4().hex[:8]}",
|
|
66
|
+
"symbol": args.symbol,
|
|
67
|
+
"market": detect_market(args.symbol),
|
|
68
|
+
"direction": args.direction,
|
|
69
|
+
"entry_price": entry_price,
|
|
70
|
+
"target_price": args.target_price,
|
|
71
|
+
"stop_price": args.stop_price,
|
|
72
|
+
"horizon_days": args.horizon_days,
|
|
73
|
+
"source": args.source,
|
|
74
|
+
"note": args.note,
|
|
75
|
+
"record_date": date,
|
|
76
|
+
"status": "open",
|
|
77
|
+
"outcome": None,
|
|
78
|
+
}
|
|
79
|
+
store = _store_path(args)
|
|
80
|
+
try:
|
|
81
|
+
store.parent.mkdir(parents=True, exist_ok=True)
|
|
82
|
+
with store.open("a", encoding="utf-8") as f:
|
|
83
|
+
f.write(json.dumps(record, ensure_ascii=False) + "\n")
|
|
84
|
+
except OSError as e:
|
|
85
|
+
return {"error": str(e)}
|
|
86
|
+
return record
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _evaluate_bars(rec: dict, bars: list):
|
|
90
|
+
"""Judge one open record against daily bars after record_date.
|
|
91
|
+
|
|
92
|
+
Returns (outcome, exit_price, exit_date), or None when the record stays open
|
|
93
|
+
(fewer post-record bars than horizon_days and nothing triggered). Stop is
|
|
94
|
+
checked before target within each bar — when both trigger on the same day
|
|
95
|
+
the conservative stop_hit wins."""
|
|
96
|
+
entry = rec.get("entry_price")
|
|
97
|
+
if not isinstance(entry, (int, float)) or entry <= 0:
|
|
98
|
+
return None
|
|
99
|
+
direction = rec.get("direction")
|
|
100
|
+
target = rec.get("target_price")
|
|
101
|
+
stop = rec.get("stop_price")
|
|
102
|
+
horizon = rec.get("horizon_days") or 10
|
|
103
|
+
eligible = sorted(
|
|
104
|
+
(b for b in bars if str(b.get("date", "")) > str(rec.get("record_date", ""))),
|
|
105
|
+
key=lambda b: str(b.get("date", "")),
|
|
106
|
+
)
|
|
107
|
+
for i, bar in enumerate(eligible, 1):
|
|
108
|
+
high, low, close = bar.get("high"), bar.get("low"), bar.get("close")
|
|
109
|
+
if direction == "buy":
|
|
110
|
+
hit_stop = stop is not None and low is not None and low <= stop
|
|
111
|
+
hit_target = target is not None and high is not None and high >= target
|
|
112
|
+
else:
|
|
113
|
+
hit_stop = stop is not None and high is not None and high >= stop
|
|
114
|
+
hit_target = target is not None and low is not None and low <= target
|
|
115
|
+
if hit_stop:
|
|
116
|
+
return "stop_hit", stop, bar.get("date")
|
|
117
|
+
if hit_target:
|
|
118
|
+
return "target_hit", target, bar.get("date")
|
|
119
|
+
if i >= horizon:
|
|
120
|
+
if not isinstance(close, (int, float)):
|
|
121
|
+
return None
|
|
122
|
+
ret = (close - entry) / entry * 100 * (1 if direction == "buy" else -1)
|
|
123
|
+
return ("timeout_profit" if ret > 0 else "timeout_loss"), close, bar.get("date")
|
|
124
|
+
return None
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _kline_count(rec: dict) -> int:
|
|
128
|
+
"""Daily bars to fetch for evaluation: horizon + buffer, but at least enough to
|
|
129
|
+
reach back to record_date (calendar days >= trading days), capped at 800."""
|
|
130
|
+
horizon = rec.get("horizon_days") or 10
|
|
131
|
+
try:
|
|
132
|
+
elapsed = (datetime.now() - datetime.strptime(str(rec.get("record_date", "")), "%Y-%m-%d")).days
|
|
133
|
+
except ValueError:
|
|
134
|
+
elapsed = 0
|
|
135
|
+
return min(max(horizon + 40, elapsed + 15), 800)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def cmd_evaluate(args):
|
|
139
|
+
store = _store_path(args)
|
|
140
|
+
records = _load_records(store)
|
|
141
|
+
results = []
|
|
142
|
+
evaluated = closed = 0
|
|
143
|
+
changed = False
|
|
144
|
+
for rec in records:
|
|
145
|
+
if rec.get("status") != "open":
|
|
146
|
+
continue
|
|
147
|
+
if args.symbol and rec.get("symbol") != args.symbol:
|
|
148
|
+
continue
|
|
149
|
+
evaluated += 1
|
|
150
|
+
entry = {"id": rec.get("id"), "symbol": rec.get("symbol")}
|
|
151
|
+
bars = run_tool(
|
|
152
|
+
"stock_data.py",
|
|
153
|
+
["kline", rec["symbol"], "--period", "daily", "--count", str(_kline_count(rec))],
|
|
154
|
+
)
|
|
155
|
+
if not isinstance(bars, list):
|
|
156
|
+
entry.update({"outcome": "skipped_no_data", "return_pct": None, "exit_date": None})
|
|
157
|
+
else:
|
|
158
|
+
ev = _evaluate_bars(rec, bars)
|
|
159
|
+
if ev is None:
|
|
160
|
+
entry.update({"outcome": "open", "return_pct": None, "exit_date": None})
|
|
161
|
+
else:
|
|
162
|
+
outcome, exit_price, exit_date = ev
|
|
163
|
+
ret = round((exit_price - rec["entry_price"]) / rec["entry_price"] * 100, 2)
|
|
164
|
+
if rec.get("direction") == "sell":
|
|
165
|
+
ret = -ret
|
|
166
|
+
rec.update(
|
|
167
|
+
{
|
|
168
|
+
"status": "closed",
|
|
169
|
+
"outcome": outcome,
|
|
170
|
+
"exit_price": exit_price,
|
|
171
|
+
"exit_date": exit_date,
|
|
172
|
+
"return_pct": ret,
|
|
173
|
+
}
|
|
174
|
+
)
|
|
175
|
+
closed += 1
|
|
176
|
+
changed = True
|
|
177
|
+
entry.update({"outcome": outcome, "return_pct": ret, "exit_date": exit_date})
|
|
178
|
+
results.append(entry)
|
|
179
|
+
if changed:
|
|
180
|
+
try:
|
|
181
|
+
_save_records(store, records)
|
|
182
|
+
except OSError as e:
|
|
183
|
+
return {"error": str(e)}
|
|
184
|
+
return {"evaluated": evaluated, "closed": closed, "still_open": evaluated - closed, "results": results}
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def cmd_summary(args):
|
|
188
|
+
records = _load_records(_store_path(args))
|
|
189
|
+
filtered = records
|
|
190
|
+
if args.source:
|
|
191
|
+
filtered = [r for r in filtered if r.get("source") == args.source]
|
|
192
|
+
if args.symbol:
|
|
193
|
+
filtered = [r for r in filtered if r.get("symbol") == args.symbol]
|
|
194
|
+
if args.status != "all":
|
|
195
|
+
filtered = [r for r in filtered if r.get("status") == args.status]
|
|
196
|
+
|
|
197
|
+
closed_recs = [r for r in filtered if r.get("status") == "closed"]
|
|
198
|
+
closed = len(closed_recs)
|
|
199
|
+
counts = {
|
|
200
|
+
o: sum(1 for r in closed_recs if r.get("outcome") == o)
|
|
201
|
+
for o in ("target_hit", "stop_hit", "timeout_profit", "timeout_loss")
|
|
202
|
+
}
|
|
203
|
+
wins = counts["target_hit"] + counts["timeout_profit"]
|
|
204
|
+
returns = [r["return_pct"] for r in closed_recs if isinstance(r.get("return_pct"), (int, float))]
|
|
205
|
+
by_source = {}
|
|
206
|
+
for r in closed_recs:
|
|
207
|
+
agg = by_source.setdefault(r.get("source") or "unknown", {"closed": 0, "wins": 0})
|
|
208
|
+
agg["closed"] += 1
|
|
209
|
+
if r.get("outcome") in ("target_hit", "timeout_profit"):
|
|
210
|
+
agg["wins"] += 1
|
|
211
|
+
for agg in by_source.values():
|
|
212
|
+
agg["win_rate"] = round(agg["wins"] / agg["closed"] * 100, 2) if agg["closed"] else None
|
|
213
|
+
return {
|
|
214
|
+
"filters": {"source": args.source, "symbol": args.symbol, "status": args.status},
|
|
215
|
+
"summary": {
|
|
216
|
+
"total": len(filtered),
|
|
217
|
+
"open": sum(1 for r in filtered if r.get("status") == "open"),
|
|
218
|
+
"closed": closed,
|
|
219
|
+
"target_hit": counts["target_hit"],
|
|
220
|
+
"stop_hit": counts["stop_hit"],
|
|
221
|
+
"timeout_profit": counts["timeout_profit"],
|
|
222
|
+
"timeout_loss": counts["timeout_loss"],
|
|
223
|
+
"win_rate": round(wins / closed * 100, 2) if closed else None,
|
|
224
|
+
"avg_return_pct": round(sum(returns) / len(returns), 2) if returns else None,
|
|
225
|
+
},
|
|
226
|
+
"by_source": by_source,
|
|
227
|
+
"records": filtered,
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def main():
|
|
232
|
+
parser = argparse.ArgumentParser(description="Signal tracker — AI suggestion outcome store (JSONL)")
|
|
233
|
+
sub = parser.add_subparsers(dest="command")
|
|
234
|
+
|
|
235
|
+
p_rec = sub.add_parser("record")
|
|
236
|
+
p_rec.add_argument("symbol")
|
|
237
|
+
p_rec.add_argument("--direction", required=True, choices=["buy", "sell"])
|
|
238
|
+
p_rec.add_argument("--entry-price", type=float, default=None, help="Default: current price via stock_data quote")
|
|
239
|
+
p_rec.add_argument("--target-price", type=float, default=None)
|
|
240
|
+
p_rec.add_argument("--stop-price", type=float, default=None)
|
|
241
|
+
p_rec.add_argument("--horizon-days", type=int, default=10)
|
|
242
|
+
p_rec.add_argument("--source", default=None)
|
|
243
|
+
p_rec.add_argument("--note", default=None)
|
|
244
|
+
p_rec.add_argument("--date", default=None, help="Record date YYYY-MM-DD (default: today)")
|
|
245
|
+
p_rec.add_argument("--store", default=None, help="JSONL store path override")
|
|
246
|
+
|
|
247
|
+
p_eval = sub.add_parser("evaluate")
|
|
248
|
+
p_eval.add_argument("--symbol", default=None)
|
|
249
|
+
p_eval.add_argument("--store", default=None, help="JSONL store path override")
|
|
250
|
+
|
|
251
|
+
p_sum = sub.add_parser("summary")
|
|
252
|
+
p_sum.add_argument("--source", default=None)
|
|
253
|
+
p_sum.add_argument("--symbol", default=None)
|
|
254
|
+
p_sum.add_argument("--status", default="all", choices=["open", "closed", "all"])
|
|
255
|
+
p_sum.add_argument("--store", default=None, help="JSONL store path override")
|
|
256
|
+
|
|
257
|
+
args = parser.parse_args()
|
|
258
|
+
if not args.command:
|
|
259
|
+
parser.print_help()
|
|
260
|
+
sys.exit(1)
|
|
261
|
+
|
|
262
|
+
dispatch = {"record": cmd_record, "evaluate": cmd_evaluate, "summary": cmd_summary}
|
|
263
|
+
result = dispatch[args.command](args)
|
|
264
|
+
print(json.dumps(result, ensure_ascii=False, default=str))
|
|
265
|
+
if isinstance(result, dict) and "error" in result:
|
|
266
|
+
sys.exit(1)
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
if __name__ == "__main__":
|
|
270
|
+
# Windows defaults stdio to a legacy code page (cp1252) that cannot encode the
|
|
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")
|
|
275
|
+
main()
|