Frontier I: machine learning in asset pricing
Survey machine learning for cross-sectional return prediction: penalized models, trees and networks, IPCA, conditional autoencoders, adversarial SDF estimation and complexity under weak signals and nonstationarity.
After this lesson you can
- Reproduce a reduced Gu-Kelly-Xiu design with strict temporal validation and out-of-sample R².
- Derive and implement IPCA by alternating least squares and interpret characteristics as dynamic loadings.
- Explain conditional autoencoders and adversarial SDFs as nonlinear extensions of factor models.
- Analyze complexity with ridge regression on random features and relate it to double descent.
- Evaluate ML models by economic value as well as R² using synthetic data with known SDF.
Before you start
- 28Fama-MacBeth procedureStochastic discount factorStatistical factor modelsThe factor zooPurged k-fold cross-validationInformation coefficientDeflated Sharpe ratioCharacteristic-sorted portfolios
- 11Ridge regressionLassoElastic netGradient boosting machineRandom forest
- 15Micro framework to PyTorch correspondenceDropout
- 13Early stopping as regularizationDouble descentRandom features model
- 19Nonlinear autoencoder
- 26Diebold-Mariano test and forecast combination
Prediction with a weak signal
Predicting asset returns combines many features with a signal small relative to noise. Valid evaluation respects publication dates, universe availability and costs. A complex model can overfit thousands of correlated observations even when the row count seems huge. Assets in the same month share shocks: they should not be arbitrarily divided between training and test.
Gu, Kelly and Xiu’s work on machine-learning return prediction compares penalized linear methods, trees and networks in a temporal evaluation. For excess returns they use zero prediction as benchmark in out-of-sample :
It is negative if predictions have greater squared error than zero in that test. It is not the of a regression centered on the test-sample mean. The zero benchmark is an explicit economic and statistical choice, not a universal requirement.
The temporal split must keep each month’s assets together: if the same shock appears in training and test, effective sample size is overstated. Accounting features can be used only after publication and transformations are fitted on available history. One month of embargo suffices for the lab’s simplified monthly-label horizon, but not every horizon or publication delay.
An of 0.5% does not mean the model gets the sign right 50.5% of the time or that the portfolio gains 0.5%. The first compares aggregate squared errors, the second is classification and the third depends on an allocation rule. Asset weighting also matters: an equal-weight evaluation can be dominated by numerous small firms that are difficult to trade.
evaluates prediction levels; a ranked portfolio can depend mainly on cross-sectional ordering. A small statistical result can coexist with useful ranking, but a concentrated portfolio’s Sharpe can also be noisy or disappear with spread, impact, borrow and constraints. Economic value must be calculated with tradable weights, costs and factor exposure. Regression alpha against a chosen benchmark does not demonstrate absence of every risk.
Characteristics and factors: IPCA
In IPCA, Kelly, Pruitt and Su model each asset’s loading using its characteristics. In the version without intercept, . Matrix relates characteristics and dynamic exposures; are common latent factors. A characteristic can modify risk covariance rather than represent independent alpha.
With fixed, each factor is obtained by cross-sectional regression of on . With factors fixed, rows are pooled and estimated by least squares. Alternating both steps reduces the sum of errors, but can converge to local optima and requires identification and rank conditions. For any invertible matrix , and give the same products; comparing columns without aligning rotations and scales does not identify recovery.
Distinguish contemporaneous reconstruction from prediction: the month’s factor is estimated using that month’s returns, so it was unavailable before they occurred. Forecasting the next period needs a model of future factor distribution or mean, fitted using earlier information. Good contemporaneous fit does not establish positive predictive .
The experiment below adds a characteristic-associated intercept diagnostic and residual bootstrap using common monthly signs. It is a toy test conditional on the fitted model, not a complete implementation of published IPCA tests. Validity of any test requires handling identification, dependence and factor selection.
Nonlinear models and pricing
The conditional pricing autoencoder of Gu, Kelly and Xiu combines nonlinear characteristic-dependent loadings with factors built from aggregate return information. The decoder reconstructs returns through interaction between loadings and factors. A linear network and certain constraints connect the idea with factor models, but an estimated autoencoder is not automatically a tradable factor or valid SDF.
Chen, Pelger and Zhu’s adversarial SDF estimation starts from moment conditions such as for excess returns. One network proposes stochastic discount factor and another searches for instruments or portfolios with large pricing errors; the first model tries to reduce those errors. Recurrent networks summarize macroeconomic information. Instrument choice, regularization, SDF positivity and future evaluation matter. Adversarial fit does not guarantee absence of arbitrage outside the tested instrument class.
The condition applies to excess returns: for a unit-payoff asset its price and risk-free rate must enter SDF normalization. Multiplying moments by observable instruments allows conditional restrictions to be investigated, but a finite instrument set examines only some. The adversarial network can find sample errors and also overfit them; evaluation requires test periods and assets without reusing features normalized using the future.
Complexity and regularization
The virtue of complexity of Kelly, Malamud and Zhou studies many-random-feature and ridge models for return prediction. The overparameterized regime can perform better under their conditions, but uncontrolled parameter increases do not guarantee improvement. Penalization limits sensitivity to poorly estimated directions; the interpolation peak and possible later improvement depend on data, scaling and objective.
Nagel questions interpretations of complexity results under specification and measurement choices. This is an empirical and theoretical debate, not a rule that all large models win or fail. Comparing regularization, intercepts, scaling and portfolios requires separating selection and test.
Ratio does not exhaust complexity: two random maps with the same number of columns can have different ranks and spectra. Ridge replaces direct inversion with a penalized one and attenuates low-variance directions, trading bias for less noise sensitivity. Near interpolation, changing penalization and training size can substantially alter the curve. The exercise keeps configurations that fail visible.
Local lab: temporal comparison
The following panel is synthetic. For each month generate uniformly over , with zero mean and unit variance; an asset has and is a nonlinear function of characteristics. With , holds under the generator and is positive for the parameters used. These are not real prices or features.
We train elastic net, gradient boosting and networks with one to five hidden layers. Training, validation and test months are disjoint, with one month between blocks; scaling is fitted only on training and best-variant selection occurs on validation. The portfolio buys and sells equal-weight deciles and pays a simplified turnover cost. Evaluation omits sizes, volume, delistings and constraints: it does not replicate the database or complete Gu and coauthors study.
import numpy as np, torch, copy
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import ElasticNet
from sklearn.ensemble import GradientBoostingRegressor
from scipy.stats import norm,skew,kurtosis
torch.set_num_threads(2); torch.manual_seed(282901)
rng=np.random.default_rng(282901); T=120; N=80; D=6
z=rng.normal(size=(T,N,D)); f=rng.uniform(-np.sqrt(3),np.sqrt(3),T)
beta=.8*np.tanh(z[:,:,0])+.3*z[:,:,1]*z[:,:,2]; lam=.004; sf=.04
r=beta*(lam+sf*f[:,None])+rng.normal(scale=.03,size=(T,N))
m=1-(lam/sf)*f; assert np.all(m>0)
train=np.arange(0,70); val=np.arange(71,90); test=np.arange(91,120)
scaler=StandardScaler().fit(z[train].reshape(-1,D))
def matriz(indices): return scaler.transform(z[indices].reshape(-1,D))
Xtr=matriz(train); Xv=matriz(val); Xt=matriz(test)
ytr=r[train].reshape(-1); yv=r[val].reshape(-1); yt=r[test].reshape(-1)
pred_val={}; pred_test={}
for nombre,modelo in [('elastic',ElasticNet(alpha=.0001,l1_ratio=.2,max_iter=3000)),
('boost',GradientBoostingRegressor(n_estimators=60,max_depth=2,learning_rate=.05,random_state=282901))]:
modelo.fit(Xtr,ytr); pred_val[nombre]=modelo.predict(Xv); pred_test[nombre]=modelo.predict(Xt)
Xtrt=torch.tensor(Xtr,dtype=torch.float32); ytrt=torch.tensor(ytr[:,None],dtype=torch.float32)
Xvt=torch.tensor(Xv,dtype=torch.float32); yvt=torch.tensor(yv[:,None],dtype=torch.float32)
for depth in range(1,6):
torch.manual_seed(282901+depth); layers=[]; width=D
for _ in range(depth): layers.extend([torch.nn.Linear(width,16),torch.nn.ReLU()]); width=16
layers.append(torch.nn.Linear(width,1)); net=torch.nn.Sequential(*layers)
opt=torch.optim.Adam(net.parameters(),lr=.003,weight_decay=.0001)
best=np.inf; best_state=None; espera=0
for epoch in range(150):
net.train(); opt.zero_grad(); loss=((net(Xtrt)-ytrt)**2).mean(); loss.backward(); opt.step()
net.eval()
with torch.no_grad(): valid=float(((net(Xvt)-yvt)**2).mean())
if valid<best-1e-8: best=valid; best_state=copy.deepcopy(net.state_dict()); espera=0
else: espera+=1
if espera>=12: break
net.load_state_dict(best_state); net.eval()
with torch.no_grad():
pred_val['red'+str(depth)]=net(Xvt).numpy().ravel()
pred_test['red'+str(depth)]=net(torch.tensor(Xt,dtype=torch.float32)).numpy().ravel()
def oos_r2(y,p): return 1-np.sum((y-p)**2)/np.sum(y*y)
def cartera(pred,indices,coste=.001):
pred=pred.reshape(len(indices),N); pesos=np.zeros((len(indices),N)); q=N//10
for t in range(len(indices)):
orden=np.argsort(pred[t]); pesos[t,orden[:q]]=-1/q; pesos[t,orden[-q:]]=1/q
prev=np.vstack([np.zeros((1,N)),pesos[:-1]])
turno=np.abs(pesos-prev).sum(axis=1)
net=(pesos*r[indices]).sum(axis=1)-coste*turno
return net,turno
def resumen(pred,indices,y):
net,turno=cartera(pred,indices); sd=np.std(net,ddof=1)
sharpe=np.mean(net)/sd*np.sqrt(12) if sd else np.nan
market=lam+sf*f[indices]
alfa=np.linalg.lstsq(np.column_stack([np.ones(len(indices)),market]),net,rcond=None)[0][0]*12
return oos_r2(y,pred),sharpe,float(turno.mean()),alfa
registro=[]
for nombre in pred_val:
v=resumen(pred_val[nombre],val,yv); out=resumen(pred_test[nombre],test,yt)
registro.append((nombre,v,out))
print(nombre,'| valid R², Sharpe, rotación, alfa anual simple:',v,
'| test:',out)
elegido=max(registro,key=lambda fila:fila[1][0])[0]
sr_trials=np.array([np.mean(cartera(pred_val[n],val)[0])/np.std(cartera(pred_val[n],val)[0],ddof=1) for n in pred_val])
best_net=cartera(pred_val[elegido],val)[0]; s=sr_trials[list(pred_val).index(elegido)]
g3=skew(best_net,bias=False); g4=kurtosis(best_net,fisher=False,bias=False); gamma=.5772156649; ntr=len(sr_trials)
zmax=(1-gamma)*norm.ppf(1-1/ntr)+gamma*norm.ppf(1-1/(ntr*np.e))
s0=sr_trials.std(ddof=1)*zmax; v=1-g3*s+(g4-1)*s*s/4
dsr=norm.cdf((s-s0)*np.sqrt(len(val)-1)/np.sqrt(v))
print('Elegido por R² de validación:',elegido,'| DSR ilustrativo validación:',dsr,
'| variantes registradas:',ntr,'| m mínimo observado:',m.min())npm run lab and open the connection link.The portfolio rebalances monthly; turnover is the sum of absolute weight changes, including initial position establishment, and cost is 10 basis points per traded notional. Displayed alpha is the monthly intercept against the synthetic factor multiplied by 12, not an SDF test. DSR uses validation returns and assumes independent trials and representative cross-sectional dispersion: the seven variants are correlated and 19 months are few. This is sensitivity analysis, not a guarantee of significance. Publishing all test outputs allows comparison, but selecting again on them would consume that test.
The variant is selected by , not Sharpe. Thus the DSR threshold built from Sharpes of all variants is only illustrative sensitivity, not an exact correction of the selection criterion used. The true search also includes prior decisions about architecture, seed and data: seven models are not necessarily a project’s complete trial count.
In this run elastic net was selected by validation, with validation approximately 0.0021 and net Sharpe 1.91; on test it obtained −0.0022 and net Sharpe −0.40. All seven variants had negative and net Sharpe on that test. Illustrative validation DSR was 0.75. These figures come from a small simulated panel and do not support a general ranking of models.
Lab: IPCA by alternating least squares
We generate characteristics and factors with two known dimensions. The fit observes only characteristics and returns; subspace comparison uses truth to check recovery, unavailable with real data. is normalized by QR and the factor transformed so the product does not change. Error is fit error on the same sample.
import numpy as np
rng=np.random.default_rng(282902); T=30; N=25; L=4; K=2
Z=rng.normal(size=(T,N,L)); Gtrue=np.array([[.8,0],[.6,0],[0,.8],[0,.6]])
Ftrue=rng.normal(size=(T,K)); R=np.einsum('tnl,lk,tk->tn',Z,Gtrue,Ftrue)+rng.normal(scale=.2,size=(T,N))
def ipca(Z,R,K,iters=30,seed=42):
T,N,L=Z.shape; rng=np.random.default_rng(seed)
G=np.linalg.qr(rng.normal(size=(L,K)))[0]; historia=[]
for _ in range(iters):
F=np.array([np.linalg.lstsq(Z[t]@G,R[t],rcond=None)[0] for t in range(T)])
A=np.einsum('tnl,tk->tnlk',Z,F).reshape(T*N,L*K)
G=np.linalg.lstsq(A,R.reshape(-1),rcond=None)[0].reshape(L,K)
G,rot=np.linalg.qr(G); [email protected]
pred=np.einsum('tnl,lk,tk->tn',Z,G,F)
historia.append(np.mean((R-pred)**2))
return G,F,pred,np.array(historia)
G,F,pred,loss=ipca(Z,R,K)
assert np.all(np.diff(loss)<1e-9)
proy_error=np.linalg.norm([email protected]@Gtrue.T)
print('MSE inicial/final:',loss[0],loss[-1],'| error de proyectores:',proy_error)The first-order condition for is . For , vectorize equations of rows and solve the pooled regression. QR changes representation, not fit. The algorithm needs restarts and convergence diagnostics in real applications.
With this seed fit MSE falls from 0.1374 to 0.0356 and the norm of the difference between projectors is approximately 0.0208. The sign test gives p ≈ 0.806; with only 30 replicates and the stated assumptions it should not be interpreted as definitive proof of absent alpha.
The next test summarizes a possible characteristic-associated linear anomaly: project residuals onto and use the norm of that coefficient. To construct a conditional null, flip all residual signs for a month jointly and refit IPCA in each replicate. This preserves some cross-sectional dependence, but assumes residual symmetry, independence across months and the fitted null model; with 30 replicates p is very discrete. It is not a general alpha test or the paper’s complete bootstrap.
def alfa_residual(Z,resid):
return np.linalg.lstsq(Z.reshape(-1,Z.shape[-1]),resid.reshape(-1),rcond=None)[0]
resid=R-pred; observado=np.linalg.norm(alfa_residual(Z,resid))
rng=np.random.default_rng(282903); B=30; nulos=[]
for b in range(B):
signos=rng.choice([-1,1],size=(T,1))
muestra=pred+resid*signos
_,_,fit,_=ipca(Z,muestra,K,iters=20,seed=42)
nulos.append(np.linalg.norm(alfa_residual(Z,muestra-fit)))
p=(1+np.sum(np.array(nulos)>=observado))/(B+1)
print('Norma residual observada:',observado,'| p bootstrap:',p,'| réplicas:',B)Lab: random features
This lab’s monthly series is synthetic and has a known weak predictive function. Fourier features are generated with parameters fixed before training. We use dual ridge, which solves a matrix even when . We compare penalties on validation for each size and later evaluate all curves on test. Showing the complete curve also exposes test: it must not be reused to choose a final result.
rng=np.random.default_rng(282904); TT=140; ntrain=60; nval=20
x=rng.normal(size=TT); y=.04*np.sin(x)+rng.normal(scale=.2,size=TT)
w=rng.normal(size=180); b=rng.uniform(0,2*np.pi,size=180)
def r2_cero(y,p): return 1-np.sum((y-p)**2)/np.sum(y*y)
def ridge_dual(X,y,Xout,penalizacion):
a=np.linalg.solve([email protected]+penalizacion*np.eye(len(X)),y)
return [email protected]@a
registro=[]
for P in (10,30,60,90,120,180):
phi=np.sqrt(2/P)*np.cos(x[:,None]*w[None,:P]+b[None,:P])
candidatos=[]
for ridge in (1e-5,.01,.1):
pv=ridge_dual(phi[:ntrain],y[:ntrain],phi[ntrain:ntrain+nval],ridge)
candidatos.append((np.mean((y[ntrain:ntrain+nval]-pv)**2),ridge))
_,elegida=min(candidatos)
real=y[ntrain+nval:]
for _,ridge in candidatos:
pred=ridge_dual(phi[:ntrain],y[:ntrain],phi[ntrain+nval:],ridge)
posicion=np.sign(pred); giro=np.abs(np.diff(np.r_[0.,posicion]))
pnl=posicion*real-.0005*giro
sharpe=pnl.mean()/pnl.std(ddof=1)*np.sqrt(12)
registro.append((P/ntrain,ridge,ridge==elegida,r2_cero(real,pred),sharpe))
print('P/T:',P/ntrain,'| validación:',candidatos,'| prueba por ridge:',registro[-3:])Scaling factor keeps feature magnitudes comparable. The timing position is long or short one unit according to prediction sign and pays 5 basis points per unit change; it models neither financing nor impact. The experiment may or may not show a peak or improvement for this seed. No curve shape should be attributed to the real market.
In this realization every table configuration has negative on test, although some timing positions show positive Sharpe. Validation losses favor the smallest penalty for several large sizes and those models have especially high test errors. This shows sensitivity to selection in a short history, without establishing a universal conclusion about ridge or complexity.
Exercises
def oos_r2(y,p):
raise NotImplementedError()
def dm_test(y,a,b,L):
raise NotImplementedError()Key takeaways
The synthetic panel provides known truth for checking algorithms; it does not validate a market strategy. Results should be accompanied by all variants, uncertainty, costs, data availability and a reserved temporal test.