How to Use LLMs for Quantitative Trading: From Automated Factor Mining to Strategy Implementation
Large language models are increasingly being applied in quantitative investing not as short-term return predictors, but as research agents that propose market hypotheses, write factor code, analyze backtest results, and drive iterative factor evolution. This article explains the methodology, multi-role workflow, engineering safeguards, and risk controls required to build a reproducible LLM-driven factor mining pipeline and turn research signals into portfolio-ready strategies.
In recent years, the use of large language models in quantitative investing has been moving from “reading research reports and financial statements” toward a more central task: automated factor mining. Existing explorations suggest that, with a carefully designed multi-round LLM collaboration framework, the resulting factor combinations can achieve relatively high annualized returns in backtests while keeping maximum drawdown at a relatively low level. That sounds attractive, but how is it actually implemented? How can an ordinary team reproduce this methodology? This article explains the right way to “use large language models for quantitative trading” across four layers: principles, workflow, engineering implementation, and risk control.
1. Correcting a Misconception: LLMs Are Not for “Guessing Candlesticks”
Many people imagine “AI quant” as feeding candlestick charts to an LLM and asking it to predict whether the market will rise or fall tomorrow. This approach is of limited use in practice for several reasons:
- Time-series prediction has a very low signal-to-noise ratio. Financial return series are close to random walks, and the statistical basis for directly predicting price levels is weak.
- LLMs do not have true market memory. Historical data placed in the context window is incomplete and can easily introduce look-ahead bias.
- The output is neither interpretable nor backtestable. A statement such as “bullish” cannot be converted into verifiable, risk-managed trading rules.
The path that has been shown to be effective is to make the LLM act as a researcher rather than a predictor. In other words, the LLM proposes market hypotheses, writes factor code, analyzes backtest results, and iterates on improvements, while the resulting factors still go through the conventional pipeline of backtesting, winsorization, standardization, and portfolio optimization. The LLM improves research efficiency and research breadth; it does not replace the entire quantitative system.
2. Where Traditional Factor Mining Breaks Down
The traditional factor research process roughly works as follows: a researcher proposes a logic based on market intuition, such as “there is a rebound effect after a price decline on shrinking volume,” manually writes the factor expression, runs a historical backtest, and tries another idea if performance is poor. This process has several hard limitations:
- Heavy dependence on labor and experience: a researcher can deeply validate only a limited number of factor ideas per year.
- Strong subjectivity and narrow coverage: it is easy to keep circling within a few familiar patterns, with little systematic exploration.
- High trial-and-error cost: each iteration from idea to code to backtest can take hours or even days.
As a result, both academia and industry have turned toward “automated factor mining”: using machines to automatically generate, screen, and evolve factors. LLMs bring a qualitative change because they combine financial domain knowledge with coding ability, allowing them to handle both “thinking of the logic” and “writing the implementation.”
3. Core Idea: Turn Factor Mining into an Evolution Game
One validated methodology models the entire factor research process as a trajectory:
One trajectory = propose a hypothesis → break down the direction → implement factor code → evaluate through backtesting → provide feedback and revise
After each trajectory is completed, it produces a complete research record and performance metrics for one factor or a batch of factors. The framework then introduces ideas from biological evolution:
- Selection: trajectories with good performance are retained, while poor ones are eliminated.
- Reproduction: high-quality trajectories serve as “parents,” and the LLM mutates or combines them to generate the next generation of factor hypotheses.
- Iteration: the loop continues, and the factor pool gradually evolves toward high IC, low correlation, and robustness.
You can think of it as raising a population of “factor babies,” letting them compete in historical market data; the surviving elites then “mate” with one another to produce stronger next-generation factors. The essence of this approach is to trade computation for research breadth and replace manual trial and error with evolutionary search.
The overall framework usually contains four modules:
- Diversified planning and initialization: define the exploration space and ensure diversity at the starting point.
- Factor implementation: the LLM translates hypotheses into executable factor code.
- Self-evolution: perform selection and mutation iteration based on backtest feedback.
- Final factor pool: aggregate high-quality factors that have passed multiple rounds of screening for portfolio use.
4. Core Workflow: Multiple LLM Calls with Distinct Roles
The most interesting part of this method is that it does not ask the LLM to output a factor in one step. Instead, it designs a pipeline with a clear division of labor, using multiple rounds of calls so that the LLM plays a different role at each stage.
1. Slice the Broad Objective into Orthogonal Pieces
The first step is task decomposition. You give the system a broad direction, such as “price-volume factor mining,” and the LLM plays the role of a senior quantitative researcher, breaking the broad direction into multiple orthogonal subdirections.
“Orthogonal” is key: subdirections should overlap as little as possible and explore the market from different dimensions. The reason is that “price-volume factors” is too broad. If the model is allowed to improvise freely, it will repeatedly output a few common patterns. Once the direction is divided into orthogonal parts, each line of research can be explored in greater depth, and the final factors will be significantly more diverse. For example, it can be decomposed into:
- Price-volume correlation direction: the co-movement between price and volume.
- Volume anomaly direction: deviation signals from unusually high or low volume.
- Intraday volatility direction: amplitude and the structure of upper and lower wicks.
- Turnover momentum direction: the changing trend of turnover.
- Volume distribution direction: the distribution of volume across different price ranges.
2. Propose Testable Hypotheses in Each Direction
For each subdirection, ask the LLM to propose specific market hypotheses. Note that the output at this step is not code, but falsifiable statements, such as: “When today’s volume is significantly above its 20-day average and the close is near the day’s high, the probability of short-term continuation is higher.” Writing explicit hypotheses has several benefits: they are traceable, reviewable, and can serve as the “genes” for evolutionary iteration.
3. Turn Hypotheses into Factor Code
Next, the LLM translates the hypotheses into factor calculation code. Key engineering requirements at this step include:
- A unified data interface: provide the model with schema documentation for market data, including field names, frequency, and adjustment method, to prevent it from fabricating fields.
- Strict look-ahead constraints: all rolling-window calculations may use only data from day T and earlier.
- Templated output: require the model to return the factor value series using a fixed function signature, so that the downstream pipeline can process it uniformly.
A schematic factor function skeleton looks roughly like this:
def factor_volume_price_alpha(df):"""Input: df contains the fields date, open, high, low, close, and volume.Output: a factor value Series with the same length as df.Constraint: use only current and historical data; future information is prohibited."""vol_ma20 = df['volume'].rolling(20).mean()vol_ratio = df['volume'] / vol_ma20close_pos = (df['close'] - df['low']) / (df['high'] - df['low'] + 1e-9)return vol_ratio * close_pos
4. Automated Backtesting and Multidimensional Evaluation
After factor code is produced, it enters a standardized evaluation process, typically examining:
- IC / RankIC: the correlation between factor values and future returns, measuring predictive power.
- ICIR: the stability of IC, preventing a factor from working only occasionally.
- Factor autocorrelation and decay: proxy indicators for turnover that determine sensitivity to trading costs.
- Layered backtesting: monotonicity across groups sorted by factor value, validating whether the logic holds.
- Correlation with the existing factor pool: controlling redundancy and ensuring incremental value at the portfolio level.
5. Feedback Evolution: Let Good Factors “Reproduce” the Next Generation
The evaluation results are passed back to the LLM in a structured format, including performance metrics and failure reasons such as code errors, low IC, or non-monotonic grouping. The LLM then performs two types of operations based on this feedback:
- Mutation: parameter perturbation, window adjustment, and logic refinement for high-performance factors.
- Crossover: combining high-quality factors from two different directions into a composite factor, such as “price-volume correlation × turnover momentum.”
After several generations of iteration, select a low-correlation, highly robust subset from the final factor pool for portfolio optimization and generate strategy signals that can be used for live trading.
5. Key Engineering Details and Pitfalls in Production
The ideal sounds good, but several issues must be considered before this workflow can run in production.
1. Overfitting is the number-one enemy. Automated mining is essentially a search over a huge hypothesis space. The more thorough the search, the higher the probability of accidentally fitting historical noise. Necessary measures include strict out-of-sample splits, segmented validation across multiple market regimes (bull, bear, and sideways markets), penalties on the number of factors, and bootstrap robustness checks on the final factor pool.
2. Consistency of the backtesting framework. Every piece of factor code generated by the LLM must run under the same evaluation standards, including unified adjustment, exclusion rules, and cost assumptions. Otherwise, performance metrics will not be comparable, and evolutionary selection will lose its meaning.
3. Code safety. LLM-generated code must be executed in a restricted sandbox, with timeouts and resource limits to prevent infinite loops or unauthorized access from bringing down the entire pipeline.
4. The tradeoff between cost and latency. Multiple rounds of LLM calls plus high-frequency backtesting can be expensive. A common optimization is layered filtering: first use low-cost pre-screening, such as quick IC calculations, to eliminate clearly poor factors, and then run full backtests on the survivors.
5. Live drift monitoring. After deployment, continuously monitor the real-time decay of factor IC. If it becomes significantly lower than in the backtest period, trigger a retirement or re-evolution process. Mining is not a one-off task but a continuously operating research system.
6. Conclusion: The Right Way to Use LLMs in Quant Trading
Returning to the original question—“How can LLMs be used for quantitative trading?”—the answer can be condensed into three points:
- Position the model correctly: let the LLM act as a researcher that proposes hypotheses, writes code, and analyzes results, rather than as a predictor.
- Build a stable framework: orthogonal task decomposition, a multi-role pipeline, standardized backtesting, and evolutionary iteration are all essential.
- Apply strict risk control: overfitting protection, sandbox execution, and live drift monitoring determine whether the system is a productive engine or a capital-draining machine.
Impressive backtest figures with high annualized returns and low drawdowns are indeed attractive, but what is truly worth learning is the underlying methodology: turning investment research into an automatable and evolvable engineering pipeline. For teams that want to enter this field, it is advisable to start with a small orthogonal direction, first close the loop of “hypothesis—code—backtest—feedback,” and then gradually expand the search space. In this way, engineering capability can turn the research benefits of LLMs into real strategy improvements.
