#!/usr/bin/env python3 """ta-daily: run TradingAgents for every ticker on a watchlist, then report. From https://exe.dev/deploy/tradingagents. For each ticker in ~/tradingagents-data/watchlist.txt it runs the official Docker Compose service, saves the report, rebuilds the report index (logs/index.html) that tradingagents-web serves, and sends one summary: by email to you (exe.dev's send-email), and to Telegram if the telegram integration is attached and TA_TELEGRAM_CHAT_ID is set. ta-daily today's date in New York ta-daily 2026-11-18 a given analysis date ta-daily --index only rebuild the report index Settings (environment, e.g. in the systemd unit): TA_ANALYSTS default market,sentiment,news,fundamentals TA_EMAIL where to send the summary; default: the VM's owner; "off" sends no email TA_TELEGRAM_CHAT_ID a chat the bot may post to; unset: no Telegram """ import base64, datetime, html, json, os, re, subprocess, sys, urllib.request from zoneinfo import ZoneInfo HOME = os.path.expanduser("~") APP = os.path.join(HOME, "TradingAgents") DATA = os.path.join(HOME, "tradingagents-data") LOGS = os.path.join(DATA, "logs") WATCHLIST = os.path.join(DATA, "watchlist.txt") SITE = f"https://{os.uname().nodename}.exe.xyz" ANALYSTS = os.environ.get("TA_ANALYSTS", "market,sentiment,news,fundamentals") MAX_ATTACH = 2_000_000 # bytes of HTML reports to attach to the email def post(url, payload, timeout=30): req = urllib.request.Request(url, data=json.dumps(payload).encode(), headers={"Content-Type": "application/json"}) with urllib.request.urlopen(req, timeout=timeout) as r: return r.read().decode() def header(report_dir): """Ticker, analysis date and rating from the top of a saved complete_report.md.""" info = {} try: with open(os.path.join(report_dir, "complete_report.md"), encoding="utf-8") as f: for line in f.readlines()[:12]: m = re.match(r"# Trading Analysis Report: (.+)|- (Analysis date|Rating): (.+)", line) if m: info["ticker" if m.group(1) else m.group(2)] = (m.group(1) or m.group(3)).strip() except OSError: pass return info def saved_reports(): d = os.path.join(LOGS, "reports") return set(os.listdir(d)) if os.path.isdir(d) else set() def build_index(): rows = [] for name in saved_reports(): h = header(os.path.join(LOGS, "reports", name)) if h: rows.append((h.get("Analysis date", "?"), name, h.get("ticker", name), h.get("Rating", "?"))) # Newest first: by analysis date, then by when it ran (the name ends in YYYYMMDD_HHMMSS). rows.sort(key=lambda r: (r[0], r[1][-15:]), reverse=True) out = ["", "", "TradingAgents reports", "", "

TradingAgents reports

", "

Research output from language models. Not investment advice.

", "
DateTickerRatingFiles"] for date, name, ticker, r in rows: base = f"reports/{html.escape(name)}" out.append(f"
{html.escape(date)}" f"{html.escape(ticker)}{html.escape(r)}sections") out.append("
") os.makedirs(LOGS, exist_ok=True) tmp = os.path.join(LOGS, ".index.html.tmp") with open(tmp, "w", encoding="utf-8") as f: f.write("\n".join(out) + "\n") os.replace(tmp, os.path.join(LOGS, "index.html")) def owner_email(): try: with urllib.request.urlopen("https://reflection.int.exe.xyz/email", timeout=10) as r: return json.load(r).get("email") or "" except Exception as e: print(f"ta-daily: no owner email from the reflection integration: {e}", file=sys.stderr) return "" def main(): if sys.argv[1:] == ["--index"]: build_index() return 0 date = sys.argv[1] if len(sys.argv) > 1 else \ datetime.datetime.now(ZoneInfo("America/New_York")).strftime("%Y-%m-%d") with open(WATCHLIST, encoding="utf-8") as f: tickers = [l.split("#")[0].strip() for l in f if l.split("#")[0].strip()] os.makedirs(os.path.join(LOGS, "ta-daily"), exist_ok=True) results, failed = [], 0 for t in tickers: print(f"ta-daily: {t} {date}", flush=True) before = saved_reports() with open(os.path.join(LOGS, "ta-daily", f"{date}_{t}.log"), "w") as log: rc = subprocess.call( ["docker", "compose", "run", "--rm", "-T", "tradingagents", "--ticker", t, "--date", date, "--analysts", ANALYSTS, "--save", "--no-show"], cwd=APP, stdout=log, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL) new = sorted(saved_reports() - before) name = new[-1] if new else "" r = header(os.path.join(LOGS, "reports", name)).get("Rating", "no rating") if name else "" if rc != 0 or not name: r = f"failed (exit {rc}), see logs/ta-daily/{date}_{t}.log" failed += 1 print(f"ta-daily: {t} {r}", flush=True) results.append((t, r, name)) build_index() lines = [f"TradingAgents, analysis date {date}", ""] lines += [f"{t}: {r}" + (f"\n {SITE}/reports/{n}/complete_report.html" if n else "") for t, r, n in results] lines += ["", f"All reports: {SITE}/", "Research output from language models. Not investment advice."] body = "\n".join(lines) subject = f"TradingAgents {date}: " + ", ".join(f"{t} {r}" for t, r, _ in results) to = os.environ.get("TA_EMAIL") or owner_email() if to and to != "off": attachments, size = [], 0 for t, _, name in results: path = os.path.join(LOGS, "reports", name, "complete_report.html") if name and os.path.exists(path) and size + os.path.getsize(path) <= MAX_ATTACH: size += os.path.getsize(path) with open(path, "rb") as f: attachments.append({"filename": f"{t}-{date}.html", "content_type": "text/html", "content": base64.b64encode(f.read()).decode()}) try: post("http://169.254.169.254/gateway/email/send", {"to": to, "subject": subject[:200], "body": body, "attachments": attachments}) print(f"ta-daily: emailed {to}") except Exception as e: print(f"ta-daily: email failed: {e}", file=sys.stderr) failed += 1 chat = os.environ.get("TA_TELEGRAM_CHAT_ID") if chat: try: post("https://telegram.int.exe.xyz/sendMessage", {"chat_id": chat, "text": body, "disable_web_page_preview": True}) print("ta-daily: sent to Telegram") except Exception as e: print(f"ta-daily: Telegram failed: {e}", file=sys.stderr) failed += 1 return 1 if failed else 0 if __name__ == "__main__": sys.exit(main())