@weaxs/openclaw-stock-analysis 0.2.8 → 0.2.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.
Files changed (46) hide show
  1. package/README.md +3 -1
  2. package/dist/index.js +154 -20
  3. package/index.ts +126 -6
  4. package/openclaw.plugin.json +4 -1
  5. package/package.json +4 -3
  6. package/scripts/profile-offline.py +127 -0
  7. package/scripts/profile-workflows.py +87 -0
  8. package/scripts/setup-python.mjs +11 -4
  9. package/scripts/venv-python.mjs +7 -0
  10. package/skills/event-driven/SKILL.md +2 -0
  11. package/skills/growth-quality/SKILL.md +2 -0
  12. package/skills/market-review/SKILL.md +1 -1
  13. package/skills/sector-rotation/SKILL.md +57 -0
  14. package/skills/sector-rotation/references/computation.md +83 -0
  15. package/skills/sector-rotation/references/strategy_rules.md +62 -0
  16. package/skills/sector-rotation/scripts/rotation_metrics.py +11 -0
  17. package/skills/stock-analysis/SKILL.md +15 -4
  18. package/skills/stock-analysis/references/host-workflows.md +45 -0
  19. package/skills/stock-analysis/references/stateless-analysis.md +16 -2
  20. package/skills/stock-screener/SKILL.md +6 -0
  21. package/skills/strategy-backtest/SKILL.md +10 -3
  22. package/tools/_cache.py +93 -21
  23. package/tools/_subproc.py +43 -8
  24. package/tools/anomaly_detect.py +11 -6
  25. package/tools/backtest.py +225 -70
  26. package/tools/capabilities.py +3 -0
  27. package/tools/cli_budgets.json +2 -1
  28. package/tools/gather.py +63 -8
  29. package/tools/market_regime.py +26 -15
  30. package/tools/market_review.py +2 -2
  31. package/tools/position_context.py +5 -2
  32. package/tools/report_renderer.py +4 -0
  33. package/tools/requirements.txt +2 -2
  34. package/tools/risk_screening.py +40 -15
  35. package/tools/screener.py +44 -18
  36. package/tools/search_intel.py +94 -32
  37. package/tools/sec_holders.py +27 -25
  38. package/tools/sector_rotation.py +466 -0
  39. package/tools/signal_tracker.py +100 -49
  40. package/tools/stateless_analysis.py +600 -33
  41. package/tools/stock_data.py +111 -26
  42. package/tools/technical.py +42 -40
  43. package/tools/trading_calendar.py +26 -21
  44. package/tools/value_data.py +6 -2
  45. package/tools/watchlist.py +24 -15
  46. package/tools/watchlist_context.py +63 -49
@@ -17,7 +17,7 @@
17
17
 
18
18
  工具输出精确到传入文本行号的变化片段、来源、截断标志和指标差异。文本差异本身不等于经营变化;Agent 要阅读上下文,说明发生了什么、与原预期的关系和可能反证,并引用原文。金额单位和 basis 一致才计算 delta;前期值大于0才计算普通增长率,亏损转盈另述。报告期可不同,但必须核实是可比同长期间(年度/同比单季等),累计季度不能直接当单季。
19
19
 
20
- ## 组合风险:analyze_portfolio_risk
20
+ ## 组合风险与压力测试:analyze_portfolio_risk
21
21
 
22
22
  输入 `base_currency`、基准币种 `cash>=0`、`positions`(1..100项)。持仓 `{symbol, quantity, price, currency, cost?, stop_price?, sector?, as_of?}`,现货多头;重复标的先汇总。价格/数量为正,单位由调用方确认。
23
23
 
@@ -27,6 +27,20 @@
27
27
 
28
28
  可选 `histories:[{symbol,prices:[{date,close}]}]`,工具按每对标的共同日期计算收益相关性;至少4个共同价格点、存在波动才有结果。不是组合收益率或汇率调整后的相关性;少样本、跨时区非同步收盘和缺交易日都应说明,不从相关性推断因果。缺历史时明确相关性未计算。
29
29
 
