检验宽基恢复后五次卖压的微盘承接与预警时点
This commit is contained in:
parent
2d98a222d1
commit
28104c5101
|
|
@ -3350,3 +3350,7 @@ a44c994于10:53:29仅发布155的web,镜像pms:proposal-copy-a44c994。开发
|
|||
## 2026-11-23 中证2000流动性研究换机接续
|
||||
|
||||
汇总两轮实验及11月22日反向观察,逐日核对宽基恢复前后5个交易日的微盘成交、资金方向和沪深价格尾部。5次宽基成交恢复仅1次随后出现微盘放量净买入。微盘低位日价格摆动较大,持续恢复仍需检验后续卖压下的承接能力。[研究结论、五次恢复与复现入口](docs/中证2000流动性风险研究接续_2026-11-23.md)
|
||||
|
||||
## 2026-11-23 宽基恢复后的首次微盘卖压
|
||||
|
||||
开发机 `intel-mbp` 核对内网远端系统分支 `a53c4f0` 已包含换机提交 `9b9ac6e`。从本机系统分支 `f5070d7` 建立隔离工作树,在协议 `2d98a22` 上按相同沪深日历回放15次宽基恢复的资金覆盖和主样本5次首卖压。十对中仅6月与7月符合四项预设条件。两例均五日未收回,6月在等待第二个收盘时已先后发生宽基复压与沪深等权入尾,7月随后五日均无。另两次净卖出当日收涨后,分别发生了成交风险和价格风险。逐次路径、配对差值及可重复的离线复核见[卖压承接实验](research/liquidity_absorption_20261123/README.md)。
|
||||
|
|
|
|||
|
|
@ -40,4 +40,12 @@
|
|||
|
||||
首轮协议与结果提交为 `c72b15f`、`b5b2679`,放量净买入协议与结果为 `1b86f52`、`d81c5e5`。11月22日对五次宽基恢复的反向观察和对价格反转的判断,均是同批历史的事后复核。两轮协议、逐日表、误报漏报、图册和审计摘要随仓库交接。首轮逐股价格终点截至2026年2月27日,存在退市覆盖缺口。补充研究用同版沪深数据独立重算至2026年10月23日。若从逐股原始行情重建首轮结果,还需同级仓库 `quant_factor_service` 的历史缓存,本次开发机对应提交为 `0425011bc8bb`。独立逐股扩散审计另用同级仓库 `factor_sys` 的2024年行情,对应提交为 `39e81b0117d8`。主要结论可直接对照仓库里的聚合表。[首轮数据与复现说明](../research/liquidity_tail_20261120/README.md#数据边界与重现) · [补充研究的输入与复核](../research/liquidity_relief_20261120/README.md#数据时点与复核)
|
||||
|
||||
待检验的是卖压再次出现时的承接能力。在宽基恢复天数、成交强度及初始回撤相近的时点,比较微盘承受相近主动净卖出时跌多少、几天收回,再从这些信息实际可见的收盘往后数5日,查宽基是否重新进入成交压力、沪深等权是否再次入尾。这一比较尚未完成。
|
||||
上次交接留下了卖压承接假设。在宽基恢复天数、成交强度及初始回撤相近的时点,比较微盘承受相近主动净卖出时跌多少、几天收回,再从这些信息实际可见的收盘往后数5日,查宽基是否重新进入成交压力、沪深等权是否再次入尾。
|
||||
|
||||
## 宽基恢复后首次卖压的检验
|
||||
|
||||
2026年11月23日上午在开发机 `intel-mbp` 核验。原研究已随 `a53c4f0` 并入 `codex/pms-order-pnl-fix`。重新核对九个低位段、173个观察日和五次宽基恢复后,按[本轮协议](../research/liquidity_absorption_20261123/实验协议.md)检验每次恢复后的首次主动净卖出。
|
||||
|
||||
五次恢复的十种配对中,仅2024年6月20日和7月15日两次卖压满足全部可比条件。净卖出分别占同一沪深成分篮子成交额的12.28%和11.51%,中证2000分别下跌2.34%和1.72%,随后五日均未收回。6月21日宽基重新进入成交压力,6月24日沪深等权进入价格尾部,7月卖压后五日两者均无。若等到卖压后第二个交易日收盘再看承接,六月的两个结果都已经发生,主样本没有可用来检验随后五日风险差异的配对。
|
||||
|
||||
9月3日及9月25日,中证2000在净卖出当日分别上涨1.07%和1.25%,之后五个交易日仍分别出现宽基重新入压和沪深等权再入尾。现有证据支持把承接受压时的涨跌作为行情观察,尚不足以解除风险。下次验证需要增加其他低位恢复阶段,并保留成分资金的实际到达时间。[五次卖压、可比条件与数据覆盖](../research/liquidity_absorption_20261123/README.md)
|
||||
|
|
|
|||
|
|
@ -76,7 +76,7 @@
|
|||
| 账户累计盈亏、消息分类收起及刷新布局 | [11月9日修复接续](账户盈亏与消息布局修复_2026-11-09.md),含账户收益基线、费用口径、桌面与窄屏验证及仅页面发布 |
|
||||
| 信号流统一四级、移除观测类别 | [11月6日四级发布](信号流四级统一发布_2026-11-06.md),含全来源计数、筛选与页面定向发布 |
|
||||
| 宽基每日资金展示、日报入口移除与当天信号完整覆盖 | [11月6日发布接续](宽基每日资金与信号覆盖发布_2026-11-06.md),最终原型、独立日度接入、四路信号覆盖及定向发布 |
|
||||
| 中证2000流动性低位、冲击恢复与沪深尾部 | [研究结论与换机接续](中证2000流动性风险研究接续_2026-11-23.md),含宽基与微盘恢复先后、五次逐日对照和待验假设。[九段冲击图册](../research/liquidity_tail_20261120/逐段图册.html) · [放量净买入补充研究](../research/liquidity_relief_20261120/README.md) |
|
||||
| 中证2000流动性低位、冲击恢复与沪深尾部 | [研究结论与换机接续](中证2000流动性风险研究接续_2026-11-23.md),含宽基与微盘恢复先后及[恢复后首次卖压的五次承接对照](../research/liquidity_absorption_20261123/README.md)。[九段冲击图册](../research/liquidity_tail_20261120/逐段图册.html) · [放量净买入补充研究](../research/liquidity_relief_20261120/README.md) |
|
||||
| 当前微盘接入、参数和运行待办 | [阶段接续与实验意见](微盘轮动阶段接续_2026-10-28.md);需要部署证据再读[50股发布记录](微盘轮动50股参数发布_2026-10-28.md) |
|
||||
| 全市场热度、涨跌幅与持有期标定 | [热度策略研究接续](全市场热度四维标定接续_2026-10-28.md),含回填限制、参数结果和复现入口;[热度反复活跃矩阵接续](热度反复活跃矩阵研究接续_2026-10-29.md),含前20日次数、持有期、数据可用性与阶段指数对照 |
|
||||
| 综合分与聪明资金分阈值及市场阶段比较 | [评分策略研究接续](综合分与聪明资金分标定接续_2026-10-28.md),含810组结果、历史版本限制和复现入口;[反复活跃矩阵接续](反复活跃矩阵研究接续_2026-10-29.md),含20日次数、1至10日持有期与指数隔离 |
|
||||
|
|
|
|||
|
|
@ -0,0 +1,41 @@
|
|||
# 宽基成交恢复后,微盘能否扛住下一次卖压
|
||||
|
||||
**等两天看微盘能否收回跌幅,在这批行情里没有验证出可用的提前量。** 五次宽基恢复中,只有2024年6月和7月的首次卖压可以按预设条件配对。两次中证2000都跌了,五个交易日内都没收回。6月随后出现了成交和价格风险,7月两者都没出现。卖压当晚的跌幅能区分这一对行情,但等到第二个交易日收盘再确认,6月的两项风险都已发生。交易员可以用当日涨跌记录资金卖出时的价格反应,现有证据不足以据此解除风险或估计稳定的提前天数。[实验协议](实验协议.md) · [配对后的逐项结果](pair_outcomes.csv)
|
||||
|
||||
## 五次卖压分别走出了什么结果
|
||||
|
||||
每次从宽基恢复的下一交易日起找首次主动净卖出。卖压占比取中证2000最近已知沪深成分的主动净卖额除以同一篮子的成交额。“收回”指收盘价重新达到卖压前收盘价。表中最后两列从卖压**后第二个交易日收盘**作判断,往后再数五个交易日。日期均为2024年。
|
||||
|
||||
| 宽基恢复 | 首次卖压 | 卖压占比 | 中证2000当日涨跌 | 何时收回 | 判断日 | 宽基成交再入压力 | 沪深等权价格再入尾部 |
|
||||
|---|---|---:|---:|---|---|---|---|
|
||||
| 6月19日 | 6月20日 | 12.28% | −2.34% | 五日内未收回 | 6月24日 | 判断前已于6月21日入压 | 判断日已入尾 |
|
||||
| 7月12日 | 7月15日 | 11.51% | −1.72% | 五日内未收回 | 7月17日 | 后五日无 | 后五日无 |
|
||||
| 8月1日 | 8月2日 | 8.27% | −1.34% | 五日内未收回 | 8月6日 | 8月12日入压 | 后五日无 |
|
||||
| 9月2日 | 9月3日 | 2.16% | +1.07% | 当日守住 | 9月5日 | 9月9日入压 | 后五日无 |
|
||||
| 9月23日 | 9月25日 | 4.18% | +1.25% | 当日守住 | 9月27日 | 后五日无 | 10月9日入尾 |
|
||||
|
||||
两次在净卖出中收涨的行情,后来分别出现了宽基成交转弱和沪深个股价格尾部。这两次卖压都较轻,与6月、7月缺少同强度对照。8月12日则说明了观察时点为何重要。从8月2日卖压当晚向后数五天尚未见到这次复压,从8月6日收盘向后数五天就能看见。[卖压与收回明细](events.csv) · [三个判断时点的五日结果](observations.csv)
|
||||
|
||||
## 六月和七月能比到什么程度
|
||||
|
||||
两次都在宽基恢复后的首个交易日遇到净卖出。卖压前一收盘,三个宽基成交活跃度的分位中位数分别为41.67%和48.02%,沪深个股等权相对前五日高点的回撤分别为0.56%和0.25%。卖压占比相差0.78个百分点。7月中证2000当日少跌约0.62个百分点,但两例后两日、乃至后五日的收回情况都相同。初始市场环境仍有差别,一对行情分不开微盘跌幅和市场本身各自提供了多少信息。
|
||||
|
||||
| 交易员何时可以判断 | 六月接下来可以观察到的风险 | 七月接下来可以观察到的风险 | 还能比较的终点 |
|
||||
|---|---|---|---|
|
||||
| 卖压当晚,假定当晚拿到资金数据 | 下一交易日宽基重新入压,第2个交易日沪深等权入尾 | 后五日两者均无 | 成交、价格各1对,较少下跌的7月随后风险较少 |
|
||||
| 若资金到下一交易日收盘才取得 | 宽基已经入压,沪深等权在下一交易日入尾 | 后五日两者均无 | 价格1对 |
|
||||
| 卖压后第2个交易日收盘,加入收回速度 | 宽基已在压力中,沪深等权也已入尾 | 后五日两者均无 | 两个终点均为0对 |
|
||||
|
||||
五次恢复可组成十对。主口径落选的九对,卖压占比差都超过了2个百分点。四项容差同时减半时,仍只有6月与7月可比,且这两次恢复同属一个低位段。放宽到两倍时有三对,新增7月与8月、9月上旬与下旬,五次恢复总共只涉及2024年两个低位段。要继续验证承接的预警价值,需要新的低位恢复阶段,并保存资金实际到达时间。[十对的条件差值与落选原因](pairs.csv)
|
||||
|
||||
## 数据范围与复现
|
||||
|
||||
2024年1月2日至2026年10月23日共678个评价日。九个低位段及段后五日共覆盖173个不同交易日,期间五次宽基成交恢复均有完整的首卖压查找窗口。全期另外十次恢复中,两次有完整的五日资金、八次整窗缺资金。主样本的五个卖压日均用最近月末沪深成分近似当天名单。沪深等权采用上轮完整同版序列,有历史退市股票覆盖缺口。资金供应商常规在交易日19时更新,缺少历史实际到达时刻。本文的成交压力沿用上轮宽基成交阶段,价格尾部沿用同版沪深等权五日回撤的训练期95%分位。[15次恢复的覆盖](coverage.csv) · [资金来源与成分覆盖](../liquidity_relief_20261120/data_coverage.json) · [前轮定义](../liquidity_relief_20261120/实验协议.md)
|
||||
|
||||
实验协议提交为 `2d98a22`。开发机 `intel-mbp` 在禁止联网的 macOS 沙箱中复跑,五张结果表及审计回执与归档逐字节相同。独立复算核对了15个判断时点、30个风险窗口,并按历史日期截断输入回放20次。在仓库根目录用 Python 3 依次运行下列命令即可复现,也可以给三个程序传入同一个 `--output-dir`,将结果保存到其他目录。[复核回执](audit.json)
|
||||
|
||||
```sh
|
||||
python3 research/liquidity_absorption_20261123/events.py
|
||||
python3 research/liquidity_absorption_20261123/pairs.py
|
||||
python3 research/liquidity_absorption_20261123/audit.py
|
||||
```
|
||||
|
|
@ -0,0 +1,64 @@
|
|||
{
|
||||
"source_sha256": {
|
||||
"index_data.csv": "f32abc9d46c1f90db8208e279293fe24b8a92dcccdcdda1de1df1f24b5381312",
|
||||
"daily_panel.csv": "5ce5f2741d7c528c525cc881062c406cf350f89511a4ad97131a69d6555946d4"
|
||||
},
|
||||
"calendar_days": 678,
|
||||
"all_recoveries": 15,
|
||||
"main_recoveries": 5,
|
||||
"recoveries_with_no_covered_days": [
|
||||
"2024-12-11",
|
||||
"2025-02-07",
|
||||
"2025-04-11",
|
||||
"2025-05-13",
|
||||
"2025-06-06",
|
||||
"2025-10-31",
|
||||
"2025-12-15",
|
||||
"2026-04-15"
|
||||
],
|
||||
"first_sell_dates": {
|
||||
"2024-06-19": "2024-06-20",
|
||||
"2024-07-12": "2024-07-15",
|
||||
"2024-08-01": "2024-08-02",
|
||||
"2024-09-02": "2024-09-03",
|
||||
"2024-09-23": "2024-09-25"
|
||||
},
|
||||
"full_five_day_reclaim": {
|
||||
"2024-06-19": "not_yet",
|
||||
"2024-07-12": "not_yet",
|
||||
"2024-08-01": "not_yet",
|
||||
"2024-09-02": 0,
|
||||
"2024-09-23": 0
|
||||
},
|
||||
"landmarks_checked": 15,
|
||||
"endpoint_windows_checked": 30,
|
||||
"eligible_pairs_by_tolerance": {
|
||||
"half": [
|
||||
[
|
||||
"2024-06-19",
|
||||
"2024-07-12"
|
||||
]
|
||||
],
|
||||
"main": [
|
||||
[
|
||||
"2024-06-19",
|
||||
"2024-07-12"
|
||||
]
|
||||
],
|
||||
"double": [
|
||||
[
|
||||
"2024-06-19",
|
||||
"2024-07-12"
|
||||
],
|
||||
[
|
||||
"2024-07-12",
|
||||
"2024-08-01"
|
||||
],
|
||||
[
|
||||
"2024-09-02",
|
||||
"2024-09-23"
|
||||
]
|
||||
]
|
||||
},
|
||||
"prefix_checks": 20
|
||||
}
|
||||
|
|
@ -0,0 +1,306 @@
|
|||
"""从归档指数行情和沪深市场序列独立核对首卖压、可比事件和判断后的五日风险。"""
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import statistics
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from itertools import combinations
|
||||
from pathlib import Path
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
INPUT = HERE.parent / "liquidity_relief_20261120"
|
||||
LANDMARKS = {"fast": 0, "delayed": 1, "day2": 2}
|
||||
ENDPOINTS = {"turnover": "state_turnover", "tail": "tail_market155"}
|
||||
TOLERANCES = {"age": 1, "prior_activity_pct": 15, "prior_drawdown_pct": 2, "sell_share_pct": 2}
|
||||
SCALES = {"half": 0.5, "main": 1, "double": 2}
|
||||
|
||||
|
||||
def rows(path):
|
||||
with path.open(encoding="utf-8-sig", newline="") as handle:
|
||||
return list(csv.DictReader(handle))
|
||||
|
||||
|
||||
def indexed(path, *fields):
|
||||
records = rows(path)
|
||||
result = {tuple(row[f] for f in fields): row for row in records}
|
||||
assert len(result) == len(records), f"{path.name} 重复记录"
|
||||
return result
|
||||
|
||||
|
||||
def check(row, expected):
|
||||
for field, wanted in expected.items():
|
||||
actual = row[field]
|
||||
if isinstance(wanted, (int, float)):
|
||||
same = actual != "" and math.isclose(float(actual), wanted, rel_tol=1e-10, abs_tol=1e-8)
|
||||
else:
|
||||
same = actual == wanted
|
||||
assert same, f"{row.get('recovery_date', '')} {field}: {actual!r} 与复算 {wanted!r} 不同"
|
||||
|
||||
|
||||
def source_data():
|
||||
panel = rows(INPUT / "daily_panel.csv")
|
||||
index = rows(INPUT / "index_data.csv")
|
||||
for table in (panel, index):
|
||||
dates = [row["date"] for row in table]
|
||||
assert dates == sorted(set(dates))
|
||||
quotes = {row["date"]: row for row in index}
|
||||
assert len(panel) == 678 and all(r["date"] in quotes for r in panel)
|
||||
for row in panel:
|
||||
quote = quotes[row["date"]]
|
||||
assert quote["active_net_yuan"] == row["net_active_yuan"]
|
||||
assert float(quote["amount_yuan"]) == float(row["amount_yuan"])
|
||||
row["liquidity_low"] = row["low"] # 指数行情另有同名的日内最低价。
|
||||
row.update(quote)
|
||||
return panel
|
||||
|
||||
|
||||
def flow_available(row):
|
||||
return bool(
|
||||
row["active_net_yuan"] and row["member_turnover_yuan"]
|
||||
and float(row["member_turnover_yuan"]) > 0 and row["active_missing_turnover_yuan"]
|
||||
and float(row["active_missing_turnover_yuan"]) == 0
|
||||
and row["member_snapshot_date"] <= row["date"] and row["member_snapshot_date"]
|
||||
)
|
||||
|
||||
|
||||
def price_path(panel, sell, wait):
|
||||
prior_close = float(panel[sell - 1]["close"])
|
||||
window = panel[sell:sell + wait + 1]
|
||||
for day, row in enumerate(window):
|
||||
if float(row["close"]) >= prior_close:
|
||||
return {"status": "reclaimed", "day": day}
|
||||
return {"status": "not_yet" if len(window) == wait + 1 else "incomplete", "day": ""}
|
||||
|
||||
|
||||
def first_sell(panel, start):
|
||||
for i in range(start + 1, min(start + 6, len(panel))):
|
||||
if panel[i - 1]["state_turnover"] == "1":
|
||||
return "stopped_pressure", None
|
||||
if panel[i - 1]["state_turnover"] != "0":
|
||||
return "unknown_state", None
|
||||
if not flow_available(panel[i]):
|
||||
return "unknown_flow", None
|
||||
if float(panel[i]["active_net_yuan"]) < 0:
|
||||
return "found", i
|
||||
return ("no_sell" if len(panel) > start + 5 else "incomplete"), None
|
||||
|
||||
|
||||
def state_changes(panel, field, left, right):
|
||||
return [
|
||||
panel[i]["date"] for i in range(left + 1, right + 1)
|
||||
if panel[i - 1][field] == "0" and panel[i][field] == "1"
|
||||
]
|
||||
|
||||
|
||||
def endpoint_values(panel, start, visible):
|
||||
out = {}
|
||||
for label, field in ENDPOINTS.items():
|
||||
past = state_changes(panel, field, start - 1, visible)
|
||||
future = state_changes(panel, field, visible, visible + 5)
|
||||
already = panel[visible][field] == "1"
|
||||
out[label + "_prior"] = "|".join(past)
|
||||
out[label + "_result"] = "already" if already else ("new" if future else "none")
|
||||
out[label + "_first"] = future[0] if future and not already else ""
|
||||
return out
|
||||
|
||||
|
||||
def verify_tables(panel, dest):
|
||||
coverage = indexed(dest / "coverage.csv", "recovery_date")
|
||||
events = indexed(dest / "events.csv", "recovery_date")
|
||||
observations = indexed(dest / "observations.csv", "recovery_date", "landmark")
|
||||
starts = [i for i in range(1, len(panel)) if
|
||||
(panel[i - 1]["state_turnover"], panel[i]["state_turnover"]) == ("1", "0")]
|
||||
assert starts == [i for i, r in enumerate(panel) if r["relief_turnover"] == "1"]
|
||||
# 任一低位日及随后五个交易日的并集,独立重建九段所属范围。
|
||||
in_scope = {i for start, row in enumerate(panel) if row["liquidity_low"] == "1"
|
||||
for i in range(start, min(start + 6, len(panel)))}
|
||||
assert len(in_scope) == 173 and in_scope == {i for i, row in enumerate(panel) if row["episodes"]}
|
||||
dates = {panel[i]["date"] for i in starts}
|
||||
assert set(coverage) == {(d,) for d in dates} and len(starts) == 15
|
||||
main = {panel[i]["date"] for i in starts if i in in_scope}
|
||||
assert set(events) == {(d,) for d in main} and len(main) == 5
|
||||
assert set(observations) == {(d, name) for d in main for name in LANDMARKS}
|
||||
reference, landmarks, sell_indices = {}, {}, {}
|
||||
missing_coverage = []
|
||||
for i in starts:
|
||||
recovery = panel[i]["date"]
|
||||
days = panel[i + 1:i + 6]
|
||||
available = [r["date"] for r in days if flow_available(r)]
|
||||
absent = [r["date"] for r in days if not flow_available(r)]
|
||||
if not available:
|
||||
missing_coverage.append(recovery)
|
||||
status, sell = first_sell(panel, i) if recovery in main else ("out_of_scope", None)
|
||||
check(coverage[recovery,], {
|
||||
"episodes": panel[i]["episodes"], "in_scope": int(recovery in main),
|
||||
"window_days": len(days), "flow_days": len(available),
|
||||
"complete_window": int(len(available) == 5),
|
||||
"flow_dates": "|".join(available), "missing_dates": "|".join(absent),
|
||||
"search_status": status, "first_sell_date": "" if sell is None else panel[sell]["date"],
|
||||
})
|
||||
if recovery not in main:
|
||||
continue
|
||||
assert sell is not None, "冻结样本五次主恢复均应有可认定的首卖压"
|
||||
current, previous = panel[sell], panel[sell - 1]
|
||||
price = float(current["close"])
|
||||
previous_price = float(previous["close"])
|
||||
sell_yuan, traded_yuan = float(current["active_net_yuan"]), float(current["member_turnover_yuan"])
|
||||
reclaim = price_path(panel, sell, 5)
|
||||
event = {
|
||||
"pressure_date": current["date"], "age": sell - i, "prior_close": previous_price,
|
||||
"pressure_close": price, "shock_return_pct": 100 * (price / previous_price - 1),
|
||||
"sell_share_pct": 100 * abs(sell_yuan) / traded_yuan,
|
||||
"prior_activity_pct": 100 * statistics.median(float(previous["pct" + s]) for s in ("300", "500", "1000")),
|
||||
"prior_drawdown_pct": 100 * float(previous["dd_market155"]),
|
||||
"active_net_yuan": sell_yuan, "member_turnover_yuan": traded_yuan,
|
||||
"member_snapshot_date": current["member_snapshot_date"], "turnover_gap_pct": 100 * float(current["turnover_gap_fraction"]),
|
||||
"first_reclaim_day": reclaim["day"], "reclaim_status": reclaim["status"], "search_status": status,
|
||||
}
|
||||
check(events[recovery,], event)
|
||||
reference[recovery] = event
|
||||
sell_indices[recovery] = sell
|
||||
for label, lag in LANDMARKS.items():
|
||||
visible = sell + lag
|
||||
known = price_path(panel[:visible + 1], sell, lag)
|
||||
row = {
|
||||
"observation_date": panel[visible]["date"], "shock_return_pct": event["shock_return_pct"],
|
||||
"reclaim_status_known": known["status"], "reclaim_day_known": known["day"],
|
||||
**endpoint_values(panel, i, visible),
|
||||
}
|
||||
check(observations[recovery, label], row)
|
||||
landmarks[recovery, label] = row
|
||||
assert len(missing_coverage) == 8
|
||||
return reference, landmarks, sell_indices, missing_coverage
|
||||
|
||||
|
||||
def verify_pairs(reference, landmarks, dest):
|
||||
pairs = indexed(dest / "pairs.csv", "left_recovery", "right_recovery")
|
||||
outcomes = indexed(dest / "pair_outcomes.csv", "left_recovery", "right_recovery", "landmark", "endpoint")
|
||||
keys = list(combinations(sorted(reference), 2))
|
||||
assert set(keys) == set(pairs)
|
||||
eligible = {scale: [] for scale in SCALES}
|
||||
expected_outcomes = set()
|
||||
for left, right in keys:
|
||||
difference = {key: abs(reference[left][key] - reference[right][key]) for key in TOLERANCES}
|
||||
expected = {"diff_" + key: v for key, v in difference.items()}
|
||||
for scale, multiple in SCALES.items():
|
||||
failed = [key for key, d in difference.items() if d > multiple * TOLERANCES[key]]
|
||||
expected[scale + "_match"] = int(not failed)
|
||||
expected[scale + "_failures"] = "|".join(failed)
|
||||
if not failed:
|
||||
eligible[scale].append([left, right])
|
||||
check(pairs[left, right], expected)
|
||||
if not expected["main_match"]:
|
||||
continue
|
||||
for label in LANDMARKS:
|
||||
a, b = landmarks[left, label], landmarks[right, label]
|
||||
price = a["shock_return_pct"] - b["shock_return_pct"]
|
||||
def speed(row):
|
||||
return row["reclaim_day_known"] if row["reclaim_status_known"] == "reclaimed" else 3
|
||||
gain = speed(b) - speed(a) if label == "day2" else 0
|
||||
if price * gain < 0:
|
||||
stronger = "conflict"
|
||||
elif price == gain == 0:
|
||||
stronger = "tie"
|
||||
else:
|
||||
stronger = "left" if max(price, gain) > 0 else "right"
|
||||
for endpoint in ENDPOINTS:
|
||||
key = (left, right, label, endpoint)
|
||||
expected_outcomes.add(key)
|
||||
outcome = {"stronger": stronger}
|
||||
for side, row in (("left", a), ("right", b)):
|
||||
outcome[side + "_date"] = row["observation_date"]
|
||||
for item in ("result", "first", "prior"):
|
||||
outcome[side + "_" + item] = row[endpoint + "_" + item]
|
||||
risks = (outcome["left_result"], outcome["right_result"])
|
||||
can_compare = all(r in {"new", "none"} for r in risks)
|
||||
if not can_compare:
|
||||
risk = "endpoint_unavailable"
|
||||
elif stronger not in ("left", "right"):
|
||||
risk = "no_order"
|
||||
elif risks[0] == risks[1]:
|
||||
risk = "same"
|
||||
else:
|
||||
risk = "more" if outcome[stronger + "_result"] == "new" else "less"
|
||||
check(outcomes[key], {**outcome, "risk_of_stronger": risk, "both_evaluable": int(can_compare)})
|
||||
assert set(outcomes) == expected_outcomes
|
||||
return eligible
|
||||
|
||||
|
||||
def verify_prefixes(panel, landmarks, sell_indices):
|
||||
"""经正式脚本截断输入,比较可见价格字段,并核实尚未到期的标签。"""
|
||||
checked = 0
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
out = Path(temp)
|
||||
for recovery, sell in sell_indices.items():
|
||||
for lag in (-1, 0, 1, 2):
|
||||
cutoff = panel[sell + lag]["date"]
|
||||
subprocess.run([sys.executable, "-B", "-I", str(HERE / "events.py"),
|
||||
"--output-dir", temp, "--as-of", cutoff], check=True)
|
||||
event = indexed(out / "events.csv", "recovery_date")[recovery,]
|
||||
obs = indexed(out / "observations.csv", "recovery_date", "landmark")
|
||||
if lag < 0:
|
||||
check(event, {"pressure_date": "", "search_status": "incomplete",
|
||||
"first_reclaim_day": "", "reclaim_status": ""})
|
||||
assert not any(date == recovery for date, label in obs)
|
||||
else:
|
||||
short_path = price_path(panel[:sell + lag + 1], sell, 5)
|
||||
check(event, {"pressure_date": panel[sell]["date"], "search_status": "found",
|
||||
"first_reclaim_day": short_path["day"], "reclaim_status": short_path["status"]})
|
||||
for label, age in LANDMARKS.items():
|
||||
observed = obs[recovery, label]
|
||||
full = landmarks[recovery, label]
|
||||
if age > lag:
|
||||
check(observed, {"observation_date": "", "shock_return_pct": "",
|
||||
"reclaim_status_known": "incomplete", "reclaim_day_known": "",
|
||||
"followup_days": 0})
|
||||
else:
|
||||
check(observed, {f: full[f] for f in
|
||||
("observation_date", "shock_return_pct", "reclaim_status_known", "reclaim_day_known")})
|
||||
check(observed, {"followup_days": lag - age})
|
||||
for endpoint, field in ENDPOINTS.items():
|
||||
current = sell + age
|
||||
past = full[endpoint + "_prior"] if age <= lag else ""
|
||||
first = ""
|
||||
status = "incomplete"
|
||||
if current <= sell + lag:
|
||||
if panel[current][field] == "1":
|
||||
status = "already"
|
||||
else:
|
||||
occurred = state_changes(panel, field, current, sell + lag)
|
||||
first = occurred[0] if occurred else ""
|
||||
check(observed, {endpoint + "_result": status, endpoint + "_first": first,
|
||||
endpoint + "_prior": past})
|
||||
checked += 1
|
||||
return checked
|
||||
|
||||
|
||||
def run(dest):
|
||||
panel = source_data()
|
||||
reference, landmarks, sell_indices, missing = verify_tables(panel, dest)
|
||||
eligible = verify_pairs(reference, landmarks, dest)
|
||||
prefix_checks = verify_prefixes(panel, landmarks, sell_indices)
|
||||
result = {
|
||||
"source_sha256": {name: hashlib.sha256((INPUT / name).read_bytes()).hexdigest()
|
||||
for name in ("index_data.csv", "daily_panel.csv")},
|
||||
"calendar_days": len(panel), "all_recoveries": 15, "main_recoveries": len(reference),
|
||||
"recoveries_with_no_covered_days": missing,
|
||||
"first_sell_dates": {date: event["pressure_date"] for date, event in reference.items()},
|
||||
"full_five_day_reclaim": {date: event["first_reclaim_day"] if event["first_reclaim_day"] != "" else event["reclaim_status"]
|
||||
for date, event in reference.items()},
|
||||
"landmarks_checked": len(landmarks), "endpoint_windows_checked": 2 * len(landmarks),
|
||||
"eligible_pairs_by_tolerance": eligible, "prefix_checks": prefix_checks,
|
||||
}
|
||||
with (dest / "audit.json").open("w", encoding="utf-8") as handle:
|
||||
json.dump(result, handle, ensure_ascii=False, indent=2)
|
||||
handle.write("\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--output-dir", type=Path, default=HERE)
|
||||
run(parser.parse_args().output_dir)
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
recovery_date,episodes,in_scope,window_days,flow_days,complete_window,flow_dates,missing_dates,search_status,first_sell_date
|
||||
2024-01-03,,0,5,5,1,2024-01-04|2024-01-05|2024-01-08|2024-01-09|2024-01-10,,out_of_scope,
|
||||
2024-01-19,,0,5,5,1,2024-01-22|2024-01-23|2024-01-24|2024-01-25|2024-01-26,,out_of_scope,
|
||||
2024-06-19,3,1,5,5,1,2024-06-20|2024-06-21|2024-06-24|2024-06-25|2024-06-26,,found,2024-06-20
|
||||
2024-07-12,3,1,5,5,1,2024-07-15|2024-07-16|2024-07-17|2024-07-18|2024-07-19,,found,2024-07-15
|
||||
2024-08-01,3,1,5,5,1,2024-08-02|2024-08-05|2024-08-06|2024-08-07|2024-08-08,,found,2024-08-02
|
||||
2024-09-02,4,1,5,5,1,2024-09-03|2024-09-04|2024-09-05|2024-09-06|2024-09-09,,found,2024-09-03
|
||||
2024-09-23,4,1,5,5,1,2024-09-24|2024-09-25|2024-09-26|2024-09-27|2024-09-30,,found,2024-09-25
|
||||
2024-12-11,,0,5,0,0,,2024-12-12|2024-12-13|2024-12-16|2024-12-17|2024-12-18,out_of_scope,
|
||||
2025-02-07,,0,5,0,0,,2025-02-10|2025-02-11|2025-02-12|2025-02-13|2025-02-14,out_of_scope,
|
||||
2025-04-11,,0,5,0,0,,2025-04-14|2025-04-15|2025-04-16|2025-04-17|2025-04-18,out_of_scope,
|
||||
2025-05-13,,0,5,0,0,,2025-05-14|2025-05-15|2025-05-16|2025-05-19|2025-05-20,out_of_scope,
|
||||
2025-06-06,,0,5,0,0,,2025-06-09|2025-06-10|2025-06-11|2025-06-12|2025-06-13,out_of_scope,
|
||||
2025-10-31,,0,5,0,0,,2025-11-03|2025-11-04|2025-11-05|2025-11-06|2025-11-07,out_of_scope,
|
||||
2025-12-15,,0,5,0,0,,2025-12-16|2025-12-17|2025-12-18|2025-12-19|2025-12-22,out_of_scope,
|
||||
2026-04-15,,0,5,0,0,,2026-04-16|2026-04-17|2026-04-20|2026-04-21|2026-04-22,out_of_scope,
|
||||
|
|
|
@ -0,0 +1,6 @@
|
|||
recovery_date,episodes,search_status,pressure_date,age,prior_date,prior_activity_pct,prior_drawdown_pct,sell_share_pct,shock_return_pct,prior_close,pressure_close,first_reclaim_day,reclaim_status,member_snapshot_date,member_count,snapshot_exact,member_turnover_yuan,active_net_yuan,turnover_gap_pct
|
||||
2024-06-19,3,found,2024-06-20,1,2024-06-19,41.66666666666667,0.5560236560296028,12.282608939929403,-2.338686789290645,1932.2596,1887.0701,,not_yet,2024-05-31,2000,0,174758676312.0,-21464924800.0,0.3641514844206455
|
||||
2024-07-12,3,found,2024-07-15,1,2024-07-12,48.01587301587302,0.25383896060130473,11.505926551159465,-1.7222641998549393,1823.8549,1792.4433,,not_yet,2024-06-28,2000,0,130951184444.0,-15067147100.0,3.3905764951214223e-07
|
||||
2024-08-01,3,found,2024-08-02,1,2024-08-01,49.60317460317461,0.0,8.274939700947016,-1.3376828865440227,1843.561,1818.9,,not_yet,2024-07-31,2000,0,190727933621.0,-15782621500.0,3.255946836588919e-07
|
||||
2024-09-02,4,found,2024-09-03,1,2024-09-02,59.92063492063492,1.6422026841749982,2.1601920492429305,1.0690632629545505,1739.7006,1758.2991,0,reclaimed,2024-08-30,2000,0,137430961337.0,-2968772700.0,2.452140250852608e-07
|
||||
2024-09-23,4,found,2024-09-25,2,2024-09-24,80.15873015873017,0.0,4.178168049742128,1.2495154565507427,1784.4117,1806.7082,0,reclaimed,2024-08-30,2000,0,248258563957.0,-10372660000.0,-0.03310533359125145
|
||||
|
|
|
@ -0,0 +1,248 @@
|
|||
"""用归档的沪深日线与成分资金重放恢复后的第一次主动净卖出。"""
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
from statistics import median
|
||||
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
ARCHIVE = HERE.parent / "liquidity_relief_20261120"
|
||||
HORIZON = 5
|
||||
LANDMARKS = {"fast": 0, "delayed": 1, "day2": 2}
|
||||
TARGETS = {"turnover": "state_turnover", "tail": "tail_market155"}
|
||||
QUOTE_FIELDS = (
|
||||
"close", "active_net_yuan", "member_snapshot_date", "member_count", "traded_members",
|
||||
"active_flow_observed_members", "member_turnover_yuan", "active_missing_turnover_yuan",
|
||||
"funds_nonzero_without_traded_quote", "snapshot_exact",
|
||||
)
|
||||
|
||||
COVERAGE_FIELDS = (
|
||||
"recovery_date episodes in_scope window_days flow_days complete_window "
|
||||
"flow_dates missing_dates search_status first_sell_date"
|
||||
).split()
|
||||
EVENT_FIELDS = (
|
||||
"recovery_date episodes search_status pressure_date age prior_date prior_activity_pct "
|
||||
"prior_drawdown_pct sell_share_pct shock_return_pct prior_close pressure_close "
|
||||
"first_reclaim_day reclaim_status member_snapshot_date member_count snapshot_exact "
|
||||
"member_turnover_yuan active_net_yuan turnover_gap_pct"
|
||||
).split()
|
||||
OBS_FIELDS = [
|
||||
"recovery_date", "pressure_date", "landmark", "observation_date", "shock_return_pct",
|
||||
"reclaim_day_known", "reclaim_status_known", "followup_days",
|
||||
]
|
||||
for target_name in TARGETS:
|
||||
OBS_FIELDS.extend(target_name + suffix for suffix in ("_result", "_first", "_prior"))
|
||||
|
||||
|
||||
def number(value):
|
||||
if value in ("", None):
|
||||
return None
|
||||
result = float(value)
|
||||
if not math.isfinite(result):
|
||||
raise ValueError(f"归档出现无穷或无效数值 {value}")
|
||||
return result
|
||||
|
||||
|
||||
def read_archive(name, hashes):
|
||||
path = ARCHIVE / name
|
||||
if hashlib.sha256(path.read_bytes()).hexdigest() != hashes[name]:
|
||||
raise ValueError(f"输入文件与上轮摘要不符 {name}")
|
||||
with path.open(encoding="utf-8-sig", newline="") as stream:
|
||||
rows = list(csv.DictReader(stream))
|
||||
dates = [r["date"] for r in rows]
|
||||
if dates != sorted(set(dates)):
|
||||
raise ValueError(f"交易日有重复或未按时间排列 {name}")
|
||||
return rows
|
||||
|
||||
|
||||
def load_inputs(as_of):
|
||||
hashes = json.loads((ARCHIVE / "audit.json").read_text())["sha256"]
|
||||
panel = read_archive("daily_panel.csv", hashes)
|
||||
index = read_archive("index_data.csv", hashes)
|
||||
if as_of is not None:
|
||||
panel = [r for r in panel if r["date"] <= as_of]
|
||||
if not panel:
|
||||
return []
|
||||
dates = [r["date"] for r in panel]
|
||||
quotes = [r for r in index if dates[0] <= r["date"] <= dates[-1]]
|
||||
if dates != [r["date"] for r in quotes]:
|
||||
raise ValueError("两张输入表的评价期交易日不一致")
|
||||
rows = []
|
||||
for p, q in zip(panel, quotes):
|
||||
if p["net_active_yuan"] != q["active_net_yuan"] or number(p["amount_yuan"]) != number(q["amount_yuan"]):
|
||||
raise ValueError(f"{p['date']} 逐日面板与来源资金或成交额不一致")
|
||||
rows.append({**p, **{field: q[field] for field in QUOTE_FIELDS}})
|
||||
return rows
|
||||
|
||||
|
||||
def has_flow(row):
|
||||
snapshot = row["member_snapshot_date"]
|
||||
if not snapshot:
|
||||
return False
|
||||
age = (date.fromisoformat(row["date"]) - date.fromisoformat(snapshot)).days
|
||||
amount = number(row["member_turnover_yuan"])
|
||||
traded = number(row["traded_members"])
|
||||
return (
|
||||
0 <= age <= 45
|
||||
and number(row["active_net_yuan"]) is not None
|
||||
and amount is not None and amount > 0
|
||||
and traded is not None and traded > 0
|
||||
and number(row["active_flow_observed_members"]) == traded
|
||||
and number(row["active_missing_turnover_yuan"]) == 0
|
||||
and number(row["funds_nonzero_without_traded_quote"]) == 0
|
||||
)
|
||||
|
||||
|
||||
def first_sell(rows, recovery):
|
||||
for i in range(recovery + 1, min(recovery + HORIZON + 1, len(rows))):
|
||||
before = rows[i - 1]["state_turnover"]
|
||||
if before == "1":
|
||||
return "stopped_pressure", None
|
||||
if before != "0":
|
||||
return "unknown_state", None
|
||||
if not has_flow(rows[i]):
|
||||
return "unknown_flow", None
|
||||
if float(rows[i]["active_net_yuan"]) < 0:
|
||||
return "found", i
|
||||
# 当天没有卖压、却已重新入压时,本轮在这个收盘结束。
|
||||
if rows[i]["state_turnover"] == "1":
|
||||
return "stopped_pressure", None
|
||||
if recovery + HORIZON >= len(rows):
|
||||
return "incomplete", None
|
||||
return "no_sell", None
|
||||
|
||||
|
||||
def reclaim(rows, pressure, days):
|
||||
base = number(rows[pressure - 1]["close"])
|
||||
if base is None or base <= 0:
|
||||
return None, "unknown"
|
||||
for offset in range(days + 1):
|
||||
if pressure + offset >= len(rows):
|
||||
return None, "incomplete"
|
||||
close = number(rows[pressure + offset]["close"])
|
||||
if close is None or close <= 0:
|
||||
return None, "unknown"
|
||||
if close >= base:
|
||||
return offset, "reclaimed"
|
||||
return None, "not_yet"
|
||||
|
||||
|
||||
def starts(rows, field, begin, end):
|
||||
return [
|
||||
rows[i]["date"] for i in range(max(begin, 1), min(end + 1, len(rows)))
|
||||
if rows[i - 1][field] == "0" and rows[i][field] == "1"
|
||||
]
|
||||
|
||||
|
||||
def endpoint(rows, field, recovery, current):
|
||||
if current >= len(rows):
|
||||
return "incomplete", None, None
|
||||
earlier = "|".join(starts(rows, field, recovery, current))
|
||||
state = rows[current][field]
|
||||
if state == "1":
|
||||
return "already", None, earlier
|
||||
if state != "0":
|
||||
return "unknown", None, earlier
|
||||
future = rows[current + 1 : current + HORIZON + 1]
|
||||
new = starts(rows, field, current + 1, current + HORIZON)
|
||||
first = new[0] if new else None
|
||||
if len(future) < HORIZON:
|
||||
return "incomplete", first, earlier
|
||||
if any(r[field] not in ("0", "1") for r in future):
|
||||
return "unknown", first, earlier
|
||||
return ("new" if first else "none"), first, earlier
|
||||
|
||||
|
||||
def measure(rows, recovery, pressure, event):
|
||||
before, day = rows[pressure - 1 : pressure + 1]
|
||||
ranks = [number(before["pct" + size]) for size in ("300", "500", "1000")]
|
||||
drawdown = number(before["dd_market155"])
|
||||
base, close = number(before["close"]), number(day["close"])
|
||||
change = 100 * (close / base - 1) if base and close and min(base, close) > 0 else None
|
||||
first_day, status = reclaim(rows, pressure, HORIZON)
|
||||
event.update(
|
||||
pressure_date=day["date"], age=pressure - recovery, prior_date=before["date"],
|
||||
prior_activity_pct=100 * median(ranks) if None not in ranks else None,
|
||||
prior_drawdown_pct=100 * drawdown if drawdown is not None else None,
|
||||
sell_share_pct=-100 * float(day["active_net_yuan"]) / float(day["member_turnover_yuan"]),
|
||||
shock_return_pct=change, prior_close=base, pressure_close=close,
|
||||
first_reclaim_day=first_day, reclaim_status=status,
|
||||
member_snapshot_date=day["member_snapshot_date"], member_count=day["member_count"],
|
||||
snapshot_exact=int(day["snapshot_exact"] == "True"),
|
||||
member_turnover_yuan=day["member_turnover_yuan"], active_net_yuan=day["active_net_yuan"],
|
||||
turnover_gap_pct=100 * float(day["member_turnover_yuan"]) / float(day["amount_yuan"]) - 100,
|
||||
)
|
||||
observations = []
|
||||
for landmark, lag in LANDMARKS.items():
|
||||
current = pressure + lag
|
||||
known_day, known_status = reclaim(rows, pressure, lag)
|
||||
obs = dict(
|
||||
recovery_date=event["recovery_date"], pressure_date=day["date"], landmark=landmark,
|
||||
observation_date=rows[current]["date"] if current < len(rows) else None,
|
||||
shock_return_pct=change if current < len(rows) else None,
|
||||
reclaim_day_known=known_day if current < len(rows) else None,
|
||||
reclaim_status_known=known_status if current < len(rows) else "incomplete",
|
||||
followup_days=max(0, min(HORIZON, len(rows) - 1 - current)),
|
||||
)
|
||||
for name, field in TARGETS.items():
|
||||
result, first, earlier = endpoint(rows, field, recovery, current)
|
||||
obs[name + "_result"] = result
|
||||
obs[name + "_first"] = first
|
||||
obs[name + "_prior"] = earlier
|
||||
observations.append(obs)
|
||||
return observations
|
||||
|
||||
|
||||
def analyze(rows):
|
||||
coverage, events, observations = [], [], []
|
||||
for recovery, r in enumerate(rows):
|
||||
if r["relief_turnover"] != "1":
|
||||
continue
|
||||
scoped = bool(r["episodes"])
|
||||
window = rows[recovery + 1 : recovery + HORIZON + 1]
|
||||
covered = [d["date"] for d in window if has_flow(d)]
|
||||
missing = [d["date"] for d in window if d["date"] not in covered]
|
||||
status, index = first_sell(rows, recovery) if scoped else ("out_of_scope", None)
|
||||
coverage.append(dict(
|
||||
recovery_date=r["date"], episodes=r["episodes"], in_scope=int(scoped),
|
||||
window_days=len(window), flow_days=len(covered), complete_window=int(len(covered) == HORIZON),
|
||||
flow_dates="|".join(covered), missing_dates="|".join(missing), search_status=status,
|
||||
first_sell_date=rows[index]["date"] if index is not None else None,
|
||||
))
|
||||
if scoped:
|
||||
event = dict(recovery_date=r["date"], episodes=r["episodes"], search_status=status)
|
||||
if index is not None:
|
||||
observations.extend(measure(rows, recovery, index, event))
|
||||
events.append(event)
|
||||
return coverage, events, observations
|
||||
|
||||
|
||||
def write_table(out, name, fields, rows):
|
||||
with (out / name).open("w", newline="", encoding="utf-8") as stream:
|
||||
writer = csv.DictWriter(stream, fieldnames=fields, lineterminator="\n")
|
||||
writer.writeheader()
|
||||
writer.writerows(rows)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--output-dir", type=Path, default=HERE)
|
||||
parser.add_argument("--as-of", type=date.fromisoformat, help="仅回放到指定收盘,用于验证当日可见信息")
|
||||
args = parser.parse_args()
|
||||
rows = load_inputs(args.as_of.isoformat() if args.as_of else None)
|
||||
coverage, events, observations = analyze(rows)
|
||||
if args.as_of is None and (len(rows), len(coverage), len(events)) != (678, 15, 5):
|
||||
raise ValueError("与上轮冻结的评价日或宽基恢复次数不一致")
|
||||
args.output_dir.mkdir(exist_ok=True, parents=True)
|
||||
write_table(args.output_dir, "coverage.csv", COVERAGE_FIELDS, coverage)
|
||||
write_table(args.output_dir, "events.csv", EVENT_FIELDS, events)
|
||||
write_table(args.output_dir, "observations.csv", OBS_FIELDS, observations)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
recovery_date,pressure_date,landmark,observation_date,shock_return_pct,reclaim_day_known,reclaim_status_known,followup_days,turnover_result,turnover_first,turnover_prior,tail_result,tail_first,tail_prior
|
||||
2024-06-19,2024-06-20,fast,2024-06-20,-2.338686789290645,,not_yet,5,new,2024-06-21,,new,2024-06-24,
|
||||
2024-06-19,2024-06-20,delayed,2024-06-21,-2.338686789290645,,not_yet,5,already,,2024-06-21,new,2024-06-24,
|
||||
2024-06-19,2024-06-20,day2,2024-06-24,-2.338686789290645,,not_yet,5,already,,2024-06-21,already,,2024-06-24
|
||||
2024-07-12,2024-07-15,fast,2024-07-15,-1.7222641998549393,,not_yet,5,none,,,none,,
|
||||
2024-07-12,2024-07-15,delayed,2024-07-16,-1.7222641998549393,,not_yet,5,none,,,none,,
|
||||
2024-07-12,2024-07-15,day2,2024-07-17,-1.7222641998549393,,not_yet,5,none,,,none,,
|
||||
2024-08-01,2024-08-02,fast,2024-08-02,-1.3376828865440227,,not_yet,5,none,,,none,,
|
||||
2024-08-01,2024-08-02,delayed,2024-08-05,-1.3376828865440227,,not_yet,5,new,2024-08-12,,none,,
|
||||
2024-08-01,2024-08-02,day2,2024-08-06,-1.3376828865440227,,not_yet,5,new,2024-08-12,,none,,
|
||||
2024-09-02,2024-09-03,fast,2024-09-03,1.0690632629545505,0,reclaimed,5,new,2024-09-09,,none,,
|
||||
2024-09-02,2024-09-03,delayed,2024-09-04,1.0690632629545505,0,reclaimed,5,new,2024-09-09,,none,,
|
||||
2024-09-02,2024-09-03,day2,2024-09-05,1.0690632629545505,0,reclaimed,5,new,2024-09-09,,none,,
|
||||
2024-09-23,2024-09-25,fast,2024-09-25,1.2495154565507427,0,reclaimed,5,none,,,new,2024-10-09,
|
||||
2024-09-23,2024-09-25,delayed,2024-09-26,1.2495154565507427,0,reclaimed,5,none,,,new,2024-10-09,
|
||||
2024-09-23,2024-09-25,day2,2024-09-27,1.2495154565507427,0,reclaimed,5,none,,,new,2024-10-09,
|
||||
|
|
|
@ -0,0 +1,7 @@
|
|||
left_recovery,right_recovery,landmark,endpoint,left_date,right_date,left_shock_return_pct,right_shock_return_pct,left_reclaim_status,right_reclaim_status,left_reclaim_day,right_reclaim_day,stronger,left_result,right_result,left_first,right_first,left_prior,right_prior,both_evaluable,risk_of_stronger
|
||||
2024-06-19,2024-07-12,fast,turnover,2024-06-20,2024-07-15,-2.338686789290645,-1.7222641998549393,,,,,right,new,none,2024-06-21,,,,1,less
|
||||
2024-06-19,2024-07-12,fast,tail,2024-06-20,2024-07-15,-2.338686789290645,-1.7222641998549393,,,,,right,new,none,2024-06-24,,,,1,less
|
||||
2024-06-19,2024-07-12,delayed,turnover,2024-06-21,2024-07-16,-2.338686789290645,-1.7222641998549393,,,,,right,already,none,,,2024-06-21,,0,endpoint_unavailable
|
||||
2024-06-19,2024-07-12,delayed,tail,2024-06-21,2024-07-16,-2.338686789290645,-1.7222641998549393,,,,,right,new,none,2024-06-24,,,,1,less
|
||||
2024-06-19,2024-07-12,day2,turnover,2024-06-24,2024-07-17,-2.338686789290645,-1.7222641998549393,not_yet,not_yet,,,right,already,none,,,2024-06-21,,0,endpoint_unavailable
|
||||
2024-06-19,2024-07-12,day2,tail,2024-06-24,2024-07-17,-2.338686789290645,-1.7222641998549393,not_yet,not_yet,,,right,already,none,,,2024-06-24,,0,endpoint_unavailable
|
||||
|
|
|
@ -0,0 +1,11 @@
|
|||
left_recovery,right_recovery,left_pressure,right_pressure,diff_age,diff_prior_activity_pct,diff_prior_drawdown_pct,diff_sell_share_pct,main_match,main_failures,half_match,half_failures,double_match,double_failures
|
||||
2024-06-19,2024-07-12,2024-06-20,2024-07-15,0,6.34920634920635,0.30218469542829807,0.776682388769938,1,,1,,1,
|
||||
2024-06-19,2024-08-01,2024-06-20,2024-08-02,0,7.93650793650794,0.5560236560296028,4.007669238982387,0,sell_share_pct,0,prior_activity_pct|sell_share_pct,0,sell_share_pct
|
||||
2024-06-19,2024-09-02,2024-06-20,2024-09-03,0,18.25396825396825,1.0861790281453954,10.1224168906864725,0,prior_activity_pct|sell_share_pct,0,prior_activity_pct|prior_drawdown_pct|sell_share_pct,0,sell_share_pct
|
||||
2024-06-19,2024-09-23,2024-06-20,2024-09-25,1,38.49206349206350,0.5560236560296028,8.104440890187275,0,prior_activity_pct|sell_share_pct,0,age|prior_activity_pct|sell_share_pct,0,prior_activity_pct|sell_share_pct
|
||||
2024-07-12,2024-08-01,2024-07-15,2024-08-02,0,1.58730158730159,0.25383896060130473,3.230986850212449,0,sell_share_pct,0,sell_share_pct,1,
|
||||
2024-07-12,2024-09-02,2024-07-15,2024-09-03,0,11.90476190476190,1.38836372357369347,9.3457345019165345,0,sell_share_pct,0,prior_activity_pct|prior_drawdown_pct|sell_share_pct,0,sell_share_pct
|
||||
2024-07-12,2024-09-23,2024-07-15,2024-09-25,1,32.14285714285715,0.25383896060130473,7.327758501417337,0,prior_activity_pct|sell_share_pct,0,age|prior_activity_pct|sell_share_pct,0,prior_activity_pct|sell_share_pct
|
||||
2024-08-01,2024-09-02,2024-08-02,2024-09-03,0,10.31746031746031,1.6422026841749982,6.1147476517040855,0,sell_share_pct,0,prior_activity_pct|prior_drawdown_pct|sell_share_pct,0,sell_share_pct
|
||||
2024-08-01,2024-09-23,2024-08-02,2024-09-25,1,30.55555555555556,0.0,4.096771651204888,0,prior_activity_pct|sell_share_pct,0,age|prior_activity_pct|sell_share_pct,0,prior_activity_pct|sell_share_pct
|
||||
2024-09-02,2024-09-23,2024-09-03,2024-09-25,1,20.23809523809525,1.6422026841749982,2.0179760004991975,0,prior_activity_pct|sell_share_pct,0,age|prior_activity_pct|prior_drawdown_pct|sell_share_pct,1,
|
||||
|
|
|
@ -0,0 +1,170 @@
|
|||
"""按预先固定的容差比较不同宽基恢复后的第一次微盘卖压。"""
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
from decimal import Decimal
|
||||
from itertools import combinations
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
# 成交强度、回撤和卖压均以百分点为单位,age 以交易日为单位。
|
||||
TOLERANCES = {
|
||||
"age": Decimal("1"),
|
||||
"prior_activity_pct": Decimal("15"),
|
||||
"prior_drawdown_pct": Decimal("2"),
|
||||
"sell_share_pct": Decimal("2"),
|
||||
}
|
||||
SCALES = {"main": Decimal("1"), "half": Decimal("0.5"), "double": Decimal("2")}
|
||||
LANDMARKS = ("fast", "delayed", "day2")
|
||||
ENDPOINTS = ("turnover", "tail")
|
||||
|
||||
PAIR_FIELDS = [
|
||||
"left_recovery", "right_recovery", "left_pressure", "right_pressure",
|
||||
*(f"diff_{field}" for field in TOLERANCES),
|
||||
*(f"{scale}_{field}" for scale in SCALES for field in ("match", "failures")),
|
||||
]
|
||||
OUTCOME_FIELDS = [
|
||||
"left_recovery", "right_recovery", "landmark", "endpoint",
|
||||
"left_date", "right_date", "left_shock_return_pct", "right_shock_return_pct",
|
||||
"left_reclaim_status", "right_reclaim_status", "left_reclaim_day", "right_reclaim_day",
|
||||
"stronger", "left_result", "right_result", "left_first", "right_first",
|
||||
"left_prior", "right_prior", "both_evaluable", "risk_of_stronger",
|
||||
]
|
||||
|
||||
|
||||
def read_index(path, keys):
|
||||
records = {}
|
||||
with path.open(encoding="utf-8-sig", newline="") as handle:
|
||||
for row in csv.DictReader(handle):
|
||||
key = tuple(row[field] for field in keys)
|
||||
if key in records:
|
||||
raise ValueError(f"{path.name} 有重复记录 {key}")
|
||||
records[key] = row
|
||||
return records
|
||||
|
||||
|
||||
def write_rows(path, rows, fields):
|
||||
with path.open("w", encoding="utf-8", newline="") as handle:
|
||||
writer = csv.DictWriter(handle, fieldnames=fields, lineterminator="\n")
|
||||
writer.writeheader()
|
||||
writer.writerows(rows)
|
||||
|
||||
|
||||
def number(value):
|
||||
return Decimal(value) if value != "" else None
|
||||
|
||||
|
||||
def match_record(left, right):
|
||||
pair = {
|
||||
"left_recovery": left["recovery_date"], "right_recovery": right["recovery_date"],
|
||||
"left_pressure": left["pressure_date"], "right_pressure": right["pressure_date"],
|
||||
}
|
||||
differences = {}
|
||||
for field in TOLERANCES:
|
||||
a, b = number(left[field]), number(right[field])
|
||||
difference = None if a is None or b is None else abs(a - b)
|
||||
differences[field] = difference
|
||||
pair[f"diff_{field}"] = difference
|
||||
|
||||
for name, scale in SCALES.items():
|
||||
failures = []
|
||||
if not (left["pressure_date"] and right["pressure_date"]):
|
||||
failures.append("missing_pressure_date")
|
||||
for field, difference in differences.items():
|
||||
if difference is None:
|
||||
failures.append(f"missing_{field}")
|
||||
elif difference > TOLERANCES[field] * scale:
|
||||
failures.append(field)
|
||||
pair[f"{name}_match"] = int(not failures)
|
||||
pair[f"{name}_failures"] = "|".join(failures)
|
||||
return pair
|
||||
|
||||
|
||||
def stronger_side(left, right, landmark):
|
||||
# 两个快速时点都只凭卖压当日涨跌判断。延后取得资金不能改变当日涨跌。
|
||||
returns = [number(row["shock_return_pct"]) for row in (left, right)]
|
||||
if not all(row["observation_date"] for row in (left, right)) or None in returns:
|
||||
return "unknown"
|
||||
a, b = returns
|
||||
price_direction = (a > b) - (a < b)
|
||||
if landmark != "day2":
|
||||
return {1: "left", -1: "right", 0: "tie"}[price_direction]
|
||||
|
||||
# 第2日仍未收回的两方速度并列,速度只使用判断日以前的收盘。
|
||||
days = []
|
||||
for row in (left, right):
|
||||
status = row["reclaim_status_known"]
|
||||
if status == "reclaimed":
|
||||
day = int(row["reclaim_day_known"])
|
||||
if day not in (0, 1, 2):
|
||||
raise ValueError(f"第二日判断含未知的收回天数 {day}")
|
||||
days.append(day)
|
||||
elif status == "not_yet":
|
||||
days.append(3) # 只用于排序,第3天是否收回尚未知。
|
||||
else:
|
||||
return "unknown"
|
||||
a_day, b_day = days
|
||||
speed_direction = (a_day < b_day) - (a_day > b_day)
|
||||
directions = {price_direction, speed_direction} - {0}
|
||||
if len(directions) == 2:
|
||||
return "conflict"
|
||||
if not directions:
|
||||
return "tie"
|
||||
return "left" if 1 in directions else "right"
|
||||
|
||||
|
||||
def compare_endpoints(pair, observations):
|
||||
for landmark in LANDMARKS:
|
||||
left = observations[pair["left_recovery"], landmark]
|
||||
right = observations[pair["right_recovery"], landmark]
|
||||
stronger = stronger_side(left, right, landmark)
|
||||
for endpoint in ENDPOINTS:
|
||||
result = {
|
||||
"left_recovery": pair["left_recovery"], "right_recovery": pair["right_recovery"],
|
||||
"landmark": landmark, "endpoint": endpoint, "stronger": stronger,
|
||||
}
|
||||
for side, row in (("left", left), ("right", right)):
|
||||
result[f"{side}_date"] = row["observation_date"]
|
||||
result[f"{side}_shock_return_pct"] = row["shock_return_pct"]
|
||||
result[f"{side}_reclaim_status"] = row["reclaim_status_known"] if landmark == "day2" else ""
|
||||
result[f"{side}_reclaim_day"] = row["reclaim_day_known"] if landmark == "day2" else ""
|
||||
for field in ("result", "first", "prior"):
|
||||
result[f"{side}_{field}"] = row[f"{endpoint}_{field}"]
|
||||
left_risk, right_risk = result["left_result"], result["right_result"]
|
||||
evaluable = all(value in ("new", "none") for value in (left_risk, right_risk))
|
||||
result["both_evaluable"] = int(evaluable)
|
||||
if not evaluable:
|
||||
result["risk_of_stronger"] = "endpoint_unavailable"
|
||||
elif stronger not in ("left", "right"):
|
||||
result["risk_of_stronger"] = "no_order"
|
||||
elif left_risk == right_risk:
|
||||
result["risk_of_stronger"] = "same"
|
||||
else:
|
||||
result["risk_of_stronger"] = "more" if result[f"{stronger}_result"] == "new" else "less"
|
||||
yield result
|
||||
|
||||
|
||||
def run(directory):
|
||||
events = read_index(directory / "events.csv", ("recovery_date",))
|
||||
observations = read_index(directory / "observations.csv", ("recovery_date", "landmark"))
|
||||
pairs = [
|
||||
match_record(events[left], events[right])
|
||||
for left, right in combinations(sorted(events), 2)
|
||||
]
|
||||
outcomes = []
|
||||
for pair in pairs:
|
||||
if pair["main_match"]:
|
||||
outcomes.extend(compare_endpoints(pair, observations))
|
||||
write_rows(directory / "pairs.csv", pairs, PAIR_FIELDS)
|
||||
write_rows(directory / "pair_outcomes.csv", outcomes, OUTCOME_FIELDS)
|
||||
for name in SCALES:
|
||||
eligible = [p for p in pairs if p[f"{name}_match"]]
|
||||
dates = {p[k] for p in eligible for k in ("left_recovery", "right_recovery")}
|
||||
print(f"{name} {len(eligible)}/{len(pairs)} 对,涉及 {len(dates)}/{len(events)} 次不同恢复")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--output-dir", type=Path, default=HERE, help="事件表、观察表与输出表所在目录")
|
||||
run(parser.parse_args().output_dir)
|
||||
Loading…
Reference in New Issue