Go to file
Ahmet Guzererler eafdce3121 fix: harden dataflows layer against silent failures and data corruption
## Problem (Incident Post-mortem)

The pipeline was emitting hundreds of errors:
  'Invalid number of return arguments after parsing column name: Date'

Root cause: after _clean_dataframe() lowercases all columns, stockstats.wrap()
promotes 'date' to the DataFrame index. Subsequent df['Date'] access caused
stockstats to try parsing 'Date' as a technical indicator name.

## Fixes

### 1. Fix df['Date'] stockstats bug (already shipped in prior commit)
- stockstats_utils.py + y_finance.py: use df.index.strftime() instead of
  df['Date'] after wrap()

### 2. Extract _load_or_fetch_ohlcv() — single OHLCV authority
- Eliminates duplicated 30-line download+cache boilerplate in two places
- Cache filename is always derived from today's date — hardcoded stale date
  '2015-01-01-2025-03-25' in local mode is gone
- Corruption/truncation detection: files <50 rows or unparseable are deleted
  and re-fetched rather than silently returning bad data
- Drops on_bad_lines='skip' — malformed CSVs now raise instead of silently
  dropping rows that would distort indicator calculations

### 3. YFinanceError typed exception
- Defined in stockstats_utils.py; raised instead of print()+return ''
- get_stockstats_indicator now raises YFinanceError on failure so errors
  surface to callers rather than delivering empty strings to LLM agents
- interface.py route_to_vendor now catches YFinanceError alongside
  AlphaVantageError and FinnhubError — failures appear in observability
  telemetry and can trigger vendor fallback

### 4. Explicit date column discovery in alpha_vantage_common
- _filter_csv_by_date_range: replaced df.columns[0] positional assumption
  with explicit search for 'time'/'timestamp'/'date' column
- ValueError re-raised (not swallowed) so bad API response shape is visible

### 5. Structured logging
- Replaced all print() calls in changed files with logging.getLogger()
- Added logging import + logger to alpha_vantage_common

## Tests
- tests/unit/test_incident_fixes.py: 12 new unit tests covering all fixes
  (dynamic cache filename, corruption re-fetch, YFinanceError propagation,
  explicit column lookup, empty download raises)
- tests/integration/test_stockstats_live.py: 11 live tests against real
  yfinance API (all major indicators, weekend N/A, regression guard)
- All 70 tests pass (59 unit + 11 live integration)
2026-03-22 00:07:32 +01:00
.claude removed hooks 2026-03-20 12:58:21 +01:00
assets chore(release): v0.1.0 – initial public release of TradingAgents 2025-06-05 04:27:57 -07:00
cli Merge pull request #84 from aguzererler/copilot/standardize-env-variables 2026-03-21 23:46:35 +01:00
docs Merge pull request #69 from aguzererler/copilot/review-financial-tools-implementation 2026-03-21 22:41:55 +01:00
tests fix: harden dataflows layer against silent failures and data corruption 2026-03-22 00:07:32 +01:00
tradingagents fix: harden dataflows layer against silent failures and data corruption 2026-03-22 00:07:32 +01:00
.DS_Store skills 2026-03-19 10:32:29 +01:00
.env.example refactor: centralize env loading in default_config.py; fix .env.example 2026-03-21 22:33:06 +00:00
.gitignore skills 2026-03-19 10:32:29 +01:00
CLAUDE.md feat: add agentic memory scaffold and migrate tracking files to docs/agent/ 2026-03-17 17:14:11 +01:00
LICENSE chore(release): v0.1.0 – initial public release of TradingAgents 2025-06-05 04:27:57 -07:00
PLAN.md feat: medium-term positioning upgrade (debate rounds, TTM, peer comparison, macro regime) (#14) 2026-03-17 22:27:40 +01:00
README.md Update portfolio flow diagram, add token estimation per model, add CLI/test commands to README 2026-03-21 02:34:23 +00:00
benchmark.py Optimize DataFrame column lowercasing in stockstats_utils.py 2026-03-21 21:47:43 +00:00
benchmark_append.py Optimize DataFrame column lowercasing in stockstats_utils.py 2026-03-21 21:47:43 +00:00
benchmark_csv.py Optimize DataFrame column lowercasing in stockstats_utils.py 2026-03-21 21:47:43 +00:00
benchmark_engine.py Optimize DataFrame column lowercasing in stockstats_utils.py 2026-03-21 21:47:43 +00:00
benchmark_full.py Optimize DataFrame column lowercasing in stockstats_utils.py 2026-03-21 21:47:43 +00:00
benchmark_iteration.py Optimize DataFrame column lowercasing in stockstats_utils.py 2026-03-21 21:47:43 +00:00
benchmark_list.py Optimize DataFrame column lowercasing in stockstats_utils.py 2026-03-21 21:47:43 +00:00
benchmark_v2.py Optimize DataFrame column lowercasing in stockstats_utils.py 2026-03-21 21:47:43 +00:00
benchmark_v3.py Optimize DataFrame column lowercasing in stockstats_utils.py 2026-03-21 21:47:43 +00:00
benchmark_v4.py Optimize DataFrame column lowercasing in stockstats_utils.py 2026-03-21 21:47:43 +00:00
benchmark_v5.py Optimize DataFrame column lowercasing in stockstats_utils.py 2026-03-21 21:47:43 +00:00
main.py fix: allow .env variables to override DEFAULT_CONFIG values 2026-03-21 23:26:37 +01:00
parse_again.py Optimize DataFrame column lowercasing in stockstats_utils.py 2026-03-21 21:47:43 +00:00
parse_issue.py Optimize DataFrame column lowercasing in stockstats_utils.py 2026-03-21 21:47:43 +00:00
pyproject.toml feat(portfolio): integrate portfolio manager into cli, add pm command 2026-03-21 03:10:06 +01:00
requirements.txt Sync fork with upstream TauricResearch/TradingAgents (v0.2.1) (#12) 2026-03-18 07:00:37 +01:00
run_benchmark_6.py Optimize DataFrame column lowercasing in stockstats_utils.py 2026-03-21 21:47:43 +00:00
run_test.py Optimize DataFrame column lowercasing in stockstats_utils.py 2026-03-21 21:47:43 +00:00
test.py Optimize DataFrame column lowercasing in stockstats_utils.py 2026-03-21 21:47:43 +00:00
test2.py Optimize DataFrame column lowercasing in stockstats_utils.py 2026-03-21 21:47:43 +00:00
test_cache.csv Optimize DataFrame column lowercasing in stockstats_utils.py 2026-03-21 21:47:43 +00:00
test_df.py Optimize DataFrame column lowercasing in stockstats_utils.py 2026-03-21 21:47:43 +00:00
test_opt.py Optimize DataFrame column lowercasing in stockstats_utils.py 2026-03-21 21:47:43 +00:00
test_pd.py Optimize DataFrame column lowercasing in stockstats_utils.py 2026-03-21 21:47:43 +00:00
test_pyarrow.py Optimize DataFrame column lowercasing in stockstats_utils.py 2026-03-21 21:47:43 +00:00
uv.lock feat(portfolio): integrate portfolio manager into cli, add pm command 2026-03-21 03:10:06 +01:00

README.md

arXiv Discord WeChat X Follow
Community

TradingAgents: Multi-Agents LLM Financial Trading Framework

News

  • [2026-03] TradingAgents v0.2.1 released with GPT-5.4, Gemini 3.1, Claude 4.6 model coverage and improved system 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 dependencies:

pip install -r requirements.txt

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 OPENROUTER_API_KEY=...      # OpenRouter
export ALPHA_VANTAGE_API_KEY=...   # Alpha Vantage

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

You can also try out the CLI directly by running:

python -m cli.main

You will see a screen where you can select your desired tickers, date, LLMs, research depth, etc.

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

CLI Commands

Command Description
analyze Interactive per-ticker multi-agent analysis (select analysts, LLM, date)
scan Run the 3-phase macro scanner (geopolitical → sector → synthesis)
pipeline Full pipeline: macro scan JSON → filter by conviction → per-ticker deep dive
portfolio Run the Portfolio Manager workflow (requires portfolio ID + scan JSON)
check-portfolio Review current holdings only — no new candidates
auto End-to-end: scan → pipeline → portfolio manager (one command)

Examples:

# Per-ticker analysis (interactive prompts for ticker, date, LLM, analysts)
python -m cli.main analyze

# Run macro scanner for a specific date
python -m cli.main scan --date 2026-03-21

# Run the full pipeline (scan → filter → per-ticker analysis)
python -m cli.main pipeline

# Run portfolio manager with a specific portfolio and scan results
python -m cli.main portfolio

# Review current holdings without new candidates
python -m cli.main check-portfolio --portfolio-id main_portfolio --date 2026-03-21

# Full autonomous mode: scan → pipeline → portfolio
python -m cli.main auto --portfolio-id main_portfolio --date 2026-03-21

Running Tests

# Install dev dependencies
pip install -e ".[dev]"

# Run all unit tests (integration and e2e excluded by default)
python -m pytest tests/ -v

# Run only portfolio tests
python -m pytest tests/portfolio/ -v

# Run a specific test file
python -m pytest tests/portfolio/test_models.py -v

# Run tests with coverage (requires pytest-cov)
python -m pytest tests/ --cov=tradingagents --cov-report=term-missing

Note: Integration tests that require network access or database connections auto-skip when the relevant environment variables (SUPABASE_CONNECTION_STRING, FINNHUB_API_KEY, etc.) are not set.

TradingAgents Package

Implementation Details

We built TradingAgents with LangGraph to ensure flexibility and modularity. The framework supports multiple LLM providers: OpenAI, Google, Anthropic, xAI, OpenRouter, and Ollama.

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, openrouter, ollama
config["deep_think_llm"] = "gpt-5.2"     # Model for complex reasoning
config["quick_think_llm"] = "gpt-5-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.

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.

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}, 
}