How to Use Large Language Models to Screen Stock Market Cycle Stages

    This article explains a three-layer pipeline for mapping a large stock universe to market cycle stages and tracking how those labels migrate over time. It shows how to define stages as reproducible quantitative rules, use a large language model only to structure and explain a compressed candidate list rather than predict price moves, and enforce risk controls with backtesting. You will find a sample stage-labeling function, a reusable JSON-constrained prompt template, a risk-check function, and practical notes on data integrity, cost assumptions, and compliance.

    1. Background: The Bottleneck Is Screening Scale, Not Judgment

    A market can contain thousands of listed symbols. For any stage-based strategy, the hard part is not defining the stages. It is mapping the entire market to stage labels every trading day and continuously tracking how those labels migrate.

    Take a common seasonal framework: bottom consolidation, breakout ignition, trend confirmation, acceleration and top formation, then distribution and clearing. A strategy might only participate in two of those phases, from breakout ignition to trend confirmation, and take profits during acceleration. The logic is simple. The complexity lives in the throughput and consistency of execution.

    Manual chart review usually works like this: pick sectors based on experience, then flip through candlestick charts one by one. A person can cover at most a few dozen symbols in a day, and the criteria drift with sentiment.

    The engineering approach is to push stage classification down into computable indicators and limit the large language model’s role to structured summarization and explanation of an already-compressed candidate set. The model should not be asked to predict price direction. This division of labor must be clear, or the whole workflow degrades into non-reproducible guesswork.

    2. Overall Architecture: Three Layers and Two Data Pipelines

    Split the system into three layers that exchange only files or structured data. This makes each layer easy to replace and backtest independently.

    • Layer 1, quantitative screening: coarse-filters the whole market. Input is market and financial data; output is a candidate pool with stage labels and scores.
    • Layer 2, model-based refinement: compares, deduplicates, and categorizes candidates within the pool. Output is structured conclusions with reasons.
    • Layer 3, execution and risk control: handles position sizing, stop losses, time windows, and mandatory close-out at expiry.

    There are two data pipelines:

    • Market data pipeline: daily OHLCV, adjustment factors, industry classification, and index constituents. Store this in a relational database or data warehouse.
    • Text pipeline: announcement summaries, research report highlights, and industry outlook descriptions. Object storage with a task queue driving batch jobs is a good fit.

    The text pipeline is only an auxiliary explanatory input. It must never override the quantitative labels.

    3. Layer 1: Writing Stages as Computable Definitions

    Stage labels must be uniquely determined by formulas. Anyone rerunning the process should get identical results. The skeleton below characterizes stages using three dimensions: moving average slope, breakout confirmation, and volume expansion. Calibrate the parameters against your own historical data; do not copy them blindly.

    1. import pandas as pd
    2. def label_stage(df, ma_win=20, vol_win=20, eps=1e-6):
    3. d = df.sort_values("date").copy()
    4. d["ma"] = d["close"].rolling(ma_win).mean()
    5. d["ma_slope"] = d["ma"].diff(5) / (d["ma"].abs() + eps)
    6. d["vol_ma"] = d["volume"].rolling(vol_win).mean()
    7. d["vol_ratio"] = d["volume"] / (d["vol_ma"] + eps)
    8. d["high_60"] = d["high"].rolling(60).max().shift(1)
    9. breakout = (d["close"] > d["high_60"]) & (d["vol_ratio"] > 1.5)
    10. trending = (d["ma_slope"] > 0.01) & (d["close"] > d["ma"])
    11. topping = (d["ma_slope"] > 0.03) & (d["vol_ratio"] > 2.0)
    12. d["stage"] = "consolidation"
    13. d.loc[breakout, "stage"] = "breakout"
    14. d.loc[trending & ~breakout, "stage"] = "trending"
    15. d.loc[topping, "stage"] = "topping"
    16. return d[["date", "close", "stage", "ma_slope", "vol_ratio"]]

    Three engineering points matter:

    1. Fix the price adjustment method. Mixing forward-adjusted and backward-adjusted prices creates false breakouts.
    2. For symbols with fewer than sixty trading days of history, mark them as insufficient data instead of assigning a low-confidence label.
    3. Preserve the raw indicator values in the stage output so Layer 2 can explain them and Layer 3 can link them to risk thresholds.

    Write the coarse-screening output to a list file with these fields: symbol, industry, stage, slope, volume ratio, position relative to the long-term high, and data completeness. Compressing the whole market down to twenty or thirty candidates is the most valuable step in this workflow, because it reduces the volume of expensive model calls by one to two orders of magnitude.

    4. Layer 2: Structured Refinement With an LLM, Not Prediction

    The model’s correct role in this layer is information integrator and constraint checker. It is good at reordering a multi-field candidate list along consistent dimensions, pointing out commonalities, and flagging anomalies. It is not good at producing reliable short-term price conclusions. So the prompt should state only constraints and the output format, with no leading language.

    Here is a reusable prompt template. Note that it explicitly forbids return predictions and price targets:

    1. You are a candidate-list organizer in a quantitative workflow.
    2. Input: a list of candidate symbols (fields: symbol, industry, stage, ma_slope, vol_ratio, distance_from_high, data_completeness).
    3. Tasks:
    4. 1. Compare candidates horizontally using only the input fields; do not introduce outside information that was not provided;
    5. 2. Rank by "trend strength x volume health x data completeness" and return the top 3 to observe;
    6. 3. For each one, output: reason for selection, main risk, and fields that need human review;
    7. 4. Do not predict price changes, do not give entry or exit levels, and do not fabricate fields that are absent from the input.
    8. Output: a strict JSON array with fields code, rank, reason, risk, need_review.

    Constraining the model to JSON lets Layer 3 and the backtesting framework consume the output directly. If the model returns an invalid structure, retry once and then fall back to pure rule-based ranking so the workflow does not break on a single failure.

    For batch processing, group the candidate list by industry and call the model concurrently, keeping each group under ten symbols to preserve context clarity. Log the input, output, model version, and timestamp of every call to a logging service for later review and attribution. If you use a cloud inference service, combine it with a message queue to smooth out traffic spikes, archive samples in object storage, and track failure rate and latency with monitoring and alerts.

    5. Layer 3: Risk Control and Backtestability

    Every screening workflow must pass backtesting before live trading. Backtesting should cover at least three cost types: slippage, market impact, and the time cost of forced liquidation. A strategy that only captures two trend phases has short holding periods and high turnover, so it is far more cost-sensitive than a long-term strategy. Assuming zero one-way cost will almost certainly overstate returns.

    Make risk controls hard constraints, not suggestions: a per-symbol position cap, an industry concentration cap, exit when price breaks the medium-term moving average, mandatory close-out after a set number of trading days regardless of profit or loss, and staying flat when the daily candidate pool is empty. Sample code:

    1. def risk_check(pos, quote, cfg):
    2. if quote["close"] < quote["ma20"] * (1 - cfg["stop_pct"]):
    3. return "exit_trend_break"
    4. if pos["hold_days"] >= cfg["max_hold_days"]:
    5. return "exit_time"
    6. if pos["weight"] > cfg["max_weight"]:
    7. return "trim"
    8. return "hold"

    6. Common Pitfalls and Compliance Notes

    First, do not treat the model’s explanation as causation. A statement that volume looks healthy is just a natural-language restatement of the input fields; it adds no new information. Second, do not change stage parameters frequently. Parameter drift makes historical backtests meaningless. Fix the parameters and run periodic out-of-sample checks instead. Third, watch for data leakage. Any factor that uses future data will inflate backtest results. Fourth, the output of this workflow is a candidate watch list, not investment advice. Live trading decisions and their risks rest with the user.

    Implemented as three layers, this structure compresses hours of repetitive comparison into minutes. More importantly, the process is reproducible, auditable, and backtestable. The model does the summarization and expression it is actually good at, while judgment stays with the rules and risk controls.