How to Build a Quantitative Stock Selection Pipeline with Large Language Models
This article explains how to build a quantitative stock selection pipeline that combines computable screening factors, large language model (LLM) analysis, and hard risk-control rules. It covers translating market-cycle stages into trend, volume, volatility, and position metrics, using an LLM for structured comparison instead of arithmetic, enforcing rejection rules, and closing the loop with backtesting and monitoring.
1. Why Full-Market Scanning Needs a Layered Funnel
The core insight behind this approach is that market conditions evolve in cycles similar to seasons. During the bottom consolidation phase, capital cautiously positions itself while the trend remains unconfirmed. In “early summer,” price breaks key levels and moving averages turn bullish, but market perception has not caught up. In “midsummer,” the trend is established and price-volume alignment drives the main advance. In “late summer,” acceleration and emotional chasing appear, and risk accumulates quickly. “Autumn” typically corresponds to good news being priced in and distribution ending. A practical strategy keeps only the “early summer to midsummer” window and takes profits before “late summer.”
The engineering challenge is not judgment but scale: manually evaluating thousands of tickers is not feasible. A layered funnel is the reasonable approach. The first layer uses computable quantitative conditions for coarse screening. The second layer uses a model with language understanding and summarization capabilities for fine screening. The third layer applies risk-control rules for rejection. Each layer should take and produce structured data, avoiding the inclusion of subjective “feel” in the process.
2. Layer 1: Translating Cycle Stages into Computable Metrics
Seasons are only a metaphor; implementation requires formula-based definitions. Cover at least four factor categories: trend, volume, volatility, and position:
trend_score = w1*close/ma20 + w2*ma20/ma60 + w3*(ma60/ma120)volume_score = 5-day average volume / 60-day average volumebreakout_flag = close > 120-day highest price * (1 - eps)volatility = standard deviation of 20-day returnsposition = (close - 250-day lowest) / (250-day highest - 250-day lowest)
“Early summer” can be approximated as: the trend score has just crossed above a threshold, the breakout flag is true, volume is moderately increasing but not extreme, volatility is in a medium-low range, and position is not high. “Midsummer” means the trend score remains high and drawdowns are controlled. “Late summer” corresponds to extreme volume expansion and overly rapid short-term gains, which should serve as a no-entry or position-reduction signal rather than a buy signal. Thresholds must be calibrated with rolling historical data, and parameter version numbers should be retained to ensure reproducibility.
The coarse-screening output should be a plain-text list plus a structured file containing only codes and key factor values, making it easy for the next layer to consume:
code,trend_score,volume_score,position,volatility600xxx,1.07,1.35,0.42,0.018000xxx,1.04,1.28,0.37,0.021
3. Layer 2: LLM Fine Screening and Comparative Summarization
LLMs are not good at precise numerical computation, but they excel at multi-factor trade-offs under given constraints, generating comparison tables, and producing risk lists. Their role is “analyst,” not “calculator.” The input should contain only the coarse-screening results and necessary context, with explicit constraints: number of candidates, time window, required output fields, and a prohibition on fabricating data.
A reusable prompt skeleton is as follows:
You are a quantitative researcher. Below are candidate tickers and factor values (CSV).Task: Select 2-3 relatively stronger candidates within the given window.Constraints:1) Use only the data I provide; write "unknown" for missing values and do not speculate;2) Output a comparison table: trend strength / volume health / position risk / drawdown risk / main uncertainties;3) Provide elimination reasons, at least 3;4) Output JSON at the end with fields picks, confidence, risk_notes.
In engineering practice, force the model output into a parseable structure for database ingestion and downstream validation:
{"picks": ["600xxx", "000xxx"],"confidence": 0.62,"risk_notes": ["Volume expansion is approaching historical extremes", "Sector linkage is unconfirmed"]}
If there are many candidates, use a two-stage “group comparison then aggregation” approach: first generate small-group conclusions in batches, then have the model perform a second consolidation of the group conclusions, reducing context pressure and information loss.
4. Layer 3: Risk Control and Rejection Rules
Model suggestions can only enter a watchlist and must not be treated directly as trading instructions. Recommended hard rejection items include: single-day turnover or gain exceeding thresholds, earnings disclosure windows, trading halts and insufficient liquidity, missing factor data, and industry or style exposure exceeding limits. At the position level, use a fixed-fraction risk budget where per-ticker caps and total-drawdown circuit breakers apply simultaneously. Set take-profit and stop-loss levels as multiples of volatility to avoid distortion from fixed percentages across different volatility environments.
5. Validation Loop: Backtesting, Monitoring, and Iteration
Every pipeline needs a closed loop. Backtesting must use rolling walk-forward validation, strictly avoid look-ahead bias, and account for costs and slippage. The monitoring layer should track watchlist size, model output stability, rejection hit rate, and live-trading deviation. Logs and metrics can be archived and traced using general-purpose cloud logging services, monitoring and alerting, and object storage. For batch computation and scheduled jobs, use a container platform with a message queue to decouple tasks, allowing coarse screening, fine screening, and risk control to scale independently.
6. Common Pitfalls
First, treating the metaphor as the model without thresholds and version management. Second, letting the model do arithmetic, which leads to numerical hallucination. Third, ignoring “late summer” identification and adding positions in the most dangerous phase. Fourth, looking only at returns while ignoring drawdown and turnover. Fifth, having a non-reproducible process whose results cannot be audited. The way to avoid these is to make each layer a deterministic, testable module, with the model responsible only for semantic summarization.
In summary, the practical path is: quantitative coarse screening reduces scale, LLM fine screening outputs structured comparisons, risk-control rules provide final rejection, and backtesting plus monitoring drive iteration. This preserves the core logic of “trading only the trend-confirmation window” while making the entire pipeline operationally maintainable and auditable.
