mirror of
https://github.com/shy3130/tick-stock-panel.git
synced 2026-11-02 10:26:13 +00:00
回测成交口径: - close_t 按收盘价成交的建仓日: 当日 high 发生在建仓之前, 不得进入移动止损 峰值 (峰值虚高会把风控线上移、退出提前) — 矩阵独立/矩阵组合/legacy 三条 路径同口径; 新增回归测试锁定 open_t+1 对照组不被误伤 - 矩阵路径补收盘封死跌停拦截 (含一字), 经 pending_exit 递延到下一可卖日, 与独立/legacy 路径同口径 (此前尾盘封板股按跌停价"卖出"低估亏损) - #388 当日指标纪律同口径: 盘中成交不可知当日收盘, 代数剔除当日 enriched - 分钟回放: 入场价用前复权口径 (与日线出场同尺度); 除权日涨停参考价按 ex_factor 还原 (直接用 raw_prev 会把涨停价算高, 除权日封板拒买漏检) - 指标管线: 涨停参考价除权口径修正 + 夏普用样本标准差 (ddof=1, 与 engine 一致) - 回测任务: _acquire_or_evict_job 收口同 key 复用/强制重建 (参数不同先取消 旧任务, 避免旧任务占着重任务槽跑完) 服务与并发: - task_registry 读-改-写加锁: 两个前端 fire-and-forget 并发上报时后写者 覆盖先写者 (丢终态翻转或整条记录); 文件写入本身原子, 锁只护 RMW 段 - quote_service 生命周期锁串行化 start/stop/enable 的 check-then-act (双标签页 并发开关会起两条轮询线程 → 双倍拉取配额 + 重复 SSE 广播) - 系统通知投递移入专用单线程池: notify_adapter 底层 subprocess 逐条最长 5s, 在 _poll_loop 同步执行会让告警风暴阻塞一轮监控评估, 拖慢行情拉取与推送 - sector_monitor / minute_refresh / wecom_bot: 同类单实例与停止时序加固 - ai_provider: 401 识别加词边界 (避免模型正文含 401 数字串误判鉴权失败并 附出不相关指引); 自定义可执行路径校验可执行位 - api/data: 清空数据期间暂停全量分钟增量线程 (否则"清完又被写回部分今日 数据"); 状态接口偏好/能力探测异常降级而不是 500 - api/kline: 失效内存 enriched 快照 (非空缓存不校验 generation, 只刷 DuckDB 视图会让重建结果对自选/筛选/监控不可见直到进程重启) - api/position_policies: 非法 ID 纵深防御按不存在处理 前端: - assistant store: 生成终态 (中断提示/流式收敛) 钉在发起会话, 切换或删除会话 不再把"已中断"写进无关新会话 - backtestTask: 键上挂着旧任务且新参数不同 (不同 job_key) 时先取消旧任务, 避免其占着重任务槽跑到自然结束; 同参重跑跳过取消 (后端按同 key 复用 / force 重建已完成任务) - 查询键集中与正确性: QK.instrumentNames (排序去重, 同一集合不同来源顺序 复用缓存)、QK.kline 滚动窗口空串边界 (useQuoteStream 焦点股增量合并可 修补)、regimeHistory 用实际请求三元组 + 裸前缀失效全部变体 - Data 页 / Regime / SectorRotationCard / RuleEditor / monitor / lots / stock-analysis 接入集中键, useQuoteStream 对齐 验证: 后端全量 3546 passed (含 close_t 峰值/分钟回测/跌停递延/并发上报等 新增用例); 前端 49 文件 348 用例 + pnpm build 通过; ruff 改动文件零新增 (141 vs 基线 142)。 Signed-off-by: shy3130 <shy3130@qq.com>
499 lines
18 KiB
Python
499 lines
18 KiB
Python
from __future__ import annotations
|
|
|
|
from datetime import date
|
|
|
|
import numpy as np
|
|
import polars as pl
|
|
import pytest
|
|
|
|
from app.api import kline
|
|
from app.backtest.matrix import load_market_data_matrix_from_parquet
|
|
from app.indicators import pipeline
|
|
from app.price_limits import (
|
|
numpy_limit_price,
|
|
numpy_price_limit_matrix,
|
|
polars_is_risk_warning_name,
|
|
polars_limit_price,
|
|
polars_price_limit_pct,
|
|
price_limit_pct,
|
|
)
|
|
from app.strategy import custom_signals
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def _limit_signal_definitions(monkeypatch):
|
|
"""注入涨跌停信号定义 (与 data/user_data/custom_signals 种子同语义),
|
|
使 signal_limit_* 列断言不依赖运行目录的用户数据。"""
|
|
def _cond(left, op, right):
|
|
return {"left": left, "op": op, "right": right, "leftDays": 0, "rightDays": 0}
|
|
|
|
sigs = [
|
|
{"id": "limit_up", "column": "signal_limit_up",
|
|
"conditions": [_cond("raw_close", ">", "0"),
|
|
_cond("raw_close", ">=", "field:limit_up_price")]},
|
|
{"id": "limit_down", "column": "signal_limit_down",
|
|
"conditions": [_cond("raw_close", ">", "0"),
|
|
_cond("raw_close", "<=", "field:limit_down_price")]},
|
|
{"id": "limit_down_recovery", "column": "signal_limit_down_recovery",
|
|
"conditions": [_cond("raw_low", ">", "0"),
|
|
_cond("raw_close", ">", "field:limit_down_price"),
|
|
_cond("raw_low", "<=", "field:limit_down_price"),
|
|
_cond("close", ">", "field:open")]},
|
|
]
|
|
monkeypatch.setattr(
|
|
pipeline, "_custom_signal_exprs", custom_signals.build_expressions(
|
|
[{**s, "name": s["id"], "kind": "both", "enabled": True} for s in sigs]
|
|
)
|
|
)
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("symbol", "trade_date", "is_st", "expected"),
|
|
[
|
|
("600001.SH", date(2026, 7, 3), True, 0.05),
|
|
("600001.SH", date(2026, 7, 6), True, 0.10),
|
|
("000001.SZ", date(2026, 7, 3), False, 0.10),
|
|
("300001.SZ", date(2026, 7, 3), True, 0.20),
|
|
("688001.SH", date(2026, 7, 3), True, 0.20),
|
|
("689001.SH", date(2026, 7, 3), True, 0.20),
|
|
("830001.BJ", date(2026, 7, 3), True, 0.30),
|
|
],
|
|
)
|
|
def test_scalar_price_limit_rules(symbol, trade_date, is_st, expected):
|
|
assert price_limit_pct(
|
|
symbol,
|
|
trade_date,
|
|
is_risk_warning=is_st,
|
|
) == pytest.approx(expected)
|
|
|
|
|
|
def test_polars_and_numpy_price_limit_rules_match():
|
|
dates = [date(2026, 7, 3), date(2026, 7, 6)]
|
|
symbols = ["600001.SH", "300001.SZ", "689001.SH", "830001.BJ"]
|
|
names = ["*st主板", "*ST创业", "科创ST", "北交ST"]
|
|
panel = pl.DataFrame({
|
|
"date": [value for value in dates for _ in symbols],
|
|
"symbol": symbols * len(dates),
|
|
"name": names * len(dates),
|
|
}).with_columns(
|
|
polars_is_risk_warning_name(pl.col("name")).alias("is_st")
|
|
).with_columns(
|
|
polars_price_limit_pct(
|
|
pl.col("symbol"), pl.col("date"), pl.col("is_st"),
|
|
).alias("limit_pct")
|
|
)
|
|
polars_values = panel["limit_pct"].to_numpy().reshape(len(dates), len(symbols))
|
|
numpy_values = numpy_price_limit_matrix(dates, symbols, names)
|
|
np.testing.assert_allclose(polars_values, numpy_values)
|
|
|
|
|
|
def test_polars_and_numpy_limit_prices_use_identical_half_up_rounding():
|
|
previous = np.array([18.90, 10.00], dtype=np.float64)
|
|
limits = np.array([0.05, 0.10], dtype=np.float64)
|
|
frame = pl.DataFrame({"previous": previous, "limit": limits})
|
|
|
|
for up in (True, False):
|
|
polars_values = frame.select(
|
|
polars_limit_price(
|
|
pl.col("previous"), pl.col("limit"), up=up,
|
|
).alias("price")
|
|
)["price"].to_numpy()
|
|
numpy_values = numpy_limit_price(previous, limits, up=up)
|
|
np.testing.assert_allclose(polars_values, numpy_values)
|
|
assert numpy_limit_price(previous, limits, up=False)[0] == pytest.approx(17.96)
|
|
|
|
|
|
def test_matrix_uses_date_specific_st_limits_across_change(tmp_path):
|
|
root = tmp_path / "market"
|
|
rows = [
|
|
(date(2026, 7, 2), 10.0),
|
|
(date(2026, 7, 3), 10.5),
|
|
(date(2026, 7, 6), 11.03),
|
|
]
|
|
for trade_date, close in rows:
|
|
partition = root / f"date={trade_date.isoformat()}"
|
|
partition.mkdir(parents=True)
|
|
pl.DataFrame({
|
|
"symbol": ["600001.SH"],
|
|
"date": [trade_date],
|
|
"open": [close],
|
|
"high": [close],
|
|
"low": [close],
|
|
"close": [close],
|
|
"raw_close": [close],
|
|
"volume": [1000.0],
|
|
}).write_parquet(partition / "part.parquet")
|
|
|
|
market = load_market_data_matrix_from_parquet(
|
|
root,
|
|
rows[0][0],
|
|
rows[-1][0],
|
|
field_columns={"raw_close", "price_limit_pct"},
|
|
instruments=pl.DataFrame({
|
|
"symbol": ["600001.SH"],
|
|
"name": ["*ST主板"],
|
|
}),
|
|
cache_root=tmp_path / "cache",
|
|
)
|
|
np.testing.assert_allclose(
|
|
market.field("price_limit_pct")[:, 0],
|
|
np.array([0.05, 0.05, 0.10], dtype=np.float32),
|
|
)
|
|
assert market.limit_up_locked[:, 0].tolist() == [0, 1, 0]
|
|
|
|
|
|
class _InstrumentRepo:
|
|
def get_instruments_asset(self, asset_type: str) -> pl.DataFrame:
|
|
assert asset_type == "stock"
|
|
return pl.DataFrame({
|
|
"symbol": ["600001.SH"],
|
|
"limit_up": [10.88],
|
|
"limit_down": [8.90],
|
|
})
|
|
|
|
|
|
def test_minute_price_limit_prefers_authoritative_prices_only_today(monkeypatch):
|
|
today = date(2026, 7, 18)
|
|
monkeypatch.setattr(kline, "cn_today", lambda: today)
|
|
current = kline._get_price_limit_info(
|
|
_InstrumentRepo(), "600001.SH", today, "stock", "*ST主板",
|
|
)
|
|
historical = kline._get_price_limit_info(
|
|
_InstrumentRepo(), "600001.SH", date(2026, 7, 3), "stock", "*ST主板",
|
|
)
|
|
|
|
assert current == {
|
|
"rate": 0.10,
|
|
"limit_up": 10.88,
|
|
"limit_down": 8.90,
|
|
"no_limit": False,
|
|
"source": "instrument",
|
|
}
|
|
assert historical == {
|
|
"rate": 0.05,
|
|
"limit_up": None,
|
|
"limit_down": None,
|
|
"no_limit": False,
|
|
"source": "rule",
|
|
}
|
|
|
|
|
|
class _NewStockRepo:
|
|
"""listing_date 在无涨跌幅窗口内的注册制新股维表 (C沈鼓场景)。"""
|
|
|
|
def __init__(self, listing: date):
|
|
self.listing = listing
|
|
|
|
def get_instruments_asset(self, asset_type: str) -> pl.DataFrame:
|
|
assert asset_type == "stock"
|
|
return pl.DataFrame({
|
|
"symbol": ["601091.SH"],
|
|
"name": ["C沈鼓"],
|
|
"limit_up": [100000.0], # 哨兵值
|
|
"limit_down": [None],
|
|
"listing_date": [self.listing],
|
|
})
|
|
|
|
|
|
def test_minute_price_limit_no_limit_window_overrides_rate_and_sentinel():
|
|
"""listing_date 命中窗口: 历史日 (哨兵/as_of 均失效) 也返回 no_limit=True。"""
|
|
listing = date(2026, 9, 17)
|
|
repo = _NewStockRepo(listing)
|
|
|
|
# 行情日 = 上市次日 (窗口内), 维表 as_of 与行情日无关 (无 as_of 列)
|
|
info = kline._get_price_limit_info(repo, "601091.SH", date(2026, 9, 18), "stock", "C沈鼓")
|
|
|
|
assert info is not None
|
|
assert info["no_limit"] is True
|
|
assert info["limit_up"] is None
|
|
assert info["limit_down"] is None
|
|
|
|
# 窗口外 (第 6 个交易日之后) 恢复 rate 口径
|
|
after = kline._get_price_limit_info(repo, "601091.SH", date(2026, 10, 15), "stock", "沈鼓能源")
|
|
assert after is not None
|
|
assert after["no_limit"] is False
|
|
assert after["rate"] == 0.10
|
|
|
|
|
|
def _daily_limit_rows(current_close: float) -> pl.DataFrame:
|
|
return pl.DataFrame({
|
|
"symbol": ["600001.SH", "600001.SH"],
|
|
"date": [date(2026, 7, 17), date(2026, 7, 20)],
|
|
"open": [10.0, current_close],
|
|
"high": [10.0, current_close],
|
|
"low": [10.0, current_close],
|
|
"close": [10.0, current_close],
|
|
"raw_close": [10.0, current_close],
|
|
"raw_high": [10.0, current_close],
|
|
})
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("instrument_as_of", "expected"),
|
|
[
|
|
(date(2026, 7, 17), False),
|
|
(date(2026, 7, 20), True),
|
|
(None, True),
|
|
],
|
|
)
|
|
def test_daily_limit_prices_require_matching_instrument_date(instrument_as_of, expected):
|
|
instrument_data = {
|
|
"symbol": ["600001.SH"],
|
|
"name": ["普通股"],
|
|
"limit_up": [10.90],
|
|
"limit_down": [9.10],
|
|
}
|
|
if instrument_as_of is not None:
|
|
instrument_data["as_of"] = [instrument_as_of]
|
|
|
|
result = pipeline.compute_limit_signals(
|
|
_daily_limit_rows(9.10),
|
|
pl.DataFrame(instrument_data),
|
|
needed={"signal_limit_down"},
|
|
)
|
|
|
|
assert result["signal_limit_down"][-1] is expected
|
|
assert "_instrument_as_of" not in result.columns
|
|
|
|
|
|
def test_daily_limit_prices_ignore_zero_placeholder_and_match_realtime():
|
|
"""维表涨跌停价为 0 (数据源未提供该字段的占位值) 时必须回退理论价。
|
|
|
|
直接采用 0 会让「raw_close >= 0 - 0.005」恒成立, 当日所有标的被判涨停,
|
|
连板数一路累加; 跌停侧反过来永远判不出跌停。实时路径
|
|
(_compute_limit_signals_today) 已有 >0 守卫, 冷路径必须同口径。
|
|
"""
|
|
instruments = pl.DataFrame({
|
|
"symbol": ["600001.SH"],
|
|
"name": ["普通股"],
|
|
"limit_up": [0.0],
|
|
"limit_down": [0.0],
|
|
"as_of": [date(2026, 7, 20)],
|
|
})
|
|
|
|
# 只涨 0.5%: 不是涨停
|
|
mild = pipeline.compute_limit_signals(
|
|
_daily_limit_rows(10.05),
|
|
instruments,
|
|
needed={"signal_limit_up", "consecutive_limit_ups"},
|
|
)
|
|
assert mild["signal_limit_up"][-1] is False
|
|
assert mild["consecutive_limit_ups"][-1] == 0
|
|
|
|
# 真涨停 11.00 = 10.00 x 1.1: 理论价兜底后仍须判出
|
|
sealed = pipeline.compute_limit_signals(
|
|
_daily_limit_rows(11.00),
|
|
instruments,
|
|
needed={"signal_limit_up", "consecutive_limit_ups"},
|
|
)
|
|
assert sealed["signal_limit_up"][-1] is True
|
|
assert sealed["consecutive_limit_ups"][-1] == 1
|
|
|
|
# 真跌停 9.00 = 10.00 x 0.9: 占位 0 不得让跌停漏判
|
|
floored = pipeline.compute_limit_signals(
|
|
_daily_limit_rows(9.00),
|
|
instruments,
|
|
needed={"signal_limit_down"},
|
|
)
|
|
assert floored["signal_limit_down"][-1] is True
|
|
|
|
# 与实时路径同一份维表同一结论
|
|
realtime = pipeline._compute_limit_signals_today(
|
|
pl.DataFrame({
|
|
"symbol": ["600001.SH"],
|
|
"date": [date(2026, 7, 20)],
|
|
"open": [10.05],
|
|
"high": [10.05],
|
|
"low": [10.05],
|
|
"close": [10.05],
|
|
"raw_close": [10.05],
|
|
"raw_high": [10.05],
|
|
"raw_low": [10.05],
|
|
"_prev_close_raw": [10.0],
|
|
"volume": [1000.0],
|
|
}),
|
|
instruments,
|
|
)
|
|
# 实时路径不注入信号列 (定义注入在 compute_enriched_today 末尾), 按引擎判定价对拍
|
|
assert realtime["limit_up_price"][0] == pytest.approx(10.995)
|
|
assert realtime["consecutive_limit_ups"][0] == 0
|
|
assert mild["limit_up_price"][-1] == realtime["limit_up_price"][0]
|
|
assert mild["consecutive_limit_ups"][-1] == realtime["consecutive_limit_ups"][0]
|
|
|
|
|
|
def test_realtime_limit_prices_ignore_stale_instrument_date():
|
|
today = date(2026, 7, 20)
|
|
rows = pl.DataFrame({
|
|
"symbol": ["600001.SH"],
|
|
"date": [today],
|
|
"open": [9.10],
|
|
"high": [9.10],
|
|
"low": [9.10],
|
|
"close": [9.10],
|
|
"raw_close": [9.10],
|
|
"raw_high": [9.10],
|
|
"raw_low": [9.10],
|
|
"_prev_close_raw": [10.0],
|
|
"volume": [1000.0],
|
|
})
|
|
instruments = pl.DataFrame({
|
|
"symbol": ["600001.SH"],
|
|
"name": ["普通股"],
|
|
"limit_up": [10.90],
|
|
"limit_down": [9.10],
|
|
"as_of": [date(2026, 7, 17)],
|
|
})
|
|
|
|
result = pipeline._compute_limit_signals_today(rows, instruments)
|
|
|
|
# 过期维表 → 回退理论跌停价 9.005 (而非权威 9.105), 9.10 未触及 → 不判跌停
|
|
assert result["limit_down_price"][0] == pytest.approx(9.005)
|
|
assert result["consecutive_limit_downs"][0] == 0
|
|
assert "_instrument_as_of" not in result.columns
|
|
|
|
|
|
def test_limit_down_recovery_uses_raw_low_under_later_ex_div():
|
|
"""除权事件之后重算历史时, 跌停翘板"曾触及跌停"必须用原始价 low 判断。
|
|
|
|
day2 (历史日): 原始 low 9.30 未触及跌停价 9.00, 不应触发翘板;
|
|
但 day3 除权 (ex_factor=2) 使 day2 前复权 low 变为 4.65,
|
|
若误用复权 low 对比原始口径跌停价会误报翘板。
|
|
day3 (除权日, 最新日不复权): 涨跌停基准切换为前复权昨收 4.825 → 跌停价 4.34,
|
|
原始 low 4.34 触及且收阳未封死 → 真翘板。
|
|
"""
|
|
raw = pl.DataFrame({
|
|
"symbol": ["600001.SH"] * 3,
|
|
"date": [date(2024, 1, 2), date(2024, 1, 3), date(2024, 1, 4)],
|
|
"open": [10.00, 9.60, 4.30],
|
|
"high": [10.10, 9.70, 4.45],
|
|
"low": [9.90, 9.30, 4.34],
|
|
"close": [10.00, 9.65, 4.42],
|
|
"volume": [10000.0, 10000.0, 10000.0],
|
|
"amount": [1.0e7, 1.0e7, 1.0e7],
|
|
})
|
|
factors = pl.DataFrame({
|
|
"symbol": ["600001.SH"],
|
|
"trade_date": [date(2024, 1, 4)],
|
|
"ex_factor": [2.0],
|
|
})
|
|
instruments = pl.DataFrame({
|
|
"symbol": ["600001.SH"],
|
|
"name": ["普通股"],
|
|
"float_shares": [1.0e8],
|
|
})
|
|
|
|
df = pipeline.compute_enriched(raw, factors=factors, instruments=instruments)
|
|
|
|
day2 = df.filter(pl.col("date") == date(2024, 1, 3))
|
|
assert day2["signal_limit_down_recovery"][0] is False
|
|
day3 = df.filter(pl.col("date") == date(2024, 1, 4))
|
|
assert day3["signal_limit_down_recovery"][0] is True
|
|
|
|
|
|
def test_matrix_limit_lock_uses_exchange_reference_on_ex_div_with_later_event(tmp_path):
|
|
"""除权日涨跌停判定价必须用交易所除权参考价, 不能直接用前复权昨收。
|
|
|
|
事件: d3 除权 (ex_factor=1.25), d6 再除权 (ex_factor=1.25)。
|
|
d3 的交易所参考价 = raw昨收/ex_factor = 10/1.25 = 8.00, 涨停价 8.80;
|
|
前复权昨收 = 10/1.5625 = 6.40 (被 d6 事件额外缩放)。旧口径拿 6.40 当参考
|
|
→ 限价 7.04, raw 8.79 被误标"涨停锁死"。
|
|
"""
|
|
root = tmp_path / "market"
|
|
spec = [
|
|
# (date, raw_close, F(d) = 该日之后所有事件因子乘积)
|
|
(date(2024, 1, 2), 10.00, 1.5625),
|
|
(date(2024, 1, 3), 10.00, 1.5625),
|
|
(date(2024, 1, 4), 8.79, 1.25), # ex1 除权日: 真涨停价 8.80, 未触及
|
|
(date(2024, 1, 5), 8.70, 1.25),
|
|
(date(2024, 1, 8), 8.70, 1.25),
|
|
(date(2024, 1, 9), 7.00, 1.0), # ex2 除权日 (窗口末日)
|
|
]
|
|
for trade_date, raw, f in spec:
|
|
partition = root / f"date={trade_date.isoformat()}"
|
|
partition.mkdir(parents=True)
|
|
pl.DataFrame({
|
|
"symbol": ["600001.SH"],
|
|
"date": [trade_date],
|
|
"open": [raw], "high": [raw], "low": [raw],
|
|
"close": [raw / f], "raw_close": [raw], "volume": [1000.0],
|
|
}).write_parquet(partition / "part.parquet")
|
|
|
|
market = load_market_data_matrix_from_parquet(
|
|
root, spec[0][0], spec[-1][0],
|
|
field_columns={"raw_close"},
|
|
instruments=pl.DataFrame({"symbol": ["600001.SH"], "name": ["普通股"]}),
|
|
cache_root=tmp_path / "cache",
|
|
)
|
|
# d3 除权日: 参考价 8.00 → 涨停 8.80 / 跌停 7.20, raw 8.79 均未触及
|
|
assert market.limit_up_locked[2, 0] == 0
|
|
assert market.limit_down_locked[2, 0] == 0
|
|
# d6 第二次除权日 (窗口末日, F=1): 参考价 8.70/1.25 = 6.96,
|
|
# 涨停 7.66 / 跌停 6.26, raw 7.00 未封板
|
|
assert market.limit_up_locked[5, 0] == 0
|
|
assert market.limit_down_locked[5, 0] == 0
|
|
|
|
|
|
def test_limit_price_on_ex_div_with_later_event_uses_exchange_reference():
|
|
"""enriched 路径同口径: 除权日 limit_up/down_price 用除权参考价, 不是前复权昨收。
|
|
|
|
事件: d3 除权 (f=1.25), d4 再除权 (f=1.25)。
|
|
d3 参考价 = 10/1.25 = 8.00 (前复权昨收 6.40 被事件额外缩放, 旧口径算出
|
|
涨停价 7.04 → raw 8.79 误判涨停); d4 参考价 = 8.79/1.25 = 7.032,
|
|
raw 7.74 恰为涨停价 → 正常检出 (防过度修正)。
|
|
"""
|
|
raw = pl.DataFrame({
|
|
"symbol": ["600001.SH"] * 4,
|
|
"date": [date(2024, 1, 2), date(2024, 1, 3), date(2024, 1, 4), date(2024, 1, 5)],
|
|
"open": [10.00, 10.00, 8.79, 7.74],
|
|
"high": [10.00, 10.00, 8.79, 7.74],
|
|
"low": [10.00, 10.00, 8.79, 7.74],
|
|
"close": [10.00, 10.00, 8.79, 7.74],
|
|
"volume": [10000.0] * 4,
|
|
"amount": [1.0e7] * 4,
|
|
})
|
|
factors = pl.DataFrame({
|
|
"symbol": ["600001.SH"] * 2,
|
|
"trade_date": [date(2024, 1, 4), date(2024, 1, 5)],
|
|
"ex_factor": [1.25, 1.25],
|
|
})
|
|
instruments = pl.DataFrame({
|
|
"symbol": ["600001.SH"], "name": ["普通股"], "float_shares": [1.0e8],
|
|
})
|
|
|
|
df = pipeline.compute_enriched(raw, factors=factors, instruments=instruments)
|
|
|
|
d3 = df.filter(pl.col("date") == date(2024, 1, 4))
|
|
# 落库列为含容差的交易所生效价: 涨停 8.80-0.005 / 跌停 7.20+0.005
|
|
assert d3["limit_up_price"][0] == pytest.approx(8.795)
|
|
assert d3["limit_down_price"][0] == pytest.approx(7.205)
|
|
assert d3["signal_limit_up"][0] is False
|
|
assert d3["consecutive_limit_ups"][0] == 0
|
|
|
|
d4 = df.filter(pl.col("date") == date(2024, 1, 5))
|
|
assert d4["limit_up_price"][0] == pytest.approx(7.725)
|
|
assert d4["signal_limit_up"][0] is True
|
|
assert d4["consecutive_limit_ups"][0] == 1
|
|
|
|
|
|
def test_chinext_302_codes_use_growth_board_rules():
|
|
"""深交所创业板已启用 302 号段 (如 2025-02-17 起的 302132.SZ 中航成飞),
|
|
与 300/301 同为 ±20%, 注册制新股同样有 5 个交易日无涨跌幅窗口。"""
|
|
assert price_limit_pct("302132.SZ", date(2026, 10, 16)) == pytest.approx(0.20)
|
|
|
|
df = pl.DataFrame({
|
|
"symbol": ["302132.SZ", "000001.SZ"],
|
|
"trade_date": [date(2026, 10, 16)] * 2,
|
|
"is_risk_warning": [False, False],
|
|
})
|
|
pct = df.select(
|
|
polars_price_limit_pct(pl.col("symbol"), pl.col("trade_date"), pl.col("is_risk_warning"))
|
|
).to_series()
|
|
assert pct.to_list() == pytest.approx([0.20, 0.10])
|
|
|
|
|
|
def test_chinext_302_no_limit_window_follows_gem_registration_date():
|
|
from app.price_limits import no_limit_window_days
|
|
|
|
# 2023-02-17 主板注册制之前、2020-08-24 创业板注册制之后上市
|
|
assert no_limit_window_days("302001.SZ", date(2021, 6, 1)) == 5
|