Quantitative Stock Screening with LLM Reasoning Models and Market Data APIs: Multi-Turn Dialogue and Strategy Implementation
This article explains how to combine LLM reasoning models with market data APIs to build a practical quantitative stock screening workflow. It covers the overall architecture, data access and preprocessing, natural language intent parsing, strategy rule generation, multi-turn context management, and key engineering considerations for turning conversational research into verifiable screening logic.
1. Background and Problem Definition
In quantitative investment research, individual investors and small teams often face two core challenges.
The first is the high cost of data processing. Market quotes, financials, sector classifications, and capital flow data are scattered across different sources with inconsistent formats. Cleaning and aligning these datasets requires substantial engineering effort.
The second is the high barrier to strategy expression. Research ideas often exist in natural language, such as “find the top-performing concept sectors over the past 10 trading days” or “screen for undervalued stocks with moderately expanding volume.” Turning these ideas into executable code requires overcoming obstacles in programming, data APIs, and indicator calculation.
Advances in large language model reasoning capabilities, together with the maturation of professional market data APIs, offer a new approach to these problems:
- Use a reasoning model as the “quantitative research brain” to interpret requirements, plan steps, generate code, and explain results.
- Use a market data API as the “data backend” to provide standardized, structured market data and basic screening capabilities.
- Connect the two through multi-turn dialogue so that users can complete the stock selection process using natural language.
This article expands on this approach and shows how to build a runnable, extensible quantitative stock screening workflow using general-purpose technical components.
2. Overall Architecture: How Reasoning Models Collaborate with Market Data
2.1 From “Prompt-Based Stock Picking” to Layered Collaboration
The simplest approach is to send the user’s question directly to a large language model and let the model generate an answer from its parametric knowledge. However, this approach has obvious limitations in financial scenarios:
- Financial data is highly time-sensitive. Model knowledge has a cutoff date and cannot reflect the latest market conditions.
- Models are prone to hallucination on computational tasks. Directly generating return rankings or moving average values is unreliable.
- Models cannot access user-specified details such as personalized screening scope, adjustment methods, or sector classifications.
A more reliable approach is a layered collaboration architecture:
- Interaction layer: Receives natural language input and maintains multi-turn dialogue context.
- Reasoning layer: Uses a reasoning model to parse user intent and generate structured query conditions or code.
- Data layer: Uses a market data API to execute queries, compute indicators, and return standardized results.
- Explanation layer: The model analyzes and summarizes the returned data and provides follow-up research suggestions.
Under this architecture, the model does not directly “fabricate data” but instead serves as a planner and explainer.
2.2 The Value of Multi-Turn Dialogue
Single-turn Q&A can generally handle only simple, one-off queries. Real stock screening requirements are often progressive:
- Round 1: The user proposes a general direction.
- Round 2: The model asks for clarification on filtering conditions such as time window, sector scope, and sorting method.
- Round 3: The user adds risk preferences or exclusion criteria.
- Round 4: The model outputs a candidate list and the screening logic.
- Round 5: The user asks to adjust parameters or explain why a particular stock was included.
The role of multi-turn dialogue is to gradually converge vague requirements into executable query tasks. The system therefore needs context memory, condition completion, and result traceability capabilities.
3. Market Data Access and Preprocessing
3.1 Basic Capabilities of a Suitable Data API
A market data API suitable for quantitative research should cover at least the following capabilities:
- Basic quotes: Daily bars, minute bars, and real-time snapshots.
- Depth data: Order book, tick-by-tick data, and bid-ask Level-2 data.
- Sectors and indices: Industry sectors, concept sectors, and their constituent stocks.
- Fundamentals and valuation: P/E ratio, P/B ratio, ROE, and related metrics.
- Capital flow: Main capital flow, northbound capital flow, and large-order activity.
- Screening and statistics: Support for sorting and filtering by price change, turnover rate, volume ratio, and technical indicators.
The API should provide a stable access method, such as a RESTful interface returning JSON structures that can be easily parsed by the model or an intermediate program.
3.2 Typical Query Flow
Take the example of “finding the top 5 concept sectors by gain over the past 10 trading days.” The system needs to complete the following steps:
- Parse the time window: Convert “the past 10 trading days” into a start date and an end date.
- Get the sector list: Retrieve all concept sectors and their constituents from the data API.
- Aggregate sector performance: Calculate the average or weighted return of each sector over the time window.
- Sort and take the top 5.
- Return results with auxiliary information such as leading constituent stocks.
This logic can be implemented through model-generated code or through the data API’s native screening functionality. The latter approach reduces model computation errors and improves response speed.
3.3 Structuring Returned Data
To help the reasoning model accurately understand returned results, data should be as structured as possible. For example:
{"ranking": [{"sector_name": "Robotics Concept","avg_return_10d": 18.35,"leading_stock": "Stock A","leading_stock_return": 32.14}],"query_params": {"window": "10d","sort_by": "avg_return","limit": 5}}
Structured responses reduce the probability of parsing errors and can serve as citable intermediate results in subsequent dialogue turns.
4. From Natural Language to Query Conditions: Intent Understanding and Parameter Extraction
4.1 Reactive Queries and Proactive Clarification
After receiving a user question, the reasoning model must first determine whether the information is sufficient. For example:
- “Find recent strong sectors” → Missing time range and sorting criteria.
- “Find undervalued high-growth stocks” → Missing sector scope, valuation threshold, and growth metric definition.
The system should support proactive clarification rather than immediately returning vague results. Clarification questions should be as specific as possible:
“Please confirm: Is the time window the past 5 trading days or the past 10 trading days? Should sorting be based on period return or volume change?”
Such follow-up questions help convert natural language into clear screening conditions.
4.2 Condition Abstraction and Template Mapping
In implementation, a set of common screening templates can be predefined to map natural language to template parameters:
| User Expression | Abstract Condition |
|---|---|
| Recently strong | Ranked in the top N by period return |
| Moderately expanding volume | Volume ratio greater than 1 and less than 3 |
| Undervalued | P/E ratio below the industry median |
| Breaking out of a range | Price at a 60-day high |
| Main capital inflow | Positive main capital inflow for 3 consecutive days |
The model identifies the condition combinations in the user’s expression, and the system translates them into query parameters supported by the data API.
5. Strategy Research: From Screening Results to Verifiable Logic
5.1 Converting Natural Language Strategies into Indicator Rules
Conversational screening is only the starting point. A complete quantitative research workflow should include strategy formalization and backtesting. At this stage, the reasoning model can help users convert natural language rules into computable indicator conditions.
For example, if the user describes:
“I want to find stocks that traded sideways for more than 20 trading days and recently broke out on high volume.”
The model can help decompose this into:
- Sideways definition: Price range over the past 20 trading days below a certain threshold.
- Volume expansion definition: Latest daily volume greater than 1.5 times the 20-day average volume.
- Breakout definition: Latest closing price above the highest price of the past 20 days.
5.2 Code Generation Guidance
Model-generated code should follow the principle of being simple and verifiable. An example implementation:
def filter_breakout(df, lookback=20, vol_ratio=1.5):df = df.copy()# Price range during the sideways perioddf['range'] = (df['high'].rolling(lookback).max() -df['low'].rolling(lookback).min()) / df['close']# Volume expansion breakoutdf['vol_ma'] = df['volume'].rolling(lookback).mean()df['condition'] = ((df['range'] < 0.15) &(df['close'] > df['high'].shift(1).rolling(lookback).max()) &(df['volume'] > df['vol_ma'] * vol_ratio))return df[df['condition']]
This example only illustrates the general logic. In practice, it should be adapted to the actual data fields and API capabilities.
5.3 Basic Dimensions of Backtesting and Evaluation
A strategy’s effectiveness should not be based on a small number of samples. Backtesting should focus on:
- Absolute and relative returns: Whether the strategy generates excess returns relative to a benchmark index.
- Maximum drawdown: The strategy’s resilience under extreme market conditions.
- Win rate and profit-loss ratio: The quality of individual trades.
- Turnover rate and transaction costs: Whether a high-turnover strategy remains effective after accounting for commissions and slippage.
- Out-of-sample stability: Whether performance remains consistent across different time periods and market regimes.
The reasoning model can help generate a backtesting report outline and explain the meaning of each metric, but the actual numerical calculations should be performed by the data processing module.
6. Context Management in Multi-Turn Dialogue
6.1 Benefits and Limits of Long Context Windows
If the reasoning model supports a large context window, it can carry substantial historical information within a single session, such as:
- The user’s original requirements.
- Multiple rounds of follow-up questions and answers.
- Summaries of intermediate query results.
- Previously generated code and backtesting results.
However, context should not grow without limit. Excessive historical information may interfere with the model’s judgment on the latest task. In practice, the following strategies can be adopted:
- Summarize and compress earlier dialogue turns.
- Retain only key query parameters and conclusions.
- Store large data response bodies in external context, with the model referencing only summaries.
6.2 Result Attribution and Traceability
In multi-turn dialogue, the model should clearly indicate which query round a given result came from. For example:
“Based on the Round 2 query results, the top 5 concept sectors by 10-day return were… Among them, after adding the low-valuation condition in Round 4, only 3 constituent stocks remained eligible.”
This traceability makes it easier for users to verify results and troubleshoot issues.
7. Engineering Considerations
7.1 Handling API Exceptions Reliably
Market data APIs may experience timeouts, rate limiting, or field changes. The system should include retry mechanisms, timeout controls, and fallback strategies. For example:
- Automatically retry failed queries up to 3 times.
- Return a user-friendly message after a timeout, suggesting a narrower query scope.
- Check returned fields for missing values to avoid model parsing errors.
7.2 Preventing Models from Generating Incorrect Data
Financial scenarios demand high data accuracy. Avoid allowing the model to fabricate market values from scratch. Feasible practices include:
- All numerical results must come from the data API response.
- The model is only responsible for explanation, summarization, planning, and code generation.
- For any numbers generated by the model, the system should remind users that the data API response is authoritative.
7.3 Permissions and Security
If live trading is involved, research and trading environments must be strictly separated. The research environment can allow natural language queries and code execution, but the trading environment should include permission isolation, manual review, and risk limits. A conversational system should never be allowed to directly place trading orders without proper risk controls.
8. Summary: A Practical Path for Quantitative Research
Combining LLM reasoning models with market data APIs creates a complete quantitative research workflow:
- The user expresses a stock screening intent in natural language.
- The reasoning model parses the intent and asks follow-up questions when necessary to complete the conditions.
- The market data API executes the query and returns structured results.
- The model explains the results and generates indicator rules or strategy code.
- The user backtests and optimizes based on the returned logic.
- Reusable screening templates and research notes are formed.
The core value of this workflow is lowering the barrier to data access and strategy expression, allowing researchers to focus on logic validation and risk control. For developers, the key is not simply connecting a model to a data API but designing robust context management, condition abstraction, result validation, and exception handling. Only when these engineering details are handled properly can natural language-driven quantitative research move from demo to production use.
