LLM-Assisted Stock Screening: Engineering Practices and Risk Controls
This article explains how to use large language models in a stock screening workflow. It covers a four-layer system design, common data cleaning problems, how to turn subjective trading criteria into testable rules, and which tasks suit an LLM. It also covers backtesting, out-of-sample validation, and risk controls for research use.
1. Problem Background and Scope
Quantitative analysis often faces two problems: large data volumes and scattered judgment criteria. Take the full market as an example. A single day of market data can cover thousands of securities, and each security includes fields such as open price, close price, trading volume, and turnover rate. Reviewing these records by hand is slow, and it is hard to apply a consistent standard.
Many analysts begin by describing their screening logic in natural language, for example, “moving averages trending up, volume expanding, price holding above key levels.” Descriptions like this are easy for people to read, but they are not precise enough for a program. To make a computer run the logic, each description must be converted into a computable indicator and threshold, and the basis for each threshold must be documented.
In this workflow, a large language model (LLM) is best suited to understanding requirements, organizing rules, explaining results, and generating reports. It is not suited to acting as a direct price predictor. Financial time series are noisy, and past performance does not indicate future returns. Model outputs must pass independent statistical testing before they can be trusted. The design below follows this boundary.
2. System Architecture Overview
A maintainable screening system typically has four layers:
- Data layer: Fetches market and basic security data, then performs cleaning, alignment, and missing value handling.
- Feature layer: Computes technical indicators from price and volume, such as moving averages, price change rates, and volume ratios.
- Rule layer: Expresses screening conditions as explicit Boolean expressions. Each rule has a name and parameters.
- Explanation and reporting layer: Uses an LLM or templates to generate structured summaries, with the underlying indicator values attached for manual checking.
This layering lets each layer be tested on its own. When a screening result looks wrong, the team can check each layer in turn to determine whether the cause is the data, the indicator calculation, or the rule settings.
3. Data Layer: Cleaning and Alignment
Data quality determines how far the screening results can be trusted. Common problems include:
- Suspensions and missing values: Suspended trading days have no volume records. Calculating moving averages directly on the time series misaligns the data.
- Price adjustment: Dividends and stock splits create price breaks. Unadjusted data distorts technical indicators.
- Ticker changes: Renaming, delisting, and restructuring can cause the same security to use different codes over time.
- Survivorship bias: If a historical backtest only includes stocks that are still trading today, the results will be systematically overstated.
The following sample code shows how to compute indicators for each stock while keeping the time order intact:
import pandas as pddef build_features(df: pd.DataFrame) -> pd.DataFrame:"""Compute technical indicators per stock code. Input must contain code, date, close, and volume fields."""df = df.sort_values(["code", "date"]).copy()grouped_close = df.groupby("code")["close"]grouped_volume = df.groupby("code")["volume"]df["ma20"] = grouped_close.transform(lambda s: s.rolling(20, min_periods=20).mean())df["ma60"] = grouped_close.transform(lambda s: s.rolling(60, min_periods=60).mean())df["vol_ma20"] = grouped_volume.transform(lambda s: s.rolling(20, min_periods=20).mean())df["vol_ratio"] = df["volume"] / df["vol_ma20"]return df
The min_periods setting matters. When a window has too few observations, returning a null value is safer than calculating on an incomplete window.
4. Rule Layer: Turning Subjective Descriptions into Testable Conditions
Suppose an analyst wants to screen for stocks with an upward medium-term trend and a recent breakout on heavy volume. This idea can be split into three rules:
- Trend condition: the short-term moving average is above the medium-term moving average.
- Position condition: the close price is above the short-term moving average.
- Volume condition: the day’s trading volume is above a set multiple of the 20-day average volume.
Each rule needs an explicit threshold. Thresholds can come from historical statistics, industry practice, or parameter sweep results, but the source must be recorded. A threshold without a documented source is hard to explain later and hard to reproduce.
def screen_stocks(df: pd.DataFrame, vol_threshold: float = 1.2) -> pd.DataFrame:"""Return records that meet the trend, position, and volume conditions."""cond_trend = df["ma20"] > df["ma60"]cond_position = df["close"] > df["ma20"]cond_volume = df["vol_ratio"] > vol_thresholdreturn df.loc[cond_trend & cond_position & cond_volume].copy()
Exposing thresholds as parameters makes sensitivity analysis easier. If changing the volume threshold from 1.2 to 1.5 shifts the results substantially, the rule is highly sensitive to that parameter and should be treated with caution.
Another common approach is to assign priorities to conditions instead of requiring all of them to hold at once. This keeps the result list at a manageable size and preserves a basis for ranking.
5. Appropriate Uses of LLMs
In this workflow, an LLM adds value in three areas.
First, requirement translation. The analyst describes an idea in natural language, and the model organizes it into a draft rule with indicator names, comparison directions, and parameter placeholders. A person must review the draft before it is used.
Second, structuring results. The screening program outputs numerical tables. The model can convert them into a fixed-format JSON object with fields for the code, date, matched rule names, and key indicator values. A fixed format is easier for downstream programs to read and archive.
{"code": "000001","date": "2026-11-23","matched_rules": ["trend_up", "above_ma20", "volume_expand"],"metrics": {"ma20": 10.52, "ma60": 10.18, "vol_ratio": 1.37}}
Third, report generation. The model can write explanatory text from the structured results. The prompt should restrict the model to the provided input data and forbid it from adding news, financial, or earnings information that was not supplied. Otherwise, the model may produce judgments that sound plausible but have no basis.
Some uses should be explicitly excluded. These include asking the model for buy or sell prices, predicting short-term price moves, or replacing risk assessment. These tasks either exceed what the model can reliably do or require dedicated statistical modeling and compliance review.
6. Backtesting and Out-of-Sample Validation
A rule that performs well on historical data is not proven to work in the future. Keep these points in mind during backtesting:
- Look-ahead bias: Indicators may only use data that was available at the time. For example, if a decision uses the closing price, the trade cannot execute at that same bar’s opening price.
- Transaction costs: Commissions, stamp duty, and slippage erode returns, so backtests must deduct them explicitly.
- Sample splitting: Split the data by time into a training segment and a validation segment. Determine parameters only on the training segment, then evaluate them independently on the validation segment.
- Multiple testing: If many parameter combinations are tried, the best result may appear by chance. Apply stricter standards when judging significance.
Backtest reports should include several metrics, such as return, maximum drawdown, win rate, and turnover rate. Reporting only the return rate hides risk, and this is a common source of misleading conclusions.
7. Risk Controls and Compliance
Any screening method based on historical data can fail. Shifts in market structure, policy changes, and sudden liquidity changes can all make existing rules stop working. Engineering teams can take the following measures:
- Add data quality checks, such as verifying that the daily record count is normal and that prices do not show extreme jumps.
- Save a version number, a parameter snapshot, and a hash of the input data for each screening run, so results can be reproduced.
- Attach a clear disclaimer to outputs, stating that results are for technical research only and do not constitute investment advice.
- Restrict system permissions. The screening program should only read data and generate reports, with no connection to any trade execution interface.
If a team plans to use this kind of tool for real decisions, it should also complete the internal approval and compliance procedures that apply. Individual users should understand the securities investment advisory and fund management rules that apply in their region.
8. Engineering Recommendations
In real projects, the following practices can significantly reduce maintenance costs:
- External configuration: Keep indicator parameters and thresholds in configuration files instead of hardcoding them.
- Unit tests: Write test cases for each indicator function, using small samples with known results to verify calculation accuracy.
- Logging: Record each run’s duration, input size, and number of matches to catch performance regressions or data anomalies.
- Staged rollout: Run offline on historical data first, then run on simulated live data, and only then consider broader use.
9. Summary
LLMs can improve the efficiency of data processing and report generation, but they cannot replace rigorous statistical testing and risk management. A reliable screening system should have clear rules, trustworthy data, strict backtesting, and traceable results. Breaking subjective judgments into computable conditions and validating them on independent out-of-sample data is the core of this engineering practice. This article is for technical discussion only and does not constitute investment advice.
