Commit Graph

27 Commits

Author SHA1 Message Date
Ahmet Guzererler 733a11bd0a feat: wire gatekeeper into scanner graph 2026-03-28 09:33:32 +01:00
Ahmet Guzererler 7aa76d0061 feat: add live-tested gatekeeper data sources 2026-03-28 09:29:28 +01:00
Ahmet Guzererler 756d8358d7 feat: add global search graph scanners 2026-03-28 07:02:45 +01:00
ahmet guzererler c1194b7f77
feat: Fast-Reject [CRITICAL ABORT] short-circuit mechanism (#128)
* chore: initial commit for feat/fast-reject-short-circuits branch

* test: fix fast-reject unit tests (25/25 passing)

- Fix test_normal_flow_without_abort: expected 'Bull Researcher' not
  'Bear Researcher' — when current_response is empty the conditional
  logic routes to Bull first (conditional_logic.py line 74)
- Analyst abort-instruction tests: replace closure-attribute hacks
  (market_analyst.llm = ...) with patch() on prefetch_tools_parallel
  and run_tool_loop so the tests run without network access
- Fix co_consts substring check: system_message is compiled into one
  large string constant, so use any(...in str(c)...) instead of direct
  tuple membership
- PM tests: create mock_llm before create_portfolio_manager so the
  closure captures it and mock_llm.invoke.called assertions work; add
  missing company_of_interest key to all state dicts
- Integration tests: merge analyst/PM node outputs back into state
  ({**state, **result}) instead of replacing it, preserving keys like
  fundamentals_report and investment_debate_state; patch network calls;
  fix normal-flow routing assertions to != 'Portfolio Manager' since
  the exact next node depends on transient debate state
2026-03-27 00:19:43 +01:00
ahmet guzererler 6b3dd4172a
feat: finalise storage layout, run history loading & phase-level re-run (#121)
* feat: introduce flow_id with timestamp-based report versioning

Replace run_id with flow_id as the primary grouping concept (one flow =
one user analysis intent spanning scan + pipeline + portfolio). Reports
are now written as {timestamp}_{name}.json so load methods always return
the latest version by lexicographic sort, eliminating the latest.json
pointer pattern for new flows.

Key changes:
- report_paths.py: add generate_flow_id(), ts_now() (ms precision),
  flow_id kwarg on all path helpers; keep run_id / pointer helpers for
  backward compatibility
- ReportStore: dual-mode save/load — flow_id uses timestamped layout,
  run_id uses legacy runs/{id}/ layout with latest.json
- MongoReportStore: add flow_id field and index; run_id stays for compat
- DualReportStore: expose flow_id property
- store_factory: accept flow_id as primary param, run_id as alias
- runs.py / langgraph_engine.py: generate and thread flow_id through all
  trigger endpoints and run methods
- Tests: add flow_id coverage for all layers; 905 tests pass

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat: finalise storage layout, run history loading & phase-level re-run

Storage / persistence
- flow_id (8-char hex) replaces run_id as the disk storage key; all
  sub-phases of one auto run share the same flow_id directory
- Startup hydration: hydrate_runs_from_disk() rebuilds in-memory run
  store from run_meta.json on server restart (events lazy-loaded)

WebSocket / run history fixes
- Lazy-load events from run_events.jsonl on first WS connect; fixes
  blank terminal when clicking a historical run after restart
- Orphaned "running" runs (server restarted mid-run) auto-detected and
  marked "failed" with partial events replayed correctly

Phase re-run fixes
- Analysts checkpoint: use any() instead of all() — Social Analyst is
  optional; all() silently blocked checkpoint saves in typical runs
- Checkpoint lookup: pass original flow_id through rerun_params so
  _date_root() resolves to the correct flow_id subdirectory
- Selective event filtering on re-run: preserves scan nodes and other
  tickers; only removes stale events for the re-run phase+ticker
- Frontend graph now shows full auto-flow context during phase re-runs

Documentation
- ADR 018: canonical reference for storage layout, event schema,
  WebSocket streaming flows, checkpoint structure, MongoDB vs local
- ADR 013 updated: reflects background-task + lazy-loading evolution
- ADR 015 marked superseded by ADR 018
- CLAUDE.md: AgentOS storage section + 4 new critical patterns
- CURRENT_STATE.md updated

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-26 11:12:16 +01:00
ahmet guzererler 97a0d0de53
feat: configurable max_auto_tickers + run persistence with phase-level node re-run (#109)
Feature 1 - Configurable max_auto_tickers:
- Add max_auto_tickers config key (default 10) with TRADINGAGENTS_MAX_AUTO_TICKERS env override
- Macro synthesis agent accepts max_scan_tickers param, injects exact count into LLM prompt
- ScannerGraph passes config value to create_macro_synthesis()
- Backend engine applies safety cap on scan candidates (portfolio holdings always included)
- Frontend adds Max Tickers number input in params panel, sends max_tickers in auto run body

Feature 2 - Run persistence + phase-level node re-run:
- 2A: ReportStore + MongoReportStore gain save/load_run_meta, save/load_run_events,
  list_run_metas methods; runs.py persists to disk in finally block; startup hydration
  restores historical runs; lazy event loading on GET /{run_id}
- 2B: Analysts + trader checkpoint save/load methods in both stores; engine saves
  checkpoints after pipeline completion alongside complete_report.json
- 2C: GraphSetup gains build_debate_subgraph() and build_risk_subgraph() for partial
  re-runs; TradingAgentsGraph exposes debate_graph/risk_graph as lazy properties;
  NODE_TO_PHASE mapping + run_pipeline_from_phase() engine method;
  POST /api/run/rerun-node endpoint with _append_and_store helper
- 2D: Frontend history popover (loads GET /api/run/, sorts by created_at, click to load);
  triggerNodeRerun() calls rerun-node endpoint; handleNodeRerun uses phase-level
  re-run when active run is loaded

All 890 existing tests pass (10 skipped).

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-25 15:27:28 +01:00
ahmet guzererler 2145b04318
fix: graceful LLM 404 handling + per-tier fallback model config (#108)
* fix: per-tier fallback LLM for provider 404/policy errors

- tool_runner: catch status_code==404 from chain.invoke(), re-raise as
  RuntimeError with actionable message (OpenRouter privacy URL + env var hint)
- langgraph_engine: wrap astream_events in try/except, detect policy errors
  and re-raise with model/provider context
- langgraph_engine: _run_one_ticker distinguishes policy 404s (logger.error,
  no traceback) from real bugs (logger.exception with traceback); if fallback
  is configured, rebuilds pipeline with fallback model tier and retries
- langgraph_engine: add _is_policy_error() and _build_fallback_config() helpers
- default_config: add quick/mid/deep_think_fallback_llm + _provider keys
  (TRADINGAGENTS_QUICK_THINK_FALLBACK_LLM etc.)
- .env.example: document new fallback env vars

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs: ADR 017 LLM policy fallback, correct ADR 016 findings, update CLAUDE.md

- docs/agent/decisions/017: add ADR for per-tier LLM fallback design decision
- docs/agent/decisions/016: correct 3 inaccurate review findings — list_pm_decisions
  ObjectId projection, created_at datetime type, and base_dir pointer handling are
  all already correctly implemented in PR#106
- CLAUDE.md: add Per-Tier Fallback LLM section and _is_policy_error critical pattern
- CURRENT_STATE.md: update milestone and recent progress for PR#106/107/108 merges

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-25 11:19:08 +01:00
Copilot 9c9cc8c0b6
fix: address all PR#106 review findings (ADR 016) (#106)
* Initial plan

* feat: add observability logging - run event persistence and enriched tool events

- Integrate RunLogger into LangGraphEngine for JSONL event persistence
- Add _start_run_logger/_finish_run_logger lifecycle in all run methods
- Enrich tool events with service, status, and error fields
- Add _TOOL_SERVICE_MAP for tool-to-service name resolution
- Frontend: color error events in red, show service badges
- Frontend: display graceful_skip status with orange indicators
- Frontend: add error tab and service info to EventDetail/EventDetailModal
- Add 11 unit tests for new observability features

Co-authored-by: aguzererler <6199053+aguzererler@users.noreply.github.com>
Agent-Logs-Url: https://github.com/aguzererler/TradingAgents/sessions/477a0676-af7b-48ff-8a3d-567e943323cf

* refactor: address code review - extract graceful keywords constant, fix imports

- Move get_daily_dir import to top-level (remove inline aliases)
- Extract _GRACEFUL_SKIP_KEYWORDS as module-level constant
- Update test patches to match top-level import location

Co-authored-by: aguzererler <6199053+aguzererler@users.noreply.github.com>
Agent-Logs-Url: https://github.com/aguzererler/TradingAgents/sessions/477a0676-af7b-48ff-8a3d-567e943323cf

* feat: add run_id to report paths, MongoDB report store, store factory, and reflexion memory

- report_paths.py: All path helpers accept optional run_id for run-scoped dirs
- report_store.py: ReportStore supports run_id + latest.json pointer mechanism
- mongo_report_store.py: MongoDB-backed store with same interface (no overwrites)
- store_factory.py: Factory returns MongoDB or filesystem store based on config
- memory/reflexion.py: Reflexion memory for learning from past decisions
- langgraph_engine.py: Uses store factory + run_id for all run methods
- Fix save_holding_reviews bug (was save_holding_reviews, now save_holding_review)
- default_config.py: Add mongo_uri and mongo_db config keys
- pyproject.toml: Add pymongo>=4.12.1 dependency
- .env.example: Document TRADINGAGENTS_MONGO_URI and TRADINGAGENTS_MONGO_DB

Co-authored-by: aguzererler <6199053+aguzererler@users.noreply.github.com>
Agent-Logs-Url: https://github.com/aguzererler/TradingAgents/sessions/16e673ea-40a1-40a0-8e77-f8cd08c1a716

* fix: clean up reflexion record_outcome (remove broken update_one with sort)

Also update runs.py reset endpoint to use store factory, fix tests,
add ADR 015, update CURRENT_STATE.md

Co-authored-by: aguzererler <6199053+aguzererler@users.noreply.github.com>
Agent-Logs-Url: https://github.com/aguzererler/TradingAgents/sessions/16e673ea-40a1-40a0-8e77-f8cd08c1a716

* fix: address all PR#106 review findings (ADR 016)

- Fix save_holding_review: iterate per-ticker instead of passing
  portfolio_id as ticker (Finding 13)
- Fix RunLogger context: replace threading.local with contextvars
  for asyncio task isolation (Finding 3)
- Fix list_pm_decisions: add _id:0 projection to exclude ObjectId (Finding 6)
- Fix ReflexionMemory: native datetime for MongoDB, ISO string for
  local JSON fallback (Finding 7)
- Fix latest pointer: write/read_latest_pointer accept base_dir
  parameter, ReportStore passes _base_dir (Finding 12)
- Wire RunLogger callback into all astream_events calls (Finding 1)
- Call ensure_indexes in MongoReportStore.__init__ (Finding 11)
- Create ADR 016 documenting all 13 findings and resolutions
- Add 14 targeted tests covering all 7 fixes
- All 886 tests pass (872 existing + 14 new)

Co-authored-by: aguzererler <6199053+aguzererler@users.noreply.github.com>
Agent-Logs-Url: https://github.com/aguzererler/TradingAgents/sessions/e52cdd2f-efae-4d2a-a56f-903d909b3342

* chore: remove unused imports in tests, remove redundant ensure_indexes call in factory

Co-authored-by: aguzererler <6199053+aguzererler@users.noreply.github.com>
Agent-Logs-Url: https://github.com/aguzererler/TradingAgents/sessions/e52cdd2f-efae-4d2a-a56f-903d909b3342

* docs: update ADR 016 — mark Finding 2 resolved, update context docs for contextvars

Co-authored-by: aguzererler <6199053+aguzererler@users.noreply.github.com>
Agent-Logs-Url: https://github.com/aguzererler/TradingAgents/sessions/ce9e2400-a60d-4a6b-896b-1b34ec786bed

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: aguzererler <6199053+aguzererler@users.noreply.github.com>
2026-03-25 11:14:23 +01:00
ahmet guzererler 4c14080d73
feat(scanner): Finviz smart money scanner + Golden Overlap strategy
## Summary
- Adds `smart_money_scanner` as a new Phase 1b node that runs sequentially after `sector_scanner`, surfacing institutional footprints via Finviz screeners
- Introduces the **Golden Overlap** strategy in `macro_synthesis`: stocks confirmed by both top-down macro themes and bottom-up Finviz signals are labelled high-conviction
- Fixes model-name badge overflow in AgentGraph (long model IDs like OpenRouter paths were visually spilling into adjacent nodes)
- Completes all documentation: ADR-014, dataflow, architecture, components, glossary, current-state

## Key Decisions (see ADR-014)
- 3 zero-parameter tools (`get_insider_buying_stocks`, `get_unusual_volume_stocks`, `get_breakout_accumulation_stocks`) instead of 1 parameterised tool — prevents LLM hallucinations on string args
- Sequential after `sector_scanner` (not parallel fan-out) — gives access to `sector_performance_report` context and avoids `MAX_TOOL_ROUNDS=5` truncation in market_movers_scanner
- Graceful fallback: `_run_finviz_screen()` catches all exceptions and returns an error string — pipeline never hard-fails on web-scraper failure
- `breakout_accumulation` (52-wk high + 2x vol = O'Neil CAN SLIM institutional signal) replaces `oversold_bounces` (RSI<30 = retail contrarian, not smart money)

## Test Plan
- [x] 6 new mocked tests in `tests/unit/test_scanner_mocked.py` (happy path, empty DF, exception, sort order)
- [x] Fixed `tests/unit/test_scanner_graph.py` — added `smart_money_scanner` mock to compilation test
- [x] 2 pre-existing test failures excluded (verified baseline before changes)
- [x] AgentGraph badge: visually verified truncation with long OpenRouter model identifiers

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2026-03-24 16:03:17 +01:00
copilot-swe-agent[bot] 8e48bb4906 Add stop_loss and take_profit fields to Trade entries in database, API, and UI
Co-authored-by: aguzererler <6199053+aguzererler@users.noreply.github.com>
Agent-Logs-Url: https://github.com/aguzererler/TradingAgents/sessions/3b6a6fcc-30ac-48fa-970f-995a3bed80ed
2026-03-23 21:12:01 +00:00
copilot-swe-agent[bot] e808031aa6 docs: update docs/agent/ with AgentOS architecture, components, conventions, and ADR 013
Co-authored-by: aguzererler <6199053+aguzererler@users.noreply.github.com>
Agent-Logs-Url: https://github.com/aguzererler/TradingAgents/sessions/7cf1fa1a-8cb0-46b4-bc20-525aa3d38d7d
2026-03-23 10:48:49 +00:00
copilot-swe-agent[bot] ada257ac3e Update portfolio flow diagram, add token estimation per model, add CLI/test commands to README
Co-authored-by: aguzererler <6199053+aguzererler@users.noreply.github.com>
Agent-Logs-Url: https://github.com/aguzererler/TradingAgents/sessions/94532c4f-3d37-464e-9a74-3c2e9899a532
2026-03-21 02:34:23 +00:00
copilot-swe-agent[bot] 96a2c79cb3 Implement Portfolio Manager Phases 2-5: risk evaluation, candidate prioritization, holding reviewer agent, PM decision agent, trade executor, and portfolio graph orchestration
Co-authored-by: aguzererler <6199053+aguzererler@users.noreply.github.com>
2026-03-20 14:44:22 +00:00
Ahmet Guzererler a17e5f3707 feat: complete portfolio data foundation — psycopg2 client, repository, tests
Replace supabase-py stubs with working psycopg2 implementation using
Supabase pooler connection string. Implement full business logic in
repository (avg cost basis, cash accounting, trade recording, snapshots).
Add 12 unit tests + 4 integration tests (51 total portfolio tests pass).
Fix cash_pct bug in models.py, update docs for psycopg2 + pooler pattern.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-20 14:06:50 +01:00
copilot-swe-agent[bot] 7ea9866d1d docs: ADR-012 — raw supabase-py over Prisma/SQLAlchemy for portfolio data layer
Co-authored-by: aguzererler <6199053+aguzererler@users.noreply.github.com>
2026-03-20 10:48:40 +00:00
ahmet guzererler d92fd9cab1
feat: NotebookLM sync with date-specific sources and consolidation (#28) 2026-03-19 15:39:25 +01:00
ahmet guzererler d4fefc804e
feat: daily digest consolidation and Google NotebookLM sync (#23)
* feat: daily digest consolidation and NotebookLM sync

- Add tradingagents/daily_digest.py: appends timestamped entries from
  analyze and scan runs into a single reports/daily/{date}/daily_digest.md
- Add tradingagents/notebook_sync.py: uploads digest to Google NotebookLM
  via nlm CLI, deleting the previous version before uploading (opt-in,
  skips silently if NOTEBOOK_ID is not set)
- Add get_digest_path() helper to report_paths.py
- Hook both analyze and scan CLI commands to append + sync after each run
- Add NOTEBOOK_ID to .env.example

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs: update agent memory for daily digest + NotebookLM sync

Update CURRENT_STATE, ARCHITECTURE, and COMPONENTS context files to
reflect the feat/daily-digest-notebooklm implementation.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: correct nlm CLI commands and env var name for NotebookLM sync

- Use nlm note list/create/update instead of source list/add/delete
- Parse notes from {"notes": [...]} response structure
- Rename NOTEBOOK_ID -> NOTEBOOKLM_ID in both code and .env.example
- Auto-discover nlm at ~/.local/bin/nlm when not in PATH
- Tested: create on first run, update on subsequent runs

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-19 12:21:03 +01:00
ahmet guzererler a90f14c086
feat: unified report paths, structured observability logging, and memory system update (#22)
* gitignore

* feat: unify report paths under reports/daily/{date}/ hierarchy

All generated artifacts now land under a single reports/ tree:
- reports/daily/{date}/market/ for scan results (was results/macro_scan/)
- reports/daily/{date}/{TICKER}/ for per-ticker analysis (was reports/{TICKER}_{timestamp}/)
- reports/daily/{date}/{TICKER}/eval/ for eval logs (was eval_results/{TICKER}/...)

Adds tradingagents/report_paths.py with centralized path helpers used by
CLI commands, trading graph, and pipeline.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: structured observability logging for LLM, tool, and vendor calls

Add RunLogger (tradingagents/observability.py) that emits JSON-lines events
for every LLM call (model, agent, tokens in/out, latency), tool invocation
(tool name, args, success, latency), data vendor call (method, vendor,
success/failure, latency), and report save.

Integration points:
- route_to_vendor: log_vendor_call() on every try/catch
- run_tool_loop: log_tool_call() on every tool invoke
- ScannerGraph: new callbacks param, passes RunLogger.callback to all LLM tiers
- pipeline/macro_bridge: picks up RunLogger from thread-local, passes to TradingAgentsGraph
- cli/main.py: one RunLogger per command (analyze/scan/pipeline), write_log()
  at end, summary line printed to console

Log files co-located with reports:
  reports/daily/{date}/{TICKER}/run_log.jsonl   (analyze)
  reports/daily/{date}/market/run_log.jsonl     (scan)
  reports/daily/{date}/run_log.jsonl            (pipeline)

Also fix test_long_response_no_nudge: update "A"*600 → "A"*2100 to match
MIN_REPORT_LENGTH=2000 threshold set in an earlier commit.

Update memory system context files (ARCHITECTURE, COMPONENTS, CONVENTIONS,
GLOSSARY, CURRENT_STATE) to document observability and report path systems.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-19 09:06:40 +01:00
ahmet guzererler 8fcd58ad0f
feat: memory system v2 — skills, context files, post-commit hook (#21)
* gitignore

* feat: memory system v2 — builder/reader skills, context files, post-commit hook

Replace architecture-coordinator skill with two focused skills:
- memory-builder: extracts repo knowledge into 4-layer memory system with
  mandatory verification steps (deps, model names, agent count, ADR cross-refs)
- memory-reader: loads memory at session start, enforces ADR constraints,
  detects staleness

Generate 5 verified context files under docs/agent/context/:
- ARCHITECTURE.md (105 lines) — system design, pipelines, LLM tiers
- COMPONENTS.md (188 lines) — 17 agent factories, extension guides, test inventory
- CONVENTIONS.md (88 lines) — coding rules with source citations
- TECH_STACK.md (75 lines) — 22 deps from pyproject.toml with versions
- GLOSSARY.md (92 lines) — 50+ terms across 9 domains

Add PostToolUse hook in .claude/settings.json to remind agent to update
CURRENT_STATE.md after git commits.

All 30 factual claims audited and verified against source code.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-18 18:38:03 +01:00
ahmet guzererler fa8a0d56fb
feat: opt-in vendor fallback — fail-fast by default (#18)
* feat: add extract_json() utility for robust LLM JSON parsing

Handles DeepSeek R1 <think> blocks, markdown code fences, and
preamble/postamble text that LLMs wrap around JSON output.
Applied to macro_synthesis, macro_bridge, and CLI scan output.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: opt-in vendor fallback — fail-fast by default (ADR 011)

Silent cross-vendor fallback corrupts signal quality when data contracts
differ (e.g., AV news has sentiment scores yfinance lacks). Only methods
with fungible data contracts (OHLCV, indices, sector/industry perf,
market movers) now get fallback. All others raise immediately.

- Add FALLBACK_ALLOWED whitelist to interface.py
- Rewrite route_to_vendor() with fail-fast/fallback branching
- Improve error messages with method name, vendors tried, and exception chaining
- Add 11 new tests in test_vendor_failfast.py
- Update ADRs 002 (superseded), 008, 010; create ADR 011

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-18 14:25:38 +01:00
Ahmet Guzererler b50bc30217 Merge branch 'claude/objective-galileo': test fixes and plans
- fix: resolve 12 pre-existing test failures across 5 test files
  (callable() check, env var isolation, integration markers, stale assertions)
- docs: add implementation plans 011 (opt-in fallback) and 012 (test fixes)
- chore: unblock docs/agent/plans/ from .gitignore

Full offline suite: 388 passed, 70 deselected, 0 failures.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-18 12:16:02 +01:00
Ahmet Guzererler ff3e2817bf docs: add implementation plans for opt-in fallback (011) and test fixes (012)
Also unblock docs/agent/plans/ from .gitignore — the plans/ rule was
intended for generated scan-result plans, not design documents.

- 011-opt-in-vendor-fallback.md: fail-fast-by-default with FALLBACK_ALLOWED
  whitelist for fungible data tools (OHLCV, indices, sector/industry perf,
  market movers); 4-phase plan covering interface.py change, new tests,
  ADR docs, and verification
- 012-fix-preexisting-test-failures.md: root-cause analysis and exact fixes
  for all 12 pre-existing failures across 5 test files (now implemented)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-18 12:12:07 +01:00
ahmet guzererler 26cd4c8b78
feat: Finnhub integration layer, 141 tests, and vendor evaluation report (#16)
* feat: add Finnhub integration layer, tests, and evaluation report

Adds a complete Finnhub data vendor integration as a supplementary
source alongside Alpha Vantage — zero changes to existing functionality.

New dataflow modules:
- finnhub_common.py: exception hierarchy, thread-safe rate limiter (60/min), _make_api_request
- finnhub_stock.py: get_stock_candles, get_quote
- finnhub_fundamentals.py: get_company_profile, get_financial_statements, get_basic_financials
- finnhub_news.py: get_company_news, get_market_news, get_insider_transactions
- finnhub_scanner.py: market movers (S&P 500 basket workaround), indices, sectors, topic news
- finnhub_indicators.py: SMA, EMA, MACD, RSI, BBANDS, ATR via /indicator endpoint
- finnhub.py: facade re-exporting all public functions

New tests:
- test_finnhub_integration.py: 100 offline (mocked HTTP) tests — all passing
- test_finnhub_live_integration.py: 41 live integration tests — skip gracefully when FINNHUB_API_KEY unset

Evaluation report (docs/finnhub_evaluation.md):
- Full coverage matrix vs Alpha Vantage across 5 data categories
- Free tier viability analysis (60 calls/min)
- Unique capabilities: earnings calendar, economic calendar, XBRL as-filed filings
- Recommendation: add as supplementary vendor for calendar data only

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* test: mark paid-tier Finnhub endpoints; update evaluation with live results

Live testing with free-tier key confirmed:
- /quote, /stock/profile2, /stock/metric, /company-news, /news,
  /stock/insider-transactions → all free tier (27 live tests PASS)
- /stock/candle, /financials-reported, /indicator → paid tier HTTP 403
  (14 tests now properly skipped with @pytest.mark.paid_tier)

Also:
- Register 'integration' and 'paid_tier' markers in pyproject.toml
- Update docs/finnhub_evaluation.md with confirmed endpoint availability table

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat: wire Finnhub into routing layer — insider txns, calendars, fallback

Changes:
- interface.py: Finnhub added as third vendor (alongside yfinance + AV)
  - get_insider_transactions: Finnhub primary (free, + MSPR bonus signal)
  - get_market_indices/sector_performance/topic_news: Finnhub added as option
  - Fallback catch extended: (AlphaVantageError, FinnhubError, ConnectionError, TimeoutError)
  - New calendar_data category with get_earnings_calendar + get_economic_calendar
- finnhub_scanner.py: added get_earnings_calendar_finnhub, get_economic_calendar_finnhub
  (FOMC/CPI/NFP/GDP events + earnings beats — unique, not in AV at any tier)
- finnhub.py: re-exports new calendar functions
- scanner_tools.py: @tool wrappers for get_earnings_calendar, get_economic_calendar
- default_config.py: tool_vendors["get_insider_transactions"]="finnhub",
  calendar_data vendor category defaulting to "finnhub"
- .env.example: FINNHUB_API_KEY documented
- docs/agent/decisions/010-finnhub-vendor-integration.md: ADR for this decision

All 173 offline tests pass. ADR 002 constraints respected throughout.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-18 11:28:43 +01:00
Ahmet Guzererler cf636232aa fix: resolve 12 pre-existing test failures across 5 test files
Root causes fixed:
- test_config_wiring.py: `callable()` returns False on LangChain @tool
  objects — replaced with `hasattr(x, "invoke")` check
- test_env_override.py: `load_dotenv()` in default_config.py re-reads
  .env on importlib.reload(), leaking user's TRADINGAGENTS_* env vars
  into isolation tests — mock env vars before reload
- test_scanner_comprehensive.py: LLM-calling test was not marked
  @pytest.mark.integration — added marker so offline runs skip it
- test_scanner_fallback.py: assertions used stale `_output_files` list
  from a previous run when output dir already existed — clear dir in
  setUp; also fixed tool-availability check using hasattr(x, "invoke")
- test_scanner_graph.py: output-file path assertions used hardcoded
  date string instead of fixture date; graph node assertions checked
  for removed node names

Full offline suite: 388 passed, 70 deselected, 0 failures.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-18 11:11:00 +01:00
Ahmet Guzererler 04b7efdb68 feat: wire Finnhub into routing layer — insider txns, calendars, fallback
Changes:
- interface.py: Finnhub added as third vendor (alongside yfinance + AV)
  - get_insider_transactions: Finnhub primary (free, + MSPR bonus signal)
  - get_market_indices/sector_performance/topic_news: Finnhub added as option
  - Fallback catch extended: (AlphaVantageError, FinnhubError, ConnectionError, TimeoutError)
  - New calendar_data category with get_earnings_calendar + get_economic_calendar
- finnhub_scanner.py: added get_earnings_calendar_finnhub, get_economic_calendar_finnhub
  (FOMC/CPI/NFP/GDP events + earnings beats — unique, not in AV at any tier)
- finnhub.py: re-exports new calendar functions
- scanner_tools.py: @tool wrappers for get_earnings_calendar, get_economic_calendar
- default_config.py: tool_vendors["get_insider_transactions"]="finnhub",
  calendar_data vendor category defaulting to "finnhub"
- .env.example: FINNHUB_API_KEY documented
- docs/agent/decisions/010-finnhub-vendor-integration.md: ADR for this decision

All 173 offline tests pass. ADR 002 constraints respected throughout.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-18 09:41:41 +01:00
Ahmet Guzererler 10484684bc docs: update memory files after PR #13 (Industry Deep Dive quality fix)
- CURRENT_STATE.md: remove Industry Deep Dive blocker (resolved), update
  test count 38 → 53, add PR #13 to Recent Progress, update milestone focus
- decisions/009-industry-deep-dive-quality.md: new ADR documenting the
  three-pronged fix (enriched data, explicit sector routing, tool-call nudge)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-17 20:20:39 +01:00
Ahmet Guzererler 0b4260a4e2 feat: add agentic memory scaffold and migrate tracking files to docs/agent/
Migrate DECISIONS.md, MISTAKES.md, PROGRESS.md, agents/, plans/, and
tradingagents/llm_clients/TODO.md into a structured docs/agent/ scaffold
with ADR-style decisions, plans, templates, and a live state tracker.

This gives agent workflows a standard memory structure for decisions,
plans, logs, and session continuity via CURRENT_STATE.md.

Agent-Ref: docs/agent/plans/global-macro-scanner.md
State-Updated: Yes

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-17 17:14:11 +01:00