How to Use Large Language Models for Stock Cycle Analysis

    This article explains why asking a large language model directly what to buy almost always fails, and how to reposition the model as a research assistant rather than a decision maker. It introduces a computable six-stage market framework, a two-level screening pipeline that combines deterministic rule-based filtering with model-based comparison, practical prompt and context engineering principles, a reproducible engineering architecture, and the risk guardrails that must be built into the workflow.

    1. Where the Problem Starts: Why “Just Ask the Model What to Buy” Almost Always Fails

    Many people who try using AI coding tools or conversational large language models for investment research get a standardized risk disclaimer instead of actionable analysis. Three separate layers explain this.

    The first layer is the compliance boundary. Public-facing conversational models are typically required not to output personalized investment advice. This is a default product constraint, not a capability gap.

    The second layer is the mismatch between knowledge and timeliness. A model’s knowledge comes from its training corpus, so it inherently does not have high-frequency data such as today’s price, volume, or fund flows. Unless you explicitly place the latest data into the context, its judgment can only stay at the methodology level.

    The third layer is the most easily overlooked one: the missing intermediate structure. Investment research is not a single question-and-answer step but a chain: data acquisition, cleaning, stage classification, candidate set convergence, cross-sectional comparison, risk validation, and post-hoc attribution. Compress that entire chain into one question, and the model can only respond in generalities.

    The correct positioning follows from this: treat the large language model as a research assistant and information compressor, not a decision engine. It is good at summarizing, comparing, listing differences, and generating checklists over structured material you supply. It is not good at, and should not be responsible for, the final decision.

    2. Giving the Model a Navigation System: A Quantifiable Stage Classification Framework

    To move output from vague to usable, you first need a clear, computable definition of stages. A common industry practice is to divide price behavior into several states and distinguish them with indicators such as volume, moving average structure, volatility, and relative strength. Below is a practical six-stage abstraction (illustrative, not any proprietary model):

    Stage Typical Characteristics Research Implication
    Winter Prolonged downtrend, shrinking volume, low attention Observe, do not engage
    Spring Bottom-range consolidation, volume recovering mildly, trend unconfirmed Build a watchlist
    Early summer Breakout at a key level, moving averages turning bullish, no market consensus yet Priority research window
    Midsummer Trend established, steady advance, healthy price-volume coordination Holding and tracking window
    Late summer Accelerating advance, overheated sentiment indicators, early signs of price-volume divergence Gradual profit-taking window
    Autumn Good news delivered, high-level volume with stalled price, structure broken Risk disposal window

    The value of this framework is not prediction but converting fuzzy market states into determinable labels. Once the labels are computable, screening turns from subjective judgment into an engineering problem.

    A minimal executable classification approach is shown below (illustrative code that expresses logic only and constitutes no live trading scheme):

    1. def classify_stage(bars, ma_short=20, ma_long=60, vol_ratio=1.5):
    2. close = [b.close for b in bars]
    3. vol = [b.volume for b in bars]
    4. ma_s = sum(close[-ma_short:]) / ma_short
    5. ma_l = sum(close[-ma_long:]) / ma_long
    6. breakout = close[-1] > max(close[-ma_long:-1])
    7. vol_expand = (sum(vol[-5:]) / 5) / (sum(vol[-20:]) / 20) > vol_ratio
    8. if ma_s > ma_l and breakout and vol_expand:
    9. return "early_summer"
    10. if ma_s > ma_l and close[-1] > ma_s:
    11. return "midsummer"
    12. return "other"

    Three engineering points matter here. First, parameters must be fixed and recorded, so that repeated tuning does not create hindsight fitting. Second, all thresholds should be written into configuration so runs are reproducible. Third, a stage label is only an entry point to the candidate set, not a reason to buy.

    3. Pipeline Design: Coarse Filtering for Convergence, Fine Filtering for Comparison

    Handing a raw list of thousands of instruments straight to the model quickly hits context length limits, and output quality degrades as input noise rises. A sensible structure is a two-stage funnel.

    Stage one is rule-based coarse filtering. Run the framework above in batch locally or in the cloud to compress the full universe down to a few dozen instruments. The key here is determinism: the same input must produce the same output, and the process must be recordable.

    Stage two is model-based fine filtering. Feed the converged candidate set together with structured features to the model, and ask it for cross-sectional comparison and difference explanation rather than a conclusion. The prompt should state only constraints and the output format, for example:

    1. Below are structured features for candidate instruments (JSON array).
    2. Within an observation window of the next 2-3 trading days, rank them by three dimensions:
    3. trend structure clarity, price-volume coordination, and volatility risk.
    4. Output no more than 3 priority watch items.
    5. Requirements:
    6. 1) Reason only from the given fields; do not introduce external information that was not provided;
    7. 2) For each item, give 3 supporting reasons and 2 opposing reasons;
    8. 3) Output strict JSON with fields name, rank, pros, cons, risk_note.

    Example of structured input:

    1. [
    2. {"code":"A1","stage":"early_summer","ma_align":true,"vol_ratio":1.8,"atr_pct":3.2,"drawdown_60d":-12.4},
    3. {"code":"B2","stage":"midsummer","ma_align":true,"vol_ratio":1.2,"atr_pct":2.1,"drawdown_60d":-4.0}
    4. ]

    This design yields three benefits: output is parseable, storable, and comparable; reasoning is confined to the given fields, which reduces speculation; and listing supporting and opposing reasons side by side naturally suppresses one-sided optimism.

    4. Prompt and Context Engineering Essentials

    The stability of model output depends mostly on how the input is organized, not on how polished the wording is. The following principles apply:

    • Separate role from boundary. State clearly that the model is a research assistant that does not issue buy or sell instructions, putting the compliance constraint up front.
    • Provide the field dictionary first. Define the meaning and unit of each field before presenting data, so the model does not guess units on its own.
    • Use few-shot examples. One or two examples of the expected output work better than long descriptions.
    • Lower the temperature. Reduce randomness when stable structured output is needed; raise it moderately only for brainstorming-style risk lists.
    • Enforce structure. Require JSON or table output so programs can consume it and batch validation is possible.
    • Feed data in segments. When the data volume is large, supply it in batches and repeat the constraints before each batch to prevent instruction decay in long contexts.

    5. Reproducibility and Engineering Implementation

    A one-off conversation accumulates no value; engineering is what makes the method iterable. A minimal architecture includes a data ingestion layer that pulls market and financial data on schedule; a feature computation layer that implements stage classification and risk indicators; a task scheduling layer triggered per trading day; a model invocation layer that wraps prompt templates and retries; a result storage layer that keeps a snapshot of every input and output; and a monitoring and alerting layer that notifies on task failures, missing fields, and malformed output. These capabilities can each map to common general-purpose categories such as container platforms, message queues, object storage, log services, and monitoring and alerting from cloud providers, with no dependency on any proprietary interface.

    An illustrative invocation wrapper:

    1. def run_screen(candidates, prompt_template, model_client):
    2. payload = build_payload(candidates) # structured fields + field dictionary
    3. prompt = prompt_template.format(data=payload)
    4. for attempt in range(3):
    5. resp = model_client.chat(prompt, temperature=0.1)
    6. try:
    7. return parse_json(resp) # strict parsing; retry on failure
    8. except ValueError:
    9. continue
    10. raise RuntimeError("output schema invalid")

    The review step matters just as much: align each round’s candidate set, stage labels, and the model’s stated reasons with the actual subsequent price action, then measure hit rate and failure modes. If the model turns out to favor instruments with excessive volatility, add an explicit volatility penalty term to the fields rather than relying on a verbal reminder.

    6. Risks and Boundaries: Guardrails That Must Be Built into the Process

    • Data quality takes priority over model capability. Missing fields, incorrect adjustment for splits and dividends, and misaligned timestamps can distort all downstream reasoning.
    • Stage classification is inherently lagging. Any framework based on moving averages and volume is confirmatory rather than predictive, and necessarily gives up part of the move.
    • Model output can sound confident while resting on thin evidence, so supporting and opposing reasons and traceable fields must be preserved.
    • Enforce position sizing and stop-loss discipline, with a preset cap on single-trade risk exposure, to avoid irreversible losses from consecutive misjudgments.
    • Keep a full audit trail in which inputs, parameters, outputs, and versions correspond one to one, enabling post-hoc attribution and compliance review.

    7. Conclusion

    A large language model will not make investment decisions for you, but it can substantially compress the cost of information processing: converging the full universe into a researchable candidate set, organizing messy material into a comparable structured view, and making implicit assumptions explicit as supporting and opposing reasons. What truly determines the outcome is whether you have first built a computable stage framework, a reproducible engineering pipeline, and enforceable discipline constraints. The stronger the tool, the greater the weight of methodology and risk control.