a
@@ -0,0 +1,15 @@
|
||||
.git
|
||||
.venv
|
||||
.env
|
||||
.claude
|
||||
.idea
|
||||
.vscode
|
||||
.DS_Store
|
||||
__pycache__
|
||||
*.egg-info
|
||||
build
|
||||
dist
|
||||
results
|
||||
eval_results
|
||||
Dockerfile
|
||||
docker-compose.yml
|
||||
@@ -0,0 +1,9 @@
|
||||
# LLM Providers (set the one you use)
|
||||
OPENAI_API_KEY=
|
||||
GOOGLE_API_KEY=
|
||||
ANTHROPIC_API_KEY=
|
||||
XAI_API_KEY=
|
||||
DEEPSEEK_API_KEY=
|
||||
DASHSCOPE_API_KEY=
|
||||
ZHIPU_API_KEY=
|
||||
OPENROUTER_API_KEY=
|
||||
@@ -0,0 +1,223 @@
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[codz]
|
||||
*$py.class
|
||||
|
||||
# C extensions
|
||||
*.so
|
||||
|
||||
# Distribution / packaging
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
share/python-wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
MANIFEST
|
||||
|
||||
# PyInstaller
|
||||
# Usually these files are written by a python script from a template
|
||||
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
||||
*.manifest
|
||||
*.spec
|
||||
|
||||
# Installer logs
|
||||
pip-log.txt
|
||||
pip-delete-this-directory.txt
|
||||
|
||||
# Unit test / coverage reports
|
||||
htmlcov/
|
||||
.tox/
|
||||
.nox/
|
||||
.coverage
|
||||
.coverage.*
|
||||
.cache
|
||||
nosetests.xml
|
||||
coverage.xml
|
||||
*.cover
|
||||
*.py.cover
|
||||
.hypothesis/
|
||||
.pytest_cache/
|
||||
cover/
|
||||
|
||||
# Translations
|
||||
*.mo
|
||||
*.pot
|
||||
|
||||
# Django stuff:
|
||||
*.log
|
||||
local_settings.py
|
||||
db.sqlite3
|
||||
db.sqlite3-journal
|
||||
|
||||
# Flask stuff:
|
||||
instance/
|
||||
.webassets-cache
|
||||
|
||||
# Scrapy stuff:
|
||||
.scrapy
|
||||
|
||||
# Sphinx documentation
|
||||
docs/_build/
|
||||
|
||||
# PyBuilder
|
||||
.pybuilder/
|
||||
target/
|
||||
|
||||
# Jupyter Notebook
|
||||
.ipynb_checkpoints
|
||||
|
||||
# IPython
|
||||
profile_default/
|
||||
ipython_config.py
|
||||
|
||||
# pyenv
|
||||
# For a library or package, you might want to ignore these files since the code is
|
||||
# intended to run in multiple environments; otherwise, check them in:
|
||||
# .python-version
|
||||
|
||||
# pipenv
|
||||
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
||||
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
||||
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
||||
# install all needed dependencies.
|
||||
# Pipfile.lock
|
||||
|
||||
# UV
|
||||
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
|
||||
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
||||
# commonly ignored for libraries.
|
||||
# uv.lock
|
||||
|
||||
# poetry
|
||||
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
||||
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
||||
# commonly ignored for libraries.
|
||||
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
||||
# poetry.lock
|
||||
# poetry.toml
|
||||
|
||||
# pdm
|
||||
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
||||
# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
|
||||
# https://pdm-project.org/en/latest/usage/project/#working-with-version-control
|
||||
# pdm.lock
|
||||
# pdm.toml
|
||||
.pdm-python
|
||||
.pdm-build/
|
||||
|
||||
# pixi
|
||||
# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
|
||||
# pixi.lock
|
||||
# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
|
||||
# in the .venv directory. It is recommended not to include this directory in version control.
|
||||
.pixi
|
||||
|
||||
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
||||
__pypackages__/
|
||||
|
||||
# Celery stuff
|
||||
celerybeat-schedule
|
||||
celerybeat.pid
|
||||
|
||||
# Redis
|
||||
*.rdb
|
||||
*.aof
|
||||
*.pid
|
||||
|
||||
# RabbitMQ
|
||||
mnesia/
|
||||
rabbitmq/
|
||||
rabbitmq-data/
|
||||
|
||||
# ActiveMQ
|
||||
activemq-data/
|
||||
|
||||
# SageMath parsed files
|
||||
*.sage.py
|
||||
|
||||
# Environments
|
||||
.env
|
||||
.envrc
|
||||
.venv
|
||||
.venv-*/
|
||||
env/
|
||||
venv/
|
||||
ENV/
|
||||
env.bak/
|
||||
venv.bak/
|
||||
|
||||
# Spyder project settings
|
||||
.spyderproject
|
||||
.spyproject
|
||||
|
||||
# Rope project settings
|
||||
.ropeproject
|
||||
|
||||
# mkdocs documentation
|
||||
/site
|
||||
|
||||
# mypy
|
||||
.mypy_cache/
|
||||
.dmypy.json
|
||||
dmypy.json
|
||||
|
||||
# Pyre type checker
|
||||
.pyre/
|
||||
|
||||
# pytype static type analyzer
|
||||
.pytype/
|
||||
|
||||
# Cython debug symbols
|
||||
cython_debug/
|
||||
|
||||
# PyCharm
|
||||
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
||||
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
||||
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
||||
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
||||
# .idea/
|
||||
|
||||
# Abstra
|
||||
# Abstra is an AI-powered process automation framework.
|
||||
# Ignore directories containing user credentials, local state, and settings.
|
||||
# Learn more at https://abstra.io/docs
|
||||
.abstra/
|
||||
|
||||
# Visual Studio Code
|
||||
# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
|
||||
# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
|
||||
# and can be added to the global gitignore or merged into this file. However, if you prefer,
|
||||
# you could uncomment the following to ignore the entire vscode folder
|
||||
# .vscode/
|
||||
|
||||
# Ruff stuff:
|
||||
.ruff_cache/
|
||||
|
||||
# PyPI configuration file
|
||||
.pypirc
|
||||
|
||||
# Marimo
|
||||
marimo/_static/
|
||||
marimo/_lsp/
|
||||
__marimo__/
|
||||
|
||||
# Streamlit
|
||||
.streamlit/secrets.toml
|
||||
|
||||
# Cache
|
||||
**/data_cache/
|
||||
|
||||
# Node dependencies (if any)
|
||||
node_modules/
|
||||
@@ -0,0 +1,266 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes to TradingAgents are documented here.
|
||||
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
||||
and this project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
Breaking changes within the 0.x line are called out explicitly.
|
||||
|
||||
## [0.2.4] — 2026-04-25
|
||||
|
||||
### Added
|
||||
|
||||
- **Structured-output decision agents.** Research Manager, Trader, and Portfolio
|
||||
Manager now use `llm.with_structured_output(Schema)` on their primary call
|
||||
and return typed Pydantic instances. Each provider's native structured-output
|
||||
mode is used (`json_schema` for OpenAI / xAI, `response_schema` for Gemini,
|
||||
tool-use for Anthropic, function-calling for OpenAI-compatible providers).
|
||||
Render helpers preserve the existing markdown shape so memory log, CLI
|
||||
display, and saved reports keep working unchanged. (#434)
|
||||
- **LangGraph checkpoint resume** — opt-in via `--checkpoint`. State is saved
|
||||
after each node so crashed or interrupted runs resume from the last
|
||||
successful step. Per-ticker SQLite databases under
|
||||
`~/.tradingagents/cache/checkpoints/`. `--clear-checkpoints` resets them. (#594)
|
||||
- **Persistent decision log** replacing the per-agent BM25 memory. Decisions
|
||||
are stored automatically at the end of `propagate()`; the next same-ticker
|
||||
run resolves prior pending entries with realised return, alpha vs SPY, and
|
||||
a one-paragraph reflection. Override path with `TRADINGAGENTS_MEMORY_LOG_PATH`.
|
||||
Optional `memory_log_max_entries` config caps resolved entries; pending
|
||||
entries are never pruned. (#578, #563, #564, #579)
|
||||
- **DeepSeek, Qwen (Alibaba DashScope), GLM (Zhipu), and Azure OpenAI**
|
||||
providers, plus dynamic OpenRouter model selection.
|
||||
- **Docker support** — multi-stage build with separate dev and runtime images.
|
||||
- **`scripts/smoke_structured_output.py`** — diagnostic that exercises the
|
||||
three structured-output agents against any provider so contributors can
|
||||
verify their setup with one command.
|
||||
- **5-tier rating scale** (Buy / Overweight / Hold / Underweight / Sell) used
|
||||
consistently by Research Manager, Portfolio Manager, signal processor, and
|
||||
the memory log; Trader keeps 3-tier (Buy / Hold / Sell) since transaction
|
||||
direction is naturally ternary.
|
||||
- **Pytest fixtures** — lazy LLM client imports plus placeholder API keys so
|
||||
the test suite runs cleanly without credentials. (#588)
|
||||
|
||||
### Changed
|
||||
|
||||
- **`backend_url` default is now `None`** rather than the OpenAI URL. Each
|
||||
provider client falls back to its native default. The previous default
|
||||
leaked the OpenAI URL into non-OpenAI clients (e.g. Gemini), producing
|
||||
malformed request URLs for Python users who switched providers without
|
||||
overriding `backend_url`. The CLI flow is unaffected.
|
||||
- All file I/O passes explicit `encoding="utf-8"` so Windows users no longer
|
||||
hit `UnicodeEncodeError` with the cp1252 default. (#543, #550, #576)
|
||||
- Cache and log directories moved to `~/.tradingagents/` to resolve Docker
|
||||
permission issues. (#519)
|
||||
- `SignalProcessor` reads the rating from the Portfolio Manager's rendered
|
||||
markdown via a deterministic heuristic — no extra LLM call.
|
||||
- OpenAI structured-output calls default to `method="function_calling"` to
|
||||
avoid noisy `PydanticSerializationUnexpectedValue` warnings emitted by
|
||||
langchain-openai's Responses-API parse path. Same typed result, no warnings.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Empty memory no longer triggers fabricated past-lessons in agent prompts;
|
||||
the memory-log redesign makes this structurally impossible since only the
|
||||
Portfolio Manager consults memory and only when entries exist. (#572)
|
||||
- Tool-call logging processes every chunk message, not just the last one, and
|
||||
memory score normalization handles empty score arrays. (#534, #531)
|
||||
|
||||
### Removed
|
||||
|
||||
- `FinancialSituationMemory` (the per-agent BM25 system) and the dead
|
||||
`reflect_and_remember()` plumbing; subsumed by the persistent decision log.
|
||||
- Hardcoded Google endpoint that caused 404 when `langchain-google-genai`
|
||||
changed its API path. (#493, #496)
|
||||
|
||||
### Contributors
|
||||
|
||||
Thanks to everyone who shaped this release through code, design, and reports:
|
||||
|
||||
- [@claytonbrown](https://github.com/claytonbrown) — checkpoint resume (#594), test fixtures (#588), design feedback on cost tracking (#582) and structured validation (#583)
|
||||
- [@Bcardo](https://github.com/Bcardo) — memory-log redesign (#579), empty-memory hallucination report (#572), encoding fix proposal (#570)
|
||||
- [@voidborne-d](https://github.com/voidborne-d) — memory persistence design (#564), portfolio manager state fix (#503)
|
||||
- [@mannubaveja007](https://github.com/mannubaveja007) — structured-output feature request (#434)
|
||||
- [@kelder66](https://github.com/kelder66) — RAM-only memory issue (#563)
|
||||
- [@Gujiassh](https://github.com/Gujiassh) — tool-call logging fix (#534), test stub PR (#533)
|
||||
- [@iuyup](https://github.com/iuyup) — memory score normalization fix (#531)
|
||||
- [@kaihg](https://github.com/kaihg) — Google base_url fix (#496)
|
||||
- [@32ryh98yfe](https://github.com/32ryh98yfe) — Gemini 404 report (#493)
|
||||
- [@uppb](https://github.com/uppb) — OpenRouter dynamic model selection (#482)
|
||||
- [@guoz14](https://github.com/guoz14) — OpenRouter limited-model report (#337)
|
||||
- [@samchenku](https://github.com/samchenku) — indicator name normalization (#490)
|
||||
- [@JasonOA888](https://github.com/JasonOA888) — y_finance pandas import fix (#488)
|
||||
- [@tiffanychum](https://github.com/tiffanychum) — stale import cleanup (#499)
|
||||
- [@zaizou](https://github.com/zaizou) — Docker permission issue (#519)
|
||||
- [@Stosman123](https://github.com/Stosman123), [@mauropuga](https://github.com/mauropuga), [@hotwind2015](https://github.com/hotwind2015) — Windows encoding bug reports (#543, #550, #576)
|
||||
- [@nnishad](https://github.com/nnishad), [@atharvajoshi01](https://github.com/atharvajoshi01) — encoding fix proposals (#568, #549)
|
||||
|
||||
## [0.2.3] — 2026-03-29
|
||||
|
||||
### Added
|
||||
|
||||
- **Multi-language output** for analyst reports and final decisions, with a
|
||||
CLI selector. Internal agent debate stays in English for reasoning quality. (#472)
|
||||
- **GPT-5.4 family models** in the default catalog, with deep/quick model split.
|
||||
- **Unified model catalog** as a single source of truth for CLI options and
|
||||
provider validation.
|
||||
|
||||
### Changed
|
||||
|
||||
- `base_url` is forwarded to Google and Anthropic clients so corporate proxies
|
||||
work consistently across providers. (#427)
|
||||
- Standardised the Google `api_key` parameter to the unified `api_key` form.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Backtesting fetchers no longer leak look-ahead data when `curr_date` is in
|
||||
the middle of a fetched window. (#475)
|
||||
- Invalid indicator names from the LLM are caught at the tool boundary instead
|
||||
of crashing the run. (#429)
|
||||
- yfinance news fetchers respect the same exponential-backoff retry as price
|
||||
fetchers. (#445)
|
||||
|
||||
### Contributors
|
||||
|
||||
- [@ahmedk20](https://github.com/ahmedk20) — multi-language output (#472)
|
||||
- [@CadeYu](https://github.com/CadeYu) — model catalog typing (#464)
|
||||
- [@javierdejesusda](https://github.com/javierdejesusda) — unified Google API key parameter (#453)
|
||||
- [@voidborne-d](https://github.com/voidborne-d) — yfinance news retry (#445)
|
||||
- [@kostakost2](https://github.com/kostakost2) — look-ahead bias report (#475)
|
||||
- [@lu-zhengda](https://github.com/lu-zhengda) — proxy/base_url support request (#427)
|
||||
- [@VamsiKrishna2021](https://github.com/VamsiKrishna2021) — invalid indicator crash report (#429)
|
||||
|
||||
## [0.2.2] — 2026-03-22
|
||||
|
||||
### Added
|
||||
|
||||
- **Five-tier rating scale** (Buy / Overweight / Hold / Underweight / Sell)
|
||||
introduced for the Portfolio Manager.
|
||||
- **Anthropic effort level** support for Claude models.
|
||||
- **OpenAI Responses API** path for native OpenAI models.
|
||||
|
||||
### Changed
|
||||
|
||||
- `risk_manager` renamed to `portfolio_manager` to match the role description
|
||||
shown in the CLI display.
|
||||
- Exchange-qualified tickers (e.g. `7203.T`, `BRK.B`) preserved across all
|
||||
agent prompts and tool calls.
|
||||
- Process-level UTF-8 default attempted for cross-platform consistency
|
||||
(note: this approach did not actually take effect; replaced in v0.2.4 with
|
||||
explicit per-call `encoding="utf-8"` arguments).
|
||||
|
||||
### Fixed
|
||||
|
||||
- yfinance rate-limit errors are retried with exponential backoff. (#426)
|
||||
- HTTP client SSL customisation is supported for environments that need
|
||||
custom certificate bundles. (#379)
|
||||
- Report-section writes handle list-of-string content gracefully.
|
||||
|
||||
### Contributors
|
||||
|
||||
- [@CadeYu](https://github.com/CadeYu) — exchange-qualified ticker preservation (#413)
|
||||
- [@yang1002378395-cmyk](https://github.com/yang1002378395-cmyk) — HTTP client SSL customisation (#379)
|
||||
|
||||
## [0.2.1] — 2026-03-15
|
||||
|
||||
### Security
|
||||
|
||||
- Patched `langchain-core` vulnerability (LangGrinch). (#335)
|
||||
- Removed `chainlit` dependency affected by CVE-2026-22218.
|
||||
|
||||
### Added
|
||||
|
||||
- `pyproject.toml` build-system configuration; the project now installs via
|
||||
modern packaging tooling.
|
||||
|
||||
### Removed
|
||||
|
||||
- `setup.py` — dependencies consolidated to `pyproject.toml`.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Risk manager reads the correct fundamental report source. (#341)
|
||||
- All `open()` calls receive an explicit UTF-8 encoding (initial pass).
|
||||
- `get_indicators` tool handles comma-separated indicator names from the LLM. (#368)
|
||||
- `Propagation` initialises every debate-state field so risk debaters never
|
||||
see missing keys.
|
||||
- Stock data parsing tolerates malformed CSVs and NaN values.
|
||||
- Conditional debate logic respects the configured round count. (#361)
|
||||
|
||||
### Contributors
|
||||
|
||||
- [@RinZ27](https://github.com/RinZ27) — `langchain-core` security patch (#335)
|
||||
- [@Ljx-007](https://github.com/Ljx-007) — risk manager fundamental-report fix (#341)
|
||||
- [@makk9](https://github.com/makk9) — debate-rounds config issue (#361)
|
||||
|
||||
## [0.2.0] — 2026-02-04
|
||||
|
||||
This is the largest release since the initial public version. The framework
|
||||
moved from single-provider to a multi-provider architecture and grew several
|
||||
production-ready surfaces.
|
||||
|
||||
### Added
|
||||
|
||||
- **Multi-provider LLM support** (OpenAI, Google, Anthropic, xAI, OpenRouter,
|
||||
Ollama) via a factory pattern, with provider-specific thinking configurations.
|
||||
- **Alpha Vantage** integration as a configurable primary data provider, with
|
||||
yfinance as a community-stability fallback.
|
||||
- **Footer statistics** in the CLI: real-time tracking of LLM calls, tool
|
||||
calls, and token usage via LangChain callbacks.
|
||||
- **Post-analysis report saving** — the framework writes per-section markdown
|
||||
files (analyst reports, debate transcripts, final decision) when a run
|
||||
completes.
|
||||
- **Announcements panel** — fetches updates from `api.tauric.ai/v1/announcements`
|
||||
for the CLI welcome screen.
|
||||
- **Tool fallbacks** so a single vendor outage does not stop the pipeline.
|
||||
|
||||
### Changed
|
||||
|
||||
- Risky / Safe risk debaters renamed to **Aggressive / Conservative** for
|
||||
consistency with the displayed agent labels.
|
||||
- Default data vendor switched to balance reliability and quota across
|
||||
community deployments.
|
||||
- Ollama and OpenRouter model lists updated; default endpoints clarified.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Analyst status tracking and message deduplication in the live display.
|
||||
- Infinite-loop guard in the agent loop; reflection and logging hardened.
|
||||
- Various data-vendor implementation bugs and tool-signature mismatches.
|
||||
|
||||
### Contributors
|
||||
|
||||
This release is the first with substantial outside contributions; many community
|
||||
PRs from late 2025 also landed here.
|
||||
|
||||
- [@luohy15](https://github.com/luohy15) — Alpha Vantage data-vendor integration (#235)
|
||||
- [@EdwardoSunny](https://github.com/EdwardoSunny) — yfinance fetching optimisations (#245)
|
||||
- [@Mirza-Samad-Ahmed-Baig](https://github.com/Mirza-Samad-Ahmed-Baig) — infinite-loop guard, reflection, and logging fixes (#89)
|
||||
- [@ZeroAct](https://github.com/ZeroAct) — saved results path support (#29)
|
||||
- [@Zhongyi-Lu](https://github.com/Zhongyi-Lu) — `.env` gitignore (#49)
|
||||
- [@csoboy](https://github.com/csoboy) — local Ollama setup (#53)
|
||||
- [@chauhang](https://github.com/chauhang) — initial Docker support attempt (#47, later reverted; the merged Docker support shipped in v0.2.4)
|
||||
|
||||
## [0.1.1] — 2025-06-07
|
||||
|
||||
### Removed
|
||||
|
||||
- Static site assets that had been bundled with v0.1.0; the public site now
|
||||
lives separately.
|
||||
|
||||
## [0.1.0] — 2025-06-05
|
||||
|
||||
### Added
|
||||
|
||||
- **Initial public release** of the TradingAgents multi-agent trading
|
||||
framework: market / sentiment / news / fundamentals analysts; bull and bear
|
||||
researchers; trader; aggressive, conservative, and neutral risk debaters;
|
||||
portfolio manager. LangGraph orchestration, yfinance data, per-agent
|
||||
BM25 memory, single-provider OpenAI integration, interactive CLI.
|
||||
|
||||
[0.2.4]: https://github.com/TauricResearch/TradingAgents/compare/v0.2.3...v0.2.4
|
||||
[0.2.3]: https://github.com/TauricResearch/TradingAgents/compare/v0.2.2...v0.2.3
|
||||
[0.2.2]: https://github.com/TauricResearch/TradingAgents/compare/v0.2.1...v0.2.2
|
||||
[0.2.1]: https://github.com/TauricResearch/TradingAgents/compare/v0.2.0...v0.2.1
|
||||
[0.2.0]: https://github.com/TauricResearch/TradingAgents/compare/v0.1.1...v0.2.0
|
||||
[0.1.1]: https://github.com/TauricResearch/TradingAgents/compare/v0.1.0...v0.1.1
|
||||
[0.1.0]: https://github.com/TauricResearch/TradingAgents/releases/tag/v0.1.0
|
||||
@@ -0,0 +1,27 @@
|
||||
FROM python:3.12-slim AS builder
|
||||
|
||||
ENV PYTHONDONTWRITEBYTECODE=1 \
|
||||
PIP_DISABLE_PIP_VERSION_CHECK=1
|
||||
|
||||
RUN python -m venv /opt/venv
|
||||
ENV PATH="/opt/venv/bin:$PATH"
|
||||
|
||||
WORKDIR /build
|
||||
COPY . .
|
||||
RUN pip install --no-cache-dir .
|
||||
|
||||
FROM python:3.12-slim
|
||||
|
||||
ENV PYTHONDONTWRITEBYTECODE=1 \
|
||||
PYTHONUNBUFFERED=1
|
||||
|
||||
COPY --from=builder /opt/venv /opt/venv
|
||||
ENV PATH="/opt/venv/bin:$PATH"
|
||||
|
||||
RUN useradd --create-home appuser
|
||||
USER appuser
|
||||
WORKDIR /home/appuser/app
|
||||
|
||||
COPY --from=builder --chown=appuser:appuser /build .
|
||||
|
||||
ENTRYPOINT ["tradingagents"]
|
||||
@@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,271 @@
|
||||
<p align="center">
|
||||
<img src="assets/TauricResearch.png" style="width: 60%; height: auto;">
|
||||
</p>
|
||||
|
||||
<div align="center" style="line-height: 1;">
|
||||
<a href="https://arxiv.org/abs/2412.20138" target="_blank"><img alt="arXiv" src="https://img.shields.io/badge/arXiv-2412.20138-B31B1B?logo=arxiv"/></a>
|
||||
<a href="https://discord.com/invite/hk9PGKShPK" target="_blank"><img alt="Discord" src="https://img.shields.io/badge/Discord-TradingResearch-7289da?logo=discord&logoColor=white&color=7289da"/></a>
|
||||
<a href="./assets/wechat.png" target="_blank"><img alt="WeChat" src="https://img.shields.io/badge/WeChat-TauricResearch-brightgreen?logo=wechat&logoColor=white"/></a>
|
||||
<a href="https://x.com/TauricResearch" target="_blank"><img alt="X Follow" src="https://img.shields.io/badge/X-TauricResearch-white?logo=x&logoColor=white"/></a>
|
||||
<br>
|
||||
<a href="https://github.com/TauricResearch/" target="_blank"><img alt="Community" src="https://img.shields.io/badge/Join_GitHub_Community-TauricResearch-14C290?logo=discourse"/></a>
|
||||
</div>
|
||||
|
||||
<div align="center">
|
||||
<!-- Keep these links. Translations will automatically update with the README. -->
|
||||
<a href="https://www.readme-i18n.com/TauricResearch/TradingAgents?lang=de">Deutsch</a> |
|
||||
<a href="https://www.readme-i18n.com/TauricResearch/TradingAgents?lang=es">Español</a> |
|
||||
<a href="https://www.readme-i18n.com/TauricResearch/TradingAgents?lang=fr">français</a> |
|
||||
<a href="https://www.readme-i18n.com/TauricResearch/TradingAgents?lang=ja">日本語</a> |
|
||||
<a href="https://www.readme-i18n.com/TauricResearch/TradingAgents?lang=ko">한국어</a> |
|
||||
<a href="https://www.readme-i18n.com/TauricResearch/TradingAgents?lang=pt">Português</a> |
|
||||
<a href="https://www.readme-i18n.com/TauricResearch/TradingAgents?lang=ru">Русский</a> |
|
||||
<a href="https://www.readme-i18n.com/TauricResearch/TradingAgents?lang=zh">中文</a>
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
# 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](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](https://arxiv.org/abs/2509.11420) released, with [Terminal](https://github.com/TauricResearch/Trading-R1) expected to land soon.
|
||||
|
||||
<div align="center">
|
||||
<a href="https://www.star-history.com/#TauricResearch/TradingAgents&Date">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=TauricResearch/TradingAgents&type=Date&theme=dark" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=TauricResearch/TradingAgents&type=Date" />
|
||||
<img alt="TradingAgents Star History" src="https://api.star-history.com/svg?repos=TauricResearch/TradingAgents&type=Date" style="width: 80%; height: auto;" />
|
||||
</picture>
|
||||
</a>
|
||||
</div>
|
||||
|
||||
> 🎉 **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!
|
||||
|
||||
<div align="center">
|
||||
|
||||
🚀 [TradingAgents](#tradingagents-framework) | ⚡ [Installation & CLI](#installation-and-cli) | 🎬 [Demo](https://www.youtube.com/watch?v=90gr5lwjIho) | 📦 [Package Usage](#tradingagents-package) | 🤝 [Contributing](#contributing) | 📄 [Citation](#citation)
|
||||
|
||||
</div>
|
||||
|
||||
## 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.
|
||||
|
||||
<p align="center">
|
||||
<img src="assets/schema.png" style="width: 100%; height: auto;">
|
||||
</p>
|
||||
|
||||
> 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.](https://tauric.ai/disclaimer/)
|
||||
|
||||
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.
|
||||
|
||||
<p align="center">
|
||||
<img src="assets/analyst.png" width="100%" style="display: inline-block; margin: 0 2%;">
|
||||
</p>
|
||||
|
||||
### 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.
|
||||
|
||||
<p align="center">
|
||||
<img src="assets/researcher.png" width="70%" style="display: inline-block; margin: 0 2%;">
|
||||
</p>
|
||||
|
||||
### 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.
|
||||
|
||||
<p align="center">
|
||||
<img src="assets/trader.png" width="70%" style="display: inline-block; margin: 0 2%;">
|
||||
</p>
|
||||
|
||||
### 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.
|
||||
|
||||
<p align="center">
|
||||
<img src="assets/risk.png" width="70%" style="display: inline-block; margin: 0 2%;">
|
||||
</p>
|
||||
|
||||
## Installation and CLI
|
||||
|
||||
### Installation
|
||||
|
||||
Clone TradingAgents:
|
||||
```bash
|
||||
git clone https://github.com/TauricResearch/TradingAgents.git
|
||||
cd TradingAgents
|
||||
```
|
||||
|
||||
Create a virtual environment in any of your favorite environment managers:
|
||||
```bash
|
||||
conda create -n tradingagents python=3.13
|
||||
conda activate tradingagents
|
||||
```
|
||||
|
||||
Install the package and its dependencies:
|
||||
```bash
|
||||
pip install .
|
||||
```
|
||||
|
||||
### Docker
|
||||
|
||||
Alternatively, run with Docker:
|
||||
```bash
|
||||
cp .env.example .env # add your API keys
|
||||
docker compose run --rm tradingagents
|
||||
```
|
||||
|
||||
For local models with Ollama:
|
||||
```bash
|
||||
docker compose --profile ollama run --rm tradingagents-ollama
|
||||
```
|
||||
|
||||
### Required APIs
|
||||
|
||||
TradingAgents supports multiple LLM providers. Set the API key for your chosen provider:
|
||||
|
||||
```bash
|
||||
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:
|
||||
```bash
|
||||
cp .env.example .env
|
||||
```
|
||||
|
||||
### CLI Usage
|
||||
|
||||
Launch the interactive CLI:
|
||||
```bash
|
||||
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.
|
||||
|
||||
<p align="center">
|
||||
<img src="assets/cli/cli_init.png" width="100%" style="display: inline-block; margin: 0 2%;">
|
||||
</p>
|
||||
|
||||
An interface will appear showing results as they load, letting you track the agent's progress as it runs.
|
||||
|
||||
<p align="center">
|
||||
<img src="assets/cli/cli_news.png" width="100%" style="display: inline-block; margin: 0 2%;">
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<img src="assets/cli/cli_transaction.png" width="100%" style="display: inline-block; margin: 0 2%;">
|
||||
</p>
|
||||
|
||||
## 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:
|
||||
|
||||
```python
|
||||
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.
|
||||
|
||||
```python
|
||||
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.
|
||||
|
||||
```bash
|
||||
tradingagents analyze --checkpoint # enable for this run
|
||||
tradingagents analyze --clear-checkpoints # reset before running
|
||||
```
|
||||
|
||||
```python
|
||||
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](https://tauric.ai/).
|
||||
|
||||
Past contributions, including code, design feedback, and bug reports, are credited per release in [`CHANGELOG.md`](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},
|
||||
}
|
||||
```
|
||||
|
After Width: | Height: | Size: 62 KiB |
|
After Width: | Height: | Size: 212 KiB |
|
After Width: | Height: | Size: 240 KiB |
|
After Width: | Height: | Size: 812 KiB |
|
After Width: | Height: | Size: 774 KiB |
|
After Width: | Height: | Size: 791 KiB |
|
After Width: | Height: | Size: 137 KiB |
|
After Width: | Height: | Size: 162 KiB |
|
After Width: | Height: | Size: 357 KiB |
|
After Width: | Height: | Size: 158 KiB |
|
After Width: | Height: | Size: 216 KiB |
@@ -0,0 +1,51 @@
|
||||
import getpass
|
||||
import requests
|
||||
from rich.console import Console
|
||||
from rich.panel import Panel
|
||||
|
||||
from cli.config import CLI_CONFIG
|
||||
|
||||
|
||||
def fetch_announcements(url: str = None, timeout: float = None) -> dict:
|
||||
"""Fetch announcements from endpoint. Returns dict with announcements and settings."""
|
||||
endpoint = url or CLI_CONFIG["announcements_url"]
|
||||
timeout = timeout or CLI_CONFIG["announcements_timeout"]
|
||||
fallback = CLI_CONFIG["announcements_fallback"]
|
||||
|
||||
try:
|
||||
response = requests.get(endpoint, timeout=timeout)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
return {
|
||||
"announcements": data.get("announcements", [fallback]),
|
||||
"require_attention": data.get("require_attention", False),
|
||||
}
|
||||
except Exception:
|
||||
return {
|
||||
"announcements": [fallback],
|
||||
"require_attention": False,
|
||||
}
|
||||
|
||||
|
||||
def display_announcements(console: Console, data: dict) -> None:
|
||||
"""Display announcements panel. Prompts for Enter if require_attention is True."""
|
||||
announcements = data.get("announcements", [])
|
||||
require_attention = data.get("require_attention", False)
|
||||
|
||||
if not announcements:
|
||||
return
|
||||
|
||||
content = "\n".join(announcements)
|
||||
|
||||
panel = Panel(
|
||||
content,
|
||||
border_style="cyan",
|
||||
padding=(1, 2),
|
||||
title="Announcements",
|
||||
)
|
||||
console.print(panel)
|
||||
|
||||
if require_attention:
|
||||
getpass.getpass("Press Enter to continue...")
|
||||
else:
|
||||
console.print()
|
||||
@@ -0,0 +1,6 @@
|
||||
CLI_CONFIG = {
|
||||
# Announcements
|
||||
"announcements_url": "https://api.tauric.ai/v1/announcements",
|
||||
"announcements_timeout": 1.0,
|
||||
"announcements_fallback": "[cyan]For more information, please visit[/cyan] [link=https://github.com/TauricResearch]https://github.com/TauricResearch[/link]",
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
from enum import Enum
|
||||
from typing import List, Optional, Dict
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class AnalystType(str, Enum):
|
||||
MARKET = "market"
|
||||
SOCIAL = "social"
|
||||
NEWS = "news"
|
||||
FUNDAMENTALS = "fundamentals"
|
||||
@@ -0,0 +1,7 @@
|
||||
|
||||
______ ___ ___ __
|
||||
/_ __/________ _____/ (_)___ ____ _/ | ____ ____ ____ / /______
|
||||
/ / / ___/ __ `/ __ / / __ \/ __ `/ /| |/ __ `/ _ \/ __ \/ __/ ___/
|
||||
/ / / / / /_/ / /_/ / / / / / /_/ / ___ / /_/ / __/ / / / /_(__ )
|
||||
/_/ /_/ \__,_/\__,_/_/_/ /_/\__, /_/ |_\__, /\___/_/ /_/\__/____/
|
||||
/____/ /____/
|
||||
@@ -0,0 +1,76 @@
|
||||
import threading
|
||||
from typing import Any, Dict, List, Union
|
||||
|
||||
from langchain_core.callbacks import BaseCallbackHandler
|
||||
from langchain_core.outputs import LLMResult
|
||||
from langchain_core.messages import AIMessage
|
||||
|
||||
|
||||
class StatsCallbackHandler(BaseCallbackHandler):
|
||||
"""Callback handler that tracks LLM calls, tool calls, and token usage."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
super().__init__()
|
||||
self._lock = threading.Lock()
|
||||
self.llm_calls = 0
|
||||
self.tool_calls = 0
|
||||
self.tokens_in = 0
|
||||
self.tokens_out = 0
|
||||
|
||||
def on_llm_start(
|
||||
self,
|
||||
serialized: Dict[str, Any],
|
||||
prompts: List[str],
|
||||
**kwargs: Any,
|
||||
) -> None:
|
||||
"""Increment LLM call counter when an LLM starts."""
|
||||
with self._lock:
|
||||
self.llm_calls += 1
|
||||
|
||||
def on_chat_model_start(
|
||||
self,
|
||||
serialized: Dict[str, Any],
|
||||
messages: List[List[Any]],
|
||||
**kwargs: Any,
|
||||
) -> None:
|
||||
"""Increment LLM call counter when a chat model starts."""
|
||||
with self._lock:
|
||||
self.llm_calls += 1
|
||||
|
||||
def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
|
||||
"""Extract token usage from LLM response."""
|
||||
try:
|
||||
generation = response.generations[0][0]
|
||||
except (IndexError, TypeError):
|
||||
return
|
||||
|
||||
usage_metadata = None
|
||||
if hasattr(generation, "message"):
|
||||
message = generation.message
|
||||
if isinstance(message, AIMessage) and hasattr(message, "usage_metadata"):
|
||||
usage_metadata = message.usage_metadata
|
||||
|
||||
if usage_metadata:
|
||||
with self._lock:
|
||||
self.tokens_in += usage_metadata.get("input_tokens", 0)
|
||||
self.tokens_out += usage_metadata.get("output_tokens", 0)
|
||||
|
||||
def on_tool_start(
|
||||
self,
|
||||
serialized: Dict[str, Any],
|
||||
input_str: str,
|
||||
**kwargs: Any,
|
||||
) -> None:
|
||||
"""Increment tool call counter when a tool starts."""
|
||||
with self._lock:
|
||||
self.tool_calls += 1
|
||||
|
||||
def get_stats(self) -> Dict[str, Any]:
|
||||
"""Return current statistics."""
|
||||
with self._lock:
|
||||
return {
|
||||
"llm_calls": self.llm_calls,
|
||||
"tool_calls": self.tool_calls,
|
||||
"tokens_in": self.tokens_in,
|
||||
"tokens_out": self.tokens_out,
|
||||
}
|
||||
@@ -0,0 +1,360 @@
|
||||
import questionary
|
||||
from typing import List, Optional, Tuple, Dict
|
||||
|
||||
from rich.console import Console
|
||||
|
||||
from cli.models import AnalystType
|
||||
from tradingagents.llm_clients.model_catalog import get_model_options
|
||||
|
||||
console = Console()
|
||||
|
||||
TICKER_INPUT_EXAMPLES = "Examples: SPY, CNC.TO, 7203.T, 0700.HK"
|
||||
|
||||
ANALYST_ORDER = [
|
||||
("Market Analyst", AnalystType.MARKET),
|
||||
("Social Media Analyst", AnalystType.SOCIAL),
|
||||
("News Analyst", AnalystType.NEWS),
|
||||
("Fundamentals Analyst", AnalystType.FUNDAMENTALS),
|
||||
]
|
||||
|
||||
|
||||
def get_ticker() -> str:
|
||||
"""Prompt the user to enter a ticker symbol."""
|
||||
ticker = questionary.text(
|
||||
f"Enter the exact ticker symbol to analyze ({TICKER_INPUT_EXAMPLES}):",
|
||||
validate=lambda x: len(x.strip()) > 0 or "Please enter a valid ticker symbol.",
|
||||
style=questionary.Style(
|
||||
[
|
||||
("text", "fg:green"),
|
||||
("highlighted", "noinherit"),
|
||||
]
|
||||
),
|
||||
).ask()
|
||||
|
||||
if not ticker:
|
||||
console.print("\n[red]No ticker symbol provided. Exiting...[/red]")
|
||||
exit(1)
|
||||
|
||||
return normalize_ticker_symbol(ticker)
|
||||
|
||||
|
||||
def normalize_ticker_symbol(ticker: str) -> str:
|
||||
"""Normalize ticker input while preserving exchange suffixes."""
|
||||
return ticker.strip().upper()
|
||||
|
||||
|
||||
def get_analysis_date() -> str:
|
||||
"""Prompt the user to enter a date in YYYY-MM-DD format."""
|
||||
import re
|
||||
from datetime import datetime
|
||||
|
||||
def validate_date(date_str: str) -> bool:
|
||||
if not re.match(r"^\d{4}-\d{2}-\d{2}$", date_str):
|
||||
return False
|
||||
try:
|
||||
datetime.strptime(date_str, "%Y-%m-%d")
|
||||
return True
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
date = questionary.text(
|
||||
"Enter the analysis date (YYYY-MM-DD):",
|
||||
validate=lambda x: validate_date(x.strip())
|
||||
or "Please enter a valid date in YYYY-MM-DD format.",
|
||||
style=questionary.Style(
|
||||
[
|
||||
("text", "fg:green"),
|
||||
("highlighted", "noinherit"),
|
||||
]
|
||||
),
|
||||
).ask()
|
||||
|
||||
if not date:
|
||||
console.print("\n[red]No date provided. Exiting...[/red]")
|
||||
exit(1)
|
||||
|
||||
return date.strip()
|
||||
|
||||
|
||||
def select_analysts() -> List[AnalystType]:
|
||||
"""Select analysts using an interactive checkbox."""
|
||||
choices = questionary.checkbox(
|
||||
"Select Your [Analysts Team]:",
|
||||
choices=[
|
||||
questionary.Choice(display, value=value) for display, value in ANALYST_ORDER
|
||||
],
|
||||
instruction="\n- Press Space to select/unselect analysts\n- Press 'a' to select/unselect all\n- Press Enter when done",
|
||||
validate=lambda x: len(x) > 0 or "You must select at least one analyst.",
|
||||
style=questionary.Style(
|
||||
[
|
||||
("checkbox-selected", "fg:green"),
|
||||
("selected", "fg:green noinherit"),
|
||||
("highlighted", "noinherit"),
|
||||
("pointer", "noinherit"),
|
||||
]
|
||||
),
|
||||
).ask()
|
||||
|
||||
if not choices:
|
||||
console.print("\n[red]No analysts selected. Exiting...[/red]")
|
||||
exit(1)
|
||||
|
||||
return choices
|
||||
|
||||
|
||||
def select_research_depth() -> int:
|
||||
"""Select research depth using an interactive selection."""
|
||||
|
||||
# Define research depth options with their corresponding values
|
||||
DEPTH_OPTIONS = [
|
||||
("Shallow - Quick research, few debate and strategy discussion rounds", 1),
|
||||
("Medium - Middle ground, moderate debate rounds and strategy discussion", 3),
|
||||
("Deep - Comprehensive research, in depth debate and strategy discussion", 5),
|
||||
]
|
||||
|
||||
choice = questionary.select(
|
||||
"Select Your [Research Depth]:",
|
||||
choices=[
|
||||
questionary.Choice(display, value=value) for display, value in DEPTH_OPTIONS
|
||||
],
|
||||
instruction="\n- Use arrow keys to navigate\n- Press Enter to select",
|
||||
style=questionary.Style(
|
||||
[
|
||||
("selected", "fg:yellow noinherit"),
|
||||
("highlighted", "fg:yellow noinherit"),
|
||||
("pointer", "fg:yellow noinherit"),
|
||||
]
|
||||
),
|
||||
).ask()
|
||||
|
||||
if choice is None:
|
||||
console.print("\n[red]No research depth selected. Exiting...[/red]")
|
||||
exit(1)
|
||||
|
||||
return choice
|
||||
|
||||
|
||||
def _fetch_openrouter_models() -> List[Tuple[str, str]]:
|
||||
"""Fetch available models from the OpenRouter API."""
|
||||
import requests
|
||||
try:
|
||||
resp = requests.get("https://openrouter.ai/api/v1/models", timeout=10)
|
||||
resp.raise_for_status()
|
||||
models = resp.json().get("data", [])
|
||||
return [(m.get("name") or m["id"], m["id"]) for m in models]
|
||||
except Exception as e:
|
||||
console.print(f"\n[yellow]Could not fetch OpenRouter models: {e}[/yellow]")
|
||||
return []
|
||||
|
||||
|
||||
def select_openrouter_model() -> str:
|
||||
"""Select an OpenRouter model from the newest available, or enter a custom ID."""
|
||||
models = _fetch_openrouter_models()
|
||||
|
||||
choices = [questionary.Choice(name, value=mid) for name, mid in models[:5]]
|
||||
choices.append(questionary.Choice("Custom model ID", value="custom"))
|
||||
|
||||
choice = questionary.select(
|
||||
"Select OpenRouter Model (latest available):",
|
||||
choices=choices,
|
||||
instruction="\n- Use arrow keys to navigate\n- Press Enter to select",
|
||||
style=questionary.Style([
|
||||
("selected", "fg:magenta noinherit"),
|
||||
("highlighted", "fg:magenta noinherit"),
|
||||
("pointer", "fg:magenta noinherit"),
|
||||
]),
|
||||
).ask()
|
||||
|
||||
if choice is None or choice == "custom":
|
||||
return questionary.text(
|
||||
"Enter OpenRouter model ID (e.g. google/gemma-4-26b-a4b-it):",
|
||||
validate=lambda x: len(x.strip()) > 0 or "Please enter a model ID.",
|
||||
).ask().strip()
|
||||
|
||||
return choice
|
||||
|
||||
|
||||
def _prompt_custom_model_id() -> str:
|
||||
"""Prompt user to type a custom model ID."""
|
||||
return questionary.text(
|
||||
"Enter model ID:",
|
||||
validate=lambda x: len(x.strip()) > 0 or "Please enter a model ID.",
|
||||
).ask().strip()
|
||||
|
||||
|
||||
def _select_model(provider: str, mode: str) -> str:
|
||||
"""Select a model for the given provider and mode (quick/deep)."""
|
||||
if provider.lower() == "openrouter":
|
||||
return select_openrouter_model()
|
||||
|
||||
if provider.lower() == "azure":
|
||||
return questionary.text(
|
||||
f"Enter Azure deployment name ({mode}-thinking):",
|
||||
validate=lambda x: len(x.strip()) > 0 or "Please enter a deployment name.",
|
||||
).ask().strip()
|
||||
|
||||
choice = questionary.select(
|
||||
f"Select Your [{mode.title()}-Thinking LLM Engine]:",
|
||||
choices=[
|
||||
questionary.Choice(display, value=value)
|
||||
for display, value in get_model_options(provider, mode)
|
||||
],
|
||||
instruction="\n- Use arrow keys to navigate\n- Press Enter to select",
|
||||
style=questionary.Style(
|
||||
[
|
||||
("selected", "fg:magenta noinherit"),
|
||||
("highlighted", "fg:magenta noinherit"),
|
||||
("pointer", "fg:magenta noinherit"),
|
||||
]
|
||||
),
|
||||
).ask()
|
||||
|
||||
if choice is None:
|
||||
console.print(f"\n[red]No {mode} thinking llm engine selected. Exiting...[/red]")
|
||||
exit(1)
|
||||
|
||||
if choice == "custom":
|
||||
return _prompt_custom_model_id()
|
||||
|
||||
return choice
|
||||
|
||||
|
||||
def select_shallow_thinking_agent(provider) -> str:
|
||||
"""Select shallow thinking llm engine using an interactive selection."""
|
||||
return _select_model(provider, "quick")
|
||||
|
||||
|
||||
def select_deep_thinking_agent(provider) -> str:
|
||||
"""Select deep thinking llm engine using an interactive selection."""
|
||||
return _select_model(provider, "deep")
|
||||
|
||||
def select_llm_provider() -> tuple[str, str | None]:
|
||||
"""Select the LLM provider and its API endpoint."""
|
||||
# (display_name, provider_key, base_url)
|
||||
PROVIDERS = [
|
||||
("OpenAI", "openai", "https://api.openai.com/v1"),
|
||||
("Google", "google", None),
|
||||
("Anthropic", "anthropic", "https://api.anthropic.com/"),
|
||||
("xAI", "xai", "https://api.x.ai/v1"),
|
||||
("DeepSeek", "deepseek", "https://api.deepseek.com"),
|
||||
("Qwen", "qwen", "https://dashscope.aliyuncs.com/compatible-mode/v1"),
|
||||
("GLM", "glm", "https://open.bigmodel.cn/api/paas/v4/"),
|
||||
("OpenRouter", "openrouter", "https://openrouter.ai/api/v1"),
|
||||
("Azure OpenAI", "azure", None),
|
||||
("Ollama", "ollama", "http://localhost:11434/v1"),
|
||||
]
|
||||
|
||||
choice = questionary.select(
|
||||
"Select your LLM Provider:",
|
||||
choices=[
|
||||
questionary.Choice(display, value=(provider_key, url))
|
||||
for display, provider_key, url in PROVIDERS
|
||||
],
|
||||
instruction="\n- Use arrow keys to navigate\n- Press Enter to select",
|
||||
style=questionary.Style(
|
||||
[
|
||||
("selected", "fg:magenta noinherit"),
|
||||
("highlighted", "fg:magenta noinherit"),
|
||||
("pointer", "fg:magenta noinherit"),
|
||||
]
|
||||
),
|
||||
).ask()
|
||||
|
||||
if choice is None:
|
||||
console.print("\n[red]No LLM provider selected. Exiting...[/red]")
|
||||
exit(1)
|
||||
|
||||
provider, url = choice
|
||||
return provider, url
|
||||
|
||||
|
||||
def ask_openai_reasoning_effort() -> str:
|
||||
"""Ask for OpenAI reasoning effort level."""
|
||||
choices = [
|
||||
questionary.Choice("Medium (Default)", "medium"),
|
||||
questionary.Choice("High (More thorough)", "high"),
|
||||
questionary.Choice("Low (Faster)", "low"),
|
||||
]
|
||||
return questionary.select(
|
||||
"Select Reasoning Effort:",
|
||||
choices=choices,
|
||||
style=questionary.Style([
|
||||
("selected", "fg:cyan noinherit"),
|
||||
("highlighted", "fg:cyan noinherit"),
|
||||
("pointer", "fg:cyan noinherit"),
|
||||
]),
|
||||
).ask()
|
||||
|
||||
|
||||
def ask_anthropic_effort() -> str | None:
|
||||
"""Ask for Anthropic effort level.
|
||||
|
||||
Controls token usage and response thoroughness on Claude 4.5+ and 4.6 models.
|
||||
"""
|
||||
return questionary.select(
|
||||
"Select Effort Level:",
|
||||
choices=[
|
||||
questionary.Choice("High (recommended)", "high"),
|
||||
questionary.Choice("Medium (balanced)", "medium"),
|
||||
questionary.Choice("Low (faster, cheaper)", "low"),
|
||||
],
|
||||
style=questionary.Style([
|
||||
("selected", "fg:cyan noinherit"),
|
||||
("highlighted", "fg:cyan noinherit"),
|
||||
("pointer", "fg:cyan noinherit"),
|
||||
]),
|
||||
).ask()
|
||||
|
||||
|
||||
def ask_gemini_thinking_config() -> str | None:
|
||||
"""Ask for Gemini thinking configuration.
|
||||
|
||||
Returns thinking_level: "high" or "minimal".
|
||||
Client maps to appropriate API param based on model series.
|
||||
"""
|
||||
return questionary.select(
|
||||
"Select Thinking Mode:",
|
||||
choices=[
|
||||
questionary.Choice("Enable Thinking (recommended)", "high"),
|
||||
questionary.Choice("Minimal/Disable Thinking", "minimal"),
|
||||
],
|
||||
style=questionary.Style([
|
||||
("selected", "fg:green noinherit"),
|
||||
("highlighted", "fg:green noinherit"),
|
||||
("pointer", "fg:green noinherit"),
|
||||
]),
|
||||
).ask()
|
||||
|
||||
|
||||
def ask_output_language() -> str:
|
||||
"""Ask for report output language."""
|
||||
choice = questionary.select(
|
||||
"Select Output Language:",
|
||||
choices=[
|
||||
questionary.Choice("English (default)", "English"),
|
||||
questionary.Choice("Chinese (中文)", "Chinese"),
|
||||
questionary.Choice("Japanese (日本語)", "Japanese"),
|
||||
questionary.Choice("Korean (한국어)", "Korean"),
|
||||
questionary.Choice("Hindi (हिन्दी)", "Hindi"),
|
||||
questionary.Choice("Spanish (Español)", "Spanish"),
|
||||
questionary.Choice("Portuguese (Português)", "Portuguese"),
|
||||
questionary.Choice("French (Français)", "French"),
|
||||
questionary.Choice("German (Deutsch)", "German"),
|
||||
questionary.Choice("Arabic (العربية)", "Arabic"),
|
||||
questionary.Choice("Russian (Русский)", "Russian"),
|
||||
questionary.Choice("Custom language", "custom"),
|
||||
],
|
||||
style=questionary.Style([
|
||||
("selected", "fg:yellow noinherit"),
|
||||
("highlighted", "fg:yellow noinherit"),
|
||||
("pointer", "fg:yellow noinherit"),
|
||||
]),
|
||||
).ask()
|
||||
|
||||
if choice == "custom":
|
||||
return questionary.text(
|
||||
"Enter language name (e.g. Turkish, Vietnamese, Thai, Indonesian):",
|
||||
validate=lambda x: len(x.strip()) > 0 or "Please enter a language name.",
|
||||
).ask().strip()
|
||||
|
||||
return choice
|
||||
@@ -0,0 +1,35 @@
|
||||
services:
|
||||
tradingagents:
|
||||
build: .
|
||||
env_file:
|
||||
- .env
|
||||
volumes:
|
||||
- tradingagents_data:/home/appuser/.tradingagents
|
||||
tty: true
|
||||
stdin_open: true
|
||||
|
||||
ollama:
|
||||
image: ollama/ollama:latest
|
||||
volumes:
|
||||
- ollama_data:/root/.ollama
|
||||
profiles:
|
||||
- ollama
|
||||
|
||||
tradingagents-ollama:
|
||||
build: .
|
||||
env_file:
|
||||
- .env
|
||||
environment:
|
||||
- LLM_PROVIDER=ollama
|
||||
volumes:
|
||||
- tradingagents_data:/home/appuser/.tradingagents
|
||||
depends_on:
|
||||
- ollama
|
||||
tty: true
|
||||
stdin_open: true
|
||||
profiles:
|
||||
- ollama
|
||||
|
||||
volumes:
|
||||
tradingagents_data:
|
||||
ollama_data:
|
||||
@@ -0,0 +1,471 @@
|
||||
# TradingAgents 技术架构分析及 akshare 集成修改
|
||||
|
||||
> **文档时间**: 2026-05-05
|
||||
> **项目路径**: `/home/ubuntu/forgithub/TradingAgents`
|
||||
> **运行端口**: `:8500` (Web UI)
|
||||
|
||||
---
|
||||
|
||||
## 一、项目概述
|
||||
|
||||
TradingAgents 是一个基于 LLM 的多智能体(Multi-Agent)金融交易分析框架。它模拟真实投资决策中的"研究员→辩论→交易员"流程,由多个分析师角色协作完成对单只股票的深入分析,并输出最终交易决策(买入/卖出/持有)。
|
||||
|
||||
核心思想:**用 LLM 扮演不同角色的分析师,使用真实市场数据工具,通过辩论机制达成投资共识。**
|
||||
|
||||
---
|
||||
|
||||
## 二、技术栈
|
||||
|
||||
| 层次 | 技术选型 |
|
||||
|------|----------|
|
||||
| 多智能体编排 | LangGraph(StateGraph) |
|
||||
| LLM 接口 | LangChain + DeepSeek / OpenAI |
|
||||
| 工具系统 | LangChain `@tool` 装饰器 |
|
||||
| 数据源 | akshare / yfinance / Alpha Vantage |
|
||||
| Web 服务 | FastAPI + 自定义 SPA 页面 |
|
||||
| 部署 | systemd(`tradingagents.service`) |
|
||||
|
||||
---
|
||||
|
||||
## 三、架构分层
|
||||
|
||||
### 3.1 整体流程
|
||||
|
||||
```
|
||||
用户输入 (ticker + date)
|
||||
│
|
||||
▼
|
||||
┌──────────────────────┐
|
||||
│ TradingAgentsGraph │ ← LangGraph StateGraph
|
||||
│ (trading_graph.py) │
|
||||
└──────┬───────────────┘
|
||||
│
|
||||
▼
|
||||
┌───────────────────────────────────────┐
|
||||
│ Researcher Team │
|
||||
│ ┌──────────┐ ┌──────────┐ │
|
||||
│ │ Market │ │ News │ ... │ ← 并行分析
|
||||
│ │ Analyst │ │ Analyst │ │
|
||||
│ └────┬─────┘ └────┬─────┘ │
|
||||
│ │ │ │
|
||||
│ └─────┬──────┘ │
|
||||
│ ▼ │
|
||||
│ Debate Layer (1~N rounds) │ ← 多轮辩论
|
||||
│ │ │
|
||||
│ ▼ │
|
||||
│ Final Decision │
|
||||
│ (Buy/Sell/Hold) │
|
||||
└───────────────────────────────────────┘
|
||||
│
|
||||
▼
|
||||
输出:分析报告 + 交易决策
|
||||
```
|
||||
|
||||
### 3.2 节点说明
|
||||
|
||||
| 节点 | 文件 | 角色 | 使用的工具 |
|
||||
|------|------|------|-----------|
|
||||
| **Market Analyst** | `analysts/market_analyst.py` | 技术面分析师 | `get_stock_data`, `get_indicators` (RSI, MACD, 布林带等 19 项指标) |
|
||||
| **News Analyst** | `analysts/news_analyst.py` | 宏观新闻分析师 | `get_news`, `get_global_news` |
|
||||
| **Social Media Analyst** | `analysts/social_media_analyst.py` | 社交媒体分析师 | `get_news` |
|
||||
| **Fundamentals Analyst** | `analysts/fundamentals_analyst.py` | 基本面分析师 | `get_fundamentals`, `get_balance_sheet`, `get_cashflow`, `get_income_statement` |
|
||||
| **Debate Layer** | `trading_graph.py` | 多智能体辩论 | 各分析师报告交叉辩论 |
|
||||
| **Final Decision** | `trading_graph.py` | 最终交易决策 | 综合所有报告和辩论结果 |
|
||||
|
||||
### 3.3 数据流
|
||||
|
||||
```
|
||||
每个 Analyst 节点
|
||||
│
|
||||
├─ 构造 system prompt + 数据查询指令
|
||||
├─ 通过 LangChain tool 调用 route_to_vendor()
|
||||
├─ route_to_vendor 按优先级选择数据源
|
||||
│ ├─ akshare (默认)
|
||||
│ ├─ yfinance (fallback)
|
||||
│ └─ alpha_vantage (fallback)
|
||||
└─ 返回格式化数据,LLM 生成分析报告
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 四、核心模块
|
||||
|
||||
### 4.1 Graph 编排层
|
||||
|
||||
**文件**: `tradingagents/graph/trading_graph.py`
|
||||
|
||||
- 基于 LangGraph `StateGraph` 构建
|
||||
- `setup_graph()` 按选定的分析师列表动态添加节点
|
||||
- 支持配置 `max_debate_rounds`(默认 1 轮,可多轮辩论)
|
||||
- 输出最终状态和交易决策
|
||||
|
||||
**文件**: `tradingagents/graph/setup.py`
|
||||
|
||||
- 提供 `create_complete_graph()` 工厂函数
|
||||
- 封装完整流程:研究员 → 辩论 → 终判
|
||||
|
||||
### 4.2 工具层
|
||||
|
||||
**文件**: `tradingagents/agents/utils/agent_utils.py`
|
||||
|
||||
- `create_completion()` — LLM 调用封装,支持 reasoning_effort 参数
|
||||
- `ToolKit` — 工具集管理,按分析师类型分发工具
|
||||
|
||||
**工具定义文件**(位于 `agents/utils/`):
|
||||
|
||||
| 文件 | 包含工具 |
|
||||
|------|---------|
|
||||
| `core_stock_tools.py` | `get_stock_data` |
|
||||
| `technical_indicators_tools.py` | `get_indicators` (19 项技术指标) |
|
||||
| `fundamental_data_tools.py` | `get_fundamentals`, `get_balance_sheet`, `get_cashflow`, `get_income_statement` |
|
||||
| `news_data_tools.py` | `get_news`, `get_global_news`, `get_insider_transactions` |
|
||||
|
||||
所有工具统一通过 `route_to_vendor(method, *args)` 调用,实现数据源透明切换。
|
||||
|
||||
### 4.3 数据源层
|
||||
|
||||
**入口**: `tradingagents/dataflows/interface.py`
|
||||
|
||||
```
|
||||
route_to_vendor(method, *args)
|
||||
│
|
||||
├─ 读取 config["data_vendors"] 确定主数据源
|
||||
├─ 按 fallback 链依次尝试:
|
||||
│ ├─ akshare (优先级最高)
|
||||
│ ├─ yfinance
|
||||
│ └─ alpha_vantage
|
||||
└─ 返回第一个成功结果
|
||||
```
|
||||
|
||||
**配置系统**: `tradingagents/dataflows/config.py` + `tradingagents/default_config.py`
|
||||
|
||||
- `default_config.py` 定义全局默认配置
|
||||
- `config.py` 提供运行时 `get_config()` / `set_config()` 接口
|
||||
- 可通过 `set_config({"data_vendors": {"...": "akshare"}})` 动态切换
|
||||
|
||||
### 4.4 Web 服务层
|
||||
|
||||
**文件**: `web_server.py`
|
||||
|
||||
- FastAPI 应用,端口 `8500`
|
||||
- `POST /api/analyze` — 提交分析任务(后台异步执行)
|
||||
- `GET /api/task/{task_id}` — 查询任务状态
|
||||
- `GET /` — 内置 Web 面板(`web.html`)
|
||||
|
||||
---
|
||||
|
||||
## 五、akshare 集成修改(详细改动点)
|
||||
|
||||
### 5.1 修改动机
|
||||
|
||||
原始项目的默认数据源是 `yfinance`,存在以下问题:
|
||||
|
||||
1. **国内访问不稳定**: yfinance 对非美股数据支持有限,频繁触发 Rate Limit
|
||||
2. **A 股数据质量差**: yfinance 的 A 股 OHLCV 数据常常缺失或不准确
|
||||
3. **新闻源偏西式**: yfinance 的新闻来源主要是英文媒体,对 A 股分析不友好
|
||||
4. **无国内数据源**: 缺少针对中国市场的本地化数据适配
|
||||
|
||||
**解决方案**: 集成 **akshare**(国内开源金融数据接口库)作为主数据源,yfinance 降级为 fallback。
|
||||
|
||||
### 5.2 文件变更清单
|
||||
|
||||
| 文件 | 类型 | 行数 | 说明 |
|
||||
|------|------|------|------|
|
||||
| `tradingagents/dataflows/akshare_data.py` | **新增** | 563 | A股/港股/美股行情、财务数据、技术指标适配 |
|
||||
| `tradingagents/dataflows/akshare_news.py` | **新增** | 165 | 个股新闻(东方财富)、全球新闻(CCTV)适配 |
|
||||
| `tradingagents/dataflows/interface.py` | **修改** | +22 | 注册 akshare 到 VENDOR_METHODS,调优 fallback 顺序 |
|
||||
| `tradingagents/default_config.py` | **修改** | +14/-8 | 默认 vendor 改为 akshare |
|
||||
| `web_server.py` | **新增** | 124 | FastAPI Web 服务 + 后台任务 |
|
||||
| `web.html` | **新增** | 480 | 前端分析面板 |
|
||||
|
||||
### 5.3 akshare_data.py 详细设计
|
||||
|
||||
#### 5.3.1 市场检测
|
||||
|
||||
```python
|
||||
def _detect_market(symbol: str) -> str:
|
||||
"""自动识别股票所属市场"""
|
||||
# 6位数字 → A股上海/深圳
|
||||
# 5位数字 → 港股
|
||||
# 字母 → 美股
|
||||
```
|
||||
|
||||
通过 ticker 格式自动路由到正确的 akshare 接口:
|
||||
- `600xxx` / `000xxx` / `300xxx` → A 股(`ak.stock_zh_a_hist`)
|
||||
- `00700` / `09988` → 港股(`ak.stock_hk_hist`)
|
||||
- `AAPL` / `MSFT` / `TSLA` → 美股(`ak.stock_us_hist`)
|
||||
|
||||
#### 5.3.2 实现的接口
|
||||
|
||||
| 接口 | 签名 | akshare 函数 | 说明 |
|
||||
|------|------|-------------|------|
|
||||
| `get_stock_data` | `(symbol, start_date, end_date)` | `stock_zh_a_hist` / `stock_hk_hist` / `stock_us_hist` | 三市场统一 OHLCV 数据 |
|
||||
| `get_indicators` | `(symbol, indicator, curr_date, look_back_days)` | `stock_zh_a_hist` + 手动计算 | 19 项技术指标(RSI/MACD/布林带等) |
|
||||
| `get_fundamentals` | `(ticker, curr_date)` | `stock_individual_info_em` | 公司概况/市盈率/市净率等 |
|
||||
| `get_balance_sheet` | `(ticker, freq, curr_date)` | `stock_balance_sheet_by_report_em` | 资产负债表(年报/季报) |
|
||||
| `get_cashflow` | `(ticker, freq, curr_date)` | `stock_cash_flow_sheet_by_report_em` | 现金流量表 |
|
||||
| `get_income_statement` | `(ticker, freq, curr_date)` | `stock_profit_sheet_by_report_em` | 利润表 |
|
||||
| `get_insider_transactions` | `(ticker)` | — | 抛出异常触发 fallback 到 yfinance |
|
||||
|
||||
#### 5.3.3 技术指标计算实现
|
||||
|
||||
采用**原始公式重算**而非依赖第三方库,确保数据一致性:
|
||||
|
||||
```
|
||||
rsi → 100 - (100 / (1 + RS)) [平均涨跌幅比值法]
|
||||
macd → EMA(12) - EMA(26), Signal=EMA(9) [指数加权移动平均]
|
||||
bb → MA ± 2*STD [布林带]
|
||||
atr → TR 的 Wilder 平滑 [真实波幅]
|
||||
sma_20 → MA(20)
|
||||
ema_20 → EMA(20)
|
||||
```
|
||||
|
||||
共支持 19 项常用技术指标,覆盖趋势类、动量类、波动类、成交量类。
|
||||
|
||||
#### 5.3.4 输出格式
|
||||
|
||||
所有接口返回统一格式:**Pandas DataFrame → Markdown 表格字符串**,与 yfinance 适配器输出格式一致,保证 LLM 可正常解析。
|
||||
|
||||
```markdown
|
||||
| Date | Open | High | Low | Close | Volume |
|
||||
|------------|--------|--------|--------|--------|-----------|
|
||||
| 2026-04-25 | 12.50 | 12.80 | 12.30 | 12.65 | 12345678 |
|
||||
```
|
||||
|
||||
#### 5.3.5 TQDM 噪音抑制
|
||||
|
||||
akshare 内部使用 tqdm 显示进度条,在 LLM 工具调用场景中会产生大量噪音输出。通过在 akshare import 之前设置环境变量解决:
|
||||
|
||||
```python
|
||||
os.environ.setdefault('TQDM_DISABLE', '1')
|
||||
import akshare as ak
|
||||
```
|
||||
|
||||
### 5.4 akshare_news.py 详细设计
|
||||
|
||||
#### 5.4.1 实现的接口
|
||||
|
||||
| 接口 | 说明 | 数据来源 |
|
||||
|------|------|---------|
|
||||
| `get_news(ticker, start_date, end_date)` | 个股新闻 | `ak.stock_news_em`(东方财富) |
|
||||
| `get_global_news(curr_date, look_back_days, limit)` | 宏观/全球新闻 | `ak.news_cctv`(CCTV 新闻联播) |
|
||||
|
||||
#### 5.4.2 Ticker 规范化
|
||||
|
||||
```
|
||||
600362 → 600362 (A股,不变)
|
||||
000001 → 000001 (A股,不变)
|
||||
AAPL → AAPL (美股,不变)
|
||||
→ 回退到原 ticker
|
||||
```
|
||||
|
||||
#### 5.4.3 东方财富新闻接口特点
|
||||
|
||||
- 返回 15 天内个股相关新闻,含标题、发布时间、来源
|
||||
- 自动按日期过滤,限制返回最近 50 条
|
||||
- 格式化输出为 Markdown 表格,便于 LLM 分析
|
||||
|
||||
#### 5.4.4 CCTV 新闻接口特点
|
||||
|
||||
- 获取新闻联播文字稿摘要
|
||||
- 适合宏观政策面分析
|
||||
- 输出为时间线格式的文本列表
|
||||
|
||||
### 5.5 interface.py 修改详情
|
||||
|
||||
#### 5.5.1 VENDOR_METHODS 注册
|
||||
|
||||
为以下 9 个方法注册了 akshare 实现:
|
||||
|
||||
```python
|
||||
VENDOR_METHODS = {
|
||||
"get_stock_data": {"akshare": ..., "yfinance": ..., "alpha_vantage": ...},
|
||||
"get_indicators": {"akshare": ..., "yfinance": ...},
|
||||
"get_fundamentals": {"akshare": ..., "yfinance": ..., "alpha_vantage": ...},
|
||||
"get_balance_sheet": {"akshare": ..., "yfinance": ..., "alpha_vantage": ...},
|
||||
"get_cashflow": {"akshare": ..., "yfinance": ..., "alpha_vantage": ...},
|
||||
"get_income_statement": {"akshare": ..., "yfinance": ..., "alpha_vantage": ...},
|
||||
"get_news": {"akshare": ..., "yfinance": ...},
|
||||
"get_global_news": {"akshare": ..., "yfinance": ...},
|
||||
"get_insider_transactions": {"akshare": ..., "yfinance": ..., "alpha_vantage": ...},
|
||||
}
|
||||
```
|
||||
|
||||
#### 5.5.2 Fallback 顺序优化
|
||||
|
||||
`get_insider_transactions` 的字典键顺序调整为 **akshare → yfinance → alpha_vantage**:
|
||||
|
||||
```
|
||||
原始顺序: alpha_vantage → yfinance → [无 akshare]
|
||||
修改后: akshare → yfinance → alpha_vantage
|
||||
```
|
||||
|
||||
原因:如果 alpha_vantage 排在 yfinance 之前,当 akshare 不支持时,会先尝试 alpha_vantage —— 它的 `get_api_key()` 在无 API key 时会抛出 `ValueError`(非 `AlphaVantageRateLimitError`),导致异常直接传播、不会继续尝试 yfinance。
|
||||
|
||||
调整后 fallback 路径:
|
||||
1. `akshare` → 抛出 `AlphaVantageRateLimitError`(触发 fallback)
|
||||
2. `yfinance` → 获取数据(成功)✓
|
||||
|
||||
#### 5.5.3 数据源分类优化
|
||||
|
||||
将 akshare 明确归入 `all_available_vendors`,确保它在所有 `data_vendors` 分类组中可用:
|
||||
|
||||
```python
|
||||
all_available_vendors = ["akshare", "yfinance", "alpha_vantage"]
|
||||
```
|
||||
|
||||
### 5.6 default_config.py 修改
|
||||
|
||||
```python
|
||||
# 修改前
|
||||
"data_vendors": {
|
||||
"core_stock_data": {"primary": "yfinance"},
|
||||
"technical_indicators": {"primary": "yfinance"},
|
||||
"fundamental_data": {"primary": "yfinance"},
|
||||
"news_data": {"primary": "yfinance"},
|
||||
}
|
||||
|
||||
# 修改后
|
||||
"data_vendors": {
|
||||
"core_stock_data": {"primary": "akshare"},
|
||||
"technical_indicators": {"primary": "akshare"},
|
||||
"fundamental_data": {"primary": "akshare"},
|
||||
"news_data": {"primary": "akshare"},
|
||||
}
|
||||
```
|
||||
|
||||
效果:所有分析请求默认走 akshare,彻底避免 yfinance Rate Limit 问题。
|
||||
|
||||
### 5.7 web_server.py 设计
|
||||
|
||||
#### 5.7.1 API 端点
|
||||
|
||||
| 方法 | 路径 | 说明 |
|
||||
|------|------|------|
|
||||
| GET | `/` | Web 分析面板(`web.html`) |
|
||||
| GET | `/api/health` | 健康检查 |
|
||||
| POST | `/api/analyze` | 提交分析任务,返回 task_id |
|
||||
| GET | `/api/task/{task_id}` | 查询任务状态和结果 |
|
||||
|
||||
#### 5.7.2 异步任务机制
|
||||
|
||||
```python
|
||||
class AnalysisRequest(BaseModel):
|
||||
ticker: str # 股票代码
|
||||
date: Optional[str] # 分析日期,默认今天
|
||||
analysts: Optional[list] # 分析师列表,默认 ["market", "news"]
|
||||
max_debate_rounds: int # 辩论轮次,默认 1
|
||||
```
|
||||
|
||||
分析流程在 `BackgroundTasks` 中异步执行,通过线程安全的 `tasks_store` 字典管理任务状态。
|
||||
|
||||
### 5.8 web.html 设计
|
||||
|
||||
- 纯原生 HTML/CSS/JS 单页应用
|
||||
- 响应式设计,支持移动端
|
||||
- 输入框:股票代码 + 日期 + 分析师选择 + 辩论轮次
|
||||
- 实时轮询任务状态(每 3 秒)
|
||||
- 结果展示:Markdown 渲染的交易决策和分析报告(使用 marked.js)
|
||||
- 适配 DeepSeek 推理过程的 `reasoning_content` 展示
|
||||
|
||||
---
|
||||
|
||||
## 六、部署架构
|
||||
|
||||
```
|
||||
http://129.211.173.87:8500/
|
||||
│
|
||||
┌────────┴────────┐
|
||||
│ web_server.py │
|
||||
│ (FastAPI) │
|
||||
│ port :8500 │
|
||||
└────────┬────────┘
|
||||
│
|
||||
┌────────┴────────┐
|
||||
│ TradingAgents │
|
||||
│ Graph │
|
||||
│ (LangGraph) │
|
||||
└──────┬─────────┘
|
||||
│
|
||||
┌───────────┼───────────┐
|
||||
▼ ▼ ▼
|
||||
┌─────────┐ ┌─────────┐ ┌─────────┐
|
||||
│ akshare │ │yfinance │ │ alpha │
|
||||
│ (主要) │ │(备用1) │ │vantage │
|
||||
└─────────┘ └─────────┘ └─────────┘
|
||||
```
|
||||
|
||||
- **进程管理**: systemd `tradingagents.service`
|
||||
- **LLM 后端**: DeepSeek(通过 `DEEPSEEK_API_KEY` 环境变量)
|
||||
- **数据源**: akshare(默认,国内数据丰富)+ yfinance(fallback,美股内部交易等场景)
|
||||
|
||||
---
|
||||
|
||||
## 七、修改前后对比
|
||||
|
||||
| 维度 | 修改前 | 修改后 |
|
||||
|------|--------|--------|
|
||||
| **默认数据源** | yfinance | **akshare** |
|
||||
| **A 股行情** | 不稳定,频繁 Rate Limit | ✅ 稳定,无限制 |
|
||||
| **A 股财务数据** | ❌ 不可用 | ✅ 完整(资产负债表/利润表/现金流) |
|
||||
| **技术指标** | 依赖 yfinance 返回 | ✅ 原始公式重算,19 项指标 |
|
||||
| **个股新闻** | 英文来源,A 股覆盖差 | ✅ 东方财富,中文,时效性强 |
|
||||
| **宏观新闻** | 英文来源 | ✅ CCTV 新闻联播,政策面 |
|
||||
| **港股支持** | 部分 | ✅ 完整 |
|
||||
| **Rate Limit** | 频繁触发 | ✅ 已消除 |
|
||||
| **内部交易** | yfinance | akshare 自动 fallback 到 yfinance |
|
||||
| **Web UI** | ❌ 无 | ✅ 新增 FastAPI + Web 面板 |
|
||||
| **任务异步** | ❌ 无 | ✅ 后台任务 + 状态查询 |
|
||||
| **TQDM 噪音** | — | ✅ 已抑制 |
|
||||
|
||||
---
|
||||
|
||||
## 八、项目目录结构
|
||||
|
||||
```
|
||||
TradingAgents/
|
||||
├── tradingagents/
|
||||
│ ├── agents/
|
||||
│ │ ├── analysts/ # 四个分析师角色
|
||||
│ │ │ ├── fundamentals_analyst.py
|
||||
│ │ │ ├── market_analyst.py
|
||||
│ │ │ ├── news_analyst.py
|
||||
│ │ │ └── social_media_analyst.py
|
||||
│ │ └── utils/ # 工具定义和 LLM 封装
|
||||
│ │ ├── agent_utils.py # LLM 调用 + ToolKit
|
||||
│ │ ├── core_stock_tools.py # get_stock_data
|
||||
│ │ ├── technical_indicators_tools.py # get_indicators
|
||||
│ │ ├── fundamental_data_tools.py # 财务分析工具
|
||||
│ │ └── news_data_tools.py # 新闻工具
|
||||
│ ├── dataflows/ # 数据源层
|
||||
│ │ ├── interface.py # 路由分发 + VENDOR_METHODS
|
||||
│ │ ├── config.py # 运行时配置
|
||||
│ │ ├── akshare_data.py # 🆕 akshare 行情+财务适配
|
||||
│ │ ├── akshare_news.py # 🆕 akshare 新闻适配
|
||||
│ │ ├── yfinance_news.py # yfinance 新闻
|
||||
│ │ ├── y_finance.py # yfinance 行情
|
||||
│ │ └── alpha_vantage*.py # Alpha Vantage 适配
|
||||
│ ├── graph/ # LangGraph 编排
|
||||
│ │ ├── trading_graph.py # 主图定义
|
||||
│ │ └── setup.py # 图工厂
|
||||
│ └── default_config.py # 默认配置(已改为 akshare)
|
||||
├── docs/ # 文档
|
||||
│ ├── architecture-and-modifications.md # 🆕 本文档
|
||||
│ └── ...
|
||||
├── web_server.py # 🆕 FastAPI Web 服务
|
||||
├── web.html # 🆕 前端面板
|
||||
└── pyproject.toml # 依赖管理
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 九、关键代码路径
|
||||
|
||||
| 功能 | 起点 | 链路 |
|
||||
|------|------|------|
|
||||
| 用户提交分析 | `web_server.py:94 POST /api/analyze` | → `run_analysis_task` → `TradingAgentsGraph.propagate()` |
|
||||
| 获取行情数据 | `core_stock_tools.py:get_stock_data` | → `route_to_vendor("get_stock_data", ...)` → `akshare_data.get_stock_data()` |
|
||||
| 获取技术指标 | `technical_indicators_tools.py:get_indicators` | → `route_to_vendor` → `akshare_data.get_indicators()` |
|
||||
| 获取财务数据 | `fundamental_data_tools.py:get_fundamentals` | → `route_to_vendor` → `akshare_data.get_fundamentals()` |
|
||||
| 获取新闻 | `news_data_tools.py:get_news` | → `route_to_vendor` → `akshare_news.get_news()` |
|
||||
| 数据源切换 | `interface.py:route_to_vendor` | 按 config → fallback 链尝试 |
|
||||
@@ -0,0 +1,148 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate TradingAgents workflow diagrams for the analysis document."""
|
||||
import sys, os
|
||||
sys.path.insert(0, '/home/ubuntu/.nanobot/workspace/skills/hand-drawn-diagram')
|
||||
from generator import DiagramGenerator, Component, Connection, Container
|
||||
|
||||
DOCS = '/home/ubuntu/nanocode/TradingAgents/docs'
|
||||
|
||||
# ──────────────────────────────────────────────────────────────────
|
||||
# Diagram 1: High-level pipeline flowchart
|
||||
# ──────────────────────────────────────────────────────────────────
|
||||
gen1 = DiagramGenerator(style="sketch")
|
||||
|
||||
steps = [
|
||||
{"type": "start", "label": "用户输入\n股票代码 + 日期"},
|
||||
{"type": "process", "label": "并行数据采集\n(4个分析师同时工作)"},
|
||||
{"type": "process", "label": "研究经理汇总\n收集4份分析报告"},
|
||||
{"type": "decision", "label": "多空辩论\nBull vs Bear × N轮"},
|
||||
{"type": "process", "label": "交易员决策\n综合辩论形成草案"},
|
||||
{"type": "decision", "label": "三级风控评审\n激进/保守/中立"},
|
||||
{"type": "end", "label": "最终输出\nBuy / Sell / Hold"},
|
||||
]
|
||||
|
||||
gen1.create_flowchart(
|
||||
title="TradingAgents 单次股票分析流程",
|
||||
steps=steps,
|
||||
output=f"{DOCS}/workflow-pipeline.html",
|
||||
)
|
||||
|
||||
print(f"✅ 1. Pipeline flowchart: {DOCS}/workflow-pipeline.html")
|
||||
|
||||
# ──────────────────────────────────────────────────────────────────
|
||||
# Diagram 2: Detailed architecture with data flows
|
||||
# ──────────────────────────────────────────────────────────────────
|
||||
W, H = 1300, 1200
|
||||
gen2 = DiagramGenerator(style="sketch")
|
||||
|
||||
# --- Component definitions ---
|
||||
center = W // 2
|
||||
|
||||
# Row 1: Input layer
|
||||
user = Component("用户浏览器", "cloud", center-70, 20, 140, 45, "cloud")
|
||||
|
||||
# Row 2: Web server
|
||||
web_srv = Component("Web Server (FastAPI)\n后台异步分析任务", "frontend", center-95, 95, 190, 55)
|
||||
|
||||
# Row 3: LangGraph
|
||||
graph = Component("TradingAgents Graph\n(LangGraph StateGraph)", "backend", center-105, 185, 210, 55, "hexagon")
|
||||
|
||||
# Row 4: Four analysts + manager (parallel)
|
||||
mkt = Component("市场分析师\n行情+技术指标", "backend", 50, 310, 150, 60)
|
||||
snt = Component("社媒分析师\n舆论情绪", "backend", 240, 310, 140, 60)
|
||||
nws = Component("新闻分析师\n个股+宏观新闻", "backend", 420, 310, 150, 60)
|
||||
fnd = Component("基本面分析师\n三表+估值", "backend", 610, 310, 150, 60)
|
||||
mgr = Component("研究经理\n汇总4份报告", "security", 810, 310, 140, 60)
|
||||
|
||||
# Row 5: Debate agents
|
||||
bull = Component("Bull 多头\n研究员", "frontend", 230, 440, 140, 50)
|
||||
bear = Component("Bear 空头\n研究员", "security", 420, 440, 140, 50)
|
||||
dbj = Component("辩论裁判\n评估论据", "backend", 610, 440, 140, 50)
|
||||
|
||||
# Row 6: Trader
|
||||
trader = Component("Trader 交易员\n综合辩论→决策草案", "backend", center-105, 560, 210, 55, "hexagon")
|
||||
|
||||
# Row 7: Risk management trio
|
||||
agg = Component("Aggressive\n激进风控", "frontend", 190, 680, 140, 55)
|
||||
con = Component("Conservative\n保守风控", "security", 390, 680, 145, 55)
|
||||
neu = Component("Neutral\n中立风控", "backend", 590, 680, 140, 55)
|
||||
rsk = Component("Risk Judge\n风控终审", "security", 800, 680, 140, 55)
|
||||
|
||||
# Row 8: Final output
|
||||
output = Component("输出结果\n分析报告 + 交易信号", "cloud", center-110, 800, 220, 55, "cloud")
|
||||
|
||||
# Row 9: Data sources
|
||||
ak = Component("akshare 主数据源\nA股/港股/美股/新闻", "database", 80, 930, 185, 55)
|
||||
yf = Component("yfinance 备用1\n美股+内部交易", "database", 320, 930, 165, 55)
|
||||
av = Component("Alpha Vantage 备用2\n美国市场备选", "database", 540, 930, 165, 55)
|
||||
llm = Component("DeepSeek LLM\n推理引擎", "database", 780, 930, 155, 55)
|
||||
|
||||
components = [user, web_srv, graph,
|
||||
mkt, snt, nws, fnd, mgr,
|
||||
bull, bear, dbj,
|
||||
trader,
|
||||
agg, con, neu, rsk,
|
||||
output,
|
||||
ak, yf, av, llm]
|
||||
|
||||
# --- Connections ---
|
||||
connections = [
|
||||
Connection("用户浏览器", "Web Server (FastAPI)\n后台异步分析任务", "solid", "POST /api/analyze", "#22d3ee"),
|
||||
Connection("Web Server (FastAPI)\n后台异步分析任务", "TradingAgents Graph\n(LangGraph StateGraph)", "solid", "启动分析", "#22d3ee"),
|
||||
# Graph → 4 analysts
|
||||
Connection("TradingAgents Graph\n(LangGraph StateGraph)", "市场分析师\n行情+技术指标", "dashed", "分发", "#fbbf24"),
|
||||
Connection("TradingAgents Graph\n(LangGraph StateGraph)", "社媒分析师\n舆论情绪", "dashed", "分发", "#fbbf24"),
|
||||
Connection("TradingAgents Graph\n(LangGraph StateGraph)", "新闻分析师\n个股+宏观新闻", "dashed", "分发", "#fbbf24"),
|
||||
Connection("TradingAgents Graph\n(LangGraph StateGraph)", "基本面分析师\n三表+估值", "dashed", "分发", "#fbbf24"),
|
||||
# Analysts → Manager
|
||||
Connection("市场分析师\n行情+技术指标", "研究经理\n汇总4份报告", "solid", "报告", "#34d399"),
|
||||
Connection("社媒分析师\n舆论情绪", "研究经理\n汇总4份报告", "solid", "报告", "#34d399"),
|
||||
Connection("新闻分析师\n个股+宏观新闻", "研究经理\n汇总4份报告", "solid", "报告", "#34d399"),
|
||||
Connection("基本面分析师\n三表+估值", "研究经理\n汇总4份报告", "solid", "报告", "#34d399"),
|
||||
# Manager → Debate
|
||||
Connection("研究经理\n汇总4份报告", "Bull 多头\n研究员", "solid", "启动辩论", "#a78bfa"),
|
||||
Connection("研究经理\n汇总4份报告", "Bear 空头\n研究员", "solid", "启动辩论", "#a78bfa"),
|
||||
Connection("Bull 多头\n研究员", "辩论裁判\n评估论据", "solid", "多方论据", "#f87171"),
|
||||
Connection("Bear 空头\n研究员", "辩论裁判\n评估论据", "solid", "空方论据", "#f87171"),
|
||||
# Judge → Trader
|
||||
Connection("辩论裁判\n评估论据", "Trader 交易员\n综合辩论→决策草案", "solid", "辩论摘要", "#fb923c"),
|
||||
# Trader → Risk
|
||||
Connection("Trader 交易员\n综合辩论→决策草案", "Aggressive\n激进风控", "dashed", "草案", "#38bdf8"),
|
||||
Connection("Trader 交易员\n综合辩论→决策草案", "Conservative\n保守风控", "dashed", "草案", "#38bdf8"),
|
||||
Connection("Trader 交易员\n综合辩论→决策草案", "Neutral\n中立风控", "dashed", "草案", "#38bdf8"),
|
||||
# Risk → Judge
|
||||
Connection("Aggressive\n激进风控", "Risk Judge\n风控终审", "solid", "评估", "#34d399"),
|
||||
Connection("Conservative\n保守风控", "Risk Judge\n风控终审", "solid", "评估", "#34d399"),
|
||||
Connection("Neutral\n中立风控", "Risk Judge\n风控终审", "solid", "评估", "#34d399"),
|
||||
# Final
|
||||
Connection("Risk Judge\n风控终审", "输出结果\n分析报告 + 交易信号", "solid", "最终决策", "#22d3ee"),
|
||||
# Data source connections
|
||||
Connection("市场分析师\n行情+技术指标", "akshare 主数据源\nA股/港股/美股/新闻", "dashed", "数据", "#94a3b8"),
|
||||
Connection("基本面分析师\n三表+估值", "akshare 主数据源\nA股/港股/美股/新闻", "dashed", "数据", "#94a3b8"),
|
||||
Connection("新闻分析师\n个股+宏观新闻", "akshare 主数据源\nA股/港股/美股/新闻", "dashed", "数据", "#94a3b8"),
|
||||
Connection("akshare 主数据源\nA股/港股/美股/新闻", "yfinance 备用1\n美股+内部交易", "dashed", "fallback", "#64748b"),
|
||||
Connection("yfinance 备用1\n美股+内部交易", "Alpha Vantage 备用2\n美国市场备选", "dashed", "fallback", "#64748b"),
|
||||
Connection("Bull 多头\n研究员", "DeepSeek LLM\n推理引擎", "dashed", "推理", "#94a3b8"),
|
||||
Connection("Bear 空头\n研究员", "DeepSeek LLM\n推理引擎", "dashed", "推理", "#94a3b8"),
|
||||
]
|
||||
|
||||
# --- Container groups ---
|
||||
containers = [
|
||||
Container("分析师团队 (并行)", 20, 285, 960, 110, "#fbbf24"),
|
||||
Container("多空辩论 (可多轮)", 200, 415, 580, 100, "#a78bfa"),
|
||||
Container("三级风控", 150, 655, 820, 105, "#f87171"),
|
||||
Container("数据源层", 50, 905, 950, 105, "#64748b"),
|
||||
]
|
||||
|
||||
# --- Generate ---
|
||||
gen2.create_architecture(
|
||||
title="TradingAgents 详细架构与数据流",
|
||||
components=components,
|
||||
connections=connections,
|
||||
output=f"{DOCS}/workflow-architecture",
|
||||
containers=containers,
|
||||
auto_layout=False,
|
||||
)
|
||||
|
||||
print(f"✅ 2. Architecture diagram: {DOCS}/workflow-architecture.html")
|
||||
print("\nDone!")
|
||||
@@ -0,0 +1,480 @@
|
||||
# TradingAgents 股票分析工作流程详解
|
||||
|
||||
> **文档时间**: 2026-05-05
|
||||
> **相关文档**: [技术架构分析](./architecture-and-modifications.md)
|
||||
> **配套图表**: [流程图](workflow-pipeline.html) | [架构图](workflow-architecture.html)
|
||||
|
||||
---
|
||||
|
||||
## 一、一次分析的完整生命周期
|
||||
|
||||
当用户在 Web UI 输入 `600362` 并点击"分析",系统会经历以下完整流程:
|
||||
|
||||
```
|
||||
用户点击 [分析] → 后台异步任务 → 约 3-8 分钟后 → 输出交易决策
|
||||
```
|
||||
|
||||
整个流程由 **LangGraph StateGraph** 驱动,状态在 15+ 个节点间流转。下面按执行顺序逐步拆解。
|
||||
|
||||
---
|
||||
|
||||
## 二、流程图
|
||||
|
||||

|
||||
|
||||
> 详细架构图: [workflow-architecture.html](workflow-architecture.html)
|
||||
|
||||
---
|
||||
|
||||
## 三、分阶段详解
|
||||
|
||||
### 阶段 1:请求接收与任务创建
|
||||
|
||||
**入口**: `web_server.py` → `POST /api/analyze`
|
||||
|
||||
```
|
||||
用户输入: { ticker: "600362", date: "2026-04-30", analysts: [...], max_debate_rounds: 1 }
|
||||
```
|
||||
|
||||
1. 生成唯一的 `task_id`(格式: `600362_20260505191807`)
|
||||
2. 创建任务记录写入 `tasks_store`(内存字典)
|
||||
3. 通过 FastAPI `BackgroundTasks` 异步启动 `run_analysis_task()`
|
||||
4. 立即返回 `{"task_id": "...", "status": "pending"}`
|
||||
5. 前端每 3 秒轮询 `GET /api/task/{task_id}` 获取进度
|
||||
|
||||
### 阶段 2:Graph 初始化
|
||||
|
||||
**文件**: `tradingagents/graph/trading_graph.py` → `TradingAgentsGraph.propagate()`
|
||||
|
||||
```python
|
||||
# 1. 读取配置
|
||||
config = get_config() # 默认 vendor: akshare
|
||||
llm_name = config["llm_provider"] # DeepSeek
|
||||
|
||||
# 2. 初始化 LangGraph StateGraph
|
||||
workflow = StateGraph(AgentState)
|
||||
|
||||
# 3. 按用户选择的分析师类型动态添加节点
|
||||
# 可选: market, sentiment, news, fundamentals
|
||||
# 默认: market + news
|
||||
```
|
||||
|
||||
`AgentState` 中关键字段:
|
||||
|
||||
| 字段 | 初始值 | 说明 |
|
||||
|------|--------|------|
|
||||
| `messages` | `[]` | 全流程消息日志 |
|
||||
| `ticker` | `"600362"` | 股票代码 |
|
||||
| `trade_date` | `"2026-04-30"` | 分析日期 |
|
||||
| `company_name` | `""` | 公司名称(初始为空) |
|
||||
| `market_report` | `""` | 市场分析报告 |
|
||||
| `sentiment_report` | `""` | 情绪分析报告 |
|
||||
| `news_report` | `""` | 新闻分析报告 |
|
||||
| `fundamentals_report` | `""` | 基本面报告 |
|
||||
| `investment_plan` | `""` | 投资决策草案 |
|
||||
| `final_decision` | `""` | 最终交易信号 |
|
||||
| `current_debate_round` | `0` | 当前辩论轮次 |
|
||||
|
||||
### 阶段 3:并行分析师采集(核心环节)
|
||||
|
||||
这是整个流程中**数据量最大、耗时最长**的阶段。四个分析师节点通过 LangGraph 的并行边**同时启动**。
|
||||
|
||||
#### 3.1 市场分析师 (Market Analyst)
|
||||
|
||||
**文件**: `tradingagents/agents/analysts/market_analyst.py`
|
||||
|
||||
**角色定位**: 技术面专家
|
||||
|
||||
**System Prompt 核心**:
|
||||
> "You are a trading assistant agent with extensive market insight. Your task is to analyze market data using technical indicators."
|
||||
|
||||
**执行的工具调用**:
|
||||
|
||||
```
|
||||
1. get_stock_data("600362", "2026-03-30", "2026-04-30")
|
||||
→ 路线: route_to_vendor → akshare_data.get_stock_data()
|
||||
→ 输出: 最近一个月 OHLCV 数据(~22条日K线)
|
||||
|
||||
2. get_indicators("600362", "rsi", "2026-04-30", 30)
|
||||
3. get_indicators("600362", "macd", "2026-04-30", 30)
|
||||
4. get_indicators("600362", "bollinger_bands", "2026-04-30", 30)
|
||||
5. get_indicators("600362", "volume", "2026-04-30", 30)
|
||||
... (最多调用 19 项技术指标中的 5-8 项关键指标)
|
||||
```
|
||||
|
||||
**指标清单**(akshare_data.py 支持的全部 19 项):
|
||||
|
||||
| 类别 | 指标 |
|
||||
|------|------|
|
||||
| 趋势类 | sma_20, ema_20, macd, adx |
|
||||
| 动量类 | rsi, stochastic_oscillator, williams_r, cci |
|
||||
| 波动类 | bollinger_bands, atr, standard_deviation |
|
||||
| 成交量类 | obv, volume, volume_sma |
|
||||
| 其他 | mfi, ppo, roc, triple_ema, vortex |
|
||||
|
||||
**输出**: 一份 800-1500 字的 Markdown 技术分析报告,含关键指标解读和趋势判断。
|
||||
|
||||
#### 3.2 社交媒体分析师 (Social Media Analyst)
|
||||
|
||||
**文件**: `tradingagents/agents/analysts/social_media_analyst.py`
|
||||
|
||||
**角色定位**: 市场情绪雷达
|
||||
|
||||
**执行的工具调用**:
|
||||
|
||||
```
|
||||
1. get_news("600362", "2026-04-01", "2026-05-04")
|
||||
→ 路线: route_to_vendor → akshare_news.get_news()
|
||||
→ 数据源: 东方财富个股新闻
|
||||
→ 输出: 最近 15 天内与该股相关的新闻(最多50条)
|
||||
```
|
||||
|
||||
**输出**: 一份舆情分析报告,提炼市场情绪信号(恐慌/贪婪/中性)。
|
||||
|
||||
#### 3.3 新闻分析师 (News Analyst)
|
||||
|
||||
**文件**: `tradingagents/agents/analysts/news_analyst.py`
|
||||
|
||||
**角色定位**: 宏观政策雷达
|
||||
|
||||
**System Prompt 核心**:
|
||||
> "You are a news analyst agent with expertise in global macro trends. Your task is to analyze news related to the company and the broader economic landscape."
|
||||
|
||||
**执行的工具调用**:
|
||||
|
||||
```
|
||||
1. get_news("600362", "2026-04-01", "2026-05-04")
|
||||
→ 与社媒分析师相同的数据源,但解读角度不同
|
||||
|
||||
2. get_global_news("2026-05-04", look_back_days=7, limit=20)
|
||||
→ 路线: route_to_vendor → akshare_news.get_global_news()
|
||||
→ 数据源: CCTV 新闻联播文字稿
|
||||
→ 输出: 宏观政策、经济事件摘要
|
||||
```
|
||||
|
||||
**输出**: 一份包含个股新闻分析和宏观经济背景的综合报告。
|
||||
|
||||
#### 3.4 基本面分析师 (Fundamentals Analyst)
|
||||
|
||||
**文件**: `tradingagents/agents/analysts/fundamentals_analyst.py`
|
||||
|
||||
**角色定位**: 价值投资者
|
||||
|
||||
**System Prompt 核心**:
|
||||
> "You are a fundamental analysis expert with deep knowledge of valuation methodologies. Your task is to analyze company fundamentals and financial health."
|
||||
|
||||
**执行的工具调用** (共 4 次):
|
||||
|
||||
```
|
||||
1. get_fundamentals("600362")
|
||||
→ 数据: 公司概况、市盈率、市净率、总市值、流通股本等
|
||||
|
||||
2. get_balance_sheet("600362")
|
||||
→ 数据: 最新一期资产负债表(总资产/负债/权益)
|
||||
|
||||
3. get_cashflow("600362")
|
||||
→ 数据: 最新一期现金流量表(经营/投资/筹资现金流)
|
||||
|
||||
4. get_income_statement("600362")
|
||||
→ 数据: 最新一期利润表(营收/成本/净利润/每股收益)
|
||||
```
|
||||
|
||||
**输出**: 一份包含估值分析、财务健康度评分、盈利能力判断的基本面报告。
|
||||
|
||||
### 阶段 4:研究经理汇总
|
||||
|
||||
**文件**: `tradingagents/graph/trading_graph.py` → `create_research_manager_node()`
|
||||
|
||||
```
|
||||
输入: 4份分析师报告(并行采集完成后的汇总)
|
||||
处理: 研究经理 LLM 阅读所有报告,提取关键矛盾点
|
||||
输出: 投资者简报 (investment briefing)
|
||||
```
|
||||
|
||||
研究经理不产生独立决策,而是**整理和总结**分析师团队输出的核心信息,为下一阶段的辩论做准备。
|
||||
|
||||
### 阶段 5:多空辩论 (Debate)
|
||||
|
||||
**文件**: `tradingagents/graph/trading_graph.py` → `create_debate_node()` + `debate_bull_researcher()` + `debate_bear_researcher()`
|
||||
|
||||
这是框架的**核心创新**:用 LLM 模拟真实投资决策中的多空辩论。
|
||||
|
||||
#### 辩论角色
|
||||
|
||||
| 角色 | 文件 | 立场 | 职责 |
|
||||
|------|------|------|------|
|
||||
| **Bull Researcher** | `agents/researchers/bull_researcher.py` | 多头 | 找出所有支撑买入的论据 |
|
||||
| **Bear Researcher** | `agents/researchers/bear_researcher.py` | 空头 | 找出所有支撑卖出的论据 |
|
||||
| **Debate Judge** | `agents/managers/research_manager.py` | 裁判 | 评估双方论据,判断胜负 |
|
||||
|
||||
#### 辩论流程
|
||||
|
||||
```
|
||||
轮次 1:
|
||||
Bull → 提出 3-5 个多方论点(基于分析师报告)
|
||||
Bear → 反驳多方论点 + 提出 3-5 个空方论点
|
||||
Judge → 评估双方论据质量,判断本轮是否分出胜负
|
||||
|
||||
轮次 2 (如果裁判认为需要继续):
|
||||
Bull → 回应空方反驳 + 补充新论点
|
||||
Bear → 回应多方回应 + 强化空方论点
|
||||
Judge → 再次评估
|
||||
|
||||
... 直到 max_debate_rounds 耗尽或裁判判定胜负
|
||||
```
|
||||
|
||||
**关键**: `max_debate_rounds` 在配置中可调,默认 **1 轮**。每增加一轮,LLM 调用次数翻倍,总耗时显著增长。
|
||||
|
||||
#### 辩论输出
|
||||
|
||||
- 辩论完整记录(谁说了什么)
|
||||
- 裁判的最终评估(多方胜/空方胜/平局)
|
||||
|
||||
### 阶段 6:交易员决策
|
||||
|
||||
**文件**: `tradingagents/agents/trader/trader_agent.py`
|
||||
|
||||
**System Prompt 核心**:
|
||||
> "You are a professional trader agent. Based on the analysts' reports and debate results, make a trading decision."
|
||||
|
||||
**输入**:
|
||||
- 4 份分析师报告
|
||||
- 辩论摘要(裁判评估)
|
||||
|
||||
**处理**: 交易员 LLM 综合所有证据,形成投资决策草案
|
||||
|
||||
**输出**: `investment_plan` — 包含:
|
||||
- 决策方向(Buy/Sell/Hold)
|
||||
- 置信度评估
|
||||
- 关键依据
|
||||
- 风险提示
|
||||
|
||||
### 阶段 7:三级风控评审
|
||||
|
||||
**文件**: `tradingagents/graph/trading_graph.py` → `create_risk_analysis_node()` + 三个风控 agent
|
||||
|
||||
这是项目的**第二道安全阀**:交易员的决策必须通过风控审查。
|
||||
|
||||
| 风控角色 | 文件 | 风格 | 关注点 |
|
||||
|----------|------|------|--------|
|
||||
| **Aggressive** | `agents/risk_mgmt/aggressive_debator.py` | 激进 | 机会最大化,风险容忍度较高 |
|
||||
| **Conservative** | `agents/risk_mgmt/conservative_debator.py` | 保守 | 本金安全第一,宁可错过不做错 |
|
||||
| **Neutral** | `agents/risk_mgmt/neutral_debator.py` | 中立 | 平衡收益与风险 |
|
||||
|
||||
#### 流程
|
||||
|
||||
```
|
||||
交易员输出投资草案
|
||||
│
|
||||
├→ Aggressive 评估 → "风险可接受,建议执行"
|
||||
├→ Conservative 评估 → "风险过高,建议降低仓位"
|
||||
└→ Neutral 评估 → "风险适中,可执行但需设置止损"
|
||||
│
|
||||
└→ Risk Judge 汇总三个评估 → 最终裁定
|
||||
```
|
||||
|
||||
**Risk Judge** 文件: `tradingagents/agents/managers/risk_manager.py` — 综合三方意见,给出最终风控建议。
|
||||
|
||||
**注意**: 风控评审是一个循环 — 如果 `final_decision` 为空(未达成一致),图会回到交易员节点重新决策。
|
||||
|
||||
### 阶段 8:最终输出
|
||||
|
||||
经过以上所有阶段后,系统输出:
|
||||
|
||||
```python
|
||||
{
|
||||
"ticker": "600362",
|
||||
"date": "2026-04-30",
|
||||
"company_name": "江西铜业",
|
||||
"market_report": "...", # 技术分析报告
|
||||
"sentiment_report": "...", # 情绪分析报告
|
||||
"news_report": "...", # 新闻分析报告
|
||||
"fundamentals_report": "...", # 基本面报告
|
||||
"investment_plan": "...", # 交易决策草案
|
||||
"debate_log": "...", # 辩论记录
|
||||
"final_decision": "BUY", # 最终交易信号: BUY / SELL / HOLD
|
||||
"risk_assessment": "...", # 风控评估
|
||||
"messages": [...] # 全流程消息日志
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 四、完整节点流转图(Graph 内部)
|
||||
|
||||
```
|
||||
┌──────────────┐
|
||||
│ START │
|
||||
└──────┬───────┘
|
||||
│
|
||||
┌────────────────┼────────────────┐
|
||||
▼ ▼ ▼ ▼
|
||||
┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐
|
||||
│mkt_start │ │snt_start │ │nws_start │ │fnd_start │
|
||||
└─────┬──────┘ └─────┬──────┘ └─────┬──────┘ └─────┬──────┘
|
||||
▼ ▼ ▼ ▼
|
||||
┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐
|
||||
│mkt_analyst │ │snt_analyst │ │nws_analyst │ │fnd_analyst │
|
||||
│(LLM分析) │ │(LLM分析) │ │(LLM分析) │ │(LLM分析) │
|
||||
└─────┬──────┘ └─────┬──────┘ └─────┬──────┘ └─────┬──────┘
|
||||
▼ ▼ ▼ ▼
|
||||
┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐
|
||||
│mkt_tools │ │snt_tools │ │nws_tools │ │fnd_tools │
|
||||
│(调用数据) │ │(调用数据) │ │(调用数据) │ │(调用数据) │
|
||||
└─────┬──────┘ └─────┬──────┘ └─────┬──────┘ └─────┬──────┘
|
||||
▼ ▼ ▼ ▼
|
||||
┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐
|
||||
│mkt_cond │ │snt_cond │ │nws_cond │ │fnd_cond │
|
||||
│(if 需继续) │ │(if 需继续) │ │(if 需继续) │ │(if 需继续) │
|
||||
└─────┬──────┘ └─────┬──────┘ └─────┬──────┘ └─────┬──────┘
|
||||
│ │ │ │
|
||||
└────────────────┼────────────────┼────────────────┘
|
||||
▼
|
||||
┌──────────────┐
|
||||
│ invest_judge │ (研究经理汇总)
|
||||
└──────┬───────┘
|
||||
│
|
||||
┌───────────┴───────────┐
|
||||
▼ ▼
|
||||
┌────────────┐ ┌────────────┐
|
||||
│bull_resrch │ │bear_resrch │
|
||||
│(多方) │ │(空方) │
|
||||
└─────┬──────┘ └─────┬──────┘
|
||||
│ │
|
||||
└──────────┬───────────┘
|
||||
▼
|
||||
┌──────────────┐
|
||||
│ invest_judge │ (辩论裁判评估)
|
||||
└──────┬───────┘
|
||||
│ (if 辩论未结束 → 回到 bull/bear)
|
||||
▼
|
||||
┌──────────────┐
|
||||
│ trader │ (交易员决策)
|
||||
└──────┬───────┘
|
||||
▼
|
||||
┌──────────────┐
|
||||
│trader_tools │ (可能需要查询数据)
|
||||
└──────┬───────┘
|
||||
│
|
||||
┌──────────────┼──────────────┐
|
||||
▼ ▼ ▼
|
||||
┌──────────┐ ┌──────────────┐ ┌──────────┐
|
||||
│aggressive│ │conservative │ │ neutral │
|
||||
│ 风控 │ │ 风控 │ │ 风控 │
|
||||
└────┬─────┘ └──────┬───────┘ └────┬─────┘
|
||||
│ │ │
|
||||
└────────────────┼────────────────┘
|
||||
▼
|
||||
┌──────────────┐
|
||||
│ risk_judge │ (风控终审)
|
||||
└──────┬───────┘
|
||||
│ (if 未通过 → 回到 trader)
|
||||
▼
|
||||
┌──────────────┐
|
||||
│ final │ (输出结果)
|
||||
└──────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 五、关键数据流路径
|
||||
|
||||
以"600362 市场分析"为例,追踪一次数据调用的完整路径:
|
||||
|
||||
```
|
||||
1. Market Analyst LLM 决定调用 get_stock_data("600362", ...)
|
||||
|
||||
2. LangChain @tool 装饰器触发
|
||||
→ agents/utils/core_stock_tools.py:28
|
||||
|
||||
3. 内部调用 route_to_vendor("get_stock_data", "600362", ...)
|
||||
→ dataflows/interface.py:140
|
||||
|
||||
4. route_to_vendor 读取 config["data_vendors"]["core_stock_data"]
|
||||
→ {"primary": "akshare"}
|
||||
|
||||
5. 按 priority 顺序尝试:
|
||||
a) akshare → akshare_data.get_stock_data("600362", ...)
|
||||
- 检测 "600362" 是6位数字 → 路由到 A 股接口
|
||||
- 调用 ak.stock_zh_a_hist(symbol="600362", period="daily", ...)
|
||||
- 格式化 DataFrame → Markdown 表格字符串
|
||||
- 成功!返回数据 ✓
|
||||
|
||||
6. route_to_vendor 获得 Markdown 字符串 → 返回给 tool
|
||||
|
||||
7. tool 将数据嵌入 LLM context
|
||||
|
||||
8. Market Analyst LLM 收到数据,生成技术分析报告
|
||||
|
||||
9. 报告写入 state.market_report
|
||||
```
|
||||
|
||||
如果第5步 akshare 失败,route_to_vendor 会自动尝试 yfinance,再失败尝试 alpha_vantage,**完全透明,LLM 无感知**。
|
||||
|
||||
---
|
||||
|
||||
## 六、耗时分布估算
|
||||
|
||||
基于 DeepSeek 推理速度的单次分析耗时(仅供参考):
|
||||
|
||||
| 阶段 | LLM 调用次数 | 数据API调用 | 耗时估算 |
|
||||
|------|-------------|------------|----------|
|
||||
| 并行分析师(4个) | 8-16次 (LLM + tool) | 8-15次 | 90-180秒 |
|
||||
| 研究经理汇总 | 1次 | 0 | 10-20秒 |
|
||||
| 辩论(1轮) | 3次 (Bull/Bear/Judge) | 0 | 30-60秒 |
|
||||
| 交易员决策 | 1次 | 0-2次 | 15-30秒 |
|
||||
| 三级风控 | 4次 (3风控+1裁判) | 0 | 40-80秒 |
|
||||
| **合计** | **17-25次** | **8-17次** | **3-6分钟** |
|
||||
|
||||
> **注意**: 如果 `max_debate_rounds` 设为 2 或更多,辩论耗时翻倍。数据源的 Rate Limit 状况也会影响实际耗时。
|
||||
|
||||
---
|
||||
|
||||
## 七、与原始实现的关键差异
|
||||
|
||||
本项目基于开源 TradingAgents 框架,做了以下适应性修改(详见[架构文档](./architecture-and-modifications.md)):
|
||||
|
||||
| 差异点 | 原始实现 | 当前实现 |
|
||||
|--------|---------|---------|
|
||||
| 数据源 | yfinance 为主 | **akshare 为主**,yfinance 降级为 fallback |
|
||||
| A股行情 | 不稳定,频繁 Rate Limit | ✅ 稳定,不限流 |
|
||||
| A股财务数据 | ❌ | ✅ 三大报表完整 |
|
||||
| 新闻源 | 英文(yfinance news) | ✅ 中文(东方财富 + CCTV) |
|
||||
| 港股支持 | 部分 | ✅ 完整 |
|
||||
| Web UI | ❌ 无 | ✅ FastAPI + 前端面板 |
|
||||
| 部署 | 脚本手动运行 | ✅ systemd 服务自动管理 |
|
||||
|
||||
---
|
||||
|
||||
## 八、配置调优建议
|
||||
|
||||
通过修改 `default_config.py` 或运行时 `set_config()` 可调整的参数:
|
||||
|
||||
| 参数 | 默认值 | 建议范围 | 说明 |
|
||||
|------|--------|---------|------|
|
||||
| `max_debate_rounds` | 1 | 1-3 | 辩论轮次,越多越深度但越慢 |
|
||||
| `data_vendors.*.primary` | `"akshare"` | `"akshare"` / `"yfinance"` | 主数据源 |
|
||||
| `llm_provider` | `"deepseek"` | — | LLM 后端 |
|
||||
| `quick_thinking` | `False` | `True` / `False` | True 使用 fast model,速度更快精度略低 |
|
||||
|
||||
---
|
||||
|
||||
## 九、监控与调试
|
||||
|
||||
### 查看服务日志
|
||||
|
||||
```bash
|
||||
journalctl -u tradingagents.service -f
|
||||
```
|
||||
|
||||
### 查看分析任务状态
|
||||
|
||||
```bash
|
||||
curl http://129.211.173.87:8500/api/task/{task_id}
|
||||
```
|
||||
|
||||
### 重启服务
|
||||
|
||||
```bash
|
||||
sudo systemctl restart tradingagents.service
|
||||
```
|
||||
@@ -0,0 +1,300 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>TradingAgents 详细架构与数据流</title>
|
||||
|
||||
<style>
|
||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
body {
|
||||
font-family: 'Noto Sans Mono CJK SC', 'JetBrains Mono', 'WenQuanYi Zen Hei Mono', monospace;
|
||||
background: #020617;
|
||||
min-height: 100vh;
|
||||
padding: 2rem;
|
||||
color: white;
|
||||
}
|
||||
.container { max-width: 1200px; margin: 0 auto; }
|
||||
.header { margin-bottom: 2rem; }
|
||||
.header-row { display: flex; align-items: center; gap: 1rem; margin-bottom: 0.5rem; }
|
||||
.pulse-dot {
|
||||
width: 12px; height: 12px; background: #22d3ee; border-radius: 50%;
|
||||
animation: pulse 2s infinite;
|
||||
}
|
||||
@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } }
|
||||
h1 { font-size: 1.5rem; font-weight: 700; letter-spacing: -0.025em; }
|
||||
.subtitle { color: #94a3b8; font-size: 0.875rem; margin-left: 1.75rem; }
|
||||
.diagram-container {
|
||||
background: rgba(15, 23, 42, 0.5); border-radius: 1rem;
|
||||
border: 1px solid #1e293b; padding: 1.5rem; overflow-x: auto;
|
||||
}
|
||||
svg { width: 100%; min-width: 900px; display: block; }
|
||||
.cards {
|
||||
display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
|
||||
gap: 1rem; margin-top: 2rem;
|
||||
}
|
||||
.card {
|
||||
background: rgba(15, 23, 42, 0.5); border-radius: 0.75rem;
|
||||
border: 1px solid #1e293b; padding: 1.25rem;
|
||||
}
|
||||
.card-header { display: flex; align-items: center; gap: 0.5rem; margin-bottom: 0.75rem; }
|
||||
.card-dot { width: 8px; height: 8px; border-radius: 50%; }
|
||||
.card h3 { font-size: 0.875rem; font-weight: 600; color: #e2e8f0; }
|
||||
.card ul { list-style: none; font-size: 0.75rem; color: #94a3b8; line-height: 1.8; }
|
||||
.card li::before { content: "• "; color: #64748b; }
|
||||
.footer {
|
||||
margin-top: 2rem; padding-top: 1rem; border-top: 1px solid #1e293b;
|
||||
font-size: 0.75rem; color: #64748b; text-align: center;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="header">
|
||||
<div class="header-row">
|
||||
<div class="pulse-dot"></div>
|
||||
<h1>TradingAgents 详细架构与数据流</h1>
|
||||
</div>
|
||||
<div class="subtitle">系统架构图 · Hand-Drawn SVG</div>
|
||||
</div>
|
||||
<div class="diagram-container">
|
||||
<svg viewBox="0 0 1100 1160" xmlns="http://www.w3.org/2000/svg" font-family="'Noto Sans Mono CJK SC', 'JetBrains Mono', 'WenQuanYi Zen Hei Mono', monospace">
|
||||
<defs>
|
||||
<pattern id="grid" width="40" height="40" patternUnits="userSpaceOnUse">
|
||||
<path d="M 40 0 L 0 0 0 40" fill="none" stroke="#1e293b" stroke-width="0.5"/>
|
||||
</pattern>
|
||||
<filter id="dropShadow" x="-50%" y="-50%" width="200%" height="200%">
|
||||
<feDropShadow dx="0" dy="2" stdDeviation="3" flood-opacity="0.3"/>
|
||||
</filter>
|
||||
<marker id="arrowhead" markerWidth="10" markerHeight="7" refX="9" refY="3.5" orient="auto">
|
||||
<polygon points="0 0, 10 3.5, 0 7" fill="#64748b"/>
|
||||
</marker>
|
||||
<marker id="arrowhead-cyan" markerWidth="10" markerHeight="7" refX="9" refY="3.5" orient="auto">
|
||||
<polygon points="0 0, 10 3.5, 0 7" fill="#22d3ee"/>
|
||||
</marker>
|
||||
<marker id="arrowhead-green" markerWidth="10" markerHeight="7" refX="9" refY="3.5" orient="auto">
|
||||
<polygon points="0 0, 10 3.5, 0 7" fill="#34d399"/>
|
||||
</marker>
|
||||
<marker id="arrowhead-rose" markerWidth="10" markerHeight="7" refX="9" refY="3.5" orient="auto">
|
||||
<polygon points="0 0, 10 3.5, 0 7" fill="#fb7185"/>
|
||||
</marker>
|
||||
<marker id="arrowhead-amber" markerWidth="10" markerHeight="7" refX="9" refY="3.5" orient="auto">
|
||||
<polygon points="0 0, 10 3.5, 0 7" fill="#fbbf24"/>
|
||||
</marker>
|
||||
<marker id="arrowhead-purple" markerWidth="10" markerHeight="7" refX="9" refY="3.5" orient="auto">
|
||||
<polygon points="0 0, 10 3.5, 0 7" fill="#a78bfa"/>
|
||||
</marker>
|
||||
</defs>
|
||||
<rect width="1100" height="1160" fill="url(#grid)"/>
|
||||
<rect x="20" y="285" width="960" height="110" rx="10" fill="rgba(15, 23, 42, 0.3)" stroke="#fbbf24" stroke-width="1.5" stroke-dasharray="5,3"/>
|
||||
<rect x="35" y="277" width="90" height="16" fill="#0f172a"/>
|
||||
<text x="80" y="288" fill="#fbbf24" font-size="9" font-weight="500" text-anchor="middle">分析师团队 (并行)</text>
|
||||
<rect x="200" y="415" width="580" height="100" rx="10" fill="rgba(15, 23, 42, 0.3)" stroke="#a78bfa" stroke-width="1.5" stroke-dasharray="5,3"/>
|
||||
<rect x="215" y="407" width="90" height="16" fill="#0f172a"/>
|
||||
<text x="260" y="418" fill="#a78bfa" font-size="9" font-weight="500" text-anchor="middle">多空辩论 (可多轮)</text>
|
||||
<rect x="150" y="655" width="820" height="105" rx="10" fill="rgba(15, 23, 42, 0.3)" stroke="#f87171" stroke-width="1.5" stroke-dasharray="5,3"/>
|
||||
<rect x="165" y="647" width="42" height="16" fill="#0f172a"/>
|
||||
<text x="186" y="658" fill="#f87171" font-size="9" font-weight="500" text-anchor="middle">三级风控</text>
|
||||
<rect x="50" y="905" width="950" height="105" rx="10" fill="rgba(15, 23, 42, 0.3)" stroke="#64748b" stroke-width="1.5" stroke-dasharray="5,3"/>
|
||||
<rect x="65" y="897" width="42" height="16" fill="#0f172a"/>
|
||||
<text x="86" y="908" fill="#64748b" font-size="9" font-weight="500" text-anchor="middle">数据源层</text>
|
||||
<path d="M 608.0 47.0 A 15.749999999999998 15.749999999999998 0 0 1 629.0 33.5 A 18.9 18.9 0 0 1 671.0 31.25 A 15.749999999999998 15.749999999999998 0 0 1 692.0 44.75 A 12.6 12.6 0 0 1 685.0 53.75 L 615.0 53.75 A 12.6 12.6 0 0 1 608.0 47.0 Z" fill="rgba(120, 53, 15, 0.3)" stroke="#fbbf24" stroke-width="1.5"/>
|
||||
<text x="650" y="46" fill="#e2e8f0" font-size="11" font-weight="600" text-anchor="middle">用户浏览器</text>
|
||||
<rect x="555" y="95" width="190" height="55" rx="6" fill="#0f172a" stroke="#22d3ee" stroke-width="1.5" opacity="1.0"/>
|
||||
<rect x="555" y="95" width="190" height="55" rx="6" fill="rgba(8, 51, 68, 0.4)" stroke="#22d3ee" stroke-width="1.5" opacity="1.0"/>
|
||||
<text x="650" y="113" fill="#e2e8f0" font-size="11" font-weight="600" text-anchor="middle">Web Server (FastAPI)
|
||||
后台异步分析任务</text>
|
||||
<rect x="545" y="185" width="210" height="55" rx="6" fill="#0f172a" stroke="#34d399" stroke-width="1.5" opacity="1.0"/>
|
||||
<rect x="545" y="185" width="210" height="55" rx="6" fill="rgba(6, 78, 59, 0.4)" stroke="#34d399" stroke-width="1.5" opacity="1.0"/>
|
||||
<text x="650" y="203" fill="#e2e8f0" font-size="11" font-weight="600" text-anchor="middle">TradingAgents Graph
|
||||
(LangGraph StateGraph)</text>
|
||||
<text x="650" y="217" fill="#94a3b8" font-size="8" font-weight="normal" text-anchor="middle">hexagon</text>
|
||||
<rect x="50" y="310" width="150" height="60" rx="6" fill="#0f172a" stroke="#34d399" stroke-width="1.5" opacity="1.0"/>
|
||||
<rect x="50" y="310" width="150" height="60" rx="6" fill="rgba(6, 78, 59, 0.4)" stroke="#34d399" stroke-width="1.5" opacity="1.0"/>
|
||||
<text x="125" y="328" fill="#e2e8f0" font-size="11" font-weight="600" text-anchor="middle">市场分析师
|
||||
行情+技术指标</text>
|
||||
<rect x="240" y="310" width="140" height="60" rx="6" fill="#0f172a" stroke="#34d399" stroke-width="1.5" opacity="1.0"/>
|
||||
<rect x="240" y="310" width="140" height="60" rx="6" fill="rgba(6, 78, 59, 0.4)" stroke="#34d399" stroke-width="1.5" opacity="1.0"/>
|
||||
<text x="310" y="328" fill="#e2e8f0" font-size="11" font-weight="600" text-anchor="middle">社媒分析师
|
||||
舆论情绪</text>
|
||||
<rect x="420" y="310" width="150" height="60" rx="6" fill="#0f172a" stroke="#34d399" stroke-width="1.5" opacity="1.0"/>
|
||||
<rect x="420" y="310" width="150" height="60" rx="6" fill="rgba(6, 78, 59, 0.4)" stroke="#34d399" stroke-width="1.5" opacity="1.0"/>
|
||||
<text x="495" y="328" fill="#e2e8f0" font-size="11" font-weight="600" text-anchor="middle">新闻分析师
|
||||
个股+宏观新闻</text>
|
||||
<rect x="610" y="310" width="150" height="60" rx="6" fill="#0f172a" stroke="#34d399" stroke-width="1.5" opacity="1.0"/>
|
||||
<rect x="610" y="310" width="150" height="60" rx="6" fill="rgba(6, 78, 59, 0.4)" stroke="#34d399" stroke-width="1.5" opacity="1.0"/>
|
||||
<text x="685" y="328" fill="#e2e8f0" font-size="11" font-weight="600" text-anchor="middle">基本面分析师
|
||||
三表+估值</text>
|
||||
<rect x="810" y="310" width="140" height="60" rx="6" fill="#0f172a" stroke="#fb7185" stroke-width="1.5" opacity="1.0"/>
|
||||
<rect x="810" y="310" width="140" height="60" rx="6" fill="rgba(136, 19, 55, 0.4)" stroke="#fb7185" stroke-width="1.5" opacity="1.0"/>
|
||||
<text x="880" y="328" fill="#e2e8f0" font-size="11" font-weight="600" text-anchor="middle">研究经理
|
||||
汇总4份报告</text>
|
||||
<rect x="230" y="440" width="140" height="50" rx="6" fill="#0f172a" stroke="#22d3ee" stroke-width="1.5" opacity="1.0"/>
|
||||
<rect x="230" y="440" width="140" height="50" rx="6" fill="rgba(8, 51, 68, 0.4)" stroke="#22d3ee" stroke-width="1.5" opacity="1.0"/>
|
||||
<text x="300" y="458" fill="#e2e8f0" font-size="11" font-weight="600" text-anchor="middle">Bull 多头
|
||||
研究员</text>
|
||||
<rect x="420" y="440" width="140" height="50" rx="6" fill="#0f172a" stroke="#fb7185" stroke-width="1.5" opacity="1.0"/>
|
||||
<rect x="420" y="440" width="140" height="50" rx="6" fill="rgba(136, 19, 55, 0.4)" stroke="#fb7185" stroke-width="1.5" opacity="1.0"/>
|
||||
<text x="490" y="458" fill="#e2e8f0" font-size="11" font-weight="600" text-anchor="middle">Bear 空头
|
||||
研究员</text>
|
||||
<rect x="610" y="440" width="140" height="50" rx="6" fill="#0f172a" stroke="#34d399" stroke-width="1.5" opacity="1.0"/>
|
||||
<rect x="610" y="440" width="140" height="50" rx="6" fill="rgba(6, 78, 59, 0.4)" stroke="#34d399" stroke-width="1.5" opacity="1.0"/>
|
||||
<text x="680" y="458" fill="#e2e8f0" font-size="11" font-weight="600" text-anchor="middle">辩论裁判
|
||||
评估论据</text>
|
||||
<rect x="545" y="560" width="210" height="55" rx="6" fill="#0f172a" stroke="#34d399" stroke-width="1.5" opacity="1.0"/>
|
||||
<rect x="545" y="560" width="210" height="55" rx="6" fill="rgba(6, 78, 59, 0.4)" stroke="#34d399" stroke-width="1.5" opacity="1.0"/>
|
||||
<text x="650" y="578" fill="#e2e8f0" font-size="11" font-weight="600" text-anchor="middle">Trader 交易员
|
||||
综合辩论→决策草案</text>
|
||||
<text x="650" y="592" fill="#94a3b8" font-size="8" font-weight="normal" text-anchor="middle">hexagon</text>
|
||||
<rect x="190" y="680" width="140" height="55" rx="6" fill="#0f172a" stroke="#22d3ee" stroke-width="1.5" opacity="1.0"/>
|
||||
<rect x="190" y="680" width="140" height="55" rx="6" fill="rgba(8, 51, 68, 0.4)" stroke="#22d3ee" stroke-width="1.5" opacity="1.0"/>
|
||||
<text x="260" y="698" fill="#e2e8f0" font-size="11" font-weight="600" text-anchor="middle">Aggressive
|
||||
激进风控</text>
|
||||
<rect x="390" y="680" width="145" height="55" rx="6" fill="#0f172a" stroke="#fb7185" stroke-width="1.5" opacity="1.0"/>
|
||||
<rect x="390" y="680" width="145" height="55" rx="6" fill="rgba(136, 19, 55, 0.4)" stroke="#fb7185" stroke-width="1.5" opacity="1.0"/>
|
||||
<text x="462" y="698" fill="#e2e8f0" font-size="11" font-weight="600" text-anchor="middle">Conservative
|
||||
保守风控</text>
|
||||
<rect x="590" y="680" width="140" height="55" rx="6" fill="#0f172a" stroke="#34d399" stroke-width="1.5" opacity="1.0"/>
|
||||
<rect x="590" y="680" width="140" height="55" rx="6" fill="rgba(6, 78, 59, 0.4)" stroke="#34d399" stroke-width="1.5" opacity="1.0"/>
|
||||
<text x="660" y="698" fill="#e2e8f0" font-size="11" font-weight="600" text-anchor="middle">Neutral
|
||||
中立风控</text>
|
||||
<rect x="800" y="680" width="140" height="55" rx="6" fill="#0f172a" stroke="#fb7185" stroke-width="1.5" opacity="1.0"/>
|
||||
<rect x="800" y="680" width="140" height="55" rx="6" fill="rgba(136, 19, 55, 0.4)" stroke="#fb7185" stroke-width="1.5" opacity="1.0"/>
|
||||
<text x="870" y="698" fill="#e2e8f0" font-size="11" font-weight="600" text-anchor="middle">Risk Judge
|
||||
风控终审</text>
|
||||
<path d="M 584.0 833.0 A 19.25 19.25 0 0 1 617.0 816.5 A 23.099999999999998 23.099999999999998 0 0 1 683.0 813.75 A 19.25 19.25 0 0 1 716.0 830.25 A 15.4 15.4 0 0 1 705.0 841.25 L 595.0 841.25 A 15.4 15.4 0 0 1 584.0 833.0 Z" fill="rgba(120, 53, 15, 0.3)" stroke="#fbbf24" stroke-width="1.5"/>
|
||||
<text x="650" y="831" fill="#e2e8f0" font-size="11" font-weight="600" text-anchor="middle">输出结果
|
||||
分析报告 + 交易信号</text>
|
||||
<path d="M 80 940 L 80 975 A 92 10 0 0 0 265 975 L 265 940 A 92 10 0 0 0 80 940 Z" fill="rgba(76, 29, 149, 0.4)" stroke="#a78bfa" stroke-width="1.5"/>
|
||||
<ellipse cx="172" cy="940" rx="92" ry="10" fill="rgba(76, 29, 149, 0.4)" stroke="#a78bfa" stroke-width="1.5"/>
|
||||
<text x="172" y="961" fill="#e2e8f0" font-size="11" font-weight="600" text-anchor="middle">akshare 主数据源
|
||||
A股/港股/美股/新闻</text>
|
||||
<path d="M 320 940 L 320 975 A 82 10 0 0 0 485 975 L 485 940 A 82 10 0 0 0 320 940 Z" fill="rgba(76, 29, 149, 0.4)" stroke="#a78bfa" stroke-width="1.5"/>
|
||||
<ellipse cx="402" cy="940" rx="82" ry="10" fill="rgba(76, 29, 149, 0.4)" stroke="#a78bfa" stroke-width="1.5"/>
|
||||
<text x="402" y="961" fill="#e2e8f0" font-size="11" font-weight="600" text-anchor="middle">yfinance 备用1
|
||||
美股+内部交易</text>
|
||||
<path d="M 540 940 L 540 975 A 82 10 0 0 0 705 975 L 705 940 A 82 10 0 0 0 540 940 Z" fill="rgba(76, 29, 149, 0.4)" stroke="#a78bfa" stroke-width="1.5"/>
|
||||
<ellipse cx="622" cy="940" rx="82" ry="10" fill="rgba(76, 29, 149, 0.4)" stroke="#a78bfa" stroke-width="1.5"/>
|
||||
<text x="622" y="961" fill="#e2e8f0" font-size="11" font-weight="600" text-anchor="middle">Alpha Vantage 备用2
|
||||
美国市场备选</text>
|
||||
<path d="M 780 940 L 780 975 A 77 10 0 0 0 935 975 L 935 940 A 77 10 0 0 0 780 940 Z" fill="rgba(76, 29, 149, 0.4)" stroke="#a78bfa" stroke-width="1.5"/>
|
||||
<ellipse cx="857" cy="940" rx="77" ry="10" fill="rgba(76, 29, 149, 0.4)" stroke="#a78bfa" stroke-width="1.5"/>
|
||||
<text x="857" y="961" fill="#e2e8f0" font-size="11" font-weight="600" text-anchor="middle">DeepSeek LLM
|
||||
推理引擎</text>
|
||||
<line x1="650" y1="65" x2="650" y2="95" stroke="POST /api/analyze" stroke-width="1.5" marker-end="url(#arrowhead)"/>
|
||||
<rect x="626" y="72" width="49" height="14" fill="#0f172a" rx="2"/>
|
||||
<text x="650" y="83" fill="POST /api/analyze" font-size="8" font-weight="normal" text-anchor="middle">#22d3ee</text>
|
||||
<line x1="650" y1="150" x2="650" y2="185" stroke="启动分析" stroke-width="1.5" marker-end="url(#arrowhead)"/>
|
||||
<rect x="626" y="159" width="49" height="14" fill="#0f172a" rx="2"/>
|
||||
<text x="650" y="170" fill="启动分析" font-size="8" font-weight="normal" text-anchor="middle">#22d3ee</text>
|
||||
<line x1="650" y1="240" x2="125" y2="310" stroke="分发" stroke-width="1.5" stroke-dasharray="5,3" marker-end="url(#arrowhead)"/>
|
||||
<rect x="363" y="267" width="49" height="14" fill="#0f172a" rx="2"/>
|
||||
<text x="387" y="278" fill="分发" font-size="8" font-weight="normal" text-anchor="middle">#fbbf24</text>
|
||||
<line x1="650" y1="240" x2="310" y2="310" stroke="分发" stroke-width="1.5" stroke-dasharray="5,3" marker-end="url(#arrowhead)"/>
|
||||
<rect x="456" y="267" width="49" height="14" fill="#0f172a" rx="2"/>
|
||||
<text x="480" y="278" fill="分发" font-size="8" font-weight="normal" text-anchor="middle">#fbbf24</text>
|
||||
<line x1="650" y1="240" x2="495" y2="310" stroke="分发" stroke-width="1.5" stroke-dasharray="5,3" marker-end="url(#arrowhead)"/>
|
||||
<rect x="548" y="267" width="49" height="14" fill="#0f172a" rx="2"/>
|
||||
<text x="572" y="278" fill="分发" font-size="8" font-weight="normal" text-anchor="middle">#fbbf24</text>
|
||||
<line x1="650" y1="240" x2="685" y2="310" stroke="分发" stroke-width="1.5" stroke-dasharray="5,3" marker-end="url(#arrowhead)"/>
|
||||
<rect x="643" y="267" width="49" height="14" fill="#0f172a" rx="2"/>
|
||||
<text x="667" y="278" fill="分发" font-size="8" font-weight="normal" text-anchor="middle">#fbbf24</text>
|
||||
<line x1="200" y1="340" x2="810" y2="340" stroke="报告" stroke-width="1.5" marker-end="url(#arrowhead)"/>
|
||||
<rect x="481" y="332" width="49" height="14" fill="#0f172a" rx="2"/>
|
||||
<text x="505" y="343" fill="报告" font-size="8" font-weight="normal" text-anchor="middle">#34d399</text>
|
||||
<line x1="380" y1="340" x2="810" y2="340" stroke="报告" stroke-width="1.5" marker-end="url(#arrowhead)"/>
|
||||
<rect x="571" y="332" width="49" height="14" fill="#0f172a" rx="2"/>
|
||||
<text x="595" y="343" fill="报告" font-size="8" font-weight="normal" text-anchor="middle">#34d399</text>
|
||||
<line x1="570" y1="340" x2="810" y2="340" stroke="报告" stroke-width="1.5" marker-end="url(#arrowhead)"/>
|
||||
<rect x="666" y="332" width="49" height="14" fill="#0f172a" rx="2"/>
|
||||
<text x="690" y="343" fill="报告" font-size="8" font-weight="normal" text-anchor="middle">#34d399</text>
|
||||
<line x1="760" y1="340" x2="810" y2="340" stroke="报告" stroke-width="1.5" marker-end="url(#arrowhead)"/>
|
||||
<rect x="761" y="332" width="49" height="14" fill="#0f172a" rx="2"/>
|
||||
<text x="785" y="343" fill="报告" font-size="8" font-weight="normal" text-anchor="middle">#34d399</text>
|
||||
<line x1="880" y1="370" x2="300" y2="440" stroke="启动辩论" stroke-width="1.5" marker-end="url(#arrowhead)"/>
|
||||
<rect x="566" y="397" width="49" height="14" fill="#0f172a" rx="2"/>
|
||||
<text x="590" y="408" fill="启动辩论" font-size="8" font-weight="normal" text-anchor="middle">#a78bfa</text>
|
||||
<line x1="880" y1="370" x2="490" y2="440" stroke="启动辩论" stroke-width="1.5" marker-end="url(#arrowhead)"/>
|
||||
<rect x="661" y="397" width="49" height="14" fill="#0f172a" rx="2"/>
|
||||
<text x="685" y="408" fill="启动辩论" font-size="8" font-weight="normal" text-anchor="middle">#a78bfa</text>
|
||||
<line x1="370" y1="465" x2="610" y2="465" stroke="多方论据" stroke-width="1.5" marker-end="url(#arrowhead)"/>
|
||||
<rect x="466" y="457" width="49" height="14" fill="#0f172a" rx="2"/>
|
||||
<text x="490" y="468" fill="多方论据" font-size="8" font-weight="normal" text-anchor="middle">#f87171</text>
|
||||
<line x1="560" y1="465" x2="610" y2="465" stroke="空方论据" stroke-width="1.5" marker-end="url(#arrowhead)"/>
|
||||
<rect x="561" y="457" width="49" height="14" fill="#0f172a" rx="2"/>
|
||||
<text x="585" y="468" fill="空方论据" font-size="8" font-weight="normal" text-anchor="middle">#f87171</text>
|
||||
<line x1="680" y1="490" x2="650" y2="560" stroke="辩论摘要" stroke-width="1.5" marker-end="url(#arrowhead)"/>
|
||||
<rect x="641" y="517" width="49" height="14" fill="#0f172a" rx="2"/>
|
||||
<text x="665" y="528" fill="辩论摘要" font-size="8" font-weight="normal" text-anchor="middle">#fb923c</text>
|
||||
<line x1="650" y1="615" x2="260" y2="680" stroke="草案" stroke-width="1.5" stroke-dasharray="5,3" marker-end="url(#arrowhead)"/>
|
||||
<rect x="431" y="639" width="49" height="14" fill="#0f172a" rx="2"/>
|
||||
<text x="455" y="650" fill="草案" font-size="8" font-weight="normal" text-anchor="middle">#38bdf8</text>
|
||||
<line x1="650" y1="615" x2="462" y2="680" stroke="草案" stroke-width="1.5" stroke-dasharray="5,3" marker-end="url(#arrowhead)"/>
|
||||
<rect x="532" y="639" width="49" height="14" fill="#0f172a" rx="2"/>
|
||||
<text x="556" y="650" fill="草案" font-size="8" font-weight="normal" text-anchor="middle">#38bdf8</text>
|
||||
<line x1="650" y1="615" x2="660" y2="680" stroke="草案" stroke-width="1.5" stroke-dasharray="5,3" marker-end="url(#arrowhead)"/>
|
||||
<rect x="631" y="639" width="49" height="14" fill="#0f172a" rx="2"/>
|
||||
<text x="655" y="650" fill="草案" font-size="8" font-weight="normal" text-anchor="middle">#38bdf8</text>
|
||||
<line x1="330" y1="707" x2="800" y2="707" stroke="评估" stroke-width="1.5" marker-end="url(#arrowhead)"/>
|
||||
<rect x="541" y="699" width="49" height="14" fill="#0f172a" rx="2"/>
|
||||
<text x="565" y="710" fill="评估" font-size="8" font-weight="normal" text-anchor="middle">#34d399</text>
|
||||
<line x1="535" y1="707" x2="800" y2="707" stroke="评估" stroke-width="1.5" marker-end="url(#arrowhead)"/>
|
||||
<rect x="643" y="699" width="49" height="14" fill="#0f172a" rx="2"/>
|
||||
<text x="667" y="710" fill="评估" font-size="8" font-weight="normal" text-anchor="middle">#34d399</text>
|
||||
<line x1="730" y1="707" x2="800" y2="707" stroke="评估" stroke-width="1.5" marker-end="url(#arrowhead)"/>
|
||||
<rect x="741" y="699" width="49" height="14" fill="#0f172a" rx="2"/>
|
||||
<text x="765" y="710" fill="评估" font-size="8" font-weight="normal" text-anchor="middle">#34d399</text>
|
||||
<line x1="870" y1="735" x2="650" y2="800" stroke="最终决策" stroke-width="1.5" marker-end="url(#arrowhead)"/>
|
||||
<rect x="736" y="759" width="49" height="14" fill="#0f172a" rx="2"/>
|
||||
<text x="760" y="770" fill="最终决策" font-size="8" font-weight="normal" text-anchor="middle">#22d3ee</text>
|
||||
<line x1="125" y1="370" x2="172" y2="930" stroke="数据" stroke-width="1.5" stroke-dasharray="5,3" marker-end="url(#arrowhead)"/>
|
||||
<rect x="124" y="642" width="49" height="14" fill="#0f172a" rx="2"/>
|
||||
<text x="148" y="653" fill="数据" font-size="8" font-weight="normal" text-anchor="middle">#94a3b8</text>
|
||||
<line x1="685" y1="370" x2="172" y2="930" stroke="数据" stroke-width="1.5" stroke-dasharray="5,3" marker-end="url(#arrowhead)"/>
|
||||
<rect x="404" y="642" width="49" height="14" fill="#0f172a" rx="2"/>
|
||||
<text x="428" y="653" fill="数据" font-size="8" font-weight="normal" text-anchor="middle">#94a3b8</text>
|
||||
<line x1="495" y1="370" x2="172" y2="930" stroke="数据" stroke-width="1.5" stroke-dasharray="5,3" marker-end="url(#arrowhead)"/>
|
||||
<rect x="309" y="642" width="49" height="14" fill="#0f172a" rx="2"/>
|
||||
<text x="333" y="653" fill="数据" font-size="8" font-weight="normal" text-anchor="middle">#94a3b8</text>
|
||||
<line x1="265" y1="957" x2="320" y2="957" stroke="fallback" stroke-width="1.5" stroke-dasharray="5,3" marker-end="url(#arrowhead)"/>
|
||||
<rect x="268" y="949" width="49" height="14" fill="#0f172a" rx="2"/>
|
||||
<text x="292" y="960" fill="fallback" font-size="8" font-weight="normal" text-anchor="middle">#64748b</text>
|
||||
<line x1="485" y1="957" x2="540" y2="957" stroke="fallback" stroke-width="1.5" stroke-dasharray="5,3" marker-end="url(#arrowhead)"/>
|
||||
<rect x="488" y="949" width="49" height="14" fill="#0f172a" rx="2"/>
|
||||
<text x="512" y="960" fill="fallback" font-size="8" font-weight="normal" text-anchor="middle">#64748b</text>
|
||||
<line x1="300" y1="490" x2="857" y2="930" stroke="推理" stroke-width="1.5" stroke-dasharray="5,3" marker-end="url(#arrowhead)"/>
|
||||
<rect x="554" y="702" width="49" height="14" fill="#0f172a" rx="2"/>
|
||||
<text x="578" y="713" fill="推理" font-size="8" font-weight="normal" text-anchor="middle">#94a3b8</text>
|
||||
<line x1="490" y1="490" x2="857" y2="930" stroke="推理" stroke-width="1.5" stroke-dasharray="5,3" marker-end="url(#arrowhead)"/>
|
||||
<rect x="649" y="702" width="49" height="14" fill="#0f172a" rx="2"/>
|
||||
<text x="673" y="713" fill="推理" font-size="8" font-weight="normal" text-anchor="middle">#94a3b8</text>
|
||||
<rect x="30" y="1090" width="850" height="60" rx="6" fill="rgba(15, 23, 42, 0.8)" stroke="#1e293b" stroke-width="1.5" opacity="1.0"/>
|
||||
<text x="45" y="1110" fill="#64748b" font-size="10" font-weight="normal" text-anchor="start">组件类型:</text>
|
||||
<rect x="120" y="1098" width="16" height="16" rx="3" fill="rgba(8, 51, 68, 0.4)" stroke="#22d3ee" stroke-width="1.5" opacity="1.0"/>
|
||||
<text x="142" y="1110" fill="#94a3b8" font-size="9" font-weight="normal" text-anchor="start">前端</text>
|
||||
<rect x="195" y="1098" width="16" height="16" rx="3" fill="rgba(6, 78, 59, 0.4)" stroke="#34d399" stroke-width="1.5" opacity="1.0"/>
|
||||
<text x="217" y="1110" fill="#94a3b8" font-size="9" font-weight="normal" text-anchor="start">后端</text>
|
||||
<rect x="270" y="1098" width="16" height="16" rx="3" fill="rgba(76, 29, 149, 0.4)" stroke="#a78bfa" stroke-width="1.5" opacity="1.0"/>
|
||||
<text x="292" y="1110" fill="#94a3b8" font-size="9" font-weight="normal" text-anchor="start">数据库</text>
|
||||
<rect x="345" y="1098" width="16" height="16" rx="3" fill="rgba(120, 53, 15, 0.3)" stroke="#fbbf24" stroke-width="1.5" opacity="1.0"/>
|
||||
<text x="367" y="1110" fill="#94a3b8" font-size="9" font-weight="normal" text-anchor="start">外部API</text>
|
||||
<rect x="420" y="1098" width="16" height="16" rx="3" fill="rgba(136, 19, 55, 0.4)" stroke="#fb7185" stroke-width="1.5" opacity="1.0"/>
|
||||
<text x="442" y="1110" fill="#94a3b8" font-size="9" font-weight="normal" text-anchor="start">认证</text>
|
||||
<rect x="495" y="1098" width="16" height="16" rx="3" fill="rgba(30, 41, 59, 0.5)" stroke="#94a3b8" stroke-width="1.5" opacity="1.0"/>
|
||||
<text x="517" y="1110" fill="#94a3b8" font-size="9" font-weight="normal" text-anchor="start">通用</text>
|
||||
<text x="45" y="1135" fill="#64748b" font-size="10" font-weight="normal" text-anchor="start">连接类型:</text>
|
||||
<line x1="120" y1="1130" x2="140" y2="1130" stroke="#64748b" stroke-width="1.5" marker-end="url(#arrowhead)"/>
|
||||
<text x="148" y="1134" fill="#94a3b8" font-size="9" font-weight="normal" text-anchor="start">数据流</text>
|
||||
<line x1="195" y1="1130" x2="215" y2="1130" stroke="#fb7185" stroke-width="1.5" marker-end="url(#arrowhead-rose)"/>
|
||||
<text x="223" y="1134" fill="#94a3b8" font-size="9" font-weight="normal" text-anchor="start">认证流</text>
|
||||
<line x1="270" y1="1130" x2="290" y2="1130" stroke="#fbbf24" stroke-width="1.5" marker-end="url(#arrowhead-amber)"/>
|
||||
<text x="298" y="1134" fill="#94a3b8" font-size="9" font-weight="normal" text-anchor="start">配置</text>
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
<div class="footer">
|
||||
生成时间: 2026-05-05 19:42 | Hand-Drawn Diagram · Zero Token Cost
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,121 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>TradingAgents 单次股票分析流程</title>
|
||||
|
||||
<style>
|
||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
body {
|
||||
font-family: 'Noto Sans Mono CJK SC', 'JetBrains Mono', 'WenQuanYi Zen Hei Mono', monospace;
|
||||
background: #020617;
|
||||
min-height: 100vh;
|
||||
padding: 2rem;
|
||||
color: white;
|
||||
}
|
||||
.container { max-width: 1200px; margin: 0 auto; }
|
||||
.header { margin-bottom: 2rem; }
|
||||
.header-row { display: flex; align-items: center; gap: 1rem; margin-bottom: 0.5rem; }
|
||||
.pulse-dot {
|
||||
width: 12px; height: 12px; background: #22d3ee; border-radius: 50%;
|
||||
animation: pulse 2s infinite;
|
||||
}
|
||||
@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } }
|
||||
h1 { font-size: 1.5rem; font-weight: 700; letter-spacing: -0.025em; }
|
||||
.subtitle { color: #94a3b8; font-size: 0.875rem; margin-left: 1.75rem; }
|
||||
.diagram-container {
|
||||
background: rgba(15, 23, 42, 0.5); border-radius: 1rem;
|
||||
border: 1px solid #1e293b; padding: 1.5rem; overflow-x: auto;
|
||||
}
|
||||
svg { width: 100%; min-width: 900px; display: block; }
|
||||
.cards {
|
||||
display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
|
||||
gap: 1rem; margin-top: 2rem;
|
||||
}
|
||||
.card {
|
||||
background: rgba(15, 23, 42, 0.5); border-radius: 0.75rem;
|
||||
border: 1px solid #1e293b; padding: 1.25rem;
|
||||
}
|
||||
.card-header { display: flex; align-items: center; gap: 0.5rem; margin-bottom: 0.75rem; }
|
||||
.card-dot { width: 8px; height: 8px; border-radius: 50%; }
|
||||
.card h3 { font-size: 0.875rem; font-weight: 600; color: #e2e8f0; }
|
||||
.card ul { list-style: none; font-size: 0.75rem; color: #94a3b8; line-height: 1.8; }
|
||||
.card li::before { content: "• "; color: #64748b; }
|
||||
.footer {
|
||||
margin-top: 2rem; padding-top: 1rem; border-top: 1px solid #1e293b;
|
||||
font-size: 0.75rem; color: #64748b; text-align: center;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="header">
|
||||
<div class="header-row">
|
||||
<div class="pulse-dot"></div>
|
||||
<h1>TradingAgents 单次股票分析流程</h1>
|
||||
</div>
|
||||
<div class="subtitle">系统架构图 · Hand-Drawn SVG</div>
|
||||
</div>
|
||||
<div class="diagram-container">
|
||||
<svg viewBox="0 0 800 660" xmlns="http://www.w3.org/2000/svg" font-family="'Noto Sans Mono CJK SC', 'JetBrains Mono', 'WenQuanYi Zen Hei Mono', monospace">
|
||||
<defs>
|
||||
<pattern id="grid" width="40" height="40" patternUnits="userSpaceOnUse">
|
||||
<path d="M 40 0 L 0 0 0 40" fill="none" stroke="#1e293b" stroke-width="0.5"/>
|
||||
</pattern>
|
||||
<filter id="dropShadow" x="-50%" y="-50%" width="200%" height="200%">
|
||||
<feDropShadow dx="0" dy="2" stdDeviation="3" flood-opacity="0.3"/>
|
||||
</filter>
|
||||
<marker id="arrowhead" markerWidth="10" markerHeight="7" refX="9" refY="3.5" orient="auto">
|
||||
<polygon points="0 0, 10 3.5, 0 7" fill="#64748b"/>
|
||||
</marker>
|
||||
<marker id="arrowhead-cyan" markerWidth="10" markerHeight="7" refX="9" refY="3.5" orient="auto">
|
||||
<polygon points="0 0, 10 3.5, 0 7" fill="#22d3ee"/>
|
||||
</marker>
|
||||
<marker id="arrowhead-green" markerWidth="10" markerHeight="7" refX="9" refY="3.5" orient="auto">
|
||||
<polygon points="0 0, 10 3.5, 0 7" fill="#34d399"/>
|
||||
</marker>
|
||||
<marker id="arrowhead-rose" markerWidth="10" markerHeight="7" refX="9" refY="3.5" orient="auto">
|
||||
<polygon points="0 0, 10 3.5, 0 7" fill="#fb7185"/>
|
||||
</marker>
|
||||
<marker id="arrowhead-amber" markerWidth="10" markerHeight="7" refX="9" refY="3.5" orient="auto">
|
||||
<polygon points="0 0, 10 3.5, 0 7" fill="#fbbf24"/>
|
||||
</marker>
|
||||
<marker id="arrowhead-purple" markerWidth="10" markerHeight="7" refX="9" refY="3.5" orient="auto">
|
||||
<polygon points="0 0, 10 3.5, 0 7" fill="#a78bfa"/>
|
||||
</marker>
|
||||
</defs>
|
||||
<rect width="800" height="660" fill="url(#grid)"/>
|
||||
<rect x="340" y="50" width="120" height="40" rx="20" fill="rgba(6, 78, 59, 0.4)" stroke="#34d399" stroke-width="1.5" opacity="1.0"/>
|
||||
<text x="400" y="74" fill="#e2e8f0" font-size="11" font-weight="600" text-anchor="middle">用户输入
|
||||
股票代码 + 日期</text>
|
||||
<rect x="320" y="130" width="160" height="50" rx="6" fill="#0f172a" stroke="#94a3b8" stroke-width="1.5" opacity="1.0"/>
|
||||
<rect x="320" y="130" width="160" height="50" rx="6" fill="rgba(30, 41, 59, 0.5)" stroke="#94a3b8" stroke-width="1.5" opacity="1.0"/>
|
||||
<text x="400" y="148" fill="#e2e8f0" font-size="11" font-weight="600" text-anchor="middle">并行数据采集
|
||||
(4个分析师同时工作)</text>
|
||||
<rect x="320" y="210" width="160" height="50" rx="6" fill="#0f172a" stroke="#94a3b8" stroke-width="1.5" opacity="1.0"/>
|
||||
<rect x="320" y="210" width="160" height="50" rx="6" fill="rgba(30, 41, 59, 0.5)" stroke="#94a3b8" stroke-width="1.5" opacity="1.0"/>
|
||||
<text x="400" y="228" fill="#e2e8f0" font-size="11" font-weight="600" text-anchor="middle">研究经理汇总
|
||||
收集4份分析报告</text>
|
||||
<polygon points="400,290 440,330 400,370 360,330" fill="rgba(251, 146, 60, 0.3)" stroke="#fb923c" stroke-width="1.5"/>
|
||||
<text x="400" y="334" fill="#e2e8f0" font-size="10" font-weight="normal" text-anchor="middle">多空辩论
|
||||
Bull vs Bear × N轮</text>
|
||||
<rect x="320" y="370" width="160" height="50" rx="6" fill="#0f172a" stroke="#94a3b8" stroke-width="1.5" opacity="1.0"/>
|
||||
<rect x="320" y="370" width="160" height="50" rx="6" fill="rgba(30, 41, 59, 0.5)" stroke="#94a3b8" stroke-width="1.5" opacity="1.0"/>
|
||||
<text x="400" y="388" fill="#e2e8f0" font-size="11" font-weight="600" text-anchor="middle">交易员决策
|
||||
综合辩论形成草案</text>
|
||||
<polygon points="400,450 440,490 400,530 360,490" fill="rgba(251, 146, 60, 0.3)" stroke="#fb923c" stroke-width="1.5"/>
|
||||
<text x="400" y="494" fill="#e2e8f0" font-size="10" font-weight="normal" text-anchor="middle">三级风控评审
|
||||
激进/保守/中立</text>
|
||||
<rect x="340" y="530" width="120" height="40" rx="20" fill="rgba(136, 19, 55, 0.4)" stroke="#fb7185" stroke-width="1.5" opacity="1.0"/>
|
||||
<text x="400" y="554" fill="#e2e8f0" font-size="11" font-weight="600" text-anchor="middle">最终输出
|
||||
Buy / Sell / Hold</text>
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
<div class="footer">
|
||||
生成时间: 2026-05-05 19:42 | Hand-Drawn Diagram · Zero Token Cost
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,31 @@
|
||||
from tradingagents.graph.trading_graph import TradingAgentsGraph
|
||||
from tradingagents.default_config import DEFAULT_CONFIG
|
||||
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
# Create a custom config
|
||||
config = DEFAULT_CONFIG.copy()
|
||||
config["deep_think_llm"] = "gpt-5.4-mini" # Use a different model
|
||||
config["quick_think_llm"] = "gpt-5.4-mini" # Use a different model
|
||||
config["max_debate_rounds"] = 1 # Increase debate rounds
|
||||
|
||||
# Configure data vendors (default uses yfinance, no extra API keys needed)
|
||||
config["data_vendors"] = {
|
||||
"core_stock_apis": "yfinance", # Options: alpha_vantage, yfinance
|
||||
"technical_indicators": "yfinance", # Options: alpha_vantage, yfinance
|
||||
"fundamental_data": "yfinance", # Options: alpha_vantage, yfinance
|
||||
"news_data": "yfinance", # Options: alpha_vantage, yfinance
|
||||
}
|
||||
|
||||
# Initialize with custom config
|
||||
ta = TradingAgentsGraph(debug=True, config=config)
|
||||
|
||||
# forward propagate
|
||||
_, decision = ta.propagate("NVDA", "2024-05-10")
|
||||
print(decision)
|
||||
|
||||
# Memorize mistakes and reflect
|
||||
# ta.reflect_and_remember(1000) # parameter is the position returns
|
||||
@@ -0,0 +1,54 @@
|
||||
[build-system]
|
||||
requires = ["setuptools>=61.0"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "tradingagents"
|
||||
version = "0.2.4"
|
||||
description = "TradingAgents: Multi-Agents LLM Financial Trading Framework"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.10"
|
||||
dependencies = [
|
||||
"langchain-core>=0.3.81",
|
||||
"backtrader>=1.9.78.123",
|
||||
"langchain-anthropic>=0.3.15",
|
||||
"langchain-experimental>=0.3.4",
|
||||
"langchain-google-genai>=4.0.0",
|
||||
"langchain-openai>=0.3.23",
|
||||
"langgraph>=0.4.8",
|
||||
"langgraph-checkpoint-sqlite>=2.0.0",
|
||||
"pandas>=2.3.0",
|
||||
"parsel>=1.10.0",
|
||||
"pytz>=2025.2",
|
||||
"questionary>=2.1.0",
|
||||
"redis>=6.2.0",
|
||||
"requests>=2.32.4",
|
||||
"rich>=14.0.0",
|
||||
"typer>=0.21.0",
|
||||
"setuptools>=80.9.0",
|
||||
"stockstats>=0.6.5",
|
||||
"tqdm>=4.67.1",
|
||||
"typing-extensions>=4.14.0",
|
||||
"yfinance>=0.2.63",
|
||||
]
|
||||
|
||||
[project.scripts]
|
||||
tradingagents = "cli.main:app"
|
||||
|
||||
[tool.setuptools.packages.find]
|
||||
include = ["tradingagents*", "cli*"]
|
||||
|
||||
[tool.setuptools.package-data]
|
||||
cli = ["static/*"]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
testpaths = ["tests"]
|
||||
addopts = "-ra --strict-markers"
|
||||
markers = [
|
||||
"unit: fast isolated unit tests",
|
||||
"integration: tests requiring external services",
|
||||
"smoke: quick sanity-check tests",
|
||||
]
|
||||
filterwarnings = [
|
||||
"ignore::DeprecationWarning",
|
||||
]
|
||||
@@ -0,0 +1 @@
|
||||
.
|
||||
@@ -0,0 +1,176 @@
|
||||
"""End-to-end smoke for structured-output agents against a real LLM provider.
|
||||
|
||||
Runs the three decision-making agents (Research Manager, Trader, Portfolio
|
||||
Manager) directly with their structured-output bindings and prints the
|
||||
typed Pydantic instance + the rendered markdown for each. Use this to
|
||||
verify a provider's native structured-output mode (json_schema for
|
||||
OpenAI / xAI / DeepSeek / Qwen / GLM, response_schema for Gemini, tool-use
|
||||
for Anthropic) returns clean instances on the schemas we ship.
|
||||
|
||||
Usage:
|
||||
OPENAI_API_KEY=... python scripts/smoke_structured_output.py openai
|
||||
GOOGLE_API_KEY=... python scripts/smoke_structured_output.py google
|
||||
ANTHROPIC_API_KEY=... python scripts/smoke_structured_output.py anthropic
|
||||
DEEPSEEK_API_KEY=... python scripts/smoke_structured_output.py deepseek
|
||||
|
||||
The script does NOT call propagate(), to keep the surface tight and the
|
||||
cost low — it exercises only the three structured-output calls we just
|
||||
added, plus the heuristic SignalProcessor.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import sys
|
||||
|
||||
from tradingagents.agents.managers.portfolio_manager import create_portfolio_manager
|
||||
from tradingagents.agents.managers.research_manager import create_research_manager
|
||||
from tradingagents.agents.trader.trader import create_trader
|
||||
from tradingagents.graph.signal_processing import SignalProcessor
|
||||
from tradingagents.llm_clients import create_llm_client
|
||||
|
||||
|
||||
PROVIDER_DEFAULTS = {
|
||||
"openai": ("gpt-5.4-mini", None),
|
||||
"google": ("gemini-2.5-flash", None),
|
||||
"anthropic": ("claude-sonnet-4-6", None),
|
||||
"deepseek": ("deepseek-v4-flash", None),
|
||||
"qwen": ("qwen-plus", None),
|
||||
"glm": ("glm-5", None),
|
||||
"xai": ("grok-4", None),
|
||||
}
|
||||
|
||||
|
||||
# Minimal but realistic state for the three agents.
|
||||
DEBATE_HISTORY = """
|
||||
Bull Analyst: NVDA's data-center revenue grew 60% YoY last quarter, driven by
|
||||
Blackwell ramp; sovereign AI deals with multiple governments add a $40B+
|
||||
multi-year tailwind. Margins remain above peer average.
|
||||
|
||||
Bear Analyst: Concentration risk is real — top three customers are >40% of
|
||||
revenue. Any pause in hyperscaler capex would compress the multiple. China
|
||||
export restrictions still cap a meaningful portion of demand.
|
||||
"""
|
||||
|
||||
|
||||
def _make_rm_state():
|
||||
return {
|
||||
"company_of_interest": "NVDA",
|
||||
"investment_debate_state": {
|
||||
"history": DEBATE_HISTORY,
|
||||
"bull_history": "Bull Analyst: NVDA's data-center revenue grew 60% YoY...",
|
||||
"bear_history": "Bear Analyst: Concentration risk is real...",
|
||||
"current_response": "",
|
||||
"judge_decision": "",
|
||||
"count": 1,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _make_trader_state(investment_plan: str):
|
||||
return {
|
||||
"company_of_interest": "NVDA",
|
||||
"investment_plan": investment_plan,
|
||||
}
|
||||
|
||||
|
||||
def _make_pm_state(investment_plan: str, trader_plan: str):
|
||||
return {
|
||||
"company_of_interest": "NVDA",
|
||||
"past_context": "",
|
||||
"risk_debate_state": {
|
||||
"history": "Aggressive: lean in. Conservative: trim. Neutral: balanced sizing.",
|
||||
"aggressive_history": "Aggressive: ...",
|
||||
"conservative_history": "Conservative: ...",
|
||||
"neutral_history": "Neutral: ...",
|
||||
"judge_decision": "",
|
||||
"current_aggressive_response": "",
|
||||
"current_conservative_response": "",
|
||||
"current_neutral_response": "",
|
||||
"count": 1,
|
||||
},
|
||||
"market_report": "Market report.",
|
||||
"sentiment_report": "Sentiment report.",
|
||||
"news_report": "News report.",
|
||||
"fundamentals_report": "Fundamentals report.",
|
||||
"investment_plan": investment_plan,
|
||||
"trader_investment_plan": trader_plan,
|
||||
}
|
||||
|
||||
|
||||
def _print_section(title: str, content: str) -> None:
|
||||
bar = "=" * 70
|
||||
print(f"\n{bar}\n{title}\n{bar}\n{content}")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("provider", choices=list(PROVIDER_DEFAULTS.keys()))
|
||||
parser.add_argument("--deep-model", default=None, help="Override deep_think_llm")
|
||||
parser.add_argument("--quick-model", default=None, help="Override quick_think_llm")
|
||||
args = parser.parse_args()
|
||||
|
||||
default_model, _ = PROVIDER_DEFAULTS[args.provider]
|
||||
deep_model = args.deep_model or default_model
|
||||
quick_model = args.quick_model or default_model
|
||||
|
||||
print(f"Provider: {args.provider}")
|
||||
print(f"Deep model: {deep_model}")
|
||||
print(f"Quick model: {quick_model}")
|
||||
|
||||
# Build the LLM clients via the framework's factory.
|
||||
deep_client = create_llm_client(provider=args.provider, model=deep_model)
|
||||
quick_client = create_llm_client(provider=args.provider, model=quick_model)
|
||||
deep_llm = deep_client.get_llm()
|
||||
quick_llm = quick_client.get_llm()
|
||||
|
||||
# 1) Research Manager
|
||||
rm = create_research_manager(deep_llm)
|
||||
rm_result = rm(_make_rm_state())
|
||||
investment_plan = rm_result["investment_plan"]
|
||||
_print_section("[1] Research Manager — investment_plan", investment_plan)
|
||||
|
||||
# 2) Trader (consumes RM's plan)
|
||||
trader = create_trader(quick_llm)
|
||||
trader_result = trader(_make_trader_state(investment_plan))
|
||||
trader_plan = trader_result["trader_investment_plan"]
|
||||
_print_section("[2] Trader — trader_investment_plan", trader_plan)
|
||||
|
||||
# 3) Portfolio Manager (consumes both)
|
||||
pm = create_portfolio_manager(deep_llm)
|
||||
pm_result = pm(_make_pm_state(investment_plan, trader_plan))
|
||||
final_decision = pm_result["final_trade_decision"]
|
||||
_print_section("[3] Portfolio Manager — final_trade_decision", final_decision)
|
||||
|
||||
# 4) SignalProcessor extracts the rating with zero LLM calls.
|
||||
sp = SignalProcessor()
|
||||
rating = sp.process_signal(final_decision)
|
||||
_print_section("[4] SignalProcessor → rating", rating)
|
||||
|
||||
# 5) Lightweight checks: each rendered output should carry the expected
|
||||
# section headers so downstream consumers (memory log, CLI display,
|
||||
# saved reports) keep working.
|
||||
checks = [
|
||||
("Research Manager", investment_plan, ["**Recommendation**:"]),
|
||||
("Trader", trader_plan, ["**Action**:", "FINAL TRANSACTION PROPOSAL:"]),
|
||||
("Portfolio Manager", final_decision, ["**Rating**:", "**Executive Summary**:", "**Investment Thesis**:"]),
|
||||
]
|
||||
print("\n" + "=" * 70 + "\nStructure checks\n" + "=" * 70)
|
||||
failures = 0
|
||||
for name, text, required in checks:
|
||||
for marker in required:
|
||||
ok = marker in text
|
||||
print(f" {'PASS' if ok else 'FAIL'} {name}: contains {marker!r}")
|
||||
failures += int(not ok)
|
||||
|
||||
print()
|
||||
if failures:
|
||||
print(f"Smoke FAILED: {failures} structure check(s) missing.")
|
||||
return 1
|
||||
print("Smoke PASSED: structured output → rendered markdown chain works for", args.provider)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,11 @@
|
||||
import time
|
||||
from tradingagents.dataflows.y_finance import get_YFin_data_online, get_stock_stats_indicators_window, get_balance_sheet as get_yfinance_balance_sheet, get_cashflow as get_yfinance_cashflow, get_income_statement as get_yfinance_income_statement, get_insider_transactions as get_yfinance_insider_transactions
|
||||
|
||||
print("Testing optimized implementation with 30-day lookback:")
|
||||
start_time = time.time()
|
||||
result = get_stock_stats_indicators_window("AAPL", "macd", "2024-11-01", 30)
|
||||
end_time = time.time()
|
||||
|
||||
print(f"Execution time: {end_time - start_time:.2f} seconds")
|
||||
print(f"Result length: {len(result)} characters")
|
||||
print(result)
|
||||
@@ -0,0 +1,87 @@
|
||||
#!/usr/bin/env python3
|
||||
"""调试 publish 流程,找出 600383 发布失败的原因。"""
|
||||
|
||||
import sys
|
||||
import json
|
||||
import os
|
||||
|
||||
sys.path.insert(0, '/home/ubuntu/.nanobot/workspace/skills/baoyu-post-to-wechat')
|
||||
|
||||
# 1. 读取 600383 的分析结果
|
||||
with open('/home/ubuntu/nanocode/TradingAgents/logs/tasks/600383_20260610161057.json', 'r') as f:
|
||||
task = json.load(f)
|
||||
|
||||
state = task["result"]
|
||||
print("✅ 读取 600383 分析结果成功")
|
||||
|
||||
# 2. 测试 Markdown 组装
|
||||
from tradingagents.publish.wechat_publisher import _build_markdown, publish_analysis_result
|
||||
|
||||
md = _build_markdown(state, "600383", "2026-06-10")
|
||||
print(f"✅ Markdown 组装成功,长度: {len(md)} 字符")
|
||||
|
||||
# 3. 测试保存到磁盘
|
||||
results_dir = os.path.join(os.path.expanduser("~"), "TradingAgents", "logs")
|
||||
publish_dir = os.path.join(results_dir, "600383", "published")
|
||||
os.makedirs(publish_dir, exist_ok=True)
|
||||
md_path = os.path.join(publish_dir, "analysis_2026-06-10.md")
|
||||
with open(md_path, "w", encoding="utf-8") as f:
|
||||
f.write(md)
|
||||
print(f"✅ Markdown 已保存到: {md_path}")
|
||||
|
||||
# 4. 测试 WeChatPublisher 初始化
|
||||
try:
|
||||
from baoyu_optimized import WeChatPublisher
|
||||
publisher = WeChatPublisher()
|
||||
print(f"✅ WeChatPublisher 初始化成功")
|
||||
print(f" 配置: {publisher.config}")
|
||||
except Exception as e:
|
||||
print(f"❌ WeChatPublisher 初始化失败: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
sys.exit(1)
|
||||
|
||||
# 5. 测试获取 access_token
|
||||
try:
|
||||
token = publisher.get_access_token()
|
||||
print(f"✅ 获取 access_token 成功: {token[:20]}...")
|
||||
except Exception as e:
|
||||
print(f"❌ 获取 access_token 失败: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
sys.exit(1)
|
||||
|
||||
# 6. 测试 blog_sync 导入(这是发布流程的一部分)
|
||||
print("\n🔍 测试 blog_sync 导入...")
|
||||
try:
|
||||
from blog_sync import sync_markdown_to_blog
|
||||
print("✅ blog_sync 导入成功")
|
||||
except Exception as e:
|
||||
print(f"❌ blog_sync 导入失败: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
|
||||
# 7. 检查封面图片是否存在
|
||||
cover = publisher.config.get('default_cover_image')
|
||||
print(f"\n🔍 检查封面图片: {cover}")
|
||||
if cover and os.path.exists(cover):
|
||||
print("✅ 封面图片存在")
|
||||
else:
|
||||
print(f"⚠️ 封面图片不存在或路径为空")
|
||||
|
||||
# 8. 测试解析 frontmatter(publish_markdown_with_images 的前几步)
|
||||
print("\n🔍 测试 Markdown 解析...")
|
||||
try:
|
||||
with open(md_path, 'r', encoding='utf-8') as f:
|
||||
content = f.read()
|
||||
frontmatter, body = publisher.markdown_parser.parse_frontmatter(content)
|
||||
print(f"✅ Frontmatter 解析成功: {frontmatter}")
|
||||
images = publisher.extract_images_from_markdown(body)
|
||||
print(f"✅ 提取到 {len(images)} 张图片")
|
||||
except Exception as e:
|
||||
print(f"❌ 解析失败: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
|
||||
print("\n--- 调试完成,未实际调用微信 API ---")
|
||||
print("如需测试完整发布流程,请手动调用 publisher.publish_markdown_with_images()")
|
||||
@@ -0,0 +1,42 @@
|
||||
"""Shared pytest fixtures that prevent CI hangs when API keys are absent."""
|
||||
|
||||
import os
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def pytest_configure(config):
|
||||
for marker in ("unit", "integration", "smoke"):
|
||||
config.addinivalue_line("markers", f"{marker}: {marker}-level tests")
|
||||
|
||||
|
||||
_API_KEY_ENV_VARS = (
|
||||
"OPENAI_API_KEY",
|
||||
"GOOGLE_API_KEY",
|
||||
"ANTHROPIC_API_KEY",
|
||||
"XAI_API_KEY",
|
||||
"DEEPSEEK_API_KEY",
|
||||
"DASHSCOPE_API_KEY",
|
||||
"ZHIPU_API_KEY",
|
||||
"OPENROUTER_API_KEY",
|
||||
"AZURE_OPENAI_API_KEY",
|
||||
"ALPHA_VANTAGE_API_KEY",
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _dummy_api_keys(monkeypatch):
|
||||
for env_var in _API_KEY_ENV_VARS:
|
||||
monkeypatch.setenv(env_var, os.environ.get(env_var, "placeholder"))
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def mock_llm_client():
|
||||
client = MagicMock()
|
||||
client.get_llm.return_value = MagicMock()
|
||||
with patch(
|
||||
"tradingagents.llm_clients.factory.create_llm_client",
|
||||
return_value=client,
|
||||
):
|
||||
yield client
|
||||
@@ -0,0 +1,147 @@
|
||||
"""Test checkpoint resume: crash mid-analysis, re-run resumes from last node."""
|
||||
|
||||
import sqlite3
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from typing import TypedDict
|
||||
|
||||
from langgraph.checkpoint.sqlite import SqliteSaver
|
||||
from langgraph.graph import END, StateGraph
|
||||
|
||||
from tradingagents.graph.checkpointer import (
|
||||
checkpoint_step,
|
||||
clear_checkpoint,
|
||||
get_checkpointer,
|
||||
has_checkpoint,
|
||||
thread_id,
|
||||
)
|
||||
|
||||
# Mutable flag to simulate crash on first run
|
||||
_should_crash = False
|
||||
|
||||
|
||||
class _SimpleState(TypedDict):
|
||||
count: int
|
||||
|
||||
|
||||
def _node_a(state: _SimpleState) -> dict:
|
||||
return {"count": state["count"] + 1}
|
||||
|
||||
|
||||
def _node_b(state: _SimpleState) -> dict:
|
||||
if _should_crash:
|
||||
raise RuntimeError("simulated mid-analysis crash")
|
||||
return {"count": state["count"] + 10}
|
||||
|
||||
|
||||
def _build_graph() -> StateGraph:
|
||||
builder = StateGraph(_SimpleState)
|
||||
builder.add_node("analyst", _node_a)
|
||||
builder.add_node("trader", _node_b)
|
||||
builder.set_entry_point("analyst")
|
||||
builder.add_edge("analyst", "trader")
|
||||
builder.add_edge("trader", END)
|
||||
return builder
|
||||
|
||||
|
||||
class TestCheckpointResume(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmpdir = tempfile.mkdtemp()
|
||||
self.ticker = "TEST"
|
||||
self.date = "2026-04-20"
|
||||
|
||||
def test_crash_and_resume(self):
|
||||
"""Crash at 'trader' node, then resume from checkpoint."""
|
||||
global _should_crash
|
||||
builder = _build_graph()
|
||||
tid = thread_id(self.ticker, self.date)
|
||||
cfg = {"configurable": {"thread_id": tid}}
|
||||
|
||||
# Run 1: crash at trader node
|
||||
_should_crash = True
|
||||
with get_checkpointer(self.tmpdir, self.ticker) as saver:
|
||||
graph = builder.compile(checkpointer=saver)
|
||||
with self.assertRaises(RuntimeError):
|
||||
graph.invoke({"count": 0}, config=cfg)
|
||||
|
||||
# Checkpoint should exist at step 1 (analyst completed)
|
||||
self.assertTrue(has_checkpoint(self.tmpdir, self.ticker, self.date))
|
||||
step = checkpoint_step(self.tmpdir, self.ticker, self.date)
|
||||
self.assertEqual(step, 1)
|
||||
|
||||
# Run 2: resume — trader succeeds this time
|
||||
_should_crash = False
|
||||
with get_checkpointer(self.tmpdir, self.ticker) as saver:
|
||||
graph = builder.compile(checkpointer=saver)
|
||||
result = graph.invoke(None, config=cfg)
|
||||
|
||||
# analyst added 1, trader added 10 → 11
|
||||
self.assertEqual(result["count"], 11)
|
||||
|
||||
def test_clear_checkpoint_allows_fresh_start(self):
|
||||
"""After clearing, the graph starts from scratch."""
|
||||
global _should_crash
|
||||
builder = _build_graph()
|
||||
tid = thread_id(self.ticker, self.date)
|
||||
cfg = {"configurable": {"thread_id": tid}}
|
||||
|
||||
# Create a checkpoint by crashing
|
||||
_should_crash = True
|
||||
with get_checkpointer(self.tmpdir, self.ticker) as saver:
|
||||
graph = builder.compile(checkpointer=saver)
|
||||
with self.assertRaises(RuntimeError):
|
||||
graph.invoke({"count": 0}, config=cfg)
|
||||
|
||||
self.assertTrue(has_checkpoint(self.tmpdir, self.ticker, self.date))
|
||||
|
||||
# Clear it
|
||||
clear_checkpoint(self.tmpdir, self.ticker, self.date)
|
||||
self.assertFalse(has_checkpoint(self.tmpdir, self.ticker, self.date))
|
||||
|
||||
# Fresh run succeeds from scratch
|
||||
_should_crash = False
|
||||
with get_checkpointer(self.tmpdir, self.ticker) as saver:
|
||||
graph = builder.compile(checkpointer=saver)
|
||||
result = graph.invoke({"count": 0}, config=cfg)
|
||||
|
||||
self.assertEqual(result["count"], 11)
|
||||
|
||||
|
||||
def test_different_date_starts_fresh(self):
|
||||
"""A different date must NOT resume from an existing checkpoint."""
|
||||
global _should_crash
|
||||
builder = _build_graph()
|
||||
date2 = "2026-04-21"
|
||||
|
||||
# Run with date1 — crash to leave a checkpoint
|
||||
_should_crash = True
|
||||
tid1 = thread_id(self.ticker, self.date)
|
||||
with get_checkpointer(self.tmpdir, self.ticker) as saver:
|
||||
graph = builder.compile(checkpointer=saver)
|
||||
with self.assertRaises(RuntimeError):
|
||||
graph.invoke({"count": 0}, config={"configurable": {"thread_id": tid1}})
|
||||
|
||||
self.assertTrue(has_checkpoint(self.tmpdir, self.ticker, self.date))
|
||||
|
||||
# date2 should have no checkpoint
|
||||
self.assertFalse(has_checkpoint(self.tmpdir, self.ticker, date2))
|
||||
|
||||
# Run with date2 — should start fresh and succeed
|
||||
_should_crash = False
|
||||
tid2 = thread_id(self.ticker, date2)
|
||||
self.assertNotEqual(tid1, tid2)
|
||||
|
||||
with get_checkpointer(self.tmpdir, self.ticker) as saver:
|
||||
graph = builder.compile(checkpointer=saver)
|
||||
result = graph.invoke({"count": 0}, config={"configurable": {"thread_id": tid2}})
|
||||
|
||||
# Fresh run: analyst +1, trader +10 = 11
|
||||
self.assertEqual(result["count"], 11)
|
||||
|
||||
# Original date checkpoint still exists (untouched)
|
||||
self.assertTrue(has_checkpoint(self.tmpdir, self.ticker, self.date))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,169 @@
|
||||
"""Tests for DeepSeekChatOpenAI thinking-mode behaviour.
|
||||
|
||||
Two pieces verified:
|
||||
|
||||
1. ``reasoning_content`` is captured on receive into the AIMessage's
|
||||
``additional_kwargs`` and re-attached on send so DeepSeek's API
|
||||
sees the same value across turns.
|
||||
2. ``with_structured_output`` raises NotImplementedError for
|
||||
``deepseek-reasoner`` so the agent factories' free-text fallback
|
||||
handles the request instead of failing at runtime.
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
import pytest
|
||||
from langchain_core.messages import AIMessage, HumanMessage
|
||||
from langchain_core.prompt_values import ChatPromptValue
|
||||
|
||||
from tradingagents.llm_clients.openai_client import (
|
||||
DeepSeekChatOpenAI,
|
||||
NormalizedChatOpenAI,
|
||||
_input_to_messages,
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# _input_to_messages — the helper that handles list / ChatPromptValue / other
|
||||
# (Gemini bot review note: non-list inputs must also work)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
class TestInputToMessages:
|
||||
def test_list_input_returned_as_is(self):
|
||||
msgs = [HumanMessage(content="hi")]
|
||||
assert _input_to_messages(msgs) is msgs
|
||||
|
||||
def test_chat_prompt_value_unwrapped(self):
|
||||
msgs = [HumanMessage(content="hi")]
|
||||
prompt_value = ChatPromptValue(messages=msgs)
|
||||
assert _input_to_messages(prompt_value) == msgs
|
||||
|
||||
def test_string_input_yields_empty_list(self):
|
||||
# A bare string isn't a message-bearing input; the caller's normal
|
||||
# langchain conversion happens upstream of _get_request_payload.
|
||||
assert _input_to_messages("hello") == []
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Reasoning content propagation across turns
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
class TestDeepSeekReasoningContent:
|
||||
def _client(self):
|
||||
os.environ.setdefault("DEEPSEEK_API_KEY", "placeholder")
|
||||
return DeepSeekChatOpenAI(
|
||||
model="deepseek-v4-flash",
|
||||
api_key="placeholder",
|
||||
base_url="https://api.deepseek.com",
|
||||
)
|
||||
|
||||
def test_capture_on_receive(self):
|
||||
"""When the response carries reasoning_content, it lands on the
|
||||
AIMessage's additional_kwargs so the next turn can echo it back."""
|
||||
client = self._client()
|
||||
result = client._create_chat_result(
|
||||
{
|
||||
"model": "deepseek-v4-flash",
|
||||
"choices": [
|
||||
{
|
||||
"index": 0,
|
||||
"message": {
|
||||
"role": "assistant",
|
||||
"content": "Plan: buy NVDA.",
|
||||
"reasoning_content": "Step 1: trend is up. Step 2: ...",
|
||||
},
|
||||
"finish_reason": "stop",
|
||||
}
|
||||
],
|
||||
"usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15},
|
||||
}
|
||||
)
|
||||
ai = result.generations[0].message
|
||||
assert ai.additional_kwargs["reasoning_content"] == "Step 1: trend is up. Step 2: ..."
|
||||
|
||||
def test_propagate_on_send(self):
|
||||
"""When an outgoing AIMessage carries reasoning_content, the request
|
||||
payload echoes it on the corresponding message dict."""
|
||||
client = self._client()
|
||||
prior = AIMessage(
|
||||
content="Plan",
|
||||
additional_kwargs={"reasoning_content": "weighed bull case"},
|
||||
)
|
||||
new_user = HumanMessage(content="Refine.")
|
||||
payload = client._get_request_payload([prior, new_user])
|
||||
# Find the assistant message in the payload
|
||||
assistant_dicts = [m for m in payload["messages"] if m.get("role") == "assistant"]
|
||||
assert assistant_dicts, "assistant message missing from outgoing payload"
|
||||
assert assistant_dicts[0]["reasoning_content"] == "weighed bull case"
|
||||
|
||||
def test_propagate_through_chat_prompt_value(self):
|
||||
"""Gemini bot review note: non-list inputs (ChatPromptValue) must
|
||||
also propagate reasoning_content."""
|
||||
client = self._client()
|
||||
prior = AIMessage(
|
||||
content="Plan",
|
||||
additional_kwargs={"reasoning_content": "weighed bull case"},
|
||||
)
|
||||
prompt_value = ChatPromptValue(messages=[prior, HumanMessage(content="Refine.")])
|
||||
payload = client._get_request_payload(prompt_value)
|
||||
assistant_dicts = [m for m in payload["messages"] if m.get("role") == "assistant"]
|
||||
assert assistant_dicts[0]["reasoning_content"] == "weighed bull case"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# deepseek-reasoner: structured output unavailable, falls through to free-text
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
class TestDeepSeekReasonerStructuredOutput:
|
||||
def test_with_structured_output_raises_for_reasoner(self):
|
||||
client = DeepSeekChatOpenAI(
|
||||
model="deepseek-reasoner",
|
||||
api_key="placeholder",
|
||||
base_url="https://api.deepseek.com",
|
||||
)
|
||||
from pydantic import BaseModel
|
||||
|
||||
class _Sample(BaseModel):
|
||||
answer: str
|
||||
|
||||
with pytest.raises(NotImplementedError):
|
||||
client.with_structured_output(_Sample)
|
||||
|
||||
def test_with_structured_output_works_for_v4(self):
|
||||
"""V4 models (non-reasoner) accept tool_choice; structured output works."""
|
||||
client = DeepSeekChatOpenAI(
|
||||
model="deepseek-v4-flash",
|
||||
api_key="placeholder",
|
||||
base_url="https://api.deepseek.com",
|
||||
)
|
||||
from pydantic import BaseModel
|
||||
|
||||
class _Sample(BaseModel):
|
||||
answer: str
|
||||
|
||||
# Should return a Runnable, not raise. (The actual API call would
|
||||
# require a real key; we only assert binding succeeds.)
|
||||
wrapped = client.with_structured_output(_Sample)
|
||||
assert wrapped is not None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Base class isolation: NormalizedChatOpenAI does NOT have DeepSeek behaviour
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
class TestBaseClassIsolation:
|
||||
def test_normalized_does_not_propagate_reasoning_content(self):
|
||||
"""The general-purpose NormalizedChatOpenAI must not carry
|
||||
DeepSeek-specific behaviour. Only the subclass does."""
|
||||
assert not hasattr(NormalizedChatOpenAI, "_get_request_payload") or (
|
||||
NormalizedChatOpenAI._get_request_payload
|
||||
is NormalizedChatOpenAI.__bases__[0]._get_request_payload
|
||||
)
|
||||
@@ -0,0 +1,31 @@
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from tradingagents.llm_clients.google_client import GoogleClient
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
class TestGoogleApiKeyStandardization(unittest.TestCase):
|
||||
"""Verify GoogleClient accepts unified api_key parameter."""
|
||||
|
||||
@patch("tradingagents.llm_clients.google_client.NormalizedChatGoogleGenerativeAI")
|
||||
def test_api_key_handling(self, mock_chat):
|
||||
test_cases = [
|
||||
("unified api_key is mapped", {"api_key": "test-key-123"}, "test-key-123"),
|
||||
("legacy google_api_key still works", {"google_api_key": "legacy-key-456"}, "legacy-key-456"),
|
||||
("unified api_key takes precedence", {"api_key": "unified", "google_api_key": "legacy"}, "unified"),
|
||||
]
|
||||
|
||||
for msg, kwargs, expected_key in test_cases:
|
||||
with self.subTest(msg=msg):
|
||||
mock_chat.reset_mock()
|
||||
client = GoogleClient("gemini-2.5-flash", **kwargs)
|
||||
client.get_llm()
|
||||
call_kwargs = mock_chat.call_args[1]
|
||||
self.assertEqual(call_kwargs.get("google_api_key"), expected_key)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,773 @@
|
||||
"""Tests for TradingMemoryLog — storage, deferred reflection, PM injection, legacy removal."""
|
||||
|
||||
import pytest
|
||||
import pandas as pd
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from tradingagents.agents.utils.memory import TradingMemoryLog
|
||||
from tradingagents.agents.schemas import PortfolioDecision, PortfolioRating
|
||||
from tradingagents.graph.reflection import Reflector
|
||||
from tradingagents.graph.trading_graph import TradingAgentsGraph
|
||||
from tradingagents.graph.propagation import Propagator
|
||||
from tradingagents.agents.managers.portfolio_manager import create_portfolio_manager
|
||||
|
||||
_SEP = TradingMemoryLog._SEPARATOR
|
||||
|
||||
DECISION_BUY = "Rating: Buy\nEnter at $189-192, 6% portfolio cap."
|
||||
DECISION_OVERWEIGHT = (
|
||||
"Rating: Overweight\n"
|
||||
"Executive Summary: Moderate position, await confirmation.\n"
|
||||
"Investment Thesis: Strong fundamentals but near-term headwinds."
|
||||
)
|
||||
DECISION_SELL = "Rating: Sell\nExit position immediately."
|
||||
DECISION_NO_RATING = (
|
||||
"Executive Summary: Complex situation with multiple competing factors.\n"
|
||||
"Investment Thesis: No clear directional signal at this time."
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Shared helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def make_log(tmp_path, filename="trading_memory.md"):
|
||||
config = {"memory_log_path": str(tmp_path / filename)}
|
||||
return TradingMemoryLog(config)
|
||||
|
||||
|
||||
def _seed_completed(tmp_path, ticker, date, decision_text, reflection_text, filename="trading_memory.md"):
|
||||
"""Write a completed entry directly to file, bypassing the API."""
|
||||
entry = (
|
||||
f"[{date} | {ticker} | Buy | +1.0% | +0.5% | 5d]\n\n"
|
||||
f"DECISION:\n{decision_text}\n\n"
|
||||
f"REFLECTION:\n{reflection_text}"
|
||||
+ _SEP
|
||||
)
|
||||
with open(tmp_path / filename, "a", encoding="utf-8") as f:
|
||||
f.write(entry)
|
||||
|
||||
|
||||
def _resolve_entry(log, ticker, date, decision, reflection="Good call."):
|
||||
"""Store a decision then immediately resolve it via the API."""
|
||||
log.store_decision(ticker, date, decision)
|
||||
log.update_with_outcome(ticker, date, 0.05, 0.02, 5, reflection)
|
||||
|
||||
|
||||
def _price_df(prices):
|
||||
"""Minimal DataFrame matching yfinance .history() output shape."""
|
||||
return pd.DataFrame({"Close": prices})
|
||||
|
||||
|
||||
def _make_pm_state(past_context=""):
|
||||
"""Minimal AgentState dict for portfolio_manager_node."""
|
||||
return {
|
||||
"company_of_interest": "NVDA",
|
||||
"past_context": past_context,
|
||||
"risk_debate_state": {
|
||||
"history": "Risk debate history.",
|
||||
"aggressive_history": "",
|
||||
"conservative_history": "",
|
||||
"neutral_history": "",
|
||||
"judge_decision": "",
|
||||
"current_aggressive_response": "",
|
||||
"current_conservative_response": "",
|
||||
"current_neutral_response": "",
|
||||
"count": 1,
|
||||
},
|
||||
"market_report": "Market report.",
|
||||
"sentiment_report": "Sentiment report.",
|
||||
"news_report": "News report.",
|
||||
"fundamentals_report": "Fundamentals report.",
|
||||
"investment_plan": "Research plan.",
|
||||
"trader_investment_plan": "Trader plan.",
|
||||
}
|
||||
|
||||
|
||||
def _structured_pm_llm(captured: dict, decision: PortfolioDecision | None = None):
|
||||
"""Build a MagicMock LLM whose with_structured_output binding captures the
|
||||
prompt and returns a real PortfolioDecision (so render_pm_decision works).
|
||||
"""
|
||||
if decision is None:
|
||||
decision = PortfolioDecision(
|
||||
rating=PortfolioRating.HOLD,
|
||||
executive_summary="Hold the position; await catalyst.",
|
||||
investment_thesis="Balanced view; neither side carried the debate.",
|
||||
)
|
||||
structured = MagicMock()
|
||||
structured.invoke.side_effect = lambda prompt: (
|
||||
captured.__setitem__("prompt", prompt) or decision
|
||||
)
|
||||
llm = MagicMock()
|
||||
llm.with_structured_output.return_value = structured
|
||||
return llm
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Core: storage and read path
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestTradingMemoryLogCore:
|
||||
|
||||
def test_store_creates_file(self, tmp_path):
|
||||
log = make_log(tmp_path)
|
||||
assert not (tmp_path / "trading_memory.md").exists()
|
||||
log.store_decision("NVDA", "2026-01-10", DECISION_BUY)
|
||||
assert (tmp_path / "trading_memory.md").exists()
|
||||
|
||||
def test_store_appends_not_overwrites(self, tmp_path):
|
||||
log = make_log(tmp_path)
|
||||
log.store_decision("NVDA", "2026-01-10", DECISION_BUY)
|
||||
log.store_decision("AAPL", "2026-01-11", DECISION_OVERWEIGHT)
|
||||
entries = log.load_entries()
|
||||
assert len(entries) == 2
|
||||
assert entries[0]["ticker"] == "NVDA"
|
||||
assert entries[1]["ticker"] == "AAPL"
|
||||
|
||||
def test_store_decision_idempotent(self, tmp_path):
|
||||
"""Calling store_decision twice with same (ticker, date) stores only one entry."""
|
||||
log = make_log(tmp_path)
|
||||
log.store_decision("NVDA", "2026-01-10", DECISION_BUY)
|
||||
log.store_decision("NVDA", "2026-01-10", DECISION_BUY)
|
||||
assert len(log.load_entries()) == 1
|
||||
|
||||
def test_batch_update_resolves_multiple_entries(self, tmp_path):
|
||||
"""batch_update_with_outcomes resolves multiple pending entries in one write."""
|
||||
log = make_log(tmp_path)
|
||||
log.store_decision("NVDA", "2026-01-05", DECISION_BUY)
|
||||
log.store_decision("NVDA", "2026-01-12", DECISION_SELL)
|
||||
|
||||
updates = [
|
||||
{"ticker": "NVDA", "trade_date": "2026-01-05",
|
||||
"raw_return": 0.05, "alpha_return": 0.02, "holding_days": 5,
|
||||
"reflection": "First correct."},
|
||||
{"ticker": "NVDA", "trade_date": "2026-01-12",
|
||||
"raw_return": -0.03, "alpha_return": -0.01, "holding_days": 5,
|
||||
"reflection": "Second correct."},
|
||||
]
|
||||
log.batch_update_with_outcomes(updates)
|
||||
|
||||
entries = log.load_entries()
|
||||
assert len(entries) == 2
|
||||
assert all(not e["pending"] for e in entries)
|
||||
assert entries[0]["reflection"] == "First correct."
|
||||
assert entries[1]["reflection"] == "Second correct."
|
||||
|
||||
def test_pending_tag_format(self, tmp_path):
|
||||
log = make_log(tmp_path)
|
||||
log.store_decision("NVDA", "2026-01-10", DECISION_BUY)
|
||||
text = (tmp_path / "trading_memory.md").read_text(encoding="utf-8")
|
||||
assert "[2026-01-10 | NVDA | Buy | pending]" in text
|
||||
|
||||
# Rating parsing
|
||||
|
||||
def test_rating_parsed_buy(self, tmp_path):
|
||||
log = make_log(tmp_path)
|
||||
log.store_decision("NVDA", "2026-01-10", DECISION_BUY)
|
||||
assert log.load_entries()[0]["rating"] == "Buy"
|
||||
|
||||
def test_rating_parsed_overweight(self, tmp_path):
|
||||
log = make_log(tmp_path)
|
||||
log.store_decision("AAPL", "2026-01-11", DECISION_OVERWEIGHT)
|
||||
assert log.load_entries()[0]["rating"] == "Overweight"
|
||||
|
||||
def test_rating_fallback_hold(self, tmp_path):
|
||||
log = make_log(tmp_path)
|
||||
log.store_decision("MSFT", "2026-01-12", DECISION_NO_RATING)
|
||||
assert log.load_entries()[0]["rating"] == "Hold"
|
||||
|
||||
def test_rating_priority_over_prose(self, tmp_path):
|
||||
"""'Rating: X' label wins even when an opposing rating word appears earlier in prose."""
|
||||
decision = (
|
||||
"The sell thesis is weak. The hold case is marginal.\n\n"
|
||||
"Rating: Buy\n\n"
|
||||
"Executive Summary: Strong fundamentals support the position."
|
||||
)
|
||||
log = make_log(tmp_path)
|
||||
log.store_decision("NVDA", "2026-01-10", decision)
|
||||
assert log.load_entries()[0]["rating"] == "Buy"
|
||||
|
||||
# Delimiter robustness
|
||||
|
||||
def test_decision_with_markdown_separator(self, tmp_path):
|
||||
"""LLM decision containing '---' must not corrupt the entry."""
|
||||
decision = "Rating: Buy\n\n---\n\nRisk: elevated volatility."
|
||||
log = make_log(tmp_path)
|
||||
log.store_decision("NVDA", "2026-01-10", decision)
|
||||
entries = log.load_entries()
|
||||
assert len(entries) == 1
|
||||
assert "Risk: elevated volatility" in entries[0]["decision"]
|
||||
|
||||
# load_entries
|
||||
|
||||
def test_load_entries_empty_file(self, tmp_path):
|
||||
log = make_log(tmp_path)
|
||||
assert log.load_entries() == []
|
||||
|
||||
def test_load_entries_single(self, tmp_path):
|
||||
log = make_log(tmp_path)
|
||||
log.store_decision("NVDA", "2026-01-10", DECISION_BUY)
|
||||
entries = log.load_entries()
|
||||
assert len(entries) == 1
|
||||
e = entries[0]
|
||||
assert e["date"] == "2026-01-10"
|
||||
assert e["ticker"] == "NVDA"
|
||||
assert e["rating"] == "Buy"
|
||||
assert e["pending"] is True
|
||||
assert e["raw"] is None
|
||||
|
||||
def test_load_entries_multiple(self, tmp_path):
|
||||
log = make_log(tmp_path)
|
||||
log.store_decision("NVDA", "2026-01-10", DECISION_BUY)
|
||||
log.store_decision("AAPL", "2026-01-11", DECISION_OVERWEIGHT)
|
||||
log.store_decision("MSFT", "2026-01-12", DECISION_NO_RATING)
|
||||
entries = log.load_entries()
|
||||
assert len(entries) == 3
|
||||
assert [e["ticker"] for e in entries] == ["NVDA", "AAPL", "MSFT"]
|
||||
|
||||
def test_decision_content_preserved(self, tmp_path):
|
||||
log = make_log(tmp_path)
|
||||
log.store_decision("NVDA", "2026-01-10", DECISION_BUY)
|
||||
assert log.load_entries()[0]["decision"] == DECISION_BUY.strip()
|
||||
|
||||
# get_pending_entries
|
||||
|
||||
def test_get_pending_returns_pending_only(self, tmp_path):
|
||||
log = make_log(tmp_path)
|
||||
_seed_completed(tmp_path, "NVDA", "2026-01-05", "Buy NVDA.", "Correct.")
|
||||
log.store_decision("NVDA", "2026-01-10", DECISION_BUY)
|
||||
pending = log.get_pending_entries()
|
||||
assert len(pending) == 1
|
||||
assert pending[0]["ticker"] == "NVDA"
|
||||
assert pending[0]["date"] == "2026-01-10"
|
||||
|
||||
# get_past_context
|
||||
|
||||
def test_get_past_context_empty(self, tmp_path):
|
||||
log = make_log(tmp_path)
|
||||
assert log.get_past_context("NVDA") == ""
|
||||
|
||||
def test_get_past_context_pending_excluded(self, tmp_path):
|
||||
log = make_log(tmp_path)
|
||||
log.store_decision("NVDA", "2026-01-10", DECISION_BUY)
|
||||
assert log.get_past_context("NVDA") == ""
|
||||
|
||||
def test_get_past_context_same_ticker(self, tmp_path):
|
||||
log = make_log(tmp_path)
|
||||
_seed_completed(tmp_path, "NVDA", "2026-01-05", "Buy NVDA — AI capex thesis intact.", "Directionally correct.")
|
||||
ctx = log.get_past_context("NVDA")
|
||||
assert "Past analyses of NVDA" in ctx
|
||||
assert "Buy NVDA" in ctx
|
||||
|
||||
def test_get_past_context_cross_ticker(self, tmp_path):
|
||||
log = make_log(tmp_path)
|
||||
_seed_completed(tmp_path, "AAPL", "2026-01-05", "Buy AAPL — Services growth.", "Correct.")
|
||||
ctx = log.get_past_context("NVDA")
|
||||
assert "Recent cross-ticker lessons" in ctx
|
||||
assert "Past analyses of NVDA" not in ctx
|
||||
|
||||
def test_n_same_limit_respected(self, tmp_path):
|
||||
"""Only the n_same most recent same-ticker entries are included."""
|
||||
log = make_log(tmp_path)
|
||||
for i in range(6):
|
||||
_seed_completed(tmp_path, "NVDA", f"2026-01-{i+1:02d}", f"Buy entry {i}.", "Correct.")
|
||||
ctx = log.get_past_context("NVDA", n_same=5)
|
||||
assert "Buy entry 0" not in ctx
|
||||
assert "Buy entry 5" in ctx
|
||||
|
||||
def test_n_cross_limit_respected(self, tmp_path):
|
||||
"""Only the n_cross most recent cross-ticker entries are included."""
|
||||
log = make_log(tmp_path)
|
||||
for i, ticker in enumerate(["AAPL", "MSFT", "GOOG", "META"]):
|
||||
_seed_completed(tmp_path, ticker, f"2026-01-{i+1:02d}", f"Buy {ticker}.", "Correct.")
|
||||
ctx = log.get_past_context("NVDA", n_cross=3)
|
||||
assert "AAPL" not in ctx
|
||||
assert "META" in ctx
|
||||
|
||||
# No-op when config is None
|
||||
|
||||
def test_no_log_path_is_noop(self):
|
||||
log = TradingMemoryLog(config=None)
|
||||
log.store_decision("NVDA", "2026-01-10", DECISION_BUY)
|
||||
assert log.load_entries() == []
|
||||
assert log.get_past_context("NVDA") == ""
|
||||
|
||||
# Rotation: opt-in cap on resolved entries
|
||||
|
||||
def test_rotation_disabled_by_default(self, tmp_path):
|
||||
"""Without max_entries, all resolved entries are kept."""
|
||||
log = make_log(tmp_path)
|
||||
for i in range(7):
|
||||
_resolve_entry(log, "NVDA", f"2026-01-{i+1:02d}", DECISION_BUY, f"Lesson {i}.")
|
||||
assert len(log.load_entries()) == 7
|
||||
|
||||
def test_rotation_prunes_oldest_resolved(self, tmp_path):
|
||||
"""When max_entries is set and exceeded, oldest resolved entries are pruned."""
|
||||
log = TradingMemoryLog({
|
||||
"memory_log_path": str(tmp_path / "trading_memory.md"),
|
||||
"memory_log_max_entries": 3,
|
||||
})
|
||||
# Resolve 5 entries; rotation should keep only the 3 most recent.
|
||||
for i in range(5):
|
||||
_resolve_entry(log, "NVDA", f"2026-01-{i+1:02d}", DECISION_BUY, f"Lesson {i}.")
|
||||
entries = log.load_entries()
|
||||
assert len(entries) == 3
|
||||
# Confirm the OLDEST were dropped, not the newest.
|
||||
dates = [e["date"] for e in entries]
|
||||
assert dates == ["2026-01-03", "2026-01-04", "2026-01-05"]
|
||||
|
||||
def test_rotation_never_prunes_pending(self, tmp_path):
|
||||
"""Pending entries (unresolved) are kept regardless of the cap."""
|
||||
log = TradingMemoryLog({
|
||||
"memory_log_path": str(tmp_path / "trading_memory.md"),
|
||||
"memory_log_max_entries": 2,
|
||||
})
|
||||
# 3 resolved + 2 pending. With cap=2, only 2 resolved survive; both pending stay.
|
||||
for i in range(3):
|
||||
_resolve_entry(log, "NVDA", f"2026-01-{i+1:02d}", DECISION_BUY, f"Resolved {i}.")
|
||||
log.store_decision("NVDA", "2026-02-01", DECISION_BUY)
|
||||
log.store_decision("NVDA", "2026-02-02", DECISION_OVERWEIGHT)
|
||||
# Trigger rotation by resolving one more entry — pending entries must stay.
|
||||
_resolve_entry(log, "NVDA", "2026-01-04", DECISION_BUY, "Resolved 3.")
|
||||
entries = log.load_entries()
|
||||
pending = [e for e in entries if e["pending"]]
|
||||
resolved = [e for e in entries if not e["pending"]]
|
||||
assert len(pending) == 2, "pending entries must never be pruned"
|
||||
assert len(resolved) == 2, f"expected 2 resolved after rotation, got {len(resolved)}"
|
||||
|
||||
def test_rotation_under_cap_is_noop(self, tmp_path):
|
||||
"""No rotation when resolved count <= max_entries."""
|
||||
log = TradingMemoryLog({
|
||||
"memory_log_path": str(tmp_path / "trading_memory.md"),
|
||||
"memory_log_max_entries": 10,
|
||||
})
|
||||
for i in range(3):
|
||||
_resolve_entry(log, "NVDA", f"2026-01-{i+1:02d}", DECISION_BUY, f"Lesson {i}.")
|
||||
assert len(log.load_entries()) == 3
|
||||
|
||||
# Rating parsing: markdown bold and numbered list formats
|
||||
|
||||
def test_rating_parsed_from_bold_markdown(self, tmp_path):
|
||||
"""**Rating**: Buy — markdown bold around the label must not prevent parsing."""
|
||||
decision = "**Rating**: Buy\nEnter at $190."
|
||||
log = make_log(tmp_path)
|
||||
log.store_decision("NVDA", "2026-01-10", decision)
|
||||
assert log.load_entries()[0]["rating"] == "Buy"
|
||||
|
||||
def test_rating_parsed_from_bold_value(self, tmp_path):
|
||||
"""Rating: **Sell** — markdown bold around the value must not prevent parsing."""
|
||||
decision = "Rating: **Sell**\nExit immediately."
|
||||
log = make_log(tmp_path)
|
||||
log.store_decision("NVDA", "2026-01-10", decision)
|
||||
assert log.load_entries()[0]["rating"] == "Sell"
|
||||
|
||||
def test_rating_label_wins_over_prose_with_markdown(self, tmp_path):
|
||||
"""Rating: **Sell** must win even when prose contains a conflicting rating word."""
|
||||
decision = (
|
||||
"The buy thesis is weakened by guidance.\n"
|
||||
"Rating: **Sell**\n"
|
||||
"Exit before earnings."
|
||||
)
|
||||
log = make_log(tmp_path)
|
||||
log.store_decision("NVDA", "2026-01-10", decision)
|
||||
assert log.load_entries()[0]["rating"] == "Sell"
|
||||
|
||||
def test_rating_parsed_from_numbered_list(self, tmp_path):
|
||||
"""1. Rating: Buy — numbered list prefix must not prevent parsing."""
|
||||
decision = "1. Rating: Buy\nEnter at $190."
|
||||
log = make_log(tmp_path)
|
||||
log.store_decision("NVDA", "2026-01-10", decision)
|
||||
assert log.load_entries()[0]["rating"] == "Buy"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Deferred reflection: update_with_outcome, Reflector, _fetch_returns
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestDeferredReflection:
|
||||
|
||||
# update_with_outcome
|
||||
|
||||
def test_update_replaces_pending_tag(self, tmp_path):
|
||||
log = make_log(tmp_path)
|
||||
log.store_decision("NVDA", "2026-01-10", DECISION_BUY)
|
||||
log.update_with_outcome("NVDA", "2026-01-10", 0.042, 0.021, 5, "Momentum confirmed.")
|
||||
text = (tmp_path / "trading_memory.md").read_text(encoding="utf-8")
|
||||
assert "[2026-01-10 | NVDA | Buy | pending]" not in text
|
||||
assert "+4.2%" in text
|
||||
assert "+2.1%" in text
|
||||
assert "5d" in text
|
||||
|
||||
def test_update_appends_reflection(self, tmp_path):
|
||||
log = make_log(tmp_path)
|
||||
log.store_decision("NVDA", "2026-01-10", DECISION_BUY)
|
||||
log.update_with_outcome("NVDA", "2026-01-10", 0.042, 0.021, 5, "Momentum confirmed.")
|
||||
entries = log.load_entries()
|
||||
assert len(entries) == 1
|
||||
e = entries[0]
|
||||
assert e["pending"] is False
|
||||
assert e["reflection"] == "Momentum confirmed."
|
||||
assert e["decision"] == DECISION_BUY.strip()
|
||||
|
||||
def test_update_preserves_other_entries(self, tmp_path):
|
||||
"""Only the matching entry is modified; all other entries remain unchanged."""
|
||||
log = make_log(tmp_path)
|
||||
log.store_decision("NVDA", "2026-01-10", DECISION_BUY)
|
||||
log.store_decision("AAPL", "2026-01-11", "Rating: Hold\nHold AAPL.")
|
||||
log.store_decision("MSFT", "2026-01-12", DECISION_SELL)
|
||||
log.update_with_outcome("AAPL", "2026-01-11", 0.01, -0.01, 5, "Neutral result.")
|
||||
entries = log.load_entries()
|
||||
assert len(entries) == 3
|
||||
nvda, aapl, msft = entries
|
||||
assert nvda["ticker"] == "NVDA" and nvda["pending"] is True
|
||||
assert aapl["ticker"] == "AAPL" and aapl["pending"] is False
|
||||
assert aapl["reflection"] == "Neutral result."
|
||||
assert msft["ticker"] == "MSFT" and msft["pending"] is True
|
||||
|
||||
def test_update_atomic_write(self, tmp_path):
|
||||
"""A pre-existing .tmp file is overwritten; the log is correctly updated."""
|
||||
log = make_log(tmp_path)
|
||||
log.store_decision("NVDA", "2026-01-10", DECISION_BUY)
|
||||
stale_tmp = tmp_path / "trading_memory.tmp"
|
||||
stale_tmp.write_text("GARBAGE CONTENT — should be overwritten", encoding="utf-8")
|
||||
log.update_with_outcome("NVDA", "2026-01-10", 0.042, 0.021, 5, "Correct.")
|
||||
assert not stale_tmp.exists()
|
||||
entries = log.load_entries()
|
||||
assert len(entries) == 1
|
||||
assert entries[0]["reflection"] == "Correct."
|
||||
assert entries[0]["pending"] is False
|
||||
|
||||
def test_update_noop_when_no_log_path(self):
|
||||
log = TradingMemoryLog(config=None)
|
||||
log.update_with_outcome("NVDA", "2026-01-10", 0.05, 0.02, 5, "Reflection")
|
||||
|
||||
def test_formatting_roundtrip_after_update(self, tmp_path):
|
||||
"""All fields intact and blank line between tag and DECISION preserved after update."""
|
||||
log = make_log(tmp_path)
|
||||
log.store_decision("NVDA", "2026-01-10", DECISION_BUY)
|
||||
log.update_with_outcome("NVDA", "2026-01-10", 0.042, 0.021, 5, "Momentum confirmed.")
|
||||
entries = log.load_entries()
|
||||
assert len(entries) == 1
|
||||
e = entries[0]
|
||||
assert e["pending"] is False
|
||||
assert e["decision"] == DECISION_BUY.strip()
|
||||
assert e["reflection"] == "Momentum confirmed."
|
||||
assert e["raw"] == "+4.2%"
|
||||
assert e["alpha"] == "+2.1%"
|
||||
assert e["holding"] == "5d"
|
||||
raw_text = (tmp_path / "trading_memory.md").read_text(encoding="utf-8")
|
||||
assert "[2026-01-10 | NVDA | Buy | +4.2% | +2.1% | 5d]\n\nDECISION:" in raw_text
|
||||
|
||||
# Reflector.reflect_on_final_decision
|
||||
|
||||
def test_reflect_on_final_decision_returns_llm_output(self):
|
||||
mock_llm = MagicMock()
|
||||
mock_llm.invoke.return_value.content = "Directionally correct. Thesis confirmed."
|
||||
reflector = Reflector(mock_llm)
|
||||
result = reflector.reflect_on_final_decision(
|
||||
final_decision=DECISION_BUY, raw_return=0.042, alpha_return=0.021
|
||||
)
|
||||
assert result == "Directionally correct. Thesis confirmed."
|
||||
mock_llm.invoke.assert_called_once()
|
||||
|
||||
def test_reflect_on_final_decision_includes_returns_in_prompt(self):
|
||||
"""Return figures are present in the human message sent to the LLM."""
|
||||
mock_llm = MagicMock()
|
||||
mock_llm.invoke.return_value.content = "Incorrect call."
|
||||
reflector = Reflector(mock_llm)
|
||||
reflector.reflect_on_final_decision(
|
||||
final_decision=DECISION_SELL, raw_return=-0.08, alpha_return=-0.05
|
||||
)
|
||||
messages = mock_llm.invoke.call_args[0][0]
|
||||
human_content = next(content for role, content in messages if role == "human")
|
||||
assert "-8.0%" in human_content
|
||||
assert "-5.0%" in human_content
|
||||
assert "Exit position immediately." in human_content
|
||||
|
||||
# TradingAgentsGraph._fetch_returns
|
||||
|
||||
def test_fetch_returns_valid_ticker(self):
|
||||
stock_prices = [100.0, 102.0, 104.0, 103.0, 105.0, 106.0]
|
||||
spy_prices = [400.0, 402.0, 404.0, 403.0, 405.0, 406.0]
|
||||
mock_graph = MagicMock(spec=TradingAgentsGraph)
|
||||
with patch("yfinance.Ticker") as mock_ticker_cls:
|
||||
def _make_ticker(sym):
|
||||
m = MagicMock()
|
||||
m.history.return_value = _price_df(spy_prices if sym == "SPY" else stock_prices)
|
||||
return m
|
||||
mock_ticker_cls.side_effect = _make_ticker
|
||||
raw, alpha, days = TradingAgentsGraph._fetch_returns(mock_graph, "NVDA", "2026-01-05")
|
||||
assert raw is not None and alpha is not None and days is not None
|
||||
assert isinstance(raw, float) and isinstance(alpha, float) and isinstance(days, int)
|
||||
assert days == 5
|
||||
|
||||
def test_fetch_returns_too_recent(self):
|
||||
"""Only 1 data point available → returns (None, None, None), no crash."""
|
||||
mock_graph = MagicMock(spec=TradingAgentsGraph)
|
||||
with patch("yfinance.Ticker") as mock_ticker_cls:
|
||||
m = MagicMock()
|
||||
m.history.return_value = _price_df([100.0])
|
||||
mock_ticker_cls.return_value = m
|
||||
raw, alpha, days = TradingAgentsGraph._fetch_returns(mock_graph, "NVDA", "2026-04-19")
|
||||
assert raw is None and alpha is None and days is None
|
||||
|
||||
def test_fetch_returns_delisted(self):
|
||||
"""Empty DataFrame → returns (None, None, None), no crash."""
|
||||
mock_graph = MagicMock(spec=TradingAgentsGraph)
|
||||
with patch("yfinance.Ticker") as mock_ticker_cls:
|
||||
m = MagicMock()
|
||||
m.history.return_value = pd.DataFrame({"Close": []})
|
||||
mock_ticker_cls.return_value = m
|
||||
raw, alpha, days = TradingAgentsGraph._fetch_returns(mock_graph, "XXXXXFAKE", "2026-01-10")
|
||||
assert raw is None and alpha is None and days is None
|
||||
|
||||
def test_fetch_returns_spy_shorter_than_stock(self):
|
||||
"""SPY having fewer rows than the stock must not raise IndexError."""
|
||||
stock_prices = [100.0, 102.0, 104.0, 103.0, 105.0, 106.0]
|
||||
spy_prices = [400.0, 402.0, 403.0]
|
||||
mock_graph = MagicMock(spec=TradingAgentsGraph)
|
||||
with patch("yfinance.Ticker") as mock_ticker_cls:
|
||||
def _make_ticker(sym):
|
||||
m = MagicMock()
|
||||
m.history.return_value = _price_df(spy_prices if sym == "SPY" else stock_prices)
|
||||
return m
|
||||
mock_ticker_cls.side_effect = _make_ticker
|
||||
raw, alpha, days = TradingAgentsGraph._fetch_returns(mock_graph, "NVDA", "2026-01-05")
|
||||
assert raw is not None and alpha is not None and days is not None
|
||||
assert days == 2
|
||||
|
||||
# TradingAgentsGraph._resolve_pending_entries
|
||||
|
||||
def test_resolve_skips_other_tickers(self, tmp_path):
|
||||
"""Pending AAPL entry is not resolved when the run is for NVDA."""
|
||||
log = make_log(tmp_path)
|
||||
log.store_decision("AAPL", "2026-01-10", DECISION_BUY)
|
||||
mock_graph = MagicMock(spec=TradingAgentsGraph)
|
||||
mock_graph.memory_log = log
|
||||
mock_graph._fetch_returns = MagicMock(return_value=(0.05, 0.02, 5))
|
||||
TradingAgentsGraph._resolve_pending_entries(mock_graph, "NVDA")
|
||||
mock_graph._fetch_returns.assert_not_called()
|
||||
assert len(log.get_pending_entries()) == 1
|
||||
|
||||
def test_resolve_marks_entry_completed(self, tmp_path):
|
||||
"""After resolve, get_pending_entries() is empty and the entry has a REFLECTION."""
|
||||
log = make_log(tmp_path)
|
||||
log.store_decision("NVDA", "2026-01-05", DECISION_BUY)
|
||||
mock_reflector = MagicMock()
|
||||
mock_reflector.reflect_on_final_decision.return_value = "Momentum confirmed."
|
||||
mock_graph = MagicMock(spec=TradingAgentsGraph)
|
||||
mock_graph.memory_log = log
|
||||
mock_graph.reflector = mock_reflector
|
||||
mock_graph._fetch_returns = MagicMock(return_value=(0.05, 0.02, 5))
|
||||
TradingAgentsGraph._resolve_pending_entries(mock_graph, "NVDA")
|
||||
assert log.get_pending_entries() == []
|
||||
entries = log.load_entries()
|
||||
assert len(entries) == 1
|
||||
assert entries[0]["pending"] is False
|
||||
assert entries[0]["reflection"] == "Momentum confirmed."
|
||||
assert "+5.0%" in entries[0]["raw"]
|
||||
assert "+2.0%" in entries[0]["alpha"]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Portfolio Manager injection: past_context in state and prompt
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestPortfolioManagerInjection:
|
||||
|
||||
# past_context in initial state
|
||||
|
||||
def test_past_context_in_initial_state(self):
|
||||
propagator = Propagator()
|
||||
state = propagator.create_initial_state("NVDA", "2026-01-10", past_context="some context")
|
||||
assert "past_context" in state
|
||||
assert state["past_context"] == "some context"
|
||||
|
||||
def test_past_context_defaults_to_empty(self):
|
||||
propagator = Propagator()
|
||||
state = propagator.create_initial_state("NVDA", "2026-01-10")
|
||||
assert state["past_context"] == ""
|
||||
|
||||
# PM prompt
|
||||
|
||||
def test_pm_prompt_includes_past_context(self):
|
||||
captured = {}
|
||||
llm = _structured_pm_llm(captured)
|
||||
pm_node = create_portfolio_manager(llm)
|
||||
state = _make_pm_state(past_context="[2026-01-05 | NVDA | Buy | +5.0% | +2.0% | 5d]\nGreat call.")
|
||||
pm_node(state)
|
||||
assert "Lessons from prior decisions and outcomes" in captured["prompt"]
|
||||
assert "Great call." in captured["prompt"]
|
||||
|
||||
def test_pm_no_past_context_no_section(self):
|
||||
"""PM prompt omits the lessons section entirely when past_context is empty."""
|
||||
captured = {}
|
||||
llm = _structured_pm_llm(captured)
|
||||
pm_node = create_portfolio_manager(llm)
|
||||
state = _make_pm_state(past_context="")
|
||||
pm_node(state)
|
||||
assert "Lessons from prior decisions" not in captured["prompt"]
|
||||
|
||||
def test_pm_returns_rendered_markdown_with_rating(self):
|
||||
"""The structured PortfolioDecision is rendered to markdown that
|
||||
downstream consumers (memory log, signal processor, CLI display)
|
||||
can parse without any extra LLM call."""
|
||||
captured = {}
|
||||
decision = PortfolioDecision(
|
||||
rating=PortfolioRating.OVERWEIGHT,
|
||||
executive_summary="Build position gradually over the next two weeks.",
|
||||
investment_thesis="AI capex cycle remains intact; institutional flows constructive.",
|
||||
price_target=215.0,
|
||||
time_horizon="3-6 months",
|
||||
)
|
||||
llm = _structured_pm_llm(captured, decision)
|
||||
pm_node = create_portfolio_manager(llm)
|
||||
result = pm_node(_make_pm_state())
|
||||
md = result["final_trade_decision"]
|
||||
assert "**Rating**: Overweight" in md
|
||||
assert "**Executive Summary**: Build position gradually" in md
|
||||
assert "**Investment Thesis**: AI capex cycle" in md
|
||||
assert "**Price Target**: 215.0" in md
|
||||
assert "**Time Horizon**: 3-6 months" in md
|
||||
|
||||
def test_pm_falls_back_to_freetext_when_structured_unavailable(self):
|
||||
"""If a provider does not support with_structured_output, the agent
|
||||
falls back to a plain invoke and returns whatever prose the model
|
||||
produced, so the pipeline never blocks."""
|
||||
plain_response = "**Rating**: Sell\n\nExit ahead of guidance."
|
||||
llm = MagicMock()
|
||||
llm.with_structured_output.side_effect = NotImplementedError("provider unsupported")
|
||||
llm.invoke.return_value = MagicMock(content=plain_response)
|
||||
pm_node = create_portfolio_manager(llm)
|
||||
result = pm_node(_make_pm_state())
|
||||
assert result["final_trade_decision"] == plain_response
|
||||
|
||||
# get_past_context ordering and limits
|
||||
|
||||
def test_same_ticker_prioritised(self, tmp_path):
|
||||
"""Same-ticker entries in same-ticker section; cross-ticker entries in cross-ticker section."""
|
||||
log = make_log(tmp_path)
|
||||
_resolve_entry(log, "NVDA", "2026-01-05", DECISION_BUY, "Momentum confirmed.")
|
||||
_resolve_entry(log, "AAPL", "2026-01-06", DECISION_SELL, "Overvalued.")
|
||||
result = log.get_past_context("NVDA")
|
||||
assert "Past analyses of NVDA" in result
|
||||
assert "Recent cross-ticker lessons" in result
|
||||
same_block, cross_block = result.split("Recent cross-ticker lessons")
|
||||
assert "NVDA" in same_block
|
||||
assert "AAPL" in cross_block
|
||||
|
||||
def test_cross_ticker_reflection_only(self, tmp_path):
|
||||
"""Cross-ticker entries show only the REFLECTION text, not the full DECISION."""
|
||||
log = make_log(tmp_path)
|
||||
_resolve_entry(log, "AAPL", "2026-01-06", DECISION_SELL, "Overvalued correction.")
|
||||
result = log.get_past_context("NVDA")
|
||||
assert "Overvalued correction." in result
|
||||
assert "Exit position immediately." not in result
|
||||
|
||||
def test_n_same_limit_respected(self, tmp_path):
|
||||
"""More than 5 same-ticker completed entries → only 5 injected."""
|
||||
log = make_log(tmp_path)
|
||||
for i in range(7):
|
||||
_resolve_entry(log, "NVDA", f"2026-01-{i+1:02d}", DECISION_BUY, f"Lesson {i}.")
|
||||
result = log.get_past_context("NVDA", n_same=5)
|
||||
lessons_present = sum(1 for i in range(7) if f"Lesson {i}." in result)
|
||||
assert lessons_present == 5
|
||||
|
||||
def test_n_cross_limit_respected(self, tmp_path):
|
||||
"""More than 3 cross-ticker completed entries → only 3 injected."""
|
||||
log = make_log(tmp_path)
|
||||
tickers = ["AAPL", "MSFT", "TSLA", "AMZN", "GOOG"]
|
||||
for i, ticker in enumerate(tickers):
|
||||
_resolve_entry(log, ticker, f"2026-01-{i+1:02d}", DECISION_BUY, f"{ticker} lesson.")
|
||||
result = log.get_past_context("NVDA", n_cross=3)
|
||||
cross_count = sum(result.count(f"{t} lesson.") for t in tickers)
|
||||
assert cross_count == 3
|
||||
|
||||
# Full A→B→C integration cycle
|
||||
|
||||
def test_full_cycle_store_resolve_inject(self, tmp_path):
|
||||
"""store pending → resolve with outcome → past_context non-empty for PM."""
|
||||
log = make_log(tmp_path)
|
||||
log.store_decision("NVDA", "2026-01-05", DECISION_BUY)
|
||||
assert len(log.get_pending_entries()) == 1
|
||||
assert log.get_past_context("NVDA") == ""
|
||||
log.update_with_outcome("NVDA", "2026-01-05", 0.05, 0.02, 5, "Correct call.")
|
||||
assert log.get_pending_entries() == []
|
||||
past_ctx = log.get_past_context("NVDA")
|
||||
assert past_ctx != ""
|
||||
assert "NVDA" in past_ctx
|
||||
assert "Correct call." in past_ctx
|
||||
assert "DECISION:" in past_ctx
|
||||
assert "REFLECTION:" in past_ctx
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Legacy removal: BM25 / FinancialSituationMemory fully gone
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestLegacyRemoval:
|
||||
|
||||
def test_financial_situation_memory_removed(self):
|
||||
"""FinancialSituationMemory must not be importable from the memory module."""
|
||||
import tradingagents.agents.utils.memory as m
|
||||
assert not hasattr(m, "FinancialSituationMemory")
|
||||
|
||||
def test_bm25_not_imported(self):
|
||||
"""rank_bm25 must not be present in the memory module namespace."""
|
||||
import tradingagents.agents.utils.memory as m
|
||||
assert not hasattr(m, "BM25Okapi")
|
||||
|
||||
def test_reflect_and_remember_removed(self):
|
||||
"""TradingAgentsGraph must not expose reflect_and_remember."""
|
||||
assert not hasattr(TradingAgentsGraph, "reflect_and_remember")
|
||||
|
||||
def test_portfolio_manager_no_memory_param(self):
|
||||
"""create_portfolio_manager accepts only llm; passing memory= raises TypeError."""
|
||||
mock_llm = MagicMock()
|
||||
create_portfolio_manager(mock_llm)
|
||||
with pytest.raises(TypeError):
|
||||
create_portfolio_manager(mock_llm, memory=MagicMock())
|
||||
|
||||
def test_full_pipeline_no_regression(self, tmp_path):
|
||||
"""propagate() completes and stores the decision after the redesign."""
|
||||
import functools
|
||||
|
||||
fake_state = {
|
||||
"final_trade_decision": "Rating: Buy\nBuy NVDA.",
|
||||
"company_of_interest": "NVDA",
|
||||
"trade_date": "2026-01-10",
|
||||
"market_report": "",
|
||||
"sentiment_report": "",
|
||||
"news_report": "",
|
||||
"fundamentals_report": "",
|
||||
"investment_debate_state": {
|
||||
"bull_history": "", "bear_history": "", "history": "",
|
||||
"current_response": "", "judge_decision": "",
|
||||
},
|
||||
"investment_plan": "",
|
||||
"trader_investment_plan": "",
|
||||
"risk_debate_state": {
|
||||
"aggressive_history": "", "conservative_history": "",
|
||||
"neutral_history": "", "history": "", "judge_decision": "",
|
||||
"current_aggressive_response": "", "current_conservative_response": "",
|
||||
"current_neutral_response": "", "count": 1, "latest_speaker": "",
|
||||
},
|
||||
}
|
||||
mock_graph = MagicMock()
|
||||
mock_graph.memory_log = TradingMemoryLog({"memory_log_path": str(tmp_path / "mem.md")})
|
||||
mock_graph.log_states_dict = {}
|
||||
mock_graph.debug = False
|
||||
mock_graph.config = {"results_dir": str(tmp_path)}
|
||||
mock_graph.graph.invoke.return_value = fake_state
|
||||
mock_graph.propagator.create_initial_state.return_value = fake_state
|
||||
mock_graph.propagator.get_graph_args.return_value = {}
|
||||
mock_graph.signal_processor.process_signal.return_value = "Buy"
|
||||
# Bind the real _run_graph so propagate's call to self._run_graph executes
|
||||
# the actual write path instead of the auto-MagicMock.
|
||||
mock_graph._run_graph = functools.partial(
|
||||
TradingAgentsGraph._run_graph, mock_graph
|
||||
)
|
||||
TradingAgentsGraph.propagate(mock_graph, "NVDA", "2026-01-10")
|
||||
entries = mock_graph.memory_log.load_entries()
|
||||
assert len(entries) == 1
|
||||
assert entries[0]["ticker"] == "NVDA"
|
||||
assert entries[0]["pending"] is True
|
||||
@@ -0,0 +1,55 @@
|
||||
import unittest
|
||||
import warnings
|
||||
|
||||
import pytest
|
||||
|
||||
from tradingagents.llm_clients.base_client import BaseLLMClient
|
||||
from tradingagents.llm_clients.model_catalog import get_known_models
|
||||
from tradingagents.llm_clients.validators import validate_model
|
||||
|
||||
|
||||
class DummyLLMClient(BaseLLMClient):
|
||||
def __init__(self, provider: str, model: str):
|
||||
self.provider = provider
|
||||
super().__init__(model)
|
||||
|
||||
def get_llm(self):
|
||||
self.warn_if_unknown_model()
|
||||
return object()
|
||||
|
||||
def validate_model(self) -> bool:
|
||||
return validate_model(self.provider, self.model)
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
class ModelValidationTests(unittest.TestCase):
|
||||
def test_cli_catalog_models_are_all_validator_approved(self):
|
||||
for provider, models in get_known_models().items():
|
||||
if provider in ("ollama", "openrouter"):
|
||||
continue
|
||||
|
||||
for model in models:
|
||||
with self.subTest(provider=provider, model=model):
|
||||
self.assertTrue(validate_model(provider, model))
|
||||
|
||||
def test_unknown_model_emits_warning_for_strict_provider(self):
|
||||
client = DummyLLMClient("openai", "not-a-real-openai-model")
|
||||
|
||||
with warnings.catch_warnings(record=True) as caught:
|
||||
warnings.simplefilter("always")
|
||||
client.get_llm()
|
||||
|
||||
self.assertEqual(len(caught), 1)
|
||||
self.assertIn("not-a-real-openai-model", str(caught[0].message))
|
||||
self.assertIn("openai", str(caught[0].message))
|
||||
|
||||
def test_openrouter_and_ollama_accept_custom_models_without_warning(self):
|
||||
for provider in ("openrouter", "ollama"):
|
||||
client = DummyLLMClient(provider, "custom-model-name")
|
||||
|
||||
with self.subTest(provider=provider):
|
||||
with warnings.catch_warnings(record=True) as caught:
|
||||
warnings.simplefilter("always")
|
||||
client.get_llm()
|
||||
|
||||
self.assertEqual(caught, [])
|
||||
@@ -0,0 +1,52 @@
|
||||
"""Tests for the ticker path-component validator that blocks directory traversal."""
|
||||
|
||||
import os
|
||||
import unittest
|
||||
|
||||
import pytest
|
||||
|
||||
from tradingagents.dataflows.utils import safe_ticker_component
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
class TestSafeTickerComponent(unittest.TestCase):
|
||||
def test_accepts_common_ticker_formats(self):
|
||||
for ticker in ("AAPL", "BRK-B", "BRK.A", "0700.HK", "7203.T", "BHP.AX", "^GSPC"):
|
||||
self.assertEqual(safe_ticker_component(ticker), ticker)
|
||||
|
||||
def test_rejects_path_separators(self):
|
||||
for bad in (".", "..", "../etc", "a/b", "a\\b", "/abs", "..\\..\\x"):
|
||||
with self.assertRaises(ValueError):
|
||||
safe_ticker_component(bad)
|
||||
|
||||
def test_rejects_null_byte_and_whitespace(self):
|
||||
for bad in ("AAP L", "AAPL\x00", "AAPL\n", "\tAAPL"):
|
||||
with self.assertRaises(ValueError):
|
||||
safe_ticker_component(bad)
|
||||
|
||||
def test_rejects_empty_or_non_string(self):
|
||||
for bad in ("", None, 123, b"AAPL"):
|
||||
with self.assertRaises(ValueError):
|
||||
safe_ticker_component(bad)
|
||||
|
||||
def test_rejects_overlong_input(self):
|
||||
with self.assertRaises(ValueError):
|
||||
safe_ticker_component("A" * 33)
|
||||
|
||||
def test_rejects_dot_only_values(self):
|
||||
# '.' and '..' pass the regex but traverse when used as a path
|
||||
# component (e.g. ``Path(results_dir) / ticker / "logs"``).
|
||||
for bad in (".", "..", "...", "...."):
|
||||
with self.assertRaises(ValueError):
|
||||
safe_ticker_component(bad)
|
||||
|
||||
def test_traversal_string_does_not_escape_join(self):
|
||||
"""Sanity: sanitized values stay within base when joined."""
|
||||
base = os.path.realpath("/tmp/cache")
|
||||
ticker = safe_ticker_component("AAPL")
|
||||
joined = os.path.realpath(os.path.join(base, f"{ticker}.csv"))
|
||||
self.assertTrue(joined.startswith(base + os.sep))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,90 @@
|
||||
"""Tests for the shared rating heuristic and the SignalProcessor adapter.
|
||||
|
||||
The Portfolio Manager produces a typed PortfolioDecision via structured
|
||||
output and renders it to markdown that always contains a ``**Rating**: X``
|
||||
header. The deterministic heuristic in ``tradingagents.agents.utils.rating``
|
||||
is therefore sufficient to extract the rating downstream — no second LLM
|
||||
call is needed — and SignalProcessor is now a thin adapter that delegates
|
||||
to it.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
from tradingagents.agents.utils.rating import RATINGS_5_TIER, parse_rating
|
||||
from tradingagents.graph.signal_processing import SignalProcessor
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Heuristic parser
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
class TestParseRating:
|
||||
def test_explicit_label_buy(self):
|
||||
assert parse_rating("Rating: Buy\nReasoning here.") == "Buy"
|
||||
|
||||
def test_explicit_label_overweight(self):
|
||||
assert parse_rating("Rating: Overweight\nDetails.") == "Overweight"
|
||||
|
||||
def test_explicit_label_with_markdown_bold_value(self):
|
||||
# Regression: Rating: **Sell** — markdown around the value.
|
||||
assert parse_rating("Rating: **Sell**\nExit immediately.") == "Sell"
|
||||
|
||||
def test_explicit_label_with_markdown_bold_label(self):
|
||||
assert parse_rating("**Rating**: Underweight\nTrim exposure.") == "Underweight"
|
||||
|
||||
def test_rendered_pm_markdown_shape(self):
|
||||
# The exact shape produced by render_pm_decision must always parse.
|
||||
text = (
|
||||
"**Rating**: Buy\n\n"
|
||||
"**Executive Summary**: Enter at $189-192, 6% portfolio cap.\n\n"
|
||||
"**Investment Thesis**: AI capex cycle intact; institutional flows constructive."
|
||||
)
|
||||
assert parse_rating(text) == "Buy"
|
||||
|
||||
def test_explicit_label_wins_over_prose_with_markdown(self):
|
||||
text = (
|
||||
"The buy thesis is weakened by guidance.\n"
|
||||
"Rating: **Sell**\n"
|
||||
"Exit before earnings."
|
||||
)
|
||||
assert parse_rating(text) == "Sell"
|
||||
|
||||
def test_no_rating_returns_default(self):
|
||||
assert parse_rating("No clear directional signal at this time.") == "Hold"
|
||||
|
||||
def test_no_rating_custom_default(self):
|
||||
assert parse_rating("Plain prose.", default="Underweight") == "Underweight"
|
||||
|
||||
def test_all_five_tiers_recognised(self):
|
||||
for r in RATINGS_5_TIER:
|
||||
assert parse_rating(f"Rating: {r}") == r
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# SignalProcessor: thin adapter over the heuristic
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
class TestSignalProcessor:
|
||||
def test_returns_rating_from_pm_markdown(self):
|
||||
sp = SignalProcessor()
|
||||
md = "**Rating**: Overweight\n\n**Executive Summary**: Build gradually."
|
||||
assert sp.process_signal(md) == "Overweight"
|
||||
|
||||
def test_makes_no_llm_calls(self):
|
||||
"""SignalProcessor must not invoke the LLM it was constructed with —
|
||||
the rating is parseable from the rendered PM markdown directly."""
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
llm = MagicMock()
|
||||
sp = SignalProcessor(llm)
|
||||
sp.process_signal("Rating: Buy\nDetails.")
|
||||
llm.invoke.assert_not_called()
|
||||
llm.with_structured_output.assert_not_called()
|
||||
|
||||
def test_default_when_no_rating_present(self):
|
||||
sp = SignalProcessor()
|
||||
assert sp.process_signal("Plain prose without a recommendation.") == "Hold"
|
||||
@@ -0,0 +1,232 @@
|
||||
"""Tests for structured-output agents (Trader and Research Manager).
|
||||
|
||||
The Portfolio Manager has its own coverage in tests/test_memory_log.py
|
||||
(which exercises the full memory-log → PM injection cycle). This file
|
||||
covers the parallel schemas, render functions, and graceful-fallback
|
||||
behavior we added for the Trader and Research Manager so all three
|
||||
decision-making agents share the same shape.
|
||||
"""
|
||||
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from tradingagents.agents.managers.research_manager import create_research_manager
|
||||
from tradingagents.agents.schemas import (
|
||||
PortfolioRating,
|
||||
ResearchPlan,
|
||||
TraderAction,
|
||||
TraderProposal,
|
||||
render_research_plan,
|
||||
render_trader_proposal,
|
||||
)
|
||||
from tradingagents.agents.trader.trader import create_trader
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Render functions
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
class TestRenderTraderProposal:
|
||||
def test_minimal_required_fields(self):
|
||||
p = TraderProposal(action=TraderAction.HOLD, reasoning="Balanced setup; no edge.")
|
||||
md = render_trader_proposal(p)
|
||||
assert "**Action**: Hold" in md
|
||||
assert "**Reasoning**: Balanced setup; no edge." in md
|
||||
# The trailing FINAL TRANSACTION PROPOSAL line is preserved for the
|
||||
# analyst stop-signal text and any external code that greps for it.
|
||||
assert "FINAL TRANSACTION PROPOSAL: **HOLD**" in md
|
||||
|
||||
def test_optional_fields_included_when_present(self):
|
||||
p = TraderProposal(
|
||||
action=TraderAction.BUY,
|
||||
reasoning="Strong technicals + fundamentals.",
|
||||
entry_price=189.5,
|
||||
stop_loss=178.0,
|
||||
position_sizing="6% of portfolio",
|
||||
)
|
||||
md = render_trader_proposal(p)
|
||||
assert "**Action**: Buy" in md
|
||||
assert "**Entry Price**: 189.5" in md
|
||||
assert "**Stop Loss**: 178.0" in md
|
||||
assert "**Position Sizing**: 6% of portfolio" in md
|
||||
assert "FINAL TRANSACTION PROPOSAL: **BUY**" in md
|
||||
|
||||
def test_optional_fields_omitted_when_absent(self):
|
||||
p = TraderProposal(action=TraderAction.SELL, reasoning="Guidance cut.")
|
||||
md = render_trader_proposal(p)
|
||||
assert "Entry Price" not in md
|
||||
assert "Stop Loss" not in md
|
||||
assert "Position Sizing" not in md
|
||||
assert "FINAL TRANSACTION PROPOSAL: **SELL**" in md
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
class TestRenderResearchPlan:
|
||||
def test_required_fields(self):
|
||||
p = ResearchPlan(
|
||||
recommendation=PortfolioRating.OVERWEIGHT,
|
||||
rationale="Bull case carried; tailwinds intact.",
|
||||
strategic_actions="Build position over two weeks; cap at 5%.",
|
||||
)
|
||||
md = render_research_plan(p)
|
||||
assert "**Recommendation**: Overweight" in md
|
||||
assert "**Rationale**: Bull case carried" in md
|
||||
assert "**Strategic Actions**: Build position" in md
|
||||
|
||||
def test_all_5_tier_ratings_render(self):
|
||||
for rating in PortfolioRating:
|
||||
p = ResearchPlan(
|
||||
recommendation=rating,
|
||||
rationale="r",
|
||||
strategic_actions="s",
|
||||
)
|
||||
md = render_research_plan(p)
|
||||
assert f"**Recommendation**: {rating.value}" in md
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Trader agent: structured happy path + fallback
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _make_trader_state():
|
||||
return {
|
||||
"company_of_interest": "NVDA",
|
||||
"investment_plan": "**Recommendation**: Buy\n**Rationale**: ...\n**Strategic Actions**: ...",
|
||||
}
|
||||
|
||||
|
||||
def _structured_trader_llm(captured: dict, proposal: TraderProposal | None = None):
|
||||
"""Build a MagicMock LLM whose with_structured_output binding captures the
|
||||
prompt and returns a real TraderProposal so render_trader_proposal works.
|
||||
"""
|
||||
if proposal is None:
|
||||
proposal = TraderProposal(
|
||||
action=TraderAction.BUY,
|
||||
reasoning="Strong setup.",
|
||||
)
|
||||
structured = MagicMock()
|
||||
structured.invoke.side_effect = lambda prompt: (
|
||||
captured.__setitem__("prompt", prompt) or proposal
|
||||
)
|
||||
llm = MagicMock()
|
||||
llm.with_structured_output.return_value = structured
|
||||
return llm
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
class TestTraderAgent:
|
||||
def test_structured_path_produces_rendered_markdown(self):
|
||||
captured = {}
|
||||
proposal = TraderProposal(
|
||||
action=TraderAction.BUY,
|
||||
reasoning="AI capex cycle intact; institutional flows constructive.",
|
||||
entry_price=189.5,
|
||||
stop_loss=178.0,
|
||||
position_sizing="6% of portfolio",
|
||||
)
|
||||
llm = _structured_trader_llm(captured, proposal)
|
||||
trader = create_trader(llm)
|
||||
result = trader(_make_trader_state())
|
||||
plan = result["trader_investment_plan"]
|
||||
assert "**Action**: Buy" in plan
|
||||
assert "**Entry Price**: 189.5" in plan
|
||||
assert "FINAL TRANSACTION PROPOSAL: **BUY**" in plan
|
||||
# The same rendered markdown is also added to messages for downstream agents.
|
||||
assert plan in result["messages"][0].content
|
||||
|
||||
def test_prompt_includes_investment_plan(self):
|
||||
captured = {}
|
||||
llm = _structured_trader_llm(captured)
|
||||
trader = create_trader(llm)
|
||||
trader(_make_trader_state())
|
||||
# The investment plan is in the user message of the captured prompt.
|
||||
prompt = captured["prompt"]
|
||||
assert any("Proposed Investment Plan" in m["content"] for m in prompt)
|
||||
|
||||
def test_falls_back_to_freetext_when_structured_unavailable(self):
|
||||
plain_response = (
|
||||
"**Action**: Sell\n\nGuidance cut hits margins.\n\n"
|
||||
"FINAL TRANSACTION PROPOSAL: **SELL**"
|
||||
)
|
||||
llm = MagicMock()
|
||||
llm.with_structured_output.side_effect = NotImplementedError("provider unsupported")
|
||||
llm.invoke.return_value = MagicMock(content=plain_response)
|
||||
trader = create_trader(llm)
|
||||
result = trader(_make_trader_state())
|
||||
assert result["trader_investment_plan"] == plain_response
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Research Manager agent: structured happy path + fallback
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _make_rm_state():
|
||||
return {
|
||||
"company_of_interest": "NVDA",
|
||||
"investment_debate_state": {
|
||||
"history": "Bull and bear arguments here.",
|
||||
"bull_history": "Bull says...",
|
||||
"bear_history": "Bear says...",
|
||||
"current_response": "",
|
||||
"judge_decision": "",
|
||||
"count": 1,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _structured_rm_llm(captured: dict, plan: ResearchPlan | None = None):
|
||||
if plan is None:
|
||||
plan = ResearchPlan(
|
||||
recommendation=PortfolioRating.HOLD,
|
||||
rationale="Balanced view across both sides.",
|
||||
strategic_actions="Hold current position; reassess after earnings.",
|
||||
)
|
||||
structured = MagicMock()
|
||||
structured.invoke.side_effect = lambda prompt: (
|
||||
captured.__setitem__("prompt", prompt) or plan
|
||||
)
|
||||
llm = MagicMock()
|
||||
llm.with_structured_output.return_value = structured
|
||||
return llm
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
class TestResearchManagerAgent:
|
||||
def test_structured_path_produces_rendered_markdown(self):
|
||||
captured = {}
|
||||
plan = ResearchPlan(
|
||||
recommendation=PortfolioRating.OVERWEIGHT,
|
||||
rationale="Bull case is stronger; AI tailwind intact.",
|
||||
strategic_actions="Build position gradually over two weeks.",
|
||||
)
|
||||
llm = _structured_rm_llm(captured, plan)
|
||||
rm = create_research_manager(llm)
|
||||
result = rm(_make_rm_state())
|
||||
ip = result["investment_plan"]
|
||||
assert "**Recommendation**: Overweight" in ip
|
||||
assert "**Rationale**: Bull case" in ip
|
||||
assert "**Strategic Actions**: Build position" in ip
|
||||
|
||||
def test_prompt_uses_5_tier_rating_scale(self):
|
||||
"""The RM prompt must list all five tiers so the schema enum matches user expectations."""
|
||||
captured = {}
|
||||
llm = _structured_rm_llm(captured)
|
||||
rm = create_research_manager(llm)
|
||||
rm(_make_rm_state())
|
||||
prompt = captured["prompt"]
|
||||
for tier in ("Buy", "Overweight", "Hold", "Underweight", "Sell"):
|
||||
assert f"**{tier}**" in prompt, f"missing {tier} in prompt"
|
||||
|
||||
def test_falls_back_to_freetext_when_structured_unavailable(self):
|
||||
plain_response = "**Recommendation**: Sell\n\n**Rationale**: ...\n\n**Strategic Actions**: ..."
|
||||
llm = MagicMock()
|
||||
llm.with_structured_output.side_effect = NotImplementedError("provider unsupported")
|
||||
llm.invoke.return_value = MagicMock(content=plain_response)
|
||||
rm = create_research_manager(llm)
|
||||
result = rm(_make_rm_state())
|
||||
assert result["investment_plan"] == plain_response
|
||||
@@ -0,0 +1,21 @@
|
||||
import unittest
|
||||
|
||||
import pytest
|
||||
|
||||
from cli.utils import normalize_ticker_symbol
|
||||
from tradingagents.agents.utils.agent_utils import build_instrument_context
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
class TickerSymbolHandlingTests(unittest.TestCase):
|
||||
def test_normalize_ticker_symbol_preserves_exchange_suffix(self):
|
||||
self.assertEqual(normalize_ticker_symbol(" cnc.to "), "CNC.TO")
|
||||
|
||||
def test_build_instrument_context_mentions_exact_symbol(self):
|
||||
context = build_instrument_context("7203.T")
|
||||
self.assertIn("7203.T", context)
|
||||
self.assertIn("exchange suffix", context)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,38 @@
|
||||
from .utils.agent_utils import create_msg_delete
|
||||
from .utils.agent_states import AgentState, InvestDebateState, RiskDebateState
|
||||
|
||||
from .analysts.fundamentals_analyst import create_fundamentals_analyst
|
||||
from .analysts.market_analyst import create_market_analyst
|
||||
from .analysts.news_analyst import create_news_analyst
|
||||
from .analysts.social_media_analyst import create_social_media_analyst
|
||||
|
||||
from .researchers.bear_researcher import create_bear_researcher
|
||||
from .researchers.bull_researcher import create_bull_researcher
|
||||
|
||||
from .risk_mgmt.aggressive_debator import create_aggressive_debator
|
||||
from .risk_mgmt.conservative_debator import create_conservative_debator
|
||||
from .risk_mgmt.neutral_debator import create_neutral_debator
|
||||
|
||||
from .managers.research_manager import create_research_manager
|
||||
from .managers.portfolio_manager import create_portfolio_manager
|
||||
|
||||
from .trader.trader import create_trader
|
||||
|
||||
__all__ = [
|
||||
"AgentState",
|
||||
"create_msg_delete",
|
||||
"InvestDebateState",
|
||||
"RiskDebateState",
|
||||
"create_bear_researcher",
|
||||
"create_bull_researcher",
|
||||
"create_research_manager",
|
||||
"create_fundamentals_analyst",
|
||||
"create_market_analyst",
|
||||
"create_neutral_debator",
|
||||
"create_news_analyst",
|
||||
"create_aggressive_debator",
|
||||
"create_portfolio_manager",
|
||||
"create_conservative_debator",
|
||||
"create_social_media_analyst",
|
||||
"create_trader",
|
||||
]
|
||||
@@ -0,0 +1,69 @@
|
||||
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
|
||||
from tradingagents.agents.utils.agent_utils import (
|
||||
build_instrument_context,
|
||||
get_balance_sheet,
|
||||
get_cashflow,
|
||||
get_fundamentals,
|
||||
get_income_statement,
|
||||
get_insider_transactions,
|
||||
get_language_instruction,
|
||||
)
|
||||
from tradingagents.dataflows.config import get_config
|
||||
|
||||
|
||||
def create_fundamentals_analyst(llm):
|
||||
def fundamentals_analyst_node(state):
|
||||
current_date = state["trade_date"]
|
||||
instrument_context = build_instrument_context(state["company_of_interest"])
|
||||
|
||||
tools = [
|
||||
get_fundamentals,
|
||||
get_balance_sheet,
|
||||
get_cashflow,
|
||||
get_income_statement,
|
||||
]
|
||||
|
||||
system_message = (
|
||||
"You are a researcher tasked with analyzing fundamental information over the past week about a company. Please write a comprehensive report of the company's fundamental information such as financial documents, company profile, basic company financials, and company financial history to gain a full view of the company's fundamental information to inform traders. Make sure to include as much detail as possible. Provide specific, actionable insights with supporting evidence to help traders make informed decisions."
|
||||
+ " Make sure to append a Markdown table at the end of the report to organize key points in the report, organized and easy to read."
|
||||
+ " Use the available tools: `get_fundamentals` for comprehensive company analysis, `get_balance_sheet`, `get_cashflow`, and `get_income_statement` for specific financial statements."
|
||||
+ get_language_instruction(),
|
||||
)
|
||||
|
||||
prompt = ChatPromptTemplate.from_messages(
|
||||
[
|
||||
(
|
||||
"system",
|
||||
"You are a helpful AI assistant, collaborating with other assistants."
|
||||
" Use the provided tools to progress towards answering the question."
|
||||
" If you are unable to fully answer, that's OK; another assistant with different tools"
|
||||
" will help where you left off. Execute what you can to make progress."
|
||||
" If you or any other assistant has the FINAL TRANSACTION PROPOSAL: **BUY/HOLD/SELL** or deliverable,"
|
||||
" prefix your response with FINAL TRANSACTION PROPOSAL: **BUY/HOLD/SELL** so the team knows to stop."
|
||||
" You have access to the following tools: {tool_names}.\n{system_message}"
|
||||
"For your reference, the current date is {current_date}. {instrument_context}",
|
||||
),
|
||||
MessagesPlaceholder(variable_name="messages"),
|
||||
]
|
||||
)
|
||||
|
||||
prompt = prompt.partial(system_message=system_message)
|
||||
prompt = prompt.partial(tool_names=", ".join([tool.name for tool in tools]))
|
||||
prompt = prompt.partial(current_date=current_date)
|
||||
prompt = prompt.partial(instrument_context=instrument_context)
|
||||
|
||||
chain = prompt | llm.bind_tools(tools)
|
||||
|
||||
result = chain.invoke(state["messages"])
|
||||
|
||||
report = ""
|
||||
|
||||
if len(result.tool_calls) == 0:
|
||||
report = result.content
|
||||
|
||||
return {
|
||||
"messages": [result],
|
||||
"fundamentals_report": report,
|
||||
}
|
||||
|
||||
return fundamentals_analyst_node
|
||||
@@ -0,0 +1,88 @@
|
||||
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
|
||||
from tradingagents.agents.utils.agent_utils import (
|
||||
build_instrument_context,
|
||||
get_indicators,
|
||||
get_language_instruction,
|
||||
get_stock_data,
|
||||
)
|
||||
from tradingagents.dataflows.config import get_config
|
||||
|
||||
|
||||
def create_market_analyst(llm):
|
||||
|
||||
def market_analyst_node(state):
|
||||
current_date = state["trade_date"]
|
||||
instrument_context = build_instrument_context(state["company_of_interest"])
|
||||
|
||||
tools = [
|
||||
get_stock_data,
|
||||
get_indicators,
|
||||
]
|
||||
|
||||
system_message = (
|
||||
"""You are a trading assistant tasked with analyzing financial markets. Your role is to select the **most relevant indicators** for a given market condition or trading strategy from the following list. The goal is to choose up to **8 indicators** that provide complementary insights without redundancy. Categories and each category's indicators are:
|
||||
|
||||
Moving Averages:
|
||||
- close_50_sma: 50 SMA: A medium-term trend indicator. Usage: Identify trend direction and serve as dynamic support/resistance. Tips: It lags price; combine with faster indicators for timely signals.
|
||||
- close_200_sma: 200 SMA: A long-term trend benchmark. Usage: Confirm overall market trend and identify golden/death cross setups. Tips: It reacts slowly; best for strategic trend confirmation rather than frequent trading entries.
|
||||
- close_10_ema: 10 EMA: A responsive short-term average. Usage: Capture quick shifts in momentum and potential entry points. Tips: Prone to noise in choppy markets; use alongside longer averages for filtering false signals.
|
||||
|
||||
MACD Related:
|
||||
- macd: MACD: Computes momentum via differences of EMAs. Usage: Look for crossovers and divergence as signals of trend changes. Tips: Confirm with other indicators in low-volatility or sideways markets.
|
||||
- macds: MACD Signal: An EMA smoothing of the MACD line. Usage: Use crossovers with the MACD line to trigger trades. Tips: Should be part of a broader strategy to avoid false positives.
|
||||
- macdh: MACD Histogram: Shows the gap between the MACD line and its signal. Usage: Visualize momentum strength and spot divergence early. Tips: Can be volatile; complement with additional filters in fast-moving markets.
|
||||
|
||||
Momentum Indicators:
|
||||
- rsi: RSI: Measures momentum to flag overbought/oversold conditions. Usage: Apply 70/30 thresholds and watch for divergence to signal reversals. Tips: In strong trends, RSI may remain extreme; always cross-check with trend analysis.
|
||||
|
||||
Volatility Indicators:
|
||||
- boll: Bollinger Middle: A 20 SMA serving as the basis for Bollinger Bands. Usage: Acts as a dynamic benchmark for price movement. Tips: Combine with the upper and lower bands to effectively spot breakouts or reversals.
|
||||
- boll_ub: Bollinger Upper Band: Typically 2 standard deviations above the middle line. Usage: Signals potential overbought conditions and breakout zones. Tips: Confirm signals with other tools; prices may ride the band in strong trends.
|
||||
- boll_lb: Bollinger Lower Band: Typically 2 standard deviations below the middle line. Usage: Indicates potential oversold conditions. Tips: Use additional analysis to avoid false reversal signals.
|
||||
- atr: ATR: Averages true range to measure volatility. Usage: Set stop-loss levels and adjust position sizes based on current market volatility. Tips: It's a reactive measure, so use it as part of a broader risk management strategy.
|
||||
|
||||
Volume-Based Indicators:
|
||||
- vwma: VWMA: A moving average weighted by volume. Usage: Confirm trends by integrating price action with volume data. Tips: Watch for skewed results from volume spikes; use in combination with other volume analyses.
|
||||
|
||||
- Select indicators that provide diverse and complementary information. Avoid redundancy (e.g., do not select both rsi and stochrsi). Also briefly explain why they are suitable for the given market context. When you tool call, please use the exact name of the indicators provided above as they are defined parameters, otherwise your call will fail. Please make sure to call get_stock_data first to retrieve the CSV that is needed to generate indicators. Then use get_indicators with the specific indicator names. Write a very detailed and nuanced report of the trends you observe. Provide specific, actionable insights with supporting evidence to help traders make informed decisions."""
|
||||
+ """ Make sure to append a Markdown table at the end of the report to organize key points in the report, organized and easy to read."""
|
||||
+ get_language_instruction()
|
||||
)
|
||||
|
||||
prompt = ChatPromptTemplate.from_messages(
|
||||
[
|
||||
(
|
||||
"system",
|
||||
"You are a helpful AI assistant, collaborating with other assistants."
|
||||
" Use the provided tools to progress towards answering the question."
|
||||
" If you are unable to fully answer, that's OK; another assistant with different tools"
|
||||
" will help where you left off. Execute what you can to make progress."
|
||||
" If you or any other assistant has the FINAL TRANSACTION PROPOSAL: **BUY/HOLD/SELL** or deliverable,"
|
||||
" prefix your response with FINAL TRANSACTION PROPOSAL: **BUY/HOLD/SELL** so the team knows to stop."
|
||||
" You have access to the following tools: {tool_names}.\n{system_message}"
|
||||
"For your reference, the current date is {current_date}. {instrument_context}",
|
||||
),
|
||||
MessagesPlaceholder(variable_name="messages"),
|
||||
]
|
||||
)
|
||||
|
||||
prompt = prompt.partial(system_message=system_message)
|
||||
prompt = prompt.partial(tool_names=", ".join([tool.name for tool in tools]))
|
||||
prompt = prompt.partial(current_date=current_date)
|
||||
prompt = prompt.partial(instrument_context=instrument_context)
|
||||
|
||||
chain = prompt | llm.bind_tools(tools)
|
||||
|
||||
result = chain.invoke(state["messages"])
|
||||
|
||||
report = ""
|
||||
|
||||
if len(result.tool_calls) == 0:
|
||||
report = result.content
|
||||
|
||||
return {
|
||||
"messages": [result],
|
||||
"market_report": report,
|
||||
}
|
||||
|
||||
return market_analyst_node
|
||||
@@ -0,0 +1,62 @@
|
||||
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
|
||||
from tradingagents.agents.utils.agent_utils import (
|
||||
build_instrument_context,
|
||||
get_global_news,
|
||||
get_language_instruction,
|
||||
get_news,
|
||||
)
|
||||
from tradingagents.dataflows.config import get_config
|
||||
|
||||
|
||||
def create_news_analyst(llm):
|
||||
def news_analyst_node(state):
|
||||
current_date = state["trade_date"]
|
||||
instrument_context = build_instrument_context(state["company_of_interest"])
|
||||
|
||||
tools = [
|
||||
get_news,
|
||||
get_global_news,
|
||||
]
|
||||
|
||||
system_message = (
|
||||
"You are a news researcher tasked with analyzing recent news and trends over the past week. Please write a comprehensive report of the current state of the world that is relevant for trading and macroeconomics. Use the available tools: get_news(query, start_date, end_date) for company-specific or targeted news searches, and get_global_news(curr_date, look_back_days, limit) for broader macroeconomic news. Provide specific, actionable insights with supporting evidence to help traders make informed decisions."
|
||||
+ """ Make sure to append a Markdown table at the end of the report to organize key points in the report, organized and easy to read."""
|
||||
+ get_language_instruction()
|
||||
)
|
||||
|
||||
prompt = ChatPromptTemplate.from_messages(
|
||||
[
|
||||
(
|
||||
"system",
|
||||
"You are a helpful AI assistant, collaborating with other assistants."
|
||||
" Use the provided tools to progress towards answering the question."
|
||||
" If you are unable to fully answer, that's OK; another assistant with different tools"
|
||||
" will help where you left off. Execute what you can to make progress."
|
||||
" If you or any other assistant has the FINAL TRANSACTION PROPOSAL: **BUY/HOLD/SELL** or deliverable,"
|
||||
" prefix your response with FINAL TRANSACTION PROPOSAL: **BUY/HOLD/SELL** so the team knows to stop."
|
||||
" You have access to the following tools: {tool_names}.\n{system_message}"
|
||||
"For your reference, the current date is {current_date}. {instrument_context}",
|
||||
),
|
||||
MessagesPlaceholder(variable_name="messages"),
|
||||
]
|
||||
)
|
||||
|
||||
prompt = prompt.partial(system_message=system_message)
|
||||
prompt = prompt.partial(tool_names=", ".join([tool.name for tool in tools]))
|
||||
prompt = prompt.partial(current_date=current_date)
|
||||
prompt = prompt.partial(instrument_context=instrument_context)
|
||||
|
||||
chain = prompt | llm.bind_tools(tools)
|
||||
result = chain.invoke(state["messages"])
|
||||
|
||||
report = ""
|
||||
|
||||
if len(result.tool_calls) == 0:
|
||||
report = result.content
|
||||
|
||||
return {
|
||||
"messages": [result],
|
||||
"news_report": report,
|
||||
}
|
||||
|
||||
return news_analyst_node
|
||||
@@ -0,0 +1,57 @@
|
||||
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
|
||||
from tradingagents.agents.utils.agent_utils import build_instrument_context, get_language_instruction, get_news
|
||||
from tradingagents.dataflows.config import get_config
|
||||
|
||||
|
||||
def create_social_media_analyst(llm):
|
||||
def social_media_analyst_node(state):
|
||||
current_date = state["trade_date"]
|
||||
instrument_context = build_instrument_context(state["company_of_interest"])
|
||||
|
||||
tools = [
|
||||
get_news,
|
||||
]
|
||||
|
||||
system_message = (
|
||||
"You are a social media and company specific news researcher/analyst tasked with analyzing social media posts, recent company news, and public sentiment for a specific company over the past week. You will be given a company's name your objective is to write a comprehensive long report detailing your analysis, insights, and implications for traders and investors on this company's current state after looking at social media and what people are saying about that company, analyzing sentiment data of what people feel each day about the company, and looking at recent company news. Use the get_news(query, start_date, end_date) tool to search for company-specific news and social media discussions. Try to look at all sources possible from social media to sentiment to news. Provide specific, actionable insights with supporting evidence to help traders make informed decisions."
|
||||
+ """ Make sure to append a Markdown table at the end of the report to organize key points in the report, organized and easy to read."""
|
||||
+ get_language_instruction()
|
||||
)
|
||||
|
||||
prompt = ChatPromptTemplate.from_messages(
|
||||
[
|
||||
(
|
||||
"system",
|
||||
"You are a helpful AI assistant, collaborating with other assistants."
|
||||
" Use the provided tools to progress towards answering the question."
|
||||
" If you are unable to fully answer, that's OK; another assistant with different tools"
|
||||
" will help where you left off. Execute what you can to make progress."
|
||||
" If you or any other assistant has the FINAL TRANSACTION PROPOSAL: **BUY/HOLD/SELL** or deliverable,"
|
||||
" prefix your response with FINAL TRANSACTION PROPOSAL: **BUY/HOLD/SELL** so the team knows to stop."
|
||||
" You have access to the following tools: {tool_names}.\n{system_message}"
|
||||
"For your reference, the current date is {current_date}. {instrument_context}",
|
||||
),
|
||||
MessagesPlaceholder(variable_name="messages"),
|
||||
]
|
||||
)
|
||||
|
||||
prompt = prompt.partial(system_message=system_message)
|
||||
prompt = prompt.partial(tool_names=", ".join([tool.name for tool in tools]))
|
||||
prompt = prompt.partial(current_date=current_date)
|
||||
prompt = prompt.partial(instrument_context=instrument_context)
|
||||
|
||||
chain = prompt | llm.bind_tools(tools)
|
||||
|
||||
result = chain.invoke(state["messages"])
|
||||
|
||||
report = ""
|
||||
|
||||
if len(result.tool_calls) == 0:
|
||||
report = result.content
|
||||
|
||||
return {
|
||||
"messages": [result],
|
||||
"sentiment_report": report,
|
||||
}
|
||||
|
||||
return social_media_analyst_node
|
||||
@@ -0,0 +1,92 @@
|
||||
"""Portfolio Manager: synthesises the risk-analyst debate into the final decision.
|
||||
|
||||
Uses LangChain's ``with_structured_output`` so the LLM produces a typed
|
||||
``PortfolioDecision`` directly, in a single call. The result is rendered
|
||||
back to markdown for storage in ``final_trade_decision`` so memory log,
|
||||
CLI display, and saved reports continue to consume the same shape they do
|
||||
today. When a provider does not expose structured output, the agent falls
|
||||
back gracefully to free-text generation.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from tradingagents.agents.schemas import PortfolioDecision, render_pm_decision
|
||||
from tradingagents.agents.utils.agent_utils import (
|
||||
build_instrument_context,
|
||||
get_language_instruction,
|
||||
)
|
||||
from tradingagents.agents.utils.structured import (
|
||||
bind_structured,
|
||||
invoke_structured_or_freetext,
|
||||
)
|
||||
|
||||
|
||||
def create_portfolio_manager(llm):
|
||||
structured_llm = bind_structured(llm, PortfolioDecision, "Portfolio Manager")
|
||||
|
||||
def portfolio_manager_node(state) -> dict:
|
||||
instrument_context = build_instrument_context(state["company_of_interest"])
|
||||
|
||||
history = state["risk_debate_state"]["history"]
|
||||
risk_debate_state = state["risk_debate_state"]
|
||||
research_plan = state["investment_plan"]
|
||||
trader_plan = state["trader_investment_plan"]
|
||||
|
||||
past_context = state.get("past_context", "")
|
||||
lessons_line = (
|
||||
f"- Lessons from prior decisions and outcomes:\n{past_context}\n"
|
||||
if past_context
|
||||
else ""
|
||||
)
|
||||
|
||||
prompt = f"""As the Portfolio Manager, synthesize the risk analysts' debate and deliver the final trading decision.
|
||||
|
||||
{instrument_context}
|
||||
|
||||
---
|
||||
|
||||
**Rating Scale** (use exactly one):
|
||||
- **Buy**: Strong conviction to enter or add to position
|
||||
- **Overweight**: Favorable outlook, gradually increase exposure
|
||||
- **Hold**: Maintain current position, no action needed
|
||||
- **Underweight**: Reduce exposure, take partial profits
|
||||
- **Sell**: Exit position or avoid entry
|
||||
|
||||
**Context:**
|
||||
- Research Manager's investment plan: **{research_plan}**
|
||||
- Trader's transaction proposal: **{trader_plan}**
|
||||
{lessons_line}
|
||||
**Risk Analysts Debate History:**
|
||||
{history}
|
||||
|
||||
---
|
||||
|
||||
Be decisive and ground every conclusion in specific evidence from the analysts.{get_language_instruction()}"""
|
||||
|
||||
final_trade_decision = invoke_structured_or_freetext(
|
||||
structured_llm,
|
||||
llm,
|
||||
prompt,
|
||||
render_pm_decision,
|
||||
"Portfolio Manager",
|
||||
)
|
||||
|
||||
new_risk_debate_state = {
|
||||
"judge_decision": final_trade_decision,
|
||||
"history": risk_debate_state["history"],
|
||||
"aggressive_history": risk_debate_state["aggressive_history"],
|
||||
"conservative_history": risk_debate_state["conservative_history"],
|
||||
"neutral_history": risk_debate_state["neutral_history"],
|
||||
"latest_speaker": "Judge",
|
||||
"current_aggressive_response": risk_debate_state["current_aggressive_response"],
|
||||
"current_conservative_response": risk_debate_state["current_conservative_response"],
|
||||
"current_neutral_response": risk_debate_state["current_neutral_response"],
|
||||
"count": risk_debate_state["count"],
|
||||
}
|
||||
|
||||
return {
|
||||
"risk_debate_state": new_risk_debate_state,
|
||||
"final_trade_decision": final_trade_decision,
|
||||
}
|
||||
|
||||
return portfolio_manager_node
|
||||
@@ -0,0 +1,64 @@
|
||||
"""Research Manager: turns the bull/bear debate into a structured investment plan for the trader."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from tradingagents.agents.schemas import ResearchPlan, render_research_plan
|
||||
from tradingagents.agents.utils.agent_utils import build_instrument_context, get_language_instruction
|
||||
from tradingagents.agents.utils.structured import (
|
||||
bind_structured,
|
||||
invoke_structured_or_freetext,
|
||||
)
|
||||
|
||||
|
||||
def create_research_manager(llm):
|
||||
structured_llm = bind_structured(llm, ResearchPlan, "Research Manager")
|
||||
|
||||
def research_manager_node(state) -> dict:
|
||||
instrument_context = build_instrument_context(state["company_of_interest"])
|
||||
history = state["investment_debate_state"].get("history", "")
|
||||
|
||||
investment_debate_state = state["investment_debate_state"]
|
||||
|
||||
prompt = f"""As the Research Manager and debate facilitator, your role is to critically evaluate this round of debate and deliver a clear, actionable investment plan for the trader.
|
||||
|
||||
{instrument_context}
|
||||
|
||||
---
|
||||
|
||||
**Rating Scale** (use exactly one):
|
||||
- **Buy**: Strong conviction in the bull thesis; recommend taking or growing the position
|
||||
- **Overweight**: Constructive view; recommend gradually increasing exposure
|
||||
- **Hold**: Balanced view; recommend maintaining the current position
|
||||
- **Underweight**: Cautious view; recommend trimming exposure
|
||||
- **Sell**: Strong conviction in the bear thesis; recommend exiting or avoiding the position
|
||||
|
||||
Commit to a clear stance whenever the debate's strongest arguments warrant one; reserve Hold for situations where the evidence on both sides is genuinely balanced.
|
||||
|
||||
---
|
||||
|
||||
**Debate History:**
|
||||
{history}""" + get_language_instruction()
|
||||
|
||||
investment_plan = invoke_structured_or_freetext(
|
||||
structured_llm,
|
||||
llm,
|
||||
prompt,
|
||||
render_research_plan,
|
||||
"Research Manager",
|
||||
)
|
||||
|
||||
new_investment_debate_state = {
|
||||
"judge_decision": investment_plan,
|
||||
"history": investment_debate_state.get("history", ""),
|
||||
"bear_history": investment_debate_state.get("bear_history", ""),
|
||||
"bull_history": investment_debate_state.get("bull_history", ""),
|
||||
"current_response": investment_plan,
|
||||
"count": investment_debate_state["count"],
|
||||
}
|
||||
|
||||
return {
|
||||
"investment_debate_state": new_investment_debate_state,
|
||||
"investment_plan": investment_plan,
|
||||
}
|
||||
|
||||
return research_manager_node
|
||||
@@ -0,0 +1,53 @@
|
||||
|
||||
|
||||
from tradingagents.agents.utils.agent_utils import build_instrument_context
|
||||
|
||||
|
||||
def create_bear_researcher(llm):
|
||||
def bear_node(state) -> dict:
|
||||
investment_debate_state = state["investment_debate_state"]
|
||||
history = investment_debate_state.get("history", "")
|
||||
bear_history = investment_debate_state.get("bear_history", "")
|
||||
|
||||
current_response = investment_debate_state.get("current_response", "")
|
||||
market_research_report = state["market_report"]
|
||||
sentiment_report = state["sentiment_report"]
|
||||
news_report = state["news_report"]
|
||||
fundamentals_report = state["fundamentals_report"]
|
||||
|
||||
prompt = f"""You are a Bear Analyst making the case against investing in the stock. Your goal is to present a well-reasoned argument emphasizing risks, challenges, and negative indicators. Leverage the provided research and data to highlight potential downsides and counter bullish arguments effectively.
|
||||
|
||||
Key points to focus on:
|
||||
|
||||
- Risks and Challenges: Highlight factors like market saturation, financial instability, or macroeconomic threats that could hinder the stock's performance.
|
||||
- Competitive Weaknesses: Emphasize vulnerabilities such as weaker market positioning, declining innovation, or threats from competitors.
|
||||
- Negative Indicators: Use evidence from financial data, market trends, or recent adverse news to support your position.
|
||||
- Bull Counterpoints: Critically analyze the bull argument with specific data and sound reasoning, exposing weaknesses or over-optimistic assumptions.
|
||||
- Engagement: Present your argument in a conversational style, directly engaging with the bull analyst's points and debating effectively rather than simply listing facts.
|
||||
|
||||
Resources available:
|
||||
|
||||
Market research report: {market_research_report}
|
||||
Social media sentiment report: {sentiment_report}
|
||||
Latest world affairs news: {news_report}
|
||||
Company fundamentals report: {fundamentals_report}
|
||||
Conversation history of the debate: {history}
|
||||
Last bull argument: {current_response}
|
||||
Use this information to deliver a compelling bear argument, refute the bull's claims, and engage in a dynamic debate that demonstrates the risks and weaknesses of investing in the stock.
|
||||
"""
|
||||
|
||||
response = llm.invoke(prompt)
|
||||
|
||||
argument = f"Bear Analyst: {response.content}"
|
||||
|
||||
new_investment_debate_state = {
|
||||
"history": history + "\n" + argument,
|
||||
"bear_history": bear_history + "\n" + argument,
|
||||
"bull_history": investment_debate_state.get("bull_history", ""),
|
||||
"current_response": argument,
|
||||
"count": investment_debate_state["count"] + 1,
|
||||
}
|
||||
|
||||
return {"investment_debate_state": new_investment_debate_state}
|
||||
|
||||
return bear_node
|
||||
@@ -0,0 +1,51 @@
|
||||
|
||||
|
||||
from tradingagents.agents.utils.agent_utils import build_instrument_context
|
||||
|
||||
|
||||
def create_bull_researcher(llm):
|
||||
def bull_node(state) -> dict:
|
||||
investment_debate_state = state["investment_debate_state"]
|
||||
history = investment_debate_state.get("history", "")
|
||||
bull_history = investment_debate_state.get("bull_history", "")
|
||||
|
||||
current_response = investment_debate_state.get("current_response", "")
|
||||
market_research_report = state["market_report"]
|
||||
sentiment_report = state["sentiment_report"]
|
||||
news_report = state["news_report"]
|
||||
fundamentals_report = state["fundamentals_report"]
|
||||
|
||||
prompt = f"""You are a Bull Analyst advocating for investing in the stock. Your task is to build a strong, evidence-based case emphasizing growth potential, competitive advantages, and positive market indicators. Leverage the provided research and data to address concerns and counter bearish arguments effectively.
|
||||
|
||||
Key points to focus on:
|
||||
- Growth Potential: Highlight the company's market opportunities, revenue projections, and scalability.
|
||||
- Competitive Advantages: Emphasize factors like unique products, strong branding, or dominant market positioning.
|
||||
- Positive Indicators: Use financial health, industry trends, and recent positive news as evidence.
|
||||
- Bear Counterpoints: Critically analyze the bear argument with specific data and sound reasoning, addressing concerns thoroughly and showing why the bull perspective holds stronger merit.
|
||||
- Engagement: Present your argument in a conversational style, engaging directly with the bear analyst's points and debating effectively rather than just listing data.
|
||||
|
||||
Resources available:
|
||||
Market research report: {market_research_report}
|
||||
Social media sentiment report: {sentiment_report}
|
||||
Latest world affairs news: {news_report}
|
||||
Company fundamentals report: {fundamentals_report}
|
||||
Conversation history of the debate: {history}
|
||||
Last bear argument: {current_response}
|
||||
Use this information to deliver a compelling bull argument, refute the bear's concerns, and engage in a dynamic debate that demonstrates the strengths of the bull position.
|
||||
"""
|
||||
|
||||
response = llm.invoke(prompt)
|
||||
|
||||
argument = f"Bull Analyst: {response.content}"
|
||||
|
||||
new_investment_debate_state = {
|
||||
"history": history + "\n" + argument,
|
||||
"bull_history": bull_history + "\n" + argument,
|
||||
"bear_history": investment_debate_state.get("bear_history", ""),
|
||||
"current_response": argument,
|
||||
"count": investment_debate_state["count"] + 1,
|
||||
}
|
||||
|
||||
return {"investment_debate_state": new_investment_debate_state}
|
||||
|
||||
return bull_node
|
||||
@@ -0,0 +1,56 @@
|
||||
|
||||
|
||||
from tradingagents.agents.utils.agent_utils import build_instrument_context
|
||||
|
||||
|
||||
def create_aggressive_debator(llm):
|
||||
def aggressive_node(state) -> dict:
|
||||
risk_debate_state = state["risk_debate_state"]
|
||||
history = risk_debate_state.get("history", "")
|
||||
aggressive_history = risk_debate_state.get("aggressive_history", "")
|
||||
|
||||
current_conservative_response = risk_debate_state.get("current_conservative_response", "")
|
||||
current_neutral_response = risk_debate_state.get("current_neutral_response", "")
|
||||
|
||||
market_research_report = state["market_report"]
|
||||
sentiment_report = state["sentiment_report"]
|
||||
news_report = state["news_report"]
|
||||
fundamentals_report = state["fundamentals_report"]
|
||||
|
||||
trader_decision = state["trader_investment_plan"]
|
||||
|
||||
prompt = f"""As the Aggressive Risk Analyst, your role is to actively champion high-reward, high-risk opportunities, emphasizing bold strategies and competitive advantages. When evaluating the trader's decision or plan, focus intently on the potential upside, growth potential, and innovative benefits—even when these come with elevated risk. Use the provided market data and sentiment analysis to strengthen your arguments and challenge the opposing views. Specifically, respond directly to each point made by the conservative and neutral analysts, countering with data-driven rebuttals and persuasive reasoning. Highlight where their caution might miss critical opportunities or where their assumptions may be overly conservative. Here is the trader's decision:
|
||||
|
||||
{trader_decision}
|
||||
|
||||
Your task is to create a compelling case for the trader's decision by questioning and critiquing the conservative and neutral stances to demonstrate why your high-reward perspective offers the best path forward. Incorporate insights from the following sources into your arguments:
|
||||
|
||||
Market Research Report: {market_research_report}
|
||||
Social Media Sentiment Report: {sentiment_report}
|
||||
Latest World Affairs Report: {news_report}
|
||||
Company Fundamentals Report: {fundamentals_report}
|
||||
Here is the current conversation history: {history} Here are the last arguments from the conservative analyst: {current_conservative_response} Here are the last arguments from the neutral analyst: {current_neutral_response}. If there are no responses from the other viewpoints yet, present your own argument based on the available data.
|
||||
|
||||
Engage actively by addressing any specific concerns raised, refuting the weaknesses in their logic, and asserting the benefits of risk-taking to outpace market norms. Maintain a focus on debating and persuading, not just presenting data. Challenge each counterpoint to underscore why a high-risk approach is optimal. Output conversationally as if you are speaking without any special formatting."""
|
||||
|
||||
response = llm.invoke(prompt)
|
||||
|
||||
argument = f"Aggressive Analyst: {response.content}"
|
||||
|
||||
new_risk_debate_state = {
|
||||
"history": history + "\n" + argument,
|
||||
"aggressive_history": aggressive_history + "\n" + argument,
|
||||
"conservative_history": risk_debate_state.get("conservative_history", ""),
|
||||
"neutral_history": risk_debate_state.get("neutral_history", ""),
|
||||
"latest_speaker": "Aggressive",
|
||||
"current_aggressive_response": argument,
|
||||
"current_conservative_response": risk_debate_state.get("current_conservative_response", ""),
|
||||
"current_neutral_response": risk_debate_state.get(
|
||||
"current_neutral_response", ""
|
||||
),
|
||||
"count": risk_debate_state["count"] + 1,
|
||||
}
|
||||
|
||||
return {"risk_debate_state": new_risk_debate_state}
|
||||
|
||||
return aggressive_node
|
||||
@@ -0,0 +1,58 @@
|
||||
|
||||
|
||||
from tradingagents.agents.utils.agent_utils import build_instrument_context
|
||||
|
||||
|
||||
def create_conservative_debator(llm):
|
||||
def conservative_node(state) -> dict:
|
||||
risk_debate_state = state["risk_debate_state"]
|
||||
history = risk_debate_state.get("history", "")
|
||||
conservative_history = risk_debate_state.get("conservative_history", "")
|
||||
|
||||
current_aggressive_response = risk_debate_state.get("current_aggressive_response", "")
|
||||
current_neutral_response = risk_debate_state.get("current_neutral_response", "")
|
||||
|
||||
market_research_report = state["market_report"]
|
||||
sentiment_report = state["sentiment_report"]
|
||||
news_report = state["news_report"]
|
||||
fundamentals_report = state["fundamentals_report"]
|
||||
|
||||
trader_decision = state["trader_investment_plan"]
|
||||
|
||||
prompt = f"""As the Conservative Risk Analyst, your primary objective is to protect assets, minimize volatility, and ensure steady, reliable growth. You prioritize stability, security, and risk mitigation, carefully assessing potential losses, economic downturns, and market volatility. When evaluating the trader's decision or plan, critically examine high-risk elements, pointing out where the decision may expose the firm to undue risk and where more cautious alternatives could secure long-term gains. Here is the trader's decision:
|
||||
|
||||
{trader_decision}
|
||||
|
||||
Your task is to actively counter the arguments of the Aggressive and Neutral Analysts, highlighting where their views may overlook potential threats or fail to prioritize sustainability. Respond directly to their points, drawing from the following data sources to build a convincing case for a low-risk approach adjustment to the trader's decision:
|
||||
|
||||
Market Research Report: {market_research_report}
|
||||
Social Media Sentiment Report: {sentiment_report}
|
||||
Latest World Affairs Report: {news_report}
|
||||
Company Fundamentals Report: {fundamentals_report}
|
||||
Here is the current conversation history: {history} Here is the last response from the aggressive analyst: {current_aggressive_response} Here is the last response from the neutral analyst: {current_neutral_response}. If there are no responses from the other viewpoints yet, present your own argument based on the available data.
|
||||
|
||||
Engage by questioning their optimism and emphasizing the potential downsides they may have overlooked. Address each of their counterpoints to showcase why a conservative stance is ultimately the safest path for the firm's assets. Focus on debating and critiquing their arguments to demonstrate the strength of a low-risk strategy over their approaches. Output conversationally as if you are speaking without any special formatting."""
|
||||
|
||||
response = llm.invoke(prompt)
|
||||
|
||||
argument = f"Conservative Analyst: {response.content}"
|
||||
|
||||
new_risk_debate_state = {
|
||||
"history": history + "\n" + argument,
|
||||
"aggressive_history": risk_debate_state.get("aggressive_history", ""),
|
||||
"conservative_history": conservative_history + "\n" + argument,
|
||||
"neutral_history": risk_debate_state.get("neutral_history", ""),
|
||||
"latest_speaker": "Conservative",
|
||||
"current_aggressive_response": risk_debate_state.get(
|
||||
"current_aggressive_response", ""
|
||||
),
|
||||
"current_conservative_response": argument,
|
||||
"current_neutral_response": risk_debate_state.get(
|
||||
"current_neutral_response", ""
|
||||
),
|
||||
"count": risk_debate_state["count"] + 1,
|
||||
}
|
||||
|
||||
return {"risk_debate_state": new_risk_debate_state}
|
||||
|
||||
return conservative_node
|
||||
@@ -0,0 +1,56 @@
|
||||
|
||||
|
||||
from tradingagents.agents.utils.agent_utils import build_instrument_context
|
||||
|
||||
|
||||
def create_neutral_debator(llm):
|
||||
def neutral_node(state) -> dict:
|
||||
risk_debate_state = state["risk_debate_state"]
|
||||
history = risk_debate_state.get("history", "")
|
||||
neutral_history = risk_debate_state.get("neutral_history", "")
|
||||
|
||||
current_aggressive_response = risk_debate_state.get("current_aggressive_response", "")
|
||||
current_conservative_response = risk_debate_state.get("current_conservative_response", "")
|
||||
|
||||
market_research_report = state["market_report"]
|
||||
sentiment_report = state["sentiment_report"]
|
||||
news_report = state["news_report"]
|
||||
fundamentals_report = state["fundamentals_report"]
|
||||
|
||||
trader_decision = state["trader_investment_plan"]
|
||||
|
||||
prompt = f"""As the Neutral Risk Analyst, your role is to provide a balanced perspective, weighing both the potential benefits and risks of the trader's decision or plan. You prioritize a well-rounded approach, evaluating the upsides and downsides while factoring in broader market trends, potential economic shifts, and diversification strategies.Here is the trader's decision:
|
||||
|
||||
{trader_decision}
|
||||
|
||||
Your task is to challenge both the Aggressive and Conservative Analysts, pointing out where each perspective may be overly optimistic or overly cautious. Use insights from the following data sources to support a moderate, sustainable strategy to adjust the trader's decision:
|
||||
|
||||
Market Research Report: {market_research_report}
|
||||
Social Media Sentiment Report: {sentiment_report}
|
||||
Latest World Affairs Report: {news_report}
|
||||
Company Fundamentals Report: {fundamentals_report}
|
||||
Here is the current conversation history: {history} Here is the last response from the aggressive analyst: {current_aggressive_response} Here is the last response from the conservative analyst: {current_conservative_response}. If there are no responses from the other viewpoints yet, present your own argument based on the available data.
|
||||
|
||||
Engage actively by analyzing both sides critically, addressing weaknesses in the aggressive and conservative arguments to advocate for a more balanced approach. Challenge each of their points to illustrate why a moderate risk strategy might offer the best of both worlds, providing growth potential while safeguarding against extreme volatility. Focus on debating rather than simply presenting data, aiming to show that a balanced view can lead to the most reliable outcomes. Output conversationally as if you are speaking without any special formatting."""
|
||||
|
||||
response = llm.invoke(prompt)
|
||||
|
||||
argument = f"Neutral Analyst: {response.content}"
|
||||
|
||||
new_risk_debate_state = {
|
||||
"history": history + "\n" + argument,
|
||||
"aggressive_history": risk_debate_state.get("aggressive_history", ""),
|
||||
"conservative_history": risk_debate_state.get("conservative_history", ""),
|
||||
"neutral_history": neutral_history + "\n" + argument,
|
||||
"latest_speaker": "Neutral",
|
||||
"current_aggressive_response": risk_debate_state.get(
|
||||
"current_aggressive_response", ""
|
||||
),
|
||||
"current_conservative_response": risk_debate_state.get("current_conservative_response", ""),
|
||||
"current_neutral_response": argument,
|
||||
"count": risk_debate_state["count"] + 1,
|
||||
}
|
||||
|
||||
return {"risk_debate_state": new_risk_debate_state}
|
||||
|
||||
return neutral_node
|
||||
@@ -0,0 +1,228 @@
|
||||
"""Pydantic schemas used by agents that produce structured output.
|
||||
|
||||
The framework's primary artifact is still prose: each agent's natural-language
|
||||
reasoning is what users read in the saved markdown reports and what the
|
||||
downstream agents read as context. Structured output is layered onto the
|
||||
three decision-making agents (Research Manager, Trader, Portfolio Manager)
|
||||
so that:
|
||||
|
||||
- Their outputs follow consistent section headers across runs and providers
|
||||
- Each provider's native structured-output mode is used (json_schema for
|
||||
OpenAI/xAI, response_schema for Gemini, tool-use for Anthropic)
|
||||
- Schema field descriptions become the model's output instructions, freeing
|
||||
the prompt body to focus on context and the rating-scale guidance
|
||||
- A render helper turns the parsed Pydantic instance back into the same
|
||||
markdown shape the rest of the system already consumes, so display,
|
||||
memory log, and saved reports keep working unchanged
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from enum import Enum
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Shared rating types
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class PortfolioRating(str, Enum):
|
||||
"""5-tier rating used by the Research Manager and Portfolio Manager."""
|
||||
|
||||
BUY = "Buy"
|
||||
OVERWEIGHT = "Overweight"
|
||||
HOLD = "Hold"
|
||||
UNDERWEIGHT = "Underweight"
|
||||
SELL = "Sell"
|
||||
|
||||
|
||||
class TraderAction(str, Enum):
|
||||
"""3-tier transaction direction used by the Trader.
|
||||
|
||||
The Trader's job is to translate the Research Manager's investment plan
|
||||
into a concrete transaction proposal: should the desk execute a Buy, a
|
||||
Sell, or sit on Hold this round. Position sizing and the nuanced
|
||||
Overweight / Underweight calls happen later at the Portfolio Manager.
|
||||
"""
|
||||
|
||||
BUY = "Buy"
|
||||
HOLD = "Hold"
|
||||
SELL = "Sell"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Research Manager
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class ResearchPlan(BaseModel):
|
||||
"""Structured investment plan produced by the Research Manager.
|
||||
|
||||
Hand-off to the Trader: the recommendation pins the directional view,
|
||||
the rationale captures which side of the bull/bear debate carried the
|
||||
argument, and the strategic actions translate that into concrete
|
||||
instructions the trader can execute against.
|
||||
"""
|
||||
|
||||
recommendation: PortfolioRating = Field(
|
||||
description=(
|
||||
"The investment recommendation. Exactly one of Buy / Overweight / "
|
||||
"Hold / Underweight / Sell. Reserve Hold for situations where the "
|
||||
"evidence on both sides is genuinely balanced; otherwise commit to "
|
||||
"the side with the stronger arguments."
|
||||
),
|
||||
)
|
||||
rationale: str = Field(
|
||||
description=(
|
||||
"Conversational summary of the key points from both sides of the "
|
||||
"debate, ending with which arguments led to the recommendation. "
|
||||
"Speak naturally, as if to a teammate."
|
||||
),
|
||||
)
|
||||
strategic_actions: str = Field(
|
||||
description=(
|
||||
"Concrete steps for the trader to implement the recommendation, "
|
||||
"including position sizing guidance consistent with the rating."
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def render_research_plan(plan: ResearchPlan) -> str:
|
||||
"""Render a ResearchPlan to markdown for storage and the trader's prompt context."""
|
||||
return "\n".join([
|
||||
f"**Recommendation**: {plan.recommendation.value}",
|
||||
"",
|
||||
f"**Rationale**: {plan.rationale}",
|
||||
"",
|
||||
f"**Strategic Actions**: {plan.strategic_actions}",
|
||||
])
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Trader
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TraderProposal(BaseModel):
|
||||
"""Structured transaction proposal produced by the Trader.
|
||||
|
||||
The trader reads the Research Manager's investment plan and the analyst
|
||||
reports, then turns them into a concrete transaction: what action to
|
||||
take, the reasoning that justifies it, and the practical levels for
|
||||
entry, stop-loss, and sizing.
|
||||
"""
|
||||
|
||||
action: TraderAction = Field(
|
||||
description="The transaction direction. Exactly one of Buy / Hold / Sell.",
|
||||
)
|
||||
reasoning: str = Field(
|
||||
description=(
|
||||
"The case for this action, anchored in the analysts' reports and "
|
||||
"the research plan. Two to four sentences."
|
||||
),
|
||||
)
|
||||
entry_price: Optional[float] = Field(
|
||||
default=None,
|
||||
description="Optional entry price target in the instrument's quote currency.",
|
||||
)
|
||||
stop_loss: Optional[float] = Field(
|
||||
default=None,
|
||||
description="Optional stop-loss price in the instrument's quote currency.",
|
||||
)
|
||||
position_sizing: Optional[str] = Field(
|
||||
default=None,
|
||||
description="Optional sizing guidance, e.g. '5% of portfolio'.",
|
||||
)
|
||||
|
||||
|
||||
def render_trader_proposal(proposal: TraderProposal) -> str:
|
||||
"""Render a TraderProposal to markdown.
|
||||
|
||||
The trailing ``FINAL TRANSACTION PROPOSAL: **BUY/HOLD/SELL**`` line is
|
||||
preserved for backward compatibility with the analyst stop-signal text
|
||||
and any external code that greps for it.
|
||||
"""
|
||||
parts = [
|
||||
f"**Action**: {proposal.action.value}",
|
||||
"",
|
||||
f"**Reasoning**: {proposal.reasoning}",
|
||||
]
|
||||
if proposal.entry_price is not None:
|
||||
parts.extend(["", f"**Entry Price**: {proposal.entry_price}"])
|
||||
if proposal.stop_loss is not None:
|
||||
parts.extend(["", f"**Stop Loss**: {proposal.stop_loss}"])
|
||||
if proposal.position_sizing:
|
||||
parts.extend(["", f"**Position Sizing**: {proposal.position_sizing}"])
|
||||
parts.extend([
|
||||
"",
|
||||
f"FINAL TRANSACTION PROPOSAL: **{proposal.action.value.upper()}**",
|
||||
])
|
||||
return "\n".join(parts)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Portfolio Manager
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class PortfolioDecision(BaseModel):
|
||||
"""Structured output produced by the Portfolio Manager.
|
||||
|
||||
The model fills every field as part of its primary LLM call; no separate
|
||||
extraction pass is required. Field descriptions double as the model's
|
||||
output instructions, so the prompt body only needs to convey context and
|
||||
the rating-scale guidance.
|
||||
"""
|
||||
|
||||
rating: PortfolioRating = Field(
|
||||
description=(
|
||||
"The final position rating. Exactly one of Buy / Overweight / Hold / "
|
||||
"Underweight / Sell, picked based on the analysts' debate."
|
||||
),
|
||||
)
|
||||
executive_summary: str = Field(
|
||||
description=(
|
||||
"A concise action plan covering entry strategy, position sizing, "
|
||||
"key risk levels, and time horizon. Two to four sentences."
|
||||
),
|
||||
)
|
||||
investment_thesis: str = Field(
|
||||
description=(
|
||||
"Detailed reasoning anchored in specific evidence from the analysts' "
|
||||
"debate. If prior lessons are referenced in the prompt context, "
|
||||
"incorporate them; otherwise rely solely on the current analysis."
|
||||
),
|
||||
)
|
||||
price_target: Optional[float] = Field(
|
||||
default=None,
|
||||
description="Optional target price in the instrument's quote currency.",
|
||||
)
|
||||
time_horizon: Optional[str] = Field(
|
||||
default=None,
|
||||
description="Optional recommended holding period, e.g. '3-6 months'.",
|
||||
)
|
||||
|
||||
|
||||
def render_pm_decision(decision: PortfolioDecision) -> str:
|
||||
"""Render a PortfolioDecision back to the markdown shape the rest of the system expects.
|
||||
|
||||
Memory log, CLI display, and saved report files all read this markdown,
|
||||
so the rendered output preserves the exact section headers (``**Rating**``,
|
||||
``**Executive Summary**``, ``**Investment Thesis**``) that downstream
|
||||
parsers and the report writers already handle.
|
||||
"""
|
||||
parts = [
|
||||
f"**Rating**: {decision.rating.value}",
|
||||
"",
|
||||
f"**Executive Summary**: {decision.executive_summary}",
|
||||
"",
|
||||
f"**Investment Thesis**: {decision.investment_thesis}",
|
||||
]
|
||||
if decision.price_target is not None:
|
||||
parts.extend(["", f"**Price Target**: {decision.price_target}"])
|
||||
if decision.time_horizon:
|
||||
parts.extend(["", f"**Time Horizon**: {decision.time_horizon}"])
|
||||
return "\n".join(parts)
|
||||
@@ -0,0 +1,62 @@
|
||||
"""Trader: turns the Research Manager's investment plan into a concrete transaction proposal."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import functools
|
||||
|
||||
from langchain_core.messages import AIMessage
|
||||
|
||||
from tradingagents.agents.schemas import TraderProposal, render_trader_proposal
|
||||
from tradingagents.agents.utils.agent_utils import build_instrument_context, get_language_instruction
|
||||
from tradingagents.agents.utils.structured import (
|
||||
bind_structured,
|
||||
invoke_structured_or_freetext,
|
||||
)
|
||||
|
||||
|
||||
def create_trader(llm):
|
||||
structured_llm = bind_structured(llm, TraderProposal, "Trader")
|
||||
|
||||
def trader_node(state, name):
|
||||
company_name = state["company_of_interest"]
|
||||
instrument_context = build_instrument_context(company_name)
|
||||
investment_plan = state["investment_plan"]
|
||||
|
||||
messages = [
|
||||
{
|
||||
"role": "system",
|
||||
"content": (
|
||||
"You are a trading agent analyzing market data to make investment decisions. "
|
||||
"Based on your analysis, provide a specific recommendation to buy, sell, or hold. "
|
||||
"Anchor your reasoning in the analysts' reports and the research plan."
|
||||
+ get_language_instruction()
|
||||
),
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"content": (
|
||||
f"Based on a comprehensive analysis by a team of analysts, here is an investment "
|
||||
f"plan tailored for {company_name}. {instrument_context} This plan incorporates "
|
||||
f"insights from current technical market trends, macroeconomic indicators, and "
|
||||
f"social media sentiment. Use this plan as a foundation for evaluating your next "
|
||||
f"trading decision.\n\nProposed Investment Plan: {investment_plan}\n\n"
|
||||
f"Leverage these insights to make an informed and strategic decision."
|
||||
),
|
||||
},
|
||||
]
|
||||
|
||||
trader_plan = invoke_structured_or_freetext(
|
||||
structured_llm,
|
||||
llm,
|
||||
messages,
|
||||
render_trader_proposal,
|
||||
"Trader",
|
||||
)
|
||||
|
||||
return {
|
||||
"messages": [AIMessage(content=trader_plan)],
|
||||
"trader_investment_plan": trader_plan,
|
||||
"sender": name,
|
||||
}
|
||||
|
||||
return functools.partial(trader_node, name="Trader")
|
||||
@@ -0,0 +1,73 @@
|
||||
from typing import Annotated
|
||||
from typing_extensions import TypedDict
|
||||
from langgraph.graph import MessagesState
|
||||
|
||||
|
||||
# Researcher team state
|
||||
class InvestDebateState(TypedDict):
|
||||
bull_history: Annotated[
|
||||
str, "Bullish Conversation history"
|
||||
] # Bullish Conversation history
|
||||
bear_history: Annotated[
|
||||
str, "Bearish Conversation history"
|
||||
] # Bullish Conversation history
|
||||
history: Annotated[str, "Conversation history"] # Conversation history
|
||||
current_response: Annotated[str, "Latest response"] # Last response
|
||||
judge_decision: Annotated[str, "Final judge decision"] # Last response
|
||||
count: Annotated[int, "Length of the current conversation"] # Conversation length
|
||||
|
||||
|
||||
# Risk management team state
|
||||
class RiskDebateState(TypedDict):
|
||||
aggressive_history: Annotated[
|
||||
str, "Aggressive Agent's Conversation history"
|
||||
] # Conversation history
|
||||
conservative_history: Annotated[
|
||||
str, "Conservative Agent's Conversation history"
|
||||
] # Conversation history
|
||||
neutral_history: Annotated[
|
||||
str, "Neutral Agent's Conversation history"
|
||||
] # Conversation history
|
||||
history: Annotated[str, "Conversation history"] # Conversation history
|
||||
latest_speaker: Annotated[str, "Analyst that spoke last"]
|
||||
current_aggressive_response: Annotated[
|
||||
str, "Latest response by the aggressive analyst"
|
||||
] # Last response
|
||||
current_conservative_response: Annotated[
|
||||
str, "Latest response by the conservative analyst"
|
||||
] # Last response
|
||||
current_neutral_response: Annotated[
|
||||
str, "Latest response by the neutral analyst"
|
||||
] # Last response
|
||||
judge_decision: Annotated[str, "Judge's decision"]
|
||||
count: Annotated[int, "Length of the current conversation"] # Conversation length
|
||||
|
||||
|
||||
class AgentState(MessagesState):
|
||||
company_of_interest: Annotated[str, "Company that we are interested in trading"]
|
||||
trade_date: Annotated[str, "What date we are trading at"]
|
||||
|
||||
sender: Annotated[str, "Agent that sent this message"]
|
||||
|
||||
# research step
|
||||
market_report: Annotated[str, "Report from the Market Analyst"]
|
||||
sentiment_report: Annotated[str, "Report from the Social Media Analyst"]
|
||||
news_report: Annotated[
|
||||
str, "Report from the News Researcher of current world affairs"
|
||||
]
|
||||
fundamentals_report: Annotated[str, "Report from the Fundamentals Researcher"]
|
||||
|
||||
# researcher team discussion step
|
||||
investment_debate_state: Annotated[
|
||||
InvestDebateState, "Current state of the debate on if to invest or not"
|
||||
]
|
||||
investment_plan: Annotated[str, "Plan generated by the Analyst"]
|
||||
|
||||
trader_investment_plan: Annotated[str, "Plan generated by the Trader"]
|
||||
|
||||
# risk management team discussion step
|
||||
risk_debate_state: Annotated[
|
||||
RiskDebateState, "Current state of the debate on evaluating risk"
|
||||
]
|
||||
final_trade_decision: Annotated[str, "Final decision made by the Risk Analysts"]
|
||||
past_context: Annotated[str, "Memory log context injected at run start (same-ticker decisions + cross-ticker lessons)"]
|
||||
@@ -0,0 +1,61 @@
|
||||
from langchain_core.messages import HumanMessage, RemoveMessage
|
||||
|
||||
# Import tools from separate utility files
|
||||
from tradingagents.agents.utils.core_stock_tools import (
|
||||
get_stock_data
|
||||
)
|
||||
from tradingagents.agents.utils.technical_indicators_tools import (
|
||||
get_indicators
|
||||
)
|
||||
from tradingagents.agents.utils.fundamental_data_tools import (
|
||||
get_fundamentals,
|
||||
get_balance_sheet,
|
||||
get_cashflow,
|
||||
get_income_statement
|
||||
)
|
||||
from tradingagents.agents.utils.news_data_tools import (
|
||||
get_news,
|
||||
get_insider_transactions,
|
||||
get_global_news
|
||||
)
|
||||
|
||||
|
||||
def get_language_instruction() -> str:
|
||||
"""Return a prompt instruction for the configured output language.
|
||||
|
||||
Returns empty string when English (default), so no extra tokens are used.
|
||||
Only applied to user-facing agents (analysts, portfolio manager).
|
||||
Internal debate agents stay in English for reasoning quality.
|
||||
"""
|
||||
from tradingagents.dataflows.config import get_config
|
||||
lang = get_config().get("output_language", "English")
|
||||
if lang.strip().lower() == "english":
|
||||
return ""
|
||||
return f" Write your entire response in {lang}."
|
||||
|
||||
|
||||
def build_instrument_context(ticker: str) -> str:
|
||||
"""Describe the exact instrument so agents preserve exchange-qualified tickers."""
|
||||
return (
|
||||
f"The instrument to analyze is `{ticker}`. "
|
||||
"Use this exact ticker in every tool call, report, and recommendation, "
|
||||
"preserving any exchange suffix (e.g. `.TO`, `.L`, `.HK`, `.T`)."
|
||||
)
|
||||
|
||||
def create_msg_delete():
|
||||
def delete_messages(state):
|
||||
"""Clear messages and add placeholder for Anthropic compatibility"""
|
||||
messages = state["messages"]
|
||||
|
||||
# Remove all messages
|
||||
removal_operations = [RemoveMessage(id=m.id) for m in messages]
|
||||
|
||||
# Add a minimal placeholder message
|
||||
placeholder = HumanMessage(content="Continue")
|
||||
|
||||
return {"messages": removal_operations + [placeholder]}
|
||||
|
||||
return delete_messages
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
from langchain_core.tools import tool
|
||||
from typing import Annotated
|
||||
from tradingagents.dataflows.interface import route_to_vendor
|
||||
|
||||
|
||||
@tool
|
||||
def get_stock_data(
|
||||
symbol: Annotated[str, "ticker symbol of the company"],
|
||||
start_date: Annotated[str, "Start date in yyyy-mm-dd format"],
|
||||
end_date: Annotated[str, "End date in yyyy-mm-dd format"],
|
||||
) -> str:
|
||||
"""
|
||||
Retrieve stock price data (OHLCV) for a given ticker symbol.
|
||||
Uses the configured core_stock_apis vendor.
|
||||
Args:
|
||||
symbol (str): Ticker symbol of the company, e.g. AAPL, TSM
|
||||
start_date (str): Start date in yyyy-mm-dd format
|
||||
end_date (str): End date in yyyy-mm-dd format
|
||||
Returns:
|
||||
str: A formatted dataframe containing the stock price data for the specified ticker symbol in the specified date range.
|
||||
"""
|
||||
return route_to_vendor("get_stock_data", symbol, start_date, end_date)
|
||||
@@ -0,0 +1,77 @@
|
||||
from langchain_core.tools import tool
|
||||
from typing import Annotated
|
||||
from tradingagents.dataflows.interface import route_to_vendor
|
||||
|
||||
|
||||
@tool
|
||||
def get_fundamentals(
|
||||
ticker: Annotated[str, "ticker symbol"],
|
||||
curr_date: Annotated[str, "current date you are trading at, yyyy-mm-dd"],
|
||||
) -> str:
|
||||
"""
|
||||
Retrieve comprehensive fundamental data for a given ticker symbol.
|
||||
Uses the configured fundamental_data vendor.
|
||||
Args:
|
||||
ticker (str): Ticker symbol of the company
|
||||
curr_date (str): Current date you are trading at, yyyy-mm-dd
|
||||
Returns:
|
||||
str: A formatted report containing comprehensive fundamental data
|
||||
"""
|
||||
return route_to_vendor("get_fundamentals", ticker, curr_date)
|
||||
|
||||
|
||||
@tool
|
||||
def get_balance_sheet(
|
||||
ticker: Annotated[str, "ticker symbol"],
|
||||
freq: Annotated[str, "reporting frequency: annual/quarterly"] = "quarterly",
|
||||
curr_date: Annotated[str, "current date you are trading at, yyyy-mm-dd"] = None,
|
||||
) -> str:
|
||||
"""
|
||||
Retrieve balance sheet data for a given ticker symbol.
|
||||
Uses the configured fundamental_data vendor.
|
||||
Args:
|
||||
ticker (str): Ticker symbol of the company
|
||||
freq (str): Reporting frequency: annual/quarterly (default quarterly)
|
||||
curr_date (str): Current date you are trading at, yyyy-mm-dd
|
||||
Returns:
|
||||
str: A formatted report containing balance sheet data
|
||||
"""
|
||||
return route_to_vendor("get_balance_sheet", ticker, freq, curr_date)
|
||||
|
||||
|
||||
@tool
|
||||
def get_cashflow(
|
||||
ticker: Annotated[str, "ticker symbol"],
|
||||
freq: Annotated[str, "reporting frequency: annual/quarterly"] = "quarterly",
|
||||
curr_date: Annotated[str, "current date you are trading at, yyyy-mm-dd"] = None,
|
||||
) -> str:
|
||||
"""
|
||||
Retrieve cash flow statement data for a given ticker symbol.
|
||||
Uses the configured fundamental_data vendor.
|
||||
Args:
|
||||
ticker (str): Ticker symbol of the company
|
||||
freq (str): Reporting frequency: annual/quarterly (default quarterly)
|
||||
curr_date (str): Current date you are trading at, yyyy-mm-dd
|
||||
Returns:
|
||||
str: A formatted report containing cash flow statement data
|
||||
"""
|
||||
return route_to_vendor("get_cashflow", ticker, freq, curr_date)
|
||||
|
||||
|
||||
@tool
|
||||
def get_income_statement(
|
||||
ticker: Annotated[str, "ticker symbol"],
|
||||
freq: Annotated[str, "reporting frequency: annual/quarterly"] = "quarterly",
|
||||
curr_date: Annotated[str, "current date you are trading at, yyyy-mm-dd"] = None,
|
||||
) -> str:
|
||||
"""
|
||||
Retrieve income statement data for a given ticker symbol.
|
||||
Uses the configured fundamental_data vendor.
|
||||
Args:
|
||||
ticker (str): Ticker symbol of the company
|
||||
freq (str): Reporting frequency: annual/quarterly (default quarterly)
|
||||
curr_date (str): Current date you are trading at, yyyy-mm-dd
|
||||
Returns:
|
||||
str: A formatted report containing income statement data
|
||||
"""
|
||||
return route_to_vendor("get_income_statement", ticker, freq, curr_date)
|
||||
@@ -0,0 +1,300 @@
|
||||
"""Append-only markdown decision log for TradingAgents."""
|
||||
|
||||
from typing import List, Optional
|
||||
from pathlib import Path
|
||||
import re
|
||||
|
||||
from tradingagents.agents.utils.rating import parse_rating
|
||||
|
||||
|
||||
class TradingMemoryLog:
|
||||
"""Append-only markdown log of trading decisions and reflections."""
|
||||
|
||||
# HTML comment: cannot appear in LLM prose output, safe as a hard delimiter
|
||||
_SEPARATOR = "\n\n<!-- ENTRY_END -->\n\n"
|
||||
# Precompiled patterns — avoids re-compilation on every load_entries() call
|
||||
_DECISION_RE = re.compile(r"DECISION:\n(.*?)(?=\nREFLECTION:|\Z)", re.DOTALL)
|
||||
_REFLECTION_RE = re.compile(r"REFLECTION:\n(.*?)$", re.DOTALL)
|
||||
|
||||
def __init__(self, config: dict = None):
|
||||
cfg = config or {}
|
||||
self._log_path = None
|
||||
path = cfg.get("memory_log_path")
|
||||
if path:
|
||||
self._log_path = Path(path).expanduser()
|
||||
self._log_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
# Optional cap on resolved entries. None disables rotation.
|
||||
self._max_entries = cfg.get("memory_log_max_entries")
|
||||
|
||||
# --- Write path (Phase A) ---
|
||||
|
||||
def store_decision(
|
||||
self,
|
||||
ticker: str,
|
||||
trade_date: str,
|
||||
final_trade_decision: str,
|
||||
) -> None:
|
||||
"""Append pending entry at end of propagate(). No LLM call."""
|
||||
if not self._log_path:
|
||||
return
|
||||
# Idempotency guard: fast raw-text scan instead of full parse
|
||||
if self._log_path.exists():
|
||||
raw = self._log_path.read_text(encoding="utf-8")
|
||||
for line in raw.splitlines():
|
||||
if line.startswith(f"[{trade_date} | {ticker} |") and line.endswith("| pending]"):
|
||||
return
|
||||
rating = parse_rating(final_trade_decision)
|
||||
tag = f"[{trade_date} | {ticker} | {rating} | pending]"
|
||||
entry = f"{tag}\n\nDECISION:\n{final_trade_decision}{self._SEPARATOR}"
|
||||
with open(self._log_path, "a", encoding="utf-8") as f:
|
||||
f.write(entry)
|
||||
|
||||
# --- Read path (Phase A) ---
|
||||
|
||||
def load_entries(self) -> List[dict]:
|
||||
"""Parse all entries from log. Returns list of dicts."""
|
||||
if not self._log_path or not self._log_path.exists():
|
||||
return []
|
||||
text = self._log_path.read_text(encoding="utf-8")
|
||||
raw_entries = [e.strip() for e in text.split(self._SEPARATOR) if e.strip()]
|
||||
entries = []
|
||||
for raw in raw_entries:
|
||||
parsed = self._parse_entry(raw)
|
||||
if parsed:
|
||||
entries.append(parsed)
|
||||
return entries
|
||||
|
||||
def get_pending_entries(self) -> List[dict]:
|
||||
"""Return entries with outcome:pending (for Phase B)."""
|
||||
return [e for e in self.load_entries() if e.get("pending")]
|
||||
|
||||
def get_past_context(self, ticker: str, n_same: int = 5, n_cross: int = 3) -> str:
|
||||
"""Return formatted past context string for agent prompt injection."""
|
||||
entries = [e for e in self.load_entries() if not e.get("pending")]
|
||||
if not entries:
|
||||
return ""
|
||||
|
||||
same, cross = [], []
|
||||
for e in reversed(entries):
|
||||
if len(same) >= n_same and len(cross) >= n_cross:
|
||||
break
|
||||
if e["ticker"] == ticker and len(same) < n_same:
|
||||
same.append(e)
|
||||
elif e["ticker"] != ticker and len(cross) < n_cross:
|
||||
cross.append(e)
|
||||
|
||||
if not same and not cross:
|
||||
return ""
|
||||
|
||||
parts = []
|
||||
if same:
|
||||
parts.append(f"Past analyses of {ticker} (most recent first):")
|
||||
parts.extend(self._format_full(e) for e in same)
|
||||
if cross:
|
||||
parts.append("Recent cross-ticker lessons:")
|
||||
parts.extend(self._format_reflection_only(e) for e in cross)
|
||||
return "\n\n".join(parts)
|
||||
|
||||
# --- Update path (Phase B) ---
|
||||
|
||||
def update_with_outcome(
|
||||
self,
|
||||
ticker: str,
|
||||
trade_date: str,
|
||||
raw_return: float,
|
||||
alpha_return: float,
|
||||
holding_days: int,
|
||||
reflection: str,
|
||||
) -> None:
|
||||
"""Replace pending tag and append REFLECTION section using atomic write.
|
||||
|
||||
Finds the first pending entry matching (trade_date, ticker), updates
|
||||
its tag with return figures, and appends a REFLECTION section. Uses
|
||||
a temp-file + os.replace() so a crash mid-write never corrupts the log.
|
||||
"""
|
||||
if not self._log_path or not self._log_path.exists():
|
||||
return
|
||||
|
||||
text = self._log_path.read_text(encoding="utf-8")
|
||||
blocks = text.split(self._SEPARATOR)
|
||||
|
||||
pending_prefix = f"[{trade_date} | {ticker} |"
|
||||
raw_pct = f"{raw_return:+.1%}"
|
||||
alpha_pct = f"{alpha_return:+.1%}"
|
||||
|
||||
updated = False
|
||||
new_blocks = []
|
||||
for block in blocks:
|
||||
stripped = block.strip()
|
||||
if not stripped:
|
||||
new_blocks.append(block)
|
||||
continue
|
||||
|
||||
lines = stripped.splitlines()
|
||||
tag_line = lines[0].strip()
|
||||
|
||||
if (
|
||||
not updated
|
||||
and tag_line.startswith(pending_prefix)
|
||||
and tag_line.endswith("| pending]")
|
||||
):
|
||||
# Parse rating from the existing pending tag
|
||||
fields = [f.strip() for f in tag_line[1:-1].split("|")]
|
||||
rating = fields[2]
|
||||
new_tag = (
|
||||
f"[{trade_date} | {ticker} | {rating}"
|
||||
f" | {raw_pct} | {alpha_pct} | {holding_days}d]"
|
||||
)
|
||||
rest = "\n".join(lines[1:])
|
||||
new_blocks.append(
|
||||
f"{new_tag}\n\n{rest.lstrip()}\n\nREFLECTION:\n{reflection}"
|
||||
)
|
||||
updated = True
|
||||
else:
|
||||
new_blocks.append(block)
|
||||
|
||||
if not updated:
|
||||
return
|
||||
|
||||
new_blocks = self._apply_rotation(new_blocks)
|
||||
new_text = self._SEPARATOR.join(new_blocks)
|
||||
tmp_path = self._log_path.with_suffix(".tmp")
|
||||
tmp_path.write_text(new_text, encoding="utf-8")
|
||||
tmp_path.replace(self._log_path)
|
||||
|
||||
def batch_update_with_outcomes(self, updates: List[dict]) -> None:
|
||||
"""Apply multiple outcome updates in a single read + atomic write.
|
||||
|
||||
Each element of updates must have keys: ticker, trade_date,
|
||||
raw_return, alpha_return, holding_days, reflection.
|
||||
"""
|
||||
if not self._log_path or not self._log_path.exists() or not updates:
|
||||
return
|
||||
|
||||
text = self._log_path.read_text(encoding="utf-8")
|
||||
blocks = text.split(self._SEPARATOR)
|
||||
|
||||
# Build lookup keyed by (trade_date, ticker) for O(1) dispatch
|
||||
update_map = {(u["trade_date"], u["ticker"]): u for u in updates}
|
||||
|
||||
new_blocks = []
|
||||
for block in blocks:
|
||||
stripped = block.strip()
|
||||
if not stripped:
|
||||
new_blocks.append(block)
|
||||
continue
|
||||
|
||||
lines = stripped.splitlines()
|
||||
tag_line = lines[0].strip()
|
||||
|
||||
matched = False
|
||||
for (trade_date, ticker), upd in list(update_map.items()):
|
||||
pending_prefix = f"[{trade_date} | {ticker} |"
|
||||
if tag_line.startswith(pending_prefix) and tag_line.endswith("| pending]"):
|
||||
fields = [f.strip() for f in tag_line[1:-1].split("|")]
|
||||
rating = fields[2]
|
||||
raw_pct = f"{upd['raw_return']:+.1%}"
|
||||
alpha_pct = f"{upd['alpha_return']:+.1%}"
|
||||
new_tag = (
|
||||
f"[{trade_date} | {ticker} | {rating}"
|
||||
f" | {raw_pct} | {alpha_pct} | {upd['holding_days']}d]"
|
||||
)
|
||||
rest = "\n".join(lines[1:])
|
||||
new_blocks.append(
|
||||
f"{new_tag}\n\n{rest.lstrip()}\n\nREFLECTION:\n{upd['reflection']}"
|
||||
)
|
||||
del update_map[(trade_date, ticker)]
|
||||
matched = True
|
||||
break
|
||||
|
||||
if not matched:
|
||||
new_blocks.append(block)
|
||||
|
||||
new_blocks = self._apply_rotation(new_blocks)
|
||||
new_text = self._SEPARATOR.join(new_blocks)
|
||||
tmp_path = self._log_path.with_suffix(".tmp")
|
||||
tmp_path.write_text(new_text, encoding="utf-8")
|
||||
tmp_path.replace(self._log_path)
|
||||
|
||||
# --- Helpers ---
|
||||
|
||||
def _apply_rotation(self, blocks: List[str]) -> List[str]:
|
||||
"""Drop oldest resolved blocks when their count exceeds max_entries.
|
||||
|
||||
Pending blocks are always kept (they represent unprocessed work).
|
||||
Returns ``blocks`` unchanged when rotation is disabled or under cap.
|
||||
"""
|
||||
if not self._max_entries or self._max_entries <= 0:
|
||||
return blocks
|
||||
|
||||
# Tag each block with (kept, is_resolved) by parsing tag-line markers.
|
||||
decisions = []
|
||||
for block in blocks:
|
||||
stripped = block.strip()
|
||||
if not stripped:
|
||||
decisions.append((block, False))
|
||||
continue
|
||||
tag_line = stripped.splitlines()[0].strip()
|
||||
is_resolved = (
|
||||
tag_line.startswith("[")
|
||||
and tag_line.endswith("]")
|
||||
and not tag_line.endswith("| pending]")
|
||||
)
|
||||
decisions.append((block, is_resolved))
|
||||
|
||||
resolved_count = sum(1 for _, r in decisions if r)
|
||||
if resolved_count <= self._max_entries:
|
||||
return blocks
|
||||
|
||||
to_drop = resolved_count - self._max_entries
|
||||
kept: List[str] = []
|
||||
for block, is_resolved in decisions:
|
||||
if is_resolved and to_drop > 0:
|
||||
to_drop -= 1
|
||||
continue
|
||||
kept.append(block)
|
||||
return kept
|
||||
|
||||
def _parse_entry(self, raw: str) -> Optional[dict]:
|
||||
lines = raw.strip().splitlines()
|
||||
if not lines:
|
||||
return None
|
||||
tag_line = lines[0].strip()
|
||||
if not (tag_line.startswith("[") and tag_line.endswith("]")):
|
||||
return None
|
||||
fields = [f.strip() for f in tag_line[1:-1].split("|")]
|
||||
if len(fields) < 4:
|
||||
return None
|
||||
entry = {
|
||||
"date": fields[0],
|
||||
"ticker": fields[1],
|
||||
"rating": fields[2],
|
||||
"pending": fields[3] == "pending",
|
||||
"raw": fields[3] if fields[3] != "pending" else None,
|
||||
"alpha": fields[4] if len(fields) > 4 else None,
|
||||
"holding": fields[5] if len(fields) > 5 else None,
|
||||
}
|
||||
body = "\n".join(lines[1:]).strip()
|
||||
decision_match = self._DECISION_RE.search(body)
|
||||
reflection_match = self._REFLECTION_RE.search(body)
|
||||
entry["decision"] = decision_match.group(1).strip() if decision_match else ""
|
||||
entry["reflection"] = reflection_match.group(1).strip() if reflection_match else ""
|
||||
return entry
|
||||
|
||||
def _format_full(self, e: dict) -> str:
|
||||
raw = e["raw"] or "n/a"
|
||||
alpha = e["alpha"] or "n/a"
|
||||
holding = e["holding"] or "n/a"
|
||||
tag = f"[{e['date']} | {e['ticker']} | {e['rating']} | {raw} | {alpha} | {holding}]"
|
||||
parts = [tag, f"DECISION:\n{e['decision']}"]
|
||||
if e["reflection"]:
|
||||
parts.append(f"REFLECTION:\n{e['reflection']}")
|
||||
return "\n\n".join(parts)
|
||||
|
||||
def _format_reflection_only(self, e: dict) -> str:
|
||||
tag = f"[{e['date']} | {e['ticker']} | {e['rating']} | {e['raw'] or 'n/a'}]"
|
||||
if e["reflection"]:
|
||||
return f"{tag}\n{e['reflection']}"
|
||||
text = e["decision"][:300]
|
||||
suffix = "..." if len(e["decision"]) > 300 else ""
|
||||
return f"{tag}\n{text}{suffix}"
|
||||
@@ -0,0 +1,53 @@
|
||||
from langchain_core.tools import tool
|
||||
from typing import Annotated
|
||||
from tradingagents.dataflows.interface import route_to_vendor
|
||||
|
||||
@tool
|
||||
def get_news(
|
||||
ticker: Annotated[str, "Ticker symbol"],
|
||||
start_date: Annotated[str, "Start date in yyyy-mm-dd format"],
|
||||
end_date: Annotated[str, "End date in yyyy-mm-dd format"],
|
||||
) -> str:
|
||||
"""
|
||||
Retrieve news data for a given ticker symbol.
|
||||
Uses the configured news_data vendor.
|
||||
Args:
|
||||
ticker (str): Ticker symbol
|
||||
start_date (str): Start date in yyyy-mm-dd format
|
||||
end_date (str): End date in yyyy-mm-dd format
|
||||
Returns:
|
||||
str: A formatted string containing news data
|
||||
"""
|
||||
return route_to_vendor("get_news", ticker, start_date, end_date)
|
||||
|
||||
@tool
|
||||
def get_global_news(
|
||||
curr_date: Annotated[str, "Current date in yyyy-mm-dd format"],
|
||||
look_back_days: Annotated[int, "Number of days to look back"] = 7,
|
||||
limit: Annotated[int, "Maximum number of articles to return"] = 5,
|
||||
) -> str:
|
||||
"""
|
||||
Retrieve global news data.
|
||||
Uses the configured news_data vendor.
|
||||
Args:
|
||||
curr_date (str): Current date in yyyy-mm-dd format
|
||||
look_back_days (int): Number of days to look back (default 7)
|
||||
limit (int): Maximum number of articles to return (default 5)
|
||||
Returns:
|
||||
str: A formatted string containing global news data
|
||||
"""
|
||||
return route_to_vendor("get_global_news", curr_date, look_back_days, limit)
|
||||
|
||||
@tool
|
||||
def get_insider_transactions(
|
||||
ticker: Annotated[str, "ticker symbol"],
|
||||
) -> str:
|
||||
"""
|
||||
Retrieve insider transaction information about a company.
|
||||
Uses the configured news_data vendor.
|
||||
Args:
|
||||
ticker (str): Ticker symbol of the company
|
||||
Returns:
|
||||
str: A report of insider transaction data
|
||||
"""
|
||||
return route_to_vendor("get_insider_transactions", ticker)
|
||||
@@ -0,0 +1,50 @@
|
||||
"""Shared 5-tier rating vocabulary and a deterministic heuristic parser.
|
||||
|
||||
The same five-tier scale (Buy, Overweight, Hold, Underweight, Sell) is used by:
|
||||
- The Research Manager (investment plan recommendation)
|
||||
- The Portfolio Manager (final position decision)
|
||||
- The signal processor (rating extracted for downstream consumers)
|
||||
- The memory log (rating tag stored alongside each decision entry)
|
||||
|
||||
Centralising it here avoids drift between those call sites.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Tuple
|
||||
|
||||
|
||||
# Canonical, ordered 5-tier scale (most bullish to most bearish).
|
||||
RATINGS_5_TIER: Tuple[str, ...] = (
|
||||
"Buy", "Overweight", "Hold", "Underweight", "Sell",
|
||||
)
|
||||
|
||||
_RATING_SET = {r.lower() for r in RATINGS_5_TIER}
|
||||
|
||||
# Matches "Rating: X" / "rating - X" / "Rating: **X**" — tolerates markdown
|
||||
# bold wrappers and either a colon or hyphen separator.
|
||||
_RATING_LABEL_RE = re.compile(r"rating.*?[:\-][\s*]*(\w+)", re.IGNORECASE)
|
||||
|
||||
|
||||
def parse_rating(text: str, default: str = "Hold") -> str:
|
||||
"""Heuristically extract a 5-tier rating from prose text.
|
||||
|
||||
Two-pass strategy:
|
||||
1. Look for an explicit "Rating: X" label (tolerant of markdown bold).
|
||||
2. Fall back to the first 5-tier rating word found anywhere in the text.
|
||||
|
||||
Returns a Title-cased rating string, or ``default`` if no rating word appears.
|
||||
"""
|
||||
for line in text.splitlines():
|
||||
m = _RATING_LABEL_RE.search(line)
|
||||
if m and m.group(1).lower() in _RATING_SET:
|
||||
return m.group(1).capitalize()
|
||||
|
||||
for line in text.splitlines():
|
||||
for word in line.lower().split():
|
||||
clean = word.strip("*:.,")
|
||||
if clean in _RATING_SET:
|
||||
return clean.capitalize()
|
||||
|
||||
return default
|
||||
@@ -0,0 +1,73 @@
|
||||
"""Shared helpers for invoking an agent with structured output and a graceful fallback.
|
||||
|
||||
The Portfolio Manager, Trader, and Research Manager all follow the same
|
||||
canonical pattern:
|
||||
|
||||
1. At agent creation, wrap the LLM with ``with_structured_output(Schema)``
|
||||
so the model returns a typed Pydantic instance. If the provider does
|
||||
not support structured output (rare; mostly older Ollama models), the
|
||||
wrap is skipped and the agent uses free-text generation instead.
|
||||
2. At invocation, run the structured call and render the result back to
|
||||
markdown. If the structured call itself fails for any reason
|
||||
(malformed JSON from a weak model, transient provider issue), fall
|
||||
back to a plain ``llm.invoke`` so the pipeline never blocks.
|
||||
|
||||
Centralising the pattern here keeps the agent factories small and ensures
|
||||
all three agents log the same warnings when fallback fires.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any, Callable, Optional, TypeVar
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
T = TypeVar("T", bound=BaseModel)
|
||||
|
||||
|
||||
def bind_structured(llm: Any, schema: type[T], agent_name: str) -> Optional[Any]:
|
||||
"""Return ``llm.with_structured_output(schema)`` or ``None`` if unsupported.
|
||||
|
||||
Logs a warning when the binding fails so the user understands the agent
|
||||
will use free-text generation for every call instead of one-shot fallback.
|
||||
"""
|
||||
try:
|
||||
return llm.with_structured_output(schema)
|
||||
except (NotImplementedError, AttributeError) as exc:
|
||||
logger.warning(
|
||||
"%s: provider does not support with_structured_output (%s); "
|
||||
"falling back to free-text generation",
|
||||
agent_name, exc,
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def invoke_structured_or_freetext(
|
||||
structured_llm: Optional[Any],
|
||||
plain_llm: Any,
|
||||
prompt: Any,
|
||||
render: Callable[[T], str],
|
||||
agent_name: str,
|
||||
) -> str:
|
||||
"""Run the structured call and render to markdown; fall back to free-text on any failure.
|
||||
|
||||
``prompt`` is whatever the underlying LLM accepts (a string for chat
|
||||
invocations, a list of message dicts for chat models that take that
|
||||
shape). The same value is forwarded to the free-text path so the
|
||||
fallback sees the same input the structured call did.
|
||||
"""
|
||||
if structured_llm is not None:
|
||||
try:
|
||||
result = structured_llm.invoke(prompt)
|
||||
return render(result)
|
||||
except Exception as exc:
|
||||
logger.warning(
|
||||
"%s: structured-output invocation failed (%s); retrying once as free text",
|
||||
agent_name, exc,
|
||||
)
|
||||
|
||||
response = plain_llm.invoke(prompt)
|
||||
return response.content
|
||||
@@ -0,0 +1,32 @@
|
||||
from langchain_core.tools import tool
|
||||
from typing import Annotated
|
||||
from tradingagents.dataflows.interface import route_to_vendor
|
||||
|
||||
@tool
|
||||
def get_indicators(
|
||||
symbol: Annotated[str, "ticker symbol of the company"],
|
||||
indicator: Annotated[str, "technical indicator to get the analysis and report of"],
|
||||
curr_date: Annotated[str, "The current trading date you are trading on, YYYY-mm-dd"],
|
||||
look_back_days: Annotated[int, "how many days to look back"] = 30,
|
||||
) -> str:
|
||||
"""
|
||||
Retrieve a single technical indicator for a given ticker symbol.
|
||||
Uses the configured technical_indicators vendor.
|
||||
Args:
|
||||
symbol (str): Ticker symbol of the company, e.g. AAPL, TSM
|
||||
indicator (str): A single technical indicator name, e.g. 'rsi', 'macd'. Call this tool once per indicator.
|
||||
curr_date (str): The current trading date you are trading on, YYYY-mm-dd
|
||||
look_back_days (int): How many days to look back, default is 30
|
||||
Returns:
|
||||
str: A formatted dataframe containing the technical indicators for the specified ticker symbol and indicator.
|
||||
"""
|
||||
# LLMs sometimes pass multiple indicators as a comma-separated string;
|
||||
# split and process each individually.
|
||||
indicators = [i.strip().lower() for i in indicator.split(",") if i.strip()]
|
||||
results = []
|
||||
for ind in indicators:
|
||||
try:
|
||||
results.append(route_to_vendor("get_indicators", symbol, ind, curr_date, look_back_days))
|
||||
except ValueError as e:
|
||||
results.append(str(e))
|
||||
return "\n\n".join(results)
|
||||
@@ -0,0 +1,563 @@
|
||||
"""
|
||||
akshare data adapter for TradingAgents.
|
||||
Replaces yfinance as the data vendor for Chinese (A-share), US, and HK stocks.
|
||||
|
||||
Uses akshare (https://github.com/akfamily/akshare) which sources data from
|
||||
East Money (东方财富), providing reliable access without Yahoo Finance rate limits.
|
||||
"""
|
||||
|
||||
import pandas as pd
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Optional
|
||||
from dateutil.relativedelta import relativedelta
|
||||
import os
|
||||
|
||||
# Suppress akshare's internal tqdm progress bars
|
||||
os.environ.setdefault('TQDM_DISABLE', '1')
|
||||
|
||||
import akshare as ak
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
# Symbol detection helpers
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
|
||||
def _detect_market(symbol: str) -> str:
|
||||
"""Detect market: 'cn' (A-share), 'us' (US), or 'hk' (HK).
|
||||
|
||||
A-share: 6-digit numeric (000001, 600519)
|
||||
US: alphabetic tickers (AAPL, TSLA)
|
||||
HK: 5-digit numeric (00700, 09988)
|
||||
"""
|
||||
sym = symbol.strip().upper().replace(".", "").replace("-", "")
|
||||
if sym.isdigit():
|
||||
if len(sym) == 6:
|
||||
return "cn"
|
||||
elif len(sym) == 5:
|
||||
return "hk"
|
||||
return "us"
|
||||
|
||||
|
||||
def _get_exchange_prefix(symbol: str) -> str:
|
||||
"""Get exchange prefix for A-share financial statement APIs.
|
||||
|
||||
Shanghai: 60xxxx, 68xxxx → 'SH'
|
||||
Shenzhen: 00xxxx, 30xxxx → 'SZ'
|
||||
Beijing: 8xxxxx, 4xxxxx → 'BJ'
|
||||
"""
|
||||
sym = symbol.strip()
|
||||
first = sym[0]
|
||||
if first == '6':
|
||||
return "SH"
|
||||
elif first in ('0', '3'):
|
||||
return "SZ"
|
||||
elif first in ('8', '4'):
|
||||
return "BJ"
|
||||
return "SZ"
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
# Data fetching helpers
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
|
||||
COLUMN_MAP = {
|
||||
"日期": "date",
|
||||
"开盘": "open",
|
||||
"收盘": "close",
|
||||
"最高": "high",
|
||||
"最低": "low",
|
||||
"成交量": "volume",
|
||||
"成交额": "amount",
|
||||
"振幅": "amplitude",
|
||||
"涨跌幅": "pct_change",
|
||||
"涨跌额": "change",
|
||||
"换手率": "turnover",
|
||||
}
|
||||
|
||||
|
||||
def _get_cn_stock_data(symbol: str, start_date: str, end_date: str) -> pd.DataFrame:
|
||||
"""Fetch A-share OHLCV via akshare stock_zh_a_hist."""
|
||||
df = ak.stock_zh_a_hist(
|
||||
symbol=symbol.strip(),
|
||||
period="daily",
|
||||
start_date=start_date.replace("-", ""),
|
||||
end_date=end_date.replace("-", ""),
|
||||
adjust="qfq",
|
||||
)
|
||||
df = df.rename(columns=COLUMN_MAP)
|
||||
needed = ["date", "open", "close", "high", "low", "volume"]
|
||||
return df[[c for c in needed if c in df.columns]]
|
||||
|
||||
|
||||
def _get_us_stock_data(symbol: str, start_date: str, end_date: str) -> pd.DataFrame:
|
||||
"""Fetch US stock OHLCV via akshare stock_us_daily (no market code needed).
|
||||
|
||||
stock_us_daily returns all historical data; we filter by date range here.
|
||||
"""
|
||||
ticker = symbol.strip().upper()
|
||||
# akshare US tickers use dot notation (BRK.B), not dash (BRK-B)
|
||||
if "-" in symbol:
|
||||
ticker = ticker.replace("-", ".")
|
||||
df = ak.stock_us_daily(symbol=ticker, adjust="qfq")
|
||||
df["date"] = pd.to_datetime(df["date"])
|
||||
mask = (df["date"] >= pd.Timestamp(start_date)) & (df["date"] <= pd.Timestamp(end_date))
|
||||
df = df[mask]
|
||||
needed = ["date", "open", "close", "high", "low", "volume"]
|
||||
return df[[c for c in needed if c in df.columns]]
|
||||
|
||||
|
||||
def _get_hk_stock_data(symbol: str, start_date: str, end_date: str) -> pd.DataFrame:
|
||||
"""Fetch HK stock OHLCV via akshare stock_hk_hist."""
|
||||
df = ak.stock_hk_hist(
|
||||
symbol=symbol.strip(),
|
||||
period="daily",
|
||||
start_date=start_date.replace("-", ""),
|
||||
end_date=end_date.replace("-", ""),
|
||||
adjust="qfq",
|
||||
)
|
||||
df = df.rename(columns=COLUMN_MAP)
|
||||
needed = ["date", "open", "close", "high", "low", "volume"]
|
||||
return df[[c for c in needed if c in df.columns]]
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
# Formatting helpers
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
|
||||
def _fmt_stock_data(df: pd.DataFrame, symbol: str) -> str:
|
||||
"""Format OHLCV DataFrame as Markdown table string."""
|
||||
if df.empty:
|
||||
return f"No stock data found for {symbol} in the given date range."
|
||||
df = df.tail(60).copy()
|
||||
df["date"] = df["date"].astype(str)
|
||||
return df.to_markdown(index=False)
|
||||
|
||||
|
||||
def _fmt_financial(df: pd.DataFrame, statement: str, symbol: str, freq: str) -> str:
|
||||
"""Format financial statement DataFrame.
|
||||
|
||||
Handles both wide format (A-share: rows=periods, cols=items) and
|
||||
long format (US: rows=item×period, cols=ITEM_NAME+AMOUNT).
|
||||
"""
|
||||
if df.empty:
|
||||
return f"No {freq} {statement} data found for {symbol}."
|
||||
|
||||
# Long format (US stocks) — pivot to wide
|
||||
if "ITEM_NAME" in df.columns and "AMOUNT" in df.columns:
|
||||
pivot = df.pivot_table(
|
||||
index="REPORT_DATE",
|
||||
columns="ITEM_NAME",
|
||||
values="AMOUNT",
|
||||
aggfunc="first",
|
||||
)
|
||||
pivot = pivot.sort_index(ascending=False)
|
||||
return pivot.head(8).to_markdown()
|
||||
|
||||
# Wide format (A-share) — select date + key items
|
||||
key_items = {
|
||||
"balance sheet": [
|
||||
"REPORT_DATE", "TOTAL_ASSETS", "TOTAL_LIABILITIES",
|
||||
"TOTAL_EQUITY", "MONETARYFUNDS", "INVENTORY",
|
||||
"TOTAL_CURRENT_ASSETS", "TOTAL_CURRENT_LIAB",
|
||||
"TOTAL_NONCURRENT_ASSETS", "TOTAL_NONCURRENT_LIAB",
|
||||
"SHORT_LOAN", "LONG_LOAN", "GOODWILL",
|
||||
],
|
||||
"cash flow": [
|
||||
"REPORT_DATE", "NETCASH_OPERATE", "NETCASH_INVEST",
|
||||
"NETCASH_FINANCE", "CASH_EQUIVALENT_BEGIN",
|
||||
"CASH_EQUIVALENT_END", "OPERATE_INFLOW",
|
||||
"OPERATE_OUTFLOW", "INVEST_INFLOW", "INVEST_OUTFLOW",
|
||||
"FINANCE_INFLOW", "FINANCE_OUTFLOW",
|
||||
],
|
||||
"income statement": [
|
||||
"REPORT_DATE", "TOTAL_OPERATE_INCOME", "OPERATE_PROFIT",
|
||||
"TOTAL_PROFIT", "NET_PROFIT", "BASIC_EPS",
|
||||
"TOTAL_OPERATE_COST", "OPERATE_COST",
|
||||
"RESEARCH_EXPENSE", "SELL_EXPENSE", "MANAGE_EXPENSE",
|
||||
"FINANCE_EXPENSE",
|
||||
],
|
||||
}
|
||||
stat_key = statement.lower().replace("_", " ")
|
||||
items = key_items.get(stat_key, [])
|
||||
available = [c for c in items if c in df.columns]
|
||||
if not available:
|
||||
# Fallback: show all columns but limit columns to first 15
|
||||
result = df.head(8).iloc[:, :15]
|
||||
else:
|
||||
result = df[available].head(8)
|
||||
return result.to_markdown(index=False)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
# Public API — matches y_finance.py interface
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
|
||||
def get_stock_data(symbol: str, start_date: str, end_date: str) -> str:
|
||||
"""Get stock OHLCV price data. Returns Markdown table string."""
|
||||
try:
|
||||
market = _detect_market(symbol)
|
||||
if market == "cn":
|
||||
df = _get_cn_stock_data(symbol, start_date, end_date)
|
||||
elif market == "us":
|
||||
df = _get_us_stock_data(symbol, start_date, end_date)
|
||||
else:
|
||||
df = _get_hk_stock_data(symbol, start_date, end_date)
|
||||
return _fmt_stock_data(df, symbol)
|
||||
except Exception as e:
|
||||
return f"[akshare] Error fetching stock data for {symbol}: {e}"
|
||||
|
||||
|
||||
def get_indicators(
|
||||
symbol: str,
|
||||
indicator: str,
|
||||
curr_date: str,
|
||||
look_back_days: int = 365,
|
||||
) -> str:
|
||||
"""Get technical indicator values. Returns formatted string with date: value lines.
|
||||
|
||||
Uses stockstats for calculation (same as yfinance adapter).
|
||||
"""
|
||||
from stockstats import wrap
|
||||
|
||||
# Indicator descriptions (same as yfinance)
|
||||
best_ind_params = {
|
||||
"close_5_sma": (
|
||||
"5-day SMA: A short-term simple moving average. "
|
||||
"Usage: Identify short-term trend direction and potential entry/exit signals. "
|
||||
"Tips: Often combined with longer SMAs (e.g., 20-day) for crossover strategies."
|
||||
),
|
||||
"close_10_sma": (
|
||||
"10-day SMA: A short to medium-term simple moving average. "
|
||||
"Usage: Useful for gauging immediate trend strength and potential support/resistance levels."
|
||||
),
|
||||
"close_20_sma": (
|
||||
"20-day SMA: A medium-term simple moving average. "
|
||||
"Usage: Commonly used to identify the intermediate trend and key swing levels."
|
||||
),
|
||||
"close_50_sma": (
|
||||
"50-day SMA: A medium to long-term simple moving average. "
|
||||
"Usage: Watched by many traders to gauge the intermediate trend strength."
|
||||
),
|
||||
"close_200_sma": (
|
||||
"200-day SMA: A long-term simple moving average. "
|
||||
"Usage: Often used to determine the overall bull/bear market trend."
|
||||
),
|
||||
"close_5_ema": (
|
||||
"5-day EMA: A short-term exponential moving average giving more weight to recent prices. "
|
||||
"Usage: Provides early signals for short-term trend changes."
|
||||
),
|
||||
"close_10_ema": (
|
||||
"10-day EMA: A short to medium-term exponential moving average. "
|
||||
"Usage: Reacts faster to price changes than SMA; good for active trading strategies."
|
||||
),
|
||||
"close_20_ema": (
|
||||
"20-day EMA: A medium-term exponential moving average. "
|
||||
"Usage: Commonly watched by swing and short-term traders for trend confirmation."
|
||||
),
|
||||
"close_50_ema": (
|
||||
"50-day EMA: A medium to long-term exponential moving average. "
|
||||
"Usage: Offers a balance between responsiveness and smoothing for trend analysis."
|
||||
),
|
||||
"close_200_ema": (
|
||||
"200-day EMA: A long-term exponential moving average. "
|
||||
"Usage: Often used by longer-term traders to gauge major trend turns."
|
||||
),
|
||||
"rsi": (
|
||||
"RSI (14): The Relative Strength Index measures momentum on a scale of 0 to 100. "
|
||||
"Usage: Identify overbought (>70) or oversold (<30) conditions. "
|
||||
"Tips: Combine with trend indicators; divergences between RSI and price can signal reversals."
|
||||
),
|
||||
"rsi_6": (
|
||||
"RSI (6): A faster-setting RSI. "
|
||||
"Usage: More sensitive and generates earlier signals, ideal for quick momentum shifts."
|
||||
),
|
||||
"rsi_14": (
|
||||
"RSI (14): The standard Relative Strength Index. "
|
||||
"Usage: Same as RSI; widely used for identifying overbought/oversold and reversals."
|
||||
),
|
||||
"macd": (
|
||||
"MACD (Moving Average Convergence Divergence): Trend-following momentum indicator. "
|
||||
"Usage: Shows the relationship between two EMAs. "
|
||||
"Tips: Crossovers of the MACD and signal line, as well as divergence from price, can indicate trades."
|
||||
),
|
||||
"macds": (
|
||||
"MACD Signal: The 9-day EMA of the MACD line. "
|
||||
"Usage: Acts as a trigger for buy/sell signals when the MACD line crosses above or below the signal line."
|
||||
),
|
||||
"macdh": (
|
||||
"MACD Histogram: The difference between MACD and signal line. "
|
||||
"Usage: Illustrates changes in momentum; a rising histogram indicates increasing momentum."
|
||||
),
|
||||
"boll": (
|
||||
"Bollinger Bands Middle: 20-day SMA central line. "
|
||||
"Usage: The baseline for volatility bands. "
|
||||
"Tips: Prices reverting to the middle may suggest fading momentum."
|
||||
),
|
||||
"boll_ub": (
|
||||
"Bollinger Bands Upper: Upper volatility band (2 std dev above middle). "
|
||||
"Usage: May indicate overbought conditions. "
|
||||
"Tips: Used with lower band to identify squeeze and breakout patterns."
|
||||
),
|
||||
"boll_lb": (
|
||||
"Bollinger Bands Lower: Lower volatility band (2 std dev below middle). "
|
||||
"Usage: May indicate oversold conditions. "
|
||||
"Tips: Price touching/extending beyond the band can signal strong trend continuation."
|
||||
),
|
||||
"atr": (
|
||||
"ATR: Average True Range measures market volatility. "
|
||||
"Usage: High ATR indicates increased volatility; useful for setting stop-losses and position sizing."
|
||||
),
|
||||
"vwma": (
|
||||
"VWMA: A moving average weighted by volume. "
|
||||
"Usage: Confirm trends by integrating price action with volume data. "
|
||||
"Tips: Watch for skewed results from volume spikes; use in combination with other volume analyses."
|
||||
),
|
||||
"mfi": (
|
||||
"MFI: The Money Flow Index is a momentum indicator that uses both price and volume to measure buying and selling pressure. "
|
||||
"Usage: Identify overbought (>80) or oversold (<20) conditions and confirm the strength of trends or reversals. "
|
||||
"Tips: Use alongside RSI or MACD to confirm signals; divergence between price and MFI can indicate potential reversals."
|
||||
),
|
||||
}
|
||||
|
||||
if indicator not in best_ind_params:
|
||||
raise ValueError(
|
||||
f"Indicator {indicator} is not supported. Please choose from: {list(best_ind_params.keys())}"
|
||||
)
|
||||
|
||||
end_date = datetime.strptime(curr_date, "%Y-%m-%d")
|
||||
start_date = end_date - relativedelta(days=look_back_days + 200) # buffer for SMA calc
|
||||
|
||||
try:
|
||||
# Fetch OHLCV via akshare
|
||||
market = _detect_market(symbol)
|
||||
if market == "cn":
|
||||
df = _get_cn_stock_data(symbol, start_date.strftime("%Y-%m-%d"), curr_date)
|
||||
elif market == "us":
|
||||
df = _get_us_stock_data(symbol, start_date.strftime("%Y-%m-%d"), curr_date)
|
||||
else:
|
||||
df = _get_hk_stock_data(symbol, start_date.strftime("%Y-%m-%d"), curr_date)
|
||||
|
||||
# Prepare for stockstats (expects capitalized column names)
|
||||
df = df.rename(columns={
|
||||
"date": "Date", "open": "Open", "close": "Close",
|
||||
"high": "High", "low": "Low", "volume": "Volume",
|
||||
})
|
||||
sdf = wrap(df)
|
||||
sdf["Date"] = pd.to_datetime(sdf["Date"]).dt.strftime("%Y-%m-%d")
|
||||
|
||||
# Trigger calculation
|
||||
sdf[indicator]
|
||||
|
||||
# Build dict: date → value
|
||||
result_map = {}
|
||||
for _, row in sdf.iterrows():
|
||||
val = row[indicator]
|
||||
result_map[row["Date"]] = f"{val:.4f}" if not pd.isna(val) and isinstance(val, float) else str(val) if not pd.isna(val) else "N/A"
|
||||
|
||||
except Exception as e:
|
||||
# Fallback: date-by-date calculation (less efficient but more resilient)
|
||||
print(f"[akshare] Bulk indicator calc failed: {e}, falling back to per-date")
|
||||
ind_string = ""
|
||||
curr_date_dt = datetime.strptime(curr_date, "%Y-%m-%d")
|
||||
fallback_dt = curr_date_dt
|
||||
while fallback_dt >= end_date - relativedelta(days=look_back_days):
|
||||
indicator_value = _get_indicator_single(symbol, indicator, fallback_dt.strftime("%Y-%m-%d"))
|
||||
ind_string += f"{fallback_dt.strftime('%Y-%m-%d')}: {indicator_value}\n"
|
||||
fallback_dt -= relativedelta(days=1)
|
||||
|
||||
result_str = (
|
||||
f"## {indicator} values from "
|
||||
f"{end_date - relativedelta(days=look_back_days):%Y-%m-%d} to {curr_date}:\n\n"
|
||||
+ ind_string
|
||||
+ "\n\n"
|
||||
+ best_ind_params.get(indicator, "")
|
||||
)
|
||||
return result_str
|
||||
|
||||
# Build output string
|
||||
ind_string = ""
|
||||
current_dt = end_date
|
||||
before = end_date - relativedelta(days=look_back_days)
|
||||
while current_dt >= before:
|
||||
date_str = current_dt.strftime("%Y-%m-%d")
|
||||
value = result_map.get(date_str, "N/A: Not a trading day (weekend or holiday)")
|
||||
ind_string += f"{date_str}: {value}\n"
|
||||
current_dt -= relativedelta(days=1)
|
||||
|
||||
result_str = (
|
||||
f"## {indicator} values from {before.strftime('%Y-%m-%d')} to {curr_date}:\n\n"
|
||||
+ ind_string
|
||||
+ "\n\n"
|
||||
+ best_ind_params.get(indicator, "")
|
||||
)
|
||||
return result_str
|
||||
|
||||
|
||||
def _get_indicator_single(symbol: str, indicator: str, date_str: str) -> str:
|
||||
"""Fallback: calculate a single indicator value for one date."""
|
||||
from stockstats import wrap
|
||||
try:
|
||||
end_date = datetime.strptime(date_str, "%Y-%m-%d")
|
||||
start_date = end_date - relativedelta(days=400)
|
||||
market = _detect_market(symbol)
|
||||
if market == "cn":
|
||||
df = _get_cn_stock_data(symbol, start_date.strftime("%Y-%m-%d"), date_str)
|
||||
elif market == "us":
|
||||
df = _get_us_stock_data(symbol, start_date.strftime("%Y-%m-%d"), date_str)
|
||||
else:
|
||||
df = _get_hk_stock_data(symbol, start_date.strftime("%Y-%m-%d"), date_str)
|
||||
|
||||
df = df.rename(columns={
|
||||
"date": "Date", "open": "Open", "close": "Close",
|
||||
"high": "High", "low": "Low", "volume": "Volume",
|
||||
})
|
||||
sdf = wrap(df)
|
||||
sdf["Date"] = pd.to_datetime(sdf["Date"]).dt.strftime("%Y-%m-%d")
|
||||
sdf[indicator]
|
||||
matching = sdf[sdf["Date"].str.startswith(date_str)]
|
||||
if not matching.empty:
|
||||
val = matching[indicator].values[0]
|
||||
return f"{val:.4f}" if isinstance(val, float) else str(val)
|
||||
return "N/A: Not a trading day (weekend or holiday)"
|
||||
except Exception as e:
|
||||
return f"N/A (error: {e})"
|
||||
|
||||
|
||||
def get_fundamentals(ticker: str, curr_date: str = None) -> str:
|
||||
"""Get company fundamentals. Returns Markdown string."""
|
||||
try:
|
||||
market = _detect_market(ticker)
|
||||
|
||||
if market == "cn":
|
||||
df = ak.stock_individual_info_em(symbol=ticker.strip())
|
||||
lines = [f"# Fundamentals for {ticker}\n"]
|
||||
for _, row in df.head(30).iterrows():
|
||||
lines.append(f"- **{row['item']}**: {row['value']}")
|
||||
return "\n".join(lines)
|
||||
|
||||
elif market == "us":
|
||||
t = ticker.strip().upper().replace("-", ".")
|
||||
df = ak.stock_individual_basic_info_us_xq(symbol=t)
|
||||
lines = [f"# Fundamentals for {ticker}\n"]
|
||||
for _, row in df.head(25).iterrows():
|
||||
lines.append(f"- **{row['item']}**: {row['value']}")
|
||||
return "\n".join(lines)
|
||||
|
||||
else: # HK
|
||||
try:
|
||||
df = ak.stock_hk_company_profile_em(symbol=ticker.strip())
|
||||
return df.to_markdown(index=False)
|
||||
except Exception:
|
||||
return f"Fundamentals not available for HK stock {ticker} via akshare."
|
||||
|
||||
except Exception as e:
|
||||
return f"[akshare] Error fetching fundamentals for {ticker}: {e}"
|
||||
|
||||
|
||||
def get_balance_sheet(ticker: str, freq: str = "annual", curr_date: str = None) -> str:
|
||||
"""Get balance sheet. freq: 'annual' or 'quarterly'. Returns Markdown string."""
|
||||
try:
|
||||
market = _detect_market(ticker)
|
||||
|
||||
if market == "cn":
|
||||
prefix = _get_exchange_prefix(ticker)
|
||||
df = ak.stock_balance_sheet_by_report_em(symbol=f"{prefix}{ticker.strip()}")
|
||||
if freq in ("annual", "yearly"):
|
||||
df = df[df["REPORT_TYPE"] == "年报"]
|
||||
else:
|
||||
df = df[df["REPORT_TYPE"].isin(["一季报", "中报", "三季报"])]
|
||||
if curr_date and not df.empty:
|
||||
df = df[pd.to_datetime(df["REPORT_DATE"]) <= pd.Timestamp(curr_date)]
|
||||
return _fmt_financial(df, "balance sheet", ticker, freq)
|
||||
|
||||
elif market == "us":
|
||||
indicator = "年报" if freq in ("annual", "yearly") else "单季报"
|
||||
t = ticker.strip().upper().replace("-", ".")
|
||||
df = ak.stock_financial_us_report_em(
|
||||
stock=t, symbol="资产负债表", indicator=indicator,
|
||||
)
|
||||
if curr_date and not df.empty:
|
||||
df = df[pd.to_datetime(df["REPORT_DATE"]) <= pd.Timestamp(curr_date)]
|
||||
return _fmt_financial(df, "balance sheet", ticker, freq)
|
||||
|
||||
else:
|
||||
return f"Balance sheet not supported for HK stock {ticker} via akshare."
|
||||
|
||||
except Exception as e:
|
||||
return f"[akshare] Error fetching balance sheet for {ticker}: {e}"
|
||||
|
||||
|
||||
def get_cashflow(ticker: str, freq: str = "annual", curr_date: str = None) -> str:
|
||||
"""Get cash flow statement. freq: 'annual' or 'quarterly'. Returns Markdown string."""
|
||||
try:
|
||||
market = _detect_market(ticker)
|
||||
|
||||
if market == "cn":
|
||||
prefix = _get_exchange_prefix(ticker)
|
||||
df = ak.stock_cash_flow_sheet_by_report_em(symbol=f"{prefix}{ticker.strip()}")
|
||||
if freq in ("annual", "yearly"):
|
||||
df = df[df["REPORT_TYPE"] == "年报"]
|
||||
else:
|
||||
df = df[df["REPORT_TYPE"].isin(["一季报", "中报", "三季报"])]
|
||||
if curr_date and not df.empty:
|
||||
df = df[pd.to_datetime(df["REPORT_DATE"]) <= pd.Timestamp(curr_date)]
|
||||
return _fmt_financial(df, "cash flow", ticker, freq)
|
||||
|
||||
elif market == "us":
|
||||
indicator = "年报" if freq in ("annual", "yearly") else "单季报"
|
||||
t = ticker.strip().upper().replace("-", ".")
|
||||
df = ak.stock_financial_us_report_em(
|
||||
stock=t, symbol="现金流量表", indicator=indicator,
|
||||
)
|
||||
if curr_date and not df.empty:
|
||||
df = df[pd.to_datetime(df["REPORT_DATE"]) <= pd.Timestamp(curr_date)]
|
||||
return _fmt_financial(df, "cash flow", ticker, freq)
|
||||
|
||||
else:
|
||||
return f"Cash flow statement not supported for HK stock {ticker} via akshare."
|
||||
|
||||
except Exception as e:
|
||||
return f"[akshare] Error fetching cash flow for {ticker}: {e}"
|
||||
|
||||
|
||||
def get_income_statement(ticker: str, freq: str = "annual", curr_date: str = None) -> str:
|
||||
"""Get income statement. freq: 'annual' or 'quarterly'. Returns Markdown string."""
|
||||
try:
|
||||
market = _detect_market(ticker)
|
||||
|
||||
if market == "cn":
|
||||
prefix = _get_exchange_prefix(ticker)
|
||||
df = ak.stock_profit_sheet_by_report_em(symbol=f"{prefix}{ticker.strip()}")
|
||||
if freq in ("annual", "yearly"):
|
||||
df = df[df["REPORT_TYPE"] == "年报"]
|
||||
else:
|
||||
df = df[df["REPORT_TYPE"].isin(["一季报", "中报", "三季报"])]
|
||||
if curr_date and not df.empty:
|
||||
df = df[pd.to_datetime(df["REPORT_DATE"]) <= pd.Timestamp(curr_date)]
|
||||
return _fmt_financial(df, "income statement", ticker, freq)
|
||||
|
||||
elif market == "us":
|
||||
indicator = "年报" if freq in ("annual", "yearly") else "单季报"
|
||||
t = ticker.strip().upper().replace("-", ".")
|
||||
df = ak.stock_financial_us_report_em(
|
||||
stock=t, symbol="综合损益表", indicator=indicator,
|
||||
)
|
||||
if curr_date and not df.empty:
|
||||
df = df[pd.to_datetime(df["REPORT_DATE"]) <= pd.Timestamp(curr_date)]
|
||||
return _fmt_financial(df, "income statement", ticker, freq)
|
||||
|
||||
else:
|
||||
return f"Income statement not supported for HK stock {ticker} via akshare."
|
||||
|
||||
except Exception as e:
|
||||
return f"[akshare] Error fetching income statement for {ticker}: {e}"
|
||||
|
||||
|
||||
def get_insider_transactions(ticker: str) -> str:
|
||||
"""Insider transactions not supported by akshare.
|
||||
Raise AlphaVantageRateLimitError to trigger fallback to yfinance."""
|
||||
from .alpha_vantage_common import AlphaVantageRateLimitError
|
||||
raise AlphaVantageRateLimitError(
|
||||
f"akshare does not support insider transactions for {ticker}. "
|
||||
"Falling back to next vendor."
|
||||
)
|
||||
@@ -0,0 +1,165 @@
|
||||
"""
|
||||
akshare news adapter for TradingAgents.
|
||||
Replaces yfinance_news for company and global news sourcing.
|
||||
|
||||
Uses:
|
||||
- stock_news_em → individual stock news (East Money)
|
||||
- news_cctv → CCTV daily news (macro/global)
|
||||
- news_economic_baidu → economic calendar/events
|
||||
"""
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Optional
|
||||
import os
|
||||
import pandas as pd
|
||||
from dateutil.relativedelta import relativedelta
|
||||
|
||||
# Suppress akshare's internal tqdm progress bars
|
||||
os.environ.setdefault('TQDM_DISABLE', '1')
|
||||
|
||||
import akshare as ak
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
# Symbol detection
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
|
||||
def _normalize_ticker(ticker: str) -> str:
|
||||
"""Normalize ticker for akshare news API.
|
||||
|
||||
stock_news_em accepts: A-share 6-digit codes, or US tickers as-is.
|
||||
"""
|
||||
sym = ticker.strip().upper()
|
||||
if sym.isdigit() and len(sym) == 6:
|
||||
return sym
|
||||
return sym
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
# Company news
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
|
||||
def get_news(
|
||||
ticker: str,
|
||||
start_date: str,
|
||||
end_date: str,
|
||||
) -> str:
|
||||
"""Get company-specific news from East Money.
|
||||
|
||||
Args:
|
||||
ticker: Stock symbol (A-share code or US ticker).
|
||||
start_date: YYYY-MM-DD format.
|
||||
end_date: YYYY-MM-DD format.
|
||||
|
||||
Returns:
|
||||
Markdown string containing news items.
|
||||
"""
|
||||
try:
|
||||
sym = _normalize_ticker(ticker)
|
||||
df = ak.stock_news_em(symbol=sym)
|
||||
|
||||
# Filter by date range
|
||||
df["发布时间"] = pd.to_datetime(df["发布时间"])
|
||||
mask = (df["发布时间"] >= pd.Timestamp(start_date)) & (
|
||||
df["发布时间"] <= pd.Timestamp(end_date) + pd.Timedelta(days=1)
|
||||
)
|
||||
df = df[mask]
|
||||
|
||||
if df.empty:
|
||||
return f"No news found for {ticker} between {start_date} and {end_date}."
|
||||
|
||||
# Select and format key columns
|
||||
cols = [c for c in ["发布时间", "新闻标题", "新闻内容", "文章来源"] if c in df.columns]
|
||||
result = df[cols].head(30) # Limit to 30 most recent
|
||||
result["发布时间"] = result["发布时间"].astype(str)
|
||||
return result.to_markdown(index=False)
|
||||
|
||||
except Exception as e:
|
||||
return f"[akshare] Error fetching news for {ticker}: {e}"
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
# Global / macro news
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
|
||||
def get_global_news(
|
||||
curr_date: str,
|
||||
look_back_days: int = 7,
|
||||
limit: int = 20,
|
||||
) -> str:
|
||||
"""Get global macroeconomic news from multiple Chinese news sources.
|
||||
|
||||
Aggregates:
|
||||
- CCTV daily news (political/economic headlines)
|
||||
- Baidu economic calendar (economic events/data releases)
|
||||
|
||||
Args:
|
||||
curr_date: Current reference date (YYYY-MM-DD).
|
||||
look_back_days: Days to look back.
|
||||
limit: Maximum total news items to return.
|
||||
|
||||
Returns:
|
||||
Markdown string with global news and economic events.
|
||||
"""
|
||||
curr_dt = datetime.strptime(curr_date, "%Y-%m-%d")
|
||||
sections = []
|
||||
|
||||
# — CCTV news —
|
||||
try:
|
||||
cctv_parts = []
|
||||
for i in range(look_back_days + 1):
|
||||
day = curr_dt - relativedelta(days=i)
|
||||
day_str = day.strftime("%Y%m%d")
|
||||
try:
|
||||
df_day = ak.news_cctv(date=day_str)
|
||||
if df_day is not None and not df_day.empty:
|
||||
for _, row in df_day.head(10).iterrows():
|
||||
if len(cctv_parts) >= limit:
|
||||
break
|
||||
title = str(row.get("title", "")) if "title" in df_day.columns else ""
|
||||
content = str(row.get("content", "")) if "content" in df_day.columns else ""
|
||||
brief = content[:120] if content else ""
|
||||
cctv_parts.append(f"- [{day_str}] **{title}** — {brief}")
|
||||
if len(cctv_parts) >= limit:
|
||||
break
|
||||
except Exception:
|
||||
continue # skip days with no data
|
||||
|
||||
if cctv_parts:
|
||||
sections.append("## CCTV News (央视新闻)\n\n" + "\n".join(cctv_parts[:limit]))
|
||||
except Exception as e:
|
||||
sections.append(f"## CCTV News\n\n*Error fetching CCTV news: {e}*")
|
||||
|
||||
# — Economic calendar —
|
||||
try:
|
||||
econ_parts = []
|
||||
for i in range(look_back_days + 1):
|
||||
day = curr_dt - relativedelta(days=i)
|
||||
day_str = day.strftime("%Y%m%d")
|
||||
try:
|
||||
df_econ = ak.news_economic_baidu(date=day_str)
|
||||
if df_econ is not None and not df_econ.empty:
|
||||
for _, row in df_econ.head(10).iterrows():
|
||||
if len(econ_parts) >= limit:
|
||||
break
|
||||
time_val = str(row.get("time", ""))
|
||||
country = str(row.get("country", "")) if "country" in df_econ.columns else ""
|
||||
event = str(row.get("event", "")) if "event" in df_econ.columns else ""
|
||||
importance = str(row.get("importance", "")) if "importance" in df_econ.columns else ""
|
||||
line = f"- **{country}** {importance} — {event} ({time_val})"
|
||||
econ_parts.append(line)
|
||||
if len(econ_parts) >= limit:
|
||||
break
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
if econ_parts:
|
||||
sections.append("## Economic Calendar (经济日历)\n\n" + "\n".join(econ_parts[:limit]))
|
||||
except Exception as e:
|
||||
sections.append(f"## Economic Calendar\n\n*Error fetching economic calendar: {e}*")
|
||||
|
||||
if not sections:
|
||||
return f"No global news found for the period ending {curr_date}."
|
||||
|
||||
header = f"**Global news and economic events from {curr_dt - relativedelta(days=look_back_days):%Y-%m-%d} to {curr_date}**\n\n"
|
||||
return header + "\n\n".join(sections)
|
||||
@@ -0,0 +1,5 @@
|
||||
# Import functions from specialized modules
|
||||
from .alpha_vantage_stock import get_stock
|
||||
from .alpha_vantage_indicator import get_indicator
|
||||
from .alpha_vantage_fundamentals import get_fundamentals, get_balance_sheet, get_cashflow, get_income_statement
|
||||
from .alpha_vantage_news import get_news, get_global_news, get_insider_transactions
|
||||
@@ -0,0 +1,122 @@
|
||||
import os
|
||||
import requests
|
||||
import pandas as pd
|
||||
import json
|
||||
from datetime import datetime
|
||||
from io import StringIO
|
||||
|
||||
API_BASE_URL = "https://www.alphavantage.co/query"
|
||||
|
||||
def get_api_key() -> str:
|
||||
"""Retrieve the API key for Alpha Vantage from environment variables."""
|
||||
api_key = os.getenv("ALPHA_VANTAGE_API_KEY")
|
||||
if not api_key:
|
||||
raise ValueError("ALPHA_VANTAGE_API_KEY environment variable is not set.")
|
||||
return api_key
|
||||
|
||||
def format_datetime_for_api(date_input) -> str:
|
||||
"""Convert various date formats to YYYYMMDDTHHMM format required by Alpha Vantage API."""
|
||||
if isinstance(date_input, str):
|
||||
# If already in correct format, return as-is
|
||||
if len(date_input) == 13 and 'T' in date_input:
|
||||
return date_input
|
||||
# Try to parse common date formats
|
||||
try:
|
||||
dt = datetime.strptime(date_input, "%Y-%m-%d")
|
||||
return dt.strftime("%Y%m%dT0000")
|
||||
except ValueError:
|
||||
try:
|
||||
dt = datetime.strptime(date_input, "%Y-%m-%d %H:%M")
|
||||
return dt.strftime("%Y%m%dT%H%M")
|
||||
except ValueError:
|
||||
raise ValueError(f"Unsupported date format: {date_input}")
|
||||
elif isinstance(date_input, datetime):
|
||||
return date_input.strftime("%Y%m%dT%H%M")
|
||||
else:
|
||||
raise ValueError(f"Date must be string or datetime object, got {type(date_input)}")
|
||||
|
||||
class AlphaVantageRateLimitError(Exception):
|
||||
"""Exception raised when Alpha Vantage API rate limit is exceeded."""
|
||||
pass
|
||||
|
||||
def _make_api_request(function_name: str, params: dict) -> dict | str:
|
||||
"""Helper function to make API requests and handle responses.
|
||||
|
||||
Raises:
|
||||
AlphaVantageRateLimitError: When API rate limit is exceeded
|
||||
"""
|
||||
# Create a copy of params to avoid modifying the original
|
||||
api_params = params.copy()
|
||||
api_params.update({
|
||||
"function": function_name,
|
||||
"apikey": get_api_key(),
|
||||
"source": "trading_agents",
|
||||
})
|
||||
|
||||
# Handle entitlement parameter if present in params or global variable
|
||||
current_entitlement = globals().get('_current_entitlement')
|
||||
entitlement = api_params.get("entitlement") or current_entitlement
|
||||
|
||||
if entitlement:
|
||||
api_params["entitlement"] = entitlement
|
||||
elif "entitlement" in api_params:
|
||||
# Remove entitlement if it's None or empty
|
||||
api_params.pop("entitlement", None)
|
||||
|
||||
response = requests.get(API_BASE_URL, params=api_params)
|
||||
response.raise_for_status()
|
||||
|
||||
response_text = response.text
|
||||
|
||||
# Check if response is JSON (error responses are typically JSON)
|
||||
try:
|
||||
response_json = json.loads(response_text)
|
||||
# Check for rate limit error
|
||||
if "Information" in response_json:
|
||||
info_message = response_json["Information"]
|
||||
if "rate limit" in info_message.lower() or "api key" in info_message.lower():
|
||||
raise AlphaVantageRateLimitError(f"Alpha Vantage rate limit exceeded: {info_message}")
|
||||
except json.JSONDecodeError:
|
||||
# Response is not JSON (likely CSV data), which is normal
|
||||
pass
|
||||
|
||||
return response_text
|
||||
|
||||
|
||||
|
||||
def _filter_csv_by_date_range(csv_data: str, start_date: str, end_date: str) -> str:
|
||||
"""
|
||||
Filter CSV data to include only rows within the specified date range.
|
||||
|
||||
Args:
|
||||
csv_data: CSV string from Alpha Vantage API
|
||||
start_date: Start date in yyyy-mm-dd format
|
||||
end_date: End date in yyyy-mm-dd format
|
||||
|
||||
Returns:
|
||||
Filtered CSV string
|
||||
"""
|
||||
if not csv_data or csv_data.strip() == "":
|
||||
return csv_data
|
||||
|
||||
try:
|
||||
# Parse CSV data
|
||||
df = pd.read_csv(StringIO(csv_data))
|
||||
|
||||
# Assume the first column is the date column (timestamp)
|
||||
date_col = df.columns[0]
|
||||
df[date_col] = pd.to_datetime(df[date_col])
|
||||
|
||||
# Filter by date range
|
||||
start_dt = pd.to_datetime(start_date)
|
||||
end_dt = pd.to_datetime(end_date)
|
||||
|
||||
filtered_df = df[(df[date_col] >= start_dt) & (df[date_col] <= end_dt)]
|
||||
|
||||
# Convert back to CSV string
|
||||
return filtered_df.to_csv(index=False)
|
||||
|
||||
except Exception as e:
|
||||
# If filtering fails, return original data with a warning
|
||||
print(f"Warning: Failed to filter CSV data by date range: {e}")
|
||||
return csv_data
|
||||
@@ -0,0 +1,55 @@
|
||||
from .alpha_vantage_common import _make_api_request
|
||||
|
||||
|
||||
def _filter_reports_by_date(result, curr_date: str):
|
||||
"""Filter annualReports/quarterlyReports to exclude entries after curr_date.
|
||||
|
||||
Prevents look-ahead bias by removing fiscal periods that end after
|
||||
the simulation's current date.
|
||||
"""
|
||||
if not curr_date or not isinstance(result, dict):
|
||||
return result
|
||||
for key in ("annualReports", "quarterlyReports"):
|
||||
if key in result:
|
||||
result[key] = [
|
||||
r for r in result[key]
|
||||
if r.get("fiscalDateEnding", "") <= curr_date
|
||||
]
|
||||
return result
|
||||
|
||||
|
||||
def get_fundamentals(ticker: str, curr_date: str = None) -> str:
|
||||
"""
|
||||
Retrieve comprehensive fundamental data for a given ticker symbol using Alpha Vantage.
|
||||
|
||||
Args:
|
||||
ticker (str): Ticker symbol of the company
|
||||
curr_date (str): Current date you are trading at, yyyy-mm-dd (not used for Alpha Vantage)
|
||||
|
||||
Returns:
|
||||
str: Company overview data including financial ratios and key metrics
|
||||
"""
|
||||
params = {
|
||||
"symbol": ticker,
|
||||
}
|
||||
|
||||
return _make_api_request("OVERVIEW", params)
|
||||
|
||||
|
||||
def get_balance_sheet(ticker: str, freq: str = "quarterly", curr_date: str = None):
|
||||
"""Retrieve balance sheet data for a given ticker symbol using Alpha Vantage."""
|
||||
result = _make_api_request("BALANCE_SHEET", {"symbol": ticker})
|
||||
return _filter_reports_by_date(result, curr_date)
|
||||
|
||||
|
||||
def get_cashflow(ticker: str, freq: str = "quarterly", curr_date: str = None):
|
||||
"""Retrieve cash flow statement data for a given ticker symbol using Alpha Vantage."""
|
||||
result = _make_api_request("CASH_FLOW", {"symbol": ticker})
|
||||
return _filter_reports_by_date(result, curr_date)
|
||||
|
||||
|
||||
def get_income_statement(ticker: str, freq: str = "quarterly", curr_date: str = None):
|
||||
"""Retrieve income statement data for a given ticker symbol using Alpha Vantage."""
|
||||
result = _make_api_request("INCOME_STATEMENT", {"symbol": ticker})
|
||||
return _filter_reports_by_date(result, curr_date)
|
||||
|
||||
@@ -0,0 +1,222 @@
|
||||
from .alpha_vantage_common import _make_api_request
|
||||
|
||||
def get_indicator(
|
||||
symbol: str,
|
||||
indicator: str,
|
||||
curr_date: str,
|
||||
look_back_days: int,
|
||||
interval: str = "daily",
|
||||
time_period: int = 14,
|
||||
series_type: str = "close"
|
||||
) -> str:
|
||||
"""
|
||||
Returns Alpha Vantage technical indicator values over a time window.
|
||||
|
||||
Args:
|
||||
symbol: ticker symbol of the company
|
||||
indicator: technical indicator to get the analysis and report of
|
||||
curr_date: The current trading date you are trading on, YYYY-mm-dd
|
||||
look_back_days: how many days to look back
|
||||
interval: Time interval (daily, weekly, monthly)
|
||||
time_period: Number of data points for calculation
|
||||
series_type: The desired price type (close, open, high, low)
|
||||
|
||||
Returns:
|
||||
String containing indicator values and description
|
||||
"""
|
||||
from datetime import datetime
|
||||
from dateutil.relativedelta import relativedelta
|
||||
|
||||
supported_indicators = {
|
||||
"close_50_sma": ("50 SMA", "close"),
|
||||
"close_200_sma": ("200 SMA", "close"),
|
||||
"close_10_ema": ("10 EMA", "close"),
|
||||
"macd": ("MACD", "close"),
|
||||
"macds": ("MACD Signal", "close"),
|
||||
"macdh": ("MACD Histogram", "close"),
|
||||
"rsi": ("RSI", "close"),
|
||||
"boll": ("Bollinger Middle", "close"),
|
||||
"boll_ub": ("Bollinger Upper Band", "close"),
|
||||
"boll_lb": ("Bollinger Lower Band", "close"),
|
||||
"atr": ("ATR", None),
|
||||
"vwma": ("VWMA", "close")
|
||||
}
|
||||
|
||||
indicator_descriptions = {
|
||||
"close_50_sma": "50 SMA: A medium-term trend indicator. Usage: Identify trend direction and serve as dynamic support/resistance. Tips: It lags price; combine with faster indicators for timely signals.",
|
||||
"close_200_sma": "200 SMA: A long-term trend benchmark. Usage: Confirm overall market trend and identify golden/death cross setups. Tips: It reacts slowly; best for strategic trend confirmation rather than frequent trading entries.",
|
||||
"close_10_ema": "10 EMA: A responsive short-term average. Usage: Capture quick shifts in momentum and potential entry points. Tips: Prone to noise in choppy markets; use alongside longer averages for filtering false signals.",
|
||||
"macd": "MACD: Computes momentum via differences of EMAs. Usage: Look for crossovers and divergence as signals of trend changes. Tips: Confirm with other indicators in low-volatility or sideways markets.",
|
||||
"macds": "MACD Signal: An EMA smoothing of the MACD line. Usage: Use crossovers with the MACD line to trigger trades. Tips: Should be part of a broader strategy to avoid false positives.",
|
||||
"macdh": "MACD Histogram: Shows the gap between the MACD line and its signal. Usage: Visualize momentum strength and spot divergence early. Tips: Can be volatile; complement with additional filters in fast-moving markets.",
|
||||
"rsi": "RSI: Measures momentum to flag overbought/oversold conditions. Usage: Apply 70/30 thresholds and watch for divergence to signal reversals. Tips: In strong trends, RSI may remain extreme; always cross-check with trend analysis.",
|
||||
"boll": "Bollinger Middle: A 20 SMA serving as the basis for Bollinger Bands. Usage: Acts as a dynamic benchmark for price movement. Tips: Combine with the upper and lower bands to effectively spot breakouts or reversals.",
|
||||
"boll_ub": "Bollinger Upper Band: Typically 2 standard deviations above the middle line. Usage: Signals potential overbought conditions and breakout zones. Tips: Confirm signals with other tools; prices may ride the band in strong trends.",
|
||||
"boll_lb": "Bollinger Lower Band: Typically 2 standard deviations below the middle line. Usage: Indicates potential oversold conditions. Tips: Use additional analysis to avoid false reversal signals.",
|
||||
"atr": "ATR: Averages true range to measure volatility. Usage: Set stop-loss levels and adjust position sizes based on current market volatility. Tips: It's a reactive measure, so use it as part of a broader risk management strategy.",
|
||||
"vwma": "VWMA: A moving average weighted by volume. Usage: Confirm trends by integrating price action with volume data. Tips: Watch for skewed results from volume spikes; use in combination with other volume analyses."
|
||||
}
|
||||
|
||||
if indicator not in supported_indicators:
|
||||
raise ValueError(
|
||||
f"Indicator {indicator} is not supported. Please choose from: {list(supported_indicators.keys())}"
|
||||
)
|
||||
|
||||
curr_date_dt = datetime.strptime(curr_date, "%Y-%m-%d")
|
||||
before = curr_date_dt - relativedelta(days=look_back_days)
|
||||
|
||||
# Get the full data for the period instead of making individual calls
|
||||
_, required_series_type = supported_indicators[indicator]
|
||||
|
||||
# Use the provided series_type or fall back to the required one
|
||||
if required_series_type:
|
||||
series_type = required_series_type
|
||||
|
||||
try:
|
||||
# Get indicator data for the period
|
||||
if indicator == "close_50_sma":
|
||||
data = _make_api_request("SMA", {
|
||||
"symbol": symbol,
|
||||
"interval": interval,
|
||||
"time_period": "50",
|
||||
"series_type": series_type,
|
||||
"datatype": "csv"
|
||||
})
|
||||
elif indicator == "close_200_sma":
|
||||
data = _make_api_request("SMA", {
|
||||
"symbol": symbol,
|
||||
"interval": interval,
|
||||
"time_period": "200",
|
||||
"series_type": series_type,
|
||||
"datatype": "csv"
|
||||
})
|
||||
elif indicator == "close_10_ema":
|
||||
data = _make_api_request("EMA", {
|
||||
"symbol": symbol,
|
||||
"interval": interval,
|
||||
"time_period": "10",
|
||||
"series_type": series_type,
|
||||
"datatype": "csv"
|
||||
})
|
||||
elif indicator == "macd":
|
||||
data = _make_api_request("MACD", {
|
||||
"symbol": symbol,
|
||||
"interval": interval,
|
||||
"series_type": series_type,
|
||||
"datatype": "csv"
|
||||
})
|
||||
elif indicator == "macds":
|
||||
data = _make_api_request("MACD", {
|
||||
"symbol": symbol,
|
||||
"interval": interval,
|
||||
"series_type": series_type,
|
||||
"datatype": "csv"
|
||||
})
|
||||
elif indicator == "macdh":
|
||||
data = _make_api_request("MACD", {
|
||||
"symbol": symbol,
|
||||
"interval": interval,
|
||||
"series_type": series_type,
|
||||
"datatype": "csv"
|
||||
})
|
||||
elif indicator == "rsi":
|
||||
data = _make_api_request("RSI", {
|
||||
"symbol": symbol,
|
||||
"interval": interval,
|
||||
"time_period": str(time_period),
|
||||
"series_type": series_type,
|
||||
"datatype": "csv"
|
||||
})
|
||||
elif indicator in ["boll", "boll_ub", "boll_lb"]:
|
||||
data = _make_api_request("BBANDS", {
|
||||
"symbol": symbol,
|
||||
"interval": interval,
|
||||
"time_period": "20",
|
||||
"series_type": series_type,
|
||||
"datatype": "csv"
|
||||
})
|
||||
elif indicator == "atr":
|
||||
data = _make_api_request("ATR", {
|
||||
"symbol": symbol,
|
||||
"interval": interval,
|
||||
"time_period": str(time_period),
|
||||
"datatype": "csv"
|
||||
})
|
||||
elif indicator == "vwma":
|
||||
# Alpha Vantage doesn't have direct VWMA, so we'll return an informative message
|
||||
# In a real implementation, this would need to be calculated from OHLCV data
|
||||
return f"## VWMA (Volume Weighted Moving Average) for {symbol}:\n\nVWMA calculation requires OHLCV data and is not directly available from Alpha Vantage API.\nThis indicator would need to be calculated from the raw stock data using volume-weighted price averaging.\n\n{indicator_descriptions.get('vwma', 'No description available.')}"
|
||||
else:
|
||||
return f"Error: Indicator {indicator} not implemented yet."
|
||||
|
||||
# Parse CSV data and extract values for the date range
|
||||
lines = data.strip().split('\n')
|
||||
if len(lines) < 2:
|
||||
return f"Error: No data returned for {indicator}"
|
||||
|
||||
# Parse header and data
|
||||
header = [col.strip() for col in lines[0].split(',')]
|
||||
try:
|
||||
date_col_idx = header.index('time')
|
||||
except ValueError:
|
||||
return f"Error: 'time' column not found in data for {indicator}. Available columns: {header}"
|
||||
|
||||
# Map internal indicator names to expected CSV column names from Alpha Vantage
|
||||
col_name_map = {
|
||||
"macd": "MACD", "macds": "MACD_Signal", "macdh": "MACD_Hist",
|
||||
"boll": "Real Middle Band", "boll_ub": "Real Upper Band", "boll_lb": "Real Lower Band",
|
||||
"rsi": "RSI", "atr": "ATR", "close_10_ema": "EMA",
|
||||
"close_50_sma": "SMA", "close_200_sma": "SMA"
|
||||
}
|
||||
|
||||
target_col_name = col_name_map.get(indicator)
|
||||
|
||||
if not target_col_name:
|
||||
# Default to the second column if no specific mapping exists
|
||||
value_col_idx = 1
|
||||
else:
|
||||
try:
|
||||
value_col_idx = header.index(target_col_name)
|
||||
except ValueError:
|
||||
return f"Error: Column '{target_col_name}' not found for indicator '{indicator}'. Available columns: {header}"
|
||||
|
||||
result_data = []
|
||||
for line in lines[1:]:
|
||||
if not line.strip():
|
||||
continue
|
||||
values = line.split(',')
|
||||
if len(values) > value_col_idx:
|
||||
try:
|
||||
date_str = values[date_col_idx].strip()
|
||||
# Parse the date
|
||||
date_dt = datetime.strptime(date_str, "%Y-%m-%d")
|
||||
|
||||
# Check if date is in our range
|
||||
if before <= date_dt <= curr_date_dt:
|
||||
value = values[value_col_idx].strip()
|
||||
result_data.append((date_dt, value))
|
||||
except (ValueError, IndexError):
|
||||
continue
|
||||
|
||||
# Sort by date and format output
|
||||
result_data.sort(key=lambda x: x[0])
|
||||
|
||||
ind_string = ""
|
||||
for date_dt, value in result_data:
|
||||
ind_string += f"{date_dt.strftime('%Y-%m-%d')}: {value}\n"
|
||||
|
||||
if not ind_string:
|
||||
ind_string = "No data available for the specified date range.\n"
|
||||
|
||||
result_str = (
|
||||
f"## {indicator.upper()} values from {before.strftime('%Y-%m-%d')} to {curr_date}:\n\n"
|
||||
+ ind_string
|
||||
+ "\n\n"
|
||||
+ indicator_descriptions.get(indicator, "No description available.")
|
||||
)
|
||||
|
||||
return result_str
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error getting Alpha Vantage indicator data for {indicator}: {e}")
|
||||
return f"Error retrieving {indicator} data: {str(e)}"
|
||||
@@ -0,0 +1,71 @@
|
||||
from .alpha_vantage_common import _make_api_request, format_datetime_for_api
|
||||
|
||||
def get_news(ticker, start_date, end_date) -> dict[str, str] | str:
|
||||
"""Returns live and historical market news & sentiment data from premier news outlets worldwide.
|
||||
|
||||
Covers stocks, cryptocurrencies, forex, and topics like fiscal policy, mergers & acquisitions, IPOs.
|
||||
|
||||
Args:
|
||||
ticker: Stock symbol for news articles.
|
||||
start_date: Start date for news search.
|
||||
end_date: End date for news search.
|
||||
|
||||
Returns:
|
||||
Dictionary containing news sentiment data or JSON string.
|
||||
"""
|
||||
|
||||
params = {
|
||||
"tickers": ticker,
|
||||
"time_from": format_datetime_for_api(start_date),
|
||||
"time_to": format_datetime_for_api(end_date),
|
||||
}
|
||||
|
||||
return _make_api_request("NEWS_SENTIMENT", params)
|
||||
|
||||
def get_global_news(curr_date, look_back_days: int = 7, limit: int = 50) -> dict[str, str] | str:
|
||||
"""Returns global market news & sentiment data without ticker-specific filtering.
|
||||
|
||||
Covers broad market topics like financial markets, economy, and more.
|
||||
|
||||
Args:
|
||||
curr_date: Current date in yyyy-mm-dd format.
|
||||
look_back_days: Number of days to look back (default 7).
|
||||
limit: Maximum number of articles (default 50).
|
||||
|
||||
Returns:
|
||||
Dictionary containing global news sentiment data or JSON string.
|
||||
"""
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
# Calculate start date
|
||||
curr_dt = datetime.strptime(curr_date, "%Y-%m-%d")
|
||||
start_dt = curr_dt - timedelta(days=look_back_days)
|
||||
start_date = start_dt.strftime("%Y-%m-%d")
|
||||
|
||||
params = {
|
||||
"topics": "financial_markets,economy_macro,economy_monetary",
|
||||
"time_from": format_datetime_for_api(start_date),
|
||||
"time_to": format_datetime_for_api(curr_date),
|
||||
"limit": str(limit),
|
||||
}
|
||||
|
||||
return _make_api_request("NEWS_SENTIMENT", params)
|
||||
|
||||
|
||||
def get_insider_transactions(symbol: str) -> dict[str, str] | str:
|
||||
"""Returns latest and historical insider transactions by key stakeholders.
|
||||
|
||||
Covers transactions by founders, executives, board members, etc.
|
||||
|
||||
Args:
|
||||
symbol: Ticker symbol. Example: "IBM".
|
||||
|
||||
Returns:
|
||||
Dictionary containing insider transaction data or JSON string.
|
||||
"""
|
||||
|
||||
params = {
|
||||
"symbol": symbol,
|
||||
}
|
||||
|
||||
return _make_api_request("INSIDER_TRANSACTIONS", params)
|
||||
@@ -0,0 +1,38 @@
|
||||
from datetime import datetime
|
||||
from .alpha_vantage_common import _make_api_request, _filter_csv_by_date_range
|
||||
|
||||
def get_stock(
|
||||
symbol: str,
|
||||
start_date: str,
|
||||
end_date: str
|
||||
) -> str:
|
||||
"""
|
||||
Returns raw daily OHLCV values, adjusted close values, and historical split/dividend events
|
||||
filtered to the specified date range.
|
||||
|
||||
Args:
|
||||
symbol: The name of the equity. For example: symbol=IBM
|
||||
start_date: Start date in yyyy-mm-dd format
|
||||
end_date: End date in yyyy-mm-dd format
|
||||
|
||||
Returns:
|
||||
CSV string containing the daily adjusted time series data filtered to the date range.
|
||||
"""
|
||||
# Parse dates to determine the range
|
||||
start_dt = datetime.strptime(start_date, "%Y-%m-%d")
|
||||
today = datetime.now()
|
||||
|
||||
# Choose outputsize based on whether the requested range is within the latest 100 days
|
||||
# Compact returns latest 100 data points, so check if start_date is recent enough
|
||||
days_from_today_to_start = (today - start_dt).days
|
||||
outputsize = "compact" if days_from_today_to_start < 100 else "full"
|
||||
|
||||
params = {
|
||||
"symbol": symbol,
|
||||
"outputsize": outputsize,
|
||||
"datatype": "csv",
|
||||
}
|
||||
|
||||
response = _make_api_request("TIME_SERIES_DAILY_ADJUSTED", params)
|
||||
|
||||
return _filter_csv_by_date_range(response, start_date, end_date)
|
||||
@@ -0,0 +1,31 @@
|
||||
import tradingagents.default_config as default_config
|
||||
from typing import Dict, Optional
|
||||
|
||||
# Use default config but allow it to be overridden
|
||||
_config: Optional[Dict] = None
|
||||
|
||||
|
||||
def initialize_config():
|
||||
"""Initialize the configuration with default values."""
|
||||
global _config
|
||||
if _config is None:
|
||||
_config = default_config.DEFAULT_CONFIG.copy()
|
||||
|
||||
|
||||
def set_config(config: Dict):
|
||||
"""Update the configuration with custom values."""
|
||||
global _config
|
||||
if _config is None:
|
||||
_config = default_config.DEFAULT_CONFIG.copy()
|
||||
_config.update(config)
|
||||
|
||||
|
||||
def get_config() -> Dict:
|
||||
"""Get the current configuration."""
|
||||
if _config is None:
|
||||
initialize_config()
|
||||
return _config.copy()
|
||||
|
||||
|
||||
# Initialize with default config
|
||||
initialize_config()
|
||||
@@ -0,0 +1,182 @@
|
||||
from typing import Annotated
|
||||
|
||||
# Import from vendor-specific modules
|
||||
from .y_finance import (
|
||||
get_YFin_data_online,
|
||||
get_stock_stats_indicators_window,
|
||||
get_fundamentals as get_yfinance_fundamentals,
|
||||
get_balance_sheet as get_yfinance_balance_sheet,
|
||||
get_cashflow as get_yfinance_cashflow,
|
||||
get_income_statement as get_yfinance_income_statement,
|
||||
get_insider_transactions as get_yfinance_insider_transactions,
|
||||
)
|
||||
from .yfinance_news import get_news_yfinance, get_global_news_yfinance
|
||||
from .alpha_vantage import (
|
||||
get_stock as get_alpha_vantage_stock,
|
||||
get_indicator as get_alpha_vantage_indicator,
|
||||
get_fundamentals as get_alpha_vantage_fundamentals,
|
||||
get_balance_sheet as get_alpha_vantage_balance_sheet,
|
||||
get_cashflow as get_alpha_vantage_cashflow,
|
||||
get_income_statement as get_alpha_vantage_income_statement,
|
||||
get_insider_transactions as get_alpha_vantage_insider_transactions,
|
||||
get_news as get_alpha_vantage_news,
|
||||
get_global_news as get_alpha_vantage_global_news,
|
||||
)
|
||||
from .alpha_vantage_common import AlphaVantageRateLimitError
|
||||
from .akshare_data import (
|
||||
get_stock_data as get_akshare_stock,
|
||||
get_indicators as get_akshare_indicator,
|
||||
get_fundamentals as get_akshare_fundamentals,
|
||||
get_balance_sheet as get_akshare_balance_sheet,
|
||||
get_cashflow as get_akshare_cashflow,
|
||||
get_income_statement as get_akshare_income_statement,
|
||||
get_insider_transactions as get_akshare_insider_transactions,
|
||||
)
|
||||
from .akshare_news import get_news as get_akshare_news, get_global_news as get_akshare_global_news
|
||||
|
||||
# Configuration and routing logic
|
||||
from .config import get_config
|
||||
|
||||
# Tools organized by category
|
||||
TOOLS_CATEGORIES = {
|
||||
"core_stock_apis": {
|
||||
"description": "OHLCV stock price data",
|
||||
"tools": [
|
||||
"get_stock_data"
|
||||
]
|
||||
},
|
||||
"technical_indicators": {
|
||||
"description": "Technical analysis indicators",
|
||||
"tools": [
|
||||
"get_indicators"
|
||||
]
|
||||
},
|
||||
"fundamental_data": {
|
||||
"description": "Company fundamentals",
|
||||
"tools": [
|
||||
"get_fundamentals",
|
||||
"get_balance_sheet",
|
||||
"get_cashflow",
|
||||
"get_income_statement"
|
||||
]
|
||||
},
|
||||
"news_data": {
|
||||
"description": "News and insider data",
|
||||
"tools": [
|
||||
"get_news",
|
||||
"get_global_news",
|
||||
"get_insider_transactions",
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
VENDOR_LIST = [
|
||||
"yfinance",
|
||||
"alpha_vantage",
|
||||
"akshare",
|
||||
]
|
||||
|
||||
# Mapping of methods to their vendor-specific implementations
|
||||
VENDOR_METHODS = {
|
||||
# core_stock_apis
|
||||
"get_stock_data": {
|
||||
"alpha_vantage": get_alpha_vantage_stock,
|
||||
"yfinance": get_YFin_data_online,
|
||||
"akshare": get_akshare_stock,
|
||||
},
|
||||
# technical_indicators
|
||||
"get_indicators": {
|
||||
"alpha_vantage": get_alpha_vantage_indicator,
|
||||
"yfinance": get_stock_stats_indicators_window,
|
||||
"akshare": get_akshare_indicator,
|
||||
},
|
||||
# fundamental_data
|
||||
"get_fundamentals": {
|
||||
"alpha_vantage": get_alpha_vantage_fundamentals,
|
||||
"yfinance": get_yfinance_fundamentals,
|
||||
"akshare": get_akshare_fundamentals,
|
||||
},
|
||||
"get_balance_sheet": {
|
||||
"alpha_vantage": get_alpha_vantage_balance_sheet,
|
||||
"yfinance": get_yfinance_balance_sheet,
|
||||
"akshare": get_akshare_balance_sheet,
|
||||
},
|
||||
"get_cashflow": {
|
||||
"alpha_vantage": get_alpha_vantage_cashflow,
|
||||
"yfinance": get_yfinance_cashflow,
|
||||
"akshare": get_akshare_cashflow,
|
||||
},
|
||||
"get_income_statement": {
|
||||
"alpha_vantage": get_alpha_vantage_income_statement,
|
||||
"yfinance": get_yfinance_income_statement,
|
||||
"akshare": get_akshare_income_statement,
|
||||
},
|
||||
# news_data
|
||||
"get_news": {
|
||||
"alpha_vantage": get_alpha_vantage_news,
|
||||
"yfinance": get_news_yfinance,
|
||||
"akshare": get_akshare_news,
|
||||
},
|
||||
"get_global_news": {
|
||||
"yfinance": get_global_news_yfinance,
|
||||
"alpha_vantage": get_alpha_vantage_global_news,
|
||||
"akshare": get_akshare_global_news,
|
||||
},
|
||||
"get_insider_transactions": {
|
||||
"akshare": get_akshare_insider_transactions,
|
||||
"yfinance": get_yfinance_insider_transactions,
|
||||
"alpha_vantage": get_alpha_vantage_insider_transactions,
|
||||
},
|
||||
}
|
||||
|
||||
def get_category_for_method(method: str) -> str:
|
||||
"""Get the category that contains the specified method."""
|
||||
for category, info in TOOLS_CATEGORIES.items():
|
||||
if method in info["tools"]:
|
||||
return category
|
||||
raise ValueError(f"Method '{method}' not found in any category")
|
||||
|
||||
def get_vendor(category: str, method: str = None) -> str:
|
||||
"""Get the configured vendor for a data category or specific tool method.
|
||||
Tool-level configuration takes precedence over category-level.
|
||||
"""
|
||||
config = get_config()
|
||||
|
||||
# Check tool-level configuration first (if method provided)
|
||||
if method:
|
||||
tool_vendors = config.get("tool_vendors", {})
|
||||
if method in tool_vendors:
|
||||
return tool_vendors[method]
|
||||
|
||||
# Fall back to category-level configuration
|
||||
return config.get("data_vendors", {}).get(category, "default")
|
||||
|
||||
def route_to_vendor(method: str, *args, **kwargs):
|
||||
"""Route method calls to appropriate vendor implementation with fallback support."""
|
||||
category = get_category_for_method(method)
|
||||
vendor_config = get_vendor(category, method)
|
||||
primary_vendors = [v.strip() for v in vendor_config.split(',')]
|
||||
|
||||
if method not in VENDOR_METHODS:
|
||||
raise ValueError(f"Method '{method}' not supported")
|
||||
|
||||
# Build fallback chain: primary vendors first, then remaining available vendors
|
||||
all_available_vendors = list(VENDOR_METHODS[method].keys())
|
||||
fallback_vendors = primary_vendors.copy()
|
||||
for vendor in all_available_vendors:
|
||||
if vendor not in fallback_vendors:
|
||||
fallback_vendors.append(vendor)
|
||||
|
||||
for vendor in fallback_vendors:
|
||||
if vendor not in VENDOR_METHODS[method]:
|
||||
continue
|
||||
|
||||
vendor_impl = VENDOR_METHODS[method][vendor]
|
||||
impl_func = vendor_impl[0] if isinstance(vendor_impl, list) else vendor_impl
|
||||
|
||||
try:
|
||||
return impl_func(*args, **kwargs)
|
||||
except AlphaVantageRateLimitError:
|
||||
continue # Only rate limits trigger fallback
|
||||
|
||||
raise RuntimeError(f"No available vendor for '{method}'")
|
||||
@@ -0,0 +1,133 @@
|
||||
import time
|
||||
import logging
|
||||
|
||||
import pandas as pd
|
||||
import yfinance as yf
|
||||
from yfinance.exceptions import YFRateLimitError
|
||||
from stockstats import wrap
|
||||
from typing import Annotated
|
||||
import os
|
||||
from .config import get_config
|
||||
from .utils import safe_ticker_component
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def yf_retry(func, max_retries=3, base_delay=2.0):
|
||||
"""Execute a yfinance call with exponential backoff on rate limits.
|
||||
|
||||
yfinance raises YFRateLimitError on HTTP 429 responses but does not
|
||||
retry them internally. This wrapper adds retry logic specifically
|
||||
for rate limits. Other exceptions propagate immediately.
|
||||
"""
|
||||
for attempt in range(max_retries + 1):
|
||||
try:
|
||||
return func()
|
||||
except YFRateLimitError:
|
||||
if attempt < max_retries:
|
||||
delay = base_delay * (2 ** attempt)
|
||||
logger.warning(f"Yahoo Finance rate limited, retrying in {delay:.0f}s (attempt {attempt + 1}/{max_retries})")
|
||||
time.sleep(delay)
|
||||
else:
|
||||
raise
|
||||
|
||||
|
||||
def _clean_dataframe(data: pd.DataFrame) -> pd.DataFrame:
|
||||
"""Normalize a stock DataFrame for stockstats: parse dates, drop invalid rows, fill price gaps."""
|
||||
data["Date"] = pd.to_datetime(data["Date"], errors="coerce")
|
||||
data = data.dropna(subset=["Date"])
|
||||
|
||||
price_cols = [c for c in ["Open", "High", "Low", "Close", "Volume"] if c in data.columns]
|
||||
data[price_cols] = data[price_cols].apply(pd.to_numeric, errors="coerce")
|
||||
data = data.dropna(subset=["Close"])
|
||||
data[price_cols] = data[price_cols].ffill().bfill()
|
||||
|
||||
return data
|
||||
|
||||
|
||||
def load_ohlcv(symbol: str, curr_date: str) -> pd.DataFrame:
|
||||
"""Fetch OHLCV data with caching, filtered to prevent look-ahead bias.
|
||||
|
||||
Downloads 15 years of data up to today and caches per symbol. On
|
||||
subsequent calls the cache is reused. Rows after curr_date are
|
||||
filtered out so backtests never see future prices.
|
||||
"""
|
||||
# Reject ticker values that would escape the cache directory when
|
||||
# interpolated into the cache filename (e.g. ``../../tmp/x``).
|
||||
safe_symbol = safe_ticker_component(symbol)
|
||||
|
||||
config = get_config()
|
||||
curr_date_dt = pd.to_datetime(curr_date)
|
||||
|
||||
# Cache uses a fixed window (15y to today) so one file per symbol
|
||||
today_date = pd.Timestamp.today()
|
||||
start_date = today_date - pd.DateOffset(years=5)
|
||||
start_str = start_date.strftime("%Y-%m-%d")
|
||||
end_str = today_date.strftime("%Y-%m-%d")
|
||||
|
||||
os.makedirs(config["data_cache_dir"], exist_ok=True)
|
||||
data_file = os.path.join(
|
||||
config["data_cache_dir"],
|
||||
f"{safe_symbol}-YFin-data-{start_str}-{end_str}.csv",
|
||||
)
|
||||
|
||||
if os.path.exists(data_file):
|
||||
data = pd.read_csv(data_file, on_bad_lines="skip", encoding="utf-8")
|
||||
else:
|
||||
data = yf_retry(lambda: yf.download(
|
||||
symbol,
|
||||
start=start_str,
|
||||
end=end_str,
|
||||
multi_level_index=False,
|
||||
progress=False,
|
||||
auto_adjust=True,
|
||||
))
|
||||
data = data.reset_index()
|
||||
data.to_csv(data_file, index=False, encoding="utf-8")
|
||||
|
||||
data = _clean_dataframe(data)
|
||||
|
||||
# Filter to curr_date to prevent look-ahead bias in backtesting
|
||||
data = data[data["Date"] <= curr_date_dt]
|
||||
|
||||
return data
|
||||
|
||||
|
||||
def filter_financials_by_date(data: pd.DataFrame, curr_date: str) -> pd.DataFrame:
|
||||
"""Drop financial statement columns (fiscal period timestamps) after curr_date.
|
||||
|
||||
yfinance financial statements use fiscal period end dates as columns.
|
||||
Columns after curr_date represent future data and are removed to
|
||||
prevent look-ahead bias.
|
||||
"""
|
||||
if not curr_date or data.empty:
|
||||
return data
|
||||
cutoff = pd.Timestamp(curr_date)
|
||||
mask = pd.to_datetime(data.columns, errors="coerce") <= cutoff
|
||||
return data.loc[:, mask]
|
||||
|
||||
|
||||
class StockstatsUtils:
|
||||
@staticmethod
|
||||
def get_stock_stats(
|
||||
symbol: Annotated[str, "ticker symbol for the company"],
|
||||
indicator: Annotated[
|
||||
str, "quantitative indicators based off of the stock data for the company"
|
||||
],
|
||||
curr_date: Annotated[
|
||||
str, "curr date for retrieving stock price data, YYYY-mm-dd"
|
||||
],
|
||||
):
|
||||
data = load_ohlcv(symbol, curr_date)
|
||||
df = wrap(data)
|
||||
df["Date"] = df["Date"].dt.strftime("%Y-%m-%d")
|
||||
curr_date_str = pd.to_datetime(curr_date).strftime("%Y-%m-%d")
|
||||
|
||||
df[indicator] # trigger stockstats to calculate the indicator
|
||||
matching_rows = df[df["Date"].str.startswith(curr_date_str)]
|
||||
|
||||
if not matching_rows.empty:
|
||||
indicator_value = matching_rows[indicator].values[0]
|
||||
return indicator_value
|
||||
else:
|
||||
return "N/A: Not a trading day (weekend or holiday)"
|
||||
@@ -0,0 +1,74 @@
|
||||
import os
|
||||
import re
|
||||
import json
|
||||
import pandas as pd
|
||||
from datetime import date, timedelta, datetime
|
||||
from typing import Annotated
|
||||
|
||||
SavePathType = Annotated[str, "File path to save data. If None, data is not saved."]
|
||||
|
||||
# Tickers can contain letters, digits, dot, dash, underscore, and caret
|
||||
# (for index symbols like ^GSPC). Anything else is rejected so the value
|
||||
# never escapes a containing directory when interpolated into a path.
|
||||
_TICKER_PATH_RE = re.compile(r"^[A-Za-z0-9._\-\^]+$")
|
||||
|
||||
|
||||
def safe_ticker_component(value: str, *, max_len: int = 32) -> str:
|
||||
"""Validate ``value`` is safe to interpolate into a filesystem path.
|
||||
|
||||
Tickers come from user CLI input or from LLM tool calls, both of which
|
||||
can be influenced by attacker-controlled content (e.g. prompt injection
|
||||
embedded in fetched news). Without validation, a value like
|
||||
``"../../../etc/foo"`` flows into ``os.path.join`` / ``Path /`` and
|
||||
escapes the configured cache, checkpoint, or results directory.
|
||||
|
||||
Returns ``value`` unchanged when it matches the allowed pattern; raises
|
||||
``ValueError`` otherwise.
|
||||
"""
|
||||
if not isinstance(value, str) or not value:
|
||||
raise ValueError(f"ticker must be a non-empty string, got {value!r}")
|
||||
if len(value) > max_len:
|
||||
raise ValueError(f"ticker exceeds {max_len} chars: {value!r}")
|
||||
if not _TICKER_PATH_RE.fullmatch(value):
|
||||
raise ValueError(
|
||||
f"ticker contains characters not allowed in a filesystem path: {value!r}"
|
||||
)
|
||||
# The regex above allows '.', so values like '.', '..', '...' would pass,
|
||||
# and as a path component they traverse the parent directory. Reject any
|
||||
# value that's only dots.
|
||||
if set(value) == {"."}:
|
||||
raise ValueError(f"ticker cannot consist solely of dots: {value!r}")
|
||||
return value
|
||||
|
||||
|
||||
def save_output(data: pd.DataFrame, tag: str, save_path: SavePathType = None) -> None:
|
||||
if save_path:
|
||||
data.to_csv(save_path, encoding="utf-8")
|
||||
print(f"{tag} saved to {save_path}")
|
||||
|
||||
|
||||
def get_current_date():
|
||||
return date.today().strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
def decorate_all_methods(decorator):
|
||||
def class_decorator(cls):
|
||||
for attr_name, attr_value in cls.__dict__.items():
|
||||
if callable(attr_value):
|
||||
setattr(cls, attr_name, decorator(attr_value))
|
||||
return cls
|
||||
|
||||
return class_decorator
|
||||
|
||||
|
||||
def get_next_weekday(date):
|
||||
|
||||
if not isinstance(date, datetime):
|
||||
date = datetime.strptime(date, "%Y-%m-%d")
|
||||
|
||||
if date.weekday() >= 5:
|
||||
days_to_add = 7 - date.weekday()
|
||||
next_weekday = date + timedelta(days=days_to_add)
|
||||
return next_weekday
|
||||
else:
|
||||
return date
|
||||
@@ -0,0 +1,422 @@
|
||||
from typing import Annotated
|
||||
from datetime import datetime
|
||||
from dateutil.relativedelta import relativedelta
|
||||
import pandas as pd
|
||||
import yfinance as yf
|
||||
import os
|
||||
from .stockstats_utils import StockstatsUtils, _clean_dataframe, yf_retry, load_ohlcv, filter_financials_by_date
|
||||
|
||||
def get_YFin_data_online(
|
||||
symbol: Annotated[str, "ticker symbol of the company"],
|
||||
start_date: Annotated[str, "Start date in yyyy-mm-dd format"],
|
||||
end_date: Annotated[str, "End date in yyyy-mm-dd format"],
|
||||
):
|
||||
|
||||
datetime.strptime(start_date, "%Y-%m-%d")
|
||||
datetime.strptime(end_date, "%Y-%m-%d")
|
||||
|
||||
# Create ticker object
|
||||
ticker = yf.Ticker(symbol.upper())
|
||||
|
||||
# Fetch historical data for the specified date range
|
||||
data = yf_retry(lambda: ticker.history(start=start_date, end=end_date))
|
||||
|
||||
# Check if data is empty
|
||||
if data.empty:
|
||||
return (
|
||||
f"No data found for symbol '{symbol}' between {start_date} and {end_date}"
|
||||
)
|
||||
|
||||
# Remove timezone info from index for cleaner output
|
||||
if data.index.tz is not None:
|
||||
data.index = data.index.tz_localize(None)
|
||||
|
||||
# Round numerical values to 2 decimal places for cleaner display
|
||||
numeric_columns = ["Open", "High", "Low", "Close", "Adj Close"]
|
||||
for col in numeric_columns:
|
||||
if col in data.columns:
|
||||
data[col] = data[col].round(2)
|
||||
|
||||
# Convert DataFrame to CSV string
|
||||
csv_string = data.to_csv()
|
||||
|
||||
# Add header information
|
||||
header = f"# Stock data for {symbol.upper()} from {start_date} to {end_date}\n"
|
||||
header += f"# Total records: {len(data)}\n"
|
||||
header += f"# Data retrieved on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n"
|
||||
|
||||
return header + csv_string
|
||||
|
||||
def get_stock_stats_indicators_window(
|
||||
symbol: Annotated[str, "ticker symbol of the company"],
|
||||
indicator: Annotated[str, "technical indicator to get the analysis and report of"],
|
||||
curr_date: Annotated[
|
||||
str, "The current trading date you are trading on, YYYY-mm-dd"
|
||||
],
|
||||
look_back_days: Annotated[int, "how many days to look back"],
|
||||
) -> str:
|
||||
|
||||
best_ind_params = {
|
||||
# Moving Averages
|
||||
"close_50_sma": (
|
||||
"50 SMA: A medium-term trend indicator. "
|
||||
"Usage: Identify trend direction and serve as dynamic support/resistance. "
|
||||
"Tips: It lags price; combine with faster indicators for timely signals."
|
||||
),
|
||||
"close_200_sma": (
|
||||
"200 SMA: A long-term trend benchmark. "
|
||||
"Usage: Confirm overall market trend and identify golden/death cross setups. "
|
||||
"Tips: It reacts slowly; best for strategic trend confirmation rather than frequent trading entries."
|
||||
),
|
||||
"close_10_ema": (
|
||||
"10 EMA: A responsive short-term average. "
|
||||
"Usage: Capture quick shifts in momentum and potential entry points. "
|
||||
"Tips: Prone to noise in choppy markets; use alongside longer averages for filtering false signals."
|
||||
),
|
||||
# MACD Related
|
||||
"macd": (
|
||||
"MACD: Computes momentum via differences of EMAs. "
|
||||
"Usage: Look for crossovers and divergence as signals of trend changes. "
|
||||
"Tips: Confirm with other indicators in low-volatility or sideways markets."
|
||||
),
|
||||
"macds": (
|
||||
"MACD Signal: An EMA smoothing of the MACD line. "
|
||||
"Usage: Use crossovers with the MACD line to trigger trades. "
|
||||
"Tips: Should be part of a broader strategy to avoid false positives."
|
||||
),
|
||||
"macdh": (
|
||||
"MACD Histogram: Shows the gap between the MACD line and its signal. "
|
||||
"Usage: Visualize momentum strength and spot divergence early. "
|
||||
"Tips: Can be volatile; complement with additional filters in fast-moving markets."
|
||||
),
|
||||
# Momentum Indicators
|
||||
"rsi": (
|
||||
"RSI: Measures momentum to flag overbought/oversold conditions. "
|
||||
"Usage: Apply 70/30 thresholds and watch for divergence to signal reversals. "
|
||||
"Tips: In strong trends, RSI may remain extreme; always cross-check with trend analysis."
|
||||
),
|
||||
# Volatility Indicators
|
||||
"boll": (
|
||||
"Bollinger Middle: A 20 SMA serving as the basis for Bollinger Bands. "
|
||||
"Usage: Acts as a dynamic benchmark for price movement. "
|
||||
"Tips: Combine with the upper and lower bands to effectively spot breakouts or reversals."
|
||||
),
|
||||
"boll_ub": (
|
||||
"Bollinger Upper Band: Typically 2 standard deviations above the middle line. "
|
||||
"Usage: Signals potential overbought conditions and breakout zones. "
|
||||
"Tips: Confirm signals with other tools; prices may ride the band in strong trends."
|
||||
),
|
||||
"boll_lb": (
|
||||
"Bollinger Lower Band: Typically 2 standard deviations below the middle line. "
|
||||
"Usage: Indicates potential oversold conditions. "
|
||||
"Tips: Use additional analysis to avoid false reversal signals."
|
||||
),
|
||||
"atr": (
|
||||
"ATR: Averages true range to measure volatility. "
|
||||
"Usage: Set stop-loss levels and adjust position sizes based on current market volatility. "
|
||||
"Tips: It's a reactive measure, so use it as part of a broader risk management strategy."
|
||||
),
|
||||
# Volume-Based Indicators
|
||||
"vwma": (
|
||||
"VWMA: A moving average weighted by volume. "
|
||||
"Usage: Confirm trends by integrating price action with volume data. "
|
||||
"Tips: Watch for skewed results from volume spikes; use in combination with other volume analyses."
|
||||
),
|
||||
"mfi": (
|
||||
"MFI: The Money Flow Index is a momentum indicator that uses both price and volume to measure buying and selling pressure. "
|
||||
"Usage: Identify overbought (>80) or oversold (<20) conditions and confirm the strength of trends or reversals. "
|
||||
"Tips: Use alongside RSI or MACD to confirm signals; divergence between price and MFI can indicate potential reversals."
|
||||
),
|
||||
}
|
||||
|
||||
if indicator not in best_ind_params:
|
||||
raise ValueError(
|
||||
f"Indicator {indicator} is not supported. Please choose from: {list(best_ind_params.keys())}"
|
||||
)
|
||||
|
||||
end_date = curr_date
|
||||
curr_date_dt = datetime.strptime(curr_date, "%Y-%m-%d")
|
||||
before = curr_date_dt - relativedelta(days=look_back_days)
|
||||
|
||||
# Optimized: Get stock data once and calculate indicators for all dates
|
||||
try:
|
||||
indicator_data = _get_stock_stats_bulk(symbol, indicator, curr_date)
|
||||
|
||||
# Generate the date range we need
|
||||
current_dt = curr_date_dt
|
||||
date_values = []
|
||||
|
||||
while current_dt >= before:
|
||||
date_str = current_dt.strftime('%Y-%m-%d')
|
||||
|
||||
# Look up the indicator value for this date
|
||||
if date_str in indicator_data:
|
||||
indicator_value = indicator_data[date_str]
|
||||
else:
|
||||
indicator_value = "N/A: Not a trading day (weekend or holiday)"
|
||||
|
||||
date_values.append((date_str, indicator_value))
|
||||
current_dt = current_dt - relativedelta(days=1)
|
||||
|
||||
# Build the result string
|
||||
ind_string = ""
|
||||
for date_str, value in date_values:
|
||||
ind_string += f"{date_str}: {value}\n"
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error getting bulk stockstats data: {e}")
|
||||
# Fallback to original implementation if bulk method fails
|
||||
ind_string = ""
|
||||
curr_date_dt = datetime.strptime(curr_date, "%Y-%m-%d")
|
||||
while curr_date_dt >= before:
|
||||
indicator_value = get_stockstats_indicator(
|
||||
symbol, indicator, curr_date_dt.strftime("%Y-%m-%d")
|
||||
)
|
||||
ind_string += f"{curr_date_dt.strftime('%Y-%m-%d')}: {indicator_value}\n"
|
||||
curr_date_dt = curr_date_dt - relativedelta(days=1)
|
||||
|
||||
result_str = (
|
||||
f"## {indicator} values from {before.strftime('%Y-%m-%d')} to {end_date}:\n\n"
|
||||
+ ind_string
|
||||
+ "\n\n"
|
||||
+ best_ind_params.get(indicator, "No description available.")
|
||||
)
|
||||
|
||||
return result_str
|
||||
|
||||
|
||||
def _get_stock_stats_bulk(
|
||||
symbol: Annotated[str, "ticker symbol of the company"],
|
||||
indicator: Annotated[str, "technical indicator to calculate"],
|
||||
curr_date: Annotated[str, "current date for reference"]
|
||||
) -> dict:
|
||||
"""
|
||||
Optimized bulk calculation of stock stats indicators.
|
||||
Fetches data once and calculates indicator for all available dates.
|
||||
Returns dict mapping date strings to indicator values.
|
||||
"""
|
||||
from stockstats import wrap
|
||||
|
||||
data = load_ohlcv(symbol, curr_date)
|
||||
df = wrap(data)
|
||||
df["Date"] = df["Date"].dt.strftime("%Y-%m-%d")
|
||||
|
||||
# Calculate the indicator for all rows at once
|
||||
df[indicator] # This triggers stockstats to calculate the indicator
|
||||
|
||||
# Create a dictionary mapping date strings to indicator values
|
||||
result_dict = {}
|
||||
for _, row in df.iterrows():
|
||||
date_str = row["Date"]
|
||||
indicator_value = row[indicator]
|
||||
|
||||
# Handle NaN/None values
|
||||
if pd.isna(indicator_value):
|
||||
result_dict[date_str] = "N/A"
|
||||
else:
|
||||
result_dict[date_str] = str(indicator_value)
|
||||
|
||||
return result_dict
|
||||
|
||||
|
||||
def get_stockstats_indicator(
|
||||
symbol: Annotated[str, "ticker symbol of the company"],
|
||||
indicator: Annotated[str, "technical indicator to get the analysis and report of"],
|
||||
curr_date: Annotated[
|
||||
str, "The current trading date you are trading on, YYYY-mm-dd"
|
||||
],
|
||||
) -> str:
|
||||
|
||||
curr_date_dt = datetime.strptime(curr_date, "%Y-%m-%d")
|
||||
curr_date = curr_date_dt.strftime("%Y-%m-%d")
|
||||
|
||||
try:
|
||||
indicator_value = StockstatsUtils.get_stock_stats(
|
||||
symbol,
|
||||
indicator,
|
||||
curr_date,
|
||||
)
|
||||
except Exception as e:
|
||||
print(
|
||||
f"Error getting stockstats indicator data for indicator {indicator} on {curr_date}: {e}"
|
||||
)
|
||||
return ""
|
||||
|
||||
return str(indicator_value)
|
||||
|
||||
|
||||
def get_fundamentals(
|
||||
ticker: Annotated[str, "ticker symbol of the company"],
|
||||
curr_date: Annotated[str, "current date (not used for yfinance)"] = None
|
||||
):
|
||||
"""Get company fundamentals overview from yfinance."""
|
||||
try:
|
||||
ticker_obj = yf.Ticker(ticker.upper())
|
||||
info = yf_retry(lambda: ticker_obj.info)
|
||||
|
||||
if not info:
|
||||
return f"No fundamentals data found for symbol '{ticker}'"
|
||||
|
||||
fields = [
|
||||
("Name", info.get("longName")),
|
||||
("Sector", info.get("sector")),
|
||||
("Industry", info.get("industry")),
|
||||
("Market Cap", info.get("marketCap")),
|
||||
("PE Ratio (TTM)", info.get("trailingPE")),
|
||||
("Forward PE", info.get("forwardPE")),
|
||||
("PEG Ratio", info.get("pegRatio")),
|
||||
("Price to Book", info.get("priceToBook")),
|
||||
("EPS (TTM)", info.get("trailingEps")),
|
||||
("Forward EPS", info.get("forwardEps")),
|
||||
("Dividend Yield", info.get("dividendYield")),
|
||||
("Beta", info.get("beta")),
|
||||
("52 Week High", info.get("fiftyTwoWeekHigh")),
|
||||
("52 Week Low", info.get("fiftyTwoWeekLow")),
|
||||
("50 Day Average", info.get("fiftyDayAverage")),
|
||||
("200 Day Average", info.get("twoHundredDayAverage")),
|
||||
("Revenue (TTM)", info.get("totalRevenue")),
|
||||
("Gross Profit", info.get("grossProfits")),
|
||||
("EBITDA", info.get("ebitda")),
|
||||
("Net Income", info.get("netIncomeToCommon")),
|
||||
("Profit Margin", info.get("profitMargins")),
|
||||
("Operating Margin", info.get("operatingMargins")),
|
||||
("Return on Equity", info.get("returnOnEquity")),
|
||||
("Return on Assets", info.get("returnOnAssets")),
|
||||
("Debt to Equity", info.get("debtToEquity")),
|
||||
("Current Ratio", info.get("currentRatio")),
|
||||
("Book Value", info.get("bookValue")),
|
||||
("Free Cash Flow", info.get("freeCashflow")),
|
||||
]
|
||||
|
||||
lines = []
|
||||
for label, value in fields:
|
||||
if value is not None:
|
||||
lines.append(f"{label}: {value}")
|
||||
|
||||
header = f"# Company Fundamentals for {ticker.upper()}\n"
|
||||
header += f"# Data retrieved on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n"
|
||||
|
||||
return header + "\n".join(lines)
|
||||
|
||||
except Exception as e:
|
||||
return f"Error retrieving fundamentals for {ticker}: {str(e)}"
|
||||
|
||||
|
||||
def get_balance_sheet(
|
||||
ticker: Annotated[str, "ticker symbol of the company"],
|
||||
freq: Annotated[str, "frequency of data: 'annual' or 'quarterly'"] = "quarterly",
|
||||
curr_date: Annotated[str, "current date in YYYY-MM-DD format"] = None
|
||||
):
|
||||
"""Get balance sheet data from yfinance."""
|
||||
try:
|
||||
ticker_obj = yf.Ticker(ticker.upper())
|
||||
|
||||
if freq.lower() == "quarterly":
|
||||
data = yf_retry(lambda: ticker_obj.quarterly_balance_sheet)
|
||||
else:
|
||||
data = yf_retry(lambda: ticker_obj.balance_sheet)
|
||||
|
||||
data = filter_financials_by_date(data, curr_date)
|
||||
|
||||
if data.empty:
|
||||
return f"No balance sheet data found for symbol '{ticker}'"
|
||||
|
||||
# Convert to CSV string for consistency with other functions
|
||||
csv_string = data.to_csv()
|
||||
|
||||
# Add header information
|
||||
header = f"# Balance Sheet data for {ticker.upper()} ({freq})\n"
|
||||
header += f"# Data retrieved on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n"
|
||||
|
||||
return header + csv_string
|
||||
|
||||
except Exception as e:
|
||||
return f"Error retrieving balance sheet for {ticker}: {str(e)}"
|
||||
|
||||
|
||||
def get_cashflow(
|
||||
ticker: Annotated[str, "ticker symbol of the company"],
|
||||
freq: Annotated[str, "frequency of data: 'annual' or 'quarterly'"] = "quarterly",
|
||||
curr_date: Annotated[str, "current date in YYYY-MM-DD format"] = None
|
||||
):
|
||||
"""Get cash flow data from yfinance."""
|
||||
try:
|
||||
ticker_obj = yf.Ticker(ticker.upper())
|
||||
|
||||
if freq.lower() == "quarterly":
|
||||
data = yf_retry(lambda: ticker_obj.quarterly_cashflow)
|
||||
else:
|
||||
data = yf_retry(lambda: ticker_obj.cashflow)
|
||||
|
||||
data = filter_financials_by_date(data, curr_date)
|
||||
|
||||
if data.empty:
|
||||
return f"No cash flow data found for symbol '{ticker}'"
|
||||
|
||||
# Convert to CSV string for consistency with other functions
|
||||
csv_string = data.to_csv()
|
||||
|
||||
# Add header information
|
||||
header = f"# Cash Flow data for {ticker.upper()} ({freq})\n"
|
||||
header += f"# Data retrieved on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n"
|
||||
|
||||
return header + csv_string
|
||||
|
||||
except Exception as e:
|
||||
return f"Error retrieving cash flow for {ticker}: {str(e)}"
|
||||
|
||||
|
||||
def get_income_statement(
|
||||
ticker: Annotated[str, "ticker symbol of the company"],
|
||||
freq: Annotated[str, "frequency of data: 'annual' or 'quarterly'"] = "quarterly",
|
||||
curr_date: Annotated[str, "current date in YYYY-MM-DD format"] = None
|
||||
):
|
||||
"""Get income statement data from yfinance."""
|
||||
try:
|
||||
ticker_obj = yf.Ticker(ticker.upper())
|
||||
|
||||
if freq.lower() == "quarterly":
|
||||
data = yf_retry(lambda: ticker_obj.quarterly_income_stmt)
|
||||
else:
|
||||
data = yf_retry(lambda: ticker_obj.income_stmt)
|
||||
|
||||
data = filter_financials_by_date(data, curr_date)
|
||||
|
||||
if data.empty:
|
||||
return f"No income statement data found for symbol '{ticker}'"
|
||||
|
||||
# Convert to CSV string for consistency with other functions
|
||||
csv_string = data.to_csv()
|
||||
|
||||
# Add header information
|
||||
header = f"# Income Statement data for {ticker.upper()} ({freq})\n"
|
||||
header += f"# Data retrieved on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n"
|
||||
|
||||
return header + csv_string
|
||||
|
||||
except Exception as e:
|
||||
return f"Error retrieving income statement for {ticker}: {str(e)}"
|
||||
|
||||
|
||||
def get_insider_transactions(
|
||||
ticker: Annotated[str, "ticker symbol of the company"]
|
||||
):
|
||||
"""Get insider transactions data from yfinance."""
|
||||
try:
|
||||
ticker_obj = yf.Ticker(ticker.upper())
|
||||
data = yf_retry(lambda: ticker_obj.insider_transactions)
|
||||
|
||||
if data is None or data.empty:
|
||||
return f"No insider transactions data found for symbol '{ticker}'"
|
||||
|
||||
# Convert to CSV string for consistency with other functions
|
||||
csv_string = data.to_csv()
|
||||
|
||||
# Add header information
|
||||
header = f"# Insider Transactions data for {ticker.upper()}\n"
|
||||
header += f"# Data retrieved on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n"
|
||||
|
||||
return header + csv_string
|
||||
|
||||
except Exception as e:
|
||||
return f"Error retrieving insider transactions for {ticker}: {str(e)}"
|
||||
@@ -0,0 +1,197 @@
|
||||
"""yfinance-based news data fetching functions."""
|
||||
|
||||
import yfinance as yf
|
||||
from datetime import datetime
|
||||
from dateutil.relativedelta import relativedelta
|
||||
|
||||
from .stockstats_utils import yf_retry
|
||||
|
||||
|
||||
def _extract_article_data(article: dict) -> dict:
|
||||
"""Extract article data from yfinance news format (handles nested 'content' structure)."""
|
||||
# Handle nested content structure
|
||||
if "content" in article:
|
||||
content = article["content"]
|
||||
title = content.get("title", "No title")
|
||||
summary = content.get("summary", "")
|
||||
provider = content.get("provider", {})
|
||||
publisher = provider.get("displayName", "Unknown")
|
||||
|
||||
# Get URL from canonicalUrl or clickThroughUrl
|
||||
url_obj = content.get("canonicalUrl") or content.get("clickThroughUrl") or {}
|
||||
link = url_obj.get("url", "")
|
||||
|
||||
# Get publish date
|
||||
pub_date_str = content.get("pubDate", "")
|
||||
pub_date = None
|
||||
if pub_date_str:
|
||||
try:
|
||||
pub_date = datetime.fromisoformat(pub_date_str.replace("Z", "+00:00"))
|
||||
except (ValueError, AttributeError):
|
||||
pass
|
||||
|
||||
return {
|
||||
"title": title,
|
||||
"summary": summary,
|
||||
"publisher": publisher,
|
||||
"link": link,
|
||||
"pub_date": pub_date,
|
||||
}
|
||||
else:
|
||||
# Fallback for flat structure
|
||||
return {
|
||||
"title": article.get("title", "No title"),
|
||||
"summary": article.get("summary", ""),
|
||||
"publisher": article.get("publisher", "Unknown"),
|
||||
"link": article.get("link", ""),
|
||||
"pub_date": None,
|
||||
}
|
||||
|
||||
|
||||
def get_news_yfinance(
|
||||
ticker: str,
|
||||
start_date: str,
|
||||
end_date: str,
|
||||
) -> str:
|
||||
"""
|
||||
Retrieve news for a specific stock ticker using yfinance.
|
||||
|
||||
Args:
|
||||
ticker: Stock ticker symbol (e.g., "AAPL")
|
||||
start_date: Start date in yyyy-mm-dd format
|
||||
end_date: End date in yyyy-mm-dd format
|
||||
|
||||
Returns:
|
||||
Formatted string containing news articles
|
||||
"""
|
||||
try:
|
||||
stock = yf.Ticker(ticker)
|
||||
news = yf_retry(lambda: stock.get_news(count=20))
|
||||
|
||||
if not news:
|
||||
return f"No news found for {ticker}"
|
||||
|
||||
# Parse date range for filtering
|
||||
start_dt = datetime.strptime(start_date, "%Y-%m-%d")
|
||||
end_dt = datetime.strptime(end_date, "%Y-%m-%d")
|
||||
|
||||
news_str = ""
|
||||
filtered_count = 0
|
||||
|
||||
for article in news:
|
||||
data = _extract_article_data(article)
|
||||
|
||||
# Filter by date if publish time is available
|
||||
if data["pub_date"]:
|
||||
pub_date_naive = data["pub_date"].replace(tzinfo=None)
|
||||
if not (start_dt <= pub_date_naive <= end_dt + relativedelta(days=1)):
|
||||
continue
|
||||
|
||||
news_str += f"### {data['title']} (source: {data['publisher']})\n"
|
||||
if data["summary"]:
|
||||
news_str += f"{data['summary']}\n"
|
||||
if data["link"]:
|
||||
news_str += f"Link: {data['link']}\n"
|
||||
news_str += "\n"
|
||||
filtered_count += 1
|
||||
|
||||
if filtered_count == 0:
|
||||
return f"No news found for {ticker} between {start_date} and {end_date}"
|
||||
|
||||
return f"## {ticker} News, from {start_date} to {end_date}:\n\n{news_str}"
|
||||
|
||||
except Exception as e:
|
||||
return f"Error fetching news for {ticker}: {str(e)}"
|
||||
|
||||
|
||||
def get_global_news_yfinance(
|
||||
curr_date: str,
|
||||
look_back_days: int = 7,
|
||||
limit: int = 10,
|
||||
) -> str:
|
||||
"""
|
||||
Retrieve global/macro economic news using yfinance Search.
|
||||
|
||||
Args:
|
||||
curr_date: Current date in yyyy-mm-dd format
|
||||
look_back_days: Number of days to look back
|
||||
limit: Maximum number of articles to return
|
||||
|
||||
Returns:
|
||||
Formatted string containing global news articles
|
||||
"""
|
||||
# Search queries for macro/global news
|
||||
search_queries = [
|
||||
"stock market economy",
|
||||
"Federal Reserve interest rates",
|
||||
"inflation economic outlook",
|
||||
"global markets trading",
|
||||
]
|
||||
|
||||
all_news = []
|
||||
seen_titles = set()
|
||||
|
||||
try:
|
||||
for query in search_queries:
|
||||
search = yf_retry(lambda q=query: yf.Search(
|
||||
query=q,
|
||||
news_count=limit,
|
||||
enable_fuzzy_query=True,
|
||||
))
|
||||
|
||||
if search.news:
|
||||
for article in search.news:
|
||||
# Handle both flat and nested structures
|
||||
if "content" in article:
|
||||
data = _extract_article_data(article)
|
||||
title = data["title"]
|
||||
else:
|
||||
title = article.get("title", "")
|
||||
|
||||
# Deduplicate by title
|
||||
if title and title not in seen_titles:
|
||||
seen_titles.add(title)
|
||||
all_news.append(article)
|
||||
|
||||
if len(all_news) >= limit:
|
||||
break
|
||||
|
||||
if not all_news:
|
||||
return f"No global news found for {curr_date}"
|
||||
|
||||
# Calculate date range
|
||||
curr_dt = datetime.strptime(curr_date, "%Y-%m-%d")
|
||||
start_dt = curr_dt - relativedelta(days=look_back_days)
|
||||
start_date = start_dt.strftime("%Y-%m-%d")
|
||||
|
||||
news_str = ""
|
||||
for article in all_news[:limit]:
|
||||
# Handle both flat and nested structures
|
||||
if "content" in article:
|
||||
data = _extract_article_data(article)
|
||||
# Skip articles published after curr_date (look-ahead guard)
|
||||
if data.get("pub_date"):
|
||||
pub_naive = data["pub_date"].replace(tzinfo=None) if hasattr(data["pub_date"], "replace") else data["pub_date"]
|
||||
if pub_naive > curr_dt + relativedelta(days=1):
|
||||
continue
|
||||
title = data["title"]
|
||||
publisher = data["publisher"]
|
||||
link = data["link"]
|
||||
summary = data["summary"]
|
||||
else:
|
||||
title = article.get("title", "No title")
|
||||
publisher = article.get("publisher", "Unknown")
|
||||
link = article.get("link", "")
|
||||
summary = ""
|
||||
|
||||
news_str += f"### {title} (source: {publisher})\n"
|
||||
if summary:
|
||||
news_str += f"{summary}\n"
|
||||
if link:
|
||||
news_str += f"Link: {link}\n"
|
||||
news_str += "\n"
|
||||
|
||||
return f"## Global Market News, from {start_date} to {curr_date}:\n\n{news_str}"
|
||||
|
||||
except Exception as e:
|
||||
return f"Error fetching global news: {str(e)}"
|
||||
@@ -0,0 +1,50 @@
|
||||
import os
|
||||
|
||||
_TRADINGAGENTS_HOME = os.path.join(os.path.expanduser("~"), ".tradingagents")
|
||||
|
||||
DEFAULT_CONFIG = {
|
||||
"project_dir": os.path.abspath(os.path.join(os.path.dirname(__file__), ".")),
|
||||
"results_dir": os.getenv("TRADINGAGENTS_RESULTS_DIR", os.path.join(_TRADINGAGENTS_HOME, "logs")),
|
||||
"data_cache_dir": os.getenv("TRADINGAGENTS_CACHE_DIR", os.path.join(_TRADINGAGENTS_HOME, "cache")),
|
||||
"memory_log_path": os.getenv("TRADINGAGENTS_MEMORY_LOG_PATH", os.path.join(_TRADINGAGENTS_HOME, "memory", "trading_memory.md")),
|
||||
# Optional cap on the number of resolved memory log entries. When set,
|
||||
# the oldest resolved entries are pruned once this limit is exceeded.
|
||||
# Pending entries are never pruned. None disables rotation entirely.
|
||||
"memory_log_max_entries": None,
|
||||
# LLM settings
|
||||
"llm_provider": "deepseek",
|
||||
"deep_think_llm": "deepseek-v4-flash",
|
||||
"quick_think_llm": "deepseek-v4-flash",
|
||||
# When None, each provider's client falls back to its own default endpoint
|
||||
# (api.openai.com for OpenAI, generativelanguage.googleapis.com for Gemini, ...).
|
||||
# The CLI overrides this per provider when the user picks one. Keeping a
|
||||
# provider-specific URL here would leak (e.g. OpenAI's /v1 was previously
|
||||
# being forwarded to Gemini, producing malformed request URLs).
|
||||
"backend_url": None,
|
||||
# Provider-specific thinking configuration
|
||||
"google_thinking_level": None, # "high", "minimal", etc.
|
||||
"openai_reasoning_effort": None, # "medium", "high", "low"
|
||||
"anthropic_effort": None, # "high", "medium", "low"
|
||||
# Checkpoint/resume: when True, LangGraph saves state after each node
|
||||
# so a crashed run can resume from the last successful step.
|
||||
"checkpoint_enabled": False,
|
||||
# Output language for analyst reports and final decision
|
||||
# Internal agent debate stays in English for reasoning quality
|
||||
"output_language": "English",
|
||||
# Debate and discussion settings
|
||||
"max_debate_rounds": 1,
|
||||
"max_risk_discuss_rounds": 1,
|
||||
"max_recur_limit": 100,
|
||||
# Data vendor configuration
|
||||
# Category-level configuration (default for all tools in category)
|
||||
"data_vendors": {
|
||||
"core_stock_apis": "akshare", # Options: alpha_vantage, yfinance, akshare
|
||||
"technical_indicators": "akshare", # Options: alpha_vantage, yfinance, akshare
|
||||
"fundamental_data": "akshare", # Options: alpha_vantage, yfinance, akshare
|
||||
"news_data": "akshare", # Options: alpha_vantage, yfinance, akshare
|
||||
},
|
||||
# Tool-level configuration (takes precedence over category-level)
|
||||
"tool_vendors": {
|
||||
# Example: "get_stock_data": "alpha_vantage", # Override category default
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
# TradingAgents/graph/__init__.py
|
||||
|
||||
from .trading_graph import TradingAgentsGraph
|
||||
from .conditional_logic import ConditionalLogic
|
||||
from .setup import GraphSetup
|
||||
from .propagation import Propagator
|
||||
from .reflection import Reflector
|
||||
from .signal_processing import SignalProcessor
|
||||
|
||||
__all__ = [
|
||||
"TradingAgentsGraph",
|
||||
"ConditionalLogic",
|
||||
"GraphSetup",
|
||||
"Propagator",
|
||||
"Reflector",
|
||||
"SignalProcessor",
|
||||
]
|
||||
@@ -0,0 +1,90 @@
|
||||
"""LangGraph checkpoint support for resumable analysis runs.
|
||||
|
||||
Per-ticker SQLite databases so concurrent tickers don't contend.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import sqlite3
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
from typing import Generator
|
||||
|
||||
from langgraph.checkpoint.sqlite import SqliteSaver
|
||||
|
||||
from tradingagents.dataflows.utils import safe_ticker_component
|
||||
|
||||
|
||||
def _db_path(data_dir: str | Path, ticker: str) -> Path:
|
||||
"""Return the SQLite checkpoint DB path for a ticker."""
|
||||
# Reject ticker values that would escape the checkpoints directory.
|
||||
safe = safe_ticker_component(ticker).upper()
|
||||
p = Path(data_dir) / "checkpoints"
|
||||
p.mkdir(parents=True, exist_ok=True)
|
||||
return p / f"{safe}.db"
|
||||
|
||||
|
||||
def thread_id(ticker: str, date: str) -> str:
|
||||
"""Deterministic thread ID for a ticker+date pair."""
|
||||
return hashlib.sha256(f"{ticker.upper()}:{date}".encode()).hexdigest()[:16]
|
||||
|
||||
|
||||
@contextmanager
|
||||
def get_checkpointer(data_dir: str | Path, ticker: str) -> Generator[SqliteSaver, None, None]:
|
||||
"""Context manager yielding a SqliteSaver backed by a per-ticker DB."""
|
||||
db = _db_path(data_dir, ticker)
|
||||
conn = sqlite3.connect(str(db), check_same_thread=False)
|
||||
try:
|
||||
saver = SqliteSaver(conn)
|
||||
saver.setup()
|
||||
yield saver
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def has_checkpoint(data_dir: str | Path, ticker: str, date: str) -> bool:
|
||||
"""Check whether a resumable checkpoint exists for ticker+date."""
|
||||
return checkpoint_step(data_dir, ticker, date) is not None
|
||||
|
||||
|
||||
def checkpoint_step(data_dir: str | Path, ticker: str, date: str) -> int | None:
|
||||
"""Return the step number of the latest checkpoint, or None if none exists."""
|
||||
db = _db_path(data_dir, ticker)
|
||||
if not db.exists():
|
||||
return None
|
||||
tid = thread_id(ticker, date)
|
||||
with get_checkpointer(data_dir, ticker) as saver:
|
||||
config = {"configurable": {"thread_id": tid}}
|
||||
cp = saver.get_tuple(config)
|
||||
if cp is None:
|
||||
return None
|
||||
return cp.metadata.get("step")
|
||||
|
||||
|
||||
def clear_all_checkpoints(data_dir: str | Path) -> int:
|
||||
"""Remove all checkpoint DBs. Returns number of files deleted."""
|
||||
cp_dir = Path(data_dir) / "checkpoints"
|
||||
if not cp_dir.exists():
|
||||
return 0
|
||||
dbs = list(cp_dir.glob("*.db"))
|
||||
for db in dbs:
|
||||
db.unlink()
|
||||
return len(dbs)
|
||||
|
||||
|
||||
def clear_checkpoint(data_dir: str | Path, ticker: str, date: str) -> None:
|
||||
"""Remove checkpoint for a specific ticker+date by deleting the thread's rows."""
|
||||
db = _db_path(data_dir, ticker)
|
||||
if not db.exists():
|
||||
return
|
||||
tid = thread_id(ticker, date)
|
||||
conn = sqlite3.connect(str(db))
|
||||
try:
|
||||
for table in ("writes", "checkpoints"):
|
||||
conn.execute(f"DELETE FROM {table} WHERE thread_id = ?", (tid,))
|
||||
conn.commit()
|
||||
except sqlite3.OperationalError:
|
||||
pass
|
||||
finally:
|
||||
conn.close()
|
||||
@@ -0,0 +1,67 @@
|
||||
# TradingAgents/graph/conditional_logic.py
|
||||
|
||||
from tradingagents.agents.utils.agent_states import AgentState
|
||||
|
||||
|
||||
class ConditionalLogic:
|
||||
"""Handles conditional logic for determining graph flow."""
|
||||
|
||||
def __init__(self, max_debate_rounds=1, max_risk_discuss_rounds=1):
|
||||
"""Initialize with configuration parameters."""
|
||||
self.max_debate_rounds = max_debate_rounds
|
||||
self.max_risk_discuss_rounds = max_risk_discuss_rounds
|
||||
|
||||
def should_continue_market(self, state: AgentState):
|
||||
"""Determine if market analysis should continue."""
|
||||
messages = state["messages"]
|
||||
last_message = messages[-1]
|
||||
if last_message.tool_calls:
|
||||
return "tools_market"
|
||||
return "Msg Clear Market"
|
||||
|
||||
def should_continue_social(self, state: AgentState):
|
||||
"""Determine if social media analysis should continue."""
|
||||
messages = state["messages"]
|
||||
last_message = messages[-1]
|
||||
if last_message.tool_calls:
|
||||
return "tools_social"
|
||||
return "Msg Clear Social"
|
||||
|
||||
def should_continue_news(self, state: AgentState):
|
||||
"""Determine if news analysis should continue."""
|
||||
messages = state["messages"]
|
||||
last_message = messages[-1]
|
||||
if last_message.tool_calls:
|
||||
return "tools_news"
|
||||
return "Msg Clear News"
|
||||
|
||||
def should_continue_fundamentals(self, state: AgentState):
|
||||
"""Determine if fundamentals analysis should continue."""
|
||||
messages = state["messages"]
|
||||
last_message = messages[-1]
|
||||
if last_message.tool_calls:
|
||||
return "tools_fundamentals"
|
||||
return "Msg Clear Fundamentals"
|
||||
|
||||
def should_continue_debate(self, state: AgentState) -> str:
|
||||
"""Determine if debate should continue."""
|
||||
|
||||
if (
|
||||
state["investment_debate_state"]["count"] >= 2 * self.max_debate_rounds
|
||||
): # 3 rounds of back-and-forth between 2 agents
|
||||
return "Research Manager"
|
||||
if state["investment_debate_state"]["current_response"].startswith("Bull"):
|
||||
return "Bear Researcher"
|
||||
return "Bull Researcher"
|
||||
|
||||
def should_continue_risk_analysis(self, state: AgentState) -> str:
|
||||
"""Determine if risk analysis should continue."""
|
||||
if (
|
||||
state["risk_debate_state"]["count"] >= 3 * self.max_risk_discuss_rounds
|
||||
): # 3 rounds of back-and-forth between 3 agents
|
||||
return "Portfolio Manager"
|
||||
if state["risk_debate_state"]["latest_speaker"].startswith("Aggressive"):
|
||||
return "Conservative Analyst"
|
||||
if state["risk_debate_state"]["latest_speaker"].startswith("Conservative"):
|
||||
return "Neutral Analyst"
|
||||
return "Aggressive Analyst"
|
||||
@@ -0,0 +1,70 @@
|
||||
# TradingAgents/graph/propagation.py
|
||||
|
||||
from typing import Dict, Any, List, Optional
|
||||
from tradingagents.agents.utils.agent_states import (
|
||||
AgentState,
|
||||
InvestDebateState,
|
||||
RiskDebateState,
|
||||
)
|
||||
|
||||
|
||||
class Propagator:
|
||||
"""Handles state initialization and propagation through the graph."""
|
||||
|
||||
def __init__(self, max_recur_limit=100):
|
||||
"""Initialize with configuration parameters."""
|
||||
self.max_recur_limit = max_recur_limit
|
||||
|
||||
def create_initial_state(
|
||||
self, company_name: str, trade_date: str, past_context: str = ""
|
||||
) -> Dict[str, Any]:
|
||||
"""Create the initial state for the agent graph."""
|
||||
return {
|
||||
"messages": [("human", company_name)],
|
||||
"company_of_interest": company_name,
|
||||
"trade_date": str(trade_date),
|
||||
"past_context": past_context,
|
||||
"investment_debate_state": InvestDebateState(
|
||||
{
|
||||
"bull_history": "",
|
||||
"bear_history": "",
|
||||
"history": "",
|
||||
"current_response": "",
|
||||
"judge_decision": "",
|
||||
"count": 0,
|
||||
}
|
||||
),
|
||||
"risk_debate_state": RiskDebateState(
|
||||
{
|
||||
"aggressive_history": "",
|
||||
"conservative_history": "",
|
||||
"neutral_history": "",
|
||||
"history": "",
|
||||
"latest_speaker": "",
|
||||
"current_aggressive_response": "",
|
||||
"current_conservative_response": "",
|
||||
"current_neutral_response": "",
|
||||
"judge_decision": "",
|
||||
"count": 0,
|
||||
}
|
||||
),
|
||||
"market_report": "",
|
||||
"fundamentals_report": "",
|
||||
"sentiment_report": "",
|
||||
"news_report": "",
|
||||
}
|
||||
|
||||
def get_graph_args(self, callbacks: Optional[List] = None) -> Dict[str, Any]:
|
||||
"""Get arguments for the graph invocation.
|
||||
|
||||
Args:
|
||||
callbacks: Optional list of callback handlers for tool execution tracking.
|
||||
Note: LLM callbacks are handled separately via LLM constructor.
|
||||
"""
|
||||
config = {"recursion_limit": self.max_recur_limit}
|
||||
if callbacks:
|
||||
config["callbacks"] = callbacks
|
||||
return {
|
||||
"stream_mode": "values",
|
||||
"config": config,
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
# TradingAgents/graph/reflection.py
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
class Reflector:
|
||||
"""Handles reflection on trading decisions."""
|
||||
|
||||
def __init__(self, quick_thinking_llm: Any):
|
||||
"""Initialize the reflector with an LLM."""
|
||||
self.quick_thinking_llm = quick_thinking_llm
|
||||
self.log_reflection_prompt = self._get_log_reflection_prompt()
|
||||
|
||||
def _get_log_reflection_prompt(self) -> str:
|
||||
"""Concise prompt for reflect_on_final_decision (Phase B log entries).
|
||||
|
||||
Produces 2-4 sentences of plain prose — compact enough to be re-injected
|
||||
into future agent prompts without bloating the context window.
|
||||
"""
|
||||
return (
|
||||
"You are a trading analyst reviewing your own past decision now that the outcome is known.\n"
|
||||
"Write exactly 2-4 sentences of plain prose (no bullets, no headers, no markdown).\n\n"
|
||||
"Cover in order:\n"
|
||||
"1. Was the directional call correct? (cite the alpha figure)\n"
|
||||
"2. Which part of the investment thesis held or failed?\n"
|
||||
"3. One concrete lesson to apply to the next similar analysis.\n\n"
|
||||
"Be specific and terse. Your output will be stored verbatim in a decision log "
|
||||
"and re-read by future analysts, so every word must earn its place."
|
||||
)
|
||||
|
||||
def reflect_on_final_decision(
|
||||
self,
|
||||
final_decision: str,
|
||||
raw_return: float,
|
||||
alpha_return: float,
|
||||
) -> str:
|
||||
"""Single reflection call on the final trade decision with outcome context.
|
||||
|
||||
Used by Phase B deferred reflection. The final_trade_decision already
|
||||
synthesises all analyst insights, so no separate market context is needed.
|
||||
"""
|
||||
messages = [
|
||||
("system", self.log_reflection_prompt),
|
||||
(
|
||||
"human",
|
||||
(
|
||||
f"Raw return: {raw_return:+.1%}\n"
|
||||
f"Alpha vs SPY: {alpha_return:+.1%}\n\n"
|
||||
f"Final Decision:\n{final_decision}"
|
||||
),
|
||||
),
|
||||
]
|
||||
return self.quick_thinking_llm.invoke(messages).content
|
||||
@@ -0,0 +1,182 @@
|
||||
# TradingAgents/graph/setup.py
|
||||
|
||||
from typing import Any, Dict
|
||||
from langgraph.graph import END, START, StateGraph
|
||||
from langgraph.prebuilt import ToolNode
|
||||
|
||||
from tradingagents.agents import *
|
||||
from tradingagents.agents.utils.agent_states import AgentState
|
||||
|
||||
from .conditional_logic import ConditionalLogic
|
||||
|
||||
|
||||
class GraphSetup:
|
||||
"""Handles the setup and configuration of the agent graph."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
quick_thinking_llm: Any,
|
||||
deep_thinking_llm: Any,
|
||||
tool_nodes: Dict[str, ToolNode],
|
||||
conditional_logic: ConditionalLogic,
|
||||
):
|
||||
"""Initialize with required components."""
|
||||
self.quick_thinking_llm = quick_thinking_llm
|
||||
self.deep_thinking_llm = deep_thinking_llm
|
||||
self.tool_nodes = tool_nodes
|
||||
self.conditional_logic = conditional_logic
|
||||
|
||||
def setup_graph(
|
||||
self, selected_analysts=["market", "social", "news", "fundamentals"]
|
||||
):
|
||||
"""Set up and compile the agent workflow graph.
|
||||
|
||||
Args:
|
||||
selected_analysts (list): List of analyst types to include. Options are:
|
||||
- "market": Market analyst
|
||||
- "social": Social media analyst
|
||||
- "news": News analyst
|
||||
- "fundamentals": Fundamentals analyst
|
||||
"""
|
||||
if len(selected_analysts) == 0:
|
||||
raise ValueError("Trading Agents Graph Setup Error: no analysts selected!")
|
||||
|
||||
# Create analyst nodes
|
||||
analyst_nodes = {}
|
||||
delete_nodes = {}
|
||||
tool_nodes = {}
|
||||
|
||||
if "market" in selected_analysts:
|
||||
analyst_nodes["market"] = create_market_analyst(
|
||||
self.quick_thinking_llm
|
||||
)
|
||||
delete_nodes["market"] = create_msg_delete()
|
||||
tool_nodes["market"] = self.tool_nodes["market"]
|
||||
|
||||
if "social" in selected_analysts:
|
||||
analyst_nodes["social"] = create_social_media_analyst(
|
||||
self.quick_thinking_llm
|
||||
)
|
||||
delete_nodes["social"] = create_msg_delete()
|
||||
tool_nodes["social"] = self.tool_nodes["social"]
|
||||
|
||||
if "news" in selected_analysts:
|
||||
analyst_nodes["news"] = create_news_analyst(
|
||||
self.quick_thinking_llm
|
||||
)
|
||||
delete_nodes["news"] = create_msg_delete()
|
||||
tool_nodes["news"] = self.tool_nodes["news"]
|
||||
|
||||
if "fundamentals" in selected_analysts:
|
||||
analyst_nodes["fundamentals"] = create_fundamentals_analyst(
|
||||
self.quick_thinking_llm
|
||||
)
|
||||
delete_nodes["fundamentals"] = create_msg_delete()
|
||||
tool_nodes["fundamentals"] = self.tool_nodes["fundamentals"]
|
||||
|
||||
# Create researcher and manager nodes
|
||||
bull_researcher_node = create_bull_researcher(self.quick_thinking_llm)
|
||||
bear_researcher_node = create_bear_researcher(self.quick_thinking_llm)
|
||||
research_manager_node = create_research_manager(self.deep_thinking_llm)
|
||||
trader_node = create_trader(self.quick_thinking_llm)
|
||||
|
||||
# Create risk analysis nodes
|
||||
aggressive_analyst = create_aggressive_debator(self.quick_thinking_llm)
|
||||
neutral_analyst = create_neutral_debator(self.quick_thinking_llm)
|
||||
conservative_analyst = create_conservative_debator(self.quick_thinking_llm)
|
||||
portfolio_manager_node = create_portfolio_manager(self.deep_thinking_llm)
|
||||
|
||||
# Create workflow
|
||||
workflow = StateGraph(AgentState)
|
||||
|
||||
# Add analyst nodes to the graph
|
||||
for analyst_type, node in analyst_nodes.items():
|
||||
workflow.add_node(f"{analyst_type.capitalize()} Analyst", node)
|
||||
workflow.add_node(
|
||||
f"Msg Clear {analyst_type.capitalize()}", delete_nodes[analyst_type]
|
||||
)
|
||||
workflow.add_node(f"tools_{analyst_type}", tool_nodes[analyst_type])
|
||||
|
||||
# Add other nodes
|
||||
workflow.add_node("Bull Researcher", bull_researcher_node)
|
||||
workflow.add_node("Bear Researcher", bear_researcher_node)
|
||||
workflow.add_node("Research Manager", research_manager_node)
|
||||
workflow.add_node("Trader", trader_node)
|
||||
workflow.add_node("Aggressive Analyst", aggressive_analyst)
|
||||
workflow.add_node("Neutral Analyst", neutral_analyst)
|
||||
workflow.add_node("Conservative Analyst", conservative_analyst)
|
||||
workflow.add_node("Portfolio Manager", portfolio_manager_node)
|
||||
|
||||
# Define edges
|
||||
# Start with the first analyst
|
||||
first_analyst = selected_analysts[0]
|
||||
workflow.add_edge(START, f"{first_analyst.capitalize()} Analyst")
|
||||
|
||||
# Connect analysts in sequence
|
||||
for i, analyst_type in enumerate(selected_analysts):
|
||||
current_analyst = f"{analyst_type.capitalize()} Analyst"
|
||||
current_tools = f"tools_{analyst_type}"
|
||||
current_clear = f"Msg Clear {analyst_type.capitalize()}"
|
||||
|
||||
# Add conditional edges for current analyst
|
||||
workflow.add_conditional_edges(
|
||||
current_analyst,
|
||||
getattr(self.conditional_logic, f"should_continue_{analyst_type}"),
|
||||
[current_tools, current_clear],
|
||||
)
|
||||
workflow.add_edge(current_tools, current_analyst)
|
||||
|
||||
# Connect to next analyst or to Bull Researcher if this is the last analyst
|
||||
if i < len(selected_analysts) - 1:
|
||||
next_analyst = f"{selected_analysts[i+1].capitalize()} Analyst"
|
||||
workflow.add_edge(current_clear, next_analyst)
|
||||
else:
|
||||
workflow.add_edge(current_clear, "Bull Researcher")
|
||||
|
||||
# Add remaining edges
|
||||
workflow.add_conditional_edges(
|
||||
"Bull Researcher",
|
||||
self.conditional_logic.should_continue_debate,
|
||||
{
|
||||
"Bear Researcher": "Bear Researcher",
|
||||
"Research Manager": "Research Manager",
|
||||
},
|
||||
)
|
||||
workflow.add_conditional_edges(
|
||||
"Bear Researcher",
|
||||
self.conditional_logic.should_continue_debate,
|
||||
{
|
||||
"Bull Researcher": "Bull Researcher",
|
||||
"Research Manager": "Research Manager",
|
||||
},
|
||||
)
|
||||
workflow.add_edge("Research Manager", "Trader")
|
||||
workflow.add_edge("Trader", "Aggressive Analyst")
|
||||
workflow.add_conditional_edges(
|
||||
"Aggressive Analyst",
|
||||
self.conditional_logic.should_continue_risk_analysis,
|
||||
{
|
||||
"Conservative Analyst": "Conservative Analyst",
|
||||
"Portfolio Manager": "Portfolio Manager",
|
||||
},
|
||||
)
|
||||
workflow.add_conditional_edges(
|
||||
"Conservative Analyst",
|
||||
self.conditional_logic.should_continue_risk_analysis,
|
||||
{
|
||||
"Neutral Analyst": "Neutral Analyst",
|
||||
"Portfolio Manager": "Portfolio Manager",
|
||||
},
|
||||
)
|
||||
workflow.add_conditional_edges(
|
||||
"Neutral Analyst",
|
||||
self.conditional_logic.should_continue_risk_analysis,
|
||||
{
|
||||
"Aggressive Analyst": "Aggressive Analyst",
|
||||
"Portfolio Manager": "Portfolio Manager",
|
||||
},
|
||||
)
|
||||
|
||||
workflow.add_edge("Portfolio Manager", END)
|
||||
|
||||
return workflow
|
||||
@@ -0,0 +1,31 @@
|
||||
"""Extract the 5-tier portfolio rating from the Portfolio Manager's decision.
|
||||
|
||||
The Portfolio Manager produces a typed ``PortfolioDecision`` via structured
|
||||
output and renders it to markdown that always carries a ``**Rating**: X``
|
||||
header (see :func:`tradingagents.agents.schemas.render_pm_decision`). The
|
||||
deterministic heuristic in :mod:`tradingagents.agents.utils.rating` is more
|
||||
than sufficient to extract that rating; no extra LLM call is needed.
|
||||
|
||||
This module exists for backwards compatibility with callers that expect a
|
||||
``SignalProcessor.process_signal(text)`` interface.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from tradingagents.agents.utils.rating import parse_rating
|
||||
|
||||
|
||||
class SignalProcessor:
|
||||
"""Read the 5-tier rating out of a Portfolio Manager decision."""
|
||||
|
||||
def __init__(self, quick_thinking_llm: Any = None):
|
||||
# The LLM argument is accepted for backwards compatibility but no
|
||||
# longer used: the PM's structured output guarantees the rating is
|
||||
# parseable from the rendered markdown without a second LLM call.
|
||||
self.quick_thinking_llm = quick_thinking_llm
|
||||
|
||||
def process_signal(self, full_signal: str) -> str:
|
||||
"""Return one of Buy / Overweight / Hold / Underweight / Sell."""
|
||||
return parse_rating(full_signal)
|
||||
@@ -0,0 +1,406 @@
|
||||
# TradingAgents/graph/trading_graph.py
|
||||
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
import json
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Dict, Any, Tuple, List, Optional
|
||||
|
||||
import yfinance as yf
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
from langgraph.prebuilt import ToolNode
|
||||
|
||||
from tradingagents.llm_clients import create_llm_client
|
||||
|
||||
from tradingagents.agents import *
|
||||
from tradingagents.default_config import DEFAULT_CONFIG
|
||||
from tradingagents.agents.utils.memory import TradingMemoryLog
|
||||
from tradingagents.dataflows.utils import safe_ticker_component
|
||||
from tradingagents.agents.utils.agent_states import (
|
||||
AgentState,
|
||||
InvestDebateState,
|
||||
RiskDebateState,
|
||||
)
|
||||
from tradingagents.dataflows.config import set_config
|
||||
|
||||
# Import the new abstract tool methods from agent_utils
|
||||
from tradingagents.agents.utils.agent_utils import (
|
||||
get_stock_data,
|
||||
get_indicators,
|
||||
get_fundamentals,
|
||||
get_balance_sheet,
|
||||
get_cashflow,
|
||||
get_income_statement,
|
||||
get_news,
|
||||
get_insider_transactions,
|
||||
get_global_news
|
||||
)
|
||||
|
||||
from .checkpointer import checkpoint_step, clear_checkpoint, get_checkpointer, thread_id
|
||||
from .conditional_logic import ConditionalLogic
|
||||
from .setup import GraphSetup
|
||||
from .propagation import Propagator
|
||||
from .reflection import Reflector
|
||||
from .signal_processing import SignalProcessor
|
||||
|
||||
|
||||
class TradingAgentsGraph:
|
||||
"""Main class that orchestrates the trading agents framework."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
selected_analysts=["market", "social", "news", "fundamentals"],
|
||||
debug=False,
|
||||
config: Dict[str, Any] = None,
|
||||
callbacks: Optional[List] = None,
|
||||
):
|
||||
"""Initialize the trading agents graph and components.
|
||||
|
||||
Args:
|
||||
selected_analysts: List of analyst types to include
|
||||
debug: Whether to run in debug mode
|
||||
config: Configuration dictionary. If None, uses default config
|
||||
callbacks: Optional list of callback handlers (e.g., for tracking LLM/tool stats)
|
||||
"""
|
||||
self.debug = debug
|
||||
self.config = config or DEFAULT_CONFIG
|
||||
self.callbacks = callbacks or []
|
||||
|
||||
# Update the interface's config
|
||||
set_config(self.config)
|
||||
|
||||
# Create necessary directories
|
||||
os.makedirs(self.config["data_cache_dir"], exist_ok=True)
|
||||
os.makedirs(self.config["results_dir"], exist_ok=True)
|
||||
|
||||
# Initialize LLMs with provider-specific thinking configuration
|
||||
llm_kwargs = self._get_provider_kwargs()
|
||||
|
||||
# Add callbacks to kwargs if provided (passed to LLM constructor)
|
||||
if self.callbacks:
|
||||
llm_kwargs["callbacks"] = self.callbacks
|
||||
|
||||
deep_client = create_llm_client(
|
||||
provider=self.config["llm_provider"],
|
||||
model=self.config["deep_think_llm"],
|
||||
base_url=self.config.get("backend_url"),
|
||||
**llm_kwargs,
|
||||
)
|
||||
quick_client = create_llm_client(
|
||||
provider=self.config["llm_provider"],
|
||||
model=self.config["quick_think_llm"],
|
||||
base_url=self.config.get("backend_url"),
|
||||
**llm_kwargs,
|
||||
)
|
||||
|
||||
self.deep_thinking_llm = deep_client.get_llm()
|
||||
self.quick_thinking_llm = quick_client.get_llm()
|
||||
|
||||
self.memory_log = TradingMemoryLog(self.config)
|
||||
|
||||
# Create tool nodes
|
||||
self.tool_nodes = self._create_tool_nodes()
|
||||
|
||||
# Initialize components
|
||||
self.conditional_logic = ConditionalLogic(
|
||||
max_debate_rounds=self.config["max_debate_rounds"],
|
||||
max_risk_discuss_rounds=self.config["max_risk_discuss_rounds"],
|
||||
)
|
||||
self.graph_setup = GraphSetup(
|
||||
self.quick_thinking_llm,
|
||||
self.deep_thinking_llm,
|
||||
self.tool_nodes,
|
||||
self.conditional_logic,
|
||||
)
|
||||
|
||||
self.propagator = Propagator()
|
||||
self.reflector = Reflector(self.quick_thinking_llm)
|
||||
self.signal_processor = SignalProcessor(self.quick_thinking_llm)
|
||||
|
||||
# State tracking
|
||||
self.curr_state = None
|
||||
self.ticker = None
|
||||
self.log_states_dict = {} # date to full state dict
|
||||
|
||||
# Set up the graph: keep the workflow for recompilation with a checkpointer.
|
||||
self.workflow = self.graph_setup.setup_graph(selected_analysts)
|
||||
self.graph = self.workflow.compile()
|
||||
self._checkpointer_ctx = None
|
||||
|
||||
def _get_provider_kwargs(self) -> Dict[str, Any]:
|
||||
"""Get provider-specific kwargs for LLM client creation."""
|
||||
kwargs = {}
|
||||
provider = self.config.get("llm_provider", "").lower()
|
||||
|
||||
if provider == "google":
|
||||
thinking_level = self.config.get("google_thinking_level")
|
||||
if thinking_level:
|
||||
kwargs["thinking_level"] = thinking_level
|
||||
|
||||
elif provider == "openai":
|
||||
reasoning_effort = self.config.get("openai_reasoning_effort")
|
||||
if reasoning_effort:
|
||||
kwargs["reasoning_effort"] = reasoning_effort
|
||||
|
||||
elif provider == "anthropic":
|
||||
effort = self.config.get("anthropic_effort")
|
||||
if effort:
|
||||
kwargs["effort"] = effort
|
||||
|
||||
return kwargs
|
||||
|
||||
def _create_tool_nodes(self) -> Dict[str, ToolNode]:
|
||||
"""Create tool nodes for different data sources using abstract methods."""
|
||||
return {
|
||||
"market": ToolNode(
|
||||
[
|
||||
# Core stock data tools
|
||||
get_stock_data,
|
||||
# Technical indicators
|
||||
get_indicators,
|
||||
]
|
||||
),
|
||||
"social": ToolNode(
|
||||
[
|
||||
# News tools for social media analysis
|
||||
get_news,
|
||||
]
|
||||
),
|
||||
"news": ToolNode(
|
||||
[
|
||||
# News and insider information
|
||||
get_news,
|
||||
get_global_news,
|
||||
get_insider_transactions,
|
||||
]
|
||||
),
|
||||
"fundamentals": ToolNode(
|
||||
[
|
||||
# Fundamental analysis tools
|
||||
get_fundamentals,
|
||||
get_balance_sheet,
|
||||
get_cashflow,
|
||||
get_income_statement,
|
||||
]
|
||||
),
|
||||
}
|
||||
|
||||
def _fetch_returns(
|
||||
self, ticker: str, trade_date: str, holding_days: int = 5
|
||||
) -> Tuple[Optional[float], Optional[float], Optional[int]]:
|
||||
"""Fetch raw and alpha return for ticker over holding_days from trade_date.
|
||||
|
||||
Returns (raw_return, alpha_return, actual_holding_days) or
|
||||
(None, None, None) if price data is unavailable (too recent, delisted,
|
||||
or network error).
|
||||
"""
|
||||
try:
|
||||
start = datetime.strptime(trade_date, "%Y-%m-%d")
|
||||
end = start + timedelta(days=holding_days + 7) # buffer for weekends/holidays
|
||||
end_str = end.strftime("%Y-%m-%d")
|
||||
|
||||
stock = yf.Ticker(ticker).history(start=trade_date, end=end_str)
|
||||
spy = yf.Ticker("SPY").history(start=trade_date, end=end_str)
|
||||
|
||||
if len(stock) < 2 or len(spy) < 2:
|
||||
return None, None, None
|
||||
|
||||
actual_days = min(holding_days, len(stock) - 1, len(spy) - 1)
|
||||
raw = float(
|
||||
(stock["Close"].iloc[actual_days] - stock["Close"].iloc[0])
|
||||
/ stock["Close"].iloc[0]
|
||||
)
|
||||
spy_ret = float(
|
||||
(spy["Close"].iloc[actual_days] - spy["Close"].iloc[0])
|
||||
/ spy["Close"].iloc[0]
|
||||
)
|
||||
alpha = raw - spy_ret
|
||||
return raw, alpha, actual_days
|
||||
except Exception as e:
|
||||
logger.warning(
|
||||
"Could not resolve outcome for %s on %s (will retry next run): %s",
|
||||
ticker, trade_date, e,
|
||||
)
|
||||
return None, None, None
|
||||
|
||||
def _resolve_pending_entries(self, ticker: str) -> None:
|
||||
"""Resolve pending log entries for ticker at the start of a new run.
|
||||
|
||||
Fetches returns for each same-ticker pending entry, generates reflections,
|
||||
then writes all updates in a single atomic batch write to avoid redundant I/O.
|
||||
Skips entries whose price data is not yet available (too recent or delisted).
|
||||
|
||||
Trade-off: only same-ticker entries are resolved per run. Entries for
|
||||
other tickers accumulate until that ticker is run again.
|
||||
"""
|
||||
pending = [e for e in self.memory_log.get_pending_entries() if e["ticker"] == ticker]
|
||||
if not pending:
|
||||
return
|
||||
|
||||
updates = []
|
||||
for entry in pending:
|
||||
raw, alpha, days = self._fetch_returns(ticker, entry["date"])
|
||||
if raw is None:
|
||||
continue # price not available yet — try again next run
|
||||
reflection = self.reflector.reflect_on_final_decision(
|
||||
final_decision=entry.get("decision", ""),
|
||||
raw_return=raw,
|
||||
alpha_return=alpha,
|
||||
)
|
||||
updates.append({
|
||||
"ticker": ticker,
|
||||
"trade_date": entry["date"],
|
||||
"raw_return": raw,
|
||||
"alpha_return": alpha,
|
||||
"holding_days": days,
|
||||
"reflection": reflection,
|
||||
})
|
||||
|
||||
if updates:
|
||||
self.memory_log.batch_update_with_outcomes(updates)
|
||||
|
||||
def propagate(self, company_name, trade_date):
|
||||
"""Run the trading agents graph for a company on a specific date.
|
||||
|
||||
When ``checkpoint_enabled`` is set in config, the graph is recompiled
|
||||
with a per-ticker SqliteSaver so a crashed run can resume from the last
|
||||
successful node on a subsequent invocation with the same ticker+date.
|
||||
"""
|
||||
self.ticker = company_name
|
||||
|
||||
# Resolve any pending memory-log entries for this ticker before the pipeline runs.
|
||||
self._resolve_pending_entries(company_name)
|
||||
|
||||
# Recompile with a checkpointer if the user opted in.
|
||||
if self.config.get("checkpoint_enabled"):
|
||||
self._checkpointer_ctx = get_checkpointer(
|
||||
self.config["data_cache_dir"], company_name
|
||||
)
|
||||
saver = self._checkpointer_ctx.__enter__()
|
||||
self.graph = self.workflow.compile(checkpointer=saver)
|
||||
|
||||
step = checkpoint_step(
|
||||
self.config["data_cache_dir"], company_name, str(trade_date)
|
||||
)
|
||||
if step is not None:
|
||||
logger.info(
|
||||
"Resuming from step %d for %s on %s", step, company_name, trade_date
|
||||
)
|
||||
else:
|
||||
logger.info("Starting fresh for %s on %s", company_name, trade_date)
|
||||
|
||||
try:
|
||||
return self._run_graph(company_name, trade_date)
|
||||
finally:
|
||||
if self._checkpointer_ctx is not None:
|
||||
self._checkpointer_ctx.__exit__(None, None, None)
|
||||
self._checkpointer_ctx = None
|
||||
self.graph = self.workflow.compile()
|
||||
|
||||
def _run_graph(self, company_name, trade_date):
|
||||
"""Execute the graph and write the resulting state to disk and memory log."""
|
||||
# Initialize state — inject memory log context for PM.
|
||||
past_context = self.memory_log.get_past_context(company_name)
|
||||
init_agent_state = self.propagator.create_initial_state(
|
||||
company_name, trade_date, past_context=past_context
|
||||
)
|
||||
args = self.propagator.get_graph_args()
|
||||
|
||||
# Inject thread_id so same ticker+date resumes, different date starts fresh.
|
||||
if self.config.get("checkpoint_enabled"):
|
||||
tid = thread_id(company_name, str(trade_date))
|
||||
args.setdefault("config", {}).setdefault("configurable", {})["thread_id"] = tid
|
||||
|
||||
if self.debug:
|
||||
trace = []
|
||||
for chunk in self.graph.stream(init_agent_state, **args):
|
||||
if len(chunk["messages"]) == 0:
|
||||
pass
|
||||
else:
|
||||
chunk["messages"][-1].pretty_print()
|
||||
trace.append(chunk)
|
||||
final_state = trace[-1]
|
||||
else:
|
||||
final_state = self.graph.invoke(init_agent_state, **args)
|
||||
|
||||
# Store current state for reflection.
|
||||
self.curr_state = final_state
|
||||
|
||||
# Log state to disk.
|
||||
self._log_state(trade_date, final_state)
|
||||
|
||||
# Store decision for deferred reflection on the next same-ticker run.
|
||||
self.memory_log.store_decision(
|
||||
ticker=company_name,
|
||||
trade_date=trade_date,
|
||||
final_trade_decision=final_state["final_trade_decision"],
|
||||
)
|
||||
|
||||
# Clear checkpoint on successful completion to avoid stale state.
|
||||
if self.config.get("checkpoint_enabled"):
|
||||
clear_checkpoint(
|
||||
self.config["data_cache_dir"], company_name, str(trade_date)
|
||||
)
|
||||
|
||||
# Publish analysis result to WeChat official account and personal blog.
|
||||
try:
|
||||
from tradingagents.publish.wechat_publisher import publish_analysis_result
|
||||
publish_analysis_result(
|
||||
final_state=final_state,
|
||||
ticker=company_name,
|
||||
trade_date=trade_date,
|
||||
results_dir=self.config.get("results_dir"),
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning("Failed to publish analysis result: %s", e)
|
||||
|
||||
return final_state, self.process_signal(final_state["final_trade_decision"])
|
||||
|
||||
def _log_state(self, trade_date, final_state):
|
||||
"""Log the final state to a JSON file."""
|
||||
self.log_states_dict[str(trade_date)] = {
|
||||
"company_of_interest": final_state["company_of_interest"],
|
||||
"trade_date": final_state["trade_date"],
|
||||
"market_report": final_state["market_report"],
|
||||
"sentiment_report": final_state["sentiment_report"],
|
||||
"news_report": final_state["news_report"],
|
||||
"fundamentals_report": final_state["fundamentals_report"],
|
||||
"investment_debate_state": {
|
||||
"bull_history": final_state["investment_debate_state"]["bull_history"],
|
||||
"bear_history": final_state["investment_debate_state"]["bear_history"],
|
||||
"history": final_state["investment_debate_state"]["history"],
|
||||
"current_response": final_state["investment_debate_state"][
|
||||
"current_response"
|
||||
],
|
||||
"judge_decision": final_state["investment_debate_state"][
|
||||
"judge_decision"
|
||||
],
|
||||
},
|
||||
"trader_investment_decision": final_state["trader_investment_plan"],
|
||||
"risk_debate_state": {
|
||||
"aggressive_history": final_state["risk_debate_state"]["aggressive_history"],
|
||||
"conservative_history": final_state["risk_debate_state"]["conservative_history"],
|
||||
"neutral_history": final_state["risk_debate_state"]["neutral_history"],
|
||||
"history": final_state["risk_debate_state"]["history"],
|
||||
"judge_decision": final_state["risk_debate_state"]["judge_decision"],
|
||||
},
|
||||
"investment_plan": final_state["investment_plan"],
|
||||
"final_trade_decision": final_state["final_trade_decision"],
|
||||
}
|
||||
|
||||
# Save to file. Reject ticker values that would escape the
|
||||
# results directory when joined as a path component.
|
||||
safe_ticker = safe_ticker_component(self.ticker)
|
||||
directory = Path(self.config["results_dir"]) / safe_ticker / "TradingAgentsStrategy_logs"
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
log_path = directory / f"full_states_log_{trade_date}.json"
|
||||
with open(log_path, "w", encoding="utf-8") as f:
|
||||
json.dump(self.log_states_dict[str(trade_date)], f, indent=4)
|
||||
|
||||
def process_signal(self, full_signal):
|
||||
"""Process a signal to extract the core decision."""
|
||||
return self.signal_processor.process_signal(full_signal)
|
||||
@@ -0,0 +1,15 @@
|
||||
# LLM Clients - Consistency Improvements
|
||||
|
||||
## Issues to Fix
|
||||
|
||||
### 1. `validate_model()` is never called
|
||||
- Add validation call in `get_llm()` with warning (not error) for unknown models
|
||||
|
||||
### 2. ~~Inconsistent parameter handling~~ (Fixed)
|
||||
- GoogleClient now accepts unified `api_key` and maps it to `google_api_key`
|
||||
|
||||
### 3. ~~`base_url` accepted but ignored~~ (Fixed)
|
||||
- All clients now pass `base_url` to their respective LLM constructors
|
||||
|
||||
### 4. ~~Update validators.py with models from CLI~~ (Fixed)
|
||||
- Synced in v0.2.2
|
||||
@@ -0,0 +1,4 @@
|
||||
from .base_client import BaseLLMClient
|
||||
from .factory import create_llm_client
|
||||
|
||||
__all__ = ["BaseLLMClient", "create_llm_client"]
|
||||
@@ -0,0 +1,48 @@
|
||||
from typing import Any, Optional
|
||||
|
||||
from langchain_anthropic import ChatAnthropic
|
||||
|
||||
from .base_client import BaseLLMClient, normalize_content
|
||||
from .validators import validate_model
|
||||
|
||||
_PASSTHROUGH_KWARGS = (
|
||||
"timeout", "max_retries", "api_key", "max_tokens",
|
||||
"callbacks", "http_client", "http_async_client", "effort",
|
||||
)
|
||||
|
||||
|
||||
class NormalizedChatAnthropic(ChatAnthropic):
|
||||
"""ChatAnthropic with normalized content output.
|
||||
|
||||
Claude models with extended thinking or tool use return content as a
|
||||
list of typed blocks. This normalizes to string for consistent
|
||||
downstream handling.
|
||||
"""
|
||||
|
||||
def invoke(self, input, config=None, **kwargs):
|
||||
return normalize_content(super().invoke(input, config, **kwargs))
|
||||
|
||||
|
||||
class AnthropicClient(BaseLLMClient):
|
||||
"""Client for Anthropic Claude models."""
|
||||
|
||||
def __init__(self, model: str, base_url: Optional[str] = None, **kwargs):
|
||||
super().__init__(model, base_url, **kwargs)
|
||||
|
||||
def get_llm(self) -> Any:
|
||||
"""Return configured ChatAnthropic instance."""
|
||||
self.warn_if_unknown_model()
|
||||
llm_kwargs = {"model": self.model}
|
||||
|
||||
if self.base_url:
|
||||
llm_kwargs["base_url"] = self.base_url
|
||||
|
||||
for key in _PASSTHROUGH_KWARGS:
|
||||
if key in self.kwargs:
|
||||
llm_kwargs[key] = self.kwargs[key]
|
||||
|
||||
return NormalizedChatAnthropic(**llm_kwargs)
|
||||
|
||||
def validate_model(self) -> bool:
|
||||
"""Validate model for Anthropic."""
|
||||
return validate_model("anthropic", self.model)
|
||||
@@ -0,0 +1,52 @@
|
||||
import os
|
||||
from typing import Any, Optional
|
||||
|
||||
from langchain_openai import AzureChatOpenAI
|
||||
|
||||
from .base_client import BaseLLMClient, normalize_content
|
||||
from .validators import validate_model
|
||||
|
||||
_PASSTHROUGH_KWARGS = (
|
||||
"timeout", "max_retries", "api_key", "reasoning_effort",
|
||||
"callbacks", "http_client", "http_async_client",
|
||||
)
|
||||
|
||||
|
||||
class NormalizedAzureChatOpenAI(AzureChatOpenAI):
|
||||
"""AzureChatOpenAI with normalized content output."""
|
||||
|
||||
def invoke(self, input, config=None, **kwargs):
|
||||
return normalize_content(super().invoke(input, config, **kwargs))
|
||||
|
||||
|
||||
class AzureOpenAIClient(BaseLLMClient):
|
||||
"""Client for Azure OpenAI deployments.
|
||||
|
||||
Requires environment variables:
|
||||
AZURE_OPENAI_API_KEY: API key
|
||||
AZURE_OPENAI_ENDPOINT: Endpoint URL (e.g. https://<resource>.openai.azure.com/)
|
||||
AZURE_OPENAI_DEPLOYMENT_NAME: Deployment name
|
||||
OPENAI_API_VERSION: API version (e.g. 2025-03-01-preview)
|
||||
"""
|
||||
|
||||
def __init__(self, model: str, base_url: Optional[str] = None, **kwargs):
|
||||
super().__init__(model, base_url, **kwargs)
|
||||
|
||||
def get_llm(self) -> Any:
|
||||
"""Return configured AzureChatOpenAI instance."""
|
||||
self.warn_if_unknown_model()
|
||||
|
||||
llm_kwargs = {
|
||||
"model": self.model,
|
||||
"azure_deployment": os.environ.get("AZURE_OPENAI_DEPLOYMENT_NAME", self.model),
|
||||
}
|
||||
|
||||
for key in _PASSTHROUGH_KWARGS:
|
||||
if key in self.kwargs:
|
||||
llm_kwargs[key] = self.kwargs[key]
|
||||
|
||||
return NormalizedAzureChatOpenAI(**llm_kwargs)
|
||||
|
||||
def validate_model(self) -> bool:
|
||||
"""Azure accepts any deployed model name."""
|
||||
return True
|
||||