Module contents
Lesson 26 of 30Core 115 min

Systematic strategies and statistical arbitrage

Implement and evaluate systematic momentum, carry, mean-reversion and statistical-arbitrage families, including cointegrated pairs, Ornstein-Uhlenbeck spreads, PCA residuals and shared risks.

After this lesson you can

  • Implement time-series momentum with volatility targeting and explain its convex profile.
  • Build synthetic carry strategies across asset classes and explain tail risk.
  • Select pairs by cointegration, model an Ornstein-Uhlenbeck spread and derive entry and exit thresholds.
  • Implement Avellaneda-Lee PCA-residual statistical arbitrage with s-scores.
  • Evaluate strategies with costs and walk-forward tests, including crisis and deleveraging behavior.

Before you start

Signal families and risks

A systematic strategy transforms available information into positions through a reproducible rule. Results also depend on financing, execution and risk. A signal can express persistent trends, compensation for holding exposure or reversal after a move. No family guarantees profits: each loses on certain paths and can stop working when the market changes.

Time-series momentum compares each asset’s past evolution with itself. A simple rule takes the direction of cumulative return over a window and scales exposure by volatility estimated using only the past. A cap prevents excessive leverage when estimated volatility is small. Moskowitz, Ooi and Pedersen document trends in their futures sample; historical results do not guarantee a particular window or market is profitable.

InteractiveTrend versus the asset

Synthetic daily returns with alternating drift and noise. The position uses prior returns only, scales with historical volatility, and is capped at 1.5. Daily returns add without compounding or costs.

Asset: −26.3 % to 26.3 %Strategy: ±26.3 %

A trend strategy can benefit from sustained moves in both directions and lose in quick reversals or sideways markets. Whether convexity holds depends on the process.

63
Quarters28
Mean strategy return before costs3.81 %
Each point summarizes 63 days from the same synthetic generator.

The strategy can benefit from persistent upward and downward moves, producing a sometimes convex relationship with asset return, resembling a straddle in certain periods. It does not literally buy an option: the position is rebalanced and can lose from reversals, costs or sudden moves before it reacts. The smile depends on horizon, process and sample; the figure shows points, not a universal law.

Carry is the return associated with holding an asset if relevant conditions remain constant, under the appropriate pricing and financing convention. In currencies rates and forward exchange rates matter; in futures, curve slope and maturity; in bonds, coupon, price and movement due to time passing. Koijen and coauthors propose a common definition. Positive carry is not a safe return: prices, financing and liquidity can change, and a joint loss can erase many periods of small gains.

Short-term cross-sectional reversal buys assets that have fallen relative to others and sells those that have risen. It can resemble liquidity provision if it absorbs temporary selling, but permanent news, short-leg borrow or common liquidation can cause losses. Signals based on nominal prices, maturities, dividends and adjustments must use consistent series and contracts.

Pairs, selection and cointegration

Historical distance between two normalized series is descriptive. Pairs cointegration poses another hypothesis: if both series are integrated of order one, some linear combination may be stationary. In Engle-Granger, estimate Yt=α+βXt+etY_t=\alpha+\beta X_t+e_t in training and test the residual for a unit root using a distribution appropriate for estimated residuals, not ordinary critical values for a directly observed series. Hedge and selection must be frozen before future testing; changing β\beta also entails trading and cost.

InteractiveSearching manufactures candidates

Fit the intercept and slope on 120 observations. Compare each residual unit-root statistic with 2,000 simulated independent pairs of the same size. The discrete p-value applies a +1 correction. A result at 5% without adjustment may occur by chance.

Fit: 120 daysTest: 80 daysResidual ±7.3

The hedge line stays fixed out of sample. The minimum p-value resolution is 1/2,001. When it exceeds 0.05 divided by the number of pairs, it cannot resolve the Bonferroni threshold. The tests share series and are dependent.

100
Pairs examined4950
Uncorrected at 5%281
Smallest simulated p-value0.0010
Bonferroni 5%Insufficient resolution
A hundred independent walks can produce apparently significant signals.

For 100 assets there are 100(99)/2=4950100(99)/2=4950 pairs. If each null test has exactly 5% size, expected false positives are 4950(0.05)=247.54950(0.05)=247.5, even if tests are dependent. That does not say how many occur in a sample or the probability of any. Bonferroni compares each p with 0.05/49500.05/4950 and controls family-wise error under any dependence if individual p-values are valid. Limited Monte Carlo may lack enough resolution for that threshold. The relationship can also break after training; significance does not demonstrate an exploitable opportunity.

