How to Export Analysis Reports in Markdown, Word, and PDF Formats from TradingAgents-CN

You can export TradingAgents-CN analysis reports in Markdown, Word, and PDF formats using the ReportExporter class in web/utils/report_exporter.py, which provides both programmatic APIs and Streamlit UI buttons for seamless document generation.

TradingAgents-CN generates comprehensive analysis results containing stock symbols, decision data, and detailed intermediate reports covering market data, fundamentals, sentiment, news, risk assessments, and team debates. The export pipeline converts these rich result dictionaries into polished documents suitable for sharing and archival, supporting Markdown for portability, Word (DOCX) for editing, and PDF for distribution.

Understanding the Export Architecture

The ReportExporter Class

The core export functionality resides in the ReportExporter class defined in web/utils/report_exporter.py. This class acts as a singleton instantiated at module load time, managing export availability, dependency detection, and format-specific generation logic.

The constructor performs state-aware initialization by checking for pypandoc availability, detecting Docker environments via docker_pdf_adapter.py, and configuring headless PDF rendering through setup_xvfb_display() when running in containerized environments.

Export Pipeline Overview

The export process follows a structured pipeline:

  1. UI Trigger: In web/components/results_display.py, three Streamlit buttons (Export Markdown, Export Word, Export PDF) invoke render_export_buttons(results).
  2. Format Routing: report_exporter.export_report(results, format_type) dispatches to generate_markdown_report, generate_docx_report, or generate_pdf_report.
  3. Content Generation: Markdown exports build strings directly; Word and PDF exports leverage pypandoc with automatic pandoc binary downloading if missing.
  4. File Persistence: save_report_to_results_dir writes files to results/<stock_symbol>/<YYYY-MM-DD>/reports/<filename>.
  5. Browser Download: Streamlit's st.download_button streams content to the user.

Exporting Reports Programmatically

You can generate export files outside the Streamlit UI by directly invoking the ReportExporter singleton:

from web.utils.report_exporter import report_exporter

# `results` is the dict returned by the analysis pipeline

markdown_bytes = report_exporter.export_report(results, 'markdown')
with open('my_stock_report.md', 'wb') as f:
    f.write(markdown_bytes)

docx_bytes = report_exporter.export_report(results, 'docx')
with open('my_stock_report.docx', 'wb') as f:
    f.write(docx_bytes)

pdf_bytes = report_exporter.export_report(results, 'pdf')
with open('my_stock_report.pdf', 'wb') as f:
    f.write(pdf_bytes)

The export_report method returns bytes for all formats, allowing direct file writing or HTTP response streaming.

Exporting via the Streamlit Web Interface

For custom Streamlit applications integrating TradingAgents-CN analysis, use the provided UI helper to render export buttons:

import streamlit as st
from web.utils.report_exporter import render_export_buttons

# Assume `analysis_results` is already populated

st.title("股票分析报告")

# … render other UI …

render_export_buttons(analysis_results)   # adds the three export buttons automatically

UI Button Implementation Details

The render_export_buttons function in web/utils/report_exporter.py creates three columns containing Streamlit download buttons. When clicked, each button triggers the full export pipeline: format generation, file saving to the results directory, and immediate browser download. The UI also displays status messages indicating how many modular reports were saved and the aggregated file location.

Required Dependencies and PDF Engine Configuration

Installing Pandoc and Optional PDF Engines

TradingAgents-CN exports rely on specific dependency tiers:

  • Markdown export: Requires only the markdown package (pure Python, always available).
  • Word (DOCX) and PDF export: Requires pypandoc. The exporter automatically downloads a recent pandoc binary if not found on the system.
  • Enhanced PDF rendering (optional): Installing wkhtmltopdf or weasyprint improves PDF quality. The exporter iterates through available engines, preferring wkhtmltopdf, then weasyprint, then falling back to pandoc's default engine.

Docker Environment Considerations

When running in containerized environments, the docker_pdf_adapter.py module detects Docker contexts and configures headless operation. The ReportExporter constructor calls setup_xvfb_display() to establish a virtual X display, enabling PDF generation without physical graphics hardware.

Customizing Export Behavior

Forcing a Specific PDF Engine

Advanced users can override the default PDF engine selection by modifying the exporter instance:

from web.utils.report_exporter import ReportExporter

custom_exporter = ReportExporter()

# Temporarily override the engine list

custom_exporter.generate_pdf_report = lambda r: custom_exporter._run_pandoc(r, engine='wkhtmltopdf')
pdf_bytes = custom_exporter.export_report(results, 'pdf')

Verifying Saved File Locations

To confirm where exported files are stored programmatically:

from web.utils.report_exporter import save_report_to_results_dir

path = save_report_to_results_dir(pdf_bytes, 'report.pdf', '600519')
print(f"文件已保存到 {path}")

# Output: results/600519/2024-01-15/reports/report.pdf

The function automatically creates date-based subdirectories under results/<stock_symbol>/ and returns the absolute path for logging or UI display.

Summary

  • Core Component: The ReportExporter class in web/utils/report_exporter.py orchestrates all export functionality, managing format generation and file persistence.
  • Three Formats: Markdown exports use pure Python string generation; Word (DOCX) and PDF exports leverage pypandoc with automatic pandoc binary management.
  • UI Integration: The render_export_buttons function provides ready-to-use Streamlit components for web interfaces.
  • Storage Pattern: Exported files save to results/<stock_symbol>/<YYYY-MM-DD>/reports/ with automatic directory creation.
  • Dependencies: Markdown requires no external tools; DOCX/PDF need pypandoc (auto-downloaded); optional wkhtmltopdf or weasyprint improve PDF quality.

Frequently Asked Questions

How do I install the required dependencies for PDF export in TradingAgents-CN?

Install pypandoc via pip (pip install pypandoc), which automatically downloads pandoc binaries if not present on your system. For enhanced PDF rendering quality, optionally install wkhtmltopdf or weasyprint. In Docker environments, the system automatically configures headless PDF generation using docker_pdf_adapter.py without manual intervention.

Can I export TradingAgents-CN reports without using the Streamlit web interface?

Yes, you can export reports programmatically by importing the report_exporter singleton from web/utils/report_exporter.py and calling export_report(results, format_type) where format_type is 'markdown', 'docx', or 'pdf'. This returns bytes that you can write directly to files or stream via HTTP responses, completely independent of the Streamlit UI.

Where are exported reports saved in the TradingAgents-CN file system?

Exported reports are saved to a structured directory path: results/<stock_symbol>/<YYYY-MM-DD>/reports/<filename>. The save_report_to_results_dir function in web/utils/report_exporter.py automatically creates these date-based subdirectories under the global results folder and returns the absolute file path for confirmation or logging purposes.

What is the difference between the Markdown, Word, and PDF export methods in TradingAgents-CN?

Markdown export generates pure text strings using Python's markdown library without external dependencies, making it the fastest and most portable option. Word (DOCX) export converts Markdown content via pypandoc to Microsoft Word format, requiring the pandoc binary. PDF export also uses pypandoc but attempts to use higher-quality engines like wkhtmltopdf or weasyprint before falling back to pandoc's default PDF generator, making it the most resource-intensive but presentation-ready format.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →