蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行点时因子、Spearman IC 和五层组合

PYTHON隔离 CPython 3.12.14、Pandas 3.1.0、SciPy 1.18.1、NumPy 2.5.4、Matplotlib 3.11.2factor.py
factor.py159 行
"""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 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:隔离 CPython 3.12.14、Pandas 3.1.0、SciPy 1.18.1、NumPy 2.5.4、Matplotlib 3.11.2

入口文件:projects/quant-factor/factor.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 factor.py,或下载右侧课程工程包。
  2. 确认本地已准备 隔离 CPython 3.12.14、Pandas 3.1.0、SciPy 1.18.1、NumPy 2.5.4、Matplotlib 3.11.2。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:量化交易

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a306.zip

下载课程关联工程包:量化交易

课程关联工程包(登记关联20章) · 含当前章节或实例 · mbskycom202612a303.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习