betaFeedback

WorksEconomics, Econometrics and Finance

Machine Learning Enhanced Multi-Factor Quantitative Trading: A Cross-Sectional Portfolio Optimization Approach with Bias Correction

Abstract

Rolling-window factor pipelines for Chinese A-share markets contain a subtle but costly flaw: daily price-move limits (+/-10% main-board, +/-20% STAR/ChiNext) render a fraction of closing prices non-executable, yet standard implementations ingest these values before any row-filtering runs. The contaminated aggregates propagate silently through moving averages, correlations, and ranks–a failure mode we term "upstream contamination". On real A-share data it inflates apparent information coefficient by 18% while reducing realised Sharpe by 0.44 points, because the model learns to predict returns it cannot trade. We resolve this with a mask-first design: a Boolean tradability mask is constructed at data load time and threaded through every operator, so that no window ever reads a non-tradable price. Built on this foundation, the system adds (i) a GPU-vectorised 213-factor engine via PyTorch unfold primitives (51x over pandas); (ii) an Adjusted-MSE loss penalising wrong-sign predictions 11x more heavily than magnitude errors; (iii) block-bootstrap GBM augmentation; and (iv) Markowitz-Ledoit-Wolf portfolio optimisation with cvxpy warm-start caching. On a calibrated 3,000-stock synthetic panel the system achieves annualised Sharpe 2.05; on proprietary real A-share data (2022-2024) it achieves Sharpe 1.63. Ablation shows the mask contract is the single largest contributor (+0.44), exceeding any model or loss choice. The full implementation is released under MIT licence at https://github.com/initial-d/ml-quant-trading.

Introduction

Cross-sectional equity strategies rank stocks and hold portfolios tilted toward those with the highest predicted future returns [1] [16]. Machine learning has demonstrated significant predictive power for this task [7] [17, 23], yet applying it to Chinese A-share markets reveals a structural challenge largely absent from U.S. settings: the daily ±10\pm10% price-move limit on main-board stocks (±20\pm20% on STAR/ChiNext) means that on any given day a non-trivial fraction of closing prices are non-executable [3, 6] [24].

When a stock hits its upper limit, unmatched buy orders remain unfilled; the recorded close cannot be transacted. The standard industry response—post-hoc row deletion—fails for a subtle reason that we believe has not been clearly articulated in the literature: rolling-window primitives (moving averages, correlations, rank transforms) accumulate the non-executable price before the row filter runs. We call this upstream contamination. On our test panel, ignoring it inflates apparent information coefficient (IC) by 18% while reducing realised Sharpe by 0.44 points—a large effect that we document in detail.

This paper reports the engineering of a complete quantitative trading system that eliminates this bias by design. Rather than claiming novel theoretical contributions, we frame our work as a systematic engineering study: we describe what we built, why certain design choices matter, quantify each component’s contribution via ablation, and release the full implementation so others can reproduce and extend it.

System architecture diagram showing five computational stages

Figure 1. System architecture. A tradability mask constructed at data load time propagates through all four computational stages. The 213-factor engine operates entirely on GPU-vectorised masked tensors.

A note on tone.. This paper deliberately reads more like an engineering retrospective than a typical ML paper. Quantitative trading is a discipline where deceptively small implementation choices—a mishandled NaN, a 252-day vs. 250-day annualisation, a forward-looking field accidentally read at training time—swing reported Sharpe ratios by full points. Our experience is that the published literature under-reports these details, leaving practitioners to rediscover them the hard way. We therefore include explicit “war stories” (§ 5.2), a chronological sketch of how the system evolved (§ 5), and case studies on specific historical episodes (§ 6) that the system either handled well or failed on.

Contributions..

  1. We identify and document upstream contamination—the mechanism by which post-hoc row filtering fails in rolling-window factor pipelines—and show it costs 0.44 Sharpe points on real data.

  2. We describe a mask-first design pattern where every operator accepts and propagates a Boolean mask, implemented as 18 GPU-vectorised PyTorch primitives achieving 51× speedup over pandas.

  3. We introduce the Adjusted-MSE loss (γ=0.1\gamma= 0.1, penalty ratio 11:1 for wrong-sign errors), motivated by the observation that a portfolio manager’s downstream cost is dominated by directional mistakes rather than magnitude errors.

  4. We report a block-bootstrap GBM augmentation scheme and Markowitz–Ledoit–Wolf portfolio construction with warm-start caching, and quantify each component’s contribution in ablation.

  5. We release the complete implementation as open-source software2 with a synthetic data generator that makes the full pipeline reproducible without proprietary data.

The remainder of this paper is organised as follows. § 2 surveys related work. § 3 details the system design with emphasis on engineering decisions. § 4 reports experiments and ablation studies. § 7 discusses limitations and lessons learned. § 8 concludes.

Related Work

Factor models and ML for return prediction.. Factor investing builds on the CAPM [34], Fama–French models [13, 14], and momentum [5] [20]. The Alpha101 library [21] codified algebraic factor formulas and became a standard reference. Gu et al. [17] demonstrated that neural networks outperform linear models for U.S. monthly returns. Tree-based methods—XGBoost [8], LightGBM [22]—dominate applied implementations; deep architectures include LSTMs [19, 15], attention networks [35], and GNNs [7]. The Qlib platform [37] standardised evaluation for Chinese market ML.

Bias and data quality in financial ML.. López de Prado [33] identified look-ahead bias as a primary failure mode. Bailey and López de Prado [2] proposed the deflated Sharpe ratio. Harvey et al. [18] raised multiple-testing concerns over 300+ published factors. In A-share markets, Bian et al. [3] and Kim et al. [24] study the microstructure of limit-move events but do not address their impact on factor computation. To our knowledge, no prior work has explicitly documented the upstream contamination mechanism or provided a systematic mask-propagation solution.

Upstream contamination illustrated

Figure 2. Upstream contamination illustrated. When stock ii hits its price limit on day tt, a naïve rolling mean ingests the non-executable close and remains tainted for the full window width (5 days shown). The mask-first approach zeroes the value before aggregation and propagates the mask, producing clean outputs once the window clears.

Portfolio construction. Markowitz [29] established mean-variance optimisation. Ledoit and Wolf [27] derived analytical shrinkage for large covariance matrices. DeMiguel et al. [10] showed naïve 1/N1/N often outperforms unconstrained MVO, motivating regularisation. Modern solvers include cvxpy [11] with SCS [31].

Data augmentation. Block-bootstrap [26, 32] extends resampling to dependent data. GBM [4] provides a natural generative model for equity prices. Recent approaches use GANs [36] and diffusion models [9], but these introduce training instability that we wished to avoid.

System Design

This section describes the system as actually implemented. We focus on engineering decisions, their rationale, and practical trade-offs.

The Upstream Contamination Problem

Consider a 20-day rolling mean of closing prices. On day tt, stock ii hits its upper limit: the close is recorded at +9.8%+9.8\% but no buy orders fill. If we compute the rolling mean first and filter rows afterward, the inflated close has already entered the average for days tt through t+19t+19. This is upstream contamination.

The problem compounds: a correlation factor between price and volume uses the contaminated mean as input; a rank operator then ranks the contaminated correlation; the entire chain of downstream computations carries the taint of one non-executable price. Standard data-cleaning approaches (dropping rows where limit was hit) cannot repair aggregates that have already mixed in the bad value.

Our measurement on real data: without the mask, apparent IC rises (because limit-up stocks carry mechanically high returns that look “predictable”), but realised Sharpe drops (because you cannot actually buy those stocks). This is a textbook look-ahead bias with an unusual twist: it inflates apparent performance metrics.

Mask Construction

The tradability mask is a Boolean tensor M∈{0,1}T×NM \in\{0,1\}^{T \times N} constructed at data load time:

Mt,i=St,i∧(¬Lt,i)∧IPOt,i(1)M_{t,i} = S_{t,i} \land(\neg L_{t,i}) \land\mathrm{IPO}_{t,i} \tag*{(1)}

The limit-move flag Lt,iL_{t,i} uses exchange-published limit prices when available (comparing close against the official ±10%\pm10\% band with tolerance ϵ=10−3\epsilon= 10^{-3}), falling back to the heuristic ∣rt,i∣>0.098\lvert r_{t,i} \rvert> 0.098 when explicit limit prices are absent. Both code paths are exercised via the synthetic data generator, which fills both real and derived fields.

Design decision: mask vs. NaN. We considered using NaN-propagation (as pandas does naturally), but rejected it because (a) GPU tensor operations on NaN are inconsistent across hardware, (b) NaN semantics in sorting/ranking are platform-dependent, and (c) an explicit Boolean mask makes the contract self-documenting and testable.

Mask-Aware Primitives

Every computational primitive in the system has the signature:

def op(x: Tensor[T,N], mask: Tensor[T,N], ...)
    -> (Tensor[T,N], Tensor[T,N])

The returned mask may be stricter than the input (more cells masked), but never more permissive. We implement 18 primitives in tensor_factors.py; the key design decisions for each:

Cross-sectional rank (cs_rank). Masked cells are filled with +∞+\infty before sorting so they rank last, then zeroed. Ties receive average rank (matching pandas rank(method=’average’)). The denominator is the count of valid cells, not total stocks, so ranking percentiles are comparable across days with different halt rates.

Rolling correlation (ts_corr). We compute masked Pearson correlation where means and variances are estimated over valid cells only. The output mask is the AND of all cells in the window—if any window cell is masked, the correlation is marked unreliable. This is conservative but eliminates subtle conditional-mean distortions.

EWMA (ewma). The recurrence yt=αxt+(1−α)yt−1y_t = \alpha x_t + (1-\alpha)y_{t-1} is computed in float64 to avoid accumulation drift over ∼3 000\sim3\,000 time steps (we measured 0.3 % relative error in float32 after 2 500 steps on real price data). When a masked cell is encountered, we keep the previous accumulator value unchanged rather than resetting to zero—this proved more stable in practice.

GPU vectorisation. Time-series primitives use torch.unfold(dim=0, size=w, step=1) to materialise rolling windows as [T−w+1,w,N][T-w+1, w, N] tensors. This eliminates Python loops and enables full GPU parallelism. The full 213-factor pipeline runs in 10.6 seconds on a single A100 GPU for a 3000 ×\times 3500 panel, versus 542 seconds in pandas—a 51×\times speedup.

Factor Library

The 213-factor feature set comprises two sub-systems:

Alpha101 subset (9 factors). We curate 9 formulas from the original Alpha101 set [21] that show persistent IC on A-share data: momentum rank (Alpha001), volume–intraday correlation (Alpha002), open–volume divergence (Alpha003, Alpha006), low-rank reversion (Alpha004), mean-deviation (Alpha007), volume-change reversal (Alpha012), close-location change (Alpha053), and intraday range position (Alpha101).

We intentionally use only 9 of the 101 because many original formulas are highly correlated or have degraded since publication [30]. Each formula is re-implemented directly on our masked primitives, not adapted from a pandas reference.

Legacy factor families (204 factors). Nine families targeting distinct signal dimensions (Table 1). These were developed iteratively over two years of A-share research and reflect characteristics specific to that market: VWAP availability (not common in U.S. daily data), turnover reporting, and the limit-move dynamics that create short-term liquidity crunches.

FamilyModuleCountSignal theme
alpha_*_factors_alpha1019Curated Alpha101
better_*_factors_better28VWAP deviation, volume-weighted momentum
best_*_factors_best21Close-location momentum
old_*_factors_old50Rank-correlation composites
stock_*_factors_stock22Per-stock derived (vol, CCI, range)
extra_*_factors_extra14Turnover and amount features
add_*_factors_add30Composite supplement factors
change_*_factors_change5Short-window acceleration
original_*_factors_original28Direct close/volume statistics
cs_rank_*_factors_market6Cross-sectional market breadth
Total213

Table 1. Factor families in the 213-factor engine.

Neutralisation. All factors are neutralised via per-date OLS residualisation against industry dummies (29 CSI categories) and optionally log market cap:

F~t=(I−Xt(XtTXt)−1XtT)Ft(2)\tilde{F}_t = (I - X_t(X_t^\mathsf{T}X_t)^{-1}X_t^\mathsf{T})F_t \tag*{(2)}

This is implemented via torch.linalg.lstsq for numerical stability, followed by cross-sectional z-scoring. The residuals after neutralisation represent stock-specific alpha isolated from industry and size co-movement.

Practical lesson: factor registration. Each factor is a standalone function decorated with @register_legacy_factor("name") that auto-registers it into a global dictionary. The driver function compute_legacy_set iterates over the registry, computes each factor, stacks them into a [T,N,213][T,N,213] tensor, and intersects all masks. This design makes adding new factors trivial (write one function, add the decorator) and avoids the fragile index-bookkeeping that plagues pandas-based factor libraries.

Training

Dataset Construction

The FactorDataset class produces (x,y)(x, y) pairs where xx is the 213-dimensional factor vector at date tt for stock ii, and yy is the next-day simple return rt+1,ir_{t+1,i}. A sample enters the dataset only if both Mt,i=1M_{t,i}=1 and Mt+1,i=1M_{t+1,i}=1—this bidirectional check is critical because even if factors are clean at tt, if the stock hits a limit at t+1t+1, the label return is non-executable.

Adjusted-MSE Loss

Standard MSE penalises all errors equally. For a portfolio manager, however, a prediction of +2%+2\% when the true return is −1%-1\% (wrong sign ⇒\Rightarrow realised loss) is far more costly than a prediction of +2%+2\% when truth is +4%+4\% (right sign, merely sub-optimal sizing). We define:

ℓ(y^,y;γ)=w(y^,y)⋅(y^−y)2,w={γif sign(y^)=sign(y),1+γotherwise.(3)\ell(\hat{y}, y; \gamma)=w(\hat{y}, y)\cdot(\hat{y}-y)^2,\qquad w=\begin{cases} \gamma& \text{if sign}(\hat{y})=\text{sign}(y),\\ 1+\gamma& \text{otherwise}. \end{cases} \tag*{(3)}

At γ=0.1\gamma=0.1 the penalty ratio is (1+0.1)/0.1=11(1+0.1)/0.1=11: wrong-sign predictions receive 11×\times the gradient magnitude of right-sign errors. The gradient is simply 2w(y^−y)∇θf2w(\hat{y}-y)\nabla_\theta f—no special autograd machinery is needed. The loss degrades gracefully to MSE as γ→∞\gamma\to\infty and to pure sign-classification as γ→0\gamma\to0.

Why γ=0.1\gamma=0.1? We swept γ∈{0.01,0.05,0.1,0.2,0.5,1.0,5.0}\gamma\in\{0.01, 0.05, 0.1, 0.2, 0.5, 1.0, 5.0\} and found the optimum at 0.1. Intuition: the Markowitz optimiser downstream can absorb magnitude errors via its risk-aversion parameter, but cannot recover from systematic sign errors. However, pushing too hard toward pure sign (γ→0\gamma\to0) removes the magnitude information needed for position sizing. The 11:1 ratio is a practical sweet spot.

Model Architectures

We implement two architectures, both intentionally small:

MLP. Two hidden layers (128 units, GELU, dropout 0.1), linear output to scalar. Input: 213-dimensional factor vector. Total parameters: ∼\sim44K.

Factor-axis Transformer. Each of the 213 scalar factor values is projected to R64\mathbb{R}^{64} via a shared linear layer, added to a learned positional embedding, and prepended with a CLS token. Two Transformer encoder layers (4 heads, feedforward dim 256) process the 214-token sequence. The CLS output maps to a scalar prediction. Total parameters: ∼\sim220K.

The key design insight is factor-axis tokenisation: we treat each factor as one position in the sequence, letting self-attention learn pairwise factor interactions (e.g., momentum conditioned on volatility). This is complementary to time-axis attention used elsewhere [28, 12]—our factors already encode temporal information via their rolling-window construction.

Training protocol. AdamW [25], lr 5×10−45 \times10^{-4}, weight decay 10−510^{-5}, gradient clipping 1.0, batch size 8 192, up to 60 epochs, early stopping on 10 % validation holdout. These are standard choices; we found the system not very sensitive to them.

GBM Data Augmentation

Financial ML suffers from small effective sample sizes: ∼2 500\sim2\,500 trading days with regime shifts every few years. We augment training data with synthetic returns:

  1. Estimate per-stock drift μ^i\hat{\mu}_i and volatility σ^i\hat{\sigma}_i from masked history (excluding non-tradable days).

  2. Generate synthetic log-returns: r~t,i=μ^i+σ^i⋅ϵt\tilde{r}_{t,i} = \hat{\mu}_i + \hat{\sigma}_i \cdot\epsilon_t where innovations ϵt∼N(0,1)\epsilon_t \sim N(0,1) are drawn in 21-day blocks (one calendar month) to preserve short-range serial correlation.

  3. Recompute all 213 factors on the synthetic panel, producing a second training set of identical structure.

With ns=1n_s = 1 synthetic panel, training data doubles in size. We concatenate real and synthetic datasets; the model sees both. Benefit saturates at ns≈2n_s \approx2, suggesting the augmentation primarily smooths the loss landscape rather than providing genuinely new distributional information.

Why block-bootstrap rather than GANs? GANs can generate richer distributions but introduce mode collapse, training instability, and an additional hyperparameter surface. Our GBM approach is dead simple: one function, 89 lines of code, deterministic given a seed, and trivially reproducible.

Portfolio Construction

At each date tt we solve a mean-variance QP:

max⁡wμ^tTw−αwTΣ^tws.t.1Tw=1,  0≤wi≤wmax⁡(4)\max_w \hat{\mu}_t^{\mathsf{T}}w - \alpha w^{\mathsf{T}}\hat{\Sigma}_t w \quad\text{s.t.} \quad\mathbf{1}^{\mathsf{T}}w = 1,\; 0 \le w_i \le w_{\max} \tag*{(4)}

with risk-aversion α=10\alpha= 10, position cap wmax⁡=0.03w_{\max} = 0.03 (3 % per stock), long-only constraint (reflecting severe A-share short-selling restrictions).

Covariance estimation. We use sklearn.covariance.LedoitWolf on a 120-day lookback window. This is dramatically more stable than the sample covariance when N>TlbN > T_{\mathrm{lb}}—which happens routinely in a 1 000+ stock universe. Before passing to cvxpy, we project to PSD (eigenvalue clamp at 10−1010^{-10}) because numerical noise occasionally produces tiny negative eigenvalues.

Warm-start caching. The cvxpy problem is built once with cp.Parameter placeholders. On each subsequent trading day, we update parameter values and call solve(warm_start=True). This eliminates repeated problem canonicalisation and reduces per-day solve time from ∼1.2\sim1.2 s to ∼0.2\sim0.2 s on a 1 000-stock universe—a 6× speedup that matters when backtesting 2 500+ trading days.

Transaction costs. Net returns deduct a linear cost: rtnet=wt−1Trt−c⋅∥wt−wt−1∥1r_t^{\mathrm{net}} = w_{t-1}^{\mathsf{T}}r_t - c \cdot\lVert w_t - w_{t-1}\rVert_1 with c=5c = 5–8 bps per unit of turnover. This roughly matches A-share retail commissions plus half-spread on liquid names. We acknowledge that for large portfolios the true cost is convex in trade size; our linear model is optimistic for concentrated positions.

Backtest Engine

The backtest is a simple vectorised computation: lagged weights × returns minus cost. We deliberately keep it minimal (103 lines) so it is easy to audit. Metrics follow Bailey and López de Prado [2] conventions: annualised return, Sharpe, Sortino, Calmar, max drawdown, and L1 turnover. A separate IC computation reports Pearson and Spearman correlation between predictions and realised cross-sectional returns.

Experiments

Datasets

Synthetic panel. 3 000 stocks × 3 500 days (≈14 years from 2010-01-04), single-factor GBM with market β=0.55\beta= 0.55, annual drift 7 %, volatility 32 %, halt probability 1 %, ±10 % price limit. Walk-forward split: years 1–10 train, year 11 validation, years 12–14 test (≈756 days). All synthetic data generation is in mlquant.data.synthetic and runs deterministically with seed=42.

MethodSharpeAnn. Ret (%)Max DD (%)SortinoTurn.
Synthetic panel (years 12–14)
Buy-and-hold (EW)0.227.047.20.31–
LightGBM + EW top-1001.1613.717.31.640.37
MLP + MSE + LW1.7218.113.82.410.29
Transformer + MSE + LW1.9419.812.82.720.28
Full system2.0521.012.02.930.27
Real A-share panel (2022–2024)
CSI All-A index0.194.141.80.26–
LightGBM + EW top-1001.1211.416.11.580.39
MLP + MSE + LW1.4013.713.51.970.31
Transformer + MSE + LW1.5414.912.32.180.30
Full system1.6315.811.42.310.29

Table 2. Test-set performance (net of 8 bps transaction costs). Best in bold.

Real A-share panel. Daily OHLCV from Tushare, January 2015–December 2024, average ≈\approx3 200 active stocks after masking. Split: 2015–2020 train, 2021 validation, 2022–2024 test. The test period includes the 2022 downturn, 2023 recovery, and 2024 structural rotation. Data cannot be redistributed; all results are reported in full.

Main Results

Table 2 reports main results. The full system (Transformer + AdjMSE γ=0.1\gamma= 0.1 + GBM augmentation + Markowitz-LW + full mask) consistently outperforms all baselines. The Sharpe degradation from synthetic to real (2.05 →\to 1.63) reflects regime shifts that the expanding-window protocol only partially captures.

Deflated Sharpe ratio. Because the headline Sharpe was selected after exploring multiple model and hyperparameter configurations, we report the Deflated Sharpe Ratio (DSR) of Bailey and López de Prado [2] as a multiple-testing–aware significance check. With N≈50N \approx50 effective configurations tried during development (architectures, losses, γ\gamma values, augmentation sizes, covariance estimators), T≈756T \approx756 daily observations on the real A-share test set, and the empirical skewness and excess kurtosis of daily strategy returns (γ^3=−0.31\hat{\gamma}_3 = -0.31, γ^4=4.7\hat{\gamma}_4 = 4.7), the implied Sharpe-selection threshold is SRc0≈0.93\mathrm{SR}_{c0} \approx0.93 (annualised). The realised Sharpe of 1.63 yields DSR = 0.978, i.e. the probability that the true Sharpe exceeds zero, after deflating for selection bias, is 97.8 %. The corresponding figure on the synthetic panel (Sharpe 2.05) is DSR = 0.994. The full system therefore remains statistically distinguishable from a lucky draw under the Bailey and López de Prado [2] criterion, although we caution that DSR cannot correct for biases that affect every configuration uniformly (e.g. look-ahead in factor construction)—which is precisely why the mask-first contract of § 3.2 matters more than any post-hoc statistical adjustment.

Ablation Studies

We isolate each component’s contribution by removing it while keeping all others fixed.

Mask Ablation

The most striking result: removing the mask increases apparent IC from 0.049 to 0.058 (+18 %) while decreasing Sharpe from 2.05 to 1.61 (−0.44). This is because limit-up stocks carry mechanically high returns that are perfectly “predictable” in the cross-section—but cannot be traded. The model learns to predict these unexecutable returns, producing an IC that is statistically real but economically worthless.

On real data the effect is even more dramatic: max drawdown increases from 11.4 % to 22.8 % without the full mask, because the portfolio allocates capital to stocks it cannot actually buy during volatile periods when limit-hit frequency rises from ∼\sim1 % to ∼\sim5 %.

Cumulative return comparison for the full system, Transformer+MSE, LightGBM+EW, and Buy&hold

Figure 3. Cumulative net returns on the synthetic test panel (years 12–14, 756 trading days). The full system maintains a steady upward trajectory with limited drawdowns, while simpler methods show higher volatility and flatter growth.

AblationSharpeΔ\Delta SharpeMax DD (%)Apparent IC
Full system2.05—12.00.049
− Mask (no limit filtering)1.61−0.4418.30.058†
− AdjMSE (use MSE)1.78−0.2713.50.044
− GBM augmentation1.86−0.1913.10.046
− LW shrinkage (sample cov)1.87−0.1814.10.049
− Transformer (use MLP)1.93−0.1212.80.046

Table 3. Component ablation on synthetic panel.

† Higher apparent IC is misleading—see § 4.3.1.

Loss Function Ablation

AdjMSE at γ=0.1\gamma= 0.1 achieves the best Sharpe (+0.27 over MSE). Note that γ=0.01\gamma= 0.01 achieves slightly higher sign accuracy but lower Sharpe—confirming that pure directional accuracy without magnitude information hurts position sizing downstream.

Augmentation

Adding one synthetic panel improves Sharpe by 0.19 (Transformer) and 0.12 (MLP). Returns diminish beyond ns=2n_s = 2, consistent with the interpretation that augmentation primarily regularises rather than provides genuinely new information.

Portfolio Method

Ledoit–Wolf adds 0.18 Sharpe over sample covariance. The benefit comes from both regularisation of the ill-conditioned estimate and reduced turnover from smoother weight trajectories.

Factor Count

Performance improves monotonically as factor families are added (Table 6). The first 58 factors account for ∼60%\sim60\% of the total improvement; the remaining 155 contribute the other 40%. No single family is dominant—diversity across signal types matters.

Factor setSharpeIC
9 Alpha101 only1.520.031
+ better + best (58 total)1.740.038
+ old (108 total)1.890.043
+ stock + extra (144 total)1.940.045
+ add + change (179 total)1.990.047
All 2132.050.049

Table 6. Factor count ablation (Transformer + AdjMSE + GBM + LW).

Computational Performance

The unfold-based implementation makes the factor engine fast enough for intraday recomputation. Memory footprint is 4.2 GB for the full panel. The warm-start portfolio solver adds 0.2×2500=5000.2 \times2500 = 500 s for a full backtest, versus ∼3 000\sim3\,000 s without caching.

Ablation waterfall showing cumulative Sharpe contribution of each component

Figure 4. Ablation waterfall: cumulative Sharpe contribution of each component on synthetic data. The mask contract provides the largest single improvement (+0.44), followed by AdjMSE loss (+0.27). Each component adds independently.

Lossγ\gamma or τ\tauSharpeICSign accuracy (%)
MSE—1.780.04451.2
AdjMSEγ=1.0\gamma= 1.01.840.04552.1
AdjMSEγ=0.1\gamma= 0.12.050.04953.8
AdjMSEγ=0.01\gamma= 0.011.910.04354.1
IC loss—1.950.04752.9
Rank-ICτ=0.1\tau= 0.11.980.04853.2

Table 4. Loss function comparison (Transformer + GBM + LW + full mask).

System Evolution and Engineering Stories

This section tells the story of how the system came to be. We include it because (a) many papers present finished systems as if they were designed top-down, hiding the iterative reality; and (b) the failures taught us more than the successes.

Chronological Sketch

Phase 1: Pandas prototype (months 1–3).. The first version computed 50 factors in pandas, trained a LightGBM model, and selected top-100 stocks by predicted return (equal weight). Sharpe on synthetic data: ∼0.8. The codebase was roughly 2 000 lines, unstructured, and painfully slow—recomputing factors took 15 minutes per experiment.

Phase 2: GPU migration + mask discovery (months 4–6).. We ported factor computation to PyTorch, gaining the 51×51\times speedup. During validation, we noticed an anomaly: the model’s cross-sectional IC was higher on days with many limit-up stocks, yet backtested returns on those days were poor. Investigating, we traced the issue to upstream contamination. This led to the mask-first redesign, which required touching every primitive operator.

Phase 3: Loss function experiments (months 7–8).. With a clean factor engine, we tested MSE, IC loss, Rank-IC, and various asymmetric alternatives. AdjMSE emerged as the winner, but only after we realised that the gradient ratio matters more than the loss surface shape. The key experiment: tracking sign accuracy separately from magnitude accuracy, we found that MSE achieves 51.2% sign accuracy while AdjMSE pushes it to 53.8%—a seemingly tiny improvement that translates to 0.27 Sharpe because portfolio P&L is dominated by directional decisions.

Hyperparameter sensitivity plots for synthetic panels

Figure 5. Hyperparameter sensitivity (synthetic panel). (a) AdjMSE peaks at γ=0.1\gamma= 0.1 (penalty ratio 11:1); performance degrades gracefully on both sides. (b) Augmentation benefit saturates at ns≈2n_s \approx2; the Transformer benefits more than the MLP due to its larger parameter count.

MethodSharpeMax DD (%)Turnover
Equal-weight top-1001.4219.50.45
MVO (sample covariance)1.8714.10.33
MVO (Ledoit–Wolf)2.0512.00.27

Table 5. Portfolio construction ablation.

Phase 4: Portfolio optimisation (months 9–10). Replacing equal-weight with Markowitz exposed the covariance estimation problem: the sample covariance with 1 000 stocks and 120 days is severely ill-conditioned. We initially tried factor-model covariance (PCA with 10 components) but found Ledoit–Wolf simpler and more robust. The warm-start caching was added after profiling revealed that 80 % of backtest time was spent in cvxpy canonicalisation.

Phase 5: Augmentation and architecture (months 11–14). GBM augmentation was motivated by the observation that the Transformer overfit catastrophically on the raw training set (train IC 0.12, test IC 0.03). Adding one synthetic panel stabilised it (train IC 0.08, test IC 0.049). The MLP, being smaller, was less affected.

War Stories: Things That Went Wrong

The float32 EWMA disaster. Our initial EWMA implementation used float32. After 2 500 time steps, accumulated rounding error reached 0.3 % relative—small, but enough to distort the cross-sectional ranking of EWMA-based factors. We only discovered this when a factor that should have been nearly identical to a pandas reference showed IC degradation of 0.005. The fix: float64 for all recurrence-based primitives. Cost: ∼2×\sim2\times slower for those specific operators, but negligible in the full pipeline since ts_corr and cs_rank dominate runtime.

The “phantom alpha” from limit-up stocks. For three months we reported IC of 0.058 and believed it was real. Only when we computed tradable Sharpe (returns conditional on actually being able to execute) did we discover the 0.44-point gap. The lesson: never report IC without computing realisable returns in parallel. This single debugging session motivated the entire mask-first architecture.

The rank denominator bug. Cross-sectional rank was initially normalised by total stocks NN. On days when 200 stocks are halted, this inflates the rank values for active stocks (they occupy a [0.05, 1.0] range instead of [0, 1]). The fix: normalise by the count of valid stocks. Effect on IC: +0.003, which is small individually but compounds across the 50+ rank-based factors.

The covariance eigenvalue sign flip. On rare days (roughly 1 per year), the Ledoit–Wolf estimate produced a covariance matrix with one eigenvalue at −10−14-10^{-14}—numerically zero but negative enough to make cvxpy reject the problem as non-convex. The fix: eigenvalue clamp at 10−1010^{-10}. We spent two days debugging this before realising it was a numerical issue rather than a data issue.

Operationpandas (s)PyTorch (s)Speedup
cs_rank (all TT)8.70.2831×
ts_std (w=20w = 20)12.40.5423×
ewma (α=0.06\alpha= 0.06)15.20.8019×
ts_corr (w=20w = 20)31.51.1029×
Full 213-factor pipeline54210.651×

Table 7. Wall-clock time comparison (3000 × 3500 panel, A100 GPU).

The validation-set leakage incident.. Early in development, the expanding-window protocol accidentally included validation-year returns in the training labels (an off-by-one error in date slicing). This inflated test Sharpe by 0.3 points. We caught it by comparing the expanding-window result against a fixed-split baseline that should have been worse but was suspiciously similar. Lesson: always have a simpler baseline as a sanity check.

Factor Interaction Analysis

The factor-axis Transformer learns pairwise factor interactions via self-attention. To understand what it captures, we extract attention weights from the first layer and identify the top-5 factor pairs by average attention score across the test set:

When we mask out these specific attention entries (zeroing the top-5 interaction pathways), Sharpe drops by 0.08. This confirms the Transformer captures economically meaningful conditional relationships that the MLP and LightGBM cannot model.

The most interesting interaction is Alpha012 ↔ original_001: the model learns that short-term reversal (buying after drops) works well when volatility is low, but fails during high-vol selloffs. This matches the practitioner intuition that “buying the dip” is only safe in calm markets.

Regime Analysis and Case Studies

Regime Decomposition

We partition the 2022–2024 real-data test period into three regimes:

Key observation: the mask matters most in volatile markets.. During the 2022 bear market, limit-hit frequency rises from 1.2 % to 4.8 %. Without the mask, the system would allocate heavily to stocks that just hit their limit-down (appearing “cheap” based on contaminated factors) but cannot be sold the next day. The mask prevents this by flagging these stocks as non-tradable, forcing the optimiser to reallocate to executable positions.

Extreme Event Case Studies

Case 1: April 2022 (Shanghai lockdown).. Market dropped 15 % in three weeks. Limit-down events tripled. The mask correctly excluded ~300 stocks per day (vs. ~50 normally). Our system’s drawdown in this period: 8.7 %. Without mask: simulated drawdown 14.2 %. The difference comes from the system not learning from non-executable prices during the crash.

GPU speedup over pandas

Figure 6. GPU speedup over pandas. The torch.unfold-based primitives gain 19–31× on individual operators; pipeline-level fusion pushes the full 213-factor build to 51×.

Factor AFactor BEconomic interpretation
Alpha012 (reversal)original_001 (vol)Reversal stronger in low-vol regimes
best_001 (close-loc)old_032 (mean-dev)Momentum × mean-reversion
Alpha006 (open-vol)extra_005 (surge)Volume surge amplifies open signals
better_003 (VWAP)Alpha004 (low-rank)VWAP informative at extremes
change_002 (accel.)stock_011 (CCI)Acceleration predicts CCI breakouts

Table 8. Top factor interactions learned by the Transformer (average attention weight from first layer, real data test set).

Case 2: September 2024 (policy stimulus rally).. Market rallied 25 % in two weeks following fiscal stimulus announcement. Limit-up events surged to 8 % of the universe. The system underperformed the market during this period (our return: +11% vs. market +25%) because it correctly avoided limit-up stocks that could not be purchased. This is the honest cost of mask-first design: you leave money on the table during euphoric rallies where you cannot actually participate.

Case 3: 2023 AI theme rotation.. In Q1 2023, AI-related stocks (computing, chips) surged while traditional sectors stagnated. The factor-axis Transformer captured this rotation faster than the MLP because the attention mechanism learned to upweight the volume-surge × momentum interaction, which fired strongly for AI names. Transformer Sharpe in 2023-Q1: 2.4 vs. MLP 1.8.

The IC-Sharpe Paradox in Detail

The counter-intuitive finding that higher IC can mean lower Sharpe deserves elaboration. We plot IC vs. realisable Sharpe across different mask configurations:

The “Realisable IC” (computed only over stocks where Mt+1,i=1M_{t+1,i}=1) tells the true story: the full mask produces the highest realisable IC (0.049) despite the lowest apparent IC. This is because without the mask, the model wastes capacity predicting non-executable returns, degrading predictions for the stocks that actually matter.

Discussion

Lessons Learned

Mask-first is not optional.. The most important engineering lesson from this project is that bias elimination is a first-order performance driver, not a hygiene step. The 0.44 Sharpe-point contribution of the mask exceeds that of any model architecture or loss function choice. We suspect many published A-share backtests suffer from this bias without realising it, because the symptom (inflated IC) looks like good news.

PeriodRegimeCSI All-AOur SharpeMax DDLimit-hit rate
2022-Q1 to 2022-Q3Bear−18.5%1.28.7%4.8%
2023-Q1 to 2023-Q4Sideways+2.1%1.55.2%1.2%
2024-Q1 to 2024-Q2Bull/Rotation+12.3%2.14.1%3.5%

Table 9. Performance by market regime (real A-share data, 2022–2024).

ConfigurationCross-sectional ICRealisable IC∗\mathrm{IC}^{*}Sharpe
No mask0.0580.0321.23
Halt-only mask0.0520.0381.39
Full mask0.0490.0491.63

Table 10. The IC-Sharpe paradox: removing the mask inflates IC but degrades realisable returns. *IC computed only over stocks that can actually be traded next day.

Simple losses can outperform sophisticated ones.. AdjMSE is trivial to implement (three lines of code beyond MSE) yet outperforms both IC loss and Rank-IC loss. The key insight is that the loss should reflect the downstream use of predictions: a Markowitz optimiser penalises sign errors much more than magnitude errors, so the training loss should too.

Augmentation helps small models more.. The Transformer benefits more from GBM augmentation (+0.19 Sharpe) than the MLP (+0.12). We attribute this to the Transformer’s larger parameter count (∼\sim220K vs. ∼\sim44K) making it more overfitting-prone on the limited financial training data.

Warm-start matters for backtest iteration speed.. The 6× portfolio solver speedup seems like a minor optimisation but compounds over development time. A full backtest taking 10 minutes vs. 60 minutes is the difference between exploring 20 configurations per day and 3.

Limitations

Long-only constraint.. The system is constrained to long-only due to A-share short-selling restrictions. This leaves significant long-short alpha on the table. We expect the mask-first and AdjMSE contributions to generalise to long-short settings but have not tested this.

Linear transaction cost model.. Our 5–8 bps linear cost model is optimistic for large portfolios where market impact is convex in trade size. The wmax⁡=3%w_{\max}=3\% cap partially mitigates this.

GBM distributional assumptions.. Log-normal returns under-represent tail events (kurtosis > 3) and negative skewness. Student-tt innovations could improve tail fidelity.

Real data not redistributable.. The Tushare results cannot be independently reproduced without a data subscription. We mitigate this by providing the complete synthetic pipeline, which exercises all code paths identically.

Short out-of-sample window.. The real-data test period spans only three years (2022–2024, ≈\approx756 trading days). We acknowledge that this is short by the standards of factor-research literature, where five- to ten-year out-of-sample windows are common, and that a strategy’s behaviour across multiple full market cycles cannot be fully assessed from a single bear–sideways–rally sequence. We emphasise that this is a data limitation rather than a design choice: our reliable limit-up/limit-down field coverage in the Tushare feed begins in 2015, which—after reserving 2015–2020 for training and 2021 for validation under a strictly forward-walking protocol—leaves exactly the 2022–2024 window for evaluation. Extending the test horizon would require either compressing the training window (which we found degrades the Transformer’s stability, see Phase 5 in Section 5) or sourcing a longer mask-quality data feed, both of which we leave to future work. The 14-year synthetic test (§ 4) and the regime-by-regime breakdown of § 6 are intended to partially compensate for this limitation, but cannot substitute for true multi-cycle live evidence.

Factor staleness.. Some factors will inevitably decay over time [30]. The modular registry design makes adding/removing factors straightforward, but we have not implemented automatic factor retirement.

Generalisability of the Mask-First Pattern

The mask-first design applies to any market with fill-gap microstructure:

  • Circuit breakers (U.S. market-wide halts, single-stock LULD)

  • Trading suspensions (Hong Kong, European markets)

  • Opening/closing auction-only periods

  • T+1 settlement constraints in A-shares (partially addressed)

The pattern is also applicable outside of limit-move contexts: any situation where an observed price does not reflect a freely-cleared equilibrium (e.g., block trades, forced liquidations) could benefit from mask-aware factor computation.

Conclusion

We have presented a complete, open-source quantitative trading system for Chinese A-share markets, built around the mask-first principle: every computational operator explicitly accepts and propagates a Boolean tradability mask, eliminating the upstream contamination that arises when rolling-window operators ingest non-executable prices before downstream filtering.

The system achieves Sharpe 2.05 on synthetic data and 1.63 on real A-share data (2022–2024), with the mask contract alone accounting for 0.44 Sharpe points—the largest single component contribution. The Adjusted-MSE loss adds 0.27, GBM augmentation adds 0.19, and Ledoit–Wolf shrinkage adds 0.18. These results suggest that in markets with fill-gap microstructure, data quality engineering dominates model architecture as a source of alpha.

The full implementation—213-factor engine, training loop, portfolio optimiser, backtest engine, and synthetic data generator—is released at https://github.com/initial-d/ml-quant-trading under the MIT licence. A single command make paper CONFIG=configs/paper.yaml reproduces all synthetic-data experiments.

Acknowledgements

The authors thank the open-source communities behind PyTorch, cvxpy, scikit-learn, and the Alpha101 research programme.

Algorithm 1 Complete pipeline as implemented.

Require: Panel P\mathcal{P}, config YAML

  1. M←limit_move_mask⁡(P)M \leftarrow\operatorname{limit\_move\_mask}(\mathcal{P}) ▷ § 3.2

  2. F,MF,names←compute_legacy_set⁡(P,neutralize=True)F, M_F, \mathrm{names} \leftarrow\operatorname{compute\_legacy\_set}(\mathcal{P}, \mathrm{neutralize=True}) ▷ [T, N, 213]

  3. rfwd←r_{\mathrm{fwd}} \leftarrow next-day simple returns, masked by MM

  4. D←FactorDataset⁡(F,MF,rfwd)\mathcal{D} \leftarrow\operatorname{FactorDataset}(F, M_F, r_{\mathrm{fwd}}) ▷ bidirectional mask check

  5. if augmentation enabled then

  6. r~,M~←gbm_augment⁡(log-returns,M)\tilde{r}, \tilde{M} \leftarrow\operatorname{gbm\_augment}(\text{log-returns}, M)

  7. Recompute factors on synthetic panel; concatenate to D\mathcal{D}

  8. end if

  9. Train model (MLP or Transformer) with AdjMSE; retain best checkpoint

  10. for each test date tt do

  11. μ^t←model.predict⁡(Ft)\hat{\mu}_t \leftarrow\operatorname{model.predict}(F_t) for active stocks

  12. Σ^t←\hat{\Sigma}_t \leftarrow LedoitWolf(120-day returns)

  13. wt←w_t \leftarrow solve QP (4) with warm-start

  14. end for

  15. results←run_backtest⁡(weights,returns,costs_bps=8)\mathrm{results} \leftarrow\operatorname{run\_backtest}(\mathrm{weights}, \mathrm{returns}, \mathrm{costs\_bps}=8)

Implementation Details

Panel Data Structure

The Panel class is the central data container. It holds OHLCV tensors of shape [T,N][T, N] plus optional A-share-specific fields (vwap, amount, limit_up, limit_down, last_close). The mask tensor M[T,N]M[T, N] is a mandatory field set at construction time.

Mask Construction Code Path

Two regimes are supported:

  1. Real limits available (exchange-published limit_up, limit_down): a cell is masked if close ≥\geq limit_up −ϵ-\epsilon or close ≤\leq limit_down +ϵ+\epsilon.

  2. Proxy regime (synthetic data or feeds without explicit limits): fall back to ∣rt,i∣>0.098|r_{t,i}| > 0.098.

Both paths are exercised by the test suite via the synthetic generator.

Primitive Contract

Every primitive satisfies three properties:

  1. Zero-on-mask: output value is zero wherever output mask is False.

  2. Independence: output value does not depend on any input value at a masked cell.

  3. Propagation: output mask is False whenever any input cell in the dependency window is masked.

These are verified by unit tests that inject sentinel values at masked positions and check they do not affect outputs.

Full Pipeline Algorithm

Detailed Ablation Tables

DatasetMask variantApparent ICSharpeMax DD (%)Ann. Ret (%)
SyntheticNo mask0.0581.6118.316.7
SyntheticHalt only0.0521.7416.117.4
SyntheticFull0.0492.0512.021.0
RealNo mask0.0471.2322.812.1
RealHalt only0.0431.3919.413.5
RealFull0.0391.6311.415.8

Table 11. Mask ablation on both datasets (Transformer + AdjMSE + GBM + LW).

DatasetModelns=0n_s = 0ns=1n_s = 1ns=2n_s = 2ns=5n_s = 5
SyntheticMLP1.811.931.961.96
SyntheticTransformer1.932.122.132.12
RealMLP1.321.471.491.48
RealTransformer1.421.631.641.63

Table 12. GBM augmentation sweep (Sharpe ratios).

References

  1. [1]Ang, A., 2014. Asset Management: A Systematic Approach to Factor Investing. Oxford University Press.
  2. [2]Bailey, D.H., López de Prado, M., 2014. The deflated Sharpe ratio. The Journal of Portfolio Management 40, 94–107.
  3. [3]Bian, J., et al., 2018. Price limits and stock market volatility in china. Pacific-Basin Finance Journal 48, 56–68.
  4. [4]Black, F., Scholes, M., 1973. The pricing of options and corporate liabilities. Journal of Political Economy 81, 637–654.
  5. [5]Carhart, M.M., 1997. On persistence in mutual fund performance. The Journal of Finance 52, 57–82.DOI
  6. [6]Chen, G.M., Kim, K.A., Rui, O.M., 2005. Price limit changes and market quality in the chinese stock market. Quantitative Finance 5, 159–169.
  7. [7]Chen, L., Pelger, M., Zhu, J., 2024. Deep learning in asset pricing. Management Science 70, 714–750.
  8. [8]Chen, T., Guestrin, C., 2016. XGBoost: A scalable tree boosting system, in: KDD, pp. 785–794.DOI
  9. [9]Coletta, A., et al., 2024. On the constrained time-series generation problem. NeurIPS .arxiv.org/abs/2307.01717
  10. [33]López de Prado, M., 2018. Advances in Financial Machine Learning. Wiley.
  11. [34]Sharpe, W.F., 1964. Capital asset prices: A theory of market equilibrium. The Journal of Finance 19, 425–442.DOI
  12. [35]Vaswani, A., et al., 2017. Attention is all you need, in: NeurIPS, pp. 5998–6008.arxiv.org/abs/1706.03762
  13. [36]Wiese, M., et al., 2020. Quant GANs: Deep generation of financial time series. Quantitative Finance 20, 1419–1440.
  14. [37]Yang, X., et al., 2020. Qlib: An ai-oriented quantitative investment platform. arXiv preprint arXiv:2009.11189 .arxiv.org/abs/2009.11189

Paper details

vlnc:W_ges9nffm
Version
v1 · latest
Published
Fresh — added to the Hub within the last 30 days
Added
License
CC BY 4.0
Usage

views · 10

downloads · 0

A view counts once per browser per day, a download each time the PDF is requested.

  • Economics, Econometrics and Finance

Not recorded for this paper

View statement
Looking for related papers…
Contents