How to Use Large Language Models for Stock Cycle Analysis

    This article explains why asking a large language model to pick stocks directly is bound to fail, and presents a practical alternative: a deterministic rules engine for candidate generation paired with the LLM for structured comparison. It covers a six-stage trend lifecycle framework, a three-layer pipeline spanning data, rules, model, and review, prompt design practices such as constraint-first instructions and forced uncertainty labeling, and the backtesting and risk controls required before any live use.

    1. The Starting Problem: Why Handing Stock Selection to an LLM Fails

    Most first attempts begin with a question like “Which stock will hit the daily limit up tomorrow?” Such a question almost always leads to one of two outcomes: the model declines on compliance and prudence grounds, or it returns a plausible-sounding but unverifiable generalization. The problem is not model capability but three flaws in the question itself.

    First, there is no decidable input. The model has no access to your holdings, no real-time quotes, and no financial statements or company announcements. It can only rely on historical statistical patterns in its training corpus, and those patterns have almost no explanatory power for an extremely short window such as “the next two trading days.”

    Second, there are no constraint boundaries. Without a defined candidate pool, time window, risk tolerance, and output structure, the model’s output space is divergent and cannot converge on an actionable conclusion.

    Third, the role is misassigned. Large language models are good at semantic understanding, information summarization, multi-source comparison, and structured expression. They are not good at high-precision numerical prediction. Treating one as a predictor is a mismatch; treating it as a research assistant is the right answer.

    The correct engineering approach, then, is to decompose the vague goal of “stock selection” into two subtasks: quantifiable candidate pool generation and cross-sectional comparison of the candidates. The former belongs to a deterministic rules engine; the latter belongs to the LLM.

    2. Methodology: Replacing Emotional Judgment with a Cycle Stage Framework

    Reproducible analysis requires an explicit standard for state classification. A common industry practice is to discretize the trend lifecycle of a target into several stages, classifying it using computable indicators such as price position, volume, moving average structure, and volatility. A typical six-stage breakdown looks like this:

    • Late decline: price has trended down for a long time, volume has shrunk, and attention is minimal;
    • Bottom consolidation: price oscillates repeatedly within a narrow range, capital begins tentative entry, and direction is unclear;
    • Trend initiation: price breaks effectively through a key level and moving averages turn bullish, but market consensus has not yet formed;
    • Mid main advance: the trend is established, price and volume cooperate well, and the upward slope is stable;
    • Accelerated blow-off: gains are steep, retail capital floods in, volatility expands, and distribution pressure rises;
    • Distribution and decline: the good news is fully priced in, price breaks key support, and the market enters a downtrend.

    The value of this framework is that it translates “it feels like it’s going up” into “it is in a specific computable state,” and it makes the strategy explicit: take positions only from trend initiation through mid main advance, and scale out in tranches during the accelerated blow-off. Once the rules are explicit, a program can execute them in batch instead of relying on a human scrolling through charts.

    It is worth stressing that stage classification must be done by deterministic code, not by the model “reading the chart.” The model is unstable in judging numerical boundaries, whereas a rules engine always returns the same conclusion for the same data. That is the prerequisite for reproducibility.

    3. Engineering Implementation: A Three-Part Pipeline

    The overall architecture has a data layer, a rules layer, a model layer, and a review layer.

    The data layer acquires market and fundamental data, then handles adjustment for corporate actions, missing value filling, and trading calendar alignment. Common engineering pitfalls are misaligned moving averages caused by inconsistent adjustment methods, and distorted indicators caused by data gaps during trading suspensions.

    The rules layer implements stage classification. Sample code:

    1. def classify_stage(df, ma_short=10, ma_long=60, vol_ratio=1.5):
    2. close = df["close"]
    3. ma_s = close.rolling(ma_short).mean()
    4. ma_l = close.rolling(ma_long).mean()
    5. vol_ma = df["volume"].rolling(20).mean()
    6. breakout = close.iloc[-1] > ma_l.iloc[-1] and ma_s.iloc[-1] > ma_l.iloc[-1]
    7. vol_expand = df["volume"].iloc[-1] > vol_ratio * vol_ma.iloc[-1]
    8. drawdown_250 = close.iloc[-1] / close.max() - 1
    9. if drawdown_250 < -0.35 and not vol_expand:
    10. return "Bottom consolidation"
    11. if breakout and vol_expand:
    12. return "Trend initiation"
    13. if breakout and not vol_expand:
    14. return "Mid main advance"
    15. return "Watch"

    The model layer receives the candidate list from the rules layer and performs a cross-sectional comparison. The key is that the prompt must be written as a strong constraint, stating the role, input, limits, and output structure all at once:

    1. You are a research assistant. You only summarize and compare information. Do not issue buy or sell instructions, and do not predict specific percentage gains.
    2. Input: a candidate list (including the industry of each target, its price and volume characteristics over the last 20 days, and its stage label).
    3. Constraints:
    4. 1) Reason only from the input information; label missing information as "unknown" and do not fill gaps with guesses;
    5. 2) Score each target from 1 to 5 on three dimensions: consistency of industry outlook, health of the price-volume structure, and volatility risk;
    6. 3) Output a Markdown table with the columns Code / Industry / Stage / Three-dimension scores / Main risk / Items to verify;
    7. 4) At the end, list no more than 3 key data items that require manual verification.

    The review layer is handled by a human, focusing on the “items to verify” flagged by the model, such as announcements, industry policy, and shareholder changes—real-time information the model cannot access.

    4. Prompt and Context Design Essentials

    Constraints matter more than role setting. Writing only “you are a senior analyst” produces almost no binding force. What actually works is stating explicitly what must not be done and what structure the output must take.

    Force uncertainty labeling. Requiring the model to output “unknown” for missing fields significantly reduces hallucinated completion, and this is a necessary condition for putting the model into a production workflow.

    Control context size. Keep the candidate list within a few dozen objects, and keep fields trimmed and standardized. Avoid stuffing large blocks of raw quote tables into the context, or the key constraints get diluted.

    Fix the output format for automation. Only tabular output with fixed fields can be parsed by downstream programs, stored, and compared against historical records.

    Lower the temperature. For analysis scenarios that need stable reproduction, reduce randomness and run consistency checks by sampling the same input multiple times.

    5. Validation and Risk Control

    Any decision-support framework must be backtested before going live. The recommendation is out-of-sample validation over rolling windows, measuring the distribution of 5-day and 20-day forward returns and the maximum drawdown after each stage classification, and confirming the strategy has positive expectancy before testing with a small position.

    Be clear-eyed about the model’s capability boundaries: it has no real-time data access, cannot read non-public information, and cannot bear responsibility for returns. On compliance, any external output should avoid constituting investment advice and should serve only as an internal research lead.

    For risk control, set a per-target position cap, an industry concentration cap, and stage-based exit rules—in particular, scale out in tranches during the accelerated blow-off rather than waiting for the trend to end on its own.

    6. Conclusion

    The correct role for a large language model in investment research is a “semantic layer processor”: it turns the structured candidates filtered by the rules engine into comparable, archivable, and reviewable research summaries. What really determines the outcome is an explicit quantitative framework, strict prompt constraints, and a complete validation loop. If greater data throughput and task scheduling capability are needed, the pipeline can be built on general cloud primitives such as object storage, message queues, container platforms, and monitoring and alerting; Baidu AI Cloud can likewise support the engineering deployment of such research tasks on this kind of general-purpose infrastructure.