[
  {
    "path": ".gitignore",
    "content": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[codz]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packaging\n.Python\nbuild/\ndevelop-eggs/\ndist/\ndownloads/\neggs/\n.eggs/\nlib/\nlib64/\nparts/\nsdist/\nvar/\nwheels/\nshare/python-wheels/\n*.egg-info/\n.installed.cfg\n*.egg\nMANIFEST\n\n# PyInstaller\n#   Usually these files are written by a python script from a template\n#   before PyInstaller builds the exe, so as to inject date/other infos into it.\n*.manifest\n*.spec\n\n# Installer logs\npip-log.txt\npip-delete-this-directory.txt\n\n# Unit test / coverage reports\nhtmlcov/\n.tox/\n.nox/\n.coverage\n.coverage.*\n.cache\nnosetests.xml\ncoverage.xml\n*.cover\n*.py.cover\n.hypothesis/\n.pytest_cache/\ncover/\n\n# Translations\n*.mo\n*.pot\n\n# Django stuff:\n*.log\nlocal_settings.py\ndb.sqlite3\ndb.sqlite3-journal\n\n# Flask stuff:\ninstance/\n.webassets-cache\n\n# Scrapy stuff:\n.scrapy\n\n# Sphinx documentation\ndocs/_build/\n\n# PyBuilder\n.pybuilder/\ntarget/\n\n# Jupyter Notebook\n.ipynb_checkpoints\n\n# IPython\nprofile_default/\nipython_config.py\n\n# pyenv\n#   For a library or package, you might want to ignore these files since the code is\n#   intended to run in multiple environments; otherwise, check them in:\n# .python-version\n\n# pipenv\n#   According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.\n#   However, in case of collaboration, if having platform-specific dependencies or dependencies\n#   having no cross-platform support, pipenv may install dependencies that don't work, or not\n#   install all needed dependencies.\n# Pipfile.lock\n\n# UV\n#   Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.\n#   This is especially recommended for binary packages to ensure reproducibility, and is more\n#   commonly ignored for libraries.\n# uv.lock\n\n# poetry\n#   Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.\n#   This is especially recommended for binary packages to ensure reproducibility, and is more\n#   commonly ignored for libraries.\n#   https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control\n# poetry.lock\n# poetry.toml\n\n# pdm\n#   Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.\n#   pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.\n#   https://pdm-project.org/en/latest/usage/project/#working-with-version-control\n# pdm.lock\n# pdm.toml\n.pdm-python\n.pdm-build/\n\n# pixi\n#   Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.\n# pixi.lock\n#   Pixi creates a virtual environment in the .pixi directory, just like venv module creates one\n#   in the .venv directory. It is recommended not to include this directory in version control.\n.pixi\n\n# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm\n__pypackages__/\n\n# Celery stuff\ncelerybeat-schedule\ncelerybeat.pid\n\n# Redis\n*.rdb\n*.aof\n*.pid\n\n# RabbitMQ\nmnesia/\nrabbitmq/\nrabbitmq-data/\n\n# ActiveMQ\nactivemq-data/\n\n# SageMath parsed files\n*.sage.py\n\n# Environments\n.env\n.envrc\n.venv\nenv/\nvenv/\nENV/\nenv.bak/\nvenv.bak/\n\n# Spyder project settings\n.spyderproject\n.spyproject\n\n# Rope project settings\n.ropeproject\n\n# mkdocs documentation\n/site\n\n# mypy\n.mypy_cache/\n.dmypy.json\ndmypy.json\n\n# Pyre type checker\n.pyre/\n\n# pytype static type analyzer\n.pytype/\n\n# Cython debug symbols\ncython_debug/\n\n# PyCharm\n#   JetBrains specific template is maintained in a separate JetBrains.gitignore that can\n#   be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore\n#   and can be added to the global gitignore or merged into this file.  For a more nuclear\n#   option (not recommended) you can uncomment the following to ignore the entire idea folder.\n# .idea/\n\n# Abstra\n#   Abstra is an AI-powered process automation framework.\n#   Ignore directories containing user credentials, local state, and settings.\n#   Learn more at https://abstra.io/docs\n.abstra/\n\n# Visual Studio Code\n#   Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore \n#   that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore\n#   and can be added to the global gitignore or merged into this file. However, if you prefer, \n#   you could uncomment the following to ignore the entire vscode folder\n# .vscode/\n\n# Ruff stuff:\n.ruff_cache/\n\n# PyPI configuration file\n.pypirc\n\n# Marimo\nmarimo/_static/\nmarimo/_lsp/\n__marimo__/\n\n# Streamlit\n.streamlit/secrets.toml\n\n# Cache\n**/data_cache/\n"
  },
  {
    "path": "LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright [yyyy] [name of copyright owner]\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "README.md",
    "content": "<p align=\"center\">\n  <img src=\"assets/TauricResearch.png\" style=\"width: 60%; height: auto;\">\n</p>\n\n<div align=\"center\" style=\"line-height: 1;\">\n  <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>\n  <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>\n  <a href=\"./assets/wechat.png\" target=\"_blank\"><img alt=\"WeChat\" src=\"https://img.shields.io/badge/WeChat-TauricResearch-brightgreen?logo=wechat&logoColor=white\"/></a>\n  <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>\n  <br>\n  <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>\n</div>\n\n<div align=\"center\">\n  <!-- Keep these links. Translations will automatically update with the README. -->\n  <a href=\"https://www.readme-i18n.com/TauricResearch/TradingAgents?lang=de\">Deutsch</a> | \n  <a href=\"https://www.readme-i18n.com/TauricResearch/TradingAgents?lang=es\">Español</a> | \n  <a href=\"https://www.readme-i18n.com/TauricResearch/TradingAgents?lang=fr\">français</a> | \n  <a href=\"https://www.readme-i18n.com/TauricResearch/TradingAgents?lang=ja\">日本語</a> | \n  <a href=\"https://www.readme-i18n.com/TauricResearch/TradingAgents?lang=ko\">한국어</a> | \n  <a href=\"https://www.readme-i18n.com/TauricResearch/TradingAgents?lang=pt\">Português</a> | \n  <a href=\"https://www.readme-i18n.com/TauricResearch/TradingAgents?lang=ru\">Русский</a> | \n  <a href=\"https://www.readme-i18n.com/TauricResearch/TradingAgents?lang=zh\">中文</a>\n</div>\n\n---\n\n# TradingAgents: Multi-Agents LLM Financial Trading Framework\n\n## News\n- [2026-03] **TradingAgents v0.2.1** released with GPT-5.4, Gemini 3.1, Claude 4.6 model coverage and improved system stability.\n- [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.\n- [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.\n\n<div align=\"center\">\n<a href=\"https://www.star-history.com/#TauricResearch/TradingAgents&Date\">\n <picture>\n   <source media=\"(prefers-color-scheme: dark)\" srcset=\"https://api.star-history.com/svg?repos=TauricResearch/TradingAgents&type=Date&theme=dark\" />\n   <source media=\"(prefers-color-scheme: light)\" srcset=\"https://api.star-history.com/svg?repos=TauricResearch/TradingAgents&type=Date\" />\n   <img alt=\"TradingAgents Star History\" src=\"https://api.star-history.com/svg?repos=TauricResearch/TradingAgents&type=Date\" style=\"width: 80%; height: auto;\" />\n </picture>\n</a>\n</div>\n\n> 🎉 **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.\n>\n> So we decided to fully open-source the framework. Looking forward to building impactful projects with you!\n\n<div align=\"center\">\n\n🚀 [TradingAgents](#tradingagents-framework) | ⚡ [Installation & CLI](#installation-and-cli) | 🎬 [Demo](https://www.youtube.com/watch?v=90gr5lwjIho) | 📦 [Package Usage](#tradingagents-package) | 🤝 [Contributing](#contributing) | 📄 [Citation](#citation)\n\n</div>\n\n## TradingAgents Framework\n\nTradingAgents 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.\n\n<p align=\"center\">\n  <img src=\"assets/schema.png\" style=\"width: 100%; height: auto;\">\n</p>\n\n> 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/)\n\nOur framework decomposes complex trading tasks into specialized roles. This ensures the system achieves a robust, scalable approach to market analysis and decision-making.\n\n### Analyst Team\n- Fundamentals Analyst: Evaluates company financials and performance metrics, identifying intrinsic values and potential red flags.\n- Sentiment Analyst: Analyzes social media and public sentiment using sentiment scoring algorithms to gauge short-term market mood.\n- News Analyst: Monitors global news and macroeconomic indicators, interpreting the impact of events on market conditions.\n- Technical Analyst: Utilizes technical indicators (like MACD and RSI) to detect trading patterns and forecast price movements.\n\n<p align=\"center\">\n  <img src=\"assets/analyst.png\" width=\"100%\" style=\"display: inline-block; margin: 0 2%;\">\n</p>\n\n### Researcher Team\n- 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.\n\n<p align=\"center\">\n  <img src=\"assets/researcher.png\" width=\"70%\" style=\"display: inline-block; margin: 0 2%;\">\n</p>\n\n### Trader Agent\n- 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.\n\n<p align=\"center\">\n  <img src=\"assets/trader.png\" width=\"70%\" style=\"display: inline-block; margin: 0 2%;\">\n</p>\n\n### Risk Management and Portfolio Manager\n- 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.\n- The Portfolio Manager approves/rejects the transaction proposal. If approved, the order will be sent to the simulated exchange and executed.\n\n<p align=\"center\">\n  <img src=\"assets/risk.png\" width=\"70%\" style=\"display: inline-block; margin: 0 2%;\">\n</p>\n\n## Installation and CLI\n\n### Installation\n\nClone TradingAgents:\n```bash\ngit clone https://github.com/TauricResearch/TradingAgents.git\ncd TradingAgents\n```\n\nCreate a virtual environment in any of your favorite environment managers:\n```bash\nconda create -n tradingagents python=3.13\nconda activate tradingagents\n```\n\nInstall dependencies:\n```bash\npip install -r requirements.txt\n```\n\n### Required APIs\n\nTradingAgents supports multiple LLM providers. Set the API key for your chosen provider:\n\n```bash\nexport OPENAI_API_KEY=...          # OpenAI (GPT)\nexport GOOGLE_API_KEY=...          # Google (Gemini)\nexport ANTHROPIC_API_KEY=...       # Anthropic (Claude)\nexport XAI_API_KEY=...             # xAI (Grok)\nexport OPENROUTER_API_KEY=...      # OpenRouter\nexport ALPHA_VANTAGE_API_KEY=...   # Alpha Vantage\n```\n\nFor local models, configure Ollama with `llm_provider: \"ollama\"` in your config.\n\nAlternatively, copy `.env.example` to `.env` and fill in your keys:\n```bash\ncp .env.example .env\n```\n\n### CLI Usage\n\nYou can also try out the CLI directly by running:\n```bash\npython -m cli.main\n```\nYou will see a screen where you can select your desired tickers, date, LLMs, research depth, etc.\n\n<p align=\"center\">\n  <img src=\"assets/cli/cli_init.png\" width=\"100%\" style=\"display: inline-block; margin: 0 2%;\">\n</p>\n\nAn interface will appear showing results as they load, letting you track the agent's progress as it runs.\n\n<p align=\"center\">\n  <img src=\"assets/cli/cli_news.png\" width=\"100%\" style=\"display: inline-block; margin: 0 2%;\">\n</p>\n\n<p align=\"center\">\n  <img src=\"assets/cli/cli_transaction.png\" width=\"100%\" style=\"display: inline-block; margin: 0 2%;\">\n</p>\n\n## TradingAgents Package\n\n### Implementation Details\n\nWe built TradingAgents with LangGraph to ensure flexibility and modularity. The framework supports multiple LLM providers: OpenAI, Google, Anthropic, xAI, OpenRouter, and Ollama.\n\n### Python Usage\n\nTo 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:\n\n```python\nfrom tradingagents.graph.trading_graph import TradingAgentsGraph\nfrom tradingagents.default_config import DEFAULT_CONFIG\n\nta = TradingAgentsGraph(debug=True, config=DEFAULT_CONFIG.copy())\n\n# forward propagate\n_, decision = ta.propagate(\"NVDA\", \"2026-01-15\")\nprint(decision)\n```\n\nYou can also adjust the default configuration to set your own choice of LLMs, debate rounds, etc.\n\n```python\nfrom tradingagents.graph.trading_graph import TradingAgentsGraph\nfrom tradingagents.default_config import DEFAULT_CONFIG\n\nconfig = DEFAULT_CONFIG.copy()\nconfig[\"llm_provider\"] = \"openai\"        # openai, google, anthropic, xai, openrouter, ollama\nconfig[\"deep_think_llm\"] = \"gpt-5.2\"     # Model for complex reasoning\nconfig[\"quick_think_llm\"] = \"gpt-5-mini\" # Model for quick tasks\nconfig[\"max_debate_rounds\"] = 2\n\nta = TradingAgentsGraph(debug=True, config=config)\n_, decision = ta.propagate(\"NVDA\", \"2026-01-15\")\nprint(decision)\n```\n\nSee `tradingagents/default_config.py` for all configuration options.\n\n## Contributing\n\nWe 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/).\n\n## Citation\n\nPlease reference our work if you find *TradingAgents* provides you with some help :)\n\n```\n@misc{xiao2025tradingagentsmultiagentsllmfinancial,\n      title={TradingAgents: Multi-Agents LLM Financial Trading Framework}, \n      author={Yijia Xiao and Edward Sun and Di Luo and Wei Wang},\n      year={2025},\n      eprint={2412.20138},\n      archivePrefix={arXiv},\n      primaryClass={q-fin.TR},\n      url={https://arxiv.org/abs/2412.20138}, \n}\n```\n"
  },
  {
    "path": "cli/__init__.py",
    "content": ""
  },
  {
    "path": "cli/announcements.py",
    "content": "import getpass\nimport requests\nfrom rich.console import Console\nfrom rich.panel import Panel\n\nfrom cli.config import CLI_CONFIG\n\n\ndef fetch_announcements(url: str = None, timeout: float = None) -> dict:\n    \"\"\"Fetch announcements from endpoint. Returns dict with announcements and settings.\"\"\"\n    endpoint = url or CLI_CONFIG[\"announcements_url\"]\n    timeout = timeout or CLI_CONFIG[\"announcements_timeout\"]\n    fallback = CLI_CONFIG[\"announcements_fallback\"]\n\n    try:\n        response = requests.get(endpoint, timeout=timeout)\n        response.raise_for_status()\n        data = response.json()\n        return {\n            \"announcements\": data.get(\"announcements\", [fallback]),\n            \"require_attention\": data.get(\"require_attention\", False),\n        }\n    except Exception:\n        return {\n            \"announcements\": [fallback],\n            \"require_attention\": False,\n        }\n\n\ndef display_announcements(console: Console, data: dict) -> None:\n    \"\"\"Display announcements panel. Prompts for Enter if require_attention is True.\"\"\"\n    announcements = data.get(\"announcements\", [])\n    require_attention = data.get(\"require_attention\", False)\n\n    if not announcements:\n        return\n\n    content = \"\\n\".join(announcements)\n\n    panel = Panel(\n        content,\n        border_style=\"cyan\",\n        padding=(1, 2),\n        title=\"Announcements\",\n    )\n    console.print(panel)\n\n    if require_attention:\n        getpass.getpass(\"Press Enter to continue...\")\n    else:\n        console.print()\n"
  },
  {
    "path": "cli/config.py",
    "content": "CLI_CONFIG = {\n    # Announcements\n    \"announcements_url\": \"https://api.tauric.ai/v1/announcements\",\n    \"announcements_timeout\": 1.0,\n    \"announcements_fallback\": \"[cyan]For more information, please visit[/cyan] [link=https://github.com/TauricResearch]https://github.com/TauricResearch[/link]\",\n}\n"
  },
  {
    "path": "cli/main.py",
    "content": "from typing import Optional\nimport datetime\nimport typer\nfrom pathlib import Path\nfrom functools import wraps\nfrom rich.console import Console\nfrom dotenv import load_dotenv\n\n# Load environment variables from .env file\nload_dotenv()\nfrom rich.panel import Panel\nfrom rich.spinner import Spinner\nfrom rich.live import Live\nfrom rich.columns import Columns\nfrom rich.markdown import Markdown\nfrom rich.layout import Layout\nfrom rich.text import Text\nfrom rich.table import Table\nfrom collections import deque\nimport time\nfrom rich.tree import Tree\nfrom rich import box\nfrom rich.align import Align\nfrom rich.rule import Rule\n\nfrom tradingagents.graph.trading_graph import TradingAgentsGraph\nfrom tradingagents.default_config import DEFAULT_CONFIG\nfrom cli.models import AnalystType\nfrom cli.utils import *\nfrom cli.announcements import fetch_announcements, display_announcements\nfrom cli.stats_handler import StatsCallbackHandler\n\nconsole = Console()\n\napp = typer.Typer(\n    name=\"TradingAgents\",\n    help=\"TradingAgents CLI: Multi-Agents LLM Financial Trading Framework\",\n    add_completion=True,  # Enable shell completion\n)\n\n\n# Create a deque to store recent messages with a maximum length\nclass MessageBuffer:\n    # Fixed teams that always run (not user-selectable)\n    FIXED_AGENTS = {\n        \"Research Team\": [\"Bull Researcher\", \"Bear Researcher\", \"Research Manager\"],\n        \"Trading Team\": [\"Trader\"],\n        \"Risk Management\": [\"Aggressive Analyst\", \"Neutral Analyst\", \"Conservative Analyst\"],\n        \"Portfolio Management\": [\"Portfolio Manager\"],\n    }\n\n    # Analyst name mapping\n    ANALYST_MAPPING = {\n        \"market\": \"Market Analyst\",\n        \"social\": \"Social Analyst\",\n        \"news\": \"News Analyst\",\n        \"fundamentals\": \"Fundamentals Analyst\",\n    }\n\n    # Report section mapping: section -> (analyst_key for filtering, finalizing_agent)\n    # analyst_key: which analyst selection controls this section (None = always included)\n    # finalizing_agent: which agent must be \"completed\" for this report to count as done\n    REPORT_SECTIONS = {\n        \"market_report\": (\"market\", \"Market Analyst\"),\n        \"sentiment_report\": (\"social\", \"Social Analyst\"),\n        \"news_report\": (\"news\", \"News Analyst\"),\n        \"fundamentals_report\": (\"fundamentals\", \"Fundamentals Analyst\"),\n        \"investment_plan\": (None, \"Research Manager\"),\n        \"trader_investment_plan\": (None, \"Trader\"),\n        \"final_trade_decision\": (None, \"Portfolio Manager\"),\n    }\n\n    def __init__(self, max_length=100):\n        self.messages = deque(maxlen=max_length)\n        self.tool_calls = deque(maxlen=max_length)\n        self.current_report = None\n        self.final_report = None  # Store the complete final report\n        self.agent_status = {}\n        self.current_agent = None\n        self.report_sections = {}\n        self.selected_analysts = []\n        self._last_message_id = None\n\n    def init_for_analysis(self, selected_analysts):\n        \"\"\"Initialize agent status and report sections based on selected analysts.\n\n        Args:\n            selected_analysts: List of analyst type strings (e.g., [\"market\", \"news\"])\n        \"\"\"\n        self.selected_analysts = [a.lower() for a in selected_analysts]\n\n        # Build agent_status dynamically\n        self.agent_status = {}\n\n        # Add selected analysts\n        for analyst_key in self.selected_analysts:\n            if analyst_key in self.ANALYST_MAPPING:\n                self.agent_status[self.ANALYST_MAPPING[analyst_key]] = \"pending\"\n\n        # Add fixed teams\n        for team_agents in self.FIXED_AGENTS.values():\n            for agent in team_agents:\n                self.agent_status[agent] = \"pending\"\n\n        # Build report_sections dynamically\n        self.report_sections = {}\n        for section, (analyst_key, _) in self.REPORT_SECTIONS.items():\n            if analyst_key is None or analyst_key in self.selected_analysts:\n                self.report_sections[section] = None\n\n        # Reset other state\n        self.current_report = None\n        self.final_report = None\n        self.current_agent = None\n        self.messages.clear()\n        self.tool_calls.clear()\n        self._last_message_id = None\n\n    def get_completed_reports_count(self):\n        \"\"\"Count reports that are finalized (their finalizing agent is completed).\n\n        A report is considered complete when:\n        1. The report section has content (not None), AND\n        2. The agent responsible for finalizing that report has status \"completed\"\n\n        This prevents interim updates (like debate rounds) from counting as completed.\n        \"\"\"\n        count = 0\n        for section in self.report_sections:\n            if section not in self.REPORT_SECTIONS:\n                continue\n            _, finalizing_agent = self.REPORT_SECTIONS[section]\n            # Report is complete if it has content AND its finalizing agent is done\n            has_content = self.report_sections.get(section) is not None\n            agent_done = self.agent_status.get(finalizing_agent) == \"completed\"\n            if has_content and agent_done:\n                count += 1\n        return count\n\n    def add_message(self, message_type, content):\n        timestamp = datetime.datetime.now().strftime(\"%H:%M:%S\")\n        self.messages.append((timestamp, message_type, content))\n\n    def add_tool_call(self, tool_name, args):\n        timestamp = datetime.datetime.now().strftime(\"%H:%M:%S\")\n        self.tool_calls.append((timestamp, tool_name, args))\n\n    def update_agent_status(self, agent, status):\n        if agent in self.agent_status:\n            self.agent_status[agent] = status\n            self.current_agent = agent\n\n    def update_report_section(self, section_name, content):\n        if section_name in self.report_sections:\n            self.report_sections[section_name] = content\n            self._update_current_report()\n\n    def _update_current_report(self):\n        # For the panel display, only show the most recently updated section\n        latest_section = None\n        latest_content = None\n\n        # Find the most recently updated section\n        for section, content in self.report_sections.items():\n            if content is not None:\n                latest_section = section\n                latest_content = content\n               \n        if latest_section and latest_content:\n            # Format the current section for display\n            section_titles = {\n                \"market_report\": \"Market Analysis\",\n                \"sentiment_report\": \"Social Sentiment\",\n                \"news_report\": \"News Analysis\",\n                \"fundamentals_report\": \"Fundamentals Analysis\",\n                \"investment_plan\": \"Research Team Decision\",\n                \"trader_investment_plan\": \"Trading Team Plan\",\n                \"final_trade_decision\": \"Portfolio Management Decision\",\n            }\n            self.current_report = (\n                f\"### {section_titles[latest_section]}\\n{latest_content}\"\n            )\n\n        # Update the final complete report\n        self._update_final_report()\n\n    def _update_final_report(self):\n        report_parts = []\n\n        # Analyst Team Reports - use .get() to handle missing sections\n        analyst_sections = [\"market_report\", \"sentiment_report\", \"news_report\", \"fundamentals_report\"]\n        if any(self.report_sections.get(section) for section in analyst_sections):\n            report_parts.append(\"## Analyst Team Reports\")\n            if self.report_sections.get(\"market_report\"):\n                report_parts.append(\n                    f\"### Market Analysis\\n{self.report_sections['market_report']}\"\n                )\n            if self.report_sections.get(\"sentiment_report\"):\n                report_parts.append(\n                    f\"### Social Sentiment\\n{self.report_sections['sentiment_report']}\"\n                )\n            if self.report_sections.get(\"news_report\"):\n                report_parts.append(\n                    f\"### News Analysis\\n{self.report_sections['news_report']}\"\n                )\n            if self.report_sections.get(\"fundamentals_report\"):\n                report_parts.append(\n                    f\"### Fundamentals Analysis\\n{self.report_sections['fundamentals_report']}\"\n                )\n\n        # Research Team Reports\n        if self.report_sections.get(\"investment_plan\"):\n            report_parts.append(\"## Research Team Decision\")\n            report_parts.append(f\"{self.report_sections['investment_plan']}\")\n\n        # Trading Team Reports\n        if self.report_sections.get(\"trader_investment_plan\"):\n            report_parts.append(\"## Trading Team Plan\")\n            report_parts.append(f\"{self.report_sections['trader_investment_plan']}\")\n\n        # Portfolio Management Decision\n        if self.report_sections.get(\"final_trade_decision\"):\n            report_parts.append(\"## Portfolio Management Decision\")\n            report_parts.append(f\"{self.report_sections['final_trade_decision']}\")\n\n        self.final_report = \"\\n\\n\".join(report_parts) if report_parts else None\n\n\nmessage_buffer = MessageBuffer()\n\n\ndef create_layout():\n    layout = Layout()\n    layout.split_column(\n        Layout(name=\"header\", size=3),\n        Layout(name=\"main\"),\n        Layout(name=\"footer\", size=3),\n    )\n    layout[\"main\"].split_column(\n        Layout(name=\"upper\", ratio=3), Layout(name=\"analysis\", ratio=5)\n    )\n    layout[\"upper\"].split_row(\n        Layout(name=\"progress\", ratio=2), Layout(name=\"messages\", ratio=3)\n    )\n    return layout\n\n\ndef format_tokens(n):\n    \"\"\"Format token count for display.\"\"\"\n    if n >= 1000:\n        return f\"{n/1000:.1f}k\"\n    return str(n)\n\n\ndef update_display(layout, spinner_text=None, stats_handler=None, start_time=None):\n    # Header with welcome message\n    layout[\"header\"].update(\n        Panel(\n            \"[bold green]Welcome to TradingAgents CLI[/bold green]\\n\"\n            \"[dim]© [Tauric Research](https://github.com/TauricResearch)[/dim]\",\n            title=\"Welcome to TradingAgents\",\n            border_style=\"green\",\n            padding=(1, 2),\n            expand=True,\n        )\n    )\n\n    # Progress panel showing agent status\n    progress_table = Table(\n        show_header=True,\n        header_style=\"bold magenta\",\n        show_footer=False,\n        box=box.SIMPLE_HEAD,  # Use simple header with horizontal lines\n        title=None,  # Remove the redundant Progress title\n        padding=(0, 2),  # Add horizontal padding\n        expand=True,  # Make table expand to fill available space\n    )\n    progress_table.add_column(\"Team\", style=\"cyan\", justify=\"center\", width=20)\n    progress_table.add_column(\"Agent\", style=\"green\", justify=\"center\", width=20)\n    progress_table.add_column(\"Status\", style=\"yellow\", justify=\"center\", width=20)\n\n    # Group agents by team - filter to only include agents in agent_status\n    all_teams = {\n        \"Analyst Team\": [\n            \"Market Analyst\",\n            \"Social Analyst\",\n            \"News Analyst\",\n            \"Fundamentals Analyst\",\n        ],\n        \"Research Team\": [\"Bull Researcher\", \"Bear Researcher\", \"Research Manager\"],\n        \"Trading Team\": [\"Trader\"],\n        \"Risk Management\": [\"Aggressive Analyst\", \"Neutral Analyst\", \"Conservative Analyst\"],\n        \"Portfolio Management\": [\"Portfolio Manager\"],\n    }\n\n    # Filter teams to only include agents that are in agent_status\n    teams = {}\n    for team, agents in all_teams.items():\n        active_agents = [a for a in agents if a in message_buffer.agent_status]\n        if active_agents:\n            teams[team] = active_agents\n\n    for team, agents in teams.items():\n        # Add first agent with team name\n        first_agent = agents[0]\n        status = message_buffer.agent_status.get(first_agent, \"pending\")\n        if status == \"in_progress\":\n            spinner = Spinner(\n                \"dots\", text=\"[blue]in_progress[/blue]\", style=\"bold cyan\"\n            )\n            status_cell = spinner\n        else:\n            status_color = {\n                \"pending\": \"yellow\",\n                \"completed\": \"green\",\n                \"error\": \"red\",\n            }.get(status, \"white\")\n            status_cell = f\"[{status_color}]{status}[/{status_color}]\"\n        progress_table.add_row(team, first_agent, status_cell)\n\n        # Add remaining agents in team\n        for agent in agents[1:]:\n            status = message_buffer.agent_status.get(agent, \"pending\")\n            if status == \"in_progress\":\n                spinner = Spinner(\n                    \"dots\", text=\"[blue]in_progress[/blue]\", style=\"bold cyan\"\n                )\n                status_cell = spinner\n            else:\n                status_color = {\n                    \"pending\": \"yellow\",\n                    \"completed\": \"green\",\n                    \"error\": \"red\",\n                }.get(status, \"white\")\n                status_cell = f\"[{status_color}]{status}[/{status_color}]\"\n            progress_table.add_row(\"\", agent, status_cell)\n\n        # Add horizontal line after each team\n        progress_table.add_row(\"─\" * 20, \"─\" * 20, \"─\" * 20, style=\"dim\")\n\n    layout[\"progress\"].update(\n        Panel(progress_table, title=\"Progress\", border_style=\"cyan\", padding=(1, 2))\n    )\n\n    # Messages panel showing recent messages and tool calls\n    messages_table = Table(\n        show_header=True,\n        header_style=\"bold magenta\",\n        show_footer=False,\n        expand=True,  # Make table expand to fill available space\n        box=box.MINIMAL,  # Use minimal box style for a lighter look\n        show_lines=True,  # Keep horizontal lines\n        padding=(0, 1),  # Add some padding between columns\n    )\n    messages_table.add_column(\"Time\", style=\"cyan\", width=8, justify=\"center\")\n    messages_table.add_column(\"Type\", style=\"green\", width=10, justify=\"center\")\n    messages_table.add_column(\n        \"Content\", style=\"white\", no_wrap=False, ratio=1\n    )  # Make content column expand\n\n    # Combine tool calls and messages\n    all_messages = []\n\n    # Add tool calls\n    for timestamp, tool_name, args in message_buffer.tool_calls:\n        formatted_args = format_tool_args(args)\n        all_messages.append((timestamp, \"Tool\", f\"{tool_name}: {formatted_args}\"))\n\n    # Add regular messages\n    for timestamp, msg_type, content in message_buffer.messages:\n        content_str = str(content) if content else \"\"\n        if len(content_str) > 200:\n            content_str = content_str[:197] + \"...\"\n        all_messages.append((timestamp, msg_type, content_str))\n\n    # Sort by timestamp descending (newest first)\n    all_messages.sort(key=lambda x: x[0], reverse=True)\n\n    # Calculate how many messages we can show based on available space\n    max_messages = 12\n\n    # Get the first N messages (newest ones)\n    recent_messages = all_messages[:max_messages]\n\n    # Add messages to table (already in newest-first order)\n    for timestamp, msg_type, content in recent_messages:\n        # Format content with word wrapping\n        wrapped_content = Text(content, overflow=\"fold\")\n        messages_table.add_row(timestamp, msg_type, wrapped_content)\n\n    layout[\"messages\"].update(\n        Panel(\n            messages_table,\n            title=\"Messages & Tools\",\n            border_style=\"blue\",\n            padding=(1, 2),\n        )\n    )\n\n    # Analysis panel showing current report\n    if message_buffer.current_report:\n        layout[\"analysis\"].update(\n            Panel(\n                Markdown(message_buffer.current_report),\n                title=\"Current Report\",\n                border_style=\"green\",\n                padding=(1, 2),\n            )\n        )\n    else:\n        layout[\"analysis\"].update(\n            Panel(\n                \"[italic]Waiting for analysis report...[/italic]\",\n                title=\"Current Report\",\n                border_style=\"green\",\n                padding=(1, 2),\n            )\n        )\n\n    # Footer with statistics\n    # Agent progress - derived from agent_status dict\n    agents_completed = sum(\n        1 for status in message_buffer.agent_status.values() if status == \"completed\"\n    )\n    agents_total = len(message_buffer.agent_status)\n\n    # Report progress - based on agent completion (not just content existence)\n    reports_completed = message_buffer.get_completed_reports_count()\n    reports_total = len(message_buffer.report_sections)\n\n    # Build stats parts\n    stats_parts = [f\"Agents: {agents_completed}/{agents_total}\"]\n\n    # LLM and tool stats from callback handler\n    if stats_handler:\n        stats = stats_handler.get_stats()\n        stats_parts.append(f\"LLM: {stats['llm_calls']}\")\n        stats_parts.append(f\"Tools: {stats['tool_calls']}\")\n\n        # Token display with graceful fallback\n        if stats[\"tokens_in\"] > 0 or stats[\"tokens_out\"] > 0:\n            tokens_str = f\"Tokens: {format_tokens(stats['tokens_in'])}\\u2191 {format_tokens(stats['tokens_out'])}\\u2193\"\n        else:\n            tokens_str = \"Tokens: --\"\n        stats_parts.append(tokens_str)\n\n    stats_parts.append(f\"Reports: {reports_completed}/{reports_total}\")\n\n    # Elapsed time\n    if start_time:\n        elapsed = time.time() - start_time\n        elapsed_str = f\"\\u23f1 {int(elapsed // 60):02d}:{int(elapsed % 60):02d}\"\n        stats_parts.append(elapsed_str)\n\n    stats_table = Table(show_header=False, box=None, padding=(0, 2), expand=True)\n    stats_table.add_column(\"Stats\", justify=\"center\")\n    stats_table.add_row(\" | \".join(stats_parts))\n\n    layout[\"footer\"].update(Panel(stats_table, border_style=\"grey50\"))\n\n\ndef get_user_selections():\n    \"\"\"Get all user selections before starting the analysis display.\"\"\"\n    # Display ASCII art welcome message\n    with open(\"./cli/static/welcome.txt\", \"r\", encoding=\"utf-8\") as f:\n        welcome_ascii = f.read()\n\n    # Create welcome box content\n    welcome_content = f\"{welcome_ascii}\\n\"\n    welcome_content += \"[bold green]TradingAgents: Multi-Agents LLM Financial Trading Framework - CLI[/bold green]\\n\\n\"\n    welcome_content += \"[bold]Workflow Steps:[/bold]\\n\"\n    welcome_content += \"I. Analyst Team → II. Research Team → III. Trader → IV. Risk Management → V. Portfolio Management\\n\\n\"\n    welcome_content += (\n        \"[dim]Built by [Tauric Research](https://github.com/TauricResearch)[/dim]\"\n    )\n\n    # Create and center the welcome box\n    welcome_box = Panel(\n        welcome_content,\n        border_style=\"green\",\n        padding=(1, 2),\n        title=\"Welcome to TradingAgents\",\n        subtitle=\"Multi-Agents LLM Financial Trading Framework\",\n    )\n    console.print(Align.center(welcome_box))\n    console.print()\n    console.print()  # Add vertical space before announcements\n\n    # Fetch and display announcements (silent on failure)\n    announcements = fetch_announcements()\n    display_announcements(console, announcements)\n\n    # Create a boxed questionnaire for each step\n    def create_question_box(title, prompt, default=None):\n        box_content = f\"[bold]{title}[/bold]\\n\"\n        box_content += f\"[dim]{prompt}[/dim]\"\n        if default:\n            box_content += f\"\\n[dim]Default: {default}[/dim]\"\n        return Panel(box_content, border_style=\"blue\", padding=(1, 2))\n\n    # Step 1: Ticker symbol\n    console.print(\n        create_question_box(\n            \"Step 1: Ticker Symbol\", \"Enter the ticker symbol to analyze\", \"SPY\"\n        )\n    )\n    selected_ticker = get_ticker()\n\n    # Step 2: Analysis date\n    default_date = datetime.datetime.now().strftime(\"%Y-%m-%d\")\n    console.print(\n        create_question_box(\n            \"Step 2: Analysis Date\",\n            \"Enter the analysis date (YYYY-MM-DD)\",\n            default_date,\n        )\n    )\n    analysis_date = get_analysis_date()\n\n    # Step 3: Select analysts\n    console.print(\n        create_question_box(\n            \"Step 3: Analysts Team\", \"Select your LLM analyst agents for the analysis\"\n        )\n    )\n    selected_analysts = select_analysts()\n    console.print(\n        f\"[green]Selected analysts:[/green] {', '.join(analyst.value for analyst in selected_analysts)}\"\n    )\n\n    # Step 4: Research depth\n    console.print(\n        create_question_box(\n            \"Step 4: Research Depth\", \"Select your research depth level\"\n        )\n    )\n    selected_research_depth = select_research_depth()\n\n    # Step 5: OpenAI backend\n    console.print(\n        create_question_box(\n            \"Step 5: OpenAI backend\", \"Select which service to talk to\"\n        )\n    )\n    selected_llm_provider, backend_url = select_llm_provider()\n    \n    # Step 6: Thinking agents\n    console.print(\n        create_question_box(\n            \"Step 6: Thinking Agents\", \"Select your thinking agents for analysis\"\n        )\n    )\n    selected_shallow_thinker = select_shallow_thinking_agent(selected_llm_provider)\n    selected_deep_thinker = select_deep_thinking_agent(selected_llm_provider)\n\n    # Step 7: Provider-specific thinking configuration\n    thinking_level = None\n    reasoning_effort = None\n\n    provider_lower = selected_llm_provider.lower()\n    if provider_lower == \"google\":\n        console.print(\n            create_question_box(\n                \"Step 7: Thinking Mode\",\n                \"Configure Gemini thinking mode\"\n            )\n        )\n        thinking_level = ask_gemini_thinking_config()\n    elif provider_lower == \"openai\":\n        console.print(\n            create_question_box(\n                \"Step 7: Reasoning Effort\",\n                \"Configure OpenAI reasoning effort level\"\n            )\n        )\n        reasoning_effort = ask_openai_reasoning_effort()\n\n    return {\n        \"ticker\": selected_ticker,\n        \"analysis_date\": analysis_date,\n        \"analysts\": selected_analysts,\n        \"research_depth\": selected_research_depth,\n        \"llm_provider\": selected_llm_provider.lower(),\n        \"backend_url\": backend_url,\n        \"shallow_thinker\": selected_shallow_thinker,\n        \"deep_thinker\": selected_deep_thinker,\n        \"google_thinking_level\": thinking_level,\n        \"openai_reasoning_effort\": reasoning_effort,\n    }\n\n\ndef get_ticker():\n    \"\"\"Get ticker symbol from user input.\"\"\"\n    return typer.prompt(\"\", default=\"SPY\")\n\n\ndef get_analysis_date():\n    \"\"\"Get the analysis date from user input.\"\"\"\n    while True:\n        date_str = typer.prompt(\n            \"\", default=datetime.datetime.now().strftime(\"%Y-%m-%d\")\n        )\n        try:\n            # Validate date format and ensure it's not in the future\n            analysis_date = datetime.datetime.strptime(date_str, \"%Y-%m-%d\")\n            if analysis_date.date() > datetime.datetime.now().date():\n                console.print(\"[red]Error: Analysis date cannot be in the future[/red]\")\n                continue\n            return date_str\n        except ValueError:\n            console.print(\n                \"[red]Error: Invalid date format. Please use YYYY-MM-DD[/red]\"\n            )\n\n\ndef save_report_to_disk(final_state, ticker: str, save_path: Path):\n    \"\"\"Save complete analysis report to disk with organized subfolders.\"\"\"\n    save_path.mkdir(parents=True, exist_ok=True)\n    sections = []\n\n    # 1. Analysts\n    analysts_dir = save_path / \"1_analysts\"\n    analyst_parts = []\n    if final_state.get(\"market_report\"):\n        analysts_dir.mkdir(exist_ok=True)\n        (analysts_dir / \"market.md\").write_text(final_state[\"market_report\"])\n        analyst_parts.append((\"Market Analyst\", final_state[\"market_report\"]))\n    if final_state.get(\"sentiment_report\"):\n        analysts_dir.mkdir(exist_ok=True)\n        (analysts_dir / \"sentiment.md\").write_text(final_state[\"sentiment_report\"])\n        analyst_parts.append((\"Social Analyst\", final_state[\"sentiment_report\"]))\n    if final_state.get(\"news_report\"):\n        analysts_dir.mkdir(exist_ok=True)\n        (analysts_dir / \"news.md\").write_text(final_state[\"news_report\"])\n        analyst_parts.append((\"News Analyst\", final_state[\"news_report\"]))\n    if final_state.get(\"fundamentals_report\"):\n        analysts_dir.mkdir(exist_ok=True)\n        (analysts_dir / \"fundamentals.md\").write_text(final_state[\"fundamentals_report\"])\n        analyst_parts.append((\"Fundamentals Analyst\", final_state[\"fundamentals_report\"]))\n    if analyst_parts:\n        content = \"\\n\\n\".join(f\"### {name}\\n{text}\" for name, text in analyst_parts)\n        sections.append(f\"## I. Analyst Team Reports\\n\\n{content}\")\n\n    # 2. Research\n    if final_state.get(\"investment_debate_state\"):\n        research_dir = save_path / \"2_research\"\n        debate = final_state[\"investment_debate_state\"]\n        research_parts = []\n        if debate.get(\"bull_history\"):\n            research_dir.mkdir(exist_ok=True)\n            (research_dir / \"bull.md\").write_text(debate[\"bull_history\"])\n            research_parts.append((\"Bull Researcher\", debate[\"bull_history\"]))\n        if debate.get(\"bear_history\"):\n            research_dir.mkdir(exist_ok=True)\n            (research_dir / \"bear.md\").write_text(debate[\"bear_history\"])\n            research_parts.append((\"Bear Researcher\", debate[\"bear_history\"]))\n        if debate.get(\"judge_decision\"):\n            research_dir.mkdir(exist_ok=True)\n            (research_dir / \"manager.md\").write_text(debate[\"judge_decision\"])\n            research_parts.append((\"Research Manager\", debate[\"judge_decision\"]))\n        if research_parts:\n            content = \"\\n\\n\".join(f\"### {name}\\n{text}\" for name, text in research_parts)\n            sections.append(f\"## II. Research Team Decision\\n\\n{content}\")\n\n    # 3. Trading\n    if final_state.get(\"trader_investment_plan\"):\n        trading_dir = save_path / \"3_trading\"\n        trading_dir.mkdir(exist_ok=True)\n        (trading_dir / \"trader.md\").write_text(final_state[\"trader_investment_plan\"])\n        sections.append(f\"## III. Trading Team Plan\\n\\n### Trader\\n{final_state['trader_investment_plan']}\")\n\n    # 4. Risk Management\n    if final_state.get(\"risk_debate_state\"):\n        risk_dir = save_path / \"4_risk\"\n        risk = final_state[\"risk_debate_state\"]\n        risk_parts = []\n        if risk.get(\"aggressive_history\"):\n            risk_dir.mkdir(exist_ok=True)\n            (risk_dir / \"aggressive.md\").write_text(risk[\"aggressive_history\"])\n            risk_parts.append((\"Aggressive Analyst\", risk[\"aggressive_history\"]))\n        if risk.get(\"conservative_history\"):\n            risk_dir.mkdir(exist_ok=True)\n            (risk_dir / \"conservative.md\").write_text(risk[\"conservative_history\"])\n            risk_parts.append((\"Conservative Analyst\", risk[\"conservative_history\"]))\n        if risk.get(\"neutral_history\"):\n            risk_dir.mkdir(exist_ok=True)\n            (risk_dir / \"neutral.md\").write_text(risk[\"neutral_history\"])\n            risk_parts.append((\"Neutral Analyst\", risk[\"neutral_history\"]))\n        if risk_parts:\n            content = \"\\n\\n\".join(f\"### {name}\\n{text}\" for name, text in risk_parts)\n            sections.append(f\"## IV. Risk Management Team Decision\\n\\n{content}\")\n\n        # 5. Portfolio Manager\n        if risk.get(\"judge_decision\"):\n            portfolio_dir = save_path / \"5_portfolio\"\n            portfolio_dir.mkdir(exist_ok=True)\n            (portfolio_dir / \"decision.md\").write_text(risk[\"judge_decision\"])\n            sections.append(f\"## V. Portfolio Manager Decision\\n\\n### Portfolio Manager\\n{risk['judge_decision']}\")\n\n    # Write consolidated report\n    header = f\"# Trading Analysis Report: {ticker}\\n\\nGenerated: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\\n\\n\"\n    (save_path / \"complete_report.md\").write_text(header + \"\\n\\n\".join(sections))\n    return save_path / \"complete_report.md\"\n\n\ndef display_complete_report(final_state):\n    \"\"\"Display the complete analysis report sequentially (avoids truncation).\"\"\"\n    console.print()\n    console.print(Rule(\"Complete Analysis Report\", style=\"bold green\"))\n\n    # I. Analyst Team Reports\n    analysts = []\n    if final_state.get(\"market_report\"):\n        analysts.append((\"Market Analyst\", final_state[\"market_report\"]))\n    if final_state.get(\"sentiment_report\"):\n        analysts.append((\"Social Analyst\", final_state[\"sentiment_report\"]))\n    if final_state.get(\"news_report\"):\n        analysts.append((\"News Analyst\", final_state[\"news_report\"]))\n    if final_state.get(\"fundamentals_report\"):\n        analysts.append((\"Fundamentals Analyst\", final_state[\"fundamentals_report\"]))\n    if analysts:\n        console.print(Panel(\"[bold]I. Analyst Team Reports[/bold]\", border_style=\"cyan\"))\n        for title, content in analysts:\n            console.print(Panel(Markdown(content), title=title, border_style=\"blue\", padding=(1, 2)))\n\n    # II. Research Team Reports\n    if final_state.get(\"investment_debate_state\"):\n        debate = final_state[\"investment_debate_state\"]\n        research = []\n        if debate.get(\"bull_history\"):\n            research.append((\"Bull Researcher\", debate[\"bull_history\"]))\n        if debate.get(\"bear_history\"):\n            research.append((\"Bear Researcher\", debate[\"bear_history\"]))\n        if debate.get(\"judge_decision\"):\n            research.append((\"Research Manager\", debate[\"judge_decision\"]))\n        if research:\n            console.print(Panel(\"[bold]II. Research Team Decision[/bold]\", border_style=\"magenta\"))\n            for title, content in research:\n                console.print(Panel(Markdown(content), title=title, border_style=\"blue\", padding=(1, 2)))\n\n    # III. Trading Team\n    if final_state.get(\"trader_investment_plan\"):\n        console.print(Panel(\"[bold]III. Trading Team Plan[/bold]\", border_style=\"yellow\"))\n        console.print(Panel(Markdown(final_state[\"trader_investment_plan\"]), title=\"Trader\", border_style=\"blue\", padding=(1, 2)))\n\n    # IV. Risk Management Team\n    if final_state.get(\"risk_debate_state\"):\n        risk = final_state[\"risk_debate_state\"]\n        risk_reports = []\n        if risk.get(\"aggressive_history\"):\n            risk_reports.append((\"Aggressive Analyst\", risk[\"aggressive_history\"]))\n        if risk.get(\"conservative_history\"):\n            risk_reports.append((\"Conservative Analyst\", risk[\"conservative_history\"]))\n        if risk.get(\"neutral_history\"):\n            risk_reports.append((\"Neutral Analyst\", risk[\"neutral_history\"]))\n        if risk_reports:\n            console.print(Panel(\"[bold]IV. Risk Management Team Decision[/bold]\", border_style=\"red\"))\n            for title, content in risk_reports:\n                console.print(Panel(Markdown(content), title=title, border_style=\"blue\", padding=(1, 2)))\n\n        # V. Portfolio Manager Decision\n        if risk.get(\"judge_decision\"):\n            console.print(Panel(\"[bold]V. Portfolio Manager Decision[/bold]\", border_style=\"green\"))\n            console.print(Panel(Markdown(risk[\"judge_decision\"]), title=\"Portfolio Manager\", border_style=\"blue\", padding=(1, 2)))\n\n\ndef update_research_team_status(status):\n    \"\"\"Update status for research team members (not Trader).\"\"\"\n    research_team = [\"Bull Researcher\", \"Bear Researcher\", \"Research Manager\"]\n    for agent in research_team:\n        message_buffer.update_agent_status(agent, status)\n\n\n# Ordered list of analysts for status transitions\nANALYST_ORDER = [\"market\", \"social\", \"news\", \"fundamentals\"]\nANALYST_AGENT_NAMES = {\n    \"market\": \"Market Analyst\",\n    \"social\": \"Social Analyst\",\n    \"news\": \"News Analyst\",\n    \"fundamentals\": \"Fundamentals Analyst\",\n}\nANALYST_REPORT_MAP = {\n    \"market\": \"market_report\",\n    \"social\": \"sentiment_report\",\n    \"news\": \"news_report\",\n    \"fundamentals\": \"fundamentals_report\",\n}\n\n\ndef update_analyst_statuses(message_buffer, chunk):\n    \"\"\"Update all analyst statuses based on current report state.\n\n    Logic:\n    - Analysts with reports = completed\n    - First analyst without report = in_progress\n    - Remaining analysts without reports = pending\n    - When all analysts done, set Bull Researcher to in_progress\n    \"\"\"\n    selected = message_buffer.selected_analysts\n    found_active = False\n\n    for analyst_key in ANALYST_ORDER:\n        if analyst_key not in selected:\n            continue\n\n        agent_name = ANALYST_AGENT_NAMES[analyst_key]\n        report_key = ANALYST_REPORT_MAP[analyst_key]\n        has_report = bool(chunk.get(report_key))\n\n        if has_report:\n            message_buffer.update_agent_status(agent_name, \"completed\")\n            message_buffer.update_report_section(report_key, chunk[report_key])\n        elif not found_active:\n            message_buffer.update_agent_status(agent_name, \"in_progress\")\n            found_active = True\n        else:\n            message_buffer.update_agent_status(agent_name, \"pending\")\n\n    # When all analysts complete, transition research team to in_progress\n    if not found_active and selected:\n        if message_buffer.agent_status.get(\"Bull Researcher\") == \"pending\":\n            message_buffer.update_agent_status(\"Bull Researcher\", \"in_progress\")\n\ndef extract_content_string(content):\n    \"\"\"Extract string content from various message formats.\n    Returns None if no meaningful text content is found.\n    \"\"\"\n    import ast\n\n    def is_empty(val):\n        \"\"\"Check if value is empty using Python's truthiness.\"\"\"\n        if val is None or val == '':\n            return True\n        if isinstance(val, str):\n            s = val.strip()\n            if not s:\n                return True\n            try:\n                return not bool(ast.literal_eval(s))\n            except (ValueError, SyntaxError):\n                return False  # Can't parse = real text\n        return not bool(val)\n\n    if is_empty(content):\n        return None\n\n    if isinstance(content, str):\n        return content.strip()\n\n    if isinstance(content, dict):\n        text = content.get('text', '')\n        return text.strip() if not is_empty(text) else None\n\n    if isinstance(content, list):\n        text_parts = [\n            item.get('text', '').strip() if isinstance(item, dict) and item.get('type') == 'text'\n            else (item.strip() if isinstance(item, str) else '')\n            for item in content\n        ]\n        result = ' '.join(t for t in text_parts if t and not is_empty(t))\n        return result if result else None\n\n    return str(content).strip() if not is_empty(content) else None\n\n\ndef classify_message_type(message) -> tuple[str, str | None]:\n    \"\"\"Classify LangChain message into display type and extract content.\n\n    Returns:\n        (type, content) - type is one of: User, Agent, Data, Control\n                        - content is extracted string or None\n    \"\"\"\n    from langchain_core.messages import AIMessage, HumanMessage, ToolMessage\n\n    content = extract_content_string(getattr(message, 'content', None))\n\n    if isinstance(message, HumanMessage):\n        if content and content.strip() == \"Continue\":\n            return (\"Control\", content)\n        return (\"User\", content)\n\n    if isinstance(message, ToolMessage):\n        return (\"Data\", content)\n\n    if isinstance(message, AIMessage):\n        return (\"Agent\", content)\n\n    # Fallback for unknown types\n    return (\"System\", content)\n\n\ndef format_tool_args(args, max_length=80) -> str:\n    \"\"\"Format tool arguments for terminal display.\"\"\"\n    result = str(args)\n    if len(result) > max_length:\n        return result[:max_length - 3] + \"...\"\n    return result\n\ndef run_analysis():\n    # First get all user selections\n    selections = get_user_selections()\n\n    # Create config with selected research depth\n    config = DEFAULT_CONFIG.copy()\n    config[\"max_debate_rounds\"] = selections[\"research_depth\"]\n    config[\"max_risk_discuss_rounds\"] = selections[\"research_depth\"]\n    config[\"quick_think_llm\"] = selections[\"shallow_thinker\"]\n    config[\"deep_think_llm\"] = selections[\"deep_thinker\"]\n    config[\"backend_url\"] = selections[\"backend_url\"]\n    config[\"llm_provider\"] = selections[\"llm_provider\"].lower()\n    # Provider-specific thinking configuration\n    config[\"google_thinking_level\"] = selections.get(\"google_thinking_level\")\n    config[\"openai_reasoning_effort\"] = selections.get(\"openai_reasoning_effort\")\n\n    # Create stats callback handler for tracking LLM/tool calls\n    stats_handler = StatsCallbackHandler()\n\n    # Normalize analyst selection to predefined order (selection is a 'set', order is fixed)\n    selected_set = {analyst.value for analyst in selections[\"analysts\"]}\n    selected_analyst_keys = [a for a in ANALYST_ORDER if a in selected_set]\n\n    # Initialize the graph with callbacks bound to LLMs\n    graph = TradingAgentsGraph(\n        selected_analyst_keys,\n        config=config,\n        debug=True,\n        callbacks=[stats_handler],\n    )\n\n    # Initialize message buffer with selected analysts\n    message_buffer.init_for_analysis(selected_analyst_keys)\n\n    # Track start time for elapsed display\n    start_time = time.time()\n\n    # Create result directory\n    results_dir = Path(config[\"results_dir\"]) / selections[\"ticker\"] / selections[\"analysis_date\"]\n    results_dir.mkdir(parents=True, exist_ok=True)\n    report_dir = results_dir / \"reports\"\n    report_dir.mkdir(parents=True, exist_ok=True)\n    log_file = results_dir / \"message_tool.log\"\n    log_file.touch(exist_ok=True)\n\n    def save_message_decorator(obj, func_name):\n        func = getattr(obj, func_name)\n        @wraps(func)\n        def wrapper(*args, **kwargs):\n            func(*args, **kwargs)\n            timestamp, message_type, content = obj.messages[-1]\n            content = content.replace(\"\\n\", \" \")  # Replace newlines with spaces\n            with open(log_file, \"a\", encoding=\"utf-8\") as f:\n                f.write(f\"{timestamp} [{message_type}] {content}\\n\")\n        return wrapper\n    \n    def save_tool_call_decorator(obj, func_name):\n        func = getattr(obj, func_name)\n        @wraps(func)\n        def wrapper(*args, **kwargs):\n            func(*args, **kwargs)\n            timestamp, tool_name, args = obj.tool_calls[-1]\n            args_str = \", \".join(f\"{k}={v}\" for k, v in args.items())\n            with open(log_file, \"a\", encoding=\"utf-8\") as f:\n                f.write(f\"{timestamp} [Tool Call] {tool_name}({args_str})\\n\")\n        return wrapper\n\n    def save_report_section_decorator(obj, func_name):\n        func = getattr(obj, func_name)\n        @wraps(func)\n        def wrapper(section_name, content):\n            func(section_name, content)\n            if section_name in obj.report_sections and obj.report_sections[section_name] is not None:\n                content = obj.report_sections[section_name]\n                if content:\n                    file_name = f\"{section_name}.md\"\n                    with open(report_dir / file_name, \"w\", encoding=\"utf-8\") as f:\n                        f.write(content)\n        return wrapper\n\n    message_buffer.add_message = save_message_decorator(message_buffer, \"add_message\")\n    message_buffer.add_tool_call = save_tool_call_decorator(message_buffer, \"add_tool_call\")\n    message_buffer.update_report_section = save_report_section_decorator(message_buffer, \"update_report_section\")\n\n    # Now start the display layout\n    layout = create_layout()\n\n    with Live(layout, refresh_per_second=4) as live:\n        # Initial display\n        update_display(layout, stats_handler=stats_handler, start_time=start_time)\n\n        # Add initial messages\n        message_buffer.add_message(\"System\", f\"Selected ticker: {selections['ticker']}\")\n        message_buffer.add_message(\n            \"System\", f\"Analysis date: {selections['analysis_date']}\"\n        )\n        message_buffer.add_message(\n            \"System\",\n            f\"Selected analysts: {', '.join(analyst.value for analyst in selections['analysts'])}\",\n        )\n        update_display(layout, stats_handler=stats_handler, start_time=start_time)\n\n        # Update agent status to in_progress for the first analyst\n        first_analyst = f\"{selections['analysts'][0].value.capitalize()} Analyst\"\n        message_buffer.update_agent_status(first_analyst, \"in_progress\")\n        update_display(layout, stats_handler=stats_handler, start_time=start_time)\n\n        # Create spinner text\n        spinner_text = (\n            f\"Analyzing {selections['ticker']} on {selections['analysis_date']}...\"\n        )\n        update_display(layout, spinner_text, stats_handler=stats_handler, start_time=start_time)\n\n        # Initialize state and get graph args with callbacks\n        init_agent_state = graph.propagator.create_initial_state(\n            selections[\"ticker\"], selections[\"analysis_date\"]\n        )\n        # Pass callbacks to graph config for tool execution tracking\n        # (LLM tracking is handled separately via LLM constructor)\n        args = graph.propagator.get_graph_args(callbacks=[stats_handler])\n\n        # Stream the analysis\n        trace = []\n        for chunk in graph.graph.stream(init_agent_state, **args):\n            # Process messages if present (skip duplicates via message ID)\n            if len(chunk[\"messages\"]) > 0:\n                last_message = chunk[\"messages\"][-1]\n                msg_id = getattr(last_message, \"id\", None)\n\n                if msg_id != message_buffer._last_message_id:\n                    message_buffer._last_message_id = msg_id\n\n                    # Add message to buffer\n                    msg_type, content = classify_message_type(last_message)\n                    if content and content.strip():\n                        message_buffer.add_message(msg_type, content)\n\n                    # Handle tool calls\n                    if hasattr(last_message, \"tool_calls\") and last_message.tool_calls:\n                        for tool_call in last_message.tool_calls:\n                            if isinstance(tool_call, dict):\n                                message_buffer.add_tool_call(\n                                    tool_call[\"name\"], tool_call[\"args\"]\n                                )\n                            else:\n                                message_buffer.add_tool_call(tool_call.name, tool_call.args)\n\n            # Update analyst statuses based on report state (runs on every chunk)\n            update_analyst_statuses(message_buffer, chunk)\n\n            # Research Team - Handle Investment Debate State\n            if chunk.get(\"investment_debate_state\"):\n                debate_state = chunk[\"investment_debate_state\"]\n                bull_hist = debate_state.get(\"bull_history\", \"\").strip()\n                bear_hist = debate_state.get(\"bear_history\", \"\").strip()\n                judge = debate_state.get(\"judge_decision\", \"\").strip()\n\n                # Only update status when there's actual content\n                if bull_hist or bear_hist:\n                    update_research_team_status(\"in_progress\")\n                if bull_hist:\n                    message_buffer.update_report_section(\n                        \"investment_plan\", f\"### Bull Researcher Analysis\\n{bull_hist}\"\n                    )\n                if bear_hist:\n                    message_buffer.update_report_section(\n                        \"investment_plan\", f\"### Bear Researcher Analysis\\n{bear_hist}\"\n                    )\n                if judge:\n                    message_buffer.update_report_section(\n                        \"investment_plan\", f\"### Research Manager Decision\\n{judge}\"\n                    )\n                    update_research_team_status(\"completed\")\n                    message_buffer.update_agent_status(\"Trader\", \"in_progress\")\n\n            # Trading Team\n            if chunk.get(\"trader_investment_plan\"):\n                message_buffer.update_report_section(\n                    \"trader_investment_plan\", chunk[\"trader_investment_plan\"]\n                )\n                if message_buffer.agent_status.get(\"Trader\") != \"completed\":\n                    message_buffer.update_agent_status(\"Trader\", \"completed\")\n                    message_buffer.update_agent_status(\"Aggressive Analyst\", \"in_progress\")\n\n            # Risk Management Team - Handle Risk Debate State\n            if chunk.get(\"risk_debate_state\"):\n                risk_state = chunk[\"risk_debate_state\"]\n                agg_hist = risk_state.get(\"aggressive_history\", \"\").strip()\n                con_hist = risk_state.get(\"conservative_history\", \"\").strip()\n                neu_hist = risk_state.get(\"neutral_history\", \"\").strip()\n                judge = risk_state.get(\"judge_decision\", \"\").strip()\n\n                if agg_hist:\n                    if message_buffer.agent_status.get(\"Aggressive Analyst\") != \"completed\":\n                        message_buffer.update_agent_status(\"Aggressive Analyst\", \"in_progress\")\n                    message_buffer.update_report_section(\n                        \"final_trade_decision\", f\"### Aggressive Analyst Analysis\\n{agg_hist}\"\n                    )\n                if con_hist:\n                    if message_buffer.agent_status.get(\"Conservative Analyst\") != \"completed\":\n                        message_buffer.update_agent_status(\"Conservative Analyst\", \"in_progress\")\n                    message_buffer.update_report_section(\n                        \"final_trade_decision\", f\"### Conservative Analyst Analysis\\n{con_hist}\"\n                    )\n                if neu_hist:\n                    if message_buffer.agent_status.get(\"Neutral Analyst\") != \"completed\":\n                        message_buffer.update_agent_status(\"Neutral Analyst\", \"in_progress\")\n                    message_buffer.update_report_section(\n                        \"final_trade_decision\", f\"### Neutral Analyst Analysis\\n{neu_hist}\"\n                    )\n                if judge:\n                    if message_buffer.agent_status.get(\"Portfolio Manager\") != \"completed\":\n                        message_buffer.update_agent_status(\"Portfolio Manager\", \"in_progress\")\n                        message_buffer.update_report_section(\n                            \"final_trade_decision\", f\"### Portfolio Manager Decision\\n{judge}\"\n                        )\n                        message_buffer.update_agent_status(\"Aggressive Analyst\", \"completed\")\n                        message_buffer.update_agent_status(\"Conservative Analyst\", \"completed\")\n                        message_buffer.update_agent_status(\"Neutral Analyst\", \"completed\")\n                        message_buffer.update_agent_status(\"Portfolio Manager\", \"completed\")\n\n            # Update the display\n            update_display(layout, stats_handler=stats_handler, start_time=start_time)\n\n            trace.append(chunk)\n\n        # Get final state and decision\n        final_state = trace[-1]\n        decision = graph.process_signal(final_state[\"final_trade_decision\"])\n\n        # Update all agent statuses to completed\n        for agent in message_buffer.agent_status:\n            message_buffer.update_agent_status(agent, \"completed\")\n\n        message_buffer.add_message(\n            \"System\", f\"Completed analysis for {selections['analysis_date']}\"\n        )\n\n        # Update final report sections\n        for section in message_buffer.report_sections.keys():\n            if section in final_state:\n                message_buffer.update_report_section(section, final_state[section])\n\n        update_display(layout, stats_handler=stats_handler, start_time=start_time)\n\n    # Post-analysis prompts (outside Live context for clean interaction)\n    console.print(\"\\n[bold cyan]Analysis Complete![/bold cyan]\\n\")\n\n    # Prompt to save report\n    save_choice = typer.prompt(\"Save report?\", default=\"Y\").strip().upper()\n    if save_choice in (\"Y\", \"YES\", \"\"):\n        timestamp = datetime.datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n        default_path = Path.cwd() / \"reports\" / f\"{selections['ticker']}_{timestamp}\"\n        save_path_str = typer.prompt(\n            \"Save path (press Enter for default)\",\n            default=str(default_path)\n        ).strip()\n        save_path = Path(save_path_str)\n        try:\n            report_file = save_report_to_disk(final_state, selections[\"ticker\"], save_path)\n            console.print(f\"\\n[green]✓ Report saved to:[/green] {save_path.resolve()}\")\n            console.print(f\"  [dim]Complete report:[/dim] {report_file.name}\")\n        except Exception as e:\n            console.print(f\"[red]Error saving report: {e}[/red]\")\n\n    # Prompt to display full report\n    display_choice = typer.prompt(\"\\nDisplay full report on screen?\", default=\"Y\").strip().upper()\n    if display_choice in (\"Y\", \"YES\", \"\"):\n        display_complete_report(final_state)\n\n\n@app.command()\ndef analyze():\n    run_analysis()\n\n\nif __name__ == \"__main__\":\n    app()\n"
  },
  {
    "path": "cli/models.py",
    "content": "from enum import Enum\nfrom typing import List, Optional, Dict\nfrom pydantic import BaseModel\n\n\nclass AnalystType(str, Enum):\n    MARKET = \"market\"\n    SOCIAL = \"social\"\n    NEWS = \"news\"\n    FUNDAMENTALS = \"fundamentals\"\n"
  },
  {
    "path": "cli/static/welcome.txt",
    "content": "\n  ______               ___             ___                    __      \n /_  __/________ _____/ (_)___  ____ _/   | ____ ____  ____  / /______\n  / / / ___/ __ `/ __  / / __ \\/ __ `/ /| |/ __ `/ _ \\/ __ \\/ __/ ___/\n / / / /  / /_/ / /_/ / / / / / /_/ / ___ / /_/ /  __/ / / / /_(__  ) \n/_/ /_/   \\__,_/\\__,_/_/_/ /_/\\__, /_/  |_\\__, /\\___/_/ /_/\\__/____/  \n                             /____/      /____/                       \n"
  },
  {
    "path": "cli/stats_handler.py",
    "content": "import threading\nfrom typing import Any, Dict, List, Union\n\nfrom langchain_core.callbacks import BaseCallbackHandler\nfrom langchain_core.outputs import LLMResult\nfrom langchain_core.messages import AIMessage\n\n\nclass StatsCallbackHandler(BaseCallbackHandler):\n    \"\"\"Callback handler that tracks LLM calls, tool calls, and token usage.\"\"\"\n\n    def __init__(self) -> None:\n        super().__init__()\n        self._lock = threading.Lock()\n        self.llm_calls = 0\n        self.tool_calls = 0\n        self.tokens_in = 0\n        self.tokens_out = 0\n\n    def on_llm_start(\n        self,\n        serialized: Dict[str, Any],\n        prompts: List[str],\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Increment LLM call counter when an LLM starts.\"\"\"\n        with self._lock:\n            self.llm_calls += 1\n\n    def on_chat_model_start(\n        self,\n        serialized: Dict[str, Any],\n        messages: List[List[Any]],\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Increment LLM call counter when a chat model starts.\"\"\"\n        with self._lock:\n            self.llm_calls += 1\n\n    def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:\n        \"\"\"Extract token usage from LLM response.\"\"\"\n        try:\n            generation = response.generations[0][0]\n        except (IndexError, TypeError):\n            return\n\n        usage_metadata = None\n        if hasattr(generation, \"message\"):\n            message = generation.message\n            if isinstance(message, AIMessage) and hasattr(message, \"usage_metadata\"):\n                usage_metadata = message.usage_metadata\n\n        if usage_metadata:\n            with self._lock:\n                self.tokens_in += usage_metadata.get(\"input_tokens\", 0)\n                self.tokens_out += usage_metadata.get(\"output_tokens\", 0)\n\n    def on_tool_start(\n        self,\n        serialized: Dict[str, Any],\n        input_str: str,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Increment tool call counter when a tool starts.\"\"\"\n        with self._lock:\n            self.tool_calls += 1\n\n    def get_stats(self) -> Dict[str, Any]:\n        \"\"\"Return current statistics.\"\"\"\n        with self._lock:\n            return {\n                \"llm_calls\": self.llm_calls,\n                \"tool_calls\": self.tool_calls,\n                \"tokens_in\": self.tokens_in,\n                \"tokens_out\": self.tokens_out,\n            }\n"
  },
  {
    "path": "cli/utils.py",
    "content": "import questionary\nfrom typing import List, Optional, Tuple, Dict\n\nfrom rich.console import Console\n\nfrom cli.models import AnalystType\n\nconsole = Console()\n\nANALYST_ORDER = [\n    (\"Market Analyst\", AnalystType.MARKET),\n    (\"Social Media Analyst\", AnalystType.SOCIAL),\n    (\"News Analyst\", AnalystType.NEWS),\n    (\"Fundamentals Analyst\", AnalystType.FUNDAMENTALS),\n]\n\n\ndef get_ticker() -> str:\n    \"\"\"Prompt the user to enter a ticker symbol.\"\"\"\n    ticker = questionary.text(\n        \"Enter the ticker symbol to analyze:\",\n        validate=lambda x: len(x.strip()) > 0 or \"Please enter a valid ticker symbol.\",\n        style=questionary.Style(\n            [\n                (\"text\", \"fg:green\"),\n                (\"highlighted\", \"noinherit\"),\n            ]\n        ),\n    ).ask()\n\n    if not ticker:\n        console.print(\"\\n[red]No ticker symbol provided. Exiting...[/red]\")\n        exit(1)\n\n    return ticker.strip().upper()\n\n\ndef get_analysis_date() -> str:\n    \"\"\"Prompt the user to enter a date in YYYY-MM-DD format.\"\"\"\n    import re\n    from datetime import datetime\n\n    def validate_date(date_str: str) -> bool:\n        if not re.match(r\"^\\d{4}-\\d{2}-\\d{2}$\", date_str):\n            return False\n        try:\n            datetime.strptime(date_str, \"%Y-%m-%d\")\n            return True\n        except ValueError:\n            return False\n\n    date = questionary.text(\n        \"Enter the analysis date (YYYY-MM-DD):\",\n        validate=lambda x: validate_date(x.strip())\n        or \"Please enter a valid date in YYYY-MM-DD format.\",\n        style=questionary.Style(\n            [\n                (\"text\", \"fg:green\"),\n                (\"highlighted\", \"noinherit\"),\n            ]\n        ),\n    ).ask()\n\n    if not date:\n        console.print(\"\\n[red]No date provided. Exiting...[/red]\")\n        exit(1)\n\n    return date.strip()\n\n\ndef select_analysts() -> List[AnalystType]:\n    \"\"\"Select analysts using an interactive checkbox.\"\"\"\n    choices = questionary.checkbox(\n        \"Select Your [Analysts Team]:\",\n        choices=[\n            questionary.Choice(display, value=value) for display, value in ANALYST_ORDER\n        ],\n        instruction=\"\\n- Press Space to select/unselect analysts\\n- Press 'a' to select/unselect all\\n- Press Enter when done\",\n        validate=lambda x: len(x) > 0 or \"You must select at least one analyst.\",\n        style=questionary.Style(\n            [\n                (\"checkbox-selected\", \"fg:green\"),\n                (\"selected\", \"fg:green noinherit\"),\n                (\"highlighted\", \"noinherit\"),\n                (\"pointer\", \"noinherit\"),\n            ]\n        ),\n    ).ask()\n\n    if not choices:\n        console.print(\"\\n[red]No analysts selected. Exiting...[/red]\")\n        exit(1)\n\n    return choices\n\n\ndef select_research_depth() -> int:\n    \"\"\"Select research depth using an interactive selection.\"\"\"\n\n    # Define research depth options with their corresponding values\n    DEPTH_OPTIONS = [\n        (\"Shallow - Quick research, few debate and strategy discussion rounds\", 1),\n        (\"Medium - Middle ground, moderate debate rounds and strategy discussion\", 3),\n        (\"Deep - Comprehensive research, in depth debate and strategy discussion\", 5),\n    ]\n\n    choice = questionary.select(\n        \"Select Your [Research Depth]:\",\n        choices=[\n            questionary.Choice(display, value=value) for display, value in DEPTH_OPTIONS\n        ],\n        instruction=\"\\n- Use arrow keys to navigate\\n- Press Enter to select\",\n        style=questionary.Style(\n            [\n                (\"selected\", \"fg:yellow noinherit\"),\n                (\"highlighted\", \"fg:yellow noinherit\"),\n                (\"pointer\", \"fg:yellow noinherit\"),\n            ]\n        ),\n    ).ask()\n\n    if choice is None:\n        console.print(\"\\n[red]No research depth selected. Exiting...[/red]\")\n        exit(1)\n\n    return choice\n\n\ndef select_shallow_thinking_agent(provider) -> str:\n    \"\"\"Select shallow thinking llm engine using an interactive selection.\"\"\"\n\n    # Define shallow thinking llm engine options with their corresponding model names\n    # Ordering: medium → light → heavy (balanced first for quick tasks)\n    # Within same tier, newer models first\n    SHALLOW_AGENT_OPTIONS = {\n        \"openai\": [\n            (\"GPT-5 Mini - Balanced speed, cost, and capability\", \"gpt-5-mini\"),\n            (\"GPT-5 Nano - High-throughput, simple tasks\", \"gpt-5-nano\"),\n            (\"GPT-5.4 - Latest frontier, 1M context\", \"gpt-5.4\"),\n            (\"GPT-4.1 - Smartest non-reasoning model\", \"gpt-4.1\"),\n        ],\n        \"anthropic\": [\n            (\"Claude Sonnet 4.6 - Best speed and intelligence balance\", \"claude-sonnet-4-6\"),\n            (\"Claude Haiku 4.5 - Fast, near-instant responses\", \"claude-haiku-4-5\"),\n            (\"Claude Sonnet 4.5 - Agents and coding\", \"claude-sonnet-4-5\"),\n        ],\n        \"google\": [\n            (\"Gemini 3 Flash - Next-gen fast\", \"gemini-3-flash-preview\"),\n            (\"Gemini 2.5 Flash - Balanced, stable\", \"gemini-2.5-flash\"),\n            (\"Gemini 3.1 Flash Lite - Most cost-efficient\", \"gemini-3.1-flash-lite-preview\"),\n            (\"Gemini 2.5 Flash Lite - Fast, low-cost\", \"gemini-2.5-flash-lite\"),\n        ],\n        \"xai\": [\n            (\"Grok 4.1 Fast (Non-Reasoning) - Speed optimized, 2M ctx\", \"grok-4-1-fast-non-reasoning\"),\n            (\"Grok 4 Fast (Non-Reasoning) - Speed optimized\", \"grok-4-fast-non-reasoning\"),\n            (\"Grok 4.1 Fast (Reasoning) - High-performance, 2M ctx\", \"grok-4-1-fast-reasoning\"),\n        ],\n        \"openrouter\": [\n            (\"NVIDIA Nemotron 3 Nano 30B (free)\", \"nvidia/nemotron-3-nano-30b-a3b:free\"),\n            (\"Z.AI GLM 4.5 Air (free)\", \"z-ai/glm-4.5-air:free\"),\n        ],\n        \"ollama\": [\n            (\"Qwen3:latest (8B, local)\", \"qwen3:latest\"),\n            (\"GPT-OSS:latest (20B, local)\", \"gpt-oss:latest\"),\n            (\"GLM-4.7-Flash:latest (30B, local)\", \"glm-4.7-flash:latest\"),\n        ],\n    }\n\n    choice = questionary.select(\n        \"Select Your [Quick-Thinking LLM Engine]:\",\n        choices=[\n            questionary.Choice(display, value=value)\n            for display, value in SHALLOW_AGENT_OPTIONS[provider.lower()]\n        ],\n        instruction=\"\\n- Use arrow keys to navigate\\n- Press Enter to select\",\n        style=questionary.Style(\n            [\n                (\"selected\", \"fg:magenta noinherit\"),\n                (\"highlighted\", \"fg:magenta noinherit\"),\n                (\"pointer\", \"fg:magenta noinherit\"),\n            ]\n        ),\n    ).ask()\n\n    if choice is None:\n        console.print(\n            \"\\n[red]No shallow thinking llm engine selected. Exiting...[/red]\"\n        )\n        exit(1)\n\n    return choice\n\n\ndef select_deep_thinking_agent(provider) -> str:\n    \"\"\"Select deep thinking llm engine using an interactive selection.\"\"\"\n\n    # Define deep thinking llm engine options with their corresponding model names\n    # Ordering: heavy → medium → light (most capable first for deep tasks)\n    # Within same tier, newer models first\n    DEEP_AGENT_OPTIONS = {\n        \"openai\": [\n            (\"GPT-5.4 - Latest frontier, 1M context\", \"gpt-5.4\"),\n            (\"GPT-5.2 - Strong reasoning, cost-effective\", \"gpt-5.2\"),\n            (\"GPT-5 Mini - Balanced speed, cost, and capability\", \"gpt-5-mini\"),\n            (\"GPT-5.4 Pro - Most capable, expensive ($30/$180 per 1M tokens)\", \"gpt-5.4-pro\"),\n        ],\n        \"anthropic\": [\n            (\"Claude Opus 4.6 - Most intelligent, agents and coding\", \"claude-opus-4-6\"),\n            (\"Claude Opus 4.5 - Premium, max intelligence\", \"claude-opus-4-5\"),\n            (\"Claude Sonnet 4.6 - Best speed and intelligence balance\", \"claude-sonnet-4-6\"),\n            (\"Claude Sonnet 4.5 - Agents and coding\", \"claude-sonnet-4-5\"),\n        ],\n        \"google\": [\n            (\"Gemini 3.1 Pro - Reasoning-first, complex workflows\", \"gemini-3.1-pro-preview\"),\n            (\"Gemini 3 Flash - Next-gen fast\", \"gemini-3-flash-preview\"),\n            (\"Gemini 2.5 Pro - Stable pro model\", \"gemini-2.5-pro\"),\n            (\"Gemini 2.5 Flash - Balanced, stable\", \"gemini-2.5-flash\"),\n        ],\n        \"xai\": [\n            (\"Grok 4 - Flagship model\", \"grok-4-0709\"),\n            (\"Grok 4.1 Fast (Reasoning) - High-performance, 2M ctx\", \"grok-4-1-fast-reasoning\"),\n            (\"Grok 4 Fast (Reasoning) - High-performance\", \"grok-4-fast-reasoning\"),\n            (\"Grok 4.1 Fast (Non-Reasoning) - Speed optimized, 2M ctx\", \"grok-4-1-fast-non-reasoning\"),\n        ],\n        \"openrouter\": [\n            (\"Z.AI GLM 4.5 Air (free)\", \"z-ai/glm-4.5-air:free\"),\n            (\"NVIDIA Nemotron 3 Nano 30B (free)\", \"nvidia/nemotron-3-nano-30b-a3b:free\"),\n        ],\n        \"ollama\": [\n            (\"GLM-4.7-Flash:latest (30B, local)\", \"glm-4.7-flash:latest\"),\n            (\"GPT-OSS:latest (20B, local)\", \"gpt-oss:latest\"),\n            (\"Qwen3:latest (8B, local)\", \"qwen3:latest\"),\n        ],\n    }\n\n    choice = questionary.select(\n        \"Select Your [Deep-Thinking LLM Engine]:\",\n        choices=[\n            questionary.Choice(display, value=value)\n            for display, value in DEEP_AGENT_OPTIONS[provider.lower()]\n        ],\n        instruction=\"\\n- Use arrow keys to navigate\\n- Press Enter to select\",\n        style=questionary.Style(\n            [\n                (\"selected\", \"fg:magenta noinherit\"),\n                (\"highlighted\", \"fg:magenta noinherit\"),\n                (\"pointer\", \"fg:magenta noinherit\"),\n            ]\n        ),\n    ).ask()\n\n    if choice is None:\n        console.print(\"\\n[red]No deep thinking llm engine selected. Exiting...[/red]\")\n        exit(1)\n\n    return choice\n\ndef select_llm_provider() -> tuple[str, str]:\n    \"\"\"Select the OpenAI api url using interactive selection.\"\"\"\n    # Define OpenAI api options with their corresponding endpoints\n    BASE_URLS = [\n        (\"OpenAI\", \"https://api.openai.com/v1\"),\n        (\"Google\", \"https://generativelanguage.googleapis.com/v1\"),\n        (\"Anthropic\", \"https://api.anthropic.com/\"),\n        (\"xAI\", \"https://api.x.ai/v1\"),\n        (\"Openrouter\", \"https://openrouter.ai/api/v1\"),\n        (\"Ollama\", \"http://localhost:11434/v1\"),\n    ]\n    \n    choice = questionary.select(\n        \"Select your LLM Provider:\",\n        choices=[\n            questionary.Choice(display, value=(display, value))\n            for display, value in BASE_URLS\n        ],\n        instruction=\"\\n- Use arrow keys to navigate\\n- Press Enter to select\",\n        style=questionary.Style(\n            [\n                (\"selected\", \"fg:magenta noinherit\"),\n                (\"highlighted\", \"fg:magenta noinherit\"),\n                (\"pointer\", \"fg:magenta noinherit\"),\n            ]\n        ),\n    ).ask()\n    \n    if choice is None:\n        console.print(\"\\n[red]no OpenAI backend selected. Exiting...[/red]\")\n        exit(1)\n    \n    display_name, url = choice\n    print(f\"You selected: {display_name}\\tURL: {url}\")\n\n    return display_name, url\n\n\ndef ask_openai_reasoning_effort() -> str:\n    \"\"\"Ask for OpenAI reasoning effort level.\"\"\"\n    choices = [\n        questionary.Choice(\"Medium (Default)\", \"medium\"),\n        questionary.Choice(\"High (More thorough)\", \"high\"),\n        questionary.Choice(\"Low (Faster)\", \"low\"),\n    ]\n    return questionary.select(\n        \"Select Reasoning Effort:\",\n        choices=choices,\n        style=questionary.Style([\n            (\"selected\", \"fg:cyan noinherit\"),\n            (\"highlighted\", \"fg:cyan noinherit\"),\n            (\"pointer\", \"fg:cyan noinherit\"),\n        ]),\n    ).ask()\n\n\ndef ask_gemini_thinking_config() -> str | None:\n    \"\"\"Ask for Gemini thinking configuration.\n\n    Returns thinking_level: \"high\" or \"minimal\".\n    Client maps to appropriate API param based on model series.\n    \"\"\"\n    return questionary.select(\n        \"Select Thinking Mode:\",\n        choices=[\n            questionary.Choice(\"Enable Thinking (recommended)\", \"high\"),\n            questionary.Choice(\"Minimal/Disable Thinking\", \"minimal\"),\n        ],\n        style=questionary.Style([\n            (\"selected\", \"fg:green noinherit\"),\n            (\"highlighted\", \"fg:green noinherit\"),\n            (\"pointer\", \"fg:green noinherit\"),\n        ]),\n    ).ask()\n"
  },
  {
    "path": "main.py",
    "content": "from tradingagents.graph.trading_graph import TradingAgentsGraph\nfrom tradingagents.default_config import DEFAULT_CONFIG\n\nfrom dotenv import load_dotenv\n\n# Load environment variables from .env file\nload_dotenv()\n\n# Create a custom config\nconfig = DEFAULT_CONFIG.copy()\nconfig[\"deep_think_llm\"] = \"gpt-5-mini\"  # Use a different model\nconfig[\"quick_think_llm\"] = \"gpt-5-mini\"  # Use a different model\nconfig[\"max_debate_rounds\"] = 1  # Increase debate rounds\n\n# Configure data vendors (default uses yfinance, no extra API keys needed)\nconfig[\"data_vendors\"] = {\n    \"core_stock_apis\": \"yfinance\",           # Options: alpha_vantage, yfinance\n    \"technical_indicators\": \"yfinance\",      # Options: alpha_vantage, yfinance\n    \"fundamental_data\": \"yfinance\",          # Options: alpha_vantage, yfinance\n    \"news_data\": \"yfinance\",                 # Options: alpha_vantage, yfinance\n}\n\n# Initialize with custom config\nta = TradingAgentsGraph(debug=True, config=config)\n\n# forward propagate\n_, decision = ta.propagate(\"NVDA\", \"2024-05-10\")\nprint(decision)\n\n# Memorize mistakes and reflect\n# ta.reflect_and_remember(1000) # parameter is the position returns\n"
  },
  {
    "path": "pyproject.toml",
    "content": "[build-system]\nrequires = [\"setuptools>=61.0\"]\nbuild-backend = \"setuptools.build_meta\"\n\n[project]\nname = \"tradingagents\"\nversion = \"0.2.1\"\ndescription = \"TradingAgents: Multi-Agents LLM Financial Trading Framework\"\nreadme = \"README.md\"\nrequires-python = \">=3.10\"\ndependencies = [\n    \"langchain-core>=0.3.81\",\n    \"backtrader>=1.9.78.123\",\n    \"langchain-anthropic>=0.3.15\",\n    \"langchain-experimental>=0.3.4\",\n    \"langchain-google-genai>=2.1.5\",\n    \"langchain-openai>=0.3.23\",\n    \"langgraph>=0.4.8\",\n    \"pandas>=2.3.0\",\n    \"parsel>=1.10.0\",\n    \"pytz>=2025.2\",\n    \"questionary>=2.1.0\",\n    \"rank-bm25>=0.2.2\",\n    \"redis>=6.2.0\",\n    \"requests>=2.32.4\",\n    \"rich>=14.0.0\",\n    \"typer>=0.21.0\",\n    \"setuptools>=80.9.0\",\n    \"stockstats>=0.6.5\",\n    \"tqdm>=4.67.1\",\n    \"typing-extensions>=4.14.0\",\n    \"yfinance>=0.2.63\",\n]\n\n[project.scripts]\ntradingagents = \"cli.main:app\"\n\n[tool.setuptools.packages.find]\ninclude = [\"tradingagents*\", \"cli*\"]\n"
  },
  {
    "path": "requirements.txt",
    "content": "typing-extensions\nlangchain-core\nlangchain-openai\nlangchain-experimental\npandas\nyfinance\nstockstats\nlanggraph\nrank-bm25\nsetuptools\nbacktrader\nparsel\nrequests\ntqdm\npytz\nredis\nrich\ntyper\nquestionary\nlangchain_anthropic\nlangchain-google-genai\n"
  },
  {
    "path": "test.py",
    "content": "import time\nfrom 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\n\nprint(\"Testing optimized implementation with 30-day lookback:\")\nstart_time = time.time()\nresult = get_stock_stats_indicators_window(\"AAPL\", \"macd\", \"2024-11-01\", 30)\nend_time = time.time()\n\nprint(f\"Execution time: {end_time - start_time:.2f} seconds\")\nprint(f\"Result length: {len(result)} characters\")\nprint(result)\n"
  },
  {
    "path": "tradingagents/__init__.py",
    "content": ""
  },
  {
    "path": "tradingagents/agents/__init__.py",
    "content": "from .utils.agent_utils import create_msg_delete\nfrom .utils.agent_states import AgentState, InvestDebateState, RiskDebateState\nfrom .utils.memory import FinancialSituationMemory\n\nfrom .analysts.fundamentals_analyst import create_fundamentals_analyst\nfrom .analysts.market_analyst import create_market_analyst\nfrom .analysts.news_analyst import create_news_analyst\nfrom .analysts.social_media_analyst import create_social_media_analyst\n\nfrom .researchers.bear_researcher import create_bear_researcher\nfrom .researchers.bull_researcher import create_bull_researcher\n\nfrom .risk_mgmt.aggressive_debator import create_aggressive_debator\nfrom .risk_mgmt.conservative_debator import create_conservative_debator\nfrom .risk_mgmt.neutral_debator import create_neutral_debator\n\nfrom .managers.research_manager import create_research_manager\nfrom .managers.risk_manager import create_risk_manager\n\nfrom .trader.trader import create_trader\n\n__all__ = [\n    \"FinancialSituationMemory\",\n    \"AgentState\",\n    \"create_msg_delete\",\n    \"InvestDebateState\",\n    \"RiskDebateState\",\n    \"create_bear_researcher\",\n    \"create_bull_researcher\",\n    \"create_research_manager\",\n    \"create_fundamentals_analyst\",\n    \"create_market_analyst\",\n    \"create_neutral_debator\",\n    \"create_news_analyst\",\n    \"create_aggressive_debator\",\n    \"create_risk_manager\",\n    \"create_conservative_debator\",\n    \"create_social_media_analyst\",\n    \"create_trader\",\n]\n"
  },
  {
    "path": "tradingagents/agents/analysts/fundamentals_analyst.py",
    "content": "from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder\nimport time\nimport json\nfrom tradingagents.agents.utils.agent_utils import get_fundamentals, get_balance_sheet, get_cashflow, get_income_statement, get_insider_transactions\nfrom tradingagents.dataflows.config import get_config\n\n\ndef create_fundamentals_analyst(llm):\n    def fundamentals_analyst_node(state):\n        current_date = state[\"trade_date\"]\n        ticker = state[\"company_of_interest\"]\n        company_name = state[\"company_of_interest\"]\n\n        tools = [\n            get_fundamentals,\n            get_balance_sheet,\n            get_cashflow,\n            get_income_statement,\n        ]\n\n        system_message = (\n            \"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. Do not simply state the trends are mixed, provide detailed and finegrained analysis and insights that may help traders make decisions.\"\n            + \" 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.\"\n            + \" Use the available tools: `get_fundamentals` for comprehensive company analysis, `get_balance_sheet`, `get_cashflow`, and `get_income_statement` for specific financial statements.\",\n        )\n\n        prompt = ChatPromptTemplate.from_messages(\n            [\n                (\n                    \"system\",\n                    \"You are a helpful AI assistant, collaborating with other assistants.\"\n                    \" Use the provided tools to progress towards answering the question.\"\n                    \" If you are unable to fully answer, that's OK; another assistant with different tools\"\n                    \" will help where you left off. Execute what you can to make progress.\"\n                    \" If you or any other assistant has the FINAL TRANSACTION PROPOSAL: **BUY/HOLD/SELL** or deliverable,\"\n                    \" prefix your response with FINAL TRANSACTION PROPOSAL: **BUY/HOLD/SELL** so the team knows to stop.\"\n                    \" You have access to the following tools: {tool_names}.\\n{system_message}\"\n                    \"For your reference, the current date is {current_date}. The company we want to look at is {ticker}\",\n                ),\n                MessagesPlaceholder(variable_name=\"messages\"),\n            ]\n        )\n\n        prompt = prompt.partial(system_message=system_message)\n        prompt = prompt.partial(tool_names=\", \".join([tool.name for tool in tools]))\n        prompt = prompt.partial(current_date=current_date)\n        prompt = prompt.partial(ticker=ticker)\n\n        chain = prompt | llm.bind_tools(tools)\n\n        result = chain.invoke(state[\"messages\"])\n\n        report = \"\"\n\n        if len(result.tool_calls) == 0:\n            report = result.content\n\n        return {\n            \"messages\": [result],\n            \"fundamentals_report\": report,\n        }\n\n    return fundamentals_analyst_node\n"
  },
  {
    "path": "tradingagents/agents/analysts/market_analyst.py",
    "content": "from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder\nimport time\nimport json\nfrom tradingagents.agents.utils.agent_utils import get_stock_data, get_indicators\nfrom tradingagents.dataflows.config import get_config\n\n\ndef create_market_analyst(llm):\n\n    def market_analyst_node(state):\n        current_date = state[\"trade_date\"]\n        ticker = state[\"company_of_interest\"]\n        company_name = state[\"company_of_interest\"]\n\n        tools = [\n            get_stock_data,\n            get_indicators,\n        ]\n\n        system_message = (\n            \"\"\"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:\n\nMoving Averages:\n- 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.\n- 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.\n- 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.\n\nMACD Related:\n- 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.\n- 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.\n- 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.\n\nMomentum Indicators:\n- 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.\n\nVolatility Indicators:\n- 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.\n- 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.\n- 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.\n- 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.\n\nVolume-Based Indicators:\n- 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.\n\n- 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. Do not simply state the trends are mixed, provide detailed and finegrained analysis and insights that may help traders make decisions.\"\"\"\n            + \"\"\" 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.\"\"\"\n        )\n\n        prompt = ChatPromptTemplate.from_messages(\n            [\n                (\n                    \"system\",\n                    \"You are a helpful AI assistant, collaborating with other assistants.\"\n                    \" Use the provided tools to progress towards answering the question.\"\n                    \" If you are unable to fully answer, that's OK; another assistant with different tools\"\n                    \" will help where you left off. Execute what you can to make progress.\"\n                    \" If you or any other assistant has the FINAL TRANSACTION PROPOSAL: **BUY/HOLD/SELL** or deliverable,\"\n                    \" prefix your response with FINAL TRANSACTION PROPOSAL: **BUY/HOLD/SELL** so the team knows to stop.\"\n                    \" You have access to the following tools: {tool_names}.\\n{system_message}\"\n                    \"For your reference, the current date is {current_date}. The company we want to look at is {ticker}\",\n                ),\n                MessagesPlaceholder(variable_name=\"messages\"),\n            ]\n        )\n\n        prompt = prompt.partial(system_message=system_message)\n        prompt = prompt.partial(tool_names=\", \".join([tool.name for tool in tools]))\n        prompt = prompt.partial(current_date=current_date)\n        prompt = prompt.partial(ticker=ticker)\n\n        chain = prompt | llm.bind_tools(tools)\n\n        result = chain.invoke(state[\"messages\"])\n\n        report = \"\"\n\n        if len(result.tool_calls) == 0:\n            report = result.content\n\n        return {\n            \"messages\": [result],\n            \"market_report\": report,\n        }\n\n    return market_analyst_node\n"
  },
  {
    "path": "tradingagents/agents/analysts/news_analyst.py",
    "content": "from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder\nimport time\nimport json\nfrom tradingagents.agents.utils.agent_utils import get_news, get_global_news\nfrom tradingagents.dataflows.config import get_config\n\n\ndef create_news_analyst(llm):\n    def news_analyst_node(state):\n        current_date = state[\"trade_date\"]\n        ticker = state[\"company_of_interest\"]\n\n        tools = [\n            get_news,\n            get_global_news,\n        ]\n\n        system_message = (\n            \"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. Do not simply state the trends are mixed, provide detailed and finegrained analysis and insights that may help traders make decisions.\"\n            + \"\"\" 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.\"\"\"\n        )\n\n        prompt = ChatPromptTemplate.from_messages(\n            [\n                (\n                    \"system\",\n                    \"You are a helpful AI assistant, collaborating with other assistants.\"\n                    \" Use the provided tools to progress towards answering the question.\"\n                    \" If you are unable to fully answer, that's OK; another assistant with different tools\"\n                    \" will help where you left off. Execute what you can to make progress.\"\n                    \" If you or any other assistant has the FINAL TRANSACTION PROPOSAL: **BUY/HOLD/SELL** or deliverable,\"\n                    \" prefix your response with FINAL TRANSACTION PROPOSAL: **BUY/HOLD/SELL** so the team knows to stop.\"\n                    \" You have access to the following tools: {tool_names}.\\n{system_message}\"\n                    \"For your reference, the current date is {current_date}. We are looking at the company {ticker}\",\n                ),\n                MessagesPlaceholder(variable_name=\"messages\"),\n            ]\n        )\n\n        prompt = prompt.partial(system_message=system_message)\n        prompt = prompt.partial(tool_names=\", \".join([tool.name for tool in tools]))\n        prompt = prompt.partial(current_date=current_date)\n        prompt = prompt.partial(ticker=ticker)\n\n        chain = prompt | llm.bind_tools(tools)\n        result = chain.invoke(state[\"messages\"])\n\n        report = \"\"\n\n        if len(result.tool_calls) == 0:\n            report = result.content\n\n        return {\n            \"messages\": [result],\n            \"news_report\": report,\n        }\n\n    return news_analyst_node\n"
  },
  {
    "path": "tradingagents/agents/analysts/social_media_analyst.py",
    "content": "from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder\nimport time\nimport json\nfrom tradingagents.agents.utils.agent_utils import get_news\nfrom tradingagents.dataflows.config import get_config\n\n\ndef create_social_media_analyst(llm):\n    def social_media_analyst_node(state):\n        current_date = state[\"trade_date\"]\n        ticker = state[\"company_of_interest\"]\n        company_name = state[\"company_of_interest\"]\n\n        tools = [\n            get_news,\n        ]\n\n        system_message = (\n            \"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. Do not simply state the trends are mixed, provide detailed and finegrained analysis and insights that may help traders make decisions.\"\n            + \"\"\" 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.\"\"\",\n        )\n\n        prompt = ChatPromptTemplate.from_messages(\n            [\n                (\n                    \"system\",\n                    \"You are a helpful AI assistant, collaborating with other assistants.\"\n                    \" Use the provided tools to progress towards answering the question.\"\n                    \" If you are unable to fully answer, that's OK; another assistant with different tools\"\n                    \" will help where you left off. Execute what you can to make progress.\"\n                    \" If you or any other assistant has the FINAL TRANSACTION PROPOSAL: **BUY/HOLD/SELL** or deliverable,\"\n                    \" prefix your response with FINAL TRANSACTION PROPOSAL: **BUY/HOLD/SELL** so the team knows to stop.\"\n                    \" You have access to the following tools: {tool_names}.\\n{system_message}\"\n                    \"For your reference, the current date is {current_date}. The current company we want to analyze is {ticker}\",\n                ),\n                MessagesPlaceholder(variable_name=\"messages\"),\n            ]\n        )\n\n        prompt = prompt.partial(system_message=system_message)\n        prompt = prompt.partial(tool_names=\", \".join([tool.name for tool in tools]))\n        prompt = prompt.partial(current_date=current_date)\n        prompt = prompt.partial(ticker=ticker)\n\n        chain = prompt | llm.bind_tools(tools)\n\n        result = chain.invoke(state[\"messages\"])\n\n        report = \"\"\n\n        if len(result.tool_calls) == 0:\n            report = result.content\n\n        return {\n            \"messages\": [result],\n            \"sentiment_report\": report,\n        }\n\n    return social_media_analyst_node\n"
  },
  {
    "path": "tradingagents/agents/managers/research_manager.py",
    "content": "import time\nimport json\n\n\ndef create_research_manager(llm, memory):\n    def research_manager_node(state) -> dict:\n        history = state[\"investment_debate_state\"].get(\"history\", \"\")\n        market_research_report = state[\"market_report\"]\n        sentiment_report = state[\"sentiment_report\"]\n        news_report = state[\"news_report\"]\n        fundamentals_report = state[\"fundamentals_report\"]\n\n        investment_debate_state = state[\"investment_debate_state\"]\n\n        curr_situation = f\"{market_research_report}\\n\\n{sentiment_report}\\n\\n{news_report}\\n\\n{fundamentals_report}\"\n        past_memories = memory.get_memories(curr_situation, n_matches=2)\n\n        past_memory_str = \"\"\n        for i, rec in enumerate(past_memories, 1):\n            past_memory_str += rec[\"recommendation\"] + \"\\n\\n\"\n\n        prompt = f\"\"\"As the portfolio manager and debate facilitator, your role is to critically evaluate this round of debate and make a definitive decision: align with the bear analyst, the bull analyst, or choose Hold only if it is strongly justified based on the arguments presented.\n\nSummarize the key points from both sides concisely, focusing on the most compelling evidence or reasoning. Your recommendation—Buy, Sell, or Hold—must be clear and actionable. Avoid defaulting to Hold simply because both sides have valid points; commit to a stance grounded in the debate's strongest arguments.\n\nAdditionally, develop a detailed investment plan for the trader. This should include:\n\nYour Recommendation: A decisive stance supported by the most convincing arguments.\nRationale: An explanation of why these arguments lead to your conclusion.\nStrategic Actions: Concrete steps for implementing the recommendation.\nTake into account your past mistakes on similar situations. Use these insights to refine your decision-making and ensure you are learning and improving. Present your analysis conversationally, as if speaking naturally, without special formatting. \n\nHere are your past reflections on mistakes:\n\\\"{past_memory_str}\\\"\n\nHere is the debate:\nDebate History:\n{history}\"\"\"\n        response = llm.invoke(prompt)\n\n        new_investment_debate_state = {\n            \"judge_decision\": response.content,\n            \"history\": investment_debate_state.get(\"history\", \"\"),\n            \"bear_history\": investment_debate_state.get(\"bear_history\", \"\"),\n            \"bull_history\": investment_debate_state.get(\"bull_history\", \"\"),\n            \"current_response\": response.content,\n            \"count\": investment_debate_state[\"count\"],\n        }\n\n        return {\n            \"investment_debate_state\": new_investment_debate_state,\n            \"investment_plan\": response.content,\n        }\n\n    return research_manager_node\n"
  },
  {
    "path": "tradingagents/agents/managers/risk_manager.py",
    "content": "import time\nimport json\n\n\ndef create_risk_manager(llm, memory):\n    def risk_manager_node(state) -> dict:\n\n        company_name = state[\"company_of_interest\"]\n\n        history = state[\"risk_debate_state\"][\"history\"]\n        risk_debate_state = state[\"risk_debate_state\"]\n        market_research_report = state[\"market_report\"]\n        news_report = state[\"news_report\"]\n        fundamentals_report = state[\"fundamentals_report\"]\n        sentiment_report = state[\"sentiment_report\"]\n        trader_plan = state[\"investment_plan\"]\n\n        curr_situation = f\"{market_research_report}\\n\\n{sentiment_report}\\n\\n{news_report}\\n\\n{fundamentals_report}\"\n        past_memories = memory.get_memories(curr_situation, n_matches=2)\n\n        past_memory_str = \"\"\n        for i, rec in enumerate(past_memories, 1):\n            past_memory_str += rec[\"recommendation\"] + \"\\n\\n\"\n\n        prompt = f\"\"\"As the Risk Management Judge and Debate Facilitator, your goal is to evaluate the debate between three risk analysts—Aggressive, Neutral, and Conservative—and determine the best course of action for the trader. Your decision must result in a clear recommendation: Buy, Sell, or Hold. Choose Hold only if strongly justified by specific arguments, not as a fallback when all sides seem valid. Strive for clarity and decisiveness.\n\nGuidelines for Decision-Making:\n1. **Summarize Key Arguments**: Extract the strongest points from each analyst, focusing on relevance to the context.\n2. **Provide Rationale**: Support your recommendation with direct quotes and counterarguments from the debate.\n3. **Refine the Trader's Plan**: Start with the trader's original plan, **{trader_plan}**, and adjust it based on the analysts' insights.\n4. **Learn from Past Mistakes**: Use lessons from **{past_memory_str}** to address prior misjudgments and improve the decision you are making now to make sure you don't make a wrong BUY/SELL/HOLD call that loses money.\n\nDeliverables:\n- A clear and actionable recommendation: Buy, Sell, or Hold.\n- Detailed reasoning anchored in the debate and past reflections.\n\n---\n\n**Analysts Debate History:**  \n{history}\n\n---\n\nFocus on actionable insights and continuous improvement. Build on past lessons, critically evaluate all perspectives, and ensure each decision advances better outcomes.\"\"\"\n\n        response = llm.invoke(prompt)\n\n        new_risk_debate_state = {\n            \"judge_decision\": response.content,\n            \"history\": risk_debate_state[\"history\"],\n            \"aggressive_history\": risk_debate_state[\"aggressive_history\"],\n            \"conservative_history\": risk_debate_state[\"conservative_history\"],\n            \"neutral_history\": risk_debate_state[\"neutral_history\"],\n            \"latest_speaker\": \"Judge\",\n            \"current_aggressive_response\": risk_debate_state[\"current_aggressive_response\"],\n            \"current_conservative_response\": risk_debate_state[\"current_conservative_response\"],\n            \"current_neutral_response\": risk_debate_state[\"current_neutral_response\"],\n            \"count\": risk_debate_state[\"count\"],\n        }\n\n        return {\n            \"risk_debate_state\": new_risk_debate_state,\n            \"final_trade_decision\": response.content,\n        }\n\n    return risk_manager_node\n"
  },
  {
    "path": "tradingagents/agents/researchers/bear_researcher.py",
    "content": "from langchain_core.messages import AIMessage\nimport time\nimport json\n\n\ndef create_bear_researcher(llm, memory):\n    def bear_node(state) -> dict:\n        investment_debate_state = state[\"investment_debate_state\"]\n        history = investment_debate_state.get(\"history\", \"\")\n        bear_history = investment_debate_state.get(\"bear_history\", \"\")\n\n        current_response = investment_debate_state.get(\"current_response\", \"\")\n        market_research_report = state[\"market_report\"]\n        sentiment_report = state[\"sentiment_report\"]\n        news_report = state[\"news_report\"]\n        fundamentals_report = state[\"fundamentals_report\"]\n\n        curr_situation = f\"{market_research_report}\\n\\n{sentiment_report}\\n\\n{news_report}\\n\\n{fundamentals_report}\"\n        past_memories = memory.get_memories(curr_situation, n_matches=2)\n\n        past_memory_str = \"\"\n        for i, rec in enumerate(past_memories, 1):\n            past_memory_str += rec[\"recommendation\"] + \"\\n\\n\"\n\n        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.\n\nKey points to focus on:\n\n- Risks and Challenges: Highlight factors like market saturation, financial instability, or macroeconomic threats that could hinder the stock's performance.\n- Competitive Weaknesses: Emphasize vulnerabilities such as weaker market positioning, declining innovation, or threats from competitors.\n- Negative Indicators: Use evidence from financial data, market trends, or recent adverse news to support your position.\n- Bull Counterpoints: Critically analyze the bull argument with specific data and sound reasoning, exposing weaknesses or over-optimistic assumptions.\n- Engagement: Present your argument in a conversational style, directly engaging with the bull analyst's points and debating effectively rather than simply listing facts.\n\nResources available:\n\nMarket research report: {market_research_report}\nSocial media sentiment report: {sentiment_report}\nLatest world affairs news: {news_report}\nCompany fundamentals report: {fundamentals_report}\nConversation history of the debate: {history}\nLast bull argument: {current_response}\nReflections from similar situations and lessons learned: {past_memory_str}\nUse 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. You must also address reflections and learn from lessons and mistakes you made in the past.\n\"\"\"\n\n        response = llm.invoke(prompt)\n\n        argument = f\"Bear Analyst: {response.content}\"\n\n        new_investment_debate_state = {\n            \"history\": history + \"\\n\" + argument,\n            \"bear_history\": bear_history + \"\\n\" + argument,\n            \"bull_history\": investment_debate_state.get(\"bull_history\", \"\"),\n            \"current_response\": argument,\n            \"count\": investment_debate_state[\"count\"] + 1,\n        }\n\n        return {\"investment_debate_state\": new_investment_debate_state}\n\n    return bear_node\n"
  },
  {
    "path": "tradingagents/agents/researchers/bull_researcher.py",
    "content": "from langchain_core.messages import AIMessage\nimport time\nimport json\n\n\ndef create_bull_researcher(llm, memory):\n    def bull_node(state) -> dict:\n        investment_debate_state = state[\"investment_debate_state\"]\n        history = investment_debate_state.get(\"history\", \"\")\n        bull_history = investment_debate_state.get(\"bull_history\", \"\")\n\n        current_response = investment_debate_state.get(\"current_response\", \"\")\n        market_research_report = state[\"market_report\"]\n        sentiment_report = state[\"sentiment_report\"]\n        news_report = state[\"news_report\"]\n        fundamentals_report = state[\"fundamentals_report\"]\n\n        curr_situation = f\"{market_research_report}\\n\\n{sentiment_report}\\n\\n{news_report}\\n\\n{fundamentals_report}\"\n        past_memories = memory.get_memories(curr_situation, n_matches=2)\n\n        past_memory_str = \"\"\n        for i, rec in enumerate(past_memories, 1):\n            past_memory_str += rec[\"recommendation\"] + \"\\n\\n\"\n\n        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.\n\nKey points to focus on:\n- Growth Potential: Highlight the company's market opportunities, revenue projections, and scalability.\n- Competitive Advantages: Emphasize factors like unique products, strong branding, or dominant market positioning.\n- Positive Indicators: Use financial health, industry trends, and recent positive news as evidence.\n- 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.\n- Engagement: Present your argument in a conversational style, engaging directly with the bear analyst's points and debating effectively rather than just listing data.\n\nResources available:\nMarket research report: {market_research_report}\nSocial media sentiment report: {sentiment_report}\nLatest world affairs news: {news_report}\nCompany fundamentals report: {fundamentals_report}\nConversation history of the debate: {history}\nLast bear argument: {current_response}\nReflections from similar situations and lessons learned: {past_memory_str}\nUse 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. You must also address reflections and learn from lessons and mistakes you made in the past.\n\"\"\"\n\n        response = llm.invoke(prompt)\n\n        argument = f\"Bull Analyst: {response.content}\"\n\n        new_investment_debate_state = {\n            \"history\": history + \"\\n\" + argument,\n            \"bull_history\": bull_history + \"\\n\" + argument,\n            \"bear_history\": investment_debate_state.get(\"bear_history\", \"\"),\n            \"current_response\": argument,\n            \"count\": investment_debate_state[\"count\"] + 1,\n        }\n\n        return {\"investment_debate_state\": new_investment_debate_state}\n\n    return bull_node\n"
  },
  {
    "path": "tradingagents/agents/risk_mgmt/aggressive_debator.py",
    "content": "import time\nimport json\n\n\ndef create_aggressive_debator(llm):\n    def aggressive_node(state) -> dict:\n        risk_debate_state = state[\"risk_debate_state\"]\n        history = risk_debate_state.get(\"history\", \"\")\n        aggressive_history = risk_debate_state.get(\"aggressive_history\", \"\")\n\n        current_conservative_response = risk_debate_state.get(\"current_conservative_response\", \"\")\n        current_neutral_response = risk_debate_state.get(\"current_neutral_response\", \"\")\n\n        market_research_report = state[\"market_report\"]\n        sentiment_report = state[\"sentiment_report\"]\n        news_report = state[\"news_report\"]\n        fundamentals_report = state[\"fundamentals_report\"]\n\n        trader_decision = state[\"trader_investment_plan\"]\n\n        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:\n\n{trader_decision}\n\nYour 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:\n\nMarket Research Report: {market_research_report}\nSocial Media Sentiment Report: {sentiment_report}\nLatest World Affairs Report: {news_report}\nCompany Fundamentals Report: {fundamentals_report}\nHere 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, do not hallucinate and just present your point.\n\nEngage 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.\"\"\"\n\n        response = llm.invoke(prompt)\n\n        argument = f\"Aggressive Analyst: {response.content}\"\n\n        new_risk_debate_state = {\n            \"history\": history + \"\\n\" + argument,\n            \"aggressive_history\": aggressive_history + \"\\n\" + argument,\n            \"conservative_history\": risk_debate_state.get(\"conservative_history\", \"\"),\n            \"neutral_history\": risk_debate_state.get(\"neutral_history\", \"\"),\n            \"latest_speaker\": \"Aggressive\",\n            \"current_aggressive_response\": argument,\n            \"current_conservative_response\": risk_debate_state.get(\"current_conservative_response\", \"\"),\n            \"current_neutral_response\": risk_debate_state.get(\n                \"current_neutral_response\", \"\"\n            ),\n            \"count\": risk_debate_state[\"count\"] + 1,\n        }\n\n        return {\"risk_debate_state\": new_risk_debate_state}\n\n    return aggressive_node\n"
  },
  {
    "path": "tradingagents/agents/risk_mgmt/conservative_debator.py",
    "content": "from langchain_core.messages import AIMessage\nimport time\nimport json\n\n\ndef create_conservative_debator(llm):\n    def conservative_node(state) -> dict:\n        risk_debate_state = state[\"risk_debate_state\"]\n        history = risk_debate_state.get(\"history\", \"\")\n        conservative_history = risk_debate_state.get(\"conservative_history\", \"\")\n\n        current_aggressive_response = risk_debate_state.get(\"current_aggressive_response\", \"\")\n        current_neutral_response = risk_debate_state.get(\"current_neutral_response\", \"\")\n\n        market_research_report = state[\"market_report\"]\n        sentiment_report = state[\"sentiment_report\"]\n        news_report = state[\"news_report\"]\n        fundamentals_report = state[\"fundamentals_report\"]\n\n        trader_decision = state[\"trader_investment_plan\"]\n\n        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:\n\n{trader_decision}\n\nYour 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:\n\nMarket Research Report: {market_research_report}\nSocial Media Sentiment Report: {sentiment_report}\nLatest World Affairs Report: {news_report}\nCompany Fundamentals Report: {fundamentals_report}\nHere 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, do not hallucinate and just present your point.\n\nEngage 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.\"\"\"\n\n        response = llm.invoke(prompt)\n\n        argument = f\"Conservative Analyst: {response.content}\"\n\n        new_risk_debate_state = {\n            \"history\": history + \"\\n\" + argument,\n            \"aggressive_history\": risk_debate_state.get(\"aggressive_history\", \"\"),\n            \"conservative_history\": conservative_history + \"\\n\" + argument,\n            \"neutral_history\": risk_debate_state.get(\"neutral_history\", \"\"),\n            \"latest_speaker\": \"Conservative\",\n            \"current_aggressive_response\": risk_debate_state.get(\n                \"current_aggressive_response\", \"\"\n            ),\n            \"current_conservative_response\": argument,\n            \"current_neutral_response\": risk_debate_state.get(\n                \"current_neutral_response\", \"\"\n            ),\n            \"count\": risk_debate_state[\"count\"] + 1,\n        }\n\n        return {\"risk_debate_state\": new_risk_debate_state}\n\n    return conservative_node\n"
  },
  {
    "path": "tradingagents/agents/risk_mgmt/neutral_debator.py",
    "content": "import time\nimport json\n\n\ndef create_neutral_debator(llm):\n    def neutral_node(state) -> dict:\n        risk_debate_state = state[\"risk_debate_state\"]\n        history = risk_debate_state.get(\"history\", \"\")\n        neutral_history = risk_debate_state.get(\"neutral_history\", \"\")\n\n        current_aggressive_response = risk_debate_state.get(\"current_aggressive_response\", \"\")\n        current_conservative_response = risk_debate_state.get(\"current_conservative_response\", \"\")\n\n        market_research_report = state[\"market_report\"]\n        sentiment_report = state[\"sentiment_report\"]\n        news_report = state[\"news_report\"]\n        fundamentals_report = state[\"fundamentals_report\"]\n\n        trader_decision = state[\"trader_investment_plan\"]\n\n        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:\n\n{trader_decision}\n\nYour 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:\n\nMarket Research Report: {market_research_report}\nSocial Media Sentiment Report: {sentiment_report}\nLatest World Affairs Report: {news_report}\nCompany Fundamentals Report: {fundamentals_report}\nHere 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, do not hallucinate and just present your point.\n\nEngage 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.\"\"\"\n\n        response = llm.invoke(prompt)\n\n        argument = f\"Neutral Analyst: {response.content}\"\n\n        new_risk_debate_state = {\n            \"history\": history + \"\\n\" + argument,\n            \"aggressive_history\": risk_debate_state.get(\"aggressive_history\", \"\"),\n            \"conservative_history\": risk_debate_state.get(\"conservative_history\", \"\"),\n            \"neutral_history\": neutral_history + \"\\n\" + argument,\n            \"latest_speaker\": \"Neutral\",\n            \"current_aggressive_response\": risk_debate_state.get(\n                \"current_aggressive_response\", \"\"\n            ),\n            \"current_conservative_response\": risk_debate_state.get(\"current_conservative_response\", \"\"),\n            \"current_neutral_response\": argument,\n            \"count\": risk_debate_state[\"count\"] + 1,\n        }\n\n        return {\"risk_debate_state\": new_risk_debate_state}\n\n    return neutral_node\n"
  },
  {
    "path": "tradingagents/agents/trader/trader.py",
    "content": "import functools\nimport time\nimport json\n\n\ndef create_trader(llm, memory):\n    def trader_node(state, name):\n        company_name = state[\"company_of_interest\"]\n        investment_plan = state[\"investment_plan\"]\n        market_research_report = state[\"market_report\"]\n        sentiment_report = state[\"sentiment_report\"]\n        news_report = state[\"news_report\"]\n        fundamentals_report = state[\"fundamentals_report\"]\n\n        curr_situation = f\"{market_research_report}\\n\\n{sentiment_report}\\n\\n{news_report}\\n\\n{fundamentals_report}\"\n        past_memories = memory.get_memories(curr_situation, n_matches=2)\n\n        past_memory_str = \"\"\n        if past_memories:\n            for i, rec in enumerate(past_memories, 1):\n                past_memory_str += rec[\"recommendation\"] + \"\\n\\n\"\n        else:\n            past_memory_str = \"No past memories found.\"\n\n        context = {\n            \"role\": \"user\",\n            \"content\": f\"Based on a comprehensive analysis by a team of analysts, here is an investment plan tailored for {company_name}. This plan incorporates insights from current technical market trends, macroeconomic indicators, and social media sentiment. Use this plan as a foundation for evaluating your next trading decision.\\n\\nProposed Investment Plan: {investment_plan}\\n\\nLeverage these insights to make an informed and strategic decision.\",\n        }\n\n        messages = [\n            {\n                \"role\": \"system\",\n                \"content\": f\"\"\"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. End with a firm decision and always conclude your response with 'FINAL TRANSACTION PROPOSAL: **BUY/HOLD/SELL**' to confirm your recommendation. Do not forget to utilize lessons from past decisions to learn from your mistakes. Here is some reflections from similar situatiosn you traded in and the lessons learned: {past_memory_str}\"\"\",\n            },\n            context,\n        ]\n\n        result = llm.invoke(messages)\n\n        return {\n            \"messages\": [result],\n            \"trader_investment_plan\": result.content,\n            \"sender\": name,\n        }\n\n    return functools.partial(trader_node, name=\"Trader\")\n"
  },
  {
    "path": "tradingagents/agents/utils/agent_states.py",
    "content": "from typing import Annotated, Sequence\nfrom datetime import date, timedelta, datetime\nfrom typing_extensions import TypedDict, Optional\nfrom langchain_openai import ChatOpenAI\nfrom tradingagents.agents import *\nfrom langgraph.prebuilt import ToolNode\nfrom langgraph.graph import END, StateGraph, START, MessagesState\n\n\n# Researcher team state\nclass InvestDebateState(TypedDict):\n    bull_history: Annotated[\n        str, \"Bullish Conversation history\"\n    ]  # Bullish Conversation history\n    bear_history: Annotated[\n        str, \"Bearish Conversation history\"\n    ]  # Bullish Conversation history\n    history: Annotated[str, \"Conversation history\"]  # Conversation history\n    current_response: Annotated[str, \"Latest response\"]  # Last response\n    judge_decision: Annotated[str, \"Final judge decision\"]  # Last response\n    count: Annotated[int, \"Length of the current conversation\"]  # Conversation length\n\n\n# Risk management team state\nclass RiskDebateState(TypedDict):\n    aggressive_history: Annotated[\n        str, \"Aggressive Agent's Conversation history\"\n    ]  # Conversation history\n    conservative_history: Annotated[\n        str, \"Conservative Agent's Conversation history\"\n    ]  # Conversation history\n    neutral_history: Annotated[\n        str, \"Neutral Agent's Conversation history\"\n    ]  # Conversation history\n    history: Annotated[str, \"Conversation history\"]  # Conversation history\n    latest_speaker: Annotated[str, \"Analyst that spoke last\"]\n    current_aggressive_response: Annotated[\n        str, \"Latest response by the aggressive analyst\"\n    ]  # Last response\n    current_conservative_response: Annotated[\n        str, \"Latest response by the conservative analyst\"\n    ]  # Last response\n    current_neutral_response: Annotated[\n        str, \"Latest response by the neutral analyst\"\n    ]  # Last response\n    judge_decision: Annotated[str, \"Judge's decision\"]\n    count: Annotated[int, \"Length of the current conversation\"]  # Conversation length\n\n\nclass AgentState(MessagesState):\n    company_of_interest: Annotated[str, \"Company that we are interested in trading\"]\n    trade_date: Annotated[str, \"What date we are trading at\"]\n\n    sender: Annotated[str, \"Agent that sent this message\"]\n\n    # research step\n    market_report: Annotated[str, \"Report from the Market Analyst\"]\n    sentiment_report: Annotated[str, \"Report from the Social Media Analyst\"]\n    news_report: Annotated[\n        str, \"Report from the News Researcher of current world affairs\"\n    ]\n    fundamentals_report: Annotated[str, \"Report from the Fundamentals Researcher\"]\n\n    # researcher team discussion step\n    investment_debate_state: Annotated[\n        InvestDebateState, \"Current state of the debate on if to invest or not\"\n    ]\n    investment_plan: Annotated[str, \"Plan generated by the Analyst\"]\n\n    trader_investment_plan: Annotated[str, \"Plan generated by the Trader\"]\n\n    # risk management team discussion step\n    risk_debate_state: Annotated[\n        RiskDebateState, \"Current state of the debate on evaluating risk\"\n    ]\n    final_trade_decision: Annotated[str, \"Final decision made by the Risk Analysts\"]\n"
  },
  {
    "path": "tradingagents/agents/utils/agent_utils.py",
    "content": "from langchain_core.messages import HumanMessage, RemoveMessage\n\n# Import tools from separate utility files\nfrom tradingagents.agents.utils.core_stock_tools import (\n    get_stock_data\n)\nfrom tradingagents.agents.utils.technical_indicators_tools import (\n    get_indicators\n)\nfrom tradingagents.agents.utils.fundamental_data_tools import (\n    get_fundamentals,\n    get_balance_sheet,\n    get_cashflow,\n    get_income_statement\n)\nfrom tradingagents.agents.utils.news_data_tools import (\n    get_news,\n    get_insider_transactions,\n    get_global_news\n)\n\ndef create_msg_delete():\n    def delete_messages(state):\n        \"\"\"Clear messages and add placeholder for Anthropic compatibility\"\"\"\n        messages = state[\"messages\"]\n\n        # Remove all messages\n        removal_operations = [RemoveMessage(id=m.id) for m in messages]\n\n        # Add a minimal placeholder message\n        placeholder = HumanMessage(content=\"Continue\")\n\n        return {\"messages\": removal_operations + [placeholder]}\n\n    return delete_messages\n\n\n        "
  },
  {
    "path": "tradingagents/agents/utils/core_stock_tools.py",
    "content": "from langchain_core.tools import tool\nfrom typing import Annotated\nfrom tradingagents.dataflows.interface import route_to_vendor\n\n\n@tool\ndef get_stock_data(\n    symbol: Annotated[str, \"ticker symbol of the company\"],\n    start_date: Annotated[str, \"Start date in yyyy-mm-dd format\"],\n    end_date: Annotated[str, \"End date in yyyy-mm-dd format\"],\n) -> str:\n    \"\"\"\n    Retrieve stock price data (OHLCV) for a given ticker symbol.\n    Uses the configured core_stock_apis vendor.\n    Args:\n        symbol (str): Ticker symbol of the company, e.g. AAPL, TSM\n        start_date (str): Start date in yyyy-mm-dd format\n        end_date (str): End date in yyyy-mm-dd format\n    Returns:\n        str: A formatted dataframe containing the stock price data for the specified ticker symbol in the specified date range.\n    \"\"\"\n    return route_to_vendor(\"get_stock_data\", symbol, start_date, end_date)\n"
  },
  {
    "path": "tradingagents/agents/utils/fundamental_data_tools.py",
    "content": "from langchain_core.tools import tool\nfrom typing import Annotated\nfrom tradingagents.dataflows.interface import route_to_vendor\n\n\n@tool\ndef get_fundamentals(\n    ticker: Annotated[str, \"ticker symbol\"],\n    curr_date: Annotated[str, \"current date you are trading at, yyyy-mm-dd\"],\n) -> str:\n    \"\"\"\n    Retrieve comprehensive fundamental data for a given ticker symbol.\n    Uses the configured fundamental_data vendor.\n    Args:\n        ticker (str): Ticker symbol of the company\n        curr_date (str): Current date you are trading at, yyyy-mm-dd\n    Returns:\n        str: A formatted report containing comprehensive fundamental data\n    \"\"\"\n    return route_to_vendor(\"get_fundamentals\", ticker, curr_date)\n\n\n@tool\ndef get_balance_sheet(\n    ticker: Annotated[str, \"ticker symbol\"],\n    freq: Annotated[str, \"reporting frequency: annual/quarterly\"] = \"quarterly\",\n    curr_date: Annotated[str, \"current date you are trading at, yyyy-mm-dd\"] = None,\n) -> str:\n    \"\"\"\n    Retrieve balance sheet data for a given ticker symbol.\n    Uses the configured fundamental_data vendor.\n    Args:\n        ticker (str): Ticker symbol of the company\n        freq (str): Reporting frequency: annual/quarterly (default quarterly)\n        curr_date (str): Current date you are trading at, yyyy-mm-dd\n    Returns:\n        str: A formatted report containing balance sheet data\n    \"\"\"\n    return route_to_vendor(\"get_balance_sheet\", ticker, freq, curr_date)\n\n\n@tool\ndef get_cashflow(\n    ticker: Annotated[str, \"ticker symbol\"],\n    freq: Annotated[str, \"reporting frequency: annual/quarterly\"] = \"quarterly\",\n    curr_date: Annotated[str, \"current date you are trading at, yyyy-mm-dd\"] = None,\n) -> str:\n    \"\"\"\n    Retrieve cash flow statement data for a given ticker symbol.\n    Uses the configured fundamental_data vendor.\n    Args:\n        ticker (str): Ticker symbol of the company\n        freq (str): Reporting frequency: annual/quarterly (default quarterly)\n        curr_date (str): Current date you are trading at, yyyy-mm-dd\n    Returns:\n        str: A formatted report containing cash flow statement data\n    \"\"\"\n    return route_to_vendor(\"get_cashflow\", ticker, freq, curr_date)\n\n\n@tool\ndef get_income_statement(\n    ticker: Annotated[str, \"ticker symbol\"],\n    freq: Annotated[str, \"reporting frequency: annual/quarterly\"] = \"quarterly\",\n    curr_date: Annotated[str, \"current date you are trading at, yyyy-mm-dd\"] = None,\n) -> str:\n    \"\"\"\n    Retrieve income statement data for a given ticker symbol.\n    Uses the configured fundamental_data vendor.\n    Args:\n        ticker (str): Ticker symbol of the company\n        freq (str): Reporting frequency: annual/quarterly (default quarterly)\n        curr_date (str): Current date you are trading at, yyyy-mm-dd\n    Returns:\n        str: A formatted report containing income statement data\n    \"\"\"\n    return route_to_vendor(\"get_income_statement\", ticker, freq, curr_date)"
  },
  {
    "path": "tradingagents/agents/utils/memory.py",
    "content": "\"\"\"Financial situation memory using BM25 for lexical similarity matching.\n\nUses BM25 (Best Matching 25) algorithm for retrieval - no API calls,\nno token limits, works offline with any LLM provider.\n\"\"\"\n\nfrom rank_bm25 import BM25Okapi\nfrom typing import List, Tuple\nimport re\n\n\nclass FinancialSituationMemory:\n    \"\"\"Memory system for storing and retrieving financial situations using BM25.\"\"\"\n\n    def __init__(self, name: str, config: dict = None):\n        \"\"\"Initialize the memory system.\n\n        Args:\n            name: Name identifier for this memory instance\n            config: Configuration dict (kept for API compatibility, not used for BM25)\n        \"\"\"\n        self.name = name\n        self.documents: List[str] = []\n        self.recommendations: List[str] = []\n        self.bm25 = None\n\n    def _tokenize(self, text: str) -> List[str]:\n        \"\"\"Tokenize text for BM25 indexing.\n\n        Simple whitespace + punctuation tokenization with lowercasing.\n        \"\"\"\n        # Lowercase and split on non-alphanumeric characters\n        tokens = re.findall(r'\\b\\w+\\b', text.lower())\n        return tokens\n\n    def _rebuild_index(self):\n        \"\"\"Rebuild the BM25 index after adding documents.\"\"\"\n        if self.documents:\n            tokenized_docs = [self._tokenize(doc) for doc in self.documents]\n            self.bm25 = BM25Okapi(tokenized_docs)\n        else:\n            self.bm25 = None\n\n    def add_situations(self, situations_and_advice: List[Tuple[str, str]]):\n        \"\"\"Add financial situations and their corresponding advice.\n\n        Args:\n            situations_and_advice: List of tuples (situation, recommendation)\n        \"\"\"\n        for situation, recommendation in situations_and_advice:\n            self.documents.append(situation)\n            self.recommendations.append(recommendation)\n\n        # Rebuild BM25 index with new documents\n        self._rebuild_index()\n\n    def get_memories(self, current_situation: str, n_matches: int = 1) -> List[dict]:\n        \"\"\"Find matching recommendations using BM25 similarity.\n\n        Args:\n            current_situation: The current financial situation to match against\n            n_matches: Number of top matches to return\n\n        Returns:\n            List of dicts with matched_situation, recommendation, and similarity_score\n        \"\"\"\n        if not self.documents or self.bm25 is None:\n            return []\n\n        # Tokenize query\n        query_tokens = self._tokenize(current_situation)\n\n        # Get BM25 scores for all documents\n        scores = self.bm25.get_scores(query_tokens)\n\n        # Get top-n indices sorted by score (descending)\n        top_indices = sorted(range(len(scores)), key=lambda i: scores[i], reverse=True)[:n_matches]\n\n        # Build results\n        results = []\n        max_score = max(scores) if max(scores) > 0 else 1  # Normalize scores\n\n        for idx in top_indices:\n            # Normalize score to 0-1 range for consistency\n            normalized_score = scores[idx] / max_score if max_score > 0 else 0\n            results.append({\n                \"matched_situation\": self.documents[idx],\n                \"recommendation\": self.recommendations[idx],\n                \"similarity_score\": normalized_score,\n            })\n\n        return results\n\n    def clear(self):\n        \"\"\"Clear all stored memories.\"\"\"\n        self.documents = []\n        self.recommendations = []\n        self.bm25 = None\n\n\nif __name__ == \"__main__\":\n    # Example usage\n    matcher = FinancialSituationMemory(\"test_memory\")\n\n    # Example data\n    example_data = [\n        (\n            \"High inflation rate with rising interest rates and declining consumer spending\",\n            \"Consider defensive sectors like consumer staples and utilities. Review fixed-income portfolio duration.\",\n        ),\n        (\n            \"Tech sector showing high volatility with increasing institutional selling pressure\",\n            \"Reduce exposure to high-growth tech stocks. Look for value opportunities in established tech companies with strong cash flows.\",\n        ),\n        (\n            \"Strong dollar affecting emerging markets with increasing forex volatility\",\n            \"Hedge currency exposure in international positions. Consider reducing allocation to emerging market debt.\",\n        ),\n        (\n            \"Market showing signs of sector rotation with rising yields\",\n            \"Rebalance portfolio to maintain target allocations. Consider increasing exposure to sectors benefiting from higher rates.\",\n        ),\n    ]\n\n    # Add the example situations and recommendations\n    matcher.add_situations(example_data)\n\n    # Example query\n    current_situation = \"\"\"\n    Market showing increased volatility in tech sector, with institutional investors\n    reducing positions and rising interest rates affecting growth stock valuations\n    \"\"\"\n\n    try:\n        recommendations = matcher.get_memories(current_situation, n_matches=2)\n\n        for i, rec in enumerate(recommendations, 1):\n            print(f\"\\nMatch {i}:\")\n            print(f\"Similarity Score: {rec['similarity_score']:.2f}\")\n            print(f\"Matched Situation: {rec['matched_situation']}\")\n            print(f\"Recommendation: {rec['recommendation']}\")\n\n    except Exception as e:\n        print(f\"Error during recommendation: {str(e)}\")\n"
  },
  {
    "path": "tradingagents/agents/utils/news_data_tools.py",
    "content": "from langchain_core.tools import tool\nfrom typing import Annotated\nfrom tradingagents.dataflows.interface import route_to_vendor\n\n@tool\ndef get_news(\n    ticker: Annotated[str, \"Ticker symbol\"],\n    start_date: Annotated[str, \"Start date in yyyy-mm-dd format\"],\n    end_date: Annotated[str, \"End date in yyyy-mm-dd format\"],\n) -> str:\n    \"\"\"\n    Retrieve news data for a given ticker symbol.\n    Uses the configured news_data vendor.\n    Args:\n        ticker (str): Ticker symbol\n        start_date (str): Start date in yyyy-mm-dd format\n        end_date (str): End date in yyyy-mm-dd format\n    Returns:\n        str: A formatted string containing news data\n    \"\"\"\n    return route_to_vendor(\"get_news\", ticker, start_date, end_date)\n\n@tool\ndef get_global_news(\n    curr_date: Annotated[str, \"Current date in yyyy-mm-dd format\"],\n    look_back_days: Annotated[int, \"Number of days to look back\"] = 7,\n    limit: Annotated[int, \"Maximum number of articles to return\"] = 5,\n) -> str:\n    \"\"\"\n    Retrieve global news data.\n    Uses the configured news_data vendor.\n    Args:\n        curr_date (str): Current date in yyyy-mm-dd format\n        look_back_days (int): Number of days to look back (default 7)\n        limit (int): Maximum number of articles to return (default 5)\n    Returns:\n        str: A formatted string containing global news data\n    \"\"\"\n    return route_to_vendor(\"get_global_news\", curr_date, look_back_days, limit)\n\n@tool\ndef get_insider_transactions(\n    ticker: Annotated[str, \"ticker symbol\"],\n) -> str:\n    \"\"\"\n    Retrieve insider transaction information about a company.\n    Uses the configured news_data vendor.\n    Args:\n        ticker (str): Ticker symbol of the company\n    Returns:\n        str: A report of insider transaction data\n    \"\"\"\n    return route_to_vendor(\"get_insider_transactions\", ticker)\n"
  },
  {
    "path": "tradingagents/agents/utils/technical_indicators_tools.py",
    "content": "from langchain_core.tools import tool\nfrom typing import Annotated\nfrom tradingagents.dataflows.interface import route_to_vendor\n\n@tool\ndef get_indicators(\n    symbol: Annotated[str, \"ticker symbol of the company\"],\n    indicator: Annotated[str, \"technical indicator to get the analysis and report of\"],\n    curr_date: Annotated[str, \"The current trading date you are trading on, YYYY-mm-dd\"],\n    look_back_days: Annotated[int, \"how many days to look back\"] = 30,\n) -> str:\n    \"\"\"\n    Retrieve a single technical indicator for a given ticker symbol.\n    Uses the configured technical_indicators vendor.\n    Args:\n        symbol (str): Ticker symbol of the company, e.g. AAPL, TSM\n        indicator (str): A single technical indicator name, e.g. 'rsi', 'macd'. Call this tool once per indicator.\n        curr_date (str): The current trading date you are trading on, YYYY-mm-dd\n        look_back_days (int): How many days to look back, default is 30\n    Returns:\n        str: A formatted dataframe containing the technical indicators for the specified ticker symbol and indicator.\n    \"\"\"\n    # LLMs sometimes pass multiple indicators as a comma-separated string;\n    # split and process each individually.\n    indicators = [i.strip() for i in indicator.split(\",\") if i.strip()]\n    if len(indicators) > 1:\n        results = []\n        for ind in indicators:\n            results.append(route_to_vendor(\"get_indicators\", symbol, ind, curr_date, look_back_days))\n        return \"\\n\\n\".join(results)\n    return route_to_vendor(\"get_indicators\", symbol, indicator.strip(), curr_date, look_back_days)"
  },
  {
    "path": "tradingagents/dataflows/__init__.py",
    "content": ""
  },
  {
    "path": "tradingagents/dataflows/alpha_vantage.py",
    "content": "# Import functions from specialized modules\nfrom .alpha_vantage_stock import get_stock\nfrom .alpha_vantage_indicator import get_indicator\nfrom .alpha_vantage_fundamentals import get_fundamentals, get_balance_sheet, get_cashflow, get_income_statement\nfrom .alpha_vantage_news import get_news, get_global_news, get_insider_transactions"
  },
  {
    "path": "tradingagents/dataflows/alpha_vantage_common.py",
    "content": "import os\nimport requests\nimport pandas as pd\nimport json\nfrom datetime import datetime\nfrom io import StringIO\n\nAPI_BASE_URL = \"https://www.alphavantage.co/query\"\n\ndef get_api_key() -> str:\n    \"\"\"Retrieve the API key for Alpha Vantage from environment variables.\"\"\"\n    api_key = os.getenv(\"ALPHA_VANTAGE_API_KEY\")\n    if not api_key:\n        raise ValueError(\"ALPHA_VANTAGE_API_KEY environment variable is not set.\")\n    return api_key\n\ndef format_datetime_for_api(date_input) -> str:\n    \"\"\"Convert various date formats to YYYYMMDDTHHMM format required by Alpha Vantage API.\"\"\"\n    if isinstance(date_input, str):\n        # If already in correct format, return as-is\n        if len(date_input) == 13 and 'T' in date_input:\n            return date_input\n        # Try to parse common date formats\n        try:\n            dt = datetime.strptime(date_input, \"%Y-%m-%d\")\n            return dt.strftime(\"%Y%m%dT0000\")\n        except ValueError:\n            try:\n                dt = datetime.strptime(date_input, \"%Y-%m-%d %H:%M\")\n                return dt.strftime(\"%Y%m%dT%H%M\")\n            except ValueError:\n                raise ValueError(f\"Unsupported date format: {date_input}\")\n    elif isinstance(date_input, datetime):\n        return date_input.strftime(\"%Y%m%dT%H%M\")\n    else:\n        raise ValueError(f\"Date must be string or datetime object, got {type(date_input)}\")\n\nclass AlphaVantageRateLimitError(Exception):\n    \"\"\"Exception raised when Alpha Vantage API rate limit is exceeded.\"\"\"\n    pass\n\ndef _make_api_request(function_name: str, params: dict) -> dict | str:\n    \"\"\"Helper function to make API requests and handle responses.\n    \n    Raises:\n        AlphaVantageRateLimitError: When API rate limit is exceeded\n    \"\"\"\n    # Create a copy of params to avoid modifying the original\n    api_params = params.copy()\n    api_params.update({\n        \"function\": function_name,\n        \"apikey\": get_api_key(),\n        \"source\": \"trading_agents\",\n    })\n    \n    # Handle entitlement parameter if present in params or global variable\n    current_entitlement = globals().get('_current_entitlement')\n    entitlement = api_params.get(\"entitlement\") or current_entitlement\n    \n    if entitlement:\n        api_params[\"entitlement\"] = entitlement\n    elif \"entitlement\" in api_params:\n        # Remove entitlement if it's None or empty\n        api_params.pop(\"entitlement\", None)\n    \n    response = requests.get(API_BASE_URL, params=api_params)\n    response.raise_for_status()\n\n    response_text = response.text\n    \n    # Check if response is JSON (error responses are typically JSON)\n    try:\n        response_json = json.loads(response_text)\n        # Check for rate limit error\n        if \"Information\" in response_json:\n            info_message = response_json[\"Information\"]\n            if \"rate limit\" in info_message.lower() or \"api key\" in info_message.lower():\n                raise AlphaVantageRateLimitError(f\"Alpha Vantage rate limit exceeded: {info_message}\")\n    except json.JSONDecodeError:\n        # Response is not JSON (likely CSV data), which is normal\n        pass\n\n    return response_text\n\n\n\ndef _filter_csv_by_date_range(csv_data: str, start_date: str, end_date: str) -> str:\n    \"\"\"\n    Filter CSV data to include only rows within the specified date range.\n\n    Args:\n        csv_data: CSV string from Alpha Vantage API\n        start_date: Start date in yyyy-mm-dd format\n        end_date: End date in yyyy-mm-dd format\n\n    Returns:\n        Filtered CSV string\n    \"\"\"\n    if not csv_data or csv_data.strip() == \"\":\n        return csv_data\n\n    try:\n        # Parse CSV data\n        df = pd.read_csv(StringIO(csv_data))\n\n        # Assume the first column is the date column (timestamp)\n        date_col = df.columns[0]\n        df[date_col] = pd.to_datetime(df[date_col])\n\n        # Filter by date range\n        start_dt = pd.to_datetime(start_date)\n        end_dt = pd.to_datetime(end_date)\n\n        filtered_df = df[(df[date_col] >= start_dt) & (df[date_col] <= end_dt)]\n\n        # Convert back to CSV string\n        return filtered_df.to_csv(index=False)\n\n    except Exception as e:\n        # If filtering fails, return original data with a warning\n        print(f\"Warning: Failed to filter CSV data by date range: {e}\")\n        return csv_data\n"
  },
  {
    "path": "tradingagents/dataflows/alpha_vantage_fundamentals.py",
    "content": "from .alpha_vantage_common import _make_api_request\n\n\ndef get_fundamentals(ticker: str, curr_date: str = None) -> str:\n    \"\"\"\n    Retrieve comprehensive fundamental data for a given ticker symbol using Alpha Vantage.\n\n    Args:\n        ticker (str): Ticker symbol of the company\n        curr_date (str): Current date you are trading at, yyyy-mm-dd (not used for Alpha Vantage)\n\n    Returns:\n        str: Company overview data including financial ratios and key metrics\n    \"\"\"\n    params = {\n        \"symbol\": ticker,\n    }\n\n    return _make_api_request(\"OVERVIEW\", params)\n\n\ndef get_balance_sheet(ticker: str, freq: str = \"quarterly\", curr_date: str = None) -> str:\n    \"\"\"\n    Retrieve balance sheet data for a given ticker symbol using Alpha Vantage.\n\n    Args:\n        ticker (str): Ticker symbol of the company\n        freq (str): Reporting frequency: annual/quarterly (default quarterly) - not used for Alpha Vantage\n        curr_date (str): Current date you are trading at, yyyy-mm-dd (not used for Alpha Vantage)\n\n    Returns:\n        str: Balance sheet data with normalized fields\n    \"\"\"\n    params = {\n        \"symbol\": ticker,\n    }\n\n    return _make_api_request(\"BALANCE_SHEET\", params)\n\n\ndef get_cashflow(ticker: str, freq: str = \"quarterly\", curr_date: str = None) -> str:\n    \"\"\"\n    Retrieve cash flow statement data for a given ticker symbol using Alpha Vantage.\n\n    Args:\n        ticker (str): Ticker symbol of the company\n        freq (str): Reporting frequency: annual/quarterly (default quarterly) - not used for Alpha Vantage\n        curr_date (str): Current date you are trading at, yyyy-mm-dd (not used for Alpha Vantage)\n\n    Returns:\n        str: Cash flow statement data with normalized fields\n    \"\"\"\n    params = {\n        \"symbol\": ticker,\n    }\n\n    return _make_api_request(\"CASH_FLOW\", params)\n\n\ndef get_income_statement(ticker: str, freq: str = \"quarterly\", curr_date: str = None) -> str:\n    \"\"\"\n    Retrieve income statement data for a given ticker symbol using Alpha Vantage.\n\n    Args:\n        ticker (str): Ticker symbol of the company\n        freq (str): Reporting frequency: annual/quarterly (default quarterly) - not used for Alpha Vantage\n        curr_date (str): Current date you are trading at, yyyy-mm-dd (not used for Alpha Vantage)\n\n    Returns:\n        str: Income statement data with normalized fields\n    \"\"\"\n    params = {\n        \"symbol\": ticker,\n    }\n\n    return _make_api_request(\"INCOME_STATEMENT\", params)\n\n"
  },
  {
    "path": "tradingagents/dataflows/alpha_vantage_indicator.py",
    "content": "from .alpha_vantage_common import _make_api_request\n\ndef get_indicator(\n    symbol: str,\n    indicator: str,\n    curr_date: str,\n    look_back_days: int,\n    interval: str = \"daily\",\n    time_period: int = 14,\n    series_type: str = \"close\"\n) -> str:\n    \"\"\"\n    Returns Alpha Vantage technical indicator values over a time window.\n\n    Args:\n        symbol: ticker symbol of the company\n        indicator: technical indicator to get the analysis and report of\n        curr_date: The current trading date you are trading on, YYYY-mm-dd\n        look_back_days: how many days to look back\n        interval: Time interval (daily, weekly, monthly)\n        time_period: Number of data points for calculation\n        series_type: The desired price type (close, open, high, low)\n\n    Returns:\n        String containing indicator values and description\n    \"\"\"\n    from datetime import datetime\n    from dateutil.relativedelta import relativedelta\n\n    supported_indicators = {\n        \"close_50_sma\": (\"50 SMA\", \"close\"),\n        \"close_200_sma\": (\"200 SMA\", \"close\"),\n        \"close_10_ema\": (\"10 EMA\", \"close\"),\n        \"macd\": (\"MACD\", \"close\"),\n        \"macds\": (\"MACD Signal\", \"close\"),\n        \"macdh\": (\"MACD Histogram\", \"close\"),\n        \"rsi\": (\"RSI\", \"close\"),\n        \"boll\": (\"Bollinger Middle\", \"close\"),\n        \"boll_ub\": (\"Bollinger Upper Band\", \"close\"),\n        \"boll_lb\": (\"Bollinger Lower Band\", \"close\"),\n        \"atr\": (\"ATR\", None),\n        \"vwma\": (\"VWMA\", \"close\")\n    }\n\n    indicator_descriptions = {\n        \"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.\",\n        \"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.\",\n        \"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.\",\n        \"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.\",\n        \"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.\",\n        \"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.\",\n        \"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.\",\n        \"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.\",\n        \"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.\",\n        \"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.\",\n        \"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.\",\n        \"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.\"\n    }\n\n    if indicator not in supported_indicators:\n        raise ValueError(\n            f\"Indicator {indicator} is not supported. Please choose from: {list(supported_indicators.keys())}\"\n        )\n\n    curr_date_dt = datetime.strptime(curr_date, \"%Y-%m-%d\")\n    before = curr_date_dt - relativedelta(days=look_back_days)\n\n    # Get the full data for the period instead of making individual calls\n    _, required_series_type = supported_indicators[indicator]\n\n    # Use the provided series_type or fall back to the required one\n    if required_series_type:\n        series_type = required_series_type\n\n    try:\n        # Get indicator data for the period\n        if indicator == \"close_50_sma\":\n            data = _make_api_request(\"SMA\", {\n                \"symbol\": symbol,\n                \"interval\": interval,\n                \"time_period\": \"50\",\n                \"series_type\": series_type,\n                \"datatype\": \"csv\"\n            })\n        elif indicator == \"close_200_sma\":\n            data = _make_api_request(\"SMA\", {\n                \"symbol\": symbol,\n                \"interval\": interval,\n                \"time_period\": \"200\",\n                \"series_type\": series_type,\n                \"datatype\": \"csv\"\n            })\n        elif indicator == \"close_10_ema\":\n            data = _make_api_request(\"EMA\", {\n                \"symbol\": symbol,\n                \"interval\": interval,\n                \"time_period\": \"10\",\n                \"series_type\": series_type,\n                \"datatype\": \"csv\"\n            })\n        elif indicator == \"macd\":\n            data = _make_api_request(\"MACD\", {\n                \"symbol\": symbol,\n                \"interval\": interval,\n                \"series_type\": series_type,\n                \"datatype\": \"csv\"\n            })\n        elif indicator == \"macds\":\n            data = _make_api_request(\"MACD\", {\n                \"symbol\": symbol,\n                \"interval\": interval,\n                \"series_type\": series_type,\n                \"datatype\": \"csv\"\n            })\n        elif indicator == \"macdh\":\n            data = _make_api_request(\"MACD\", {\n                \"symbol\": symbol,\n                \"interval\": interval,\n                \"series_type\": series_type,\n                \"datatype\": \"csv\"\n            })\n        elif indicator == \"rsi\":\n            data = _make_api_request(\"RSI\", {\n                \"symbol\": symbol,\n                \"interval\": interval,\n                \"time_period\": str(time_period),\n                \"series_type\": series_type,\n                \"datatype\": \"csv\"\n            })\n        elif indicator in [\"boll\", \"boll_ub\", \"boll_lb\"]:\n            data = _make_api_request(\"BBANDS\", {\n                \"symbol\": symbol,\n                \"interval\": interval,\n                \"time_period\": \"20\",\n                \"series_type\": series_type,\n                \"datatype\": \"csv\"\n            })\n        elif indicator == \"atr\":\n            data = _make_api_request(\"ATR\", {\n                \"symbol\": symbol,\n                \"interval\": interval,\n                \"time_period\": str(time_period),\n                \"datatype\": \"csv\"\n            })\n        elif indicator == \"vwma\":\n            # Alpha Vantage doesn't have direct VWMA, so we'll return an informative message\n            # In a real implementation, this would need to be calculated from OHLCV data\n            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.')}\"\n        else:\n            return f\"Error: Indicator {indicator} not implemented yet.\"\n\n        # Parse CSV data and extract values for the date range\n        lines = data.strip().split('\\n')\n        if len(lines) < 2:\n            return f\"Error: No data returned for {indicator}\"\n\n        # Parse header and data\n        header = [col.strip() for col in lines[0].split(',')]\n        try:\n            date_col_idx = header.index('time')\n        except ValueError:\n            return f\"Error: 'time' column not found in data for {indicator}. Available columns: {header}\"\n\n        # Map internal indicator names to expected CSV column names from Alpha Vantage\n        col_name_map = {\n            \"macd\": \"MACD\", \"macds\": \"MACD_Signal\", \"macdh\": \"MACD_Hist\",\n            \"boll\": \"Real Middle Band\", \"boll_ub\": \"Real Upper Band\", \"boll_lb\": \"Real Lower Band\",\n            \"rsi\": \"RSI\", \"atr\": \"ATR\", \"close_10_ema\": \"EMA\",\n            \"close_50_sma\": \"SMA\", \"close_200_sma\": \"SMA\"\n        }\n\n        target_col_name = col_name_map.get(indicator)\n\n        if not target_col_name:\n            # Default to the second column if no specific mapping exists\n            value_col_idx = 1\n        else:\n            try:\n                value_col_idx = header.index(target_col_name)\n            except ValueError:\n                return f\"Error: Column '{target_col_name}' not found for indicator '{indicator}'. Available columns: {header}\"\n\n        result_data = []\n        for line in lines[1:]:\n            if not line.strip():\n                continue\n            values = line.split(',')\n            if len(values) > value_col_idx:\n                try:\n                    date_str = values[date_col_idx].strip()\n                    # Parse the date\n                    date_dt = datetime.strptime(date_str, \"%Y-%m-%d\")\n\n                    # Check if date is in our range\n                    if before <= date_dt <= curr_date_dt:\n                        value = values[value_col_idx].strip()\n                        result_data.append((date_dt, value))\n                except (ValueError, IndexError):\n                    continue\n\n        # Sort by date and format output\n        result_data.sort(key=lambda x: x[0])\n\n        ind_string = \"\"\n        for date_dt, value in result_data:\n            ind_string += f\"{date_dt.strftime('%Y-%m-%d')}: {value}\\n\"\n\n        if not ind_string:\n            ind_string = \"No data available for the specified date range.\\n\"\n\n        result_str = (\n            f\"## {indicator.upper()} values from {before.strftime('%Y-%m-%d')} to {curr_date}:\\n\\n\"\n            + ind_string\n            + \"\\n\\n\"\n            + indicator_descriptions.get(indicator, \"No description available.\")\n        )\n\n        return result_str\n\n    except Exception as e:\n        print(f\"Error getting Alpha Vantage indicator data for {indicator}: {e}\")\n        return f\"Error retrieving {indicator} data: {str(e)}\"\n"
  },
  {
    "path": "tradingagents/dataflows/alpha_vantage_news.py",
    "content": "from .alpha_vantage_common import _make_api_request, format_datetime_for_api\n\ndef get_news(ticker, start_date, end_date) -> dict[str, str] | str:\n    \"\"\"Returns live and historical market news & sentiment data from premier news outlets worldwide.\n\n    Covers stocks, cryptocurrencies, forex, and topics like fiscal policy, mergers & acquisitions, IPOs.\n\n    Args:\n        ticker: Stock symbol for news articles.\n        start_date: Start date for news search.\n        end_date: End date for news search.\n\n    Returns:\n        Dictionary containing news sentiment data or JSON string.\n    \"\"\"\n\n    params = {\n        \"tickers\": ticker,\n        \"time_from\": format_datetime_for_api(start_date),\n        \"time_to\": format_datetime_for_api(end_date),\n    }\n\n    return _make_api_request(\"NEWS_SENTIMENT\", params)\n\ndef get_global_news(curr_date, look_back_days: int = 7, limit: int = 50) -> dict[str, str] | str:\n    \"\"\"Returns global market news & sentiment data without ticker-specific filtering.\n\n    Covers broad market topics like financial markets, economy, and more.\n\n    Args:\n        curr_date: Current date in yyyy-mm-dd format.\n        look_back_days: Number of days to look back (default 7).\n        limit: Maximum number of articles (default 50).\n\n    Returns:\n        Dictionary containing global news sentiment data or JSON string.\n    \"\"\"\n    from datetime import datetime, timedelta\n\n    # Calculate start date\n    curr_dt = datetime.strptime(curr_date, \"%Y-%m-%d\")\n    start_dt = curr_dt - timedelta(days=look_back_days)\n    start_date = start_dt.strftime(\"%Y-%m-%d\")\n\n    params = {\n        \"topics\": \"financial_markets,economy_macro,economy_monetary\",\n        \"time_from\": format_datetime_for_api(start_date),\n        \"time_to\": format_datetime_for_api(curr_date),\n        \"limit\": str(limit),\n    }\n\n    return _make_api_request(\"NEWS_SENTIMENT\", params)\n\n\ndef get_insider_transactions(symbol: str) -> dict[str, str] | str:\n    \"\"\"Returns latest and historical insider transactions by key stakeholders.\n\n    Covers transactions by founders, executives, board members, etc.\n\n    Args:\n        symbol: Ticker symbol. Example: \"IBM\".\n\n    Returns:\n        Dictionary containing insider transaction data or JSON string.\n    \"\"\"\n\n    params = {\n        \"symbol\": symbol,\n    }\n\n    return _make_api_request(\"INSIDER_TRANSACTIONS\", params)"
  },
  {
    "path": "tradingagents/dataflows/alpha_vantage_stock.py",
    "content": "from datetime import datetime\nfrom .alpha_vantage_common import _make_api_request, _filter_csv_by_date_range\n\ndef get_stock(\n    symbol: str,\n    start_date: str,\n    end_date: str\n) -> str:\n    \"\"\"\n    Returns raw daily OHLCV values, adjusted close values, and historical split/dividend events\n    filtered to the specified date range.\n\n    Args:\n        symbol: The name of the equity. For example: symbol=IBM\n        start_date: Start date in yyyy-mm-dd format\n        end_date: End date in yyyy-mm-dd format\n\n    Returns:\n        CSV string containing the daily adjusted time series data filtered to the date range.\n    \"\"\"\n    # Parse dates to determine the range\n    start_dt = datetime.strptime(start_date, \"%Y-%m-%d\")\n    today = datetime.now()\n\n    # Choose outputsize based on whether the requested range is within the latest 100 days\n    # Compact returns latest 100 data points, so check if start_date is recent enough\n    days_from_today_to_start = (today - start_dt).days\n    outputsize = \"compact\" if days_from_today_to_start < 100 else \"full\"\n\n    params = {\n        \"symbol\": symbol,\n        \"outputsize\": outputsize,\n        \"datatype\": \"csv\",\n    }\n\n    response = _make_api_request(\"TIME_SERIES_DAILY_ADJUSTED\", params)\n\n    return _filter_csv_by_date_range(response, start_date, end_date)"
  },
  {
    "path": "tradingagents/dataflows/config.py",
    "content": "import tradingagents.default_config as default_config\nfrom typing import Dict, Optional\n\n# Use default config but allow it to be overridden\n_config: Optional[Dict] = None\n\n\ndef initialize_config():\n    \"\"\"Initialize the configuration with default values.\"\"\"\n    global _config\n    if _config is None:\n        _config = default_config.DEFAULT_CONFIG.copy()\n\n\ndef set_config(config: Dict):\n    \"\"\"Update the configuration with custom values.\"\"\"\n    global _config\n    if _config is None:\n        _config = default_config.DEFAULT_CONFIG.copy()\n    _config.update(config)\n\n\ndef get_config() -> Dict:\n    \"\"\"Get the current configuration.\"\"\"\n    if _config is None:\n        initialize_config()\n    return _config.copy()\n\n\n# Initialize with default config\ninitialize_config()\n"
  },
  {
    "path": "tradingagents/dataflows/interface.py",
    "content": "from typing import Annotated\n\n# Import from vendor-specific modules\nfrom .y_finance import (\n    get_YFin_data_online,\n    get_stock_stats_indicators_window,\n    get_fundamentals as get_yfinance_fundamentals,\n    get_balance_sheet as get_yfinance_balance_sheet,\n    get_cashflow as get_yfinance_cashflow,\n    get_income_statement as get_yfinance_income_statement,\n    get_insider_transactions as get_yfinance_insider_transactions,\n)\nfrom .yfinance_news import get_news_yfinance, get_global_news_yfinance\nfrom .alpha_vantage import (\n    get_stock as get_alpha_vantage_stock,\n    get_indicator as get_alpha_vantage_indicator,\n    get_fundamentals as get_alpha_vantage_fundamentals,\n    get_balance_sheet as get_alpha_vantage_balance_sheet,\n    get_cashflow as get_alpha_vantage_cashflow,\n    get_income_statement as get_alpha_vantage_income_statement,\n    get_insider_transactions as get_alpha_vantage_insider_transactions,\n    get_news as get_alpha_vantage_news,\n    get_global_news as get_alpha_vantage_global_news,\n)\nfrom .alpha_vantage_common import AlphaVantageRateLimitError\n\n# Configuration and routing logic\nfrom .config import get_config\n\n# Tools organized by category\nTOOLS_CATEGORIES = {\n    \"core_stock_apis\": {\n        \"description\": \"OHLCV stock price data\",\n        \"tools\": [\n            \"get_stock_data\"\n        ]\n    },\n    \"technical_indicators\": {\n        \"description\": \"Technical analysis indicators\",\n        \"tools\": [\n            \"get_indicators\"\n        ]\n    },\n    \"fundamental_data\": {\n        \"description\": \"Company fundamentals\",\n        \"tools\": [\n            \"get_fundamentals\",\n            \"get_balance_sheet\",\n            \"get_cashflow\",\n            \"get_income_statement\"\n        ]\n    },\n    \"news_data\": {\n        \"description\": \"News and insider data\",\n        \"tools\": [\n            \"get_news\",\n            \"get_global_news\",\n            \"get_insider_transactions\",\n        ]\n    }\n}\n\nVENDOR_LIST = [\n    \"yfinance\",\n    \"alpha_vantage\",\n]\n\n# Mapping of methods to their vendor-specific implementations\nVENDOR_METHODS = {\n    # core_stock_apis\n    \"get_stock_data\": {\n        \"alpha_vantage\": get_alpha_vantage_stock,\n        \"yfinance\": get_YFin_data_online,\n    },\n    # technical_indicators\n    \"get_indicators\": {\n        \"alpha_vantage\": get_alpha_vantage_indicator,\n        \"yfinance\": get_stock_stats_indicators_window,\n    },\n    # fundamental_data\n    \"get_fundamentals\": {\n        \"alpha_vantage\": get_alpha_vantage_fundamentals,\n        \"yfinance\": get_yfinance_fundamentals,\n    },\n    \"get_balance_sheet\": {\n        \"alpha_vantage\": get_alpha_vantage_balance_sheet,\n        \"yfinance\": get_yfinance_balance_sheet,\n    },\n    \"get_cashflow\": {\n        \"alpha_vantage\": get_alpha_vantage_cashflow,\n        \"yfinance\": get_yfinance_cashflow,\n    },\n    \"get_income_statement\": {\n        \"alpha_vantage\": get_alpha_vantage_income_statement,\n        \"yfinance\": get_yfinance_income_statement,\n    },\n    # news_data\n    \"get_news\": {\n        \"alpha_vantage\": get_alpha_vantage_news,\n        \"yfinance\": get_news_yfinance,\n    },\n    \"get_global_news\": {\n        \"yfinance\": get_global_news_yfinance,\n        \"alpha_vantage\": get_alpha_vantage_global_news,\n    },\n    \"get_insider_transactions\": {\n        \"alpha_vantage\": get_alpha_vantage_insider_transactions,\n        \"yfinance\": get_yfinance_insider_transactions,\n    },\n}\n\ndef get_category_for_method(method: str) -> str:\n    \"\"\"Get the category that contains the specified method.\"\"\"\n    for category, info in TOOLS_CATEGORIES.items():\n        if method in info[\"tools\"]:\n            return category\n    raise ValueError(f\"Method '{method}' not found in any category\")\n\ndef get_vendor(category: str, method: str = None) -> str:\n    \"\"\"Get the configured vendor for a data category or specific tool method.\n    Tool-level configuration takes precedence over category-level.\n    \"\"\"\n    config = get_config()\n\n    # Check tool-level configuration first (if method provided)\n    if method:\n        tool_vendors = config.get(\"tool_vendors\", {})\n        if method in tool_vendors:\n            return tool_vendors[method]\n\n    # Fall back to category-level configuration\n    return config.get(\"data_vendors\", {}).get(category, \"default\")\n\ndef route_to_vendor(method: str, *args, **kwargs):\n    \"\"\"Route method calls to appropriate vendor implementation with fallback support.\"\"\"\n    category = get_category_for_method(method)\n    vendor_config = get_vendor(category, method)\n    primary_vendors = [v.strip() for v in vendor_config.split(',')]\n\n    if method not in VENDOR_METHODS:\n        raise ValueError(f\"Method '{method}' not supported\")\n\n    # Build fallback chain: primary vendors first, then remaining available vendors\n    all_available_vendors = list(VENDOR_METHODS[method].keys())\n    fallback_vendors = primary_vendors.copy()\n    for vendor in all_available_vendors:\n        if vendor not in fallback_vendors:\n            fallback_vendors.append(vendor)\n\n    for vendor in fallback_vendors:\n        if vendor not in VENDOR_METHODS[method]:\n            continue\n\n        vendor_impl = VENDOR_METHODS[method][vendor]\n        impl_func = vendor_impl[0] if isinstance(vendor_impl, list) else vendor_impl\n\n        try:\n            return impl_func(*args, **kwargs)\n        except AlphaVantageRateLimitError:\n            continue  # Only rate limits trigger fallback\n\n    raise RuntimeError(f\"No available vendor for '{method}'\")"
  },
  {
    "path": "tradingagents/dataflows/stockstats_utils.py",
    "content": "import pandas as pd\nimport yfinance as yf\nfrom stockstats import wrap\nfrom typing import Annotated\nimport os\nfrom .config import get_config\n\n\ndef _clean_dataframe(data: pd.DataFrame) -> pd.DataFrame:\n    \"\"\"Normalize a stock DataFrame for stockstats: parse dates, drop invalid rows, fill price gaps.\"\"\"\n    data[\"Date\"] = pd.to_datetime(data[\"Date\"], errors=\"coerce\")\n    data = data.dropna(subset=[\"Date\"])\n\n    price_cols = [c for c in [\"Open\", \"High\", \"Low\", \"Close\", \"Volume\"] if c in data.columns]\n    data[price_cols] = data[price_cols].apply(pd.to_numeric, errors=\"coerce\")\n    data = data.dropna(subset=[\"Close\"])\n    data[price_cols] = data[price_cols].ffill().bfill()\n\n    return data\n\n\nclass StockstatsUtils:\n    @staticmethod\n    def get_stock_stats(\n        symbol: Annotated[str, \"ticker symbol for the company\"],\n        indicator: Annotated[\n            str, \"quantitative indicators based off of the stock data for the company\"\n        ],\n        curr_date: Annotated[\n            str, \"curr date for retrieving stock price data, YYYY-mm-dd\"\n        ],\n    ):\n        config = get_config()\n\n        today_date = pd.Timestamp.today()\n        curr_date_dt = pd.to_datetime(curr_date)\n\n        end_date = today_date\n        start_date = today_date - pd.DateOffset(years=15)\n        start_date_str = start_date.strftime(\"%Y-%m-%d\")\n        end_date_str = end_date.strftime(\"%Y-%m-%d\")\n\n        # Ensure cache directory exists\n        os.makedirs(config[\"data_cache_dir\"], exist_ok=True)\n\n        data_file = os.path.join(\n            config[\"data_cache_dir\"],\n            f\"{symbol}-YFin-data-{start_date_str}-{end_date_str}.csv\",\n        )\n\n        if os.path.exists(data_file):\n            data = pd.read_csv(data_file, on_bad_lines=\"skip\")\n        else:\n            data = yf.download(\n                symbol,\n                start=start_date_str,\n                end=end_date_str,\n                multi_level_index=False,\n                progress=False,\n                auto_adjust=True,\n            )\n            data = data.reset_index()\n            data.to_csv(data_file, index=False)\n\n        data = _clean_dataframe(data)\n        df = wrap(data)\n        df[\"Date\"] = df[\"Date\"].dt.strftime(\"%Y-%m-%d\")\n        curr_date_str = curr_date_dt.strftime(\"%Y-%m-%d\")\n\n        df[indicator]  # trigger stockstats to calculate the indicator\n        matching_rows = df[df[\"Date\"].str.startswith(curr_date_str)]\n\n        if not matching_rows.empty:\n            indicator_value = matching_rows[indicator].values[0]\n            return indicator_value\n        else:\n            return \"N/A: Not a trading day (weekend or holiday)\"\n"
  },
  {
    "path": "tradingagents/dataflows/utils.py",
    "content": "import os\nimport json\nimport pandas as pd\nfrom datetime import date, timedelta, datetime\nfrom typing import Annotated\n\nSavePathType = Annotated[str, \"File path to save data. If None, data is not saved.\"]\n\ndef save_output(data: pd.DataFrame, tag: str, save_path: SavePathType = None) -> None:\n    if save_path:\n        data.to_csv(save_path)\n        print(f\"{tag} saved to {save_path}\")\n\n\ndef get_current_date():\n    return date.today().strftime(\"%Y-%m-%d\")\n\n\ndef decorate_all_methods(decorator):\n    def class_decorator(cls):\n        for attr_name, attr_value in cls.__dict__.items():\n            if callable(attr_value):\n                setattr(cls, attr_name, decorator(attr_value))\n        return cls\n\n    return class_decorator\n\n\ndef get_next_weekday(date):\n\n    if not isinstance(date, datetime):\n        date = datetime.strptime(date, \"%Y-%m-%d\")\n\n    if date.weekday() >= 5:\n        days_to_add = 7 - date.weekday()\n        next_weekday = date + timedelta(days=days_to_add)\n        return next_weekday\n    else:\n        return date\n"
  },
  {
    "path": "tradingagents/dataflows/y_finance.py",
    "content": "from typing import Annotated\nfrom datetime import datetime\nfrom dateutil.relativedelta import relativedelta\nimport yfinance as yf\nimport os\nfrom .stockstats_utils import StockstatsUtils, _clean_dataframe\n\ndef get_YFin_data_online(\n    symbol: Annotated[str, \"ticker symbol of the company\"],\n    start_date: Annotated[str, \"Start date in yyyy-mm-dd format\"],\n    end_date: Annotated[str, \"End date in yyyy-mm-dd format\"],\n):\n\n    datetime.strptime(start_date, \"%Y-%m-%d\")\n    datetime.strptime(end_date, \"%Y-%m-%d\")\n\n    # Create ticker object\n    ticker = yf.Ticker(symbol.upper())\n\n    # Fetch historical data for the specified date range\n    data = ticker.history(start=start_date, end=end_date)\n\n    # Check if data is empty\n    if data.empty:\n        return (\n            f\"No data found for symbol '{symbol}' between {start_date} and {end_date}\"\n        )\n\n    # Remove timezone info from index for cleaner output\n    if data.index.tz is not None:\n        data.index = data.index.tz_localize(None)\n\n    # Round numerical values to 2 decimal places for cleaner display\n    numeric_columns = [\"Open\", \"High\", \"Low\", \"Close\", \"Adj Close\"]\n    for col in numeric_columns:\n        if col in data.columns:\n            data[col] = data[col].round(2)\n\n    # Convert DataFrame to CSV string\n    csv_string = data.to_csv()\n\n    # Add header information\n    header = f\"# Stock data for {symbol.upper()} from {start_date} to {end_date}\\n\"\n    header += f\"# Total records: {len(data)}\\n\"\n    header += f\"# Data retrieved on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\\n\\n\"\n\n    return header + csv_string\n\ndef get_stock_stats_indicators_window(\n    symbol: Annotated[str, \"ticker symbol of the company\"],\n    indicator: Annotated[str, \"technical indicator to get the analysis and report of\"],\n    curr_date: Annotated[\n        str, \"The current trading date you are trading on, YYYY-mm-dd\"\n    ],\n    look_back_days: Annotated[int, \"how many days to look back\"],\n) -> str:\n\n    best_ind_params = {\n        # Moving Averages\n        \"close_50_sma\": (\n            \"50 SMA: A medium-term trend indicator. \"\n            \"Usage: Identify trend direction and serve as dynamic support/resistance. \"\n            \"Tips: It lags price; combine with faster indicators for timely signals.\"\n        ),\n        \"close_200_sma\": (\n            \"200 SMA: A long-term trend benchmark. \"\n            \"Usage: Confirm overall market trend and identify golden/death cross setups. \"\n            \"Tips: It reacts slowly; best for strategic trend confirmation rather than frequent trading entries.\"\n        ),\n        \"close_10_ema\": (\n            \"10 EMA: A responsive short-term average. \"\n            \"Usage: Capture quick shifts in momentum and potential entry points. \"\n            \"Tips: Prone to noise in choppy markets; use alongside longer averages for filtering false signals.\"\n        ),\n        # MACD Related\n        \"macd\": (\n            \"MACD: Computes momentum via differences of EMAs. \"\n            \"Usage: Look for crossovers and divergence as signals of trend changes. \"\n            \"Tips: Confirm with other indicators in low-volatility or sideways markets.\"\n        ),\n        \"macds\": (\n            \"MACD Signal: An EMA smoothing of the MACD line. \"\n            \"Usage: Use crossovers with the MACD line to trigger trades. \"\n            \"Tips: Should be part of a broader strategy to avoid false positives.\"\n        ),\n        \"macdh\": (\n            \"MACD Histogram: Shows the gap between the MACD line and its signal. \"\n            \"Usage: Visualize momentum strength and spot divergence early. \"\n            \"Tips: Can be volatile; complement with additional filters in fast-moving markets.\"\n        ),\n        # Momentum Indicators\n        \"rsi\": (\n            \"RSI: Measures momentum to flag overbought/oversold conditions. \"\n            \"Usage: Apply 70/30 thresholds and watch for divergence to signal reversals. \"\n            \"Tips: In strong trends, RSI may remain extreme; always cross-check with trend analysis.\"\n        ),\n        # Volatility Indicators\n        \"boll\": (\n            \"Bollinger Middle: A 20 SMA serving as the basis for Bollinger Bands. \"\n            \"Usage: Acts as a dynamic benchmark for price movement. \"\n            \"Tips: Combine with the upper and lower bands to effectively spot breakouts or reversals.\"\n        ),\n        \"boll_ub\": (\n            \"Bollinger Upper Band: Typically 2 standard deviations above the middle line. \"\n            \"Usage: Signals potential overbought conditions and breakout zones. \"\n            \"Tips: Confirm signals with other tools; prices may ride the band in strong trends.\"\n        ),\n        \"boll_lb\": (\n            \"Bollinger Lower Band: Typically 2 standard deviations below the middle line. \"\n            \"Usage: Indicates potential oversold conditions. \"\n            \"Tips: Use additional analysis to avoid false reversal signals.\"\n        ),\n        \"atr\": (\n            \"ATR: Averages true range to measure volatility. \"\n            \"Usage: Set stop-loss levels and adjust position sizes based on current market volatility. \"\n            \"Tips: It's a reactive measure, so use it as part of a broader risk management strategy.\"\n        ),\n        # Volume-Based Indicators\n        \"vwma\": (\n            \"VWMA: A moving average weighted by volume. \"\n            \"Usage: Confirm trends by integrating price action with volume data. \"\n            \"Tips: Watch for skewed results from volume spikes; use in combination with other volume analyses.\"\n        ),\n        \"mfi\": (\n            \"MFI: The Money Flow Index is a momentum indicator that uses both price and volume to measure buying and selling pressure. \"\n            \"Usage: Identify overbought (>80) or oversold (<20) conditions and confirm the strength of trends or reversals. \"\n            \"Tips: Use alongside RSI or MACD to confirm signals; divergence between price and MFI can indicate potential reversals.\"\n        ),\n    }\n\n    if indicator not in best_ind_params:\n        raise ValueError(\n            f\"Indicator {indicator} is not supported. Please choose from: {list(best_ind_params.keys())}\"\n        )\n\n    end_date = curr_date\n    curr_date_dt = datetime.strptime(curr_date, \"%Y-%m-%d\")\n    before = curr_date_dt - relativedelta(days=look_back_days)\n\n    # Optimized: Get stock data once and calculate indicators for all dates\n    try:\n        indicator_data = _get_stock_stats_bulk(symbol, indicator, curr_date)\n        \n        # Generate the date range we need\n        current_dt = curr_date_dt\n        date_values = []\n        \n        while current_dt >= before:\n            date_str = current_dt.strftime('%Y-%m-%d')\n            \n            # Look up the indicator value for this date\n            if date_str in indicator_data:\n                indicator_value = indicator_data[date_str]\n            else:\n                indicator_value = \"N/A: Not a trading day (weekend or holiday)\"\n            \n            date_values.append((date_str, indicator_value))\n            current_dt = current_dt - relativedelta(days=1)\n        \n        # Build the result string\n        ind_string = \"\"\n        for date_str, value in date_values:\n            ind_string += f\"{date_str}: {value}\\n\"\n        \n    except Exception as e:\n        print(f\"Error getting bulk stockstats data: {e}\")\n        # Fallback to original implementation if bulk method fails\n        ind_string = \"\"\n        curr_date_dt = datetime.strptime(curr_date, \"%Y-%m-%d\")\n        while curr_date_dt >= before:\n            indicator_value = get_stockstats_indicator(\n                symbol, indicator, curr_date_dt.strftime(\"%Y-%m-%d\")\n            )\n            ind_string += f\"{curr_date_dt.strftime('%Y-%m-%d')}: {indicator_value}\\n\"\n            curr_date_dt = curr_date_dt - relativedelta(days=1)\n\n    result_str = (\n        f\"## {indicator} values from {before.strftime('%Y-%m-%d')} to {end_date}:\\n\\n\"\n        + ind_string\n        + \"\\n\\n\"\n        + best_ind_params.get(indicator, \"No description available.\")\n    )\n\n    return result_str\n\n\ndef _get_stock_stats_bulk(\n    symbol: Annotated[str, \"ticker symbol of the company\"],\n    indicator: Annotated[str, \"technical indicator to calculate\"],\n    curr_date: Annotated[str, \"current date for reference\"]\n) -> dict:\n    \"\"\"\n    Optimized bulk calculation of stock stats indicators.\n    Fetches data once and calculates indicator for all available dates.\n    Returns dict mapping date strings to indicator values.\n    \"\"\"\n    from .config import get_config\n    import pandas as pd\n    from stockstats import wrap\n    import os\n    \n    config = get_config()\n    online = config[\"data_vendors\"][\"technical_indicators\"] != \"local\"\n    \n    if not online:\n        # Local data path\n        try:\n            data = pd.read_csv(\n                os.path.join(\n                    config.get(\"data_cache_dir\", \"data\"),\n                    f\"{symbol}-YFin-data-2015-01-01-2025-03-25.csv\",\n                ),\n                on_bad_lines=\"skip\",\n            )\n        except FileNotFoundError:\n            raise Exception(\"Stockstats fail: Yahoo Finance data not fetched yet!\")\n    else:\n        # Online data fetching with caching\n        today_date = pd.Timestamp.today()\n        curr_date_dt = pd.to_datetime(curr_date)\n\n        end_date = today_date\n        start_date = today_date - pd.DateOffset(years=15)\n        start_date_str = start_date.strftime(\"%Y-%m-%d\")\n        end_date_str = end_date.strftime(\"%Y-%m-%d\")\n\n        os.makedirs(config[\"data_cache_dir\"], exist_ok=True)\n\n        data_file = os.path.join(\n            config[\"data_cache_dir\"],\n            f\"{symbol}-YFin-data-{start_date_str}-{end_date_str}.csv\",\n        )\n\n        if os.path.exists(data_file):\n            data = pd.read_csv(data_file, on_bad_lines=\"skip\")\n        else:\n            data = yf.download(\n                symbol,\n                start=start_date_str,\n                end=end_date_str,\n                multi_level_index=False,\n                progress=False,\n                auto_adjust=True,\n            )\n            data = data.reset_index()\n            data.to_csv(data_file, index=False)\n\n    data = _clean_dataframe(data)\n    df = wrap(data)\n    df[\"Date\"] = df[\"Date\"].dt.strftime(\"%Y-%m-%d\")\n    \n    # Calculate the indicator for all rows at once\n    df[indicator]  # This triggers stockstats to calculate the indicator\n    \n    # Create a dictionary mapping date strings to indicator values\n    result_dict = {}\n    for _, row in df.iterrows():\n        date_str = row[\"Date\"]\n        indicator_value = row[indicator]\n        \n        # Handle NaN/None values\n        if pd.isna(indicator_value):\n            result_dict[date_str] = \"N/A\"\n        else:\n            result_dict[date_str] = str(indicator_value)\n    \n    return result_dict\n\n\ndef get_stockstats_indicator(\n    symbol: Annotated[str, \"ticker symbol of the company\"],\n    indicator: Annotated[str, \"technical indicator to get the analysis and report of\"],\n    curr_date: Annotated[\n        str, \"The current trading date you are trading on, YYYY-mm-dd\"\n    ],\n) -> str:\n\n    curr_date_dt = datetime.strptime(curr_date, \"%Y-%m-%d\")\n    curr_date = curr_date_dt.strftime(\"%Y-%m-%d\")\n\n    try:\n        indicator_value = StockstatsUtils.get_stock_stats(\n            symbol,\n            indicator,\n            curr_date,\n        )\n    except Exception as e:\n        print(\n            f\"Error getting stockstats indicator data for indicator {indicator} on {curr_date}: {e}\"\n        )\n        return \"\"\n\n    return str(indicator_value)\n\n\ndef get_fundamentals(\n    ticker: Annotated[str, \"ticker symbol of the company\"],\n    curr_date: Annotated[str, \"current date (not used for yfinance)\"] = None\n):\n    \"\"\"Get company fundamentals overview from yfinance.\"\"\"\n    try:\n        ticker_obj = yf.Ticker(ticker.upper())\n        info = ticker_obj.info\n\n        if not info:\n            return f\"No fundamentals data found for symbol '{ticker}'\"\n\n        fields = [\n            (\"Name\", info.get(\"longName\")),\n            (\"Sector\", info.get(\"sector\")),\n            (\"Industry\", info.get(\"industry\")),\n            (\"Market Cap\", info.get(\"marketCap\")),\n            (\"PE Ratio (TTM)\", info.get(\"trailingPE\")),\n            (\"Forward PE\", info.get(\"forwardPE\")),\n            (\"PEG Ratio\", info.get(\"pegRatio\")),\n            (\"Price to Book\", info.get(\"priceToBook\")),\n            (\"EPS (TTM)\", info.get(\"trailingEps\")),\n            (\"Forward EPS\", info.get(\"forwardEps\")),\n            (\"Dividend Yield\", info.get(\"dividendYield\")),\n            (\"Beta\", info.get(\"beta\")),\n            (\"52 Week High\", info.get(\"fiftyTwoWeekHigh\")),\n            (\"52 Week Low\", info.get(\"fiftyTwoWeekLow\")),\n            (\"50 Day Average\", info.get(\"fiftyDayAverage\")),\n            (\"200 Day Average\", info.get(\"twoHundredDayAverage\")),\n            (\"Revenue (TTM)\", info.get(\"totalRevenue\")),\n            (\"Gross Profit\", info.get(\"grossProfits\")),\n            (\"EBITDA\", info.get(\"ebitda\")),\n            (\"Net Income\", info.get(\"netIncomeToCommon\")),\n            (\"Profit Margin\", info.get(\"profitMargins\")),\n            (\"Operating Margin\", info.get(\"operatingMargins\")),\n            (\"Return on Equity\", info.get(\"returnOnEquity\")),\n            (\"Return on Assets\", info.get(\"returnOnAssets\")),\n            (\"Debt to Equity\", info.get(\"debtToEquity\")),\n            (\"Current Ratio\", info.get(\"currentRatio\")),\n            (\"Book Value\", info.get(\"bookValue\")),\n            (\"Free Cash Flow\", info.get(\"freeCashflow\")),\n        ]\n\n        lines = []\n        for label, value in fields:\n            if value is not None:\n                lines.append(f\"{label}: {value}\")\n\n        header = f\"# Company Fundamentals for {ticker.upper()}\\n\"\n        header += f\"# Data retrieved on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\\n\\n\"\n\n        return header + \"\\n\".join(lines)\n\n    except Exception as e:\n        return f\"Error retrieving fundamentals for {ticker}: {str(e)}\"\n\n\ndef get_balance_sheet(\n    ticker: Annotated[str, \"ticker symbol of the company\"],\n    freq: Annotated[str, \"frequency of data: 'annual' or 'quarterly'\"] = \"quarterly\",\n    curr_date: Annotated[str, \"current date (not used for yfinance)\"] = None\n):\n    \"\"\"Get balance sheet data from yfinance.\"\"\"\n    try:\n        ticker_obj = yf.Ticker(ticker.upper())\n        \n        if freq.lower() == \"quarterly\":\n            data = ticker_obj.quarterly_balance_sheet\n        else:\n            data = ticker_obj.balance_sheet\n            \n        if data.empty:\n            return f\"No balance sheet data found for symbol '{ticker}'\"\n            \n        # Convert to CSV string for consistency with other functions\n        csv_string = data.to_csv()\n        \n        # Add header information\n        header = f\"# Balance Sheet data for {ticker.upper()} ({freq})\\n\"\n        header += f\"# Data retrieved on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\\n\\n\"\n        \n        return header + csv_string\n        \n    except Exception as e:\n        return f\"Error retrieving balance sheet for {ticker}: {str(e)}\"\n\n\ndef get_cashflow(\n    ticker: Annotated[str, \"ticker symbol of the company\"],\n    freq: Annotated[str, \"frequency of data: 'annual' or 'quarterly'\"] = \"quarterly\",\n    curr_date: Annotated[str, \"current date (not used for yfinance)\"] = None\n):\n    \"\"\"Get cash flow data from yfinance.\"\"\"\n    try:\n        ticker_obj = yf.Ticker(ticker.upper())\n        \n        if freq.lower() == \"quarterly\":\n            data = ticker_obj.quarterly_cashflow\n        else:\n            data = ticker_obj.cashflow\n            \n        if data.empty:\n            return f\"No cash flow data found for symbol '{ticker}'\"\n            \n        # Convert to CSV string for consistency with other functions\n        csv_string = data.to_csv()\n        \n        # Add header information\n        header = f\"# Cash Flow data for {ticker.upper()} ({freq})\\n\"\n        header += f\"# Data retrieved on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\\n\\n\"\n        \n        return header + csv_string\n        \n    except Exception as e:\n        return f\"Error retrieving cash flow for {ticker}: {str(e)}\"\n\n\ndef get_income_statement(\n    ticker: Annotated[str, \"ticker symbol of the company\"],\n    freq: Annotated[str, \"frequency of data: 'annual' or 'quarterly'\"] = \"quarterly\",\n    curr_date: Annotated[str, \"current date (not used for yfinance)\"] = None\n):\n    \"\"\"Get income statement data from yfinance.\"\"\"\n    try:\n        ticker_obj = yf.Ticker(ticker.upper())\n        \n        if freq.lower() == \"quarterly\":\n            data = ticker_obj.quarterly_income_stmt\n        else:\n            data = ticker_obj.income_stmt\n            \n        if data.empty:\n            return f\"No income statement data found for symbol '{ticker}'\"\n            \n        # Convert to CSV string for consistency with other functions\n        csv_string = data.to_csv()\n        \n        # Add header information\n        header = f\"# Income Statement data for {ticker.upper()} ({freq})\\n\"\n        header += f\"# Data retrieved on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\\n\\n\"\n        \n        return header + csv_string\n        \n    except Exception as e:\n        return f\"Error retrieving income statement for {ticker}: {str(e)}\"\n\n\ndef get_insider_transactions(\n    ticker: Annotated[str, \"ticker symbol of the company\"]\n):\n    \"\"\"Get insider transactions data from yfinance.\"\"\"\n    try:\n        ticker_obj = yf.Ticker(ticker.upper())\n        data = ticker_obj.insider_transactions\n        \n        if data is None or data.empty:\n            return f\"No insider transactions data found for symbol '{ticker}'\"\n            \n        # Convert to CSV string for consistency with other functions\n        csv_string = data.to_csv()\n        \n        # Add header information\n        header = f\"# Insider Transactions data for {ticker.upper()}\\n\"\n        header += f\"# Data retrieved on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\\n\\n\"\n        \n        return header + csv_string\n        \n    except Exception as e:\n        return f\"Error retrieving insider transactions for {ticker}: {str(e)}\""
  },
  {
    "path": "tradingagents/dataflows/yfinance_news.py",
    "content": "\"\"\"yfinance-based news data fetching functions.\"\"\"\n\nimport yfinance as yf\nfrom datetime import datetime\nfrom dateutil.relativedelta import relativedelta\n\n\ndef _extract_article_data(article: dict) -> dict:\n    \"\"\"Extract article data from yfinance news format (handles nested 'content' structure).\"\"\"\n    # Handle nested content structure\n    if \"content\" in article:\n        content = article[\"content\"]\n        title = content.get(\"title\", \"No title\")\n        summary = content.get(\"summary\", \"\")\n        provider = content.get(\"provider\", {})\n        publisher = provider.get(\"displayName\", \"Unknown\")\n\n        # Get URL from canonicalUrl or clickThroughUrl\n        url_obj = content.get(\"canonicalUrl\") or content.get(\"clickThroughUrl\") or {}\n        link = url_obj.get(\"url\", \"\")\n\n        # Get publish date\n        pub_date_str = content.get(\"pubDate\", \"\")\n        pub_date = None\n        if pub_date_str:\n            try:\n                pub_date = datetime.fromisoformat(pub_date_str.replace(\"Z\", \"+00:00\"))\n            except (ValueError, AttributeError):\n                pass\n\n        return {\n            \"title\": title,\n            \"summary\": summary,\n            \"publisher\": publisher,\n            \"link\": link,\n            \"pub_date\": pub_date,\n        }\n    else:\n        # Fallback for flat structure\n        return {\n            \"title\": article.get(\"title\", \"No title\"),\n            \"summary\": article.get(\"summary\", \"\"),\n            \"publisher\": article.get(\"publisher\", \"Unknown\"),\n            \"link\": article.get(\"link\", \"\"),\n            \"pub_date\": None,\n        }\n\n\ndef get_news_yfinance(\n    ticker: str,\n    start_date: str,\n    end_date: str,\n) -> str:\n    \"\"\"\n    Retrieve news for a specific stock ticker using yfinance.\n\n    Args:\n        ticker: Stock ticker symbol (e.g., \"AAPL\")\n        start_date: Start date in yyyy-mm-dd format\n        end_date: End date in yyyy-mm-dd format\n\n    Returns:\n        Formatted string containing news articles\n    \"\"\"\n    try:\n        stock = yf.Ticker(ticker)\n        news = stock.get_news(count=20)\n\n        if not news:\n            return f\"No news found for {ticker}\"\n\n        # Parse date range for filtering\n        start_dt = datetime.strptime(start_date, \"%Y-%m-%d\")\n        end_dt = datetime.strptime(end_date, \"%Y-%m-%d\")\n\n        news_str = \"\"\n        filtered_count = 0\n\n        for article in news:\n            data = _extract_article_data(article)\n\n            # Filter by date if publish time is available\n            if data[\"pub_date\"]:\n                pub_date_naive = data[\"pub_date\"].replace(tzinfo=None)\n                if not (start_dt <= pub_date_naive <= end_dt + relativedelta(days=1)):\n                    continue\n\n            news_str += f\"### {data['title']} (source: {data['publisher']})\\n\"\n            if data[\"summary\"]:\n                news_str += f\"{data['summary']}\\n\"\n            if data[\"link\"]:\n                news_str += f\"Link: {data['link']}\\n\"\n            news_str += \"\\n\"\n            filtered_count += 1\n\n        if filtered_count == 0:\n            return f\"No news found for {ticker} between {start_date} and {end_date}\"\n\n        return f\"## {ticker} News, from {start_date} to {end_date}:\\n\\n{news_str}\"\n\n    except Exception as e:\n        return f\"Error fetching news for {ticker}: {str(e)}\"\n\n\ndef get_global_news_yfinance(\n    curr_date: str,\n    look_back_days: int = 7,\n    limit: int = 10,\n) -> str:\n    \"\"\"\n    Retrieve global/macro economic news using yfinance Search.\n\n    Args:\n        curr_date: Current date in yyyy-mm-dd format\n        look_back_days: Number of days to look back\n        limit: Maximum number of articles to return\n\n    Returns:\n        Formatted string containing global news articles\n    \"\"\"\n    # Search queries for macro/global news\n    search_queries = [\n        \"stock market economy\",\n        \"Federal Reserve interest rates\",\n        \"inflation economic outlook\",\n        \"global markets trading\",\n    ]\n\n    all_news = []\n    seen_titles = set()\n\n    try:\n        for query in search_queries:\n            search = yf.Search(\n                query=query,\n                news_count=limit,\n                enable_fuzzy_query=True,\n            )\n\n            if search.news:\n                for article in search.news:\n                    # Handle both flat and nested structures\n                    if \"content\" in article:\n                        data = _extract_article_data(article)\n                        title = data[\"title\"]\n                    else:\n                        title = article.get(\"title\", \"\")\n\n                    # Deduplicate by title\n                    if title and title not in seen_titles:\n                        seen_titles.add(title)\n                        all_news.append(article)\n\n            if len(all_news) >= limit:\n                break\n\n        if not all_news:\n            return f\"No global news found for {curr_date}\"\n\n        # Calculate date range\n        curr_dt = datetime.strptime(curr_date, \"%Y-%m-%d\")\n        start_dt = curr_dt - relativedelta(days=look_back_days)\n        start_date = start_dt.strftime(\"%Y-%m-%d\")\n\n        news_str = \"\"\n        for article in all_news[:limit]:\n            # Handle both flat and nested structures\n            if \"content\" in article:\n                data = _extract_article_data(article)\n                title = data[\"title\"]\n                publisher = data[\"publisher\"]\n                link = data[\"link\"]\n                summary = data[\"summary\"]\n            else:\n                title = article.get(\"title\", \"No title\")\n                publisher = article.get(\"publisher\", \"Unknown\")\n                link = article.get(\"link\", \"\")\n                summary = \"\"\n\n            news_str += f\"### {title} (source: {publisher})\\n\"\n            if summary:\n                news_str += f\"{summary}\\n\"\n            if link:\n                news_str += f\"Link: {link}\\n\"\n            news_str += \"\\n\"\n\n        return f\"## Global Market News, from {start_date} to {curr_date}:\\n\\n{news_str}\"\n\n    except Exception as e:\n        return f\"Error fetching global news: {str(e)}\"\n"
  },
  {
    "path": "tradingagents/default_config.py",
    "content": "import os\n\nDEFAULT_CONFIG = {\n    \"project_dir\": os.path.abspath(os.path.join(os.path.dirname(__file__), \".\")),\n    \"results_dir\": os.getenv(\"TRADINGAGENTS_RESULTS_DIR\", \"./results\"),\n    \"data_cache_dir\": os.path.join(\n        os.path.abspath(os.path.join(os.path.dirname(__file__), \".\")),\n        \"dataflows/data_cache\",\n    ),\n    # LLM settings\n    \"llm_provider\": \"openai\",\n    \"deep_think_llm\": \"gpt-5.2\",\n    \"quick_think_llm\": \"gpt-5-mini\",\n    \"backend_url\": \"https://api.openai.com/v1\",\n    # Provider-specific thinking configuration\n    \"google_thinking_level\": None,      # \"high\", \"minimal\", etc.\n    \"openai_reasoning_effort\": None,    # \"medium\", \"high\", \"low\"\n    # Debate and discussion settings\n    \"max_debate_rounds\": 1,\n    \"max_risk_discuss_rounds\": 1,\n    \"max_recur_limit\": 100,\n    # Data vendor configuration\n    # Category-level configuration (default for all tools in category)\n    \"data_vendors\": {\n        \"core_stock_apis\": \"yfinance\",       # Options: alpha_vantage, yfinance\n        \"technical_indicators\": \"yfinance\",  # Options: alpha_vantage, yfinance\n        \"fundamental_data\": \"yfinance\",      # Options: alpha_vantage, yfinance\n        \"news_data\": \"yfinance\",             # Options: alpha_vantage, yfinance\n    },\n    # Tool-level configuration (takes precedence over category-level)\n    \"tool_vendors\": {\n        # Example: \"get_stock_data\": \"alpha_vantage\",  # Override category default\n    },\n}\n"
  },
  {
    "path": "tradingagents/graph/__init__.py",
    "content": "# TradingAgents/graph/__init__.py\n\nfrom .trading_graph import TradingAgentsGraph\nfrom .conditional_logic import ConditionalLogic\nfrom .setup import GraphSetup\nfrom .propagation import Propagator\nfrom .reflection import Reflector\nfrom .signal_processing import SignalProcessor\n\n__all__ = [\n    \"TradingAgentsGraph\",\n    \"ConditionalLogic\",\n    \"GraphSetup\",\n    \"Propagator\",\n    \"Reflector\",\n    \"SignalProcessor\",\n]\n"
  },
  {
    "path": "tradingagents/graph/conditional_logic.py",
    "content": "# TradingAgents/graph/conditional_logic.py\n\nfrom tradingagents.agents.utils.agent_states import AgentState\n\n\nclass ConditionalLogic:\n    \"\"\"Handles conditional logic for determining graph flow.\"\"\"\n\n    def __init__(self, max_debate_rounds=1, max_risk_discuss_rounds=1):\n        \"\"\"Initialize with configuration parameters.\"\"\"\n        self.max_debate_rounds = max_debate_rounds\n        self.max_risk_discuss_rounds = max_risk_discuss_rounds\n\n    def should_continue_market(self, state: AgentState):\n        \"\"\"Determine if market analysis should continue.\"\"\"\n        messages = state[\"messages\"]\n        last_message = messages[-1]\n        if last_message.tool_calls:\n            return \"tools_market\"\n        return \"Msg Clear Market\"\n\n    def should_continue_social(self, state: AgentState):\n        \"\"\"Determine if social media analysis should continue.\"\"\"\n        messages = state[\"messages\"]\n        last_message = messages[-1]\n        if last_message.tool_calls:\n            return \"tools_social\"\n        return \"Msg Clear Social\"\n\n    def should_continue_news(self, state: AgentState):\n        \"\"\"Determine if news analysis should continue.\"\"\"\n        messages = state[\"messages\"]\n        last_message = messages[-1]\n        if last_message.tool_calls:\n            return \"tools_news\"\n        return \"Msg Clear News\"\n\n    def should_continue_fundamentals(self, state: AgentState):\n        \"\"\"Determine if fundamentals analysis should continue.\"\"\"\n        messages = state[\"messages\"]\n        last_message = messages[-1]\n        if last_message.tool_calls:\n            return \"tools_fundamentals\"\n        return \"Msg Clear Fundamentals\"\n\n    def should_continue_debate(self, state: AgentState) -> str:\n        \"\"\"Determine if debate should continue.\"\"\"\n\n        if (\n            state[\"investment_debate_state\"][\"count\"] >= 2 * self.max_debate_rounds\n        ):  # 3 rounds of back-and-forth between 2 agents\n            return \"Research Manager\"\n        if state[\"investment_debate_state\"][\"current_response\"].startswith(\"Bull\"):\n            return \"Bear Researcher\"\n        return \"Bull Researcher\"\n\n    def should_continue_risk_analysis(self, state: AgentState) -> str:\n        \"\"\"Determine if risk analysis should continue.\"\"\"\n        if (\n            state[\"risk_debate_state\"][\"count\"] >= 3 * self.max_risk_discuss_rounds\n        ):  # 3 rounds of back-and-forth between 3 agents\n            return \"Risk Judge\"\n        if state[\"risk_debate_state\"][\"latest_speaker\"].startswith(\"Aggressive\"):\n            return \"Conservative Analyst\"\n        if state[\"risk_debate_state\"][\"latest_speaker\"].startswith(\"Conservative\"):\n            return \"Neutral Analyst\"\n        return \"Aggressive Analyst\"\n"
  },
  {
    "path": "tradingagents/graph/propagation.py",
    "content": "# TradingAgents/graph/propagation.py\n\nfrom typing import Dict, Any, List, Optional\nfrom tradingagents.agents.utils.agent_states import (\n    AgentState,\n    InvestDebateState,\n    RiskDebateState,\n)\n\n\nclass Propagator:\n    \"\"\"Handles state initialization and propagation through the graph.\"\"\"\n\n    def __init__(self, max_recur_limit=100):\n        \"\"\"Initialize with configuration parameters.\"\"\"\n        self.max_recur_limit = max_recur_limit\n\n    def create_initial_state(\n        self, company_name: str, trade_date: str\n    ) -> Dict[str, Any]:\n        \"\"\"Create the initial state for the agent graph.\"\"\"\n        return {\n            \"messages\": [(\"human\", company_name)],\n            \"company_of_interest\": company_name,\n            \"trade_date\": str(trade_date),\n            \"investment_debate_state\": InvestDebateState(\n                {\n                    \"bull_history\": \"\",\n                    \"bear_history\": \"\",\n                    \"history\": \"\",\n                    \"current_response\": \"\",\n                    \"judge_decision\": \"\",\n                    \"count\": 0,\n                }\n            ),\n            \"risk_debate_state\": RiskDebateState(\n                {\n                    \"aggressive_history\": \"\",\n                    \"conservative_history\": \"\",\n                    \"neutral_history\": \"\",\n                    \"history\": \"\",\n                    \"latest_speaker\": \"\",\n                    \"current_aggressive_response\": \"\",\n                    \"current_conservative_response\": \"\",\n                    \"current_neutral_response\": \"\",\n                    \"judge_decision\": \"\",\n                    \"count\": 0,\n                }\n            ),\n            \"market_report\": \"\",\n            \"fundamentals_report\": \"\",\n            \"sentiment_report\": \"\",\n            \"news_report\": \"\",\n        }\n\n    def get_graph_args(self, callbacks: Optional[List] = None) -> Dict[str, Any]:\n        \"\"\"Get arguments for the graph invocation.\n\n        Args:\n            callbacks: Optional list of callback handlers for tool execution tracking.\n                       Note: LLM callbacks are handled separately via LLM constructor.\n        \"\"\"\n        config = {\"recursion_limit\": self.max_recur_limit}\n        if callbacks:\n            config[\"callbacks\"] = callbacks\n        return {\n            \"stream_mode\": \"values\",\n            \"config\": config,\n        }\n"
  },
  {
    "path": "tradingagents/graph/reflection.py",
    "content": "# TradingAgents/graph/reflection.py\n\nfrom typing import Dict, Any\nfrom langchain_openai import ChatOpenAI\n\n\nclass Reflector:\n    \"\"\"Handles reflection on decisions and updating memory.\"\"\"\n\n    def __init__(self, quick_thinking_llm: ChatOpenAI):\n        \"\"\"Initialize the reflector with an LLM.\"\"\"\n        self.quick_thinking_llm = quick_thinking_llm\n        self.reflection_system_prompt = self._get_reflection_prompt()\n\n    def _get_reflection_prompt(self) -> str:\n        \"\"\"Get the system prompt for reflection.\"\"\"\n        return \"\"\"\nYou are an expert financial analyst tasked with reviewing trading decisions/analysis and providing a comprehensive, step-by-step analysis. \nYour goal is to deliver detailed insights into investment decisions and highlight opportunities for improvement, adhering strictly to the following guidelines:\n\n1. Reasoning:\n   - For each trading decision, determine whether it was correct or incorrect. A correct decision results in an increase in returns, while an incorrect decision does the opposite.\n   - Analyze the contributing factors to each success or mistake. Consider:\n     - Market intelligence.\n     - Technical indicators.\n     - Technical signals.\n     - Price movement analysis.\n     - Overall market data analysis \n     - News analysis.\n     - Social media and sentiment analysis.\n     - Fundamental data analysis.\n     - Weight the importance of each factor in the decision-making process.\n\n2. Improvement:\n   - For any incorrect decisions, propose revisions to maximize returns.\n   - Provide a detailed list of corrective actions or improvements, including specific recommendations (e.g., changing a decision from HOLD to BUY on a particular date).\n\n3. Summary:\n   - Summarize the lessons learned from the successes and mistakes.\n   - Highlight how these lessons can be adapted for future trading scenarios and draw connections between similar situations to apply the knowledge gained.\n\n4. Query:\n   - Extract key insights from the summary into a concise sentence of no more than 1000 tokens.\n   - Ensure the condensed sentence captures the essence of the lessons and reasoning for easy reference.\n\nAdhere strictly to these instructions, and ensure your output is detailed, accurate, and actionable. You will also be given objective descriptions of the market from a price movements, technical indicator, news, and sentiment perspective to provide more context for your analysis.\n\"\"\"\n\n    def _extract_current_situation(self, current_state: Dict[str, Any]) -> str:\n        \"\"\"Extract the current market situation from the state.\"\"\"\n        curr_market_report = current_state[\"market_report\"]\n        curr_sentiment_report = current_state[\"sentiment_report\"]\n        curr_news_report = current_state[\"news_report\"]\n        curr_fundamentals_report = current_state[\"fundamentals_report\"]\n\n        return f\"{curr_market_report}\\n\\n{curr_sentiment_report}\\n\\n{curr_news_report}\\n\\n{curr_fundamentals_report}\"\n\n    def _reflect_on_component(\n        self, component_type: str, report: str, situation: str, returns_losses\n    ) -> str:\n        \"\"\"Generate reflection for a component.\"\"\"\n        messages = [\n            (\"system\", self.reflection_system_prompt),\n            (\n                \"human\",\n                f\"Returns: {returns_losses}\\n\\nAnalysis/Decision: {report}\\n\\nObjective Market Reports for Reference: {situation}\",\n            ),\n        ]\n\n        result = self.quick_thinking_llm.invoke(messages).content\n        return result\n\n    def reflect_bull_researcher(self, current_state, returns_losses, bull_memory):\n        \"\"\"Reflect on bull researcher's analysis and update memory.\"\"\"\n        situation = self._extract_current_situation(current_state)\n        bull_debate_history = current_state[\"investment_debate_state\"][\"bull_history\"]\n\n        result = self._reflect_on_component(\n            \"BULL\", bull_debate_history, situation, returns_losses\n        )\n        bull_memory.add_situations([(situation, result)])\n\n    def reflect_bear_researcher(self, current_state, returns_losses, bear_memory):\n        \"\"\"Reflect on bear researcher's analysis and update memory.\"\"\"\n        situation = self._extract_current_situation(current_state)\n        bear_debate_history = current_state[\"investment_debate_state\"][\"bear_history\"]\n\n        result = self._reflect_on_component(\n            \"BEAR\", bear_debate_history, situation, returns_losses\n        )\n        bear_memory.add_situations([(situation, result)])\n\n    def reflect_trader(self, current_state, returns_losses, trader_memory):\n        \"\"\"Reflect on trader's decision and update memory.\"\"\"\n        situation = self._extract_current_situation(current_state)\n        trader_decision = current_state[\"trader_investment_plan\"]\n\n        result = self._reflect_on_component(\n            \"TRADER\", trader_decision, situation, returns_losses\n        )\n        trader_memory.add_situations([(situation, result)])\n\n    def reflect_invest_judge(self, current_state, returns_losses, invest_judge_memory):\n        \"\"\"Reflect on investment judge's decision and update memory.\"\"\"\n        situation = self._extract_current_situation(current_state)\n        judge_decision = current_state[\"investment_debate_state\"][\"judge_decision\"]\n\n        result = self._reflect_on_component(\n            \"INVEST JUDGE\", judge_decision, situation, returns_losses\n        )\n        invest_judge_memory.add_situations([(situation, result)])\n\n    def reflect_risk_manager(self, current_state, returns_losses, risk_manager_memory):\n        \"\"\"Reflect on risk manager's decision and update memory.\"\"\"\n        situation = self._extract_current_situation(current_state)\n        judge_decision = current_state[\"risk_debate_state\"][\"judge_decision\"]\n\n        result = self._reflect_on_component(\n            \"RISK JUDGE\", judge_decision, situation, returns_losses\n        )\n        risk_manager_memory.add_situations([(situation, result)])\n"
  },
  {
    "path": "tradingagents/graph/setup.py",
    "content": "# TradingAgents/graph/setup.py\n\nfrom typing import Dict, Any\nfrom langchain_openai import ChatOpenAI\nfrom langgraph.graph import END, StateGraph, START\nfrom langgraph.prebuilt import ToolNode\n\nfrom tradingagents.agents import *\nfrom tradingagents.agents.utils.agent_states import AgentState\n\nfrom .conditional_logic import ConditionalLogic\n\n\nclass GraphSetup:\n    \"\"\"Handles the setup and configuration of the agent graph.\"\"\"\n\n    def __init__(\n        self,\n        quick_thinking_llm: ChatOpenAI,\n        deep_thinking_llm: ChatOpenAI,\n        tool_nodes: Dict[str, ToolNode],\n        bull_memory,\n        bear_memory,\n        trader_memory,\n        invest_judge_memory,\n        risk_manager_memory,\n        conditional_logic: ConditionalLogic,\n    ):\n        \"\"\"Initialize with required components.\"\"\"\n        self.quick_thinking_llm = quick_thinking_llm\n        self.deep_thinking_llm = deep_thinking_llm\n        self.tool_nodes = tool_nodes\n        self.bull_memory = bull_memory\n        self.bear_memory = bear_memory\n        self.trader_memory = trader_memory\n        self.invest_judge_memory = invest_judge_memory\n        self.risk_manager_memory = risk_manager_memory\n        self.conditional_logic = conditional_logic\n\n    def setup_graph(\n        self, selected_analysts=[\"market\", \"social\", \"news\", \"fundamentals\"]\n    ):\n        \"\"\"Set up and compile the agent workflow graph.\n\n        Args:\n            selected_analysts (list): List of analyst types to include. Options are:\n                - \"market\": Market analyst\n                - \"social\": Social media analyst\n                - \"news\": News analyst\n                - \"fundamentals\": Fundamentals analyst\n        \"\"\"\n        if len(selected_analysts) == 0:\n            raise ValueError(\"Trading Agents Graph Setup Error: no analysts selected!\")\n\n        # Create analyst nodes\n        analyst_nodes = {}\n        delete_nodes = {}\n        tool_nodes = {}\n\n        if \"market\" in selected_analysts:\n            analyst_nodes[\"market\"] = create_market_analyst(\n                self.quick_thinking_llm\n            )\n            delete_nodes[\"market\"] = create_msg_delete()\n            tool_nodes[\"market\"] = self.tool_nodes[\"market\"]\n\n        if \"social\" in selected_analysts:\n            analyst_nodes[\"social\"] = create_social_media_analyst(\n                self.quick_thinking_llm\n            )\n            delete_nodes[\"social\"] = create_msg_delete()\n            tool_nodes[\"social\"] = self.tool_nodes[\"social\"]\n\n        if \"news\" in selected_analysts:\n            analyst_nodes[\"news\"] = create_news_analyst(\n                self.quick_thinking_llm\n            )\n            delete_nodes[\"news\"] = create_msg_delete()\n            tool_nodes[\"news\"] = self.tool_nodes[\"news\"]\n\n        if \"fundamentals\" in selected_analysts:\n            analyst_nodes[\"fundamentals\"] = create_fundamentals_analyst(\n                self.quick_thinking_llm\n            )\n            delete_nodes[\"fundamentals\"] = create_msg_delete()\n            tool_nodes[\"fundamentals\"] = self.tool_nodes[\"fundamentals\"]\n\n        # Create researcher and manager nodes\n        bull_researcher_node = create_bull_researcher(\n            self.quick_thinking_llm, self.bull_memory\n        )\n        bear_researcher_node = create_bear_researcher(\n            self.quick_thinking_llm, self.bear_memory\n        )\n        research_manager_node = create_research_manager(\n            self.deep_thinking_llm, self.invest_judge_memory\n        )\n        trader_node = create_trader(self.quick_thinking_llm, self.trader_memory)\n\n        # Create risk analysis nodes\n        aggressive_analyst = create_aggressive_debator(self.quick_thinking_llm)\n        neutral_analyst = create_neutral_debator(self.quick_thinking_llm)\n        conservative_analyst = create_conservative_debator(self.quick_thinking_llm)\n        risk_manager_node = create_risk_manager(\n            self.deep_thinking_llm, self.risk_manager_memory\n        )\n\n        # Create workflow\n        workflow = StateGraph(AgentState)\n\n        # Add analyst nodes to the graph\n        for analyst_type, node in analyst_nodes.items():\n            workflow.add_node(f\"{analyst_type.capitalize()} Analyst\", node)\n            workflow.add_node(\n                f\"Msg Clear {analyst_type.capitalize()}\", delete_nodes[analyst_type]\n            )\n            workflow.add_node(f\"tools_{analyst_type}\", tool_nodes[analyst_type])\n\n        # Add other nodes\n        workflow.add_node(\"Bull Researcher\", bull_researcher_node)\n        workflow.add_node(\"Bear Researcher\", bear_researcher_node)\n        workflow.add_node(\"Research Manager\", research_manager_node)\n        workflow.add_node(\"Trader\", trader_node)\n        workflow.add_node(\"Aggressive Analyst\", aggressive_analyst)\n        workflow.add_node(\"Neutral Analyst\", neutral_analyst)\n        workflow.add_node(\"Conservative Analyst\", conservative_analyst)\n        workflow.add_node(\"Risk Judge\", risk_manager_node)\n\n        # Define edges\n        # Start with the first analyst\n        first_analyst = selected_analysts[0]\n        workflow.add_edge(START, f\"{first_analyst.capitalize()} Analyst\")\n\n        # Connect analysts in sequence\n        for i, analyst_type in enumerate(selected_analysts):\n            current_analyst = f\"{analyst_type.capitalize()} Analyst\"\n            current_tools = f\"tools_{analyst_type}\"\n            current_clear = f\"Msg Clear {analyst_type.capitalize()}\"\n\n            # Add conditional edges for current analyst\n            workflow.add_conditional_edges(\n                current_analyst,\n                getattr(self.conditional_logic, f\"should_continue_{analyst_type}\"),\n                [current_tools, current_clear],\n            )\n            workflow.add_edge(current_tools, current_analyst)\n\n            # Connect to next analyst or to Bull Researcher if this is the last analyst\n            if i < len(selected_analysts) - 1:\n                next_analyst = f\"{selected_analysts[i+1].capitalize()} Analyst\"\n                workflow.add_edge(current_clear, next_analyst)\n            else:\n                workflow.add_edge(current_clear, \"Bull Researcher\")\n\n        # Add remaining edges\n        workflow.add_conditional_edges(\n            \"Bull Researcher\",\n            self.conditional_logic.should_continue_debate,\n            {\n                \"Bear Researcher\": \"Bear Researcher\",\n                \"Research Manager\": \"Research Manager\",\n            },\n        )\n        workflow.add_conditional_edges(\n            \"Bear Researcher\",\n            self.conditional_logic.should_continue_debate,\n            {\n                \"Bull Researcher\": \"Bull Researcher\",\n                \"Research Manager\": \"Research Manager\",\n            },\n        )\n        workflow.add_edge(\"Research Manager\", \"Trader\")\n        workflow.add_edge(\"Trader\", \"Aggressive Analyst\")\n        workflow.add_conditional_edges(\n            \"Aggressive Analyst\",\n            self.conditional_logic.should_continue_risk_analysis,\n            {\n                \"Conservative Analyst\": \"Conservative Analyst\",\n                \"Risk Judge\": \"Risk Judge\",\n            },\n        )\n        workflow.add_conditional_edges(\n            \"Conservative Analyst\",\n            self.conditional_logic.should_continue_risk_analysis,\n            {\n                \"Neutral Analyst\": \"Neutral Analyst\",\n                \"Risk Judge\": \"Risk Judge\",\n            },\n        )\n        workflow.add_conditional_edges(\n            \"Neutral Analyst\",\n            self.conditional_logic.should_continue_risk_analysis,\n            {\n                \"Aggressive Analyst\": \"Aggressive Analyst\",\n                \"Risk Judge\": \"Risk Judge\",\n            },\n        )\n\n        workflow.add_edge(\"Risk Judge\", END)\n\n        # Compile and return\n        return workflow.compile()\n"
  },
  {
    "path": "tradingagents/graph/signal_processing.py",
    "content": "# TradingAgents/graph/signal_processing.py\n\nfrom langchain_openai import ChatOpenAI\n\n\nclass SignalProcessor:\n    \"\"\"Processes trading signals to extract actionable decisions.\"\"\"\n\n    def __init__(self, quick_thinking_llm: ChatOpenAI):\n        \"\"\"Initialize with an LLM for processing.\"\"\"\n        self.quick_thinking_llm = quick_thinking_llm\n\n    def process_signal(self, full_signal: str) -> str:\n        \"\"\"\n        Process a full trading signal to extract the core decision.\n\n        Args:\n            full_signal: Complete trading signal text\n\n        Returns:\n            Extracted decision (BUY, SELL, or HOLD)\n        \"\"\"\n        messages = [\n            (\n                \"system\",\n                \"You are an efficient assistant designed to analyze paragraphs or financial reports provided by a group of analysts. Your task is to extract the investment decision: SELL, BUY, or HOLD. Provide only the extracted decision (SELL, BUY, or HOLD) as your output, without adding any additional text or information.\",\n            ),\n            (\"human\", full_signal),\n        ]\n\n        return self.quick_thinking_llm.invoke(messages).content\n"
  },
  {
    "path": "tradingagents/graph/trading_graph.py",
    "content": "# TradingAgents/graph/trading_graph.py\n\nimport os\nfrom pathlib import Path\nimport json\nfrom datetime import date\nfrom typing import Dict, Any, Tuple, List, Optional\n\nfrom langgraph.prebuilt import ToolNode\n\nfrom tradingagents.llm_clients import create_llm_client\n\nfrom tradingagents.agents import *\nfrom tradingagents.default_config import DEFAULT_CONFIG\nfrom tradingagents.agents.utils.memory import FinancialSituationMemory\nfrom tradingagents.agents.utils.agent_states import (\n    AgentState,\n    InvestDebateState,\n    RiskDebateState,\n)\nfrom tradingagents.dataflows.config import set_config\n\n# Import the new abstract tool methods from agent_utils\nfrom tradingagents.agents.utils.agent_utils import (\n    get_stock_data,\n    get_indicators,\n    get_fundamentals,\n    get_balance_sheet,\n    get_cashflow,\n    get_income_statement,\n    get_news,\n    get_insider_transactions,\n    get_global_news\n)\n\nfrom .conditional_logic import ConditionalLogic\nfrom .setup import GraphSetup\nfrom .propagation import Propagator\nfrom .reflection import Reflector\nfrom .signal_processing import SignalProcessor\n\n\nclass TradingAgentsGraph:\n    \"\"\"Main class that orchestrates the trading agents framework.\"\"\"\n\n    def __init__(\n        self,\n        selected_analysts=[\"market\", \"social\", \"news\", \"fundamentals\"],\n        debug=False,\n        config: Dict[str, Any] = None,\n        callbacks: Optional[List] = None,\n    ):\n        \"\"\"Initialize the trading agents graph and components.\n\n        Args:\n            selected_analysts: List of analyst types to include\n            debug: Whether to run in debug mode\n            config: Configuration dictionary. If None, uses default config\n            callbacks: Optional list of callback handlers (e.g., for tracking LLM/tool stats)\n        \"\"\"\n        self.debug = debug\n        self.config = config or DEFAULT_CONFIG\n        self.callbacks = callbacks or []\n\n        # Update the interface's config\n        set_config(self.config)\n\n        # Create necessary directories\n        os.makedirs(\n            os.path.join(self.config[\"project_dir\"], \"dataflows/data_cache\"),\n            exist_ok=True,\n        )\n\n        # Initialize LLMs with provider-specific thinking configuration\n        llm_kwargs = self._get_provider_kwargs()\n\n        # Add callbacks to kwargs if provided (passed to LLM constructor)\n        if self.callbacks:\n            llm_kwargs[\"callbacks\"] = self.callbacks\n\n        deep_client = create_llm_client(\n            provider=self.config[\"llm_provider\"],\n            model=self.config[\"deep_think_llm\"],\n            base_url=self.config.get(\"backend_url\"),\n            **llm_kwargs,\n        )\n        quick_client = create_llm_client(\n            provider=self.config[\"llm_provider\"],\n            model=self.config[\"quick_think_llm\"],\n            base_url=self.config.get(\"backend_url\"),\n            **llm_kwargs,\n        )\n\n        self.deep_thinking_llm = deep_client.get_llm()\n        self.quick_thinking_llm = quick_client.get_llm()\n        \n        # Initialize memories\n        self.bull_memory = FinancialSituationMemory(\"bull_memory\", self.config)\n        self.bear_memory = FinancialSituationMemory(\"bear_memory\", self.config)\n        self.trader_memory = FinancialSituationMemory(\"trader_memory\", self.config)\n        self.invest_judge_memory = FinancialSituationMemory(\"invest_judge_memory\", self.config)\n        self.risk_manager_memory = FinancialSituationMemory(\"risk_manager_memory\", self.config)\n\n        # Create tool nodes\n        self.tool_nodes = self._create_tool_nodes()\n\n        # Initialize components\n        self.conditional_logic = ConditionalLogic(\n            max_debate_rounds=self.config[\"max_debate_rounds\"],\n            max_risk_discuss_rounds=self.config[\"max_risk_discuss_rounds\"],\n        )\n        self.graph_setup = GraphSetup(\n            self.quick_thinking_llm,\n            self.deep_thinking_llm,\n            self.tool_nodes,\n            self.bull_memory,\n            self.bear_memory,\n            self.trader_memory,\n            self.invest_judge_memory,\n            self.risk_manager_memory,\n            self.conditional_logic,\n        )\n\n        self.propagator = Propagator()\n        self.reflector = Reflector(self.quick_thinking_llm)\n        self.signal_processor = SignalProcessor(self.quick_thinking_llm)\n\n        # State tracking\n        self.curr_state = None\n        self.ticker = None\n        self.log_states_dict = {}  # date to full state dict\n\n        # Set up the graph\n        self.graph = self.graph_setup.setup_graph(selected_analysts)\n\n    def _get_provider_kwargs(self) -> Dict[str, Any]:\n        \"\"\"Get provider-specific kwargs for LLM client creation.\"\"\"\n        kwargs = {}\n        provider = self.config.get(\"llm_provider\", \"\").lower()\n\n        if provider == \"google\":\n            thinking_level = self.config.get(\"google_thinking_level\")\n            if thinking_level:\n                kwargs[\"thinking_level\"] = thinking_level\n\n        elif provider == \"openai\":\n            reasoning_effort = self.config.get(\"openai_reasoning_effort\")\n            if reasoning_effort:\n                kwargs[\"reasoning_effort\"] = reasoning_effort\n\n        return kwargs\n\n    def _create_tool_nodes(self) -> Dict[str, ToolNode]:\n        \"\"\"Create tool nodes for different data sources using abstract methods.\"\"\"\n        return {\n            \"market\": ToolNode(\n                [\n                    # Core stock data tools\n                    get_stock_data,\n                    # Technical indicators\n                    get_indicators,\n                ]\n            ),\n            \"social\": ToolNode(\n                [\n                    # News tools for social media analysis\n                    get_news,\n                ]\n            ),\n            \"news\": ToolNode(\n                [\n                    # News and insider information\n                    get_news,\n                    get_global_news,\n                    get_insider_transactions,\n                ]\n            ),\n            \"fundamentals\": ToolNode(\n                [\n                    # Fundamental analysis tools\n                    get_fundamentals,\n                    get_balance_sheet,\n                    get_cashflow,\n                    get_income_statement,\n                ]\n            ),\n        }\n\n    def propagate(self, company_name, trade_date):\n        \"\"\"Run the trading agents graph for a company on a specific date.\"\"\"\n\n        self.ticker = company_name\n\n        # Initialize state\n        init_agent_state = self.propagator.create_initial_state(\n            company_name, trade_date\n        )\n        args = self.propagator.get_graph_args()\n\n        if self.debug:\n            # Debug mode with tracing\n            trace = []\n            for chunk in self.graph.stream(init_agent_state, **args):\n                if len(chunk[\"messages\"]) == 0:\n                    pass\n                else:\n                    chunk[\"messages\"][-1].pretty_print()\n                    trace.append(chunk)\n\n            final_state = trace[-1]\n        else:\n            # Standard mode without tracing\n            final_state = self.graph.invoke(init_agent_state, **args)\n\n        # Store current state for reflection\n        self.curr_state = final_state\n\n        # Log state\n        self._log_state(trade_date, final_state)\n\n        # Return decision and processed signal\n        return final_state, self.process_signal(final_state[\"final_trade_decision\"])\n\n    def _log_state(self, trade_date, final_state):\n        \"\"\"Log the final state to a JSON file.\"\"\"\n        self.log_states_dict[str(trade_date)] = {\n            \"company_of_interest\": final_state[\"company_of_interest\"],\n            \"trade_date\": final_state[\"trade_date\"],\n            \"market_report\": final_state[\"market_report\"],\n            \"sentiment_report\": final_state[\"sentiment_report\"],\n            \"news_report\": final_state[\"news_report\"],\n            \"fundamentals_report\": final_state[\"fundamentals_report\"],\n            \"investment_debate_state\": {\n                \"bull_history\": final_state[\"investment_debate_state\"][\"bull_history\"],\n                \"bear_history\": final_state[\"investment_debate_state\"][\"bear_history\"],\n                \"history\": final_state[\"investment_debate_state\"][\"history\"],\n                \"current_response\": final_state[\"investment_debate_state\"][\n                    \"current_response\"\n                ],\n                \"judge_decision\": final_state[\"investment_debate_state\"][\n                    \"judge_decision\"\n                ],\n            },\n            \"trader_investment_decision\": final_state[\"trader_investment_plan\"],\n            \"risk_debate_state\": {\n                \"aggressive_history\": final_state[\"risk_debate_state\"][\"aggressive_history\"],\n                \"conservative_history\": final_state[\"risk_debate_state\"][\"conservative_history\"],\n                \"neutral_history\": final_state[\"risk_debate_state\"][\"neutral_history\"],\n                \"history\": final_state[\"risk_debate_state\"][\"history\"],\n                \"judge_decision\": final_state[\"risk_debate_state\"][\"judge_decision\"],\n            },\n            \"investment_plan\": final_state[\"investment_plan\"],\n            \"final_trade_decision\": final_state[\"final_trade_decision\"],\n        }\n\n        # Save to file\n        directory = Path(f\"eval_results/{self.ticker}/TradingAgentsStrategy_logs/\")\n        directory.mkdir(parents=True, exist_ok=True)\n\n        with open(\n            f\"eval_results/{self.ticker}/TradingAgentsStrategy_logs/full_states_log_{trade_date}.json\",\n            \"w\",\n            encoding=\"utf-8\",\n        ) as f:\n            json.dump(self.log_states_dict, f, indent=4)\n\n    def reflect_and_remember(self, returns_losses):\n        \"\"\"Reflect on decisions and update memory based on returns.\"\"\"\n        self.reflector.reflect_bull_researcher(\n            self.curr_state, returns_losses, self.bull_memory\n        )\n        self.reflector.reflect_bear_researcher(\n            self.curr_state, returns_losses, self.bear_memory\n        )\n        self.reflector.reflect_trader(\n            self.curr_state, returns_losses, self.trader_memory\n        )\n        self.reflector.reflect_invest_judge(\n            self.curr_state, returns_losses, self.invest_judge_memory\n        )\n        self.reflector.reflect_risk_manager(\n            self.curr_state, returns_losses, self.risk_manager_memory\n        )\n\n    def process_signal(self, full_signal):\n        \"\"\"Process a signal to extract the core decision.\"\"\"\n        return self.signal_processor.process_signal(full_signal)\n"
  },
  {
    "path": "tradingagents/llm_clients/TODO.md",
    "content": "# LLM Clients - Consistency Improvements\n\n## Issues to Fix\n\n### 1. `validate_model()` is never called\n- Add validation call in `get_llm()` with warning (not error) for unknown models\n\n### 2. Inconsistent parameter handling\n| Client | API Key Param | Special Params |\n|--------|---------------|----------------|\n| OpenAI | `api_key` | `reasoning_effort` |\n| Anthropic | `api_key` | `thinking_config` → `thinking` |\n| Google | `google_api_key` | `thinking_budget` |\n\n**Fix:** Standardize with unified `api_key` that maps to provider-specific keys\n\n### 3. `base_url` accepted but ignored\n- `AnthropicClient`: accepts `base_url` but never uses it\n- `GoogleClient`: accepts `base_url` but never uses it (correct - Google doesn't support it)\n\n**Fix:** Remove unused `base_url` from clients that don't support it\n\n### 4. Update validators.py with models from CLI\n- Sync `VALID_MODELS` dict with CLI model options after Feature 2 is complete\n"
  },
  {
    "path": "tradingagents/llm_clients/__init__.py",
    "content": "from .base_client import BaseLLMClient\nfrom .factory import create_llm_client\n\n__all__ = [\"BaseLLMClient\", \"create_llm_client\"]\n"
  },
  {
    "path": "tradingagents/llm_clients/anthropic_client.py",
    "content": "from typing import Any, Optional\n\nfrom langchain_anthropic import ChatAnthropic\n\nfrom .base_client import BaseLLMClient\nfrom .validators import validate_model\n\n\nclass AnthropicClient(BaseLLMClient):\n    \"\"\"Client for Anthropic Claude models.\"\"\"\n\n    def __init__(self, model: str, base_url: Optional[str] = None, **kwargs):\n        super().__init__(model, base_url, **kwargs)\n\n    def get_llm(self) -> Any:\n        \"\"\"Return configured ChatAnthropic instance.\"\"\"\n        llm_kwargs = {\"model\": self.model}\n\n        for key in (\"timeout\", \"max_retries\", \"api_key\", \"max_tokens\", \"callbacks\", \"http_client\", \"http_async_client\"):\n            if key in self.kwargs:\n                llm_kwargs[key] = self.kwargs[key]\n\n        return ChatAnthropic(**llm_kwargs)\n\n    def validate_model(self) -> bool:\n        \"\"\"Validate model for Anthropic.\"\"\"\n        return validate_model(\"anthropic\", self.model)\n"
  },
  {
    "path": "tradingagents/llm_clients/base_client.py",
    "content": "from abc import ABC, abstractmethod\nfrom typing import Any, Optional\n\n\nclass BaseLLMClient(ABC):\n    \"\"\"Abstract base class for LLM clients.\"\"\"\n\n    def __init__(self, model: str, base_url: Optional[str] = None, **kwargs):\n        self.model = model\n        self.base_url = base_url\n        self.kwargs = kwargs\n\n    @abstractmethod\n    def get_llm(self) -> Any:\n        \"\"\"Return the configured LLM instance.\"\"\"\n        pass\n\n    @abstractmethod\n    def validate_model(self) -> bool:\n        \"\"\"Validate that the model is supported by this client.\"\"\"\n        pass\n"
  },
  {
    "path": "tradingagents/llm_clients/factory.py",
    "content": "from typing import Optional\n\nfrom .base_client import BaseLLMClient\nfrom .openai_client import OpenAIClient\nfrom .anthropic_client import AnthropicClient\nfrom .google_client import GoogleClient\n\n\ndef create_llm_client(\n    provider: str,\n    model: str,\n    base_url: Optional[str] = None,\n    **kwargs,\n) -> BaseLLMClient:\n    \"\"\"Create an LLM client for the specified provider.\n\n    Args:\n        provider: LLM provider (openai, anthropic, google, xai, ollama, openrouter)\n        model: Model name/identifier\n        base_url: Optional base URL for API endpoint\n        **kwargs: Additional provider-specific arguments\n            - http_client: Custom httpx.Client for SSL proxy or certificate customization\n            - http_async_client: Custom httpx.AsyncClient for async operations\n            - timeout: Request timeout in seconds\n            - max_retries: Maximum retry attempts\n            - api_key: API key for the provider\n            - callbacks: LangChain callbacks\n\n    Returns:\n        Configured BaseLLMClient instance\n\n    Raises:\n        ValueError: If provider is not supported\n    \"\"\"\n    provider_lower = provider.lower()\n\n    if provider_lower in (\"openai\", \"ollama\", \"openrouter\"):\n        return OpenAIClient(model, base_url, provider=provider_lower, **kwargs)\n\n    if provider_lower == \"xai\":\n        return OpenAIClient(model, base_url, provider=\"xai\", **kwargs)\n\n    if provider_lower == \"anthropic\":\n        return AnthropicClient(model, base_url, **kwargs)\n\n    if provider_lower == \"google\":\n        return GoogleClient(model, base_url, **kwargs)\n\n    raise ValueError(f\"Unsupported LLM provider: {provider}\")\n"
  },
  {
    "path": "tradingagents/llm_clients/google_client.py",
    "content": "from typing import Any, Optional\n\nfrom langchain_google_genai import ChatGoogleGenerativeAI\n\nfrom .base_client import BaseLLMClient\nfrom .validators import validate_model\n\n\nclass NormalizedChatGoogleGenerativeAI(ChatGoogleGenerativeAI):\n    \"\"\"ChatGoogleGenerativeAI with normalized content output.\n\n    Gemini 3 models return content as list: [{'type': 'text', 'text': '...'}]\n    This normalizes to string for consistent downstream handling.\n    \"\"\"\n\n    def _normalize_content(self, response):\n        content = response.content\n        if isinstance(content, list):\n            texts = [\n                item.get(\"text\", \"\") if isinstance(item, dict) and item.get(\"type\") == \"text\"\n                else item if isinstance(item, str) else \"\"\n                for item in content\n            ]\n            response.content = \"\\n\".join(t for t in texts if t)\n        return response\n\n    def invoke(self, input, config=None, **kwargs):\n        return self._normalize_content(super().invoke(input, config, **kwargs))\n\n\nclass GoogleClient(BaseLLMClient):\n    \"\"\"Client for Google Gemini models.\"\"\"\n\n    def __init__(self, model: str, base_url: Optional[str] = None, **kwargs):\n        super().__init__(model, base_url, **kwargs)\n\n    def get_llm(self) -> Any:\n        \"\"\"Return configured ChatGoogleGenerativeAI instance.\"\"\"\n        llm_kwargs = {\"model\": self.model}\n\n        for key in (\"timeout\", \"max_retries\", \"google_api_key\", \"callbacks\", \"http_client\", \"http_async_client\"):\n            if key in self.kwargs:\n                llm_kwargs[key] = self.kwargs[key]\n\n        # Map thinking_level to appropriate API param based on model\n        # Gemini 3 Pro: low, high\n        # Gemini 3 Flash: minimal, low, medium, high\n        # Gemini 2.5: thinking_budget (0=disable, -1=dynamic)\n        thinking_level = self.kwargs.get(\"thinking_level\")\n        if thinking_level:\n            model_lower = self.model.lower()\n            if \"gemini-3\" in model_lower:\n                # Gemini 3 Pro doesn't support \"minimal\", use \"low\" instead\n                if \"pro\" in model_lower and thinking_level == \"minimal\":\n                    thinking_level = \"low\"\n                llm_kwargs[\"thinking_level\"] = thinking_level\n            else:\n                # Gemini 2.5: map to thinking_budget\n                llm_kwargs[\"thinking_budget\"] = -1 if thinking_level == \"high\" else 0\n\n        return NormalizedChatGoogleGenerativeAI(**llm_kwargs)\n\n    def validate_model(self) -> bool:\n        \"\"\"Validate model for Google.\"\"\"\n        return validate_model(\"google\", self.model)\n"
  },
  {
    "path": "tradingagents/llm_clients/openai_client.py",
    "content": "import os\nfrom typing import Any, Optional\n\nfrom langchain_openai import ChatOpenAI\n\nfrom .base_client import BaseLLMClient\nfrom .validators import validate_model\n\n\nclass UnifiedChatOpenAI(ChatOpenAI):\n    \"\"\"ChatOpenAI subclass that strips temperature/top_p for GPT-5 family models.\n\n    GPT-5 family models use reasoning natively. temperature/top_p are only\n    accepted when reasoning.effort is 'none'; with any other effort level\n    (or for older GPT-5/GPT-5-mini/GPT-5-nano which always reason) the API\n    rejects these params. Langchain defaults temperature=0.7, so we must\n    strip it to avoid errors.\n\n    Non-GPT-5 models (GPT-4.1, xAI, Ollama, etc.) are unaffected.\n    \"\"\"\n\n    def __init__(self, **kwargs):\n        if \"gpt-5\" in kwargs.get(\"model\", \"\").lower():\n            kwargs.pop(\"temperature\", None)\n            kwargs.pop(\"top_p\", None)\n        super().__init__(**kwargs)\n\n\nclass OpenAIClient(BaseLLMClient):\n    \"\"\"Client for OpenAI, Ollama, OpenRouter, and xAI providers.\"\"\"\n\n    def __init__(\n        self,\n        model: str,\n        base_url: Optional[str] = None,\n        provider: str = \"openai\",\n        **kwargs,\n    ):\n        super().__init__(model, base_url, **kwargs)\n        self.provider = provider.lower()\n\n    def get_llm(self) -> Any:\n        \"\"\"Return configured ChatOpenAI instance.\"\"\"\n        llm_kwargs = {\"model\": self.model}\n\n        if self.provider == \"xai\":\n            llm_kwargs[\"base_url\"] = \"https://api.x.ai/v1\"\n            api_key = os.environ.get(\"XAI_API_KEY\")\n            if api_key:\n                llm_kwargs[\"api_key\"] = api_key\n        elif self.provider == \"openrouter\":\n            llm_kwargs[\"base_url\"] = \"https://openrouter.ai/api/v1\"\n            api_key = os.environ.get(\"OPENROUTER_API_KEY\")\n            if api_key:\n                llm_kwargs[\"api_key\"] = api_key\n        elif self.provider == \"ollama\":\n            llm_kwargs[\"base_url\"] = \"http://localhost:11434/v1\"\n            llm_kwargs[\"api_key\"] = \"ollama\"  # Ollama doesn't require auth\n        elif self.base_url:\n            llm_kwargs[\"base_url\"] = self.base_url\n\n        for key in (\"timeout\", \"max_retries\", \"reasoning_effort\", \"api_key\", \"callbacks\", \"http_client\", \"http_async_client\"):\n            if key in self.kwargs:\n                llm_kwargs[key] = self.kwargs[key]\n\n        return UnifiedChatOpenAI(**llm_kwargs)\n\n    def validate_model(self) -> bool:\n        \"\"\"Validate model for the provider.\"\"\"\n        return validate_model(self.provider, self.model)\n"
  },
  {
    "path": "tradingagents/llm_clients/validators.py",
    "content": "\"\"\"Model name validators for each provider.\n\nOnly validates model names - does NOT enforce limits.\nLet LLM providers use their own defaults for unspecified params.\n\"\"\"\n\nVALID_MODELS = {\n    \"openai\": [\n        # GPT-5 series\n        \"gpt-5.4-pro\",\n        \"gpt-5.4\",\n        \"gpt-5.2\",\n        \"gpt-5.1\",\n        \"gpt-5\",\n        \"gpt-5-mini\",\n        \"gpt-5-nano\",\n        # GPT-4.1 series\n        \"gpt-4.1\",\n        \"gpt-4.1-mini\",\n        \"gpt-4.1-nano\",\n    ],\n    \"anthropic\": [\n        # Claude 4.6 series (latest)\n        \"claude-opus-4-6\",\n        \"claude-sonnet-4-6\",\n        # Claude 4.5 series\n        \"claude-opus-4-5\",\n        \"claude-sonnet-4-5\",\n        \"claude-haiku-4-5\",\n    ],\n    \"google\": [\n        # Gemini 3.1 series (preview)\n        \"gemini-3.1-pro-preview\",\n        \"gemini-3.1-flash-lite-preview\",\n        # Gemini 3 series (preview)\n        \"gemini-3-flash-preview\",\n        # Gemini 2.5 series\n        \"gemini-2.5-pro\",\n        \"gemini-2.5-flash\",\n        \"gemini-2.5-flash-lite\",\n    ],\n    \"xai\": [\n        # Grok 4.1 series\n        \"grok-4-1-fast-reasoning\",\n        \"grok-4-1-fast-non-reasoning\",\n        # Grok 4 series\n        \"grok-4-0709\",\n        \"grok-4-fast-reasoning\",\n        \"grok-4-fast-non-reasoning\",\n    ],\n}\n\n\ndef validate_model(provider: str, model: str) -> bool:\n    \"\"\"Check if model name is valid for the given provider.\n\n    For ollama, openrouter - any model is accepted.\n    \"\"\"\n    provider_lower = provider.lower()\n\n    if provider_lower in (\"ollama\", \"openrouter\"):\n        return True\n\n    if provider_lower not in VALID_MODELS:\n        return True\n\n    return model in VALID_MODELS[provider_lower]\n"
  }
]