An OU spread and a specific objective

The Ornstein-Uhlenbeck spread model is dXt=κ(θ−Xt)dt+σdWtdX_t=\kappa(\theta-X_t)dt+\sigma dW_t, with κ,σ>0\kappa,\sigma>0. Its exact transition over interval Δ\Delta is Xt+Δ=θ+ϕ(Xt−θ)+ϵtX_{t+\Delta}=\theta+\phi(X_t-\theta)+\epsilon_t, where ϕ=e−κΔ\phi=e^{-\kappa\Delta} and ϵt\epsilon_t is normal with variance σ2(1−ϕ2)/(2κ)\sigma^2(1-\phi^2)/(2\kappa). Therefore, in a valid AR(1) with intercept cc and 0<ϕ<10<\phi<1, θ=c/(1−ϕ)\theta=c/(1-\phi), κ=−log⁡(ϕ)/Δ\kappa=-\log(\phi)/\Delta and half-life is log⁡(2)/κ\log(2)/\kappa. A negative estimate or one greater than one does not correspond to this scalar OU with monotonic mean reversion; fit uncertainty matters.

To obtain the transition, multiply the X−θX-\theta equation by eκte^{\kappa t} and integrate between tt and t+Δt+\Delta. The random term is σ∫tt+Δe−κ(t+Δ−u)dWu\sigma\int_t^{t+\Delta} e^{-\kappa(t+\Delta-u)}dW_u. It is zero-mean Gaussian and, by Itô isometry, has variance σ2∫0Δe−2κvdv\sigma^2\int_0^\Delta e^{-2\kappa v}dv, exactly the previous expression. Integrals over disjoint intervals are independent, so observations on a regular grid form the indicated AR(1).

To see how the objective enters, assume zero mean, continuous observation, one unit bought on touching −a-a and sold on returning to zero, and fixed cost cc per execution. Profit per cycle is a−2ca-2c. Expected round-trip time is πerfi⁡(aκ/σ)/κ\pi\operatorname{erfi}(a\sqrt{\kappa}/\sigma)/\kappa, so the long-run rate is

g(a)=κ(a−2c)πerfi⁡(aκ/σ),a>0.g(a)=\frac{\kappa(a-2c)}{\pi\operatorname{erfi}(a\sqrt{\kappa}/\sigma)},\qquad a>0.

Here erfi⁡(z)=2π−1/2∫0zeu2du\operatorname{erfi}(z)=2\pi^{-1/2}\int_0^z e^{u^2}du. It is maximized numerically within a family of bands; this is not a universal rule. Bertram studies first-passage times and profitability and Sharpe objectives. Changing the objective or allowing shorts, stops, discrete execution or uncertain parameters changes the problem. If a≤2ca\le 2c, the ideal cycle has no positive net profit.

InteractiveOU bands and cycles

OU with κ = 0.08 per day and σ = 0.15 per square root of a day. Buy one unit when the observed spread is ≤ −a and sell when it reaches ≥ 0. There are two fixed costs per cycle. The curve accumulates closed trades only.

Spread and bandsRealized profit1,000 daily observations

The optimum maximizes the ideal rate for a continuous cycle from 0 to −a and back to 0, without discrete observation jumps or financing. Profit on a finite path can differ from that rate.

0.40
0.02
Continuous-time optimum in this family0.265
Ideal rate for the selected band0.0088
Closed trades15
Realized profit8.24
Compare the ideal rate with trades observed once daily.

Factors and concentration

Avellaneda and Lee’s PCA statistical arbitrage estimates common factors and models reversion of residual components; it also studies ETF-derived factors. A teaching version computes PCA on a previous window, removes the common projection, integrates residual returns and fits an AR(1). The s-score is the distance from its latest level to estimated mean divided by stationary standard deviation. A negative s-score may motivate a long residual position, but estimating the residual does not mean a tradable neutral portfolio has been constructed. Exposures must be translated into shares, both legs paid for, and turnover and borrow availability controlled.

Risk profiles appear in tails, drawdowns, financing and common exposure as well as Sharpe. In August 2007 several quantitative strategies suffered simultaneous losses. Khandani and Lo analyze factors and transactions and propose an explanation linked to deleveraging and temporary withdrawal of market-making capital; each participant’s identity and motivation do not follow from this toy model.

InteractiveShared selling

