The response has been limited to 50k tokens of the smallest files in the repo. You can remove this limitation by removing the max tokens filter.
├── .gitignore
├── .python-version
├── LICENSE
├── README.md
├── assets
    ├── TauricResearch.png
    ├── analyst.png
    ├── cli
    │   ├── cli_init.png
    │   ├── cli_news.png
    │   ├── cli_technical.png
    │   └── cli_transaction.png
    ├── researcher.png
    ├── risk.png
    ├── schema.png
    ├── trader.png
    └── wechat.png
├── cli
    ├── __init__.py
    ├── main.py
    ├── models.py
    ├── static
    │   └── welcome.txt
    └── utils.py
├── main.py
├── pyproject.toml
├── requirements.txt
├── setup.py
├── tradingagents
    ├── agents
    │   ├── __init__.py
    │   ├── analysts
    │   │   ├── fundamentals_analyst.py
    │   │   ├── market_analyst.py
    │   │   ├── news_analyst.py
    │   │   └── social_media_analyst.py
    │   ├── managers
    │   │   ├── research_manager.py
    │   │   └── risk_manager.py
    │   ├── researchers
    │   │   ├── bear_researcher.py
    │   │   └── bull_researcher.py
    │   ├── risk_mgmt
    │   │   ├── aggresive_debator.py
    │   │   ├── conservative_debator.py
    │   │   └── neutral_debator.py
    │   ├── trader
    │   │   └── trader.py
    │   └── utils
    │   │   ├── agent_states.py
    │   │   ├── agent_utils.py
    │   │   └── memory.py
    ├── dataflows
    │   ├── __init__.py
    │   ├── config.py
    │   ├── finnhub_utils.py
    │   ├── googlenews_utils.py
    │   ├── interface.py
    │   ├── reddit_utils.py
    │   ├── stockstats_utils.py
    │   ├── utils.py
    │   └── yfin_utils.py
    ├── default_config.py
    └── graph
    │   ├── __init__.py
    │   ├── conditional_logic.py
    │   ├── propagation.py
    │   ├── reflection.py
    │   ├── setup.py
    │   ├── signal_processing.py
    │   └── trading_graph.py
└── uv.lock


/.gitignore:
--------------------------------------------------------------------------------
 1 | env/
 2 | __pycache__/
 3 | .DS_Store
 4 | *.csv
 5 | src/
 6 | eval_results/
 7 | eval_data/
 8 | *.egg-info/
 9 | .env
10 | 


--------------------------------------------------------------------------------
/.python-version:
--------------------------------------------------------------------------------
1 | 3.10
2 | 


--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
  1 |                                  Apache License
  2 |                            Version 2.0, January 2004
  3 |                         http://www.apache.org/licenses/
  4 | 
  5 |    TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
  6 | 
  7 |    1. Definitions.
  8 | 
  9 |       "License" shall mean the terms and conditions for use, reproduction,
 10 |       and distribution as defined by Sections 1 through 9 of this document.
 11 | 
 12 |       "Licensor" shall mean the copyright owner or entity authorized by
 13 |       the copyright owner that is granting the License.
 14 | 
 15 |       "Legal Entity" shall mean the union of the acting entity and all
 16 |       other entities that control, are controlled by, or are under common
 17 |       control with that entity. For the purposes of this definition,
 18 |       "control" means (i) the power, direct or indirect, to cause the
 19 |       direction or management of such entity, whether by contract or
 20 |       otherwise, or (ii) ownership of fifty percent (50%) or more of the
 21 |       outstanding shares, or (iii) beneficial ownership of such entity.
 22 | 
 23 |       "You" (or "Your") shall mean an individual or Legal Entity
 24 |       exercising permissions granted by this License.
 25 | 
 26 |       "Source" form shall mean the preferred form for making modifications,
 27 |       including but not limited to software source code, documentation
 28 |       source, and configuration files.
 29 | 
 30 |       "Object" form shall mean any form resulting from mechanical
 31 |       transformation or translation of a Source form, including but
 32 |       not limited to compiled object code, generated documentation,
 33 |       and conversions to other media types.
 34 | 
 35 |       "Work" shall mean the work of authorship, whether in Source or
 36 |       Object form, made available under the License, as indicated by a
 37 |       copyright notice that is included in or attached to the work
 38 |       (an example is provided in the Appendix below).
 39 | 
 40 |       "Derivative Works" shall mean any work, whether in Source or Object
 41 |       form, that is based on (or derived from) the Work and for which the
 42 |       editorial revisions, annotations, elaborations, or other modifications
 43 |       represent, as a whole, an original work of authorship. For the purposes
 44 |       of this License, Derivative Works shall not include works that remain
 45 |       separable from, or merely link (or bind by name) to the interfaces of,
 46 |       the Work and Derivative Works thereof.
 47 | 
 48 |       "Contribution" shall mean any work of authorship, including
 49 |       the original version of the Work and any modifications or additions
 50 |       to that Work or Derivative Works thereof, that is intentionally
 51 |       submitted to Licensor for inclusion in the Work by the copyright owner
 52 |       or by an individual or Legal Entity authorized to submit on behalf of
 53 |       the copyright owner. For the purposes of this definition, "submitted"
 54 |       means any form of electronic, verbal, or written communication sent
 55 |       to the Licensor or its representatives, including but not limited to
 56 |       communication on electronic mailing lists, source code control systems,
 57 |       and issue tracking systems that are managed by, or on behalf of, the
 58 |       Licensor for the purpose of discussing and improving the Work, but
 59 |       excluding communication that is conspicuously marked or otherwise
 60 |       designated in writing by the copyright owner as "Not a Contribution."
 61 | 
 62 |       "Contributor" shall mean Licensor and any individual or Legal Entity
 63 |       on behalf of whom a Contribution has been received by Licensor and
 64 |       subsequently incorporated within the Work.
 65 | 
 66 |    2. Grant of Copyright License. Subject to the terms and conditions of
 67 |       this License, each Contributor hereby grants to You a perpetual,
 68 |       worldwide, non-exclusive, no-charge, royalty-free, irrevocable
 69 |       copyright license to reproduce, prepare Derivative Works of,
 70 |       publicly display, publicly perform, sublicense, and distribute the
 71 |       Work and such Derivative Works in Source or Object form.
 72 | 
 73 |    3. Grant of Patent License. Subject to the terms and conditions of
 74 |       this License, each Contributor hereby grants to You a perpetual,
 75 |       worldwide, non-exclusive, no-charge, royalty-free, irrevocable
 76 |       (except as stated in this section) patent license to make, have made,
 77 |       use, offer to sell, sell, import, and otherwise transfer the Work,
 78 |       where such license applies only to those patent claims licensable
 79 |       by such Contributor that are necessarily infringed by their
 80 |       Contribution(s) alone or by combination of their Contribution(s)
 81 |       with the Work to which such Contribution(s) was submitted. If You
 82 |       institute patent litigation against any entity (including a
 83 |       cross-claim or counterclaim in a lawsuit) alleging that the Work
 84 |       or a Contribution incorporated within the Work constitutes direct
 85 |       or contributory patent infringement, then any patent licenses
 86 |       granted to You under this License for that Work shall terminate
 87 |       as of the date such litigation is filed.
 88 | 
 89 |    4. Redistribution. You may reproduce and distribute copies of the
 90 |       Work or Derivative Works thereof in any medium, with or without
 91 |       modifications, and in Source or Object form, provided that You
 92 |       meet the following conditions:
 93 | 
 94 |       (a) You must give any other recipients of the Work or
 95 |           Derivative Works a copy of this License; and
 96 | 
 97 |       (b) You must cause any modified files to carry prominent notices
 98 |           stating that You changed the files; and
 99 | 
100 |       (c) You must retain, in the Source form of any Derivative Works
101 |           that You distribute, all copyright, patent, trademark, and
102 |           attribution notices from the Source form of the Work,
103 |           excluding those notices that do not pertain to any part of
104 |           the Derivative Works; and
105 | 
106 |       (d) If the Work includes a "NOTICE" text file as part of its
107 |           distribution, then any Derivative Works that You distribute must
108 |           include a readable copy of the attribution notices contained
109 |           within such NOTICE file, excluding those notices that do not
110 |           pertain to any part of the Derivative Works, in at least one
111 |           of the following places: within a NOTICE text file distributed
112 |           as part of the Derivative Works; within the Source form or
113 |           documentation, if provided along with the Derivative Works; or,
114 |           within a display generated by the Derivative Works, if and
115 |           wherever such third-party notices normally appear. The contents
116 |           of the NOTICE file are for informational purposes only and
117 |           do not modify the License. You may add Your own attribution
118 |           notices within Derivative Works that You distribute, alongside
119 |           or as an addendum to the NOTICE text from the Work, provided
120 |           that such additional attribution notices cannot be construed
121 |           as modifying the License.
122 | 
123 |       You may add Your own copyright statement to Your modifications and
124 |       may provide additional or different license terms and conditions
125 |       for use, reproduction, or distribution of Your modifications, or
126 |       for any such Derivative Works as a whole, provided Your use,
127 |       reproduction, and distribution of the Work otherwise complies with
128 |       the conditions stated in this License.
129 | 
130 |    5. Submission of Contributions. Unless You explicitly state otherwise,
131 |       any Contribution intentionally submitted for inclusion in the Work
132 |       by You to the Licensor shall be under the terms and conditions of
133 |       this License, without any additional terms or conditions.
134 |       Notwithstanding the above, nothing herein shall supersede or modify
135 |       the terms of any separate license agreement you may have executed
136 |       with Licensor regarding such Contributions.
137 | 
138 |    6. Trademarks. This License does not grant permission to use the trade
139 |       names, trademarks, service marks, or product names of the Licensor,
140 |       except as required for reasonable and customary use in describing the
141 |       origin of the Work and reproducing the content of the NOTICE file.
142 | 
143 |    7. Disclaimer of Warranty. Unless required by applicable law or
144 |       agreed to in writing, Licensor provides the Work (and each
145 |       Contributor provides its Contributions) on an "AS IS" BASIS,
146 |       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 |       implied, including, without limitation, any warranties or conditions
148 |       of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 |       PARTICULAR PURPOSE. You are solely responsible for determining the
150 |       appropriateness of using or redistributing the Work and assume any
151 |       risks associated with Your exercise of permissions under this License.
152 | 
153 |    8. Limitation of Liability. In no event and under no legal theory,
154 |       whether in tort (including negligence), contract, or otherwise,
155 |       unless required by applicable law (such as deliberate and grossly
156 |       negligent acts) or agreed to in writing, shall any Contributor be
157 |       liable to You for damages, including any direct, indirect, special,
158 |       incidental, or consequential damages of any character arising as a
159 |       result of this License or out of the use or inability to use the
160 |       Work (including but not limited to damages for loss of goodwill,
161 |       work stoppage, computer failure or malfunction, or any and all
162 |       other commercial damages or losses), even if such Contributor
163 |       has been advised of the possibility of such damages.
164 | 
165 |    9. Accepting Warranty or Additional Liability. While redistributing
166 |       the Work or Derivative Works thereof, You may choose to offer,
167 |       and charge a fee for, acceptance of support, warranty, indemnity,
168 |       or other liability obligations and/or rights consistent with this
169 |       License. However, in accepting such obligations, You may act only
170 |       on Your own behalf and on Your sole responsibility, not on behalf
171 |       of any other Contributor, and only if You agree to indemnify,
172 |       defend, and hold each Contributor harmless for any liability
173 |       incurred by, or claims asserted against, such Contributor by reason
174 |       of your accepting any such warranty or additional liability.
175 | 
176 |    END OF TERMS AND CONDITIONS
177 | 
178 |    APPENDIX: How to apply the Apache License to your work.
179 | 
180 |       To apply the Apache License to your work, attach the following
181 |       boilerplate notice, with the fields enclosed by brackets "[]"
182 |       replaced with your own identifying information. (Don't include
183 |       the brackets!)  The text should be enclosed in the appropriate
184 |       comment syntax for the file format. We also recommend that a
185 |       file or class name and description of purpose be included on the
186 |       same "printed page" as the copyright notice for easier
187 |       identification within third-party archives.
188 | 
189 |    Copyright [yyyy] [name of copyright owner]
190 | 
191 |    Licensed under the Apache License, Version 2.0 (the "License");
192 |    you may not use this file except in compliance with the License.
193 |    You may obtain a copy of the License at
194 | 
195 |        http://www.apache.org/licenses/LICENSE-2.0
196 | 
197 |    Unless required by applicable law or agreed to in writing, software
198 |    distributed under the License is distributed on an "AS IS" BASIS,
199 |    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 |    See the License for the specific language governing permissions and
201 |    limitations under the License.
202 | 


--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
  1 | <p align="center">
  2 |   <img src="assets/TauricResearch.png" style="width: 60%; height: auto;">
  3 | </p>
  4 | 
  5 | <div align="center" style="line-height: 1;">
  6 |   <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>
  7 |   <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>
  8 |   <a href="./assets/wechat.png" target="_blank"><img alt="WeChat" src="https://img.shields.io/badge/WeChat-TauricResearch-brightgreen?logo=wechat&logoColor=white"/></a>
  9 |   <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>
 10 |   <br>
 11 |   <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>
 12 | </div>
 13 | 
 14 | <div align="center">
 15 |   <!-- Keep these links. Translations will automatically update with the README. -->
 16 |   <a href="https://www.readme-i18n.com/TauricResearch/TradingAgents?lang=de">Deutsch</a> | 
 17 |   <a href="https://www.readme-i18n.com/TauricResearch/TradingAgents?lang=es">Español</a> | 
 18 |   <a href="https://www.readme-i18n.com/TauricResearch/TradingAgents?lang=fr">français</a> | 
 19 |   <a href="https://www.readme-i18n.com/TauricResearch/TradingAgents?lang=ja">日本語</a> | 
 20 |   <a href="https://www.readme-i18n.com/TauricResearch/TradingAgents?lang=ko">한국어</a> | 
 21 |   <a href="https://www.readme-i18n.com/TauricResearch/TradingAgents?lang=pt">Português</a> | 
 22 |   <a href="https://www.readme-i18n.com/TauricResearch/TradingAgents?lang=ru">Русский</a> | 
 23 |   <a href="https://www.readme-i18n.com/TauricResearch/TradingAgents?lang=zh">中文</a>
 24 | </div>
 25 | 
 26 | ---
 27 | 
 28 | # TradingAgents: Multi-Agents LLM Financial Trading Framework 
 29 | 
 30 | > 🎉 **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.
 31 | >
 32 | > So we decided to fully open-source the framework. Looking forward to building impactful projects with you!
 33 | 
 34 | <div align="center">
 35 | <a href="https://www.star-history.com/#TauricResearch/TradingAgents&Date">
 36 |  <picture>
 37 |    <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=TauricResearch/TradingAgents&type=Date&theme=dark" />
 38 |    <source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=TauricResearch/TradingAgents&type=Date" />
 39 |    <img alt="TradingAgents Star History" src="https://api.star-history.com/svg?repos=TauricResearch/TradingAgents&type=Date" style="width: 80%; height: auto;" />
 40 |  </picture>
 41 | </a>
 42 | </div>
 43 | 
 44 | <div align="center">
 45 | 
 46 | 🚀 [TradingAgents](#tradingagents-framework) | ⚡ [Installation & CLI](#installation-and-cli) | 🎬 [Demo](https://www.youtube.com/watch?v=90gr5lwjIho) | 📦 [Package Usage](#tradingagents-package) | 🤝 [Contributing](#contributing) | 📄 [Citation](#citation)
 47 | 
 48 | </div>
 49 | 
 50 | ## TradingAgents Framework
 51 | 
 52 | TradingAgents is a multi-agent trading framework that mirrors the dynamics of real-world trading firms. By deploying specialized LLM-powered agents: from fundamental analysts, sentiment experts, and technical analysts, to trader, risk management team, the platform collaboratively evaluates market conditions and informs trading decisions. Moreover, these agents engage in dynamic discussions to pinpoint the optimal strategy.
 53 | 
 54 | <p align="center">
 55 |   <img src="assets/schema.png" style="width: 100%; height: auto;">
 56 | </p>
 57 | 
 58 | > 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/)
 59 | 
 60 | Our framework decomposes complex trading tasks into specialized roles. This ensures the system achieves a robust, scalable approach to market analysis and decision-making.
 61 | 
 62 | ### Analyst Team
 63 | - Fundamentals Analyst: Evaluates company financials and performance metrics, identifying intrinsic values and potential red flags.
 64 | - Sentiment Analyst: Analyzes social media and public sentiment using sentiment scoring algorithms to gauge short-term market mood.
 65 | - News Analyst: Monitors global news and macroeconomic indicators, interpreting the impact of events on market conditions.
 66 | - Technical Analyst: Utilizes technical indicators (like MACD and RSI) to detect trading patterns and forecast price movements.
 67 | 
 68 | <p align="center">
 69 |   <img src="assets/analyst.png" width="100%" style="display: inline-block; margin: 0 2%;">
 70 | </p>
 71 | 
 72 | ### Researcher Team
 73 | - 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.
 74 | 
 75 | <p align="center">
 76 |   <img src="assets/researcher.png" width="70%" style="display: inline-block; margin: 0 2%;">
 77 | </p>
 78 | 
 79 | ### Trader Agent
 80 | - 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.
 81 | 
 82 | <p align="center">
 83 |   <img src="assets/trader.png" width="70%" style="display: inline-block; margin: 0 2%;">
 84 | </p>
 85 | 
 86 | ### Risk Management and Portfolio Manager
 87 | - 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.
 88 | - The Portfolio Manager approves/rejects the transaction proposal. If approved, the order will be sent to the simulated exchange and executed.
 89 | 
 90 | <p align="center">
 91 |   <img src="assets/risk.png" width="70%" style="display: inline-block; margin: 0 2%;">
 92 | </p>
 93 | 
 94 | ## Installation and CLI
 95 | 
 96 | ### Installation
 97 | 
 98 | Clone TradingAgents:
 99 | ```bash
100 | git clone https://github.com/TauricResearch/TradingAgents.git
101 | cd TradingAgents
102 | ```
103 | 
104 | Create a virtual environment in any of your favorite environment managers:
105 | ```bash
106 | conda create -n tradingagents python=3.13
107 | conda activate tradingagents
108 | ```
109 | 
110 | Install dependencies:
111 | ```bash
112 | pip install -r requirements.txt
113 | ```
114 | 
115 | ### Required APIs
116 | 
117 | You will also need the FinnHub API for financial data. All of our code is implemented with the free tier.
118 | ```bash
119 | export FINNHUB_API_KEY=$YOUR_FINNHUB_API_KEY
120 | ```
121 | 
122 | You will need the OpenAI API for all the agents.
123 | ```bash
124 | export OPENAI_API_KEY=$YOUR_OPENAI_API_KEY
125 | ```
126 | 
127 | ### CLI Usage
128 | 
129 | You can also try out the CLI directly by running:
130 | ```bash
131 | python -m cli.main
132 | ```
133 | You will see a screen where you can select your desired tickers, date, LLMs, research depth, etc.
134 | 
135 | <p align="center">
136 |   <img src="assets/cli/cli_init.png" width="100%" style="display: inline-block; margin: 0 2%;">
137 | </p>
138 | 
139 | An interface will appear showing results as they load, letting you track the agent's progress as it runs.
140 | 
141 | <p align="center">
142 |   <img src="assets/cli/cli_news.png" width="100%" style="display: inline-block; margin: 0 2%;">
143 | </p>
144 | 
145 | <p align="center">
146 |   <img src="assets/cli/cli_transaction.png" width="100%" style="display: inline-block; margin: 0 2%;">
147 | </p>
148 | 
149 | ## TradingAgents Package
150 | 
151 | ### Implementation Details
152 | 
153 | We built TradingAgents with LangGraph to ensure flexibility and modularity. We utilize `o1-preview` and `gpt-4o` as our deep thinking and fast thinking LLMs for our experiments. However, for testing purposes, we recommend you use `o4-mini` and `gpt-4.1-mini` to save on costs as our framework makes **lots of** API calls.
154 | 
155 | ### Python Usage
156 | 
157 | To use TradingAgents inside your code, you can import the `tradingagents` module and initialize a `TradingAgentsGraph()` object. The `.propagate()` function will return a decision. You can run `main.py`, here's also a quick example:
158 | 
159 | ```python
160 | from tradingagents.graph.trading_graph import TradingAgentsGraph
161 | from tradingagents.default_config import DEFAULT_CONFIG
162 | 
163 | ta = TradingAgentsGraph(debug=True, config=DEFAULT_CONFIG.copy())
164 | 
165 | # forward propagate
166 | _, decision = ta.propagate("NVDA", "2024-05-10")
167 | print(decision)
168 | ```
169 | 
170 | You can also adjust the default configuration to set your own choice of LLMs, debate rounds, etc.
171 | 
172 | ```python
173 | from tradingagents.graph.trading_graph import TradingAgentsGraph
174 | from tradingagents.default_config import DEFAULT_CONFIG
175 | 
176 | # Create a custom config
177 | config = DEFAULT_CONFIG.copy()
178 | config["deep_think_llm"] = "gpt-4.1-nano"  # Use a different model
179 | config["quick_think_llm"] = "gpt-4.1-nano"  # Use a different model
180 | config["max_debate_rounds"] = 1  # Increase debate rounds
181 | config["online_tools"] = True # Use online tools or cached data
182 | 
183 | # Initialize with custom config
184 | ta = TradingAgentsGraph(debug=True, config=config)
185 | 
186 | # forward propagate
187 | _, decision = ta.propagate("NVDA", "2024-05-10")
188 | print(decision)
189 | ```
190 | 
191 | > For `online_tools`, we recommend enabling them for experimentation, as they provide access to real-time data. The agents' offline tools rely on cached data from our **Tauric TradingDB**, a curated dataset we use for backtesting. We're currently in the process of refining this dataset, and we plan to release it soon alongside our upcoming projects. Stay tuned!
192 | 
193 | You can view the full list of configurations in `tradingagents/default_config.py`.
194 | 
195 | ## Contributing
196 | 
197 | We welcome contributions from the community! Whether it's fixing a bug, improving documentation, or suggesting a new feature, your input helps make this project better. If you are interested in this line of research, please consider joining our open-source financial AI research community [Tauric Research](https://tauric.ai/).
198 | 
199 | ## Citation
200 | 
201 | Please reference our work if you find *TradingAgents* provides you with some help :)
202 | 
203 | ```
204 | @misc{xiao2025tradingagentsmultiagentsllmfinancial,
205 |       title={TradingAgents: Multi-Agents LLM Financial Trading Framework}, 
206 |       author={Yijia Xiao and Edward Sun and Di Luo and Wei Wang},
207 |       year={2025},
208 |       eprint={2412.20138},
209 |       archivePrefix={arXiv},
210 |       primaryClass={q-fin.TR},
211 |       url={https://arxiv.org/abs/2412.20138}, 
212 | }
213 | ```
214 | 


--------------------------------------------------------------------------------
/assets/TauricResearch.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TauricResearch/TradingAgents/a438acdbbd622a4d3c112d23f7462651f8f9aeee/assets/TauricResearch.png


--------------------------------------------------------------------------------
/assets/analyst.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TauricResearch/TradingAgents/a438acdbbd622a4d3c112d23f7462651f8f9aeee/assets/analyst.png


--------------------------------------------------------------------------------
/assets/cli/cli_init.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TauricResearch/TradingAgents/a438acdbbd622a4d3c112d23f7462651f8f9aeee/assets/cli/cli_init.png


--------------------------------------------------------------------------------
/assets/cli/cli_news.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TauricResearch/TradingAgents/a438acdbbd622a4d3c112d23f7462651f8f9aeee/assets/cli/cli_news.png


--------------------------------------------------------------------------------
/assets/cli/cli_technical.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TauricResearch/TradingAgents/a438acdbbd622a4d3c112d23f7462651f8f9aeee/assets/cli/cli_technical.png


--------------------------------------------------------------------------------
/assets/cli/cli_transaction.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TauricResearch/TradingAgents/a438acdbbd622a4d3c112d23f7462651f8f9aeee/assets/cli/cli_transaction.png


--------------------------------------------------------------------------------
/assets/researcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TauricResearch/TradingAgents/a438acdbbd622a4d3c112d23f7462651f8f9aeee/assets/researcher.png


--------------------------------------------------------------------------------
/assets/risk.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TauricResearch/TradingAgents/a438acdbbd622a4d3c112d23f7462651f8f9aeee/assets/risk.png


--------------------------------------------------------------------------------
/assets/schema.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TauricResearch/TradingAgents/a438acdbbd622a4d3c112d23f7462651f8f9aeee/assets/schema.png


