From 141a1c64dcdd50beaea1007d08dcb07fea3f53ca Mon Sep 17 00:00:00 2001 From: Filipe Salvio Date: Sun, 29 Mar 2026 19:34:39 -0300 Subject: [PATCH] docs: create roadmap (10 phases) --- .planning/REQUIREMENTS.md | 90 +++++++------- .planning/ROADMAP.md | 160 ++++++++++++++++++++++++ .planning/STATE.md | 64 ++++++++++ CLAUDE.md | 253 ++++++++++++++++++++++++++++++++++++++ 4 files changed, 522 insertions(+), 45 deletions(-) create mode 100644 .planning/ROADMAP.md create mode 100644 .planning/STATE.md create mode 100644 CLAUDE.md diff --git a/.planning/REQUIREMENTS.md b/.planning/REQUIREMENTS.md index 28887576..48a2c337 100644 --- a/.planning/REQUIREMENTS.md +++ b/.planning/REQUIREMENTS.md @@ -104,54 +104,54 @@ Which phases cover which requirements. Updated during roadmap creation. | Requirement | Phase | Status | |-------------|-------|--------| -| DATA-01 | TBD | Pending | -| DATA-02 | TBD | Pending | -| DATA-03 | TBD | Pending | -| DATA-04 | TBD | Pending | -| DATA-05 | TBD | Pending | -| DATA-06 | TBD | Pending | -| DATA-07 | TBD | Pending | -| DATA-08 | TBD | Pending | -| VOL-01 | TBD | Pending | -| VOL-02 | TBD | Pending | -| VOL-03 | TBD | Pending | -| VOL-04 | TBD | Pending | -| VOL-05 | TBD | Pending | -| VOL-06 | TBD | Pending | -| VOL-07 | TBD | Pending | -| GEX-01 | TBD | Pending | -| GEX-02 | TBD | Pending | -| GEX-03 | TBD | Pending | -| GEX-04 | TBD | Pending | -| FLOW-01 | TBD | Pending | -| FLOW-02 | TBD | Pending | -| STRAT-01 | TBD | Pending | -| STRAT-02 | TBD | Pending | -| STRAT-03 | TBD | Pending | -| STRAT-04 | TBD | Pending | -| STRAT-05 | TBD | Pending | -| STRAT-06 | TBD | Pending | -| AGENT-01 | TBD | Pending | -| AGENT-02 | TBD | Pending | -| AGENT-03 | TBD | Pending | -| AGENT-04 | TBD | Pending | -| AGENT-05 | TBD | Pending | -| AGENT-06 | TBD | Pending | -| AGENT-07 | TBD | Pending | -| AGENT-08 | TBD | Pending | -| AGENT-09 | TBD | Pending | -| AGENT-10 | TBD | Pending | -| INT-01 | TBD | Pending | -| INT-02 | TBD | Pending | -| INT-03 | TBD | Pending | -| INT-04 | TBD | Pending | -| INT-05 | TBD | Pending | +| DATA-01 | Phase 1 | Pending | +| DATA-02 | Phase 1 | Pending | +| DATA-03 | Phase 1 | Pending | +| DATA-04 | Phase 1 | Pending | +| DATA-05 | Phase 1 | Pending | +| DATA-06 | Phase 2 | Pending | +| DATA-07 | Phase 10 | Pending | +| DATA-08 | Phase 1 | Pending | +| VOL-01 | Phase 3 | Pending | +| VOL-02 | Phase 3 | Pending | +| VOL-03 | Phase 6 | Pending | +| VOL-04 | Phase 5 | Pending | +| VOL-05 | Phase 7 | Pending | +| VOL-06 | Phase 7 | Pending | +| VOL-07 | Phase 3 | Pending | +| GEX-01 | Phase 4 | Pending | +| GEX-02 | Phase 4 | Pending | +| GEX-03 | Phase 4 | Pending | +| GEX-04 | Phase 4 | Pending | +| FLOW-01 | Phase 4 | Pending | +| FLOW-02 | Phase 4 | Pending | +| STRAT-01 | Phase 6 | Pending | +| STRAT-02 | Phase 6 | Pending | +| STRAT-03 | Phase 6 | Pending | +| STRAT-04 | Phase 6 | Pending | +| STRAT-05 | Phase 6 | Pending | +| STRAT-06 | Phase 6 | Pending | +| AGENT-01 | Phase 8 | Pending | +| AGENT-02 | Phase 8 | Pending | +| AGENT-03 | Phase 8 | Pending | +| AGENT-04 | Phase 8 | Pending | +| AGENT-05 | Phase 8 | Pending | +| AGENT-06 | Phase 8 | Pending | +| AGENT-07 | Phase 9 | Pending | +| AGENT-08 | Phase 9 | Pending | +| AGENT-09 | Phase 8 | Pending | +| AGENT-10 | Phase 8 | Pending | +| INT-01 | Phase 9 | Pending | +| INT-02 | Phase 9 | Pending | +| INT-03 | Phase 9 | Pending | +| INT-04 | Phase 9 | Pending | +| INT-05 | Phase 2 | Pending | **Coverage:** - v1 requirements: 42 total -- Mapped to phases: 0 -- Unmapped: 42 ⚠️ +- Mapped to phases: 42 +- Unmapped: 0 --- *Requirements defined: 2026-03-29* -*Last updated: 2026-03-29 after initial definition* +*Last updated: 2026-03-29 after roadmap creation* diff --git a/.planning/ROADMAP.md b/.planning/ROADMAP.md new file mode 100644 index 00000000..3a0bcbc6 --- /dev/null +++ b/.planning/ROADMAP.md @@ -0,0 +1,160 @@ +# Roadmap: TradingAgents Options Module + +## Overview + +This roadmap delivers a parallel options analysis team for TradingAgents, building from data foundation through computation modules, agent wrappers, and full pipeline integration. The build order follows a strict dependency chain: raw data first (Tradier), then deterministic math modules (Greeks, GEX, volatility, strategies), then LLM agent wrappers that interpret pre-computed signals, then debate/synthesis and pipeline integration. Tastyworks streaming is a final enhancement after the batch pipeline proves correct. + +## Phases + +**Phase Numbering:** +- Integer phases (1, 2, 3): Planned milestone work +- Decimal phases (2.1, 2.2): Urgent insertions (marked with INSERTED) + +Decimal phases appear between their surrounding integers in numeric order. + +- [ ] **Phase 1: Tradier Data Layer** - Options chain retrieval, 1st-order Greeks, IV, and vendor routing integration +- [ ] **Phase 2: Deterministic Math Core** - Pure Python module for 2nd-order Greeks and all non-LLM computation +- [ ] **Phase 3: Volatility Metrics** - IV Rank, IV Percentile, and Volatility Risk Premium calculations +- [ ] **Phase 4: GEX & Market Microstructure** - Gamma exposure, dealer positioning, walls, flow detection +- [ ] **Phase 5: Volatility Surface** - SVI parametric fitting across strikes and expirations +- [ ] **Phase 6: Strategy Construction** - Multi-leg strategy building, P/L profiles, PoP estimation +- [ ] **Phase 7: TastyTrade Rules Engine** - IVR-based strategy selection and position management rules +- [ ] **Phase 8: Options Agent Team** - LLM agent factories for all options analyst roles +- [ ] **Phase 9: Debate, Scoring & Pipeline Integration** - Options debate, portfolio manager, composite score, LangGraph integration, CLI +- [ ] **Phase 10: Tastyworks Streaming** - Real-time Greeks and quotes via DXLink WebSocket + +## Phase Details + +### Phase 1: Tradier Data Layer +**Goal**: System can retrieve and display complete options chain data with Greeks and IV for any ticker +**Depends on**: Nothing (first phase) +**Requirements**: DATA-01, DATA-02, DATA-03, DATA-04, DATA-05, DATA-08 +**Success Criteria** (what must be TRUE): + 1. User can request an options chain for any ticker and receive strikes, expirations, bid/ask, volume, and OI from Tradier + 2. User can see 1st-order Greeks (Delta, Gamma, Theta, Vega, Rho) displayed per contract with ORATS source timestamp + 3. User can see implied volatility per contract (bid_iv, mid_iv, ask_iv, smv_vol) from Tradier + 4. User can filter the options chain by DTE range (e.g., 30-60 DTE) + 5. Tradier is registered as a new vendor in the existing data routing layer following the established provider pattern +**Plans**: TBD + +### Phase 2: Deterministic Math Core +**Goal**: All deterministic financial math lives in a pure Python module with comprehensive tests, never as LLM tool calls +**Depends on**: Phase 1 +**Requirements**: DATA-06, INT-05 +**Success Criteria** (what must be TRUE): + 1. System calculates 2nd-order Greeks (Charm, Vanna, Volga/Vomma) via blackscholes library and returns correct values for known test cases + 2. A standalone pure Python module exists for all deterministic math (Black-Scholes, Greeks, GEX formulas, P/L calculations) with no LLM dependencies + 3. Every public function in the math module has unit tests with known analytical values +**Plans**: TBD + +### Phase 3: Volatility Metrics +**Goal**: System can assess the implied volatility environment for any ticker to inform premium selling vs buying decisions +**Depends on**: Phase 1 +**Requirements**: VOL-01, VOL-02, VOL-07 +**Success Criteria** (what must be TRUE): + 1. System calculates IV Rank using 52-week IV high/low and returns a percentage that matches manual calculation + 2. System calculates IV Percentile using 252-day lookback of IV readings + 3. System calculates Volatility Risk Premium (VRP) by comparing current IV to realized/historical volatility + 4. All three metrics are deterministic Python functions with unit tests (not LLM computed) +**Plans**: TBD + +### Phase 4: GEX & Market Microstructure +**Goal**: System can analyze dealer positioning and detect unusual options flow to identify structural support/resistance levels +**Depends on**: Phase 1 +**Requirements**: GEX-01, GEX-02, GEX-03, GEX-04, FLOW-01, FLOW-02 +**Success Criteria** (what must be TRUE): + 1. System computes Net Gamma Exposure (GEX) across all strikes with documented sign convention and unit tests confirming positive GEX above spot for typical equities + 2. System identifies Call Wall and Put Wall levels (max positive/negative gamma strikes) from the GEX profile + 3. System identifies Gamma Flip zone and Vol Trigger level where cumulative GEX changes sign + 4. System classifies market regime as positive gamma (mean-reverting) or negative gamma (trending) + 5. System detects unusual options activity by comparing current volume to historical average and open interest, classifying flow as bullish or bearish +**Plans**: TBD + +### Phase 5: Volatility Surface +**Goal**: System can construct a full implied volatility surface via SVI parametric fitting for skew and term structure analysis +**Depends on**: Phase 1, Phase 3 +**Requirements**: VOL-04 +**Success Criteria** (what must be TRUE): + 1. System fits SVI parameters across strikes and expirations using scipy optimization with Gatheral no-butterfly-arbitrage constraints + 2. System gracefully falls back to linear interpolation when fewer than 5 liquid strikes exist for an expiration + 3. System filters illiquid strikes (OI < 100, spread > 30% of mid) before calibration to prevent garbage fits +**Plans**: TBD + +### Phase 6: Strategy Construction +**Goal**: System can construct multi-leg options strategies with complete risk/reward profiles for any volatility and directional environment +**Depends on**: Phase 2, Phase 3 +**Requirements**: STRAT-01, STRAT-02, STRAT-03, STRAT-04, STRAT-05, STRAT-06, VOL-03 +**Success Criteria** (what must be TRUE): + 1. System constructs multi-leg strategies (verticals, iron condors, straddles, strangles, butterflies, jade lizards, diagonals, calendars) from actual chain data + 2. System selects strategy type based on IV environment (high IV = credit strategies, low IV = debit strategies) and directional bias + 3. System outputs specific contract recommendations with exact strikes, expirations, and leg quantities drawn only from available chain contracts + 4. System outputs alternative strike/expiration ranges when primary recommendations are illiquid or near thresholds + 5. System calculates max profit, max loss, breakeven points, and Probability of Profit for each strategy using deterministic math +**Plans**: TBD + +### Phase 7: TastyTrade Rules Engine +**Goal**: System applies proven TastyTrade methodology rules to guide strategy selection and position management timing +**Depends on**: Phase 3, Phase 6 +**Requirements**: VOL-05, VOL-06 +**Success Criteria** (what must be TRUE): + 1. System applies IVR-based strategy selection rules (IVR >= 50% = sell premium, IVR < 30% = buy premium) and recommends appropriate strategy class + 2. System applies position management rules: 45 DTE entry targeting, 21 DTE management trigger, 50% profit target, 2x credit stop-loss + 3. Rules engine outputs are deterministic given the same IV Rank and DTE inputs (no LLM variance) +**Plans**: TBD + +### Phase 8: Options Agent Team +**Goal**: Each options analysis domain has a dedicated LLM agent that interprets pre-computed signals and writes structured analysis to shared state +**Depends on**: Phase 2, Phase 3, Phase 4, Phase 5, Phase 6, Phase 7 +**Requirements**: AGENT-01, AGENT-02, AGENT-03, AGENT-04, AGENT-05, AGENT-06, AGENT-09, AGENT-10 +**Success Criteria** (what must be TRUE): + 1. Volatility agent interprets IV Rank, IV Percentile, VRP, vol surface, and skew and writes a structured volatility assessment to AgentState + 2. Greeks agent interprets 1st and 2nd-order Greeks and writes risk implications to AgentState + 3. Flow agent interprets unusual activity signals and writes smart money assessment to AgentState + 4. GEX agent interprets dealer positioning, gamma walls, regime, and structural levels and writes to AgentState + 5. Strategy agent recommends specific multi-leg strategies based on all analysis inputs and writes to AgentState + 6. Position sizing agent calculates risk/reward profiles and writes max P/L, breakevens, and PoP to AgentState + 7. All agents follow the existing create_*() factory pattern and composite Options Score (0-5) is computed from IV rank, GEX regime, flow signals, and vol skew +**Plans**: TBD + +### Phase 9: Debate, Scoring & Pipeline Integration +**Goal**: Options analysis runs end-to-end as a parallel team in the LangGraph pipeline with debate, synthesis, and CLI support +**Depends on**: Phase 8 +**Requirements**: AGENT-07, AGENT-08, INT-01, INT-02, INT-03, INT-04 +**Success Criteria** (what must be TRUE): + 1. Options debate phase runs bull/bear debate on the options thesis with configurable rounds, producing a structured debate transcript + 2. Options portfolio manager synthesizes all agent analysis and debate into a final recommendation with transparent reasoning chain + 3. Options analysis team runs as a parallel section in the LangGraph StateGraph alongside existing stock analysis + 4. Options agents are configurable and optional (can be enabled/disabled like existing analysts) + 5. CLI supports options analysis mode with interactive options-specific prompts + 6. Deterministic validation layer checks strategy structural validity, risk limits, and liquidity before final output +**Plans**: TBD +**UI hint**: yes + +### Phase 10: Tastyworks Streaming +**Goal**: System can receive real-time streaming Greeks and quotes via Tastyworks for sub-minute data freshness +**Depends on**: Phase 1, Phase 9 +**Requirements**: DATA-07 +**Success Criteria** (what must be TRUE): + 1. System connects to Tastyworks DXLink WebSocket and receives real-time streaming Greeks and quotes + 2. Streaming data integrates into the existing vendor routing layer as an alternative to Tradier's hourly ORATS refresh + 3. System gracefully falls back to Tradier REST data when WebSocket connection is unavailable +**Plans**: TBD + +## Progress + +**Execution Order:** +Phases execute in numeric order: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10 +Note: Phases 2, 3, and 4 can execute in parallel after Phase 1. Phase 6 depends on Phases 2+3. Phase 7 depends on Phases 3+6. Phase 8 depends on all computation phases (2-7). + +| Phase | Plans Complete | Status | Completed | +|-------|----------------|--------|-----------| +| 1. Tradier Data Layer | 0/TBD | Not started | - | +| 2. Deterministic Math Core | 0/TBD | Not started | - | +| 3. Volatility Metrics | 0/TBD | Not started | - | +| 4. GEX & Market Microstructure | 0/TBD | Not started | - | +| 5. Volatility Surface | 0/TBD | Not started | - | +| 6. Strategy Construction | 0/TBD | Not started | - | +| 7. TastyTrade Rules Engine | 0/TBD | Not started | - | +| 8. Options Agent Team | 0/TBD | Not started | - | +| 9. Debate, Scoring & Pipeline Integration | 0/TBD | Not started | - | +| 10. Tastyworks Streaming | 0/TBD | Not started | - | diff --git a/.planning/STATE.md b/.planning/STATE.md new file mode 100644 index 00000000..3c5f988f --- /dev/null +++ b/.planning/STATE.md @@ -0,0 +1,64 @@ +# Project State + +## Project Reference + +See: .planning/PROJECT.md (updated 2026-03-29) + +**Core value:** Agents produce actionable multi-leg options recommendations with transparent, educational reasoning +**Current focus:** Phase 1: Tradier Data Layer + +## Current Position + +Phase: 1 of 10 (Tradier Data Layer) +Plan: 0 of TBD in current phase +Status: Ready to plan +Last activity: 2026-03-29 -- Roadmap created with 10 phases covering 42 requirements + +Progress: [░░░░░░░░░░] 0% + +## Performance Metrics + +**Velocity:** +- Total plans completed: 0 +- Average duration: - +- Total execution time: 0 hours + +**By Phase:** + +| Phase | Plans | Total | Avg/Plan | +|-------|-------|-------|----------| +| - | - | - | - | + +**Recent Trend:** +- Last 5 plans: - +- Trend: - + +*Updated after each plan completion* + +## Accumulated Context + +### Decisions + +Decisions are logged in PROJECT.md Key Decisions table. +Recent decisions affecting current work: + +- [Roadmap]: Phases 2, 3, 4 can run in parallel after Phase 1 (all depend only on Tradier data layer) +- [Roadmap]: SVI volatility surface isolated in its own phase (Phase 5) due to highest implementation risk +- [Roadmap]: All deterministic math in Phase 2 as standalone module before any agents consume it (critical pitfall mitigation) +- [Roadmap]: Tastyworks streaming deferred to Phase 10 as enhancement; batch pipeline uses Tradier REST throughout + +### Pending Todos + +None yet. + +### Blockers/Concerns + +- Historical IV data endpoint for IV Rank (52-week history) needs validation during Phase 1/3 planning +- Python version bump to >=3.11 required for tastytrade SDK (Phase 10) +- Tradier sandbox vs production Greeks fidelity unknown until Phase 1 implementation + +## Session Continuity + +Last session: 2026-03-29 +Stopped at: Roadmap created, ready to plan Phase 1 +Resume file: None diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 00000000..7afa19fe --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,253 @@ + +## Project + +**TradingAgents — Options Trading Module** + +An options trading analysis module for TradingAgents — a multi-agent AI system that uses LLM-powered agent teams to analyze financial markets. The new module adds a parallel options analysis team that evaluates options chains, Greeks, volatility surfaces, dealer positioning, and options flow to recommend specific multi-leg options strategies with transparent reasoning. + +**Core Value:** Agents produce actionable multi-leg options recommendations (with specific contracts AND alternative ranges) backed by transparent, educational reasoning that helps the user both trade and learn. + +### Constraints + +- **Data providers**: Tradier (REST, 120 req/min, Greeks hourly) and Tastyworks (REST + WebSocket streaming) as primary options data sources +- **No 2nd-order Greeks from API**: Charm, Vanna, Volga must be calculated from 1st-order Greeks + Black-Scholes +- **Architecture**: Must follow existing patterns — agent factory functions, vendor routing, LangGraph StateGraph +- **Python**: >=3.10, consistent with existing codebase +- **LLM provider agnostic**: Options agents must work with any supported LLM provider via the client factory + + + +## Technology Stack + +## Languages +- Python >=3.10 - Entire codebase (agents, dataflows, CLI, graph orchestration) +- None detected +## Runtime +- Python 3.10+ (compatible up to 3.13 per `uv.lock` resolution markers) +- uv (primary - `uv.lock` present at project root) +- pip/setuptools (build backend, `pyproject.toml` uses `setuptools>=61.0`) +- Lockfile: `uv.lock` present +## Frameworks +- LangGraph >=0.4.8 - Multi-agent workflow orchestration via `StateGraph` (`tradingagents/graph/setup.py`) +- LangChain Core >=0.3.81 - Base abstractions for LLM agents, callbacks, messages +- langchain-openai >=0.3.23 - OpenAI, Ollama, OpenRouter, xAI via `ChatOpenAI` (`tradingagents/llm_clients/openai_client.py`) +- langchain-anthropic >=0.3.15 - Anthropic Claude via `ChatAnthropic` (`tradingagents/llm_clients/anthropic_client.py`) +- langchain-google-genai >=2.1.5 - Google Gemini via `ChatGoogleGenerativeAI` (`tradingagents/llm_clients/google_client.py`) +- langchain-experimental >=0.3.4 - Experimental LangChain features +- Typer >=0.21.0 - CLI framework (`cli/main.py`) +- Rich >=14.0.0 - Terminal UI, panels, spinners, tables (`cli/main.py`) +- Questionary >=2.1.0 - Interactive prompts +- No test framework declared in `pyproject.toml`. One test file exists: `tests/test_ticker_symbol_handling.py` +- setuptools >=80.9.0 - Build backend +- uv - Package/dependency management +## Key Dependencies +- `langgraph >=0.4.8` - Core orchestration engine; all agent workflows are LangGraph `StateGraph` instances compiled and executed via `.stream()` / `.invoke()` +- `langchain-core >=0.3.81` - Provides `BaseCallbackHandler`, message types (`AIMessage`), and tool abstractions used throughout +- `yfinance >=0.2.63` - Default financial data vendor for stock prices, fundamentals, news, insider transactions +- `backtrader >=1.9.78.123` - Backtesting engine (imported but usage not prominent in core flow) +- `pandas >=2.3.0` - DataFrame operations for financial data manipulation (`tradingagents/dataflows/`) +- `stockstats >=0.6.5` - Technical indicator calculations on stock data (`tradingagents/dataflows/stockstats_utils.py`) +- `rank-bm25 >=0.2.2` - BM25 lexical similarity for agent memory retrieval (`tradingagents/agents/utils/memory.py`) +- `parsel >=1.10.0` - HTML/XML parsing (likely for web scraping) +- `requests >=2.32.4` - HTTP client for Alpha Vantage API calls (`tradingagents/dataflows/alpha_vantage_common.py`) +- `redis >=6.2.0` - Redis client (declared as dependency, usage not prominent in core flow) +- `python-dotenv` - Environment variable loading from `.env` files (`main.py`, `cli/main.py`) +- `tqdm >=4.67.1` - Progress bars +- `pytz >=2025.2` - Timezone handling +## Configuration +- `.env` file present - loaded via `python-dotenv` at startup +- `.env.example` documents required API keys: `OPENAI_API_KEY`, `GOOGLE_API_KEY`, `ANTHROPIC_API_KEY`, `XAI_API_KEY`, `OPENROUTER_API_KEY` +- `ALPHA_VANTAGE_API_KEY` - Required when using Alpha Vantage data vendor +- `TRADINGAGENTS_RESULTS_DIR` - Optional, defaults to `./results` +- `tradingagents/default_config.py` - Central config dict (`DEFAULT_CONFIG`) controlling: +- `pyproject.toml` - Project metadata, dependencies, entry points, package discovery +## Data Storage +- `tradingagents/dataflows/data_cache/` - Cached financial data +- `eval_results/{ticker}/` - Logged trading states as JSON +- `results/` - Trade results output directory +- `redis >=6.2.0` declared as dependency. Connection details would come via environment config. +## CLI Entry Point +- Maps to `cli.main:app` (Typer application) +- Fetches announcements from `https://api.tauric.ai/v1/announcements` (`cli/config.py`) +## Platform Requirements +- Python 3.10+ +- uv package manager (recommended) or pip +- At least one LLM provider API key (OpenAI, Anthropic, Google, xAI, or OpenRouter) +- Redis server (if redis-based features are used) +- Same as development; runs as a Python CLI application +- No containerization or deployment configs detected + + + +## Conventions + +## Naming Patterns +- Use `snake_case.py` for all Python modules: `bull_researcher.py`, `agent_states.py`, `y_finance.py` +- No hyphens in file names; underscores only +- Module names describe the single responsibility: `signal_processing.py`, `conditional_logic.py` +- Use `snake_case` for all functions: `create_bull_researcher()`, `get_stock_data()`, `process_signal()` +- Factory functions use `create_` prefix: `create_fundamentals_analyst()`, `create_llm_client()`, `create_trader()` +- Getter functions use `get_` prefix: `get_config()`, `get_memories()`, `get_vendor()` +- Private/internal methods use `_` prefix: `_get_provider_kwargs()`, `_log_state()`, `_rebuild_index()` +- Use `snake_case` for all variables: `curr_situation`, `past_memory_str`, `trade_date` +- Abbreviations are common and accepted: `llm`, `curr_date`, `curr_date_dt` +- Config keys use `snake_case` strings: `"deep_think_llm"`, `"max_debate_rounds"`, `"data_vendors"` +- Use `PascalCase`: `TradingAgentsGraph`, `FinancialSituationMemory`, `BaseLLMClient`, `SignalProcessor` +- State types use `TypedDict` with `PascalCase`: `AgentState`, `InvestDebateState`, `RiskDebateState` +- Enums use `PascalCase` with `UPPER_CASE` members: `AnalystType.MARKET`, `AnalystType.SOCIAL` +- Use `UPPER_SNAKE_CASE`: `DEFAULT_CONFIG`, `TOOLS_CATEGORIES`, `VENDOR_METHODS`, `VENDOR_LIST` +- Module-level private constants use `_UPPER_SNAKE_CASE`: `_PASSTHROUGH_KWARGS`, `_PROVIDER_CONFIG` +## Code Style +- No automated formatter configured (no black, ruff, or yapf config files detected) +- Indentation: 4 spaces (standard Python) +- Line length varies; no enforced limit. Some lines exceed 120 characters, especially LLM prompt strings +- Trailing commas used inconsistently +- No linter configured (no flake8, pylint, ruff, or mypy config detected) +- No pre-commit hooks +- No CI/CD pipeline detected +- Used selectively, not comprehensively +- Present on class methods and factory function signatures: `def create_llm_client(provider: str, model: str, ...) -> BaseLLMClient` +- `Annotated` types used extensively for LangChain tool parameters: `Annotated[str, "ticker symbol"]` +- `TypedDict` used for agent state definitions in `tradingagents/agents/utils/agent_states.py` +- Missing from most inner function closures and callback signatures +## Import Organization +- Wildcard imports used in some places: `from tradingagents.agents import *` in `tradingagents/graph/setup.py` and `tradingagents/agents/utils/agent_states.py` +- Relative imports within packages: `from .base_client import BaseLLMClient` in `tradingagents/llm_clients/` +- Absolute imports across packages: `from tradingagents.dataflows.interface import route_to_vendor` +- `__all__` lists defined in key `__init__.py` files: `tradingagents/agents/__init__.py`, `tradingagents/llm_clients/__init__.py` +- None. All imports use full dotted paths. +## Error Handling +- Broad `try/except Exception as e` is the dominant pattern throughout the codebase +- Error returns as formatted strings rather than raising exceptions: `return f"Error retrieving fundamentals for {ticker}: {str(e)}"` in `tradingagents/dataflows/y_finance.py` +- This is intentional for LLM tool functions: errors become text the LLM can interpret +- `ValueError` raised for invalid configuration: `raise ValueError(f"Unsupported LLM provider: {provider}")` in `tradingagents/llm_clients/factory.py` +- Custom exception class: `AlphaVantageRateLimitError` in `tradingagents/dataflows/alpha_vantage_common.py` for vendor fallback logic +- Fallback pattern in `tradingagents/dataflows/interface.py`: `route_to_vendor()` tries primary vendor, catches rate limit errors, falls back to alternatives +- Silent error swallowing with `print()` in `tradingagents/dataflows/y_finance.py`: `print(f"Error getting bulk stockstats data: {e}")` followed by fallback logic +- Raise `ValueError` for programming errors (bad config, invalid arguments) +- Return error strings from data-fetching tool functions (these become LLM context) +- Raise `RuntimeError` when all vendor fallbacks exhausted +## Logging +- Debug output via `print()`: `print(f"Error getting stockstats indicator data...")` in `tradingagents/dataflows/y_finance.py` +- Rich console for CLI user-facing output: `console = Console()` with `console.print()` in `cli/main.py` and `cli/utils.py` +- No log levels, no log files, no structured log format +## Agent/Node Design Pattern +- Analyst nodes: `create_*_analyst(llm)` - take only LLM, use tool-calling +- Researcher/manager nodes: `create_*(llm, memory)` - take LLM + memory for reflection +- Trader node: uses `functools.partial` to bind name: `return functools.partial(trader_node, name="Trader")` +- All nodes return a dict updating parts of `AgentState` +- Analyst nodes return `{"messages": [result], "_report": report}` +- Debate nodes return `{"investment_debate_state": {...}}` or `{"risk_debate_state": {...}}` +## LLM Prompt Construction +## Configuration Pattern +- `tradingagents/dataflows/config.py` holds a module-level `_config` dict +- `set_config()` and `get_config()` provide access +- `DEFAULT_CONFIG` in `tradingagents/default_config.py` provides defaults +- Config is a plain `dict`, not a dataclass or Pydantic model +## Module Design +- Key `__init__.py` files define `__all__` lists for controlled exports +- `tradingagents/agents/__init__.py` re-exports all agent factory functions +- `tradingagents/llm_clients/__init__.py` exports `BaseLLMClient` and `create_llm_client` +- `tradingagents/agents/__init__.py` serves as a barrel file aggregating all agent creators +- `tradingagents/dataflows/interface.py` acts as the routing interface for all data operations +## Docstrings +- Present on classes and public methods, especially in `tradingagents/graph/` and `tradingagents/llm_clients/` +- Google-style docstrings with `Args:` and `Returns:` sections: see `tradingagents/llm_clients/factory.py`, `tradingagents/graph/trading_graph.py` +- Missing from most inner closure functions and some utility functions +- Tool functions use docstrings as LLM-readable descriptions (LangChain `@tool` convention) + + + +## Architecture + +## Pattern Overview +- Stateful DAG execution via LangGraph `StateGraph` with a single shared `AgentState` +- Factory-function pattern: every agent is created by a `create_*()` function that returns a closure +- Two debate loops (investment + risk) with configurable round limits +- Vendor-abstracted data layer with pluggable providers (yfinance, Alpha Vantage) +- BM25-based memory system for reflection/learning across runs +- Two LLM tiers: "quick think" (analysts, researchers, debators) and "deep think" (managers) +## Layers +- Purpose: Interactive terminal interface for configuring and running analyses +- Location: `cli/` +- Contains: Typer app, Rich UI rendering, interactive prompts, stats tracking +- Depends on: `tradingagents.graph.trading_graph`, `tradingagents.default_config` +- Used by: End users via `tradingagents` CLI command +- Purpose: Constructs, configures, and executes the LangGraph agent workflow +- Location: `tradingagents/graph/` +- Contains: Graph setup, state propagation, conditional routing, reflection, signal processing +- Depends on: Agents layer, LLM clients layer, dataflows config +- Used by: CLI layer, `main.py` script, any Python consumer +- Purpose: Implements all LLM-powered agent behaviors as node functions +- Location: `tradingagents/agents/` +- Contains: Analyst nodes, researcher debate nodes, trader node, manager nodes, risk debator nodes +- Depends on: LangChain prompts/tools, dataflows (via tool functions), memory system +- Used by: Graph orchestration layer +- Purpose: Retrieves and routes financial data from external providers +- Location: `tradingagents/dataflows/` +- Contains: Vendor-specific implementations (yfinance, Alpha Vantage), routing interface, caching +- Depends on: External APIs (yfinance, Alpha Vantage), local filesystem cache +- Used by: Agent tool functions in `tradingagents/agents/utils/` +- Purpose: Abstracts LLM provider creation behind a factory pattern +- Location: `tradingagents/llm_clients/` +- Contains: Base client ABC, provider-specific clients (OpenAI, Anthropic, Google), factory +- Depends on: LangChain provider packages (langchain-openai, langchain-anthropic, langchain-google-genai) +- Used by: Graph orchestration layer (`TradingAgentsGraph.__init__`) +## Data Flow +- Single `AgentState` (extends LangGraph `MessagesState`) flows through the entire graph +- `AgentState` contains: messages, company/date, 4 analyst reports, `InvestDebateState`, `RiskDebateState`, trader plan, final decision +- `InvestDebateState` tracks bull/bear debate history and round count +- `RiskDebateState` tracks aggressive/conservative/neutral debate history and round count +- State is immutable within LangGraph; nodes return partial state dicts that get merged +## Key Abstractions +- Purpose: Create agent node callables with captured LLM and memory references +- Examples: `tradingagents/agents/analysts/market_analyst.py::create_market_analyst`, `tradingagents/agents/researchers/bull_researcher.py::create_bull_researcher`, `tradingagents/agents/trader/trader.py::create_trader` +- Pattern: Each `create_*()` function returns an inner function (closure) that takes `state` and returns a partial state dict +- Purpose: Decouple agents from specific data providers +- Examples: `tradingagents/dataflows/interface.py::route_to_vendor`, `tradingagents/agents/utils/core_stock_tools.py::get_stock_data` +- Pattern: Tool functions (decorated with `@tool`) call `route_to_vendor(method_name, *args)`, which resolves the configured vendor and calls the appropriate implementation. Supports automatic fallback on rate-limit errors. +- Purpose: Create LLM instances for any supported provider via a single entry point +- Examples: `tradingagents/llm_clients/factory.py::create_llm_client` +- Pattern: Factory function maps provider string to client class; each client implements `BaseLLMClient` ABC with `get_llm()` and `validate_model()` +- Purpose: Store and retrieve past trading reflections for agent learning +- Examples: `tradingagents/agents/utils/memory.py::FinancialSituationMemory` +- Pattern: BM25-based lexical similarity search over stored situation-recommendation pairs. No external API or embedding model required. +## Entry Points +- Location: `main.py` +- Triggers: Direct script execution (`python main.py`) +- Responsibilities: Creates `TradingAgentsGraph` with custom config, calls `propagate()`, prints decision +- Location: `cli/main.py` +- Triggers: `tradingagents` shell command (registered via `pyproject.toml` `[project.scripts]`) +- Responsibilities: Interactive wizard for selecting provider, models, analysts, depth; runs analysis with Rich live UI; displays progress and final report +- Location: `tradingagents/graph/trading_graph.py` +- Triggers: `from tradingagents.graph.trading_graph import TradingAgentsGraph` +- Responsibilities: Programmatic usage as a Python library +## Error Handling +- Data vendor fallback: `route_to_vendor()` catches `AlphaVantageRateLimitError` and falls through to next vendor in chain (`tradingagents/dataflows/interface.py`) +- Analyst validation: `GraphSetup.setup_graph()` raises `ValueError` if no analysts selected (`tradingagents/graph/setup.py`) +- LLM provider validation: `create_llm_client()` raises `ValueError` for unsupported providers (`tradingagents/llm_clients/factory.py`) +- No structured error handling within agent nodes; LLM failures propagate as exceptions +## Cross-Cutting Concerns + + + +## GSD Workflow Enforcement + +Before using Edit, Write, or other file-changing tools, start work through a GSD command so planning artifacts and execution context stay in sync. + +Use these entry points: +- `/gsd:quick` for small fixes, doc updates, and ad-hoc tasks +- `/gsd:debug` for investigation and bug fixing +- `/gsd:execute-phase` for planned phase work + +Do not make direct repo edits outside a GSD workflow unless the user explicitly asks to bypass it. + + + + + +## Developer Profile + +> Profile not yet configured. Run `/gsd:profile-user` to generate your developer profile. +> This section is managed by `generate-claude-profile` -- do not edit manually. +