""" 阶段1:被动单聚合。 利用上交所 L2 语义——被动方 order_id 才是真实的挂单 ID: - active_buy → ask_order_id(卖方限价单被吃掉) - active_sell → bid_order_id(买方限价单被吃掉) 按被动方 order_id 聚合,提取每笔被动挂单的行为指纹特征。 """ from __future__ import annotations import numpy as np import pandas as pd def compute_vwap(trades: pd.DataFrame) -> float: """从 trades 计算当日 VWAP(成交量加权均价)。""" valid = trades if "is_cancellation" in trades.columns: valid = trades[~trades["is_cancellation"]] if valid.empty: return np.nan qty = valid["qty"].astype(float) return float((valid["price"] * qty).sum() / qty.sum()) def _compute_amount(trades: pd.DataFrame) -> pd.Series: """成交额 = price * qty(yuan)。""" return trades["price"].astype(float) * trades["qty"].astype(float) def extract_passive_orders( trades: pd.DataFrame, vwap: float | None = None, ) -> pd.DataFrame: """ 从单日 trades 提取被动单特征。 Args: trades: 单日逐笔成交 DataFrame。 必须有列: bs_flag_desc, bid_order_id, ask_order_id, price, amount, time_ms vwap: 当日 VWAP。为 None 则自动计算。 Returns: DataFrame,每行一个被动 order_id,含行为指纹特征。 """ if vwap is None or np.isnan(vwap): vwap = compute_vwap(trades) # 过滤撤单 + 空 bs_flag_desc(集合竞价/中性) if "is_cancellation" in trades.columns: trades = trades[~trades["is_cancellation"]] trades = trades[trades["bs_flag_desc"].isin(["active_buy", "active_sell"])].copy() # 计算成交额 trades["_amount"] = _compute_amount(trades) rows = [] # active_buy → ask_order_id 是真正的卖方挂单(被动卖出) buy_trades = trades[trades["bs_flag_desc"] == "active_buy"] rows.extend(_aggregate_side(buy_trades, "ask_order_id", "ask", vwap)) # active_sell → bid_order_id 是真正的买方挂单(被动买入=承接) sell_trades = trades[trades["bs_flag_desc"] == "active_sell"] rows.extend(_aggregate_side(sell_trades, "bid_order_id", "bid", vwap)) df = pd.DataFrame(rows) if df.empty: return df # 日内时段归一化 [0, 1]:9:30=0, 15:00=1 df["time_centroid"] = (df["time_centroid_raw"] - 34_200_000) / ( 54_000_000 - 34_200_000 ) df["time_centroid"] = df["time_centroid"].clip(0, 1) # 价格偏离 (bps) if vwap and not np.isnan(vwap): df["avg_price_bps"] = ((df["avg_price"] / vwap) - 1) * 10000 else: df["avg_price_bps"] = 0.0 # 对数额外特征 df["log_amount"] = np.log1p(df["total_amount"]) df["log_duration"] = np.log1p(df["duration_sec"]) df["log_trade_count"] = np.log1p(df["trade_count"]) # 过滤无意义的单笔单(无节奏信息) df["cv_interval"] = df["cv_interval"].fillna(0) return df def _aggregate_side( trades: pd.DataFrame, passive_col: str, side: str, vwap: float, ) -> list[dict]: """聚合某个方向(bid 或 ask)的被动单。""" rows = [] for oid, grp in trades.groupby(passive_col): if oid == 0: continue # 跳过无效 order_id grp = grp.sort_values("time_ms") times = grp["time_ms"].values.astype(float) prices = grp["price"].values.astype(float) qtys = grp["qty"].values.astype(float) amounts = grp["_amount"].values.astype(float) # 成交间隔 if len(times) > 1: intervals = np.diff(times) / 1000.0 # 秒 cv = float(intervals.std() / intervals.mean()) if intervals.mean() > 0 else 0.0 else: cv = 0.0 # VWAP for this passive order (weighted by qty) total_qty = qtys.sum() order_vwap = float(np.average(prices, weights=qtys)) if total_qty > 0 else prices.mean() rows.append({ "order_id": int(oid), "side": side, "total_amount": float(amounts.sum()), "total_qty": float(total_qty), "avg_price": order_vwap, "trade_count": len(grp), "time_centroid_raw": float(np.average(times, weights=amounts)) if amounts.sum() > 0 else float(times.mean()), "first_time_ms": int(times.min()), "last_time_ms": int(times.max()), "duration_sec": float((times.max() - times.min()) / 1000.0), "cv_interval": cv, "price_min": float(prices.min()), "price_max": float(prices.max()), "price_range_bps": float((prices.max() - prices.min()) / vwap * 10000) if vwap and vwap > 0 else 0.0, }) return rows def select_candidates( passive_orders: pd.DataFrame, top_n: int = 150, ) -> pd.DataFrame: """取成交额 top N 的被动单作为主力候选。""" if passive_orders.empty: return passive_orders return passive_orders.nlargest(top_n, "total_amount").copy() # 聚类 & 匹配用的 7 维特征列 FEATURE_COLS = [ "log_amount", "avg_price_bps", "time_centroid", "log_duration", "cv_interval", "side_num", # 0=bid, 1=ask — clustering 阶段填入 "price_range_bps", ] def prepare_features(candidates: pd.DataFrame) -> np.ndarray: """将候选 DataFrame 转为 (N, 7) 聚类特征矩阵。""" df = candidates.copy() df["side_num"] = df["side"].map({"bid": 0, "ask": 1}).fillna(0.5) # 日级 min-max 归一化 feats = df[FEATURE_COLS].values.astype(np.float64) # 处理 inf/nan feats = np.nan_to_num(feats, nan=0.0, posinf=0.0, neginf=0.0) # 每列 min-max f_min = feats.min(axis=0, keepdims=True) f_max = feats.max(axis=0, keepdims=True) denom = f_max - f_min denom[denom == 0] = 1.0 feats = (feats - f_min) / denom return feats