Eight funds each hold 1.5 units, with equity of 1 and a leverage limit of 1.5. One fund loses equity after an external shock. Each round they sell simultaneously to meet the limit at the previous price. Impact lowers the price used to mark their remaining positions.

Price, scale 0 to 1Round: 0 to 20

Sales use the previous price and the new price has a floor of 0.05. The model omits liquidity replenishment and extra costs and may require more than 20 rounds to converge. It illustrates a mechanism using synthetic data.

0.30
0.04
Final price0.976
Total sales0.588
Funds with nonpositive equity0
Rounds calculated12
An initial loss can propagate to other funds holding the same exposure.

Lab: trend and carry

We construct three synthetic futures without explicit maturities. Drift, carry and a common shock are planted, not market data. Each position is determined before the day’s return, with a cost for notional change and daily borrow on short exposure. This lesson’s engine marks returns directly with weights; it does not reproduce fills, margin, roll or depth of the previous lesson’s event engine. A notional capital is set, reinvested to obtain the curve, and returns exhausting capital are rejected.

[ ]Generate panel and weight engineBrowser
import numpy as np
rng=np.random.default_rng(282601); T=1260; N=3
carry=np.tile(np.array([.00025,-.0001,.00015]),(T,1))
regimen=np.where((np.arange(T)//126)%2==0,.0006,-.0006)
r=rng.normal(0,.01,(T,N))+regimen[:,None]*np.array([1.,-.4,.7])+carry
r[850:855]-=.035*np.array([1.,.6,.8])
def motor_pesos(r,w,coste=.0005,prestamo=.02):
    r=np.asarray(r); w=np.asarray(w)
    assert r.shape==w.shape and np.isfinite(r).all() and np.isfinite(w).all()
    anterior=np.vstack([np.zeros((1,w.shape[1])),w[:-1]])
    rot=np.abs(w-anterior).sum(axis=1)
    net=(w*r).sum(axis=1)-coste*rot-prestamo*np.maximum(-w,0).sum(axis=1)/252
    if np.any(net<=-1): raise ValueError('Capital agotado')
    return net,np.cumprod(1+net),rot
def tendencia(r,ventana):
    w=np.zeros_like(r)
    for t in range(ventana,len(r)):
        hist=r[t-ventana:t]; vol=np.sqrt(np.mean(hist**2,axis=0))
        w[t]=np.sign(hist.sum(axis=0))*np.minimum(1.5,.01/np.maximum(vol,.001))/r.shape[1]
    return w
def pesos_carry(carry):
    w=np.zeros_like(carry); w[1:]=np.sign(carry[:-1])/carry.shape[1]
    return w
print('Panel sintético:',r.shape,'| shock plantado en días 850 a 854')

Carry observation is lagged one day in the example; the trend signal uses only previous returns. Exposure is per unit of capital at the start of the day and cost assumes prior weights remain starting weights without intraday drift: this is a simplification. No execution price is simulated and no financing charged on the long leg.

[ ]Walk-forward and metricsBrowser
ventanas=[21,63,126]; candidatos={v:tendencia(r,v) for v in ventanas}; wc=pesos_carry(carry)
def resumen(x):
    curva=np.cumprod(1+x); volatilidad=np.std(x,ddof=1)
    q=np.quantile(x,.05); peor=x[x<=q]
    return {'retorno':float(curva[-1]-1),'sharpe':float(np.mean(x)/volatilidad*np.sqrt(252)) if volatilidad else 0.,
            'asimetria':float(np.mean(((x-np.mean(x))/volatilidad)**3)) if volatilidad else 0.,
            'ES_5pct':float(np.mean(peor)),'drawdown':float(np.min(curva/np.maximum.accumulate(np.r_[1.,curva])[1:]-1))}
elegida=np.zeros_like(r); registro=[]
for inicio in range(504,T,126):
    scores={v:resumen(motor_pesos(r[inicio-504:inicio],candidatos[v][inicio-504:inicio])[0])['sharpe'] for v in ventanas}
    mejor=max(ventanas,key=lambda v:scores[v]); fin=min(T,inicio+126)
    elegida[inicio:fin]=candidatos[mejor][inicio:fin]
    registro.append((inicio,fin,mejor,scores))
net,curva,rot=motor_pesos(r,elegida); nc,cc,rc=motor_pesos(r,wc)
print('Selección registrada:',registro)
print('Tendencia test:',resumen(net[504:]),'| rotación:',rot[504:].sum())
print('Carry test:',resumen(nc[504:]),'| rotación:',rc[504:].sum())
print('Pérdida carry durante shock:',float(np.sum(nc[850:855])))

Training chooses among three windows by conventional Sharpe and the first day’s position in each block uses prior history. Evaluation concatenates only later blocks, although each selection retrains. Cost on the first day of the training split is calculated from zero position, a convention affecting selection. The shock was designed to show common risk, not represent a real crisis. ES is the mean of daily returns in the bottom 5%, not a maximum-loss guarantee. The log retains all three scores per block; if the design changes after observing test, it ceases to be independent.

With this seed concatenated trend loses approximately 24.3% and carry gains 12.9% on test; carry loses about 4.6% summing the five returns during the planted shock. These are results of the generator and chosen costs. Carry has a constant position during test, so turnover there is zero; that excludes rollover and the initial trade before the split.

Lab: pairs and PCA

We simulate independent null pairs and calibrate the residual statistic with other equal-length null pairs. This calibration is specific to the generator, not a universal Engle-Granger table. The +1 corrected p avoids zero, but its resolution prevents very small thresholds. Next we add a pair with planted OU spread and estimate its parameters using training only.

[ ]Multiple search and planted pairBrowser
rng=np.random.default_rng(282602); train=120; test=80; n=20; B=4000
series=np.cumsum(rng.normal(size=(n,train+test)),axis=1)
def residuo(x,y,m):
    beta=np.sum((x[:m]-x[:m].mean())*(y[:m]-y[:m].mean()))/np.sum((x[:m]-x[:m].mean())**2)
    alpha=y[:m].mean()-beta*x[:m].mean()
    return y-alpha-beta*x,beta
def estadistico(e,m):
    lag=e[:m-1]; delta=np.diff(e[:m]); b=lag@delta/(lag@lag)
    return b/np.sqrt(np.sum((delta-b*lag)**2)/(m-2)/(lag@lag))
null=np.empty(B)
for b in range(B):
    x=np.cumsum(rng.normal(size=train)); y=np.cumsum(rng.normal(size=train))
    null[b]=estadistico(residuo(x,y,train)[0],train)
resultados=[]
for i in range(n):
    for j in range(i+1,n):
        e,beta=residuo(series[i],series[j],train); t=estadistico(e,train)
        p=(1+np.sum(null<=t))/(B+1); resultados.append((p,i,j,t,beta))
resultados.sort(); umbral=.05/len(resultados)
print('Pares:',len(resultados),'| sin corregir:',sum(z[0]<=.05 for z in resultados))
print('Mejor par, p/i/j/t/beta:',resultados[0],'| Bonferroni:',umbral,'| resolución:',1/(B+1))
base=np.cumsum(rng.normal(size=train+test)); spread=np.zeros(train+test)
for t in range(1,len(spread)): spread[t]=.9*spread[t-1]+rng.normal(scale=.3)
y=1.2*base+spread; estimado,beta=residuo(base,y,train)
print('Par plantado, beta estimada:',beta,'| desviación residual train/test:',np.std(estimado[:train]),np.std(estimado[train:]))

Monte Carlo calibration shares a single null sample and has statistical error; it does not certify real cointegration or eliminate selection. The planted pair contains the relationship by construction. To estimate its OU, regress estimated spread on its lag. The interval is one day and the annual parameter assumes 252 days; regression on estimated residuals ignores hedge uncertainty.

[ ]Estimate OU and optimize a bandBrowser
from scipy.special import erfi
e=estimado[:train]; A=np.column_stack([np.ones(train-1),e[:-1]])
c,phi=np.linalg.lstsq(A,e[1:],rcond=None)[0]; innov=e[1:][email protected]([c,phi])
if 0<phi<1:
    k=-np.log(phi); theta=c/(1-phi); sigma=np.std(innov,ddof=1)*np.sqrt(2*k/(1-phi**2))
    bandas=np.linspace(.01,3*sigma/np.sqrt(k),1000); coste=.02
    tasas=k*(bandas-2*coste)/(np.pi*erfi(bandas*np.sqrt(k)/sigma))
    print('phi, k diario, theta, sigma, vida media:',phi,k,theta,sigma,np.log(2)/k)
    print('Banda óptima en rejilla:',bandas[np.argmax(tasas)],'| tasa ideal:',np.max(tasas))
else: print('El ajuste no corresponde a un OU escalar con reversión monótona:',phi)

In the next panel factors and mean-reverting residuals are generated in a known way. PCA is refit on each past window and the window’s centered residual is integrated. The result is a teaching simplification of Avellaneda-Lee: it excludes universe selection, tradable factors, rebalancing schedule and execution. Invalid s-scores remain NaN. The perturbation test checks causality for that particular change.

[ ]S-scores with rolling PCABrowser
def avellaneda_lee_scores(returns,k,window):
    returns=np.asarray(returns,float); T,N=returns.shape
    if not (0<=k<N and window>=4): raise ValueError('Parámetros inválidos')
    scores=np.full((T,N),np.nan)
    for t in range(window,T):
        hist=returns[t-window:t]; centered=hist-hist.mean(axis=0)
        _,vec=np.linalg.eigh(centered.T@centered/(window-1)); V=vec[:,-k:] if k else np.empty((N,0))
        residual=centered-(centered@V)@V.T; levels=np.cumsum(residual,axis=0)
        for j in range(N):
            lag=levels[:-1,j]; nxt=levels[1:,j]; mat=np.column_stack([np.ones(len(lag)),lag])
            c,phi=np.linalg.lstsq(mat,nxt,rcond=None)[0]
            if 0<phi<1:
                [email protected]([c,phi]); sd=np.std(err,ddof=1)/np.sqrt(1-phi**2)
                if sd>1e-12: scores[t,j]=(levels[-1,j]-c/(1-phi))/sd
    return scores
rng=np.random.default_rng(282603); TT=350; NN=12
factor=rng.normal(scale=.01,size=(TT,2)); load=rng.normal(size=(2,NN)); state=np.zeros((TT,NN))
for t in range(1,TT): state[t]=.9*state[t-1]+rng.normal(scale=.004,size=NN)
panel=factor@load+np.diff(state,axis=0,prepend=state[:1]); score=avellaneda_lee_scores(panel,2,80)
alternativo=panel.copy(); alternativo[201:]+=5
assert np.allclose(score[:201],avellaneda_lee_scores(alternativo,2,80)[:201],equal_nan=True)
print('S-scores finitos desde día 80:',np.isfinite(score[80:]).sum(),'| primer vector:',score[80])

Scores are not returns. For a specific comparison we use the same weight engine: for the planted pair we calculate exponential-price returns from the walks and convert the estimated hedge into normalized two-leg weights. One short unit of X accompanies each long unit of Y weighted by beta. The signal observes residuals through the previous day; band and hedge remain fixed in test. The PCA portfolio uses a signal opposite the s-score sign when it exceeds a band and normalizes gross exposure, but does not remove factor exposure and is therefore not called neutral. Both use commission, borrow and the same simplified clock as the first lab.

[ ]Net evaluation of pairs and PCABrowser
logs=np.column_stack([base,y])*.01
ret_par=np.vstack([np.zeros(2),np.diff(logs,axis=0)])
ret_par=np.expm1(ret_par)
for banda in [.4,.7]:
    w=np.zeros_like(ret_par); activa=False
    for t in range(train,len(w)):
        anterior=estimado[t-1]
        if not activa and anterior<=-banda: activa=True
        elif activa and anterior>=0: activa=False
        if activa: w[t]=np.array([-beta,1.])/(1+abs(beta))
    rr,_,turn=motor_pesos(ret_par,w)
    print('Par banda',banda,'| test neto:',resumen(rr[train:]),'| rotación:',turn[train:].sum())
for banda in [1.,1.5]:
    w=np.zeros_like(panel)
    for t in range(220,TT):
        senal=np.where(np.isfinite(score[t]) & (np.abs(score[t])>banda),-np.sign(score[t]),0.)
        bruto=np.sum(np.abs(senal))
        if bruto: w[t]=senal/bruto
    rr,_,turn=motor_pesos(panel,w)
    print('PCA banda',banda,'| test neto:',resumen(rr[220:]),'| rotación:',turn[220:].sum())
print('Registro completo: par', [.4,.7], '| PCA', [1.,1.5], '| semillas', [282602,282603])

PCA returns were treated as small simple returns and pair returns as exponential-price changes. The engine approximates costs on weights without intraday drift and does not model margin, size, borrow constraints or impact. Bands were fixed before seeing these outputs; all are shown, not just the winner. The planted pair is a demonstration, not evidence a real search finds a stable relationship. A perturbation stability test alone does not verify the entire data clock; factor parameters and eligible securities must also exist on each date. Record seed, windows, factor count, variants and rejected results with any later evaluation.

In this realization both pair bands finish positive, while PCA with band 1 loses and band 1.5 wins; that difference does not justify retrospectively choosing a configuration.

Now repeat band selection for the planted pair and PCA in later blocks. The pair is already identified by construction, so this does not evaluate a pair search: it reestimates the hedge from the past and chooses between two bands. The hedge estimated at the end of training is applied retrospectively to the same training set when comparing bands: that score is in-sample and can be optimistic. Each block’s test starts flat; the engine charges the difference between the previous block’s last weight and the new one. For PCA the band is chosen over the previous 100 days and causally calculated scores are used at each date. Blocks are short and variants highly correlated; the result is not an independent final sample if the procedure is changed after seeing it.

[ ]Walk-forward blocks for pairs and PCABrowser
def posiciones_par(e,beta,banda,inicio,fin):
    w=np.zeros((fin-inicio,2)); activa=False
    for t in range(inicio,fin):
        if t==0: continue
        if not activa and e[t-1]<=-banda: activa=True
        elif activa and e[t-1]>=0: activa=False
        if activa: w[t-inicio]=np.array([-beta,1.])/(1+abs(beta))
    return w
wp=np.zeros_like(ret_par); registros_par=[]
for inicio in range(120,len(base),20):
    e,beta_w=residuo(base,y,inicio); scores_p={}
    for b in [.4,.7]:
        ww=posiciones_par(e,beta_w,b,1,inicio)
        scores_p[b]=resumen(motor_pesos(ret_par[1:inicio],ww)[0])['sharpe']
    elegido=max(scores_p,key=scores_p.get); fin=min(len(base),inicio+20)
    wp[inicio:fin]=posiciones_par(e,beta_w,elegido,inicio,fin)
    registros_par.append((inicio,fin,beta_w,elegido,scores_p))
rp,_,_=motor_pesos(ret_par,wp)
def pesos_score(score,banda):
    valid=np.isfinite(score) & (np.abs(score)>banda)
    senal=np.where(valid,-np.sign(score),0.); bruto=np.sum(np.abs(senal),axis=1)
    return senal/np.maximum(bruto[:,None],1.)
variantes={b:pesos_score(score,b) for b in [1.,1.5]}; ws=np.zeros_like(panel); registros_pca=[]
for inicio in range(220,TT,25):
    scores_s={b:resumen(motor_pesos(panel[inicio-100:inicio],w[inicio-100:inicio])[0])['sharpe'] for b,w in variantes.items()}
    elegido=max(scores_s,key=scores_s.get); fin=min(TT,inicio+25)
    ws[inicio:fin]=variantes[elegido][inicio:fin]
    registros_pca.append((inicio,fin,elegido,scores_s))
rs,_,_=motor_pesos(panel,ws)
print('Registro par:',registros_par,'| prueba neta:',resumen(rp[120:]))
print('Registro PCA:',registros_pca,'| prueba neta:',resumen(rs[220:]))

A real search must repeat candidate selection and calibration within each training set, apply an embargo if windows overlap and concatenate only later tests, including attempts with no candidates. This example’s fits do not quantify parameter uncertainty or simulate searching a real population.

Exercises

NumericAnnual speed
If the daily AR coefficient is 0.95, what is annual κ assuming 252 days per year?
NumericMultiple search
With 4,950 null pairs and individual size 5%, how many false positives are expected?
QuizOU discretization
What is the noise variance of the exact transition of a scalar OU over Δ?
QuizProlonged crisis
What is a reasonable interpretation of trend and carry during a prolonged move?
CodeS-scores with a previous window
Implement avellaneda_lee_scores(returns,k,window). Return a matrix of the same shape, NaN before window; on each date fit PCA to the previous window centered rows, remove k components, integrate residuals and fit an AR(1) with intercept to each level. For 0<phi<1 and positive stationary deviation, return (last level−stationary mean)/deviation; otherwise NaN. Use only NumPy.
def avellaneda_lee_scores(returns,k,window):
  raise NotImplementedError()
Shift+Enter to run

Key takeaways

Key idea
A signal family is not a return: it requires a clock, hedge, costs, financing, out-of-sample evaluation and analysis of shared risks.

Historical evidence motivates hypotheses; the OU model and synthetic examples help explain mechanisms. None replaces evaluation of available data, execution and stability of the selected relationship.