How AI Agents Use Code Execution to Eliminate Hallucinations in Financial Data Analysis

    Large language models are highly effective at understanding tasks, writing code, and organizing analysis, but they are not reliable numerical calculators. This article explains how AI Agents can use code execution to calculate financial indicators such as inventory and basis percentiles, generate data-driven charts, and produce reproducible research reports. It also compares Agent-based calculation results and presents practical recommendations for building auditable financial data analysis pipelines.

    1. Why Precise Calculations Cannot Rely on an LLM’s “Best Guess”

    Large language models are fundamentally probabilistic sequence predictors. When a task involves structured calculations governed by strict mathematical rules—such as percentiles or basis values—the model does not necessarily perform genuine numerical computation internally. Instead, it may infer an answer that appears plausible based on its training data and the surrounding context.

    In practice, different models can produce inventory percentile results that vary by several percentage points when operating in pure conversational mode. The decimal places are often unreliable as well.

    This is known as a calculation hallucination: the output may be perfectly correct in format while the numerical value is only an approximation and cannot be reproduced consistently. Such errors are unacceptable in financial research and risk metrics, where numerical precision is critical.

    2. The Core Value of Agent Mode: Let AI Write Code Instead of Memorizing Answers

    Agent mode—also known as tool-calling or code-execution mode—takes a different approach. Instead of directly answering a numerical question, the model acts as a programmer. It automatically generates a script, runs the script in an interpreter, reads actual data files, and produces an answer based on the computed results.

    This approach provides three layers of protection:

    1. Reproducible calculations: The same script produces consistent results and does not depend on sampling temperature or context length.
    2. Traceable data: Every output value can be linked to specific lines of code and input data.
    3. Verifiable charts: Charts generated by visualization libraries contain data points calculated from real data, rather than pixels produced probabilistically by an image-generation model.

    A representative workflow looks like this:

    1. User request
    2. └─> Agent creates a task list
    3. ├─> 1. Write a script to read Excel/CSV files
    4. ├─> 2. Calculate percentiles, basis values, and other metrics
    5. ├─> 3. Use visualization libraries to generate charts
    6. ├─> 4. Search a local information repository or the web for context
    7. └─> 5. Combine text and charts and export a PDF research report

    A typical percentile calculation script might look like this:

    1. import pandas as pd
    2. df = pd.read_excel("inventory.xlsx")
    3. current = df["库存"].iloc[-1]
    4. quantile = (df["库存"] <= current).mean()
    5. print(f"Current inventory percentile: {quantile:.1%}")

    The model is responsible for writing the code, while the interpreter is responsible for calculating the exact result. This separation of responsibilities is one of the most reliable engineering methods for reducing numerical hallucinations.

    3. Chart Generation Determines Professional Quality: Code-Based Charts vs. AI-Generated Images

    One often-overlooked difference in automated reporting is how charts are produced:

    • Code-based charts: The Agent calls Python visualization libraries. Axes, data points, trend lines, labels, and formatting are all driven by actual data. This provides precise control over scales, annotations, and styles, making the approach suitable for research reports and compliance documents.
    • AI-generated images: Diffusion-based models generate images based on textual descriptions. The result may look attractive, but the positions of data points are probabilistic and cannot be mapped to real numerical values. This makes the images unsuitable when accuracy and professional reliability are required.

    For this reason, automated research pipelines should explicitly require the Agent to generate charts through code. A prompt can include an instruction such as:

    Automatically call a visualization library to create the charts, then combine the written content and charts into a PDF report.

    This connects the full workflow:

    1. Read data → Calculate metrics → Generate charts → Format the report → Export a PDF

    4. Practical Comparison: Percentile Calculations in Agent Mode

    Two test metrics were used: the current inventory percentile and the current basis percentile. Multiple mainstream large language models were asked to generate scripts and perform the calculations in Agent mode. The results were as follows:

    Mode Model Inventory Percentile Basis Percentile
    Agent Model A 26.3% 55.0%
    Agent Model B 21.2% 55.2%
    Agent Model C 27.4% 68.0%
    Agent Model D Approximately 30% Approximately 30%

    Several observations can be drawn from these results:

    1. Agent mode does not automatically eliminate differences between results. The main source of variation is how each model interprets the definition of a percentile—for example, whether boundary values are included and which interpolation method is used. The differences are not necessarily caused by the arithmetic itself. Prompts should therefore define the methodology explicitly, such as using the empirical distribution function P(X≤x).

    2. Approximate outputs may indicate that no strict calculation was performed. A result such as “approximately 30%” suggests that the model may still be answering approximately rather than executing the script. It is important to verify that the code was actually run.

    3. Basis percentiles show greater variation than inventory percentiles. The basis results range from 55.0% to 68.0%, while the inventory results are more concentrated. This suggests that when a calculation involves the difference between two data columns, variations in script-generation quality can have a greater impact.

    5. Implementation Recommendations for a Reliable Agent-Based Data Analysis Pipeline

    Based on these experiments, the following engineering recommendations can improve reliability:

    1. Require code execution: The prompt should explicitly state that the Agent must write and run a script to obtain the result and must not estimate.
    2. Define the metric precisely: Include the mathematical definition and data-processing rules in the prompt to eliminate ambiguity.
    3. Require intermediate outputs: Ask the Agent to print intermediate variables and sample counts so that the results can be checked manually.
    4. Generate all charts with code: Avoid AI-generated images for analytical charts to ensure consistency between the text and the underlying data.
    5. Cross-check critical results: Use multiple models to calculate important indicators independently, or compare the results with an offline calculation.
    6. Plan for usage limits and costs: Cloud-based Agent platforms may provide limited free usage, and complex tasks can be interrupted when the quota is exhausted. Production systems should reserve sufficient calling capacity or consider a private deployment.

    6. Conclusion

    Large language models are strong at understanding intent, organizing language, and writing code. Precise numerical computation, however, should be delegated to a deterministic script runtime.

    Agent mode combines these strengths in the appropriate way: the model handles orchestration, while code handles computation. For quantitative analysis and financial research, where numerical accuracy is essential, asking AI to write and execute code is not merely an efficiency improvement—it is a reliability requirement.

    With clear metric definitions, strict execution requirements, and appropriate validation mechanisms, organizations can build automated analysis pipelines that are reproducible, traceable, and auditable.