横截面因子、信息系数与分层回测
按可知时点构建因子、固定排名和组合,再用未来标签评价预测与成本。
学完这一章,你能够
- 按可知时点构建因子、固定排名和组合,再用未来标签评价预测与成本。
把因子定义和输入日期写清
时间序列策略比较同一标的的不同时点,横截面策略在同一决策时点比较多个标的。因子是可计算的特征,预测方向需要检验。动量可以用 120 个交易观测的价格变化,等于同口径价格除以前 120 条再减 1。真实下载要明确复权、股票代码与列层级。
价值、质量和规模可以分别用盈利收益率、权益收益率和市值表示。负盈利不直接当作低市盈率,市场价格与报告数字的单位要一致。本例依报告可知日选择记录,未来披露不得回填。四类因子按方向转为分位排名,再等权组合,缺任一输入则留空。
月度信息系数以可知因子对未来标签
保留真正的月末会话日期,本站用该会话收盘时可知的因子建组,下一个会话开盘执行。未来标签从本期执行价量到下一期执行价,只参与评价。前 120 条是预热,缺少下一执行日的期末记录不构造标签。
每期 Spearman IC 使用共同且有有效观测的标的。报告配对数量、方向、均值、样本标准差与正比例。常量排序、观察数不足或 IC 标准差为零时相应统计无定义。ICIR 在本例指 IC 均值除以样本标准差,未经年化。0.03 或 0.3 一类阈值只是经验,不能代替不确定性估计。
合成数据包含方向切换。按训练期已完整落地的标签锁定因子方向,边界处尚未兑现的训练标签剔除。单期负 IC 或小样本历史负均值不直接证明某个市场长期反转,也不应用同一份留出结果改方向再当检验。
持仓由当时排名决定
固定小样本中按分数排序,分数相同时按标的代码稳定排序,再切成五组。每组期初等权,按照实现收益和漂移后的旧权重算实际换手。股票池必须按当时可交易集合重建,使用当前成分回看会引入幸存者偏差。
建组只看当时分数,不能先根据未来收益是否缺失来删除标的。实验验证少于 15 条分数时跳过该期,未来持仓缺收益时组结果继续缺失。示例的完整行情可以直接连乘各期净收益。真实缺失、停牌、退市或空组须事先约定处理。
图中五组按各自实际月度净收益连乘,虚线标出留出边界。几何年化从实际净值计算,不能用月算术均值复利冒充。多空差应由同频双腿组合逐期记账,考虑杠杆、卖空、交易费与借券,不能直接减两组 CAGR。

