Package com.quantfinlib.alpha
@NullMarked
package com.quantfinlib.alpha
Cross-sectional alpha research: signal generation, evaluation,
validation, execution-aware backtesting, portfolio construction and
reporting, each a separate step.
- Signal generation:
Factors(MA crossover, contrarian RSI, MACD, Bollinger reversion, mean reversion, 12-1 momentum, value, quality, low volatility) over anAlphaContextpanel, with per-date winsorise, z-score and sector-neutralise decorators. Value and quality need point-in-time fundamentals (FundamentalsHistory); a static snapshot is refused for historical bars. - Evaluation:
SignalEvaluator: rank IC at every bar with Newey-West t-stats and IC autocorrelation, demeaned hit rate, turnover, quantile spreads, cross-factor exposure. - Validation:
AlphaValidation: walk-forward selection with observation-weighted folds and a best-of-N haircut, blocked k-fold consistency, permutation nulls (cross-sectional label permutation by default; circular shift and date permutation as diagnostics), parameter sensitivity. - Execution-aware backtest:
AlphaBacktester: next-open fills by default, weights that drift between trades, commission, spread, slippage and square-root impact, participation caps with carry-over, financing, and terminal events for held names. - Portfolio construction:
PortfolioConstruction(dollar-neutral z-score books with water-filling caps, inverse-vol budgeting, joint sector/beta/dollar neutralisation, mean-variance tilt) andTurnoverAwareOptimizer(alpha, risk, L1 turnover penalty, boxes, trade limits and neutrality equalities, solved by ADMM). - Reporting:
AlphaReport: alpha decay on lagged one-bar returns with an exponential fit, holding-period IC, OLS attribution with Newey-West errors onFactorReturnsstreams, drawdown curves, rolling Sharpe.
All scores and weights flow as double[] aligned with the
sorted AlphaContext.symbols(); NaN marks "no data" at every
stage. Factors must never read past their evaluation index. Attach a
data.PointInTimeUniverse via
AlphaContext.withUniverse(PointInTimeUniverse): non-members score
NaN, and forward returns and held positions earn delisting and merger
proceeds instead of forward-filled ghost bars.
Pricing and seasonality: FamaMacBeth
(cross-sectional premia with Newey-West errors on the premium series,
optional per-period standardisation, QR solves) and
CalendarAnomalies (day-of-week and
turn-of-month profiles with HAC t-stats and Holm-corrected flags).
Shared statistics: NeweyWest,
Ols.
-
ClassDescriptionExecution-aware factor backtest: runs a factor through a construction pipeline into target weights at each rebalance and simulates holding, trading and financing the book bar by bar.Backtest settings: decision schedule, costs and capital.Net and gross curves (one point per close from
startIndex), the cumulative fraction of equity each cost consumed, and turnover.Risk-model-driven construction forAlphaBacktester.run(AlphaContext, AlphaFactor, Config, RiskOptions): at each rebalance aFactorRiskModelis rebuilt from the panel up to the decision bar (AlphaRiskModels) and the book comes fromTurnoverAwareOptimizerstarted at the drifted book actually held.A run with its per-bar trace: the book held over each close-to-close bar, each name's P&L, the cost and the financing, all as fractions of equity at the start of the bar.Builds target weights from raw scores at a rebalance (the construction hook).Combines several alpha factors into one by information-coefficient weights that match the holding horizon, account for signal decay, remove redundancy by orthogonalisation and shrink toward equal weights.Fitted weights and the combined factor.Combination settings.The research dataset an alpha factor operates on: an index-aligned panel of price series over a fixed symbol order, with optional fundamentals and an optional point-in-time universe.A cross-sectional alpha factor: at a bar index, one raw score per symbol, where higher = more attractive to own (buy high scores, sell low).Alpha reporting: the diagnostics that explain a factor's P&L rather than just totalling it.OLS attribution with standard errors.Mean IC per cumulative horizon, plus the horizon where it first falls below half the shortest-horizon value.Lagged-return IC profile with its exponential fit.Risk model specification.Validation for alpha factors, run before any capital-weighted conclusion: Walk-forward: pick the best candidate on a training window by in-sample IC, measure it on the next unseen window, roll forward.Per-block ICs with their dispersion: consistency across regimes.One walk-forward fold.Which link the null distribution destroys.Observed mean IC against its null distribution.IC across the sweep.All folds plus the aggregate in-sample vs out-of-sample comparison.P&L attribution of a traced backtest over time: factor, specific, trading, cost and financing components per bar, with long/short leg and sector splits.Calendar anomaly profiles: day-of-week and turn-of-month seasonality with their t-statistics.Per-day-of-week profile, indexed Monday = 0 … Sunday = 6.The turn-of-month split.Strategy capacity: net Sharpe ratio against book size.Factor return streams built from the library's own factors, the inputAlphaReport.attribute(double[], double[][], List)regresses a portfolio on.The standard alpha factor library — nine signal generators covering the classic technical, factor-investing and defensive families.Fama-MacBeth (1973, J.Point-in-time fundamentals: every record is keyed by the time it became public, andFundamentalsHistory.asOf(String, long)returns only what was published by then.One published record.Heteroskedasticity and autocorrelation consistent (HAC) standard errors with Bartlett weights (Newey and West 1987, Econometrica 55(3), eq. 2).Ordinary least squares by Householder QR, with classical and Newey-West HAC standard errors.Turns raw factor scores into tradeable weight vectors, as a chain of small, composable, pure functions so a construction pipeline reads as what it does:A constructed book with what it actually achieved.Signal evaluation: the metrics that decide whether a factor is worth building a portfolio from, computed before any backtest so weak signals die cheaply.Mean forward return per score quantile:meanReturns()[0]is the lowest-scored names' average forward return, the last entry the highest-scored.The evaluation scorecard;SignalEvaluator.Report.format()renders it.Turnover-penalised, constrained mean-variance optimiser solved by ADMM.Optimiser settings.