feat(reports): save the report as one HTML page as well (#1419)

- a saved report also includes complete_report.html: the report as one self-contained page with its sections listed beside the text, readable in a browser, on a phone and in print
- answering the save question at the prompt also asks about the page and offers to open it in a local browser window; --no-html and save_reports(..., html=False) skip it
- the Tauric Research logo leads the header at the top left, and a line at the foot credits TradingAgents and Tauric Research
- the page loads nothing and runs nothing (inline styles, a content-security policy); report text is rendered without raw HTML or images
- markdown-it-py is declared as a dependency
This commit is contained in:
Yijia-Xiao
2026-10-03 21:27:43 +00:00
parent d53b076b7a
commit 56a98d9df7
11 changed files with 820 additions and 93 deletions
+2
View File
@@ -212,6 +212,8 @@ tradingagents --ticker NVDA --date 2026-09-23 --analysts market,news,fundamental
```
Each flag skips only its own question. Run without a terminal, a missing answer stops the run before it starts and names the flag or variable to set.
A saved report also includes `complete_report.html`, the report as one page with its sections listed beside the text, for reading in a browser, on a phone or in print. Answering the save question at the prompt also asks about the page and can open it in your browser; `--no-html` skips it, and so does `ta.save_reports(state, "NVDA", html=False)` from Python.
### Markets and tickers
TradingAgents works with any market Yahoo Finance covers, using the exchange-suffixed ticker. Company identity and the alpha benchmark resolve automatically per market.
+5 -1
View File
@@ -60,6 +60,10 @@ def analyze(
show: bool | None = typer.Option(
None, "--show/--no-show", help="Show the full report at the end without asking"
),
html: bool | None = typer.Option(
None, "--html/--no-html",
help="Save the report as one HTML page too, complete_report.html, without asking (default: yes)",
),
):
"""Run an analysis. This is what a bare `tradingagents` does.
@@ -81,7 +85,7 @@ def analyze(
raise typer.Exit(code=1) from None
try:
flags = {"ticker": ticker, "date": date, "analysts": analysts, "save": save, "show": show}
flags = {"ticker": ticker, "date": date, "analysts": analysts, "save": save, "show": show, "html": html}
run_analysis(checkpoint=checkpoint, portfolio=portfolio_context, flags=flags)
except _NO_CONSOLE_ERRORS:
# A terminal with no console buffer cannot host the interactive prompts.
+53 -4
View File
@@ -3,6 +3,7 @@
import os
import sys
import time
import webbrowser
from functools import wraps
from pathlib import Path
@@ -384,11 +385,50 @@ def run_analysis(checkpoint: bool | None = None, portfolio=None, flags=None):
console.print(f"[dim]{analyst_wall_time_tracker.format_summary()}[/dim]")
_offer_reports(final_state, graph, selections["ticker"],
save=flags.get("save"), show=flags.get("show"))
save=flags.get("save"), show=flags.get("show"), html=flags.get("html"))
def _offer_reports(final_state, graph, ticker, save=None, show=None):
"""Save the report tree and show it; ``save``/``show`` answer the questions when given."""
def _yes(question: str) -> bool:
return typer.prompt(question, default="Y").strip().upper() in ("Y", "YES", "")
def _graphical_browser():
"""A browser that opens a page in its own window on this machine, or None.
Over SSH the page sits on the remote machine, and a terminal browser (lynx,
w3m, elinks) would take over the terminal, so neither is offered.
"""
if os.environ.get("SSH_CONNECTION") or os.environ.get("SSH_TTY"):
return None
try:
browser = webbrowser.get()
except webbrowser.Error:
return None
if type(browser) is webbrowser.GenericBrowser or isinstance(browser, webbrowser.Elinks):
return None
return browser
def _open_page(page: Path) -> None:
"""Offer to open the saved page in a browser window, and say where it is if opening fails."""
browser = _graphical_browser()
if browser is None or not _yes("Open it in your browser?"):
return
try:
opened = browser.open(page.as_uri())
except (webbrowser.Error, OSError):
opened = False
if not opened:
console.print(f" [dim]Could not open a browser; the page is at:[/dim] {page}")
def _offer_reports(final_state, graph, ticker, save=None, show=None, html=None):
"""Save the report tree and show it; ``save``/``show``/``html`` answer the questions when given.
A saved report includes the HTML page unless ``html`` is False. Someone
answering the save question at the prompt is also asked about the page and
offered to open it; a run whose flags answer the save question asks neither.
"""
asked = save is None
if asked:
save = typer.prompt("Save report?", default="Y").strip().upper() in ("Y", "YES", "")
@@ -401,12 +441,21 @@ def _offer_reports(final_state, graph, ticker, save=None, show=None):
save_path = Path(typer.prompt(
"Save path (press Enter for default)", default=str(save_path)
).strip())
if html is None:
html = _yes("Also save it as an HTML page?") if asked else True
saved = False
try:
report_file = graph.save_reports(final_state, ticker, save_path)
report_file = graph.save_reports(final_state, ticker, save_path, html=html)
saved = True
console.print(f"\n[green]✓ Report saved to:[/green] {save_path.resolve()}")
console.print(f" [dim]Complete report:[/dim] {report_file.name}")
except Exception as e:
console.print(f"[red]Error saving report: {e}[/red]")
if saved and html:
page = (save_path / "complete_report.html").resolve()
console.print(f" [dim]HTML report:[/dim] {page.name}")
if asked:
_open_page(page)
if show is None:
show = typer.prompt("\nDisplay full report on screen?", default="Y").strip().upper() in ("Y", "YES", "")
+2
View File
@@ -15,6 +15,7 @@ dependencies = [
"langchain-openai>=1.6.6",
"langgraph>=1.2.12",
"langgraph-checkpoint-sqlite>=3.1.1",
"markdown-it-py>=4.0",
"pandas>=3.0.6",
"python-dotenv>=1.0.0",
"pytz>=2025.2",
@@ -50,6 +51,7 @@ include = ["tradingagents*", "cli*"]
[tool.setuptools.package-data]
cli = ["static/*"]
tradingagents = ["assets/*.svg"]
[tool.pytest.ini_options]
testpaths = ["tests"]
+1 -1
View File
@@ -25,7 +25,7 @@ calls: list = []
@pytest.mark.unit
def test_no_arguments_still_runs_an_analysis(runner):
assert runner.invoke(m.app, []).exit_code == 0
no_flags = {"ticker": None, "date": None, "analysts": None, "save": None, "show": None}
no_flags = {"ticker": None, "date": None, "analysts": None, "save": None, "show": None, "html": None}
assert calls == [("analysis", {"checkpoint": None, "portfolio": None, "flags": no_flags})]
+147 -1
View File
@@ -87,12 +87,22 @@ def test_nothing_is_missing_when_flags_and_environment_answer_every_step(monkeyp
assert selections.unattended_gaps(FLAGS) == []
class _Browser:
def __init__(self):
self.opened = []
def open(self, url):
self.opened.append(url)
return True
@pytest.mark.unit
def test_save_and_show_answer_the_questions_after_the_run(monkeypatch, tmp_path):
def no_prompt(*a, **k):
raise AssertionError("prompted although --save/--show answered")
monkeypatch.setattr(run.typer, "prompt", no_prompt)
monkeypatch.setattr(run, "_graphical_browser", lambda: _Browser()) # even at a desktop
shown = []
monkeypatch.setattr(run, "display_complete_report", lambda state: shown.append(state))
from tradingagents.graph.trading_graph import TradingAgentsGraph
@@ -145,7 +155,7 @@ def test_the_command_passes_its_flags_to_the_run(monkeypatch):
"--analysts", "market,news", "--save", "--no-show"])
assert result.exit_code == 0, result.output
assert seen["flags"] == FLAGS
assert seen["flags"] == {**FLAGS, "html": None}
@pytest.mark.unit
@@ -220,6 +230,126 @@ def test_each_tier_provider_s_key_is_checked_before_the_run(monkeypatch):
assert checked == ["openai", "anthropic"]
def _report_graph(tmp_path):
from tradingagents.graph.trading_graph import TradingAgentsGraph
graph = object.__new__(TradingAgentsGraph)
graph.config = {"results_dir": str(tmp_path)}
graph.run_settings = lambda: {}
return graph
STATE = {"market_report": "M", "final_trade_decision": "**Rating**: Hold"}
@pytest.mark.unit
def test_a_saved_report_includes_the_html_page_unless_declined(monkeypatch, tmp_path):
monkeypatch.setattr(run, "display_complete_report", lambda state: None)
run._offer_reports(STATE, _report_graph(tmp_path / "a"), "NVDA", save=True, show=False)
run._offer_reports(STATE, _report_graph(tmp_path / "b"), "NVDA", save=True, show=False, html=False)
assert list((tmp_path / "a").glob("reports/NVDA_*/complete_report.html"))
assert list((tmp_path / "b").glob("reports/NVDA_*/complete_report.md"))
assert not list((tmp_path / "b").glob("reports/NVDA_*/complete_report.html"))
def _answer(monkeypatch, answers):
asked = []
def prompt(text, default=None, **k):
asked.append(text)
for question, answer in answers.items():
if question in text:
return default if answer is None else answer
raise AssertionError(f"unexpected question: {text}")
monkeypatch.setattr(run.typer, "prompt", prompt)
monkeypatch.setattr(run, "display_complete_report", lambda state: None)
return asked
@pytest.mark.unit
def test_an_interactive_run_asks_for_the_html_page_and_opens_it(monkeypatch, tmp_path):
asked = _answer(monkeypatch, {"Save report": "Y", "Save path": "rel/out", "HTML": "Y",
"browser": "Y", "Display full report": "N"})
browser = _Browser()
monkeypatch.setattr(run, "_graphical_browser", lambda: browser)
monkeypatch.chdir(tmp_path)
run._offer_reports(STATE, _report_graph(tmp_path), "NVDA")
page = tmp_path / "rel" / "out" / "complete_report.html"
assert page.exists() and browser.opened == [page.resolve().as_uri()]
assert [q for q in asked if "HTML" in q] and [q for q in asked if "browser" in q]
@pytest.mark.unit
def test_without_a_browser_window_the_page_is_not_offered_for_opening(monkeypatch, tmp_path):
asked = _answer(monkeypatch, {"Save report": "Y", "Save path": None, "HTML": "Y",
"Display full report": "N"})
monkeypatch.setattr(run, "_graphical_browser", lambda: None)
run._offer_reports(STATE, _report_graph(tmp_path), "NVDA")
assert not [q for q in asked if "browser" in q]
assert list(tmp_path.glob("reports/NVDA_*/complete_report.html"))
@pytest.mark.unit
def test_declining_the_html_page_saves_only_the_markdown(monkeypatch, tmp_path):
asked = _answer(monkeypatch, {"Save report": "Y", "Save path": None, "HTML": "N",
"Display full report": "N"})
monkeypatch.setattr(run, "_graphical_browser", lambda: _Browser())
run._offer_reports(STATE, _report_graph(tmp_path), "NVDA")
assert not list(tmp_path.glob("reports/NVDA_*/complete_report.html"))
assert not [q for q in asked if "browser" in q]
@pytest.mark.unit
@pytest.mark.parametrize("env, browser, offered", [
({}, "background", True),
({"SSH_CONNECTION": "10.0.0.1 22 10.0.0.2 22"}, "background", False), # the page is on the remote
({"SSH_TTY": "/dev/pts/0"}, "background", False),
({}, "terminal", False), # a text browser would take over the terminal
({}, "elinks", False),
({}, None, False), # no browser at all
])
def test_a_page_is_opened_only_in_a_browser_window_on_this_machine(monkeypatch, env, browser, offered):
import webbrowser
for name in ("SSH_CONNECTION", "SSH_TTY"):
monkeypatch.delenv(name, raising=False)
for name, value in env.items():
monkeypatch.setenv(name, value)
def get():
if browser is None:
raise webbrowser.Error("no runnable browser")
return {"background": lambda: webbrowser.BackgroundBrowser("firefox"),
"terminal": lambda: webbrowser.GenericBrowser("lynx"),
"elinks": lambda: webbrowser.Elinks("elinks")}[browser]()
monkeypatch.setattr(run.webbrowser, "get", get)
assert (run._graphical_browser() is not None) is offered
@pytest.mark.unit
@pytest.mark.parametrize("args, expected", [([], None), (["--no-html"], False), (["--html"], True)])
def test_the_html_flag_reaches_the_run(monkeypatch, args, expected):
from typer.testing import CliRunner
from cli import main as cli_main
seen = {}
monkeypatch.setattr(cli_main, "run_analysis", lambda **kw: seen.update(kw))
result = CliRunner().invoke(cli_main.app, ["--ticker", "NVDA", "--save", "--no-show", *args])
assert result.exit_code == 0 and seen["flags"]["html"] is expected
@pytest.mark.unit
def test_only_the_providers_the_tiers_use_need_a_key(monkeypatch):
"""Both tiers on a local Ollama: the main provider's key is not needed."""
@@ -231,3 +361,19 @@ def test_only_the_providers_the_tiers_use_need_a_key(monkeypatch):
selections._prompt_selections({}, FLAGS)
assert checked == ["ollama"]
@pytest.mark.unit
def test_a_page_the_browser_cannot_open_is_pointed_to(monkeypatch, tmp_path, capsys):
class Failing(_Browser):
def open(self, url):
return False
_answer(monkeypatch, {"Save report": "Y", "Save path": None, "HTML": "Y", "browser": "Y",
"Display full report": "N"})
monkeypatch.setattr(run, "_graphical_browser", lambda: Failing())
monkeypatch.setattr(run.console, "print", lambda *a, **k: print(*a))
run._offer_reports(STATE, _report_graph(tmp_path), "NVDA")
assert "complete_report.html" in capsys.readouterr().out.split("the page is at:")[-1]
+174
View File
@@ -0,0 +1,174 @@
"""An optional HTML copy of the report, for readers who do not open Markdown (#1419).
It is one self-contained file: no script, no remote asset, nothing a report's
text can inject; the Markdown report is unchanged.
"""
import re
import pytest
from tradingagents.reporting import write_report_tree
SETTINGS = {"version": "1.2.3", "llm_provider": "openai", "deep_think_llm": "gpt-6-sol",
"quick_think_llm": "gpt-6-luna", "analysts": ["market", "news"], "max_debate_rounds": 1,
"max_risk_discuss_rounds": 1, "data_vendors": {"core_stock_apis": "yfinance"}}
def _state(**overrides):
state = {"trade_date": "2026-09-26",
"market_report": "# Market view\n\nPrice | Level\n--- | ---\nClose | 181.2\n",
"news_report": "News text.",
"final_trade_decision": "**Rating**: Overweight\n\nAdd on weakness."}
state.update(overrides)
return state
def _html(tmp_path, **overrides):
write_report_tree(_state(**overrides), "NVDA", tmp_path, settings=SETTINGS, html=True)
return (tmp_path / "complete_report.html").read_text(encoding="utf-8")
@pytest.mark.unit
def test_the_html_page_is_written_unless_declined(tmp_path):
write_report_tree(_state(), "NVDA", tmp_path / "plain", settings=SETTINGS, html=False)
assert not (tmp_path / "plain" / "complete_report.html").exists()
write_report_tree(_state(), "NVDA", tmp_path / "default", settings=SETTINGS)
assert (tmp_path / "default" / "complete_report.html").exists()
page = _html(tmp_path / "html")
assert "<h1" in page and "NVDA" in page and "Overweight" in page and "2026-09-26" in page
assert '<table>' in page and "181.2" in page
@pytest.mark.unit
def test_the_markdown_report_is_the_same_with_or_without_html(tmp_path):
write_report_tree(_state(), "NVDA", tmp_path / "a", settings=SETTINGS, html=False)
write_report_tree(_state(), "NVDA", tmp_path / "b", settings=SETTINGS)
def undated(path):
return re.sub(r"- Generated: .*\n", "", path.read_text(encoding="utf-8"))
assert undated(tmp_path / "a" / "complete_report.md") == undated(tmp_path / "b" / "complete_report.md")
@pytest.mark.unit
def test_the_page_loads_nothing_and_runs_nothing(tmp_path):
page = _html(tmp_path)
assert "Content-Security-Policy" in page and "default-src 'none'" in page
assert "<script" not in page.lower()
assert not re.search(r'<(img|link|iframe|object|embed)\b', page, re.IGNORECASE)
@pytest.mark.unit
def test_report_text_cannot_inject_markup_or_fetch_anything(tmp_path):
hostile = ("<script>alert(1)</script> <img src=x onerror=alert(1)>\n\n"
"![pixel](https://tracker.example/p.png) [x](javascript:alert(1))")
page = _html(tmp_path, news_report=hostile)
assert "<script>alert" not in page and "<img" not in page.lower()
assert "tracker.example/p.png" not in re.findall(r'(?:src|href)="([^"]*)"', page)
assert 'href="javascript:' not in page
@pytest.mark.unit
def test_header_values_are_escaped(tmp_path):
write_report_tree(_state(), "<b>NV</b>", tmp_path, settings={**SETTINGS, "deep_think_llm": "<i>m</i>"}, html=True)
page = (tmp_path / "complete_report.html").read_text(encoding="utf-8")
assert "<b>NV</b>" not in page and "&lt;b&gt;NV&lt;/b&gt;" in page and "<i>m</i>" not in page
@pytest.mark.unit
def test_an_agent_s_own_headings_sit_below_its_heading(tmp_path):
page = _html(tmp_path)
assert page.count("<h1") == 1 # only the report's title
assert re.search(r"<h4[^>]*>Market view</h4>", page)
def _fields(fragment):
return re.findall(r'<span class="field">([^<]*)</span>', fragment)
@pytest.mark.unit
def test_run_details_show_each_value_as_its_own_field(tmp_path):
settings = {**SETTINGS, "deep_think_provider": "anthropic", "deep_think_llm": "claude-opus-5-5",
"data_vendors": {"core_stock_apis": "yfinance", "fundamental_data": "sec_edgar,yfinance"}}
write_report_tree(_state(), "NVDA", tmp_path, settings=settings, html=True)
page = (tmp_path / "complete_report.html").read_text(encoding="utf-8")
header = page[page.index("<header"):page.index("</header>")]
for value in ("anthropic", "claude-opus-5-5", "openai", "gpt-6-luna", "market", "news",
"sec_edgar", "yfinance"):
assert value in _fields(header)
# Vendors are named by what they serve, and a chain keeps its order.
assert "Prices" in header and "Fundamentals" in header and "fundamental_data" not in header
assert header.index(">sec_edgar<") < header.rindex(">yfinance<")
@pytest.mark.unit
def test_the_contents_name_each_section_once_and_list_its_agents_beneath(tmp_path):
page = _html(tmp_path)
nav = page[page.index('<nav class="contents"'):page.index("</nav>")]
assert "<ol" not in nav # no list numbers beside the sections' own I-V
assert re.search(r'<a href="#s1"><span class="num">I</span>\s*<span class="label">Analyst Team Reports</span></a>', nav)
assert re.search(r'<a href="#s1-1"><span class="bar"></span>\s*<span class="label">Market Analyst</span></a>', nav)
@pytest.mark.unit
def test_the_section_rail_opens_on_hover_and_keyboard_focus(tmp_path):
page = _html(tmp_path)
css = page[page.index("<style>"):page.index("</style>")]
# Wide screens: a rail centred on the left edge whose names are hidden from
# sight only (still read by screen readers) until it is pointed at or focused.
assert "top: 50%" in css and "translateY(-50%)" in css
assert ".contents:hover .label" in css and ".contents:focus-within .label" in css
assert "display: none" not in css.split(".contents .label", 1)[1].split("}", 1)[0]
@pytest.mark.unit
def test_the_sections_stay_within_reach(tmp_path):
page = _html(tmp_path)
nav = page[page.index('<nav class="contents"'):page.index("</nav>")]
assert "<h2" not in nav # the list needs no heading
assert 'id="top"' in page and 'href="#top"' in page # a way back on small screens
assert ".contents { position: fixed;" in page # beside the text on wide ones
@pytest.mark.unit
def test_the_page_heading_is_the_ticker_and_its_rating(tmp_path):
page = _html(tmp_path)
heading = re.search(r"<h1>(.*?)</h1>", page).group(1)
assert re.sub(r"<[^>]+>", "", heading).split() == ["NVDA", "Overweight"]
@pytest.mark.unit
def test_the_header_carries_the_official_logo_unaltered(tmp_path):
from importlib.resources import files
logo = files("tradingagents").joinpath("assets/tauric-logo.svg").read_text(encoding="utf-8").strip()
page = _html(tmp_path)
header = page[page.index("<header"):page.index("</header>")]
assert logo in header # drawn in the page, nothing fetched
assert 'href="https://tauric.ai"' in header and 'aria-label="Tauric Research"' in header
assert header.index('class="logo"') < header.index("<h1") # leads the header, above the title
@pytest.mark.unit
def test_the_page_credits_its_maker_in_a_line_of_text(tmp_path):
page = _html(tmp_path)
footer = page[page.index('<footer class="credit">'):page.index("</footer>")]
assert re.sub(r"<[^>]+>", "", footer).split() == ["TradingAgents", "powered", "by", "Tauric", "Research"]
# The logo already leads to tauric.ai; the credit leads to the project and the org.
assert 'href="https://github.com/TauricResearch/TradingAgents"' in footer
assert 'href="https://github.com/TauricResearch"' in footer and "tauric.ai" not in footer
assert "<svg" not in footer and 'class="brand"' in footer
assert page.index("</main>") < page.index('<footer class="credit">')
@pytest.mark.unit
def test_the_packaged_logo_stays_inert(tmp_path):
# The logo is drawn inside every report, so it may only ever hold shapes:
# no script, event handler, link, embedded document or external reference.
from importlib.resources import files
logo = files("tradingagents").joinpath("assets/tauric-logo.svg").read_text(encoding="utf-8")
tags = set(re.findall(r"<\s*([a-zA-Z][\w:-]*)", logo))
assert tags <= {"svg", "path", "rect", "circle", "g", "defs", "clipPath", "linearGradient", "stop"}
assert not re.search(r"\son\w+\s*=|href|url\(|@import|javascript:|<!entity|<!doctype", logo, re.IGNORECASE)
File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 16 KiB

+5 -4
View File
@@ -274,15 +274,16 @@ class TradingAgentsGraph:
"tool_vendors": dict(cfg.get("tool_vendors") or {}),
}
def save_reports(self, final_state, ticker, save_path=None) -> Path:
"""Write the markdown report tree for a completed run, like the CLI does.
def save_reports(self, final_state, ticker, save_path=None, html=True) -> Path:
"""Write the report tree for a completed run, like the CLI does.
Programmatic callers get the same on-disk reports the CLI produces. Pass
an explicit ``save_path`` or let it default under ``results_dir``.
an explicit ``save_path`` or let it default under ``results_dir``; the
report is also written as one HTML page unless ``html`` is False.
"""
if save_path is None:
save_path = self.default_report_path(ticker)
return write_report_tree(final_state, ticker, save_path, settings=self.run_settings())
return write_report_tree(final_state, ticker, save_path, settings=self.run_settings(), html=html)
def default_report_path(self, ticker) -> Path:
"""Where a run's reports go unless told otherwise: under results_dir, stamped now."""
+304
View File
@@ -0,0 +1,304 @@
"""The report as one self-contained HTML page (#1419).
The page reads well in a browser, on a phone and in print. It loads nothing and
runs nothing: styles are inline, there is no script, and a Content-Security-Policy
forbids any fetch. Report text is rendered as CommonMark with raw HTML and images
off, so nothing a model wrote can inject markup or load a remote asset.
"""
from datetime import datetime
from html import escape
from importlib.resources import files
from markdown_it import MarkdownIt
from tradingagents.agents.rating import run_rating
# Ratings by direction, so the page can show which way the call leans.
_TONE = {"Buy": "up", "Overweight": "up", "Hold": "level", "Underweight": "down", "Sell": "down"}
# The Tauric Research logo as published (tauric.ai/brand/tauric-logo.svg), drawn
# in the page so it loads nothing.
_LOGO = files("tradingagents").joinpath("assets/tauric-logo.svg").read_text(encoding="utf-8").strip()
_COMPANY = "https://tauric.ai"
_ORG = "https://github.com/TauricResearch"
_PROJECT = f"{_ORG}/TradingAgents"
_CSS = """
:root {
--paper: #fbfbfa; --ink: #1c2126; --muted: #5d6670; --rule: #e2e5e8; --wash: #f2f4f5;
--accent: #087a59; --up: #087a59; --down: #b4372f; --level: #5d6670; --edge: #d3d8dc; --mark: #878f97;
--serif: Charter, "Bitstream Charter", "Sitka Text", Cambria, Georgia, serif;
--sans: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
color-scheme: light dark;
}
@media (prefers-color-scheme: dark) {
:root {
--paper: #131a1f; --ink: #e4e8eb; --muted: #9aa6af; --rule: #263239; --wash: #1a242a;
--accent: #14c290; --up: #14c290; --down: #ef6f63; --level: #9aa6af; --edge: #3d4c55; --mark: #66737c;
}
}
@media (prefers-color-scheme: dark) {
.masthead .logo [stroke="#363636"] { stroke: var(--muted); }
}
* { box-sizing: border-box; }
html { -webkit-text-size-adjust: 100%; }
body {
margin: 0; background: var(--paper); color: var(--ink);
font: 17px/1.62 var(--serif); font-kerning: normal;
}
.page { max-width: 46rem; margin: 0 auto; padding: 3.5rem 1.5rem 6rem; }
main h2, main h3 { scroll-margin-top: 1rem; }
a { color: var(--accent); text-underline-offset: 0.15em; }
h1, h2, h3, h4 { text-wrap: balance; }
a:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
.masthead { padding-bottom: 1.75rem; border-bottom: 1px solid var(--rule); }
/* The logo leads at the top left, where readers look for it, 24px tall (the usual
on-screen floor for a wordmark) with at least its height clear below. */
.masthead .logo { display: block; width: fit-content; margin: 0 0 2.25rem; }
.masthead .logo svg { display: block; height: 1.5rem; width: auto; }
.masthead h1 {
margin: 0; font: 600 2.6rem/1.1 var(--sans); letter-spacing: -0.02em;
display: flex; flex-wrap: wrap; align-items: baseline; gap: 0.2em 0.5em;
}
.masthead .rating { font-weight: 500; }
.rating.up { color: var(--up); } .rating.down { color: var(--down); } .rating.level { color: var(--level); }
.rating.review { color: var(--muted); font-style: italic; }
.masthead .date { margin: 0.55rem 0 1.5rem; font: 1rem/1.4 var(--sans); color: var(--muted); }
.run { margin: 0; display: grid; grid-template-columns: max-content 1fr; gap: 0.45rem 1.25rem;
font: 0.85rem/1.5 var(--sans); }
.run > div { display: contents; }
.run dt { color: var(--muted); }
.run dd { margin: 0; overflow-wrap: anywhere; }
.run .note dd { color: var(--down); }
.field { display: inline-block; margin: 0 0.15rem 0.15rem 0; padding: 0 0.4rem; border: 1px solid var(--edge);
border-radius: 4px; background: var(--wash); font: 0.8rem/1.6 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
.run .group { display: inline-block; margin-right: 0.9rem; white-space: nowrap; }
.run .group > .name { color: var(--muted); margin-right: 0.3rem; }
.run .then { color: var(--muted); margin: 0 0.2rem; }
/* The sections: listed under the header on narrow screens. On wide ones, a
quiet rail centred on the left edge (numerals for the sections, short bars
for their agents) that opens into the full list when pointed at or focused. */
.contents { margin: 2.25rem 0 0; font: 0.9rem/1.45 var(--sans); }
.contents ul { margin: 0; padding: 0; list-style: none; }
.contents > ul > li { margin: 0 0 0.75rem; }
.contents ul ul { margin-top: 0.2rem; padding-left: 1.6rem; font-size: 0.85rem; }
.contents ul ul li { margin: 0.1rem 0; }
.contents a { display: flex; align-items: center; gap: 0.6rem; color: var(--muted); text-decoration: none; }
.contents > ul > li > a { color: var(--ink); }
.contents .num { min-width: 1.6rem; color: var(--muted); font-variant-numeric: tabular-nums; }
.contents .bar { display: none; }
.contents a:hover .label, .contents a:focus-visible .label { color: var(--accent); text-decoration: underline; }
.to-top { position: fixed; right: 1rem; bottom: calc(1rem + env(safe-area-inset-bottom));
padding: 0.25rem 0.6rem; border: 1px solid var(--edge); border-radius: 4px; background: var(--paper);
color: var(--muted); font: 0.8rem/1.4 var(--sans); text-decoration: none; }
@media (min-width: 60rem) {
.contents { position: fixed; left: 1rem; top: 50%; transform: translateY(-50%); z-index: 1;
max-height: 86vh; overflow-y: auto; overscroll-behavior: contain; margin: 0;
padding: 0.7rem 0.9rem; border: 1px solid transparent; border-radius: 6px;
transition: background-color 0.15s, border-color 0.15s, box-shadow 0.15s; }
.contents > ul > li { margin: 0 0 0.35rem; }
.contents ul ul { margin-top: 0; padding-left: 0; }
.contents ul ul li { margin: 0; }
/* Marks reach 3:1 contrast and rows 24px, the WCAG 2.2 floors for a control's
visual cue and its pointer target. */
.contents a { min-height: 1.5rem; }
.contents .num { min-width: 1.4rem; }
.contents .bar { display: block; flex: none; width: 1.25rem; height: 2px; margin-left: 0.2rem;
border-radius: 1px; background: var(--mark); }
.contents .label { max-width: 0; opacity: 0; overflow: hidden; white-space: nowrap;
transition: opacity 0.15s, max-width 0.2s; }
.contents:hover, .contents:focus-within { background: var(--paper); border-color: var(--rule);
box-shadow: 0 6px 24px rgb(0 0 0 / 0.08); }
.contents:hover .label, .contents:focus-within .label { max-width: 18rem; opacity: 1; }
.contents a:hover .bar, .contents a:focus-visible .bar { background: var(--accent); }
.to-top { display: none; }
}
@media (prefers-reduced-motion: reduce) {
.contents, .contents .label { transition: none; }
}
/* The maker's credit: one quiet line at the foot. */
.credit { margin-top: 4.5rem; padding-top: 1.25rem; border-top: 1px solid var(--rule);
color: var(--muted); font: 0.8rem/1.4 var(--sans); }
.credit a { color: inherit; text-decoration: none; }
.credit a.brand { color: var(--accent); }
.credit a:hover, .credit a:focus-visible { text-decoration: underline; }
/* Three levels of separation: the five groups, the agents within a group, and
breaks an agent draws inside its own text. */
main h2 {
margin: 4.5rem 0 0.25rem; padding-top: 1.5rem; border-top: 2px solid var(--ink);
font: 600 1.45rem/1.3 var(--sans); letter-spacing: -0.01em;
}
main section:first-child h2 { margin-top: 3rem; }
main h3 { margin: 2.75rem 0 0.75rem; padding-top: 1.1rem; border-top: 1px solid var(--rule);
font: 600 1.15rem/1.35 var(--sans); color: var(--accent); }
main h2 + h3 { margin-top: 1.25rem; padding-top: 0; border-top: 0; }
main h4, main h5, main h6 { margin: 1.75rem 0 0.5rem; font: 600 1rem/1.4 var(--sans); }
main h5, main h6 { color: var(--muted); }
main p, main ul, main ol { margin: 0 0 1rem; }
main li { margin: 0.25rem 0; }
main strong { font-weight: 650; }
main blockquote { margin: 1.25rem 0; padding: 0.1rem 0 0.1rem 1rem; border-left: 3px solid var(--rule);
color: var(--muted); }
main code { font: 0.88em/1.4 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
background: var(--wash); padding: 0.1em 0.3em; border-radius: 3px; }
main pre { background: var(--wash); padding: 0.9rem 1rem; border-radius: 4px; overflow-x: auto; }
main pre code { background: none; padding: 0; }
main hr { width: 3rem; margin: 2rem auto; border: 0; border-top: 1px solid var(--rule); }
.table { overflow-x: auto; margin: 0 0 1.25rem; }
table { border-collapse: collapse; width: 100%; font: 0.86rem/1.45 var(--sans);
font-variant-numeric: tabular-nums; }
th, td { padding: 0.45rem 0.7rem; text-align: left; vertical-align: top; border-bottom: 1px solid var(--rule); }
th { font-weight: 600; border-bottom-color: var(--muted); }
tbody tr:last-child td { border-bottom: 0; }
@media (max-width: 34rem) {
body { font-size: 16px; }
.page { padding: 2rem 1rem 3rem; }
.masthead h1 { font-size: 2rem; }
.masthead .logo svg { height: 1.25rem; }
.run { grid-template-columns: 1fr; gap: 0 0; }
.run dd { margin-bottom: 0.45rem; }
.run .group { white-space: normal; }
}
@media print {
:root { --paper: #fff; --ink: #000; --muted: #444; --rule: #bbb; --accent: #000; --wash: #f2f2f2;
--edge: #bbb; --up: #087a59; --down: #b4372f; --level: #444; }
body { font-size: 11pt; }
.table { overflow: visible; }
.page { max-width: none; padding: 0; }
.contents, .to-top { display: none; }
main h2 { break-before: page; border-top: 0; margin-top: 0; }
main section:first-child h2 { break-before: auto; }
main h3, main h4 { break-after: avoid; }
a { color: inherit; text-decoration: none; }
table { break-inside: avoid; }
}
"""
def _markdown() -> MarkdownIt:
md = MarkdownIt("commonmark", {"html": False}).enable("table").disable("image")
md.add_render_rule("table_open", lambda *a: '<div class="table"><table>\n')
md.add_render_rule("table_close", lambda *a: "</table></div>\n")
return md
def _render_agent_text(md: MarkdownIt, text: str) -> str:
"""An agent's text, its own headings placed below the agent's heading (h3)."""
tokens = md.parse(text)
for token in tokens:
if token.type in ("heading_open", "heading_close"):
token.tag = f"h{min(int(token.tag[1]) + 3, 6)}"
return md.renderer.render(tokens, md.options, {})
# What each data category serves, as a reader would name it.
_CATEGORY = {
"core_stock_apis": "Prices", "technical_indicators": "Indicators", "fundamental_data": "Fundamentals",
"news_data": "News", "macro_data": "Macro", "prediction_markets": "Prediction markets",
}
def _fields(values) -> str:
return " ".join(f'<span class="field">{escape(str(v))}</span>' for v in values)
def _chain(vendors: str) -> str:
"""A vendor chain in the order it is tried: ``a,b`` reads a, then b."""
names = [v.strip() for v in str(vendors).split(",") if v.strip()]
return ' <span class="then">\u2192</span> '.join(_fields([n]) for n in names)
def _group(name: str, values_html: str) -> str:
return f'<span class="group"><span class="name">{escape(name)}</span>{values_html}</span>'
def _run_details(final_state: dict, settings: dict | None) -> list[tuple[str, str]]:
"""The run details as (label, value HTML); every value from the run is escaped."""
details = [("Generated", escape(datetime.now().strftime("%Y-%m-%d %H:%M")))]
if settings:
s = settings.get
for tier in ("deep", "quick"):
provider = s(f"{tier}_think_provider") or s("llm_provider", "?")
details.append((f"{tier.capitalize()} model", _fields([provider, s(f"{tier}_think_llm", "?")])))
details.append(("Analysts", _fields(s("analysts") or [])))
details.append(("Debate rounds", " ".join((
_group("research", _fields([s("max_debate_rounds", "?")])),
_group("risk", _fields([s("max_risk_discuss_rounds", "?")])),
))))
vendors = {**(s("data_vendors") or {}), **(s("tool_vendors") or {})}
if vendors:
details.append(("Data vendors", " ".join(
_group(_CATEGORY.get(k, k), _chain(v)) for k, v in vendors.items()
)))
details.append(("Version", escape(f"TradingAgents {s('version', '?')}")))
if final_state.get("memory_note"):
details.append(("Memory log", escape(final_state["memory_note"])))
return details
def render_report(ticker: str, final_state: dict, settings: dict | None, parts) -> str:
"""The report page: title and rating, what produced the run, contents, sections."""
md = _markdown()
rating = run_rating(final_state) if final_state.get("final_trade_decision") else ""
tone = _TONE.get(rating, "review")
date = final_state.get("trade_date", "")
title = f'<span class="ticker">{escape(ticker)}</span>'
if rating:
title += f' <span class="rating {tone}">{escape(rating)}</span>'
details = "".join(
f'<div class="{"note" if label == "Memory log" else "detail"}">'
f"<dt>{escape(label)}</dt><dd>{value}</dd></div>"
for label, value in _run_details(final_state, settings)
)
contents, body = [], []
for n, (heading, _folder, written) in enumerate(parts, 1):
agents = "".join(
f'<li><a href="#s{n}-{m}"><span class="bar"></span> <span class="label">{escape(agent)}</span></a></li>'
for m, (agent, _f, _t) in enumerate(written, 1)
)
numeral, _, name = heading.partition(". ")
contents.append(f'<li><a href="#s{n}"><span class="num">{escape(numeral)}</span> '
f'<span class="label">{escape(name)}</span></a><ul>{agents}</ul></li>')
body.append(f'<section id="s{n}"><h2>{escape(heading)}</h2>')
for m, (agent, _filename, text) in enumerate(written, 1):
body.append(f'<h3 id="s{n}-{m}">{escape(agent)}</h3>\n{_render_agent_text(md, text)}')
body.append("</section>")
page_title = " ".join(x for x in (ticker, date, rating) if x)
return f"""<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'">
<title>{escape(page_title)}: TradingAgents report</title>
<style>{_CSS}</style>
</head>
<body>
<div class="page" id="top">
<header class="masthead">
<a class="logo" href="{_COMPANY}" rel="noopener" aria-label="Tauric Research">{_LOGO}</a>
<h1>{title}</h1>
<p class="date">{escape(f"Analysis of {date}" if date else "Analysis")}</p>
<dl class="run">{details}</dl>
</header>
<nav class="contents" aria-label="Sections"><ul>{"".join(contents)}</ul></nav>
<main>
{"".join(body)}
</main>
<footer class="credit"><a href="{_PROJECT}" rel="noopener">TradingAgents</a> powered by <a class="brand" href="{_ORG}" rel="noopener">Tauric Research</a></footer>
</div>
<a class="to-top" href="#top">Top</a>
</body>
</html>
"""
+60 -82
View File
@@ -41,97 +41,75 @@ def _header(ticker: str, final_state: dict, settings: dict | None) -> str:
return "\n".join(lines) + "\n\n"
def write_report_tree(final_state: dict, ticker: str, save_path, settings: dict | None = None) -> Path:
# The report's sections in order: (heading, folder, [(agent, file, state path)]).
_SECTIONS = (
("I. Analyst Team Reports", "1_analysts", (
("Market Analyst", "market.md", ("market_report",)),
("Sentiment Analyst", "sentiment.md", ("sentiment_report",)),
("News Analyst", "news.md", ("news_report",)),
("Fundamentals Analyst", "fundamentals.md", ("fundamentals_report",)),
)),
("II. Research Team Decision", "2_research", (
("Bull Researcher", "bull.md", ("investment_debate_state", "bull_history")),
("Bear Researcher", "bear.md", ("investment_debate_state", "bear_history")),
("Research Manager", "manager.md", ("investment_plan",)),
)),
("III. Trading Team Plan", "3_trading", (
("Trader", "trader.md", ("trader_investment_plan",)),
)),
("IV. Risk Management Team Decision", "4_risk", (
("Aggressive Analyst", "aggressive.md", ("risk_debate_state", "aggressive_history")),
("Conservative Analyst", "conservative.md", ("risk_debate_state", "conservative_history")),
("Neutral Analyst", "neutral.md", ("risk_debate_state", "neutral_history")),
)),
("V. Portfolio Manager Decision", "5_portfolio", (
("Portfolio Manager", "decision.md", ("final_trade_decision",)),
)),
)
def _report_parts(final_state: dict) -> list[tuple[str, str, list[tuple[str, str, str]]]]:
"""The sections with something to say: (heading, folder, [(agent, file, text)])."""
parts = []
for heading, folder, agents in _SECTIONS:
written = []
for agent, filename, path in agents:
value = final_state
for key in path:
value = (value or {}).get(key)
if value:
written.append((agent, filename, value))
if written:
parts.append((heading, folder, written))
return parts
def write_report_tree(final_state: dict, ticker: str, save_path, settings: dict | None = None,
html: bool = True) -> Path:
"""Save a completed run's reports to ``save_path``; return the complete-report path.
``settings`` (``TradingAgentsGraph.run_settings()``) adds what produced the run
to the report's header.
to the report's header. ``html`` also writes ``complete_report.html``, one
self-contained page of the same report (#1419).
"""
save_path = Path(save_path)
save_path.mkdir(parents=True, exist_ok=True)
parts = _report_parts(final_state)
sections = []
for heading, folder, written in parts:
(save_path / folder).mkdir(exist_ok=True)
for _agent, filename, text in written:
(save_path / folder / filename).write_text(text, encoding="utf-8")
content = "\n\n".join(f"### {agent}\n{text}" for agent, _filename, text in written)
sections.append(f"## {heading}\n\n{content}")
# 1. Analysts
analysts_dir = save_path / "1_analysts"
analyst_parts = []
if final_state.get("market_report"):
analysts_dir.mkdir(exist_ok=True)
(analysts_dir / "market.md").write_text(final_state["market_report"], encoding="utf-8")
analyst_parts.append(("Market Analyst", final_state["market_report"]))
if final_state.get("sentiment_report"):
analysts_dir.mkdir(exist_ok=True)
(analysts_dir / "sentiment.md").write_text(final_state["sentiment_report"], encoding="utf-8")
analyst_parts.append(("Sentiment Analyst", final_state["sentiment_report"]))
if final_state.get("news_report"):
analysts_dir.mkdir(exist_ok=True)
(analysts_dir / "news.md").write_text(final_state["news_report"], encoding="utf-8")
analyst_parts.append(("News Analyst", final_state["news_report"]))
if final_state.get("fundamentals_report"):
analysts_dir.mkdir(exist_ok=True)
(analysts_dir / "fundamentals.md").write_text(final_state["fundamentals_report"], encoding="utf-8")
analyst_parts.append(("Fundamentals Analyst", final_state["fundamentals_report"]))
if analyst_parts:
content = "\n\n".join(f"### {name}\n{text}" for name, text in analyst_parts)
sections.append(f"## I. Analyst Team Reports\n\n{content}")
# 2. Research
if final_state.get("investment_debate_state"):
research_dir = save_path / "2_research"
debate = final_state["investment_debate_state"]
research_parts = []
if debate.get("bull_history"):
research_dir.mkdir(exist_ok=True)
(research_dir / "bull.md").write_text(debate["bull_history"], encoding="utf-8")
research_parts.append(("Bull Researcher", debate["bull_history"]))
if debate.get("bear_history"):
research_dir.mkdir(exist_ok=True)
(research_dir / "bear.md").write_text(debate["bear_history"], encoding="utf-8")
research_parts.append(("Bear Researcher", debate["bear_history"]))
if final_state.get("investment_plan"):
research_dir.mkdir(exist_ok=True)
(research_dir / "manager.md").write_text(final_state["investment_plan"], encoding="utf-8")
research_parts.append(("Research Manager", final_state["investment_plan"]))
if research_parts:
content = "\n\n".join(f"### {name}\n{text}" for name, text in research_parts)
sections.append(f"## II. Research Team Decision\n\n{content}")
# 3. Trading
if final_state.get("trader_investment_plan"):
trading_dir = save_path / "3_trading"
trading_dir.mkdir(exist_ok=True)
(trading_dir / "trader.md").write_text(final_state["trader_investment_plan"], encoding="utf-8")
sections.append(f"## III. Trading Team Plan\n\n### Trader\n{final_state['trader_investment_plan']}")
# 4. Risk Management
if final_state.get("risk_debate_state"):
risk_dir = save_path / "4_risk"
risk = final_state["risk_debate_state"]
risk_parts = []
if risk.get("aggressive_history"):
risk_dir.mkdir(exist_ok=True)
(risk_dir / "aggressive.md").write_text(risk["aggressive_history"], encoding="utf-8")
risk_parts.append(("Aggressive Analyst", risk["aggressive_history"]))
if risk.get("conservative_history"):
risk_dir.mkdir(exist_ok=True)
(risk_dir / "conservative.md").write_text(risk["conservative_history"], encoding="utf-8")
risk_parts.append(("Conservative Analyst", risk["conservative_history"]))
if risk.get("neutral_history"):
risk_dir.mkdir(exist_ok=True)
(risk_dir / "neutral.md").write_text(risk["neutral_history"], encoding="utf-8")
risk_parts.append(("Neutral Analyst", risk["neutral_history"]))
if risk_parts:
content = "\n\n".join(f"### {name}\n{text}" for name, text in risk_parts)
sections.append(f"## IV. Risk Management Team Decision\n\n{content}")
# 5. Portfolio Manager
if final_state.get("final_trade_decision"):
portfolio_dir = save_path / "5_portfolio"
portfolio_dir.mkdir(exist_ok=True)
(portfolio_dir / "decision.md").write_text(final_state["final_trade_decision"], encoding="utf-8")
sections.append(f"## V. Portfolio Manager Decision\n\n### Portfolio Manager\n{final_state['final_trade_decision']}")
# Write consolidated report
(save_path / "complete_report.md").write_text(
_header(ticker, final_state, settings) + "\n\n".join(sections), encoding="utf-8"
)
if html:
from tradingagents.report_html import render_report
(save_path / "complete_report.html").write_text(
render_report(ticker, final_state, settings, parts), encoding="utf-8"
)
return save_path / "complete_report.md"