量化时间序列清洗与时点对齐
用可复现的合成行情检查缺失、异常标记、周月聚合及跨标的对齐。
学完这一章,你能够
- 用可复现的合成行情检查缺失、异常标记、周月聚合及跨标的对齐。
保存缺失原因与可用时点
先保留供应商原始记录、交易所时间、标的与缺失原因。停牌、尚未上市、市场闭市、行情漏传和有效的零成交量需要分开。遇到确定的漏传,先补取可验证数据。清洗产物保留原值、标记、处置与对应版本。
本例把六行价格 [缺失, 100, 缺失, 缺失, 缺失, 105] 用 ffill(limit=2) 生成估值序列。开头没有旧报价,所以仍空。连续三处缺失只有前两处沿用 100,超过上限继续为空。可成交掩码仍读原始记录,估值点 100 不构成新报价。limit 是按连续缺失行计数,跨市场和不规则时间戳还要另设时间上限。
样本中直接对未填充的原价运行 pct_change(fill_method=None),相邻原始价格对有缺失,结果保持缺失。若用于估值并明确用旧价填充,期间的零变化应带有估值标记。bfill 会把随后出现的 100 写到首行,用全样本均值或中位数也可能使用未来数据。删除行前要确认是否会把跨多日变化当作单日变化。
异常先标记,再求证
用已知历史窗口的均值和样本标准差计算 3σ 阈值,或按 Q1、Q3 与 1.5 倍四分位距标记候选。演示的两条候选是 −10% 和 +36%。−10% 在合成注释中有对应市场事件,保留。+36% 有单独证据表明小数点错误,修正为 +0.36% 并保留原值。零价、复权漏调和数据误差都需要单独判因。
阈值用于即时决策时,滚动计算先 shift(1) 再 rolling,预热不足不判定。本例修改第 40 行价格变化时,该行阈值不动。真实市场尾部可以很厚,价格跌到制度边界也可能是真实变化。跨标的、制度变化和取样窗口会改变阈值。
除权价差用独立公司行动数据解释。用前收 100、除息参考 96、当日收盘 97 比较,原始收盘变化 −3%,调整口径变化约 +1.0417%。可用调整价分析连续收益,成交、限价及现金账保留原价和事件明细。
周月标签与观察时间分别保留
Pandas 的 W-FRI 和 ME 按周五、月末分桶。示例显式设置 closed='right' 与 label='right'。2025 年 1 月 3 日是桶标签,桶里最后的真实样本来自 1 月 2 日。1 月 31 日月标签也可以对应 1 月 13 日的未完结样本。回测要记录数据到达和策略可用时间,未完结周期和已完结周期分别处理。
聚合 OHLC 时用开盘首值、最高最大值、最低最小值、收盘末值,成交量求和并要求至少一个非空观察。全缺失的成交量继续为空。只取末值的收盘与从当期末标签向前标注的数据可用性是两回事。单列 last 默认跳过空值,缺失是否允许跳过要提前定义。
图中圆点为日收盘,方块画在周桶最后实际观察日期。若改画到桶标签,横轴位置会移动。把日线降为周线可以丢弃细节,把周线插回日线只生成插值,无法恢复真实成交记录。
对齐时保留缺腿与报价年龄
把交易时间换到同一时区,再明确按会话还是按真实时点对齐。外连接保留任一标的存在的日期,分子或分母缺失则比值为空。内连接只保留共同日期,本例剩 1 月 2 日和 1 月 6 日。用于估值的限定向前填充可额外产生比值,但标记报价沿用,后续检查零分母和过期报价。
需要在决策时间查另一市场最近报价时,按时间排序后用 merge_asof(direction='backward', tolerance='2min')。样本在 10:01 可用 10:00 的报价,在 10:05 既不能用过期的 10:00 报价,也不能取 10:06 的未来报价。比值、价差和协整等研究应保留这一时间约束。
常见数据问题及处置
| 问题 | 先核实的条件 | 处理和后续限制 |
| 缺失 | 停牌、未上市、休市、漏传 | 保留原样与原因,限量向前估值或剔除,执行使用真实报价 |
| 异常候选 | 事件、精度、单位和公司行动 | 用已知数据标记,只有证据支持时改正 |
| 价格断点 | 复核除权除息及行情原价 | 记录复权口径与现金事件,交易仍走原价 |
| 采样不齐 | 时区、会话、桶标签和真实观察时点 | 先按字段聚合,按共同日期或可知报价对齐 |
运行离线缺失、异常、聚合与对齐实验
展开查看收起
"""Reproducible time-series cleaning with synthetic prices and timestamps."""
import json
from pathlib import Path
import platform
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import pandas as pd
def values(series):
return [None if pd.isna(value) else round(float(value), 8) for value in series]
def labels(index):
return index.strftime("%Y-%m-%d").tolist()
def missing_case():
prices = pd.Series([None, 100, None, None, None, 105], dtype="float64")
valued = prices.ffill(limit=2)
observed_returns = prices.pct_change(fill_method=None)
assert values(valued) == [None, 100, 100, 100, None, 105]
assert values(observed_returns) == [None] * 6
assert pd.isna(valued.iloc[0]) and prices.bfill().iloc[0] == 100
# An as-of mark is separate from the unmodified, executable quote series.
executable = prices.notna()
assert not executable.iloc[2] and valued.iloc[2] == 100
return dict(raw=values(prices), marks=values(valued), executable=executable.tolist(),
observed_returns=values(observed_returns), bfill_first=float(prices.bfill().iloc[0]))
def anomaly_case():
changes = pd.Series([-.012, -.006, 0, .006, .012] * 8 + [-.1, .36], dtype="float64")
history = changes.iloc[:40]
sigma = history.std(ddof=1)
q1, q3 = history.quantile([.25,.75])
iqr = q3 - q1
candidates = (changes-history.mean()).abs() > 3*sigma
outside_iqr = (changes < q1-1.5*iqr) | (changes > q3+1.5*iqr)
# Fixture annotations stand in for independent exchange or vendor evidence.
confirmed_corrections = {41: .0036}
cleaned = changes.copy()
for index, corrected in confirmed_corrections.items():
cleaned.loc[index] = corrected
rolling = changes.shift(1).rolling(20, min_periods=20)
rolling_threshold = rolling.mean() + 3*rolling.std(ddof=1)
assert candidates[candidates].index.tolist() == outside_iqr[outside_iqr].index.tolist() == [40, 41]
assert cleaned.loc[40] == -.1 and cleaned.loc[41] == .0036
assert rolling_threshold.isna().iloc[:20].all()
changed = changes.copy()
changed.iloc[40] = .9
alternate = changed.shift(1).rolling(20, min_periods=20)
assert rolling_threshold.loc[40] == (alternate.mean() + 3*alternate.std()).loc[40]
return dict(prior_mean=float(history.mean()), prior_std=float(sigma), iqr=float(iqr),
sigma_flags=candidates[candidates].index.tolist(), iqr_flags=outside_iqr[outside_iqr].index.tolist(),
source=values(changes.iloc[-2:]), reviewed=values(cleaned.iloc[-2:]),
no_future_at_row_40=True)
def corporate_action():
raw = pd.Series([100., 97.])
adjusted = pd.Series([96., 97.])
before, after = (float(series.pct_change(fill_method=None).iloc[1]) for series in (raw, adjusted))
assert round(before, 8) == -.03 and round(after, 8) == .01041667
return dict(raw=values(raw), adjusted=values(adjusted), raw_return=before, adjusted_return=after)
def aggregation(output):
frame = pd.DataFrame({
"open":[98, 101, 103, 102, 108, 109, 105],
"high":[102, 105, 106, 109, 110, 112, 110],
"low":[97, 99, 101, 100, 104, 104, 103],
"close":[101, 103, 104, 108, 109, 105, 108],
"volume":[500, 700, 550, 600, 0, None, 900],
},index=pd.to_datetime(["2024-12-26","2024-12-27","2024-12-30","2025-01-02",
"2025-01-06","2025-01-07","2025-01-13"]))
def roll(rule):
group = frame.resample(rule, closed="right", label="right")
result = group.agg({"open":"first","high":"max","low":"min","close":"last"})
result["volume"] = group["volume"].sum(min_count=1)
result["last_observed_date"] = pd.Series(frame.index,index=frame.index).resample(
rule, closed="right", label="right").last()
return result
weekly, monthly = roll("W-FRI"), roll("ME")
assert values(weekly["close"]) == [103, 108, 105, 108]
assert weekly.iloc[0][["open","high","low","close","volume"]].tolist() == [98,105,97,103,1200]
assert values(monthly["close"]) == [104,108]
assert weekly.index[1] == pd.Timestamp("2025-01-03")
assert weekly["last_observed_date"].iloc[1] == pd.Timestamp("2025-01-02")
assert monthly.index[-1] == pd.Timestamp("2025-01-31")
assert monthly["last_observed_date"].iloc[-1] == pd.Timestamp("2025-01-13")
assert weekly["volume"].iloc[2] == 0
blank_volume = frame["volume"].iloc[5:6].resample("W-FRI").sum(min_count=1)
assert pd.isna(blank_volume.iloc[0])
fig, ax = plt.subplots(figsize=(8,3.7),layout="constrained")
ax.plot(frame.index,frame["close"],"o-",color="#31475b",label="Daily close")
ax.plot(weekly["last_observed_date"],weekly["close"],"s--",color="#007d68",
label="Weekly close on last observation")
ax.set(title="Daily closes and their weekly samples",ylabel="Synthetic price")
ax.grid(alpha=.2)
ax.legend()
fig.autofmt_xdate()
fig.savefig(output,dpi=120)
plt.close(fig)
return dict(weekly_labels=labels(weekly.index), weekly_observations=labels(weekly["last_observed_date"].dt),
weekly_closes=values(weekly["close"]), weekly_volumes=values(weekly["volume"]),
monthly_labels=labels(monthly.index), monthly_observations=labels(monthly["last_observed_date"].dt),
monthly_closes=values(monthly["close"]), missing_volume_is_unknown=True)
def aligned_quotes():
a = pd.Series([100.,105.,106.],index=pd.to_datetime(["2025-01-02","2025-01-03","2025-01-06"]))
b = pd.Series([50.,52.,53.],index=pd.to_datetime(["2025-01-02","2025-01-06","2025-01-07"]))
a_outer,b_outer = a.align(b,join="outer")
simultaneous = a_outer/b_outer
marked = a_outer.ffill(limit=1)/b_outer.ffill(limit=1)
inner_a,inner_b = a.align(b,join="inner")
assert labels(inner_a.index) == ["2025-01-02","2025-01-06"]
assert values(simultaneous) == [2.,None,round(106/52,8),None]
assert values(marked) == [2.,2.1,round(106/52,8),2.]
decisions = pd.DataFrame({"decision":pd.to_datetime(["2025-01-06 10:01Z","2025-01-06 10:05Z"])})
quotes = pd.DataFrame({"quote":pd.to_datetime(["2025-01-06 10:00Z","2025-01-06 10:06Z"]),
"price":[52.,53.]})
asof = pd.merge_asof(decisions,quotes,left_on="decision",right_on="quote",direction="backward",
tolerance=pd.Timedelta("2min"))
assert values(asof["price"]) == [52.,None]
assert asof["quote"].iloc[0] < asof["decision"].iloc[0]
return dict(outer_dates=labels(a_outer.index), simultaneous=values(simultaneous),
carried_marks=values(marked), common_dates=labels(inner_b.index),
asof_prices=values(asof["price"]), matched_utc=str(asof["quote"].iloc[0]))
def run(output):
return {
"versions":{"python":platform.python_version(),"pandas":pd.__version__,"matplotlib":matplotlib.__version__},
"missing":missing_case(),"outliers":anomaly_case(),"corporate_action":corporate_action(),
"aggregation":aggregation(output),"alignment":aligned_quotes(),
}
if __name__ == "__main__":
print(json.dumps(run(Path("weekly-samples.png")),indent=2,allow_nan=False))
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
离线实验包
解压后阅读 README。运行 Python 程序查看各分支输出,目录中生成周线取样对比图。
本章附件与实例包
常见错误与边界检查
- 保留原始缺失与报价时点。人工估值、异常标记和真正成交使用不同字段。
技术规范与官方资料
练习与参考解答
查看参考解答
周五定义采样桶边界。该桶最后有效观察可能来自周四,应同时保存观察日期、标签和数据可用时点。