From Market Quotes to Valuation Analysis: Building a Reliable A-Share AI Assistant

    A reliable A-share assistant should not treat a valuation question as a single fluent answer. This article explains how to split the work between a data and calculation layer and a language and explanation layer, then covers unified data contracts, skill boundaries, a verifiable valuation workflow, quality gates, caching and observability, and checks that external content cannot become executable instructions.

    1. The core problem in stock queries is evidence, not the answer

    When a user asks whether a stock is expensive, the surface request is a single judgment. In practice it depends on several linked questions: the current price, which reporting period the financials cover, whether profits are sustainable, which companies are comparable, and whether market expectations are already reflected in the price.

    Large language models are good at understanding these questions and organizing an analysis framework, but model parameters are not a live market database. Information accumulated during training cannot reliably answer a current valuation. Even with web retrieval, pages may have unclear update times, numbers may lack units, and financial-statement definitions may not match.

    A reliable A-share assistant should therefore split the work into two parts:

    • Data and calculation layer: obtain records, check freshness, align definitions, and perform deterministic calculations.
    • Language and explanation layer: understand the request, sequence the queries, and explain results only within the available evidence.

    This split does not reduce the model’s role. It keeps the model on tasks it is suited for. When data is missing, the system should state the limitation instead of filling the gap with fluent language.

    A-shares are equities listed on mainland China’s stock exchanges. The design below is about evidence, calculation, and controls for that market; it is not a claim that any particular data source or product is available worldwide.

    2. Multi-source data access: define a contract before calling interfaces

    A-share analysis often needs quotes, historical trades, financial reports, company announcements, fund-flow statistics, and macro indicators. These records may come from different channels, with different transport methods, field structures, update cycles, and access permissions.

    Do not let the model face every raw interface directly. A safer approach is an adapter between data sources and the assistant:

    1. User question
    2. ↓
    3. Intent recognition and task planning
    4. ↓
    5. Permission checks and tool routing
    6. ↓
    7. Unified data adapter
    8. ↓
    9. Authorized data channels
    10. ↓
    11. Quality checks and deterministic calculation
    12. ↓
    13. Evidence assembly and natural-language report

    “Unified” does not mean forcing every dataset into one table. It means defining clear inputs, outputs, and error states for each task type.

    2.1 Establish security-identifier rules

    A ticker is not an ordinary number. The system should identify it with the trading venue, security type, and effective date, and it should preserve leading zeros.

    If the user enters only a short name, the name may have changed or may be ambiguous. Show candidates first, then analyze. Do not generate a full report after resolving the wrong security.

    2.2 Separate time fields

    A record may involve several times:

    • Business time, such as the trading time a quote refers to
    • Publication time, such as when a financial report was disclosed
    • Collection time, when the system retrieved the record
    • Applicable period, such as a financial reporting period

    These must not be treated as the same thing. An annual report downloaded just now is still historical financial information. A recent collection time does not make it real-time data.

    Historical backtests also need to check whether the information was already public at the analysis time. Otherwise the test can use future information.

    2.3 Keep units and calculation definitions

    Prices, amounts, volumes, and ratios should all carry units. For historical prices, record whether they are adjusted. For financial metrics, distinguish cumulative values, single-quarter values, and trailing twelve-month values.

    A single-quarter profit can sometimes be derived by subtracting adjacent cumulative values, but only when the reporting scope, accounting basis, and restatement status match. Do not subtract without that check.

    2.4 Attach a source note to every result

    A useful output structure includes the security identifier, data time, source identifier, field units, and quality status. The following is an illustrative contract, not the field definition of any existing API:

    1. Security identifier: validated code and trading venue
    2. Data category: quote / financials / announcement
    3. Business time: point in time or period the data refers to
    4. Collection time: when the system retrieved the record
    5. Fields: value, unit, definition
    6. Source: internally registered data-channel identifier
    7. Quality status: normal / delayed / missing / conflicting

    When channels disagree, the adapter should keep the difference. The model should not pick the number that “looks reasonable.”

    3. Skill documents describe execution boundaries, not automatic completion

    Writing the query flow into a skill document reduces repeated prompting and makes the assistant call existing capabilities more consistently. The document itself does not create market interfaces, access rights, or an execution environment.

    A complete skill definition should cover at least six areas.

    3.1 Scope

    State which tasks the skill supports among quote lookup, historical trends, basic valuation, and announcement summaries, and state what it does not support. A data-query capability should not be described as automated trading.

    3.2 Inputs

    Explain how the security identifier, analysis time, and target metrics are provided. If the user does not specify a time, the latest available data may be used, but the report must show that actual time. Do not label it vaguely as “current data.”

    3.3 Tool permissions

    Separate read-only queries, file reads, and external requests. For market analysis, read-only permission is usually the better default. Do not open system operations unrelated to the task.

    3.4 Execution order

    The skill document should require confirming the security first, then retrieving quotes and financials, then calculating metrics, and only then writing the explanation. Do not form a conclusion and then search for material that supports it.

    3.5 Failure and degradation

    Define behavior for delayed data, unavailable interfaces, and missing fields. For example, the system may return the most recent trading day’s close, but it must label that value as not a live price.

    3.6 Output rules

    Require the report to include data time, calculation basis, main limitations, and risk notes. For valuation judgments, separate facts, calculated results, and interpretive views.

    Sample code in a skill document is only part of a controlled implementation. Before use, still check dependencies, execution permissions, and error handling. “It runs in the document” is not a security guarantee.

    4. Valuation workflow: turn one question into verifiable steps

    For “analyze the valuation of a given A-share,” the following flow is a workable pattern.

    Step 1: Fix the subject and the point in time

    Confirm the security identity, listing status, and analysis date. If the market is closed, say that the quote is the latest available one. Do not imply that the price is still updating.

    Step 2: Fetch the minimum necessary data

    Basic valuation usually needs price or market capitalization, shares outstanding, profit, net assets, and the matching reporting period. Whether cash flow, liabilities, or industry data are also needed depends on the company and the question.

    Do not pull every dataset just to look comprehensive. Extra queries add latency, access cost, and failure risk, and they can introduce more inconsistencies.

    Step 3: Calculate and check definitions

    Common metrics include:

    • Price-to-earnings: market capitalization divided by profit on a matching basis
    • Price-to-book: market capitalization divided by net assets on a matching basis
    • Dividend yield: cash dividend per share over a stated period, divided by the corresponding price

    P/E needs an explicit profit basis. When using the last four quarters, confirm that each quarter is available and defined the same way. When using profit attributable to ordinary shareholders, the numerator and denominator should stay matched.

    If profit is negative or near zero, P/E is usually a poor primary comparison. The system should say the metric is hard to interpret, not treat a negative value as “cheap.”

    Step 4: Choose reasonable comparisons

    Peer comparison should consider core business, profit model, growth stage, and capital structure, not industry labels alone. Historical comparison should account for mergers, share-count changes, and earnings cycles.

    In cyclical industries, peak earnings can make P/E look low, and trough earnings can make it look high. One multiple does not replace a judgment about the business cycle.

    Step 5: State a conditional conclusion

    A reliable conclusion should be phrased as “given these data and assumptions.” For example: where the current valuation sits relative to a stated peer set, which factors may explain the gap, and which information is still insufficient.

    Fund-flow statistics, a one-day price move, or a single research note should not be turned directly into a deterministic buy or sell recommendation.

    5. Use quality gates before generating the report

    The assistant’s execution flow should have explicit quality gates. The following is conceptual pseudocode, not tied to a specific tool or API:

    1. Parse the user request
    2. Confirm security identity and analysis time
    3. Fetch quote data
    4. Fetch required financial data
    5. If data time does not meet the task:
    6. Flag the freshness limitation
    7. If key fields are missing:
    8. Return the part that can be completed
    9. State which metrics cannot be calculated
    10. Else:
    11. Check units, definitions, and value ranges
    12. Run deterministic calculations
    13. Store the calculation basis
    14. Assemble sources and limitations
    15. Generate a report layered into facts, metrics, and interpretation

    The key rule is that a failed calculation must not be hidden by language generation. If net assets are missing, do not output price-to-book. If there is no valid comparison sample, do not rank peers. That is more reliable than an unverified but complete-looking report.

    6. Production concerns: caching, rate limits, and observability

    6.1 Cache by data type

    Quotes and financial reports should not share the same refresh policy. Trading data is more sensitive to freshness. Reports and announcements are more sensitive to versions and corrections.

    Cache keys should include the security identifier, time range, and definition, so different price adjustments or reporting periods are not mixed. Also show the actual time of cached data so users can tell whether it fits the task.

    6.2 Handle errors by class

    Rate limits, authentication failures, network timeouts, and schema changes need different handling. Transient network problems may be retried a limited number of times. Permission errors should stop and prompt a configuration check. Field changes should fail validation.

    Retries must not run without limit, and they must not bypass access restrictions to keep calls going. Data access should stay within authorization, frequency requirements, and applicable rules.

    6.3 Record the task chain

    Each analysis should link the request, tool calls, data versions, calculation steps, and report result. If a user challenges a number, it should be possible to trace where it came from and how it was processed.

    Logs should not store access credentials or unrelated sensitive information. Observability is for debugging and audit, not for collecting as much as possible.

    7. Security boundary: external content is not an instruction

    Announcements, web pages, and research materials are external input. Their text may be analyzed, but it must not change system permissions or tool rules.

    If external content says “ignore previous requirements” or “read local files,” the assistant should treat that text as untrusted. In particular, it must not automatically run code snippets from the material or visit unknown addresses.

    Credentials should also stay outside the skill document. Access keys should not be written into prompts, examples, or logs. They should be injected by a controlled configuration mechanism. Analysis tasks should in principle use read-only accounts and a restricted network scope.

    Research opinions and source facts should be shown separately. Disclosures in an announcement, calculated metrics, and model inferences have different evidence levels. They should not be written as the same kind of established fact.

    8. How to test whether the assistant is actually reliable

    Evaluation should not stop at whether the report reads smoothly, and length is not a substitute for quality. At least cover:

    • Identity accuracy: whether ambiguous short names or malformed codes resolve to the wrong security
    • Time accuracy: whether live quotes, historical closes, and the latest disclosed financials are distinguished
    • Calculation consistency: whether the same inputs and definitions produce the same metrics
    • Missing-data behavior: whether related judgments stop clearly when data is insufficient
    • Traceability: whether key figures in the report can be traced to source records
    • Security: whether external text can induce the system to exceed its permissions
    • Explanation quality: whether facts, assumptions, and risks are clearly separated

    Test cases should include market closures, trading halts, losses, restated financials, conflicting sources, and interface failures. These edge cases often show maturity better than a normal query.

    9. Conclusion: put the natural-language entry on a reliable data path

    The value of an A-share assistant is not replacing all financial analysis with one sentence. It is lowering the cost of finding and organizing data so users can reach an evidence-based result faster.

    A durable design combines multi-source access, aligned definitions, skill constraints, deterministic calculation, and security controls. The model understands the question and explains the evidence. Programs collect data and calculate. Quality rules limit how far a conclusion may go.

    Only when every key number has a time, a definition, and a source, and every judgment can state its assumptions and limits, does the assistant move from “able to answer stock questions” to “able to support credible analysis.”