--------------------------------------------------------------------------------
/assets/trader.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TauricResearch/TradingAgents/a438acdbbd622a4d3c112d23f7462651f8f9aeee/assets/trader.png


--------------------------------------------------------------------------------
/assets/wechat.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TauricResearch/TradingAgents/a438acdbbd622a4d3c112d23f7462651f8f9aeee/assets/wechat.png


--------------------------------------------------------------------------------
/cli/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TauricResearch/TradingAgents/a438acdbbd622a4d3c112d23f7462651f8f9aeee/cli/__init__.py


--------------------------------------------------------------------------------
/cli/models.py:
--------------------------------------------------------------------------------
 1 | from enum import Enum
 2 | from typing import List, Optional, Dict
 3 | from pydantic import BaseModel
 4 | 
 5 | 
 6 | class AnalystType(str, Enum):
 7 |     MARKET = "market"
 8 |     SOCIAL = "social"
 9 |     NEWS = "news"
10 |     FUNDAMENTALS = "fundamentals"
11 | 


--------------------------------------------------------------------------------
/cli/static/welcome.txt:
--------------------------------------------------------------------------------
1 | 
2 |   ______               ___             ___                    __      
3 |  /_  __/________ _____/ (_)___  ____ _/   | ____ ____  ____  / /______
4 |   / / / ___/ __ `/ __  / / __ \/ __ `/ /| |/ __ `/ _ \/ __ \/ __/ ___/
5 |  / / / /  / /_/ / /_/ / / / / / /_/ / ___ / /_/ /  __/ / / / /_(__  ) 
6 | /_/ /_/   \__,_/\__,_/_/_/ /_/\__, /_/  |_\__, /\___/_/ /_/\__/____/  
7 |                              /____/      /____/                       
8 | 


--------------------------------------------------------------------------------
/cli/utils.py:
--------------------------------------------------------------------------------
  1 | import questionary
  2 | from typing import List, Optional, Tuple, Dict
  3 | 
  4 | from cli.models import AnalystType
  5 | 
  6 | ANALYST_ORDER = [
  7 |     ("Market Analyst", AnalystType.MARKET),
  8 |     ("Social Media Analyst", AnalystType.SOCIAL),
  9 |     ("News Analyst", AnalystType.NEWS),
 10 |     ("Fundamentals Analyst", AnalystType.FUNDAMENTALS),
 11 | ]
 12 | 
 13 | 
 14 | def get_ticker() -> str:
 15 |     """Prompt the user to enter a ticker symbol."""
 16 |     ticker = questionary.text(
 17 |         "Enter the ticker symbol to analyze:",
 18 |         validate=lambda x: len(x.strip()) > 0 or "Please enter a valid ticker symbol.",
 19 |         style=questionary.Style(
 20 |             [
 21 |                 ("text", "fg:green"),
 22 |                 ("highlighted", "noinherit"),
 23 |             ]
 24 |         ),
 25 |     ).ask()
 26 | 
 27 |     if not ticker:
 28 |         console.print("\n[red]No ticker symbol provided. Exiting...[/red]")
 29 |         exit(1)
 30 | 
 31 |     return ticker.strip().upper()
 32 | 
 33 | 
 34 | def get_analysis_date() -> str:
 35 |     """Prompt the user to enter a date in YYYY-MM-DD format."""
 36 |     import re
 37 |     from datetime import datetime
 38 | 
 39 |     def validate_date(date_str: str) -> bool:
 40 |         if not re.match(r"^\d{4}-\d{2}-\d{2}
quot;, date_str):
 41 |             return False
 42 |         try:
 43 |             datetime.strptime(date_str, "%Y-%m-%d")
 44 |             return True
 45 |         except ValueError:
 46 |             return False
 47 | 
 48 |     date = questionary.text(
 49 |         "Enter the analysis date (YYYY-MM-DD):",
 50 |         validate=lambda x: validate_date(x.strip())
 51 |         or "Please enter a valid date in YYYY-MM-DD format.",
 52 |         style=questionary.Style(
 53 |             [
 54 |                 ("text", "fg:green"),
 55 |                 ("highlighted", "noinherit"),
 56 |             ]
 57 |         ),
 58 |     ).ask()
 59 | 
 60 |     if not date:
 61 |         console.print("\n[red]No date provided. Exiting...[/red]")
 62 |         exit(1)
 63 | 
 64 |     return date.strip()
 65 | 
 66 | 
 67 | def select_analysts() -> List[AnalystType]:
 68 |     """Select analysts using an interactive checkbox."""
 69 |     choices = questionary.checkbox(
 70 |         "Select Your [Analysts Team]:",
 71 |         choices=[
 72 |             questionary.Choice(display, value=value) for display, value in ANALYST_ORDER
 73 |         ],
 74 |         instruction="\n- Press Space to select/unselect analysts\n- Press 'a' to select/unselect all\n- Press Enter when done",
 75 |         validate=lambda x: len(x) > 0 or "You must select at least one analyst.",
 76 |         style=questionary.Style(
 77 |             [
 78 |                 ("checkbox-selected", "fg:green"),
 79 |                 ("selected", "fg:green noinherit"),
 80 |                 ("highlighted", "noinherit"),
 81 |                 ("pointer", "noinherit"),
 82 |             ]
 83 |         ),
 84 |     ).ask()
 85 | 
 86 |     if not choices:
 87 |         console.print("\n[red]No analysts selected. Exiting...[/red]")
 88 |         exit(1)
 89 | 
 90 |     return choices
 91 | 
 92 | 
 93 | def select_research_depth() -> int:
 94 |     """Select research depth using an interactive selection."""
 95 | 
 96 |     # Define research depth options with their corresponding values
 97 |     DEPTH_OPTIONS = [
 98 |         ("Shallow - Quick research, few debate and strategy discussion rounds", 1),
 99 |         ("Medium - Middle ground, moderate debate rounds and strategy discussion", 3),
100 |         ("Deep - Comprehensive research, in depth debate and strategy discussion", 5),
101 |     ]
102 | 
103 |     choice = questionary.select(
104 |         "Select Your [Research Depth]:",
105 |         choices=[
106 |             questionary.Choice(display, value=value) for display, value in DEPTH_OPTIONS
107 |         ],
108 |         instruction="\n- Use arrow keys to navigate\n- Press Enter to select",
109 |         style=questionary.Style(
110 |             [
111 |                 ("selected", "fg:yellow noinherit"),
112 |                 ("highlighted", "fg:yellow noinherit"),
113 |                 ("pointer", "fg:yellow noinherit"),
114 |             ]
115 |         ),
116 |     ).ask()
117 | 
118 |     if choice is None:
119 |         console.print("\n[red]No research depth selected. Exiting...[/red]")
120 |         exit(1)
121 | 
122 |     return choice
123 | 
124 | 
125 | def select_shallow_thinking_agent(provider) -> str:
126 |     """Select shallow thinking llm engine using an interactive selection."""
127 | 
128 |     # Define shallow thinking llm engine options with their corresponding model names
129 |     SHALLOW_AGENT_OPTIONS = {
130 |         "openai": [
131 |             ("GPT-4o-mini - Fast and efficient for quick tasks", "gpt-4o-mini"),
132 |             ("GPT-4.1-nano - Ultra-lightweight model for basic operations", "gpt-4.1-nano"),
133 |             ("GPT-4.1-mini - Compact model with good performance", "gpt-4.1-mini"),
134 |             ("GPT-4o - Standard model with solid capabilities", "gpt-4o"),
135 |         ],
136 |         "anthropic": [
137 |             ("Claude Haiku 3.5 - Fast inference and standard capabilities", "claude-3-5-haiku-latest"),
138 |             ("Claude Sonnet 3.5 - Highly capable standard model", "claude-3-5-sonnet-latest"),
139 |             ("Claude Sonnet 3.7 - Exceptional hybrid reasoning and agentic capabilities", "claude-3-7-sonnet-latest"),
140 |             ("Claude Sonnet 4 - High performance and excellent reasoning", "claude-sonnet-4-0"),
141 |         ],
142 |         "google": [
143 |             ("Gemini 2.0 Flash-Lite - Cost efficiency and low latency", "gemini-2.0-flash-lite"),
144 |             ("Gemini 2.0 Flash - Next generation features, speed, and thinking", "gemini-2.0-flash"),
145 |             ("Gemini 2.5 Flash - Adaptive thinking, cost efficiency", "gemini-2.5-flash-preview-05-20"),
146 |         ],
147 |         "openrouter": [
148 |             ("Meta: Llama 4 Scout", "meta-llama/llama-4-scout:free"),
149 |             ("Meta: Llama 3.3 8B Instruct - A lightweight and ultra-fast variant of Llama 3.3 70B", "meta-llama/llama-3.3-8b-instruct:free"),
150 |             ("google/gemini-2.0-flash-exp:free - Gemini Flash 2.0 offers a significantly faster time to first token", "google/gemini-2.0-flash-exp:free"),
151 |         ],
152 |         "ollama": [
153 |             ("llama3.1 local", "llama3.1"),
154 |             ("llama3.2 local", "llama3.2"),
155 |         ]
156 |     }
157 | 
158 |     choice = questionary.select(
159 |         "Select Your [Quick-Thinking LLM Engine]:",
160 |         choices=[
161 |             questionary.Choice(display, value=value)
162 |             for display, value in SHALLOW_AGENT_OPTIONS[provider.lower()]
163 |         ],
164 |         instruction="\n- Use arrow keys to navigate\n- Press Enter to select",
165 |         style=questionary.Style(
166 |             [
167 |                 ("selected", "fg:magenta noinherit"),
168 |                 ("highlighted", "fg:magenta noinherit"),
169 |                 ("pointer", "fg:magenta noinherit"),
170 |             ]
171 |         ),
172 |     ).ask()
173 | 
174 |     if choice is None:
175 |         console.print(
176 |             "\n[red]No shallow thinking llm engine selected. Exiting...[/red]"
177 |         )
178 |         exit(1)
179 | 
180 |     return choice
181 | 
182 | 
183 | def select_deep_thinking_agent(provider) -> str:
184 |     """Select deep thinking llm engine using an interactive selection."""
185 | 
186 |     # Define deep thinking llm engine options with their corresponding model names
187 |     DEEP_AGENT_OPTIONS = {
188 |         "openai": [
189 |             ("GPT-4.1-nano - Ultra-lightweight model for basic operations", "gpt-4.1-nano"),
190 |             ("GPT-4.1-mini - Compact model with good performance", "gpt-4.1-mini"),
191 |             ("GPT-4o - Standard model with solid capabilities", "gpt-4o"),
192 |             ("o4-mini - Specialized reasoning model (compact)", "o4-mini"),
193 |             ("o3-mini - Advanced reasoning model (lightweight)", "o3-mini"),
194 |             ("o3 - Full advanced reasoning model", "o3"),
195 |             ("o1 - Premier reasoning and problem-solving model", "o1"),
196 |         ],
197 |         "anthropic": [
198 |             ("Claude Haiku 3.5 - Fast inference and standard capabilities", "claude-3-5-haiku-latest"),
199 |             ("Claude Sonnet 3.5 - Highly capable standard model", "claude-3-5-sonnet-latest"),
200 |             ("Claude Sonnet 3.7 - Exceptional hybrid reasoning and agentic capabilities", "claude-3-7-sonnet-latest"),
201 |             ("Claude Sonnet 4 - High performance and excellent reasoning", "claude-sonnet-4-0"),
202 |             ("Claude Opus 4 - Most powerful Anthropic model", "	claude-opus-4-0"),
203 |         ],
204 |         "google": [
205 |             ("Gemini 2.0 Flash-Lite - Cost efficiency and low latency", "gemini-2.0-flash-lite"),
206 |             ("Gemini 2.0 Flash - Next generation features, speed, and thinking", "gemini-2.0-flash"),
207 |             ("Gemini 2.5 Flash - Adaptive thinking, cost efficiency", "gemini-2.5-flash-preview-05-20"),
208 |             ("Gemini 2.5 Pro", "gemini-2.5-pro-preview-06-05"),
209 |         ],
210 |         "openrouter": [
211 |             ("DeepSeek V3 - a 685B-parameter, mixture-of-experts model", "deepseek/deepseek-chat-v3-0324:free"),
212 |             ("Deepseek - latest iteration of the flagship chat model family from the DeepSeek team.", "deepseek/deepseek-chat-v3-0324:free"),
213 |         ],
214 |         "ollama": [
215 |             ("llama3.1 local", "llama3.1"),
216 |             ("qwen3", "qwen3"),
217 |         ]
218 |     }
219 |     
220 |     choice = questionary.select(
221 |         "Select Your [Deep-Thinking LLM Engine]:",
222 |         choices=[
223 |             questionary.Choice(display, value=value)
224 |             for display, value in DEEP_AGENT_OPTIONS[provider.lower()]
225 |         ],
226 |         instruction="\n- Use arrow keys to navigate\n- Press Enter to select",
227 |         style=questionary.Style(
228 |             [
229 |                 ("selected", "fg:magenta noinherit"),
230 |                 ("highlighted", "fg:magenta noinherit"),
231 |                 ("pointer", "fg:magenta noinherit"),
232 |             ]
233 |         ),
234 |     ).ask()
235 | 
236 |     if choice is None:
237 |         console.print("\n[red]No deep thinking llm engine selected. Exiting...[/red]")
238 |         exit(1)
239 | 
240 |     return choice
241 | 
242 | def select_llm_provider() -> tuple[str, str]:
243 |     """Select the OpenAI api url using interactive selection."""
244 |     # Define OpenAI api options with their corresponding endpoints
245 |     BASE_URLS = [
246 |         ("OpenAI", "https://api.openai.com/v1"),
247 |         ("Anthropic", "https://api.anthropic.com/"),
248 |         ("Google", "https://generativelanguage.googleapis.com/v1"),
249 |         ("Openrouter", "https://openrouter.ai/api/v1"),
250 |         ("Ollama", "http://localhost:11434/v1"),        
251 |     ]
252 |     
253 |     choice = questionary.select(
254 |         "Select your LLM Provider:",
255 |         choices=[
256 |             questionary.Choice(display, value=(display, value))
257 |             for display, value in BASE_URLS
258 |         ],
259 |         instruction="\n- Use arrow keys to navigate\n- Press Enter to select",
260 |         style=questionary.Style(
261 |             [
262 |                 ("selected", "fg:magenta noinherit"),
263 |                 ("highlighted", "fg:magenta noinherit"),
264 |                 ("pointer", "fg:magenta noinherit"),
265 |             ]
266 |         ),
267 |     ).ask()
268 |     
269 |     if choice is None:
270 |         console.print("\n[red]no OpenAI backend selected. Exiting...[/red]")
271 |         exit(1)
272 |     
273 |     display_name, url = choice
274 |     print(f"You selected: {display_name}\tURL: {url}")
275 |     
276 |     return display_name, url
277 | 


--------------------------------------------------------------------------------
/main.py:
--------------------------------------------------------------------------------
 1 | from tradingagents.graph.trading_graph import TradingAgentsGraph
 2 | from tradingagents.default_config import DEFAULT_CONFIG
 3 | 
 4 | # Create a custom config
 5 | config = DEFAULT_CONFIG.copy()
 6 | config["llm_provider"] = "google"  # Use a different model
 7 | config["backend_url"] = "https://generativelanguage.googleapis.com/v1"  # Use a different backend
 8 | config["deep_think_llm"] = "gemini-2.0-flash"  # Use a different model
 9 | config["quick_think_llm"] = "gemini-2.0-flash"  # Use a different model
10 | config["max_debate_rounds"] = 1  # Increase debate rounds
11 | config["online_tools"] = True  # Increase debate rounds
12 | 
13 | # Initialize with custom config
14 | ta = TradingAgentsGraph(debug=True, config=config)
15 | 
16 | # forward propagate
17 | _, decision = ta.propagate("NVDA", "2024-05-10")
18 | print(decision)
19 | 
20 | # Memorize mistakes and reflect
21 | # ta.reflect_and_remember(1000) # parameter is the position returns
22 | 


--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
 1 | [project]
 2 | name = "tradingagents"
 3 | version = "0.1.0"
 4 | description = "Add your description here"
 5 | readme = "README.md"
 6 | requires-python = ">=3.10"
 7 | dependencies = [
 8 |     "akshare>=1.16.98",
 9 |     "backtrader>=1.9.78.123",
10 |     "chainlit>=2.5.5",
11 |     "chromadb>=1.0.12",
12 |     "eodhd>=1.0.32",
13 |     "feedparser>=6.0.11",
14 |     "finnhub-python>=2.4.23",
15 |     "langchain-anthropic>=0.3.15",
16 |     "langchain-experimental>=0.3.4",
17 |     "langchain-google-genai>=2.1.5",
18 |     "langchain-openai>=0.3.23",
19 |     "langgraph>=0.4.8",
20 |     "pandas>=2.3.0",
21 |     "parsel>=1.10.0",
22 |     "praw>=7.8.1",
23 |     "pytz>=2025.2",
24 |     "questionary>=2.1.0",
25 |     "redis>=6.2.0",
26 |     "requests>=2.32.4",
27 |     "rich>=14.0.0",
28 |     "setuptools>=80.9.0",
29 |     "stockstats>=0.6.5",
30 |     "tqdm>=4.67.1",
31 |     "tushare>=1.4.21",
32 |     "typing-extensions>=4.14.0",
33 |     "yfinance>=0.2.63",
34 | ]
35 | 


--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
 1 | typing-extensions
 2 | langchain-openai
 3 | langchain-experimental
 4 | pandas
 5 | yfinance
 6 | praw
 7 | feedparser
 8 | stockstats
 9 | eodhd
10 | langgraph
11 | chromadb
12 | setuptools
13 | backtrader
14 | akshare
15 | tushare
16 | finnhub-python
17 | parsel
18 | requests
19 | tqdm
20 | pytz
21 | redis
22 | chainlit
23 | rich
24 | questionary
25 | langchain_anthropic
26 | langchain-google-genai
27 | 


--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
 1 | """
 2 | Setup script for the TradingAgents package.
 3 | """
 4 | 
 5 | from setuptools import setup, find_packages
 6 | 
 7 | setup(
 8 |     name="tradingagents",
 9 |     version="0.1.0",
10 |     description="Multi-Agents LLM Financial Trading Framework",
11 |     author="TradingAgents Team",
12 |     author_email="yijia.xiao@cs.ucla.edu",
13 |     url="https://github.com/TauricResearch",
14 |     packages=find_packages(),
15 |     install_requires=[
16 |         "langchain>=0.1.0",
17 |         "langchain-openai>=0.0.2",
18 |         "langchain-experimental>=0.0.40",
19 |         "langgraph>=0.0.20",
20 |         "numpy>=1.24.0",
21 |         "pandas>=2.0.0",
22 |         "praw>=7.7.0",
23 |         "stockstats>=0.5.4",
24 |         "yfinance>=0.2.31",
25 |         "typer>=0.9.0",
26 |         "rich>=13.0.0",
27 |         "questionary>=2.0.1",
28 |     ],
29 |     python_requires=">=3.10",
30 |     entry_points={
31 |         "console_scripts": [
32 |             "tradingagents=cli.main:app",
33 |         ],
34 |     },
35 |     classifiers=[
36 |         "Development Status :: 3 - Alpha",
37 |         "Intended Audience :: Financial and Trading Industry",
38 |         "License :: OSI Approved :: Apache Software License",
39 |         "Programming Language :: Python :: 3",
40 |         "Programming Language :: Python :: 3.10",
41 |         "Topic :: Office/Business :: Financial :: Investment",
42 |     ],
43 | )
44 | 


--------------------------------------------------------------------------------
/tradingagents/agents/__init__.py:
--------------------------------------------------------------------------------
 1 | from .utils.agent_utils import Toolkit, create_msg_delete
 2 | from .utils.agent_states import AgentState, InvestDebateState, RiskDebateState
 3 | from .utils.memory import FinancialSituationMemory
 4 | 
 5 | from .analysts.fundamentals_analyst import create_fundamentals_analyst
 6 | from .analysts.market_analyst import create_market_analyst
 7 | from .analysts.news_analyst import create_news_analyst
 8 | from .analysts.social_media_analyst import create_social_media_analyst
 9 | 
10 | from .researchers.bear_researcher import create_bear_researcher
11 | from .researchers.bull_researcher import create_bull_researcher
12 | 
13 | from .risk_mgmt.aggresive_debator import create_risky_debator
14 | from .risk_mgmt.conservative_debator import create_safe_debator
15 | from .risk_mgmt.neutral_debator import create_neutral_debator
16 | 
17 | from .managers.research_manager import create_research_manager
18 | from .managers.risk_manager import create_risk_manager
19 | 
20 | from .trader.trader import create_trader
21 | 
22 | __all__ = [
23 |     "FinancialSituationMemory",
24 |     "Toolkit",
25 |     "AgentState",
26 |     "create_msg_delete",
27 |     "InvestDebateState",
28 |     "RiskDebateState",
29 |     "create_bear_researcher",
30 |     "create_bull_researcher",
31 |     "create_research_manager",
32 |     "create_fundamentals_analyst",
33 |     "create_market_analyst",
34 |     "create_neutral_debator",
35 |     "create_news_analyst",
36 |     "create_risky_debator",
37 |     "create_risk_manager",
38 |     "create_safe_debator",
39 |     "create_social_media_analyst",
40 |     "create_trader",
41 | ]
42 | 


--------------------------------------------------------------------------------
/tradingagents/agents/analysts/fundamentals_analyst.py:
--------------------------------------------------------------------------------
 1 | from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
 2 | import time
 3 | import json
 4 | 
 5 | 
 6 | def create_fundamentals_analyst(llm, toolkit):
 7 |     def fundamentals_analyst_node(state):
 8 |         current_date = state["trade_date"]
 9 |         ticker = state["company_of_interest"]
10 |         company_name = state["company_of_interest"]
11 | 
12 |         if toolkit.config["online_tools"]:
13 |             tools = [toolkit.get_fundamentals_openai]
14 |         else:
15 |             tools = [
16 |                 toolkit.get_finnhub_company_insider_sentiment,
17 |                 toolkit.get_finnhub_company_insider_transactions,
18 |                 toolkit.get_simfin_balance_sheet,
19 |                 toolkit.get_simfin_cashflow,
20 |                 toolkit.get_simfin_income_stmt,
21 |             ]
22 | 
23 |         system_message = (
24 |             "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, company financial history, insider sentiment and insider transactions 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."
25 |             + " 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.",
26 |         )
27 | 
28 |         prompt = ChatPromptTemplate.from_messages(
29 |             [
30 |                 (
31 |                     "system",
32 |                     "You are a helpful AI assistant, collaborating with other assistants."
33 |                     " Use the provided tools to progress towards answering the question."
34 |                     " If you are unable to fully answer, that's OK; another assistant with different tools"
35 |                     " will help where you left off. Execute what you can to make progress."
36 |                     " If you or any other assistant has the FINAL TRANSACTION PROPOSAL: **BUY/HOLD/SELL** or deliverable,"
37 |                     " prefix your response with FINAL TRANSACTION PROPOSAL: **BUY/HOLD/SELL** so the team knows to stop."
38 |                     " You have access to the following tools: {tool_names}.\n{system_message}"
39 |                     "For your reference, the current date is {current_date}. The company we want to look at is {ticker}",
40 |                 ),
41 |                 MessagesPlaceholder(variable_name="messages"),
42 |             ]
43 |         )
44 | 
45 |         prompt = prompt.partial(system_message=system_message)
46 |         prompt = prompt.partial(tool_names=", ".join([tool.name for tool in tools]))
47 |         prompt = prompt.partial(current_date=current_date)
48 |         prompt = prompt.partial(ticker=ticker)
49 | 
50 |         chain = prompt | llm.bind_tools(tools)
51 | 
52 |         result = chain.invoke(state["messages"])
53 | 
54 |         report = ""
55 | 
56 |         if len(result.tool_calls) == 0:
57 |             report = result.content
58 | 
59 |         return {
60 |             "messages": [result],
61 |             "fundamentals_report": report,
62 |         }
63 | 
64 |     return fundamentals_analyst_node
65 | 


--------------------------------------------------------------------------------
/tradingagents/agents/analysts/market_analyst.py:
--------------------------------------------------------------------------------
 1 | from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
 2 | import time
 3 | import json
 4 | 
 5 | 
 6 | def create_market_analyst(llm, toolkit):
 7 | 
 8 |     def market_analyst_node(state):
 9 |         current_date = state["trade_date"]
10 |         ticker = state["company_of_interest"]
11 |         company_name = state["company_of_interest"]
12 | 
13 |         if toolkit.config["online_tools"]:
14 |             tools = [
15 |                 toolkit.get_YFin_data_online,
16 |                 toolkit.get_stockstats_indicators_report_online,
17 |             ]
18 |         else:
19 |             tools = [
20 |                 toolkit.get_YFin_data,
21 |                 toolkit.get_stockstats_indicators_report,
22 |             ]
23 | 
24 |         system_message = (
25 |             """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:
26 | 
27 | Moving Averages:
28 | - 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.
29 | - 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.
30 | - 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.
31 | 
32 | MACD Related:
33 | - 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.
34 | - 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.
35 | - 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.
36 | 
37 | Momentum Indicators:
38 | - 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.
39 | 
40 | Volatility Indicators:
41 | - 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.
42 | - 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.
43 | - 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.
44 | - 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.
45 | 
46 | Volume-Based Indicators:
47 | - 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.
48 | 
49 | - 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_YFin_data first to retrieve the CSV that is needed to generate indicators. 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."""
50 |             + """ 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."""
51 |         )
52 | 
53 |         prompt = ChatPromptTemplate.from_messages(
54 |             [
55 |                 (
56 |                     "system",
57 |                     "You are a helpful AI assistant, collaborating with other assistants."
58 |                     " Use the provided tools to progress towards answering the question."
59 |                     " If you are unable to fully answer, that's OK; another assistant with different tools"
60 |                     " will help where you left off. Execute what you can to make progress."
61 |                     " If you or any other assistant has the FINAL TRANSACTION PROPOSAL: **BUY/HOLD/SELL** or deliverable,"
62 |                     " prefix your response with FINAL TRANSACTION PROPOSAL: **BUY/HOLD/SELL** so the team knows to stop."
63 |                     " You have access to the following tools: {tool_names}.\n{system_message}"
64 |                     "For your reference, the current date is {current_date}. The company we want to look at is {ticker}",
65 |                 ),
66 |                 MessagesPlaceholder(variable_name="messages"),
67 |             ]
68 |         )
69 | 
70 |         prompt = prompt.partial(system_message=system_message)
71 |         prompt = prompt.partial(tool_names=", ".join([tool.name for tool in tools]))
72 |         prompt = prompt.partial(current_date=current_date)
73 |         prompt = prompt.partial(ticker=ticker)
74 | 
75 |         chain = prompt | llm.bind_tools(tools)
76 | 
77 |         result = chain.invoke(state["messages"])
78 | 
79 |         report = ""
80 | 
81 |         if len(result.tool_calls) == 0:
82 |             report = result.content
83 |        
84 |         return {
85 |             "messages": [result],
86 |             "market_report": report,
87 |         }
88 | 
89 |     return market_analyst_node
90 | 


--------------------------------------------------------------------------------
/tradingagents/agents/analysts/news_analyst.py:
--------------------------------------------------------------------------------
 1 | from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
 2 | import time
 3 | import json
 4 | 
 5 | 
 6 | def create_news_analyst(llm, toolkit):
 7 |     def news_analyst_node(state):
 8 |         current_date = state["trade_date"]
 9 |         ticker = state["company_of_interest"]
10 | 
11 |         if toolkit.config["online_tools"]:
12 |             tools = [toolkit.get_global_news_openai, toolkit.get_google_news]
13 |         else:
14 |             tools = [
15 |                 toolkit.get_finnhub_news,
16 |                 toolkit.get_reddit_news,
17 |                 toolkit.get_google_news,
18 |             ]
19 | 
20 |         system_message = (
21 |             "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. Look at news from EODHD, and finnhub to be comprehensive. Do not simply state the trends are mixed, provide detailed and finegrained analysis and insights that may help traders make decisions."
22 |             + """ Make sure to append a Makrdown table at the end of the report to organize key points in the report, organized and easy to read."""
23 |         )
24 | 
25 |         prompt = ChatPromptTemplate.from_messages(
26 |             [
27 |                 (
28 |                     "system",
29 |                     "You are a helpful AI assistant, collaborating with other assistants."
30 |                     " Use the provided tools to progress towards answering the question."
31 |                     " If you are unable to fully answer, that's OK; another assistant with different tools"
32 |                     " will help where you left off. Execute what you can to make progress."
33 |                     " If you or any other assistant has the FINAL TRANSACTION PROPOSAL: **BUY/HOLD/SELL** or deliverable,"
34 |                     " prefix your response with FINAL TRANSACTION PROPOSAL: **BUY/HOLD/SELL** so the team knows to stop."
35 |                     " You have access to the following tools: {tool_names}.\n{system_message}"
36 |                     "For your reference, the current date is {current_date}. We are looking at the company {ticker}",
37 |                 ),
38 |                 MessagesPlaceholder(variable_name="messages"),
39 |             ]
40 |         )
41 | 
42 |         prompt = prompt.partial(system_message=system_message)
43 |         prompt = prompt.partial(tool_names=", ".join([tool.name for tool in tools]))
44 |         prompt = prompt.partial(current_date=current_date)
45 |         prompt = prompt.partial(ticker=ticker)
46 | 
47 |         chain = prompt | llm.bind_tools(tools)
48 |         result = chain.invoke(state["messages"])
49 | 
50 |         report = ""
51 | 
52 |         if len(result.tool_calls) == 0:
53 |             report = result.content
54 | 
55 |         return {
56 |             "messages": [result],
57 |             "news_report": report,
58 |         }
59 | 
60 |     return news_analyst_node
61 | 


--------------------------------------------------------------------------------
/tradingagents/agents/analysts/social_media_analyst.py:
--------------------------------------------------------------------------------
 1 | from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
 2 | import time
 3 | import json
 4 | 
 5 | 
 6 | def create_social_media_analyst(llm, toolkit):
 7 |     def social_media_analyst_node(state):
 8 |         current_date = state["trade_date"]
 9 |         ticker = state["company_of_interest"]
10 |         company_name = state["company_of_interest"]
11 | 
12 |         if toolkit.config["online_tools"]:
13 |             tools = [toolkit.get_stock_news_openai]
14 |         else:
15 |             tools = [
16 |                 toolkit.get_reddit_stock_info,
17 |             ]
18 | 
19 |         system_message = (
20 |             "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. 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."
21 |             + """ Make sure to append a Makrdown table at the end of the report to organize key points in the report, organized and easy to read.""",
22 |         )
23 | 
24 |         prompt = ChatPromptTemplate.from_messages(
25 |             [
26 |                 (
27 |                     "system",
28 |                     "You are a helpful AI assistant, collaborating with other assistants."
29 |                     " Use the provided tools to progress towards answering the question."
30 |                     " If you are unable to fully answer, that's OK; another assistant with different tools"
31 |                     " will help where you left off. Execute what you can to make progress."
32 |                     " If you or any other assistant has the FINAL TRANSACTION PROPOSAL: **BUY/HOLD/SELL** or deliverable,"
33 |                     " prefix your response with FINAL TRANSACTION PROPOSAL: **BUY/HOLD/SELL** so the team knows to stop."
34 |                     " You have access to the following tools: {tool_names}.\n{system_message}"
35 |                     "For your reference, the current date is {current_date}. The current company we want to analyze is {ticker}",
36 |                 ),
37 |                 MessagesPlaceholder(variable_name="messages"),
38 |             ]
39 |         )
40 | 
41 |         prompt = prompt.partial(system_message=system_message)
42 |         prompt = prompt.partial(tool_names=", ".join([tool.name for tool in tools]))
43 |         prompt = prompt.partial(current_date=current_date)
44 |         prompt = prompt.partial(ticker=ticker)
45 | 
46 |         chain = prompt | llm.bind_tools(tools)
47 | 
48 |         result = chain.invoke(state["messages"])
49 | 
50 |         report = ""
51 | 
52 |         if len(result.tool_calls) == 0:
53 |             report = result.content
54 | 
55 |         return {
56 |             "messages": [result],
57 |             "sentiment_report": report,
58 |         }
59 | 
60 |     return social_media_analyst_node
61 | 


--------------------------------------------------------------------------------
/tradingagents/agents/managers/research_manager.py:
--------------------------------------------------------------------------------
 1 | import time
 2 | import json
 3 | 
 4 | 
 5 | def create_research_manager(llm, memory):
 6 |     def research_manager_node(state) -> dict:
 7 |         history = state["investment_debate_state"].get("history", "")
 8 |         market_research_report = state["market_report"]
 9 |         sentiment_report = state["sentiment_report"]
10 |         news_report = state["news_report"]
11 |         fundamentals_report = state["fundamentals_report"]
12 | 
13 |         investment_debate_state = state["investment_debate_state"]
14 | 
15 |         curr_situation = f"{market_research_report}\n\n{sentiment_report}\n\n{news_report}\n\n{fundamentals_report}"
16 |         past_memories = memory.get_memories(curr_situation, n_matches=2)
17 | 
18 |         past_memory_str = ""
19 |         for i, rec in enumerate(past_memories, 1):
20 |             past_memory_str += rec["recommendation"] + "\n\n"
21 | 
22 |         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.
23 | 
24 | Summarize 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.
25 | 
26 | Additionally, develop a detailed investment plan for the trader. This should include:
27 | 
28 | Your Recommendation: A decisive stance supported by the most convincing arguments.
29 | Rationale: An explanation of why these arguments lead to your conclusion.
30 | Strategic Actions: Concrete steps for implementing the recommendation.
31 | Take 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. 
32 | 
33 | Here are your past reflections on mistakes:
34 | \"{past_memory_str}\"
35 | 
36 | Here is the debate:
37 | Debate History:
38 | {history}"""
39 |         response = llm.invoke(prompt)
40 | 
41 |         new_investment_debate_state = {
42 |             "judge_decision": response.content,
43 |             "history": investment_debate_state.get("history", ""),
44 |             "bear_history": investment_debate_state.get("bear_history", ""),
45 |             "bull_history": investment_debate_state.get("bull_history", ""),
46 |             "current_response": response.content,
47 |             "count": investment_debate_state["count"],
48 |         }
49 | 
50 |         return {
51 |             "investment_debate_state": new_investment_debate_state,
52 |             "investment_plan": response.content,
53 |         }
54 | 
55 |     return research_manager_node
56 | 


--------------------------------------------------------------------------------
/tradingagents/agents/managers/risk_manager.py:
--------------------------------------------------------------------------------
 1 | import time
 2 | import json
 3 | 
 4 | 
 5 | def create_risk_manager(llm, memory):
 6 |     def risk_manager_node(state) -> dict:
 7 | 
 8 |         company_name = state["company_of_interest"]
 9 | 
10 |         history = state["risk_debate_state"]["history"]
11 |         risk_debate_state = state["risk_debate_state"]
12 |         market_research_report = state["market_report"]
13 |         news_report = state["news_report"]
14 |         fundamentals_report = state["news_report"]
15 |         sentiment_report = state["sentiment_report"]
16 |         trader_plan = state["investment_plan"]
17 | 
18 |         curr_situation = f"{market_research_report}\n\n{sentiment_report}\n\n{news_report}\n\n{fundamentals_report}"
19 |         past_memories = memory.get_memories(curr_situation, n_matches=2)
20 | 
21 |         past_memory_str = ""
22 |         for i, rec in enumerate(past_memories, 1):
23 |             past_memory_str += rec["recommendation"] + "\n\n"
24 | 
25 |         prompt = f"""As the Risk Management Judge and Debate Facilitator, your goal is to evaluate the debate between three risk analysts—Risky, Neutral, and Safe/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.
26 | 
27 | Guidelines for Decision-Making:
28 | 1. **Summarize Key Arguments**: Extract the strongest points from each analyst, focusing on relevance to the context.
29 | 2. **Provide Rationale**: Support your recommendation with direct quotes and counterarguments from the debate.
30 | 3. **Refine the Trader's Plan**: Start with the trader's original plan, **{trader_plan}**, and adjust it based on the analysts' insights.
31 | 4. **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.
32 | 
33 | Deliverables:
34 | - A clear and actionable recommendation: Buy, Sell, or Hold.
35 | - Detailed reasoning anchored in the debate and past reflections.
36 | 
37 | ---
38 | 
39 | **Analysts Debate History:**  
40 | {history}
41 | 
42 | ---
43 | 
44 | Focus on actionable insights and continuous improvement. Build on past lessons, critically evaluate all perspectives, and ensure each decision advances better outcomes."""
45 | 
46 |         response = llm.invoke(prompt)
47 | 
48 |         new_risk_debate_state = {
49 |             "judge_decision": response.content,
50 |             "history": risk_debate_state["history"],
51 |             "risky_history": risk_debate_state["risky_history"],
52 |             "safe_history": risk_debate_state["safe_history"],
53 |             "neutral_history": risk_debate_state["neutral_history"],
54 |             "latest_speaker": "Judge",
55 |             "current_risky_response": risk_debate_state["current_risky_response"],
56 |             "current_safe_response": risk_debate_state["current_safe_response"],
57 |             "current_neutral_response": risk_debate_state["current_neutral_response"],
58 |             "count": risk_debate_state["count"],
59 |         }
60 | 
61 |         return {
62 |             "risk_debate_state": new_risk_debate_state,
63 |             "final_trade_decision": response.content,
64 |         }
65 | 
66 |     return risk_manager_node
67 | 


--------------------------------------------------------------------------------
/tradingagents/agents/researchers/bear_researcher.py:
--------------------------------------------------------------------------------
 1 | from langchain_core.messages import AIMessage
 2 | import time
 3 | import json
 4 | 
 5 | 
 6 | def create_bear_researcher(llm, memory):
 7 |     def bear_node(state) -> dict:
 8 |         investment_debate_state = state["investment_debate_state"]
 9 |         history = investment_debate_state.get("history", "")
10 |         bear_history = investment_debate_state.get("bear_history", "")
11 | 
12 |         current_response = investment_debate_state.get("current_response", "")
13 |         market_research_report = state["market_report"]
14 |         sentiment_report = state["sentiment_report"]
15 |         news_report = state["news_report"]
16 |         fundamentals_report = state["fundamentals_report"]
17 | 
18 |         curr_situation = f"{market_research_report}\n\n{sentiment_report}\n\n{news_report}\n\n{fundamentals_report}"
19 |         past_memories = memory.get_memories(curr_situation, n_matches=2)
20 | 
21 |         past_memory_str = ""
22 |         for i, rec in enumerate(past_memories, 1):
23 |             past_memory_str += rec["recommendation"] + "\n\n"
24 | 
25 |         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.
26 | 
27 | Key points to focus on:
28 | 
29 | - Risks and Challenges: Highlight factors like market saturation, financial instability, or macroeconomic threats that could hinder the stock's performance.
30 | - Competitive Weaknesses: Emphasize vulnerabilities such as weaker market positioning, declining innovation, or threats from competitors.
31 | - Negative Indicators: Use evidence from financial data, market trends, or recent adverse news to support your position.
32 | - Bull Counterpoints: Critically analyze the bull argument with specific data and sound reasoning, exposing weaknesses or over-optimistic assumptions.
33 | - Engagement: Present your argument in a conversational style, directly engaging with the bull analyst's points and debating effectively rather than simply listing facts.
34 | 
35 | Resources available:
36 | 
37 | Market research report: {market_research_report}
38 | Social media sentiment report: {sentiment_report}
39 | Latest world affairs news: {news_report}
40 | Company fundamentals report: {fundamentals_report}
41 | Conversation history of the debate: {history}
42 | Last bull argument: {current_response}
43 | Reflections from similar situations and lessons learned: {past_memory_str}
44 | Use this information to deliver a compelling bear argument, refute the bull's claims, and engage in a dynamic debate that demonstrates the risks and weaknesses of investing in the stock. You must also address reflections and learn from lessons and mistakes you made in the past.
45 | """
46 | 
47 |         response = llm.invoke(prompt)
48 | 
49 |         argument = f"Bear Analyst: {response.content}"
50 | 
51 |         new_investment_debate_state = {
52 |             "history": history + "\n" + argument,
53 |             "bear_history": bear_history + "\n" + argument,
54 |             "bull_history": investment_debate_state.get("bull_history", ""),
55 |             "current_response": argument,
56 |             "count": investment_debate_state["count"] + 1,
57 |         }
58 | 
59 |         return {"investment_debate_state": new_investment_debate_state}
60 | 
61 |     return bear_node
62 | 


--------------------------------------------------------------------------------
/tradingagents/agents/researchers/bull_researcher.py:
--------------------------------------------------------------------------------
 1 | from langchain_core.messages import AIMessage
 2 | import time
 3 | import json
 4 | 
 5 | 
 6 | def create_bull_researcher(llm, memory):
 7 |     def bull_node(state) -> dict:
 8 |         investment_debate_state = state["investment_debate_state"]
 9 |         history = investment_debate_state.get("history", "")
10 |         bull_history = investment_debate_state.get("bull_history", "")
11 | 
12 |         current_response = investment_debate_state.get("current_response", "")
13 |         market_research_report = state["market_report"]
14 |         sentiment_report = state["sentiment_report"]
15 |         news_report = state["news_report"]
16 |         fundamentals_report = state["fundamentals_report"]
17 | 
18 |         curr_situation = f"{market_research_report}\n\n{sentiment_report}\n\n{news_report}\n\n{fundamentals_report}"
19 |         past_memories = memory.get_memories(curr_situation, n_matches=2)
20 | 
21 |         past_memory_str = ""
22 |         for i, rec in enumerate(past_memories, 1):
23 |             past_memory_str += rec["recommendation"] + "\n\n"
24 | 
25 |         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.
26 | 
27 | Key points to focus on:
28 | - Growth Potential: Highlight the company's market opportunities, revenue projections, and scalability.
29 | - Competitive Advantages: Emphasize factors like unique products, strong branding, or dominant market positioning.
30 | - Positive Indicators: Use financial health, industry trends, and recent positive news as evidence.
31 | - 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.
32 | - Engagement: Present your argument in a conversational style, engaging directly with the bear analyst's points and debating effectively rather than just listing data.
33 | 
34 | Resources available:
35 | Market research report: {market_research_report}
36 | Social media sentiment report: {sentiment_report}
37 | Latest world affairs news: {news_report}
38 | Company fundamentals report: {fundamentals_report}
39 | Conversation history of the debate: {history}
40 | Last bear argument: {current_response}
41 | Reflections from similar situations and lessons learned: {past_memory_str}
42 | Use this information to deliver a compelling bull argument, refute the bear's concerns, and engage in a dynamic debate that demonstrates the strengths of the bull position. You must also address reflections and learn from lessons and mistakes you made in the past.
43 | """
44 | 
45 |         response = llm.invoke(prompt)
46 | 
47 |         argument = f"Bull Analyst: {response.content}"
48 | 
49 |         new_investment_debate_state = {
50 |             "history": history + "\n" + argument,
51 |             "bull_history": bull_history + "\n" + argument,
52 |             "bear_history": investment_debate_state.get("bear_history", ""),
53 |             "current_response": argument,
54 |             "count": investment_debate_state["count"] + 1,
55 |         }
56 | 
57 |         return {"investment_debate_state": new_investment_debate_state}
58 | 
59 |     return bull_node
60 | 


--------------------------------------------------------------------------------
/tradingagents/agents/risk_mgmt/aggresive_debator.py:
--------------------------------------------------------------------------------
 1 | import time
 2 | import json
 3 | 
 4 | 
 5 | def create_risky_debator(llm):
 6 |     def risky_node(state) -> dict:
 7 |         risk_debate_state = state["risk_debate_state"]
 8 |         history = risk_debate_state.get("history", "")
 9 |         risky_history = risk_debate_state.get("risky_history", "")
10 | 
11 |         current_safe_response = risk_debate_state.get("current_safe_response", "")
12 |         current_neutral_response = risk_debate_state.get("current_neutral_response", "")
13 | 
14 |         market_research_report = state["market_report"]
15 |         sentiment_report = state["sentiment_report"]
16 |         news_report = state["news_report"]
17 |         fundamentals_report = state["fundamentals_report"]
18 | 
19 |         trader_decision = state["trader_investment_plan"]
20 | 
21 |         prompt = f"""As the Risky 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:
22 | 
23 | {trader_decision}
24 | 
25 | Your task is to create a compelling case for the trader's decision by questioning and critiquing the conservative and neutral stances to demonstrate why your high-reward perspective offers the best path forward. Incorporate insights from the following sources into your arguments:
26 | 
27 | Market Research Report: {market_research_report}
28 | Social Media Sentiment Report: {sentiment_report}
29 | Latest World Affairs Report: {news_report}
30 | Company Fundamentals Report: {fundamentals_report}
31 | Here is the current conversation history: {history} Here are the last arguments from the conservative analyst: {current_safe_response} Here are the last arguments from the neutral analyst: {current_neutral_response}. If there are no responses from the other viewpoints, do not halluncinate and just present your point.
32 | 
33 | Engage actively by addressing any specific concerns raised, refuting the weaknesses in their logic, and asserting the benefits of risk-taking to outpace market norms. Maintain a focus on debating and persuading, not just presenting data. Challenge each counterpoint to underscore why a high-risk approach is optimal. Output conversationally as if you are speaking without any special formatting."""
34 | 
35 |         response = llm.invoke(prompt)
36 | 
37 |         argument = f"Risky Analyst: {response.content}"
38 | 
39 |         new_risk_debate_state = {
40 |             "history": history + "\n" + argument,
41 |             "risky_history": risky_history + "\n" + argument,
42 |             "safe_history": risk_debate_state.get("safe_history", ""),
43 |             "neutral_history": risk_debate_state.get("neutral_history", ""),
44 |             "latest_speaker": "Risky",
45 |             "current_risky_response": argument,
46 |             "current_safe_response": risk_debate_state.get("current_safe_response", ""),
47 |             "current_neutral_response": risk_debate_state.get(
48 |                 "current_neutral_response", ""
49 |             ),
50 |             "count": risk_debate_state["count"] + 1,
51 |         }
52 | 
53 |         return {"risk_debate_state": new_risk_debate_state}
54 | 
55 |     return risky_node
56 | 


--------------------------------------------------------------------------------
/tradingagents/agents/risk_mgmt/conservative_debator.py:
--------------------------------------------------------------------------------
 1 | from langchain_core.messages import AIMessage
 2 | import time
 3 | import json
 4 | 
 5 | 
 6 | def create_safe_debator(llm):
 7 |     def safe_node(state) -> dict:
 8 |         risk_debate_state = state["risk_debate_state"]
 9 |         history = risk_debate_state.get("history", "")
10 |         safe_history = risk_debate_state.get("safe_history", "")
11 | 
12 |         current_risky_response = risk_debate_state.get("current_risky_response", "")
13 |         current_neutral_response = risk_debate_state.get("current_neutral_response", "")
14 | 
15 |         market_research_report = state["market_report"]
16 |         sentiment_report = state["sentiment_report"]
17 |         news_report = state["news_report"]
18 |         fundamentals_report = state["fundamentals_report"]
19 | 
20 |         trader_decision = state["trader_investment_plan"]
21 | 
22 |         prompt = f"""As the Safe/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:
23 | 
24 | {trader_decision}
25 | 
26 | Your task is to actively counter the arguments of the Risky 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:
27 | 
28 | Market Research Report: {market_research_report}
29 | Social Media Sentiment Report: {sentiment_report}
30 | Latest World Affairs Report: {news_report}
31 | Company Fundamentals Report: {fundamentals_report}
32 | Here is the current conversation history: {history} Here is the last response from the risky analyst: {current_risky_response} Here is the last response from the neutral analyst: {current_neutral_response}. If there are no responses from the other viewpoints, do not halluncinate and just present your point.
33 | 
34 | Engage by questioning their optimism and emphasizing the potential downsides they may have overlooked. Address each of their counterpoints to showcase why a conservative stance is ultimately the safest path for the firm's assets. Focus on debating and critiquing their arguments to demonstrate the strength of a low-risk strategy over their approaches. Output conversationally as if you are speaking without any special formatting."""
35 | 
36 |         response = llm.invoke(prompt)
37 | 
38 |         argument = f"Safe Analyst: {response.content}"
39 | 
40 |         new_risk_debate_state = {
41 |             "history": history + "\n" + argument,
42 |             "risky_history": risk_debate_state.get("risky_history", ""),
43 |             "safe_history": safe_history + "\n" + argument,
44 |             "neutral_history": risk_debate_state.get("neutral_history", ""),
45 |             "latest_speaker": "Safe",
46 |             "current_risky_response": risk_debate_state.get(
47 |                 "current_risky_response", ""
48 |             ),
49 |             "current_safe_response": argument,
50 |             "current_neutral_response": risk_debate_state.get(
51 |                 "current_neutral_response", ""
52 |             ),
53 |             "count": risk_debate_state["count"] + 1,
54 |         }
55 | 
56 |         return {"risk_debate_state": new_risk_debate_state}
57 | 
58 |     return safe_node
59 | 


--------------------------------------------------------------------------------
/tradingagents/agents/risk_mgmt/neutral_debator.py:
--------------------------------------------------------------------------------
 1 | import time
 2 | import json
 3 | 
 4 | 
 5 | def create_neutral_debator(llm):
 6 |     def neutral_node(state) -> dict:
 7 |         risk_debate_state = state["risk_debate_state"]
 8 |         history = risk_debate_state.get("history", "")
 9 |         neutral_history = risk_debate_state.get("neutral_history", "")
10 | 
11 |         current_risky_response = risk_debate_state.get("current_risky_response", "")
12 |         current_safe_response = risk_debate_state.get("current_safe_response", "")
13 | 
14 |         market_research_report = state["market_report"]
15 |         sentiment_report = state["sentiment_report"]
16 |         news_report = state["news_report"]
17 |         fundamentals_report = state["fundamentals_report"]
18 | 
19 |         trader_decision = state["trader_investment_plan"]
20 | 
21 |         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:
22 | 
23 | {trader_decision}
24 | 
25 | Your task is to challenge both the Risky and Safe 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:
26 | 
27 | Market Research Report: {market_research_report}
28 | Social Media Sentiment Report: {sentiment_report}
29 | Latest World Affairs Report: {news_report}
30 | Company Fundamentals Report: {fundamentals_report}
31 | Here is the current conversation history: {history} Here is the last response from the risky analyst: {current_risky_response} Here is the last response from the safe analyst: {current_safe_response}. If there are no responses from the other viewpoints, do not halluncinate and just present your point.
32 | 
33 | Engage actively by analyzing both sides critically, addressing weaknesses in the risky 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."""
34 | 
35 |         response = llm.invoke(prompt)
36 | 
37 |         argument = f"Neutral Analyst: {response.content}"
38 | 
39 |         new_risk_debate_state = {
40 |             "history": history + "\n" + argument,
41 |             "risky_history": risk_debate_state.get("risky_history", ""),
42 |             "safe_history": risk_debate_state.get("safe_history", ""),
43 |             "neutral_history": neutral_history + "\n" + argument,
44 |             "latest_speaker": "Neutral",
45 |             "current_risky_response": risk_debate_state.get(
46 |                 "current_risky_response", ""
47 |             ),
48 |             "current_safe_response": risk_debate_state.get("current_safe_response", ""),
49 |             "current_neutral_response": argument,
50 |             "count": risk_debate_state["count"] + 1,
51 |         }
52 | 
53 |         return {"risk_debate_state": new_risk_debate_state}
54 | 
55 |     return neutral_node
56 | 


--------------------------------------------------------------------------------
/tradingagents/agents/trader/trader.py:
--------------------------------------------------------------------------------
 1 | import functools
 2 | import time
 3 | import json
 4 | 
 5 | 
 6 | def create_trader(llm, memory):
 7 |     def trader_node(state, name):
 8 |         company_name = state["company_of_interest"]
 9 |         investment_plan = state["investment_plan"]
10 |         market_research_report = state["market_report"]
11 |         sentiment_report = state["sentiment_report"]
12 |         news_report = state["news_report"]
13 |         fundamentals_report = state["fundamentals_report"]
14 | 
15 |         curr_situation = f"{market_research_report}\n\n{sentiment_report}\n\n{news_report}\n\n{fundamentals_report}"
16 |         past_memories = memory.get_memories(curr_situation, n_matches=2)
17 | 
18 |         past_memory_str = ""
19 |         if past_memories:
20 |             for i, rec in enumerate(past_memories, 1):
21 |                 past_memory_str += rec["recommendation"] + "\n\n"
22 |         else:
23 |             past_memory_str = "No past memories found."
24 | 
25 |         context = {
26 |             "role": "user",
27 |             "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.",
28 |         }
29 | 
30 |         messages = [
31 |             {
32 |                 "role": "system",
33 |                 "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}""",
34 |             },
35 |             context,
36 |         ]
37 | 
38 |         result = llm.invoke(messages)
39 | 
40 |         return {
41 |             "messages": [result],
42 |             "trader_investment_plan": result.content,
43 |             "sender": name,
44 |         }
45 | 
46 |     return functools.partial(trader_node, name="Trader")
47 | 


--------------------------------------------------------------------------------
/tradingagents/agents/utils/agent_states.py:
--------------------------------------------------------------------------------
 1 | from typing import Annotated, Sequence
 2 | from datetime import date, timedelta, datetime
 3 | from typing_extensions import TypedDict, Optional
 4 | from langchain_openai import ChatOpenAI
 5 | from tradingagents.agents import *
 6 | from langgraph.prebuilt import ToolNode
 7 | from langgraph.graph import END, StateGraph, START, MessagesState
 8 | 
 9 | 
10 | # Researcher team state
11 | class InvestDebateState(TypedDict):
12 |     bull_history: Annotated[
13 |         str, "Bullish Conversation history"
14 |     ]  # Bullish Conversation history
15 |     bear_history: Annotated[
16 |         str, "Bearish Conversation history"
17 |     ]  # Bullish Conversation history
18 |     history: Annotated[str, "Conversation history"]  # Conversation history
19 |     current_response: Annotated[str, "Latest response"]  # Last response
20 |     judge_decision: Annotated[str, "Final judge decision"]  # Last response
21 |     count: Annotated[int, "Length of the current conversation"]  # Conversation length
22 | 
23 | 
24 | # Risk management team state
25 | class RiskDebateState(TypedDict):
26 |     risky_history: Annotated[
27 |         str, "Risky Agent's Conversation history"
28 |     ]  # Conversation history
29 |     safe_history: Annotated[
30 |         str, "Safe Agent's Conversation history"
31 |     ]  # Conversation history
32 |     neutral_history: Annotated[
33 |         str, "Neutral Agent's Conversation history"
34 |     ]  # Conversation history
35 |     history: Annotated[str, "Conversation history"]  # Conversation history
36 |     latest_speaker: Annotated[str, "Analyst that spoke last"]
37 |     current_risky_response: Annotated[
38 |         str, "Latest response by the risky analyst"
39 |     ]  # Last response
40 |     current_safe_response: Annotated[
41 |         str, "Latest response by the safe analyst"
42 |     ]  # Last response
43 |     current_neutral_response: Annotated[
44 |         str, "Latest response by the neutral analyst"
45 |     ]  # Last response
46 |     judge_decision: Annotated[str, "Judge's decision"]
47 |     count: Annotated[int, "Length of the current conversation"]  # Conversation length
48 | 
49 | 
50 | class AgentState(MessagesState):
51 |     company_of_interest: Annotated[str, "Company that we are interested in trading"]
52 |     trade_date: Annotated[str, "What date we are trading at"]
53 | 
54 |     sender: Annotated[str, "Agent that sent this message"]
55 | 
56 |     # research step
57 |     market_report: Annotated[str, "Report from the Market Analyst"]
58 |     sentiment_report: Annotated[str, "Report from the Social Media Analyst"]
59 |     news_report: Annotated[
60 |         str, "Report from the News Researcher of current world affairs"
61 |     ]
62 |     fundamentals_report: Annotated[str, "Report from the Fundamentals Researcher"]
63 | 
64 |     # researcher team discussion step
65 |     investment_debate_state: Annotated[
66 |         InvestDebateState, "Current state of the debate on if to invest or not"
67 |     ]
68 |     investment_plan: Annotated[str, "Plan generated by the Analyst"]
69 | 
70 |     trader_investment_plan: Annotated[str, "Plan generated by the Trader"]
71 | 
72 |     # risk management team discussion step
73 |     risk_debate_state: Annotated[
74 |         RiskDebateState, "Current state of the debate on evaluating risk"
75 |     ]
76 |     final_trade_decision: Annotated[str, "Final decision made by the Risk Analysts"]
77 | 


--------------------------------------------------------------------------------
/tradingagents/agents/utils/agent_utils.py:
--------------------------------------------------------------------------------
  1 | from langchain_core.messages import BaseMessage, HumanMessage, ToolMessage, AIMessage
  2 | from typing import List
  3 | from typing import Annotated
  4 | from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
  5 | from langchain_core.messages import RemoveMessage
  6 | from langchain_core.tools import tool
  7 | from datetime import date, timedelta, datetime
  8 | import functools
  9 | import pandas as pd
 10 | import os
 11 | from dateutil.relativedelta import relativedelta
 12 | from langchain_openai import ChatOpenAI
 13 | import tradingagents.dataflows.interface as interface
 14 | from tradingagents.default_config import DEFAULT_CONFIG
 15 | from langchain_core.messages import HumanMessage
 16 | 
 17 | 
 18 | def create_msg_delete():
 19 |     def delete_messages(state):
 20 |         """Clear messages and add placeholder for Anthropic compatibility"""
 21 |         messages = state["messages"]
 22 |         
 23 |         # Remove all messages
 24 |         removal_operations = [RemoveMessage(id=m.id) for m in messages]
 25 |         
 26 |         # Add a minimal placeholder message
 27 |         placeholder = HumanMessage(content="Continue")
 28 |         
 29 |         return {"messages": removal_operations + [placeholder]}
 30 |     
 31 |     return delete_messages
 32 | 
 33 | 
 34 | class Toolkit:
 35 |     _config = DEFAULT_CONFIG.copy()
 36 | 
 37 |     @classmethod
 38 |     def update_config(cls, config):
 39 |         """Update the class-level configuration."""
 40 |         cls._config.update(config)
 41 | 
 42 |     @property
 43 |     def config(self):
 44 |         """Access the configuration."""
 45 |         return self._config
 46 | 
 47 |     def __init__(self, config=None):
 48 |         if config:
 49 |             self.update_config(config)
 50 | 
 51 |     @staticmethod
 52 |     @tool
 53 |     def get_reddit_news(
 54 |         curr_date: Annotated[str, "Date you want to get news for in yyyy-mm-dd format"],
 55 |     ) -> str:
 56 |         """
 57 |         Retrieve global news from Reddit within a specified time frame.
 58 |         Args:
 59 |             curr_date (str): Date you want to get news for in yyyy-mm-dd format
 60 |         Returns:
 61 |             str: A formatted dataframe containing the latest global news from Reddit in the specified time frame.
 62 |         """
 63 |         
 64 |         global_news_result = interface.get_reddit_global_news(curr_date, 7, 5)
 65 | 
 66 |         return global_news_result
 67 | 
 68 |     @staticmethod
 69 |     @tool
 70 |     def get_finnhub_news(
 71 |         ticker: Annotated[
 72 |             str,
 73 |             "Search query of a company, e.g. 'AAPL, TSM, etc.",
 74 |         ],
 75 |         start_date: Annotated[str, "Start date in yyyy-mm-dd format"],
 76 |         end_date: Annotated[str, "End date in yyyy-mm-dd format"],
 77 |     ):
 78 |         """
 79 |         Retrieve the latest news about a given stock from Finnhub within a date range
 80 |         Args:
 81 |             ticker (str): Ticker of a company. e.g. AAPL, TSM
 82 |             start_date (str): Start date in yyyy-mm-dd format
 83 |             end_date (str): End date in yyyy-mm-dd format
 84 |         Returns:
 85 |             str: A formatted dataframe containing news about the company within the date range from start_date to end_date
 86 |         """
 87 | 
 88 |         end_date_str = end_date
 89 | 
 90 |         end_date = datetime.strptime(end_date, "%Y-%m-%d")
 91 |         start_date = datetime.strptime(start_date, "%Y-%m-%d")
 92 |         look_back_days = (end_date - start_date).days
 93 | 
 94 |         finnhub_news_result = interface.get_finnhub_news(
 95 |             ticker, end_date_str, look_back_days
 96 |         )
 97 | 
 98 |         return finnhub_news_result
 99 | 
100 |     @staticmethod
101 |     @tool
102 |     def get_reddit_stock_info(
103 |         ticker: Annotated[
104 |             str,
105 |             "Ticker of a company. e.g. AAPL, TSM",
106 |         ],
107 |         curr_date: Annotated[str, "Current date you want to get news for"],
108 |     ) -> str:
109 |         """
110 |         Retrieve the latest news about a given stock from Reddit, given the current date.
111 |         Args:
112 |             ticker (str): Ticker of a company. e.g. AAPL, TSM
113 |             curr_date (str): current date in yyyy-mm-dd format to get news for
114 |         Returns:
115 |             str: A formatted dataframe containing the latest news about the company on the given date
116 |         """
117 | 
118 |         stock_news_results = interface.get_reddit_company_news(ticker, curr_date, 7, 5)
119 | 
120 |         return stock_news_results
121 | 
122 |     @staticmethod
123 |     @tool
124 |     def get_YFin_data(
125 |         symbol: Annotated[str, "ticker symbol of the company"],
126 |         start_date: Annotated[str, "Start date in yyyy-mm-dd format"],
127 |         end_date: Annotated[str, "End date in yyyy-mm-dd format"],
128 |     ) -> str:
129 |         """
130 |         Retrieve the stock price data for a given ticker symbol from Yahoo Finance.
131 |         Args:
132 |             symbol (str): Ticker symbol of the company, e.g. AAPL, TSM
133 |             start_date (str): Start date in yyyy-mm-dd format
134 |             end_date (str): End date in yyyy-mm-dd format
135 |         Returns:
136 |             str: A formatted dataframe containing the stock price data for the specified ticker symbol in the specified date range.
137 |         """
138 | 
139 |         result_data = interface.get_YFin_data(symbol, start_date, end_date)
140 | 
141 |         return result_data
142 | 
143 |     @staticmethod
144 |     @tool
145 |     def get_YFin_data_online(
146 |         symbol: Annotated[str, "ticker symbol of the company"],
147 |         start_date: Annotated[str, "Start date in yyyy-mm-dd format"],
148 |         end_date: Annotated[str, "End date in yyyy-mm-dd format"],
149 |     ) -> str:
150 |         """
151 |         Retrieve the stock price data for a given ticker symbol from Yahoo Finance.
152 |         Args:
153 |             symbol (str): Ticker symbol of the company, e.g. AAPL, TSM
154 |             start_date (str): Start date in yyyy-mm-dd format
155 |             end_date (str): End date in yyyy-mm-dd format
156 |         Returns:
157 |             str: A formatted dataframe containing the stock price data for the specified ticker symbol in the specified date range.
158 |         """
159 | 
160 |         result_data = interface.get_YFin_data_online(symbol, start_date, end_date)
161 | 
162 |         return result_data
163 | 
164 |     @staticmethod
165 |     @tool
166 |     def get_stockstats_indicators_report(
167 |         symbol: Annotated[str, "ticker symbol of the company"],
168 |         indicator: Annotated[
169 |             str, "technical indicator to get the analysis and report of"
170 |         ],
171 |         curr_date: Annotated[
172 |             str, "The current trading date you are trading on, YYYY-mm-dd"
173 |         ],
174 |         look_back_days: Annotated[int, "how many days to look back"] = 30,
175 |     ) -> str:
176 |         """
177 |         Retrieve stock stats indicators for a given ticker symbol and indicator.
178 |         Args:
179 |             symbol (str): Ticker symbol of the company, e.g. AAPL, TSM
180 |             indicator (str): Technical indicator to get the analysis and report of
181 |             curr_date (str): The current trading date you are trading on, YYYY-mm-dd
182 |             look_back_days (int): How many days to look back, default is 30
183 |         Returns:
184 |             str: A formatted dataframe containing the stock stats indicators for the specified ticker symbol and indicator.
185 |         """
186 | 
187 |         result_stockstats = interface.get_stock_stats_indicators_window(
188 |             symbol, indicator, curr_date, look_back_days, False
189 |         )
190 | 
191 |         return result_stockstats
192 | 
193 |     @staticmethod
194 |     @tool
195 |     def get_stockstats_indicators_report_online(
196 |         symbol: Annotated[str, "ticker symbol of the company"],
197 |         indicator: Annotated[
198 |             str, "technical indicator to get the analysis and report of"
199 |         ],
200 |         curr_date: Annotated[
201 |             str, "The current trading date you are trading on, YYYY-mm-dd"
202 |         ],
203 |         look_back_days: Annotated[int, "how many days to look back"] = 30,
204 |     ) -> str:
205 |         """
206 |         Retrieve stock stats indicators for a given ticker symbol and indicator.
207 |         Args:
208 |             symbol (str): Ticker symbol of the company, e.g. AAPL, TSM
209 |             indicator (str): Technical indicator to get the analysis and report of
210 |             curr_date (str): The current trading date you are trading on, YYYY-mm-dd
211 |             look_back_days (int): How many days to look back, default is 30
212 |         Returns:
213 |             str: A formatted dataframe containing the stock stats indicators for the specified ticker symbol and indicator.
214 |         """
215 | 
216 |         result_stockstats = interface.get_stock_stats_indicators_window(
217 |             symbol, indicator, curr_date, look_back_days, True
218 |         )
219 | 
220 |         return result_stockstats
221 | 
222 |     @staticmethod
223 |     @tool
224 |     def get_finnhub_company_insider_sentiment(
225 |         ticker: Annotated[str, "ticker symbol for the company"],
226 |         curr_date: Annotated[
227 |             str,
228 |             "current date of you are trading at, yyyy-mm-dd",
229 |         ],
230 |     ):
231 |         """
232 |         Retrieve insider sentiment information about a company (retrieved from public SEC information) for the past 30 days
233 |         Args:
234 |             ticker (str): ticker symbol of the company
235 |             curr_date (str): current date you are trading at, yyyy-mm-dd
236 |         Returns:
237 |             str: a report of the sentiment in the past 30 days starting at curr_date
238 |         """
239 | 
240 |         data_sentiment = interface.get_finnhub_company_insider_sentiment(
241 |             ticker, curr_date, 30
242 |         )
243 | 
244 |         return data_sentiment
245 | 
246 |     @staticmethod
247 |     @tool
248 |     def get_finnhub_company_insider_transactions(
249 |         ticker: Annotated[str, "ticker symbol"],
250 |         curr_date: Annotated[
251 |             str,
252 |             "current date you are trading at, yyyy-mm-dd",
253 |         ],
254 |     ):
255 |         """
256 |         Retrieve insider transaction information about a company (retrieved from public SEC information) for the past 30 days
257 |         Args:
258 |             ticker (str): ticker symbol of the company
259 |             curr_date (str): current date you are trading at, yyyy-mm-dd
260 |         Returns:
261 |             str: a report of the company's insider transactions/trading information in the past 30 days
262 |         """
263 | 
264 |         data_trans = interface.get_finnhub_company_insider_transactions(
265 |             ticker, curr_date, 30
266 |         )
267 | 
268 |         return data_trans
269 | 
270 |     @staticmethod
271 |     @tool
272 |     def get_simfin_balance_sheet(
273 |         ticker: Annotated[str, "ticker symbol"],
274 |         freq: Annotated[
275 |             str,
276 |             "reporting frequency of the company's financial history: annual/quarterly",
277 |         ],
278 |         curr_date: Annotated[str, "current date you are trading at, yyyy-mm-dd"],
279 |     ):
280 |         """
281 |         Retrieve the most recent balance sheet of a company
282 |         Args:
283 |             ticker (str): ticker symbol of the company
284 |             freq (str): reporting frequency of the company's financial history: annual / quarterly
285 |             curr_date (str): current date you are trading at, yyyy-mm-dd
286 |         Returns:
287 |             str: a report of the company's most recent balance sheet
288 |         """
289 | 
290 |         data_balance_sheet = interface.get_simfin_balance_sheet(ticker, freq, curr_date)
291 | 
292 |         return data_balance_sheet
293 | 
294 |     @staticmethod
295 |     @tool
296 |     def get_simfin_cashflow(
297 |         ticker: Annotated[str, "ticker symbol"],
298 |         freq: Annotated[
299 |             str,
300 |             "reporting frequency of the company's financial history: annual/quarterly",
301 |         ],
302 |         curr_date: Annotated[str, "current date you are trading at, yyyy-mm-dd"],
303 |     ):
304 |         """
305 |         Retrieve the most recent cash flow statement of a company
306 |         Args:
307 |             ticker (str): ticker symbol of the company
308 |             freq (str): reporting frequency of the company's financial history: annual / quarterly
309 |             curr_date (str): current date you are trading at, yyyy-mm-dd
310 |         Returns:
311 |                 str: a report of the company's most recent cash flow statement
312 |         """
313 | 
314 |         data_cashflow = interface.get_simfin_cashflow(ticker, freq, curr_date)
315 | 
316 |         return data_cashflow
317 | 
318 |     @staticmethod
319 |     @tool
320 |     def get_simfin_income_stmt(
321 |         ticker: Annotated[str, "ticker symbol"],
322 |         freq: Annotated[
323 |             str,
324 |             "reporting frequency of the company's financial history: annual/quarterly",
325 |         ],
326 |         curr_date: Annotated[str, "current date you are trading at, yyyy-mm-dd"],
327 |     ):
328 |         """
329 |         Retrieve the most recent income statement of a company
330 |         Args:
331 |             ticker (str): ticker symbol of the company
332 |             freq (str): reporting frequency of the company's financial history: annual / quarterly
333 |             curr_date (str): current date you are trading at, yyyy-mm-dd
334 |         Returns:
335 |                 str: a report of the company's most recent income statement
336 |         """
337 | 
338 |         data_income_stmt = interface.get_simfin_income_statements(
339 |             ticker, freq, curr_date
340 |         )
341 | 
342 |         return data_income_stmt
343 | 
344 |     @staticmethod
345 |     @tool
346 |     def get_google_news(
347 |         query: Annotated[str, "Query to search with"],
348 |         curr_date: Annotated[str, "Curr date in yyyy-mm-dd format"],
349 |     ):
350 |         """
351 |         Retrieve the latest news from Google News based on a query and date range.
352 |         Args:
353 |             query (str): Query to search with
354 |             curr_date (str): Current date in yyyy-mm-dd format
355 |             look_back_days (int): How many days to look back
356 |         Returns:
357 |             str: A formatted string containing the latest news from Google News based on the query and date range.
358 |         """
359 | 
360 |         google_news_results = interface.get_google_news(query, curr_date, 7)
361 | 
362 |         return google_news_results
363 | 
364 |     @staticmethod
365 |     @tool
366 |     def get_stock_news_openai(
367 |         ticker: Annotated[str, "the company's ticker"],
368 |         curr_date: Annotated[str, "Current date in yyyy-mm-dd format"],
369 |     ):
370 |         """
371 |         Retrieve the latest news about a given stock by using OpenAI's news API.
372 |         Args:
373 |             ticker (str): Ticker of a company. e.g. AAPL, TSM
374 |             curr_date (str): Current date in yyyy-mm-dd format
375 |         Returns:
376 |             str: A formatted string containing the latest news about the company on the given date.
377 |         """
378 | 
379 |         openai_news_results = interface.get_stock_news_openai(ticker, curr_date)
380 | 
381 |         return openai_news_results
382 | 
383 |     @staticmethod
384 |     @tool
385 |     def get_global_news_openai(
386 |         curr_date: Annotated[str, "Current date in yyyy-mm-dd format"],
387 |     ):
388 |         """
389 |         Retrieve the latest macroeconomics news on a given date using OpenAI's macroeconomics news API.
390 |         Args:
391 |             curr_date (str): Current date in yyyy-mm-dd format
392 |         Returns:
393 |             str: A formatted string containing the latest macroeconomic news on the given date.
394 |         """
395 | 
396 |         openai_news_results = interface.get_global_news_openai(curr_date)
397 | 
398 |         return openai_news_results
399 | 
400 |     @staticmethod
401 |     @tool
402 |     def get_fundamentals_openai(
403 |         ticker: Annotated[str, "the company's ticker"],
404 |         curr_date: Annotated[str, "Current date in yyyy-mm-dd format"],
405 |     ):
406 |         """
407 |         Retrieve the latest fundamental information about a given stock on a given date by using OpenAI's news API.
408 |         Args:
409 |             ticker (str): Ticker of a company. e.g. AAPL, TSM
410 |             curr_date (str): Current date in yyyy-mm-dd format
411 |         Returns:
412 |             str: A formatted string containing the latest fundamental information about the company on the given date.
413 |         """
414 | 
415 |         openai_fundamentals_results = interface.get_fundamentals_openai(
416 |             ticker, curr_date
417 |         )
418 | 
419 |         return openai_fundamentals_results
420 | 


--------------------------------------------------------------------------------
/tradingagents/agents/utils/memory.py:
--------------------------------------------------------------------------------
  1 | import chromadb
  2 | from chromadb.config import Settings
  3 | from openai import OpenAI
  4 | 
  5 | 
  6 | class FinancialSituationMemory:
  7 |     def __init__(self, name, config):
  8 |         if config["backend_url"] == "http://localhost:11434/v1":
  9 |             self.embedding = "nomic-embed-text"
 10 |         else:
 11 |             self.embedding = "text-embedding-3-small"
 12 |         self.client = OpenAI(base_url=config["backend_url"])
 13 |         self.chroma_client = chromadb.Client(Settings(allow_reset=True))
 14 |         self.situation_collection = self.chroma_client.create_collection(name=name)
 15 | 
 16 |     def get_embedding(self, text):
 17 |         """Get OpenAI embedding for a text"""
 18 |         
 19 |         response = self.client.embeddings.create(
 20 |             model=self.embedding, input=text
 21 |         )
 22 |         return response.data[0].embedding
 23 | 
 24 |     def add_situations(self, situations_and_advice):
 25 |         """Add financial situations and their corresponding advice. Parameter is a list of tuples (situation, rec)"""
 26 | 
 27 |         situations = []
 28 |         advice = []
 29 |         ids = []
 30 |         embeddings = []
 31 | 
 32 |         offset = self.situation_collection.count()
 33 | 
 34 |         for i, (situation, recommendation) in enumerate(situations_and_advice):
 35 |             situations.append(situation)
 36 |             advice.append(recommendation)
 37 |             ids.append(str(offset + i))
 38 |             embeddings.append(self.get_embedding(situation))
 39 | 
 40 |         self.situation_collection.add(
 41 |             documents=situations,
 42 |             metadatas=[{"recommendation": rec} for rec in advice],
 43 |             embeddings=embeddings,
 44 |             ids=ids,
 45 |         )
 46 | 
 47 |     def get_memories(self, current_situation, n_matches=1):
 48 |         """Find matching recommendations using OpenAI embeddings"""
 49 |         query_embedding = self.get_embedding(current_situation)
 50 | 
 51 |         results = self.situation_collection.query(
 52 |             query_embeddings=[query_embedding],
 53 |             n_results=n_matches,
 54 |             include=["metadatas", "documents", "distances"],
 55 |         )
 56 | 
 57 |         matched_results = []
 58 |         for i in range(len(results["documents"][0])):
 59 |             matched_results.append(
 60 |                 {
 61 |                     "matched_situation": results["documents"][0][i],
 62 |                     "recommendation": results["metadatas"][0][i]["recommendation"],
 63 |                     "similarity_score": 1 - results["distances"][0][i],
 64 |                 }
 65 |             )
 66 | 
 67 |         return matched_results
 68 | 
 69 | 
 70 | if __name__ == "__main__":
 71 |     # Example usage
 72 |     matcher = FinancialSituationMemory()
 73 | 
 74 |     # Example data
 75 |     example_data = [
 76 |         (
 77 |             "High inflation rate with rising interest rates and declining consumer spending",
 78 |             "Consider defensive sectors like consumer staples and utilities. Review fixed-income portfolio duration.",
 79 |         ),
 80 |         (
 81 |             "Tech sector showing high volatility with increasing institutional selling pressure",
 82 |             "Reduce exposure to high-growth tech stocks. Look for value opportunities in established tech companies with strong cash flows.",
 83 |         ),
 84 |         (
 85 |             "Strong dollar affecting emerging markets with increasing forex volatility",
 86 |             "Hedge currency exposure in international positions. Consider reducing allocation to emerging market debt.",
 87 |         ),
 88 |         (
 89 |             "Market showing signs of sector rotation with rising yields",
 90 |             "Rebalance portfolio to maintain target allocations. Consider increasing exposure to sectors benefiting from higher rates.",
 91 |         ),
 92 |     ]
 93 | 
 94 |     # Add the example situations and recommendations
 95 |     matcher.add_situations(example_data)
 96 | 
 97 |     # Example query
 98 |     current_situation = """
 99 |     Market showing increased volatility in tech sector, with institutional investors 
100 |     reducing positions and rising interest rates affecting growth stock valuations
101 |     """
102 | 
103 |     try:
104 |         recommendations = matcher.get_memories(current_situation, n_matches=2)
105 | 
106 |         for i, rec in enumerate(recommendations, 1):
107 |             print(f"\nMatch {i}:")
108 |             print(f"Similarity Score: {rec['similarity_score']:.2f}")
109 |             print(f"Matched Situation: {rec['matched_situation']}")
110 |             print(f"Recommendation: {rec['recommendation']}")
111 | 
112 |     except Exception as e:
113 |         print(f"Error during recommendation: {str(e)}")
114 | 


--------------------------------------------------------------------------------
/tradingagents/dataflows/__init__.py:
--------------------------------------------------------------------------------
 1 | from .finnhub_utils import get_data_in_range
 2 | from .googlenews_utils import getNewsData
 3 | from .yfin_utils import YFinanceUtils
 4 | from .reddit_utils import fetch_top_from_category
 5 | from .stockstats_utils import StockstatsUtils
 6 | from .yfin_utils import YFinanceUtils
 7 | 
 8 | from .interface import (
 9 |     # News and sentiment functions
10 |     get_finnhub_news,
11 |     get_finnhub_company_insider_sentiment,
12 |     get_finnhub_company_insider_transactions,
13 |     get_google_news,
14 |     get_reddit_global_news,
15 |     get_reddit_company_news,
16 |     # Financial statements functions
17 |     get_simfin_balance_sheet,
18 |     get_simfin_cashflow,
19 |     get_simfin_income_statements,
20 |     # Technical analysis functions
21 |     get_stock_stats_indicators_window,
22 |     get_stockstats_indicator,
23 |     # Market data functions
24 |     get_YFin_data_window,
25 |     get_YFin_data,
26 | )
27 | 
28 | __all__ = [
29 |     # News and sentiment functions
30 |     "get_finnhub_news",
31 |     "get_finnhub_company_insider_sentiment",
32 |     "get_finnhub_company_insider_transactions",
33 |     "get_google_news",
34 |     "get_reddit_global_news",
35 |     "get_reddit_company_news",
36 |     # Financial statements functions
37 |     "get_simfin_balance_sheet",
38 |     "get_simfin_cashflow",
39 |     "get_simfin_income_statements",
40 |     # Technical analysis functions
41 |     "get_stock_stats_indicators_window",
42 |     "get_stockstats_indicator",
43 |     # Market data functions
44 |     "get_YFin_data_window",
45 |     "get_YFin_data",
46 | ]
47 | 


--------------------------------------------------------------------------------
/tradingagents/dataflows/config.py:
--------------------------------------------------------------------------------
 1 | import tradingagents.default_config as default_config
 2 | from typing import Dict, Optional
 3 | 
 4 | # Use default config but allow it to be overridden
 5 | _config: Optional[Dict] = None
 6 | DATA_DIR: Optional[str] = None
 7 | 
 8 | 
 9 | def initialize_config():
10 |     """Initialize the configuration with default values."""
11 |     global _config, DATA_DIR
12 |     if _config is None:
13 |         _config = default_config.DEFAULT_CONFIG.copy()
14 |         DATA_DIR = _config["data_dir"]
15 | 
16 | 
17 | def set_config(config: Dict):
18 |     """Update the configuration with custom values."""
19 |     global _config, DATA_DIR
20 |     if _config is None:
21 |         _config = default_config.DEFAULT_CONFIG.copy()
22 |     _config.update(config)
23 |     DATA_DIR = _config["data_dir"]
24 | 
25 | 
26 | def get_config() -> Dict:
27 |     """Get the current configuration."""
28 |     if _config is None:
29 |         initialize_config()
30 |     return _config.copy()
31 | 
32 | 
33 | # Initialize with default config
34 | initialize_config()
35 | 


--------------------------------------------------------------------------------
/tradingagents/dataflows/finnhub_utils.py:
--------------------------------------------------------------------------------
 1 | import json
 2 | import os
 3 | 
 4 | 
 5 | def get_data_in_range(ticker, start_date, end_date, data_type, data_dir, period=None):
 6 |     """
 7 |     Gets finnhub data saved and processed on disk.
 8 |     Args:
 9 |         start_date (str): Start date in YYYY-MM-DD format.
10 |         end_date (str): End date in YYYY-MM-DD format.
11 |         data_type (str): Type of data from finnhub to fetch. Can be insider_trans, SEC_filings, news_data, insider_senti, or fin_as_reported.
12 |         data_dir (str): Directory where the data is saved.
13 |         period (str): Default to none, if there is a period specified, should be annual or quarterly.
14 |     """
15 | 
16 |     if period:
17 |         data_path = os.path.join(
18 |             data_dir,
19 |             "finnhub_data",
20 |             data_type,
21 |             f"{ticker}_{period}_data_formatted.json",
22 |         )
23 |     else:
24 |         data_path = os.path.join(
25 |             data_dir, "finnhub_data", data_type, f"{ticker}_data_formatted.json"
26 |         )
27 | 
28 |     data = open(data_path, "r")
29 |     data = json.load(data)
30 | 
31 |     # filter keys (date, str in format YYYY-MM-DD) by the date range (str, str in format YYYY-MM-DD)
32 |     filtered_data = {}
33 |     for key, value in data.items():
34 |         if start_date <= key <= end_date and len(value) > 0:
35 |             filtered_data[key] = value
36 |     return filtered_data
37 | 


--------------------------------------------------------------------------------
/tradingagents/dataflows/googlenews_utils.py:
--------------------------------------------------------------------------------
  1 | import json
  2 | import requests
  3 | from bs4 import BeautifulSoup
  4 | from datetime import datetime
  5 | import time
  6 | import random
  7 | from tenacity import (
  8 |     retry,
  9 |     stop_after_attempt,
 10 |     wait_exponential,
 11 |     retry_if_exception_type,
 12 |     retry_if_result,
 13 | )
 14 | 
 15 | 
 16 | def is_rate_limited(response):
 17 |     """Check if the response indicates rate limiting (status code 429)"""
 18 |     return response.status_code == 429
 19 | 
 20 | 
 21 | @retry(
 22 |     retry=(retry_if_result(is_rate_limited)),
 23 |     wait=wait_exponential(multiplier=1, min=4, max=60),
 24 |     stop=stop_after_attempt(5),
 25 | )
 26 | def make_request(url, headers):
 27 |     """Make a request with retry logic for rate limiting"""
 28 |     # Random delay before each request to avoid detection
 29 |     time.sleep(random.uniform(2, 6))
 30 |     response = requests.get(url, headers=headers)
 31 |     return response
 32 | 
 33 | 
 34 | def getNewsData(query, start_date, end_date):
 35 |     """
 36 |     Scrape Google News search results for a given query and date range.
 37 |     query: str - search query
 38 |     start_date: str - start date in the format yyyy-mm-dd or mm/dd/yyyy
 39 |     end_date: str - end date in the format yyyy-mm-dd or mm/dd/yyyy
 40 |     """
 41 |     if "-" in start_date:
 42 |         start_date = datetime.strptime(start_date, "%Y-%m-%d")
 43 |         start_date = start_date.strftime("%m/%d/%Y")
 44 |     if "-" in end_date:
 45 |         end_date = datetime.strptime(end_date, "%Y-%m-%d")
 46 |         end_date = end_date.strftime("%m/%d/%Y")
 47 | 
 48 |     headers = {
 49 |         "User-Agent": (
 50 |             "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
 51 |             "AppleWebKit/537.36 (KHTML, like Gecko) "
 52 |             "Chrome/101.0.4951.54 Safari/537.36"
 53 |         )
 54 |     }
 55 | 
 56 |     news_results = []
 57 |     page = 0
 58 |     while True:
 59 |         offset = page * 10
 60 |         url = (
 61 |             f"https://www.google.com/search?q={query}"
 62 |             f"&tbs=cdr:1,cd_min:{start_date},cd_max:{end_date}"
 63 |             f"&tbm=nws&start={offset}"
 64 |         )
 65 | 
 66 |         try:
 67 |             response = make_request(url, headers)
 68 |             soup = BeautifulSoup(response.content, "html.parser")
 69 |             results_on_page = soup.select("div.SoaBEf")
 70 | 
 71 |             if not results_on_page:
 72 |                 break  # No more results found
 73 | 
 74 |             for el in results_on_page:
 75 |                 try:
 76 |                     link = el.find("a")["href"]
 77 |                     title = el.select_one("div.MBeuO").get_text()
 78 |                     snippet = el.select_one(".GI74Re").get_text()
 79 |                     date = el.select_one(".LfVVr").get_text()
 80 |                     source = el.select_one(".NUnG9d span").get_text()
 81 |                     news_results.append(
 82 |                         {
 83 |                             "link": link,
 84 |                             "title": title,
 85 |                             "snippet": snippet,
 86 |                             "date": date,
 87 |                             "source": source,
 88 |                         }
 89 |                     )
 90 |                 except Exception as e:
 91 |                     print(f"Error processing result: {e}")
 92 |                     # If one of the fields is not found, skip this result
 93 |                     continue
 94 | 
 95 |             # Update the progress bar with the current count of results scraped
 96 | 
 97 |             # Check for the "Next" link (pagination)
 98 |             next_link = soup.find("a", id="pnnext")
 99 |             if not next_link:
100 |                 break
101 | 
102 |             page += 1
103 | 
104 |         except Exception as e:
105 |             print(f"Failed after multiple retries: {e}")
106 |             break
107 | 
108 |     return news_results
109 | 


--------------------------------------------------------------------------------
/tradingagents/dataflows/interface.py:
--------------------------------------------------------------------------------
  1 | from typing import Annotated, Dict
  2 | from .reddit_utils import fetch_top_from_category
  3 | from .yfin_utils import *
  4 | from .stockstats_utils import *
  5 | from .googlenews_utils import *
  6 | from .finnhub_utils import get_data_in_range
  7 | from dateutil.relativedelta import relativedelta
  8 | from concurrent.futures import ThreadPoolExecutor
  9 | from datetime import datetime
 10 | import json
 11 | import os
 12 | import pandas as pd
 13 | from tqdm import tqdm
 14 | import yfinance as yf
 15 | from openai import OpenAI
 16 | from .config import get_config, set_config, DATA_DIR
 17 | 
 18 | 
 19 | def get_finnhub_news(
 20 |     ticker: Annotated[
 21 |         str,
 22 |         "Search query of a company's, e.g. 'AAPL, TSM, etc.",
 23 |     ],
 24 |     curr_date: Annotated[str, "Current date in yyyy-mm-dd format"],
 25 |     look_back_days: Annotated[int, "how many days to look back"],
 26 | ):
 27 |     """
 28 |     Retrieve news about a company within a time frame
 29 | 
 30 |     Args
 31 |         ticker (str): ticker for the company you are interested in
 32 |         start_date (str): Start date in yyyy-mm-dd format
 33 |         end_date (str): End date in yyyy-mm-dd format
 34 |     Returns
 35 |         str: dataframe containing the news of the company in the time frame
 36 | 
 37 |     """
 38 | 
 39 |     start_date = datetime.strptime(curr_date, "%Y-%m-%d")
 40 |     before = start_date - relativedelta(days=look_back_days)
 41 |     before = before.strftime("%Y-%m-%d")
 42 | 
 43 |     result = get_data_in_range(ticker, before, curr_date, "news_data", DATA_DIR)
 44 | 
 45 |     if len(result) == 0:
 46 |         return ""
 47 | 
 48 |     combined_result = ""
 49 |     for day, data in result.items():
 50 |         if len(data) == 0:
 51 |             continue
 52 |         for entry in data:
 53 |             current_news = (
 54 |                 "### " + entry["headline"] + f" ({day})" + "\n" + entry["summary"]
 55 |             )
 56 |             combined_result += current_news + "\n\n"
 57 | 
 58 |     return f"## {ticker} News, from {before} to {curr_date}:\n" + str(combined_result)
 59 | 
 60 | 
 61 | def get_finnhub_company_insider_sentiment(
 62 |     ticker: Annotated[str, "ticker symbol for the company"],
 63 |     curr_date: Annotated[
 64 |         str,
 65 |         "current date of you are trading at, yyyy-mm-dd",
 66 |     ],
 67 |     look_back_days: Annotated[int, "number of days to look back"],
 68 | ):
 69 |     """
 70 |     Retrieve insider sentiment about a company (retrieved from public SEC information) for the past 15 days
 71 |     Args:
 72 |         ticker (str): ticker symbol of the company
 73 |         curr_date (str): current date you are trading on, yyyy-mm-dd
 74 |     Returns:
 75 |         str: a report of the sentiment in the past 15 days starting at curr_date
 76 |     """
 77 | 
 78 |     date_obj = datetime.strptime(curr_date, "%Y-%m-%d")
 79 |     before = date_obj - relativedelta(days=look_back_days)
 80 |     before = before.strftime("%Y-%m-%d")
 81 | 
 82 |     data = get_data_in_range(ticker, before, curr_date, "insider_senti", DATA_DIR)
 83 | 
 84 |     if len(data) == 0:
 85 |         return ""
 86 | 
 87 |     result_str = ""
 88 |     seen_dicts = []
 89 |     for date, senti_list in data.items():
 90 |         for entry in senti_list:
 91 |             if entry not in seen_dicts:
 92 |                 result_str += f"### {entry['year']}-{entry['month']}:\nChange: {entry['change']}\nMonthly Share Purchase Ratio: {entry['mspr']}\n\n"
 93 |                 seen_dicts.append(entry)
 94 | 
 95 |     return (
 96 |         f"## {ticker} Insider Sentiment Data for {before} to {curr_date}:\n"
 97 |         + result_str
 98 |         + "The change field refers to the net buying/selling from all insiders' transactions. The mspr field refers to monthly share purchase ratio."
 99 |     )
100 | 
101 | 
102 | def get_finnhub_company_insider_transactions(
103 |     ticker: Annotated[str, "ticker symbol"],
104 |     curr_date: Annotated[
105 |         str,
106 |         "current date you are trading at, yyyy-mm-dd",
107 |     ],
108 |     look_back_days: Annotated[int, "how many days to look back"],
109 | ):
110 |     """
111 |     Retrieve insider transcaction information about a company (retrieved from public SEC information) for the past 15 days
112 |     Args:
113 |         ticker (str): ticker symbol of the company
114 |         curr_date (str): current date you are trading at, yyyy-mm-dd
115 |     Returns:
116 |         str: a report of the company's insider transaction/trading informtaion in the past 15 days
117 |     """
118 | 
119 |     date_obj = datetime.strptime(curr_date, "%Y-%m-%d")
120 |     before = date_obj - relativedelta(days=look_back_days)
121 |     before = before.strftime("%Y-%m-%d")
122 | 
123 |     data = get_data_in_range(ticker, before, curr_date, "insider_trans", DATA_DIR)
124 | 
125 |     if len(data) == 0:
126 |         return ""
127 | 
128 |     result_str = ""
129 | 
130 |     seen_dicts = []
131 |     for date, senti_list in data.items():
132 |         for entry in senti_list:
133 |             if entry not in seen_dicts:
134 |                 result_str += f"### Filing Date: {entry['filingDate']}, {entry['name']}:\nChange:{entry['change']}\nShares: {entry['share']}\nTransaction Price: {entry['transactionPrice']}\nTransaction Code: {entry['transactionCode']}\n\n"
135 |                 seen_dicts.append(entry)
136 | 
137 |     return (
138 |         f"## {ticker} insider transactions from {before} to {curr_date}:\n"
139 |         + result_str
140 |         + "The change field reflects the variation in share count—here a negative number indicates a reduction in holdings—while share specifies the total number of shares involved. The transactionPrice denotes the per-share price at which the trade was executed, and transactionDate marks when the transaction occurred. The name field identifies the insider making the trade, and transactionCode (e.g., S for sale) clarifies the nature of the transaction. FilingDate records when the transaction was officially reported, and the unique id links to the specific SEC filing, as indicated by the source. Additionally, the symbol ties the transaction to a particular company, isDerivative flags whether the trade involves derivative securities, and currency notes the currency context of the transaction."
141 |     )
142 | 
143 | 
144 | def get_simfin_balance_sheet(
145 |     ticker: Annotated[str, "ticker symbol"],
146 |     freq: Annotated[
147 |         str,
148 |         "reporting frequency of the company's financial history: annual / quarterly",
149 |     ],
150 |     curr_date: Annotated[str, "current date you are trading at, yyyy-mm-dd"],
151 | ):
152 |     data_path = os.path.join(
153 |         DATA_DIR,
154 |         "fundamental_data",
155 |         "simfin_data_all",
156 |         "balance_sheet",
157 |         "companies",
158 |         "us",
159 |         f"us-balance-{freq}.csv",
160 |     )
161 |     df = pd.read_csv(data_path, sep=";")
162 | 
163 |     # Convert date strings to datetime objects and remove any time components
164 |     df["Report Date"] = pd.to_datetime(df["Report Date"], utc=True).dt.normalize()
165 |     df["Publish Date"] = pd.to_datetime(df["Publish Date"], utc=True).dt.normalize()
166 | 
167 |     # Convert the current date to datetime and normalize
168 |     curr_date_dt = pd.to_datetime(curr_date, utc=True).normalize()
169 | 
170 |     # Filter the DataFrame for the given ticker and for reports that were published on or before the current date
171 |     filtered_df = df[(df["Ticker"] == ticker) & (df["Publish Date"] <= curr_date_dt)]
172 | 
173 |     # Check if there are any available reports; if not, return a notification
174 |     if filtered_df.empty:
175 |         print("No balance sheet available before the given current date.")
176 |         return ""
177 | 
178 |     # Get the most recent balance sheet by selecting the row with the latest Publish Date
179 |     latest_balance_sheet = filtered_df.loc[filtered_df["Publish Date"].idxmax()]
180 | 
181 |     # drop the SimFinID column
182 |     latest_balance_sheet = latest_balance_sheet.drop("SimFinId")
183 | 
184 |     return (
185 |         f"## {freq} balance sheet for {ticker} released on {str(latest_balance_sheet['Publish Date'])[0:10]}: \n"
186 |         + str(latest_balance_sheet)
187 |         + "\n\nThis includes metadata like reporting dates and currency, share details, and a breakdown of assets, liabilities, and equity. Assets are grouped as current (liquid items like cash and receivables) and noncurrent (long-term investments and property). Liabilities are split between short-term obligations and long-term debts, while equity reflects shareholder funds such as paid-in capital and retained earnings. Together, these components ensure that total assets equal the sum of liabilities and equity."
188 |     )
189 | 
190 | 
191 | def get_simfin_cashflow(
192 |     ticker: Annotated[str, "ticker symbol"],
193 |     freq: Annotated[
194 |         str,
195 |         "reporting frequency of the company's financial history: annual / quarterly",
196 |     ],
197 |     curr_date: Annotated[str, "current date you are trading at, yyyy-mm-dd"],
198 | ):
199 |     data_path = os.path.join(
200 |         DATA_DIR,
201 |         "fundamental_data",
202 |         "simfin_data_all",
203 |         "cash_flow",
204 |         "companies",
205 |         "us",
206 |         f"us-cashflow-{freq}.csv",
207 |     )
208 |     df = pd.read_csv(data_path, sep=";")
209 | 
210 |     # Convert date strings to datetime objects and remove any time components
211 |     df["Report Date"] = pd.to_datetime(df["Report Date"], utc=True).dt.normalize()
212 |     df["Publish Date"] = pd.to_datetime(df["Publish Date"], utc=True).dt.normalize()
213 | 
214 |     # Convert the current date to datetime and normalize
215 |     curr_date_dt = pd.to_datetime(curr_date, utc=True).normalize()
216 | 
217 |     # Filter the DataFrame for the given ticker and for reports that were published on or before the current date
218 |     filtered_df = df[(df["Ticker"] == ticker) & (df["Publish Date"] <= curr_date_dt)]
219 | 
220 |     # Check if there are any available reports; if not, return a notification
221 |     if filtered_df.empty:
222 |         print("No cash flow statement available before the given current date.")
223 |         return ""
224 | 
225 |     # Get the most recent cash flow statement by selecting the row with the latest Publish Date
226 |     latest_cash_flow = filtered_df.loc[filtered_df["Publish Date"].idxmax()]
227 | 
228 |     # drop the SimFinID column
229 |     latest_cash_flow = latest_cash_flow.drop("SimFinId")
230 | 
231 |     return (
232 |         f"## {freq} cash flow statement for {ticker} released on {str(latest_cash_flow['Publish Date'])[0:10]}: \n"
233 |         + str(latest_cash_flow)
234 |         + "\n\nThis includes metadata like reporting dates and currency, share details, and a breakdown of cash movements. Operating activities show cash generated from core business operations, including net income adjustments for non-cash items and working capital changes. Investing activities cover asset acquisitions/disposals and investments. Financing activities include debt transactions, equity issuances/repurchases, and dividend payments. The net change in cash represents the overall increase or decrease in the company's cash position during the reporting period."
235 |     )
236 | 
237 | 
238 | def get_simfin_income_statements(
239 |     ticker: Annotated[str, "ticker symbol"],
240 |     freq: Annotated[
241 |         str,
242 |         "reporting frequency of the company's financial history: annual / quarterly",
243 |     ],
244 |     curr_date: Annotated[str, "current date you are trading at, yyyy-mm-dd"],
245 | ):
246 |     data_path = os.path.join(
247 |         DATA_DIR,
248 |         "fundamental_data",
249 |         "simfin_data_all",
250 |         "income_statements",
251 |         "companies",
252 |         "us",
253 |         f"us-income-{freq}.csv",
254 |     )
255 |     df = pd.read_csv(data_path, sep=";")
256 | 
257 |     # Convert date strings to datetime objects and remove any time components
258 |     df["Report Date"] = pd.to_datetime(df["Report Date"], utc=True).dt.normalize()
259 |     df["Publish Date"] = pd.to_datetime(df["Publish Date"], utc=True).dt.normalize()
260 | 
261 |     # Convert the current date to datetime and normalize
262 |     curr_date_dt = pd.to_datetime(curr_date, utc=True).normalize()
263 | 
264 |     # Filter the DataFrame for the given ticker and for reports that were published on or before the current date
265 |     filtered_df = df[(df["Ticker"] == ticker) & (df["Publish Date"] <= curr_date_dt)]
266 | 
267 |     # Check if there are any available reports; if not, return a notification
268 |     if filtered_df.empty:
269 |         print("No income statement available before the given current date.")
270 |         return ""
271 | 
272 |     # Get the most recent income statement by selecting the row with the latest Publish Date
273 |     latest_income = filtered_df.loc[filtered_df["Publish Date"].idxmax()]
274 | 
275 |     # drop the SimFinID column
276 |     latest_income = latest_income.drop("SimFinId")
277 | 
278 |     return (
279 |         f"## {freq} income statement for {ticker} released on {str(latest_income['Publish Date'])[0:10]}: \n"
280 |         + str(latest_income)
281 |         + "\n\nThis includes metadata like reporting dates and currency, share details, and a comprehensive breakdown of the company's financial performance. Starting with Revenue, it shows Cost of Revenue and resulting Gross Profit. Operating Expenses are detailed, including SG&A, R&D, and Depreciation. The statement then shows Operating Income, followed by non-operating items and Interest Expense, leading to Pretax Income. After accounting for Income Tax and any Extraordinary items, it concludes with Net Income, representing the company's bottom-line profit or loss for the period."
282 |     )
283 | 
284 | 
285 | def get_google_news(
286 |     query: Annotated[str, "Query to search with"],
287 |     curr_date: Annotated[str, "Curr date in yyyy-mm-dd format"],
288 |     look_back_days: Annotated[int, "how many days to look back"],
289 | ) -> str:
290 |     query = query.replace(" ", "+")
291 | 
292 |     start_date = datetime.strptime(curr_date, "%Y-%m-%d")
293 |     before = start_date - relativedelta(days=look_back_days)
294 |     before = before.strftime("%Y-%m-%d")
295 | 
296 |     news_results = getNewsData(query, before, curr_date)
297 | 
298 |     news_str = ""
299 | 
300 |     for news in news_results:
301 |         news_str += (
302 |             f"### {news['title']} (source: {news['source']}) \n\n{news['snippet']}\n\n"
303 |         )
304 | 
305 |     if len(news_results) == 0:
306 |         return ""
307 | 
308 |     return f"## {query} Google News, from {before} to {curr_date}:\n\n{news_str}"
309 | 
310 | 
311 | def get_reddit_global_news(
312 |     start_date: Annotated[str, "Start date in yyyy-mm-dd format"],
313 |     look_back_days: Annotated[int, "how many days to look back"],
314 |     max_limit_per_day: Annotated[int, "Maximum number of news per day"],
315 | ) -> str:
316 |     """
317 |     Retrieve the latest top reddit news
318 |     Args:
319 |         start_date: Start date in yyyy-mm-dd format
320 |         end_date: End date in yyyy-mm-dd format
321 |     Returns:
322 |         str: A formatted dataframe containing the latest news articles posts on reddit and meta information in these columns: "created_utc", "id", "title", "selftext", "score", "num_comments", "url"
323 |     """
324 | 
325 |     start_date = datetime.strptime(start_date, "%Y-%m-%d")
326 |     before = start_date - relativedelta(days=look_back_days)
327 |     before = before.strftime("%Y-%m-%d")
328 | 
329 |     posts = []
330 |     # iterate from start_date to end_date
331 |     curr_date = datetime.strptime(before, "%Y-%m-%d")
332 | 
333 |     total_iterations = (start_date - curr_date).days + 1
334 |     pbar = tqdm(desc=f"Getting Global News on {start_date}", total=total_iterations)
335 | 
336 |     while curr_date <= start_date:
337 |         curr_date_str = curr_date.strftime("%Y-%m-%d")
338 |         fetch_result = fetch_top_from_category(
339 |             "global_news",
340 |             curr_date_str,
341 |             max_limit_per_day,
342 |             data_path=os.path.join(DATA_DIR, "reddit_data"),
343 |         )
344 |         posts.extend(fetch_result)
345 |         curr_date += relativedelta(days=1)
346 |         pbar.update(1)
347 | 
348 |     pbar.close()
349 | 
350 |     if len(posts) == 0:
351 |         return ""
352 | 
353 |     news_str = ""
354 |     for post in posts:
355 |         if post["content"] == "":
356 |             news_str += f"### {post['title']}\n\n"
357 |         else:
358 |             news_str += f"### {post['title']}\n\n{post['content']}\n\n"
359 | 
360 |     return f"## Global News Reddit, from {before} to {curr_date}:\n{news_str}"
361 | 
362 | 
363 | def get_reddit_company_news(
364 |     ticker: Annotated[str, "ticker symbol of the company"],
365 |     start_date: Annotated[str, "Start date in yyyy-mm-dd format"],
366 |     look_back_days: Annotated[int, "how many days to look back"],
367 |     max_limit_per_day: Annotated[int, "Maximum number of news per day"],
368 | ) -> str:
369 |     """
370 |     Retrieve the latest top reddit news
371 |     Args:
372 |         ticker: ticker symbol of the company
373 |         start_date: Start date in yyyy-mm-dd format
374 |         end_date: End date in yyyy-mm-dd format
375 |     Returns:
376 |         str: A formatted dataframe containing the latest news articles posts on reddit and meta information in these columns: "created_utc", "id", "title", "selftext", "score", "num_comments", "url"
377 |     """
378 | 
379 |     start_date = datetime.strptime(start_date, "%Y-%m-%d")
380 |     before = start_date - relativedelta(days=look_back_days)
381 |     before = before.strftime("%Y-%m-%d")
382 | 
383 |     posts = []
384 |     # iterate from start_date to end_date
385 |     curr_date = datetime.strptime(before, "%Y-%m-%d")
386 | 
387 |     total_iterations = (start_date - curr_date).days + 1
388 |     pbar = tqdm(
389 |         desc=f"Getting Company News for {ticker} on {start_date}",
390 |         total=total_iterations,
391 |     )
392 | 
393 |     while curr_date <= start_date:
394 |         curr_date_str = curr_date.strftime("%Y-%m-%d")
395 |         fetch_result = fetch_top_from_category(
396 |             "company_news",
397 |             curr_date_str,
398 |             max_limit_per_day,
399 |             ticker,
400 |             data_path=os.path.join(DATA_DIR, "reddit_data"),
401 |         )
402 |         posts.extend(fetch_result)
403 |         curr_date += relativedelta(days=1)
404 | 
405 |         pbar.update(1)
406 | 
407 |     pbar.close()
408 | 
409 |     if len(posts) == 0:
410 |         return ""
411 | 
412 |     news_str = ""
413 |     for post in posts:
414 |         if post["content"] == "":
415 |             news_str += f"### {post['title']}\n\n"
416 |         else:
417 |             news_str += f"### {post['title']}\n\n{post['content']}\n\n"
418 | 
419 |     return f"##{ticker} News Reddit, from {before} to {curr_date}:\n\n{news_str}"
420 | 
421 | 
422 | def get_stock_stats_indicators_window(
423 |     symbol: Annotated[str, "ticker symbol of the company"],
424 |     indicator: Annotated[str, "technical indicator to get the analysis and report of"],
425 |     curr_date: Annotated[
426 |         str, "The current trading date you are trading on, YYYY-mm-dd"
427 |     ],
428 |     look_back_days: Annotated[int, "how many days to look back"],
429 |     online: Annotated[bool, "to fetch data online or offline"],
430 | ) -> str:
431 | 
432 |     best_ind_params = {
433 |         # Moving Averages
434 |         "close_50_sma": (
435 |             "50 SMA: A medium-term trend indicator. "
436 |             "Usage: Identify trend direction and serve as dynamic support/resistance. "
437 |             "Tips: It lags price; combine with faster indicators for timely signals."
438 |         ),
439 |         "close_200_sma": (
440 |             "200 SMA: A long-term trend benchmark. "
441 |             "Usage: Confirm overall market trend and identify golden/death cross setups. "
442 |             "Tips: It reacts slowly; best for strategic trend confirmation rather than frequent trading entries."
443 |         ),
444 |         "close_10_ema": (
445 |             "10 EMA: A responsive short-term average. "
446 |             "Usage: Capture quick shifts in momentum and potential entry points. "
447 |             "Tips: Prone to noise in choppy markets; use alongside longer averages for filtering false signals."
448 |         ),
449 |         # MACD Related
450 |         "macd": (
451 |             "MACD: Computes momentum via differences of EMAs. "
452 |             "Usage: Look for crossovers and divergence as signals of trend changes. "
453 |             "Tips: Confirm with other indicators in low-volatility or sideways markets."
454 |         ),
455 |         "macds": (
456 |             "MACD Signal: An EMA smoothing of the MACD line. "
457 |             "Usage: Use crossovers with the MACD line to trigger trades. "
458 |             "Tips: Should be part of a broader strategy to avoid false positives."
459 |         ),
460 |         "macdh": (
461 |             "MACD Histogram: Shows the gap between the MACD line and its signal. "
462 |             "Usage: Visualize momentum strength and spot divergence early. "
463 |             "Tips: Can be volatile; complement with additional filters in fast-moving markets."
464 |         ),
465 |         # Momentum Indicators
466 |         "rsi": (
467 |             "RSI: Measures momentum to flag overbought/oversold conditions. "
468 |             "Usage: Apply 70/30 thresholds and watch for divergence to signal reversals. "
469 |             "Tips: In strong trends, RSI may remain extreme; always cross-check with trend analysis."
470 |         ),
471 |         # Volatility Indicators
472 |         "boll": (
473 |             "Bollinger Middle: A 20 SMA serving as the basis for Bollinger Bands. "
474 |             "Usage: Acts as a dynamic benchmark for price movement. "
475 |             "Tips: Combine with the upper and lower bands to effectively spot breakouts or reversals."
476 |         ),
477 |         "boll_ub": (
478 |             "Bollinger Upper Band: Typically 2 standard deviations above the middle line. "
479 |             "Usage: Signals potential overbought conditions and breakout zones. "
480 |             "Tips: Confirm signals with other tools; prices may ride the band in strong trends."
481 |         ),
482 |         "boll_lb": (
483 |             "Bollinger Lower Band: Typically 2 standard deviations below the middle line. "
484 |             "Usage: Indicates potential oversold conditions. "
485 |             "Tips: Use additional analysis to avoid false reversal signals."
486 |         ),
487 |         "atr": (
488 |             "ATR: Averages true range to measure volatility. "
489 |             "Usage: Set stop-loss levels and adjust position sizes based on current market volatility. "
490 |             "Tips: It's a reactive measure, so use it as part of a broader risk management strategy."
491 |         ),
492 |         # Volume-Based Indicators
493 |         "vwma": (
494 |             "VWMA: A moving average weighted by volume. "
495 |             "Usage: Confirm trends by integrating price action with volume data. "
496 |             "Tips: Watch for skewed results from volume spikes; use in combination with other volume analyses."
497 |         ),
498 |         "mfi": (
499 |             "MFI: The Money Flow Index is a momentum indicator that uses both price and volume to measure buying and selling pressure. "
500 |             "Usage: Identify overbought (>80) or oversold (<20) conditions and confirm the strength of trends or reversals. "
501 |             "Tips: Use alongside RSI or MACD to confirm signals; divergence between price and MFI can indicate potential reversals."
502 |         ),
503 |     }
504 | 
505 |     if indicator not in best_ind_params:
506 |         raise ValueError(
507 |             f"Indicator {indicator} is not supported. Please choose from: {list(best_ind_params.keys())}"
508 |         )
509 | 
510 |     end_date = curr_date
511 |     curr_date = datetime.strptime(curr_date, "%Y-%m-%d")
512 |     before = curr_date - relativedelta(days=look_back_days)
513 | 
514 |     if not online:
515 |         # read from YFin data
516 |         data = pd.read_csv(
517 |             os.path.join(
518 |                 DATA_DIR,
519 |                 f"market_data/price_data/{symbol}-YFin-data-2015-01-01-2025-03-25.csv",
520 |             )
521 |         )
522 |         data["Date"] = pd.to_datetime(data["Date"], utc=True)
523 |         dates_in_df = data["Date"].astype(str).str[:10]
524 | 
525 |         ind_string = ""
526 |         while curr_date >= before:
527 |             # only do the trading dates
528 |             if curr_date.strftime("%Y-%m-%d") in dates_in_df.values:
529 |                 indicator_value = get_stockstats_indicator(
530 |                     symbol, indicator, curr_date.strftime("%Y-%m-%d"), online
531 |                 )
532 | 
533 |                 ind_string += f"{curr_date.strftime('%Y-%m-%d')}: {indicator_value}\n"
534 | 
535 |             curr_date = curr_date - relativedelta(days=1)
536 |     else:
537 |         # online gathering
538 |         ind_string = ""
539 |         while curr_date >= before:
540 |             indicator_value = get_stockstats_indicator(
541 |                 symbol, indicator, curr_date.strftime("%Y-%m-%d"), online
542 |             )
543 | 
544 |             ind_string += f"{curr_date.strftime('%Y-%m-%d')}: {indicator_value}\n"
545 | 
546 |             curr_date = curr_date - relativedelta(days=1)
547 | 
548 |     result_str = (
549 |         f"## {indicator} values from {before.strftime('%Y-%m-%d')} to {end_date}:\n\n"
550 |         + ind_string
551 |         + "\n\n"
552 |         + best_ind_params.get(indicator, "No description available.")
553 |     )
554 | 
555 |     return result_str
556 | 
557 | 
558 | def get_stockstats_indicator(
559 |     symbol: Annotated[str, "ticker symbol of the company"],
560 |     indicator: Annotated[str, "technical indicator to get the analysis and report of"],
561 |     curr_date: Annotated[
562 |         str, "The current trading date you are trading on, YYYY-mm-dd"
563 |     ],
564 |     online: Annotated[bool, "to fetch data online or offline"],
565 | ) -> str:
566 | 
567 |     curr_date = datetime.strptime(curr_date, "%Y-%m-%d")
568 |     curr_date = curr_date.strftime("%Y-%m-%d")
569 | 
570 |     try:
571 |         indicator_value = StockstatsUtils.get_stock_stats(
572 |             symbol,
573 |             indicator,
574 |             curr_date,
575 |             os.path.join(DATA_DIR, "market_data", "price_data"),
576 |             online=online,
577 |         )
578 |     except Exception as e:
579 |         print(
580 |             f"Error getting stockstats indicator data for indicator {indicator} on {curr_date}: {e}"
581 |         )
582 |         return ""
583 | 
584 |     return str(indicator_value)
585 | 
586 | 
587 | def get_YFin_data_window(
588 |     symbol: Annotated[str, "ticker symbol of the company"],
589 |     curr_date: Annotated[str, "Start date in yyyy-mm-dd format"],
590 |     look_back_days: Annotated[int, "how many days to look back"],
591 | ) -> str:
592 |     # calculate past days
593 |     date_obj = datetime.strptime(curr_date, "%Y-%m-%d")
594 |     before = date_obj - relativedelta(days=look_back_days)
595 |     start_date = before.strftime("%Y-%m-%d")
596 | 
597 |     # read in data
598 |     data = pd.read_csv(
599 |         os.path.join(
600 |             DATA_DIR,
601 |             f"market_data/price_data/{symbol}-YFin-data-2015-01-01-2025-03-25.csv",
602 |         )
603 |     )
604 | 
605 |     # Extract just the date part for comparison
606 |     data["DateOnly"] = data["Date"].str[:10]
607 | 
608 |     # Filter data between the start and end dates (inclusive)
609 |     filtered_data = data[
610 |         (data["DateOnly"] >= start_date) & (data["DateOnly"] <= curr_date)
611 |     ]
612 | 
613 |     # Drop the temporary column we created
614 |     filtered_data = filtered_data.drop("DateOnly", axis=1)
615 | 
616 |     # Set pandas display options to show the full DataFrame
617 |     with pd.option_context(
618 |         "display.max_rows", None, "display.max_columns", None, "display.width", None
619 |     ):
620 |         df_string = filtered_data.to_string()
621 | 
622 |     return (
623 |         f"## Raw Market Data for {symbol} from {start_date} to {curr_date}:\n\n"
624 |         + df_string
625 |     )
626 | 
627 | 
628 | def get_YFin_data_online(
629 |     symbol: Annotated[str, "ticker symbol of the company"],
630 |     start_date: Annotated[str, "Start date in yyyy-mm-dd format"],
631 |     end_date: Annotated[str, "End date in yyyy-mm-dd format"],
632 | ):
633 | 
634 |     datetime.strptime(start_date, "%Y-%m-%d")
635 |     datetime.strptime(end_date, "%Y-%m-%d")
636 | 
637 |     # Create ticker object
638 |     ticker = yf.Ticker(symbol.upper())
639 | 
640 |     # Fetch historical data for the specified date range
641 |     data = ticker.history(start=start_date, end=end_date)
642 | 
643 |     # Check if data is empty
644 |     if data.empty:
645 |         return (
646 |             f"No data found for symbol '{symbol}' between {start_date} and {end_date}"
647 |         )
648 | 
649 |     # Remove timezone info from index for cleaner output
650 |     if data.index.tz is not None:
651 |         data.index = data.index.tz_localize(None)
652 | 
653 |     # Round numerical values to 2 decimal places for cleaner display
654 |     numeric_columns = ["Open", "High", "Low", "Close", "Adj Close"]
655 |     for col in numeric_columns:
656 |         if col in data.columns:
657 |             data[col] = data[col].round(2)
658 | 
659 |     # Convert DataFrame to CSV string
660 |     csv_string = data.to_csv()
661 | 
662 |     # Add header information
663 |     header = f"# Stock data for {symbol.upper()} from {start_date} to {end_date}\n"
664 |     header += f"# Total records: {len(data)}\n"
665 |     header += f"# Data retrieved on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n"
666 | 
667 |     return header + csv_string
668 | 
669 | 
670 | def get_YFin_data(
671 |     symbol: Annotated[str, "ticker symbol of the company"],
672 |     start_date: Annotated[str, "Start date in yyyy-mm-dd format"],
673 |     end_date: Annotated[str, "End date in yyyy-mm-dd format"],
674 | ) -> str:
675 |     # read in data
676 |     data = pd.read_csv(
677 |         os.path.join(
678 |             DATA_DIR,
679 |             f"market_data/price_data/{symbol}-YFin-data-2015-01-01-2025-03-25.csv",
680 |         )
681 |     )
682 | 
683 |     if end_date > "2025-03-25":
684 |         raise Exception(
685 |             f"Get_YFin_Data: {end_date} is outside of the data range of 2015-01-01 to 2025-03-25"
686 |         )
687 | 
688 |     # Extract just the date part for comparison
689 |     data["DateOnly"] = data["Date"].str[:10]
690 | 
691 |     # Filter data between the start and end dates (inclusive)
692 |     filtered_data = data[
693 |         (data["DateOnly"] >= start_date) & (data["DateOnly"] <= end_date)
694 |     ]
695 | 
696 |     # Drop the temporary column we created
697 |     filtered_data = filtered_data.drop("DateOnly", axis=1)
698 | 
699 |     # remove the index from the dataframe
700 |     filtered_data = filtered_data.reset_index(drop=True)
701 | 
702 |     return filtered_data
703 | 
704 | 
705 | def get_stock_news_openai(ticker, curr_date):
706 |     config = get_config()
707 |     client = OpenAI(base_url=config["backend_url"])
708 | 
709 |     response = client.responses.create(
710 |         model=config["quick_think_llm"],
711 |         input=[
712 |             {
713 |                 "role": "system",
714 |                 "content": [
715 |                     {
716 |                         "type": "input_text",
717 |                         "text": f"Can you search Social Media for {ticker} from 7 days before {curr_date} to {curr_date}? Make sure you only get the data posted during that period.",
718 |                     }
719 |                 ],
720 |             }
721 |         ],
722 |         text={"format": {"type": "text"}},
723 |         reasoning={},
724 |         tools=[
725 |             {
726 |                 "type": "web_search_preview",
727 |                 "user_location": {"type": "approximate"},
728 |                 "search_context_size": "low",
729 |             }
730 |         ],
731 |         temperature=1,
732 |         max_output_tokens=4096,
733 |         top_p=1,
734 |         store=True,
735 |     )
736 | 
737 |     return response.output[1].content[0].text
738 | 
739 | 
740 | def get_global_news_openai(curr_date):
741 |     config = get_config()
742 |     client = OpenAI(base_url=config["backend_url"])
743 | 
744 |     response = client.responses.create(
745 |         model=config["quick_think_llm"],
746 |         input=[
747 |             {
748 |                 "role": "system",
749 |                 "content": [
750 |                     {
751 |                         "type": "input_text",
752 |                         "text": f"Can you search global or macroeconomics news from 7 days before {curr_date} to {curr_date} that would be informative for trading purposes? Make sure you only get the data posted during that period.",
753 |                     }
754 |                 ],
755 |             }
756 |         ],
757 |         text={"format": {"type": "text"}},
758 |         reasoning={},
759 |         tools=[
760 |             {
761 |                 "type": "web_search_preview",
762 |                 "user_location": {"type": "approximate"},
763 |                 "search_context_size": "low",
764 |             }
765 |         ],
766 |         temperature=1,
767 |         max_output_tokens=4096,
768 |         top_p=1,
769 |         store=True,
770 |     )
771 | 
772 |     return response.output[1].content[0].text
773 | 
774 | 
775 | def get_fundamentals_openai(ticker, curr_date):
776 |     config = get_config()
777 |     client = OpenAI(base_url=config["backend_url"])
778 | 
779 |     response = client.responses.create(
780 |         model=config["quick_think_llm"],
781 |         input=[
782 |             {
783 |                 "role": "system",
784 |                 "content": [
785 |                     {
786 |                         "type": "input_text",
787 |                         "text": f"Can you search Fundamental for discussions on {ticker} during of the month before {curr_date} to the month of {curr_date}. Make sure you only get the data posted during that period. List as a table, with PE/PS/Cash flow/ etc",
788 |                     }
789 |                 ],
790 |             }
791 |         ],
792 |         text={"format": {"type": "text"}},
793 |         reasoning={},
794 |         tools=[
795 |             {
796 |                 "type": "web_search_preview",
797 |                 "user_location": {"type": "approximate"},
798 |                 "search_context_size": "low",
799 |             }
800 |         ],
801 |         temperature=1,
802 |         max_output_tokens=4096,
803 |         top_p=1,
804 |         store=True,
805 |     )
806 | 
807 |     return response.output[1].content[0].text
808 | 


--------------------------------------------------------------------------------
/tradingagents/dataflows/reddit_utils.py:
--------------------------------------------------------------------------------
  1 | import requests
  2 | import time
  3 | import json
  4 | from datetime import datetime, timedelta
  5 | from contextlib import contextmanager
  6 | from typing import Annotated
  7 | import os
  8 | import re
  9 | 
 10 | ticker_to_company = {
 11 |     "AAPL": "Apple",
 12 |     "MSFT": "Microsoft",
 13 |     "GOOGL": "Google",
 14 |     "AMZN": "Amazon",
 15 |     "TSLA": "Tesla",
 16 |     "NVDA": "Nvidia",
 17 |     "TSM": "Taiwan Semiconductor Manufacturing Company OR TSMC",
 18 |     "JPM": "JPMorgan Chase OR JP Morgan",
 19 |     "JNJ": "Johnson & Johnson OR JNJ",
 20 |     "V": "Visa",
 21 |     "WMT": "Walmart",
 22 |     "META": "Meta OR Facebook",
 23 |     "AMD": "AMD",
 24 |     "INTC": "Intel",
 25 |     "QCOM": "Qualcomm",
 26 |     "BABA": "Alibaba",
 27 |     "ADBE": "Adobe",
 28 |     "NFLX": "Netflix",
 29 |     "CRM": "Salesforce",
 30 |     "PYPL": "PayPal",
 31 |     "PLTR": "Palantir",
 32 |     "MU": "Micron",
 33 |     "SQ": "Block OR Square",
 34 |     "ZM": "Zoom",
 35 |     "CSCO": "Cisco",
 36 |     "SHOP": "Shopify",
 37 |     "ORCL": "Oracle",
 38 |     "X": "Twitter OR X",
 39 |     "SPOT": "Spotify",
 40 |     "AVGO": "Broadcom",
 41 |     "ASML": "ASML ",
 42 |     "TWLO": "Twilio",
 43 |     "SNAP": "Snap Inc.",
 44 |     "TEAM": "Atlassian",
 45 |     "SQSP": "Squarespace",
 46 |     "UBER": "Uber",
 47 |     "ROKU": "Roku",
 48 |     "PINS": "Pinterest",
 49 | }
 50 | 
 51 | 
 52 | def fetch_top_from_category(
 53 |     category: Annotated[
 54 |         str, "Category to fetch top post from. Collection of subreddits."
 55 |     ],
 56 |     date: Annotated[str, "Date to fetch top posts from."],
 57 |     max_limit: Annotated[int, "Maximum number of posts to fetch."],
 58 |     query: Annotated[str, "Optional query to search for in the subreddit."] = None,
 59 |     data_path: Annotated[
 60 |         str,
 61 |         "Path to the data folder. Default is 'reddit_data'.",
 62 |     ] = "reddit_data",
 63 | ):
 64 |     base_path = data_path
 65 | 
 66 |     all_content = []
 67 | 
 68 |     if max_limit < len(os.listdir(os.path.join(base_path, category))):
 69 |         raise ValueError(
 70 |             "REDDIT FETCHING ERROR: max limit is less than the number of files in the category. Will not be able to fetch any posts"
 71 |         )
 72 | 
 73 |     limit_per_subreddit = max_limit // len(
 74 |         os.listdir(os.path.join(base_path, category))
 75 |     )
 76 | 
 77 |     for data_file in os.listdir(os.path.join(base_path, category)):
 78 |         # check if data_file is a .jsonl file
 79 |         if not data_file.endswith(".jsonl"):
 80 |             continue
 81 | 
 82 |         all_content_curr_subreddit = []
 83 | 
 84 |         with open(os.path.join(base_path, category, data_file), "rb") as f:
 85 |             for i, line in enumerate(f):
 86 |                 # skip empty lines
 87 |                 if not line.strip():
 88 |                     continue
 89 | 
 90 |                 parsed_line = json.loads(line)
 91 | 
 92 |                 # select only lines that are from the date
 93 |                 post_date = datetime.utcfromtimestamp(
 94 |                     parsed_line["created_utc"]
 95 |                 ).strftime("%Y-%m-%d")
 96 |                 if post_date != date:
 97 |                     continue
 98 | 
 99 |                 # if is company_news, check that the title or the content has the company's name (query) mentioned
100 |                 if "company" in category and query:
101 |                     search_terms = []
102 |                     if "OR" in ticker_to_company[query]:
103 |                         search_terms = ticker_to_company[query].split(" OR ")
104 |                     else:
105 |                         search_terms = [ticker_to_company[query]]
106 | 
107 |                     search_terms.append(query)
108 | 
109 |                     found = False
110 |                     for term in search_terms:
111 |                         if re.search(
112 |                             term, parsed_line["title"], re.IGNORECASE
113 |                         ) or re.search(term, parsed_line["selftext"], re.IGNORECASE):
114 |                             found = True
115 |                             break
116 | 
117 |                     if not found:
118 |                         continue
119 | 
120 |                 post = {
121 |                     "title": parsed_line["title"],
122 |                     "content": parsed_line["selftext"],
123 |                     "url": parsed_line["url"],
124 |                     "upvotes": parsed_line["ups"],
125 |                     "posted_date": post_date,
126 |                 }
127 | 
128 |                 all_content_curr_subreddit.append(post)
129 | 
130 |         # sort all_content_curr_subreddit by upvote_ratio in descending order
131 |         all_content_curr_subreddit.sort(key=lambda x: x["upvotes"], reverse=True)
132 | 
133 |         all_content.extend(all_content_curr_subreddit[:limit_per_subreddit])
134 | 
135 |     return all_content
136 | 


--------------------------------------------------------------------------------
/tradingagents/dataflows/stockstats_utils.py:
--------------------------------------------------------------------------------
 1 | import pandas as pd
 2 | import yfinance as yf
 3 | from stockstats import wrap
 4 | from typing import Annotated
 5 | import os
 6 | from .config import get_config
 7 | 
 8 | 
 9 | class StockstatsUtils:
10 |     @staticmethod
11 |     def get_stock_stats(
12 |         symbol: Annotated[str, "ticker symbol for the company"],
13 |         indicator: Annotated[
14 |             str, "quantitative indicators based off of the stock data for the company"
15 |         ],
16 |         curr_date: Annotated[
17 |             str, "curr date for retrieving stock price data, YYYY-mm-dd"
18 |         ],
19 |         data_dir: Annotated[
20 |             str,
21 |             "directory where the stock data is stored.",
22 |         ],
23 |         online: Annotated[
24 |             bool,
25 |             "whether to use online tools to fetch data or offline tools. If True, will use online tools.",
26 |         ] = False,
27 |     ):
28 |         df = None
29 |         data = None
30 | 
31 |         if not online:
32 |             try:
33 |                 data = pd.read_csv(
34 |                     os.path.join(
35 |                         data_dir,
36 |                         f"{symbol}-YFin-data-2015-01-01-2025-03-25.csv",
37 |                     )
38 |                 )
39 |                 df = wrap(data)
40 |             except FileNotFoundError:
41 |                 raise Exception("Stockstats fail: Yahoo Finance data not fetched yet!")
42 |         else:
43 |             # Get today's date as YYYY-mm-dd to add to cache
44 |             today_date = pd.Timestamp.today()
45 |             curr_date = pd.to_datetime(curr_date)
46 | 
47 |             end_date = today_date
48 |             start_date = today_date - pd.DateOffset(years=15)
49 |             start_date = start_date.strftime("%Y-%m-%d")
50 |             end_date = end_date.strftime("%Y-%m-%d")
51 | 
52 |             # Get config and ensure cache directory exists
53 |             config = get_config()
54 |             os.makedirs(config["data_cache_dir"], exist_ok=True)
55 | 
56 |             data_file = os.path.join(
57 |                 config["data_cache_dir"],
58 |                 f"{symbol}-YFin-data-{start_date}-{end_date}.csv",
59 |             )
60 | 
61 |             if os.path.exists(data_file):
62 |                 data = pd.read_csv(data_file)
63 |                 data["Date"] = pd.to_datetime(data["Date"])
64 |             else:
65 |                 data = yf.download(
66 |                     symbol,
67 |                     start=start_date,
68 |                     end=end_date,
69 |                     multi_level_index=False,
70 |                     progress=False,
71 |                     auto_adjust=True,
72 |                 )
73 |                 data = data.reset_index()
74 |                 data.to_csv(data_file, index=False)
75 | 
76 |             df = wrap(data)
77 |             df["Date"] = df["Date"].dt.strftime("%Y-%m-%d")
78 |             curr_date = curr_date.strftime("%Y-%m-%d")
79 | 
80 |         df[indicator]  # trigger stockstats to calculate the indicator
81 |         matching_rows = df[df["Date"].str.startswith(curr_date)]
82 | 
83 |         if not matching_rows.empty:
84 |             indicator_value = matching_rows[indicator].values[0]
85 |             return indicator_value
86 |         else:
87 |             return "N/A: Not a trading day (weekend or holiday)"
88 | 


--------------------------------------------------------------------------------
/tradingagents/dataflows/utils.py:
--------------------------------------------------------------------------------
 1 | import os
 2 | import json
 3 | import pandas as pd
 4 | from datetime import date, timedelta, datetime
 5 | from typing import Annotated
 6 | 
 7 | SavePathType = Annotated[str, "File path to save data. If None, data is not saved."]
 8 | 
 9 | def save_output(data: pd.DataFrame, tag: str, save_path: SavePathType = None) -> None:
10 |     if save_path:
11 |         data.to_csv(save_path)
12 |         print(f"{tag} saved to {save_path}")
13 | 
14 | 
15 | def get_current_date():
16 |     return date.today().strftime("%Y-%m-%d")
17 | 
18 | 
19 | def decorate_all_methods(decorator):
20 |     def class_decorator(cls):
21 |         for attr_name, attr_value in cls.__dict__.items():
22 |             if callable(attr_value):
23 |                 setattr(cls, attr_name, decorator(attr_value))
24 |         return cls
25 | 
26 |     return class_decorator
27 | 
28 | 
29 | def get_next_weekday(date):
30 | 
31 |     if not isinstance(date, datetime):
32 |         date = datetime.strptime(date, "%Y-%m-%d")
33 | 
34 |     if date.weekday() >= 5:
35 |         days_to_add = 7 - date.weekday()
36 |         next_weekday = date + timedelta(days=days_to_add)
37 |         return next_weekday
38 |     else:
39 |         return date
40 | 


--------------------------------------------------------------------------------
/tradingagents/dataflows/yfin_utils.py:
--------------------------------------------------------------------------------
  1 | # gets data/stats
  2 | 
  3 | import yfinance as yf
  4 | from typing import Annotated, Callable, Any, Optional
  5 | from pandas import DataFrame
  6 | import pandas as pd
  7 | from functools import wraps
  8 | 
  9 | from .utils import save_output, SavePathType, decorate_all_methods
 10 | 
 11 | 
 12 | def init_ticker(func: Callable) -> Callable:
 13 |     """Decorator to initialize yf.Ticker and pass it to the function."""
 14 | 
 15 |     @wraps(func)
 16 |     def wrapper(symbol: Annotated[str, "ticker symbol"], *args, **kwargs) -> Any:
 17 |         ticker = yf.Ticker(symbol)
 18 |         return func(ticker, *args, **kwargs)
 19 | 
 20 |     return wrapper
 21 | 
 22 | 
 23 | @decorate_all_methods(init_ticker)
 24 | class YFinanceUtils:
 25 | 
 26 |     def get_stock_data(
 27 |         symbol: Annotated[str, "ticker symbol"],
 28 |         start_date: Annotated[
 29 |             str, "start date for retrieving stock price data, YYYY-mm-dd"
 30 |         ],
 31 |         end_date: Annotated[
 32 |             str, "end date for retrieving stock price data, YYYY-mm-dd"
 33 |         ],
 34 |         save_path: SavePathType = None,
 35 |     ) -> DataFrame:
 36 |         """retrieve stock price data for designated ticker symbol"""
 37 |         ticker = symbol
 38 |         # add one day to the end_date so that the data range is inclusive
 39 |         end_date = pd.to_datetime(end_date) + pd.DateOffset(days=1)
 40 |         end_date = end_date.strftime("%Y-%m-%d")
 41 |         stock_data = ticker.history(start=start_date, end=end_date)
 42 |         # save_output(stock_data, f"Stock data for {ticker.ticker}", save_path)
 43 |         return stock_data
 44 | 
 45 |     def get_stock_info(
 46 |         symbol: Annotated[str, "ticker symbol"],
 47 |     ) -> dict:
 48 |         """Fetches and returns latest stock information."""
 49 |         ticker = symbol
 50 |         stock_info = ticker.info
 51 |         return stock_info
 52 | 
 53 |     def get_company_info(
 54 |         symbol: Annotated[str, "ticker symbol"],
 55 |         save_path: Optional[str] = None,
 56 |     ) -> DataFrame:
 57 |         """Fetches and returns company information as a DataFrame."""
 58 |         ticker = symbol
 59 |         info = ticker.info
 60 |         company_info = {
 61 |             "Company Name": info.get("shortName", "N/A"),
 62 |             "Industry": info.get("industry", "N/A"),
 63 |             "Sector": info.get("sector", "N/A"),
 64 |             "Country": info.get("country", "N/A"),
 65 |             "Website": info.get("website", "N/A"),
 66 |         }
 67 |         company_info_df = DataFrame([company_info])
 68 |         if save_path:
 69 |             company_info_df.to_csv(save_path)
 70 |             print(f"Company info for {ticker.ticker} saved to {save_path}")
 71 |         return company_info_df
 72 | 
 73 |     def get_stock_dividends(
 74 |         symbol: Annotated[str, "ticker symbol"],
 75 |         save_path: Optional[str] = None,
 76 |     ) -> DataFrame:
 77 |         """Fetches and returns the latest dividends data as a DataFrame."""
 78 |         ticker = symbol
 79 |         dividends = ticker.dividends
 80 |         if save_path:
 81 |             dividends.to_csv(save_path)
 82 |             print(f"Dividends for {ticker.ticker} saved to {save_path}")
 83 |         return dividends
 84 | 
 85 |     def get_income_stmt(symbol: Annotated[str, "ticker symbol"]) -> DataFrame:
 86 |         """Fetches and returns the latest income statement of the company as a DataFrame."""
 87 |         ticker = symbol
 88 |         income_stmt = ticker.financials
 89 |         return income_stmt
 90 | 
 91 |     def get_balance_sheet(symbol: Annotated[str, "ticker symbol"]) -> DataFrame:
 92 |         """Fetches and returns the latest balance sheet of the company as a DataFrame."""
 93 |         ticker = symbol
 94 |         balance_sheet = ticker.balance_sheet
 95 |         return balance_sheet
 96 | 
 97 |     def get_cash_flow(symbol: Annotated[str, "ticker symbol"]) -> DataFrame:
 98 |         """Fetches and returns the latest cash flow statement of the company as a DataFrame."""
 99 |         ticker = symbol
100 |         cash_flow = ticker.cashflow
101 |         return cash_flow
102 | 
103 |     def get_analyst_recommendations(symbol: Annotated[str, "ticker symbol"]) -> tuple:
104 |         """Fetches the latest analyst recommendations and returns the most common recommendation and its count."""
105 |         ticker = symbol
106 |         recommendations = ticker.recommendations
107 |         if recommendations.empty:
108 |             return None, 0  # No recommendations available
109 | 
110 |         # Assuming 'period' column exists and needs to be excluded
111 |         row_0 = recommendations.iloc[0, 1:]  # Exclude 'period' column if necessary
112 | 
113 |         # Find the maximum voting result
114 |         max_votes = row_0.max()
115 |         majority_voting_result = row_0[row_0 == max_votes].index.tolist()
116 | 
117 |         return majority_voting_result[0], max_votes
118 | 


--------------------------------------------------------------------------------
/tradingagents/default_config.py:
--------------------------------------------------------------------------------
 1 | import os
 2 | 
 3 | DEFAULT_CONFIG = {
 4 |     "project_dir": os.path.abspath(os.path.join(os.path.dirname(__file__), ".")),
 5 |     "results_dir": os.getenv("TRADINGAGENTS_RESULTS_DIR", "./results"),
 6 |     "data_dir": "/Users/yluo/Documents/Code/ScAI/FR1-data",
 7 |     "data_cache_dir": os.path.join(
 8 |         os.path.abspath(os.path.join(os.path.dirname(__file__), ".")),
 9 |         "dataflows/data_cache",
10 |     ),
11 |     # LLM settings
12 |     "llm_provider": "openai",
13 |     "deep_think_llm": "o4-mini",
14 |     "quick_think_llm": "gpt-4o-mini",
15 |     "backend_url": "https://api.openai.com/v1",
16 |     # Debate and discussion settings
17 |     "max_debate_rounds": 1,
18 |     "max_risk_discuss_rounds": 1,
19 |     "max_recur_limit": 100,
20 |     # Tool settings
21 |     "online_tools": True,
22 | }
23 | 


--------------------------------------------------------------------------------
/tradingagents/graph/__init__.py:
--------------------------------------------------------------------------------
 1 | # TradingAgents/graph/__init__.py
 2 | 
 3 | from .trading_graph import TradingAgentsGraph
 4 | from .conditional_logic import ConditionalLogic
 5 | from .setup import GraphSetup
 6 | from .propagation import Propagator
 7 | from .reflection import Reflector
 8 | from .signal_processing import SignalProcessor
 9 | 
10 | __all__ = [
11 |     "TradingAgentsGraph",
12 |     "ConditionalLogic",
13 |     "GraphSetup",
14 |     "Propagator",
15 |     "Reflector",
16 |     "SignalProcessor",
17 | ]
18 | 


--------------------------------------------------------------------------------
/tradingagents/graph/conditional_logic.py:
--------------------------------------------------------------------------------
 1 | # TradingAgents/graph/conditional_logic.py
 2 | 
 3 | from tradingagents.agents.utils.agent_states import AgentState
 4 | 
 5 | 
 6 | class ConditionalLogic:
 7 |     """Handles conditional logic for determining graph flow."""
 8 | 
 9 |     def __init__(self, max_debate_rounds=1, max_risk_discuss_rounds=1):
10 |         """Initialize with configuration parameters."""
11 |         self.max_debate_rounds = max_debate_rounds
12 |         self.max_risk_discuss_rounds = max_risk_discuss_rounds
13 | 
14 |     def should_continue_market(self, state: AgentState):
15 |         """Determine if market analysis should continue."""
16 |         messages = state["messages"]
17 |         last_message = messages[-1]
18 |         if last_message.tool_calls:
19 |             return "tools_market"
20 |         return "Msg Clear Market"
21 | 
22 |     def should_continue_social(self, state: AgentState):
23 |         """Determine if social media analysis should continue."""
24 |         messages = state["messages"]
25 |         last_message = messages[-1]
26 |         if last_message.tool_calls:
27 |             return "tools_social"
28 |         return "Msg Clear Social"
29 | 
30 |     def should_continue_news(self, state: AgentState):
31 |         """Determine if news analysis should continue."""
32 |         messages = state["messages"]
33 |         last_message = messages[-1]
34 |         if last_message.tool_calls:
35 |             return "tools_news"
36 |         return "Msg Clear News"
37 | 
38 |     def should_continue_fundamentals(self, state: AgentState):
39 |         """Determine if fundamentals analysis should continue."""
40 |         messages = state["messages"]
41 |         last_message = messages[-1]
42 |         if last_message.tool_calls:
43 |             return "tools_fundamentals"
44 |         return "Msg Clear Fundamentals"
45 | 
46 |     def should_continue_debate(self, state: AgentState) -> str:
47 |         """Determine if debate should continue."""
48 | 
49 |         if (
50 |             state["investment_debate_state"]["count"] >= 2 * self.max_debate_rounds
51 |         ):  # 3 rounds of back-and-forth between 2 agents
52 |             return "Research Manager"
53 |         if state["investment_debate_state"]["current_response"].startswith("Bull"):
54 |             return "Bear Researcher"
55 |         return "Bull Researcher"
56 | 
57 |     def should_continue_risk_analysis(self, state: AgentState) -> str:
58 |         """Determine if risk analysis should continue."""
59 |         if (
60 |             state["risk_debate_state"]["count"] >= 3 * self.max_risk_discuss_rounds
61 |         ):  # 3 rounds of back-and-forth between 3 agents
62 |             return "Risk Judge"
63 |         if state["risk_debate_state"]["latest_speaker"].startswith("Risky"):
64 |             return "Safe Analyst"
65 |         if state["risk_debate_state"]["latest_speaker"].startswith("Safe"):
66 |             return "Neutral Analyst"
67 |         return "Risky Analyst"
68 | 


--------------------------------------------------------------------------------
/tradingagents/graph/propagation.py:
--------------------------------------------------------------------------------
 1 | # TradingAgents/graph/propagation.py
 2 | 
 3 | from typing import Dict, Any
 4 | from tradingagents.agents.utils.agent_states import (
 5 |     AgentState,
 6 |     InvestDebateState,
 7 |     RiskDebateState,
 8 | )
 9 | 
10 | 
11 | class Propagator:
12 |     """Handles state initialization and propagation through the graph."""
13 | 
14 |     def __init__(self, max_recur_limit=100):
15 |         """Initialize with configuration parameters."""
16 |         self.max_recur_limit = max_recur_limit
17 | 
18 |     def create_initial_state(
19 |         self, company_name: str, trade_date: str
20 |     ) -> Dict[str, Any]:
21 |         """Create the initial state for the agent graph."""
22 |         return {
23 |             "messages": [("human", company_name)],
24 |             "company_of_interest": company_name,
25 |             "trade_date": str(trade_date),
26 |             "investment_debate_state": InvestDebateState(
27 |                 {"history": "", "current_response": "", "count": 0}
28 |             ),
29 |             "risk_debate_state": RiskDebateState(
30 |                 {
31 |                     "history": "",
32 |                     "current_risky_response": "",
33 |                     "current_safe_response": "",
34 |                     "current_neutral_response": "",
35 |                     "count": 0,
36 |                 }
37 |             ),
38 |             "market_report": "",
39 |             "fundamentals_report": "",
40 |             "sentiment_report": "",
41 |             "news_report": "",
42 |         }
43 | 
44 |     def get_graph_args(self) -> Dict[str, Any]:
45 |         """Get arguments for the graph invocation."""
46 |         return {
47 |             "stream_mode": "values",
48 |             "config": {"recursion_limit": self.max_recur_limit},
49 |         }
50 | 


--------------------------------------------------------------------------------
/tradingagents/graph/reflection.py:
--------------------------------------------------------------------------------
  1 | # TradingAgents/graph/reflection.py
  2 | 
  3 | from typing import Dict, Any
  4 | from langchain_openai import ChatOpenAI
  5 | 
  6 | 
  7 | class Reflector:
  8 |     """Handles reflection on decisions and updating memory."""
  9 | 
 10 |     def __init__(self, quick_thinking_llm: ChatOpenAI):
 11 |         """Initialize the reflector with an LLM."""
 12 |         self.quick_thinking_llm = quick_thinking_llm
 13 |         self.reflection_system_prompt = self._get_reflection_prompt()
 14 | 
 15 |     def _get_reflection_prompt(self) -> str:
 16 |         """Get the system prompt for reflection."""
 17 |         return """
 18 | You are an expert financial analyst tasked with reviewing trading decisions/analysis and providing a comprehensive, step-by-step analysis. 
 19 | Your goal is to deliver detailed insights into investment decisions and highlight opportunities for improvement, adhering strictly to the following guidelines:
 20 | 
 21 | 1. Reasoning:
 22 |    - 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.
 23 |    - Analyze the contributing factors to each success or mistake. Consider:
 24 |      - Market intelligence.
 25 |      - Technical indicators.
 26 |      - Technical signals.
 27 |      - Price movement analysis.
 28 |      - Overall market data analysis 
 29 |      - News analysis.
 30 |      - Social media and sentiment analysis.
 31 |      - Fundamental data analysis.
 32 |      - Weight the importance of each factor in the decision-making process.
 33 | 
 34 | 2. Improvement:
 35 |    - For any incorrect decisions, propose revisions to maximize returns.
 36 |    - 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).
 37 | 
 38 | 3. Summary:
 39 |    - Summarize the lessons learned from the successes and mistakes.
 40 |    - Highlight how these lessons can be adapted for future trading scenarios and draw connections between similar situations to apply the knowledge gained.
 41 | 
 42 | 4. Query:
 43 |    - Extract key insights from the summary into a concise sentence of no more than 1000 tokens.
 44 |    - Ensure the condensed sentence captures the essence of the lessons and reasoning for easy reference.
 45 | 
 46 | Adhere 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.
 47 | """
 48 | 
 49 |     def _extract_current_situation(self, current_state: Dict[str, Any]) -> str:
 50 |         """Extract the current market situation from the state."""
 51 |         curr_market_report = current_state["market_report"]
 52 |         curr_sentiment_report = current_state["sentiment_report"]
 53 |         curr_news_report = current_state["news_report"]
 54 |         curr_fundamentals_report = current_state["fundamentals_report"]
 55 | 
 56 |         return f"{curr_market_report}\n\n{curr_sentiment_report}\n\n{curr_news_report}\n\n{curr_fundamentals_report}"
 57 | 
 58 |     def _reflect_on_component(
 59 |         self, component_type: str, report: str, situation: str, returns_losses
 60 |     ) -> str:
 61 |         """Generate reflection for a component."""
 62 |         messages = [
 63 |             ("system", self.reflection_system_prompt),
 64 |             (
 65 |                 "human",
 66 |                 f"Returns: {returns_losses}\n\nAnalysis/Decision: {report}\n\nObjective Market Reports for Reference: {situation}",
 67 |             ),
 68 |         ]
 69 | 
 70 |         result = self.quick_thinking_llm.invoke(messages).content
 71 |         return result
 72 | 
 73 |     def reflect_bull_researcher(self, current_state, returns_losses, bull_memory):
 74 |         """Reflect on bull researcher's analysis and update memory."""
 75 |         situation = self._extract_current_situation(current_state)
 76 |         bull_debate_history = current_state["investment_debate_state"]["bull_history"]
 77 | 
 78 |         result = self._reflect_on_component(
 79 |             "BULL", bull_debate_history, situation, returns_losses
 80 |         )
 81 |         bull_memory.add_situations([(situation, result)])
 82 | 
 83 |     def reflect_bear_researcher(self, current_state, returns_losses, bear_memory):
 84 |         """Reflect on bear researcher's analysis and update memory."""
 85 |         situation = self._extract_current_situation(current_state)
 86 |         bear_debate_history = current_state["investment_debate_state"]["bear_history"]
 87 | 
 88 |         result = self._reflect_on_component(
 89 |             "BEAR", bear_debate_history, situation, returns_losses
 90 |         )
 91 |         bear_memory.add_situations([(situation, result)])
 92 | 
 93 |     def reflect_trader(self, current_state, returns_losses, trader_memory):
 94 |         """Reflect on trader's decision and update memory."""
 95 |         situation = self._extract_current_situation(current_state)
 96 |         trader_decision = current_state["trader_investment_plan"]
 97 | 
 98 |         result = self._reflect_on_component(
 99 |             "TRADER", trader_decision, situation, returns_losses
100 |         )
101 |         trader_memory.add_situations([(situation, result)])
102 | 
103 |     def reflect_invest_judge(self, current_state, returns_losses, invest_judge_memory):
104 |         """Reflect on investment judge's decision and update memory."""
105 |         situation = self._extract_current_situation(current_state)
106 |         judge_decision = current_state["investment_debate_state"]["judge_decision"]
107 | 
108 |         result = self._reflect_on_component(
109 |             "INVEST JUDGE", judge_decision, situation, returns_losses
110 |         )
111 |         invest_judge_memory.add_situations([(situation, result)])
112 | 
113 |     def reflect_risk_manager(self, current_state, returns_losses, risk_manager_memory):
114 |         """Reflect on risk manager's decision and update memory."""
115 |         situation = self._extract_current_situation(current_state)
116 |         judge_decision = current_state["risk_debate_state"]["judge_decision"]
117 | 
118 |         result = self._reflect_on_component(
119 |             "RISK JUDGE", judge_decision, situation, returns_losses
120 |         )
121 |         risk_manager_memory.add_situations([(situation, result)])
122 | 


--------------------------------------------------------------------------------
/tradingagents/graph/setup.py:
--------------------------------------------------------------------------------
  1 | # TradingAgents/graph/setup.py
  2 | 
  3 | from typing import Dict, Any
  4 | from langchain_openai import ChatOpenAI
  5 | from langgraph.graph import END, StateGraph, START
  6 | from langgraph.prebuilt import ToolNode
  7 | 
  8 | from tradingagents.agents import *
  9 | from tradingagents.agents.utils.agent_states import AgentState
 10 | from tradingagents.agents.utils.agent_utils import Toolkit
 11 | 
 12 | from .conditional_logic import ConditionalLogic
 13 | 
 14 | 
 15 | class GraphSetup:
 16 |     """Handles the setup and configuration of the agent graph."""
 17 | 
 18 |     def __init__(
 19 |         self,
 20 |         quick_thinking_llm: ChatOpenAI,
 21 |         deep_thinking_llm: ChatOpenAI,
 22 |         toolkit: Toolkit,
 23 |         tool_nodes: Dict[str, ToolNode],
 24 |         bull_memory,
 25 |         bear_memory,
 26 |         trader_memory,
 27 |         invest_judge_memory,
 28 |         risk_manager_memory,
 29 |         conditional_logic: ConditionalLogic,
 30 |     ):
 31 |         """Initialize with required components."""
 32 |         self.quick_thinking_llm = quick_thinking_llm
 33 |         self.deep_thinking_llm = deep_thinking_llm
 34 |         self.toolkit = toolkit
 35 |         self.tool_nodes = tool_nodes
 36 |         self.bull_memory = bull_memory
 37 |         self.bear_memory = bear_memory
 38 |         self.trader_memory = trader_memory
 39 |         self.invest_judge_memory = invest_judge_memory
 40 |         self.risk_manager_memory = risk_manager_memory
 41 |         self.conditional_logic = conditional_logic
 42 | 
 43 |     def setup_graph(
 44 |         self, selected_analysts=["market", "social", "news", "fundamentals"]
 45 |     ):
 46 |         """Set up and compile the agent workflow graph.
 47 | 
 48 |         Args:
 49 |             selected_analysts (list): List of analyst types to include. Options are:
 50 |                 - "market": Market analyst
 51 |                 - "social": Social media analyst
 52 |                 - "news": News analyst
 53 |                 - "fundamentals": Fundamentals analyst
 54 |         """
 55 |         if len(selected_analysts) == 0:
 56 |             raise ValueError("Trading Agents Graph Setup Error: no analysts selected!")
 57 | 
 58 |         # Create analyst nodes
 59 |         analyst_nodes = {}
 60 |         delete_nodes = {}
 61 |         tool_nodes = {}
 62 | 
 63 |         if "market" in selected_analysts:
 64 |             analyst_nodes["market"] = create_market_analyst(
 65 |                 self.quick_thinking_llm, self.toolkit
 66 |             )
 67 |             delete_nodes["market"] = create_msg_delete()
 68 |             tool_nodes["market"] = self.tool_nodes["market"]
 69 | 
 70 |         if "social" in selected_analysts:
 71 |             analyst_nodes["social"] = create_social_media_analyst(
 72 |                 self.quick_thinking_llm, self.toolkit
 73 |             )
 74 |             delete_nodes["social"] = create_msg_delete()
 75 |             tool_nodes["social"] = self.tool_nodes["social"]
 76 | 
 77 |         if "news" in selected_analysts:
 78 |             analyst_nodes["news"] = create_news_analyst(
 79 |                 self.quick_thinking_llm, self.toolkit
 80 |             )
 81 |             delete_nodes["news"] = create_msg_delete()
 82 |             tool_nodes["news"] = self.tool_nodes["news"]
 83 | 
 84 |         if "fundamentals" in selected_analysts:
 85 |             analyst_nodes["fundamentals"] = create_fundamentals_analyst(
 86 |                 self.quick_thinking_llm, self.toolkit
 87 |             )
 88 |             delete_nodes["fundamentals"] = create_msg_delete()
 89 |             tool_nodes["fundamentals"] = self.tool_nodes["fundamentals"]
 90 | 
 91 |         # Create researcher and manager nodes
 92 |         bull_researcher_node = create_bull_researcher(
 93 |             self.quick_thinking_llm, self.bull_memory
 94 |         )
 95 |         bear_researcher_node = create_bear_researcher(
 96 |             self.quick_thinking_llm, self.bear_memory
 97 |         )
 98 |         research_manager_node = create_research_manager(
 99 |             self.deep_thinking_llm, self.invest_judge_memory
100 |         )
101 |         trader_node = create_trader(self.quick_thinking_llm, self.trader_memory)
102 | 
103 |         # Create risk analysis nodes
104 |         risky_analyst = create_risky_debator(self.quick_thinking_llm)
105 |         neutral_analyst = create_neutral_debator(self.quick_thinking_llm)
106 |         safe_analyst = create_safe_debator(self.quick_thinking_llm)
107 |         risk_manager_node = create_risk_manager(
108 |             self.deep_thinking_llm, self.risk_manager_memory
109 |         )
110 | 
111 |         # Create workflow
112 |         workflow = StateGraph(AgentState)
113 | 
114 |         # Add analyst nodes to the graph
115 |         for analyst_type, node in analyst_nodes.items():
116 |             workflow.add_node(f"{analyst_type.capitalize()} Analyst", node)
117 |             workflow.add_node(
118 |                 f"Msg Clear {analyst_type.capitalize()}", delete_nodes[analyst_type]
119 |             )
120 |             workflow.add_node(f"tools_{analyst_type}", tool_nodes[analyst_type])
121 | 
122 |         # Add other nodes
123 |         workflow.add_node("Bull Researcher", bull_researcher_node)
124 |         workflow.add_node("Bear Researcher", bear_researcher_node)
125 |         workflow.add_node("Research Manager", research_manager_node)
126 |         workflow.add_node("Trader", trader_node)
127 |         workflow.add_node("Risky Analyst", risky_analyst)
128 |         workflow.add_node("Neutral Analyst", neutral_analyst)
129 |         workflow.add_node("Safe Analyst", safe_analyst)
130 |         workflow.add_node("Risk Judge", risk_manager_node)
131 | 
132 |         # Define edges
133 |         # Start with the first analyst
134 |         first_analyst = selected_analysts[0]
135 |         workflow.add_edge(START, f"{first_analyst.capitalize()} Analyst")
136 | 
137 |         # Connect analysts in sequence
138 |         for i, analyst_type in enumerate(selected_analysts):
139 |             current_analyst = f"{analyst_type.capitalize()} Analyst"
140 |             current_tools = f"tools_{analyst_type}"
141 |             current_clear = f"Msg Clear {analyst_type.capitalize()}"
142 | 
143 |             # Add conditional edges for current analyst
144 |             workflow.add_conditional_edges(
145 |                 current_analyst,
146 |                 getattr(self.conditional_logic, f"should_continue_{analyst_type}"),
147 |                 [current_tools, current_clear],
148 |             )
149 |             workflow.add_edge(current_tools, current_analyst)
150 | 
151 |             # Connect to next analyst or to Bull Researcher if this is the last analyst
152 |             if i < len(selected_analysts) - 1:
153 |                 next_analyst = f"{selected_analysts[i+1].capitalize()} Analyst"
154 |                 workflow.add_edge(current_clear, next_analyst)
155 |             else:
156 |                 workflow.add_edge(current_clear, "Bull Researcher")
157 | 
158 |         # Add remaining edges
159 |         workflow.add_conditional_edges(
160 |             "Bull Researcher",
161 |             self.conditional_logic.should_continue_debate,
162 |             {
163 |                 "Bear Researcher": "Bear Researcher",
164 |                 "Research Manager": "Research Manager",
165 |             },
166 |         )
167 |         workflow.add_conditional_edges(
168 |             "Bear Researcher",
169 |             self.conditional_logic.should_continue_debate,
170 |             {
171 |                 "Bull Researcher": "Bull Researcher",
172 |                 "Research Manager": "Research Manager",
173 |             },
174 |         )
175 |         workflow.add_edge("Research Manager", "Trader")
176 |         workflow.add_edge("Trader", "Risky Analyst")
177 |         workflow.add_conditional_edges(
178 |             "Risky Analyst",
179 |             self.conditional_logic.should_continue_risk_analysis,
180 |             {
181 |                 "Safe Analyst": "Safe Analyst",
182 |                 "Risk Judge": "Risk Judge",
183 |             },
184 |         )
185 |         workflow.add_conditional_edges(
186 |             "Safe Analyst",
187 |             self.conditional_logic.should_continue_risk_analysis,
188 |             {
189 |                 "Neutral Analyst": "Neutral Analyst",
190 |                 "Risk Judge": "Risk Judge",
191 |             },
192 |         )
193 |         workflow.add_conditional_edges(
194 |             "Neutral Analyst",
195 |             self.conditional_logic.should_continue_risk_analysis,
196 |             {
197 |                 "Risky Analyst": "Risky Analyst",
198 |                 "Risk Judge": "Risk Judge",
199 |             },
200 |         )
201 | 
202 |         workflow.add_edge("Risk Judge", END)
203 | 
204 |         # Compile and return
205 |         return workflow.compile()
206 | 


--------------------------------------------------------------------------------
/tradingagents/graph/signal_processing.py:
--------------------------------------------------------------------------------
 1 | # TradingAgents/graph/signal_processing.py
 2 | 
 3 | from langchain_openai import ChatOpenAI
 4 | 
 5 | 
 6 | class SignalProcessor:
 7 |     """Processes trading signals to extract actionable decisions."""
 8 | 
 9 |     def __init__(self, quick_thinking_llm: ChatOpenAI):
10 |         """Initialize with an LLM for processing."""
11 |         self.quick_thinking_llm = quick_thinking_llm
12 | 
13 |     def process_signal(self, full_signal: str) -> str:
14 |         """
15 |         Process a full trading signal to extract the core decision.
16 | 
17 |         Args:
18 |             full_signal: Complete trading signal text
19 | 
20 |         Returns:
21 |             Extracted decision (BUY, SELL, or HOLD)
22 |         """
23 |         messages = [
24 |             (
25 |                 "system",
26 |                 "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.",
27 |             ),
28 |             ("human", full_signal),
29 |         ]
30 | 
31 |         return self.quick_thinking_llm.invoke(messages).content
32 | 


--------------------------------------------------------------------------------
/tradingagents/graph/trading_graph.py:
--------------------------------------------------------------------------------
  1 | # TradingAgents/graph/trading_graph.py
  2 | 
  3 | import os
  4 | from pathlib import Path
  5 | import json
  6 | from datetime import date
  7 | from typing import Dict, Any, Tuple, List, Optional
  8 | 
  9 | from langchain_openai import ChatOpenAI
 10 | from langchain_anthropic import ChatAnthropic
 11 | from langchain_google_genai import ChatGoogleGenerativeAI
 12 | 
 13 | from langgraph.prebuilt import ToolNode
 14 | 
 15 | from tradingagents.agents import *
 16 | from tradingagents.default_config import DEFAULT_CONFIG
 17 | from tradingagents.agents.utils.memory import FinancialSituationMemory
 18 | from tradingagents.agents.utils.agent_states import (
 19 |     AgentState,
 20 |     InvestDebateState,
 21 |     RiskDebateState,
 22 | )
 23 | from tradingagents.dataflows.interface import set_config
 24 | 
 25 | from .conditional_logic import ConditionalLogic
 26 | from .setup import GraphSetup
 27 | from .propagation import Propagator
 28 | from .reflection import Reflector
 29 | from .signal_processing import SignalProcessor
 30 | 
 31 | 
 32 | class TradingAgentsGraph:
 33 |     """Main class that orchestrates the trading agents framework."""
 34 | 
 35 |     def __init__(
 36 |         self,
 37 |         selected_analysts=["market", "social", "news", "fundamentals"],
 38 |         debug=False,
 39 |         config: Dict[str, Any] = None,
 40 |     ):
 41 |         """Initialize the trading agents graph and components.
 42 | 
 43 |         Args:
 44 |             selected_analysts: List of analyst types to include
 45 |             debug: Whether to run in debug mode
 46 |             config: Configuration dictionary. If None, uses default config
 47 |         """
 48 |         self.debug = debug
 49 |         self.config = config or DEFAULT_CONFIG
 50 | 
 51 |         # Update the interface's config
 52 |         set_config(self.config)
 53 | 
 54 |         # Create necessary directories
 55 |         os.makedirs(
 56 |             os.path.join(self.config["project_dir"], "dataflows/data_cache"),
 57 |             exist_ok=True,
 58 |         )
 59 | 
 60 |         # Initialize LLMs
 61 |         if self.config["llm_provider"].lower() == "openai" or self.config["llm_provider"] == "ollama" or self.config["llm_provider"] == "openrouter":
 62 |             self.deep_thinking_llm = ChatOpenAI(model=self.config["deep_think_llm"], base_url=self.config["backend_url"])
 63 |             self.quick_thinking_llm = ChatOpenAI(model=self.config["quick_think_llm"], base_url=self.config["backend_url"])
 64 |         elif self.config["llm_provider"].lower() == "anthropic":
 65 |             self.deep_thinking_llm = ChatAnthropic(model=self.config["deep_think_llm"], base_url=self.config["backend_url"])
 66 |             self.quick_thinking_llm = ChatAnthropic(model=self.config["quick_think_llm"], base_url=self.config["backend_url"])
 67 |         elif self.config["llm_provider"].lower() == "google":
 68 |             self.deep_thinking_llm = ChatGoogleGenerativeAI(model=self.config["deep_think_llm"])
 69 |             self.quick_thinking_llm = ChatGoogleGenerativeAI(model=self.config["quick_think_llm"])
 70 |         else:
 71 |             raise ValueError(f"Unsupported LLM provider: {self.config['llm_provider']}")
 72 |         
 73 |         self.toolkit = Toolkit(config=self.config)
 74 | 
 75 |         # Initialize memories
 76 |         self.bull_memory = FinancialSituationMemory("bull_memory", self.config)
 77 |         self.bear_memory = FinancialSituationMemory("bear_memory", self.config)
 78 |         self.trader_memory = FinancialSituationMemory("trader_memory", self.config)
 79 |         self.invest_judge_memory = FinancialSituationMemory("invest_judge_memory", self.config)
 80 |         self.risk_manager_memory = FinancialSituationMemory("risk_manager_memory", self.config)
 81 | 
 82 |         # Create tool nodes
 83 |         self.tool_nodes = self._create_tool_nodes()
 84 | 
 85 |         # Initialize components
 86 |         self.conditional_logic = ConditionalLogic()
 87 |         self.graph_setup = GraphSetup(
 88 |             self.quick_thinking_llm,
 89 |             self.deep_thinking_llm,
 90 |             self.toolkit,
 91 |             self.tool_nodes,
 92 |             self.bull_memory,
 93 |             self.bear_memory,
 94 |             self.trader_memory,
 95 |             self.invest_judge_memory,
 96 |             self.risk_manager_memory,
 97 |             self.conditional_logic,
 98 |         )
 99 | 
100 |         self.propagator = Propagator()
101 |         self.reflector = Reflector(self.quick_thinking_llm)
102 |         self.signal_processor = SignalProcessor(self.quick_thinking_llm)
103 | 
104 |         # State tracking
105 |         self.curr_state = None
106 |         self.ticker = None
107 |         self.log_states_dict = {}  # date to full state dict
108 | 
109 |         # Set up the graph
110 |         self.graph = self.graph_setup.setup_graph(selected_analysts)
111 | 
112 |     def _create_tool_nodes(self) -> Dict[str, ToolNode]:
113 |         """Create tool nodes for different data sources."""
114 |         return {
115 |             "market": ToolNode(
116 |                 [
117 |                     # online tools
118 |                     self.toolkit.get_YFin_data_online,
119 |                     self.toolkit.get_stockstats_indicators_report_online,
120 |                     # offline tools
121 |                     self.toolkit.get_YFin_data,
122 |                     self.toolkit.get_stockstats_indicators_report,
123 |                 ]
124 |             ),
125 |             "social": ToolNode(
126 |                 [
127 |                     # online tools
128 |                     self.toolkit.get_stock_news_openai,
129 |                     # offline tools
130 |                     self.toolkit.get_reddit_stock_info,
131 |                 ]
132 |             ),
133 |             "news": ToolNode(
134 |                 [
135 |                     # online tools
136 |                     self.toolkit.get_global_news_openai,
137 |                     self.toolkit.get_google_news,
138 |                     # offline tools
139 |                     self.toolkit.get_finnhub_news,
140 |                     self.toolkit.get_reddit_news,
141 |                 ]
142 |             ),
143 |             "fundamentals": ToolNode(
144 |                 [
145 |                     # online tools
146 |                     self.toolkit.get_fundamentals_openai,
147 |                     # offline tools
148 |                     self.toolkit.get_finnhub_company_insider_sentiment,
149 |                     self.toolkit.get_finnhub_company_insider_transactions,
150 |                     self.toolkit.get_simfin_balance_sheet,
151 |                     self.toolkit.get_simfin_cashflow,
152 |                     self.toolkit.get_simfin_income_stmt,
153 |                 ]
154 |             ),
155 |         }
156 | 
157 |     def propagate(self, company_name, trade_date):
158 |         """Run the trading agents graph for a company on a specific date."""
159 | 
160 |         self.ticker = company_name
161 | 
162 |         # Initialize state
163 |         init_agent_state = self.propagator.create_initial_state(
164 |             company_name, trade_date
165 |         )
166 |         args = self.propagator.get_graph_args()
167 | 
168 |         if self.debug:
169 |             # Debug mode with tracing
170 |             trace = []
171 |             for chunk in self.graph.stream(init_agent_state, **args):
172 |                 if len(chunk["messages"]) == 0:
173 |                     pass
174 |                 else:
175 |                     chunk["messages"][-1].pretty_print()
176 |                     trace.append(chunk)
177 | 
178 |             final_state = trace[-1]
179 |         else:
180 |             # Standard mode without tracing
181 |             final_state = self.graph.invoke(init_agent_state, **args)
182 | 
183 |         # Store current state for reflection
184 |         self.curr_state = final_state
185 | 
186 |         # Log state
187 |         self._log_state(trade_date, final_state)
188 | 
189 |         # Return decision and processed signal
190 |         return final_state, self.process_signal(final_state["final_trade_decision"])
191 | 
192 |     def _log_state(self, trade_date, final_state):
193 |         """Log the final state to a JSON file."""
194 |         self.log_states_dict[str(trade_date)] = {
195 |             "company_of_interest": final_state["company_of_interest"],
196 |             "trade_date": final_state["trade_date"],
197 |             "market_report": final_state["market_report"],
198 |             "sentiment_report": final_state["sentiment_report"],
199 |             "news_report": final_state["news_report"],
200 |             "fundamentals_report": final_state["fundamentals_report"],
201 |             "investment_debate_state": {
202 |                 "bull_history": final_state["investment_debate_state"]["bull_history"],
203 |                 "bear_history": final_state["investment_debate_state"]["bear_history"],
204 |                 "history": final_state["investment_debate_state"]["history"],
205 |                 "current_response": final_state["investment_debate_state"][
206 |                     "current_response"
207 |                 ],
208 |                 "judge_decision": final_state["investment_debate_state"][
209 |                     "judge_decision"
210 |                 ],
211 |             },
212 |             "trader_investment_decision": final_state["trader_investment_plan"],
213 |             "risk_debate_state": {
214 |                 "risky_history": final_state["risk_debate_state"]["risky_history"],
215 |                 "safe_history": final_state["risk_debate_state"]["safe_history"],
216 |                 "neutral_history": final_state["risk_debate_state"]["neutral_history"],
217 |                 "history": final_state["risk_debate_state"]["history"],
218 |                 "judge_decision": final_state["risk_debate_state"]["judge_decision"],
219 |             },
220 |             "investment_plan": final_state["investment_plan"],
221 |             "final_trade_decision": final_state["final_trade_decision"],
222 |         }
223 | 
224 |         # Save to file
225 |         directory = Path(f"eval_results/{self.ticker}/TradingAgentsStrategy_logs/")
226 |         directory.mkdir(parents=True, exist_ok=True)
227 | 
228 |         with open(
229 |             f"eval_results/{self.ticker}/TradingAgentsStrategy_logs/full_states_log_{trade_date}.json",
230 |             "w",
231 |         ) as f:
232 |             json.dump(self.log_states_dict, f, indent=4)
233 | 
234 |     def reflect_and_remember(self, returns_losses):
235 |         """Reflect on decisions and update memory based on returns."""
236 |         self.reflector.reflect_bull_researcher(
237 |             self.curr_state, returns_losses, self.bull_memory
238 |         )
239 |         self.reflector.reflect_bear_researcher(
240 |             self.curr_state, returns_losses, self.bear_memory
241 |         )
242 |         self.reflector.reflect_trader(
243 |             self.curr_state, returns_losses, self.trader_memory
244 |         )
245 |         self.reflector.reflect_invest_judge(
246 |             self.curr_state, returns_losses, self.invest_judge_memory
247 |         )
248 |         self.reflector.reflect_risk_manager(
249 |             self.curr_state, returns_losses, self.risk_manager_memory
250 |         )
251 | 
252 |     def process_signal(self, full_signal):
253 |         """Process a signal to extract the core decision."""
254 |         return self.signal_processor.process_signal(full_signal)
255 | 


--------------------------------------------------------------------------------