Skip to content
 
 

Repository files navigation

arXiv Discord WeChat X Follow
Community

TradingAgents: Multi-Agents LLM Financial Trading Framework

News

  • [2026-04] TradingAgents v0.2.4 released with structured-output agents (Research Manager, Trader, Portfolio Manager), LangGraph checkpoint resume, persistent decision log, DeepSeek/Qwen/GLM/Azure provider support, Docker, and a Windows UTF-8 encoding fix. See CHANGELOG.md for the full list.
  • [2026-03] TradingAgents v0.2.3 released with multi-language support, GPT-5.4 family models, unified model catalog, backtesting date fidelity, and proxy support.
  • [2026-03] TradingAgents v0.2.2 released with GPT-5.4/Gemini 3.1/Claude 4.6 model coverage, five-tier rating scale, OpenAI Responses API, Anthropic effort control, and cross-platform stability.
  • [2026-02] TradingAgents v0.2.0 released with multi-provider LLM support (GPT-5.x, Gemini 3.x, Claude 4.x, Grok 4.x) and improved system architecture.
  • [2026-01] Trading-R1 Technical Report released, with Terminal expected to land soon.

🎉 TradingAgents officially released! We have received numerous inquiries about the work, and we would like to express our thanks for the enthusiasm in our community.

So we decided to fully open-source the framework. Looking forward to building impactful projects with you!

🚀 TradingAgents | ⚡ Installation & CLI | 🎬 Demo | 📦 Package Usage | 🤝 Contributing | 📄 Citation

TradingAgents Framework

TradingAgents is a multi-agent trading framework that mirrors the dynamics of real-world trading firms. By deploying specialized LLM-powered agents: from fundamental analysts, sentiment experts, and technical analysts, to trader, risk management team, the platform collaboratively evaluates market conditions and informs trading decisions. Moreover, these agents engage in dynamic discussions to pinpoint the optimal strategy.

TradingAgents framework is designed for research purposes. Trading performance may vary based on many factors, including the chosen backbone language models, model temperature, trading periods, the quality of data, and other non-deterministic factors. It is not intended as financial, investment, or trading advice.

Our framework decomposes complex trading tasks into specialized roles. This ensures the system achieves a robust, scalable approach to market analysis and decision-making.

Analyst Team

  • Fundamentals Analyst: Evaluates company financials and performance metrics, identifying intrinsic values and potential red flags.
  • Sentiment Analyst: Analyzes social media and public sentiment using sentiment scoring algorithms to gauge short-term market mood.
  • News Analyst: Monitors global news and macroeconomic indicators, interpreting the impact of events on market conditions.
  • Technical Analyst: Utilizes technical indicators (like MACD and RSI) to detect trading patterns and forecast price movements.

Researcher Team

  • Comprises both bullish and bearish researchers who critically assess the insights provided by the Analyst Team. Through structured debates, they balance potential gains against inherent risks.

Trader Agent

  • Composes reports from the analysts and researchers to make informed trading decisions. It determines the timing and magnitude of trades based on comprehensive market insights.

Risk Management and Portfolio Manager

  • Continuously evaluates portfolio risk by assessing market volatility, liquidity, and other risk factors. The risk management team evaluates and adjusts trading strategies, providing assessment reports to the Portfolio Manager for final decision.
  • The Portfolio Manager approves/rejects the transaction proposal. If approved, the order will be sent to the simulated exchange and executed.

Installation and CLI

Installation

Clone TradingAgents:

git clone https://github.com/TauricResearch/TradingAgents.git
cd TradingAgents

Create a virtual environment in any of your favorite environment managers:

conda create -n tradingagents python=3.13
conda activate tradingagents

Install the package and its dependencies:

pip install .

Docker

Alternatively, run with Docker:

cp .env.example .env  # add your API keys
docker compose run --rm tradingagents

For local models with Ollama:

docker compose --profile ollama run --rm tradingagents-ollama

Required APIs

TradingAgents supports multiple LLM providers. Set the API key for your chosen provider:

