171 lines
7.0 KiB
Python
171 lines
7.0 KiB
Python
"""按预先固定的容差比较不同宽基恢复后的第一次微盘卖压。"""
|
||
|
||
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)
|