TradingAgents: Multi-Agents LLM Financial Trading Framework
feat(reports): save the report as one HTML page as well (#1419)
Yijia-Xiao56a98d9df7dc
diff --git a/README.md b/README.mdindex 16268c846..bbfdea404 100644--- a/README.md+++ b/README.md@@ -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 tickersTradingAgents works with any market Yahoo Finance covers, using the exchange-suffixed ticker. Company identity and the alpha benchmark resolve automatically per market.diff --git a/cli/main.py b/cli/main.pyindex 7fbb53b15..7c13acaed 100644--- a/cli/main.py+++ b/cli/main.py@@ -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 Nonetry:- 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.diff --git a/cli/run.py b/cli/run.pyindex c7ac64acd..77bf95558 100644--- a/cli/run.py+++ b/cli/run.py@@ -3,6 +3,7 @@import osimport sysimport time+import webbrowserfrom functools import wrapsfrom 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 Noneif 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 = Falsetry:- report_file = graph.save_reports(final_state, ticker, save_path)+ report_file = graph.save_reports(final_state, ticker, save_path, html=html)+ saved = Trueconsole.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", "")diff --git a/pyproject.toml b/pyproject.tomlindex 47c4269b1..5dedc530c 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -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"]diff --git a/tests/test_cli_commands.py b/tests/test_cli_commands.pyindex a0bd36a9a..37c9c2859 100644--- a/tests/test_cli_commands.py+++ b/tests/test_cli_commands.py@@ -25,7 +25,7 @@ calls: list = []@pytest.mark.unitdef 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})]diff --git a/tests/test_cli_headless.py b/tests/test_cli_headless.pyindex e08543cfb..a800ecfe3 100644--- a/tests/test_cli_headless.py+++ b/tests/test_cli_headless.py@@ -87,12 +87,22 @@ def test_nothing_is_missing_when_flags_and_environment_answer_every_step(monkeypassert selections.unattended_gaps(FLAGS) == []+class _Browser:+ def __init__(self):+ self.opened = []++ def open(self, url):+ self.opened.append(url)+ return True++@pytest.mark.unitdef 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 desktopshown = []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"}+++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+++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]+++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"))+++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]++[email protected]("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++[email protected]("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.unitdef 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"]+++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]diff --git a/tests/test_report_html.py b/tests/test_report_html.pynew file mode 100644index 000000000..d7a6dfdc7--- /dev/null+++ b/tests/test_report_html.py@@ -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")+++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+++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")+++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)+++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"+ " [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+++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 "<b>NV</b>" in page and "<i>m</i>" not in page+++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)+++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<")+++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)+++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]+++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+++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"]+++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+++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">')+++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)diff --git a/tradingagents/assets/tauric-logo.svg b/tradingagents/assets/tauric-logo.svgnew file mode 100644index 000000000..c4a48de4c--- /dev/null+++ b/tradingagents/assets/tauric-logo.svg@@ -0,0 +1,67 @@+<svg width="993" height="115" viewBox="0 0 993 115" fill="none" xmlns="http://www.w3.org/2000/svg">+<path d="M189.86 95.0459V37.9779H165.924V29.9259H223.74V37.9779H199.804V95.0459H189.86ZM251.026 46.4259C256.071 46.4259 260.178 47.0272 263.345 48.2299C266.514 49.4032 268.89 51.3686 270.474 54.1259C272.058 56.8832 272.85 60.6379 272.85 65.3899V95.0459H264.666L263.961 89.8979H263.434C261.644 91.7752 259.386 93.2419 256.657 94.2979C253.929 95.3246 251.025 95.8379 247.946 95.8379C244.426 95.8379 241.419 95.2952 238.925 94.2099C236.432 93.0952 234.54 91.5406 233.249 89.5459C231.959 87.5512 231.313 85.2046 231.313 82.5059C231.313 78.2526 232.897 74.9672 236.065 72.6499C239.263 70.3032 244.337 68.8219 251.29 68.2059L263.258 67.0179V64.7299C263.258 61.9139 262.774 59.7139 261.806 58.1299C260.838 56.5459 259.371 55.4312 257.406 54.7859C255.47 54.1406 252.888 53.8179 249.662 53.8179C247.432 53.8179 245.012 54.0086 242.401 54.3899C239.82 54.7712 237.341 55.3432 234.965 56.1059V48.8019C237.312 48.0392 239.908 47.4526 242.754 47.0419C245.628 46.6312 248.386 46.4259 251.026 46.4259ZM250.541 89.0619C252.888 89.0619 255.162 88.6512 257.362 87.8299C259.562 86.9792 261.527 85.7179 263.258 84.0459V72.8259L252.038 73.9259C248.136 74.3659 245.35 75.2166 243.678 76.4779C242.005 77.7099 241.169 79.4699 241.169 81.7579C241.169 84.0752 241.947 85.8792 243.501 87.1699C245.056 88.4312 247.403 89.0619 250.541 89.0619ZM313.339 95.8379C307.59 95.8379 303.087 94.2979 299.831 91.2179C296.575 88.1086 294.947 83.2686 294.947 76.6979V47.1739H304.715V76.1699C304.715 80.1886 305.624 83.0779 307.443 84.8379C309.291 86.5979 311.916 87.4779 315.319 87.4779C317.871 87.4779 320.379 86.9939 322.843 86.0259C325.336 85.0286 327.492 83.5766 329.311 81.6699V47.1739H339.079V95.0459H330.983L330.367 89.9419H329.883C327.624 91.8486 325.072 93.3152 322.227 94.3419C319.382 95.3392 316.419 95.8379 313.339 95.8379ZM362.371 47.1739H370.423L371.171 53.2899H371.743C373.474 51.2072 375.703 49.5792 378.431 48.4059C381.188 47.2326 384.063 46.6459 387.055 46.6459C388.756 46.6459 390.355 46.7926 391.851 47.0859V55.8419C390.414 55.5779 388.654 55.4459 386.571 55.4459C383.99 55.4459 381.364 55.9446 378.695 56.9419C376.026 57.9392 373.84 59.4206 372.139 61.3859V95.0459H362.371V47.1739ZM409.069 95.0459V47.1739H418.837V95.0459H409.069ZM413.953 37.8459C411.871 37.8459 410.287 37.3912 409.201 36.4819C408.145 35.5726 407.617 34.2672 407.617 32.5659C407.617 30.8352 408.145 29.5152 409.201 28.6059C410.287 27.6672 411.871 27.1979 413.953 27.1979C416.036 27.1979 417.605 27.6672 418.661 28.6059C419.747 29.5152 420.289 30.8352 420.289 32.5659C420.289 34.2672 419.747 35.5726 418.661 36.4819C417.605 37.3912 416.036 37.8459 413.953 37.8459ZM464.85 95.9259C456.607 95.9259 450.315 93.8432 445.974 89.6779C441.662 85.5126 439.506 79.3526 439.506 71.1979C439.506 63.0139 441.779 56.8392 446.326 52.6739C450.902 48.5086 457.575 46.4259 466.346 46.4259C470.716 46.4259 474.735 46.9246 478.402 47.9219V55.7099C476.378 55.2406 474.486 54.8886 472.726 54.6539C470.966 54.4192 469.118 54.3019 467.182 54.3019C461.168 54.3019 456.71 55.6512 453.806 58.3499C450.931 61.0486 449.494 65.2872 449.494 71.0659C449.494 76.8739 450.858 81.1566 453.586 83.9139C456.343 86.6712 460.42 88.0499 465.818 88.0499C467.695 88.0499 469.616 87.8886 471.582 87.5659C473.547 87.2139 475.82 86.6712 478.402 85.9379V93.7259C474.236 95.1926 469.719 95.9259 464.85 95.9259ZM574.428 95.0459L553.704 69.0859C553.176 69.1152 552.37 69.1299 551.284 69.1299C548.38 69.1299 544.978 68.9832 541.076 68.6899V95.0459H531.308V31.4659C537.967 29.9699 544.846 29.2219 551.944 29.2219C561.595 29.2219 568.752 30.8059 573.416 33.9739C578.08 37.1126 580.412 42.1286 580.412 49.0219C580.412 54.0086 579.004 58.0859 576.188 61.2539C573.402 64.4219 569.266 66.6366 563.78 67.8979L585.648 95.0459H574.428ZM541.076 61.2099C543.071 61.4152 544.816 61.5619 546.312 61.6499C547.838 61.7379 549.627 61.7819 551.68 61.7819C558.427 61.7819 563.34 60.7699 566.42 58.7459C569.5 56.6926 571.04 53.4952 571.04 49.1539C571.04 46.0739 570.395 43.6099 569.104 41.7619C567.843 39.9139 565.863 38.5792 563.164 37.7579C560.495 36.9366 556.975 36.5259 552.604 36.5259C550.404 36.5259 548.424 36.6139 546.664 36.7899C544.904 36.9659 543.042 37.2299 541.076 37.5819V61.2099ZM642.947 74.0139H608.231C608.407 77.4752 609.155 80.2766 610.475 82.4179C611.795 84.5299 613.775 86.0846 616.415 87.0819C619.055 88.0792 622.443 88.5779 626.579 88.5779C630.686 88.5779 635.233 87.9472 640.219 86.6859V93.9459C635.027 95.2659 630.026 95.9259 625.215 95.9259C616.298 95.9259 609.61 93.9166 605.151 89.8979C600.722 85.8499 598.507 79.6166 598.507 71.1979C598.507 65.9179 599.402 61.4299 601.191 57.7339C602.981 54.0379 605.562 51.2366 608.935 49.3299C612.338 47.3939 616.43 46.4259 621.211 46.4259C628.251 46.4259 633.634 48.5819 637.359 52.8939C641.085 57.1766 642.947 63.3659 642.947 71.4619V74.0139ZM621.079 52.8939C616.973 52.8939 613.834 54.1406 611.663 56.6339C609.493 59.0979 608.334 62.9259 608.187 68.1179H633.751C633.634 62.9259 632.519 59.0979 630.407 56.6339C628.295 54.1406 625.186 52.8939 621.079 52.8939ZM677.365 95.9259C671.352 95.9259 665.896 95.2219 660.997 93.8139V86.7299C666.248 88.1966 671.718 88.9299 677.409 88.9299C681.809 88.9299 684.977 88.3432 686.913 87.1699C688.849 85.9672 689.817 84.2219 689.817 81.9339C689.817 80.7019 689.597 79.6899 689.157 78.8979C688.717 78.0766 687.969 77.4019 686.913 76.8739C685.857 76.3166 684.405 75.8912 682.557 75.5979L674.065 74.2779C669.137 73.4859 665.573 71.9899 663.373 69.7899C661.202 67.5899 660.117 64.6419 660.117 60.9459C660.117 56.4579 661.965 52.9232 665.661 50.3419C669.386 47.7312 675.062 46.4259 682.689 46.4259C685.094 46.4259 687.485 46.5872 689.861 46.9099C692.266 47.2032 694.481 47.6432 696.505 48.2299V55.2699C692.046 54.0379 687.456 53.4219 682.733 53.4219C677.893 53.4219 674.476 54.0526 672.481 55.3139C670.486 56.5752 669.489 58.3206 669.489 60.5499C669.489 62.2219 670.002 63.5859 671.029 64.6419C672.056 65.6686 673.889 66.4166 676.529 66.8859L685.021 68.2059C689.92 68.9686 693.513 70.3766 695.801 72.4299C698.089 74.4832 699.233 77.4606 699.233 81.3619C699.233 84.3832 698.412 86.9792 696.769 89.1499C695.156 91.3206 692.706 92.9926 689.421 94.1659C686.165 95.3392 682.146 95.9259 677.365 95.9259ZM760.579 74.0139H725.863C726.039 77.4752 726.787 80.2766 728.107 82.4179C729.427 84.5299 731.407 86.0846 734.047 87.0819C736.687 88.0792 740.075 88.5779 744.211 88.5779C748.317 88.5779 752.864 87.9472 757.851 86.6859V93.9459C752.659 95.2659 747.657 95.9259 742.847 95.9259C733.929 95.9259 727.241 93.9166 722.783 89.8979C718.353 85.8499 716.139 79.6166 716.139 71.1979C716.139 65.9179 717.033 61.4299 718.823 57.7339C720.612 54.0379 723.193 51.2366 726.567 49.3299C729.969 47.3939 734.061 46.4259 738.843 46.4259C745.883 46.4259 751.265 48.5819 754.991 52.8939C758.716 57.1766 760.579 63.3659 760.579 71.4619V74.0139ZM738.711 52.8939C734.604 52.8939 731.465 54.1406 729.295 56.6339C727.124 59.0979 725.965 62.9259 725.819 68.1179H751.383C751.265 62.9259 750.151 59.0979 748.039 56.6339C745.927 54.1406 742.817 52.8939 738.711 52.8939ZM796.986 46.4259C802.032 46.4259 806.138 47.0272 809.306 48.2299C812.474 49.4032 814.85 51.3686 816.434 54.1259C818.018 56.8832 818.81 60.6379 818.81 65.3899V95.0459H810.626L809.922 89.8979H809.394C807.605 91.7752 805.346 93.2419 802.618 94.2979C799.89 95.3246 796.986 95.8379 793.906 95.8379C790.386 95.8379 787.38 95.2952 784.886 94.2099C782.393 93.0952 780.501 91.5406 779.21 89.5459C777.92 87.5512 777.274 85.2046 777.274 82.5059C777.274 78.2526 778.858 74.9672 782.026 72.6499C785.224 70.3032 790.298 68.8219 797.25 68.2059L809.218 67.0179V64.7299C809.218 61.9139 808.734 59.7139 807.766 58.1299C806.798 56.5459 805.332 55.4312 803.366 54.7859C801.43 54.1406 798.849 53.8179 795.622 53.8179C793.393 53.8179 790.973 54.0086 788.362 54.3899C785.781 54.7712 783.302 55.3432 780.926 56.1059V48.8019C783.273 48.0392 785.869 47.4526 788.714 47.0419C791.589 46.6312 794.346 46.4259 796.986 46.4259ZM796.502 89.0619C798.849 89.0619 801.122 88.6512 803.322 87.8299C805.522 86.9792 807.488 85.7179 809.218 84.0459V72.8259L797.998 73.9259C794.097 74.3659 791.31 75.2166 789.638 76.4779C787.966 77.7099 787.13 79.4699 787.13 81.7579C787.13 84.0752 787.908 85.8792 789.462 87.1699C791.017 88.4312 793.364 89.0619 796.502 89.0619ZM841.524 47.1739H849.576L850.324 53.2899H850.896C852.627 51.2072 854.856 49.5792 857.584 48.4059C860.341 47.2326 863.216 46.6459 866.208 46.6459C867.909 46.6459 869.508 46.7926 871.004 47.0859V55.8419C869.567 55.5779 867.807 55.4459 865.724 55.4459C863.143 55.4459 860.517 55.9446 857.848 56.9419C855.179 57.9392 852.993 59.4206 851.292 61.3859V95.0459H841.524V47.1739ZM909.164 95.9259C900.921 95.9259 894.629 93.8432 890.288 89.6779C885.976 85.5126 883.82 79.3526 883.82 71.1979C883.82 63.0139 886.093 56.8392 890.64 52.6739C895.216 48.5086 901.889 46.4259 910.66 46.4259C915.03 46.4259 919.049 46.9246 922.716 47.9219V55.7099C920.692 55.2406 918.8 54.8886 917.04 54.6539C915.28 54.4192 913.432 54.3019 911.496 54.3019C905.482 54.3019 901.024 55.6512 898.12 58.3499C895.245 61.0486 893.808 65.2872 893.808 71.0659C893.808 76.8739 895.172 81.1566 897.9 83.9139C900.657 86.6712 904.734 88.0499 910.132 88.0499C912.009 88.0499 913.93 87.8886 915.896 87.5659C917.861 87.2139 920.134 86.6712 922.716 85.9379V93.7259C918.55 95.1926 914.033 95.9259 909.164 95.9259ZM941.796 23.9419H951.564V52.2779H952.048C954.248 50.3712 956.756 48.9192 959.572 47.9219C962.417 46.9246 965.395 46.4259 968.504 46.4259C974.019 46.4259 978.375 47.9952 981.572 51.1339C984.769 54.2432 986.368 59.0686 986.368 65.6099V95.0459H976.6V66.0939C976.6 62.0459 975.661 59.1566 973.784 57.4259C971.936 55.6952 969.237 54.8299 965.688 54.8299C963.048 54.8299 960.481 55.3286 957.988 56.3259C955.524 57.2939 953.383 58.7312 951.564 60.6379V95.0459H941.796V23.9419Z" fill="#14C290"/>+<rect x="0.205322" y="14.873" width="10.7289" height="10.7289" rx="5.36447" fill="#14C290"/>+<rect x="43.1211" y="29.1787" width="10.7289" height="10.7289" rx="5.36447" fill="#14C290"/>+<rect y="29.1787" width="10.7289" height="10.7289" rx="5.36447" fill="#14C290"/>+<rect x="14.679" y="29.1787" width="10.7289" height="10.7289" rx="5.36447" fill="#14C290"/>+<rect x="14.679" y="44.0371" width="10.7289" height="10.7289" rx="5.36447" fill="#14C290"/>+<rect x="29.3579" y="29.1787" width="10.7289" height="10.7289" rx="5.36447" fill="#14C290"/>+<rect x="29.3579" y="44.0371" width="10.7289" height="10.7289" rx="5.36447" fill="#14C290"/>+<rect x="71.9265" y="29.1787" width="10.7289" height="10.7289" rx="5.36447" fill="#14C290"/>+<rect x="71.9265" y="44.0371" width="10.7289" height="10.7289" rx="5.36447" fill="#14C290"/>+<rect x="57.2478" y="29.1787" width="10.7289" height="10.7289" rx="5.36447" fill="#14C290"/>+<rect x="86.6055" y="29.1787" width="10.7289" height="10.7289" rx="5.36447" fill="#14C290"/>+<rect x="86.6055" y="44.0371" width="10.7289" height="10.7289" rx="5.36447" fill="#14C290"/>+<rect x="101.284" y="29.1787" width="10.7289" height="10.7289" rx="5.36447" fill="#14C290"/>+<rect x="29.3579" y="58.7158" width="10.7289" height="10.7289" rx="5.36447" fill="#14C290"/>+<rect x="71.9265" y="58.7158" width="10.7289" height="10.7289" rx="5.36447" fill="#14C290"/>+<rect x="43.1211" y="87.1592" width="10.7289" height="10.7289" rx="5.36447" fill="#14C290"/>+<rect x="57.2478" y="87.1592" width="10.7289" height="10.7289" rx="5.36447" fill="#14C290"/>+<rect x="29.3579" y="73.0205" width="10.7289" height="10.7289" rx="5.36447" fill="#14C290"/>+<rect x="71.9265" y="73.0205" width="10.7289" height="10.7289" rx="5.36447" fill="#14C290"/>+<rect x="29.3579" y="87.3262" width="10.7289" height="10.7289" rx="5.36447" fill="#14C290"/>+<rect x="71.9265" y="87.3262" width="10.7289" height="10.7289" rx="5.36447" fill="#14C290"/>+<rect x="43.1211" y="101.631" width="10.7289" height="10.7289" rx="5.36447" fill="#14C290"/>+<rect x="57.2478" y="101.631" width="10.7289" height="10.7289" rx="5.36447" fill="#14C290"/>+<rect width="10.7289" height="10.7289" rx="5.36447" fill="#14C290"/>+<rect x="101.284" width="10.7289" height="10.7289" rx="5.36447" fill="#14C290"/>+<rect x="15.0187" y="15.213" width="10.0489" height="10.0489" rx="5.02447" stroke="#363636" stroke-width="0.68"/>+<rect x="29.6979" y="15.213" width="10.0489" height="10.0489" rx="5.02447" stroke="#363636" stroke-width="0.68"/>+<rect x="43.4611" y="15.213" width="10.0489" height="10.0489" rx="5.02447" stroke="#363636" stroke-width="0.68"/>+<rect x="57.5876" y="15.213" width="10.0489" height="10.0489" rx="5.02447" stroke="#363636" stroke-width="0.68"/>+<rect x="43.4611" y="44.3771" width="10.0489" height="10.0489" rx="5.02447" stroke="#363636" stroke-width="0.68"/>+<rect x="0.34" y="44.3771" width="10.0489" height="10.0489" rx="5.02447" stroke="#363636" stroke-width="0.68"/>+<rect x="57.5876" y="44.3771" width="10.0489" height="10.0489" rx="5.02447" stroke="#363636" stroke-width="0.68"/>+<rect x="101.624" y="44.3771" width="10.0489" height="10.0489" rx="5.02447" stroke="#363636" stroke-width="0.68"/>+<rect x="43.4611" y="59.0558" width="10.0489" height="10.0489" rx="5.02447" stroke="#363636" stroke-width="0.68"/>+<rect x="57.5876" y="59.0558" width="10.0489" height="10.0489" rx="5.02447" stroke="#363636" stroke-width="0.68"/>+<rect x="0.34" y="59.0558" width="10.0489" height="10.0489" rx="5.02447" stroke="#363636" stroke-width="0.68"/>+<rect x="15.0187" y="59.0558" width="10.0489" height="10.0489" rx="5.02447" stroke="#363636" stroke-width="0.68"/>+<rect x="86.9455" y="59.0558" width="10.0489" height="10.0489" rx="5.02447" stroke="#363636" stroke-width="0.68"/>+<rect x="101.624" y="59.0558" width="10.0489" height="10.0489" rx="5.02447" stroke="#363636" stroke-width="0.68"/>+<rect x="43.4611" y="73.3605" width="10.0489" height="10.0489" rx="5.02447" stroke="#363636" stroke-width="0.68"/>+<rect x="57.5876" y="73.3605" width="10.0489" height="10.0489" rx="5.02447" stroke="#363636" stroke-width="0.68"/>+<rect x="0.34" y="73.3605" width="10.0489" height="10.0489" rx="5.02447" stroke="#363636" stroke-width="0.68"/>+<rect x="15.0187" y="73.3605" width="10.0489" height="10.0489" rx="5.02447" stroke="#363636" stroke-width="0.68"/>+<rect x="86.9455" y="73.3605" width="10.0489" height="10.0489" rx="5.02447" stroke="#363636" stroke-width="0.68"/>+<rect x="101.624" y="73.3605" width="10.0489" height="10.0489" rx="5.02447" stroke="#363636" stroke-width="0.68"/>+<rect x="0.34" y="87.6662" width="10.0489" height="10.0489" rx="5.02447" stroke="#363636" stroke-width="0.68"/>+<rect x="15.0187" y="87.6662" width="10.0489" height="10.0489" rx="5.02447" stroke="#363636" stroke-width="0.68"/>+<rect x="86.9455" y="87.6662" width="10.0489" height="10.0489" rx="5.02447" stroke="#363636" stroke-width="0.68"/>+<rect x="101.624" y="87.6662" width="10.0489" height="10.0489" rx="5.02447" stroke="#363636" stroke-width="0.68"/>+<rect x="0.34" y="101.971" width="10.0489" height="10.0489" rx="5.02447" stroke="#363636" stroke-width="0.68"/>+<rect x="15.0187" y="101.971" width="10.0489" height="10.0489" rx="5.02447" stroke="#363636" stroke-width="0.68"/>+<rect x="29.6979" y="101.971" width="10.0489" height="10.0489" rx="5.02447" stroke="#363636" stroke-width="0.68"/>+<rect x="72.2668" y="101.971" width="10.0489" height="10.0489" rx="5.02447" stroke="#363636" stroke-width="0.68"/>+<rect x="86.9455" y="101.971" width="10.0489" height="10.0489" rx="5.02447" stroke="#363636" stroke-width="0.68"/>+<rect x="101.624" y="101.971" width="10.0489" height="10.0489" rx="5.02447" stroke="#363636" stroke-width="0.68"/>+<rect x="43.4611" y="0.34" width="10.0489" height="10.0489" rx="5.02447" stroke="#363636" stroke-width="0.68"/>+<rect x="57.5876" y="0.34" width="10.0489" height="10.0489" rx="5.02447" stroke="#363636" stroke-width="0.68"/>+<rect x="15.0187" y="0.34" width="10.0489" height="10.0489" rx="5.02447" stroke="#363636" stroke-width="0.68"/>+<rect x="29.6979" y="0.34" width="10.0489" height="10.0489" rx="5.02447" stroke="#363636" stroke-width="0.68"/>+<rect x="72.2668" y="0.34" width="10.0489" height="10.0489" rx="5.02447" stroke="#363636" stroke-width="0.68"/>+<rect x="86.9455" y="0.34" width="10.0489" height="10.0489" rx="5.02447" stroke="#363636" stroke-width="0.68"/>+<rect x="72.445" y="15.213" width="10.0489" height="10.0489" rx="5.02447" stroke="#363636" stroke-width="0.68"/>+<rect x="86.7506" y="15.213" width="10.0489" height="10.0489" rx="5.02447" stroke="#363636" stroke-width="0.68"/>+<rect x="100.716" y="14.873" width="10.7289" height="10.7289" rx="5.36447" fill="#14C290"/>+</svg>diff --git a/tradingagents/graph/trading_graph.py b/tradingagents/graph/trading_graph.pyindex bdd4a64b5..3ee417aa1 100644--- a/tradingagents/graph/trading_graph.py+++ b/tradingagents/graph/trading_graph.py@@ -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."""diff --git a/tradingagents/report_html.py b/tradingagents/report_html.pynew file mode 100644index 000000000..99987b456--- /dev/null+++ b/tradingagents/report_html.py@@ -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>+"""diff --git a/tradingagents/reporting.py b/tradingagents/reporting.pyindex f1b4268ed..50a414d9f 100644--- a/tradingagents/reporting.py+++ b/tradingagents/reporting.py@@ -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"