mirror of
https://github.com/TauricResearch/TradingAgents.git
synced 2026-11-20 08:09:56 +02:00
+6
-2
@@ -22,6 +22,10 @@ NVIDIA_API_KEY=
|
||||
# FRED (Federal Reserve macro data). Free key: https://fred.stlouisfed.org/docs/api/api_key.html
|
||||
#FRED_API_KEY=
|
||||
|
||||
# TypeSafe Jev: screens StockTwits and Reddit posts for the Sentiment Analyst. Optional.
|
||||
#TYPESAFE_API_KEY=
|
||||
#TYPESAFE_DEFAULT_MODEL=jev-latest
|
||||
|
||||
# Custom OpenAI-compatible endpoint (vLLM, LM Studio, llama.cpp). Local servers need no key.
|
||||
#OPENAI_COMPATIBLE_API_KEY=
|
||||
|
||||
@@ -35,8 +39,8 @@ NVIDIA_API_KEY=
|
||||
|
||||
# Override these DEFAULT_CONFIG keys. Provider, models, language and round counts also skip their CLI prompt.
|
||||
#TRADINGAGENTS_LLM_PROVIDER=openai
|
||||
#TRADINGAGENTS_DEEP_THINK_LLM=gpt-5.6
|
||||
#TRADINGAGENTS_QUICK_THINK_LLM=gpt-5.6-luna
|
||||
#TRADINGAGENTS_DEEP_THINK_LLM=gpt-6-sol
|
||||
#TRADINGAGENTS_QUICK_THINK_LLM=gpt-6-luna
|
||||
#TRADINGAGENTS_LLM_BACKEND_URL=
|
||||
#TRADINGAGENTS_OUTPUT_LANGUAGE=English
|
||||
#TRADINGAGENTS_MAX_DEBATE_ROUNDS=1
|
||||
|
||||
@@ -2,7 +2,7 @@ name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
branches: [main, 'v[0-9]+.[0-9]+.[0-9]+']
|
||||
pull_request:
|
||||
|
||||
concurrency:
|
||||
@@ -11,12 +11,18 @@ concurrency:
|
||||
|
||||
jobs:
|
||||
test:
|
||||
name: tests (py${{ matrix.python-version }})
|
||||
name: tests (py${{ matrix.python-version }}${{ matrix.tz && format(', {0}', matrix.tz) || '' }})
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
python-version: ["3.10", "3.11", "3.12", "3.13"]
|
||||
# One run away from UTC, so a test that only passes in UTC fails here.
|
||||
include:
|
||||
- python-version: "3.12"
|
||||
tz: America/New_York
|
||||
env:
|
||||
TZ: ${{ matrix.tz }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
|
||||
+47
-1
@@ -4,7 +4,53 @@ All notable changes to TradingAgents are documented here.
|
||||
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
||||
and this project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
Breaking changes within the 0.x line are called out explicitly.
|
||||
Changes that need action when upgrading are listed first in their release.
|
||||
|
||||
## [0.5.1] — 2026-09-24
|
||||
|
||||
A package layout organised by what each module holds, social posts screened by
|
||||
TypeSafe's Jev when a key is set, GPT-6 Sol and Luna as the default models, and
|
||||
fixes to run isolation, SEC EDGAR statements and historical runs.
|
||||
|
||||
### Upgrading from 0.5.0
|
||||
|
||||
Some modules moved, and the old import paths are gone. Update imports as follows:
|
||||
|
||||
- `tradingagents.dataflows.interface` is `tradingagents.dataflows.router`, and `dataflows.symbol_utils` is `dataflows.symbols`. `dataflows.utils` is gone: `get_current_date` is in `dataflows.date_window`, `safe_ticker_component` in `dataflows.symbols`.
|
||||
- Vendor modules live under `tradingagents.dataflows.vendors`: `yahoo` (`ohlcv`, `market`, `fundamentals`, `news`, `snapshot`, from the former `stockstats_utils`, `y_finance`, `yfinance_news` and `market_data_validator`), `alpha_vantage` (a package, from the `alpha_vantage_*` modules), and `sec_edgar`, `fred`, `polymarket`, `reddit`, `stocktwits`.
|
||||
- `tradingagents.agents.utils` is gone: the agent tools are in `agents.tools`, and `agent_utils`, `agent_states`, `rating` and `structured` are `agents.context`, `agents.state`, `agents.rating` and `agents.structured`.
|
||||
- The decision log is `tradingagents.decision_log` (was `agents.utils.memory`), and `cli.utils` is `cli.prompts`.
|
||||
- `backtest.summarize` takes a `run_backtest` result or the path of a decision log, in place of a `TradingMemoryLog`.
|
||||
- Removed: `SignalProcessor` (the rating is parsed by `process_signal`), the `create_social_media_analyst` alias (use `create_sentiment_analyst`), the unused `project_dir` config key, and the graph attributes `curr_state`, `ticker` and `log_states_dict`, which held the previous run's state.
|
||||
|
||||
### Added
|
||||
|
||||
- **Jev post screening.** With `TYPESAFE_API_KEY` set, TypeSafe's Jev reads each StockTwits and Reddit post the Sentiment Analyst fetches: posts that are not about the company are dropped, and each source opens with a count of the rest by stance. Without the key nothing changes. (#1376)
|
||||
- B3 tickers (`.SA`) are benchmarked against the Ibovespa. (#1366)
|
||||
|
||||
### Models
|
||||
|
||||
- GPT-6 Sol and GPT-6 Luna are the default deep and quick models, and Claude Opus 5.5 replaces Opus 5 in the picker. Opus 5 and GPT-5.4 Mini remain valid model IDs.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Several graphs in one process each read their own data vendors. (#1369)
|
||||
- SEC EDGAR cash flow statements find capital expenditure for filers that moved it to purchases of productive assets (NVIDIA since fiscal 2022, Amazon since 2016), whose recent periods read as empty. (#1370)
|
||||
- SEC EDGAR annual statements list fiscal years only.
|
||||
- A historical run is no longer told today's date, or a date after the run, in coverage notices and the instrument context.
|
||||
- The Fundamentals Analyst can call the insider transactions tool.
|
||||
- An unreachable Yahoo on insider transactions is reported as unavailable, not as a symbol without data.
|
||||
- A graph reused across runs, as in a backtest, no longer keeps every run's full state.
|
||||
- A checkpointed CLI run says whether it resumed or started fresh.
|
||||
- A blank path variable (`TRADINGAGENTS_RESULTS_DIR` and the like) keeps the default path.
|
||||
- StockTwits messages reach the prompt as plain text rather than HTML-escaped.
|
||||
- The test suite is independent of the developer's `.env`, time zone and network. (#1368, #1372)
|
||||
|
||||
### Contributors
|
||||
|
||||
Thanks to everyone who reported these or sent a fix:
|
||||
|
||||
[@codify88](https://github.com/codify88), [@davidalmeida90](https://github.com/davidalmeida90), [@duongylinh](https://github.com/duongylinh), [@jccl2](https://github.com/jccl2), [@yuina368](https://github.com/yuina368).
|
||||
|
||||
## [0.5.0] — 2026-09-18
|
||||
|
||||
|
||||
@@ -30,6 +30,7 @@
|
||||
# TradingAgents: Multi-Agents LLM Financial Trading Framework
|
||||
|
||||
## News
|
||||
- [2026-09] **TradingAgents v0.5.1** released with a package layout organised by what each module holds, optional Jev screening of social posts, GPT-6 Sol and Luna as the default models, and fixes to run isolation and SEC EDGAR statements. Module paths moved; see [CHANGELOG.md](CHANGELOG.md) for the new imports.
|
||||
- [2026-09] **TradingAgents v0.5.0** released with point-in-time integrity across every dated path, SEC EDGAR fundamentals served as filed, backtesting over a ticker and date grid, portfolio-aware runs, and current model lineups across every provider. See [CHANGELOG.md](CHANGELOG.md) for the full list.
|
||||
- [2026-08] **TradingAgents v0.4.0** released with look-ahead / point-in-time fixes across FRED macro, social sentiment, and the decision-log memory; clearer decision signals; working CLI checkpoint resume; Trader price grounding; and the GPT-5.6 and GLM-5.3 models.
|
||||
- [2026-07] **TradingAgents v0.3.1** released with correctness and stability fixes: Alpha Vantage look-ahead filtering, graph-router crash-safety, graph-shape-aware checkpoint resume, working crypto sentiment sources, a configurable LLM retry budget, Bedrock API-key auth, and Claude Sonnet 5 / Fable 5 support.
|
||||
@@ -166,6 +167,7 @@ export GROQ_API_KEY=... # Groq
|
||||
export NVIDIA_API_KEY=... # NVIDIA NIM
|
||||
export FRED_API_KEY=... # FRED macro data (free, optional)
|
||||
export ALPHA_VANTAGE_API_KEY=... # Alpha Vantage
|
||||
export TYPESAFE_API_KEY=... # Jev social-post screening (optional)
|
||||
```
|
||||
|
||||
For Azure OpenAI, copy `.env.enterprise.example` to `.env.enterprise` and fill in your credentials.
|
||||
@@ -176,6 +178,8 @@ For local models, configure Ollama with `llm_provider: "ollama"`. The default en
|
||||
|
||||
For any other OpenAI-compatible server (vLLM, LM Studio, llama.cpp, or a custom relay), use `llm_provider: "openai_compatible"` and set the endpoint via `backend_url` (or `TRADINGAGENTS_LLM_BACKEND_URL`), e.g. `http://localhost:8000/v1` for vLLM or `http://localhost:1234/v1` for LM Studio. The model is whatever your server serves. No key is needed for local servers; set `OPENAI_COMPATIBLE_API_KEY` when the endpoint requires one.
|
||||
|
||||
With `TYPESAFE_API_KEY` set, the Sentiment Analyst screens StockTwits and Reddit posts with TypeSafe's Jev before reading them. Posts that are not about the company are dropped, and each source opens with a count of the remaining posts by stance: bullish, bearish, neutral, or unclear. Without the key, posts pass through unscreened. `jev-latest` moves with new releases; set `TYPESAFE_DEFAULT_MODEL` to a versioned ID such as `jev-1.13.0` to hold it fixed across runs.
|
||||
|
||||
Alternatively, copy `.env.example` to `.env` and fill in your keys:
|
||||
```bash
|
||||
cp .env.example .env
|
||||
@@ -243,8 +247,8 @@ from tradingagents.default_config import DEFAULT_CONFIG
|
||||
|
||||
config = DEFAULT_CONFIG.copy()
|
||||
config["llm_provider"] = "openai" # e.g. openai, google, anthropic, deepseek, groq, ollama; openai_compatible covers any OpenAI-compatible endpoint (vLLM, LM Studio, llama.cpp, ...)
|
||||
config["deep_think_llm"] = "gpt-5.6" # Model for complex reasoning
|
||||
config["quick_think_llm"] = "gpt-5.6-luna" # Model for quick tasks
|
||||
config["deep_think_llm"] = "gpt-6-sol" # Model for complex reasoning
|
||||
config["quick_think_llm"] = "gpt-6-luna" # Model for quick tasks
|
||||
config["max_debate_rounds"] = 2
|
||||
|
||||
ta = TradingAgentsGraph(debug=True, config=config)
|
||||
@@ -325,11 +329,10 @@ One run gives one decision, which cannot tell you whether the system decides wel
|
||||
|
||||
```python
|
||||
from tradingagents.backtest import iter_grid, run_backtest, summarize
|
||||
from tradingagents.agents.utils.memory import TradingMemoryLog
|
||||
|
||||
dates = iter_grid("2026-06-01", "2026-08-01", every_n_days=7)
|
||||
result = run_backtest(["NVDA", "AAPL"], dates, config, selected_analysts=["market", "news"])
|
||||
print(summarize(TradingMemoryLog({"memory_log_path": str(result.log_path)})).render())
|
||||
print(summarize(result).render())
|
||||
```
|
||||
|
||||
From the CLI:
|
||||
@@ -344,7 +347,7 @@ Each cell is scored on realized alpha against the instrument's regional benchmar
|
||||
|
||||
TradingAgents is LLM-driven, so two runs of the same ticker and date can differ. This is expected for a research tool built on language models, not a defect. The variation comes from a few distinct sources, and it helps to separate them.
|
||||
|
||||
Language model sampling is non-deterministic. Even at a fixed temperature, providers do not guarantee byte-identical output across calls, and reasoning models (the default GPT-5.x family, and any thinking-mode model) vary the most because their internal reasoning is itself sampled.
|
||||
Language model sampling is non-deterministic. Even at a fixed temperature, providers do not guarantee byte-identical output across calls, and reasoning models (the default GPT-6 family, and any thinking-mode model) vary the most because their internal reasoning is itself sampled.
|
||||
|
||||
Live data moves. News, StockTwits, and Reddit return different content as time passes, so a run today sees different inputs than a run last week even for the same historical trade date. Pin the analysis date to hold the price and indicator window fixed, but the social and news sources still reflect "now".
|
||||
|
||||
|
||||
+640
@@ -0,0 +1,640 @@
|
||||
"""The live view of a run: message log, agent status, report panels and timings."""
|
||||
|
||||
import datetime
|
||||
import time
|
||||
from collections import deque
|
||||
from time import monotonic
|
||||
|
||||
from rich import box
|
||||
from rich.console import Console
|
||||
from rich.layout import Layout
|
||||
from rich.markdown import Markdown
|
||||
from rich.panel import Panel
|
||||
from rich.rule import Rule
|
||||
from rich.spinner import Spinner
|
||||
from rich.table import Table
|
||||
from rich.text import Text
|
||||
|
||||
from tradingagents.graph.analyst_execution import (
|
||||
ANALYST_NODE_SPECS,
|
||||
AnalystExecutionPlan,
|
||||
)
|
||||
|
||||
console = Console()
|
||||
|
||||
|
||||
class MessageBuffer:
|
||||
# Fixed teams that always run (not user-selectable)
|
||||
FIXED_AGENTS = {
|
||||
"Research Team": ["Bull Researcher", "Bear Researcher", "Research Manager"],
|
||||
"Trading Team": ["Trader"],
|
||||
"Risk Management": ["Aggressive Analyst", "Neutral Analyst", "Conservative Analyst"],
|
||||
"Portfolio Management": ["Portfolio Manager"],
|
||||
}
|
||||
|
||||
# Analyst name mapping
|
||||
ANALYST_MAPPING = {
|
||||
"market": "Market Analyst",
|
||||
"social": "Sentiment Analyst",
|
||||
"news": "News Analyst",
|
||||
"fundamentals": "Fundamentals Analyst",
|
||||
}
|
||||
|
||||
# Report section mapping: section -> (analyst_key for filtering, finalizing_agent)
|
||||
# analyst_key: which analyst selection controls this section (None = always included)
|
||||
# finalizing_agent: which agent must be "completed" for this report to count as done
|
||||
REPORT_SECTIONS = {
|
||||
"market_report": ("market", "Market Analyst"),
|
||||
"sentiment_report": ("social", "Sentiment Analyst"),
|
||||
"news_report": ("news", "News Analyst"),
|
||||
"fundamentals_report": ("fundamentals", "Fundamentals Analyst"),
|
||||
"investment_plan": (None, "Research Manager"),
|
||||
"trader_investment_plan": (None, "Trader"),
|
||||
"final_trade_decision": (None, "Portfolio Manager"),
|
||||
}
|
||||
|
||||
def __init__(self, max_length=100):
|
||||
self.messages = deque(maxlen=max_length)
|
||||
self.tool_calls = deque(maxlen=max_length)
|
||||
self.current_report = None
|
||||
self.agent_status = {}
|
||||
self.report_sections = {}
|
||||
self.selected_analysts = []
|
||||
self._processed_message_ids = set()
|
||||
|
||||
def init_for_analysis(self, selected_analysts):
|
||||
"""Initialize agent status and report sections based on selected analysts.
|
||||
|
||||
Args:
|
||||
selected_analysts: List of analyst type strings (e.g., ["market", "news"])
|
||||
"""
|
||||
self.selected_analysts = [a.lower() for a in selected_analysts]
|
||||
|
||||
self.agent_status = {}
|
||||
|
||||
for analyst_key in self.selected_analysts:
|
||||
if analyst_key in self.ANALYST_MAPPING:
|
||||
self.agent_status[self.ANALYST_MAPPING[analyst_key]] = "pending"
|
||||
|
||||
for team_agents in self.FIXED_AGENTS.values():
|
||||
for agent in team_agents:
|
||||
self.agent_status[agent] = "pending"
|
||||
|
||||
self.report_sections = {}
|
||||
for section, (analyst_key, _) in self.REPORT_SECTIONS.items():
|
||||
if analyst_key is None or analyst_key in self.selected_analysts:
|
||||
self.report_sections[section] = None
|
||||
|
||||
# Reset other state
|
||||
self.current_report = None
|
||||
self.messages.clear()
|
||||
self.tool_calls.clear()
|
||||
self._processed_message_ids.clear()
|
||||
|
||||
def get_completed_reports_count(self):
|
||||
"""Count reports that are finalized (their finalizing agent is completed).
|
||||
|
||||
A report is considered complete when:
|
||||
1. The report section has content (not None), AND
|
||||
2. The agent responsible for finalizing that report has status "completed"
|
||||
|
||||
This prevents interim updates (like debate rounds) from counting as completed.
|
||||
"""
|
||||
count = 0
|
||||
for section in self.report_sections:
|
||||
if section not in self.REPORT_SECTIONS:
|
||||
continue
|
||||
_, finalizing_agent = self.REPORT_SECTIONS[section]
|
||||
# Report is complete if it has content AND its finalizing agent is done
|
||||
has_content = self.report_sections.get(section) is not None
|
||||
agent_done = self.agent_status.get(finalizing_agent) == "completed"
|
||||
if has_content and agent_done:
|
||||
count += 1
|
||||
return count
|
||||
|
||||
def add_message(self, message_type, content):
|
||||
timestamp = datetime.datetime.now().strftime("%H:%M:%S")
|
||||
self.messages.append((timestamp, message_type, content))
|
||||
|
||||
def add_tool_call(self, tool_name, args):
|
||||
timestamp = datetime.datetime.now().strftime("%H:%M:%S")
|
||||
self.tool_calls.append((timestamp, tool_name, args))
|
||||
|
||||
def update_agent_status(self, agent, status):
|
||||
if agent in self.agent_status:
|
||||
self.agent_status[agent] = status
|
||||
|
||||
def update_report_section(self, section_name, content):
|
||||
if section_name in self.report_sections:
|
||||
self.report_sections[section_name] = content
|
||||
self._update_current_report()
|
||||
|
||||
def _update_current_report(self):
|
||||
# For the panel display, only show the most recently updated section
|
||||
latest_section = None
|
||||
latest_content = None
|
||||
|
||||
for section, content in self.report_sections.items():
|
||||
if content is not None:
|
||||
latest_section = section
|
||||
latest_content = content
|
||||
|
||||
if latest_section and latest_content:
|
||||
section_titles = {
|
||||
"market_report": "Market Analysis",
|
||||
"sentiment_report": "Social Sentiment",
|
||||
"news_report": "News Analysis",
|
||||
"fundamentals_report": "Fundamentals Analysis",
|
||||
"investment_plan": "Research Team Decision",
|
||||
"trader_investment_plan": "Trading Team Plan",
|
||||
"final_trade_decision": "Portfolio Management Decision",
|
||||
}
|
||||
self.current_report = (
|
||||
f"### {section_titles[latest_section]}\n{latest_content}"
|
||||
)
|
||||
|
||||
|
||||
message_buffer = MessageBuffer()
|
||||
|
||||
|
||||
def create_layout():
|
||||
layout = Layout()
|
||||
layout.split_column(
|
||||
Layout(name="header", size=3),
|
||||
Layout(name="main"),
|
||||
Layout(name="footer", size=3),
|
||||
)
|
||||
layout["main"].split_column(
|
||||
Layout(name="upper", ratio=3), Layout(name="analysis", ratio=5)
|
||||
)
|
||||
layout["upper"].split_row(
|
||||
Layout(name="progress", ratio=2), Layout(name="messages", ratio=3)
|
||||
)
|
||||
return layout
|
||||
|
||||
|
||||
def format_tokens(n):
|
||||
"""Format token count for display."""
|
||||
if n >= 1000:
|
||||
return f"{n/1000:.1f}k"
|
||||
return str(n)
|
||||
|
||||
|
||||
def update_display(layout, spinner_text=None, stats_handler=None, start_time=None):
|
||||
# Header with welcome message
|
||||
layout["header"].update(
|
||||
Panel(
|
||||
"[bold green]Welcome to TradingAgents CLI[/bold green]\n"
|
||||
"[dim]© [Tauric Research](https://github.com/TauricResearch)[/dim]",
|
||||
title="Welcome to TradingAgents",
|
||||
border_style="green",
|
||||
padding=(1, 2),
|
||||
expand=True,
|
||||
)
|
||||
)
|
||||
|
||||
# Progress panel showing agent status
|
||||
progress_table = Table(
|
||||
show_header=True,
|
||||
header_style="bold magenta",
|
||||
show_footer=False,
|
||||
box=box.SIMPLE_HEAD, # Use simple header with horizontal lines
|
||||
title=None, # Remove the redundant Progress title
|
||||
padding=(0, 2), # Add horizontal padding
|
||||
expand=True, # Make table expand to fill available space
|
||||
)
|
||||
progress_table.add_column("Team", style="cyan", justify="center", width=20)
|
||||
progress_table.add_column("Agent", style="green", justify="center", width=20)
|
||||
progress_table.add_column("Status", style="yellow", justify="center", width=20)
|
||||
|
||||
# Group agents by team - filter to only include agents in agent_status
|
||||
all_teams = {
|
||||
"Analyst Team": [
|
||||
"Market Analyst",
|
||||
"Sentiment Analyst",
|
||||
"News Analyst",
|
||||
"Fundamentals Analyst",
|
||||
],
|
||||
"Research Team": ["Bull Researcher", "Bear Researcher", "Research Manager"],
|
||||
"Trading Team": ["Trader"],
|
||||
"Risk Management": ["Aggressive Analyst", "Neutral Analyst", "Conservative Analyst"],
|
||||
"Portfolio Management": ["Portfolio Manager"],
|
||||
}
|
||||
|
||||
teams = {}
|
||||
for team, agents in all_teams.items():
|
||||
active_agents = [a for a in agents if a in message_buffer.agent_status]
|
||||
if active_agents:
|
||||
teams[team] = active_agents
|
||||
|
||||
for team, agents in teams.items():
|
||||
first_agent = agents[0]
|
||||
status = message_buffer.agent_status.get(first_agent, "pending")
|
||||
if status == "in_progress":
|
||||
spinner = Spinner(
|
||||
"dots", text="[blue]in_progress[/blue]", style="bold cyan"
|
||||
)
|
||||
status_cell = spinner
|
||||
else:
|
||||
status_color = {
|
||||
"pending": "yellow",
|
||||
"completed": "green",
|
||||
"error": "red",
|
||||
}.get(status, "white")
|
||||
status_cell = f"[{status_color}]{status}[/{status_color}]"
|
||||
progress_table.add_row(team, first_agent, status_cell)
|
||||
|
||||
for agent in agents[1:]:
|
||||
status = message_buffer.agent_status.get(agent, "pending")
|
||||
if status == "in_progress":
|
||||
spinner = Spinner(
|
||||
"dots", text="[blue]in_progress[/blue]", style="bold cyan"
|
||||
)
|
||||
status_cell = spinner
|
||||
else:
|
||||
status_color = {
|
||||
"pending": "yellow",
|
||||
"completed": "green",
|
||||
"error": "red",
|
||||
}.get(status, "white")
|
||||
status_cell = f"[{status_color}]{status}[/{status_color}]"
|
||||
progress_table.add_row("", agent, status_cell)
|
||||
|
||||
progress_table.add_row("─" * 20, "─" * 20, "─" * 20, style="dim")
|
||||
|
||||
layout["progress"].update(
|
||||
Panel(progress_table, title="Progress", border_style="cyan", padding=(1, 2))
|
||||
)
|
||||
|
||||
# Messages panel showing recent messages and tool calls
|
||||
messages_table = Table(
|
||||
show_header=True,
|
||||
header_style="bold magenta",
|
||||
show_footer=False,
|
||||
expand=True, # Make table expand to fill available space
|
||||
box=box.MINIMAL, # Use minimal box style for a lighter look
|
||||
show_lines=True, # Keep horizontal lines
|
||||
padding=(0, 1), # Add some padding between columns
|
||||
)
|
||||
messages_table.add_column("Time", style="cyan", width=8, justify="center")
|
||||
messages_table.add_column("Type", style="green", width=10, justify="center")
|
||||
messages_table.add_column(
|
||||
"Content", style="white", no_wrap=False, ratio=1
|
||||
) # Make content column expand
|
||||
|
||||
# Combine tool calls and messages
|
||||
all_messages = []
|
||||
|
||||
for timestamp, tool_name, args in message_buffer.tool_calls:
|
||||
formatted_args = format_tool_args(args)
|
||||
all_messages.append((timestamp, "Tool", f"{tool_name}: {formatted_args}"))
|
||||
|
||||
for timestamp, msg_type, content in message_buffer.messages:
|
||||
content_str = str(content) if content else ""
|
||||
if len(content_str) > 200:
|
||||
content_str = content_str[:197] + "..."
|
||||
all_messages.append((timestamp, msg_type, content_str))
|
||||
|
||||
# Sort by timestamp descending (newest first)
|
||||
all_messages.sort(key=lambda x: x[0], reverse=True)
|
||||
|
||||
max_messages = 12
|
||||
|
||||
recent_messages = all_messages[:max_messages]
|
||||
|
||||
for timestamp, msg_type, content in recent_messages:
|
||||
wrapped_content = Text(content, overflow="fold")
|
||||
messages_table.add_row(timestamp, msg_type, wrapped_content)
|
||||
|
||||
layout["messages"].update(
|
||||
Panel(
|
||||
messages_table,
|
||||
title="Messages & Tools",
|
||||
border_style="blue",
|
||||
padding=(1, 2),
|
||||
)
|
||||
)
|
||||
|
||||
# Analysis panel showing current report
|
||||
if message_buffer.current_report:
|
||||
layout["analysis"].update(
|
||||
Panel(
|
||||
Markdown(message_buffer.current_report),
|
||||
title="Current Report",
|
||||
border_style="green",
|
||||
padding=(1, 2),
|
||||
)
|
||||
)
|
||||
else:
|
||||
layout["analysis"].update(
|
||||
Panel(
|
||||
"[italic]Waiting for analysis report...[/italic]",
|
||||
title="Current Report",
|
||||
border_style="green",
|
||||
padding=(1, 2),
|
||||
)
|
||||
)
|
||||
|
||||
# Footer with statistics
|
||||
# Agent progress - derived from agent_status dict
|
||||
agents_completed = sum(
|
||||
1 for status in message_buffer.agent_status.values() if status == "completed"
|
||||
)
|
||||
agents_total = len(message_buffer.agent_status)
|
||||
|
||||
# Report progress - based on agent completion (not just content existence)
|
||||
reports_completed = message_buffer.get_completed_reports_count()
|
||||
reports_total = len(message_buffer.report_sections)
|
||||
|
||||
stats_parts = [f"Agents: {agents_completed}/{agents_total}"]
|
||||
|
||||
# LLM and tool stats from callback handler
|
||||
if stats_handler:
|
||||
stats = stats_handler.get_stats()
|
||||
stats_parts.append(f"LLM: {stats['llm_calls']}")
|
||||
stats_parts.append(f"Tools: {stats['tool_calls']}")
|
||||
|
||||
# Token display with graceful fallback
|
||||
if stats["tokens_in"] > 0 or stats["tokens_out"] > 0:
|
||||
tokens_str = f"Tokens: {format_tokens(stats['tokens_in'])}\u2191 {format_tokens(stats['tokens_out'])}\u2193"
|
||||
else:
|
||||
tokens_str = "Tokens: --"
|
||||
stats_parts.append(tokens_str)
|
||||
|
||||
stats_parts.append(f"Reports: {reports_completed}/{reports_total}")
|
||||
|
||||
# Elapsed time
|
||||
if start_time:
|
||||
elapsed = time.time() - start_time
|
||||
elapsed_str = f"\u23f1 {int(elapsed // 60):02d}:{int(elapsed % 60):02d}"
|
||||
stats_parts.append(elapsed_str)
|
||||
|
||||
stats_table = Table(show_header=False, box=None, padding=(0, 2), expand=True)
|
||||
stats_table.add_column("Stats", justify="center")
|
||||
stats_table.add_row(" | ".join(stats_parts))
|
||||
|
||||
layout["footer"].update(Panel(stats_table, border_style="grey50"))
|
||||
|
||||
|
||||
def display_complete_report(final_state):
|
||||
"""Display the complete analysis report sequentially (avoids truncation)."""
|
||||
console.print()
|
||||
console.print(Rule("Complete Analysis Report", style="bold green"))
|
||||
|
||||
# I. Analyst Team Reports
|
||||
analysts = []
|
||||
if final_state.get("market_report"):
|
||||
analysts.append(("Market Analyst", final_state["market_report"]))
|
||||
if final_state.get("sentiment_report"):
|
||||
analysts.append(("Sentiment Analyst", final_state["sentiment_report"]))
|
||||
if final_state.get("news_report"):
|
||||
analysts.append(("News Analyst", final_state["news_report"]))
|
||||
if final_state.get("fundamentals_report"):
|
||||
analysts.append(("Fundamentals Analyst", final_state["fundamentals_report"]))
|
||||
if analysts:
|
||||
console.print(Panel("[bold]I. Analyst Team Reports[/bold]", border_style="cyan"))
|
||||
for title, content in analysts:
|
||||
console.print(Panel(Markdown(content), title=title, border_style="blue", padding=(1, 2)))
|
||||
|
||||
# II. Research Team Reports
|
||||
if final_state.get("investment_debate_state"):
|
||||
debate = final_state["investment_debate_state"]
|
||||
research = []
|
||||
if debate.get("bull_history"):
|
||||
research.append(("Bull Researcher", debate["bull_history"]))
|
||||
if debate.get("bear_history"):
|
||||
research.append(("Bear Researcher", debate["bear_history"]))
|
||||
if debate.get("judge_decision"):
|
||||
research.append(("Research Manager", debate["judge_decision"]))
|
||||
if research:
|
||||
console.print(Panel("[bold]II. Research Team Decision[/bold]", border_style="magenta"))
|
||||
for title, content in research:
|
||||
console.print(Panel(Markdown(content), title=title, border_style="blue", padding=(1, 2)))
|
||||
|
||||
# III. Trading Team
|
||||
if final_state.get("trader_investment_plan"):
|
||||
console.print(Panel("[bold]III. Trading Team Plan[/bold]", border_style="yellow"))
|
||||
console.print(Panel(Markdown(final_state["trader_investment_plan"]), title="Trader", border_style="blue", padding=(1, 2)))
|
||||
|
||||
# IV. Risk Management Team
|
||||
if final_state.get("risk_debate_state"):
|
||||
risk = final_state["risk_debate_state"]
|
||||
risk_reports = []
|
||||
if risk.get("aggressive_history"):
|
||||
risk_reports.append(("Aggressive Analyst", risk["aggressive_history"]))
|
||||
if risk.get("conservative_history"):
|
||||
risk_reports.append(("Conservative Analyst", risk["conservative_history"]))
|
||||
if risk.get("neutral_history"):
|
||||
risk_reports.append(("Neutral Analyst", risk["neutral_history"]))
|
||||
if risk_reports:
|
||||
console.print(Panel("[bold]IV. Risk Management Team Decision[/bold]", border_style="red"))
|
||||
for title, content in risk_reports:
|
||||
console.print(Panel(Markdown(content), title=title, border_style="blue", padding=(1, 2)))
|
||||
|
||||
# V. Portfolio Manager Decision
|
||||
if risk.get("judge_decision"):
|
||||
console.print(Panel("[bold]V. Portfolio Manager Decision[/bold]", border_style="green"))
|
||||
console.print(Panel(Markdown(risk["judge_decision"]), title="Portfolio Manager", border_style="blue", padding=(1, 2)))
|
||||
|
||||
|
||||
def update_research_team_status(status):
|
||||
"""Update status for research team members (not Trader)."""
|
||||
research_team = ["Bull Researcher", "Bear Researcher", "Research Manager"]
|
||||
for agent in research_team:
|
||||
message_buffer.update_agent_status(agent, status)
|
||||
|
||||
|
||||
# Ordered list of analysts for status transitions
|
||||
ANALYST_ORDER = ["market", "social", "news", "fundamentals"]
|
||||
|
||||
ANALYST_AGENT_NAMES = {
|
||||
"market": "Market Analyst",
|
||||
"social": "Sentiment Analyst",
|
||||
"news": "News Analyst",
|
||||
"fundamentals": "Fundamentals Analyst",
|
||||
}
|
||||
|
||||
ANALYST_REPORT_MAP = {
|
||||
"market": "market_report",
|
||||
"social": "sentiment_report",
|
||||
"news": "news_report",
|
||||
"fundamentals": "fundamentals_report",
|
||||
}
|
||||
|
||||
|
||||
def update_analyst_statuses(message_buffer, chunk, wall_time_tracker=None):
|
||||
"""Update analyst statuses based on accumulated report state.
|
||||
|
||||
Logic:
|
||||
- Store new report content from the current chunk if present
|
||||
- Check accumulated report_sections (not just current chunk) for status
|
||||
- Analysts with reports = completed
|
||||
- First analyst without report = in_progress
|
||||
- Remaining analysts without reports = pending
|
||||
- When all analysts done, set Bull Researcher to in_progress
|
||||
"""
|
||||
selected = message_buffer.selected_analysts
|
||||
found_active = False
|
||||
|
||||
if wall_time_tracker is not None:
|
||||
sync_analyst_tracker_from_chunk(wall_time_tracker, chunk)
|
||||
|
||||
for analyst_key in ANALYST_ORDER:
|
||||
if analyst_key not in selected:
|
||||
continue
|
||||
|
||||
agent_name = ANALYST_AGENT_NAMES[analyst_key]
|
||||
report_key = ANALYST_REPORT_MAP[analyst_key]
|
||||
|
||||
# Capture new report content from current chunk
|
||||
if chunk.get(report_key):
|
||||
message_buffer.update_report_section(report_key, chunk[report_key])
|
||||
|
||||
# Determine status from accumulated sections, not just current chunk
|
||||
has_report = bool(message_buffer.report_sections.get(report_key))
|
||||
|
||||
if has_report:
|
||||
message_buffer.update_agent_status(agent_name, "completed")
|
||||
elif not found_active:
|
||||
message_buffer.update_agent_status(agent_name, "in_progress")
|
||||
found_active = True
|
||||
else:
|
||||
message_buffer.update_agent_status(agent_name, "pending")
|
||||
|
||||
# When all analysts complete, transition research team to in_progress
|
||||
if (
|
||||
not found_active
|
||||
and selected
|
||||
and message_buffer.agent_status.get("Bull Researcher") == "pending"
|
||||
):
|
||||
message_buffer.update_agent_status("Bull Researcher", "in_progress")
|
||||
|
||||
|
||||
def extract_content_string(content):
|
||||
"""Extract string content from various message formats.
|
||||
Returns None if no meaningful text content is found.
|
||||
"""
|
||||
def is_empty(val):
|
||||
"""Whether a value carries nothing to show.
|
||||
|
||||
Text is judged by whether anything was written, not by what it would
|
||||
mean as Python: a report saying "0" or "None" is a message the run
|
||||
produced, and reading it as a falsy literal dropped it from the display.
|
||||
"""
|
||||
if isinstance(val, str):
|
||||
return not val.strip()
|
||||
return val is None or not bool(val)
|
||||
|
||||
if is_empty(content):
|
||||
return None
|
||||
|
||||
if isinstance(content, str):
|
||||
return content.strip()
|
||||
|
||||
if isinstance(content, dict):
|
||||
text = content.get('text', '')
|
||||
return text.strip() if not is_empty(text) else None
|
||||
|
||||
if isinstance(content, list):
|
||||
text_parts = [
|
||||
item.get('text', '').strip() if isinstance(item, dict) and item.get('type') == 'text'
|
||||
else (item.strip() if isinstance(item, str) else '')
|
||||
for item in content
|
||||
]
|
||||
result = ' '.join(t for t in text_parts if t and not is_empty(t))
|
||||
return result if result else None
|
||||
|
||||
return str(content).strip() if not is_empty(content) else None
|
||||
|
||||
|
||||
def classify_message_type(message) -> tuple[str, str | None]:
|
||||
"""Classify LangChain message into display type and extract content.
|
||||
|
||||
Returns:
|
||||
(type, content) - type is one of: User, Agent, Data, Control
|
||||
- content is extracted string or None
|
||||
"""
|
||||
from langchain_core.messages import AIMessage, HumanMessage, ToolMessage
|
||||
|
||||
content = extract_content_string(getattr(message, 'content', None))
|
||||
|
||||
if isinstance(message, HumanMessage):
|
||||
if content and content.strip() == "Continue":
|
||||
return ("Control", content)
|
||||
return ("User", content)
|
||||
|
||||
if isinstance(message, ToolMessage):
|
||||
return ("Data", content)
|
||||
|
||||
if isinstance(message, AIMessage):
|
||||
return ("Agent", content)
|
||||
|
||||
# Fallback for unknown types
|
||||
return ("System", content)
|
||||
|
||||
|
||||
def format_tool_args(args, max_length=80) -> str:
|
||||
"""Format tool arguments for terminal display."""
|
||||
result = str(args)
|
||||
if len(result) > max_length:
|
||||
return result[:max_length - 3] + "..."
|
||||
return result
|
||||
|
||||
|
||||
class AnalystWallTimeTracker:
|
||||
def __init__(self, plan: AnalystExecutionPlan):
|
||||
self.plan = plan
|
||||
self._started_at: dict[str, float] = {}
|
||||
self._wall_times: dict[str, float] = {}
|
||||
|
||||
def mark_started(self, analyst_key: str, started_at: float | None = None) -> None:
|
||||
if analyst_key not in ANALYST_NODE_SPECS:
|
||||
raise ValueError(f"unknown analyst key: {analyst_key}")
|
||||
self._started_at.setdefault(analyst_key, monotonic() if started_at is None else started_at)
|
||||
|
||||
def mark_completed(
|
||||
self,
|
||||
analyst_key: str,
|
||||
completed_at: float | None = None,
|
||||
) -> None:
|
||||
if analyst_key not in ANALYST_NODE_SPECS:
|
||||
raise ValueError(f"unknown analyst key: {analyst_key}")
|
||||
if analyst_key in self._wall_times:
|
||||
return
|
||||
started_at = self._started_at.get(analyst_key)
|
||||
if started_at is None:
|
||||
return
|
||||
finished_at = monotonic() if completed_at is None else completed_at
|
||||
self._wall_times[analyst_key] = max(0.0, finished_at - started_at)
|
||||
|
||||
def format_summary(self) -> str:
|
||||
parts = []
|
||||
for spec in self.plan.specs:
|
||||
duration = self._wall_times.get(spec.key)
|
||||
if duration is not None:
|
||||
label = spec.agent_node.removesuffix(" Analyst")
|
||||
parts.append(f"{label} {duration:.2f}s")
|
||||
if not parts:
|
||||
return "Analyst wall time: pending"
|
||||
return "Analyst wall time: " + " | ".join(parts)
|
||||
|
||||
|
||||
def sync_analyst_tracker_from_chunk(
|
||||
tracker: AnalystWallTimeTracker,
|
||||
chunk: dict[str, str],
|
||||
now: float | None = None,
|
||||
) -> None:
|
||||
current_time = monotonic() if now is None else now
|
||||
active_found = False
|
||||
|
||||
for spec in tracker.plan.specs:
|
||||
has_report = bool(chunk.get(spec.report_key))
|
||||
|
||||
if has_report:
|
||||
tracker.mark_started(spec.key, started_at=current_time)
|
||||
tracker.mark_completed(spec.key, completed_at=current_time)
|
||||
continue
|
||||
|
||||
if not active_found:
|
||||
tracker.mark_started(spec.key, started_at=current_time)
|
||||
active_found = True
|
||||
+3
-1333
File diff suppressed because it is too large
Load Diff
+1
-1
@@ -21,7 +21,7 @@ import os
|
||||
from pathlib import Path
|
||||
|
||||
from cli.models import AnalystType, AssetType
|
||||
from cli.utils import _llm_provider_table, filter_analysts_for_asset_type
|
||||
from cli.prompts import _llm_provider_table, filter_analysts_for_asset_type
|
||||
from tradingagents.llm_clients.model_catalog import get_model_options
|
||||
|
||||
_PREFS_PATH = Path(os.path.expanduser("~")) / ".tradingagents" / "cli_prefs.json"
|
||||
|
||||
@@ -3,17 +3,15 @@ from pathlib import Path
|
||||
|
||||
import questionary
|
||||
from dotenv import find_dotenv, set_key
|
||||
from rich.console import Console
|
||||
|
||||
from cli.display import console
|
||||
from cli.models import AnalystType, AssetType
|
||||
from tradingagents.llm_clients.api_key_env import get_api_key_env
|
||||
from tradingagents.llm_clients.model_catalog import get_model_options
|
||||
|
||||
console = Console()
|
||||
|
||||
TICKER_INPUT_EXAMPLES = "SPY, 0700.HK, BTC-USD"
|
||||
|
||||
ANALYST_ORDER = [
|
||||
ANALYST_CHOICES = [
|
||||
("Market Analyst", AnalystType.MARKET),
|
||||
("Sentiment Analyst", AnalystType.SOCIAL),
|
||||
("News Analyst", AnalystType.NEWS),
|
||||
@@ -71,7 +69,7 @@ def normalize_ticker_symbol(ticker: str) -> str:
|
||||
plain upper-case if the data layer is unavailable.
|
||||
"""
|
||||
try:
|
||||
from tradingagents.dataflows.symbol_utils import normalize_symbol
|
||||
from tradingagents.dataflows.symbols import normalize_symbol
|
||||
|
||||
return normalize_symbol(ticker)
|
||||
except Exception:
|
||||
@@ -99,39 +97,6 @@ def filter_analysts_for_asset_type(
|
||||
]
|
||||
|
||||
|
||||
def get_analysis_date() -> str:
|
||||
"""Prompt the user to enter a date in YYYY-MM-DD format."""
|
||||
import re
|
||||
from datetime import datetime
|
||||
|
||||
def validate_date(date_str: str) -> bool:
|
||||
if not re.match(r"^\d{4}-\d{2}-\d{2}$", date_str):
|
||||
return False
|
||||
try:
|
||||
datetime.strptime(date_str, "%Y-%m-%d")
|
||||
return True
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
date = questionary.text(
|
||||
"Enter the analysis date (YYYY-MM-DD):",
|
||||
validate=lambda x: validate_date(x.strip())
|
||||
or "Please enter a valid date in YYYY-MM-DD format.",
|
||||
style=questionary.Style(
|
||||
[
|
||||
("text", "fg:green"),
|
||||
("highlighted", "noinherit"),
|
||||
]
|
||||
),
|
||||
).ask()
|
||||
|
||||
if not date:
|
||||
console.print("\n[red]No date provided. Exiting...[/red]")
|
||||
exit(1)
|
||||
|
||||
return date.strip()
|
||||
|
||||
|
||||
def _matching_choice(options, default):
|
||||
"""The option value equal to ``default``, or None to leave the menu as is."""
|
||||
return next((value for _, value in options if value == default), None)
|
||||
@@ -143,14 +108,14 @@ def select_analysts(asset_type: AssetType = AssetType.STOCK, default=None) -> li
|
||||
``default`` pre-checks the previous run's analysts; the prompt still shows.
|
||||
"""
|
||||
available_analysts = filter_analysts_for_asset_type(
|
||||
[value for _, value in ANALYST_ORDER],
|
||||
[value for _, value in ANALYST_CHOICES],
|
||||
asset_type,
|
||||
)
|
||||
choices = questionary.checkbox(
|
||||
"Select Your [Analysts Team]:",
|
||||
choices=[
|
||||
questionary.Choice(display, value=value, checked=value.value in (default or []))
|
||||
for display, value in ANALYST_ORDER
|
||||
for display, value in ANALYST_CHOICES
|
||||
if value in available_analysts
|
||||
],
|
||||
instruction="\n- Press Space to select/unselect analysts\n- Press 'a' to select/unselect all\n- Press Enter when done",
|
||||
@@ -175,7 +140,6 @@ def select_analysts(asset_type: AssetType = AssetType.STOCK, default=None) -> li
|
||||
def select_research_depth(default=None) -> int:
|
||||
"""Select research depth using an interactive selection."""
|
||||
|
||||
# Define research depth options with their corresponding values
|
||||
DEPTH_OPTIONS = [
|
||||
("Shallow - Quick research, few debate and strategy discussion rounds", 1),
|
||||
("Medium - Middle ground, moderate debate rounds and strategy discussion", 3),
|
||||
@@ -345,6 +309,7 @@ def select_deep_thinking_agent(provider, default=None) -> str:
|
||||
"""Select deep thinking llm engine using an interactive selection."""
|
||||
return _select_model(provider, "deep", default)
|
||||
|
||||
|
||||
def _llm_provider_table() -> list[tuple[str, str, str | None]]:
|
||||
"""(display_name, provider_key, base_url) for every supported provider.
|
||||
|
||||
+393
@@ -0,0 +1,393 @@
|
||||
"""Running one analysis from the CLI: build the graph, stream it into the live view, save the report."""
|
||||
|
||||
import datetime
|
||||
import os
|
||||
import time
|
||||
from functools import wraps
|
||||
from pathlib import Path
|
||||
|
||||
import typer
|
||||
from rich.live import Live
|
||||
|
||||
from cli.display import (
|
||||
ANALYST_ORDER,
|
||||
AnalystWallTimeTracker,
|
||||
classify_message_type,
|
||||
console,
|
||||
create_layout,
|
||||
display_complete_report,
|
||||
message_buffer,
|
||||
update_analyst_statuses,
|
||||
update_display,
|
||||
update_research_team_status,
|
||||
)
|
||||
from cli.selections import get_user_selections
|
||||
from cli.stats_handler import StatsCallbackHandler
|
||||
from tradingagents.agents.rating import is_review
|
||||
from tradingagents.dataflows.symbols import safe_ticker_component
|
||||
from tradingagents.default_config import DEFAULT_CONFIG
|
||||
from tradingagents.graph.analyst_execution import (
|
||||
build_analyst_execution_plan,
|
||||
)
|
||||
from tradingagents.graph.trading_graph import TradingAgentsGraph
|
||||
from tradingagents.reporting import write_report_tree
|
||||
|
||||
|
||||
def _run_directory(config: dict, ticker: str, trade_date: str) -> Path:
|
||||
"""Where this run writes, with the ticker validated as a path component.
|
||||
|
||||
Every other path that interpolates a ticker checks it first; a value of
|
||||
".." here would place the run outside the results directory.
|
||||
"""
|
||||
return Path(config["results_dir"]) / safe_ticker_component(ticker) / trade_date
|
||||
|
||||
|
||||
def _announce_checkpoint_state(graph, ticker: str, trade_date: str) -> None:
|
||||
"""Say whether this run resumed a saved one, where the user can see it.
|
||||
|
||||
The graph logs this, but nothing in the CLI configures logging and the live
|
||||
view owns the screen, so a resume was invisible.
|
||||
"""
|
||||
if getattr(graph, "_resuming", False):
|
||||
message_buffer.add_message(
|
||||
"System", f"Resuming the saved run for {ticker} on {trade_date}"
|
||||
)
|
||||
else:
|
||||
message_buffer.add_message("System", f"Starting fresh for {ticker} on {trade_date}")
|
||||
|
||||
|
||||
def _build_run_config(selections: dict, checkpoint: bool | None) -> dict:
|
||||
"""Assemble the run config from interactive selections, honoring env precedence.
|
||||
|
||||
Round counts and checkpoint follow "explicit env/flag wins": an env-applied
|
||||
value on DEFAULT_CONFIG is preserved unless the user overrode it on the CLI.
|
||||
"""
|
||||
config = DEFAULT_CONFIG.copy()
|
||||
# Research depth sets both round counts, but an explicit env override
|
||||
# (TRADINGAGENTS_MAX_DEBATE_ROUNDS / _MAX_RISK_ROUNDS) wins over the
|
||||
# interactive selection — leave the env-applied value in place (#977).
|
||||
for env_var, key in (("TRADINGAGENTS_MAX_DEBATE_ROUNDS", "max_debate_rounds"),
|
||||
("TRADINGAGENTS_MAX_RISK_ROUNDS", "max_risk_discuss_rounds")):
|
||||
if os.environ.get(env_var):
|
||||
# The depth prompt still appeared (it is skipped only when both are
|
||||
# set), so say which half of the answer the environment overrode.
|
||||
console.print(
|
||||
f"[green]✓ {key} from environment:[/green] {config[key]} "
|
||||
f"(set by {env_var}, so the research depth you chose does not apply to it)"
|
||||
)
|
||||
else:
|
||||
config[key] = selections["research_depth"]
|
||||
config["quick_think_llm"] = selections["quick_think_llm"]
|
||||
config["deep_think_llm"] = selections["deep_think_llm"]
|
||||
config["backend_url"] = selections["backend_url"]
|
||||
config["llm_provider"] = selections["llm_provider"].lower()
|
||||
# Provider-specific thinking configuration
|
||||
config["google_thinking_level"] = selections.get("google_thinking_level")
|
||||
config["openai_reasoning_effort"] = selections.get("openai_reasoning_effort")
|
||||
config["anthropic_effort"] = selections.get("anthropic_effort")
|
||||
config["output_language"] = selections.get("output_language", "English")
|
||||
# --checkpoint/--no-checkpoint overrides only when explicitly given; omitting
|
||||
# the flag preserves TRADINGAGENTS_CHECKPOINT_ENABLED / the default (#976).
|
||||
if checkpoint is not None:
|
||||
config["checkpoint_enabled"] = checkpoint
|
||||
return config
|
||||
|
||||
|
||||
def run_analysis(checkpoint: bool | None = None, portfolio=None):
|
||||
# First get all user selections
|
||||
selections = get_user_selections()
|
||||
|
||||
config = _build_run_config(selections, checkpoint)
|
||||
|
||||
stats_handler = StatsCallbackHandler()
|
||||
|
||||
# Normalize analyst selection to predefined order (selection is a 'set', order is fixed)
|
||||
selected_set = {analyst.value for analyst in selections["analysts"]}
|
||||
selected_analyst_keys = [a for a in ANALYST_ORDER if a in selected_set]
|
||||
analyst_execution_plan = build_analyst_execution_plan(selected_analyst_keys)
|
||||
analyst_wall_time_tracker = AnalystWallTimeTracker(analyst_execution_plan)
|
||||
|
||||
graph = TradingAgentsGraph(
|
||||
selected_analyst_keys,
|
||||
config=config,
|
||||
debug=True,
|
||||
callbacks=[stats_handler],
|
||||
)
|
||||
|
||||
message_buffer.init_for_analysis(selected_analyst_keys)
|
||||
|
||||
# Track start time for elapsed display
|
||||
start_time = time.time()
|
||||
|
||||
results_dir = _run_directory(config, selections["ticker"], selections["analysis_date"])
|
||||
results_dir.mkdir(parents=True, exist_ok=True)
|
||||
report_dir = results_dir / "reports"
|
||||
report_dir.mkdir(parents=True, exist_ok=True)
|
||||
log_file = results_dir / "message_tool.log"
|
||||
log_file.touch(exist_ok=True)
|
||||
|
||||
def save_message_decorator(obj, func_name):
|
||||
func = getattr(obj, func_name)
|
||||
|
||||
@wraps(func)
|
||||
def wrapper(*args, **kwargs):
|
||||
func(*args, **kwargs)
|
||||
timestamp, message_type, content = obj.messages[-1]
|
||||
content = content.replace("\n", " ") # Replace newlines with spaces
|
||||
with open(log_file, "a", encoding="utf-8") as f:
|
||||
f.write(f"{timestamp} [{message_type}] {content}\n")
|
||||
return wrapper
|
||||
|
||||
def save_tool_call_decorator(obj, func_name):
|
||||
func = getattr(obj, func_name)
|
||||
|
||||
@wraps(func)
|
||||
def wrapper(*args, **kwargs):
|
||||
func(*args, **kwargs)
|
||||
timestamp, tool_name, args = obj.tool_calls[-1]
|
||||
args_str = ", ".join(f"{k}={v}" for k, v in args.items())
|
||||
with open(log_file, "a", encoding="utf-8") as f:
|
||||
f.write(f"{timestamp} [Tool Call] {tool_name}({args_str})\n")
|
||||
return wrapper
|
||||
|
||||
def save_report_section_decorator(obj, func_name):
|
||||
func = getattr(obj, func_name)
|
||||
|
||||
@wraps(func)
|
||||
def wrapper(section_name, content):
|
||||
func(section_name, content)
|
||||
if section_name in obj.report_sections and obj.report_sections[section_name] is not None:
|
||||
content = obj.report_sections[section_name]
|
||||
if content:
|
||||
file_name = f"{section_name}.md"
|
||||
text = "\n".join(str(item) for item in content) if isinstance(content, list) else content
|
||||
with open(report_dir / file_name, "w", encoding="utf-8") as f:
|
||||
f.write(text)
|
||||
return wrapper
|
||||
|
||||
message_buffer.add_message = save_message_decorator(message_buffer, "add_message")
|
||||
message_buffer.add_tool_call = save_tool_call_decorator(message_buffer, "add_tool_call")
|
||||
message_buffer.update_report_section = save_report_section_decorator(message_buffer, "update_report_section")
|
||||
|
||||
layout = create_layout()
|
||||
|
||||
# The alternate screen keeps a layout taller than the window from redrawing
|
||||
# by scrolling; the final report prints after this block, on the normal screen.
|
||||
with Live(layout, refresh_per_second=4, screen=True):
|
||||
# Initial display
|
||||
update_display(layout, stats_handler=stats_handler, start_time=start_time)
|
||||
|
||||
message_buffer.add_message("System", f"Selected ticker: {selections['ticker']}")
|
||||
if selections["asset_type"] != "stock":
|
||||
message_buffer.add_message("System", f"Detected asset type: {selections['asset_type']}")
|
||||
message_buffer.add_message(
|
||||
"System", f"Analysis date: {selections['analysis_date']}"
|
||||
)
|
||||
message_buffer.add_message(
|
||||
"System",
|
||||
f"Selected analysts: {', '.join(analyst.value for analyst in selections['analysts'])}",
|
||||
)
|
||||
update_display(layout, stats_handler=stats_handler, start_time=start_time)
|
||||
|
||||
first_analyst = analyst_execution_plan.specs[0].agent_node
|
||||
message_buffer.update_agent_status(first_analyst, "in_progress")
|
||||
analyst_wall_time_tracker.mark_started(selected_analyst_keys[0])
|
||||
update_display(layout, stats_handler=stats_handler, start_time=start_time)
|
||||
|
||||
spinner_text = (
|
||||
f"Analyzing {selections['ticker']} on {selections['analysis_date']}..."
|
||||
)
|
||||
update_display(layout, spinner_text, stats_handler=stats_handler, start_time=start_time)
|
||||
|
||||
# The same initial state propagate() builds: settled decision log, past
|
||||
# context and resolved instrument identity.
|
||||
init_agent_state = graph.create_run_state(
|
||||
selections["ticker"], selections["analysis_date"], selections["asset_type"], portfolio
|
||||
)
|
||||
# Pass callbacks to graph config for tool execution tracking
|
||||
# (LLM tracking is handled separately via LLM constructor)
|
||||
args = graph.propagator.get_graph_args(callbacks=[stats_handler])
|
||||
|
||||
# Recompile with a checkpointer and inject the thread_id so --checkpoint
|
||||
# actually saves and resumes on the CLI path (#1249); a no-op when
|
||||
# checkpointing is disabled. Torn down in the finally below.
|
||||
checkpoint_tid = graph.begin_checkpoint(
|
||||
selections["ticker"], selections["analysis_date"], selections["asset_type"], portfolio
|
||||
)
|
||||
if checkpoint_tid is not None:
|
||||
args.setdefault("config", {}).setdefault("configurable", {})["thread_id"] = checkpoint_tid
|
||||
_announce_checkpoint_state(graph, selections["ticker"], selections["analysis_date"])
|
||||
|
||||
# Stream the analysis. On resume, feed None so LangGraph continues the
|
||||
# interrupted run instead of re-appending the initial state (#1249); the
|
||||
# try/finally tears the checkpointer down even if the stream raises.
|
||||
trace = []
|
||||
try:
|
||||
for chunk in graph.graph.stream(graph.checkpoint_input(init_agent_state), **args):
|
||||
for message in chunk.get("messages", []):
|
||||
msg_id = getattr(message, "id", None)
|
||||
if msg_id is not None:
|
||||
if msg_id in message_buffer._processed_message_ids:
|
||||
continue
|
||||
message_buffer._processed_message_ids.add(msg_id)
|
||||
|
||||
msg_type, content = classify_message_type(message)
|
||||
if content and content.strip():
|
||||
message_buffer.add_message(msg_type, content)
|
||||
|
||||
if hasattr(message, "tool_calls") and message.tool_calls:
|
||||
for tool_call in message.tool_calls:
|
||||
if isinstance(tool_call, dict):
|
||||
message_buffer.add_tool_call(tool_call["name"], tool_call["args"])
|
||||
else:
|
||||
message_buffer.add_tool_call(tool_call.name, tool_call.args)
|
||||
|
||||
update_analyst_statuses(
|
||||
message_buffer,
|
||||
chunk,
|
||||
wall_time_tracker=analyst_wall_time_tracker,
|
||||
)
|
||||
|
||||
# Research Team - Handle Investment Debate State
|
||||
if chunk.get("investment_debate_state"):
|
||||
debate_state = chunk["investment_debate_state"]
|
||||
bull_hist = debate_state.get("bull_history", "").strip()
|
||||
bear_hist = debate_state.get("bear_history", "").strip()
|
||||
judge = debate_state.get("judge_decision", "").strip()
|
||||
|
||||
# Only update status when there's actual content
|
||||
if bull_hist or bear_hist:
|
||||
update_research_team_status("in_progress")
|
||||
if bull_hist:
|
||||
message_buffer.update_report_section(
|
||||
"investment_plan", f"### Bull Researcher Analysis\n{bull_hist}"
|
||||
)
|
||||
if bear_hist:
|
||||
message_buffer.update_report_section(
|
||||
"investment_plan", f"### Bear Researcher Analysis\n{bear_hist}"
|
||||
)
|
||||
if judge:
|
||||
message_buffer.update_report_section(
|
||||
"investment_plan", f"### Research Manager Decision\n{judge}"
|
||||
)
|
||||
update_research_team_status("completed")
|
||||
message_buffer.update_agent_status("Trader", "in_progress")
|
||||
|
||||
# Trading Team
|
||||
if chunk.get("trader_investment_plan"):
|
||||
message_buffer.update_report_section(
|
||||
"trader_investment_plan", chunk["trader_investment_plan"]
|
||||
)
|
||||
if message_buffer.agent_status.get("Trader") != "completed":
|
||||
message_buffer.update_agent_status("Trader", "completed")
|
||||
message_buffer.update_agent_status("Aggressive Analyst", "in_progress")
|
||||
|
||||
# Risk Management Team - Handle Risk Debate State
|
||||
if chunk.get("risk_debate_state"):
|
||||
risk_state = chunk["risk_debate_state"]
|
||||
agg_hist = risk_state.get("aggressive_history", "").strip()
|
||||
con_hist = risk_state.get("conservative_history", "").strip()
|
||||
neu_hist = risk_state.get("neutral_history", "").strip()
|
||||
judge = risk_state.get("judge_decision", "").strip()
|
||||
|
||||
if agg_hist:
|
||||
if message_buffer.agent_status.get("Aggressive Analyst") != "completed":
|
||||
message_buffer.update_agent_status("Aggressive Analyst", "in_progress")
|
||||
message_buffer.update_report_section(
|
||||
"final_trade_decision", f"### Aggressive Analyst Analysis\n{agg_hist}"
|
||||
)
|
||||
if con_hist:
|
||||
if message_buffer.agent_status.get("Conservative Analyst") != "completed":
|
||||
message_buffer.update_agent_status("Conservative Analyst", "in_progress")
|
||||
message_buffer.update_report_section(
|
||||
"final_trade_decision", f"### Conservative Analyst Analysis\n{con_hist}"
|
||||
)
|
||||
if neu_hist:
|
||||
if message_buffer.agent_status.get("Neutral Analyst") != "completed":
|
||||
message_buffer.update_agent_status("Neutral Analyst", "in_progress")
|
||||
message_buffer.update_report_section(
|
||||
"final_trade_decision", f"### Neutral Analyst Analysis\n{neu_hist}"
|
||||
)
|
||||
if judge and message_buffer.agent_status.get("Portfolio Manager") != "completed":
|
||||
message_buffer.update_agent_status("Portfolio Manager", "in_progress")
|
||||
message_buffer.update_report_section(
|
||||
"final_trade_decision", f"### Portfolio Manager Decision\n{judge}"
|
||||
)
|
||||
message_buffer.update_agent_status("Aggressive Analyst", "completed")
|
||||
message_buffer.update_agent_status("Conservative Analyst", "completed")
|
||||
message_buffer.update_agent_status("Neutral Analyst", "completed")
|
||||
message_buffer.update_agent_status("Portfolio Manager", "completed")
|
||||
|
||||
update_display(layout, stats_handler=stats_handler, start_time=start_time)
|
||||
|
||||
trace.append(chunk)
|
||||
|
||||
# Streamed chunks are per-node deltas, not full state. Merge them
|
||||
# so every report field populated across the run is present.
|
||||
final_state = {}
|
||||
for chunk in trace:
|
||||
final_state.update(chunk)
|
||||
|
||||
# Clean run: log the decision, then drop this run's checkpoint so a
|
||||
# later run starts fresh. A mid-stream failure skips both, keeping
|
||||
# the checkpoint for resume.
|
||||
graph.record_decision(selections["ticker"], selections["analysis_date"], final_state)
|
||||
graph.clear_checkpoint_on_success(
|
||||
selections["ticker"], selections["analysis_date"], selections["asset_type"], portfolio
|
||||
)
|
||||
finally:
|
||||
# Always restore the plain uncheckpointed graph, even on failure.
|
||||
graph.end_checkpoint()
|
||||
|
||||
for agent in message_buffer.agent_status:
|
||||
message_buffer.update_agent_status(agent, "completed")
|
||||
|
||||
message_buffer.add_message(
|
||||
"System", f"Completed analysis for {selections['analysis_date']}"
|
||||
)
|
||||
message_buffer.add_message("System", analyst_wall_time_tracker.format_summary())
|
||||
|
||||
for section in message_buffer.report_sections:
|
||||
if section in final_state:
|
||||
message_buffer.update_report_section(section, final_state[section])
|
||||
|
||||
update_display(layout, stats_handler=stats_handler, start_time=start_time)
|
||||
|
||||
# Post-analysis prompts (outside Live context for clean interaction)
|
||||
console.print("\n[bold cyan]Analysis Complete![/bold cyan]\n")
|
||||
|
||||
# A decision nobody can read is not a position. Say so here rather than
|
||||
# leaving the run to look like a normal result.
|
||||
if is_review(graph.process_signal(final_state.get("final_trade_decision", ""))):
|
||||
console.print(
|
||||
"[yellow]No rating could be read from the final decision, so this run "
|
||||
"is recorded for review rather than as a position. Re-run, or read the "
|
||||
"decision text below and judge it yourself.[/yellow]\n"
|
||||
)
|
||||
console.print(f"[dim]{analyst_wall_time_tracker.format_summary()}[/dim]")
|
||||
|
||||
# Prompt to save report
|
||||
save_choice = typer.prompt("Save report?", default="Y").strip().upper()
|
||||
if save_choice in ("Y", "YES", ""):
|
||||
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
# Under results_dir, not the working directory: in Docker the working
|
||||
# directory is inside the container and the report goes with it, while
|
||||
# results_dir is the mounted volume the rest of the run already writes to.
|
||||
default_path = (Path(config["results_dir"]) / "reports"
|
||||
/ f"{safe_ticker_component(selections['ticker'])}_{timestamp}")
|
||||
save_path_str = typer.prompt(
|
||||
"Save path (press Enter for default)",
|
||||
default=str(default_path)
|
||||
).strip()
|
||||
save_path = Path(save_path_str)
|
||||
try:
|
||||
report_file = write_report_tree(final_state, selections["ticker"], save_path)
|
||||
console.print(f"\n[green]✓ Report saved to:[/green] {save_path.resolve()}")
|
||||
console.print(f" [dim]Complete report:[/dim] {report_file.name}")
|
||||
except Exception as e:
|
||||
console.print(f"[red]Error saving report: {e}[/red]")
|
||||
|
||||
# Prompt to display full report
|
||||
display_choice = typer.prompt("\nDisplay full report on screen?", default="Y").strip().upper()
|
||||
if display_choice in ("Y", "YES", ""):
|
||||
display_complete_report(final_state)
|
||||
@@ -0,0 +1,315 @@
|
||||
"""The interactive choices for a run: ticker, date, analysts, depth, provider and models."""
|
||||
|
||||
import datetime
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import typer
|
||||
from rich.align import Align
|
||||
from rich.panel import Panel
|
||||
|
||||
from cli.announcements import display_announcements, fetch_announcements
|
||||
from cli.display import (
|
||||
console,
|
||||
)
|
||||
from cli.prefs import load_last_run, sanitize, save_last_run
|
||||
from cli.prompts import (
|
||||
ask_anthropic_effort,
|
||||
ask_gemini_thinking_config,
|
||||
ask_glm_region,
|
||||
ask_minimax_region,
|
||||
ask_openai_reasoning_effort,
|
||||
ask_output_language,
|
||||
ask_qwen_region,
|
||||
confirm_ollama_endpoint,
|
||||
detect_asset_type,
|
||||
ensure_api_key,
|
||||
get_ticker,
|
||||
prompt_openai_compatible_url,
|
||||
resolve_backend_url,
|
||||
select_analysts,
|
||||
select_deep_thinking_agent,
|
||||
select_llm_provider,
|
||||
select_research_depth,
|
||||
select_shallow_thinking_agent,
|
||||
)
|
||||
from tradingagents.default_config import DEFAULT_CONFIG
|
||||
|
||||
|
||||
def get_user_selections():
|
||||
"""Ask for the run's settings, offering the previous run's answers."""
|
||||
selections = _prompt_selections(load_last_run())
|
||||
save_last_run(selections)
|
||||
return selections
|
||||
|
||||
|
||||
def _prompt_selections(prefs):
|
||||
"""Walk the selection steps. ``prefs`` prefills, the environment skips."""
|
||||
with open(Path(__file__).parent / "static" / "welcome.txt", encoding="utf-8") as f:
|
||||
welcome_ascii = f.read()
|
||||
|
||||
welcome_content = f"{welcome_ascii}\n"
|
||||
welcome_content += "[bold green]TradingAgents: Multi-Agents LLM Financial Trading Framework - CLI[/bold green]\n\n"
|
||||
welcome_content += "[bold]Workflow Steps:[/bold]\n"
|
||||
welcome_content += "I. Analyst Team → II. Research Team → III. Trader → IV. Risk Management → V. Portfolio Management\n\n"
|
||||
welcome_content += (
|
||||
"[dim]Built by [Tauric Research](https://github.com/TauricResearch)[/dim]"
|
||||
)
|
||||
|
||||
welcome_box = Panel(
|
||||
welcome_content,
|
||||
border_style="green",
|
||||
padding=(1, 2),
|
||||
title="Welcome to TradingAgents",
|
||||
subtitle="Multi-Agents LLM Financial Trading Framework",
|
||||
)
|
||||
console.print(Align.center(welcome_box))
|
||||
console.print()
|
||||
console.print() # Add vertical space before announcements
|
||||
|
||||
# Fetch and display announcements (silent on failure)
|
||||
announcements = fetch_announcements()
|
||||
display_announcements(console, announcements)
|
||||
|
||||
def create_question_box(title, prompt, default=None):
|
||||
box_content = f"[bold]{title}[/bold]\n"
|
||||
box_content += f"[dim]{prompt}[/dim]"
|
||||
if default:
|
||||
box_content += f"\n[dim]Default: {default}[/dim]"
|
||||
return Panel(box_content, border_style="blue", padding=(1, 2))
|
||||
|
||||
def thinking_value_or_prompt(env_var, config_key, label, box_title, box_body, prompt_fn):
|
||||
"""Return the env-configured reasoning/thinking value, or prompt for it.
|
||||
|
||||
When ``env_var`` is set the interactive choice is skipped and the value
|
||||
the env overlay placed on DEFAULT_CONFIG is used — mirroring the
|
||||
env-precedence rule applied to the other selection steps.
|
||||
"""
|
||||
if os.environ.get(env_var):
|
||||
value = DEFAULT_CONFIG[config_key]
|
||||
console.print(f"[green]✓ {label} from environment:[/green] {value}")
|
||||
return value
|
||||
console.print(create_question_box(box_title, box_body))
|
||||
return prompt_fn()
|
||||
|
||||
# Step 1: Ticker symbol
|
||||
console.print(
|
||||
create_question_box(
|
||||
"Step 1: Ticker Symbol",
|
||||
"Enter the ticker, with exchange suffix when needed (e.g. SPY, 0700.HK, BTC-USD)",
|
||||
"SPY",
|
||||
)
|
||||
)
|
||||
selected_ticker = get_ticker()
|
||||
asset_type = detect_asset_type(selected_ticker)
|
||||
# Only announce when it's not the default stock path, to avoid printing
|
||||
# "stock" on every run.
|
||||
if asset_type.value != "stock":
|
||||
console.print(
|
||||
f"[green]Detected asset type:[/green] {asset_type.value}"
|
||||
)
|
||||
|
||||
# Step 2: Analysis date
|
||||
default_date = datetime.datetime.now().strftime("%Y-%m-%d")
|
||||
console.print(
|
||||
create_question_box(
|
||||
"Step 2: Analysis Date",
|
||||
"Enter the analysis date (YYYY-MM-DD)",
|
||||
default_date,
|
||||
)
|
||||
)
|
||||
analysis_date = get_analysis_date()
|
||||
|
||||
# Step 3: Output language (skipped when set via TRADINGAGENTS_OUTPUT_LANGUAGE)
|
||||
if os.environ.get("TRADINGAGENTS_OUTPUT_LANGUAGE"):
|
||||
output_language = DEFAULT_CONFIG["output_language"]
|
||||
console.print(
|
||||
f"[green]✓ Output language from environment:[/green] {output_language}"
|
||||
)
|
||||
else:
|
||||
console.print(
|
||||
create_question_box(
|
||||
"Step 3: Output Language",
|
||||
"Select the language for analyst reports and final decision"
|
||||
)
|
||||
)
|
||||
output_language = ask_output_language(prefs.get("output_language"))
|
||||
|
||||
# Step 4: Select analysts
|
||||
console.print(
|
||||
create_question_box(
|
||||
"Step 4: Analysts Team", "Select your LLM analyst agents for the analysis"
|
||||
)
|
||||
)
|
||||
prefs = sanitize(prefs, asset_type.value)
|
||||
selected_analysts = select_analysts(asset_type, prefs.get("analysts"))
|
||||
console.print(
|
||||
f"[green]Selected analysts:[/green] {', '.join(analyst.value for analyst in selected_analysts)}"
|
||||
)
|
||||
|
||||
# Step 5: Research depth (skipped when both round counts are set via env).
|
||||
# Research depth maps to the debate + risk round counts; when both are
|
||||
# supplied through TRADINGAGENTS_MAX_DEBATE_ROUNDS / _MAX_RISK_ROUNDS we keep
|
||||
# the run non-interactive and honor the env values (#977).
|
||||
depth_from_env = bool(os.environ.get("TRADINGAGENTS_MAX_DEBATE_ROUNDS")) and bool(
|
||||
os.environ.get("TRADINGAGENTS_MAX_RISK_ROUNDS")
|
||||
)
|
||||
if depth_from_env:
|
||||
selected_research_depth = DEFAULT_CONFIG["max_debate_rounds"]
|
||||
console.print(
|
||||
f"[green]✓ Research depth from environment:[/green] "
|
||||
f"{DEFAULT_CONFIG['max_debate_rounds']} debate / "
|
||||
f"{DEFAULT_CONFIG['max_risk_discuss_rounds']} risk rounds"
|
||||
)
|
||||
else:
|
||||
console.print(
|
||||
create_question_box(
|
||||
"Step 5: Research Depth", "Select your research depth level"
|
||||
)
|
||||
)
|
||||
selected_research_depth = select_research_depth(prefs.get("research_depth"))
|
||||
|
||||
# Step 6: LLM Provider (skipped when set via TRADINGAGENTS_LLM_PROVIDER).
|
||||
# The backend URL comes from TRADINGAGENTS_LLM_BACKEND_URL when set,
|
||||
# otherwise the provider's default endpoint — the same value the menu
|
||||
# would have picked.
|
||||
provider_from_env = bool(os.environ.get("TRADINGAGENTS_LLM_PROVIDER"))
|
||||
if provider_from_env:
|
||||
selected_llm_provider = DEFAULT_CONFIG["llm_provider"].lower()
|
||||
backend_url = resolve_backend_url(
|
||||
selected_llm_provider, env_url=DEFAULT_CONFIG["backend_url"]
|
||||
)
|
||||
console.print(f"[green]✓ LLM provider from environment:[/green] {selected_llm_provider}")
|
||||
console.print(f"[green]✓ Backend URL:[/green] {backend_url}")
|
||||
# Still confirm/persist the API key so the run doesn't fail later.
|
||||
ensure_api_key(selected_llm_provider)
|
||||
else:
|
||||
console.print(
|
||||
create_question_box(
|
||||
"Step 6: LLM Provider", "Select your LLM provider"
|
||||
)
|
||||
)
|
||||
selected_llm_provider, backend_url = select_llm_provider(prefs.get("llm_provider"))
|
||||
|
||||
# Providers with regional endpoints prompt for the region as a secondary
|
||||
# step so the main dropdown stays clean (mainland China and international
|
||||
# accounts cannot share API keys).
|
||||
if selected_llm_provider == "qwen":
|
||||
selected_llm_provider, backend_url = ask_qwen_region()
|
||||
elif selected_llm_provider == "minimax":
|
||||
selected_llm_provider, backend_url = ask_minimax_region()
|
||||
elif selected_llm_provider == "glm":
|
||||
selected_llm_provider, backend_url = ask_glm_region()
|
||||
|
||||
# Honor an explicit env backend URL even when the provider was chosen
|
||||
# interactively, so it isn't overwritten by the menu default (#978).
|
||||
backend_url = resolve_backend_url(
|
||||
selected_llm_provider, backend_url, env_url=DEFAULT_CONFIG["backend_url"]
|
||||
)
|
||||
|
||||
# The generic OpenAI-compatible endpoint has no default; ask for it if
|
||||
# neither the menu nor the environment supplied one.
|
||||
if selected_llm_provider == "openai_compatible" and not backend_url:
|
||||
remembered_url = (prefs.get("backend_url")
|
||||
if prefs.get("llm_provider") == selected_llm_provider else None)
|
||||
backend_url = prompt_openai_compatible_url(remembered_url)
|
||||
|
||||
# For Ollama, surface the resolved endpoint (OLLAMA_BASE_URL vs default)
|
||||
# before model selection so it's obvious where we're connecting.
|
||||
if selected_llm_provider == "ollama":
|
||||
confirm_ollama_endpoint(backend_url)
|
||||
|
||||
# Confirm the provider's API key is present; prompt the user to paste
|
||||
# one and persist it to .env if it's missing, so the analysis run
|
||||
# doesn't fail later at the first API call.
|
||||
ensure_api_key(selected_llm_provider)
|
||||
|
||||
# Step 7: Thinking agents (skipped when either model is set via environment)
|
||||
if os.environ.get("TRADINGAGENTS_QUICK_THINK_LLM") or os.environ.get("TRADINGAGENTS_DEEP_THINK_LLM"):
|
||||
selected_shallow_thinker = DEFAULT_CONFIG["quick_think_llm"]
|
||||
selected_deep_thinker = DEFAULT_CONFIG["deep_think_llm"]
|
||||
console.print(
|
||||
f"[green]✓ Thinking agents from environment:[/green] "
|
||||
f"quick={selected_shallow_thinker}, deep={selected_deep_thinker}"
|
||||
)
|
||||
else:
|
||||
console.print(
|
||||
create_question_box(
|
||||
"Step 7: Thinking Agents", "Select your thinking agents for analysis"
|
||||
)
|
||||
)
|
||||
remembered = prefs if prefs.get("llm_provider") == selected_llm_provider else {}
|
||||
selected_shallow_thinker = select_shallow_thinking_agent(
|
||||
selected_llm_provider, remembered.get("quick_think_llm")
|
||||
)
|
||||
selected_deep_thinker = select_deep_thinking_agent(
|
||||
selected_llm_provider, remembered.get("deep_think_llm")
|
||||
)
|
||||
|
||||
# Step 8: Provider-specific reasoning/thinking configuration. Each knob is
|
||||
# settable via its TRADINGAGENTS_* env var; when that var is set (or the
|
||||
# provider itself came from env) the prompt is skipped and the configured
|
||||
# value is used — same env-precedence rule as the steps above. None = each
|
||||
# provider's own default.
|
||||
thinking_level = None
|
||||
reasoning_effort = None
|
||||
anthropic_effort = None
|
||||
|
||||
provider_lower = selected_llm_provider.lower()
|
||||
if provider_from_env:
|
||||
thinking_level = DEFAULT_CONFIG["google_thinking_level"]
|
||||
reasoning_effort = DEFAULT_CONFIG["openai_reasoning_effort"]
|
||||
anthropic_effort = DEFAULT_CONFIG["anthropic_effort"]
|
||||
elif provider_lower == "google":
|
||||
thinking_level = thinking_value_or_prompt(
|
||||
"TRADINGAGENTS_GOOGLE_THINKING_LEVEL", "google_thinking_level",
|
||||
"Gemini thinking mode", "Step 8: Thinking Mode",
|
||||
"Configure Gemini thinking mode", ask_gemini_thinking_config,
|
||||
)
|
||||
elif provider_lower == "openai":
|
||||
reasoning_effort = thinking_value_or_prompt(
|
||||
"TRADINGAGENTS_OPENAI_REASONING_EFFORT", "openai_reasoning_effort",
|
||||
"Reasoning effort", "Step 8: Reasoning Effort",
|
||||
"Configure OpenAI reasoning effort level", ask_openai_reasoning_effort,
|
||||
)
|
||||
elif provider_lower == "anthropic":
|
||||
anthropic_effort = thinking_value_or_prompt(
|
||||
"TRADINGAGENTS_ANTHROPIC_EFFORT", "anthropic_effort",
|
||||
"Claude effort", "Step 8: Effort Level",
|
||||
"Configure Claude effort level", ask_anthropic_effort,
|
||||
)
|
||||
|
||||
return {
|
||||
"ticker": selected_ticker,
|
||||
"asset_type": asset_type.value,
|
||||
"analysis_date": analysis_date,
|
||||
"analysts": selected_analysts,
|
||||
"research_depth": selected_research_depth,
|
||||
"llm_provider": selected_llm_provider.lower(),
|
||||
"backend_url": backend_url,
|
||||
"quick_think_llm": selected_shallow_thinker,
|
||||
"deep_think_llm": selected_deep_thinker,
|
||||
"google_thinking_level": thinking_level,
|
||||
"openai_reasoning_effort": reasoning_effort,
|
||||
"anthropic_effort": anthropic_effort,
|
||||
"output_language": output_language,
|
||||
}
|
||||
|
||||
|
||||
def get_analysis_date():
|
||||
"""Get the analysis date from user input."""
|
||||
while True:
|
||||
date_str = typer.prompt(
|
||||
"", default=datetime.datetime.now().strftime("%Y-%m-%d")
|
||||
)
|
||||
try:
|
||||
# Validate date format and ensure it's not in the future
|
||||
analysis_date = datetime.datetime.strptime(date_str, "%Y-%m-%d")
|
||||
if analysis_date.date() > datetime.datetime.now().date():
|
||||
console.print("[red]Error: Analysis date cannot be in the future[/red]")
|
||||
continue
|
||||
return date_str
|
||||
except ValueError:
|
||||
console.print(
|
||||
"[red]Error: Invalid date format. Please use YYYY-MM-DD[/red]"
|
||||
)
|
||||
+2
-2
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "tradingagents"
|
||||
version = "0.5.0"
|
||||
version = "0.5.1"
|
||||
description = "TradingAgents: Multi-Agents LLM Financial Trading Framework"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.10"
|
||||
@@ -78,5 +78,5 @@ ignore = ["E501"]
|
||||
|
||||
[tool.ruff.lint.isort]
|
||||
# Keep multiple aliased names from one module in a single combined import block
|
||||
# (e.g. the vendor re-exports in interface.py) instead of one statement per name.
|
||||
# (e.g. the vendor imports in router.py) instead of one statement per name.
|
||||
combine-as-imports = true
|
||||
|
||||
+35
-12
@@ -1,16 +1,50 @@
|
||||
"""Shared pytest fixtures that prevent CI hangs when API keys are absent."""
|
||||
|
||||
import os
|
||||
from unittest.mock import MagicMock, patch
|
||||
import socket
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def _blank_settings_overlay():
|
||||
"""Blank every TRADINGAGENTS_* setting before the package is imported.
|
||||
|
||||
The package loads .env on import and folds these variables into
|
||||
DEFAULT_CONFIG, so a contributor's own settings would become the defaults
|
||||
the suite asserts on. A blank value is still present, so load_dotenv leaves
|
||||
it alone, and the overlay reads it as unset. Tests of the overlay set their own.
|
||||
"""
|
||||
from dotenv import dotenv_values, find_dotenv
|
||||
|
||||
names = set(os.environ)
|
||||
for filename in (".env", ".env.enterprise"):
|
||||
names |= set(dotenv_values(find_dotenv(filename, usecwd=True)))
|
||||
for name in names:
|
||||
if name.startswith("TRADINGAGENTS_"):
|
||||
os.environ[name] = ""
|
||||
|
||||
|
||||
_blank_settings_overlay()
|
||||
|
||||
|
||||
def pytest_configure(config):
|
||||
for marker in ("unit", "integration", "smoke"):
|
||||
config.addinivalue_line("markers", f"{marker}: {marker}-level tests")
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _no_network(request, monkeypatch):
|
||||
"""Tests do not reach the network; one that must is marked integration."""
|
||||
if request.node.get_closest_marker("integration"):
|
||||
return
|
||||
|
||||
def refuse(self, address):
|
||||
raise OSError(f"test tried to reach the network: {address}")
|
||||
|
||||
monkeypatch.setattr(socket.socket, "connect", refuse)
|
||||
monkeypatch.setattr(socket.socket, "connect_ex", refuse)
|
||||
|
||||
|
||||
_API_KEY_ENV_VARS = (
|
||||
"OPENAI_API_KEY",
|
||||
"GOOGLE_API_KEY",
|
||||
@@ -54,14 +88,3 @@ def _isolate_config():
|
||||
config_module._config = copy.deepcopy(default_config.DEFAULT_CONFIG)
|
||||
yield
|
||||
config_module._config = copy.deepcopy(default_config.DEFAULT_CONFIG)
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def mock_llm_client():
|
||||
client = MagicMock()
|
||||
client.get_llm.return_value = MagicMock()
|
||||
with patch(
|
||||
"tradingagents.llm_clients.factory.create_llm_client",
|
||||
return_value=client,
|
||||
):
|
||||
yield client
|
||||
|
||||
@@ -10,10 +10,10 @@ import json
|
||||
|
||||
import pytest
|
||||
|
||||
import tradingagents.dataflows.alpha_vantage_common as av
|
||||
import tradingagents.dataflows.alpha_vantage_fundamentals as avf
|
||||
import tradingagents.dataflows.alpha_vantage_stock as avs
|
||||
import tradingagents.dataflows.utils as utils
|
||||
import tradingagents.dataflows.net as net
|
||||
import tradingagents.dataflows.vendors.alpha_vantage.common as av
|
||||
import tradingagents.dataflows.vendors.alpha_vantage.fundamentals as avf
|
||||
import tradingagents.dataflows.vendors.alpha_vantage.stock as avs
|
||||
|
||||
|
||||
class _FakeResponse:
|
||||
@@ -37,7 +37,7 @@ def _patched_get(body, capture=None):
|
||||
@pytest.mark.unit
|
||||
def test_request_passes_timeout(monkeypatch):
|
||||
captured = {}
|
||||
monkeypatch.setattr(utils.requests, "get", _patched_get("Date,Close\n2025-01-02,1.0", captured))
|
||||
monkeypatch.setattr(net.requests, "get", _patched_get("Date,Close\n2025-01-02,1.0", captured))
|
||||
av._make_api_request("TIME_SERIES_DAILY", {"symbol": "AAPL"})
|
||||
assert captured.get("timeout") == av.REQUEST_TIMEOUT # #990
|
||||
|
||||
@@ -45,7 +45,7 @@ def test_request_passes_timeout(monkeypatch):
|
||||
@pytest.mark.unit
|
||||
def test_rate_limit_detected(monkeypatch):
|
||||
body = '{"Information": "Our standard API rate limit is 25 requests per day. ... your API key ..."}'
|
||||
monkeypatch.setattr(utils.requests, "get", _patched_get(body))
|
||||
monkeypatch.setattr(net.requests, "get", _patched_get(body))
|
||||
with pytest.raises(av.AlphaVantageRateLimitError):
|
||||
av._make_api_request("TIME_SERIES_DAILY", {"symbol": "AAPL"})
|
||||
|
||||
@@ -56,11 +56,11 @@ def test_invalid_key_not_mislabeled_as_rate_limit(monkeypatch):
|
||||
# (transient) rate limit, but surface as a real configuration error (#991).
|
||||
body = ('{"Information": "the parameter apikey is invalid or missing. '
|
||||
'Please claim your free API key on (https://www.alphavantage.co/support/#api-key)."}')
|
||||
monkeypatch.setattr(utils.requests, "get", _patched_get(body))
|
||||
monkeypatch.setattr(net.requests, "get", _patched_get(body))
|
||||
with pytest.raises(av.AlphaVantageNotConfiguredError):
|
||||
av._make_api_request("TIME_SERIES_DAILY", {"symbol": "AAPL"})
|
||||
with pytest.raises(av.AlphaVantageRateLimitError): # sanity: rate-limit path still distinct
|
||||
monkeypatch.setattr(utils.requests, "get", _patched_get('{"Note": "API call frequency is 5 calls per minute."}'))
|
||||
monkeypatch.setattr(net.requests, "get", _patched_get('{"Note": "API call frequency is 5 calls per minute."}'))
|
||||
av._make_api_request("TIME_SERIES_DAILY", {"symbol": "AAPL"})
|
||||
|
||||
|
||||
@@ -147,7 +147,7 @@ def test_request_error_message_carries_no_key(monkeypatch):
|
||||
def boom(*a, **k):
|
||||
raise requests.Timeout(f"Read timed out. url: https://www.alphavantage.co/query?apikey={key}")
|
||||
|
||||
monkeypatch.setattr(utils.requests, "get", boom)
|
||||
monkeypatch.setattr(net.requests, "get", boom)
|
||||
with pytest.raises(requests.Timeout) as caught:
|
||||
av._make_api_request("OVERVIEW", {"symbol": "IBM"})
|
||||
assert key not in str(caught.value)
|
||||
@@ -156,7 +156,7 @@ def test_request_error_message_carries_no_key(monkeypatch):
|
||||
@pytest.mark.unit
|
||||
def test_global_news_omitted_optionals_use_the_configured_defaults(monkeypatch):
|
||||
"""The tool passes None for an omitted look_back_days or limit (#1326)."""
|
||||
from tradingagents.dataflows import alpha_vantage_news
|
||||
from tradingagents.dataflows.vendors.alpha_vantage import news as alpha_vantage_news
|
||||
|
||||
monkeypatch.setattr(alpha_vantage_news, "get_config",
|
||||
lambda: {"global_news_lookback_days": 3, "global_news_article_limit": 9})
|
||||
@@ -173,7 +173,7 @@ def test_the_news_window_includes_the_analysis_day(monkeypatch):
|
||||
"""time_to was midnight at the start of the end date, so everything
|
||||
published during the analysis day, the most decision-relevant day, was
|
||||
excluded. The yfinance path includes it."""
|
||||
from tradingagents.dataflows import alpha_vantage_news
|
||||
from tradingagents.dataflows.vendors.alpha_vantage import news as alpha_vantage_news
|
||||
|
||||
seen = {}
|
||||
monkeypatch.setattr(alpha_vantage_news, "_make_api_request",
|
||||
@@ -190,8 +190,8 @@ def test_the_news_window_includes_the_analysis_day(monkeypatch):
|
||||
def test_an_indicator_this_vendor_lacks_lets_the_next_one_serve_it(indicator):
|
||||
"""Returning prose counts as success to the router, so the chain stops at a
|
||||
vendor that cannot compute the indicator while the next one can."""
|
||||
from tradingagents.dataflows import alpha_vantage_indicator
|
||||
from tradingagents.dataflows.errors import VendorError
|
||||
from tradingagents.dataflows.vendors.alpha_vantage import indicator as alpha_vantage_indicator
|
||||
|
||||
with pytest.raises(VendorError):
|
||||
alpha_vantage_indicator.get_indicator("AAPL", indicator, "2026-05-08", 30)
|
||||
@@ -201,7 +201,7 @@ def test_an_indicator_this_vendor_lacks_lets_the_next_one_serve_it(indicator):
|
||||
def test_ticker_news_asks_for_only_as_many_articles_as_configured(monkeypatch):
|
||||
"""The endpoint returns 50 articles with per-article sentiment arrays by
|
||||
default, and the whole payload went into the prompt."""
|
||||
from tradingagents.dataflows import alpha_vantage_news
|
||||
from tradingagents.dataflows.vendors.alpha_vantage import news as alpha_vantage_news
|
||||
|
||||
monkeypatch.setattr(alpha_vantage_news, "get_config", lambda: {"news_article_limit": 8})
|
||||
seen = {}
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
import unittest
|
||||
|
||||
from tradingagents.graph.analyst_execution import (
|
||||
AnalystWallTimeTracker,
|
||||
build_analyst_execution_plan,
|
||||
get_initial_analyst_node,
|
||||
sync_analyst_tracker_from_chunk,
|
||||
)
|
||||
|
||||
|
||||
@@ -21,14 +18,6 @@ class AnalystExecutionPlanTests(unittest.TestCase):
|
||||
with self.assertRaises(ValueError):
|
||||
build_analyst_execution_plan(["market", "macro"])
|
||||
|
||||
def test_get_initial_analyst_node_uses_plan_metadata(self):
|
||||
plan = build_analyst_execution_plan(["fundamentals", "news"])
|
||||
|
||||
self.assertEqual(
|
||||
get_initial_analyst_node(plan),
|
||||
"Fundamentals Analyst",
|
||||
)
|
||||
|
||||
def test_social_key_displays_as_sentiment_analyst(self):
|
||||
# The wire key stays "social" for saved-config back-compat, but the
|
||||
# user-visible agent_node label must match the v0.2.5 rename so the
|
||||
@@ -39,52 +28,3 @@ class AnalystExecutionPlanTests(unittest.TestCase):
|
||||
self.assertEqual(spec.key, "social")
|
||||
self.assertEqual(spec.agent_node, "Sentiment Analyst")
|
||||
self.assertEqual(spec.report_key, "sentiment_report")
|
||||
|
||||
|
||||
class AnalystWallTimeTrackerTests(unittest.TestCase):
|
||||
def test_records_wall_time_when_analyst_completes(self):
|
||||
plan = build_analyst_execution_plan(["market", "news"])
|
||||
tracker = AnalystWallTimeTracker(plan)
|
||||
|
||||
tracker.mark_started("market", started_at=10.0)
|
||||
tracker.mark_completed("market", completed_at=13.5)
|
||||
|
||||
self.assertEqual(tracker.get_wall_times(), {"market": 3.5})
|
||||
|
||||
def test_formats_summary_in_plan_order(self):
|
||||
plan = build_analyst_execution_plan(["news", "market"])
|
||||
tracker = AnalystWallTimeTracker(plan)
|
||||
|
||||
tracker.mark_started("market", started_at=20.0)
|
||||
tracker.mark_completed("market", completed_at=22.25)
|
||||
tracker.mark_started("news", started_at=10.0)
|
||||
tracker.mark_completed("news", completed_at=14.0)
|
||||
|
||||
self.assertEqual(
|
||||
tracker.format_summary(),
|
||||
"Analyst wall time: News 4.00s | Market 2.25s",
|
||||
)
|
||||
|
||||
def test_syncs_wall_time_from_sequential_chunks(self):
|
||||
plan = build_analyst_execution_plan(["market", "news"])
|
||||
tracker = AnalystWallTimeTracker(plan)
|
||||
|
||||
sync_analyst_tracker_from_chunk(tracker, {}, now=10.0)
|
||||
self.assertEqual(tracker.get_wall_times(), {})
|
||||
|
||||
sync_analyst_tracker_from_chunk(
|
||||
tracker,
|
||||
{"market_report": "done"},
|
||||
now=13.0,
|
||||
)
|
||||
self.assertEqual(tracker.get_wall_times(), {"market": 3.0})
|
||||
|
||||
sync_analyst_tracker_from_chunk(
|
||||
tracker,
|
||||
{"market_report": "done", "news_report": "done"},
|
||||
now=18.0,
|
||||
)
|
||||
self.assertEqual(
|
||||
tracker.get_wall_times(),
|
||||
{"market": 3.0, "news": 5.0},
|
||||
)
|
||||
|
||||
@@ -60,7 +60,8 @@ class TestEffortGate:
|
||||
@pytest.mark.parametrize(
|
||||
"model",
|
||||
# Claude 5 family uses single-number version IDs; all are effort-capable.
|
||||
["claude-sonnet-5", "claude-fable-5", "claude-mythos-5", "claude-opus-5", "claude-fable-5-1"],
|
||||
["claude-sonnet-5", "claude-fable-5", "claude-mythos-5", "claude-opus-5", "claude-opus-5-5",
|
||||
"claude-fable-5-1"],
|
||||
)
|
||||
def test_claude_5_family_receives_effort(self, monkeypatch, model):
|
||||
captured = _capture_kwargs(monkeypatch)
|
||||
|
||||
+32
-33
@@ -15,7 +15,7 @@ from tradingagents.llm_clients.api_key_env import PROVIDER_API_KEY_ENV, get_api_
|
||||
|
||||
def test_every_select_llm_provider_choice_has_an_entry():
|
||||
"""select_llm_provider() must not present a provider the mapping doesn't know about."""
|
||||
# Mirrors the dropdown order in cli/utils.select_llm_provider so the two
|
||||
# Mirrors the dropdown order in cli/prompts.select_llm_provider so the two
|
||||
# stay in lockstep. Region-specific keys (qwen-cn / minimax-cn / glm-cn)
|
||||
# are reached via the secondary region prompt, so they must also be present.
|
||||
expected = {
|
||||
@@ -67,44 +67,44 @@ def test_case_insensitive_lookup():
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cli_utils(monkeypatch):
|
||||
"""Import cli.utils with a fresh environment so module-level state is consistent."""
|
||||
def prompts(monkeypatch):
|
||||
"""Import cli.prompts with a fresh environment so module-level state is consistent."""
|
||||
import importlib
|
||||
|
||||
import cli.utils as cli_utils_module
|
||||
return importlib.reload(cli_utils_module)
|
||||
import cli.prompts as prompts_module
|
||||
return importlib.reload(prompts_module)
|
||||
|
||||
|
||||
def test_ensure_api_key_returns_existing(monkeypatch, cli_utils):
|
||||
def test_ensure_api_key_returns_existing(monkeypatch, prompts):
|
||||
monkeypatch.setenv("OPENAI_API_KEY", "sk-already-set")
|
||||
result = cli_utils.ensure_api_key("openai")
|
||||
result = prompts.ensure_api_key("openai")
|
||||
assert result == "sk-already-set"
|
||||
|
||||
|
||||
def test_ensure_api_key_no_op_for_ollama(monkeypatch, cli_utils):
|
||||
def test_ensure_api_key_no_op_for_ollama(monkeypatch, prompts):
|
||||
# Even with no env var set, ollama should not prompt and should return None.
|
||||
monkeypatch.delenv("OPENAI_API_KEY", raising=False)
|
||||
with patch.object(cli_utils, "questionary") as mock_q:
|
||||
result = cli_utils.ensure_api_key("ollama")
|
||||
with patch.object(prompts, "questionary") as mock_q:
|
||||
result = prompts.ensure_api_key("ollama")
|
||||
assert result is None
|
||||
mock_q.password.assert_not_called()
|
||||
|
||||
|
||||
def test_ensure_api_key_unknown_provider_no_prompt(monkeypatch, cli_utils):
|
||||
with patch.object(cli_utils, "questionary") as mock_q:
|
||||
result = cli_utils.ensure_api_key("totally-fake-provider")
|
||||
def test_ensure_api_key_unknown_provider_no_prompt(monkeypatch, prompts):
|
||||
with patch.object(prompts, "questionary") as mock_q:
|
||||
result = prompts.ensure_api_key("totally-fake-provider")
|
||||
assert result is None
|
||||
mock_q.password.assert_not_called()
|
||||
|
||||
|
||||
def test_ensure_api_key_prompts_and_writes_to_env(monkeypatch, tmp_path, cli_utils):
|
||||
def test_ensure_api_key_prompts_and_writes_to_env(monkeypatch, tmp_path, prompts):
|
||||
"""When key is missing, user-pasted value must be written to .env AND os.environ."""
|
||||
monkeypatch.delenv("DEEPSEEK_API_KEY", raising=False)
|
||||
monkeypatch.chdir(tmp_path)
|
||||
|
||||
fake_prompt = type("P", (), {"ask": staticmethod(lambda: "sk-deepseek-test")})()
|
||||
with patch.object(cli_utils.questionary, "password", return_value=fake_prompt):
|
||||
result = cli_utils.ensure_api_key("deepseek")
|
||||
with patch.object(prompts.questionary, "password", return_value=fake_prompt):
|
||||
result = prompts.ensure_api_key("deepseek")
|
||||
|
||||
assert result == "sk-deepseek-test"
|
||||
assert os.environ["DEEPSEEK_API_KEY"] == "sk-deepseek-test"
|
||||
@@ -114,14 +114,14 @@ def test_ensure_api_key_prompts_and_writes_to_env(monkeypatch, tmp_path, cli_uti
|
||||
assert "sk-deepseek-test" in env_file.read_text()
|
||||
|
||||
|
||||
def test_ensure_api_key_user_cancels_returns_none(monkeypatch, tmp_path, cli_utils):
|
||||
def test_ensure_api_key_user_cancels_returns_none(monkeypatch, tmp_path, prompts):
|
||||
"""Empty prompt response (user cancelled) must not write to .env."""
|
||||
monkeypatch.delenv("XAI_API_KEY", raising=False)
|
||||
monkeypatch.chdir(tmp_path)
|
||||
|
||||
fake_prompt = type("P", (), {"ask": staticmethod(lambda: None)})()
|
||||
with patch.object(cli_utils.questionary, "password", return_value=fake_prompt):
|
||||
result = cli_utils.ensure_api_key("xai")
|
||||
with patch.object(prompts.questionary, "password", return_value=fake_prompt):
|
||||
result = prompts.ensure_api_key("xai")
|
||||
|
||||
assert result is None
|
||||
assert "XAI_API_KEY" not in os.environ
|
||||
@@ -132,7 +132,7 @@ def test_ensure_api_key_user_cancels_returns_none(monkeypatch, tmp_path, cli_uti
|
||||
assert "XAI_API_KEY" not in env_file.read_text()
|
||||
|
||||
|
||||
def test_ensure_api_key_updates_existing_env_file(monkeypatch, tmp_path, cli_utils):
|
||||
def test_ensure_api_key_updates_existing_env_file(monkeypatch, tmp_path, prompts):
|
||||
"""An existing .env with other keys must be preserved on writeback."""
|
||||
monkeypatch.delenv("OPENROUTER_API_KEY", raising=False)
|
||||
monkeypatch.chdir(tmp_path)
|
||||
@@ -140,8 +140,8 @@ def test_ensure_api_key_updates_existing_env_file(monkeypatch, tmp_path, cli_uti
|
||||
env_file.write_text("OPENAI_API_KEY=sk-existing\nOTHER=value\n")
|
||||
|
||||
fake_prompt = type("P", (), {"ask": staticmethod(lambda: "sk-openrouter-new")})()
|
||||
with patch.object(cli_utils.questionary, "password", return_value=fake_prompt):
|
||||
cli_utils.ensure_api_key("openrouter")
|
||||
with patch.object(prompts.questionary, "password", return_value=fake_prompt):
|
||||
prompts.ensure_api_key("openrouter")
|
||||
|
||||
content = env_file.read_text()
|
||||
assert "OPENAI_API_KEY" in content and "sk-existing" in content
|
||||
@@ -149,22 +149,22 @@ def test_ensure_api_key_updates_existing_env_file(monkeypatch, tmp_path, cli_uti
|
||||
assert "OPENROUTER_API_KEY" in content and "sk-openrouter-new" in content
|
||||
|
||||
|
||||
def _prompt_key(cli_utils, monkeypatch, tmp_path, key="sk-typed-in"):
|
||||
def _prompt_key(prompts, monkeypatch, tmp_path, key="sk-typed-in"):
|
||||
monkeypatch.chdir(tmp_path)
|
||||
monkeypatch.delenv("OPENAI_API_KEY", raising=False)
|
||||
monkeypatch.setattr(cli_utils, "find_dotenv", lambda **k: "")
|
||||
with patch.object(cli_utils, "questionary") as mock_q:
|
||||
monkeypatch.setattr(prompts, "find_dotenv", lambda **k: "")
|
||||
with patch.object(prompts, "questionary") as mock_q:
|
||||
mock_q.password.return_value.ask.return_value = key
|
||||
cli_utils.ensure_api_key("openai")
|
||||
prompts.ensure_api_key("openai")
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name == "nt", reason="POSIX file modes")
|
||||
def test_saved_key_file_is_owner_only(monkeypatch, cli_utils, tmp_path):
|
||||
def test_saved_key_file_is_owner_only(monkeypatch, prompts, tmp_path):
|
||||
# The prompt writes a real credential; the file must not be readable by
|
||||
# other local users whatever the umask is.
|
||||
old = os.umask(0o002)
|
||||
try:
|
||||
_prompt_key(cli_utils, monkeypatch, tmp_path)
|
||||
_prompt_key(prompts, monkeypatch, tmp_path)
|
||||
finally:
|
||||
os.umask(old)
|
||||
env = tmp_path / ".env"
|
||||
@@ -173,21 +173,20 @@ def test_saved_key_file_is_owner_only(monkeypatch, cli_utils, tmp_path):
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name == "nt", reason="POSIX file modes")
|
||||
def test_existing_key_file_is_tightened_before_writing(monkeypatch, cli_utils, tmp_path):
|
||||
def test_existing_key_file_is_tightened_before_writing(monkeypatch, prompts, tmp_path):
|
||||
env = tmp_path / ".env"
|
||||
env.write_text("OTHER=1\n")
|
||||
os.chmod(env, 0o664)
|
||||
_prompt_key(cli_utils, monkeypatch, tmp_path)
|
||||
_prompt_key(prompts, monkeypatch, tmp_path)
|
||||
assert stat.S_IMODE(env.stat().st_mode) == 0o600
|
||||
assert "OTHER=1" in env.read_text()
|
||||
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name == "nt", reason="POSIX file modes")
|
||||
def test_read_only_key_file_is_still_updated(monkeypatch, cli_utils, tmp_path):
|
||||
def test_read_only_key_file_is_still_updated(monkeypatch, prompts, tmp_path):
|
||||
env = tmp_path / ".env"
|
||||
env.write_text("OTHER=1\n")
|
||||
os.chmod(env, 0o400)
|
||||
_prompt_key(cli_utils, monkeypatch, tmp_path)
|
||||
_prompt_key(prompts, monkeypatch, tmp_path)
|
||||
assert "sk-typed-in" in env.read_text()
|
||||
assert stat.S_IMODE(env.stat().st_mode) == 0o600
|
||||
|
||||
+31
-3
@@ -10,8 +10,8 @@ from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from tradingagents.agents.utils.memory import TradingMemoryLog
|
||||
from tradingagents.backtest import iter_grid, run_backtest, summarize
|
||||
from tradingagents.decision_log import TradingMemoryLog
|
||||
|
||||
DECISION = "Rating: Buy\n\nbuy it"
|
||||
|
||||
@@ -120,7 +120,7 @@ def _log_with(tmp_path, rows):
|
||||
log.store_decision(ticker, date, decision)
|
||||
if outcome is not None:
|
||||
log.update_with_outcome(ticker, date, outcome[0], outcome[1], 5, "note", "2026-02-01")
|
||||
return log
|
||||
return tmp_path / "m.md"
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@@ -245,4 +245,32 @@ def test_the_window_reported_is_the_one_the_outcomes_used(tmp_path):
|
||||
log.store_decision("NVDA", "2026-01-05", "**Rating**: Buy\n\nx")
|
||||
log.update_with_outcome("NVDA", "2026-01-05", 0.1, 0.04, 21, "note", "2026-02-01")
|
||||
|
||||
assert "21 trading days" in summarize(log).render()
|
||||
assert "21 trading days" in summarize(tmp_path / "m.md").render()
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_a_backtest_result_is_summarized_directly(tmp_path):
|
||||
"""The result names its own log, so a caller never builds the log to score it."""
|
||||
from tradingagents.backtest import BacktestResult
|
||||
|
||||
path = _log_with(tmp_path, [("NVDA", "2026-01-05", "Rating: Buy\n\nx", (0.10, 0.04))])
|
||||
|
||||
assert summarize(BacktestResult(run_id="r", log_path=path)).resolved == 1
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_a_log_path_that_does_not_exist_is_an_error_not_an_empty_summary(tmp_path):
|
||||
missing = tmp_path / "no-such-dir" / "m.md"
|
||||
|
||||
with pytest.raises(FileNotFoundError):
|
||||
summarize(missing)
|
||||
assert not missing.parent.exists()
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_a_result_whose_cells_all_failed_summarizes_as_empty(tmp_path):
|
||||
from tradingagents.backtest import BacktestResult
|
||||
|
||||
result = BacktestResult(run_id="r", log_path=tmp_path / "never-written.md")
|
||||
|
||||
assert summarize(result).resolved == 0
|
||||
|
||||
@@ -58,8 +58,6 @@ def _bare_graph(tmpdir, *, enabled=True):
|
||||
return g
|
||||
|
||||
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_disabled_is_a_noop():
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
|
||||
@@ -10,7 +10,6 @@ from tradingagents.graph.checkpointer import (
|
||||
checkpoint_step,
|
||||
clear_checkpoint,
|
||||
get_checkpointer,
|
||||
has_checkpoint,
|
||||
thread_id,
|
||||
)
|
||||
|
||||
@@ -63,7 +62,7 @@ class TestCheckpointResume(unittest.TestCase):
|
||||
graph.invoke({"count": 0}, config=cfg)
|
||||
|
||||
# Checkpoint should exist at step 1 (analyst completed)
|
||||
self.assertTrue(has_checkpoint(self.tmpdir, self.ticker, self.date))
|
||||
self.assertIsNotNone(checkpoint_step(self.tmpdir, self.ticker, self.date))
|
||||
step = checkpoint_step(self.tmpdir, self.ticker, self.date)
|
||||
self.assertEqual(step, 1)
|
||||
|
||||
@@ -90,11 +89,11 @@ class TestCheckpointResume(unittest.TestCase):
|
||||
with self.assertRaises(RuntimeError):
|
||||
graph.invoke({"count": 0}, config=cfg)
|
||||
|
||||
self.assertTrue(has_checkpoint(self.tmpdir, self.ticker, self.date))
|
||||
self.assertIsNotNone(checkpoint_step(self.tmpdir, self.ticker, self.date))
|
||||
|
||||
# Clear it
|
||||
clear_checkpoint(self.tmpdir, self.ticker, self.date)
|
||||
self.assertFalse(has_checkpoint(self.tmpdir, self.ticker, self.date))
|
||||
self.assertIsNone(checkpoint_step(self.tmpdir, self.ticker, self.date))
|
||||
|
||||
# Fresh run succeeds from scratch
|
||||
_should_crash = False
|
||||
@@ -104,7 +103,6 @@ class TestCheckpointResume(unittest.TestCase):
|
||||
|
||||
self.assertEqual(result["count"], 11)
|
||||
|
||||
|
||||
def test_different_date_starts_fresh(self):
|
||||
"""A different date must NOT resume from an existing checkpoint."""
|
||||
global _should_crash
|
||||
@@ -119,10 +117,10 @@ class TestCheckpointResume(unittest.TestCase):
|
||||
with self.assertRaises(RuntimeError):
|
||||
graph.invoke({"count": 0}, config={"configurable": {"thread_id": tid1}})
|
||||
|
||||
self.assertTrue(has_checkpoint(self.tmpdir, self.ticker, self.date))
|
||||
self.assertIsNotNone(checkpoint_step(self.tmpdir, self.ticker, self.date))
|
||||
|
||||
# date2 should have no checkpoint
|
||||
self.assertFalse(has_checkpoint(self.tmpdir, self.ticker, date2))
|
||||
self.assertIsNone(checkpoint_step(self.tmpdir, self.ticker, date2))
|
||||
|
||||
# Run with date2 — should start fresh and succeed
|
||||
_should_crash = False
|
||||
@@ -137,7 +135,7 @@ class TestCheckpointResume(unittest.TestCase):
|
||||
self.assertEqual(result["count"], 11)
|
||||
|
||||
# Original date checkpoint still exists (untouched)
|
||||
self.assertTrue(has_checkpoint(self.tmpdir, self.ticker, self.date))
|
||||
self.assertIsNotNone(checkpoint_step(self.tmpdir, self.ticker, self.date))
|
||||
|
||||
|
||||
class TestCheckpointSignature(unittest.TestCase):
|
||||
@@ -178,9 +176,9 @@ class TestCheckpointSignature(unittest.TestCase):
|
||||
with self.assertRaises(RuntimeError):
|
||||
graph.invoke({"count": 0}, config={"configurable": {"thread_id": tid1}})
|
||||
|
||||
self.assertTrue(has_checkpoint(self.tmpdir, self.ticker, self.date, sig1))
|
||||
self.assertIsNotNone(checkpoint_step(self.tmpdir, self.ticker, self.date, sig1))
|
||||
# A different graph shape has no checkpoint to resume from.
|
||||
self.assertFalse(has_checkpoint(self.tmpdir, self.ticker, self.date, sig2))
|
||||
self.assertIsNone(checkpoint_step(self.tmpdir, self.ticker, self.date, sig2))
|
||||
|
||||
_should_crash = False
|
||||
tid2 = thread_id(self.ticker, self.date, sig2)
|
||||
@@ -190,7 +188,7 @@ class TestCheckpointSignature(unittest.TestCase):
|
||||
result = graph.invoke({"count": 0}, config={"configurable": {"thread_id": tid2}})
|
||||
self.assertEqual(result["count"], 11)
|
||||
# sig1's checkpoint remains untouched.
|
||||
self.assertTrue(has_checkpoint(self.tmpdir, self.ticker, self.date, sig1))
|
||||
self.assertIsNotNone(checkpoint_step(self.tmpdir, self.ticker, self.date, sig1))
|
||||
|
||||
def test_run_signature_captures_graph_shape(self):
|
||||
from tradingagents.graph.trading_graph import TradingAgentsGraph
|
||||
|
||||
@@ -95,23 +95,6 @@ def test_every_command_is_registered_when_run_as_a_module():
|
||||
assert "--start" in plain
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_the_cli_says_whether_a_run_resumed(monkeypatch):
|
||||
"""The README promises the user can tell a resumed run from a fresh one.
|
||||
The graph logs it, but nothing configures logging, so it was never shown."""
|
||||
import cli.main as m
|
||||
|
||||
messages = []
|
||||
monkeypatch.setattr(m.message_buffer, "add_message",
|
||||
lambda kind, text: messages.append(text), raising=False)
|
||||
|
||||
m._announce_checkpoint_state(type("G", (), {"_resuming": True})(), "NVDA", "2026-01-10")
|
||||
m._announce_checkpoint_state(type("G", (), {"_resuming": False})(), "NVDA", "2026-01-10")
|
||||
|
||||
assert any("resum" in text.lower() for text in messages)
|
||||
assert any("fresh" in text.lower() for text in messages)
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_backtest_can_continue_an_interrupted_sweep(runner, monkeypatch, tmp_path):
|
||||
"""Resuming is what makes a long sweep practical, and the Python API has it."""
|
||||
|
||||
@@ -10,6 +10,7 @@ from unittest import mock
|
||||
import pytest
|
||||
|
||||
import cli.main as m
|
||||
import cli.run as cli_run
|
||||
|
||||
# Minimal selections dict shaped like get_user_selections()'s return value.
|
||||
SELECTIONS = {
|
||||
@@ -28,7 +29,7 @@ SELECTIONS = {
|
||||
def test_research_depth_sets_both_rounds_without_env(monkeypatch):
|
||||
for var in ("TRADINGAGENTS_MAX_DEBATE_ROUNDS", "TRADINGAGENTS_MAX_RISK_ROUNDS"):
|
||||
monkeypatch.delenv(var, raising=False)
|
||||
cfg = m._build_run_config(SELECTIONS, checkpoint=None)
|
||||
cfg = cli_run._build_run_config(SELECTIONS, checkpoint=None)
|
||||
assert cfg["max_debate_rounds"] == 5
|
||||
assert cfg["max_risk_discuss_rounds"] == 5
|
||||
|
||||
@@ -37,9 +38,9 @@ def test_env_round_counts_win_over_selection(monkeypatch):
|
||||
monkeypatch.setenv("TRADINGAGENTS_MAX_DEBATE_ROUNDS", "2")
|
||||
monkeypatch.setenv("TRADINGAGENTS_MAX_RISK_ROUNDS", "4")
|
||||
# DEFAULT_CONFIG already reflects the env (applied at import); emulate that.
|
||||
patched = dict(m.DEFAULT_CONFIG, max_debate_rounds=2, max_risk_discuss_rounds=4)
|
||||
with mock.patch.object(m, "DEFAULT_CONFIG", patched):
|
||||
cfg = m._build_run_config(SELECTIONS, checkpoint=None)
|
||||
patched = dict(cli_run.DEFAULT_CONFIG, max_debate_rounds=2, max_risk_discuss_rounds=4)
|
||||
with mock.patch.object(cli_run, "DEFAULT_CONFIG", patched):
|
||||
cfg = cli_run._build_run_config(SELECTIONS, checkpoint=None)
|
||||
assert cfg["max_debate_rounds"] == 2 # env value, not research_depth=5
|
||||
assert cfg["max_risk_discuss_rounds"] == 4
|
||||
|
||||
@@ -47,25 +48,25 @@ def test_env_round_counts_win_over_selection(monkeypatch):
|
||||
def test_partial_env_only_overrides_that_count(monkeypatch):
|
||||
monkeypatch.setenv("TRADINGAGENTS_MAX_DEBATE_ROUNDS", "2")
|
||||
monkeypatch.delenv("TRADINGAGENTS_MAX_RISK_ROUNDS", raising=False)
|
||||
patched = dict(m.DEFAULT_CONFIG, max_debate_rounds=2)
|
||||
with mock.patch.object(m, "DEFAULT_CONFIG", patched):
|
||||
cfg = m._build_run_config(SELECTIONS, checkpoint=None)
|
||||
patched = dict(cli_run.DEFAULT_CONFIG, max_debate_rounds=2)
|
||||
with mock.patch.object(cli_run, "DEFAULT_CONFIG", patched):
|
||||
cfg = cli_run._build_run_config(SELECTIONS, checkpoint=None)
|
||||
assert cfg["max_debate_rounds"] == 2 # env wins
|
||||
assert cfg["max_risk_discuss_rounds"] == 5 # falls through to research_depth
|
||||
|
||||
|
||||
def test_checkpoint_none_preserves_env_default():
|
||||
patched = dict(m.DEFAULT_CONFIG, checkpoint_enabled=True) # e.g. env-enabled
|
||||
with mock.patch.object(m, "DEFAULT_CONFIG", patched):
|
||||
cfg = m._build_run_config(SELECTIONS, checkpoint=None)
|
||||
patched = dict(cli_run.DEFAULT_CONFIG, checkpoint_enabled=True) # e.g. env-enabled
|
||||
with mock.patch.object(cli_run, "DEFAULT_CONFIG", patched):
|
||||
cfg = cli_run._build_run_config(SELECTIONS, checkpoint=None)
|
||||
assert cfg["checkpoint_enabled"] is True # not clobbered back to False
|
||||
|
||||
|
||||
@pytest.mark.parametrize("flag", [True, False])
|
||||
def test_checkpoint_flag_overrides_env(flag):
|
||||
patched = dict(m.DEFAULT_CONFIG, checkpoint_enabled=not flag)
|
||||
with mock.patch.object(m, "DEFAULT_CONFIG", patched):
|
||||
cfg = m._build_run_config(SELECTIONS, checkpoint=flag)
|
||||
patched = dict(cli_run.DEFAULT_CONFIG, checkpoint_enabled=not flag)
|
||||
with mock.patch.object(cli_run, "DEFAULT_CONFIG", patched):
|
||||
cfg = cli_run._build_run_config(SELECTIONS, checkpoint=flag)
|
||||
assert cfg["checkpoint_enabled"] is flag
|
||||
|
||||
|
||||
@@ -75,7 +76,7 @@ def test_glm_resolves_to_the_endpoint_its_key_belongs_to():
|
||||
same platform: glm is Z.AI international (ZHIPU_API_KEY) and glm-cn is
|
||||
BigModel China. A mismatch sends the key to the other platform and every
|
||||
call fails auth."""
|
||||
from cli.utils import resolve_backend_url
|
||||
from cli.prompts import resolve_backend_url
|
||||
from tradingagents.llm_clients.api_key_env import get_api_key_env
|
||||
from tradingagents.llm_clients.openai_client import OPENAI_COMPATIBLE_PROVIDERS
|
||||
|
||||
@@ -89,14 +90,13 @@ def test_glm_resolves_to_the_endpoint_its_key_belongs_to():
|
||||
def test_a_half_set_round_count_says_which_value_won(capsys, monkeypatch):
|
||||
"""With only one of the two round-count variables set, the depth prompt is
|
||||
still shown but half the answer is discarded; the user was never told."""
|
||||
import cli.main as m
|
||||
|
||||
monkeypatch.setenv("TRADINGAGENTS_MAX_DEBATE_ROUNDS", "1")
|
||||
monkeypatch.delenv("TRADINGAGENTS_MAX_RISK_ROUNDS", raising=False)
|
||||
printed = []
|
||||
monkeypatch.setattr(m.console, "print", lambda *a, **k: printed.append(str(a[0]) if a else ""))
|
||||
|
||||
config = m._build_run_config({
|
||||
config = cli_run._build_run_config({
|
||||
"ticker": "NVDA", "analysis_date": "2026-09-01", "asset_type": "stock",
|
||||
"analysts": [], "research_depth": 5, "llm_provider": "openai",
|
||||
"quick_think_llm": "gpt-5.6-luna", "deep_think_llm": "gpt-5.6",
|
||||
|
||||
@@ -11,7 +11,8 @@ from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from tradingagents.agents.utils.memory import TradingMemoryLog
|
||||
import cli.run as cli_run
|
||||
from tradingagents.decision_log import TradingMemoryLog
|
||||
from tradingagents.graph.trading_graph import TradingAgentsGraph
|
||||
|
||||
|
||||
@@ -30,7 +31,7 @@ def test_create_run_state_settles_pending_and_carries_context(tmp_path, monkeypa
|
||||
graph = _bare_graph(tmp_path)
|
||||
graph.propagator = Propagator()
|
||||
settled = []
|
||||
monkeypatch.setattr(graph, "_resolve_pending_entries", settled.append, raising=False)
|
||||
monkeypatch.setattr(graph, "settle_pending", settled.append, raising=False)
|
||||
monkeypatch.setattr(graph, "resolve_instrument_context", lambda t, a="stock", d=None: f"id:{t}", raising=False)
|
||||
monkeypatch.setattr(graph, "_memory_as_of", lambda d: d, raising=False)
|
||||
graph.memory_log.store_decision("NVDA", "2026-01-05", "Rating: Buy\nold call")
|
||||
@@ -64,18 +65,20 @@ def test_record_decision_skips_a_run_without_a_decision(tmp_path):
|
||||
class _FakeGraph:
|
||||
"""Records the lifecycle calls run_analysis makes."""
|
||||
|
||||
def __init__(self):
|
||||
def __init__(self, resuming=None):
|
||||
self.calls = []
|
||||
self.graph = self
|
||||
self.propagator = self
|
||||
self.resuming = resuming # None: checkpointing off
|
||||
self._resuming = False
|
||||
|
||||
def create_run_state(self, ticker, trade_date, asset_type="stock", portfolio=None):
|
||||
self.calls.append(("create_run_state", ticker, trade_date))
|
||||
return {"messages": [], "company_of_interest": ticker}
|
||||
|
||||
def process_signal(self, text):
|
||||
from tradingagents.graph.signal_processing import SignalProcessor
|
||||
return SignalProcessor.process_signal(None, text)
|
||||
from tradingagents.agents.rating import parse_rating
|
||||
return parse_rating(text)
|
||||
|
||||
def record_decision(self, ticker, trade_date, final_state):
|
||||
self.calls.append(("record_decision", ticker, trade_date, final_state.get("final_trade_decision")))
|
||||
@@ -84,7 +87,8 @@ class _FakeGraph:
|
||||
return {}
|
||||
|
||||
def begin_checkpoint(self, *a, **k):
|
||||
return None
|
||||
self._resuming = bool(self.resuming)
|
||||
return None if self.resuming is None else "thread"
|
||||
|
||||
def checkpoint_input(self, state):
|
||||
return state
|
||||
@@ -136,27 +140,33 @@ class _FakeBuffer:
|
||||
self.agent_status[agent] = status
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_cli_run_uses_the_decision_log_like_propagate(tmp_path, monkeypatch):
|
||||
def _run_cli(monkeypatch, tmp_path, fake):
|
||||
"""Drive run_analysis against ``fake``; returns the message buffer."""
|
||||
import cli.main as m
|
||||
from cli.models import AnalystType
|
||||
|
||||
fake = _FakeGraph()
|
||||
monkeypatch.setattr(m, "TradingAgentsGraph", lambda *a, **k: fake)
|
||||
monkeypatch.setattr(m, "message_buffer", _FakeBuffer())
|
||||
monkeypatch.setattr(m, "create_layout", lambda: None)
|
||||
monkeypatch.setattr(m, "update_display", lambda *a, **k: None)
|
||||
monkeypatch.setattr(m, "Live", _NullLive)
|
||||
monkeypatch.setattr(m, "get_user_selections", lambda: {
|
||||
buffer = _FakeBuffer()
|
||||
monkeypatch.setattr(cli_run, "TradingAgentsGraph", lambda *a, **k: fake)
|
||||
monkeypatch.setattr(cli_run, "message_buffer", buffer)
|
||||
monkeypatch.setattr(cli_run, "create_layout", lambda: None)
|
||||
monkeypatch.setattr(cli_run, "update_display", lambda *a, **k: None)
|
||||
monkeypatch.setattr(cli_run, "Live", _NullLive)
|
||||
monkeypatch.setattr(cli_run, "get_user_selections", lambda: {
|
||||
"ticker": "NVDA", "analysis_date": "2026-01-10",
|
||||
"analysts": [AnalystType.MARKET], "asset_type": "stock",
|
||||
})
|
||||
monkeypatch.setattr(m, "_build_run_config", lambda selections, checkpoint: {
|
||||
monkeypatch.setattr(cli_run, "_build_run_config", lambda selections, checkpoint: {
|
||||
"data_cache_dir": str(tmp_path / "cache"), "results_dir": str(tmp_path / "results"),
|
||||
})
|
||||
monkeypatch.setattr(m.typer, "prompt", lambda *a, **k: "N")
|
||||
cli_run.run_analysis()
|
||||
return buffer
|
||||
|
||||
m.run_analysis()
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_cli_run_uses_the_decision_log_like_propagate(tmp_path, monkeypatch):
|
||||
fake = _FakeGraph()
|
||||
_run_cli(monkeypatch, tmp_path, fake)
|
||||
|
||||
assert fake.calls == [
|
||||
("create_run_state", "NVDA", "2026-01-10"),
|
||||
@@ -165,3 +175,19 @@ def test_cli_run_uses_the_decision_log_like_propagate(tmp_path, monkeypatch):
|
||||
("record_decision", "NVDA", "2026-01-10", "Rating: Buy\n\nBuy NVDA."),
|
||||
("clear_checkpoint",),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.parametrize("resuming, said", [(True, "resuming"), (False, "starting fresh")])
|
||||
def test_the_cli_run_says_whether_it_resumed(tmp_path, monkeypatch, resuming, said):
|
||||
"""The README promises the run view tells a resumed run from a fresh one."""
|
||||
buffer = _run_cli(monkeypatch, tmp_path, _FakeGraph(resuming=resuming))
|
||||
|
||||
assert any(said in text.lower() for _, kind, text in buffer.messages if kind == "System")
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_a_run_without_checkpointing_says_nothing_about_resuming(tmp_path, monkeypatch):
|
||||
buffer = _run_cli(monkeypatch, tmp_path, _FakeGraph())
|
||||
|
||||
assert not any("resum" in text.lower() or "fresh" in text.lower() for _, _, text in buffer.messages)
|
||||
|
||||
+72
-15
@@ -7,10 +7,16 @@ person to read afterwards. Both got that wrong in ways that hide real content.
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import unittest
|
||||
|
||||
import pytest
|
||||
|
||||
from cli.main import extract_content_string
|
||||
from cli.display import (
|
||||
AnalystWallTimeTracker,
|
||||
extract_content_string,
|
||||
sync_analyst_tracker_from_chunk,
|
||||
)
|
||||
from tradingagents.graph.analyst_execution import build_analyst_execution_plan
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@@ -35,21 +41,12 @@ def test_the_other_shapes_are_unchanged(value, expected):
|
||||
assert extract_content_string(value) == expected
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_the_state_log_keeps_non_ascii_readable(tmp_path):
|
||||
"""Reports can be in any language; the log is read by a person."""
|
||||
from tradingagents.graph.trading_graph import TradingAgentsGraph
|
||||
|
||||
graph = object.__new__(TradingAgentsGraph)
|
||||
graph.config = {"results_dir": str(tmp_path)}
|
||||
graph.ticker = "600519.SS"
|
||||
graph.log_states_dict = {}
|
||||
|
||||
graph._log_state("2026-09-01", {
|
||||
"company_of_interest": "600519.SS", "trade_date": "2026-09-01",
|
||||
def _state(ticker, final="评级: 买入"):
|
||||
return {
|
||||
"company_of_interest": ticker, "trade_date": "2026-09-01",
|
||||
"market_report": "市场", "sentiment_report": "情绪", "news_report": "新闻",
|
||||
"fundamentals_report": "基本面", "investment_plan": "计划",
|
||||
"trader_investment_plan": "交易计划", "final_trade_decision": "评级: 买入",
|
||||
"trader_investment_plan": "交易计划", "final_trade_decision": final,
|
||||
"investment_debate_state": {"bull_history": "", "bear_history": "", "history": "",
|
||||
"current_response": "", "judge_decision": "", "count": 0},
|
||||
"risk_debate_state": {"aggressive_history": "", "conservative_history": "",
|
||||
@@ -57,7 +54,21 @@ def test_the_state_log_keeps_non_ascii_readable(tmp_path):
|
||||
"latest_speaker": "", "current_aggressive_response": "",
|
||||
"current_conservative_response": "", "current_neutral_response": "",
|
||||
"count": 0},
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
def _bare_graph(tmp_path):
|
||||
from tradingagents.graph.trading_graph import TradingAgentsGraph
|
||||
|
||||
graph = object.__new__(TradingAgentsGraph)
|
||||
graph.config = {"results_dir": str(tmp_path)}
|
||||
return graph
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_the_state_log_keeps_non_ascii_readable(tmp_path):
|
||||
"""Reports can be in any language; the log is read by a person."""
|
||||
_bare_graph(tmp_path)._log_state("2026-09-01", _state("600519.SS"))
|
||||
|
||||
written = next(tmp_path.rglob("full_states_log*.json")).read_text(encoding="utf-8")
|
||||
assert "买入" in written
|
||||
@@ -75,3 +86,49 @@ def test_the_live_display_does_not_scroll_the_terminal():
|
||||
import cli.main as m
|
||||
|
||||
assert "screen=True" in inspect.getsource(m.run_analysis)
|
||||
|
||||
|
||||
class AnalystWallTimeTrackerTests(unittest.TestCase):
|
||||
def test_records_wall_time_when_analyst_completes(self):
|
||||
plan = build_analyst_execution_plan(["market", "news"])
|
||||
tracker = AnalystWallTimeTracker(plan)
|
||||
|
||||
tracker.mark_started("market", started_at=10.0)
|
||||
tracker.mark_completed("market", completed_at=13.5)
|
||||
|
||||
self.assertEqual(tracker.format_summary(), "Analyst wall time: Market 3.50s")
|
||||
|
||||
def test_formats_summary_in_plan_order(self):
|
||||
plan = build_analyst_execution_plan(["news", "market"])
|
||||
tracker = AnalystWallTimeTracker(plan)
|
||||
|
||||
tracker.mark_started("market", started_at=20.0)
|
||||
tracker.mark_completed("market", completed_at=22.25)
|
||||
tracker.mark_started("news", started_at=10.0)
|
||||
tracker.mark_completed("news", completed_at=14.0)
|
||||
|
||||
self.assertEqual(
|
||||
tracker.format_summary(),
|
||||
"Analyst wall time: News 4.00s | Market 2.25s",
|
||||
)
|
||||
|
||||
def test_syncs_wall_time_from_sequential_chunks(self):
|
||||
plan = build_analyst_execution_plan(["market", "news"])
|
||||
tracker = AnalystWallTimeTracker(plan)
|
||||
|
||||
sync_analyst_tracker_from_chunk(tracker, {}, now=10.0)
|
||||
self.assertEqual(tracker.format_summary(), "Analyst wall time: pending")
|
||||
|
||||
sync_analyst_tracker_from_chunk(
|
||||
tracker,
|
||||
{"market_report": "done"},
|
||||
now=13.0,
|
||||
)
|
||||
self.assertEqual(tracker.format_summary(), "Analyst wall time: Market 3.00s")
|
||||
|
||||
sync_analyst_tracker_from_chunk(
|
||||
tracker,
|
||||
{"market_report": "done", "news_report": "done"},
|
||||
now=18.0,
|
||||
)
|
||||
self.assertEqual(tracker.format_summary(), "Analyst wall time: Market 3.00s | News 5.00s")
|
||||
|
||||
+49
-50
@@ -11,21 +11,23 @@ from unittest import mock
|
||||
|
||||
import pytest
|
||||
|
||||
import cli.selections as cli_selections
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
class TestProviderDefaultUrl(unittest.TestCase):
|
||||
def test_known_providers_resolve(self):
|
||||
from cli.utils import provider_default_url
|
||||
from cli.prompts import provider_default_url
|
||||
self.assertEqual(provider_default_url("openai"), "https://api.openai.com/v1")
|
||||
self.assertEqual(provider_default_url("DeepSeek"), "https://api.deepseek.com")
|
||||
self.assertIsNone(provider_default_url("google")) # uses SDK default
|
||||
|
||||
def test_unknown_provider_returns_none(self):
|
||||
from cli.utils import provider_default_url
|
||||
from cli.prompts import provider_default_url
|
||||
self.assertIsNone(provider_default_url("not-a-provider"))
|
||||
|
||||
def test_ollama_honors_base_url_env(self):
|
||||
from cli.utils import provider_default_url
|
||||
from cli.prompts import provider_default_url
|
||||
with mock.patch.dict(os.environ, {"OLLAMA_BASE_URL": "http://host:1234/v1"}):
|
||||
self.assertEqual(provider_default_url("ollama"), "http://host:1234/v1")
|
||||
|
||||
@@ -33,7 +35,6 @@ class TestProviderDefaultUrl(unittest.TestCase):
|
||||
@pytest.mark.unit
|
||||
class TestCliSkipsPromptsFromEnv(unittest.TestCase):
|
||||
def test_env_config_skips_llm_prompts(self):
|
||||
import cli.main as m
|
||||
|
||||
env = {
|
||||
"TRADINGAGENTS_LLM_PROVIDER": "openai",
|
||||
@@ -42,7 +43,7 @@ class TestCliSkipsPromptsFromEnv(unittest.TestCase):
|
||||
"TRADINGAGENTS_LLM_BACKEND_URL": "https://opencode.ai/zen/go/v1",
|
||||
"TRADINGAGENTS_OUTPUT_LANGUAGE": "Japanese",
|
||||
}
|
||||
fake_cfg = dict(m.DEFAULT_CONFIG)
|
||||
fake_cfg = dict(cli_selections.DEFAULT_CONFIG)
|
||||
fake_cfg.update({
|
||||
"llm_provider": "openai",
|
||||
"backend_url": "https://opencode.ai/zen/go/v1",
|
||||
@@ -52,19 +53,19 @@ class TestCliSkipsPromptsFromEnv(unittest.TestCase):
|
||||
})
|
||||
|
||||
with mock.patch.dict(os.environ, env, clear=False), \
|
||||
mock.patch.object(m, "DEFAULT_CONFIG", fake_cfg), \
|
||||
mock.patch.object(m, "fetch_announcements", return_value=None), \
|
||||
mock.patch.object(m, "display_announcements"), \
|
||||
mock.patch.object(m, "get_ticker", return_value="AAPL"), \
|
||||
mock.patch.object(m, "get_analysis_date", return_value="2026-05-29"), \
|
||||
mock.patch.object(m, "select_analysts", return_value=[]), \
|
||||
mock.patch.object(m, "select_research_depth", return_value=1), \
|
||||
mock.patch.object(m, "ensure_api_key") as ensure_key, \
|
||||
mock.patch.object(m, "select_llm_provider") as prompt_provider, \
|
||||
mock.patch.object(m, "ask_output_language") as prompt_lang, \
|
||||
mock.patch.object(m, "select_shallow_thinking_agent") as prompt_quick, \
|
||||
mock.patch.object(m, "select_deep_thinking_agent") as prompt_deep:
|
||||
sel = m.get_user_selections()
|
||||
mock.patch.object(cli_selections, "DEFAULT_CONFIG", fake_cfg), \
|
||||
mock.patch.object(cli_selections, "fetch_announcements", return_value=None), \
|
||||
mock.patch.object(cli_selections, "display_announcements"), \
|
||||
mock.patch.object(cli_selections, "get_ticker", return_value="AAPL"), \
|
||||
mock.patch.object(cli_selections, "get_analysis_date", return_value="2026-05-29"), \
|
||||
mock.patch.object(cli_selections, "select_analysts", return_value=[]), \
|
||||
mock.patch.object(cli_selections, "select_research_depth", return_value=1), \
|
||||
mock.patch.object(cli_selections, "ensure_api_key") as ensure_key, \
|
||||
mock.patch.object(cli_selections, "select_llm_provider") as prompt_provider, \
|
||||
mock.patch.object(cli_selections, "ask_output_language") as prompt_lang, \
|
||||
mock.patch.object(cli_selections, "select_shallow_thinking_agent") as prompt_quick, \
|
||||
mock.patch.object(cli_selections, "select_deep_thinking_agent") as prompt_deep:
|
||||
sel = cli_selections.get_user_selections()
|
||||
|
||||
# None of the LLM selection prompts should have been shown.
|
||||
prompt_provider.assert_not_called()
|
||||
@@ -85,30 +86,29 @@ class TestCliSkipsPromptsFromEnv(unittest.TestCase):
|
||||
@pytest.mark.unit
|
||||
class TestResearchDepthSkippedFromEnv(unittest.TestCase):
|
||||
def test_both_round_envs_skip_depth_prompt(self):
|
||||
import cli.main as m
|
||||
|
||||
env = {
|
||||
"TRADINGAGENTS_MAX_DEBATE_ROUNDS": "2",
|
||||
"TRADINGAGENTS_MAX_RISK_ROUNDS": "4",
|
||||
}
|
||||
fake_cfg = dict(m.DEFAULT_CONFIG)
|
||||
fake_cfg = dict(cli_selections.DEFAULT_CONFIG)
|
||||
fake_cfg.update({"max_debate_rounds": 2, "max_risk_discuss_rounds": 4})
|
||||
|
||||
with mock.patch.dict(os.environ, env, clear=False), \
|
||||
mock.patch.object(m, "DEFAULT_CONFIG", fake_cfg), \
|
||||
mock.patch.object(m, "fetch_announcements", return_value=None), \
|
||||
mock.patch.object(m, "display_announcements"), \
|
||||
mock.patch.object(m, "get_ticker", return_value="AAPL"), \
|
||||
mock.patch.object(m, "get_analysis_date", return_value="2026-05-29"), \
|
||||
mock.patch.object(m, "select_analysts", return_value=[]), \
|
||||
mock.patch.object(m, "select_research_depth") as prompt_depth, \
|
||||
mock.patch.object(m, "ensure_api_key"), \
|
||||
mock.patch.object(m, "select_llm_provider", return_value=("openai", None)), \
|
||||
mock.patch.object(m, "ask_output_language", return_value="English"), \
|
||||
mock.patch.object(m, "select_shallow_thinking_agent", return_value="gpt-5.4-mini"), \
|
||||
mock.patch.object(m, "select_deep_thinking_agent", return_value="gpt-5.5"), \
|
||||
mock.patch.object(m, "ask_openai_reasoning_effort", return_value=None):
|
||||
sel = m.get_user_selections()
|
||||
mock.patch.object(cli_selections, "DEFAULT_CONFIG", fake_cfg), \
|
||||
mock.patch.object(cli_selections, "fetch_announcements", return_value=None), \
|
||||
mock.patch.object(cli_selections, "display_announcements"), \
|
||||
mock.patch.object(cli_selections, "get_ticker", return_value="AAPL"), \
|
||||
mock.patch.object(cli_selections, "get_analysis_date", return_value="2026-05-29"), \
|
||||
mock.patch.object(cli_selections, "select_analysts", return_value=[]), \
|
||||
mock.patch.object(cli_selections, "select_research_depth") as prompt_depth, \
|
||||
mock.patch.object(cli_selections, "ensure_api_key"), \
|
||||
mock.patch.object(cli_selections, "select_llm_provider", return_value=("openai", None)), \
|
||||
mock.patch.object(cli_selections, "ask_output_language", return_value="English"), \
|
||||
mock.patch.object(cli_selections, "select_shallow_thinking_agent", return_value="gpt-5.4-mini"), \
|
||||
mock.patch.object(cli_selections, "select_deep_thinking_agent", return_value="gpt-5.5"), \
|
||||
mock.patch.object(cli_selections, "ask_openai_reasoning_effort", return_value=None):
|
||||
sel = cli_selections.get_user_selections()
|
||||
|
||||
# The research-depth prompt is skipped; the value comes from the env config.
|
||||
prompt_depth.assert_not_called()
|
||||
@@ -118,27 +118,26 @@ class TestResearchDepthSkippedFromEnv(unittest.TestCase):
|
||||
@pytest.mark.unit
|
||||
class TestReasoningEffortSkippedFromEnv(unittest.TestCase):
|
||||
def test_effort_env_skips_step8_prompt(self):
|
||||
import cli.main as m
|
||||
|
||||
env = {"TRADINGAGENTS_OPENAI_REASONING_EFFORT": "high"}
|
||||
fake_cfg = dict(m.DEFAULT_CONFIG)
|
||||
fake_cfg = dict(cli_selections.DEFAULT_CONFIG)
|
||||
fake_cfg.update({"openai_reasoning_effort": "high"})
|
||||
|
||||
with mock.patch.dict(os.environ, env, clear=False), \
|
||||
mock.patch.object(m, "DEFAULT_CONFIG", fake_cfg), \
|
||||
mock.patch.object(m, "fetch_announcements", return_value=None), \
|
||||
mock.patch.object(m, "display_announcements"), \
|
||||
mock.patch.object(m, "get_ticker", return_value="AAPL"), \
|
||||
mock.patch.object(m, "get_analysis_date", return_value="2026-05-29"), \
|
||||
mock.patch.object(m, "select_analysts", return_value=[]), \
|
||||
mock.patch.object(m, "select_research_depth", return_value=1), \
|
||||
mock.patch.object(m, "ensure_api_key"), \
|
||||
mock.patch.object(m, "select_llm_provider", return_value=("openai", None)), \
|
||||
mock.patch.object(m, "ask_output_language", return_value="English"), \
|
||||
mock.patch.object(m, "select_shallow_thinking_agent", return_value="gpt-5.4-mini"), \
|
||||
mock.patch.object(m, "select_deep_thinking_agent", return_value="gpt-5.5"), \
|
||||
mock.patch.object(m, "ask_openai_reasoning_effort") as prompt_effort:
|
||||
sel = m.get_user_selections()
|
||||
mock.patch.object(cli_selections, "DEFAULT_CONFIG", fake_cfg), \
|
||||
mock.patch.object(cli_selections, "fetch_announcements", return_value=None), \
|
||||
mock.patch.object(cli_selections, "display_announcements"), \
|
||||
mock.patch.object(cli_selections, "get_ticker", return_value="AAPL"), \
|
||||
mock.patch.object(cli_selections, "get_analysis_date", return_value="2026-05-29"), \
|
||||
mock.patch.object(cli_selections, "select_analysts", return_value=[]), \
|
||||
mock.patch.object(cli_selections, "select_research_depth", return_value=1), \
|
||||
mock.patch.object(cli_selections, "ensure_api_key"), \
|
||||
mock.patch.object(cli_selections, "select_llm_provider", return_value=("openai", None)), \
|
||||
mock.patch.object(cli_selections, "ask_output_language", return_value="English"), \
|
||||
mock.patch.object(cli_selections, "select_shallow_thinking_agent", return_value="gpt-5.4-mini"), \
|
||||
mock.patch.object(cli_selections, "select_deep_thinking_agent", return_value="gpt-5.5"), \
|
||||
mock.patch.object(cli_selections, "ask_openai_reasoning_effort") as prompt_effort:
|
||||
sel = cli_selections.get_user_selections()
|
||||
|
||||
# The reasoning-effort prompt is skipped; the value comes from env config.
|
||||
prompt_effort.assert_not_called()
|
||||
|
||||
+28
-28
@@ -13,6 +13,7 @@ from unittest import mock
|
||||
|
||||
import pytest
|
||||
|
||||
import cli.selections as cli_selections
|
||||
from cli.models import AnalystType
|
||||
from cli.prefs import load_last_run, sanitize, save_last_run
|
||||
|
||||
@@ -100,26 +101,26 @@ def _answer_every_prompt(monkeypatch):
|
||||
"""Drive the real selection flow, answering each prompt with a fixed value."""
|
||||
import cli.main as m
|
||||
|
||||
monkeypatch.setattr(m, "fetch_announcements", lambda: [])
|
||||
monkeypatch.setattr(m, "display_announcements", lambda *a: None)
|
||||
monkeypatch.setattr(m, "get_ticker", lambda: "NVDA")
|
||||
monkeypatch.setattr(m, "get_analysis_date", lambda: "2026-09-01")
|
||||
monkeypatch.setattr(m, "ask_output_language", lambda default=None: "English")
|
||||
monkeypatch.setattr(m, "select_analysts", lambda asset_type, default=None: [AnalystType.MARKET])
|
||||
monkeypatch.setattr(m, "select_research_depth", lambda default=None: 3)
|
||||
monkeypatch.setattr(m, "select_llm_provider", lambda default=None: ("openai", None))
|
||||
monkeypatch.setattr(m, "select_shallow_thinking_agent", lambda p, default=None: "gpt-5.6-mini")
|
||||
monkeypatch.setattr(m, "select_deep_thinking_agent", lambda p, default=None: "gpt-5.6")
|
||||
monkeypatch.setattr(m, "ask_openai_reasoning_effort", lambda: "medium")
|
||||
monkeypatch.setattr(cli_selections, "fetch_announcements", lambda: [])
|
||||
monkeypatch.setattr(cli_selections, "display_announcements", lambda *a: None)
|
||||
monkeypatch.setattr(cli_selections, "get_ticker", lambda: "NVDA")
|
||||
monkeypatch.setattr(cli_selections, "get_analysis_date", lambda: "2026-09-01")
|
||||
monkeypatch.setattr(cli_selections, "ask_output_language", lambda default=None: "English")
|
||||
monkeypatch.setattr(cli_selections, "select_analysts", lambda asset_type, default=None: [AnalystType.MARKET])
|
||||
monkeypatch.setattr(cli_selections, "select_research_depth", lambda default=None: 3)
|
||||
monkeypatch.setattr(cli_selections, "select_llm_provider", lambda default=None: ("openai", None))
|
||||
monkeypatch.setattr(cli_selections, "select_shallow_thinking_agent", lambda p, default=None: "gpt-5.6-mini")
|
||||
monkeypatch.setattr(cli_selections, "select_deep_thinking_agent", lambda p, default=None: "gpt-5.6")
|
||||
monkeypatch.setattr(cli_selections, "ask_openai_reasoning_effort", lambda: "medium")
|
||||
return m
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_selections_are_remembered_after_a_run(monkeypatch):
|
||||
"""Drives the real flow: a stubbed selections dict would hide a key mismatch."""
|
||||
m = _answer_every_prompt(monkeypatch)
|
||||
_answer_every_prompt(monkeypatch)
|
||||
|
||||
m.get_user_selections()
|
||||
cli_selections.get_user_selections()
|
||||
|
||||
remembered = load_last_run()
|
||||
assert remembered["analysts"] == ["market"]
|
||||
@@ -134,10 +135,10 @@ def test_selections_are_remembered_after_a_run(monkeypatch):
|
||||
def test_a_custom_language_is_remembered_without_breaking_the_next_run():
|
||||
"""A free-text answer is not one of the menu's choices, and questionary
|
||||
rejects a default it cannot find, so offering it back would crash startup."""
|
||||
from cli.utils import ask_output_language
|
||||
from cli.prompts import ask_output_language
|
||||
|
||||
save_last_run({"output_language": "Turkish"})
|
||||
with mock.patch("cli.utils.questionary.select") as select:
|
||||
with mock.patch("cli.prompts.questionary.select") as select:
|
||||
select.return_value.ask.return_value = "English"
|
||||
ask_output_language(load_last_run()["output_language"])
|
||||
assert select.call_args.kwargs["default"] is None
|
||||
@@ -147,23 +148,22 @@ def test_a_custom_language_is_remembered_without_breaking_the_next_run():
|
||||
def test_a_remembered_endpoint_is_offered_back(monkeypatch):
|
||||
"""Users of a local or custom endpoint retyped the URL every run: it was
|
||||
remembered and validated, then never read."""
|
||||
import cli.main as m
|
||||
|
||||
save_last_run({"llm_provider": "openai_compatible", "backend_url": "http://localhost:1234/v1"})
|
||||
offered = {}
|
||||
monkeypatch.setattr(m, "select_llm_provider", lambda default=None: ("openai_compatible", None))
|
||||
monkeypatch.setattr(m, "prompt_openai_compatible_url",
|
||||
monkeypatch.setattr(cli_selections, "select_llm_provider", lambda default=None: ("openai_compatible", None))
|
||||
monkeypatch.setattr(cli_selections, "prompt_openai_compatible_url",
|
||||
lambda default=None: offered.setdefault("default", default) or "http://x/v1")
|
||||
monkeypatch.setattr(m, "fetch_announcements", lambda: [])
|
||||
monkeypatch.setattr(m, "display_announcements", lambda *a: None)
|
||||
monkeypatch.setattr(m, "get_ticker", lambda: "NVDA")
|
||||
monkeypatch.setattr(m, "get_analysis_date", lambda: "2026-09-01")
|
||||
monkeypatch.setattr(m, "ask_output_language", lambda default=None: "English")
|
||||
monkeypatch.setattr(m, "select_analysts", lambda asset_type, default=None: [AnalystType.MARKET])
|
||||
monkeypatch.setattr(m, "select_research_depth", lambda default=None: 1)
|
||||
monkeypatch.setattr(m, "select_shallow_thinking_agent", lambda p, default=None: "local-model")
|
||||
monkeypatch.setattr(m, "select_deep_thinking_agent", lambda p, default=None: "local-model")
|
||||
monkeypatch.setattr(cli_selections, "fetch_announcements", lambda: [])
|
||||
monkeypatch.setattr(cli_selections, "display_announcements", lambda *a: None)
|
||||
monkeypatch.setattr(cli_selections, "get_ticker", lambda: "NVDA")
|
||||
monkeypatch.setattr(cli_selections, "get_analysis_date", lambda: "2026-09-01")
|
||||
monkeypatch.setattr(cli_selections, "ask_output_language", lambda default=None: "English")
|
||||
monkeypatch.setattr(cli_selections, "select_analysts", lambda asset_type, default=None: [AnalystType.MARKET])
|
||||
monkeypatch.setattr(cli_selections, "select_research_depth", lambda default=None: 1)
|
||||
monkeypatch.setattr(cli_selections, "select_shallow_thinking_agent", lambda p, default=None: "local-model")
|
||||
monkeypatch.setattr(cli_selections, "select_deep_thinking_agent", lambda p, default=None: "local-model")
|
||||
|
||||
m.get_user_selections()
|
||||
cli_selections.get_user_selections()
|
||||
|
||||
assert offered["default"] == "http://localhost:1234/v1"
|
||||
|
||||
@@ -5,9 +5,10 @@ stock), #982 (BTC-USDT accepted but unpriceable on Yahoo).
|
||||
"""
|
||||
import pytest
|
||||
|
||||
import cli.run as cli_run
|
||||
from cli.models import AssetType
|
||||
from cli.utils import detect_asset_type, is_valid_ticker_input, normalize_ticker_symbol
|
||||
from tradingagents.dataflows.symbol_utils import normalize_symbol
|
||||
from cli.prompts import detect_asset_type, is_valid_ticker_input, normalize_ticker_symbol
|
||||
from tradingagents.dataflows.symbols import normalize_symbol
|
||||
|
||||
|
||||
# --- #982: stablecoin-quoted crypto normalizes to Yahoo's -USD pair ---
|
||||
@@ -66,10 +67,9 @@ def test_cli_normalize_delegates_to_data_layer():
|
||||
def test_the_run_directory_cannot_escape_the_results_directory(tmp_path, monkeypatch):
|
||||
"""Every other path that interpolates a ticker validates it first; the CLI's
|
||||
own results tree did not, so a ticker of '..' wrote a level up."""
|
||||
import cli.main as m
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
m._run_directory({"results_dir": str(tmp_path)}, "..", "2026-09-01")
|
||||
cli_run._run_directory({"results_dir": str(tmp_path)}, "..", "2026-09-01")
|
||||
|
||||
ok = m._run_directory({"results_dir": str(tmp_path)}, "NVDA", "2026-09-01")
|
||||
ok = cli_run._run_directory({"results_dir": str(tmp_path)}, "NVDA", "2026-09-01")
|
||||
assert str(ok).startswith(str(tmp_path))
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import unittest
|
||||
|
||||
from cli.models import AnalystType, AssetType
|
||||
from cli.utils import detect_asset_type, filter_analysts_for_asset_type
|
||||
from cli.prompts import detect_asset_type, filter_analysts_for_asset_type
|
||||
from tradingagents.graph.propagation import Propagator
|
||||
|
||||
|
||||
|
||||
@@ -59,3 +59,145 @@ class DataflowsConfigIsolationTests(unittest.TestCase):
|
||||
fresh = get_config()
|
||||
self.assertEqual(fresh["tool_vendors"]["get_stock_data"], "alpha_vantage")
|
||||
self.assertEqual(fresh["tool_vendors"]["get_news"], "alpha_vantage")
|
||||
|
||||
|
||||
# --- the config of the run in progress (#1369) --------------------------------
|
||||
|
||||
def _graph(config):
|
||||
from tradingagents.graph.trading_graph import TradingAgentsGraph
|
||||
|
||||
g = object.__new__(TradingAgentsGraph)
|
||||
g.config = config
|
||||
g._checkpointer_ctx = None
|
||||
return g
|
||||
|
||||
|
||||
def _vendors_seen_by_a_run(graph, ticker="AAPL"):
|
||||
from tradingagents.dataflows.router import get_vendor
|
||||
|
||||
seen = []
|
||||
|
||||
def _run(*a, **k):
|
||||
seen.append(get_vendor("fundamental_data", "get_balance_sheet"))
|
||||
return {}, "Hold"
|
||||
|
||||
graph._run_graph = _run
|
||||
graph.propagate(ticker, "2026-09-01")
|
||||
return seen
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_a_run_reads_its_own_graphs_vendors_not_the_last_graph_built():
|
||||
"""Building a graph sets the process-wide config, and set_config merges, so
|
||||
a second graph built with the defaults was served the first one's vendors."""
|
||||
first = copy.deepcopy(default_config.DEFAULT_CONFIG)
|
||||
first["tool_vendors"] = {"get_balance_sheet": "sec_edgar,yfinance"}
|
||||
set_config(first) # graph A is built
|
||||
second = _graph(copy.deepcopy(default_config.DEFAULT_CONFIG))
|
||||
|
||||
assert _vendors_seen_by_a_run(second) == ["yfinance"]
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_a_graph_built_earlier_still_runs_with_its_own_config():
|
||||
"""Scoping at construction would hand graph A graph B's config if B was built
|
||||
after A; the config must be bound when the run starts."""
|
||||
a_config = copy.deepcopy(default_config.DEFAULT_CONFIG)
|
||||
a_config["tool_vendors"] = {"get_balance_sheet": "sec_edgar,yfinance"}
|
||||
a = _graph(a_config)
|
||||
set_config(copy.deepcopy(default_config.DEFAULT_CONFIG)) # graph B is built
|
||||
|
||||
assert _vendors_seen_by_a_run(a) == ["sec_edgar,yfinance"]
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_concurrent_runs_each_read_their_own_config():
|
||||
import threading
|
||||
|
||||
barrier = threading.Barrier(2)
|
||||
results = {}
|
||||
|
||||
def run(name, vendor):
|
||||
config = copy.deepcopy(default_config.DEFAULT_CONFIG)
|
||||
config["tool_vendors"] = {"get_balance_sheet": vendor}
|
||||
graph = _graph(config)
|
||||
from tradingagents.dataflows.router import get_vendor
|
||||
|
||||
def _run(*a, **k):
|
||||
barrier.wait(timeout=5) # both runs are in flight
|
||||
results[name] = get_vendor("fundamental_data", "get_balance_sheet")
|
||||
return {}, "Hold"
|
||||
|
||||
graph._run_graph = _run
|
||||
graph.propagate("AAPL", "2026-09-01")
|
||||
|
||||
threads = [threading.Thread(target=run, args=("a", "alpha_vantage")),
|
||||
threading.Thread(target=run, args=("b", "sec_edgar,yfinance"))]
|
||||
[t.start() for t in threads]
|
||||
[t.join() for t in threads]
|
||||
|
||||
assert results == {"a": "alpha_vantage", "b": "sec_edgar,yfinance"}
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_settling_reads_the_graphs_own_config(monkeypatch):
|
||||
from tradingagents.dataflows.router import get_vendor
|
||||
|
||||
config = copy.deepcopy(default_config.DEFAULT_CONFIG)
|
||||
config["tool_vendors"] = {"get_stock_data": "alpha_vantage"}
|
||||
graph = _graph(config)
|
||||
graph.memory_log = graph.reflector = None # the settlement below is a stand-in
|
||||
seen = []
|
||||
from tradingagents.graph import settlement
|
||||
|
||||
monkeypatch.setattr(settlement, "settle_pending",
|
||||
lambda *a: seen.append(get_vendor("core_stock_apis", "get_stock_data")))
|
||||
|
||||
graph.settle_pending("AAPL")
|
||||
|
||||
assert seen == ["alpha_vantage"]
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_tools_inside_a_langgraph_run_see_the_run_config():
|
||||
"""The fix rests on LangGraph carrying the caller's context into tool calls."""
|
||||
from langchain_core.messages import AIMessage
|
||||
from langchain_core.tools import tool
|
||||
from langgraph.graph import END, START, MessagesState, StateGraph
|
||||
from langgraph.prebuilt import ToolNode
|
||||
|
||||
from tradingagents.dataflows.config import run_config
|
||||
from tradingagents.dataflows.router import get_vendor
|
||||
|
||||
@tool
|
||||
def probe() -> str:
|
||||
"""Report the vendor the run would use."""
|
||||
return get_vendor("fundamental_data", "get_balance_sheet")
|
||||
|
||||
def call(state):
|
||||
return {"messages": [AIMessage("", tool_calls=[{"name": "probe", "args": {}, "id": "1"}])]}
|
||||
|
||||
g = StateGraph(MessagesState)
|
||||
g.add_node("call", call)
|
||||
g.add_node("tools", ToolNode([probe]))
|
||||
g.add_edge(START, "call")
|
||||
g.add_edge("call", "tools")
|
||||
g.add_edge("tools", END)
|
||||
|
||||
config = copy.deepcopy(default_config.DEFAULT_CONFIG)
|
||||
config["tool_vendors"] = {"get_balance_sheet": "sec_edgar,yfinance"}
|
||||
with run_config(config):
|
||||
out = g.compile().invoke({"messages": [("user", "go")]})
|
||||
|
||||
assert out["messages"][-1].content == "sec_edgar,yfinance"
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_a_run_config_missing_a_newer_key_still_reads_the_default():
|
||||
"""A config saved before a key existed must not fail inside a run."""
|
||||
from tradingagents.dataflows.config import get_config, run_config
|
||||
|
||||
config = copy.deepcopy(default_config.DEFAULT_CONFIG)
|
||||
del config["news_article_limit"]
|
||||
with run_config(config):
|
||||
assert get_config()["news_article_limit"] == default_config.DEFAULT_CONFIG["news_article_limit"]
|
||||
|
||||
@@ -7,9 +7,9 @@ row omitted).
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
import tradingagents.dataflows.stockstats_utils as su
|
||||
import tradingagents.dataflows.y_finance as yfin
|
||||
import tradingagents.dataflows.vendors.yahoo.market as yfin
|
||||
from tradingagents.dataflows.config import set_config
|
||||
from tradingagents.dataflows.vendors.yahoo import ohlcv
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@@ -53,9 +53,9 @@ def test_load_ohlcv_requests_inclusive_end(monkeypatch, tmp_path):
|
||||
index=idx,
|
||||
)
|
||||
|
||||
monkeypatch.setattr(su.yf, "download", fake_download)
|
||||
monkeypatch.setattr(ohlcv.yf, "download", fake_download)
|
||||
today = pd.Timestamp.today().strftime("%Y-%m-%d")
|
||||
su.load_ohlcv("AAPL", today)
|
||||
ohlcv.load_ohlcv("AAPL", today)
|
||||
|
||||
expected_end = (pd.Timestamp.today() + pd.Timedelta(days=1)).strftime("%Y-%m-%d")
|
||||
assert captured["end"] == expected_end # tomorrow -> today's row included (#986)
|
||||
|
||||
@@ -12,12 +12,12 @@ from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from tradingagents.agents.context import opponent_argument_or_opening
|
||||
from tradingagents.agents.researchers.bear_researcher import create_bear_researcher
|
||||
from tradingagents.agents.researchers.bull_researcher import create_bull_researcher
|
||||
from tradingagents.agents.risk_mgmt.aggressive_debator import create_aggressive_debator
|
||||
from tradingagents.agents.risk_mgmt.conservative_debator import create_conservative_debator
|
||||
from tradingagents.agents.risk_mgmt.neutral_debator import create_neutral_debator
|
||||
from tradingagents.agents.utils.agent_utils import opponent_argument_or_opening
|
||||
|
||||
_REPORTS = {
|
||||
"company_of_interest": "AAPL", "asset_type": "stock",
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -21,8 +22,8 @@ def _reload_with_env(monkeypatch, **overrides):
|
||||
def test_no_env_uses_built_in_defaults(monkeypatch):
|
||||
dc = _reload_with_env(monkeypatch)
|
||||
assert dc.DEFAULT_CONFIG["llm_provider"] == "openai"
|
||||
assert dc.DEFAULT_CONFIG["deep_think_llm"] == "gpt-5.6"
|
||||
assert dc.DEFAULT_CONFIG["quick_think_llm"] == "gpt-5.6-luna"
|
||||
assert dc.DEFAULT_CONFIG["deep_think_llm"] == "gpt-6-sol"
|
||||
assert dc.DEFAULT_CONFIG["quick_think_llm"] == "gpt-6-luna"
|
||||
assert dc.DEFAULT_CONFIG["backend_url"] is None
|
||||
assert dc.DEFAULT_CONFIG["max_debate_rounds"] == 1
|
||||
assert dc.DEFAULT_CONFIG["checkpoint_enabled"] is False
|
||||
@@ -100,6 +101,21 @@ def test_empty_env_value_is_passthrough(monkeypatch):
|
||||
assert dc.DEFAULT_CONFIG["max_debate_rounds"] == 1
|
||||
|
||||
|
||||
def test_empty_path_value_keeps_the_default_path(monkeypatch):
|
||||
""".env.example lists the path variables blank; uncommenting one made the
|
||||
path empty, and the graph failed creating its directories."""
|
||||
dc = _reload_with_env(
|
||||
monkeypatch,
|
||||
TRADINGAGENTS_RESULTS_DIR="",
|
||||
TRADINGAGENTS_CACHE_DIR="",
|
||||
TRADINGAGENTS_MEMORY_LOG_PATH="",
|
||||
)
|
||||
home = dc._TRADINGAGENTS_HOME
|
||||
assert dc.DEFAULT_CONFIG["results_dir"] == os.path.join(home, "logs")
|
||||
assert dc.DEFAULT_CONFIG["data_cache_dir"] == os.path.join(home, "cache")
|
||||
assert dc.DEFAULT_CONFIG["memory_log_path"] == os.path.join(home, "memory", "trading_memory.md")
|
||||
|
||||
|
||||
def test_invalid_int_raises(monkeypatch):
|
||||
"""Garbage int values should surface a ValueError at import, not silently misconfigure."""
|
||||
monkeypatch.setenv("TRADINGAGENTS_MAX_DEBATE_ROUNDS", "not-a-number")
|
||||
|
||||
+10
-9
@@ -12,8 +12,9 @@ import requests
|
||||
|
||||
import tradingagents.dataflows.config as config_module
|
||||
import tradingagents.default_config as default_config
|
||||
from tradingagents.dataflows import fred, interface
|
||||
from tradingagents.dataflows import router
|
||||
from tradingagents.dataflows.config import set_config
|
||||
from tradingagents.dataflows.vendors import fred
|
||||
|
||||
# A small, stable set of observations to format against.
|
||||
_META = {
|
||||
@@ -203,15 +204,15 @@ class FredRoutingTests(unittest.TestCase):
|
||||
|
||||
def test_macro_category_routes_to_fred(self):
|
||||
self.assertEqual(
|
||||
interface.get_category_for_method("get_macro_indicators"), "macro_data"
|
||||
router.get_category_for_method("get_macro_indicators"), "macro_data"
|
||||
)
|
||||
set_config({"data_vendors": {"macro_data": "fred"}})
|
||||
with mock.patch.dict(
|
||||
interface.VENDOR_METHODS,
|
||||
router.VENDOR_METHODS,
|
||||
{"get_macro_indicators": {"fred": lambda *a, **k: "MACRO_OK"}},
|
||||
clear=False,
|
||||
):
|
||||
out = interface.route_to_vendor("get_macro_indicators", "cpi", "2026-06-01", 365)
|
||||
out = router.route_to_vendor("get_macro_indicators", "cpi", "2026-06-01", 365)
|
||||
self.assertEqual(out, "MACRO_OK")
|
||||
|
||||
def test_not_configured_degrades_gracefully(self):
|
||||
@@ -224,11 +225,11 @@ class FredRoutingTests(unittest.TestCase):
|
||||
raise fred.FredNotConfiguredError("FRED_API_KEY not set")
|
||||
|
||||
with mock.patch.dict(
|
||||
interface.VENDOR_METHODS,
|
||||
router.VENDOR_METHODS,
|
||||
{"get_macro_indicators": {"fred": _unconfigured}},
|
||||
clear=False,
|
||||
):
|
||||
out = interface.route_to_vendor("get_macro_indicators", "cpi", "2026-06-01", 365)
|
||||
out = router.route_to_vendor("get_macro_indicators", "cpi", "2026-06-01", 365)
|
||||
self.assertIn("DATA_UNAVAILABLE", out)
|
||||
|
||||
|
||||
@@ -246,7 +247,7 @@ class TestKeyKeptOutOfErrors:
|
||||
|
||||
def _raises(self, side_effect):
|
||||
with mock.patch.dict("os.environ", {"FRED_API_KEY": _KEY}), \
|
||||
mock.patch("tradingagents.dataflows.utils.requests.get", side_effect=side_effect), \
|
||||
mock.patch("tradingagents.dataflows.net.requests.get", side_effect=side_effect), \
|
||||
pytest.raises(requests.RequestException) as caught:
|
||||
fred._request("series", {"series_id": "DGS10"})
|
||||
return caught.value
|
||||
@@ -258,7 +259,7 @@ class TestKeyKeptOutOfErrors:
|
||||
response=response,
|
||||
)
|
||||
with mock.patch.dict("os.environ", {"FRED_API_KEY": _KEY}), \
|
||||
mock.patch("tradingagents.dataflows.utils.requests.get", return_value=response), \
|
||||
mock.patch("tradingagents.dataflows.net.requests.get", return_value=response), \
|
||||
pytest.raises(requests.HTTPError) as caught:
|
||||
fred._request("series", {"series_id": "DGS10"})
|
||||
exc = caught.value
|
||||
@@ -280,7 +281,7 @@ def test_error_without_the_key_in_its_message_still_drops_the_request():
|
||||
import requests as rq
|
||||
req = rq.Request("GET", f"https://api.stlouisfed.org/fred/series?api_key={_KEY}").prepare()
|
||||
with mock.patch.dict("os.environ", {"FRED_API_KEY": _KEY}), \
|
||||
mock.patch("tradingagents.dataflows.utils.requests.get", side_effect=rq.Timeout("Read timed out.", request=req)), \
|
||||
mock.patch("tradingagents.dataflows.net.requests.get", side_effect=rq.Timeout("Read timed out.", request=req)), \
|
||||
pytest.raises(rq.Timeout) as caught:
|
||||
fred._request("series", {"series_id": "DGS10"})
|
||||
assert caught.value.request is None
|
||||
|
||||
@@ -19,7 +19,12 @@ from unittest import mock
|
||||
|
||||
import pytest
|
||||
|
||||
from tradingagents.dataflows import alpha_vantage_fundamentals as av, date_window, y_finance
|
||||
from tradingagents.dataflows import date_window
|
||||
from tradingagents.dataflows.vendors.alpha_vantage import fundamentals as av
|
||||
from tradingagents.dataflows.vendors.yahoo import (
|
||||
fundamentals as yahoo_fundamentals,
|
||||
market as yahoo_market,
|
||||
)
|
||||
|
||||
_TODAY = "2026-09-07"
|
||||
_PAST = "2024-05-10"
|
||||
@@ -42,9 +47,9 @@ _LEAKY = ("3500000000000", "34.2", "260.1", "391000000000",
|
||||
|
||||
def _yf(curr_date, info=_INFO, today=_TODAY):
|
||||
with mock.patch.object(date_window, "get_current_date", return_value=today), \
|
||||
mock.patch.object(y_finance, "yf_retry", lambda fn: info), \
|
||||
mock.patch.object(y_finance.yf, "Ticker"):
|
||||
return y_finance.get_fundamentals("AAPL", curr_date)
|
||||
mock.patch.object(yahoo_fundamentals, "yf_retry", lambda fn: info), \
|
||||
mock.patch.object(yahoo_market.yf, "Ticker"):
|
||||
return yahoo_fundamentals.get_fundamentals("AAPL", curr_date)
|
||||
|
||||
|
||||
def _av(curr_date, today=_TODAY):
|
||||
@@ -68,7 +73,7 @@ class TestYFinanceHistoricalRun:
|
||||
out = _yf(_PAST)
|
||||
assert f"Point-in-time as of: {_PAST}" in out
|
||||
assert "withheld" in out
|
||||
assert _PAST in out and _TODAY in out
|
||||
assert _PAST in out and _TODAY not in out
|
||||
|
||||
def test_no_wall_clock_retrieval_stamp(self):
|
||||
# The old header stamped datetime.now(), which is what surfaced the leak.
|
||||
@@ -78,8 +83,8 @@ class TestYFinanceHistoricalRun:
|
||||
# The response would only be discarded; skipping it also avoids burning
|
||||
# vendor quota on a call whose result cannot be used.
|
||||
with mock.patch.object(date_window, "get_current_date", return_value=_TODAY), \
|
||||
mock.patch.object(y_finance.yf, "Ticker") as tk:
|
||||
y_finance.get_fundamentals("AAPL", _PAST)
|
||||
mock.patch.object(yahoo_market.yf, "Ticker") as tk:
|
||||
yahoo_fundamentals.get_fundamentals("AAPL", _PAST)
|
||||
tk.assert_not_called()
|
||||
|
||||
|
||||
@@ -110,7 +115,6 @@ class TestLiveRunUnchanged:
|
||||
out = _yf(_TODAY)
|
||||
for value in _LEAKY:
|
||||
assert value in out
|
||||
assert "Data retrieved on:" in out
|
||||
assert "withheld" not in out
|
||||
|
||||
def test_yfinance_absent_curr_date_returns_the_full_profile(self):
|
||||
@@ -124,7 +128,7 @@ class TestNoUsableFieldsStillRaises:
|
||||
def test_stub_payload_raises_no_market_data(self):
|
||||
# yfinance returns {"trailingPegRatio": None} for unknown symbols; on a
|
||||
# live run that must stay a hard "no data", not a bare header.
|
||||
from tradingagents.dataflows.symbol_utils import NoMarketDataError
|
||||
from tradingagents.dataflows.errors import NoMarketDataError
|
||||
|
||||
with pytest.raises(NoMarketDataError):
|
||||
_yf(_TODAY, info={"trailingPegRatio": None})
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
"""The whole graph, end to end, with scripted models and no network.
|
||||
|
||||
Every tool-using analyst calls each of its tools once through the vendor router,
|
||||
the debates and managers run, and the decision is parsed and logged. This pins
|
||||
the wiring: a restructure that drops a node, a tool or an edge fails here.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
|
||||
import pandas as pd
|
||||
import pytest
|
||||
from langchain_core.language_models.chat_models import BaseChatModel
|
||||
from langchain_core.messages import AIMessage, ToolMessage
|
||||
from langchain_core.outputs import ChatGeneration, ChatResult
|
||||
from langchain_core.runnables import RunnableLambda
|
||||
from pydantic import Field
|
||||
|
||||
from tradingagents.agents import context, schemas
|
||||
from tradingagents.agents.analysts import sentiment_analyst
|
||||
from tradingagents.dataflows import router
|
||||
from tradingagents.dataflows.vendors.yahoo import market as yahoo_market, snapshot
|
||||
from tradingagents.default_config import DEFAULT_CONFIG
|
||||
from tradingagents.graph import trading_graph
|
||||
|
||||
TRADE_DATE = "2026-01-09"
|
||||
|
||||
# Enough for every free-text reader: the PM's labelled rating and the trader's
|
||||
# closing proposal line.
|
||||
TEXT = "Report.\n\n**Rating**: Overweight\n\nFINAL TRANSACTION PROPOSAL: **BUY**"
|
||||
|
||||
STRUCTURED = {
|
||||
schemas.ResearchPlan: schemas.ResearchPlan(
|
||||
recommendation=schemas.PortfolioRating.OVERWEIGHT, rationale="r", strategic_actions="a"),
|
||||
schemas.TraderProposal: schemas.TraderProposal(action=schemas.TraderAction.BUY, reasoning="r"),
|
||||
schemas.PortfolioDecision: schemas.PortfolioDecision(
|
||||
rating=schemas.PortfolioRating.OVERWEIGHT, executive_summary="s", investment_thesis="t"),
|
||||
schemas.SentimentReport: schemas.SentimentReport(
|
||||
overall_band=schemas.SentimentBand.NEUTRAL, overall_score=5.0, confidence="low", narrative="n"),
|
||||
}
|
||||
|
||||
ARGS = {"symbol": "NVDA", "ticker": "NVDA", "curr_date": TRADE_DATE, "start_date": "2026-01-02",
|
||||
"end_date": TRADE_DATE, "indicator": "rsi", "topic": "Fed rate cut", "freq": "quarterly"}
|
||||
|
||||
|
||||
class ScriptedModel(BaseChatModel):
|
||||
"""Calls every bound tool once, then answers with TEXT."""
|
||||
|
||||
structured: bool = False
|
||||
tools: tuple = ()
|
||||
calls: list = Field(default_factory=list) # shared across bound copies
|
||||
fail_at: int | None = None # raise on this call, once
|
||||
|
||||
@property
|
||||
def _llm_type(self) -> str:
|
||||
return "scripted"
|
||||
|
||||
def bind_tools(self, tools, **kwargs):
|
||||
return self.model_copy(update={"tools": tuple(tools)})
|
||||
|
||||
def with_structured_output(self, schema, **kwargs):
|
||||
if not self.structured:
|
||||
raise NotImplementedError
|
||||
return RunnableLambda(lambda _: self._count() or STRUCTURED[schema])
|
||||
|
||||
def _count(self) -> None:
|
||||
self.calls.append(1)
|
||||
if len(self.calls) == self.fail_at:
|
||||
raise RuntimeError("provider unavailable")
|
||||
|
||||
def _generate(self, messages, stop=None, run_manager=None, **kwargs) -> ChatResult:
|
||||
self._count()
|
||||
if self.tools and not isinstance(messages[-1], ToolMessage):
|
||||
calls = [{"name": t.name, "id": f"call_{i}",
|
||||
"args": {k: v for k, v in ARGS.items()
|
||||
if k in t.tool_call_schema.model_json_schema()["properties"]}}
|
||||
for i, t in enumerate(self.tools)]
|
||||
message = AIMessage(content="", tool_calls=calls)
|
||||
else:
|
||||
message = AIMessage(content=TEXT)
|
||||
return ChatResult(generations=[ChatGeneration(message=message)])
|
||||
|
||||
|
||||
class _Client:
|
||||
def __init__(self, model):
|
||||
self.model = model
|
||||
|
||||
def get_llm(self):
|
||||
return self.model
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def offline(monkeypatch, tmp_path):
|
||||
"""Every vendor answers offline; returns the set of router methods called."""
|
||||
called: set[str] = set()
|
||||
for method, vendors in router.VENDOR_METHODS.items():
|
||||
for vendor in vendors:
|
||||
monkeypatch.setitem(vendors, vendor,
|
||||
lambda *a, _m=method, **k: called.add(_m) or f"{_m} data")
|
||||
prices = pd.DataFrame({
|
||||
"Date": pd.bdate_range(end=TRADE_DATE, periods=60),
|
||||
"Open": 100.0, "High": 101.0, "Low": 99.0, "Close": 100.5, "Volume": 1_000_000,
|
||||
})
|
||||
monkeypatch.setattr(snapshot, "load_ohlcv",
|
||||
lambda *a, **k: called.add("ohlcv") or prices.copy())
|
||||
monkeypatch.setattr(sentiment_analyst, "fetch_stocktwits_messages", lambda *a, **k: "no posts")
|
||||
monkeypatch.setattr(sentiment_analyst, "fetch_reddit_posts", lambda *a, **k: "no posts")
|
||||
monkeypatch.setattr(yahoo_market.yf, "Ticker", lambda s: type("T", (), {"info": {"longName": "NVIDIA"}})())
|
||||
context.resolve_instrument_identity.cache_clear()
|
||||
return called
|
||||
|
||||
|
||||
def _graph(tmp_path, monkeypatch, model, **config):
|
||||
cfg = copy.deepcopy(DEFAULT_CONFIG)
|
||||
cfg.update(results_dir=str(tmp_path / "results"), data_cache_dir=str(tmp_path / "cache"),
|
||||
memory_log_path=str(tmp_path / "log.md"), **config)
|
||||
monkeypatch.setattr(trading_graph, "create_llm_client", lambda **k: _Client(model))
|
||||
return trading_graph.TradingAgentsGraph(config=cfg)
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.parametrize("structured", [False, True], ids=["free-text", "structured"])
|
||||
def test_a_full_run_reaches_a_logged_decision(tmp_path, monkeypatch, offline, structured):
|
||||
graph = _graph(tmp_path, monkeypatch, ScriptedModel(structured=structured))
|
||||
|
||||
state, signal = graph.propagate("NVDA", TRADE_DATE)
|
||||
|
||||
assert signal == "Overweight"
|
||||
for key in ("market_report", "sentiment_report", "news_report", "fundamentals_report",
|
||||
"investment_plan", "trader_investment_plan", "final_trade_decision"):
|
||||
assert state[key].strip(), key
|
||||
tool_methods = {"get_stock_data", "get_indicators", "get_news", "get_global_news",
|
||||
"get_macro_indicators", "get_prediction_markets", "get_fundamentals",
|
||||
"get_balance_sheet", "get_cashflow", "get_income_statement",
|
||||
"get_insider_transactions", "ohlcv"}
|
||||
assert offline == tool_methods
|
||||
assert [e["rating"] for e in graph.memory_log.load_entries()] == ["Overweight"]
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_an_interrupted_run_resumes_from_its_checkpoint(tmp_path, monkeypatch, offline):
|
||||
model = ScriptedModel(fail_at=12) # past the analysts, before the decision
|
||||
graph = _graph(tmp_path, monkeypatch, model, checkpoint_enabled=True)
|
||||
with pytest.raises(RuntimeError, match="provider unavailable"):
|
||||
graph.propagate("NVDA", TRADE_DATE)
|
||||
calls_before = len(model.calls)
|
||||
|
||||
_, signal = graph.propagate("NVDA", TRADE_DATE)
|
||||
|
||||
assert signal == "Overweight"
|
||||
resumed_calls = len(model.calls) - calls_before
|
||||
full_run = ScriptedModel()
|
||||
_graph(tmp_path / "fresh", monkeypatch, full_run).propagate("NVDA", TRADE_DATE)
|
||||
# The resumed run makes only the calls the interrupted one had not completed.
|
||||
assert resumed_calls == len(full_run.calls) - (model.fail_at - 1)
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_a_graph_reused_across_runs_keeps_no_run_state(tmp_path, monkeypatch, offline):
|
||||
"""A backtest reuses one graph over its whole grid; holding every run's full
|
||||
state would grow without bound."""
|
||||
graph = _graph(tmp_path, monkeypatch, ScriptedModel())
|
||||
for trade_date in ("2026-01-08", TRADE_DATE):
|
||||
graph.propagate("NVDA", trade_date)
|
||||
|
||||
held = [v for v in vars(graph).values() if isinstance(v, dict) and TRADE_DATE in v]
|
||||
assert held == []
|
||||
assert len(list(tmp_path.glob("results/NVDA/TradingAgentsStrategy_logs/*.json"))) == 2
|
||||
@@ -10,7 +10,7 @@ from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from tradingagents.agents.utils.agent_utils import get_language_instruction
|
||||
from tradingagents.agents.context import get_language_instruction
|
||||
|
||||
_AGENTS_DIR = Path(__file__).resolve().parents[1] / "tradingagents" / "agents"
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ from unittest.mock import patch
|
||||
import pytest
|
||||
from langchain_core.messages import AIMessage, HumanMessage, RemoveMessage
|
||||
|
||||
from tradingagents.agents.utils.agent_utils import (
|
||||
from tradingagents.agents.context import (
|
||||
build_instrument_context,
|
||||
create_msg_delete,
|
||||
get_instrument_context_from_state,
|
||||
@@ -21,7 +21,7 @@ class ResolveInstrumentIdentityTests(unittest.TestCase):
|
||||
resolve_instrument_identity.cache_clear()
|
||||
|
||||
def test_resolves_company_metadata_from_yfinance(self):
|
||||
with patch("tradingagents.agents.utils.agent_utils.yf.Ticker") as mock:
|
||||
with patch("tradingagents.dataflows.vendors.yahoo.market.yf.Ticker") as mock:
|
||||
mock.return_value.info = {
|
||||
"longName": "TOTO LTD.",
|
||||
"shortName": "TOTO",
|
||||
@@ -38,26 +38,26 @@ class ResolveInstrumentIdentityTests(unittest.TestCase):
|
||||
self.assertEqual(identity["exchange"], "PNK")
|
||||
|
||||
def test_falls_back_to_short_name(self):
|
||||
with patch("tradingagents.agents.utils.agent_utils.yf.Ticker") as mock:
|
||||
with patch("tradingagents.dataflows.vendors.yahoo.market.yf.Ticker") as mock:
|
||||
mock.return_value.info = {"shortName": "TOTO", "sector": "Industrials"}
|
||||
identity = resolve_instrument_identity("TOTDY")
|
||||
self.assertEqual(identity["company_name"], "TOTO")
|
||||
|
||||
def test_skips_placeholder_values(self):
|
||||
with patch("tradingagents.agents.utils.agent_utils.yf.Ticker") as mock:
|
||||
with patch("tradingagents.dataflows.vendors.yahoo.market.yf.Ticker") as mock:
|
||||
mock.return_value.info = {"longName": " ", "sector": "None", "industry": "n/a"}
|
||||
identity = resolve_instrument_identity("TOTDY")
|
||||
self.assertEqual(identity, {})
|
||||
|
||||
def test_fails_open_on_exception(self):
|
||||
with patch(
|
||||
"tradingagents.agents.utils.agent_utils.yf.Ticker",
|
||||
"tradingagents.dataflows.vendors.yahoo.market.yf.Ticker",
|
||||
side_effect=RuntimeError("rate limited"),
|
||||
):
|
||||
self.assertEqual(resolve_instrument_identity("TOTDY"), {})
|
||||
|
||||
def test_result_is_cached(self):
|
||||
with patch("tradingagents.agents.utils.agent_utils.yf.Ticker") as mock:
|
||||
with patch("tradingagents.dataflows.vendors.yahoo.market.yf.Ticker") as mock:
|
||||
mock.return_value.info = {"longName": "TOTO LTD."}
|
||||
first = resolve_instrument_identity("TOTDY")
|
||||
second = resolve_instrument_identity("TOTDY")
|
||||
@@ -104,7 +104,7 @@ class GetInstrumentContextFromStateTests(unittest.TestCase):
|
||||
|
||||
def test_fallback_is_network_free_ticker_only(self):
|
||||
# No instrument_context and no yfinance call — must not hit the network.
|
||||
with patch("tradingagents.agents.utils.agent_utils.yf.Ticker") as mock:
|
||||
with patch("tradingagents.dataflows.vendors.yahoo.market.yf.Ticker") as mock:
|
||||
context = get_instrument_context_from_state(
|
||||
{"company_of_interest": "NVDA", "asset_type": "stock"}
|
||||
)
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
"""Only the data layer imports vendor libraries.
|
||||
|
||||
Vendor calls belong in dataflows, where failures are raised as VendorError
|
||||
subclasses; a call made elsewhere can report an outage as a fact about the market.
|
||||
"""
|
||||
|
||||
import ast
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
VENDOR_LIBRARIES = {"yfinance"}
|
||||
|
||||
|
||||
def _imports(path: Path) -> set[str]:
|
||||
names = set()
|
||||
for node in ast.walk(ast.parse(path.read_text(encoding="utf-8"))):
|
||||
if isinstance(node, ast.Import):
|
||||
names |= {a.name.split(".")[0] for a in node.names}
|
||||
elif isinstance(node, ast.ImportFrom) and node.module and not node.level:
|
||||
names.add(node.module.split(".")[0])
|
||||
return names
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_vendor_libraries_are_imported_only_by_the_data_layer():
|
||||
data_layer = ROOT / "tradingagents" / "dataflows"
|
||||
offenders = sorted(
|
||||
str(path.relative_to(ROOT))
|
||||
for package in ("tradingagents", "cli")
|
||||
for path in (ROOT / package).rglob("*.py")
|
||||
if data_layer not in path.parents and _imports(path) & VENDOR_LIBRARIES
|
||||
)
|
||||
assert offenders == []
|
||||
@@ -11,10 +11,11 @@ import importlib
|
||||
import pytest
|
||||
|
||||
import tradingagents.default_config as default_config_module
|
||||
from tradingagents.graph.trading_graph import TradingAgentsGraph, _coerce_max_retries
|
||||
from tradingagents.llm_clients.factory import _coerce_max_retries, build_llm_kwargs
|
||||
|
||||
# --- coercion / validation -------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.parametrize("value,expected", [(0, 0), (2, 2), (10, 10), ("6", 6)])
|
||||
def test_coerce_accepts_non_negative_ints_and_numeric_strings(value, expected):
|
||||
@@ -44,36 +45,31 @@ def test_coerce_rejects_non_integers(bad):
|
||||
|
||||
# --- forwarding into provider kwargs --------------------------------------
|
||||
|
||||
def _bare_graph(config):
|
||||
g = object.__new__(TradingAgentsGraph)
|
||||
g.config = config
|
||||
return g
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_not_forwarded_when_unset():
|
||||
kwargs = _bare_graph({"llm_provider": "openai", "llm_max_retries": None})._get_provider_kwargs()
|
||||
kwargs = build_llm_kwargs({"llm_provider": "openai", "llm_max_retries": None})
|
||||
assert "max_retries" not in kwargs
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.parametrize("provider", ["openai", "anthropic", "google"])
|
||||
def test_forwarded_across_providers(provider):
|
||||
kwargs = _bare_graph({"llm_provider": provider, "llm_max_retries": 6})._get_provider_kwargs()
|
||||
kwargs = build_llm_kwargs({"llm_provider": provider, "llm_max_retries": 6})
|
||||
assert kwargs["max_retries"] == 6
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_forwarded_env_string_is_coerced():
|
||||
# env vars arrive as strings; the consumer coerces (like temperature)
|
||||
kwargs = _bare_graph({"llm_provider": "openai", "llm_max_retries": "4"})._get_provider_kwargs()
|
||||
kwargs = build_llm_kwargs({"llm_provider": "openai", "llm_max_retries": "4"})
|
||||
assert kwargs["max_retries"] == 4
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_invalid_config_value_fails_loudly():
|
||||
with pytest.raises(ValueError):
|
||||
_bare_graph({"llm_provider": "openai", "llm_max_retries": -1})._get_provider_kwargs()
|
||||
build_llm_kwargs({"llm_provider": "openai", "llm_max_retries": -1})
|
||||
|
||||
|
||||
# --- env overlay -----------------------------------------------------------
|
||||
|
||||
@@ -13,10 +13,11 @@ import importlib
|
||||
import pytest
|
||||
|
||||
import tradingagents.default_config as default_config_module
|
||||
from tradingagents.graph.trading_graph import TradingAgentsGraph, _coerce_max_tokens
|
||||
from tradingagents.llm_clients.factory import _coerce_max_tokens, build_llm_kwargs
|
||||
|
||||
# --- coercion / validation -------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.parametrize("value,expected", [(1, 1), (8192, 8192), ("4096", 4096)])
|
||||
def test_coerce_accepts_positive_ints_and_numeric_strings(value, expected):
|
||||
@@ -46,15 +47,10 @@ def test_coerce_rejects_non_integers(bad):
|
||||
|
||||
# --- forwarding into provider kwargs (right key per provider) --------------
|
||||
|
||||
def _bare_graph(config):
|
||||
g = object.__new__(TradingAgentsGraph)
|
||||
g.config = config
|
||||
return g
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_not_forwarded_when_unset():
|
||||
kwargs = _bare_graph({"llm_provider": "openai", "max_tokens": None})._get_provider_kwargs()
|
||||
kwargs = build_llm_kwargs({"llm_provider": "openai", "max_tokens": None})
|
||||
assert "max_tokens" not in kwargs
|
||||
assert "max_output_tokens" not in kwargs
|
||||
|
||||
@@ -62,7 +58,7 @@ def test_not_forwarded_when_unset():
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.parametrize("provider", ["openai", "anthropic", "deepseek", "openai_compatible"])
|
||||
def test_forwarded_as_max_tokens_for_non_google(provider):
|
||||
kwargs = _bare_graph({"llm_provider": provider, "max_tokens": 8192})._get_provider_kwargs()
|
||||
kwargs = build_llm_kwargs({"llm_provider": provider, "max_tokens": 8192})
|
||||
assert kwargs["max_tokens"] == 8192
|
||||
assert "max_output_tokens" not in kwargs
|
||||
|
||||
@@ -70,21 +66,21 @@ def test_forwarded_as_max_tokens_for_non_google(provider):
|
||||
@pytest.mark.unit
|
||||
def test_forwarded_as_max_output_tokens_for_google():
|
||||
# Gemini's kwarg name differs; forwarding plain max_tokens would be rejected.
|
||||
kwargs = _bare_graph({"llm_provider": "google", "max_tokens": 8192})._get_provider_kwargs()
|
||||
kwargs = build_llm_kwargs({"llm_provider": "google", "max_tokens": 8192})
|
||||
assert kwargs["max_output_tokens"] == 8192
|
||||
assert "max_tokens" not in kwargs
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_env_string_is_coerced():
|
||||
kwargs = _bare_graph({"llm_provider": "openai", "max_tokens": "4096"})._get_provider_kwargs()
|
||||
kwargs = build_llm_kwargs({"llm_provider": "openai", "max_tokens": "4096"})
|
||||
assert kwargs["max_tokens"] == 4096
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_invalid_value_fails_loudly():
|
||||
with pytest.raises(ValueError):
|
||||
_bare_graph({"llm_provider": "openai", "max_tokens": 0})._get_provider_kwargs()
|
||||
build_llm_kwargs({"llm_provider": "openai", "max_tokens": 0})
|
||||
|
||||
|
||||
# --- client-side allowlists carry the kwarg --------------------------------
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
"""The market analyst is bound (and prompt-instructed) to call
|
||||
get_verified_market_snapshot; if the executor ToolNode doesn't register it, the
|
||||
call fails and the model reports the tool "unavailable" and skips verification.
|
||||
|
||||
Regression guard for that wiring gap (snapshot bound to the LLM but missing from
|
||||
the market ToolNode).
|
||||
"""
|
||||
import pytest
|
||||
|
||||
from tradingagents.graph.trading_graph import TradingAgentsGraph
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_market_toolnode_can_execute_verified_snapshot():
|
||||
# _create_tool_nodes does not use self -> call unbound (avoids building LLMs).
|
||||
nodes = TradingAgentsGraph._create_tool_nodes(None)
|
||||
market_tools = set(nodes["market"].tools_by_name)
|
||||
assert "get_verified_market_snapshot" in market_tools, (
|
||||
"get_verified_market_snapshot is bound to the market analyst but not "
|
||||
"registered in the market ToolNode, so the model's call fails."
|
||||
)
|
||||
# the other core market tools must remain too
|
||||
assert {"get_stock_data", "get_indicators"} <= market_tools
|
||||
+67
-86
@@ -7,7 +7,8 @@ import pytest
|
||||
|
||||
from tradingagents.agents.managers.portfolio_manager import create_portfolio_manager
|
||||
from tradingagents.agents.schemas import PortfolioDecision, PortfolioRating
|
||||
from tradingagents.agents.utils.memory import TradingMemoryLog
|
||||
from tradingagents.decision_log import TradingMemoryLog
|
||||
from tradingagents.graph import settlement
|
||||
from tradingagents.graph.propagation import Propagator
|
||||
from tradingagents.graph.reflection import Reflector
|
||||
from tradingagents.graph.trading_graph import TradingAgentsGraph
|
||||
@@ -196,7 +197,7 @@ class TestTradingMemoryLogCore:
|
||||
def test_an_unreadable_decision_is_tagged_for_review(self, tmp_path):
|
||||
"""Not a Hold: a fabricated rating is quoted back to the next run as a
|
||||
call that was never made, and counted in the backtest figures."""
|
||||
from tradingagents.agents.utils.rating import RATING_REVIEW
|
||||
from tradingagents.agents.rating import RATING_REVIEW
|
||||
|
||||
log = make_log(tmp_path)
|
||||
log.store_decision("MSFT", "2026-01-12", DECISION_NO_RATING)
|
||||
@@ -407,7 +408,7 @@ class TestTradingMemoryLogCore:
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Deferred reflection: update_with_outcome, Reflector, _fetch_returns
|
||||
# Deferred reflection: update_with_outcome, Reflector, fetch_returns
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestDeferredReflection:
|
||||
@@ -510,19 +511,18 @@ class TestDeferredReflection:
|
||||
assert "-5.0%" in human_content
|
||||
assert "Exit position immediately." in human_content
|
||||
|
||||
# TradingAgentsGraph._fetch_returns
|
||||
# settlement.fetch_returns
|
||||
|
||||
def test_fetch_returns_valid_ticker(self):
|
||||
stock_prices = [100.0, 102.0, 104.0, 103.0, 105.0, 106.0]
|
||||
spy_prices = [400.0, 402.0, 404.0, 403.0, 405.0, 406.0]
|
||||
mock_graph = MagicMock(spec=TradingAgentsGraph)
|
||||
with patch("yfinance.Ticker") as mock_ticker_cls:
|
||||
def _make_ticker(sym):
|
||||
m = MagicMock()
|
||||
m.history.return_value = _price_df(spy_prices if sym == "SPY" else stock_prices)
|
||||
return m
|
||||
mock_ticker_cls.side_effect = _make_ticker
|
||||
raw, alpha, days, resolved = TradingAgentsGraph._fetch_returns(mock_graph, "NVDA", "2026-01-05")
|
||||
raw, alpha, days, resolved = settlement.fetch_returns("NVDA", "2026-01-05")
|
||||
assert raw is not None and alpha is not None and days is not None
|
||||
assert isinstance(raw, float) and isinstance(alpha, float) and isinstance(days, int)
|
||||
assert days == 5
|
||||
@@ -531,22 +531,20 @@ class TestDeferredReflection:
|
||||
|
||||
def test_fetch_returns_too_recent(self):
|
||||
"""Only 1 data point available → returns all-None, no crash."""
|
||||
mock_graph = MagicMock(spec=TradingAgentsGraph)
|
||||
with patch("yfinance.Ticker") as mock_ticker_cls:
|
||||
m = MagicMock()
|
||||
m.history.return_value = _price_df([100.0])
|
||||
mock_ticker_cls.return_value = m
|
||||
raw, alpha, days, resolved = TradingAgentsGraph._fetch_returns(mock_graph, "NVDA", "2026-04-19")
|
||||
raw, alpha, days, resolved = settlement.fetch_returns("NVDA", "2026-04-19")
|
||||
assert (raw, alpha, days, resolved) == (None, None, None, None)
|
||||
|
||||
def test_fetch_returns_delisted(self):
|
||||
"""Empty DataFrame → returns all-None, no crash."""
|
||||
mock_graph = MagicMock(spec=TradingAgentsGraph)
|
||||
with patch("yfinance.Ticker") as mock_ticker_cls:
|
||||
m = MagicMock()
|
||||
m.history.return_value = pd.DataFrame({"Close": []})
|
||||
mock_ticker_cls.return_value = m
|
||||
raw, alpha, days, resolved = TradingAgentsGraph._fetch_returns(mock_graph, "XXXXXFAKE", "2026-01-10")
|
||||
raw, alpha, days, resolved = settlement.fetch_returns("XXXXXFAKE", "2026-01-10")
|
||||
assert (raw, alpha, days, resolved) == (None, None, None, None)
|
||||
|
||||
def test_fetch_returns_spy_shorter_than_stock(self):
|
||||
@@ -554,14 +552,13 @@ class TestDeferredReflection:
|
||||
not raise IndexError."""
|
||||
stock_prices = [100.0, 102.0, 104.0, 103.0, 105.0, 106.0, 107.0, 108.0] # 8 rows
|
||||
spy_prices = [400.0, 402.0, 403.0, 405.0, 406.0, 407.0] # 6 rows
|
||||
mock_graph = MagicMock(spec=TradingAgentsGraph)
|
||||
with patch("yfinance.Ticker") as mock_ticker_cls:
|
||||
def _make_ticker(sym):
|
||||
m = MagicMock()
|
||||
m.history.return_value = _price_df(spy_prices if sym == "SPY" else stock_prices)
|
||||
return m
|
||||
mock_ticker_cls.side_effect = _make_ticker
|
||||
raw, alpha, days, resolved = TradingAgentsGraph._fetch_returns(mock_graph, "NVDA", "2026-01-05")
|
||||
raw, alpha, days, resolved = settlement.fetch_returns("NVDA", "2026-01-05")
|
||||
assert raw is not None and alpha is not None
|
||||
assert days == 5 # full holding window used for both series
|
||||
assert resolved == "2026-01-10"
|
||||
@@ -572,32 +569,29 @@ class TestDeferredReflection:
|
||||
on a premature partial return."""
|
||||
stock_prices = [100.0, 102.0, 104.0] # only 3 rows; holding window is 5
|
||||
spy_prices = [400.0, 402.0, 404.0]
|
||||
mock_graph = MagicMock(spec=TradingAgentsGraph)
|
||||
with patch("yfinance.Ticker") as mock_ticker_cls:
|
||||
def _make_ticker(sym):
|
||||
m = MagicMock()
|
||||
m.history.return_value = _price_df(spy_prices if sym == "SPY" else stock_prices)
|
||||
return m
|
||||
mock_ticker_cls.side_effect = _make_ticker
|
||||
result = TradingAgentsGraph._fetch_returns(mock_graph, "NVDA", "2026-01-05")
|
||||
result = settlement.fetch_returns("NVDA", "2026-01-05")
|
||||
assert result == (None, None, None, None)
|
||||
|
||||
# TradingAgentsGraph._resolve_benchmark — picks index for alpha calc
|
||||
# settlement.resolve_benchmark picks the index for the alpha calculation
|
||||
|
||||
def test_resolve_benchmark_explicit_override(self):
|
||||
"""config['benchmark_ticker'] wins for every ticker."""
|
||||
mock_graph = MagicMock(spec=TradingAgentsGraph)
|
||||
mock_graph.config = {
|
||||
config = {
|
||||
"benchmark_ticker": "QQQ",
|
||||
"benchmark_map": {"": "SPY", ".T": "^N225"},
|
||||
}
|
||||
assert TradingAgentsGraph._resolve_benchmark(mock_graph, "7203.T") == "QQQ"
|
||||
assert TradingAgentsGraph._resolve_benchmark(mock_graph, "NVDA") == "QQQ"
|
||||
assert settlement.resolve_benchmark("7203.T", config) == "QQQ"
|
||||
assert settlement.resolve_benchmark("NVDA", config) == "QQQ"
|
||||
|
||||
def test_resolve_benchmark_suffix_map(self):
|
||||
"""Known suffixes route to their regional index."""
|
||||
mock_graph = MagicMock(spec=TradingAgentsGraph)
|
||||
mock_graph.config = {
|
||||
config = {
|
||||
"benchmark_ticker": None,
|
||||
"benchmark_map": {
|
||||
".T": "^N225", ".HK": "^HSI", ".NS": "^NSEI",
|
||||
@@ -605,58 +599,60 @@ class TestDeferredReflection:
|
||||
".BO": "^BSESN", "": "SPY",
|
||||
},
|
||||
}
|
||||
assert TradingAgentsGraph._resolve_benchmark(mock_graph, "7203.T") == "^N225"
|
||||
assert TradingAgentsGraph._resolve_benchmark(mock_graph, "0700.HK") == "^HSI"
|
||||
assert TradingAgentsGraph._resolve_benchmark(mock_graph, "RELIANCE.NS") == "^NSEI"
|
||||
assert TradingAgentsGraph._resolve_benchmark(mock_graph, "AZN.L") == "^FTSE"
|
||||
assert settlement.resolve_benchmark("7203.T", config) == "^N225"
|
||||
assert settlement.resolve_benchmark("0700.HK", config) == "^HSI"
|
||||
assert settlement.resolve_benchmark("RELIANCE.NS", config) == "^NSEI"
|
||||
assert settlement.resolve_benchmark("AZN.L", config) == "^FTSE"
|
||||
|
||||
def test_explicit_benchmark_is_resolved_like_any_other_symbol(self):
|
||||
"""A configured benchmark takes the same alias mapping as the ticker, or
|
||||
the return lookup finds nothing and the decision never settles."""
|
||||
mock_graph = MagicMock(spec=TradingAgentsGraph)
|
||||
mock_graph.config = {"benchmark_ticker": "SPX500", "benchmark_map": {"": "SPY"}}
|
||||
assert TradingAgentsGraph._resolve_benchmark(mock_graph, "NVDA") == "^GSPC"
|
||||
config = {"benchmark_ticker": "SPX500", "benchmark_map": {"": "SPY"}}
|
||||
assert settlement.resolve_benchmark("NVDA", config) == "^GSPC"
|
||||
|
||||
def test_resolve_benchmark_china_a_shares(self):
|
||||
"""A-share tickers route to their exchange composite (uses the real
|
||||
default benchmark_map, since A-share support relies on it)."""
|
||||
from tradingagents.default_config import DEFAULT_CONFIG
|
||||
mock_graph = MagicMock(spec=TradingAgentsGraph)
|
||||
mock_graph.config = {"benchmark_ticker": None,
|
||||
config = {"benchmark_ticker": None,
|
||||
"benchmark_map": DEFAULT_CONFIG["benchmark_map"]}
|
||||
assert TradingAgentsGraph._resolve_benchmark(mock_graph, "600519.SS") == "000001.SS"
|
||||
assert TradingAgentsGraph._resolve_benchmark(mock_graph, "000001.SZ") == "399001.SZ"
|
||||
assert settlement.resolve_benchmark("600519.SS", config) == "000001.SS"
|
||||
assert settlement.resolve_benchmark("000001.SZ", config) == "399001.SZ"
|
||||
# .SH is the exchange's own suffix; Yahoo spells Shanghai .SS (#1260)
|
||||
assert TradingAgentsGraph._resolve_benchmark(mock_graph, "600519.SH") == "000001.SS"
|
||||
assert settlement.resolve_benchmark("600519.SH", config) == "000001.SS"
|
||||
|
||||
def test_resolve_benchmark_brazil(self):
|
||||
"""B3 tickers were measured against SPY."""
|
||||
from tradingagents.default_config import DEFAULT_CONFIG
|
||||
config = {"benchmark_ticker": None,
|
||||
"benchmark_map": DEFAULT_CONFIG["benchmark_map"]}
|
||||
assert settlement.resolve_benchmark("PETR4.SA", config) == "^BVSP"
|
||||
|
||||
def test_resolve_benchmark_us_ticker_defaults_to_spy(self):
|
||||
"""US tickers (no dotted suffix) take the empty-suffix entry."""
|
||||
mock_graph = MagicMock(spec=TradingAgentsGraph)
|
||||
mock_graph.config = {
|
||||
config = {
|
||||
"benchmark_ticker": None,
|
||||
"benchmark_map": {"": "SPY", ".T": "^N225"},
|
||||
}
|
||||
assert TradingAgentsGraph._resolve_benchmark(mock_graph, "NVDA") == "SPY"
|
||||
assert TradingAgentsGraph._resolve_benchmark(mock_graph, "AAPL") == "SPY"
|
||||
assert settlement.resolve_benchmark("NVDA", config) == "SPY"
|
||||
assert settlement.resolve_benchmark("AAPL", config) == "SPY"
|
||||
|
||||
def test_resolve_benchmark_unknown_suffix_falls_back(self):
|
||||
"""Unrecognised suffix (BRK.B, FAKE.XX) falls back to SPY."""
|
||||
mock_graph = MagicMock(spec=TradingAgentsGraph)
|
||||
mock_graph.config = {
|
||||
config = {
|
||||
"benchmark_ticker": None,
|
||||
"benchmark_map": {"": "SPY", ".T": "^N225"},
|
||||
}
|
||||
assert TradingAgentsGraph._resolve_benchmark(mock_graph, "FAKE.XX") == "SPY"
|
||||
assert TradingAgentsGraph._resolve_benchmark(mock_graph, "BRK.B") == "SPY"
|
||||
assert settlement.resolve_benchmark("FAKE.XX", config) == "SPY"
|
||||
assert settlement.resolve_benchmark("BRK.B", config) == "SPY"
|
||||
|
||||
def test_resolve_benchmark_case_insensitive(self):
|
||||
"""Suffix matching is case-insensitive so 7203.t resolves like 7203.T."""
|
||||
mock_graph = MagicMock(spec=TradingAgentsGraph)
|
||||
mock_graph.config = {
|
||||
config = {
|
||||
"benchmark_ticker": None,
|
||||
"benchmark_map": {".T": "^N225", "": "SPY"},
|
||||
}
|
||||
assert TradingAgentsGraph._resolve_benchmark(mock_graph, "7203.t") == "^N225"
|
||||
assert settlement.resolve_benchmark("7203.t", config) == "^N225"
|
||||
|
||||
def test_reflector_includes_benchmark_in_label(self):
|
||||
"""benchmark_name appears in the prompt label, not 'SPY' hardcoded."""
|
||||
@@ -688,32 +684,25 @@ class TestDeferredReflection:
|
||||
human_content = next(content for role, content in messages if role == "human")
|
||||
assert "Alpha vs SPY:" in human_content
|
||||
|
||||
# TradingAgentsGraph._resolve_pending_entries
|
||||
# settlement.settle_pending
|
||||
|
||||
def test_resolve_skips_other_tickers(self, tmp_path):
|
||||
"""Pending AAPL entry is not resolved when the run is for NVDA."""
|
||||
log = make_log(tmp_path)
|
||||
log.store_decision("AAPL", "2026-01-10", DECISION_BUY)
|
||||
mock_graph = MagicMock(spec=TradingAgentsGraph)
|
||||
mock_graph.config = {}
|
||||
mock_graph.memory_log = log
|
||||
mock_graph._fetch_returns = MagicMock(return_value=(0.05, 0.02, 5, "2026-01-12"))
|
||||
TradingAgentsGraph._resolve_pending_entries(mock_graph, "NVDA")
|
||||
mock_graph._fetch_returns.assert_not_called()
|
||||
with patch.object(settlement, "fetch_returns", return_value=(0.05, 0.02, 5, "2026-01-12")) as fetch:
|
||||
settlement.settle_pending("NVDA", log, MagicMock(), {})
|
||||
fetch.assert_not_called()
|
||||
assert len(log.get_pending_entries()) == 1
|
||||
|
||||
def test_resolve_marks_entry_completed(self, tmp_path):
|
||||
"""After resolve, get_pending_entries() is empty and the entry has a REFLECTION."""
|
||||
log = make_log(tmp_path)
|
||||
log.store_decision("NVDA", "2026-01-05", DECISION_BUY)
|
||||
mock_reflector = MagicMock()
|
||||
mock_reflector.reflect_on_final_decision.return_value = "Momentum confirmed."
|
||||
mock_graph = MagicMock(spec=TradingAgentsGraph)
|
||||
mock_graph.config = {}
|
||||
mock_graph.memory_log = log
|
||||
mock_graph.reflector = mock_reflector
|
||||
mock_graph._fetch_returns = MagicMock(return_value=(0.05, 0.02, 5, "2026-01-12"))
|
||||
TradingAgentsGraph._resolve_pending_entries(mock_graph, "NVDA")
|
||||
reflector = MagicMock()
|
||||
reflector.reflect_on_final_decision.return_value = "Momentum confirmed."
|
||||
with patch.object(settlement, "fetch_returns", return_value=(0.05, 0.02, 5, "2026-01-12")):
|
||||
settlement.settle_pending("NVDA", log, reflector, {})
|
||||
assert log.get_pending_entries() == []
|
||||
entries = log.load_entries()
|
||||
assert len(entries) == 1
|
||||
@@ -723,19 +712,15 @@ class TestDeferredReflection:
|
||||
assert "+2.0%" in entries[0]["alpha"]
|
||||
|
||||
def test_resolve_leaves_premature_entry_pending(self, tmp_path):
|
||||
"""#1169: when the outcome can't be settled yet (_fetch_returns None),
|
||||
"""#1169: when the outcome can't be settled yet (fetch_returns None),
|
||||
the entry stays pending and the reflector is never called."""
|
||||
log = make_log(tmp_path)
|
||||
log.store_decision("NVDA", "2026-01-05", DECISION_BUY)
|
||||
mock_reflector = MagicMock()
|
||||
mock_graph = MagicMock(spec=TradingAgentsGraph)
|
||||
mock_graph.config = {}
|
||||
mock_graph.memory_log = log
|
||||
mock_graph.reflector = mock_reflector
|
||||
mock_graph._fetch_returns = MagicMock(return_value=(None, None, None, None))
|
||||
TradingAgentsGraph._resolve_pending_entries(mock_graph, "NVDA")
|
||||
reflector = MagicMock()
|
||||
with patch.object(settlement, "fetch_returns", return_value=(None, None, None, None)):
|
||||
settlement.settle_pending("NVDA", log, reflector, {})
|
||||
assert len(log.get_pending_entries()) == 1 # still pending
|
||||
mock_reflector.reflect_on_final_decision.assert_not_called()
|
||||
reflector.reflect_on_final_decision.assert_not_called()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -878,12 +863,12 @@ class TestLegacyRemoval:
|
||||
|
||||
def test_financial_situation_memory_removed(self):
|
||||
"""FinancialSituationMemory must not be importable from the memory module."""
|
||||
import tradingagents.agents.utils.memory as m
|
||||
import tradingagents.decision_log as m
|
||||
assert not hasattr(m, "FinancialSituationMemory")
|
||||
|
||||
def test_bm25_not_imported(self):
|
||||
"""rank_bm25 must not be present in the memory module namespace."""
|
||||
import tradingagents.agents.utils.memory as m
|
||||
import tradingagents.decision_log as m
|
||||
assert not hasattr(m, "BM25Okapi")
|
||||
|
||||
def test_reflect_and_remember_removed(self):
|
||||
@@ -924,13 +909,12 @@ class TestLegacyRemoval:
|
||||
}
|
||||
mock_graph = MagicMock()
|
||||
mock_graph.memory_log = TradingMemoryLog({"memory_log_path": str(tmp_path / "mem.md")})
|
||||
mock_graph.log_states_dict = {}
|
||||
mock_graph.debug = False
|
||||
mock_graph.config = {"results_dir": str(tmp_path)}
|
||||
mock_graph.graph.invoke.return_value = fake_state
|
||||
mock_graph.propagator.create_initial_state.return_value = fake_state
|
||||
mock_graph.propagator.get_graph_args.return_value = {}
|
||||
mock_graph.signal_processor.process_signal.return_value = "Buy"
|
||||
mock_graph.process_signal.return_value = "Buy"
|
||||
# Bind the real _run_graph so propagate's call to self._run_graph executes
|
||||
# the actual write path instead of the auto-MagicMock.
|
||||
mock_graph._run_graph = functools.partial(
|
||||
@@ -950,7 +934,7 @@ class TestLegacyRemoval:
|
||||
def test_a_failed_reflection_leaves_the_entry_pending_and_lets_the_run_start(tmp_path, monkeypatch):
|
||||
"""Settling past decisions happens on the way into a new run, and reflection
|
||||
calls an LLM. A transient failure there must not stop the new analysis."""
|
||||
from tradingagents.agents.utils.memory import TradingMemoryLog
|
||||
from tradingagents.decision_log import TradingMemoryLog
|
||||
from tradingagents.graph.trading_graph import TradingAgentsGraph
|
||||
|
||||
graph = object.__new__(TradingAgentsGraph)
|
||||
@@ -958,9 +942,9 @@ def test_a_failed_reflection_leaves_the_entry_pending_and_lets_the_run_start(tmp
|
||||
graph.memory_log = TradingMemoryLog(graph.config)
|
||||
graph.memory_log.store_decision("NVDA", "2026-01-05", "Rating: Buy\n\nx")
|
||||
graph.memory_log.store_decision("NVDA", "2026-01-12", "Rating: Sell\n\ny")
|
||||
monkeypatch.setattr(graph, "_resolve_benchmark", lambda t: "SPY", raising=False)
|
||||
monkeypatch.setattr(graph, "_fetch_returns",
|
||||
lambda t, d, holding_days=5, benchmark=None: (0.01, 0.005, holding_days, "2026-01-19"), raising=False)
|
||||
monkeypatch.setattr(settlement, "resolve_benchmark", lambda t, c: "SPY")
|
||||
monkeypatch.setattr(settlement, "fetch_returns",
|
||||
lambda t, d, holding_days=5, benchmark=None: (0.01, 0.005, holding_days, "2026-01-19"))
|
||||
|
||||
class _Reflector:
|
||||
calls = 0
|
||||
@@ -973,7 +957,7 @@ def test_a_failed_reflection_leaves_the_entry_pending_and_lets_the_run_start(tmp
|
||||
|
||||
graph.reflector = _Reflector()
|
||||
|
||||
graph._resolve_pending_entries("NVDA") # must not raise
|
||||
graph.settle_pending("NVDA") # must not raise
|
||||
|
||||
entries = graph.memory_log.load_entries()
|
||||
assert [e["pending"] for e in entries] == [True, False] # the failed one waits for next time
|
||||
@@ -983,24 +967,24 @@ def test_a_failed_reflection_leaves_the_entry_pending_and_lets_the_run_start(tmp
|
||||
def test_the_holding_window_is_configurable(tmp_path, monkeypatch):
|
||||
"""A decision written for months should not be graded at a week without the
|
||||
operator choosing that window."""
|
||||
from tradingagents.agents.utils.memory import TradingMemoryLog
|
||||
from tradingagents.decision_log import TradingMemoryLog
|
||||
from tradingagents.graph.trading_graph import TradingAgentsGraph
|
||||
|
||||
graph = object.__new__(TradingAgentsGraph)
|
||||
graph.config = {"memory_log_path": str(tmp_path / "m.md"), "holding_period_days": 21}
|
||||
graph.memory_log = TradingMemoryLog(graph.config)
|
||||
graph.memory_log.store_decision("NVDA", "2026-01-05", "**Rating**: Buy\n\nx")
|
||||
monkeypatch.setattr(graph, "_resolve_benchmark", lambda t: "SPY", raising=False)
|
||||
monkeypatch.setattr(settlement, "resolve_benchmark", lambda t, c: "SPY")
|
||||
asked = {}
|
||||
|
||||
def _returns(ticker, date, holding_days=5, benchmark=None):
|
||||
asked["holding_days"] = holding_days
|
||||
return 0.05, 0.02, holding_days, "2026-02-02"
|
||||
|
||||
monkeypatch.setattr(graph, "_fetch_returns", _returns, raising=False)
|
||||
monkeypatch.setattr(settlement, "fetch_returns", _returns)
|
||||
graph.reflector = type("R", (), {"reflect_on_final_decision": lambda self, **kw: "lesson"})()
|
||||
|
||||
graph._resolve_pending_entries("NVDA")
|
||||
graph.settle_pending("NVDA")
|
||||
|
||||
assert asked["holding_days"] == 21
|
||||
assert graph.memory_log.load_entries()[0]["holding"] == "21d"
|
||||
@@ -1020,9 +1004,6 @@ def test_the_reflection_states_the_window_it_judges():
|
||||
def test_a_longer_window_asks_for_enough_price_history(monkeypatch):
|
||||
"""Trading days are not calendar days: a 21-day window needs about a month
|
||||
of bars, and asking for 28 days left every outcome unsettled."""
|
||||
from tradingagents.graph.trading_graph import TradingAgentsGraph
|
||||
|
||||
graph = object.__new__(TradingAgentsGraph)
|
||||
asked = {}
|
||||
|
||||
class _Ticker:
|
||||
@@ -1035,8 +1016,8 @@ def test_a_longer_window_asks_for_enough_price_history(monkeypatch):
|
||||
days = pd.bdate_range(start, end)
|
||||
return pd.DataFrame({"Close": range(len(days))}, index=days)
|
||||
|
||||
monkeypatch.setattr("tradingagents.graph.trading_graph.yf.Ticker", _Ticker)
|
||||
monkeypatch.setattr("tradingagents.dataflows.vendors.yahoo.market.yf.Ticker", _Ticker)
|
||||
|
||||
raw, alpha, days, resolved = graph._fetch_returns("NVDA", "2026-06-01", 21, benchmark="SPY")
|
||||
raw, alpha, days, resolved = settlement.fetch_returns("NVDA", "2026-06-01", 21, benchmark="SPY")
|
||||
|
||||
assert days == 21 and resolved is not None, (raw, alpha, days, resolved)
|
||||
|
||||
@@ -10,7 +10,7 @@ from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from tradingagents.agents.utils.memory import TradingMemoryLog
|
||||
from tradingagents.decision_log import TradingMemoryLog
|
||||
|
||||
|
||||
def _log(tmp_path):
|
||||
|
||||
@@ -8,7 +8,7 @@ import inspect
|
||||
import pytest
|
||||
|
||||
import tradingagents.agents.analysts.news_analyst as na
|
||||
from tradingagents.agents.utils.news_data_tools import get_news
|
||||
from tradingagents.agents.tools import get_news
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
|
||||
@@ -10,7 +10,7 @@ from datetime import datetime, timezone
|
||||
|
||||
import pytest
|
||||
|
||||
import tradingagents.dataflows.yfinance_news as ynews
|
||||
import tradingagents.dataflows.vendors.yahoo.news as ynews
|
||||
from tradingagents.dataflows.date_window import in_window
|
||||
|
||||
|
||||
@@ -106,7 +106,6 @@ def test_global_news_empty_after_filter_is_informative(monkeypatch):
|
||||
assert "unavailable" in out and "not an absence" in out
|
||||
|
||||
|
||||
|
||||
def _ticker_with(articles, monkeypatch):
|
||||
class FakeTicker:
|
||||
def __init__(self, *a, **k):
|
||||
@@ -128,7 +127,7 @@ def test_ticker_news_window_before_feed_coverage_is_unavailable(monkeypatch):
|
||||
out = ynews.get_news_yfinance("AAPL", "2026-08-07", "2026-08-14")
|
||||
assert "RECENT" not in out
|
||||
assert "unavailable" in out and "not an absence" in out
|
||||
assert "2026-09-10" in out # says how far back the feed actually reaches
|
||||
assert "2026-09-10" not in out # an article after the window
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@@ -162,7 +161,6 @@ def test_coverage_gap_boundaries(dates, expect_gap):
|
||||
assert "unavailable for 2026-05-01..2026-05-08" in out and "not an absence" in out
|
||||
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_ticker_news_empty_feed_for_a_past_window_is_unavailable(monkeypatch):
|
||||
_ticker_with([], monkeypatch)
|
||||
|
||||
@@ -14,9 +14,10 @@ from unittest import mock
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
from tradingagents.dataflows import interface, stockstats_utils
|
||||
from tradingagents.dataflows import router
|
||||
from tradingagents.dataflows.config import set_config
|
||||
from tradingagents.dataflows.symbol_utils import NoMarketDataError
|
||||
from tradingagents.dataflows.errors import NoMarketDataError
|
||||
from tradingagents.dataflows.vendors.yahoo import ohlcv
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@@ -33,16 +34,20 @@ class TestLoadOhlcvNoPoison(unittest.TestCase):
|
||||
|
||||
def test_empty_download_raises_and_does_not_cache(self):
|
||||
empty = pd.DataFrame()
|
||||
with mock.patch.object(stockstats_utils.yf, "download", return_value=empty), \
|
||||
# Yahoo answers, so an empty download means the symbol has no data.
|
||||
reachable = mock.patch.object(ohlcv, "vendor_reachable", return_value=True)
|
||||
reachable.start()
|
||||
self.addCleanup(reachable.stop)
|
||||
with mock.patch.object(ohlcv.yf, "download", return_value=empty), \
|
||||
self.assertRaises(NoMarketDataError):
|
||||
stockstats_utils.load_ohlcv("FAKE", "2026-01-01")
|
||||
ohlcv.load_ohlcv("FAKE", "2026-01-01")
|
||||
# Nothing should have been written to the cache.
|
||||
self.assertEqual(os.listdir(self._tmp), [])
|
||||
|
||||
# A second call must re-attempt the fetch (no poisoned cache served).
|
||||
with mock.patch.object(stockstats_utils.yf, "download", return_value=empty) as dl2:
|
||||
with mock.patch.object(ohlcv.yf, "download", return_value=empty) as dl2:
|
||||
with self.assertRaises(NoMarketDataError):
|
||||
stockstats_utils.load_ohlcv("FAKE", "2026-01-01")
|
||||
ohlcv.load_ohlcv("FAKE", "2026-01-01")
|
||||
self.assertTrue(dl2.called)
|
||||
|
||||
|
||||
@@ -54,9 +59,9 @@ class TestRouteToVendorSentinel(unittest.TestCase):
|
||||
|
||||
patched = {"yfinance": raises_no_data, "alpha_vantage": raises_no_data}
|
||||
with mock.patch.dict(
|
||||
interface.VENDOR_METHODS, {"get_stock_data": patched}, clear=False
|
||||
router.VENDOR_METHODS, {"get_stock_data": patched}, clear=False
|
||||
):
|
||||
result = interface.route_to_vendor(
|
||||
result = router.route_to_vendor(
|
||||
"get_stock_data", "XAUUSD+", "2026-01-01", "2026-01-10"
|
||||
)
|
||||
self.assertIn("NO_DATA_AVAILABLE", result)
|
||||
@@ -76,9 +81,9 @@ class TestRouteToVendorSentinel(unittest.TestCase):
|
||||
|
||||
patched = {"yfinance": raises_no_data, "alpha_vantage": raises_unavailable}
|
||||
with mock.patch.dict(
|
||||
interface.VENDOR_METHODS, {"get_stock_data": patched}, clear=False
|
||||
router.VENDOR_METHODS, {"get_stock_data": patched}, clear=False
|
||||
):
|
||||
result = interface.route_to_vendor(
|
||||
result = router.route_to_vendor(
|
||||
"get_stock_data", "FAKE", "2026-01-01", "2026-01-10"
|
||||
)
|
||||
self.assertIn("NO_DATA_AVAILABLE", result)
|
||||
@@ -86,3 +91,15 @@ class TestRouteToVendorSentinel(unittest.TestCase):
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_an_unreachable_yahoo_is_not_reported_as_a_symbol_without_insider_data():
|
||||
from tradingagents.dataflows.errors import VendorRateLimitError
|
||||
from tradingagents.dataflows.vendors.yahoo import fundamentals
|
||||
|
||||
ticker = type("T", (), {"insider_transactions": pd.DataFrame()})()
|
||||
with mock.patch.object(fundamentals.yf, "Ticker", return_value=ticker), \
|
||||
mock.patch.object(fundamentals, "vendor_reachable", return_value=False), \
|
||||
pytest.raises(VendorRateLimitError):
|
||||
fundamentals.get_insider_transactions("AAPL", curr_date="2026-09-21")
|
||||
|
||||
@@ -12,25 +12,31 @@ import os
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
import tradingagents.dataflows.stockstats_utils as su
|
||||
from tradingagents.dataflows.vendors.yahoo import ohlcv
|
||||
|
||||
NOW = pd.Timestamp("2026-07-18 12:00")
|
||||
STALE = su.OHLCV_CACHE_TTL_SECONDS + 60
|
||||
STALE = ohlcv.OHLCV_CACHE_TTL_SECONDS + 60
|
||||
|
||||
|
||||
def _stamp(path, ts):
|
||||
"""Set ``path``'s mtime to the wall-clock ``ts``, read back in local time as
|
||||
the cache does. A naive ``pd.Timestamp.timestamp()`` would be taken as UTC."""
|
||||
t = ts.to_pydatetime().timestamp()
|
||||
os.utime(path, (t, t))
|
||||
|
||||
|
||||
def _write(tmp_path, name="AAPL-YFin-data.csv", age_seconds=0.0, last_date="2026-07-17"):
|
||||
f = tmp_path / name
|
||||
pd.DataFrame({"Date": [last_date], "Close": [100.0]}).to_csv(f, index=False)
|
||||
written = NOW.timestamp() - age_seconds
|
||||
os.utime(f, (written, written))
|
||||
_stamp(f, NOW - pd.Timedelta(seconds=age_seconds))
|
||||
return f
|
||||
|
||||
|
||||
def _load(tmp_path, monkeypatch, curr_date, download):
|
||||
monkeypatch.setattr(su, "get_config", lambda: {"data_cache_dir": str(tmp_path)})
|
||||
monkeypatch.setattr(su.pd.Timestamp, "today", staticmethod(lambda: NOW))
|
||||
monkeypatch.setattr(su.yf, "download", download)
|
||||
return su.load_ohlcv("AAPL", curr_date)
|
||||
monkeypatch.setattr(ohlcv, "get_config", lambda: {"data_cache_dir": str(tmp_path)})
|
||||
monkeypatch.setattr(ohlcv.pd.Timestamp, "today", staticmethod(lambda: NOW))
|
||||
monkeypatch.setattr(ohlcv.yf, "download", download)
|
||||
return ohlcv.load_ohlcv("AAPL", curr_date)
|
||||
|
||||
|
||||
def _fail_download(*a, **k):
|
||||
@@ -40,27 +46,27 @@ def _fail_download(*a, **k):
|
||||
@pytest.mark.unit
|
||||
def test_current_day_cache_past_ttl_is_not_fresh(tmp_path):
|
||||
# Today's bar missing or still in progress: row inspection can't tell, so the TTL governs.
|
||||
assert su._cache_is_fresh(_write(tmp_path, age_seconds=STALE), NOW.normalize(), NOW) is False
|
||||
assert ohlcv._cache_is_fresh(_write(tmp_path, age_seconds=STALE), NOW.normalize(), NOW) is False
|
||||
f = _write(tmp_path, age_seconds=STALE, last_date="2026-07-18")
|
||||
assert su._cache_is_fresh(f, NOW.normalize(), NOW) is False
|
||||
assert ohlcv._cache_is_fresh(f, NOW.normalize(), NOW) is False
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_recent_cache_is_fresh(tmp_path):
|
||||
# Written moments ago: don't hammer the vendor (weekend/holiday guard).
|
||||
assert su._cache_is_fresh(_write(tmp_path), NOW.normalize(), NOW) is True
|
||||
assert ohlcv._cache_is_fresh(_write(tmp_path), NOW.normalize(), NOW) is True
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_historical_request_uses_todays_cache_past_the_ttl(tmp_path):
|
||||
f = _write(tmp_path, age_seconds=STALE, last_date="2026-04-30")
|
||||
assert su._cache_is_fresh(f, pd.Timestamp("2026-05-01"), NOW) is True
|
||||
assert ohlcv._cache_is_fresh(f, pd.Timestamp("2026-05-01"), NOW) is True
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_a_download_from_an_earlier_day_is_not_fresh(tmp_path):
|
||||
f = _write(tmp_path, age_seconds=13 * 3600) # yesterday 23:00
|
||||
assert su._cache_is_fresh(f, pd.Timestamp("2026-05-01"), NOW) is False
|
||||
assert ohlcv._cache_is_fresh(f, pd.Timestamp("2026-05-01"), NOW) is False
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@@ -89,17 +95,17 @@ def test_load_ohlcv_reuses_fresh_same_day_cache(tmp_path, monkeypatch):
|
||||
@pytest.mark.unit
|
||||
def test_one_cache_file_per_symbol_across_days(tmp_path, monkeypatch):
|
||||
"""A later day's download replaces the symbol's file instead of adding one (#1330)."""
|
||||
monkeypatch.setattr(su, "get_config", lambda: {"data_cache_dir": str(tmp_path)})
|
||||
monkeypatch.setattr(ohlcv, "get_config", lambda: {"data_cache_dir": str(tmp_path)})
|
||||
frame = pd.DataFrame({"Date": pd.to_datetime(["2026-07-16", "2026-07-17"]), "Close": [1.0, 2.0]})
|
||||
downloads = []
|
||||
monkeypatch.setattr(su.yf, "download", lambda *a, **k: downloads.append(1) or frame.set_index("Date"))
|
||||
monkeypatch.setattr(ohlcv.yf, "download", lambda *a, **k: downloads.append(1) or frame.set_index("Date"))
|
||||
|
||||
for day in ("2026-07-18 10:00", "2026-07-19 10:00", "2026-07-20 10:00"):
|
||||
now = pd.Timestamp(day)
|
||||
monkeypatch.setattr(su.pd.Timestamp, "today", staticmethod(lambda now=now: now))
|
||||
su.load_ohlcv("AAPL", "2026-07-17")
|
||||
monkeypatch.setattr(ohlcv.pd.Timestamp, "today", staticmethod(lambda now=now: now))
|
||||
ohlcv.load_ohlcv("AAPL", "2026-07-17")
|
||||
written = list(tmp_path.glob("AAPL-*.csv"))
|
||||
os.utime(written[0], (now.timestamp(), now.timestamp()))
|
||||
_stamp(written[0], now)
|
||||
|
||||
assert len(downloads) == 3, "each new day refetches"
|
||||
assert [p.name for p in tmp_path.iterdir()] == ["AAPL-YFin-data.csv"]
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Tests for tolerating a non-`Date` index column in stockstats_utils (#890).
|
||||
"""Tests for tolerating a non-`Date` index column in the Yahoo OHLCV loader (#890).
|
||||
|
||||
Guards against a download frame whose date column is `index` or `Datetime`
|
||||
instead of `Date`, which would otherwise silently drop every indicator.
|
||||
@@ -6,10 +6,12 @@ instead of `Date`, which would otherwise silently drop every indicator.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import warnings
|
||||
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
from tradingagents.dataflows import stockstats_utils as su
|
||||
from tradingagents.dataflows.vendors.yahoo import ohlcv
|
||||
|
||||
|
||||
def _ohlcv(date_col: str) -> pd.DataFrame:
|
||||
@@ -28,20 +30,20 @@ def _ohlcv(date_col: str) -> pd.DataFrame:
|
||||
@pytest.mark.unit
|
||||
class TestEnsureDateColumn:
|
||||
def test_renames_index_column(self):
|
||||
out = su._ensure_date_column(_ohlcv("index"))
|
||||
out = ohlcv._ensure_date_column(_ohlcv("index"))
|
||||
assert "Date" in out.columns and "index" not in out.columns
|
||||
|
||||
def test_renames_datetime_and_date_variants(self):
|
||||
assert "Date" in su._ensure_date_column(_ohlcv("Datetime")).columns
|
||||
assert "Date" in su._ensure_date_column(_ohlcv("date")).columns
|
||||
assert "Date" in ohlcv._ensure_date_column(_ohlcv("Datetime")).columns
|
||||
assert "Date" in ohlcv._ensure_date_column(_ohlcv("date")).columns
|
||||
|
||||
def test_leaves_existing_date_untouched(self):
|
||||
df = _ohlcv("Date")
|
||||
assert su._ensure_date_column(df) is df # no-op short-circuit
|
||||
assert ohlcv._ensure_date_column(df) is df # no-op short-circuit
|
||||
|
||||
def test_no_datelike_column_is_left_alone(self):
|
||||
df = pd.DataFrame({"Close": [1, 2, 3]})
|
||||
out = su._ensure_date_column(df)
|
||||
out = ohlcv._ensure_date_column(df)
|
||||
assert "Date" not in out.columns # nothing to rename; caller handles
|
||||
|
||||
|
||||
@@ -50,21 +52,30 @@ class TestCleanDataframeAcrossVersions:
|
||||
def test_clean_handles_index_column(self):
|
||||
"""A frame with `index` instead of `Date` must still clean to a
|
||||
usable, date-parsed frame (was KeyError: 'Date')."""
|
||||
cleaned = su._clean_dataframe(_ohlcv("index"))
|
||||
cleaned = ohlcv._clean_dataframe(_ohlcv("index"))
|
||||
assert "Date" in cleaned.columns
|
||||
assert pd.api.types.is_datetime64_any_dtype(cleaned["Date"])
|
||||
assert len(cleaned) == 10
|
||||
|
||||
def test_clean_handles_legacy_date_column(self):
|
||||
cleaned = su._clean_dataframe(_ohlcv("Date"))
|
||||
cleaned = ohlcv._clean_dataframe(_ohlcv("Date"))
|
||||
assert len(cleaned) == 10
|
||||
|
||||
def test_indicators_compute_after_index_rename(self):
|
||||
"""stockstats must compute indicators on a frame whose date column
|
||||
arrived as `index`, instead of erroring per indicator."""
|
||||
from stockstats import wrap
|
||||
cleaned = su._clean_dataframe(_ohlcv("index"))
|
||||
cleaned = ohlcv._clean_dataframe(_ohlcv("index"))
|
||||
df = wrap(cleaned)
|
||||
df["close_5_sma"] # triggers calculation
|
||||
assert "close_5_sma" in df.columns
|
||||
assert df["close_5_sma"].notna().any()
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_cleaning_a_frame_with_undated_rows_writes_to_its_own_copy():
|
||||
raw = pd.DataFrame({"Date": ["2026-01-08", None, "2026-01-09"], "Close": ["1", "2", "x"]})
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("error")
|
||||
cleaned = ohlcv._clean_dataframe(raw)
|
||||
assert cleaned["Close"].tolist()[0] == 1.0
|
||||
@@ -18,17 +18,25 @@ import os
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
from tradingagents.dataflows import stockstats_utils as su
|
||||
from tradingagents.dataflows.symbol_utils import NoMarketDataError
|
||||
from tradingagents.dataflows.errors import NoMarketDataError
|
||||
from tradingagents.dataflows.vendors.yahoo import ohlcv
|
||||
|
||||
|
||||
def _stamp(path, ts):
|
||||
"""Set ``path``'s mtime to the wall-clock ``ts``, read back in local time as
|
||||
the cache does. A naive ``pd.Timestamp.timestamp()`` would be taken as UTC."""
|
||||
t = ts.to_pydatetime().timestamp()
|
||||
os.utime(path, (t, t))
|
||||
|
||||
# --- date normalization -----------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_normalize_dates_strips_tz_and_normalizes_to_midnight():
|
||||
aware = pd.Series(pd.to_datetime(
|
||||
["2026-05-08 09:30:00-04:00", "2026-05-09 16:00:00-04:00"]
|
||||
))
|
||||
out = su._normalize_dates(aware)
|
||||
out = ohlcv._normalize_dates(aware)
|
||||
assert out.dt.tz is None
|
||||
assert list(out) == [pd.Timestamp("2026-05-08"), pd.Timestamp("2026-05-09")]
|
||||
|
||||
@@ -36,7 +44,7 @@ def test_normalize_dates_strips_tz_and_normalizes_to_midnight():
|
||||
@pytest.mark.unit
|
||||
def test_normalize_dates_leaves_naive_dates_at_midnight():
|
||||
naive = pd.Series(pd.to_datetime(["2026-05-08 14:30:00", "2026-05-09 00:00:00"]))
|
||||
out = su._normalize_dates(naive)
|
||||
out = ohlcv._normalize_dates(naive)
|
||||
assert out.dt.tz is None
|
||||
assert list(out) == [pd.Timestamp("2026-05-08"), pd.Timestamp("2026-05-09")]
|
||||
|
||||
@@ -50,7 +58,7 @@ def test_normalize_dates_handles_mixed_dst_offsets():
|
||||
"2026-06-08 00:00:00-04:00", # EDT
|
||||
"not-a-date", # -> NaT
|
||||
])
|
||||
out = su._normalize_dates(mixed)
|
||||
out = ohlcv._normalize_dates(mixed)
|
||||
assert out.iloc[0] == pd.Timestamp("2026-01-08")
|
||||
assert out.iloc[1] == pd.Timestamp("2026-06-08")
|
||||
assert pd.isna(out.iloc[2])
|
||||
@@ -61,7 +69,7 @@ def test_normalize_dates_keeps_positive_offset_local_date():
|
||||
# A Tokyo bar at local midnight (+09:00) must stay on its own calendar day,
|
||||
# not shift to the previous UTC day (which utc=True parsing would cause).
|
||||
jst = pd.Series(["2026-05-08 00:00:00+09:00"])
|
||||
assert su._normalize_dates(jst).iloc[0] == pd.Timestamp("2026-05-08")
|
||||
assert ohlcv._normalize_dates(jst).iloc[0] == pd.Timestamp("2026-05-08")
|
||||
|
||||
|
||||
# --- fill vs guard responsibilities ----------------------------------------
|
||||
@@ -70,7 +78,7 @@ def test_normalize_dates_keeps_positive_offset_local_date():
|
||||
def test_clean_dataframe_keeps_nan_close_for_the_caller_to_inspect():
|
||||
# _clean_dataframe normalizes but no longer drops the NaN close itself.
|
||||
df = pd.DataFrame({"Date": ["2026-05-08", "2026-05-09"], "Close": [100.0, float("nan")]})
|
||||
cleaned = su._clean_dataframe(df)
|
||||
cleaned = ohlcv._clean_dataframe(df)
|
||||
assert len(cleaned) == 2
|
||||
assert pd.isna(cleaned["Close"].iloc[-1])
|
||||
|
||||
@@ -79,7 +87,7 @@ def test_clean_dataframe_keeps_nan_close_for_the_caller_to_inspect():
|
||||
def test_fill_price_gaps_drops_nan_close_rows():
|
||||
df = pd.DataFrame({"Date": pd.to_datetime(["2026-05-07", "2026-05-08"]),
|
||||
"Close": [float("nan"), 100.0]})
|
||||
filled = su._fill_price_gaps(df)
|
||||
filled = ohlcv._fill_price_gaps(df)
|
||||
assert len(filled) == 1
|
||||
assert filled["Close"].iloc[0] == 100.0
|
||||
|
||||
@@ -88,17 +96,17 @@ def test_fill_price_gaps_drops_nan_close_rows():
|
||||
|
||||
def _run_load(monkeypatch, tmp_path, frame, curr_date):
|
||||
"""Drive load_ohlcv against a pre-seeded cache frame (no network)."""
|
||||
monkeypatch.setattr(su, "get_config", lambda: {"data_cache_dir": str(tmp_path)})
|
||||
monkeypatch.setattr(ohlcv, "get_config", lambda: {"data_cache_dir": str(tmp_path)})
|
||||
today = pd.Timestamp(curr_date)
|
||||
monkeypatch.setattr(su.pd.Timestamp, "today", staticmethod(lambda: today))
|
||||
monkeypatch.setattr(ohlcv.pd.Timestamp, "today", staticmethod(lambda: today))
|
||||
cache_file = tmp_path / "AAPL-YFin-data.csv"
|
||||
cache_file.write_text(frame.to_csv(index=False))
|
||||
os.utime(cache_file, (today.timestamp(), today.timestamp()))
|
||||
_stamp(cache_file, today)
|
||||
|
||||
def _fail_download(*a, **k):
|
||||
raise AssertionError("should use the seeded cache, not download")
|
||||
monkeypatch.setattr(su.yf, "download", _fail_download)
|
||||
return su.load_ohlcv("AAPL", curr_date)
|
||||
monkeypatch.setattr(ohlcv.yf, "download", _fail_download)
|
||||
return ohlcv.load_ohlcv("AAPL", curr_date)
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@@ -174,7 +182,7 @@ def test_the_snapshot_does_not_present_a_filled_price_as_reported(monkeypatch, t
|
||||
"""Gap filling exists so indicators compute on a continuous series. The
|
||||
verification snapshot is the one place a number must be what the vendor
|
||||
reported, or the module built to stop invented prices supplies them."""
|
||||
from tradingagents.dataflows import market_data_validator as mdv, stockstats_utils as su
|
||||
from tradingagents.dataflows.vendors.yahoo import ohlcv, snapshot
|
||||
|
||||
frame = pd.DataFrame({
|
||||
"Date": ["2026-05-06", "2026-05-07", "2026-05-08"],
|
||||
@@ -185,15 +193,15 @@ def test_the_snapshot_does_not_present_a_filled_price_as_reported(monkeypatch, t
|
||||
"Volume": [1000000, 1000000, ""],
|
||||
})
|
||||
today = pd.Timestamp("2026-05-08 12:00")
|
||||
monkeypatch.setattr(su, "get_config", lambda: {"data_cache_dir": str(tmp_path)})
|
||||
monkeypatch.setattr(su.pd.Timestamp, "today", staticmethod(lambda: today))
|
||||
monkeypatch.setattr(ohlcv, "get_config", lambda: {"data_cache_dir": str(tmp_path)})
|
||||
monkeypatch.setattr(ohlcv.pd.Timestamp, "today", staticmethod(lambda: today))
|
||||
cache = tmp_path / "AAPL-YFin-data.csv"
|
||||
cache.write_text(frame.to_csv(index=False))
|
||||
os.utime(cache, (today.timestamp(), today.timestamp()))
|
||||
monkeypatch.setattr(su.yf, "download", lambda *a, **k: (_ for _ in ()).throw(
|
||||
_stamp(cache, today)
|
||||
monkeypatch.setattr(ohlcv.yf, "download", lambda *a, **k: (_ for _ in ()).throw(
|
||||
AssertionError("should read the seeded cache")))
|
||||
|
||||
out = mdv.build_verified_market_snapshot("AAPL", "2026-05-08", 3)
|
||||
out = snapshot.build_verified_market_snapshot("AAPL", "2026-05-08", 3)
|
||||
|
||||
row = out.split("Latest verified OHLCV row")[1].split("###")[0]
|
||||
assert "104.50" not in row and "105.50" not in row # the previous session's numbers
|
||||
|
||||
@@ -22,17 +22,18 @@ def _console_out(capsys) -> str:
|
||||
def _resync_reloaded_modules():
|
||||
"""Restore module state after this file's importlib.reload() calls.
|
||||
|
||||
Several tests below reload ``cli.utils`` to re-evaluate OLLAMA_BASE_URL.
|
||||
That leaves ``cli.main``'s star-imported names (e.g. get_ticker) bound to
|
||||
the pre-reload module objects, which breaks identity checks in unrelated
|
||||
tests that happen to run afterward. Re-sync once on teardown so the reload
|
||||
doesn't leak across test modules.
|
||||
Several tests below reload ``cli.prompts`` to re-evaluate OLLAMA_BASE_URL.
|
||||
That leaves the modules importing from it (cli.selections, then cli.run and
|
||||
cli.main) bound to the pre-reload functions, which breaks identity checks in
|
||||
unrelated tests that run afterward. Re-sync them in import order on teardown.
|
||||
"""
|
||||
yield
|
||||
import cli.main
|
||||
import cli.utils
|
||||
importlib.reload(cli.utils)
|
||||
importlib.reload(cli.main)
|
||||
import cli.prompts
|
||||
import cli.run
|
||||
import cli.selections
|
||||
for module in (cli.prompts, cli.selections, cli.run, cli.main):
|
||||
importlib.reload(module)
|
||||
|
||||
|
||||
# ---- openai_client side: registry-driven base_url resolution --------------
|
||||
@@ -98,14 +99,14 @@ def test_explicit_base_url_overrides_env(monkeypatch):
|
||||
assert "env-set" not in str(llm.openai_api_base)
|
||||
|
||||
|
||||
# ---- cli.utils side: select_llm_provider dropdown -------------------------
|
||||
# ---- cli.prompts side: select_llm_provider dropdown -------------------------
|
||||
|
||||
|
||||
def test_cli_dropdown_uses_env(monkeypatch):
|
||||
"""The Ollama entry in the CLI dropdown must reflect OLLAMA_BASE_URL."""
|
||||
monkeypatch.setenv("OLLAMA_BASE_URL", "http://cli-remote:11434/v1")
|
||||
import cli.utils as cli_utils
|
||||
importlib.reload(cli_utils)
|
||||
from cli import prompts
|
||||
importlib.reload(prompts)
|
||||
# Reach inside the function via the same env-read it does at call time
|
||||
ollama_url = (
|
||||
__import__("os").environ.get("OLLAMA_BASE_URL")
|
||||
@@ -116,8 +117,8 @@ def test_cli_dropdown_uses_env(monkeypatch):
|
||||
|
||||
def test_cli_dropdown_default_when_unset(monkeypatch):
|
||||
monkeypatch.delenv("OLLAMA_BASE_URL", raising=False)
|
||||
import cli.utils as cli_utils
|
||||
importlib.reload(cli_utils)
|
||||
from cli import prompts
|
||||
importlib.reload(prompts)
|
||||
ollama_url = (
|
||||
__import__("os").environ.get("OLLAMA_BASE_URL")
|
||||
or "http://localhost:11434/v1"
|
||||
@@ -130,9 +131,9 @@ def test_cli_dropdown_default_when_unset(monkeypatch):
|
||||
|
||||
def test_confirm_endpoint_shows_default(monkeypatch, capsys):
|
||||
monkeypatch.delenv("OLLAMA_BASE_URL", raising=False)
|
||||
import cli.utils as cli_utils
|
||||
importlib.reload(cli_utils)
|
||||
cli_utils.confirm_ollama_endpoint("http://localhost:11434/v1")
|
||||
from cli import prompts
|
||||
importlib.reload(prompts)
|
||||
prompts.confirm_ollama_endpoint("http://localhost:11434/v1")
|
||||
out = _console_out(capsys)
|
||||
assert "http://localhost:11434/v1" in out
|
||||
assert "OLLAMA_BASE_URL" not in out # not from env
|
||||
@@ -141,9 +142,9 @@ def test_confirm_endpoint_shows_default(monkeypatch, capsys):
|
||||
|
||||
def test_confirm_endpoint_marks_env_origin(monkeypatch, capsys):
|
||||
monkeypatch.setenv("OLLAMA_BASE_URL", "http://remote-host:11434/v1")
|
||||
import cli.utils as cli_utils
|
||||
importlib.reload(cli_utils)
|
||||
cli_utils.confirm_ollama_endpoint("http://remote-host:11434/v1")
|
||||
from cli import prompts
|
||||
importlib.reload(prompts)
|
||||
prompts.confirm_ollama_endpoint("http://remote-host:11434/v1")
|
||||
out = _console_out(capsys)
|
||||
assert "http://remote-host:11434/v1" in out
|
||||
assert "OLLAMA_BASE_URL" in out
|
||||
@@ -152,9 +153,9 @@ def test_confirm_endpoint_marks_env_origin(monkeypatch, capsys):
|
||||
def test_confirm_endpoint_warns_on_missing_scheme(monkeypatch, capsys):
|
||||
"""If user sets OLLAMA_BASE_URL=0.0.0.128, advise on the expected shape."""
|
||||
monkeypatch.setenv("OLLAMA_BASE_URL", "0.0.0.128")
|
||||
import cli.utils as cli_utils
|
||||
importlib.reload(cli_utils)
|
||||
cli_utils.confirm_ollama_endpoint("0.0.0.128")
|
||||
from cli import prompts
|
||||
importlib.reload(prompts)
|
||||
prompts.confirm_ollama_endpoint("0.0.0.128")
|
||||
out = _console_out(capsys)
|
||||
assert "missing a scheme" in out
|
||||
assert "http://<host>:11434/v1" in out
|
||||
@@ -163,9 +164,9 @@ def test_confirm_endpoint_warns_on_missing_scheme(monkeypatch, capsys):
|
||||
def test_confirm_endpoint_warns_on_non_default_port_remote(monkeypatch, capsys):
|
||||
"""A remote host with no :11434 gets a soft hint about port mismatch."""
|
||||
monkeypatch.setenv("OLLAMA_BASE_URL", "http://remote-host/v1")
|
||||
import cli.utils as cli_utils
|
||||
importlib.reload(cli_utils)
|
||||
cli_utils.confirm_ollama_endpoint("http://remote-host/v1")
|
||||
from cli import prompts
|
||||
importlib.reload(prompts)
|
||||
prompts.confirm_ollama_endpoint("http://remote-host/v1")
|
||||
out = _console_out(capsys)
|
||||
assert "port 11434" in out
|
||||
|
||||
@@ -173,9 +174,9 @@ def test_confirm_endpoint_warns_on_non_default_port_remote(monkeypatch, capsys):
|
||||
def test_confirm_endpoint_quiet_on_local_no_port(monkeypatch, capsys):
|
||||
"""Local host without port shouldn't trigger the remote-port hint."""
|
||||
monkeypatch.setenv("OLLAMA_BASE_URL", "http://localhost/v1")
|
||||
import cli.utils as cli_utils
|
||||
importlib.reload(cli_utils)
|
||||
cli_utils.confirm_ollama_endpoint("http://localhost/v1")
|
||||
from cli import prompts
|
||||
importlib.reload(prompts)
|
||||
prompts.confirm_ollama_endpoint("http://localhost/v1")
|
||||
out = _console_out(capsys)
|
||||
assert "Note" not in out # localhost is fine without explicit port
|
||||
|
||||
|
||||
@@ -68,7 +68,7 @@ def test_any_model_accepted_no_forced_key():
|
||||
@pytest.mark.unit
|
||||
def test_env_backend_url_precedence():
|
||||
# #978: explicit env URL wins over the menu/default regardless of provider source.
|
||||
from cli.utils import resolve_backend_url
|
||||
from cli.prompts import resolve_backend_url
|
||||
assert resolve_backend_url("openai", "https://api.openai.com/v1", env_url="http://proxy/v1") == "http://proxy/v1"
|
||||
assert resolve_backend_url("openai", "https://api.openai.com/v1", env_url=None) == "https://api.openai.com/v1"
|
||||
assert resolve_backend_url("deepseek", None, None) == "https://api.deepseek.com"
|
||||
|
||||
@@ -6,7 +6,7 @@ from unittest import mock
|
||||
|
||||
import pytest
|
||||
|
||||
from cli import utils
|
||||
from cli import prompts
|
||||
|
||||
|
||||
def _asks(value):
|
||||
@@ -23,10 +23,10 @@ class TestOpenRouterPromptLabel:
|
||||
captured["message"] = message
|
||||
return _asks("openrouter/some-model")
|
||||
|
||||
with mock.patch.object(utils, "_fetch_openrouter_models",
|
||||
with mock.patch.object(prompts, "_fetch_openrouter_models",
|
||||
return_value=[("Some Model", "openrouter/some-model")]), \
|
||||
mock.patch.object(utils.questionary, "select", side_effect=fake_select):
|
||||
out = utils.select_openrouter_model(mode)
|
||||
mock.patch.object(prompts.questionary, "select", side_effect=fake_select):
|
||||
out = prompts.select_openrouter_model(mode)
|
||||
|
||||
assert label in captured["message"]
|
||||
assert out == "openrouter/some-model"
|
||||
@@ -44,7 +44,7 @@ class TestOpenRouterLatestFirst:
|
||||
resp.json.return_value = payload
|
||||
resp.raise_for_status = mock.Mock()
|
||||
with mock.patch("requests.get", return_value=resp):
|
||||
out = utils._fetch_openrouter_models()
|
||||
out = prompts._fetch_openrouter_models()
|
||||
assert [mid for _, mid in out] == ["new/model", "mid/model", "old/model"]
|
||||
|
||||
|
||||
@@ -64,9 +64,9 @@ class TestMainstreamFilter:
|
||||
captured["values"] = [c.value for c in kwargs["choices"]]
|
||||
return _asks("anthropic/claude-x")
|
||||
|
||||
with mock.patch.object(utils, "_fetch_openrouter_models", return_value=models), \
|
||||
mock.patch.object(utils.questionary, "select", side_effect=fake_select):
|
||||
utils.select_openrouter_model("quick")
|
||||
with mock.patch.object(prompts, "_fetch_openrouter_models", return_value=models), \
|
||||
mock.patch.object(prompts.questionary, "select", side_effect=fake_select):
|
||||
prompts.select_openrouter_model("quick")
|
||||
|
||||
assert "anthropic/claude-x" in captured["values"]
|
||||
assert "openai/gpt-x" in captured["values"]
|
||||
@@ -82,9 +82,9 @@ class TestMainstreamFilter:
|
||||
captured["values"] = [c.value for c in kwargs["choices"]]
|
||||
return _asks("nex-agi/x")
|
||||
|
||||
with mock.patch.object(utils, "_fetch_openrouter_models", return_value=models), \
|
||||
mock.patch.object(utils.questionary, "select", side_effect=fake_select):
|
||||
utils.select_openrouter_model("deep")
|
||||
with mock.patch.object(prompts, "_fetch_openrouter_models", return_value=models), \
|
||||
mock.patch.object(prompts.questionary, "select", side_effect=fake_select):
|
||||
prompts.select_openrouter_model("deep")
|
||||
|
||||
assert "nex-agi/x" in captured["values"] # fallback keeps the list usable
|
||||
|
||||
@@ -92,31 +92,31 @@ class TestMainstreamFilter:
|
||||
@pytest.mark.unit
|
||||
class TestCancelExitsCleanly:
|
||||
def test_dropdown_cancel_exits(self):
|
||||
with mock.patch.object(utils, "_fetch_openrouter_models", return_value=[]), \
|
||||
mock.patch.object(utils.questionary, "select", return_value=_asks(None)), \
|
||||
with mock.patch.object(prompts, "_fetch_openrouter_models", return_value=[]), \
|
||||
mock.patch.object(prompts.questionary, "select", return_value=_asks(None)), \
|
||||
pytest.raises(SystemExit):
|
||||
utils.select_openrouter_model("quick")
|
||||
prompts.select_openrouter_model("quick")
|
||||
|
||||
def test_custom_id_cancel_exits(self):
|
||||
with mock.patch.object(utils, "_fetch_openrouter_models", return_value=[]), \
|
||||
mock.patch.object(utils.questionary, "select", return_value=_asks("custom")), \
|
||||
mock.patch.object(utils.questionary, "text", return_value=_asks(None)), \
|
||||
with mock.patch.object(prompts, "_fetch_openrouter_models", return_value=[]), \
|
||||
mock.patch.object(prompts.questionary, "select", return_value=_asks("custom")), \
|
||||
mock.patch.object(prompts.questionary, "text", return_value=_asks(None)), \
|
||||
pytest.raises(SystemExit):
|
||||
utils.select_openrouter_model("deep")
|
||||
prompts.select_openrouter_model("deep")
|
||||
|
||||
def test_prompt_custom_model_id_cancel_exits(self):
|
||||
with mock.patch.object(utils.questionary, "text", return_value=_asks(None)), \
|
||||
with mock.patch.object(prompts.questionary, "text", return_value=_asks(None)), \
|
||||
pytest.raises(SystemExit):
|
||||
utils._prompt_custom_model_id()
|
||||
prompts._prompt_custom_model_id()
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
class TestLanguageDefaultsToEnglish:
|
||||
def test_select_cancel_defaults_english(self):
|
||||
with mock.patch.object(utils.questionary, "select", return_value=_asks(None)):
|
||||
assert utils.ask_output_language() == "English"
|
||||
with mock.patch.object(prompts.questionary, "select", return_value=_asks(None)):
|
||||
assert prompts.ask_output_language() == "English"
|
||||
|
||||
def test_custom_language_cancel_defaults_english(self):
|
||||
with mock.patch.object(utils.questionary, "select", return_value=_asks("custom")), \
|
||||
mock.patch.object(utils.questionary, "text", return_value=_asks(None)):
|
||||
assert utils.ask_output_language() == "English"
|
||||
with mock.patch.object(prompts.questionary, "select", return_value=_asks("custom")), \
|
||||
mock.patch.object(prompts.questionary, "text", return_value=_asks(None)):
|
||||
assert prompts.ask_output_language() == "English"
|
||||
|
||||
@@ -12,8 +12,9 @@ import requests
|
||||
|
||||
import tradingagents.dataflows.config as config_module
|
||||
import tradingagents.default_config as default_config
|
||||
from tradingagents.dataflows import interface, polymarket
|
||||
from tradingagents.dataflows import router
|
||||
from tradingagents.dataflows.config import set_config
|
||||
from tradingagents.dataflows.vendors import polymarket
|
||||
|
||||
|
||||
def _market(question, prob, *, volume, end_date, closed=False, wk=None):
|
||||
@@ -112,16 +113,16 @@ class PolymarketRoutingTests(unittest.TestCase):
|
||||
|
||||
def test_category_routes_to_polymarket(self):
|
||||
self.assertEqual(
|
||||
interface.get_category_for_method("get_prediction_markets"),
|
||||
router.get_category_for_method("get_prediction_markets"),
|
||||
"prediction_markets",
|
||||
)
|
||||
set_config({"data_vendors": {"prediction_markets": "polymarket"}})
|
||||
with mock.patch.dict(
|
||||
interface.VENDOR_METHODS,
|
||||
router.VENDOR_METHODS,
|
||||
{"get_prediction_markets": {"polymarket": lambda *a, **k: "POLY_OK"}},
|
||||
clear=False,
|
||||
):
|
||||
out = interface.route_to_vendor("get_prediction_markets", "fed", 5)
|
||||
out = router.route_to_vendor("get_prediction_markets", "fed", 5)
|
||||
self.assertEqual(out, "POLY_OK")
|
||||
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ import json
|
||||
|
||||
import pytest
|
||||
|
||||
from tradingagents.agents.utils.agent_utils import get_portfolio_context_from_state
|
||||
from tradingagents.agents.context import get_portfolio_context_from_state
|
||||
from tradingagents.portfolio import PortfolioContext, load_portfolio
|
||||
|
||||
HOLDING = {
|
||||
@@ -76,7 +76,7 @@ def test_load_reads_a_valid_file(tmp_path):
|
||||
# --- threading through the graph --------------------------------------------
|
||||
|
||||
def _bare_graph(tmp_path):
|
||||
from tradingagents.agents.utils.memory import TradingMemoryLog
|
||||
from tradingagents.decision_log import TradingMemoryLog
|
||||
from tradingagents.graph.propagation import Propagator
|
||||
from tradingagents.graph.trading_graph import TradingAgentsGraph
|
||||
|
||||
@@ -86,7 +86,7 @@ def _bare_graph(tmp_path):
|
||||
graph.memory_log = TradingMemoryLog(graph.config)
|
||||
graph.propagator = Propagator()
|
||||
graph.selected_analysts = ["market"]
|
||||
graph._resolve_pending_entries = lambda t: None
|
||||
graph.settle_pending = lambda t: None
|
||||
graph.resolve_instrument_context = lambda t, a="stock", d=None: ""
|
||||
graph._memory_as_of = lambda d: None
|
||||
return graph
|
||||
|
||||
@@ -0,0 +1,288 @@
|
||||
"""Jev post screening, against TypeSafe's documented request and response shapes."""
|
||||
|
||||
import pytest
|
||||
import requests
|
||||
|
||||
from tradingagents.agents import post_screen as typesafe
|
||||
|
||||
QUESTIONS = {"is_urgent": {"type": "noul", "instructions": "Does this convey urgency?"}}
|
||||
ANSWERS = {"is_urgent": {"type": "noul", "noul": 0.95}}
|
||||
|
||||
|
||||
class _Response:
|
||||
def __init__(self, status, payload=None, headers=None):
|
||||
self.status_code = status
|
||||
self._payload = payload
|
||||
self.headers = headers or {}
|
||||
|
||||
def json(self):
|
||||
if self._payload is None:
|
||||
raise ValueError("no JSON")
|
||||
return self._payload
|
||||
|
||||
|
||||
class _Calls(list):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.queue = []
|
||||
self.sleeps = []
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def post(monkeypatch):
|
||||
"""Queue responses on ``.queue``; the list records each call to requests.post."""
|
||||
calls = _Calls()
|
||||
queue = calls.queue
|
||||
|
||||
def fake_post(url, **kwargs):
|
||||
calls.append((url, kwargs))
|
||||
item = queue.pop(0)
|
||||
if isinstance(item, Exception):
|
||||
raise item
|
||||
return item
|
||||
|
||||
monkeypatch.setattr(typesafe.requests, "post", fake_post)
|
||||
monkeypatch.setattr(typesafe.time, "sleep", calls.sleeps.append)
|
||||
monkeypatch.setenv("TYPESAFE_API_KEY", "ts-test")
|
||||
monkeypatch.delenv("TYPESAFE_DEFAULT_MODEL", raising=False)
|
||||
return calls
|
||||
|
||||
|
||||
def _ok():
|
||||
return _Response(200, {"model": "jev-1.13.0", "answers": ANSWERS,
|
||||
"usage": {"input_tokens": 296, "output_tokens": 20}})
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_sends_the_documented_request_and_returns_the_answers(post):
|
||||
post.queue.append(_ok())
|
||||
|
||||
assert typesafe.system_one("Help! My payouts have been failing.", QUESTIONS) == ANSWERS
|
||||
|
||||
url, kwargs = post[0]
|
||||
assert url == "https://api.typesafe.ai/v1/systemone"
|
||||
assert kwargs["headers"]["Authorization"] == "Bearer ts-test"
|
||||
assert kwargs["json"] == {"state": "Help! My payouts have been failing.",
|
||||
"model": "jev-latest", "questions": QUESTIONS}
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_the_model_follows_the_sdk_environment(post, monkeypatch):
|
||||
monkeypatch.setenv("TYPESAFE_DEFAULT_MODEL", "jev-1.13.0")
|
||||
post.queue.append(_ok())
|
||||
|
||||
typesafe.system_one("s", QUESTIONS)
|
||||
|
||||
assert post[0][1]["json"]["model"] == "jev-1.13.0"
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.parametrize("transient", [
|
||||
_Response(429), _Response(529), requests.ConnectionError(), requests.Timeout(),
|
||||
requests.exceptions.ChunkedEncodingError(),
|
||||
])
|
||||
def test_rate_limits_overload_and_dropped_connections_are_retried(post, transient):
|
||||
post.queue.extend([transient, _ok()])
|
||||
|
||||
assert typesafe.system_one("s", QUESTIONS) == ANSWERS
|
||||
assert len(post) == 2
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_a_retry_after_header_sets_the_wait(post):
|
||||
post.queue.extend([_Response(429, headers={"retry-after": "7"}), _ok()])
|
||||
|
||||
typesafe.system_one("s", QUESTIONS)
|
||||
|
||||
assert post.sleeps == [7.0]
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_a_long_retry_after_is_capped(post):
|
||||
post.queue.extend([_Response(529, headers={"retry-after": "600"}), _ok()])
|
||||
|
||||
typesafe.system_one("s", QUESTIONS)
|
||||
|
||||
assert post.sleeps == [typesafe._MAX_WAIT]
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_retries_are_bounded(post):
|
||||
post.queue.extend([_Response(529)] * 3)
|
||||
|
||||
with pytest.raises(typesafe.TypeSafeError, match="HTTP 529"):
|
||||
typesafe.system_one("s", QUESTIONS)
|
||||
assert len(post) == 3
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.parametrize("error", [requests.exceptions.InvalidHeader(), requests.exceptions.TooManyRedirects()])
|
||||
def test_other_request_errors_are_screening_failures_without_retry(post, error):
|
||||
post.queue.append(error)
|
||||
|
||||
with pytest.raises(typesafe.TypeSafeError, match=type(error).__name__):
|
||||
typesafe.system_one("s", QUESTIONS)
|
||||
assert len(post) == 1
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.parametrize("status", [401, 422, 500])
|
||||
def test_other_failures_raise_without_retry(post, status):
|
||||
post.queue.append(_Response(status))
|
||||
|
||||
with pytest.raises(typesafe.TypeSafeError, match=f"HTTP {status}"):
|
||||
typesafe.system_one("s", QUESTIONS)
|
||||
assert len(post) == 1
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.parametrize("payload", [
|
||||
None, {"model": "jev"}, {"answers": {"other": {}}},
|
||||
{"answers": {"is_urgent": {"type": "choice", "choice": "yes"}}},
|
||||
])
|
||||
def test_a_response_without_every_answer_is_an_error(post, payload):
|
||||
post.queue.append(_Response(200, payload))
|
||||
|
||||
with pytest.raises(typesafe.TypeSafeError, match="malformed"):
|
||||
typesafe.system_one("s", QUESTIONS)
|
||||
|
||||
|
||||
|
||||
def _post_answers(about: float, stance: str = "bullish", confidence: float = 0.9):
|
||||
return _Response(200, {"model": "jev-1.13.0", "answers": {
|
||||
"about": {"type": "noul", "noul": about},
|
||||
"stance": {"type": "choice", "choice": stance, "confidence": confidence,
|
||||
"probabilities": {stance: 1.0}},
|
||||
}})
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def jev(post, monkeypatch):
|
||||
"""Answer each post by its text: ``post`` maps text -> response."""
|
||||
answers = {}
|
||||
|
||||
def fake_post(url, **kwargs):
|
||||
post.append((url, kwargs))
|
||||
return answers[kwargs["json"]["state"]["post"]]
|
||||
|
||||
monkeypatch.setattr(typesafe.requests, "post", fake_post)
|
||||
monkeypatch.setattr(typesafe, "resolve_instrument_identity",
|
||||
lambda t: {"company_name": "NVIDIA Corporation"})
|
||||
return answers
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_no_key_no_screen(monkeypatch):
|
||||
monkeypatch.delenv("TYPESAFE_API_KEY", raising=False)
|
||||
assert typesafe.jev_screen("NVDA") is None
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_each_post_is_its_own_state_under_the_fixed_questions(jev, post):
|
||||
jev["NVDA to 200"] = _post_answers(0.9)
|
||||
|
||||
typesafe.jev_screen("NVDA")(["NVDA to 200"])
|
||||
|
||||
body = post[0][1]["json"]
|
||||
assert body["state"] == {"instrument": "NVIDIA Corporation (NVDA)", "post": "NVDA to 200"}
|
||||
assert body["questions"] == typesafe.QUESTIONS
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_screen_drops_clear_off_topic_posts_and_counts_confident_stances(jev):
|
||||
jev.update({
|
||||
"long NVDA": _post_answers(0.95, "bullish"),
|
||||
"NVDA puts": _post_answers(0.9, "bearish"),
|
||||
"maybe NVDA": _post_answers(0.4, "neutral"), # uncertain relevance: kept
|
||||
"NVDA?": _post_answers(0.8, "bullish", 0.3), # uncertain stance: unclear
|
||||
"NVDA!": _post_answers(0.8, "sideways"), # not an option: unclear
|
||||
"$AAPL $MSFT $NVDA pump": _post_answers(0.1, "bullish"),
|
||||
})
|
||||
|
||||
keep, note = typesafe.jev_screen("NVDA")(list(jev))
|
||||
|
||||
assert keep == [True, True, True, True, True, False]
|
||||
assert note == ("Screened by Jev: 5 of the 6 posts fetched are about NVIDIA Corporation (NVDA); "
|
||||
"their stance on its stock: 1 bullish, 1 bearish, 1 neutral, 2 unclear.")
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_one_failed_request_leaves_every_post_unscreened(jev):
|
||||
jev.update({"a": _post_answers(0.1), "b": _Response(401)})
|
||||
|
||||
keep, note = typesafe.jev_screen("NVDA")(["a", "b"])
|
||||
|
||||
assert keep == [True, True]
|
||||
assert note == "<Jev screening unavailable (HTTP 401); posts are unscreened>"
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_an_answer_missing_its_fields_reads_as_malformed(jev):
|
||||
jev["a"] = _Response(200, {"answers": {"about": {"type": "noul"},
|
||||
"stance": {"type": "choice"}}})
|
||||
|
||||
keep, note = typesafe.jev_screen("NVDA")(["a"])
|
||||
|
||||
assert keep == [True]
|
||||
assert note == "<Jev screening unavailable (malformed response); posts are unscreened>"
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_the_first_failure_cancels_the_requests_not_yet_sent(jev, post, monkeypatch):
|
||||
monkeypatch.setattr(typesafe, "_WORKERS", 1)
|
||||
jev.update({"a": _Response(401), **{f"p{i}": _post_answers(0.9) for i in range(20)}})
|
||||
|
||||
typesafe.jev_screen("NVDA")(list(jev))
|
||||
|
||||
assert len(post) < 21
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_the_sentiment_analyst_hands_the_screen_to_both_social_fetchers(monkeypatch):
|
||||
from langchain_core.messages import AIMessage
|
||||
|
||||
from tradingagents.agents.analysts import sentiment_analyst
|
||||
|
||||
screen = object()
|
||||
seen = []
|
||||
monkeypatch.setattr(sentiment_analyst, "jev_screen", lambda ticker: screen)
|
||||
monkeypatch.setattr(sentiment_analyst.get_news, "func", lambda *a: "news")
|
||||
for name in ("fetch_stocktwits_messages", "fetch_reddit_posts"):
|
||||
monkeypatch.setattr(sentiment_analyst, name, lambda *a, screen=None, **k: seen.append(screen) or "")
|
||||
|
||||
class _LLM:
|
||||
def with_structured_output(self, *a, **k):
|
||||
raise NotImplementedError
|
||||
|
||||
def invoke(self, messages):
|
||||
return AIMessage(content="report")
|
||||
|
||||
node = sentiment_analyst.create_sentiment_analyst(_LLM())
|
||||
node({"company_of_interest": "NVDA", "trade_date": "2026-01-09", "messages": []})
|
||||
|
||||
assert seen == [screen, screen]
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_a_failure_does_not_wait_for_requests_still_in_flight(jev, monkeypatch):
|
||||
import threading
|
||||
import time
|
||||
|
||||
release = threading.Event()
|
||||
|
||||
class _Slow:
|
||||
status_code = 200
|
||||
headers = {}
|
||||
|
||||
def json(self):
|
||||
release.wait(5)
|
||||
return _post_answers(0.9).json()
|
||||
|
||||
jev.update({"slow": _Slow(), "bad": _Response(401)})
|
||||
started = time.monotonic()
|
||||
keep, note = typesafe.jev_screen("NVDA")(["slow", "bad"])
|
||||
elapsed = time.monotonic() - started
|
||||
release.set()
|
||||
|
||||
assert keep == [True, True] and "unavailable" in note
|
||||
assert elapsed < 2
|
||||
@@ -11,7 +11,8 @@ from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from tradingagents.agents.utils.rating import RATING_REVIEW, extract_rating, parse_rating
|
||||
import cli.run as cli_run
|
||||
from tradingagents.agents.rating import RATING_REVIEW, extract_rating, parse_rating
|
||||
|
||||
INVERTED = ("The aggressive analyst pushed hard for a Buy on the AI backlog, but the "
|
||||
"conservative case on margin compression carried the debate. "
|
||||
@@ -63,7 +64,7 @@ def test_the_scale_quoted_in_a_prompt_does_not_become_the_rating():
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_the_memory_log_records_review_rather_than_a_tradeable_hold(tmp_path):
|
||||
from tradingagents.agents.utils.memory import TradingMemoryLog
|
||||
from tradingagents.decision_log import TradingMemoryLog
|
||||
|
||||
log = TradingMemoryLog({"memory_log_path": str(tmp_path / "m.md")})
|
||||
log.store_decision("NVDA", "2026-01-05", REFUSAL)
|
||||
@@ -74,14 +75,14 @@ def test_the_memory_log_records_review_rather_than_a_tradeable_hold(tmp_path):
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_the_signal_and_the_log_agree_on_the_same_decision(tmp_path):
|
||||
from tradingagents.agents.utils.memory import TradingMemoryLog
|
||||
from tradingagents.graph.signal_processing import SignalProcessor
|
||||
from tradingagents.agents.rating import parse_rating
|
||||
from tradingagents.decision_log import TradingMemoryLog
|
||||
|
||||
log = TradingMemoryLog({"memory_log_path": str(tmp_path / "m.md")})
|
||||
for text in (INVERTED, REFUSAL, "**Rating**: Buy\n\nAccumulate."):
|
||||
log.store_decision("NVDA", f"2026-01-0{len(log.load_entries()) + 1}", text)
|
||||
|
||||
signals = [SignalProcessor.process_signal(None, text)
|
||||
signals = [parse_rating(text)
|
||||
for text in (INVERTED, REFUSAL, "**Rating**: Buy\n\nAccumulate.")]
|
||||
assert [e["rating"] for e in log.load_entries()] == signals
|
||||
|
||||
@@ -89,8 +90,8 @@ def test_the_signal_and_the_log_agree_on_the_same_decision(tmp_path):
|
||||
@pytest.mark.unit
|
||||
def test_an_unscored_decision_is_left_out_of_the_backtest_figures(tmp_path):
|
||||
"""REVIEW has no direction, so it cannot count for or against the system."""
|
||||
from tradingagents.agents.utils.memory import TradingMemoryLog
|
||||
from tradingagents.backtest import summarize
|
||||
from tradingagents.decision_log import TradingMemoryLog
|
||||
|
||||
log = TradingMemoryLog({"memory_log_path": str(tmp_path / "m.md")})
|
||||
log.store_decision("NVDA", "2026-01-05", "**Rating**: Buy\n\nx")
|
||||
@@ -98,7 +99,7 @@ def test_an_unscored_decision_is_left_out_of_the_backtest_figures(tmp_path):
|
||||
log.store_decision("AAPL", "2026-01-05", REFUSAL)
|
||||
log.update_with_outcome("AAPL", "2026-01-05", 0.1, 0.04, 5, "note", "2026-02-01")
|
||||
|
||||
summary = summarize(log)
|
||||
summary = summarize(tmp_path / "m.md")
|
||||
assert set(summary.by_rating) == {"Buy"}
|
||||
|
||||
|
||||
@@ -121,8 +122,8 @@ def test_the_cli_says_when_a_run_produced_no_usable_rating(monkeypatch, tmp_path
|
||||
pass
|
||||
|
||||
def process_signal(self, text):
|
||||
from tradingagents.graph.signal_processing import SignalProcessor
|
||||
return SignalProcessor.process_signal(None, text)
|
||||
from tradingagents.agents.rating import parse_rating
|
||||
return parse_rating(text)
|
||||
|
||||
def get_graph_args(self, callbacks=None):
|
||||
return {}
|
||||
@@ -145,23 +146,23 @@ def test_the_cli_says_when_a_run_produced_no_usable_rating(monkeypatch, tmp_path
|
||||
fake = _Graph()
|
||||
fake.graph = fake
|
||||
fake.propagator = fake
|
||||
monkeypatch.setattr(m, "TradingAgentsGraph", lambda *a, **k: fake)
|
||||
monkeypatch.setattr(m, "create_layout", lambda: None)
|
||||
monkeypatch.setattr(m, "update_display", lambda *a, **k: None)
|
||||
monkeypatch.setattr(m, "Live", type("L", (), {"__init__": lambda s, *a, **k: None,
|
||||
monkeypatch.setattr(cli_run, "TradingAgentsGraph", lambda *a, **k: fake)
|
||||
monkeypatch.setattr(cli_run, "create_layout", lambda: None)
|
||||
monkeypatch.setattr(cli_run, "update_display", lambda *a, **k: None)
|
||||
monkeypatch.setattr(cli_run, "Live", type("L", (), {"__init__": lambda s, *a, **k: None,
|
||||
"__enter__": lambda s: s,
|
||||
"__exit__": lambda s, *a: False}))
|
||||
monkeypatch.setattr(m.console, "print", lambda *a, **k: printed.append(" ".join(str(x) for x in a)))
|
||||
monkeypatch.setattr(m, "display_complete_report", lambda *a, **k: None)
|
||||
monkeypatch.setattr(cli_run, "display_complete_report", lambda *a, **k: None)
|
||||
monkeypatch.setattr(m.typer, "prompt", lambda *a, **k: "N")
|
||||
monkeypatch.setattr(m, "get_user_selections", lambda: {
|
||||
monkeypatch.setattr(cli_run, "get_user_selections", lambda: {
|
||||
"ticker": "NVDA", "analysis_date": "2026-01-10",
|
||||
"analysts": [AnalystType.MARKET], "asset_type": "stock",
|
||||
})
|
||||
monkeypatch.setattr(m, "_build_run_config", lambda s, c: {
|
||||
monkeypatch.setattr(cli_run, "_build_run_config", lambda s, c: {
|
||||
"data_cache_dir": str(tmp_path / "c"), "results_dir": str(tmp_path / "r")})
|
||||
|
||||
m.run_analysis()
|
||||
cli_run.run_analysis()
|
||||
|
||||
assert any("review" in line.lower() for line in printed), printed[-5:]
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ from urllib.error import HTTPError
|
||||
|
||||
import pytest
|
||||
|
||||
from tradingagents.dataflows import reddit
|
||||
from tradingagents.dataflows.vendors import reddit
|
||||
|
||||
_SAMPLE_ATOM = """<?xml version="1.0" encoding="UTF-8"?>
|
||||
<feed xmlns="http://www.w3.org/2005/Atom">
|
||||
@@ -251,7 +251,6 @@ def test_posts_from_an_unrequested_or_unnamed_subreddit_are_not_dropped():
|
||||
assert "NO LABEL" in out
|
||||
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_each_subreddit_keeps_its_own_quota():
|
||||
busy = [{"title": f"A{i}", "created_utc": None, "selftext": "", "subreddit": "a"} for i in range(9)]
|
||||
@@ -272,3 +271,43 @@ def test_empty_subreddit_on_a_full_page_is_not_called_empty():
|
||||
out = reddit.fetch_reddit_posts("NVDA", subreddits=("a", "b"))
|
||||
assert "r/b: <no posts found" not in out
|
||||
assert f"newest {reddit._FEED_PAGE}" in out
|
||||
|
||||
|
||||
def _screen_out(*dropped):
|
||||
"""A screen that drops posts whose text starts with one of ``dropped``."""
|
||||
def screen(texts):
|
||||
return [not t.startswith(dropped) for t in texts], "Screened: note"
|
||||
return screen
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_screened_out_posts_free_their_subreddit_slots():
|
||||
posts = [{"title": t, "created_utc": None, "selftext": "", "subreddit": "a"}
|
||||
for t in ("SPAM1", "SPAM2", "A1", "A2")]
|
||||
with patch.object(reddit, "_fetch_subreddit_rss", return_value=posts):
|
||||
out = reddit.fetch_reddit_posts("NVDA", subreddits=("a",), limit_per_sub=2,
|
||||
screen=_screen_out("SPAM"))
|
||||
assert out.startswith("Screened: note")
|
||||
assert "A1" in out and "A2" in out and "SPAM" not in out
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_a_subreddit_emptied_by_screening_is_not_called_empty():
|
||||
posts = [{"title": "SPAM", "created_utc": None, "selftext": "", "subreddit": "b"},
|
||||
{"title": "A1", "created_utc": None, "selftext": "", "subreddit": "a"}]
|
||||
with patch.object(reddit, "_fetch_subreddit_rss", return_value=posts):
|
||||
out = reddit.fetch_reddit_posts("NVDA", subreddits=("a", "b"), screen=_screen_out("SPAM"))
|
||||
assert "r/b: <no posts about NVDA after screening>" in out
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_an_unavailable_screen_keeps_every_post_and_says_so():
|
||||
posts = [{"title": "A1", "created_utc": None, "selftext": "", "subreddit": "a"}]
|
||||
|
||||
def unavailable(texts):
|
||||
return [True] * len(texts), "<Jev screening unavailable (HTTP 529); posts are unscreened>"
|
||||
|
||||
with patch.object(reddit, "_fetch_subreddit_rss", return_value=posts):
|
||||
screened = reddit.fetch_reddit_posts("NVDA", subreddits=("a", "b"), screen=unavailable)
|
||||
plain = reddit.fetch_reddit_posts("NVDA", subreddits=("a", "b"))
|
||||
assert screened == "<Jev screening unavailable (HTTP 529); posts are unscreened>\n\n" + plain
|
||||
|
||||
@@ -5,7 +5,7 @@ import unittest
|
||||
|
||||
import pytest
|
||||
|
||||
from tradingagents.dataflows.utils import safe_ticker_component
|
||||
from tradingagents.dataflows.symbols import safe_ticker_component
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
|
||||
+57
-1
@@ -13,8 +13,8 @@ from unittest import mock
|
||||
|
||||
import pytest
|
||||
|
||||
from tradingagents.dataflows import sec_edgar
|
||||
from tradingagents.dataflows.errors import NoMarketDataError
|
||||
from tradingagents.dataflows.vendors import sec_edgar
|
||||
|
||||
_REAL_FETCH = sec_edgar._fetch_json
|
||||
|
||||
@@ -237,3 +237,59 @@ def test_an_uninstalled_checkout_still_identifies_itself(monkeypatch):
|
||||
|
||||
monkeypatch.setattr(sec_edgar.metadata, "version", _missing)
|
||||
assert "@" in sec_edgar._user_agent()
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_capital_expenditure_is_found_under_either_tag_filers_use(monkeypatch):
|
||||
"""NVIDIA and Amazon report purchases of productive assets, not of property and equipment."""
|
||||
facts = {"facts": {"us-gaap": {"PaymentsToAcquireProductiveAssets": {"units": {"USD": [
|
||||
_fact("2024-12-31", 70_000_000, "2025-02-10", start="2024-01-01")]}}}}}
|
||||
monkeypatch.setattr(sec_edgar, "_fetch_json",
|
||||
lambda url: TICKER_MAP if "company_tickers" in url else facts)
|
||||
out = sec_edgar.get_cashflow("AAPL", "annual", "2025-03-01")
|
||||
assert [r for r in out.splitlines() if r.startswith("Capital Expenditure")] == ["Capital Expenditure,70"]
|
||||
|
||||
|
||||
def _columns(out):
|
||||
return [line for line in out.splitlines() if line.startswith(",")][0].split(",")[1:]
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_an_annual_balance_sheet_has_no_quarter_end_columns():
|
||||
"""A balance has no span, so a 10-Q's quarter-end balance passed as annual."""
|
||||
annual = _columns(sec_edgar.get_balance_sheet("AAPL", "annual", "2024-11-15"))
|
||||
quarterly = _columns(sec_edgar.get_balance_sheet("AAPL", "quarterly", "2024-11-15"))
|
||||
assert "2022-03-26" not in annual and "2024-09-28" in annual
|
||||
assert "2022-03-26" in quarterly
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_a_twelve_month_total_from_a_quarterly_report_is_not_a_fiscal_year(monkeypatch):
|
||||
"""Amazon's 10-Qs report trailing twelve months, which passed the annual span
|
||||
check and read as fiscal years overlapping the real ones."""
|
||||
facts = {"facts": {"us-gaap": {"NetCashProvidedByUsedInOperatingActivities": {"units": {"USD": [
|
||||
_fact("2024-12-31", 115_000_000_000, "2025-02-07", start="2024-01-01"),
|
||||
_fact("2025-03-31", 113_000_000_000, "2025-05-02", form="10-Q", fp="Q1", start="2024-04-01"),
|
||||
]}}}}}
|
||||
monkeypatch.setattr(sec_edgar, "_fetch_json",
|
||||
lambda url: TICKER_MAP if "company_tickers" in url else facts)
|
||||
assert _columns(sec_edgar.get_cashflow("AAPL", "annual", "2025-06-01")) == ["2024-12-31"]
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_a_recast_outside_the_annual_report_still_counts_from_its_filing(monkeypatch):
|
||||
"""Filers recast past years in an 8-K after a split or spin-off. The annual
|
||||
report decides the columns; the value is the latest filing of any form."""
|
||||
facts = {"facts": {"us-gaap": {"EarningsPerShareDiluted": {"units": {"USD/shares": [
|
||||
_fact("2017-03-31", 16.97, "2017-06-15", form="20-F", start="2016-04-01"),
|
||||
_fact("2017-03-31", 2.12, "2019-09-30", form="6-K", start="2016-04-01"),
|
||||
]}}}}}
|
||||
monkeypatch.setattr(sec_edgar, "_fetch_json",
|
||||
lambda url: TICKER_MAP if "company_tickers" in url else facts)
|
||||
|
||||
def eps(date):
|
||||
out = sec_edgar.get_income_statement("AAPL", "annual", date)
|
||||
return [line for line in out.splitlines() if line.startswith("Diluted EPS")][0].split(",")[1]
|
||||
|
||||
assert eps("2019-01-01") == "16.97"
|
||||
assert eps("2020-01-01") == "2.12"
|
||||
|
||||
@@ -1,23 +1,12 @@
|
||||
"""Tests for the shared rating heuristic and the SignalProcessor adapter.
|
||||
"""The rating heuristic that reads the decision's 5-tier rating.
|
||||
|
||||
The Portfolio Manager produces a typed PortfolioDecision via structured
|
||||
output and renders it to markdown that always contains a ``**Rating**: X``
|
||||
header. The deterministic heuristic in ``tradingagents.agents.utils.rating``
|
||||
is therefore sufficient to extract the rating downstream — no second LLM
|
||||
call is needed — and SignalProcessor is now a thin adapter that delegates
|
||||
to it.
|
||||
The Portfolio Manager's rendered decision always carries a ``**Rating**: X``
|
||||
header, so the rating is read deterministically; no second model call is made.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
from tradingagents.agents.utils.rating import (
|
||||
RATING_REVIEW,
|
||||
RATINGS_5_TIER,
|
||||
extract_rating,
|
||||
is_review,
|
||||
parse_rating,
|
||||
)
|
||||
from tradingagents.graph.signal_processing import SignalProcessor
|
||||
from tradingagents.agents.rating import RATING_REVIEW, RATINGS_5_TIER, extract_rating, parse_rating
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Heuristic parser
|
||||
@@ -67,44 +56,9 @@ class TestParseRating:
|
||||
for r in RATINGS_5_TIER:
|
||||
assert parse_rating(f"Rating: {r}") == r
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# SignalProcessor: thin adapter over the heuristic
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
class TestSignalProcessor:
|
||||
def test_returns_rating_from_pm_markdown(self):
|
||||
sp = SignalProcessor()
|
||||
md = "**Rating**: Overweight\n\n**Executive Summary**: Build gradually."
|
||||
assert sp.process_signal(md) == "Overweight"
|
||||
|
||||
def test_makes_no_llm_calls(self):
|
||||
"""SignalProcessor must not invoke the LLM it was constructed with —
|
||||
the rating is parseable from the rendered PM markdown directly."""
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
llm = MagicMock()
|
||||
sp = SignalProcessor(llm)
|
||||
sp.process_signal("Rating: Buy\nDetails.")
|
||||
llm.invoke.assert_not_called()
|
||||
llm.with_structured_output.assert_not_called()
|
||||
|
||||
def test_unparseable_signal_is_review_not_silent_hold(self):
|
||||
# #1170: an unrecognizable decision must surface REVIEW, not a fabricated
|
||||
# tradeable Hold.
|
||||
sp = SignalProcessor()
|
||||
signal = sp.process_signal("Plain prose without a recommendation.")
|
||||
assert signal == RATING_REVIEW
|
||||
assert is_review(signal)
|
||||
assert signal not in RATINGS_5_TIER
|
||||
|
||||
def test_fullwidth_colon_is_parsed_not_reviewed(self):
|
||||
# #1170: `Rating:Overweight` (fullwidth colon) used to defeat the regex
|
||||
# and silently become Hold; NFKC normalization now parses it.
|
||||
sp = SignalProcessor()
|
||||
assert sp.process_signal("Rating:Overweight\n理由はこちら。") == "Overweight"
|
||||
# `Rating:Overweight` (fullwidth colon) is read, not sent to review (#1170).
|
||||
assert parse_rating("Rating:Overweight\n理由はこちら。") == "Overweight"
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@@ -131,7 +85,6 @@ class TestGraphSignalContract:
|
||||
def _bare_graph(self):
|
||||
from tradingagents.graph.trading_graph import TradingAgentsGraph
|
||||
g = object.__new__(TradingAgentsGraph)
|
||||
g.signal_processor = SignalProcessor()
|
||||
return g
|
||||
|
||||
def test_graph_surfaces_review(self):
|
||||
|
||||
@@ -12,8 +12,8 @@ from datetime import datetime, timezone
|
||||
|
||||
import pytest
|
||||
|
||||
from tradingagents.dataflows import reddit, stocktwits
|
||||
from tradingagents.dataflows.date_window import in_window
|
||||
from tradingagents.dataflows.vendors import reddit, stocktwits
|
||||
|
||||
|
||||
class _JsonResp:
|
||||
@@ -172,7 +172,6 @@ def test_reddit_live_empty_feed_is_a_real_absence(monkeypatch):
|
||||
assert "unavailable" not in out
|
||||
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_stocktwits_empty_stream_for_a_past_window_is_unavailable(monkeypatch):
|
||||
monkeypatch.setattr(stocktwits, "urlopen", lambda *a, **k: _JsonResp({"messages": []}))
|
||||
@@ -180,7 +179,6 @@ def test_stocktwits_empty_stream_for_a_past_window_is_unavailable(monkeypatch):
|
||||
assert "unavailable" in out and "not an absence" in out
|
||||
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_reddit_window_straddling_the_lookback_is_unavailable(monkeypatch):
|
||||
# Ten days ago through five days ago: the week-long search never reaches the
|
||||
|
||||
@@ -8,12 +8,13 @@ transport error must degrade to a placeholder rather than raise.
|
||||
from __future__ import annotations
|
||||
|
||||
import http.client
|
||||
import json
|
||||
from unittest.mock import patch
|
||||
from urllib.error import HTTPError
|
||||
|
||||
import pytest
|
||||
|
||||
from tradingagents.dataflows import stocktwits
|
||||
from tradingagents.dataflows.vendors import stocktwits
|
||||
|
||||
|
||||
def _raise(exc):
|
||||
@@ -75,3 +76,48 @@ class TestStockTwitsCryptoSymbols:
|
||||
with patch.object(stocktwits, "urlopen", side_effect=fake_urlopen):
|
||||
stocktwits.fetch_stocktwits_messages("BTC-USD")
|
||||
assert "/symbol/BTC.X.json" in seen["url"]
|
||||
|
||||
|
||||
def _stream(*bodies):
|
||||
payload = {"messages": [
|
||||
{"body": b, "created_at": "2026-01-09T15:00:00Z", "user": {"username": "u"},
|
||||
"entities": {"sentiment": {"basic": "Bullish"}}}
|
||||
for b in bodies
|
||||
]}
|
||||
|
||||
class _Resp:
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *a):
|
||||
return False
|
||||
|
||||
def read(self):
|
||||
return json.dumps(payload).encode()
|
||||
return _Resp()
|
||||
|
||||
|
||||
def _drop_spam(texts):
|
||||
return [not t.startswith("SPAM") for t in texts], "Screened: note"
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
class TestStockTwitsScreening:
|
||||
def test_screened_out_messages_leave_the_block_and_its_counts(self):
|
||||
with patch.object(stocktwits, "urlopen", return_value=_stream("SPAM", "long NVDA")):
|
||||
out = stocktwits.fetch_stocktwits_messages("NVDA", screen=_drop_spam)
|
||||
assert out.startswith("Screened: note")
|
||||
assert "long NVDA" in out and "SPAM" not in out
|
||||
assert "Total: 1 most-recent" in out
|
||||
|
||||
def test_all_screened_out_is_not_called_empty(self):
|
||||
with patch.object(stocktwits, "urlopen", return_value=_stream("SPAM")):
|
||||
out = stocktwits.fetch_stocktwits_messages("NVDA", screen=_drop_spam)
|
||||
assert "none of the 1 StockTwits messages is about $NVDA" in out
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_html_entities_in_message_bodies_are_decoded():
|
||||
with patch.object(stocktwits, "urlopen", return_value=_stream("S&P wasn't up")):
|
||||
out = stocktwits.fetch_stocktwits_messages("NVDA")
|
||||
assert "S&P wasn't up" in out
|
||||
|
||||
@@ -18,8 +18,8 @@ import pytest
|
||||
import tradingagents.agents.analysts.sentiment_analyst as sentiment
|
||||
from tradingagents.agents.managers.portfolio_manager import create_portfolio_manager
|
||||
from tradingagents.agents.managers.research_manager import create_research_manager
|
||||
from tradingagents.agents.structured import NO_EXTERNAL_TOOLS
|
||||
from tradingagents.agents.trader.trader import create_trader
|
||||
from tradingagents.agents.utils.structured import NO_EXTERNAL_TOOLS
|
||||
|
||||
|
||||
def _capturing_llm(captured: dict, result):
|
||||
|
||||
@@ -197,7 +197,7 @@ def _structured_trader_llm(captured: dict, proposal: TraderProposal | None = Non
|
||||
def test_invoke_structured_falls_back_when_result_is_none():
|
||||
# A thinking model can answer in plain text, leaving the parser with None.
|
||||
# That must fall back to free text, not crash on render(None) (#1051).
|
||||
from tradingagents.agents.utils.structured import invoke_structured_or_freetext
|
||||
from tradingagents.agents.structured import invoke_structured_or_freetext
|
||||
|
||||
structured = MagicMock()
|
||||
structured.invoke.return_value = None
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
"""The suite runs the same on any machine: no test reaches the network."""
|
||||
|
||||
import socket
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.parametrize("connect", [
|
||||
lambda: socket.create_connection(("192.0.2.1", 80), timeout=1),
|
||||
lambda: socket.socket().connect_ex(("192.0.2.1", 80)),
|
||||
], ids=["connect", "connect_ex"])
|
||||
def test_a_test_cannot_reach_the_network(connect):
|
||||
"""A test that silently depends on a live vendor passes or fails with the
|
||||
machine it runs on; conftest refuses the connection instead."""
|
||||
with pytest.raises(OSError, match="reach the network"):
|
||||
connect()
|
||||
@@ -7,10 +7,10 @@ hit the right instrument instead of failing/mismatching.
|
||||
"""
|
||||
import pandas as pd
|
||||
|
||||
import tradingagents.agents.utils.agent_utils as au
|
||||
import tradingagents.dataflows.yfinance_news as ynews
|
||||
import tradingagents.graph.trading_graph as tg
|
||||
from tradingagents.graph.trading_graph import TradingAgentsGraph
|
||||
import tradingagents.agents.context as au
|
||||
import tradingagents.dataflows.vendors.yahoo.market as yahoo_market
|
||||
import tradingagents.dataflows.vendors.yahoo.news as ynews
|
||||
from tradingagents.graph import settlement
|
||||
|
||||
|
||||
def test_identity_lookup_normalizes_symbol(monkeypatch):
|
||||
@@ -24,7 +24,7 @@ def test_identity_lookup_normalizes_symbol(monkeypatch):
|
||||
def info(self):
|
||||
return {"longName": "Gold Futures", "quoteType": "FUTURE"}
|
||||
|
||||
monkeypatch.setattr(au.yf, "Ticker", FakeTicker)
|
||||
monkeypatch.setattr(yahoo_market.yf, "Ticker", FakeTicker)
|
||||
au.resolve_instrument_identity.cache_clear()
|
||||
|
||||
identity = au.resolve_instrument_identity("XAUUSD")
|
||||
@@ -45,11 +45,10 @@ def test_fetch_returns_normalizes_symbol(monkeypatch):
|
||||
idx = pd.date_range(start="2025-01-02", periods=len(prices), freq="D")
|
||||
return pd.DataFrame({"Close": prices}, index=idx)
|
||||
|
||||
monkeypatch.setattr(tg.yf, "Ticker", FakeTicker)
|
||||
monkeypatch.setattr(yahoo_market.yf, "Ticker", FakeTicker)
|
||||
|
||||
# _fetch_returns does not use ``self``; call unbound to avoid building the graph.
|
||||
raw, alpha, days, resolved = TradingAgentsGraph._fetch_returns(
|
||||
None, "XAUUSD", "2025-01-02", holding_days=5, benchmark="SPY"
|
||||
raw, alpha, days, resolved = settlement.fetch_returns(
|
||||
"XAUUSD", "2025-01-02", holding_days=5, benchmark="SPY"
|
||||
)
|
||||
|
||||
assert queried[0] == "GC=F" # stock symbol normalized (#984)
|
||||
|
||||
@@ -4,12 +4,8 @@ import unittest
|
||||
|
||||
import pytest
|
||||
|
||||
from tradingagents.dataflows.symbol_utils import (
|
||||
NoMarketDataError,
|
||||
crypto_base,
|
||||
is_yahoo_safe,
|
||||
normalize_symbol,
|
||||
)
|
||||
from tradingagents.dataflows.errors import NoMarketDataError
|
||||
from tradingagents.dataflows.symbols import crypto_base, normalize_symbol
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@@ -88,17 +84,6 @@ class TestNoMarketDataError(unittest.TestCase):
|
||||
self.assertEqual(err.canonical, "FOOBAR")
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
class TestIsYahooSafe(unittest.TestCase):
|
||||
def test_accepts_structural_chars(self):
|
||||
for sym in ("AAPL", "GC=F", "^GSPC", "BRK.B", "BTC-USD"):
|
||||
self.assertTrue(is_yahoo_safe(sym))
|
||||
|
||||
def test_rejects_slash_and_space(self):
|
||||
for sym in ("a/b", "AA PL", ""):
|
||||
self.assertFalse(is_yahoo_safe(sym))
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
class TestCryptoBase(unittest.TestCase):
|
||||
def test_resolves_known_crypto_forms(self):
|
||||
@@ -61,14 +61,11 @@ class TestTemperatureEnvOverlay:
|
||||
|
||||
@pytest.mark.unit
|
||||
class TestProviderKwargsTemperature:
|
||||
"""_get_provider_kwargs float-coerces and forwards temperature, or omits it."""
|
||||
"""build_llm_kwargs float-coerces and forwards temperature, or omits it."""
|
||||
|
||||
def _kwargs_for(self, temperature):
|
||||
from tradingagents.graph.trading_graph import TradingAgentsGraph
|
||||
# Call the method without constructing the full graph.
|
||||
graph = TradingAgentsGraph.__new__(TradingAgentsGraph)
|
||||
graph.config = {"llm_provider": "openai", "temperature": temperature}
|
||||
return TradingAgentsGraph._get_provider_kwargs(graph)
|
||||
from tradingagents.llm_clients import build_llm_kwargs
|
||||
return build_llm_kwargs({"llm_provider": "openai", "temperature": temperature})
|
||||
|
||||
def test_float_string_coerced(self):
|
||||
assert self._kwargs_for("0.3")["temperature"] == 0.3
|
||||
|
||||
@@ -2,8 +2,8 @@ import unittest
|
||||
|
||||
import pytest
|
||||
|
||||
from cli.utils import normalize_ticker_symbol
|
||||
from tradingagents.agents.utils.agent_utils import build_instrument_context
|
||||
from cli.prompts import normalize_ticker_symbol
|
||||
from tradingagents.agents.context import build_instrument_context
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@@ -17,12 +17,11 @@ class TickerSymbolHandlingTests(unittest.TestCase):
|
||||
self.assertIn("exchange suffix", context)
|
||||
|
||||
def test_single_get_ticker_no_shadow(self):
|
||||
# Regression: cli/main.py had a duplicate get_ticker with an empty
|
||||
# questionary prompt (rendered as a bare "?") that shadowed the
|
||||
# descriptive one in cli/utils. Keep a single canonical definition.
|
||||
import cli.main
|
||||
import cli.utils
|
||||
self.assertIs(cli.main.get_ticker, cli.utils.get_ticker)
|
||||
# A second get_ticker with an empty prompt (a bare "?") once shadowed
|
||||
# the descriptive one; the selection flow must use the one in prompts.
|
||||
import cli.prompts
|
||||
import cli.selections
|
||||
self.assertIs(cli.selections.get_ticker, cli.prompts.get_ticker)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -15,14 +15,7 @@ from langchain_core.messages import AIMessage
|
||||
from langgraph.graph import END, START, MessagesState, StateGraph
|
||||
from langgraph.prebuilt import ToolNode
|
||||
|
||||
from tradingagents.agents.utils import (
|
||||
core_stock_tools,
|
||||
fundamental_data_tools,
|
||||
macro_data_tools,
|
||||
market_data_validation_tools,
|
||||
news_data_tools,
|
||||
technical_indicators_tools,
|
||||
)
|
||||
from tradingagents.agents import tools
|
||||
from tradingagents.dataflows.date_window import as_of, as_of_window
|
||||
|
||||
TRADE_DATE = "2026-08-14"
|
||||
@@ -56,16 +49,16 @@ def test_as_of_window(start, end, expected):
|
||||
|
||||
|
||||
DATED_TOOLS = [
|
||||
core_stock_tools.get_stock_data,
|
||||
fundamental_data_tools.get_fundamentals,
|
||||
fundamental_data_tools.get_balance_sheet,
|
||||
fundamental_data_tools.get_cashflow,
|
||||
fundamental_data_tools.get_income_statement,
|
||||
news_data_tools.get_news,
|
||||
news_data_tools.get_global_news,
|
||||
technical_indicators_tools.get_indicators,
|
||||
macro_data_tools.get_macro_indicators,
|
||||
market_data_validation_tools.get_verified_market_snapshot,
|
||||
tools.get_stock_data,
|
||||
tools.get_fundamentals,
|
||||
tools.get_balance_sheet,
|
||||
tools.get_cashflow,
|
||||
tools.get_income_statement,
|
||||
tools.get_news,
|
||||
tools.get_global_news,
|
||||
tools.get_indicators,
|
||||
tools.get_macro_indicators,
|
||||
tools.get_verified_market_snapshot,
|
||||
]
|
||||
|
||||
|
||||
@@ -95,28 +88,28 @@ def _run(tool, args, module):
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_statement_tool_with_omitted_date_uses_the_run_date():
|
||||
args = _run(fundamental_data_tools.get_balance_sheet, {"ticker": "AAPL"}, fundamental_data_tools)
|
||||
args = _run(tools.get_balance_sheet, {"ticker": "AAPL"}, tools)
|
||||
assert args[-1] == TRADE_DATE # #1331: an omitted date no longer means unfiltered
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_future_curr_date_from_the_model_is_clamped():
|
||||
args = _run(fundamental_data_tools.get_fundamentals,
|
||||
{"ticker": "AAPL", "curr_date": "2026-09-14"}, fundamental_data_tools)
|
||||
args = _run(tools.get_fundamentals,
|
||||
{"ticker": "AAPL", "curr_date": "2026-09-14"}, tools)
|
||||
assert args == ("get_fundamentals", "AAPL", TRADE_DATE)
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_future_window_from_the_model_is_clamped():
|
||||
args = _run(core_stock_tools.get_stock_data,
|
||||
{"symbol": "AAPL", "start_date": "2026-08-01", "end_date": "2026-09-14"}, core_stock_tools)
|
||||
args = _run(tools.get_stock_data,
|
||||
{"symbol": "AAPL", "start_date": "2026-08-01", "end_date": "2026-09-14"}, tools)
|
||||
assert args == ("get_stock_data", "AAPL", "2026-08-01", TRADE_DATE)
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_direct_call_without_state_is_unchanged():
|
||||
with mock.patch.object(news_data_tools, "route_to_vendor", return_value="ok") as routed:
|
||||
news_data_tools.get_news.func("AAPL", "2026-09-01", "2026-09-08")
|
||||
with mock.patch.object(tools, "route_to_vendor", return_value="ok") as routed:
|
||||
tools.get_news.func("AAPL", "2026-09-01", "2026-09-08")
|
||||
assert routed.call_args.args == ("get_news", "AAPL", "2026-09-01", "2026-09-08")
|
||||
|
||||
|
||||
|
||||
@@ -13,8 +13,13 @@ from unittest import mock
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
from tradingagents.agents.utils import news_data_tools, prediction_markets_tools
|
||||
from tradingagents.dataflows import alpha_vantage_news, polymarket, y_finance
|
||||
from tradingagents.agents import tools
|
||||
from tradingagents.dataflows.vendors import polymarket
|
||||
from tradingagents.dataflows.vendors.alpha_vantage import news as alpha_vantage_news
|
||||
from tradingagents.dataflows.vendors.yahoo import (
|
||||
fundamentals as yahoo_fundamentals,
|
||||
market as yahoo_market,
|
||||
)
|
||||
|
||||
|
||||
def _insider_frame(*dates):
|
||||
@@ -27,8 +32,8 @@ def _insider_frame(*dates):
|
||||
|
||||
def _yf_insider(frame, curr_date):
|
||||
ticker = mock.Mock(insider_transactions=frame)
|
||||
with mock.patch.object(y_finance.yf, "Ticker", return_value=ticker):
|
||||
return y_finance.get_insider_transactions("AAPL", curr_date)
|
||||
with mock.patch.object(yahoo_market.yf, "Ticker", return_value=ticker):
|
||||
return yahoo_fundamentals.get_insider_transactions("AAPL", curr_date)
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@@ -42,7 +47,7 @@ def test_yfinance_insider_filings_after_the_date_are_dropped():
|
||||
def test_yfinance_insider_date_before_coverage_is_unavailable_not_absent():
|
||||
out = _yf_insider(_insider_frame("2026-09-08", "2025-06-02"), "2024-01-01")
|
||||
assert "unavailable" in out and "No insider transactions reported" not in out
|
||||
assert "2025-06-02" in out # where coverage starts
|
||||
assert "2025-06-02" not in out # a transaction after the run date
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@@ -77,8 +82,8 @@ def test_polymarket_serves_a_current_run():
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.parametrize("tool", [news_data_tools.get_insider_transactions,
|
||||
prediction_markets_tools.get_prediction_markets], ids=lambda t: t.name)
|
||||
@pytest.mark.parametrize("tool", [tools.get_insider_transactions,
|
||||
tools.get_prediction_markets], ids=lambda t: t.name)
|
||||
def test_trade_date_is_injected_not_model_visible(tool):
|
||||
assert "trade_date" in tool.func.__code__.co_varnames
|
||||
props = tool.tool_call_schema.model_json_schema()["properties"]
|
||||
@@ -93,7 +98,7 @@ def test_a_historical_run_is_told_the_identity_is_current(monkeypatch):
|
||||
They are usually right for a past date, but a company that renamed or was
|
||||
reclassified since would read wrong, and every agent is told to anchor to
|
||||
this identity, so the run has to know which date it describes."""
|
||||
from tradingagents.agents.utils.agent_utils import build_instrument_context
|
||||
from tradingagents.agents.context import build_instrument_context
|
||||
|
||||
identity = {"company_name": "Example Corp", "sector": "Technology",
|
||||
"industry": "Software", "exchange": "NMS"}
|
||||
@@ -105,8 +110,8 @@ def test_a_historical_run_is_told_the_identity_is_current(monkeypatch):
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_a_current_run_is_not_cluttered_with_a_vintage_note(monkeypatch):
|
||||
from tradingagents.agents.utils.agent_utils import build_instrument_context
|
||||
from tradingagents.dataflows.utils import get_current_date
|
||||
from tradingagents.agents.context import build_instrument_context
|
||||
from tradingagents.dataflows.date_window import get_current_date
|
||||
|
||||
today = build_instrument_context("EXMP", "stock", {"company_name": "Example Corp"},
|
||||
curr_date=get_current_date())
|
||||
@@ -121,16 +126,14 @@ def test_insider_rows_are_dated_by_the_trade_not_the_filing():
|
||||
run must not be told these rows were public on their transaction date."""
|
||||
import pandas as pd
|
||||
|
||||
from tradingagents.dataflows import y_finance
|
||||
|
||||
frame = pd.DataFrame({
|
||||
"Shares": [100, 200],
|
||||
"Text": ["Sale at price 10.00 per share.", "Sale at price 11.00 per share."],
|
||||
"Start Date": pd.to_datetime(["2026-05-01", "2026-05-20"]),
|
||||
})
|
||||
ticker = mock.Mock(insider_transactions=frame)
|
||||
with mock.patch.object(y_finance.yf, "Ticker", return_value=ticker):
|
||||
out = y_finance.get_insider_transactions("AAPL", "2026-05-10")
|
||||
with mock.patch.object(yahoo_market.yf, "Ticker", return_value=ticker):
|
||||
out = yahoo_fundamentals.get_insider_transactions("AAPL", "2026-05-10")
|
||||
|
||||
assert "2026-05-01" in out and "2026-05-20" not in out # still bounded by the date
|
||||
assert "transaction date" in out.lower() # and says what the date means
|
||||
@@ -142,13 +145,12 @@ def test_an_indicator_that_could_not_be_read_is_not_shown_as_a_blank_value():
|
||||
"""The per-day fallback returned an empty string for a failed read, so the
|
||||
table rendered a row per day with nothing after the colon: an analyst reads
|
||||
that as "no value on that day" rather than "could not be obtained"."""
|
||||
from tradingagents.dataflows import y_finance
|
||||
from tradingagents.dataflows.errors import VendorError
|
||||
|
||||
with mock.patch.object(y_finance.StockstatsUtils, "get_stock_stats",
|
||||
with mock.patch.object(yahoo_market, "get_stock_stats",
|
||||
side_effect=RuntimeError("cache parse failed")), \
|
||||
pytest.raises(VendorError):
|
||||
y_finance.get_stockstats_indicator("AAPL", "rsi", "2026-05-08")
|
||||
yahoo_market.get_stockstats_indicator("AAPL", "rsi", "2026-05-08")
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@@ -165,12 +167,11 @@ def test_a_yfinance_failure_is_a_vendor_error_not_a_report(func, args):
|
||||
"""Returning the failure as text makes the router count it as an answer, so
|
||||
the chain stops and the analyst reads the error message as if it were data.
|
||||
yfinance serves the default path, so this is the one that matters most."""
|
||||
from tradingagents.dataflows import y_finance
|
||||
from tradingagents.dataflows.errors import VendorError
|
||||
|
||||
with mock.patch.object(y_finance.yf, "Ticker", side_effect=RuntimeError("yahoo hiccup")), \
|
||||
with mock.patch.object(yahoo_market.yf, "Ticker", side_effect=RuntimeError("yahoo hiccup")), \
|
||||
pytest.raises(VendorError):
|
||||
getattr(y_finance, func)(*args)
|
||||
getattr(yahoo_fundamentals, func)(*args)
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@@ -179,13 +180,13 @@ def test_a_yfinance_failure_is_a_vendor_error_not_a_report(func, args):
|
||||
("get_global_news_yfinance", ("2026-09-01", 7, 5)),
|
||||
])
|
||||
def test_a_yfinance_news_failure_is_a_vendor_error_not_a_report(func, args):
|
||||
from tradingagents.dataflows import yfinance_news
|
||||
from tradingagents.dataflows.errors import VendorError
|
||||
from tradingagents.dataflows.vendors.yahoo import news as yahoo_news
|
||||
|
||||
target = "Ticker" if "global" not in func else "Search"
|
||||
with mock.patch.object(yfinance_news.yf, target, side_effect=RuntimeError("yahoo hiccup")), \
|
||||
with mock.patch.object(yahoo_news.yf, target, side_effect=RuntimeError("yahoo hiccup")), \
|
||||
pytest.raises(VendorError):
|
||||
getattr(yfinance_news, func)(*args)
|
||||
getattr(yahoo_news, func)(*args)
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@@ -195,34 +196,34 @@ def test_an_unreachable_vendor_is_not_reported_as_a_missing_symbol(monkeypatch):
|
||||
company has no balance sheet, when the truth is we could not ask."""
|
||||
import pandas as pd
|
||||
|
||||
from tradingagents.dataflows import stockstats_utils, y_finance
|
||||
from tradingagents.dataflows.errors import NoMarketDataError, VendorRateLimitError
|
||||
from tradingagents.dataflows.vendors.yahoo import ohlcv
|
||||
|
||||
empty = mock.Mock(quarterly_balance_sheet=pd.DataFrame(), balance_sheet=pd.DataFrame())
|
||||
monkeypatch.setattr(y_finance.yf, "Ticker", lambda s: empty)
|
||||
monkeypatch.setattr(yahoo_market.yf, "Ticker", lambda s: empty)
|
||||
|
||||
monkeypatch.setattr(stockstats_utils, "vendor_reachable", lambda url: False)
|
||||
monkeypatch.setattr(ohlcv, "vendor_reachable", lambda url: False)
|
||||
with pytest.raises(VendorRateLimitError, match="unreachable"):
|
||||
y_finance.get_balance_sheet("AAPL", "annual", "2026-09-01")
|
||||
yahoo_fundamentals.get_balance_sheet("AAPL", "annual", "2026-09-01")
|
||||
|
||||
monkeypatch.setattr(stockstats_utils, "vendor_reachable", lambda url: True)
|
||||
monkeypatch.setattr(ohlcv, "vendor_reachable", lambda url: True)
|
||||
with pytest.raises(NoMarketDataError):
|
||||
y_finance.get_balance_sheet("AAPL", "annual", "2026-09-01")
|
||||
yahoo_fundamentals.get_balance_sheet("AAPL", "annual", "2026-09-01")
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_every_vendor_unavailable_says_so_rather_than_crashing(monkeypatch):
|
||||
"""A throttled or unreachable chain used to raise RuntimeError('No available
|
||||
vendor'), which ends the run, and never said the vendor was the problem."""
|
||||
from tradingagents.dataflows import interface
|
||||
from tradingagents.dataflows import router
|
||||
from tradingagents.dataflows.errors import VendorRateLimitError
|
||||
|
||||
def _down(*a, **k):
|
||||
raise VendorRateLimitError("Yahoo Finance is unreachable")
|
||||
|
||||
monkeypatch.setitem(interface.VENDOR_METHODS["get_balance_sheet"], "yfinance", _down)
|
||||
monkeypatch.setitem(router.VENDOR_METHODS["get_balance_sheet"], "yfinance", _down)
|
||||
|
||||
out = interface.route_to_vendor("get_balance_sheet", "AAPL", "annual", "2026-09-01")
|
||||
out = router.route_to_vendor("get_balance_sheet", "AAPL", "annual", "2026-09-01")
|
||||
|
||||
assert "unavailable" in out.lower() and "unreachable" in out.lower()
|
||||
assert "delisted" not in out.lower() # not a claim about the symbol
|
||||
@@ -234,15 +235,69 @@ def test_the_price_path_also_tells_an_outage_from_an_unknown_symbol(monkeypatch)
|
||||
delisted symbol either."""
|
||||
import pandas as pd
|
||||
|
||||
from tradingagents.dataflows import stockstats_utils, y_finance
|
||||
from tradingagents.dataflows.errors import NoMarketDataError, VendorRateLimitError
|
||||
from tradingagents.dataflows.vendors.yahoo import ohlcv
|
||||
|
||||
monkeypatch.setattr(y_finance.yf, "Ticker", lambda s: mock.Mock(history=lambda **k: pd.DataFrame()))
|
||||
monkeypatch.setattr(yahoo_market.yf, "Ticker", lambda s: mock.Mock(history=lambda **k: pd.DataFrame()))
|
||||
|
||||
monkeypatch.setattr(stockstats_utils, "vendor_reachable", lambda url: False)
|
||||
monkeypatch.setattr(ohlcv, "vendor_reachable", lambda url: False)
|
||||
with pytest.raises(VendorRateLimitError, match="unreachable"):
|
||||
y_finance.get_YFin_data_online("AAPL", "2026-09-01", "2026-09-10")
|
||||
yahoo_market.get_YFin_data_online("AAPL", "2026-09-01", "2026-09-10")
|
||||
|
||||
monkeypatch.setattr(stockstats_utils, "vendor_reachable", lambda url: True)
|
||||
monkeypatch.setattr(ohlcv, "vendor_reachable", lambda url: True)
|
||||
with pytest.raises(NoMarketDataError):
|
||||
y_finance.get_YFin_data_online("AAPL", "2026-09-01", "2026-09-10")
|
||||
yahoo_market.get_YFin_data_online("AAPL", "2026-09-01", "2026-09-10")
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.parametrize("func, args", [
|
||||
pytest.param(f, a, id=f.__name__) for f, a in (
|
||||
(yahoo_market.get_YFin_data_online, ("AAPL", "2025-06-02", "2025-06-06")),
|
||||
(yahoo_fundamentals.get_balance_sheet, ("AAPL", "quarterly", "2025-06-06")),
|
||||
(yahoo_fundamentals.get_cashflow, ("AAPL", "quarterly", "2025-06-06")),
|
||||
(yahoo_fundamentals.get_income_statement, ("AAPL", "quarterly", "2025-06-06")),
|
||||
(yahoo_fundamentals.get_insider_transactions, ("AAPL", "2025-06-06")),
|
||||
)
|
||||
])
|
||||
def test_a_historical_run_is_not_told_todays_date(func, args):
|
||||
"""A header stamped with the wall clock tells a backtest when it is really running."""
|
||||
from datetime import date
|
||||
|
||||
statement = pd.DataFrame({pd.Timestamp("2025-03-31"): [1.0]}, index=["Total Assets"])
|
||||
prices = pd.DataFrame({"Open": [1.0], "High": [1.0], "Low": [1.0], "Close": [1.0], "Volume": [1]},
|
||||
index=pd.DatetimeIndex(["2025-06-02"], name="Date"))
|
||||
ticker = mock.Mock(quarterly_balance_sheet=statement, quarterly_cashflow=statement,
|
||||
quarterly_income_stmt=statement,
|
||||
insider_transactions=_insider_frame("2025-05-30"),
|
||||
history=lambda **k: prices)
|
||||
with mock.patch.object(yahoo_market.yf, "Ticker", return_value=ticker):
|
||||
out = func(*args)
|
||||
|
||||
assert date.today().isoformat() not in out
|
||||
|
||||
|
||||
def _dates_after(text: str, cutoff: str) -> list[str]:
|
||||
import re
|
||||
return [d for d in re.findall(r"\d{4}-\d{2}-\d{2}", text) if d > cutoff]
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_an_unavailable_notice_names_no_date_after_the_run():
|
||||
"""A notice explaining why data is missing named where the vendor's coverage
|
||||
starts or today's date, both after a historical run's date."""
|
||||
from tradingagents.agents.context import build_instrument_context
|
||||
from tradingagents.dataflows.date_window import (
|
||||
coverage_gap,
|
||||
get_current_date,
|
||||
withhold_live_profile,
|
||||
)
|
||||
|
||||
today = get_current_date()
|
||||
notices = [
|
||||
coverage_gap([pd.Timestamp(today, tz="UTC")], "2025-01-01", "2025-01-07", "Feed", "news"),
|
||||
withhold_live_profile("2025-01-07", "AAPL"),
|
||||
_yf_insider(_insider_frame(today), "2025-01-07"),
|
||||
build_instrument_context("EXMP", "stock", {"company_name": "Example"}, curr_date="2025-01-07"),
|
||||
]
|
||||
for notice in notices:
|
||||
assert _dates_after(notice, "2025-01-07") == [], notice
|
||||
|
||||
+12
-18
@@ -10,11 +10,7 @@ import pytest
|
||||
|
||||
import tradingagents.dataflows.config as config_module
|
||||
import tradingagents.default_config as default_config
|
||||
from tradingagents.dataflows import interface
|
||||
from tradingagents.dataflows.alpha_vantage_common import (
|
||||
AlphaVantageNotConfiguredError,
|
||||
AlphaVantageRateLimitError,
|
||||
)
|
||||
from tradingagents.dataflows import router
|
||||
from tradingagents.dataflows.config import set_config
|
||||
from tradingagents.dataflows.errors import (
|
||||
NoMarketDataError,
|
||||
@@ -22,7 +18,11 @@ from tradingagents.dataflows.errors import (
|
||||
VendorNotConfiguredError,
|
||||
VendorRateLimitError,
|
||||
)
|
||||
from tradingagents.dataflows.fred import FredNotConfiguredError
|
||||
from tradingagents.dataflows.vendors.alpha_vantage.common import (
|
||||
AlphaVantageNotConfiguredError,
|
||||
AlphaVantageRateLimitError,
|
||||
)
|
||||
from tradingagents.dataflows.vendors.fred import FredNotConfiguredError
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@@ -42,12 +42,6 @@ class HierarchyTests(unittest.TestCase):
|
||||
# ... and therefore still ValueErrors
|
||||
self.assertTrue(issubclass(FredNotConfiguredError, ValueError))
|
||||
|
||||
def test_symbol_utils_reexports_no_market_data_error(self):
|
||||
from tradingagents.dataflows.symbol_utils import (
|
||||
NoMarketDataError as ReExported,
|
||||
)
|
||||
self.assertIs(ReExported, NoMarketDataError)
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
class RouterHandlesBaseTypesTests(unittest.TestCase):
|
||||
@@ -65,11 +59,11 @@ class RouterHandlesBaseTypesTests(unittest.TestCase):
|
||||
raise AlphaVantageRateLimitError("slow down")
|
||||
|
||||
with mock.patch.dict(
|
||||
interface.VENDOR_METHODS,
|
||||
router.VENDOR_METHODS,
|
||||
{"get_stock_data": {"alpha_vantage": _throttled, "yfinance": lambda *a, **k: "YF"}},
|
||||
clear=False,
|
||||
):
|
||||
out = interface.route_to_vendor("get_stock_data", "AAPL", "2026-01-01", "2026-01-10")
|
||||
out = router.route_to_vendor("get_stock_data", "AAPL", "2026-01-01", "2026-01-10")
|
||||
self.assertEqual(out, "YF")
|
||||
|
||||
def test_not_configured_falls_through_to_next_vendor(self):
|
||||
@@ -79,11 +73,11 @@ class RouterHandlesBaseTypesTests(unittest.TestCase):
|
||||
raise AlphaVantageNotConfiguredError("no key")
|
||||
|
||||
with mock.patch.dict(
|
||||
interface.VENDOR_METHODS,
|
||||
router.VENDOR_METHODS,
|
||||
{"get_stock_data": {"alpha_vantage": _unconfigured, "yfinance": lambda *a, **k: "YF"}},
|
||||
clear=False,
|
||||
):
|
||||
out = interface.route_to_vendor("get_stock_data", "AAPL", "2026-01-01", "2026-01-10")
|
||||
out = router.route_to_vendor("get_stock_data", "AAPL", "2026-01-01", "2026-01-10")
|
||||
self.assertEqual(out, "YF")
|
||||
|
||||
def test_sole_unconfigured_vendor_surfaces_the_error(self):
|
||||
@@ -94,11 +88,11 @@ class RouterHandlesBaseTypesTests(unittest.TestCase):
|
||||
raise AlphaVantageNotConfiguredError("no key")
|
||||
|
||||
with mock.patch.dict(
|
||||
interface.VENDOR_METHODS,
|
||||
router.VENDOR_METHODS,
|
||||
{"get_stock_data": {"alpha_vantage": _unconfigured}},
|
||||
clear=False,
|
||||
), self.assertRaises(AlphaVantageNotConfiguredError):
|
||||
interface.route_to_vendor("get_stock_data", "AAPL", "2026-01-01", "2026-01-10")
|
||||
router.route_to_vendor("get_stock_data", "AAPL", "2026-01-01", "2026-01-10")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -13,9 +13,9 @@ import pytest
|
||||
|
||||
import tradingagents.dataflows.config as config_module
|
||||
import tradingagents.default_config as default_config
|
||||
from tradingagents.dataflows import interface
|
||||
from tradingagents.dataflows import router
|
||||
from tradingagents.dataflows.config import set_config
|
||||
from tradingagents.dataflows.symbol_utils import NoMarketDataError
|
||||
from tradingagents.dataflows.errors import NoMarketDataError
|
||||
|
||||
|
||||
def _reset_config():
|
||||
@@ -50,7 +50,7 @@ class VendorRoutingTests(unittest.TestCase):
|
||||
|
||||
def _route(self, vendors_for_get_stock_data):
|
||||
return mock.patch.dict(
|
||||
interface.VENDOR_METHODS,
|
||||
router.VENDOR_METHODS,
|
||||
{"get_stock_data": vendors_for_get_stock_data},
|
||||
clear=False,
|
||||
)
|
||||
@@ -60,7 +60,7 @@ class VendorRoutingTests(unittest.TestCase):
|
||||
set_config({"data_vendors": {"core_stock_apis": "yfinance"}})
|
||||
av = mock.Mock(side_effect=_returns("AV_DATA"))
|
||||
with self._route({"yfinance": _no_data, "alpha_vantage": av}):
|
||||
result = interface.route_to_vendor("get_stock_data", "FAKE", "2026-01-01", "2026-01-10")
|
||||
result = router.route_to_vendor("get_stock_data", "FAKE", "2026-01-01", "2026-01-10")
|
||||
self.assertIn("NO_DATA_AVAILABLE", result)
|
||||
av.assert_not_called() # the unchosen vendor was never tried
|
||||
|
||||
@@ -68,7 +68,7 @@ class VendorRoutingTests(unittest.TestCase):
|
||||
# Listing both vendors opts in to ordered fallback.
|
||||
set_config({"data_vendors": {"core_stock_apis": "yfinance,alpha_vantage"}})
|
||||
with self._route({"yfinance": _no_data, "alpha_vantage": _returns("AV_DATA")}):
|
||||
result = interface.route_to_vendor("get_stock_data", "AAPL", "2026-01-01", "2026-01-10")
|
||||
result = router.route_to_vendor("get_stock_data", "AAPL", "2026-01-01", "2026-01-10")
|
||||
self.assertEqual(result, "AV_DATA")
|
||||
|
||||
def test_primary_error_is_logged_not_masked(self):
|
||||
@@ -76,8 +76,8 @@ class VendorRoutingTests(unittest.TestCase):
|
||||
# must be visible in logs (broken primary not hidden).
|
||||
set_config({"data_vendors": {"core_stock_apis": "yfinance,alpha_vantage"}})
|
||||
with self._route({"yfinance": _raises(ValueError("boom")), "alpha_vantage": _no_data}), \
|
||||
self.assertLogs("tradingagents.dataflows.interface", level="WARNING") as cm:
|
||||
result = interface.route_to_vendor("get_stock_data", "AAPL", "2026-01-01", "2026-01-10")
|
||||
self.assertLogs("tradingagents.dataflows.router", level="WARNING") as cm:
|
||||
result = router.route_to_vendor("get_stock_data", "AAPL", "2026-01-01", "2026-01-10")
|
||||
self.assertIn("NO_DATA_AVAILABLE", result)
|
||||
joined = "\n".join(cm.output)
|
||||
self.assertIn("boom", joined) # the real error surfaced in logs
|
||||
@@ -86,18 +86,18 @@ class VendorRoutingTests(unittest.TestCase):
|
||||
def test_unknown_configured_vendor_raises(self):
|
||||
set_config({"data_vendors": {"core_stock_apis": "bogus_vendor"}})
|
||||
with self.assertRaises(ValueError) as ctx:
|
||||
interface.route_to_vendor("get_stock_data", "AAPL", "2026-01-01", "2026-01-10")
|
||||
router.route_to_vendor("get_stock_data", "AAPL", "2026-01-01", "2026-01-10")
|
||||
self.assertIn("bogus_vendor", str(ctx.exception))
|
||||
|
||||
def test_default_sentinel_uses_all_vendors(self):
|
||||
# No explicit choice ("default") keeps the resilient full-chain behavior.
|
||||
set_config({"data_vendors": {"core_stock_apis": "default"}})
|
||||
with self._route({"yfinance": _no_data, "alpha_vantage": _returns("AV_DATA")}):
|
||||
result = interface.route_to_vendor("get_stock_data", "AAPL", "2026-01-01", "2026-01-10")
|
||||
result = router.route_to_vendor("get_stock_data", "AAPL", "2026-01-01", "2026-01-10")
|
||||
self.assertEqual(result, "AV_DATA")
|
||||
|
||||
def _route_method(self, method, vendors):
|
||||
return mock.patch.dict(interface.VENDOR_METHODS, {method: vendors}, clear=False)
|
||||
return mock.patch.dict(router.VENDOR_METHODS, {method: vendors}, clear=False)
|
||||
|
||||
def test_optional_category_degrades_instead_of_raising(self):
|
||||
# An optional enrichment vendor (FRED macro) that raises must NOT abort
|
||||
@@ -106,7 +106,7 @@ class VendorRoutingTests(unittest.TestCase):
|
||||
with self._route_method(
|
||||
"get_macro_indicators", {"fred": _raises(ValueError("FRED 400: bad series"))}
|
||||
):
|
||||
result = interface.route_to_vendor("get_macro_indicators", "cpi", "2026-01-01")
|
||||
result = router.route_to_vendor("get_macro_indicators", "cpi", "2026-01-01")
|
||||
self.assertIn("DATA_UNAVAILABLE", result)
|
||||
self.assertIn("macro_data", result)
|
||||
|
||||
@@ -116,7 +116,7 @@ class VendorRoutingTests(unittest.TestCase):
|
||||
set_config({"data_vendors": {"core_stock_apis": "yfinance"}})
|
||||
with self._route({"yfinance": _raises(ValueError("boom"))}), \
|
||||
self.assertRaises(ValueError):
|
||||
interface.route_to_vendor("get_stock_data", "AAPL", "2026-01-01", "2026-01-10")
|
||||
router.route_to_vendor("get_stock_data", "AAPL", "2026-01-01", "2026-01-10")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -5,7 +5,7 @@ from __future__ import annotations
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
import tradingagents.dataflows.market_data_validator as validator
|
||||
import tradingagents.dataflows.vendors.yahoo.snapshot as validator
|
||||
|
||||
|
||||
def _sample_ohlcv() -> pd.DataFrame:
|
||||
@@ -66,9 +66,7 @@ class TestVerifiedSnapshot:
|
||||
@pytest.mark.unit
|
||||
class TestTool:
|
||||
def test_tool_delegates_to_builder(self, monkeypatch):
|
||||
from tradingagents.agents.utils.market_data_validation_tools import (
|
||||
get_verified_market_snapshot,
|
||||
)
|
||||
from tradingagents.agents.tools import get_verified_market_snapshot
|
||||
monkeypatch.setattr(validator, "load_ohlcv", lambda s, d, fill_gaps=True: _sample_ohlcv())
|
||||
out = get_verified_market_snapshot.invoke(
|
||||
{"symbol": "COF", "curr_date": "2026-05-20"}
|
||||
@@ -13,12 +13,12 @@ import pandas as pd
|
||||
import pytest
|
||||
|
||||
import tradingagents.dataflows.config as config_module
|
||||
import tradingagents.dataflows.y_finance as y_finance
|
||||
import tradingagents.dataflows.vendors.yahoo.market as yahoo_market
|
||||
import tradingagents.default_config as default_config
|
||||
from tradingagents.dataflows import interface
|
||||
from tradingagents.dataflows import router
|
||||
from tradingagents.dataflows.config import set_config
|
||||
from tradingagents.dataflows.stockstats_utils import _assert_ohlcv_not_stale
|
||||
from tradingagents.dataflows.symbol_utils import NoMarketDataError
|
||||
from tradingagents.dataflows.errors import NoMarketDataError
|
||||
from tradingagents.dataflows.vendors.yahoo.ohlcv import _assert_ohlcv_not_stale
|
||||
|
||||
|
||||
def _frame(date):
|
||||
@@ -76,9 +76,9 @@ class StaleGuardPropagationTests(unittest.TestCase):
|
||||
def history(self, start, end):
|
||||
return stale
|
||||
|
||||
with mock.patch.object(y_finance.yf, "Ticker", DummyTicker), \
|
||||
with mock.patch.object(yahoo_market.yf, "Ticker", DummyTicker), \
|
||||
self.assertRaises(NoMarketDataError):
|
||||
y_finance.get_YFin_data_online("CB", "2026-06-01", "2026-06-11")
|
||||
yahoo_market.get_YFin_data_online("CB", "2026-06-01", "2026-06-11")
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@@ -98,11 +98,11 @@ class StaleGuardRoutingTests(unittest.TestCase):
|
||||
)
|
||||
|
||||
with mock.patch.dict(
|
||||
interface.VENDOR_METHODS,
|
||||
router.VENDOR_METHODS,
|
||||
{"get_stock_data": {"yfinance": _stale}},
|
||||
clear=False,
|
||||
):
|
||||
out = interface.route_to_vendor(
|
||||
out = router.route_to_vendor(
|
||||
"get_stock_data", "CB", "2026-06-01", "2026-06-11"
|
||||
)
|
||||
self.assertIn("NO_DATA_AVAILABLE", out)
|
||||
|
||||
@@ -1,37 +1,9 @@
|
||||
import contextlib
|
||||
import warnings
|
||||
from dotenv import find_dotenv, load_dotenv
|
||||
|
||||
# Load .env files at package import so DEFAULT_CONFIG's env-var overlay
|
||||
# (and every llm_clients consumer) sees the user's keys regardless of
|
||||
# which entry point started the process. find_dotenv(usecwd=True) walks
|
||||
# from the CWD, so the installed `tradingagents` console script picks up
|
||||
# the project's .env instead of stepping up from site-packages.
|
||||
# load_dotenv defaults to override=False, so it never clobbers values
|
||||
# the caller has already exported.
|
||||
try:
|
||||
from dotenv import find_dotenv, load_dotenv
|
||||
|
||||
load_dotenv(find_dotenv(usecwd=True))
|
||||
load_dotenv(find_dotenv(".env.enterprise", usecwd=True), override=False)
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
# langchain-core 1.3.3 calls surface_langchain_deprecation_warnings() in
|
||||
# its own __init__, which prepends default-action filters for its
|
||||
# subclassed warning categories. To suppress a specific warning we must
|
||||
# install our filter AFTER langchain-core has installed its own, so import
|
||||
# it first. The package is a guaranteed transitive dep via langgraph.
|
||||
with contextlib.suppress(ImportError):
|
||||
import langchain_core # noqa: F401
|
||||
|
||||
# langgraph-checkpoint 4.0.3 calls Reviver() at module load without an
|
||||
# explicit allowed_objects, which triggers a noisy pending-deprecation
|
||||
# warning from langchain-core 1.3.3 on every interpreter start. The fix
|
||||
# is already merged upstream (langchain-ai/langgraph#7743, 2026-05-08)
|
||||
# and will arrive in the next langgraph-checkpoint release. Remove this
|
||||
# block (and the langchain_core preload above) when we bump past it.
|
||||
warnings.filterwarnings(
|
||||
"ignore",
|
||||
message=r"The default value of `allowed_objects`.*",
|
||||
category=PendingDeprecationWarning,
|
||||
)
|
||||
# Load .env at package import so DEFAULT_CONFIG's env-var overlay and every LLM
|
||||
# client see the user's keys whichever entry point started the process.
|
||||
# usecwd=True walks from the working directory, so the installed console script
|
||||
# finds the project's .env rather than looking beside site-packages. Values the
|
||||
# caller has already exported are never overridden.
|
||||
load_dotenv(find_dotenv(usecwd=True))
|
||||
load_dotenv(find_dotenv(".env.enterprise", usecwd=True), override=False)
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
from .analysts.fundamentals_analyst import create_fundamentals_analyst
|
||||
from .analysts.market_analyst import create_market_analyst
|
||||
from .analysts.news_analyst import create_news_analyst
|
||||
from .analysts.sentiment_analyst import (
|
||||
create_sentiment_analyst,
|
||||
create_social_media_analyst, # deprecated alias kept for back-compat
|
||||
)
|
||||
from .analysts.sentiment_analyst import create_sentiment_analyst
|
||||
from .context import create_msg_delete
|
||||
from .managers.portfolio_manager import create_portfolio_manager
|
||||
from .managers.research_manager import create_research_manager
|
||||
from .researchers.bear_researcher import create_bear_researcher
|
||||
@@ -12,9 +10,8 @@ from .researchers.bull_researcher import create_bull_researcher
|
||||
from .risk_mgmt.aggressive_debator import create_aggressive_debator
|
||||
from .risk_mgmt.conservative_debator import create_conservative_debator
|
||||
from .risk_mgmt.neutral_debator import create_neutral_debator
|
||||
from .state import AgentState, InvestDebateState, RiskDebateState
|
||||
from .trader.trader import create_trader
|
||||
from .utils.agent_states import AgentState, InvestDebateState, RiskDebateState
|
||||
from .utils.agent_utils import create_msg_delete
|
||||
|
||||
__all__ = [
|
||||
"AgentState",
|
||||
@@ -32,6 +29,5 @@ __all__ = [
|
||||
"create_portfolio_manager",
|
||||
"create_conservative_debator",
|
||||
"create_sentiment_analyst",
|
||||
"create_social_media_analyst", # deprecated; will be removed in a future version
|
||||
"create_trader",
|
||||
]
|
||||
|
||||
@@ -1,12 +1,21 @@
|
||||
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
|
||||
|
||||
from tradingagents.agents.utils.agent_utils import (
|
||||
from tradingagents.agents.context import get_instrument_context_from_state, get_language_instruction
|
||||
from tradingagents.agents.tools import (
|
||||
get_balance_sheet,
|
||||
get_cashflow,
|
||||
get_fundamentals,
|
||||
get_income_statement,
|
||||
get_instrument_context_from_state,
|
||||
get_language_instruction,
|
||||
get_insider_transactions,
|
||||
)
|
||||
|
||||
# The tools this analyst is offered; its tool node is built from the same tuple.
|
||||
TOOLS = (
|
||||
get_fundamentals,
|
||||
get_balance_sheet,
|
||||
get_cashflow,
|
||||
get_income_statement,
|
||||
get_insider_transactions,
|
||||
)
|
||||
|
||||
|
||||
@@ -15,17 +24,10 @@ def create_fundamentals_analyst(llm):
|
||||
current_date = state["trade_date"]
|
||||
instrument_context = get_instrument_context_from_state(state)
|
||||
|
||||
tools = [
|
||||
get_fundamentals,
|
||||
get_balance_sheet,
|
||||
get_cashflow,
|
||||
get_income_statement,
|
||||
]
|
||||
|
||||
system_message = (
|
||||
"You are a researcher tasked with analyzing fundamental information over the past week about a company. Please write a comprehensive report of the company's fundamental information such as financial documents, company profile, basic company financials, and company financial history to gain a full view of the company's fundamental information to inform traders. Make sure to include as much detail as possible. Provide specific, actionable insights with supporting evidence to help traders make informed decisions."
|
||||
+ " Make sure to append a Markdown table at the end of the report to organize key points in the report, organized and easy to read."
|
||||
+ " Use the available tools: `get_fundamentals` for comprehensive company analysis, `get_balance_sheet`, `get_cashflow`, and `get_income_statement` for specific financial statements."
|
||||
+ " Use the available tools: `get_fundamentals` for comprehensive company analysis, `get_balance_sheet`, `get_cashflow`, and `get_income_statement` for specific financial statements, and `get_insider_transactions` for recent insider buying and selling."
|
||||
+ get_language_instruction()
|
||||
)
|
||||
|
||||
@@ -47,11 +49,11 @@ def create_fundamentals_analyst(llm):
|
||||
)
|
||||
|
||||
prompt = prompt.partial(system_message=system_message)
|
||||
prompt = prompt.partial(tool_names=", ".join([tool.name for tool in tools]))
|
||||
prompt = prompt.partial(tool_names=", ".join([tool.name for tool in TOOLS]))
|
||||
prompt = prompt.partial(current_date=current_date)
|
||||
prompt = prompt.partial(instrument_context=instrument_context)
|
||||
|
||||
chain = prompt | llm.bind_tools(tools)
|
||||
chain = prompt | llm.bind_tools(TOOLS)
|
||||
|
||||
result = chain.invoke(state["messages"])
|
||||
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
|
||||
|
||||
from tradingagents.agents.utils.agent_utils import (
|
||||
get_indicators,
|
||||
get_instrument_context_from_state,
|
||||
get_language_instruction,
|
||||
from tradingagents.agents.context import get_instrument_context_from_state, get_language_instruction
|
||||
from tradingagents.agents.tools import get_indicators, get_stock_data, get_verified_market_snapshot
|
||||
|
||||
# The tools this analyst is offered; its tool node is built from the same tuple.
|
||||
TOOLS = (
|
||||
get_stock_data,
|
||||
get_indicators,
|
||||
get_verified_market_snapshot,
|
||||
)
|
||||
|
||||
@@ -15,12 +17,6 @@ def create_market_analyst(llm):
|
||||
current_date = state["trade_date"]
|
||||
instrument_context = get_instrument_context_from_state(state)
|
||||
|
||||
tools = [
|
||||
get_stock_data,
|
||||
get_indicators,
|
||||
get_verified_market_snapshot,
|
||||
]
|
||||
|
||||
system_message = (
|
||||
"""You are a trading assistant tasked with analyzing financial markets. Your role is to select the **most relevant indicators** for a given market condition or trading strategy from the following list. The goal is to choose up to **8 indicators** that provide complementary insights without redundancy. Categories and each category's indicators are:
|
||||
|
||||
@@ -73,11 +69,11 @@ Write a very detailed and nuanced report of the trends you observe. Provide spec
|
||||
)
|
||||
|
||||
prompt = prompt.partial(system_message=system_message)
|
||||
prompt = prompt.partial(tool_names=", ".join([tool.name for tool in tools]))
|
||||
prompt = prompt.partial(tool_names=", ".join([tool.name for tool in TOOLS]))
|
||||
prompt = prompt.partial(current_date=current_date)
|
||||
prompt = prompt.partial(instrument_context=instrument_context)
|
||||
|
||||
chain = prompt | llm.bind_tools(tools)
|
||||
chain = prompt | llm.bind_tools(TOOLS)
|
||||
|
||||
result = chain.invoke(state["messages"])
|
||||
|
||||
|
||||
@@ -1,14 +1,21 @@
|
||||
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
|
||||
|
||||
from tradingagents.agents.utils.agent_utils import (
|
||||
from tradingagents.agents.context import get_instrument_context_from_state, get_language_instruction
|
||||
from tradingagents.agents.tools import (
|
||||
get_global_news,
|
||||
get_instrument_context_from_state,
|
||||
get_language_instruction,
|
||||
get_macro_indicators,
|
||||
get_news,
|
||||
get_prediction_markets,
|
||||
)
|
||||
|
||||
# The tools this analyst is offered; its tool node is built from the same tuple.
|
||||
TOOLS = (
|
||||
get_news,
|
||||
get_global_news,
|
||||
get_macro_indicators,
|
||||
get_prediction_markets,
|
||||
)
|
||||
|
||||
|
||||
def create_news_analyst(llm):
|
||||
def news_analyst_node(state):
|
||||
@@ -17,13 +24,6 @@ def create_news_analyst(llm):
|
||||
asset_label = "company" if asset_type == "stock" else "asset"
|
||||
instrument_context = get_instrument_context_from_state(state)
|
||||
|
||||
tools = [
|
||||
get_news,
|
||||
get_global_news,
|
||||
get_macro_indicators,
|
||||
get_prediction_markets,
|
||||
]
|
||||
|
||||
system_message = (
|
||||
f"You are a news researcher tasked with analyzing recent news and trends over the past week. Please write a comprehensive report of the current state of the world that is relevant for trading and macroeconomics. Use the available tools: get_news(ticker, start_date, end_date) for {asset_label}-specific news by ticker symbol, get_global_news(curr_date, look_back_days, limit) for broader macroeconomic news, get_macro_indicators(indicator, curr_date, look_back_days) to ground macro commentary in actual data from FRED (e.g. 'cpi', 'core_pce', 'unemployment', 'fed_funds_rate', '10y_treasury', 'yield_curve'), and get_prediction_markets(topic, limit) for live market-implied probabilities of forward-looking events (e.g. 'Fed rate cut', 'recession 2026', geopolitical or sector events). Provide specific, actionable insights with supporting evidence to help traders make informed decisions."
|
||||
+ """ Make sure to append a Markdown table at the end of the report to organize key points in the report, organized and easy to read."""
|
||||
@@ -48,11 +48,11 @@ def create_news_analyst(llm):
|
||||
)
|
||||
|
||||
prompt = prompt.partial(system_message=system_message)
|
||||
prompt = prompt.partial(tool_names=", ".join([tool.name for tool in tools]))
|
||||
prompt = prompt.partial(tool_names=", ".join([tool.name for tool in TOOLS]))
|
||||
prompt = prompt.partial(current_date=current_date)
|
||||
prompt = prompt.partial(instrument_context=instrument_context)
|
||||
|
||||
chain = prompt | llm.bind_tools(tools)
|
||||
chain = prompt | llm.bind_tools(TOOLS)
|
||||
result = chain.invoke(state["messages"])
|
||||
|
||||
report = ""
|
||||
|
||||
@@ -1,31 +1,20 @@
|
||||
"""Sentiment analyst — multi-source sentiment analysis for a target ticker.
|
||||
"""Sentiment analyst: one sentiment report from three sources.
|
||||
|
||||
Previously named ``social_media_analyst``. Renamed and redesigned because
|
||||
the old version had a prompt that demanded social-media analysis but the
|
||||
only tool available was Yahoo Finance news — which led LLMs to fabricate
|
||||
Reddit/X/StockTwits content under prompt pressure (verified live).
|
||||
The node fetches its sources before calling the model and puts them in the
|
||||
prompt, so the model reports on data it was given rather than inventing posts:
|
||||
|
||||
The redesigned agent pre-fetches three complementary data sources before
|
||||
the LLM is invoked and injects them into the prompt as structured blocks:
|
||||
1. News headlines: Yahoo Finance
|
||||
2. StockTwits messages: the cashtag stream, with Bullish/Bearish tags
|
||||
3. Reddit posts: r/wallstreetbets, r/stocks, r/investing
|
||||
|
||||
1. News headlines — Yahoo Finance (institutional framing)
|
||||
2. StockTwits messages — retail-trader posts indexed by cashtag, with
|
||||
user-labeled Bullish/Bearish sentiment tags
|
||||
3. Reddit posts — r/wallstreetbets, r/stocks, r/investing
|
||||
Each source is trimmed to the analysis window. With a TypeSafe key, the social
|
||||
posts are screened by Jev first (see post_screen). These feeds serve recent items
|
||||
and are not archived, so a historical run's sentiment inputs are not
|
||||
point-in-time.
|
||||
|
||||
Each source is trimmed to the analysis window. These text feeds serve recent
|
||||
items and are not archived as of a past date, so sentiment inputs for a
|
||||
historical run are not guaranteed to be point-in-time.
|
||||
|
||||
The agent does not use tool-calling; the data is in the prompt from
|
||||
turn 0. Output uses the structured-output pattern (json_schema for
|
||||
OpenAI/xAI, response_schema for Gemini, tool-use for Anthropic), falling
|
||||
back to free-text generation for providers that lack native support, so
|
||||
the sentiment header (band + score + confidence) is deterministic across
|
||||
runs and providers instead of free-form per-model prose.
|
||||
|
||||
See: https://github.com/TauricResearch/TradingAgents/issues/557
|
||||
See: https://github.com/TauricResearch/TradingAgents/issues/796
|
||||
The report is a SentimentReport through structured output where the provider
|
||||
supports it and free text otherwise, so the band, score and confidence header
|
||||
reads the same across providers.
|
||||
"""
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
@@ -33,19 +22,17 @@ from datetime import datetime, timedelta
|
||||
from langchain_core.messages import AIMessage
|
||||
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
|
||||
|
||||
from tradingagents.agents.context import get_instrument_context_from_state, get_language_instruction
|
||||
from tradingagents.agents.post_screen import jev_screen
|
||||
from tradingagents.agents.schemas import SentimentReport, render_sentiment_report
|
||||
from tradingagents.agents.utils.agent_utils import (
|
||||
get_instrument_context_from_state,
|
||||
get_language_instruction,
|
||||
get_news,
|
||||
)
|
||||
from tradingagents.agents.utils.structured import (
|
||||
from tradingagents.agents.structured import (
|
||||
NO_EXTERNAL_TOOLS,
|
||||
bind_structured,
|
||||
invoke_structured_or_freetext,
|
||||
)
|
||||
from tradingagents.dataflows.reddit import fetch_reddit_posts
|
||||
from tradingagents.dataflows.stocktwits import fetch_stocktwits_messages
|
||||
from tradingagents.agents.tools import get_news
|
||||
from tradingagents.dataflows.vendors.reddit import fetch_reddit_posts
|
||||
from tradingagents.dataflows.vendors.stocktwits import fetch_stocktwits_messages
|
||||
|
||||
|
||||
def _seven_days_back(trade_date: str) -> str:
|
||||
@@ -74,10 +61,11 @@ def create_sentiment_analyst(llm):
|
||||
news_block = get_news.func(ticker, start_date, end_date)
|
||||
# Pass the analysis window so a historical run trims social posts to it
|
||||
# instead of leaking today's chatter into a backtest (#1220).
|
||||
screen = jev_screen(ticker)
|
||||
stocktwits_block = fetch_stocktwits_messages(
|
||||
ticker, limit=30, start_date=start_date, end_date=end_date
|
||||
ticker, limit=30, start_date=start_date, end_date=end_date, screen=screen
|
||||
)
|
||||
reddit_block = fetch_reddit_posts(ticker, start_date=start_date, end_date=end_date)
|
||||
reddit_block = fetch_reddit_posts(ticker, start_date=start_date, end_date=end_date, screen=screen)
|
||||
|
||||
system_message = _build_system_message(
|
||||
ticker=ticker,
|
||||
@@ -167,7 +155,7 @@ Community discussion, without vote or comment counts. Subreddit character matter
|
||||
|
||||
## How to analyze this data (best practices)
|
||||
|
||||
1. **Read the StockTwits Bullish/Bearish ratio as a leading retail-sentiment signal.** A 70/30 bullish/bearish split is moderately bullish; ≥90/10 may indicate over-extension and contrarian risk; 50/50 is uncertainty. Sample size matters — base rates on the actual message count, not percentages alone.
|
||||
1. **Read the StockTwits Bullish/Bearish ratio as a leading retail-sentiment signal.** A 70/30 bullish/bearish split is moderately bullish; ≥90/10 may indicate over-extension and contrarian risk; 50/50 is uncertainty. Sample size matters — base rates on the actual message count, not percentages alone. A block headed "Screened by Jev" has had off-topic posts removed; its stance count is a classifier's read of every on-topic post fetched, labelled or not, of which the posts listed are a sample. Read it alongside the user tags.
|
||||
|
||||
2. **Look for cross-source divergences.** If news framing is bearish but StockTwits is overwhelmingly bullish, that mismatch is itself a signal — it can mean retail is leaning into a thesis the news flow hasn't caught up to (or vice versa, that retail is chasing while institutions are cautious).
|
||||
|
||||
@@ -193,25 +181,3 @@ Fill the following fields:
|
||||
- **narrative**: Full source-by-source breakdown, divergences, dominant narrative themes, catalysts and risks, and a markdown summary table of key sentiment signals (direction, source, supporting evidence).
|
||||
|
||||
{get_language_instruction()}"""
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Backwards-compatibility shim
|
||||
# ---------------------------------------------------------------------------
|
||||
def create_social_media_analyst(llm):
|
||||
"""Deprecated alias for :func:`create_sentiment_analyst`.
|
||||
|
||||
Kept so existing code that imports ``create_social_media_analyst``
|
||||
continues to work.
|
||||
|
||||
.. deprecated::
|
||||
Import :func:`create_sentiment_analyst` directly instead.
|
||||
"""
|
||||
import warnings
|
||||
warnings.warn(
|
||||
"create_social_media_analyst is deprecated and will be removed in a "
|
||||
"future version. Use create_sentiment_analyst instead.",
|
||||
DeprecationWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
return create_sentiment_analyst(llm)
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
"""Backwards-compatibility shim for the renamed module.
|
||||
|
||||
The agent is now ``sentiment_analyst`` and aggregates Yahoo Finance news,
|
||||
StockTwits cashtag streams, and Reddit posts into a single sentiment
|
||||
report. Import from ``tradingagents.agents.analysts.sentiment_analyst``
|
||||
going forward; this module will be removed in a future release.
|
||||
|
||||
See: https://github.com/TauricResearch/TradingAgents/issues/557
|
||||
"""
|
||||
|
||||
import warnings as _warnings
|
||||
|
||||
from tradingagents.agents.analysts.sentiment_analyst import ( # noqa: F401
|
||||
create_sentiment_analyst,
|
||||
create_social_media_analyst,
|
||||
)
|
||||
|
||||
_warnings.warn(
|
||||
"tradingagents.agents.analysts.social_media_analyst is deprecated. "
|
||||
"Import from tradingagents.agents.analysts.sentiment_analyst instead.",
|
||||
DeprecationWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
@@ -1,55 +1,18 @@
|
||||
"""Prompt context shared by the agents: instrument identity, output language,
|
||||
portfolio, and the message reset between analysts."""
|
||||
|
||||
import functools
|
||||
import logging
|
||||
from collections.abc import Mapping
|
||||
from typing import Any
|
||||
|
||||
import yfinance as yf
|
||||
from langchain_core.messages import HumanMessage, RemoveMessage
|
||||
|
||||
# Import tools from separate utility files
|
||||
from tradingagents.agents.utils.core_stock_tools import get_stock_data
|
||||
from tradingagents.agents.utils.fundamental_data_tools import (
|
||||
get_balance_sheet,
|
||||
get_cashflow,
|
||||
get_fundamentals,
|
||||
get_income_statement,
|
||||
)
|
||||
from tradingagents.agents.utils.macro_data_tools import get_macro_indicators
|
||||
from tradingagents.agents.utils.market_data_validation_tools import get_verified_market_snapshot
|
||||
from tradingagents.agents.utils.news_data_tools import (
|
||||
get_global_news,
|
||||
get_insider_transactions,
|
||||
get_news,
|
||||
)
|
||||
from tradingagents.agents.utils.prediction_markets_tools import get_prediction_markets
|
||||
from tradingagents.agents.utils.technical_indicators_tools import get_indicators
|
||||
|
||||
# Public surface: the data tools are imported here so agents and the graph
|
||||
# import them from one place, plus the instrument/language helpers defined below.
|
||||
__all__ = [
|
||||
"get_stock_data",
|
||||
"get_indicators",
|
||||
"get_fundamentals",
|
||||
"get_balance_sheet",
|
||||
"get_cashflow",
|
||||
"get_income_statement",
|
||||
"get_news",
|
||||
"get_global_news",
|
||||
"get_insider_transactions",
|
||||
"get_macro_indicators",
|
||||
"get_prediction_markets",
|
||||
"get_verified_market_snapshot",
|
||||
"build_instrument_context",
|
||||
"resolve_instrument_identity",
|
||||
"get_instrument_context_from_state",
|
||||
"get_language_instruction",
|
||||
"create_msg_delete",
|
||||
]
|
||||
from tradingagents.dataflows.date_window import get_current_date
|
||||
from tradingagents.dataflows.vendors.yahoo.fundamentals import get_company_profile
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
from tradingagents.dataflows.utils import get_current_date # noqa: E402
|
||||
|
||||
|
||||
def get_language_instruction() -> str:
|
||||
"""Return a prompt instruction for the configured output language.
|
||||
@@ -106,13 +69,11 @@ def resolve_instrument_identity(ticker: str) -> dict:
|
||||
ticker-only context rather than failing before analysis starts. Cached so
|
||||
the lookup happens at most once per ticker per process.
|
||||
|
||||
The symbol is normalized first (e.g. ``XAUUSD`` -> ``GC=F``) so identity
|
||||
resolves for the same instrument the price path actually fetches (#983).
|
||||
Identity resolves for the same instrument the price path fetches
|
||||
(``XAUUSD`` -> ``GC=F``, #983).
|
||||
"""
|
||||
from tradingagents.dataflows.symbol_utils import normalize_symbol
|
||||
|
||||
try:
|
||||
info = yf.Ticker(normalize_symbol(ticker)).info or {}
|
||||
info = get_company_profile(ticker)
|
||||
except Exception as exc: # noqa: BLE001 — fail open, never block the run
|
||||
logger.debug("Could not resolve instrument identity for %s: %s", ticker, exc)
|
||||
return {}
|
||||
@@ -185,9 +146,9 @@ def build_instrument_context(
|
||||
today = get_current_date()
|
||||
if curr_date and str(curr_date) < today:
|
||||
context += (
|
||||
f" This identity is how the vendor describes the instrument today "
|
||||
f"({today}), not necessarily on {curr_date}: a name or "
|
||||
f"classification changed since then would read as the current one."
|
||||
f" This identity is how the vendor describes the instrument today, "
|
||||
f"not necessarily on {curr_date}: a name or classification changed "
|
||||
f"since then would read as the current one."
|
||||
)
|
||||
|
||||
if is_crypto:
|
||||
@@ -10,13 +10,13 @@ back gracefully to free-text generation.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from tradingagents.agents.schemas import PortfolioDecision, render_pm_decision
|
||||
from tradingagents.agents.utils.agent_utils import (
|
||||
from tradingagents.agents.context import (
|
||||
get_instrument_context_from_state,
|
||||
get_language_instruction,
|
||||
get_portfolio_context_from_state,
|
||||
)
|
||||
from tradingagents.agents.utils.structured import (
|
||||
from tradingagents.agents.schemas import PortfolioDecision, render_pm_decision
|
||||
from tradingagents.agents.structured import (
|
||||
NO_EXTERNAL_TOOLS,
|
||||
bind_structured,
|
||||
invoke_structured_or_freetext,
|
||||
|
||||
@@ -2,12 +2,9 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from tradingagents.agents.context import get_instrument_context_from_state, get_language_instruction
|
||||
from tradingagents.agents.schemas import ResearchPlan, render_research_plan
|
||||
from tradingagents.agents.utils.agent_utils import (
|
||||
get_instrument_context_from_state,
|
||||
get_language_instruction,
|
||||
)
|
||||
from tradingagents.agents.utils.structured import (
|
||||
from tradingagents.agents.structured import (
|
||||
NO_EXTERNAL_TOOLS,
|
||||
bind_structured,
|
||||
invoke_structured_or_freetext,
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
"""Social-post screening with TypeSafe's Jev, when ``TYPESAFE_API_KEY`` is set.
|
||||
|
||||
Jev answers typed questions with calibrated probabilities. Each StockTwits or
|
||||
Reddit post is asked two: is it about the instrument, and which way does it
|
||||
lean on the instrument's stock. Code turns the answers into what the Sentiment
|
||||
Analyst reads: posts that are clearly about something else are dropped, and a
|
||||
stance count over the rest heads the source's block.
|
||||
|
||||
Configured by TypeSafe's own SDK variables, ``TYPESAFE_API_KEY`` and
|
||||
``TYPESAFE_DEFAULT_MODEL``. Without a key nothing here runs; if any request fails, the source's posts are kept unscreened and the
|
||||
block says screening was unavailable.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import os
|
||||
import random
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
|
||||
import requests
|
||||
|
||||
from tradingagents.agents.context import resolve_instrument_identity
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_URL = "https://api.typesafe.ai/v1/systemone"
|
||||
_DEFAULT_MODEL = "jev-latest"
|
||||
_RETRY_STATUSES = (429, 529) # rate limited, overloaded: back off and retry
|
||||
_TRANSIENT = (requests.ConnectionError, requests.Timeout, requests.exceptions.ChunkedEncodingError)
|
||||
_ATTEMPTS = 3
|
||||
_MAX_WAIT = 30.0
|
||||
_TIMEOUT = 15.0
|
||||
_WORKERS = 16 # well inside the documented 1,200 requests per minute
|
||||
|
||||
# A post is dropped only on a clear "not about it"; the uncertain middle stays.
|
||||
_OFF_TOPIC_BELOW = 0.3
|
||||
# A stance counts only when Jev is not genuinely uncertain about it.
|
||||
_STANCE_CONFIDENCE = 0.5
|
||||
|
||||
QUESTIONS = {
|
||||
"about": {
|
||||
"type": "noul",
|
||||
"instructions": "Is `post` about `instrument`: the company, its stock, its products or its outlook?",
|
||||
"criteria": {
|
||||
"true": "`post` discusses `instrument` itself.",
|
||||
"false": "`post` names `instrument` only in passing or in a list of tickers, is spam or "
|
||||
"promotion, or is about a different company.",
|
||||
},
|
||||
},
|
||||
"stance": {
|
||||
"type": "choice",
|
||||
"instructions": "What does the author of `post` expect for the stock price of `instrument`?",
|
||||
"criteria": {
|
||||
"bullish": "The author expects `instrument`'s stock to rise, or is buying or holding it long.",
|
||||
"bearish": "The author expects `instrument`'s stock to fall, or is selling or shorting it.",
|
||||
"neutral": "The author gives no view of their own on `instrument`'s stock: a question, "
|
||||
"news without opinion, or someone else's view quoted.",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
class TypeSafeError(Exception):
|
||||
"""A System One request that did not produce answers."""
|
||||
|
||||
|
||||
def system_one(state, questions: dict) -> dict[str, dict]:
|
||||
"""Ask ``questions`` about ``state``; return the answers keyed by question name.
|
||||
|
||||
Rate-limit and overload responses and dropped connections are retried with
|
||||
backoff, honouring ``Retry-After``; any other failure raises
|
||||
``TypeSafeError`` at once.
|
||||
"""
|
||||
body = {
|
||||
"state": state,
|
||||
"model": os.environ.get("TYPESAFE_DEFAULT_MODEL") or _DEFAULT_MODEL,
|
||||
"questions": questions,
|
||||
}
|
||||
headers = {"Authorization": f"Bearer {os.environ.get('TYPESAFE_API_KEY', '')}"}
|
||||
backoff, retry_after = 1.0, None
|
||||
for attempt in range(_ATTEMPTS):
|
||||
if attempt:
|
||||
time.sleep(retry_after if retry_after is not None else backoff * random.uniform(0.8, 1.2))
|
||||
backoff *= 2
|
||||
try:
|
||||
response = requests.post(_URL, json=body, headers=headers, timeout=_TIMEOUT)
|
||||
except requests.RequestException as exc:
|
||||
failure, retry_after = type(exc).__name__, None
|
||||
if isinstance(exc, _TRANSIENT):
|
||||
continue
|
||||
break
|
||||
if response.status_code == 200:
|
||||
return _answers(response, questions)
|
||||
failure, retry_after = f"HTTP {response.status_code}", _retry_after(response)
|
||||
if response.status_code not in _RETRY_STATUSES:
|
||||
break
|
||||
raise TypeSafeError(failure)
|
||||
|
||||
|
||||
def _retry_after(response) -> float | None:
|
||||
try:
|
||||
return min(max(0.0, float(response.headers.get("retry-after"))), _MAX_WAIT)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _answers(response, questions: dict) -> dict[str, dict]:
|
||||
try:
|
||||
payload = response.json()
|
||||
answers = payload["answers"]
|
||||
if all(answers[q]["type"] == spec["type"] for q, spec in questions.items()):
|
||||
logger.debug("TypeSafe answered with %s", payload.get("model"))
|
||||
return answers
|
||||
except (ValueError, KeyError, TypeError):
|
||||
pass
|
||||
raise TypeSafeError("malformed response")
|
||||
|
||||
|
||||
def _stance(answer: dict) -> str:
|
||||
choice = answer["choice"]
|
||||
if choice not in QUESTIONS["stance"]["criteria"] or answer["confidence"] < _STANCE_CONFIDENCE:
|
||||
return "unclear"
|
||||
return choice
|
||||
|
||||
|
||||
def jev_screen(ticker: str):
|
||||
"""A post screen for the social fetchers, or None without a TypeSafe key.
|
||||
|
||||
The screen takes the post texts and returns one keep flag per post and a
|
||||
note line for the top of the source's block.
|
||||
"""
|
||||
if not os.environ.get("TYPESAFE_API_KEY"):
|
||||
return None
|
||||
name = resolve_instrument_identity(ticker).get("company_name")
|
||||
instrument = f"{name} ({ticker})" if name else ticker
|
||||
|
||||
def screen(posts: list[str]) -> tuple[list[bool], str]:
|
||||
try:
|
||||
answers = _ask_each(instrument, posts)
|
||||
keep = [a["about"]["noul"] >= _OFF_TOPIC_BELOW for a in answers]
|
||||
stances = [_stance(a["stance"]) for a, kept in zip(answers, keep, strict=True) if kept]
|
||||
except (KeyError, TypeError):
|
||||
return _unscreened(instrument, posts, "malformed response")
|
||||
except TypeSafeError as exc:
|
||||
return _unscreened(instrument, posts, str(exc))
|
||||
counts = ", ".join(f"{stances.count(s)} {s}" for s in ("bullish", "bearish", "neutral", "unclear"))
|
||||
return keep, (
|
||||
f"Screened by Jev: {len(stances)} of the {len(posts)} posts fetched are about "
|
||||
f"{instrument}; their stance on its stock: {counts}."
|
||||
)
|
||||
|
||||
return screen
|
||||
|
||||
|
||||
def _unscreened(instrument: str, posts: list[str], failure: str) -> tuple[list[bool], str]:
|
||||
logger.warning("Jev screening failed for %s: %s", instrument, failure)
|
||||
return [True] * len(posts), f"<Jev screening unavailable ({failure}); posts are unscreened>"
|
||||
|
||||
|
||||
def _ask_each(instrument: str, posts: list[str]) -> list[dict]:
|
||||
"""One request per post. The first failure raises at once: requests not yet
|
||||
sent are cancelled, and those in flight finish in the background unread."""
|
||||
answers: list = [None] * len(posts)
|
||||
pool = ThreadPoolExecutor(max_workers=_WORKERS)
|
||||
try:
|
||||
futures = {
|
||||
pool.submit(system_one, {"instrument": instrument, "post": post}, QUESTIONS): i
|
||||
for i, post in enumerate(posts)
|
||||
}
|
||||
for future in as_completed(futures):
|
||||
answers[futures[future]] = future.result()
|
||||
finally:
|
||||
pool.shutdown(wait=False, cancel_futures=True)
|
||||
return answers
|
||||
@@ -1,4 +1,4 @@
|
||||
from tradingagents.agents.utils.agent_utils import (
|
||||
from tradingagents.agents.context import (
|
||||
get_instrument_context_from_state,
|
||||
get_language_instruction,
|
||||
opponent_argument_or_opening,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from tradingagents.agents.utils.agent_utils import (
|
||||
from tradingagents.agents.context import (
|
||||
get_instrument_context_from_state,
|
||||
get_language_instruction,
|
||||
opponent_argument_or_opening,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from tradingagents.agents.utils.agent_utils import (
|
||||
from tradingagents.agents.context import (
|
||||
get_instrument_context_from_state,
|
||||
get_language_instruction,
|
||||
get_portfolio_context_from_state,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from tradingagents.agents.utils.agent_utils import (
|
||||
from tradingagents.agents.context import (
|
||||
get_instrument_context_from_state,
|
||||
get_language_instruction,
|
||||
get_portfolio_context_from_state,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from tradingagents.agents.utils.agent_utils import (
|
||||
from tradingagents.agents.context import (
|
||||
get_instrument_context_from_state,
|
||||
get_language_instruction,
|
||||
get_portfolio_context_from_state,
|
||||
|
||||
@@ -0,0 +1,284 @@
|
||||
"""The data tools the analysts call.
|
||||
|
||||
Each dated tool takes the run's ``trade_date`` from graph state (``InjectedState``)
|
||||
and never serves data past it, whatever date the model asks for.
|
||||
"""
|
||||
|
||||
from typing import Annotated
|
||||
|
||||
from langchain_core.tools import tool
|
||||
from langgraph.prebuilt import InjectedState
|
||||
|
||||
from tradingagents.dataflows.date_window import as_of, as_of_window
|
||||
from tradingagents.dataflows.router import route_to_vendor
|
||||
from tradingagents.dataflows.vendors.yahoo.snapshot import build_verified_market_snapshot
|
||||
|
||||
|
||||
@tool
|
||||
def get_stock_data(
|
||||
symbol: Annotated[str, "ticker symbol of the company"],
|
||||
start_date: Annotated[str, "Start date in yyyy-mm-dd format"],
|
||||
end_date: Annotated[str, "End date in yyyy-mm-dd format"],
|
||||
trade_date: Annotated[str, InjectedState("trade_date")] = "",
|
||||
) -> str:
|
||||
"""
|
||||
Retrieve stock price data (OHLCV) for a given ticker symbol.
|
||||
Uses the configured core_stock_apis vendor.
|
||||
Args:
|
||||
symbol (str): Ticker symbol of the company, e.g. AAPL, TSM
|
||||
start_date (str): Start date in yyyy-mm-dd format
|
||||
end_date (str): End date in yyyy-mm-dd format
|
||||
Returns:
|
||||
str: A formatted dataframe containing the stock price data for the specified ticker symbol in the specified date range.
|
||||
"""
|
||||
start_date, end_date = as_of_window(start_date, end_date, trade_date)
|
||||
return route_to_vendor("get_stock_data", symbol, start_date, end_date)
|
||||
|
||||
|
||||
@tool
|
||||
def get_indicators(
|
||||
symbol: Annotated[str, "ticker symbol of the company"],
|
||||
indicator: Annotated[str, "technical indicator to get the analysis and report of"],
|
||||
curr_date: Annotated[str, "The current trading date you are trading on, YYYY-mm-dd"],
|
||||
look_back_days: Annotated[int, "how many days to look back"] = 30,
|
||||
trade_date: Annotated[str, InjectedState("trade_date")] = "",
|
||||
) -> str:
|
||||
"""
|
||||
Retrieve a single technical indicator for a given ticker symbol.
|
||||
Uses the configured technical_indicators vendor.
|
||||
Args:
|
||||
symbol (str): Ticker symbol of the company, e.g. AAPL, TSM
|
||||
indicator (str): A single technical indicator name, e.g. 'rsi', 'macd'. Call this tool once per indicator.
|
||||
curr_date (str): The current trading date you are trading on, YYYY-mm-dd
|
||||
look_back_days (int): How many days to look back, default is 30
|
||||
Returns:
|
||||
str: A formatted dataframe containing the technical indicators for the specified ticker symbol and indicator.
|
||||
"""
|
||||
# LLMs sometimes pass multiple indicators as a comma-separated string;
|
||||
# split and process each individually.
|
||||
curr_date = as_of(curr_date, trade_date)
|
||||
indicators = [i.strip().lower() for i in indicator.split(",") if i.strip()]
|
||||
results = []
|
||||
for ind in indicators:
|
||||
try:
|
||||
results.append(route_to_vendor("get_indicators", symbol, ind, curr_date, look_back_days))
|
||||
except ValueError as e:
|
||||
results.append(str(e))
|
||||
return "\n\n".join(results)
|
||||
|
||||
|
||||
@tool
|
||||
def get_verified_market_snapshot(
|
||||
symbol: Annotated[str, "ticker symbol of the company"],
|
||||
curr_date: Annotated[str, "the current trading date, YYYY-mm-dd"],
|
||||
look_back_days: Annotated[
|
||||
int, "number of recent trading rows to include for sanity-checking"
|
||||
] = 30,
|
||||
trade_date: Annotated[str, InjectedState("trade_date")] = "",
|
||||
) -> str:
|
||||
"""Deterministic verification snapshot for exact market-data claims.
|
||||
|
||||
Returns the latest OHLCV row on or before curr_date, common technical
|
||||
indicators, and recent closes. Call this before making exact claims about
|
||||
price levels, Bollinger bands, RSI, MACD, moving averages, support /
|
||||
resistance, or historical comparisons, and treat it as the source of truth.
|
||||
"""
|
||||
return build_verified_market_snapshot(symbol, as_of(curr_date, trade_date), look_back_days)
|
||||
|
||||
|
||||
@tool
|
||||
def get_fundamentals(
|
||||
ticker: Annotated[str, "ticker symbol"],
|
||||
curr_date: Annotated[str, "current date you are trading at, yyyy-mm-dd"],
|
||||
trade_date: Annotated[str, InjectedState("trade_date")] = "",
|
||||
) -> str:
|
||||
"""
|
||||
Retrieve comprehensive fundamental data for a given ticker symbol.
|
||||
Uses the configured fundamental_data vendor.
|
||||
Args:
|
||||
ticker (str): Ticker symbol of the company
|
||||
curr_date (str): Current date you are trading at, yyyy-mm-dd
|
||||
Returns:
|
||||
str: A formatted report containing comprehensive fundamental data
|
||||
"""
|
||||
return route_to_vendor("get_fundamentals", ticker, as_of(curr_date, trade_date))
|
||||
|
||||
|
||||
@tool
|
||||
def get_balance_sheet(
|
||||
ticker: Annotated[str, "ticker symbol"],
|
||||
freq: Annotated[str, "reporting frequency: annual/quarterly"] = "quarterly",
|
||||
curr_date: Annotated[str, "current date you are trading at, yyyy-mm-dd"] = None,
|
||||
trade_date: Annotated[str, InjectedState("trade_date")] = "",
|
||||
) -> str:
|
||||
"""
|
||||
Retrieve balance sheet data for a given ticker symbol.
|
||||
Uses the configured fundamental_data vendor.
|
||||
Args:
|
||||
ticker (str): Ticker symbol of the company
|
||||
freq (str): Reporting frequency: annual/quarterly (default quarterly)
|
||||
curr_date (str): Current date you are trading at, yyyy-mm-dd
|
||||
Returns:
|
||||
str: A formatted report containing balance sheet data
|
||||
"""
|
||||
return route_to_vendor("get_balance_sheet", ticker, freq, as_of(curr_date, trade_date))
|
||||
|
||||
|
||||
@tool
|
||||
def get_cashflow(
|
||||
ticker: Annotated[str, "ticker symbol"],
|
||||
freq: Annotated[str, "reporting frequency: annual/quarterly"] = "quarterly",
|
||||
curr_date: Annotated[str, "current date you are trading at, yyyy-mm-dd"] = None,
|
||||
trade_date: Annotated[str, InjectedState("trade_date")] = "",
|
||||
) -> str:
|
||||
"""
|
||||
Retrieve cash flow statement data for a given ticker symbol.
|
||||
Uses the configured fundamental_data vendor.
|
||||
Args:
|
||||
ticker (str): Ticker symbol of the company
|
||||
freq (str): Reporting frequency: annual/quarterly (default quarterly)
|
||||
curr_date (str): Current date you are trading at, yyyy-mm-dd
|
||||
Returns:
|
||||
str: A formatted report containing cash flow statement data
|
||||
"""
|
||||
return route_to_vendor("get_cashflow", ticker, freq, as_of(curr_date, trade_date))
|
||||
|
||||
|
||||
@tool
|
||||
def get_income_statement(
|
||||
ticker: Annotated[str, "ticker symbol"],
|
||||
freq: Annotated[str, "reporting frequency: annual/quarterly"] = "quarterly",
|
||||
curr_date: Annotated[str, "current date you are trading at, yyyy-mm-dd"] = None,
|
||||
trade_date: Annotated[str, InjectedState("trade_date")] = "",
|
||||
) -> str:
|
||||
"""
|
||||
Retrieve income statement data for a given ticker symbol.
|
||||
Uses the configured fundamental_data vendor.
|
||||
Args:
|
||||
ticker (str): Ticker symbol of the company
|
||||
freq (str): Reporting frequency: annual/quarterly (default quarterly)
|
||||
curr_date (str): Current date you are trading at, yyyy-mm-dd
|
||||
Returns:
|
||||
str: A formatted report containing income statement data
|
||||
"""
|
||||
return route_to_vendor("get_income_statement", ticker, freq, as_of(curr_date, trade_date))
|
||||
|
||||
|
||||
@tool
|
||||
def get_news(
|
||||
ticker: Annotated[str, "Ticker symbol"],
|
||||
start_date: Annotated[str, "Start date in yyyy-mm-dd format"],
|
||||
end_date: Annotated[str, "End date in yyyy-mm-dd format"],
|
||||
trade_date: Annotated[str, InjectedState("trade_date")] = "",
|
||||
) -> str:
|
||||
"""
|
||||
Retrieve news data for a given ticker symbol.
|
||||
Uses the configured news_data vendor.
|
||||
Args:
|
||||
ticker (str): Ticker symbol
|
||||
start_date (str): Start date in yyyy-mm-dd format
|
||||
end_date (str): End date in yyyy-mm-dd format
|
||||
Returns:
|
||||
str: A formatted string containing news data
|
||||
"""
|
||||
start_date, end_date = as_of_window(start_date, end_date, trade_date)
|
||||
return route_to_vendor("get_news", ticker, start_date, end_date)
|
||||
|
||||
|
||||
@tool
|
||||
def get_global_news(
|
||||
curr_date: Annotated[str, "Current date in yyyy-mm-dd format"],
|
||||
look_back_days: Annotated[int | None, "Days to look back; omit to use the configured default"] = None,
|
||||
limit: Annotated[int | None, "Max articles to return; omit to use the configured default"] = None,
|
||||
trade_date: Annotated[str, InjectedState("trade_date")] = "",
|
||||
) -> str:
|
||||
"""
|
||||
Retrieve global news data.
|
||||
Uses the configured news_data vendor. Defaults for look_back_days and
|
||||
limit come from DEFAULT_CONFIG (global_news_lookback_days,
|
||||
global_news_article_limit); pass explicit values to override.
|
||||
|
||||
Args:
|
||||
curr_date (str): Current date in yyyy-mm-dd format
|
||||
look_back_days (int): Number of days to look back; omit to inherit config
|
||||
limit (int): Maximum number of articles to return; omit to inherit config
|
||||
|
||||
Returns:
|
||||
str: A formatted string containing global news data
|
||||
"""
|
||||
return route_to_vendor("get_global_news", as_of(curr_date, trade_date), look_back_days, limit)
|
||||
|
||||
|
||||
@tool
|
||||
def get_insider_transactions(
|
||||
ticker: Annotated[str, "ticker symbol"],
|
||||
trade_date: Annotated[str, InjectedState("trade_date")] = "",
|
||||
) -> str:
|
||||
"""
|
||||
Retrieve insider transaction information about a company.
|
||||
Uses the configured news_data vendor.
|
||||
Args:
|
||||
ticker (str): Ticker symbol of the company
|
||||
Returns:
|
||||
str: A report of insider transaction data
|
||||
"""
|
||||
return route_to_vendor("get_insider_transactions", ticker, trade_date or None)
|
||||
|
||||
|
||||
@tool
|
||||
def get_macro_indicators(
|
||||
indicator: Annotated[
|
||||
str,
|
||||
"Macro indicator: a friendly alias such as 'cpi', 'core_pce', "
|
||||
"'unemployment', 'fed_funds_rate', '10y_treasury', 'yield_curve', "
|
||||
"'real_gdp', 'vix', or a raw FRED series ID such as 'CPIAUCSL'.",
|
||||
],
|
||||
curr_date: Annotated[str, "Current date in yyyy-mm-dd format; the end of the window"],
|
||||
look_back_days: Annotated[
|
||||
int | None, "Trailing window length in days; omit for a 1-year window"
|
||||
] = None,
|
||||
trade_date: Annotated[str, InjectedState("trade_date")] = "",
|
||||
) -> str:
|
||||
"""
|
||||
Retrieve a macroeconomic indicator time series from FRED (Federal Reserve
|
||||
Economic Data): policy rates, Treasury yields, inflation, labor, and growth.
|
||||
Returns the series title, units, frequency, the latest value, the change
|
||||
over the window, and a recent observation table. Uses the configured
|
||||
macro_data vendor.
|
||||
|
||||
Args:
|
||||
indicator (str): Friendly alias or raw FRED series ID
|
||||
curr_date (str): Current date in yyyy-mm-dd format
|
||||
look_back_days (int): Trailing window length; omit for a 1-year window
|
||||
|
||||
Returns:
|
||||
str: A formatted markdown report of the macro series
|
||||
"""
|
||||
return route_to_vendor("get_macro_indicators", indicator, as_of(curr_date, trade_date), look_back_days)
|
||||
|
||||
|
||||
@tool
|
||||
def get_prediction_markets(
|
||||
topic: Annotated[
|
||||
str,
|
||||
"Event topic/keyword, e.g. 'Fed rate cut', 'recession 2026', "
|
||||
"'US election', or a sector/company event.",
|
||||
],
|
||||
limit: Annotated[int | None, "Max markets to return; omit for a default of 6"] = None,
|
||||
trade_date: Annotated[str, InjectedState("trade_date")] = "",
|
||||
) -> str:
|
||||
"""
|
||||
Retrieve live, market-implied probabilities for forward-looking events from
|
||||
prediction markets (Polymarket): Fed decisions, recession, elections,
|
||||
geopolitics, crypto. Returns the most-traded open markets matching the
|
||||
topic, each with its implied probability, traded volume, resolution date,
|
||||
and recent move. Uses the configured prediction_markets vendor.
|
||||
|
||||
Args:
|
||||
topic (str): Event keyword(s) to search
|
||||
limit (int): Max markets to return; omit for a default of 6
|
||||
|
||||
Returns:
|
||||
str: A formatted markdown report of matching prediction markets
|
||||
"""
|
||||
return route_to_vendor("get_prediction_markets", topic, limit, trade_date or None)
|
||||
@@ -6,13 +6,13 @@ import functools
|
||||
|
||||
from langchain_core.messages import AIMessage
|
||||
|
||||
from tradingagents.agents.schemas import TraderProposal, render_trader_proposal
|
||||
from tradingagents.agents.utils.agent_utils import (
|
||||
from tradingagents.agents.context import (
|
||||
get_instrument_context_from_state,
|
||||
get_language_instruction,
|
||||
get_portfolio_context_from_state,
|
||||
)
|
||||
from tradingagents.agents.utils.structured import (
|
||||
from tradingagents.agents.schemas import TraderProposal, render_trader_proposal
|
||||
from tradingagents.agents.structured import (
|
||||
NO_EXTERNAL_TOOLS,
|
||||
bind_structured,
|
||||
invoke_structured_or_freetext,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user