export OPENAI_API_KEY=...          # OpenAI (GPT)
export GOOGLE_API_KEY=...          # Google (Gemini)
export ANTHROPIC_API_KEY=...       # Anthropic (Claude)
export XAI_API_KEY=...             # xAI (Grok)
export DEEPSEEK_API_KEY=...        # DeepSeek
export DASHSCOPE_API_KEY=...       # Qwen (Alibaba DashScope)
export ZHIPU_API_KEY=...           # GLM (Zhipu)
export OPENROUTER_API_KEY=...      # OpenRouter
export ALPHA_VANTAGE_API_KEY=...   # Alpha Vantage

For enterprise providers (e.g. Azure OpenAI, AWS Bedrock), copy .env.enterprise.example to .env.enterprise and fill in your credentials.

For local models, configure Ollama with llm_provider: "ollama" in your config.

Alternatively, copy .env.example to .env and fill in your keys:

cp .env.example .env

CLI Usage

Launch the interactive CLI:

tradingagents          # installed command
python -m cli.main     # alternative: run directly from source

You will see a screen where you can select your desired tickers, analysis date, LLM provider, research depth, and more.

An interface will appear showing results as they load, letting you track the agent's progress as it runs.

Screener Pipeline (Fork Addition)

This fork adds a Finviz-driven batch screener (pipeline.py plus a thin run.sh wrapper) on top of the upstream framework. Each run pulls candidates from Finviz, dedupes against today's already-analyzed tickers, runs each through TradingAgentsGraph, and writes one Markdown report per ticker (BLUF up top + every pipeline step as its own section) plus a JSON archive.

Quick start

pip install -e .                          # one-time; pulls finvizfinance + python-dotenv on top of upstream deps

./run.sh --tickers AAPL --dry-run                # preview the queue, no LLM calls or writes
./run.sh --tickers AAPL,MSFT,NVDA                # analyze a hand-picked list
./run.sh --max-tickers 5                         # screen Finviz, analyze top 5
./run.sh --screen-only watchlist.txt             # write Finviz candidates to a file, no agents
./run.sh --ticker-file watchlist.txt             # analyze the (edited) list with no Finviz step
./run.sh --help                                  # full CLI surface

Setup pointers: see Required APIs above for LLM-provider keys (OPENAI_API_KEY, OPENROUTER_API_KEY, …) and .env placement, Optional API keys below for the screener's data extras (FRED / Finnhub / SEC), and Per-role LLM routing below for assigning different models to specific agent roles.

The --screen-only → edit → --ticker-file flow lets you split the two halves of the pipeline: pull a candidate list, hand-curate it in your editor, then run the agents on just what survives. A pre-seeded watchlist.txt lives at the repo root and is gitignored (along with any watchlist-*.txt variants), so your personal picks stay local.

Run output

Each invocation prints a banner with the run's source, output dir, LLM provider, per-role models, and resolved queue, followed by a per-ticker block with the decision and the JSON / Markdown paths the report landed at:

======================================================================
  TradingAgents pipeline — 2026-05-04
======================================================================
  Source       : --ticker-file watchlist.txt (3 candidates)
  Output dir   : .../results
  Provider     : openrouter
  Deep think   : nvidia/nemotron-3-super-120b-a12b:free
  Quick think  : openai/gpt-oss-20b:free
  Tickers      : AAPL, MSFT, NVDA
  ...
---------------------------------------------------------------------- 
  Analyzing tickers
---------------------------------------------------------------------- 
[1/3] Analyzing AAPL...
  → Decision : Buy
  → JSON     : results/by_ticker/AAPL/AAPL_20260504_090000.json
  → Markdown : results/by_ticker/AAPL/AAPL_20260504_090000.md
...
---------------------------------------------------------------------- 
  Summary
---------------------------------------------------------------------- 
  Analyzed         : 3
  Failed           : 0
  Already run today: 0
  Deferred (cap)   : 0

Background runs