30
+ 可选 `stress_scenarios`(1..20项)执行确定性压力测试。每项包含唯一 `name`,以及可选 `market_shock`、`sector_shocks:[{sector,shock}]`、`symbol_shocks:[{symbol,shock}]`、`currency_shocks:[{currency,shock}]`;shock 是 -1..1 的小数。个股冲击覆盖行业冲击,行业冲击覆盖市场冲击;汇率冲击独立乘算,不能与资产冲击重复相加。基准币种不能相对自身冲击,重复或当前组合中不存在的标的/行业/币种会报错。
31
+
32
+ `stress_tests` 返回每个情景的 `equity_before/equity_after/pnl_base/return_pct` 和逐持仓 `asset_shock/fx_shock/value_before/value_after/pnl_base`。这些是用户指定冲击下的 what-if 结果,不是预测、VaR 或最大亏损保证。
33
+
34
+ ## 目标权重调仓:plan_portfolio_rebalance
35
+
36
+ 输入 `base_currency`、基准币种 `cash>=0`、当前 `positions`(0..100项,纯现金可为空)和 `targets`(1..100项),汇率格式同上。当前持仓字段与组合风险一致,cost/stop_price 可保留但不参与调仓。
37
+
38
+ 每个 target 包含 `{symbol,weight,price?,currency?,sector?,as_of?,lot_size?}`。已有标的可继承当前价格、币种、行业和时点;新标的必须提供 price/currency。已有标的覆盖 price/currency 时,该有效价格与汇率同时用于初始权益、目标数量和调后权益,不能把新旧价差异计为无交易成本。weight 为 0..1,所有目标权重之和不得超过1,未分配部分保留现金;weight>0 时必须提供用户或交易规则确认的 lot_size。未出现在 targets 的当前持仓按 weight=0 全部退出。正目标权重按初始权益、参考价格和汇率向下取整到交易单位,不足一个交易单位则报错,不向上凑整。
39
+
40
+ 可选 `fee_rate`、`slippage_rate`(每边0..0.1)和 `max_turnover_fraction`(非负,默认不限制)。换手按买卖参考金额合计/初始权益计算,全仓换仓可超过1。计划先卖后买;卖出按 price×(1-slippage)×(1-fee) 估算回收,买入按 price×(1+slippage)×(1+fee) 估算成本。现金不足时所有买单按同一比例缩减并向下取整到各自交易单位,`cash_limited=true`。
41
+
42
+ 输出 `orders` 是参考价下的计划订单,不是已提交委托或成交;`unfilled` 分别用 `reason=lot_rounding/cash` 标记整手差额和现金未满足数量。整手差额按未取整原始调整需求减去整手后的计划数量计算,现金缩减另按计划前数量减去最终数量计算,两者不得重复。`positions_after` 同时保留 `target_weight` 与计划后的实际 `weight`,并返回 `cash_after/equity_after/gross_turnover_fraction/estimated_cost_base`。全额退出允许卖出当前全部数量;部分买卖向下取整,不为了贴近目标而超出目标。工具不提交订单,实际成交、未提供税费/最低收费、结算和流动性仍需核实。
43
+
30
44
  ## 仓位预算:calculate_position_size
31
45
 
32
46
  必需 `equity,cash,entry_price,stop_price,risk_fraction,lot_size`。风险比例0..1,止损正且低于入场价,现金0..equity,交易单位正整数。所有金额同币种。
@@ -43,7 +57,7 @@ lot_size 来自用户或可核实交易规则,尤其港股不能统一猜100
43
57
 
44
58
  事件日映射到股票序列中不早于指定日期的首日;盘后事件应显式使用下一交易日。基点是该日前一个股票交易日收盘;horizon=0表示事件当日收盘。基准必须同市场,并在两个端点都有数据,缺失时不移动事件日期。收益差是股票与基准各自买入持有收益的差(百分点),不等于因果影响。
45
59
 
46
- MUST 核实完整交易日、复权、币种和股息处理。工具无法从缺行判断是停牌、节假日还是数据故障。重叠事件标识意味着样本不独立;少样本均值不能作为稳定预测。
60
+ MUST 核实完整交易日、复权、币种和股息处理。工具无法从缺行判断是停牌、节假日还是数据故障。重叠事件标识意味着样本不独立;完全没有有效超额收益样本(包括股票窗口不足或基准端点缺失)的事件不参与重叠计算,不应误标相邻有效事件;部分 horizon 无效时,重叠区间只覆盖有效 horizon。少样本均值不能作为稳定预测。
47
61
 
48
62
  ## 回测稳健性:validate_backtest
49
63
 
@@ -5,6 +5,8 @@ description: 全市场股票筛选:按市场、估值、成长、趋势或自
5
5
 
6
6
  # 全市场股票筛选
7
7
 
8
+ 批量研究、子任务分工或报告文件交付时,必须读取[宿主研究与报告交付](../stock-analysis/references/host-workflows.md),使用当前宿主实际提供的能力。
9
+
8
10
  显式筛选条件缺少数据时工具返回 `error`,不能把该条件当作已通过。`filters_applied` 只包含实际执行的条件,基于返回的覆盖情况说明候选范围。
9
11
 
10
12
  ## 执行流程
@@ -68,6 +70,10 @@ python3 tools/screener.py screen --market A --top 20
68
70
 
69
71
  每个候选必须读取 `factor_coverage.available/missing/ratio/effective_weights`。ratio 是已覆盖因子的原始权重之和;L1 与 L2 的 effective_weights 均按可用因子重归一化,缺失或非有限值不按零分计,排序前先按实际可用因子计算综合分,effective_scores 保留实际参与计算的各组分数;用 sum(effective_scores[g] × effective_weights[g]) × market_sentiment.multiplier 核对 scores.final(四舍五入至一位)。scores.momentum 仍保留 L1 参考值,L2 贡献以 effective_scores.momentum 为准。相同分数但缺失因子不同的候选不能视为同等证据,报告缺失项和覆盖度,不以 `enriched=true` 代替覆盖判断。`scores.final=null` 表示没有足够因子计算,不能作为高分候选推荐。
70
72
 
73
+ 估值比较还需读取 `pe_basis`:dynamic、trailing 与 unknown 不得当成同一 PE 口径。筛选中的有限非正 PE/PB 价值子分为 0,不能因数值更低而获得最高价值分;缺失或非有限因子仍保持未知,不按零分处理。
74
+
75
+ L2 的 `vol20` 只使用恰好 20 个有效日收益,`factor_coverage.vol20_samples` 记录实际样本数,非正/非有限收盘价先剔除,空输入为 0;短样本为缺测。质量因子按 `report_date` 分组归一,年度累计与单季累计不得直接排名;资金流 5/10/20 日窗口不足时返回 null,不按 0 或完整窗口处理。
76
+
71
77
  完成标准:列出实际生效的市场、过滤条件、排序口径和候选数量,且推荐理由只使用返回数据,并说明因子覆盖。
72
78
 
73
79
  ## 策略模板
@@ -5,6 +5,8 @@ description: 策略回测:定义或读取 AlphaEvo YAML 策略,回测收益
5
5
 
6
6
  # 策略回测与优化
7
7
 
8
+ 批量研究、子任务分工或报告文件交付时,必须读取[宿主研究与报告交付](../stock-analysis/references/host-workflows.md),使用当前宿主实际提供的能力。
9
+
8
10
  生成股票池月度右侧趋势计划时,先读 [月度右侧趋势策略](../bull-trend/references/monthly-trend-strategy.md),直接以股票代码调用 `analyze_trend_strategy(symbols, ...)` 自动取行情,无需用户准备文件。这是整池信号/预算分析;共享资金历史绩效仍依据冻结研究,MUST NOT 用单股YAML或信号计划冒充组合回测。报告尚未通过跨样本效果验证的边界。
9
11
 
10
12
  开始前读取[短线交易决策框架](../stock-analysis/references/short-term-trading.md)的风险单位和回测约束。回测用于反证策略,不把样本内收益包装成预测。
@@ -55,12 +57,14 @@ simulation:
55
57
 
56
58
  position:
57
59
  size: 1.0 # 仓位比例
58
- max_positions: 1 # 最大持仓数
60
+ max_positions: 1 # 当前仅支持单持仓,其他值明确报错
59
61
  ```
60
62
 
61
63
  **可用指标**:rsi, ma, ema, macd_dif, macd_dea, macd, volume_ratio, price_change, bollinger_position, close, volume
62
64
 
63
- `monthly_momentum` 是共享核心的月度观察对数收益:`period` 默认63,支持21/63/252等正整数;月初首根正成交量日K收盘计算并保持到下次月度观察,次日开盘才可能成交。零成交量记录不计回溯根数。MUST 读取 [多期限月度趋势](../bull-trend/references/trend-horizons.md),不能把单期限YAML等同三子策略组合。需要在观察日已有period+1根有效日K;默认回测起点会截断输入历史,不能据此声称提前完成预热。三期限同资金起点的完整研究复现使用参考里的研究脚本。
65
+ `rsi` 在预热不足时不可用,连续上涨窗口为 100,全平窗口为中性 50;不可用值不能满足条件或制造交叉。`volume_ratio` 是当根成交量除以前 N 根平均成交量,不包含当根本身。
66
+
67
+ `monthly_momentum` 是共享核心的月度观察对数收益:`period` 默认63,支持21/63/252等正整数;月初首根正成交量日K收盘计算并保持到下次月度观察,次日开盘才可能成交。零成交量记录不计回溯根数。MUST 读取 [多期限月度趋势](../bull-trend/references/trend-horizons.md),不能把单期限YAML等同三子策略组合。需要在观察日已有period+1根有效日K;回测按策略最大 lookback 增加取数,起点前历史仅用于指标预热,交易和权益仍限于请求区间;`warnings` 出现 `Entry indicator is unavailable` 时必须披露指标不可用及数据质量,提供方历史不足时不能声称完成预热。三期限同资金起点的完整研究复现使用参考里的研究脚本。
64
68
 
65
69
  独立趋势强度可用 `trend_score`,默认 `(EMA20-EMA60)/ATR14`,ATR 为真实波幅简单平均。`fast_period/slow_period/period` 分别控制快 EMA、慢 EMA、ATR,要求正整数且快线小于慢线;默认 60 根预热,预热或零 ATR 不触发条件。解释七档显示、初始化与样本外验证前 MUST 读取 [独立趋势温度](../bull-trend/references/trend-temperature.md)。它不是星球温度或肥尾信号,原固定止损/止盈默认值仍生效。
66
70
 
@@ -68,6 +72,8 @@ position:
68
72
 
69
73
  **可用运算符**:`>`, `<`, `>=`, `<=`, `==`, `cross_above`, `cross_below`
70
74
 
75
+ `entry/exit.logic` 仅允许 `all/any`,operator 仅限上表;period/fast_period/slow_period 仅接受正整数或整数字符串,非法输入明确报错,不静默替换默认值或截断。
76
+
71
77
  ### 第二步:运行回测
72
78
 
73
79
  A 股股票/ETF 回测统一使用前复权 K 线(每条记录 `adjusted="qfq"`),显式指数使用原始点位(`adjusted="none"`)。复权源不可用时停止本次回测并说明缺失,不混用未复权历史价格。
@@ -83,7 +89,7 @@ python3 tools/backtest.py run <path.yaml> <symbol> --start <date> --end <date>
83
89
  - `--start` / `--end`:回测时间范围(可选,默认近一年)
84
90
  - 初始资金默认 100 万,可用 `--capital` 调整
85
91
 
86
- 默认 `simulation.execution=next_open`:信号在前一交易日收盘确定,下一有效交易日按开盘价加滑点成交;交易同时保留 `signal_date` 与实际 `date`。最后一天新信号没有后续开盘时不能成交。需要复现旧结果时显式使用 `same_close`,并说明它按信号日收盘成交,可能高估可执行收益。零/缺失成交量(已有 volume 字段时)阻止成交;一字涨跌停仅在输入提供同口径历史 `limit_up/limit_down` 时保守阻止,不猜 ST、IPO 或 ETF 限价。
92
+ 默认 `simulation.execution=next_open`:信号在前一交易日收盘确定,下一有效交易日按开盘价加滑点成交;交易同时保留 `signal_date` 与实际 `date`。最后一天新信号没有后续开盘时不能成交。需要复现旧结果时显式使用 `same_close`,并说明它按信号日收盘成交,可能高估可执行收益。零/缺失成交量(已有 volume 字段时)阻止成交;一字涨跌停仅在输入提供同口径历史 `limit_up/limit_down` 时保守阻止,不猜 ST、IPO 或 ETF 限价。延迟的入场信号在新收盘失效时撤单,风险退出 pending 保留至成交。回测仅接受单一 `qfq`/`total_return`/`none` 复权口径,unknown 或混合口径明确报错。
87
93
 
88
94
  读取 `execution.model/blocked_orders/unfilled_order/limitations` 并说明未成交情况。止损、止盈和移动止损均是收盘信号,不承诺盘中按阈值成交;次日跳空按实际开盘价计算。没有历史限价数据时,不能声称已验证涨跌停可成交性。
89
95
 
@@ -91,6 +97,7 @@ python3 tools/backtest.py run <path.yaml> <symbol> --start <date> --end <date>
91
97
 
92
98
  回测完成后,按共享框架的风险单位和回测约束解释原始结果。针对本工具:
93
99
 
100
+ - 基准与策略使用相同首日执行口径,无预热时以策略首条权益日期为起点;覆盖不符或首末价格非法时读取 `benchmark.error`,不能输出超额。
94
101
  - 从 `metrics` 和 `trades` 计算期望值并与盈亏比一起报告。
95
102
  - 报告最大回撤、连续亏损、交易次数和平均持有期;结果未携带初始风险时,将 1R 分布标为不可计算。
96
103
  - 使用用户指定的互斥日期区间分别运行样本内和样本外回测。
package/tools/_cache.py CHANGED
@@ -1,14 +1,16 @@
1
1
  """TTL cache for slow public datasets; live quotes and errors are never stored."""
2
2
 
3
3
  import contextlib
4
+ import errno
4
5
  import hashlib
5
6
  import json
6
7
  import os
7
- import tempfile
8
+ import sys
8
9
  import time
9
10
  from pathlib import Path
11
+ from uuid import uuid4
10
12
 
11
- CACHE_DIR = Path.home() / ".stock-analysis" / "cache"
13
+ CACHE_DIR = Path(os.environ.get("STOCK_CACHE_DIR") or Path.home() / ".stock-analysis" / "cache")
12
14
  DAY = 86400
13
15
  WEEK = 7 * DAY
14
16
 
@@ -34,28 +36,98 @@ def cached_values(namespace, ttl):
34
36
  yield entry.get("data")
35
37
 
36
38
 
39
+ @contextlib.contextmanager
40
+ def file_lock(path, timeout=5):
41
+ """Coordinate processes using a stable lock inode, with bounded waiting."""
42
+ path = Path(path)
43
+ path.parent.mkdir(parents=True, exist_ok=True)
44
+ with path.open("a+b") as lock:
45
+ if sys.platform == "win32":
46
+ import msvcrt
47
+
48
+ if lock.seek(0, os.SEEK_END) == 0:
49
+ lock.write(b"\0")
50
+ lock.flush()
51
+
52
+ def acquire():
53
+ lock.seek(0)
54
+ msvcrt.locking(lock.fileno(), msvcrt.LK_NBLCK, 1)
55
+
56
+ def release():
57
+ lock.seek(0)
58
+ msvcrt.locking(lock.fileno(), msvcrt.LK_UNLCK, 1)
59
+ else:
60
+ import fcntl
61
+
62
+ def acquire():
63
+ fcntl.flock(lock.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
64
+
65
+ def release():
66
+ fcntl.flock(lock.fileno(), fcntl.LOCK_UN)
67
+
68
+ deadline = time.monotonic() + timeout
69
+ while True:
70
+ try:
71
+ acquire()
72
+ break
73
+ except OSError as exc:
74
+ if exc.errno not in (errno.EACCES, errno.EAGAIN):
75
+ raise
76
+ remaining = deadline - time.monotonic()
77
+ if remaining <= 0:
78
+ raise TimeoutError("File lock timed out") from None
79
+ time.sleep(min(0.05, remaining))
80
+ try:
81
+ yield
82
+ finally:
83
+ release()
84
+
85
+
86
+ @contextlib.contextmanager
87
+ def atomic_write(path, *, binary=False):
88
+ """Publish a private same-directory file only after its writer succeeds."""
89
+ path = Path(path)
90
+ path.parent.mkdir(parents=True, exist_ok=True)
91
+ candidate = path.with_suffix(f".tmp-{uuid4().hex}")
92
+ tmp = None
93
+ try:
94
+ # tempfile may retry ACL denial billions of times on Windows.
95
+ with open(
96
+ candidate,
97
+ "x+b" if binary else "x",
98
+ encoding=None if binary else "utf-8",
99
+ opener=lambda name, flags: os.open(name, flags, 0o600),
100
+ ) as stream:
101
+ tmp = candidate
102
+ yield stream
103
+ os.replace(candidate, path)
104
+ finally:
105
+ if tmp is not None:
106
+ with contextlib.suppress(OSError):
107
+ tmp.unlink(missing_ok=True)
108
+
109
+
37
110
  def cached(key: str, ttl: int, fetch):
38
111
  path = CACHE_DIR / f"{_namespace_prefix(key.partition(':')[0])}-{hashlib.sha256(key.encode()).hexdigest()}.json"
39
112
  entry = _read(path, ttl)
40
113
  if entry and "data" in entry:
41
114
  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):
115
+ with contextlib.ExitStack() as stack:
116
+ # shortcut: slow fetches may outlast lock wait; prefer duplicate work to blocking callers indefinitely.
117
+ with contextlib.suppress(OSError):
118
+ stack.enter_context(file_lock(path.with_suffix(".lock")))
119
+ entry = _read(path, ttl)
120
+ if entry and "data" in entry:
121
+ return entry["data"]
122
+ result = fetch()
123
+ rows = result if isinstance(result, list) else [result]
124
+ if not result or any(isinstance(row, dict) and (row.get("error") or row.get("warnings")) for row in rows):
125
+ return result
126
+ try:
127
+ with atomic_write(path) as stream:
128
+ json.dump(
129
+ {"key": key, "fetched_at": time.time(), "data": result}, stream, ensure_ascii=False, allow_nan=False
130
+ )
131
+ except (OSError, ValueError, TypeError):
132
+ pass
45
133
  return result
46
- tmp = None
47
- try:
48
- CACHE_DIR.mkdir(parents=True, exist_ok=True)
49
- with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=CACHE_DIR, delete=False) as stream:
50
- tmp = stream.name
51
- json.dump(
52
- {"key": key, "fetched_at": time.time(), "data": result}, stream, ensure_ascii=False, allow_nan=False
53
- )
54
- os.replace(tmp, path)
55
- except (OSError, ValueError, TypeError):
56
- pass
57
- finally:
58
- if tmp:
59
- with contextlib.suppress(OSError):
60
- Path(tmp).unlink(missing_ok=True)
61
- return result
package/tools/_subproc.py CHANGED
@@ -14,6 +14,7 @@ import re
14
14
  import socket
15
15
  import subprocess
16
16
  import sys
17
+ import threading
17
18
  from pathlib import Path
18
19
 
19
20
  TOOLS_DIR = os.path.dirname(os.path.abspath(__file__))
@@ -113,19 +114,53 @@ def utf8_stdio() -> None:
113
114
  s.reconfigure(encoding="utf-8")
114
115
 
115
116
 
117
+ _timeout_lock = threading.RLock()
118
+ _active_timeouts = {}
119
+ _original_socket_timeout = None
120
+ _original_send = None
121
+
122
+
116
123
  @contextlib.contextmanager
117
124
  def socket_timeout(seconds: float):
118
- """Bound every blocking socket op for the wrapped chain's duration: akshare/efinance
119
- leave requests timeout-less, so on a blackholed network a leg hangs until the kernel
120
- TCP timeout (~2min) and the chain would overrun the caller's subprocess budget before
121
- ever reaching the plain-HTTPS legs. try/finally always restores the previous default
122
- (no global-state leak); explicit per-request timeouts (tencent/sina legs) still win."""
123
- old_timeout = socket.getdefaulttimeout()
124
- socket.setdefaulttimeout(seconds)
125
+ """Default socket/requests timeouts while guards are active (not a total deadline).
126
+
127
+ Like the socket default, this is process-wide: overlapping guards use the shortest
128
+ budget. Explicit requests timeouts still win. Restore only after the last guard exits.
129
+ """
130
+ try:
131
+ import requests
132
+ except ImportError:
133
+ requests = None
134
+
135
+ global _original_socket_timeout, _original_send
136
+ token = object()
137
+ with _timeout_lock:
138
+ if not _active_timeouts:
139
+ _original_socket_timeout = socket.getdefaulttimeout()
140
+ _original_send = requests.sessions.Session.send if requests is not None else None
141
+ if requests is not None:
142
+ original_send = _original_send
143
+
144
+ def bounded_send(session, request, **kwargs):
145
+ with _timeout_lock:
146
+ if kwargs.get("timeout") is None and _active_timeouts:
147
+ kwargs["timeout"] = min(_active_timeouts.values())
148
+ return original_send(session, request, **kwargs)
149
+
150
+ requests.sessions.Session.send = bounded_send
151
+ _active_timeouts[token] = seconds
152
+ socket.setdefaulttimeout(min(_active_timeouts.values()))
125
153
  try:
126
154
  yield
127
155
  finally:
128
- socket.setdefaulttimeout(old_timeout)
156
+ with _timeout_lock:
157
+ del _active_timeouts[token]
158
+ if _active_timeouts:
159
+ socket.setdefaulttimeout(min(_active_timeouts.values()))
160
+ else:
161
+ if requests is not None and _original_send is not None:
162
+ requests.sessions.Session.send = _original_send
163
+ socket.setdefaulttimeout(_original_socket_timeout)
129
164
 
130
165
 
131
166
  _SECRET_PARAM_RE = re.compile(r"(?i)((?:api[_-]?key|token|secret|access[_-]?token)=)[^&\s]+")
@@ -323,12 +323,12 @@ def detect_limit_hit(symbol: str, quote: dict) -> list:
323
323
  return anomalies
324
324
 
325
325
 
326
- def detect_capital_flow_anomaly(symbol: str) -> list:
326
+ def detect_capital_flow_anomaly(symbol: str, *, run=None) -> list:
327
327
  market = detect_market(symbol)
328
328
  if market != "A":
329
329
  return []
330
330
 
331
- flow_data = _run_tool("stock_data.py", ["capital_flow", symbol, "--mode", "detail"])
331
+ flow_data = (run or _run_tool)("stock_data.py", ["capital_flow", symbol, "--mode", "detail"])
332
332
  if not flow_data or not isinstance(flow_data, list) or len(flow_data) < 3:
333
333
  return []
334
334
 
@@ -468,8 +468,12 @@ def detect_gap(df: pd.DataFrame) -> list:
468
468
  # --------------- Orchestration ---------------
469
469
 
470
470
 
471
- def detect_anomalies(symbol: str) -> dict:
472
- records = fetch_kline(symbol, "daily", 60)
471
+ _UNSET = object()
472
+
473
+
474
+ def detect_anomalies(symbol: str, *, records=_UNSET, quote=_UNSET, run=None) -> dict:
475
+ if records is _UNSET:
476
+ records = fetch_kline(symbol, "daily", 60)
473
477
  if isinstance(records, dict) and "error" in records:
474
478
  return {"symbol": symbol, "error": records.get("error", "Failed to fetch kline")}
475
479
  if not records:
@@ -484,7 +488,8 @@ def detect_anomalies(symbol: str) -> dict:
484
488
  low = df["low"]
485
489
  volume = df["volume"]
486
490
 
487
- quote = _run_tool("stock_data.py", ["quote", symbol]) or {}
491
+ if quote is _UNSET:
492
+ quote = _run_tool("stock_data.py", ["quote", symbol]) or {}
488
493
 
489
494
  anomalies = []
490
495
  anomalies.extend(detect_macd_cross(close))
@@ -501,7 +506,7 @@ def detect_anomalies(symbol: str) -> dict:
501
506
  anomalies.extend(detect_limit_hit(symbol, quote))
502
507
  anomalies.extend(detect_large_move(quote))
503
508
 
504
- anomalies.extend(detect_capital_flow_anomaly(symbol))
509
+ anomalies.extend(detect_capital_flow_anomaly(symbol, **({"run": run} if run else {})))
505
510
 
506
511
  severity_order = {"high": 0, "medium": 1, "low": 2}
507
512
  anomalies.sort(key=lambda a: severity_order.get(a["severity"], 3))