Build long-short factor portfolios from a characteristic panel and test the alpha with standard errors that survive serial correlation. TRIGGER - factor model, Fama-French, Fama-MacBeth, cross-sectional regression, decile or quintile long-short sort, 2x3 sort, SMB and HML, value- weight vs equal-weight portfolio, characteristic panel, alpha t-stat, Newey-West, HAC standard errors, cov_type="HAC" maxlags, Ken French Data Library, F-F_Research_Data_Factors, book-to- market, 11-1 momentum; "my factor has a t-stat of 15", "should I lag the signal", "my HML does not match Ken French", "joining monthly factors to daily returns". SKIP for scoring one alpha signal with alphalens, IC decay or GARCH (factor-and-timeseries-research), for the covariance matrix a factor model implies (covariance-and-risk-models), for turning expected returns into weights (portfolio-optimizers), and for counting the specifications you tried (backtest-validation).
Ships in fin-models. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them; scripts run unread.
A factor portfolio is a subscript problem before it is a statistics problem. The formula for HML is public and takes one line; what decides whether your HML is a factor or a look-ahead is when the characteristic was measured relative to the return it earns. Get that wrong and the t-statistic is not weak evidence, it is manufactured evidence, and every standard error correction downstream is beside the point.
characteristic known at t -> portfolio formed at t -> return measured over t -> t+1
Every number below is printed by scripts/factor_regression.py (numpy / pandas, seed 0, about
3 s, statsmodels optional). The panel is 500 stocks x 240 months in which the truth is alpha = 0
and there is no value premium: r_it = beta_i * m_t + e_it, book equity is a slow random walk,
so book-to-market moves almost entirely with the stock's own price. Anything a sort finds in it is
an artefact.
✅ Measured, seed 0, top 30 % minus bottom 30 %, re-sorted monthly, Newey-West lags
floor(4(T/100)^(2/9)) = 4. mean and CAPM a are percent per month; CAPM a is the intercept
of the long-short return on the value-weighted market:
| formation | mean %/mo | NW t | CAPM alpha % | HAC t | beta |
|---|---|---|---|---|---|
| lag 1, value-weight (B/M at t-1) | -0.071 | -0.67 | +0.002 | 0.02 | -0.13 |
| lag 1, equal-weight | -0.038 | -0.47 | -0.003 | -0.03 | -0.07 |
| lag 6, value-weight (Fama-French-style delay) | -0.104 | -0.93 | -0.033 | -0.31 | -0.12 |
| 🚨 LEAK lag 0, value-weight (B/M at t) | -1.378 | -14.78 | -1.318 | -14.63 | -0.11 |
| 🚨 LEAK lag 0, equal-weight | -1.870 | -19.50 | -1.846 | -19.46 | -0.04 |
| 11-1 momentum, lag 1 (months t-11..t-1) | +0.065 | 0.46 | +0.022 | 0.16 | 0.07 |
| 🚨 LEAK momentum, lag 0 (window ends in month t) | +5.198 | 50.30 | +5.180 | 52.36 | 0.03 |
Read the two bolded pairs. The same panel, the same code, the same true alpha of zero: formed honestly the alpha is +0.002 %/month with t = 0.02; formed on the contemporaneous characteristic it is -1.318 %/month with t = -14.63, or +5.180 %/month with t = 52.36 if the leaked signal is momentum instead of value.
🚨 The sign is a distraction. The leaked book-to-market sort is negative because a stock that fell during month t has a higher B/M at the end of month t: "value" becomes a list of this month's losers, and the long-short is short the winners. Sort the identical panel on a signal whose leak points the other way — a momentum window whose last month is the month being predicted — and the same bug reads as a 5 %/month premium with a t-statistic of 52. A leak does not announce itself with an implausible sign; it announces itself with an implausible t-statistic. A t of 15 on 240 months of a single characteristic is not a discovery.
The guard. sort_portfolio() and fama_french_2x3() refuse lag=0 unless you pass
allow_lookahead=True, so a pipeline can call them and fail loudly rather than print a great
number:
ValueError: lag=0: the sorting characteristic would be measured at the end of the return
period it is supposed to predict (a one-period look-ahead). ...
Value-weight unless you mean to bet on microcaps. ✅ Measured: the equal-weight leak is 40 % larger than the value-weight leak (-1.846 vs -1.318 %/month alpha), because equal weighting puts the same money in the panel's 12 %-a-month idiosyncratic minnows as in its 5 % giants. The honest rows differ by almost nothing (+0.002 vs -0.003). Equal weighting does not fix a leak; it amplifies one, and it changes what the portfolio is a bet on.
✅ Source-verified 2026-09-09 at Ken French's Data Library
(mba.tuck.dartmouth.edu/pages/faculty/ken.french/Data_Library/, factor and six-portfolio
description pages):
fama_french_2x3()
implements exactly these two averages.✅ Measured on the synthetic panel (same seed, same NW lags), where truth is again zero:
| factor | mean %/mo | NW t | CAPM alpha % | HAC t |
|---|---|---|---|---|
| SMB, lag 1, re-sorted every month | -0.021 | -0.30 | +0.010 | 0.14 |
| SMB, lag 1, re-sorted every 12 months | +0.038 | 0.56 | +0.075 | 1.06 |
| 🚨 SMB, LEAK lag 0 | -0.123 | -1.73 | -0.089 | -1.20 |
| HML, lag 1, re-sorted every month | -0.016 | -0.18 | +0.024 | 0.27 |
| HML, lag 1, re-sorted every 12 months | -0.074 | -0.76 | -0.042 | -0.45 |
| 🚨 HML, LEAK lag 0 | -1.616 | -18.84 | -1.585 | -18.97 |
The leak reaches HML through the B/M sort (t = -18.97) and SMB through the size sort — a stock that fell is "small" at the end of the month — but SMB's leak is an order of magnitude weaker (-0.089, t = -1.20) because market cap is dominated by its own cross-sectional spread rather than by one month of return. A leak in a two-way sort shows up in one leg and hides in the other.
⚠️ Reproducing the published factors is a different job from implementing the formulas. Monthly
re-sorting, full-universe breakpoints and a contemporaneous ME in the ratio each give a series
that satisfies the formulas above and correlates imperfectly with the file you downloaded. If your
HML "does not match Ken French", check the re-form calendar and the breakpoint universe before
you check your code: references/ken_french_data_library.md has the full timing diagram, the two
different market equities in the ratio and the sort, and a seven-step reproduction checklist.
✅ Source-verified in the installed statsmodels 0.15.0
(statsmodels/stats/sandwich_covariance.py, statsmodels/base/covtype.py):
| what you call | nlags / maxlags | small-sample correction |
|---|---|---|
OLS(y, X).fit(cov_type="HAC", cov_kwds={"maxlags": L}) | required — kwds["maxlags"], KeyError without it | off: kwds.get("use_correction", False) |
sw.cov_hac_simple(res, nlags=L) | optional | on: use_correction=True is the signature default |
sw.cov_hac_simple(res, nlags=None) | int(np.floor(4 * (T/100)**(2/9))) inside S_hac_simple | on |
weights_bartlett(nlags) returns 1 - np.arange(nlags + 1) / (nlags + 1.0), so the weight
on lag j is 1 - j/(L+1) and L is the highest lag included, not counting lag 0. An
implementation that divides by L instead of L+1, or that treats L as a count of terms, gives
different standard errors from statsmodels on the same data.floor(4(T/100)^(2/9)) rule is not applied by fit(). It lives in S_hac_simple
and only fires when nlags is None. ✅ Measured: fit(cov_type="HAC") with no maxlags raises
KeyError: 'maxlags'. There is no default lag length in the fit() path — you must state one,
and you should state it in the paper too.fit(cov_type="HAC", cov_kwds={"maxlags": 4}) to 1.04e-17 on standard errors and
5.18e-19 on coefficients. statsmodels labels the result "Standard Errors are
heteroscedasticity and autocorrelation robust (HAC) using 4 lags and without small sample
correction".cov_hac_simple(res, nlags=4) standard errors are 1.00421054x the fit()
ones, exactly sqrt(T/(T-k)) = 1.00421054. Same estimator, two defaults; quoting the ratio is
how you tell which one produced a t-statistic.cov_hac_simple's own docstring says it is "verified only for nlags=0" and that the
correction factor is a guess needing a reference. The lag-0 case matches White exactly; the
general case matched this module's independent implementation to 1e-17, which is the check
worth running rather than trusting either.fama_macbeth() runs a cross-sectional regression of ret[t] on the characteristics at t - lag
every period, then tests the mean slope. ✅ Measured, 239 monthly cross-sections, slopes x 100:
| characteristic | slope (t-1) | t plain | t NW(4) | 🚨 slope (LEAK, t) | t plain | t NW(4) |
|---|---|---|---|---|---|---|
| log(B/M) | +0.003 | 0.08 | 0.07 | -0.901 | -19.62 | -11.61 |
| log(cap) | -0.003 | -0.19 | -0.17 | +0.009 | 0.52 | 0.40 |
Two things to take from it. First, the two-pass procedure does not repair a subscript error — the leaked slope is 300x the honest one and significant at any threshold. Second, the leak's plain t of -19.62 falls to -11.61 once the slope series is given Newey-West errors, a 41 % haircut, because the leaked slopes are strongly autocorrelated. On the honest rows the two t-statistics are indistinguishable (0.08 vs 0.07). 🚨 The Fama-MacBeth standard error is the standard deviation of the slope series; it fixes cross-sectional correlation and nothing else. Serial correlation in the slopes needs a HAC correction on top, and it is the leaked or persistent specifications where that matters most.
✅ Measured: pd.to_datetime("202607", format="%Y%m") returns 2026-07-01, a first-of-month
timestamp. Inner-joining six monthly factor rows parsed that way to a month-end strategy series
keeps 0 of 6 rows; french_period_index() + align_monthly(), which convert both sides to a
PeriodIndex(freq="M"), keep 6 of 6. A silent empty join is the most common way factor
regressions "have no data", and an inner join that silently keeps 3 of 6 is worse.
🚨 Frequency must match on both sides. The monthly file's row for 202607 is the return over
the whole month of July 2026; regress monthly strategy returns on it. The daily file stamps
YYYYMMDD and joins on the day. Regressing daily returns on monthly factors (or the reverse,
after a forward-fill) produces betas that are arithmetic, not estimates.
🚨 Check the units. ✅ Measured: the same decimal strategy regressed on the same factor column gives beta -0.004243 if the column is treated as percent and -0.4243 if it is treated as a decimal — a factor of exactly 100. ⚠️ This skill did not verify the units of the archive files themselves; read the first rows of your own download and confirm before you divide by 100.
lag=0 on any characteristic derived from price. Book-to-market, market cap, dividend
yield, earnings yield, 1/P, and any momentum window whose last period is the return period.
Section 1 is what it costs.fit(cov_type="HAC") with no maxlags. It raises; there is no default. And the two
call paths disagree by sqrt(T/(T-k)) (section 3).../../../fin-core/skills/research-integrity-guards/SKILL.md.../../../fin-core/skills/backtest-validation/scripts/trial_ledger.py before reporting the
best one.linearmodels (which ships a panel FamaMacBeth) is not installed in this environment
and nothing about it was verified here.scripts/factor_regression.py - all five sections. simulate_panel, sort_portfolio,
momentum, fama_french_2x3, newey_west, ts_alpha, fama_macbeth,
french_period_index, align_monthly, and statsmodels_hac_check, which prints the
comparison against statsmodels rather than asserting it. Without statsmodels the numpy
Newey-West is still the reference and section 3's cross-check says it was skipped. About 3 s.../../../fin-models/skills/factor-and-timeseries-research/SKILL.md owns scoring a single alpha
signal (alphalens, IC, decay, turnover) and volatility forecasting;
../../../fin-core/skills/backtest-validation/SKILL.md counts the specifications;
../../../fin-core/skills/research-integrity-guards/SKILL.md owns point-in-time universes and the
result gate; ../covariance-and-risk-models/SKILL.md turns these factors into a covariance
matrix; ../portfolio-optimizers/SKILL.md turns expected returns into weights; and
../../../fin-libraries/skills/lib-alphalens/SKILL.md is the per-library deep dive for the
signal-scoring tool.
What SKILL.md sets; muted values are Claude Code's defaults
Other plugins' skills for the same job
/fin-models:factor-modelsfrom fin-models
npx claudepluginhub howard-lynn-ye/fin-rsi --plugin fin-models13 skills in this plugin
/covariance-and-risk-modelsEstimate a covariance matrix an optimizer can actually invert, and report how much variance it hides. TRIGGER - covariance matrix estimation, sample covariance singular, "matrix is not positive definite", np.cov more assets than observations, N > T, condition number, Ledoit-Wolf shrinkage, sklearn LedoitWolf, CovarianceShrinkage, shrinkage intensity or delta, RiskMetrics EWMA, lambda 0.94 or 0.97, exponentially weighted covariance, exp_cov span, PCA or statistical factor risk model, Marchenko-Pastur, Barra fundamental factor model, specific risk, predicted vs realized volatility, risk model bias test; "my minimum-variance portfolio has 90x leverage", "the optimizer says 0% risk". SKIP for turning a covariance into weights and the optimizers themselves (portfolio-optimizers), for VaR, Expected Shortfall and their backtests (risk-measures-var-cvar), for GARCH and univariate volatility forecasting (volatility-models), and for Sharpe and drawdown conventions (portfolio-and-risk)./credit-risk-modelsEstimate a default probability and price credit, and keep the two probabilities apart - the risk-neutral one that prices and the physical one that forecasts. TRIGGER - Merton model, structural credit model, KMV, distance to default, asset value and asset volatility from equity, N(-d2), solve the two Merton equations; hazard rate, intensity, reduced form, survival probability, constant hazard, credit curve bootstrapping; CDS par spread, premium leg, protection leg, risky PV01, RPV01, accrual on default, "spread = lambda times one minus recovery", implied hazard from a CDS spread, recovery assumption, 40% recovery; risk-neutral vs physical default probability, rating agency default table, "my CDS spread is too low", credit spread from a bond price, expected loss, CVA default probability. SKIP for option pricing and Greeks (option-pricing-models, derivatives-pricing), for interest-rate curves and short-rate models (term-structure-models), and for portfolio risk and VaR (portfolio-and-risk)./factor-and-timeseries-researchJudge whether a cross-sectional factor predicts returns, and forecast financial series. TRIGGER - information coefficient, IC, quantile returns, factor decay, turnover, alphalens; Fama-French, Fama-MacBeth, PanelOLS, linearmodels, cross-sectional asset pricing; event study, abnormal returns, CAR, BHAR; Alpha101, Alpha158, symbolic alpha mining, gplearn; or forecasting with ARIMA, GARCH, volatility models, arch, Nixtla, statsforecast, mlforecast, sktime, darts, Prophet or a time-series foundation model. SKIP for computing the indicator itself (signal-construction) and for portfolio weights or Sharpe (portfolio-and-risk)./implied-vol-surfaceBuild a volatility surface that is not silently arbitrageable - invert prices to implied vols, fit a smile, check butterfly and calendar arbitrage, and interpolate between maturities. TRIGGER - implied volatility solver, Newton diverges, bisection bracket, "implied vol returns 0.001", "no implied volatility for this option", price below intrinsic, BelowIntrinsicException; SVI, raw SVI, Gatheral, svi calibration, a b rho m sigma, SviSmileSection; volatility smile, skew, surface fitting, total variance, log-moneyness; butterfly arbitrage, negative implied density, Durrleman g(k), calendar spread arbitrage, static arbitrage check, Gatheral and Jacquier 2014; interpolating the vol surface, "my interpolated surface has arbitrage", "vol interpolation between expiries". SKIP for pricing one option and the models themselves - Heston, CRR, SABR, Monte Carlo (option-pricing-models), for library choice, Greek units and licences (derivatives-pricing), and for option chain data and historical chains (options-backtesting)./option-pricing-modelsImplement an option pricing model correctly - closed form, tree, characteristic function, Monte Carlo - and the four places each silently returns a plausible wrong number. TRIGGER - Black-Scholes-Merton with dividend yield, binomial tree, CRR, Cox-Ross-Rubinstein, American early exercise, Richardson extrapolation; Heston, "the little Heston trap", branch cut, complex log, AnalyticHestonEngine, Gatheral vs BranchCorrection; SABR, Hagan 2002, sabrVolatility, ATM 0/0, z/x(z); antithetic variates, standard error, Euler discretisation bias; "my Heston price is wrong at long maturity", "my Heston price is NaN", "my binomial tree will not converge", "my Monte Carlo error bar is tiny but the price is wrong", "my tree does not match QuantLib". SKIP for choosing a pricing library, Greek units and licences (derivatives-pricing), for fitting a whole surface and its no-arbitrage checks (implied-vol-surface), and for assignment, expiry and option lifecycle (options-backtesting)./portfolio-optimizersTurn expected returns and a covariance matrix into weights, and measure what the optimizer did to your estimation error on the way. TRIGGER - portfolio optimization, mean-variance, Markowitz, efficient frontier, tangency or max-Sharpe portfolio, minimum-variance portfolio, long-only and budget constraints, scipy SLSQP or linprog for weights, Black-Litterman, BlackLittermanModel, tau, Omega, market-implied prior, views matrix P and Q, risk parity, equal risk contribution, ERC, inverse volatility, minimum CVaR, Rockafellar-Uryasev linear program, 1/N benchmark, DeMiguel Garlappi Uppal, weight turnover; "my optimizer puts 90% in one asset", "the weights change completely every month". SKIP for choosing between optimizer libraries and reporting the result (portfolio-and-risk), for the covariance matrix and its N > T failure (covariance-and-risk-models), for expected returns (factor-models), for VaR and ES (risk-measures-var-cvar), and for HRP and PyPortfolioOpt's API traps (lib-pyportfolioopt).