Analyze invocations via run.sh (anything that isn't --help, --dry-run, or --screen-only) detach into the background by default. run.sh prints the run id, run dir, log path, and a tail -f command so you can watch progress, then returns control of the shell:

[run.sh] Run started in background (id: 2026_05_04_09_30_15)
[run.sh]   Run dir : results/by_run/2026_05_04_09_30_15
[run.sh]   Log     : results/by_run/2026_05_04_09_30_15/pipeline.log
[run.sh]   Watch   : tail -f results/by_run/2026_05_04_09_30_15/pipeline.log
[run.sh]   PID     : 12345

Kill an in-flight run with kill <PID>. Direct invocations of pipeline.py stay foregrounded — run.sh is what adds the detach.

Reports land at

results/
├── by_ticker/{TICKER}/{TICKER}_{YYYYMMDD_HHMMSS}.{json,md}        ← canonical store
└── by_run/{YYYY_MM_DD_HH_mm_ss}/
    ├── {TICKER}_{YYYYMMDD_HHMMSS}.{json,md}                       ← relative symlinks (same basename)
    └── pipeline.log                                               ← captured stdout+stderr

The run-id folder is keyed off the run's start timestamp, so multiple runs on the same day each get their own folder. The canonical JSON/MD reports always live under by_ticker/; by_run/ is just an index by run.

Each report opens with a Bottom Line Up Front block carrying a colour-coded rating indicator (✅ Buy · 🟢 Overweight · 🟨 Hold · 🟧 Underweight · ❌ Sell), then renders every pipeline step as its own section (Macro Backdrop, IV Context, 5 Analyst sections, Bull/Bear debate, Research Manager Verdict, Investment Plan, Trader Proposal, 3 Risk Debaters, Portfolio Manager Verdict). The Portfolio Manager Verdict closes with a ### Recommended Options Strategies table when an options report is available.

CLI flags

Flag Purpose
--tickers AAPL,MSFT,NVDA bypass Finviz, analyze a hand-picked list
--ticker-file path.txt read tickers from a file (one per line; # comments OK; comma-on-line OK)
--screen-only path.txt run Finviz, write candidates to path.txt (compatible with --ticker-file), then exit — no agents
--run-id ID name the results/by_run/<ID>/ folder (default: YYYY_MM_DD_HH_mm_ss timestamp); run.sh sets this when backgrounding
--max-tickers N cap the queue (overrides config.py max_tickers_per_run)
--dry-run resolve the queue and print it, then exit — no LLM calls, no writes
--rerun-today bypass the today-already-run dedup; useful for retrying a partially failed batch
--filter-overrides "Sector=Technology,Price=Over $20" patch the Finviz filter dict from the CLI
--strategies N number of options strategies the Portfolio Manager attaches to each verdict (range 0–10; 0 disables; default from options_strategies_count config, currently 3)
-v / -q DEBUG / WARNING-and-above log levels

New data sources

Beyond the upstream yfinance and Alpha Vantage tools, agents in this fork also call:

  • SEC EDGAR Form 4 (sec_insider) — insider buying/selling with cluster summary and a $500k large-purchase flag. XML parsed via defusedxml (XXE / billion-laughs hardening).
  • Congressional STOCK Act disclosures (congress_trades) — Lambda Finance primary, Finnhub secondary, Senate Stock Watcher fallback. Lambda's free tier covers House + Senate with party + state attribution. Senate Stock Watcher fetches are size-capped at 100 MB.
  • SEC financials (lambda_finance_sec) — Lambda Finance income statement + balance sheet adapter; opt in by setting tool_vendors.get_income_statement = "lambda_finance" and tool_vendors.get_balance_sheet = "lambda_finance". Default fundamental_data vendor stays yfinance.
  • Peer comparison (lambda_finance_compare) — Lambda's /api/sec/compare adapter; Fundamentals analyst calls it for single-company tickers with 2-4 sector peers.
  • ETF holdings (etf_holdings) — yfinance funds_data: sector weights, top-10 holdings, concentration metric, asset-class breakdown. Fundamentals analyst routes ETFs (SPY, QQQ, IWM, sector ETFs, ...) here instead of get_peer_comparison.
  • ETF peer comparison (etf_peer_compare) — yfinance prices + info: profile (AUM / expense ratio / yield / beta) + returns (1M/3M/YTD/1Y) + risk (1Y vol + max drawdown) across 2-6 peer ETFs.
  • Options flow (options_flow) — yfinance option chains: P/C ratios, max pain, call/put walls, IV Rank
  • Macro snapshot (macro_data) — FRED yields / curve / HY credit spread / USD with FAVORABLE / NEUTRAL / UNFAVORABLE rating
  • Earnings transcript sentiment (earnings_transcript) — Motley Fool scrape + LLM-scored sentiment with hedge-word and Q&A deflection metrics. Transcript content wrapped in <untrusted_content> tags before reaching the scorer (prompt-injection defense).
  • Sector relative strength (sector_analysis) — SPDR sector ETF vs SPY + 63-day correlations to GLD / USO / BTC-USD / UUP / ^VIX

A new Options Analyst agent is included in the analyst chain when enable_options_analyst=True (default). Risk debaters receive a macro snapshot and IV-rank snapshot pre-fetched once at run start, so the prompt-only debaters can reason about systemic context without their own tool nodes.

The Portfolio Manager attaches a ### Recommended Options Strategies table to every verdict — N concrete strategies (Bull Call Spread, Cash-Secured Put, Iron Condor, ...) with real strikes pulled from the run's options report, chosen to match the rating direction × IV regime. Configure via --strategies N (CLI, 0–10) or options_strategies_count in config.

Optional API keys

In addition to the upstream LLM-provider keys, the screener uses:

export FRED_API_KEY=...                              # https://fred.stlouisfed.org/docs/api/api_key.html
export FINNHUB_API_KEY=...                           # https://finnhub.io  (congressional trades fallback)
export LAMBDA_FINANCE_API_KEY=...                    # https://www.lambdafin.com (congressional trades primary + SEC financials)
export SEC_USER_AGENT="Your Name your@email.com"     # SEC EDGAR fair-access policy

Keep your .env file at mode 0600 (chmod 600 .env) so other local users can't read your keys — ~/.tradingagents/cache/ and ~/.tradingagents/memory/ are also owner-only by default.

Each key is optional. When a key is missing, the corresponding dataflow returns a bracketed fallback string that the agent reads as "data unavailable, proceed without it" — the run is never blocked.

Per-role LLM routing

config.py lets you assign different LLMs to specific agent roles (in addition to deep_think_llm and quick_think_llm):

Config key Used by
structured_output_llm Research Manager, Portfolio Manager
quant_llm Market analyst, Options analyst, three risk debaters
light_llm Social analyst, News analyst

Empty strings fall back to deep_think_llm / quick_think_llm. Identical model strings across roles share a single client.

Fallback chains

Each role above accepts an optional *_fallbacks list. On a recoverable upstream error (429 rate limit, 5xx, request timeout, transport drop) the wrapper retries the call against each fallback in order; non-recoverable errors (auth, schema, other 4xx) propagate immediately so the real bug surfaces. Order entries best-quality-first; a free model 429'ing on its upstream pool typically rotates through different providers if you pick fallbacks from :free models with different upstream backends.

cfg["quick_think_llm"]           = "openai/gpt-oss-20b:free"
cfg["quick_think_llm_fallbacks"] = [
    "meta-llama/llama-3.3-70b-instruct:free",   # different upstream
    "deepseek/deepseek-chat-v3.1:free",         # different upstream
    ("openai", "gpt-5-mini"),                   # cross-provider fallback (paid)
]

OpenRouter periodically delists free models (e.g. google/gemini-2.0-flash-exp:free was dropped in May 2026). FallbackChatModel treats 404 NotFoundError as recoverable so a single delisted entry in the chain rotates to the next model instead of crashing the run — but you should still update the config when you notice the WARNING in pipeline.log.

Same pattern for deep_think_llm_fallbacks, structured_output_llm_fallbacks, quant_llm_fallbacks, light_llm_fallbacks. Plain strings use the run's llm_provider; (provider, model) tuples (or {"provider": ..., "model": ...} dicts) cross providers, which is how a free OpenRouter primary can fall back to a paid OpenAI key from your .env. Empty list (the default) disables fallback for that role.

Free-tier OpenRouter caveat: free models route through shared upstream providers with aggressive RPM caps. If a free model 429s persistently, configure *_fallbacks (above) so the run survives one upstream stalling, or BYOK at openrouter.ai/settings/integrations so requests hit your own quota pool.

See CLAUDE.md for the deeper architecture: data flow, vendor router, role-LLM construction, persistence layout, and repo-specific coding conventions.

TradingAgents Package

Implementation Details

We built TradingAgents with LangGraph to ensure flexibility and modularity. The framework supports multiple LLM providers: OpenAI, Google, Anthropic, xAI, DeepSeek, Qwen (Alibaba DashScope), GLM (Zhipu), OpenRouter, Ollama for local models, and Azure OpenAI for enterprise.

Python Usage

To use TradingAgents inside your code, you can import the tradingagents module and initialize a TradingAgentsGraph() object. The .propagate() function will return a decision. You can run main.py, here's also a quick example:

from tradingagents.graph.trading_graph import TradingAgentsGraph
from tradingagents.default_config import DEFAULT_CONFIG

ta = TradingAgentsGraph(debug=True, config=DEFAULT_CONFIG.copy())

# forward propagate
_, decision = ta.propagate("NVDA", "2026-01-15")
print(decision)

You can also adjust the default configuration to set your own choice of LLMs, debate rounds, etc.

from tradingagents.graph.trading_graph import TradingAgentsGraph
from tradingagents.default_config import DEFAULT_CONFIG

config = DEFAULT_CONFIG.copy()
config["llm_provider"] = "openai"        # openai, google, anthropic, xai, deepseek, qwen, glm, openrouter, ollama, azure
config["deep_think_llm"] = "gpt-5.4"     # Model for complex reasoning
config["quick_think_llm"] = "gpt-5.4-mini" # Model for quick tasks
config["max_debate_rounds"] = 2

ta = TradingAgentsGraph(debug=True, config=config)
_, decision = ta.propagate("NVDA", "2026-01-15")
print(decision)

See tradingagents/default_config.py for all configuration options.

Persistence and Recovery

TradingAgents persists two kinds of state across runs.

Decision log

The decision log is always on. Each completed run appends its decision to ~/.tradingagents/memory/trading_memory.md. On the next run for the same ticker, TradingAgents fetches the realised return (raw and alpha vs SPY), generates a one-paragraph reflection, and injects the most recent same-ticker decisions plus recent cross-ticker lessons into the Portfolio Manager prompt, so each analysis carries forward what worked and what didn't.

Override the path with TRADINGAGENTS_MEMORY_LOG_PATH.

Checkpoint resume

Checkpoint resume is opt-in via --checkpoint. When enabled, LangGraph saves state after each node so a crashed or interrupted run resumes from the last successful step instead of starting over. On a resume run you will see Resuming from step N for <TICKER> on <date> in the logs; on a new run you will see Starting fresh. Checkpoints are cleared automatically on successful completion.

Per-ticker SQLite databases live at ~/.tradingagents/cache/checkpoints/<TICKER>.db (override the base with TRADINGAGENTS_CACHE_DIR). Use --clear-checkpoints to reset all of them before a run.

tradingagents analyze --checkpoint           # enable for this run
tradingagents analyze --clear-checkpoints    # reset before running
config = DEFAULT_CONFIG.copy()
config["checkpoint_enabled"] = True
ta = TradingAgentsGraph(config=config)
_, decision = ta.propagate("NVDA", "2026-01-15")

Contributing

We welcome contributions from the community! Whether it's fixing a bug, improving documentation, or suggesting a new feature, your input helps make this project better. If you are interested in this line of research, please consider joining our open-source financial AI research community Tauric Research.

Past contributions, including code, design feedback, and bug reports, are credited per release in CHANGELOG.md.

Citation

Please reference our work if you find TradingAgents provides you with some help :)

@misc{xiao2025tradingagentsmultiagentsllmfinancial,
      title={TradingAgents: Multi-Agents LLM Financial Trading Framework}, 
      author={Yijia Xiao and Edward Sun and Di Luo and Wei Wang},
      year={2025},
      eprint={2412.20138},
      archivePrefix={arXiv},
      primaryClass={q-fin.TR},
      url={https://arxiv.org/abs/2412.20138}, 
}

About

TradingAgentsStock: Multi-Agents LLM Financial Trading Framework for Picking Stocks

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages