Cross-sectional stock selection on point-in-time CSI 300 data: LightGBM, XGBoost, LSTM, ALSTM, GRU and a Transformer, scored by rank IC and a costed top-k back-test
Each trading day, every model scores the stocks that are in the CSI 300 on that day, using only
information available at that day's close. The highest-scored k stocks are bought at the next open,
held for h days, and the portfolio is compared with the CSI 300 index after commissions and stamp duty.
The models are trained on 2012–2016, early-stopped on 2017, and evaluated once on 2018-01 to 2020-09.
Note
History. The first version (April 2025) was written under my older GitHub account
trader-jackson; the model architectures in models/, the
pairwise ranking loss and the top-k / holding-period back-test idea draw on
FinTSB and StockFormer.
The November 2026 revision replaced the data pipeline with a direct reader of the public Qlib China A-share
dataset, fixed the correctness bugs listed under Bugs fixed, added a cost-aware back-test,
baselines, tests and CI, and produced every result below.
| Data | Qlib China A-share daily dataset, point-in-time CSI 300 membership (597 stocks over 2012–2020, about 290 eligible per day) |
| Split | train 2012–2016, validation 2017, test 2018-01-02 to 2020-09-23 (665 trading days), each period purged |
| Models | LightGBM, XGBoost, LSTM, attention-LSTM, GRU, Transformer; MSE + pairwise ranking loss on cross-sectionally z-scored 5-day returns |
| Test rank IC | 0.046 (GRU) to 0.062 (XGBoost); ICIR 0.30–0.52 |
| Top-30, 5-day rebalance, net of costs | 11.7%–15.4% a year, Sharpe 0.53–0.65, vs CSI 300 4.4% (Sharpe 0.30) and equal-weight members 3.8% |
| Costs | 0.05% buy, 0.15% sell; they take 6–9 points a year off gross returns (turnover 1.1–1.55 per rebalance) |
| Reference strategies | random picks: −5.1% a year net; 5-day reversal: −1.4% net |
| Caveat | one 2.7-year test path; net information ratios 0.62–0.84 correspond to t-statistics of only about 1.0–1.4 |
All numbers come from running ./run_all.sh in this repository (November 2026, 2 shared CPU cores); the
per-run reports are committed in reports/.
- Quick start
- Data and timing
- Results
- What was changed
- Bugs fixed
- Repository layout
- Status and limitations
- Credits and licence
git clone https://github.com/MXGao-A/QuantStock.git && cd QuantStock
pip install -r requirements.txt # CPU torch is enough
python -m pytest -q # 23 tests, about 1 minute, no data needed
python train.py --config model_config/lstm_config.json --data synthetic --epochs 1 # offline smoke runThe synthetic market (qlib_data.synthetic_panel) only exercises the pipeline end to end; numbers
produced on it say nothing about real markets.
For real results, download the Qlib dataset (about 200 MB, unpacked to ~/.qlib/qlib_data/cn_data) and run:
python qlib_data.py --download # or point --qlib-root at an existing copy
python train.py --config model_config/lgbm_config.json --data qlib --topk 30 --hold 5 # ~30 s
./run_all.sh # all six models + baselines + table + figure, ~20 min on 2 coresEach run writes results/<project>_<model>/report.json (config, split dates, rank IC, back-test tables),
daily back-test CSVs, a NAV plot and the training log. The runs in this README used 0.8–1.3 GB of RAM at peak.
Dataset. The public Qlib China A-share daily dataset (the copy Microsoft Qlib / RD-Agent use; mirror
https://github.com/SunsetWolf/qlib_dataset/releases/download/v0/qlib_data_cn_1d_latest.zip), 1999-11 to
2020-09-25, about 3,875 stocks, split/dividend-adjusted OHLCV. qlib_data.py reads the .day.bin files
directly with NumPy (about 40 lines); the qlib package is not needed. The dataset is not committed.
Universe. instruments/csi300.txt lists every membership spell with entry and exit dates. All 597
stocks that were CSI 300 members at any time between 2012 and 2020 are loaded, and on each day only the
stocks that were members on that day can be scored, bought, or count in the equal-weight reference, so
there is no survivorship bias from using today's constituents.
Split (chronological, config.SPLITS): train 2012-01-04 to 2016-12-22, validation 2017-01-03 to
2017-12-21, test 2018-01-02 to 2020-09-23. The last h + 1 days of train and validation are purged so that
no label reaches into the next period. Feature standardisation uses training-period statistics only.
Timing.
| Features for day t | 13 scale-free features from prices up to the close of day t (1-day return, open/high/low relative to close, volume relative to its 20-day mean, MACD, Bollinger bands, RSI-30, CCI-30, DX-30, 30/60-day SMA relative to close); window of seq_len days |
| Decision | after the close of day t |
| Execution | open of day t+1; a stock that is suspended or opens ±9.5% from the previous close (limit move) cannot be traded that day, and a held one stays in the book |
| Label | open[t+1+h] / open[t+1] − 1, h = 5, cross-sectionally z-scored for training |
| Back-test | equal weight in the top k, rebalanced every h days, weights drift in between; daily returns open-to-open |
| Costs | 0.05% of value bought, 0.15% of value sold (commission plus 0.1% stamp duty) |
| Benchmark | CSI 300 index SH000300 (open-to-open), plus an equal-weight portfolio of the day's CSI 300 members |
Produced by ./run_all.sh (the table is python summarize_results.py reports). Each model was trained
once with the committed config, early-stopped on the 2017 validation set, and evaluated once on the test
period; no setting was chosen by looking at test results in this session. Top-30 stocks, rebalanced every
5 trading days, 0.05% / 0.15% buy / sell costs.
| model | valid rank IC | test rank IC (ICIR) | ann. return, net (gross) | Sharpe, net | max drawdown, net | excess vs CSI 300, net | info ratio, net | turnover / rebalance |
|---|---|---|---|---|---|---|---|---|
| LightGBM | 0.084 | 0.061 (0.50) | 12.6% (21.6%) | 0.57 | −28.1% | +8.6% | 0.71 | 1.55 |
| XGBoost | 0.086 | 0.062 (0.52) | 13.1% (22.1%) | 0.59 | −27.2% | +9.1% | 0.76 | 1.54 |
| LSTM | 0.080 | 0.049 (0.32) | 14.0% (21.6%) | 0.65 | −21.2% | +9.4% | 0.84 | 1.28 |
| ALSTM | 0.068 | 0.055 (0.39) | 12.4% (20.0%) | 0.58 | −22.7% | +8.1% | 0.69 | 1.32 |
| GRU | 0.049 | 0.046 (0.30) | 15.4% (22.9%) | 0.64 | −27.5% | +11.5% | 0.84 | 1.28 |
| Transformer* | 0.068 | 0.059 (0.37) | 11.7% (17.8%) | 0.53 | −31.8% | +8.2% | 0.62 | 1.07 |
Same test period, same back-test (python baselines.py):
| reference | ann. return | Sharpe | max drawdown |
|---|---|---|---|
CSI 300 index (SH000300, price index) |
4.4% | 0.30 | −33.0% |
| equal-weight CSI 300 members (daily rebalanced, no costs) | 3.8% | 0.28 | −33.7% |
| random top-30 picks, mean of 5 seeds, net (gross) | −5.1% (3.7%) | −0.09 | −38.1% |
| 5-day reversal top-30, net (gross) | −1.4% (7.5%) | 0.09 | −36.7% |
"Excess" is the annualised arithmetic mean of the daily return difference. *The Transformer was shrunk to
fit the shared machine: 5 epochs on every second training day (train_stride: 2); it still took 10.6
minutes and 1.3 GB, the other models 1–3 minutes and about 0.8 GB.
How to read this.
- All six models rank stocks better than chance out of sample (daily rank IC 0.05–0.06, positive in every model) and their top-30 portfolios beat both the index and the random portfolio, which loses about 9 points a year to costs. The tree models have the highest rank IC; the neural models' higher returns here are within noise of each other.
- The evidence is thin. It is one 2.7-year path, the six models are strongly correlated with each other (see the figure), and an information ratio of 0.6–0.8 over 2.7 years is a t-statistic of roughly 1.0–1.4, not statistically significant.
- Costs matter: they cost 6–9 points a year at this turnover. The model does not see costs when it ranks; a turnover penalty or a longer holding period would be the obvious next step.
- The CSI 300 benchmark is a price index while the stock prices are dividend-adjusted, which flatters the strategy by roughly the index dividend yield (about 2% a year). The equal-weight member portfolio uses the same adjusted prices and is the cleaner comparison; it did slightly worse than the index here.
- Data: the bundled DOW30 / NASDAQ100 / SSE50 CSVs (about 530k lines, pre-split, fixed ticker
lists) and the yfinance downloader were removed and replaced with
qlib_data.py, a direct reader of the Qlib dataset with point-in-time index membership, plus a synthetic market for tests. - Features: the original inputs were raw price and volume levels and raw indicator levels, standardised across all stocks together, so a ¥100 stock and a ¥5 stock looked different for no economic reason. They are now ratios and returns (same indicators, made relative to the close).
- Pipeline: one base class (
pm/PM.py) with a masked loss, training loop, best-epoch restore, scoring and the back-test; the five per-model copies of the training and back-test loops were removed. The GRU draft was ported (pm/PM_gru.py).train.pyruns any model from its JSON config;baselines.pyandsummarize_results.pyproduce the comparison table and figure. - Back-test (
utils/backtest.py): next-open execution, untradable days, weight drift, turnover, costs, the index benchmark and an equal-weight reference. - Housekeeping: removed tracked
__pycache__files, ten 17 MB checkpoints, logs and the notebook; addedrequirements.txt,.gitignore, tests and a GitHub Actions workflow (replacing the unused PyPI-publishing template workflow; the project has no package metadata).
Bugs in the April 2025 version, each with a regression test in tests/ where practical:
- Same-bar look-ahead. The label was
close[t+h] / close[t] − 1with features that includeclose[t], and the back-test earned that return as if bought at the same close the signal was computed from. Now: decide after the close, trade at the next open, open-to-open label (test_label_is_next_open_to_open). - Labels leaked across the split. Labels were computed on train+valid+test concatenated, so the last
htraining labels used validation-period prices. Now purged (test_split_is_chronological_and_purged). - Scaler fitted on the full sample.
StandardScaler.fit_transformran on train, validation and test together. Now fitted on the training period only (test_scaler_fitted_on_training_period_only). - Back-test compounded the h-day forward return every day. With
prediction_len = 5each day's "daily" return was a 5-day return, overlapping with the next four days, which inflates returns roughly five-fold. Now one-day returns are compounded (test_backtest_compounds_one_day_returns_and_charges_costs). - The "market" benchmark was not a market. It was the mean of the same 5-day labels over the fixed ticker list. Now the CSI 300 index plus an equal-weight member portfolio, both one-day open-to-open.
- No transaction costs and no turnover accounting. Added.
- Survivorship bias. A fixed list of current index constituents was used for the whole history, and
the code reshaped the long table into
[days, stocks]assuming every stock traded every day. Now point-in-time membership with explicit masks (test_universe_mask_is_point_in_time). - Rank IC was not a rank correlation. It correlated
argsortoutputs (positions of the sorted elements), not ranks. Now Spearman (test_rank_ic_is_spearman). - Sortino ratio used the standard deviation of the negative returns instead of the downside
deviation (
test_performance_definitions). - The test DataLoader used
drop_last=True, silently dropping the last days of the test set (test_test_loader_keeps_every_day). - Training metrics accumulated across epochs (the meters were created once before the loop), and test-set metrics were computed every epoch during training. Now fresh meters per epoch, and the test set is touched once, after model selection on the validation set.
- Crashes: the LSTM configs set
input_size = 5while the data had 13 features; the XGBoost wrapper called.geton aSimpleNamespace; both tree wrappers passedfitarguments removed in xgboost ≥ 2 / lightgbm ≥ 4, and the LightGBM wrapper ignored most of its config;utils/tools.pyimportedshortuuid(not a dependency) at module level;np.Infno longer exists in NumPy 2; the GRU / GCN / diffusion modules importedfrom PM import PM, which fails.
Found while reviewing the interrupted rewrite (November 2026):
- Equal-weight reference dropped returns across data gaps. The Qlib copy has no stock prices on
2019-04-29 and 2019-04-30. Returns across the gap are booked on that day, but the equal-weight
reference averaged only stocks with a score that day (none), so it silently skipped the move. It
now averages over index members (
test_equal_weight_reference_keeps_returns_across_data_gaps). Found because random stock picks lagged the equal-weight reference by about 3% a year, far more than chance; after the fix the gap is within noise (+1.0 ± 0.6% at daily rebalancing, −0.8 ± 0.5% at 5-day rebalancing, 40 seeds each).
├── qlib_data.py direct reader for the Qlib bin format, downloader, synthetic market
├── config.py universe, benchmark, split dates, feature names, costs
├── stock_data_handle.py features, labels, masks, chronological split, torch Dataset
├── train.py train one model, evaluate rank IC, back-test, write report.json + plots
├── baselines.py random and 5-day-reversal portfolios through the same back-test
├── summarize_results.py table and figure from report.json files
├── run_all.sh reproduces every number in this README
├── pm/ prediction models: PM.py base class; LSTM/ALSTM, GRU, Transformer, LightGBM, XGBoost
├── models/ architectures; GAT, GCN, TCN, Mamba, diffusion are not wired in
├── model_config/ one JSON config per model
├── utils/ losses and metrics, back-test, misc
├── experimental/ GCN and diffusion drafts, not ported (see its README)
├── reports/ report.json of each run below, baselines.txt
├── figures/ test_nav.png
└── tests/ pytest suite (synthetic data only)
- Back-test realism. No slippage or market impact beyond the fixed cost rates; fills at the open price; limit moves approximated by a ±9.5% open gap for every stock (ST stocks have ±5% limits and ChiNext/STAR boards ±20% since 2020); delisted stocks keep their last price; no position-size or liquidity limits.
- Data quirks. The Qlib copy ends on 2020-09-25 and has no stock prices on 2019-04-29 and 2019-04-30 (the index does); positions are held through the gap and the move is booked on the next available day. The dataset's own adjustment and membership files are taken as given.
- Not tuned. Hyperparameters are the committed defaults (small networks,
seq_len20 for the nets, 5 for the trees). No search was run, so the numbers say little about the best achievable result. - Shrunk for the machine. The Transformer was trained for 5 epochs on half the training days; the networks have one recurrent / attention layer and 32–64 hidden units.
- Not wired in.
models/also holds GAT, GCN, TCN, Mamba and diffusion architectures from the April 2025 version; they are not connected to the current pipeline (Mamba needsmamba_ssm, the diffusion model needsdenoising_diffusion_pytorch).experimental/holds the unported drafts. - CI runs the pytest suite on synthetic data only (CPU torch); the real-data runs above were done locally and are not part of CI.
- Architectures and the ranking loss build on FinTSB and StockFormer; the ALSTM attention follows Adv-ALSTM.
- Data: the Qlib China A-share daily dataset from Microsoft Qlib, via the SunsetWolf/qlib_dataset mirror. Not redistributed here.
- Licence: MIT, © Mingxian Gao.