"""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))
本例需在 隔离 CPython 3.12.14、Pandas 3.1.0 与 Matplotlib 3.11.2 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:隔离 CPython 3.12.14、Pandas 3.1.0 与 Matplotlib 3.11.2
入口文件:projects/quant-cleaning/cleaning.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
cleaning.py,或下载右侧课程工程包。 - 确认本地已准备 隔离 CPython 3.12.14、Pandas 3.1.0 与 Matplotlib 3.11.2。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a304.zip
课程关联工程包(登记关联20章) · 含当前章节或实例 · mbskycom202612a303.zip