Quantitative Analysis and Research Report Generation with LLM Agents
LLM agents are moving beyond conversational question answering toward reliable task execution. This article presents a practical framework for using code-execution agents in quantitative analysis and research report generation, covering deterministic calculations, workflow planning, chart rendering, document assembly, validation, error evaluation, security controls, and auditability. The central principle is simple: let code perform the calculations, let the model explain the results, and use human review for high-value outputs.
Large language model (LLM) agents are evolving from conversational assistants into systems that execute multi-step tasks. In quantitative analysis and research report generation, their value is not measured by whether they can describe conclusions in natural language, but by whether they can reliably read data, calculate indicators, render charts, assemble documents, and verify the final output.
This article presents a practical, technology-oriented workflow for building code-execution agents that reduce uncertainty in structured data analysis.
1. Problem Definition: Why Arithmetic Should Be Delegated to Code
A typical quantitative research workflow includes:
- Reading data from multiple sources
- Cleaning and standardizing fields
- Calculating factors or basis values
- Computing percentile statistics
- Rendering charts
- Writing textual conclusions
- Combining text and charts into a final document
This workflow is long and involves many definitions and assumptions. A misunderstanding at any stage can propagate into the final report.
LLMs are good at understanding tasks, decomposing workflows, and generating explanatory text. However, they can produce probabilistic errors when directly outputting numerical values. For example, a model may infer an approximate decimal from context instead of following the required mathematical rules exactly.
A safer division of responsibilities is:
The model plans the task, generates scripts, and explains results; the script performs deterministic calculations; and the execution environment returns the actual values.
In quantitative workflows, percentile calculations must explicitly define the sample range, missing-value handling, interpolation method, unit, and decimal precision. These rules should be encoded in code. The model must not override script results with a natural-language answer.
In this setup, the agent acts as a programmer: it writes code to process the data and then inserts the execution results into the report. This approach preserves the model’s automation capabilities while reducing hallucinations when it handles complex structured information.
2. The Agent Workflow: Plan, Execute, Validate, and Correct
A practical analysis agent typically creates a task list before execution and then works through the list step by step. Typical stages include:
- Confirm the data definitions and scope
- Load the data
- Calculate metrics
- Generate charts
- Write conclusions
- Assemble the document
- Validate the generated artifacts
The task specification should clearly define the required outputs, such as chart files, data snapshots, execution logs, and the final document. This prevents the agent from returning only a seemingly complete block of text.
A simplified pseudocode workflow is shown below:
plan = planner(task_spec, output_requirements)for step in plan.steps:if step.kind == "load":script = generate_script(step, schema)result = sandbox.run(script, inputs=authorized_inputs)if step.kind == "calculate":script = generate_script(step, formula_spec)result = sandbox.run(script, inputs=loaded_data)assert result.values_are_numeric()if step.kind == "chart":chart_spec = build_chart_spec(result, style_template)chart = render_chart(result.series, chart_spec)if step.kind == "report":text = explain(result, chart_meta)document = merge_document(template, text, chart, metadata)validate(document, required_sections, numeric_consistency)
The critical stage is validation after execution. Once the agent generates a script, the script should first undergo static checks and then run inside an isolated environment. The output should be checked for:
- Numerical consistency
- Field completeness
- Chart metadata
- Expected output files
- Required report sections
If the script fails or produces abnormal results, the agent can use the logs to correct the script. However, corrected numerical values must still come from execution results rather than being invented by the model.
For web-based or local knowledge-base retrieval, the agent should be restricted to authorized sources. Retrieved information should also be labeled separately from calculated results so that external content does not contaminate numerical conclusions.
3. The Boundary Between Programmatic Charts and Generative Images
Charts in quantitative reports require a high degree of precision. Programmatic charting libraries read data series through code, with every point derived from a specific value. Axes, ticks, legends, and annotations can all be reproduced. Generative image models, by contrast, generate pixels probabilistically. They are suitable for covers, illustrative scenes, or conceptual graphics, but they should not replace data charts.
The most important difference is traceability. A programmatic chart can retain the data snapshot, plotting parameters, and script version used to create it. A generated image generally cannot guarantee a one-to-one correspondence between numerical values and visual elements.
For this reason, data charts should generally be created programmatically. The agent can generate a plotting script based on the factor logic, produce the chart file, and record the chart title, data range, and unit in the document.
For daily reports or research reports that contain multiple charts, a document assembly module can combine text, charts, headers, and footers into a PDF. The document should include the generation time, data version, and task identifier.
For auditability and reproducibility, it is advisable to retain:
- The final document
- Chart source files
- Execution scripts
- Runtime logs
- Data snapshots
4. Sources of Error and Evaluation Methods
Structured analysis agents can fail for many reasons, including:
- Misunderstanding the analytical scope
- Inconsistent missing-value handling
- Different interpolation methods
- Unit conversion errors
- Decimal truncation
- Incorrect sample ranges
- Script defects
- Approximate numerical values generated directly in natural language
In a general capability evaluation, different implementations produced different inventory and basis percentiles. Further review showed that some of the discrepancy came from the model outputting approximate decimals in text instead of invoking a calculation script.
This leads to an important rule:
Statistical results such as percentiles must be based on script output. The model should only explain what those results mean.
Evaluation should focus on the following metrics:
- Numerical consistency: Whether the values in the report exactly match the script output
- Reproducibility: Whether the same data snapshot and script produce the same results
- Chart correctness: Whether axes, units, legends, and data series match
- Report completeness: Whether all required sections and artifacts are present
- Execution success rate: How often the workflow completes without failure
- Manual review time: Whether automation actually reduces repetitive work
For high-value reports, a dual-path calculation strategy can be used. One path uses the agent-generated script, while an independent validation script recalculates the results. If the difference exceeds a defined threshold, the system should issue an alert and route the output for human review.
5. Engineering Implementation and Security Auditing
Code execution by an agent requires clear engineering constraints.
The first principle is least privilege:
- Make data access read-only where possible
- Isolate working directories
- Restrict network access
- Set limits on resource usage
The execution environment should also use dependency locking and sandboxing. This reduces the risk of scripts introducing uncontrolled dependencies or damaging the runtime environment.
Logging and auditing are equally important. The system should record:
- Task inputs
- Generated scripts
- Execution commands
- Output files
- Error messages
Sensitive fields should be masked or anonymized in logs.
For reports intended for external publication, a human approval step should be retained. An agent should not publish a report directly without review.
Observability is another essential capability. Task logs, execution metrics, and exception alerts can be connected to general-purpose logging and monitoring systems. Intermediate artifacts can be stored in object storage and archived by task identifier.
Cost control can be improved through:
- Caching frequently used data
- Incremental computation
- Timeout termination
- Reusing existing results
Security and efficiency are not contradictory. The more clearly the system defines calculation boundaries, permission boundaries, and audit boundaries, the more reliably the agent can handle repetitive work.
6. Practical Lessons and Recommendations
In practice, agents provide significant value in quantitative report generation by automating mechanical work. They can split tasks, generate scripts, call charting libraries, and combine text and charts into a document, substantially reducing the time from raw data to an initial report.
However, an agent should be treated as an auditable analysis assistant, not as a generator of final conclusions.
The most effective collaboration model is a closed loop:
Plan → Code → Validate → Correct
The model creates the plan and generates code. The execution environment returns real results. The validation module checks numerical values and output artifacts. The model then writes explanations based on those verified results.
The key implementation recommendations are:
- Define the required artifacts and numerical backfilling rules in the task specification.
- Require all statistical values to be calculated by scripts and written to structured results.
- Use programmatic charting for data visualizations and retain the chart parameters.
- Automatically check report sections, charts, and numerical consistency after document assembly.
- Retain manual spot checks for critical reports.
- Archive logs, data snapshots, and script versions.
As long as the boundary remains clear—code performs the calculations, the model explains the results, and humans review critical outputs—LLM agents can deliver stable value in quantitative analysis and research report generation.
