@weaxs/dsh-stock-analysis 0.2.4 → 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/dist/index.js +248 -14
- package/package.json +1 -1
- package/schemas/report_schema.json +3 -3
- package/scripts/setup-python.mjs +6 -6
- 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/stock-analysis/SKILL.md +31 -3
- package/skills/stock-screener/SKILL.md +20 -0
- package/skills/strategy-backtest/SKILL.md +6 -0
- package/skills/wisburg-research/SKILL.md +2 -0
- 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/alert_rules.py +32 -4
- package/tools/backtest.py +22 -4
- package/tools/capabilities.py +12 -0
- package/tools/diagnostics.py +6 -0
- package/tools/gather.py +20 -10
- package/tools/lixinger.py +100 -0
- package/tools/market_regime.py +7 -3
- package/tools/market_review.py +7 -6
- package/tools/position_context.py +20 -2
- package/tools/report_renderer.py +2 -0
- package/tools/risk_screening.py +45 -17
- package/tools/screener.py +64 -4
- package/tools/sec_edgar.py +346 -0
- package/tools/sec_holders.py +263 -0
- package/tools/signal_tracker.py +142 -19
- package/tools/stock_data.py +321 -116
- package/tools/technical.py +16 -2
- package/tools/value_data.py +1527 -0
- package/tools/watchlist.py +24 -1
- package/tools/watchlist_context.py +7 -3
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Skill-local tail diagnostics from historical returns or backtest JSON."""
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import json
|
|
6
|
+
import math
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
import numpy as np
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class Parser(argparse.ArgumentParser):
|
|
14
|
+
def error(self, message):
|
|
15
|
+
raise ValueError(message)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def finite_number(value):
|
|
19
|
+
if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):
|
|
20
|
+
raise ValueError("Input values must be finite JSON numbers")
|
|
21
|
+
return float(value)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def analyze_returns(data, args):
|
|
25
|
+
if not isinstance(data, list) or len(data) < 2:
|
|
26
|
+
raise ValueError("Expected a JSON array of at least two historical returns")
|
|
27
|
+
values = np.array([finite_number(value) for value in data])
|
|
28
|
+
if not 100 <= args.draws <= 1000000 or args.seed < 0 or any(n < 2 or n > 10000 for n in args.n):
|
|
29
|
+
raise ValueError("Require draws in 100..1000000, seed >= 0, and n in 2..10000")
|
|
30
|
+
centered = values - values.mean()
|
|
31
|
+
mad = float(np.abs(centered).mean())
|
|
32
|
+
rng = np.random.default_rng(args.seed)
|
|
33
|
+
rows = []
|
|
34
|
+
for n in args.n:
|
|
35
|
+
total = 0.0
|
|
36
|
+
if mad > 0:
|
|
37
|
+
# Bound temporary arrays when either summands or draws is large.
|
|
38
|
+
batch_size = max(1, 1000000 // n)
|
|
39
|
+
for start in range(0, args.draws, batch_size):
|
|
40
|
+
batch = min(batch_size, args.draws - start)
|
|
41
|
+
sums = rng.choice(centered, size=(batch, n)).sum(axis=1)
|
|
42
|
+
total += float(np.abs(sums).sum())
|
|
43
|
+
summed_mad = total / args.draws
|
|
44
|
+
denominator = math.log(summed_mad / mad) if mad > 0 and summed_mad > 0 else 0
|
|
45
|
+
rows.append(
|
|
46
|
+
{
|
|
47
|
+
"n0": 1,
|
|
48
|
+
"n": n,
|
|
49
|
+
"mean_absolute_deviation_sum": summed_mad,
|
|
50
|
+
"kappa": 2 - math.log(n) / denominator if denominator else None,
|
|
51
|
+
"unavailable_reason": None if denominator else "Zero dispersion or degenerate aggregation",
|
|
52
|
+
}
|
|
53
|
+
)
|
|
54
|
+
event = None
|
|
55
|
+
if args.current is not None:
|
|
56
|
+
current = finite_number(args.current)
|
|
57
|
+
event = {
|
|
58
|
+
"return": current,
|
|
59
|
+
"percentile": float(np.mean(values <= current)),
|
|
60
|
+
"upper_exceedances": int(np.sum(values > current)),
|
|
61
|
+
"lower_exceedances": int(np.sum(values < current)),
|
|
62
|
+
}
|
|
63
|
+
return {
|
|
64
|
+
"sample_count": len(values),
|
|
65
|
+
"draws": args.draws,
|
|
66
|
+
"seed": args.seed,
|
|
67
|
+
"mean_absolute_deviation": mad,
|
|
68
|
+
"kappa": rows,
|
|
69
|
+
"current_event": event,
|
|
70
|
+
"method": "iid resampling of centered empirical returns; not a population tail estimate or trading signal",
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def analyze_trades(data):
|
|
75
|
+
if not isinstance(data, dict) or not isinstance(data.get("trades"), list):
|
|
76
|
+
raise ValueError("Expected a backtest JSON object with a trades array")
|
|
77
|
+
if any(not isinstance(trade, dict) or trade.get("type") not in {"buy", "sell"} for trade in data["trades"]):
|
|
78
|
+
raise ValueError("Each trade must have type buy or sell")
|
|
79
|
+
pnl = [finite_number(trade.get("pnl")) for trade in data["trades"] if trade["type"] == "sell"]
|
|
80
|
+
winners = sorted((value for value in pnl if value > 0), reverse=True)
|
|
81
|
+
gross_profit = math.fsum(winners)
|
|
82
|
+
gross_loss = math.fsum(value for value in pnl if value < 0)
|
|
83
|
+
net = math.fsum(pnl)
|
|
84
|
+
return {
|
|
85
|
+
"closed_trades": len(pnl),
|
|
86
|
+
"winning_trades": len(winners),
|
|
87
|
+
"gross_profit": gross_profit,
|
|
88
|
+
"gross_loss": gross_loss,
|
|
89
|
+
"realized_net_pnl": net,
|
|
90
|
+
"worst_trade_pnl": min(pnl) if pnl else None,
|
|
91
|
+
"winner_contribution": [
|
|
92
|
+
{
|
|
93
|
+
"requested_k": k,
|
|
94
|
+
"actual_k": min(k, len(winners)),
|
|
95
|
+
"share_of_gross_profit": math.fsum(winners[:k]) / gross_profit if gross_profit else None,
|
|
96
|
+
"realized_pnl_without_top_k": net - math.fsum(winners[:k]),
|
|
97
|
+
}
|
|
98
|
+
for k in (1, 3)
|
|
99
|
+
],
|
|
100
|
+
"method": "closed monetary pnl only; deletion sensitivity is not an equity-curve rerun",
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def main():
|
|
105
|
+
try:
|
|
106
|
+
parser = Parser(description=__doc__)
|
|
107
|
+
sub = parser.add_subparsers(dest="command", required=True, parser_class=Parser)
|
|
108
|
+
returns = sub.add_parser("returns", help="Analyze a JSON array of historical log returns")
|
|
109
|
+
returns.add_argument("input", type=Path)
|
|
110
|
+
returns.add_argument("--n", nargs="+", type=int, default=[2, 10, 30])
|
|
111
|
+
returns.add_argument("--draws", type=int, default=20000)
|
|
112
|
+
returns.add_argument("--seed", type=int, default=42)
|
|
113
|
+
returns.add_argument("--current", type=float, help="Separate current return, excluded from historical input")
|
|
114
|
+
trades = sub.add_parser("trades", help="Analyze a complete run_backtest JSON result")
|
|
115
|
+
trades.add_argument("input", type=Path)
|
|
116
|
+
args = parser.parse_args()
|
|
117
|
+
data = json.loads(args.input.read_text(encoding="utf-8"))
|
|
118
|
+
result = analyze_returns(data, args) if args.command == "returns" else analyze_trades(data)
|
|
119
|
+
print(json.dumps(result, ensure_ascii=True, allow_nan=False))
|
|
120
|
+
return 0
|
|
121
|
+
except OSError:
|
|
122
|
+
error = "Cannot read input JSON file"
|
|
123
|
+
except (ValueError, OverflowError) as exc:
|
|
124
|
+
error = "Invalid JSON input" if isinstance(exc, json.JSONDecodeError) else str(exc)
|
|
125
|
+
except Exception:
|
|
126
|
+
error = "Tail analysis failed unexpectedly"
|
|
127
|
+
print(json.dumps({"error": error}, ensure_ascii=True))
|
|
128
|
+
return 1
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
if __name__ == "__main__":
|
|
132
|
+
sys.exit(main())
|
|
@@ -22,6 +22,8 @@ gather 工具返回:
|
|
|
22
22
|
- `stock_info` — 公司基本信息
|
|
23
23
|
- `sector_rankings` — 板块排名
|
|
24
24
|
|
|
25
|
+
A 股事件原文先调用 `get_announcements`:业绩预告用 `forecast`、快报用 `express`、减持用 `reduction`、增发用 `issuance`、问询及回复用 `inquiry`、分红用 `dividend`,指定 `start_date/end_date`。返回 PDF 链接而非正文;读取原文后再量化,`truncated=true` 时缩小日期范围。
|
|
26
|
+
|
|
25
27
|
新闻摘要只用于发现事件。金额、期限、合同对手、业绩变化或政策原文必须由公告/原文确认;只有摘要时不做精确量化。
|
|
26
28
|
|
|
27
29
|
制定短线计划时读取[短线交易决策框架](../stock-analysis/references/short-term-trading.md),用状态机、相对强弱和风险单位约束事件交易。
|
|
@@ -87,3 +89,9 @@ gather 工具返回:
|
|
|
87
89
|
5. 触发、失效、时间止损、潜在收益/R 与风险提示
|
|
88
90
|
|
|
89
91
|
完成标准:区分“已确认事实”“推断的影响路径”和“待验证项”,并为交易计划给出可观察的失效条件。
|
|
92
|
+
|
|
93
|
+
财报季排期使用 `get_earnings_calendar(report_date="YYYY-MM-DD", symbol=...)`:最新预约/修订日期是计划,实际披露日期是实绩时间,业绩预告是已公告预估。除息事件用 `get_dividends(mode="calendar", symbol=...)`;不补造未公告日期或把分红预案计入已支付现金。
|
|
94
|
+
|
|
95
|
+
### 补充数据覆盖
|
|
96
|
+
|
|
97
|
+
get_earnings_calendar 查询 A 股仍需 report_date;HK 提供 symbol,可选财政期末 report_date;优先 HKEX 已公告业绩审批董事会排期 confirmation=official_board_meeting_notice、date_kind=scheduled_board_meeting,不能称实际披露日。供应商备选日期为 provider_only,未知期次在请求特定报告期时另列 unverified_schedules,不能强行匹配。
|
|
@@ -22,6 +22,8 @@ gather 工具返回:
|
|
|
22
22
|
- `stock_info` — 公司基本信息(行业、板块)
|
|
23
23
|
- `sector_rankings` — 板块排名
|
|
24
24
|
|
|
25
|
+
需要财务趋势时调用 `get_financials(symbol, annual=true, periods=10)`。港股配置 `LIXINGER_TOKEN` 后优先理杏仁非金融公司财报,按真实 `report_type` 判断年报,保留实际财年末、披露日期、币种;历史 ROE/毛利率/净利率为百分数,顶层 `roe/profit_margin` 延续小数比例。读取 `available_periods/warnings`,缺期不补造。有效 Yahoo 顶层快照与历史行分开读:`currency` 为快照财报币种、`market_cap_currency` 为市值币种,历史币种在 `periods` 每行,`snapshot_source` 标记快照来源;null 不用历史值补成跨期或跨币种数字;顶层 `report_date` 未知时读取 `periods` 的历史日期,不当作当前快照报告期。
|
|
26
|
+
|
|
25
27
|
`financials` 通常只是单期摘要。多期趋势、经营现金流、应收账款或同业估值未返回时,把对应维度标为“数据不足”,不推断趋势、不计分。
|
|
26
28
|
|
|
27
29
|
## 分析框架(4 步法)
|
|
@@ -77,3 +79,9 @@ gather 工具返回:
|
|
|
77
79
|
5. 投资建议与关注风险点
|
|
78
80
|
|
|
79
81
|
只有收入、利润、现金流和 ROE 均有可比多期数据时,才可给出“优质”结论;否则完成标准是给出已验证项、缺失项和最小补证建议。
|
|
82
|
+
|
|
83
|
+
用户要求长期质量、五到十年财报或 ROE/利润率趋势时,补充 `get_financials(symbol, periods=10, annual=true)`;逐年比较同口径年报,实际可得年份不足时明确标注,不以最近十个季度代替十年。结合 `get_valuation_history` 检查估值分位,分位窗口以实际返回数据为准。
|
|
84
|
+
|
|
85
|
+
### 补充数据覆盖
|
|
86
|
+
|
|
87
|
+
指数估值可用 get_index_valuation;中证补充多年滚动 PE,配置 LIXINGER_TOKEN 可补理杏仁 mcw 历史 PB。每个指标按其来源/口径使用,不把缺失 PB 或近期 PE1 当长期数据。
|
|
@@ -5,6 +5,10 @@ description: 综合股票分析:联合技术、基本面、资金、消息和
|
|
|
5
5
|
|
|
6
6
|
# 综合股票分析
|
|
7
7
|
|
|
8
|
+
美股机构研究调用 `get_us_holdings(cik, mode=auto)`:有当前或已检索历史 13F 时返回机构组合,否则按发行人 CIK 反查机构;也可显式选 `manager/issuer`,如 Berkshire `0001067983` 查组合、Apple `0000320193` 用 `issuer` 查机构。发行人映射仅使用核对 CIK 的官方 13D/G CUSIP,不做名称猜测;无映射直接报缺失。首次下载约 100 MB,后续缓存,Hermes 查询预算 300 秒。读取 `report_date/filing_window_end/cusip_evidence`,区分持仓日期与披露窗口;修订重述替换、新增补充,缺基础版或未知修订时总量 null,并计入 `unresolved_manager_count`。`mapping_complete=false` 表示不能保证涵盖所有类别或变更,`complete_for_mapped_cusips` 只表示已映射证券在公开数据窗口的申报链完整性,不能称实时全部股东。期权/本金在 `positions` 单列,不能把跨机构持股简单合计成去重比例。机构组合查询仍返回最新已知报告期的原始 13F 与修订链接,缺少对应原始版时明确报错;`history_truncated=true` 时不能将旧记录当作已完整检索。存在修订先读原文,不能自动推断变化。
|
|
9
|
+
|
|
10
|
+
美股内部人研究调用 `get_insider_trades(symbol, days=90, top=10)`,需设置含真实联系邮箱的 `SEC_USER_AGENT`。`days` 按申报日期过滤,`top` 限制文件数;只将代码 P/S 视作买卖信号,授予、行权、赠与等保留原始代码和脚注,衍生品单列。Form 4/A 与原申报勿重复计算,检查截断和失败提示;`screen_risk` 仍仅支持 A 股。
|
|
11
|
+
|
|
8
12
|
## 意图路由表
|
|
9
13
|
|
|
10
14
|
快速问答先判断意图,按下表走最短调用链;完整综合研判走下方执行流程(gather 采集管线),不受此表限制。单工具可答的问题按各工具描述中的适用场景选择,本表不再重复。
|
|
@@ -22,16 +26,18 @@ description: 综合股票分析:联合技术、基本面、资金、消息和
|
|
|
22
26
|
|
|
23
27
|
### 第一步:采集数据
|
|
24
28
|
|
|
25
|
-
|
|
29
|
+
运行数据采集脚本(并行采集行情、K 线、财务、资金、筹码、新闻、舆情、风险和大盘状态;技术指标复用本次 K 线计算):
|
|
26
30
|
|
|
27
31
|
```bash
|
|
28
32
|
python3 scripts/gather.py <symbol>
|
|
29
33
|
```
|
|
30
34
|
|
|
31
|
-
解析返回的 JSON 数据。如果某个字段为 `null
|
|
35
|
+
解析返回的 JSON 数据。如果某个字段为 `null` 或包含 `error`,表示该数据不可用,基于可用数据继续分析。大盘状态按股票所属市场查询;日/韩/台市场暂不支持,标明缺失,不能套用 A 股状态。
|
|
32
36
|
|
|
33
37
|
解读实时行情前先调 `get_trading_phase` 确认该市场当前盘中阶段(盘前/早盘/午间休市/午盘/交易中/盘后/休市),避免把休市时的静态快照当作盘中信号解读。
|
|
34
38
|
|
|
39
|
+
港股 `get_quote` 自动按 yfinance → 腾讯 → finnhub → longbridge 容灾,腾讯无需 API key,使用 `r_hk` 实时报价通道(`hk` 通道延迟约 15 分钟)。腾讯港股成交量为股,成交额及市值为港元;PB、换手率、量比为 null 时按缺失处理。该备用源只覆盖报价,K 线仍走原链路。
|
|
40
|
+
|
|
35
41
|
### 第二步:综合研判
|
|
36
42
|
|
|
37
43
|
根据获取的数据进行多维度分析:
|
|
@@ -60,7 +66,7 @@ python3 scripts/gather.py <symbol>
|
|
|
60
66
|
|
|
61
67
|
**风险筛查**:
|
|
62
68
|
- 7维度风险标记(估值极端/技术预警/解禁到期/内部人减持/业绩预警/监管处罚/行业政策)
|
|
63
|
-
- 风险评级(low/medium/high)和一票否决(veto_buy
|
|
69
|
+
- 风险评级(low/medium/high/unknown)和一票否决(veto_buy);查看 data_complete、warnings,unknown 或 null 表示缺少数据,不能据此判定低风险或已通过检查
|
|
64
70
|
- 如果 veto_buy=true,必须在报告中醒目提示
|
|
65
71
|
|
|
66
72
|
### 第三步:渲染研报
|
|
@@ -77,6 +83,7 @@ python3 scripts/gather.py <symbol>
|
|
|
77
83
|
- 信号持久化在本地 JSONL(`$STOCK_SIGNAL_STORE` 或 `~/.stock-analysis/signals.jsonl`);是否记录由宿主 Agent 决定,不阻塞报告输出。
|
|
78
84
|
|
|
79
85
|
## 注意事项
|
|
86
|
+
- `get_kline` 的 A 股股票/ETF 数据为前复权,每条记录 `adjusted="qfq"`;显式指数 `sh000xxx` / `sz399xxx` 为原始点位,`adjusted="none"`。复权数据源全部失败时说明数据缺失,不用未复权价格补算指标或信号。
|
|
80
87
|
- 始终提供风险提示
|
|
81
88
|
- 不做绝对化的涨跌预测
|
|
82
89
|
- 建议用户结合自身风险偏好做决策
|
|
@@ -84,3 +91,24 @@ python3 scripts/gather.py <symbol>
|
|
|
84
91
|
- 如果风险筛查返回 veto_buy=true,必须醒目标注并建议谨慎
|
|
85
92
|
|
|
86
93
|
完成标准:每个买卖建议都对应可观察的触发条件和失效条件,且所有缺失数据及其影响已说明。
|
|
94
|
+
|
|
95
|
+
## 低频价投数据
|
|
96
|
+
|
|
97
|
+
按用户问题选择数据,完整说明口径、采样覆盖和缺失项:
|
|
98
|
+
|
|
99
|
+
- 判断估值贵贱:`get_valuation_history(symbol, years=5)` 的 PE-TTM/PB 历史正值分位与 Band;亏损 PE 不计算分位,实际采样不足五年必须说明。
|
|
100
|
+
- 读多年财报:`get_financials(symbol, periods=10, annual=true)`;A 股按年报筛选,港股按源实际可得年度数返回。财报期不等于公告日,年报历史不能用于假定当时已知信息的回测。
|
|
101
|
+
- 财报季排期:`get_earnings_calendar(report_date="YYYY-MM-DD", symbol=...)`,区分最新预约日期、实际披露日期和已公告业绩预告,不把预告当业绩实绩。
|
|
102
|
+
- 股东变化:`get_shareholder_structure`。A 股北向值是财报十大流通股东中的 HKSCC 名义持股,缺席不等于零,不能当成日度北向买卖;港股南向值按港交所披露日期使用。
|
|
103
|
+
- 大盘估值:`get_index_valuation(symbol="000300", years=5)`;中证近期 PE1 不冒充 PE-TTM、PB 或多年分位。
|
|
104
|
+
- ETF:`get_etf_details(symbol="510300", benchmark="sh000300")`。折溢价须看净值/行情日期;披露持仓不是完整实时申赎篮子,指数成分与基金持仓分别呈现。跟踪误差必须给出用户认可的基准。
|
|
105
|
+
- 股息:`get_dividends` 区分历史、未来已公布除息日历和 A 股报告期排行;预案不计入已实现 TTM 股息。名义每股现金未重算送转股口径,遇送转股时不得据此精确比较持有收益。
|
|
106
|
+
- 两融:`get_margin_trading(include_ratio=true)` 的 `margin_buy_ratio_pct` 只使用同日成交额;null 表示不可计算。
|
|
107
|
+
|
|
108
|
+
慢变数据存于 `~/.stock-analysis/cache`:财报、基本信息及新历史数据按天,板块映射按周;行情仍实时查询。输出中的报告期/数据日期决定能否用于判断,缓存命中不代表数据已更新。
|
|
109
|
+
|
|
110
|
+
### 补充数据覆盖
|
|
111
|
+
|
|
112
|
+
get_shareholder_structure 的 northbound 优先使用沪深官方季度总量;northbound_nominee 只是十大股东推断,不能混同。get_etf_details 的 basket 是完整已发布 PCF,对价数量/现金替代规则不是基金实际持仓或NAV权重。HK 股息排行使用 get_dividends(mode=ranking, market=HK),年度口径不能称 TTM。
|
|
113
|
+
|
|
114
|
+
实际披露股票持仓可用 get_etf_details(include_full_holdings=true) 获取半年度/年度表;按 as_of 解释,数量为股、市值为人民币元。默认不取大量明细;不是实时全资产组合,不与 PCF 对价数量混同。
|
|
@@ -5,6 +5,8 @@ description: 全市场股票筛选:按市场、估值、成长、趋势或自
|
|
|
5
5
|
|
|
6
6
|
# 全市场股票筛选
|
|
7
7
|
|
|
8
|
+
显式筛选条件缺少数据时工具返回 `error`,不能把该条件当作已通过。`filters_applied` 只包含实际执行的条件,基于返回的覆盖情况说明候选范围。
|
|
9
|
+
|
|
8
10
|
## 执行流程
|
|
9
11
|
|
|
10
12
|
### 第一步:确定筛选条件
|
|
@@ -73,3 +75,21 @@ python3 tools/screener.py screen --market A --top 20
|
|
|
73
75
|
- **成长型**:中等PE + 高营收增长 + 高换手率
|
|
74
76
|
- **趋势型**:放量突破 + 均线多头 + 高量比
|
|
75
77
|
- **低估反转**:超跌 + 低PB + 资金净流入
|
|
78
|
+
|
|
79
|
+
## 股息因子(A股,可选)
|
|
80
|
+
|
|
81
|
+
配置 `filters.dividend_yield_min` / `dividend_yield_max` 或 `sort_by: dividend_score` / `dividend_yield` 时才拉取股息数据。`dividend_report_date` 可指定报告期,默认上一年年末。这里使用已实施方案的**报告期股息率**(百分数),不是滚动十二个月股息率;缺失为未知,使用股息阈值时排除。启用后 value 分项加入股息横截面评分,未启用时不增加股息请求。
|
|
82
|
+
|
|
83
|
+
```yaml
|
|
84
|
+
filters:
|
|
85
|
+
dividend_yield_min: 3
|
|
86
|
+
sort_by: dividend_score
|
|
87
|
+
sort_order: desc
|
|
88
|
+
dividend_report_date: "2025-12-31"
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
筛选结果仍需用 `get_dividends(mode="history", symbol=...)` 核查已实施现金分红、连续支付年数与除息时间,不能把高股息直接解释为低风险。
|
|
92
|
+
|
|
93
|
+
### 补充数据覆盖
|
|
94
|
+
|
|
95
|
+
股息筛选支持 A/HK:A 股为报告期已实施方案股息率,HK 为 HKEX/LSEG 年度股息率。两者都不是当前价 TTM;使用结果的 yield_basis 和 report_date,缺失不当零。
|
|
@@ -7,6 +7,8 @@ description: 策略回测:定义或读取 AlphaEvo YAML 策略,回测收益
|
|
|
7
7
|
|
|
8
8
|
开始前读取[短线交易决策框架](../stock-analysis/references/short-term-trading.md)的风险单位和回测约束。回测用于反证策略,不把样本内收益包装成预测。
|
|
9
9
|
|
|
10
|
+
解读回测时,`period` 是实际取得的数据期间,`requested_period` 保留用户请求,`warnings` 提示两者差异。年化收益按实际期间计算;覆盖不完整时明确说明,不能声称完成了完整请求期间的验证。买入预算包含佣金,`position.size` 为 0..1 的资金比例。
|
|
11
|
+
|
|
10
12
|
## 工作流程
|
|
11
13
|
|
|
12
14
|
### 第一步:策略定义
|
|
@@ -55,6 +57,8 @@ position:
|
|
|
55
57
|
|
|
56
58
|
### 第二步:运行回测
|
|
57
59
|
|
|
60
|
+
A 股股票/ETF 回测统一使用前复权 K 线(每条记录 `adjusted="qfq"`),显式指数使用原始点位(`adjusted="none"`)。复权源不可用时停止本次回测并说明缺失,不混用未复权历史价格。
|
|
61
|
+
|
|
58
62
|
运行回测脚本:
|
|
59
63
|
|
|
60
64
|
```bash
|
|
@@ -75,6 +79,8 @@ python3 tools/backtest.py run <path.yaml> <symbol> --start <date> --end <date>
|
|
|
75
79
|
- 使用用户指定的互斥日期区间分别运行样本内和样本外回测。
|
|
76
80
|
- 成本假设引用结果中的 `costs` 字段(实际生效的佣金/滑点/印花税费率与实付费用合计),未模拟的费用与成交约束列入限制。
|
|
77
81
|
|
|
82
|
+
趋势策略或用户要求肥尾收益诊断时,读取 [肥尾度量与趋势收益诊断](../bull-trend/references/fat-tails.md)的盈利集中度部分,基于平仓 `pnl` 计算大赢家贡献和删除敏感性。只有用户询问市场收益分布时才进入 κ 分支。
|
|
83
|
+
|
|
78
84
|
未模拟的结算、涨跌停、复权或特定市场费用列入限制,结论限定为该模拟条件下的历史表现。
|
|
79
85
|
|
|
80
86
|
### 第四步:诊断
|
|
@@ -7,6 +7,8 @@ description: 智堡投研检索:查找机构研报、财报公告、电话会
|
|
|
7
7
|
|
|
8
8
|
智堡 MCP 涵盖海外投行研报、国内券商研究、资管报告、央行/政府文献、电话会纪要和财报公告。首先检查这些 MCP 工具是否可用;不可用时直接改用 `search_comprehensive_intel`。
|
|
9
9
|
|
|
10
|
+
港股估值功课调用 `get_valuation_history(symbol, years=10)`;配置 `LIXINGER_TOKEN` 时优先理杏仁非金融公司每日 PE-TTM/PB,失败回退百度。以返回的实际窗口和正值样本计算分位及 Band,不混接同一指标的不同来源,不将缺失解释为低估。
|
|
11
|
+
|
|
10
12
|
## 可用工具
|
|
11
13
|
|
|
12
14
|
智堡 MCP 提供以下工具(通过 `mcp__wisburg-mcp-server__` 前缀调用):
|
|
@@ -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/alert_rules.py
CHANGED
|
@@ -6,6 +6,7 @@ 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
|
|
10
11
|
from concurrent.futures import ThreadPoolExecutor
|
|
11
12
|
from datetime import datetime, timezone
|
|
@@ -31,8 +32,14 @@ RULE_TYPES = {
|
|
|
31
32
|
def _check_rule(rule: dict, quote: dict, tech: dict, anom: dict, risk: dict) -> dict | None:
|
|
32
33
|
rtype = rule.get("type")
|
|
33
34
|
value = rule.get("value")
|
|
34
|
-
if rtype not in RULE_TYPES:
|
|
35
|
+
if not isinstance(rtype, str) or rtype not in RULE_TYPES:
|
|
35
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"}
|
|
36
43
|
|
|
37
44
|
price = quote.get("price")
|
|
38
45
|
change_pct = quote.get("change_pct")
|
|
@@ -90,6 +97,8 @@ def _check_rule(rule: dict, quote: dict, tech: dict, anom: dict, risk: dict) ->
|
|
|
90
97
|
"message": f"量比 {ratio} 超过 {value}",
|
|
91
98
|
}
|
|
92
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"}
|
|
93
102
|
# value is an anomaly type string, e.g. "macd_golden_cross"
|
|
94
103
|
anomalies = (anom or {}).get("anomalies", [])
|
|
95
104
|
for a in anomalies:
|
|
@@ -106,6 +115,8 @@ def _check_rule(rule: dict, quote: dict, tech: dict, anom: dict, risk: dict) ->
|
|
|
106
115
|
return {"rule": rtype, "triggered": True, "severity": "high", "message": "风险筛查触发一票否决"}
|
|
107
116
|
elif rtype == "risk_level_at_least":
|
|
108
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"}
|
|
109
120
|
cur = order.get((risk or {}).get("risk_level"))
|
|
110
121
|
want = order.get(value)
|
|
111
122
|
if cur is not None and want is not None and cur >= want:
|
|
@@ -122,7 +133,7 @@ def _check_rule(rule: dict, quote: dict, tech: dict, anom: dict, risk: dict) ->
|
|
|
122
133
|
|
|
123
134
|
|
|
124
135
|
def check_rules(symbol: str, rules: list[dict]) -> dict:
|
|
125
|
-
if not rules:
|
|
136
|
+
if not isinstance(rules, list) or not rules or any(not isinstance(rule, dict) for rule in rules):
|
|
126
137
|
return {"symbol": symbol, "error": "no rules provided"}
|
|
127
138
|
|
|
128
139
|
needs_tech = any(r.get("type") == "volume_ratio_above" for r in rules)
|
|
@@ -141,6 +152,9 @@ def check_rules(symbol: str, rules: list[dict]) -> dict:
|
|
|
141
152
|
with ThreadPoolExecutor(max_workers=len(jobs)) as pool:
|
|
142
153
|
futures = {key: pool.submit(_run_json, script, args) for key, (script, args) in jobs.items()}
|
|
143
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
|
+
}
|
|
144
158
|
quote = fetched["quote"] or {}
|
|
145
159
|
tech = fetched.get("tech")
|
|
146
160
|
anom = fetched.get("anom")
|
|
@@ -153,13 +167,25 @@ def check_rules(symbol: str, rules: list[dict]) -> dict:
|
|
|
153
167
|
warnings.append("technical analysis fetch failed — volume_ratio rules cannot fire")
|
|
154
168
|
if needs_anom and not anom:
|
|
155
169
|
warnings.append("anomaly fetch failed — anomaly rules cannot fire")
|
|
156
|
-
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"):
|
|
157
171
|
warnings.append("risk screening fetch failed — risk rules cannot fire")
|
|
158
172
|
|
|
159
173
|
hits = []
|
|
160
174
|
evaluated = []
|
|
161
175
|
for rule in rules:
|
|
162
|
-
|
|
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)
|
|
163
189
|
if result is None:
|
|
164
190
|
evaluated.append({"rule": rule.get("type"), "triggered": False})
|
|
165
191
|
else:
|
|
@@ -214,6 +240,8 @@ def main():
|
|
|
214
240
|
result = check_rules(args.symbol, rules)
|
|
215
241
|
json.dump(result, sys.stdout, ensure_ascii=False, indent=2, default=str)
|
|
216
242
|
print()
|
|
243
|
+
if "error" in result:
|
|
244
|
+
sys.exit(1)
|
|
217
245
|
|
|
218
246
|
|
|
219
247
|
if __name__ == "__main__":
|
package/tools/backtest.py
CHANGED
|
@@ -16,6 +16,7 @@ import yaml
|
|
|
16
16
|
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
|
17
17
|
|
|
18
18
|
from _subproc import json_safe, run_tool, utf8_stdio
|
|
19
|
+
from stock_data import detect_market
|
|
19
20
|
from technical import bollinger_series, ema_series, ma_series, macd_series, rsi_series
|
|
20
21
|
|
|
21
22
|
# --------------- Strategy Loading ---------------
|
|
@@ -67,7 +68,7 @@ def fetch_kline(symbol: str, start: str | None, end: str | None) -> pd.DataFrame
|
|
|
67
68
|
if start and end:
|
|
68
69
|
d0 = datetime.strptime(start, "%Y-%m-%d")
|
|
69
70
|
d1 = datetime.strptime(end, "%Y-%m-%d")
|
|
70
|
-
count = max((d1 - d0).days + 60, 300)
|
|
71
|
+
count = max((datetime.now() - d0).days + 60, (d1 - d0).days + 60, 300)
|
|
71
72
|
|
|
72
73
|
# run_tool gives venv-python + a bounded timeout + None on any failure
|
|
73
74
|
# (non-zero exit, empty/invalid stdout); callers turn that into clean JSON.
|
|
@@ -251,7 +252,11 @@ def evaluate_conditions(df: pd.DataFrame, conditions: list, logic: str, idx: int
|
|
|
251
252
|
|
|
252
253
|
|
|
253
254
|
def simulate(df: pd.DataFrame, strategy: dict, capital: float, symbol: str) -> dict:
|
|
254
|
-
|
|
255
|
+
if not math.isfinite(capital) or capital <= 0:
|
|
256
|
+
raise ValueError("capital must be finite and positive")
|
|
257
|
+
if not np.isfinite(df["close"]).all() or (df["close"] <= 0).any():
|
|
258
|
+
raise ValueError("backtest prices must be finite and positive")
|
|
259
|
+
market = detect_market(symbol)
|
|
255
260
|
lot_size = 100 if market == "A" else 1
|
|
256
261
|
sim_cfg = strategy.get("simulation", {})
|
|
257
262
|
slippage = float(sim_cfg.get("slippage", 0.001))
|
|
@@ -268,6 +273,8 @@ def simulate(df: pd.DataFrame, strategy: dict, capital: float, symbol: str) -> d
|
|
|
268
273
|
exit_ = strategy.get("exit", {})
|
|
269
274
|
position_cfg = strategy.get("position", {})
|
|
270
275
|
size_frac = float(position_cfg.get("size", 1.0))
|
|
276
|
+
if not 0 <= size_frac <= 1:
|
|
277
|
+
raise ValueError("position.size must be a fraction in [0, 1]")
|
|
271
278
|
stop_loss = float(exit_.get("stop_loss", -0.10))
|
|
272
279
|
take_profit = float(exit_.get("take_profit", 0.50))
|
|
273
280
|
ts_val = exit_.get("trailing_stop")
|
|
@@ -297,7 +304,7 @@ def simulate(df: pd.DataFrame, strategy: dict, capital: float, symbol: str) -> d
|
|
|
297
304
|
if hit:
|
|
298
305
|
buy_price = price * (1 + slippage)
|
|
299
306
|
buy_amount = cash * size_frac
|
|
300
|
-
shares = int(buy_amount / buy_price / lot_size) * lot_size
|
|
307
|
+
shares = int(buy_amount / (buy_price * (1 + commission)) / lot_size) * lot_size
|
|
301
308
|
if shares <= 0:
|
|
302
309
|
continue
|
|
303
310
|
cost = shares * buy_price * (1 + commission)
|
|
@@ -417,7 +424,7 @@ def compute_metrics(trades: list, equity_curve: list, initial: float, final: flo
|
|
|
417
424
|
years = 1
|
|
418
425
|
annual_return = (1 + total_return) ** (1 / max(years, 0.01)) - 1 if total_return > -1 else total_return
|
|
419
426
|
|
|
420
|
-
equities = pd.Series([e["equity"] for e in equity_curve], dtype=float)
|
|
427
|
+
equities = pd.Series([initial, *[e["equity"] for e in equity_curve]], dtype=float)
|
|
421
428
|
peak = equities.cummax()
|
|
422
429
|
dd = (equities - peak) / peak
|
|
423
430
|
max_drawdown = float(dd.min()) if len(dd) > 0 else 0
|
|
@@ -653,6 +660,13 @@ def run_backtest(strategy_path: str, symbol: str, start: str | None, end: str |
|
|
|
653
660
|
if len(df) < 30:
|
|
654
661
|
return {"error": f"Insufficient data: {len(df)} rows (need at least 30)"}
|
|
655
662
|
|
|
663
|
+
requested_period = f"{start} to {end}"
|
|
664
|
+
actual_start = df["date"].iloc[0].strftime("%Y-%m-%d")
|
|
665
|
+
actual_end = df["date"].iloc[-1].strftime("%Y-%m-%d")
|
|
666
|
+
warnings = []
|
|
667
|
+
if actual_start != start or actual_end != end:
|
|
668
|
+
warnings.append(f"Actual data covers {actual_start} to {actual_end}; requested {requested_period}")
|
|
669
|
+
start, end = actual_start, actual_end
|
|
656
670
|
sim = simulate(df, strategy, capital, symbol)
|
|
657
671
|
final = sim["final_equity"]
|
|
658
672
|
metrics = compute_metrics(sim["trades"], sim["equity_curve"], capital, final, start, end)
|
|
@@ -661,6 +675,8 @@ def run_backtest(strategy_path: str, symbol: str, start: str | None, end: str |
|
|
|
661
675
|
"strategy": strategy.get("name", "unnamed"),
|
|
662
676
|
"symbol": symbol,
|
|
663
677
|
"period": f"{start} to {end}",
|
|
678
|
+
"requested_period": requested_period,
|
|
679
|
+
"warnings": warnings,
|
|
664
680
|
"initial_capital": capital,
|
|
665
681
|
"final_capital": final,
|
|
666
682
|
"costs": sim["costs"],
|
|
@@ -837,6 +853,8 @@ def main():
|
|
|
837
853
|
sys.exit(1)
|
|
838
854
|
|
|
839
855
|
print(json.dumps(json_safe(result), ensure_ascii=False, default=str))
|
|
856
|
+
if "error" in result:
|
|
857
|
+
sys.exit(1)
|
|
840
858
|
|
|
841
859
|
|
|
842
860
|
if __name__ == "__main__":
|
package/tools/capabilities.py
CHANGED
|
@@ -18,6 +18,18 @@ ALL_MARKETS = ["A", "HK", "US", "JP", "KR", "TW"]
|
|
|
18
18
|
|
|
19
19
|
# tool_name -> {markets: [supported markets], reason: str for unsupported}
|
|
20
20
|
TOOL_MATRIX = {
|
|
21
|
+
"get_announcements": {"markets": ["A"], "reason": "cninfo A-share disclosures only"},
|
|
22
|
+
"get_us_holdings": {"markets": ["US"], "reason": "SEC manager holdings or verified issuer-CUSIP reverse lookup"},
|
|
23
|
+
"get_insider_trades": {"markets": ["US"], "reason": "SEC issuer Form 4 only"},
|
|
24
|
+
"get_valuation_history": {"markets": ["A", "HK"], "reason": "A/HK historical valuation providers only"},
|
|
25
|
+
"get_index_valuation": {"markets": ["A"], "reason": "Chinese index valuation only"},
|
|
26
|
+
"get_earnings_calendar": {
|
|
27
|
+
"markets": ["A", "HK"],
|
|
28
|
+
"reason": "A-share disclosed calendar / HK single-symbol provider schedule",
|
|
29
|
+
},
|
|
30
|
+
"get_shareholder_structure": {"markets": ["A", "HK"], "reason": "A-share shareholder reports / HK southbound only"},
|
|
31
|
+
"get_etf_details": {"markets": ["A"], "reason": "A-share ETF portfolio/NAV/size only"},
|
|
32
|
+
"get_dividends": {"markets": ["A", "HK"], "reason": "A/HK dividend history and report-year ranking"},
|
|
21
33
|
"get_kline": {"markets": ALL_MARKETS, "reason": None},
|
|
22
34
|
"get_quote": {"markets": ALL_MARKETS, "reason": None},
|
|
23
35
|
"get_news": {"markets": ALL_MARKETS, "reason": None},
|
package/tools/diagnostics.py
CHANGED
|
@@ -27,6 +27,12 @@ PROVIDERS = {
|
|
|
27
27
|
# see stock_data._kline_tushare) — the tushare package is not in requirements,
|
|
28
28
|
# so availability is the token, not a package probe
|
|
29
29
|
"tushare": ("requests", ["TUSHARE_TOKEN"], ["A"], "pure-HTTP API (api.tushare.pro); no tushare package needed"),
|
|
30
|
+
"lixinger": (
|
|
31
|
+
"requests",
|
|
32
|
+
["LIXINGER_TOKEN"],
|
|
33
|
+
["A"],
|
|
34
|
+
"optional index PE/PB history; subscription permissions not probed",
|
|
35
|
+
),
|
|
30
36
|
"efinance": ("efinance", [], ["A"], None),
|
|
31
37
|
"tencent": ("requests", [], ["A"], "qt.gtimg.cn quote/kline, no auth (issue #25)"),
|
|
32
38
|
"sina": (
|