Signal research: from data to evaluated forecasts
Formalize alpha research through signal information coefficients, decay and turnover; relate skill, breadth and information ratio; and study neutralization, shrinkage, triple-barrier labels, meta-labeling and research logs.
After this lesson you can
- Define cross-sectional and time-series signals and evaluate Pearson and rank IC, stability and horizon decay.
- Derive the fundamental law IR ≈ IC·√breadth and its transfer-coefficient version.
- Neutralize signals against risk factors and combine them using shrunk weights.
- Build triple-barrier labels and apply meta-labeling to position sizing.
- Maintain a reproducible trial log for later deflation of results.
Before you start
- 28Fama-MacBeth procedureCharacteristic-sorted portfoliosSharpe ratioFactor covariance structureJensen's alphaMultiple testing in factor discovery
- 05Pearson, Spearman and Kendall correlation coefficients
- 11Confusion matrix and derived metricsROC curve and AUCGradient boosting machineClassifier calibration
- 00Complete seeding of a training runExperiment metric tracking
A signal needs a clock and universe
A signal is information available at a date used to form a prediction, not the future return we want to explain. A cross-sectional signal ranks assets on the same date; a time-series signal compares an asset’s opportunity over time. Before measuring it, fix universe, availability date, entry price, horizon, costs and treatment of assets entering or leaving. A feature published after the close cannot decide a trade executed at that same close without another assumption.
The cross-sectional information coefficient (IC) is correlation between prediction and subsequent return across assets on a date. Pearson measures linear association; Spearman correlates ranks and is less sensitive to extreme magnitudes, but measures a different object. Calculate one IC observation per date, then its mean and dispersion. A small positive IC may matter if persistent, but 0.05 is not universally excellent: horizon, universe, costs and uncertainty matter.
For example, if a feature is published Tuesday after the close, a rule knowing it that Tuesday can decide to trade from the next executable opportunity. For a one-period horizon, correlate predictions available at with returns after entry, not returns contributing to the signal calculation. Reconstruct the universe using assets eligible then, including those that later disappeared; using only survivors can bias results. Define treatment of missing data and assets without cross-sectional variation in advance.
The naive standard error of the mean is if ICs are independent. Overlapping returns, persistent signals and shared regimes can create autocorrelation. The Newey-West HAC estimator sums weighted autocovariances; it requires a bandwidth choice and does not fix information leakage or trial selection. A pointwise band calculated after repeatedly looking at the data also does not automatically retain coverage under an adaptive stopping rule.
With and Bartlett weights, one estimate is
The ratio is an approximate test statistic, not a probability that the signal works. Its interpretation requires sufficient-sample assumptions and a hypothesis defined before observing results. Choosing solely to obtain significance adds another research decision.
From skill to breadth
The fundamental law of active management summarizes, under idealized assumptions, , where is mean active return divided by its risk and is the number of independent bets per year. To see the square root, consider independent bets with mean contribution and common standard deviation : their sum has mean and deviation , so the ratio is . Identifying with IC additionally requires the law’s forecasting model, standardization and optimal portfolio; it is not an identity for every sign portfolio. Grinold develops the framework.
With constraints, incorporates a transfer coefficient measuring how much information becomes positions in the corresponding formulation. Short-sale, sector, risk or turnover constraints can reduce it. Clarke, de Silva and Thorley study the generalized law. Costs, estimation errors and regime changes reduce the net result, and future is unknown.
If equally weighted bets have equal variance and common correlation , their sum’s variance is times individual variance. For this sum, reproduces the same ratio as independent bets. Multiplying by frequencies is valid only if periods are independent. There is no single effective-breadth formula for every correlation matrix and portfolio.
Decay, exposure and combination
Signal decay compares the prediction at with future returns over several horizons. If with , its half-life is periods. In data, overlapping horizons share returns and a straight line on a log scale is only a model: a noisy, negative or nonmonotonic curve may have no identifiable half-life. Turnover measures portfolio change, not the same thing as IC decay; both affect implementation cost.
Neutralization and combination require factors available at the date. For exposure matrix including a constant and industries or beta estimated from past information, least-squares residual is orthogonal to columns of in the cross-sectional sample used. Weights, missing values and constraints change that property. Neutralizing the signal does not guarantee a neutral portfolio after truncation, limits or weight transformation: check final exposure.
To combine correlated signals, a linear rule estimates covariance and their relationship with returns in training, shrinks covariance toward a stable matrix and applies fixed weights in testing. Inverting a noisy matrix or choosing weights after seeing test results can produce an apparently superior combination through overfitting. Comparison should include each signal, a simple blend and costs over the same period.
Labels and positions
Triple-barrier labeling defines an upper threshold, lower threshold and maximum time per event. The first observed barrier determines exit; if time expires, specify whether zero or the return’s sign is used. Scaling thresholds by volatility estimated up to the start adapts their size to the regime without using future volatility. With discrete prices, a jump can overshoot the barrier and the first observed price need not be the exact level or guarantee a fill.
An event open between start and exit shares returns with overlapping events. If is the number of events active at an instant, an event’s uniqueness can be defined as the average of over its life. These weights reduce redundant observations’ influence but do not make the set independent. When splitting training and test, purge training examples whose label windows cross the split and calculate training weights without later events.
For example, two events active over discrete intervals and share step 2. Concurrency is 1, 2 and 1 at steps 1, 2 and 3; each event’s uniqueness is . A time split must consider each label’s full interval, not just its start date. In validation with several blocks it may be necessary to purge around each block and apply an embargo according to dependence and feature windows.
Meta-labeling separates a primary rule proposing direction from a second model deciding whether to filter or size that proposal. The secondary label indicates whether the rule’s signed result was positive under the chosen barriers and cost convention. Precision, recall and F1 answer different questions; improving precision by trading less does not guarantee greater profitability or net Sharpe. A probabilistic classifier requires calibration and temporal validation before converting probabilities into sizes.
The research log retains every attempt, including discarded ones: hypothesis, data version or hash, universe, windows, parameters, seeds, metrics, costs, date and decisions. Counting trials is necessary for later multiple-selection analysis, but a count alone does not automatically correct their dependence or unrecorded trials.
Lab: planted signal
We generate 320 dates and 200 assets. The latent AR(1) signal has and stationary variance one. It is assumed available at the boundary before the next return begins, without entry cost. The subsequent one-period return is , so population IC at one period is 0.03 and that of the point return at horizon is . These are synthetic units, not historical data. The fixed factor added to one signal is available from the start; neutralization is fitted per date. The final period is reserved to compare combinations.
import numpy as np
from scipy.stats import rankdata
rng=np.random.default_rng(282401); T,N=320,200; rho=.9; ic_real=.03
z=np.empty((T,N)); z[0]=rng.normal(size=N)
for t in range(1,T): z[t]=rho*z[t-1]+np.sqrt(1-rho*rho)*rng.normal(size=N)
rend=np.zeros((T,N)); rend[1:]=ic_real*z[:-1]+np.sqrt(1-ic_real**2)*rng.normal(size=(T-1,N))
factor=rng.normal(size=N); sector=(np.arange(N)%4==0).astype(float)
F=np.c_[np.ones(N),factor,sector]
senal=z+.7*factor; alternativa=z+1.2*rng.normal(size=(T,N))
def correlacion_filas(a,b):
a=a-a.mean(axis=1,keepdims=True); b=b-b.mean(axis=1,keepdims=True)
den=np.sqrt((a*a).sum(axis=1)*(b*b).sum(axis=1))
return np.sum(a*b,axis=1)/den
def hac_error(v,lag):
v=np.asarray(v,float); n=len(v); d=v-v.mean(); lag=min(lag,n-1)
var=d@d/n+2*sum((1-k/(lag+1))*np.dot(d[k:],d[:-k])/n for k in range(1,lag+1))
return np.sqrt(max(0.,var)/n)
horizontes=(1,2,4,6,8,10)
for h in horizontes:
vals=correlacion_filas(z[:-h],rend[h:])
se=hac_error(vals,h-1)
print('h, IC, SD, error HAC, t aproximado, verdad:',h,vals.mean(),vals.std(ddof=1),se,vals.mean()/se if se>0 else np.nan,ic_real*rho**(h-1))The HAC band uses lags as a demonstration choice and does not guarantee capturing all persistence. Half-life estimation requires a negative log-IC slope and enough positive points; a finite sample can fail that condition.
medias=np.array([correlacion_filas(z[:-h],rend[h:]).mean() for h in horizontes])
validos=medias>0
pendiente=np.polyfit(np.array(horizontes)[validos],np.log(medias[validos]),1)[0] if validos.sum()>=2 else np.nan
semivida=np.log(.5)/pendiente if np.isfinite(pendiente) and pendiente<0 else np.nan
rank_signal=np.apply_along_axis(rankdata,1,z[:-1]); rank_return=np.apply_along_axis(rankdata,1,rend[1:])
neutral=senal-(senal@F)@np.linalg.inv(F.T@F)@F.T
print('IC de rangos:',correlacion_filas(rank_signal,rank_return).mean(),'| semivida estimada:',semivida,'| verdad:',np.log(.5)/np.log(rho))
print('Máximo residuo de exposición:',np.max(np.abs(neutral@F)))
print('IC original / neutral:',correlacion_filas(senal[:-1],rend[1:]).mean(),correlacion_filas(neutral[:-1],rend[1:]).mean())The neutralization regression uses a full-rank matrix in this example. In production, use stable factorizations, check each exposure’s rank and date, and handle missing assets without looking ahead. The log-linear fit uses all displayed horizons and is descriptive: changing the range after seeing the curve adds a trial.
def estandarizar(x):
y=x-x.mean(axis=1,keepdims=True); return y/np.sqrt(np.mean(y*y,axis=1,keepdims=True))
def quintiles(s):
orden=np.argsort(s,axis=1); w=np.zeros_like(s); k=s.shape[1]//5
for i in range(len(s)): w[i,orden[i,:k]]=-1/k; w[i,orden[i,-k:]]=1/k
return w
w=quintiles(neutral[:-1]); cartera=np.sum(w*rend[1:],axis=1)
turnover=np.mean(np.sum(np.abs(np.diff(w,axis=0)),axis=1)/2)
print('Rentabilidad media largo-corto:',cartera.mean(),'| rotación media 1/2 L1:',turnover)
corte=220; s1=estandarizar(neutral); s2=estandarizar(alternativa)
X=np.stack([s1[:corte].ravel(),s2[:corte].ravel()],axis=1); y=rend[1:corte+1].ravel()
S=np.cov(X,rowvar=False); Scontraida=.7*S+.3*np.eye(2); vector=X.T@y/len(y)
pesos=np.linalg.solve(Scontraida,vector); combinado=pesos[0]*s1+pesos[1]*s2
test=slice(corte,T-1)
print('Pesos fijados en entrenamiento:',pesos)
print('IC test individual 1 / 2 / mezcla igual / contraída:',*[correlacion_filas(a[test],rend[1:][test]).mean() for a in (s1,s2,(s1+s2)/2,combinado)])The quintile is fully rebalanced and turnover uses ; it omits costs and is not an implementable portfolio. The combination uses signal at and return at ; weights and shrinkage intensity are fixed before test. The result depends on this seed and does not prove shrinkage always improves performance.
In this run the shrunk combination has test IC approximately 0.031, below the first signal’s 0.034 and above the equal-weight blend’s 0.027. The comparison favors some benchmarks but not others. Weights are estimated on finite samples and the second result can change with the seed: there is no reason to present the combination as a universal improvement.
Lab: barriers and meta-model
We simulate log returns with two persistent regimes: one with continuation and another with reversal. On each date a noisy regime indicator is available at that time. It is a synthetic feature useful by construction, not a market variable. The primary rule takes the direction of a moving-average crossover at close and enters at the next closing price; barriers are evaluated after entry. Costs and additional latency are excluded.
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.metrics import precision_score,recall_score,f1_score
rng=np.random.default_rng(282402); D=3000; estado=np.zeros(D,dtype=int); ret=np.zeros(D); proxy=np.zeros(D)
estado[0]=1
for t in range(1,D):
estado[t]=estado[t-1] if rng.random()>.015 else 1-estado[t-1]
phi=.45 if estado[t-1] else -.45; vol=.012 if estado[t-1] else .008
ret[t]=phi*ret[t-1]+vol*rng.normal(); proxy[t]=estado[t]+.8*rng.normal()
logprecio=np.cumsum(ret); ewma=np.empty(D); ewma[0]=.01**2
for t in range(1,D): ewma[t]=.94*ewma[t-1]+.06*ret[t]**2
vol_est=np.sqrt(ewma)
rapida=np.convolve(logprecio,np.ones(5)/5,'full')[:D]
lenta=np.convolve(logprecio,np.ones(20)/20,'full')[:D]
decision=np.arange(60,D-12,5); entrada=decision+1; lado=np.where(rapida[decision]>=lenta[decision],1,-1)
print('Eventos propuestos:',len(entrada),'| último cierre:',D-1)The following barriers use observed log returns, times volatility available at the decision and a maximum of 10 steps. The array compares all future paths at once and selects the first touch. When the horizon expires, the observed return’s sign is retained. Trading occurs at the observed exit price, not the theoretical barrier level.
H=10; offsets=np.arange(1,H+1); trayectorias=logprecio[entrada[:,None]+offsets]-logprecio[entrada,None]
umbral=1.5*vol_est[decision,None]; toca=(trayectorias>=umbral)|(trayectorias<=-umbral)
paso=np.where(toca.any(axis=1),np.argmax(toca,axis=1)+1,H); salida=entrada+paso
logret=trayectorias[np.arange(len(entrada)),paso-1]; exito=(lado*logret>0).astype(int)
causa=np.where(toca.any(axis=1),np.where(logret>0,1,-1),0)
def unicidad(inicios,finales,longitud):
concurrencia=np.zeros(longitud)
for a,b in zip(inicios,finales): concurrencia[a+1:b+1]+=1
return np.array([np.mean(1/concurrencia[a+1:b+1]) for a,b in zip(inicios,finales)])
pesos=unicidad(entrada,salida,D)
print('Superior, inferior, vertical:',[(int(k),int((causa==k).sum())) for k in (1,-1,0)])
print('Unicidad media:',pesos.mean(),'| éxito de la regla:',exito.mean())The split is temporal. Train only on events ending before the cutoff and evaluate those starting afterwards; events crossing the cutoff are purged. The 0.5 threshold is fixed beforehand, without tuning on test. Training uniqueness is calculated only from training events. The classifier is small gradient boosting for the browser environment; the synthetic indicator is not interpreted as a real accessible feature.
corte=2100; train=salida<corte; test=entrada>=corte
# Comprobación de purga con intervalos de juguete que sí cruzan el corte.
inicio_demo=np.array([9,13,14]); fin_demo=np.array([12,15,18]); corte_demo=14
assert np.array_equal(fin_demo<corte_demo,[True,False,False])
assert np.array_equal(inicio_demo>=corte_demo,[False,False,True])
caracteristicas=np.c_[proxy[decision],(rapida[decision]-lenta[decision])/vol_est[decision],ret[decision]/vol_est[decision],vol_est[decision]]
pesos_train=unicidad(entrada[train],salida[train],D)
modelo=GradientBoostingClassifier(n_estimators=60,max_depth=2,random_state=282403)
modelo.fit(caracteristicas[train],exito[train],sample_weight=pesos_train)
proba=modelo.predict_proba(caracteristicas[test])[:,1]; elegido=proba>=.5; ytest=exito[test]
print('Entrenamiento / purgados / test:',train.sum(),(~(train|test)).sum(),test.sum())
for nombre,pred in [('base',np.ones(len(ytest),dtype=bool)),('meta',elegido)]:
print(nombre,'seleccionados:',pred.sum(),'| precisión, recall, F1:',precision_score(ytest,pred,zero_division=0),recall_score(ytest,pred,zero_division=0),f1_score(ytest,pred,zero_division=0))With this seed no actual event in the example crosses the cutoff, although a toy-interval check verifies the criterion when one does. On test, precision falls from approximately 0.466 to 0.442 and F1 from 0.636 to 0.450 after filtering. The meta-model does not demonstrate classification improvement in this run; selecting fewer events is insufficient to establish an edge.
For a toy portfolio measure, each active event contributes of signed exposure, since entries are five steps apart and the maximum horizon is ten. Sum open positions and multiply by each step’s log return. The annualized ratio uses by convention, without adjusting for dependence, costs or financing; it is not an expectation of future profitability. Position uses only test events, with exit determined by the simulated path.
def pnl_eventos(mascara):
posicion=np.zeros(D); idx=np.flatnonzero(test)
for j,usar in zip(idx,mascara):
if usar: posicion[entrada[j]+1:salida[j]+1]+=lado[j]/2
return posicion[corte:]*ret[corte:]
def ratio_convencional(r):
return float(np.mean(r)/np.std(r,ddof=1)*np.sqrt(252)) if np.std(r,ddof=1)>0 else np.nan
for nombre,seleccion in [('base',np.ones(test.sum(),dtype=bool)),('meta',elegido)]:
pnl=pnl_eventos(seleccion); print(nombre,'| media diaria:',pnl.mean(),'| ratio convencional:',ratio_convencional(pnl),'| días con posición:',int(np.count_nonzero(pnl)))The conventional ratio moves from approximately −0.840 to −0.666, but both are negative and exclude costs. That descriptive difference does not demonstrate statistically significant improvement or profitability; the classifier also worsened the classification metrics shown above.
The following log retains variants actually evaluated in this lab. The hash summarizes training data; it does not establish provenance of an external dataset. Copy the JSON to persistent storage alongside the code version, date and all variants tried later: this cell’s environment does not preserve the log between sessions.
import hashlib,json
huella=hashlib.sha256(caracteristicas[train].tobytes()+exito[train].tobytes()).hexdigest()
registro=[{'id':nombre,'semilla_datos':282402,'semilla_modelo':282403 if nombre=='meta' else None,
'corte':corte,'regla':'cruce 5/20; entrada cierre siguiente; H=10',
'umbral':.5 if nombre=='meta' else None,'hash_entrenamiento_sha256':huella,
'precision_test':float(precision_score(ytest,pred,zero_division=0)),
'f1_test':float(f1_score(ytest,pred,zero_division=0)),'ratio_test_sin_costes':ratio_convencional(pnl_eventos(pred))}
for nombre,pred in [('base',np.ones(len(ytest),dtype=bool)),('meta',elegido)]]
print(json.dumps(registro,ensure_ascii=False,indent=2))Exercises
Step 1 of 3. What are the mean and variance of the sum?
def ic_decay(signal, returns, horizons):
raise NotImplementedError()Key takeaways
IC measures predictive association, not net profit. Breadth counts independent decisions under a model, not simply assets multiplied by dates. Neutralization, labels, validation and costs must use information available at each instant. Recording failed experiments as well allows the selection that produced the final result to be audited.