扩展因子时继续验证
扩大股票池时要保存历史成分、退市与复权版本,可分别研究行业或市值中性化。按市场、日期和模型训练范围保存分层稳定性、交易约束、交易费与检验次数。Alphalens 等工具可组织诊断,本例仅独立运行本地算法。
四类可观测特征
| 类别 | 一个可计算口径及限制 |
|---|---|
| 动量 | 同口径收盘的 120 观测变动 |
| 价值 | 已披露盈利除以同口径价格,明确负值政策 |
| 质量 | 以报告可知日使用 ROE,负净资产等条件分开 |
| 规模 | 按同一时点总市值,示例把小市值排到较高方向 |
月度 IC 的判读
| 字段 | 含义与边界 |
|---|---|
| 绝对值 | 同时记录样本量、离散度、区间和基准 |
| 符号 | 表示该段样本的秩关系,可随时期切换 |
| ICIR | 本实验是均值除以样本标准差,常量时留空 |
分层研究可重跑的四步
| 步骤 | 对应证据 |
|---|---|
| 构建 | 保留预热、交易日和发布时间 |
| 检验 | 标注有效配对、样本内外日期与冻结方向 |
| 分层 | 只按当时分数决定组别,观察真实换手和净值 |
| 结论 | 合成实验仅说明流程,历史股票数值须单独复现 |
运行点时因子、Spearman IC 和五层组合
"""Point-in-time ranking and five-layer portfolio research on synthetic data."""
import json
from pathlib import Path
from platform import python_version
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import scipy
from scipy.stats import spearmanr
def eligible_financials(reports, decision):
return (reports.loc[reports.available<=decision].sort_values("available")
.drop_duplicates("symbol",keep="last").set_index("symbol"))
def score_case():
assets=list("ABCDE")
reports=pd.DataFrame({"symbol":assets+["A"],"available":pd.to_datetime(
["2024-01-01"]*5+["2024-03-05"]),"earnings":[5,4,3,2,-1,20],
"roe":[.16,.18,.10,.12,.09,.80],"cap":[70,30,50,45,20,70]})
decision=pd.Timestamp("2024-02-29")
at_time=eligible_financials(reports,decision)
at_later=eligible_financials(reports,pd.Timestamp("2024-03-06"))
assert at_time.loc["A","earnings"]==5 and at_later.loc["A","earnings"]==20
close=pd.Series([50,50,40,25,20],index=assets,dtype=float)
momentum=pd.Series([.04,.02,.05,.01,.03],index=assets)
factors=pd.DataFrame({"momentum":momentum,"value":(at_time.earnings/close).where(at_time.earnings>0),
"quality":at_time.roe,"small_size":-at_time.cap})
ranks=factors.rank(pct=True,method="average")
combined=ranks.mean(axis=1,skipna=False)
assert pd.isna(combined.loc["E"]) and combined.notna().sum()==4
assert ranks.loc["E","small_size"]==1
return dict(known_earnings_a=int(at_time.loc["A","earnings"]),later_earnings_a=int(at_later.loc["A","earnings"]),
excluded_invalid_value=combined[combined.isna()].index.tolist(),
combined=combined.dropna().round(6).to_dict())
def group_assets(scores):
"""Stable tie order by symbol. All groups exist when enough scores exist."""
ordered=scores.dropna().sort_index().sort_values(kind="stable")
if len(ordered)<15:
return None
return [list(group) for group in np.array_split(ordered.index.to_numpy(),5)]
def evaluate_ic(scores,future):
paired=pd.concat([scores.rename("score"),future.rename("label")],axis=1,join="inner").dropna()
if len(paired)<15 or paired.score.nunique()<2 or paired.label.nunique()<2:
return None
return float(spearmanr(paired.score,paired.label).statistic)
def panel():
rng=np.random.default_rng(51)
index=pd.bdate_range("2022-01-03","2024-12-31")
names=[f"S{i:02d}" for i in range(20)]
exposure=np.linspace(-1,1,20)
months=(index.year-2022)*12+index.month-1
direction=np.where(months//6%2==0,1,-1)
daily=.00025+np.asarray(direction)[:,None]*exposure[None,:]*.0018+rng.normal(0,.0015,(len(index),20))
return pd.DataFrame(100*np.cumprod(1+daily,axis=0),index=index,columns=names)
def layers(output):
close=panel()
momentum=close/close.shift(120)-1
assert momentum.iloc[:120].isna().all().all() and momentum.iloc[120].notna().all()
observations=close.groupby(close.index.to_period("M")).tail(1).index
gaps=.0007*np.sin(np.arange(len(close))[:,None]+np.arange(len(close.columns)))
openings=close.shift()*(1+gaps)
ranked, label_dates, raw_ics, layer_rows, turnovers = [], [], [], [], []
drifted=[pd.Series(0.,index=close.columns) for _ in range(5)]
for current,next_month in zip(observations[:-1],observations[1:]):
scores=momentum.loc[current]
groups=group_assets(scores)
if groups is None:
continue
start=close.index.get_loc(current)+1
end=close.index.get_loc(next_month)+1
if end>=len(close):
continue
future=openings.iloc[end]/openings.iloc[start]-1
assert close.index[start]>current and close.index[end]>next_month
ic=evaluate_ic(scores,future)
assert ic is not None
row=[]; turnover=[]
for index,group in enumerate(groups):
target=pd.Series(0.,index=close.columns)
target.loc[group]=1/len(group)
assert len(group)==4 and np.isclose(target.sum(),1)
gross=float(future.loc[group].mean())
traded=float((target-drifted[index]).abs().sum())
net=(1+gross)*(1-.001*traded)-1
drifted[index]=target*(1+future)/(1+gross)
assert np.isclose(drifted[index].sum(),1)
row.append(net)
turnover.append(traded)
ranked.append(current); label_dates.append(close.index[end]); raw_ics.append(ic)
layer_rows.append(row); turnovers.append(turnover)
assert len(ranked)>18
ics=pd.Series(raw_ics,index=ranked)
realized=pd.DataFrame(layer_rows,index=pd.DatetimeIndex(label_dates),columns=list("12345"))
turnover=pd.DataFrame(turnovers,index=realized.index)
assert (turnover.iloc[0]==1).all()
train=ics.loc[ics.index<"2024-01-01"]
test=ics.loc[ics.index>="2024-01-01"]
# Purge training labels whose measurement finishes after the split.
train=train.loc[[label<pd.Timestamp("2024-01-01") for label in
pd.Series(label_dates,index=ranked).loc[train.index]]]
assert len(train)>8 and len(test)>8
selected_direction=1 if train.mean()>=0 else -1
wealth=(1+realized).cumprod()
cagr=(1+realized).prod()**(12/len(realized))-1
assert not np.allclose(cagr,(1+realized.mean())**12-1)
assert (ics>0).any() and (ics<0).any()
tied=pd.Series([1.]*20,index=close.columns)
assert all(len(g)==4 for g in group_assets(tied))
assert tied.rank(method="average",pct=True).nunique()==1
assert evaluate_ic(tied,pd.Series(np.arange(20),index=close.columns)) is None
missing=momentum.loc[ranked[0]].copy()
missing.iloc[:6]=np.nan
assert group_assets(missing) is None
simulated_future_missing=pd.Series(np.ones(20),index=close.columns)
original_groups=group_assets(momentum.loc[ranked[0]])
simulated_future_missing.loc[original_groups[0][0]]=np.nan
assert group_assets(momentum.loc[ranked[0]])==original_groups
assert pd.isna(simulated_future_missing.loc[original_groups[0]].mean(skipna=False))
fig,ax=plt.subplots(figsize=(8,4.2),layout="constrained")
for col in wealth:
ax.plot(wealth[col],label=f"Group {col}")
ax.axvline(pd.Timestamp("2024-01-01"),color="#526576",linestyle="--",label="Holdout boundary")
ax.set(title="Five synthetic momentum layers after turnover costs",xlabel="Interval end",
ylabel="Equity from 1")
ax.grid(alpha=.2); ax.legend(ncols=3); fig.savefig(output,dpi=120); plt.close(fig)
return dict(factor=dict(input_shape=list(close.shape),lookback_sessions=120,
first_factor_date=str(momentum.dropna().index[0].date())),
ic=dict(periods=len(ics),mean=float(ics.mean()),sample_std=float(ics.std()),icir=float(ics.mean()/ics.std()) if ics.std()>0 else None,
positive_rate=float((ics>0).mean()),train_count=len(train),test_count=len(test),
fixed_training_direction=selected_direction,holdout_signed_ic=float(test.mean()*selected_direction),
tied_or_incomplete_skipped=True),
layers=dict(first_signal=str(ranked[0].date()),first_label_end=str(label_dates[0].date()),
terminal_equity=wealth.iloc[-1].to_dict(),compounded_annual=cagr.to_dict(),
mean_turnover=turnover.mean().tolist(),average_monthly_net=realized.mean().to_dict(),
future_missing_keeps_membership=True,missing_group_return_preserved=True))
if __name__=="__main__":
result=layers(Path("factor-layers.png"))
result["score"]=score_case()
result["versions"]=dict(python=python_version(),numpy=np.__version__,pandas=pd.__version__,
scipy=scipy.__version__,matplotlib=matplotlib.__version__)
print(json.dumps(result,indent=2,allow_nan=False))
- 每层四个标的。发布时间晚的报告不会进入早期评分。未来缺失不改变持仓名单,缺值保留。程序输出冻结训练方向与五组净值。
所需环境:隔离 CPython 3.12.14、Pandas 3.1.0、SciPy 1.18.1、NumPy 2.5.4、Matplotlib 3.11.2
当前源码 SHA256:353ba9770db71908613aec8cec33ef343fd746113daba45f141d8e98c273fb5c
本地实验包
解压按 README 安装依赖,运行 Python 程序并查看分层曲线与 JSON 输出。
所需环境:隔离 CPython 3.12.14、Pandas 3.1.0、SciPy 1.18.1、NumPy 2.5.4、Matplotlib 3.11.2
ZIP SHA256:75e80b944f61ed8cbbdb852a6cce26c674fd87043a8a145eea8cdf4f6c70aec0
常见错误与边界
- 评分、成交、兑现标签与留出日期应分别保存。
练习与解答
为什么不能在分层前先删掉下一期收益缺失的标的?
展开参考解答
下一期是否有数据是将来才知道的。用它筛选当前组合会让回测获得当时不可知的信息。