Coverage for notebooks/src/01_signal_evaluation.py: 100%

53 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-22 12:55 +0000

1# %% [markdown] 

2# # Signal evaluation: does a score predict returns? 

3# 

4# [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/leon1706-lol/Aether-quant/blob/main/notebooks/01_signal_evaluation.ipynb) 

5# 

6# The checks the project runs on every candidate signal, on three classic crypto signals: 

7# 

8# 1. **Targets from prices.** Forward returns and their cross-sectional ranks, dated so that a score at D uses only D's close. 

9# 2. **The IC report.** The mean daily rank IC, its HAC t-statistic and a block-bootstrap interval. 

10# 3. **Returns by quantile and IC decay.** 

11# 4. **Purged folds and a leakage audit.** One signal is deliberately leaked, to show the audit catches it. 

12# 5. **Factor spanning.** Is the signal more than market (BTC) exposure? 

13 

14# %% 

15import sys 

16from pathlib import Path 

17 

18if "google.colab" in sys.modules: # Colab: install the library (numpy and pandas come with it) 

19 get_ipython().run_line_magic("pip", 'install -q "aether-quant[notebooks]"') # noqa: F821 

20else: # a clone: run against the checkout's code 

21 for parent in (Path.cwd(), *Path.cwd().parents): 

22 if (parent / "aether_quant" / "__init__.py").is_file(): 

23 sys.path.insert(0, str(parent)) 

24 break 

25 

26# %% 

27import numpy as np 

28import pandas as pd 

29 

30from aether_quant import samples, signals 

31 

32closes = samples.load_sample_prices() 

33closes = closes.loc["2023-07-13":] # every coin trades from here (XRP-USD relisted on Coinbase in July 2023) 

34returns = closes.pct_change(fill_method=None) 

35print(closes.shape, closes.index.min(), "to", closes.index.max()) 

36 

37# %% [markdown] 

38# ## Three signals, each known at D's close 

39# 

40# - **Momentum:** the trailing 20-day return. 

41# - **Reversal:** minus the trailing 5-day return. 

42# - **Low volatility:** minus the 30-day realized volatility. 

43 

44# %% 

45scores = { 

46 "momentum_20d": closes / closes.shift(20) - 1, 

47 "reversal_5d": -(closes / closes.shift(5) - 1), 

48 "low_vol_30d": -returns.rolling(30).std(), 

49} 

50 

51# %% [markdown] 

52# ## Targets, and the IC report 

53# 

54# `forward_rank_targets` builds the long table that `evaluate_signal` reads. With 11 names a day the IC is noisy, which is why the report gives a HAC t-statistic and a bootstrap interval, not just a mean. 

55 

56# %% 

57targets = signals.forward_rank_targets(closes, horizons=(5, 20)) 

58rows = [] 

59for name, frame in scores.items(): 

60 long = frame.rename_axis(index="date", columns="ticker").reset_index().melt(id_vars="date", var_name="ticker", value_name="score") 

61 table = targets.merge(long, on=["date", "ticker"]).dropna(subset=["score", "target_rank_20d"]) 

62 report = signals.evaluate_signal(table, score_column="score", splits=("validation",), min_names_per_date=8, bootstrap_draws=300) 

63 h20 = report["splits"]["validation"]["h20"] 

64 rows.append({"signal": name, "mean IC (20d)": h20["mean_ic"], "HAC t": h20["hac_t"], "CI low": h20["ci95"][0], "CI high": h20["ci95"][1], "dates": h20["num_dates"]}) 

65pd.DataFrame(rows).set_index("signal").round(3) 

66 

67# %% [markdown] 

68# ## Returns by quantile, and how the IC decays with the horizon 

69 

70# %% 

71future_5d = signals.forward_returns(closes, 5) 

72quantiles = signals.quantile_returns(scores["momentum_20d"], future_5d, n_quantiles=3) 

73print("Mean 5-day forward return by momentum tercile (1 = lowest):") 

74print((quantiles.mean() * 100).round(3).to_string()) 

75 

76decay = pd.DataFrame({name: signals.ic_decay(frame, closes, horizons=(1, 5, 10, 20, 60)) for name, frame in scores.items()}) 

77decay.index.name = "horizon (days)" 

78decay.round(3) 

79 

80# %% 

81import matplotlib.pyplot as plt 

82 

83axes = decay.plot(marker="o", figsize=(8, 3.5), title="Mean rank IC by forward horizon") 

84axes.axhline(0, color="#9ca3af", linewidth=0.8) 

85plt.show() 

86 

87# %% [markdown] 

88# ## Purged, embargoed folds 

89# 

90# A 20-day label overlaps the next 20 days. A test fold must purge training rows whose labels reach into it, and embargo a gap after it. Otherwise the model is graded on the answers it trained on. 

91 

92# %% 

93row_dates = targets["date"].to_numpy() 

94folds = signals.purged_embargoed_folds(row_dates, n_folds=4, horizon_days=20, embargo_days=5) 

95pd.DataFrame( 

96 [{"fold": n, "validation from": row_dates[val].min(), "validation to": row_dates[val].max(), "train rows": len(train), "validation rows": len(val), 

97 "purged or embargoed rows": len(row_dates) - len(train) - len(val)} for n, (train, val) in enumerate(folds, 1)] 

98).set_index("fold") 

99 

100# %% [markdown] 

101# ## A leakage audit catches a leaked signal 

102# 

103# `leaked` is the 20-day *forward* return plus noise, a feature that knows the future. The audit's single-feature IC check flags it, while the honest momentum signal passes. 

104 

105# %% 

106from aether_quant import overfitting 

107 

108audit_table = targets.merge(scores["momentum_20d"].rename_axis(index="date", columns="ticker").reset_index().melt(id_vars="date", var_name="ticker", value_name="momentum"), on=["date", "ticker"]) 

109audit_table["leaked"] = audit_table["target_return_20d"] + np.random.default_rng(0).normal(0, 0.02, len(audit_table)) 

110audit_table = audit_table.dropna(subset=["momentum", "leaked", "target_rank_20d"]).copy() 

111audit_table["split"] = np.where(audit_table["date"] < "2025-06-01", "train", "validation") 

112audit = overfitting.audit_leakage(audit_table, feature_columns=["momentum", "leaked"], min_names=8) 

113pd.DataFrame(audit["single_feature_ic"]).T.rename(columns={"ic": "mean IC on validation", "flag": "flagged (|IC| > 0.15)"}) 

114 

115# %% [markdown] 

116# ## Factor spanning: is momentum more than BTC? 

117# 

118# Regress the signal's long-short return on the market factor (BTC's daily return), with HAC errors. An alpha whose t-statistic is near zero means the signal's return is market exposure under another name. 

119 

120# %% 

121rank = scores["momentum_20d"].rank(axis=1, pct=True) 

122weights = rank.sub(rank.mean(axis=1), axis=0) 

123weights = weights.div(weights.abs().sum(axis=1), axis=0) 

124long_short = (weights.shift(1) * returns).sum(axis=1).loc["2023-09-01":] 

125market = returns["BTCUSD"].loc[long_short.index] 

126spanning = signals.factor_spanning(long_short, pd.DataFrame({"BTC": market}), periods_per_year=365) 

127print(f"alpha {spanning['alpha_annual']:.1%} a year, t {spanning['alpha_t']:.2f}; BTC beta {spanning['betas']['BTC']:.2f}; R2 {spanning['r2']:.2f}; {spanning['num_dates']} days") 

128 

129# %% [markdown] 

130# **Next:** [02 book construction](02_book_construction.ipynb). Signals become weights, neutral books, sizing and costs.