Compare commits

..
123 Commits
Author SHA1 Message Date
Tauric-Research 9fa1196fff announce Trading-R1 official release 2026-11-04 02:13:55 -08:00
Yijia Xiao c4544913a1 Merge pull request #1613 from TauricResearch/v0.7.1
TradingAgents v0.7.1 release
2026-10-27 01:38:40 -07:00
Yijia-Xiao 3e44faafa0 release: 0.7.1 2026-10-27 08:01:34 +00:00
Yijia-Xiao bf7f4b55a3 fix(tools): accept only the statement frequencies the vendors serve (#1593)
- freq is annual or quarterly in the tool schema; any other word is sent back to the model instead of being served annual figures under that word
2026-10-27 08:01:21 +00:00
Yijia-Xiao d46c052278 test: fix tests that failed on Windows and macOS (#1506, #1485, #1541)
- the module-help subprocess is read as UTF-8 under a cp1252 locale
- the yfinance cache check names the suite's directory, which may sit under the home on Windows
- POSIX file modes and shell upgrade commands are checked only off Windows
- file locking names errno.EDEADLK, which macOS also defines
2026-10-27 08:01:08 +00:00
Yijia-Xiao ec4e2c8e5a build(docker): keep every .env file out of the image
- .dockerignore excludes .env files at any depth, so a local .env.enterprise with Azure keys is not copied into image layers
- the README says to put Azure keys in .env for Docker
2026-10-27 08:00:55 +00:00
Yijia-Xiao a334a1f878 fix(cli): check a ticker with the data layer's own rule (#1604)
- the prompt and --ticker accept what the run accepts: XAUUSD+ resolves to GC=F, while ".." and full-width letters are refused at entry instead of after the graph is built
2026-10-27 08:00:43 +00:00
Yijia-Xiao ae0424745e fix(llm): read a dated Claude snapshot's version without its date (#1585)
- claude-sonnet-4-20250514 no longer receives the effort setting it rejects, and claude-opus-4-5-20251101 now receives it
2026-10-27 08:00:30 +00:00
Yijia-Xiao 347974a000 fix(llm): pass the output-token cap and a configured endpoint to Azure OpenAI (#1584, #1600)
- max_tokens reaches the Azure deployment
- a tier's backend_url is used as the Azure endpoint, else AZURE_OPENAI_ENDPOINT
2026-10-27 08:00:17 +00:00
Yijia-Xiao b78f136ba3 fix(polymarket): keep a long shot's odds from printing as 0% or 100% (#1598)
- within 1% of 0 or 100, the distance keeps two significant digits: 0.05%, 99.95%
2026-10-27 08:00:04 +00:00
Yijia-Xiao caf6792bba fix(memory): take the most recent lessons by decision date (#1603)
- get_past_context orders a ticker's settled decisions by their date, so a backfill of older dates no longer pushes out the latest lesson
- rotation drops the oldest-dated settled entries, not the first written
2026-10-27 07:59:51 +00:00
Yijia-Xiao ee06dcb961 fix(tools): send a date window that ends before it starts back to the model (#1595)
- as_of_window refuses a start after the end, as it does an unreadable start, instead of passing it to the vendor
2026-10-27 07:59:39 +00:00
Yijia-Xiao 21bc5d8fe7 fix(reporting): remove a previous run's sections when a report is saved to the same folder (#1566)
- write_report_tree deletes the section files and HTML page this run did not write; other files in the folder are kept
2026-10-27 07:59:26 +00:00
Yijia-Xiao 2717033ad8 fix(sec_edgar): serve a statement one row per period (#1517, #1542)
- a row per period with the line items as columns, so each figure sits beside its own date across a filer's whole history
- lines the filer never tagged are named once in the header
2026-10-27 07:59:13 +00:00
Yijia-Xiao 50bf38ee92 fix(sec_edgar): print a figure under one million instead of 0 (#1589)
- a USD figure under one million keeps three significant digits in the statement table
2026-10-27 07:59:01 +00:00
Yijia-Xiao 6c23d7551c fix(yahoo): print prices with their significant digits (#1567)
- the price table and the verified snapshot keep six significant digits and at least two decimals, so a sub-cent close is no longer 0.00 and a currency pair keeps its pips
2026-10-27 07:58:48 +00:00
Yijia-Xiao 3225a3c054 fix(portfolio): refuse a portfolio with a number that is not finite (#1509)
- cash, quantities and average prices reject NaN and infinity when the file loads
2026-10-27 07:58:35 +00:00
Yijia-Xiao 62a06edb38 fix(portfolio): match a holding listed under a broker alias to the analyzed instrument (#1556)
- a holding matches when its symbol resolves to the one the run prices (BTCUSDT -> BTC-USD, 700.HK -> 0700.HK); holdings keep the spelling they were given
- every matching holding is shown, labelled with its listed spelling
2026-10-27 07:58:23 +00:00
Yijia-Xiao 28d32653d3 fix(backtest): give each sweep started without a run_id its own run (#1549)
- the stamped run directory is claimed atomically; a second sweep in the same second takes the next suffix instead of resuming the first
2026-10-27 07:58:10 +00:00
Yijia-Xiao 1c0e3e37fc fix(backtest): report the settlement failures a sweep's last pass records (#1557)
- run_backtest adds settle_pending's failed entries to settlement_failures, each reason prefixed with its date
2026-10-27 07:57:57 +00:00
Yijia-Xiao eb4a486092 fix(memory): settle decisions on final closes, across long market closures (#1548, #1539)
- the bar of a session still trading, by its market's date, is not scored
- a holding window that has passed without the stock or its benchmark trading through is fetched again through today
- a window that cannot have traded yet asks for no prices
2026-10-27 07:57:45 +00:00
Yijia-Xiao a5b0f217e3 fix(tools): hand vendors the model's dates as YYYY-MM-DD (#1488)
- as_of and as_of_window return canonical dates, so an unpadded date such as 2024-7-5 no longer compares as later than a filing dated 2024-07-24
- create_run_state validates the run date, as propagate does
2026-10-27 07:57:32 +00:00
Yijia-Xiao 2fe04cc771 chore: start 0.7.1 development (0.7.1.dev0) 2026-10-27 07:57:19 +00:00
Tauric-Research e8f5503e9b Merge pull request #1536 from TauricResearch/v0.7.0
TradingAgents v0.7.0 release
2026-10-16 16:38:41 -05:00
Yijia-Xiao f802271fb3 release: 0.7.0 2026-10-16 21:13:16 +00:00
Yijia-Xiao bc55fe3ed7 docs: ChatGPT plan sign-in and the start-up update check (#1475)
- README and .env.example cover the chatgpt provider, `tradingagents login chatgpt` (also in Docker) and logout
- README and .env.example name TRADINGAGENTS_NO_UPDATE_CHECK
2026-10-16 21:13:04 +00:00
Yijia-Xiao f5e3eae3a8 fix(memory): score a decision from the first close after its date (#1518)
- settlement enters at the first session after the decision date, so news published after that day's close is not scored against the same day's close
2026-10-16 21:12:51 +00:00
Yijia-Xiao 7142746bde fix(cli): keep a tier's configured thinking setting when the main provider has none (#1440)
- the run config takes reasoning effort, thinking level and Claude effort from the selections only when one was chosen
2026-10-16 21:12:39 +00:00
Yijia-Xiao 36479ae1fa feat(llm): chatgpt provider runs on the signed-in ChatGPT plan (#1475)
- ChatGPTPlanChatOpenAI streams unstored Responses, sends system instructions as developer messages, drops refused settings with a warning, and sends no API organization or project
- the CLI offers it under "Subscription" after Anthropic, checks the sign-in before a run (signing in or stopping with the login command), and lists the plan's models
- reasoning effort applies to chatgpt as to openai; remembered plan models are offered again
2026-10-16 21:12:26 +00:00
Yijia-Xiao 69042d6d33 feat(llm): sign in with a ChatGPT plan (#1475)
- chatgpt_auth signs in through OpenAI's flow for open-source apps (PKCE, loopback or pasted redirect, verified ID token, plan scope) and keeps the sign-in in ~/.tradingagents/chatgpt-auth.json, readable only by its owner
- access tokens renew under a lock shared across threads and processes, from the refresh token on disk
- `tradingagents login chatgpt` and `tradingagents logout chatgpt`; logout revokes the sign-in at OpenAI
2026-10-16 21:12:14 +00:00
Yijia-Xiao 071a6cea2a refactor(llm): let a provider sign in with its own credential at a pinned endpoint
- a provider entry can supply a credential, a token callable per request, and pin its base URL
- such a provider never sends an API key, and refuses another backend_url or an explicit api_key
2026-10-16 21:12:05 +00:00
Yijia-Xiao c3cdaeb4eb feat(cli): tell people at a terminal about a newer release and Tauric's notices
- once a day a background thread records the latest GitHub release and the notices for each version; the welcome screen shows them from that cache, so no run waits on the network
- the release notice names the upgrade command for how TradingAgents was installed
- TRADINGAGENTS_NO_UPDATE_CHECK=1 turns the check off; unattended and CI runs never make it
- notices are read from a new `notices` key, so earlier versions keep reading `announcements`
2026-10-16 21:11:55 +00:00
Yijia-Xiao c9be8b6047 ci: attach the source archive and wheel to each GitHub release
- on a published release, or by hand for an earlier tag, build both from the tag, install the wheel in a clean environment, and upload them to the release
2026-10-16 21:11:45 +00:00
Yijia-Xiao 609c8e80a1 chore: start 0.7.0 development (0.7.0.dev0) 2026-10-16 21:11:35 +00:00
Tauric-Research 1394a3f72a Merge pull request #1478 from TauricResearch/v0.6.0
TradingAgents v0.6.0 release
2026-10-03 16:30:07 -05:00
Yijia-Xiao ff0d0b1b4d release: 0.6.0 2026-10-03 21:27:43 +00:00
Yijia-Xiao dca93d5290 docs: show the Tauric Research logo from the SVG the report uses 2026-10-03 21:27:43 +00:00
Yijia-Xiao f72382414c fix(tools): send a start date that is not a date back to the model (#1476)
- get_news and get_stock_data answer an unreadable start_date with the form to use, instead of passing it to a vendor
2026-10-03 21:27:43 +00:00
Yijia-Xiao b3ca569c4c feat(fred): name the euro-area macro series (#1465)
- get_macro_indicators accepts ecb_deposit_rate, ecb_main_refi_rate, euro_hicp, euro_core_hicp, euro_real_gdp, germany_10y, france_10y and eur_usd
2026-10-03 21:27:43 +00:00
Yijia-Xiao c925f60328 feat(sentiment): search crypto communities on Reddit for a crypto ticker (#1461)
- a crypto pair is searched in r/CryptoCurrency and r/CryptoMarkets, plus r/Bitcoin, r/ethereum or r/solana for those coins, still in one request
- the Sentiment Analyst's prompt names the subreddits actually searched
2026-10-03 21:27:43 +00:00
Yijia-Xiao df630b9aea fix(rating): read a rating another party gave as evidence, not as the decision (#1466)
- a decision that opens with its rating line, plain or as the list item the prompt asks for, is read from that line
- only words naming the decision itself ("final", "our", "overall") may qualify its rating line; "Consensus rating: Buy" or "Trader's rating: Buy" is another party's
- otherwise the decision's own rating lines, or failing those all rating labels, must agree; ratings that differ need review
2026-10-03 21:27:43 +00:00
Yijia-Xiao 442907897e fix(yahoo): read a symbol's news from Yahoo search when its quote feed is empty (#1467, #1469)
- an empty quote feed falls back to the search articles tagged with the symbol
- when search has no article tagged with the symbol, or neither source answers, Yahoo news is unavailable, so a configured next vendor serves the call
- articles from search never make an empty window read as no news
2026-10-03 21:27:43 +00:00
Yijia-Xiao 11dab3b0fe fix(memory): settle each decision once, and keep each outcome as soon as it is known
- a settlement pass holds the log's settlement lock, so runs sharing a log never pay for the same reflection twice; only outcomes actually written count as settled, and a run's Memory Log step does not wait for another run's pass
- each outcome is written when its reflection is done, so an interrupted pass keeps what it finished
- any failure to price a decision is reported as a failed settlement, not taken for a window that has yet to trade
2026-10-03 21:27:43 +00:00
Yijia-Xiao 460b82e20d fix(reports): name the sentiment analyst in the report header as users select it
- the header lists "sentiment", the name the CLI and flags use, where it printed the internal key "social"
2026-10-03 21:27:43 +00:00
Yijia-Xiao 56a98d9df7 feat(reports): save the report as one HTML page as well (#1419)
- a saved report also includes complete_report.html: the report as one self-contained page with its sections listed beside the text, readable in a browser, on a phone and in print
- answering the save question at the prompt also asks about the page and offers to open it in a local browser window; --no-html and save_reports(..., html=False) skip it
- the Tauric Research logo leads the header at the top left, and a line at the foot credits TradingAgents and Tauric Research
- the page loads nothing and runs nothing (inline styles, a content-security policy); report text is rendered without raw HTML or images
- markdown-it-py is declared as a dependency
2026-10-03 21:27:43 +00:00
Yijia-Xiao d53b076b7a feat(reports): name the rating in the report header
- the header lists the run's rating, REVIEW when the decision has none
2026-10-03 21:27:43 +00:00
Yijia-Xiao cc39a35c42 feat(llm): let each model tier run on its own provider (#1440)
- quick_think_provider / deep_think_provider and their backend URLs (with TRADINGAGENTS_* variables) choose a tier's provider; unset, a tier uses llm_provider and backend_url
- a tier on another provider gets that provider's own settings and endpoint, and the run settings and report header name each tier's provider
- the CLI checks each tier provider's model variable and key before the run
2026-10-03 21:27:43 +00:00
Yijia-Xiao f65fcabb60 feat(graph): settle past decisions alongside the analysts (#1428)
- a Memory Log step runs beside the analysts, settles every ticker's due decisions and loads the lessons known by the trade date for the Portfolio Manager; the run no longer settles before it starts
- a settlement failure is logged and noted in the report's header instead of ending the run
- the checkpoint signature records the new layout
2026-10-03 21:27:43 +00:00
Yijia-Xiao 5d8de36f6d feat(memory): settle the pending decisions of every ticker on request (#1445)
- TradingAgentsGraph.settle_all_pending() settles each ticker with a due decision; settle_pending and it return the decisions settled and those that failed
2026-10-03 21:27:43 +00:00
Yijia-Xiao 97b79e08c3 fix(alpha_vantage): keep the API key out of every error an Alpha Vantage answer raises
- rate-limit and invalid-key notices are scrubbed of the key as the rejection message is
2026-10-03 21:27:43 +00:00
Yijia-Xiao b838e257ee fix(sentiment): send Jev requests to the endpoint TYPESAFE_BASE_URL names (#1416)
- post screening reads TypeSafe's own TYPESAFE_BASE_URL and appends /v1/systemone, as the TypeSafe SDKs do, so Jev can be reached through OpenRouter; the key still turns screening on
2026-10-03 21:27:43 +00:00
Yijia-Xiao 9df071b25b fix(google): give a Gemini call the same 600-second timeout as the other providers (#1417)
- GoogleClient sets timeout=600 unless one is passed, as the OpenAI and Anthropic SDKs do by default, so a stalled call no longer hangs the run
2026-10-03 21:27:43 +00:00
Yijia-Xiao 810b4cc48d fix(yahoo): print each fundamentals money figure with the currency it is in (#1456)
- price levels carry the quote currency (GBp for London), market cap and per-share figures its main unit (GBP), and income figures the reporting currency (TWD for TSMC's ADR)
2026-10-03 21:27:43 +00:00
Yijia-Xiao 5ca37b5088 fix(alpha_vantage): report a request Alpha Vantage rejects as unavailable (#1442)
- an {"Error Message": ...} answer raises VendorUnavailableError, with the key scrubbed, instead of being served as data or as "no data"
2026-10-03 21:27:43 +00:00
Yijia-Xiao 8af6eefb18 docs: say in requirements.txt where the dependencies are declared 2026-10-03 21:27:43 +00:00
Yijia-Xiao 9dceea6e9d fix(yahoo): read a news article whose fields are null (#1458)
- each article field falls back to its default on a null as well as on a missing key, so one malformed article no longer loses a ticker's news
2026-10-03 21:27:43 +00:00
Yijia-Xiao 99c79e6fb1 chore: start 0.6.0 development (0.6.0.dev0) 2026-10-03 21:27:43 +00:00
Tauric-Research 8b22d43d01 Merge pull request docs: TradingAgents v0.5.2 release #1450
docs: TradingAgents v0.5.2 release
2026-09-29 01:15:09 -05:00
Yijia-Xiao 4b7d39856b docs: TradingAgents v0.5.2 release 2026-09-29 06:10:24 +00:00
Yijia Xiao 5eb50854da TradingAgents v0.5.2 release 2026-09-28 22:59:16 -07:00
Yijia-Xiao 23536f545a release: 0.5.2 2026-09-29 05:57:18 +00:00
Yijia-Xiao 7d38885e81 build: require Python 3.11 and pandas 3
- requires-python 3.11 and pandas 3.0.6; the CI matrix runs Python 3.11 to 3.14 and ruff targets 3.11
- datetime.UTC in place of timezone.utc, and the rating, action, band, analyst and asset enums are StrEnum, which formats a member as its value
2026-09-29 05:57:18 +00:00
Yijia-Xiao da6b35f22f fix(dataflows): withhold insider trades with no filing date from a past run
- Yahoo and Alpha Vantage date a trade by when it happened, not by its Form 4 filing, so a run dated in the past is told they are withheld instead of served trades that may not yet have been public
2026-09-29 05:57:18 +00:00
Yijia-Xiao 1cf16bd0e4 fix(sec_edgar): serve a quarterly figure filed only year to date, naming its span
- each row takes the quarter where filed, else its 6- or 9-month figure to date, in a column labelled with the span; a filer that tags 10-Q cash flows only year to date no longer stops at each first quarter
2026-09-29 05:57:18 +00:00
Yijia-Xiao 2486470495 fix(yahoo): read Yahoo's answer that a window has no prices as no data
- a chart with no prices, or Yahoo saying the data does not exist, is an empty answer; yfinance's same error for an error status or a service failure, and a missing time zone, stay unavailable
2026-09-29 05:57:18 +00:00
Yijia-Xiao bd9693f8ba docs: write the provider key notes without em-dashes 2026-09-29 05:57:18 +00:00
Yijia-Xiao b21f8ce1c9 refactor(cli): write the saved selections through the shared file writer
- save_last_run uses files.replace_file, with a temp file of its own, in place of a fixed .tmp name
2026-09-29 05:57:18 +00:00
Yijia-Xiao e1a19fd78e refactor(cli): save a run's reports through the graph, as a script does
- TradingAgentsGraph.default_report_path names the results_dir/reports/TICKER_stamp folder; save_reports and the CLI both use it
2026-09-29 05:57:18 +00:00
Yijia-Xiao ad39133569 refactor(yahoo): keep what every Yahoo request shares in yahoo.common
- yf_retry, raise_for_empty and YAHOO_HOST move from yahoo.ohlcv, which the news, fundamentals and market modules imported them from
2026-09-29 05:57:18 +00:00
Yijia-Xiao d7ac9461da fix(dataflows): serve a past run financial statements only with a known filing date
- Yahoo and Alpha Vantage statements, dated by the period they cover, are withheld from a run dated in the past, with a notice saying why
- statements come from SEC EDGAR by default (fundamental_data "sec_edgar,yfinance"), so a past run reads US filers as filed
2026-09-29 05:57:18 +00:00
Yijia-Xiao 1d92269d35 fix(rating): read a decision's rating only from its label
- a decision without a rating label is REVIEW; a lone rating word in its prose may be one it argues against ("not a Sell"), so it is no longer read as the call
2026-09-29 05:57:18 +00:00
Yijia-Xiao 1bf67e35b6 fix(yahoo): report the failed requests yfinance would answer as empty
- yfinance raises its failures instead of answering them with an empty result, so a statement request that timed out is unavailable, not "no data"
- Yahoo answering that it has no such symbol (HTTP 404) stays an answer: no data
2026-09-29 05:57:18 +00:00
Yijia-Xiao 0f05689334 docs: show a current Claude model ID in the Bedrock example 2026-09-29 05:57:18 +00:00
Yijia-Xiao 76a93480dd build: run the Docker image on Python 3.13, and set up with it in the README 2026-09-29 05:57:18 +00:00
Yijia-Xiao 23bed8dace ci: test Python 3.14 and run the current checkout and setup-python actions
- the test matrix adds Python 3.14
- actions/checkout and actions/setup-python v7; the lint job installs ruff 0.16
2026-09-29 05:57:18 +00:00
Yijia-Xiao f65eab7b80 build(deps): require the current yfinance, LangChain and LangGraph releases
- yfinance 1.7.0, langchain-core 1.6.5, langchain-openai 1.6.6, langchain-anthropic 1.7.4, langchain-google-genai 4.4.0, langgraph 1.2.12, langgraph-checkpoint-sqlite 3.1.1
- langchain-aws 1.7.9 for the bedrock extra, and ruff 0.16 for development
2026-09-29 05:57:18 +00:00
Yijia-Xiao 660966d168 refactor(dataflows): decide in one place whether a run is dated in the past
- date_window.is_historical replaces the four copies of the rule in the profile guard, Polymarket, the instrument context and the memory cutoff, which read the clock on its own
2026-09-29 05:57:18 +00:00
Yijia-Xiao 06bf82569d docs: drop comments that describe code no longer there
- agents.context no longer holds a message reset between analysts
- main.py no longer ends on a reflection step it does not take
2026-09-29 05:57:18 +00:00
Yijia-Xiao 0d2cfa32e0 docs(changelog): complete the 0.5.1 import moves (#1437)
- get_scrubbed and vendor_reachable moved to dataflows.net, and symbol_utils.is_yahoo_safe was removed
2026-09-29 05:57:18 +00:00
Yijia-Xiao e44cbbc8eb test: run the live integration tests only when asked for
- pytest deselects integration tests unless -m integration is given, so a key in .env no longer makes a plain run call a paid provider
2026-09-29 05:57:18 +00:00
Yijia-Xiao 4bb9272c8f test: keep the suite off the network and out of the home directory, yfinance included
- the network guard also refuses DNS lookups and curl_cffi requests, the HTTP client yfinance uses, which never touches Python's sockets
- results, the data cache, the memory log and yfinance's time-zone cache live in a directory of the suite's own
2026-09-29 05:57:18 +00:00
Yijia-Xiao fa87947c33 test: stop reloading modules, so the suite passes in any order
- default_config.build_default_config gives the defaults with the environment as it is now; the overlay tests call it instead of reloading the module, whose reloaded DEFAULT_CONFIG leaked their settings into later tests
- the Ollama and API-key tests import the modules they check, which read the environment when called; two tests that only read os.environ are dropped
2026-09-29 05:57:18 +00:00
Yijia-Xiao 9a568d19b1 fix(graph): start a checkpointed run afresh when the settings that shape it change
- the checkpoint signature folds in the run config (provider, models, endpoint, language, vendors, limits), leaving out only file locations, the checkpoint switch and the retry count, so a resume no longer carries reports that other settings produced
2026-09-29 05:57:18 +00:00
Yijia-Xiao b99b843415 fix(agents): give a past run the company's current name only, as an identifier
- the vendor profile describes the company today, so a run dated earlier is given its name marked as the current one and no sector, industry or exchange
2026-09-29 05:57:18 +00:00
Yijia-Xiao 540ea8ca7f fix(agents): keep the labelled rating lines in English in every output language (#1435)
- the language instruction exempts the lines the program reads, the "**Rating**:" line and the transaction proposal, so a decision written in another language keeps a rating that can be read
2026-09-29 05:57:18 +00:00
Yijia-Xiao ca2ebbbdcb fix(graph): ask an analyst for its report once its tool rounds are spent (#1420)
- after max_tool_rounds rounds of tool calls (default 20, TRADINGAGENTS_MAX_TOOL_ROUNDS) the analyst takes one last turn with no tools, its tool calls and results given as text, and that turn ends its graph
- the three tool-using analysts take their turns through analysts.turn.take_turn
- a limit the recursion limit cannot hold is refused when the graph is built
2026-09-29 05:57:18 +00:00
Yijia-Xiao 0d22cad2af fix(yahoo): print the fundamentals given in percent with their unit (#1414)
- Dividend Yield and Debt to Equity carry a % sign, and Debt to Equity its ratio, beside the margins and returns Yahoo gives as fractions
2026-09-29 05:57:18 +00:00
Yijia-Xiao d201105a4d fix(cli): take the backtest's analysts as an analysis does
- backtest --analysts accepts sentiment and is checked against --asset-type before the sweep
- without --analysts, a crypto sweep runs the analysts crypto allows, not fundamentals
2026-09-29 05:57:18 +00:00
Yijia-Xiao e973dd0e25 fix(backtest): run and settle a ticker or date given twice once (#1415)
- run_backtest drops repeated tickers and dates before building the grid
2026-09-29 05:57:18 +00:00
Yijia-Xiao 13cf1e8138 fix(memory): score a decision against its benchmark over the same dates
- the stock's own sessions set the holding window; the benchmark is valued at its last close by entry and by exit, so a coin held over a weekend is compared with SPY over the same span
- bars meet on their calendar day across time zones, and a missing or non-positive close is dropped rather than scored
- an outcome waits until the benchmark has traded through the exit
2026-09-29 05:57:18 +00:00
Yijia-Xiao 42e2d569e0 fix(memory): let one writer at a time change the memory log
- storing a decision and settling outcomes hold a lock across the read, change and write, so runs sharing a log no longer drop each other's entries
- files.locked takes the lock on a .lock file beside the log, across threads and processes
2026-09-29 05:57:18 +00:00
Yijia-Xiao b89909724a fix(agents): ask again for an instrument identity whose lookup failed
- only an answered lookup is cached for the process, so one failed request no longer leaves every later run for that ticker without an identity
2026-09-29 05:57:18 +00:00
Yijia-Xiao 466d33ab3b fix(agents): answer a snapshot with no price rows as no data instead of ending the run
- build_verified_market_snapshot raises NoMarketDataError for an unknown symbol or no row by the date
- get_verified_market_snapshot returns the router's no-data answer, shared as router.no_data_available
2026-09-29 05:57:18 +00:00
Yijia-Xiao ec2ecc79c3 fix(router): report a vendor chain with an unavailable vendor as unavailable, not as no data
- a vendor that throttled or failed the request never said whether it has the symbol, so another vendor's "no data" no longer speaks for the chain
2026-09-29 05:57:18 +00:00
Yijia-Xiao 00924bb203 refactor(dataflows): name the unavailable-vendor error for what it covers
- VendorRateLimitError is VendorUnavailableError: a vendor that throttled or failed the request
2026-09-29 05:57:18 +00:00
Yijia-Xiao a6318b31cc fix(graph): stream a run under its graph's own config
- stream_run, which the CLI uses, scopes the graph's config like propagate() does, so a process-wide config changed elsewhere does not reach its tools
2026-09-29 05:57:17 +00:00
Yijia-Xiao 389ff46507 fix(yahoo): report a Yahoo request that failed as unavailable, not as no data
- yf_retry raises any failed request as unavailable: an unknown symbol comes back empty, so an exception is a failed request whether or not Yahoo's host answers a probe
- fundamentals, statements, insider transactions, the company profile, news and closes no longer turn a failed request into "no data"
2026-09-29 05:57:17 +00:00
Yijia-Xiao c540c00778 docs: show save_reports in the Python example 2026-09-29 05:57:17 +00:00
Yijia-Xiao f4828b84ea feat(backtest): show each cell as it starts, and the run id to continue with
- run_backtest takes a progress(done, total, ticker, date) callback; tradingagents backtest prints [n/total] per cell and ends with the --run-id that continues or settles the sweep
2026-09-29 05:57:17 +00:00
Yijia-Xiao 052a98d6eb fix(agents): serve the run's instrument, whatever symbol the model passes
- the nine ticker-taking tools read company_of_interest from graph state, like trade_date; the model no longer supplies a symbol (it had passed indicator names such as RSI, a real ticker)
- the News Analyst prompt and the tool descriptions no longer ask for a ticker
2026-09-29 05:57:17 +00:00
Yijia-Xiao 9470b92150 fix(cli): write the state log, and name the analysts as users know them
- record_decision writes the run's state log, so CLI runs save full_states_log like propagate() does
- with both round counts from the environment, the CLI no longer says a chosen research depth was overridden
- an unknown --analysts name lists sentiment, not social
2026-09-29 05:57:17 +00:00
Yijia-Xiao 9968bd8dd1 feat(graph): run the analysts at the same time (#1255)
- each analyst is a graph of its own (model and tools on a private message history) that returns only its report; all start together and the research debate waits for every report
- the message-clearing nodes are gone; a checkpoint saved by the sequential layout starts fresh
- TradingAgentsGraph.stream_run streams the analysts' messages for debug mode and the CLI, whose status and timing now track the analysts side by side
2026-09-25 06:35:54 +00:00
Yijia-Xiao fc1ab1db07 fix(dataflows): write cache files whole, through a temp file of their own
- the OHLCV cache and the SEC EDGAR cache go through dataflows.files.replace_file: a reader sees the old file or the new one, and concurrent writers never share a temp file
2026-09-25 06:35:54 +00:00
Yijia-Xiao 0c602846ba feat(cli): run an analysis without questions from flags (#1127, #1133)
- --ticker, --date and --analysts answer their steps, checked as the prompts check them; --save/--no-save and --show/--no-show answer the questions after the run
- with no terminal, the run stops before it starts and names every flag or TRADINGAGENTS_* variable still needed; a missing API key and an announcement no longer wait for input
- README shows an unattended run
2026-09-24 20:42:51 +00:00
Yijia-Xiao a1b3b5bab8 feat(reports): record the analysis date and what produced a run (#752)
- TradingAgentsGraph.run_settings(): version, provider, models, analysts, debate rounds, language and vendors; no endpoints, keys or paths
- complete_report.md opens with the analysis date and those settings; the saved state log carries them as run_settings
2026-09-24 19:38:41 +00:00
Yijia-Xiao d91d1f4cb4 build: keep the package version in tradingagents.__version__
- pyproject reads the version from tradingagents/__init__.py, so a source checkout, an editable install and a wheel report the same one
- the SEC EDGAR User-Agent names tradingagents.__version__
2026-09-24 19:38:41 +00:00
Yijia-Xiao 45391d0962 feat(docker): keep results in a host folder when TRADINGAGENTS_DATA_DIR is set (#865)
- both compose services mount ${TRADINGAGENTS_DATA_DIR:-tradingagents_data}; unset keeps the named volume
- README and .env.example show the setting
2026-09-24 19:38:41 +00:00
Yijia-Xiao cf960d6382 refactor: one name per decision in the state and its log
- the Research Manager's plan and the Portfolio Manager's decision live only in investment_plan and final_trade_decision; the debate states no longer copy them as judge_decision
- the saved state log writes the Trader's plan as trader_investment_plan, its state key
- the report tree, the final display and the live CLI read the decisions from those fields
2026-09-24 19:38:41 +00:00
Yijia-Xiao 1d20780095 chore: remove code nothing reads
- router.VENDOR_LIST, and the state's sender field with the Trader's partial that only set it
2026-09-24 19:38:41 +00:00
Yijia-Xiao 3f6ad5dc12 docs: say which agent writes each state field, and what the debate limits count
- state field descriptions name the Research Manager, the News and Fundamentals Analysts and the Portfolio Manager; comments that only repeat them are gone
- the debate-limit comments count turns per max_debate_rounds and max_risk_discuss_rounds
- date_window's docstring covers all the point-in-time rules it holds
2026-09-24 19:38:41 +00:00
Yijia-Xiao 674f1087d1 refactor: name the data layer's date argument as_of_date
- vendor functions and date_window take as_of_date, the date data is served as of; the model-facing tool arguments are unchanged
- build_instrument_context and resolve_instrument_context take trade_date, which is what they receive
2026-09-24 19:38:41 +00:00
Yijia-Xiao 5ac5786d0d docs: call it the memory log throughout
- docstrings, comments, messages and the README section use "memory log", matching TradingMemoryLog and memory_log_path
- the write, read and settle paths are named for what they do, not by design phase
2026-09-24 19:38:41 +00:00
Yijia-Xiao c50420fc5c refactor: gather the memory log, settlement and reflection in tradingagents/memory
- memory/log.py holds TradingMemoryLog, still imported from tradingagents.memory
- graph/settlement.py and graph/reflection.py move to memory/; Reflector leaves tradingagents.graph's exports
2026-09-24 19:38:41 +00:00
Yijia-Xiao b690dc7988 fix(rating): read a free-text rating from the decision's own rating line (#1383)
- the first line opening with a rating label is the call, not a rating the text quotes later ("Consensus rating: Buy")
- "rating" must start a word, so "Operating margin: Sell-side" is not a label
2026-09-24 18:45:44 +00:00
Yijia-Xiao a94a411b0e fix(agents): carry the Portfolio Manager's rating through the run (#1383)
- the typed rating is the state's final_rating; propagate returns it, and the memory log tag, the state log and the CLI review check read it
- the decision text is parsed only when the Portfolio Manager answered in free text
- TradingAgentsGraph.process_signal is removed
2026-09-24 18:45:44 +00:00
Yijia-Xiao 05878c96a8 test(net): pin that get_scrubbed keeps the vendor key out of errors (#1398)
- the message and args are masked; no request, response or chained original travels with the error; a passthrough status is returned
2026-09-24 18:45:44 +00:00
Yijia-Xiao f9d6495dca fix(fred): state the dates a macro change spans (#1397)
- the change line reads "Change from <first> to <last>" instead of "Change over window", so a partial-year move no longer reads as year on year
2026-09-24 18:45:44 +00:00
Yijia-Xiao f4269bf193 test: keep the CLI's saved selections out of the user's home (#1395)
- every test saves and reads CLI selections under its own tmp_path
2026-09-24 18:45:44 +00:00
Yijia-Xiao 47ac1f2d1e feat(config): benchmark Taiwan, Korea, Singapore and the main European exchanges (#1392)
- .TW, .TWO, .KS, .KQ, .SI, .DE, .PA, .AS, .SW and .MI tickers are measured against their regional index instead of SPY
2026-09-24 18:45:44 +00:00
Yijia-Xiao 51066935b8 refactor: name the decision log module tradingagents/memory.py
- TradingMemoryLog imports from tradingagents.memory, matching the class, the memory_log_path key and graph.memory_log
2026-09-24 18:45:44 +00:00
Yijia-Xiao 73e0aa0fa6 chore: start 0.5.2 development (0.5.2.dev0) 2026-09-24 18:45:44 +00:00
Chaoqi 6ac7c6f017 fix(dataflows): report a Yahoo rate limit as a rate limit (#1387) 2026-09-24 11:45:39 -07:00
olivergpt ecd3404213 fix(llm): treat deepseek-flash as a thinking model (#1389) 2026-09-24 11:45:29 -07:00
154 changed files with 8563 additions and 2338 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
.git
.venv
.env
**/.env*
.claude
.idea
.vscode
+16
View File
@@ -25,6 +25,7 @@ NVIDIA_API_KEY=
# TypeSafe Jev: screens StockTwits and Reddit posts for the Sentiment Analyst. Optional.
#TYPESAFE_API_KEY=
#TYPESAFE_DEFAULT_MODEL=jev-latest
#TYPESAFE_BASE_URL=https://openrouter.ai/api # Jev through OpenRouter, with an OpenRouter key above
# Custom OpenAI-compatible endpoint (vLLM, LM Studio, llama.cpp). Local servers need no key.
#OPENAI_COMPATIBLE_API_KEY=
@@ -34,6 +35,9 @@ NVIDIA_API_KEY=
#AWS_DEFAULT_REGION=us-west-2
#AWS_PROFILE=
# ChatGPT Plus or Pro plan: no key; sign in once with `tradingagents login chatgpt`.
#TRADINGAGENTS_LLM_PROVIDER=chatgpt
# Remote Ollama server. Unset uses http://localhost:11434/v1.
#OLLAMA_BASE_URL=http://your-ollama-host:11434/v1
@@ -41,12 +45,24 @@ NVIDIA_API_KEY=
#TRADINGAGENTS_LLM_PROVIDER=openai
#TRADINGAGENTS_DEEP_THINK_LLM=gpt-6-sol
#TRADINGAGENTS_QUICK_THINK_LLM=gpt-6-luna
# A tier on its own provider (set its model above too); its URL only for a local or relay endpoint.
#TRADINGAGENTS_DEEP_THINK_PROVIDER=
#TRADINGAGENTS_QUICK_THINK_PROVIDER=
#TRADINGAGENTS_DEEP_THINK_BACKEND_URL=
#TRADINGAGENTS_QUICK_THINK_BACKEND_URL=
#TRADINGAGENTS_LLM_BACKEND_URL=
#TRADINGAGENTS_OUTPUT_LANGUAGE=English
#TRADINGAGENTS_MAX_DEBATE_ROUNDS=1
#TRADINGAGENTS_MAX_RISK_ROUNDS=1
#TRADINGAGENTS_MAX_TOOL_ROUNDS=20
#TRADINGAGENTS_CHECKPOINT_ENABLED=false
# Turn off the start-up note about a newer release and Tauric Research notices.
#TRADINGAGENTS_NO_UPDATE_CHECK=1
# Docker: a host folder for results, reports and the memory log (unset: the tradingagents_data volume).
#TRADINGAGENTS_DATA_DIR=./data
# Paths and alpha benchmark. Unset uses ~/.tradingagents and the regional index.
#TRADINGAGENTS_RESULTS_DIR=
#TRADINGAGENTS_CACHE_DIR=
+8 -8
View File
@@ -16,7 +16,7 @@ jobs:
strategy:
fail-fast: false
matrix:
python-version: ["3.10", "3.11", "3.12", "3.13"]
python-version: ["3.11", "3.12", "3.13", "3.14"]
# One run away from UTC, so a test that only passes in UTC fails here.
include:
- python-version: "3.12"
@@ -24,8 +24,8 @@ jobs:
env:
TZ: ${{ matrix.tz }}
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: ${{ matrix.python-version }}
- name: Install (with dev extras)
@@ -39,8 +39,8 @@ jobs:
name: clean-install smoke
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: "3.12"
- name: Fresh install (no dev extras) and import
@@ -55,12 +55,12 @@ jobs:
name: ruff (strict, full repo)
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: "3.12"
- name: Install ruff
run: pip install "ruff>=0.15"
run: pip install "ruff>=0.16"
- name: Lint the repository
# The repo is fully clean under the strict select, so we lint everything
# (generated results/ is excluded via pyproject extend-exclude).
+59
View File
@@ -0,0 +1,59 @@
name: Release assets
# Builds the source archive and wheel from the release tag and attaches them to
# the GitHub release, so a version can be installed without cloning:
# pip install https://github.com/TauricResearch/TradingAgents/releases/download/<tag>/<wheel>
# Run it by hand with a tag to attach builds to an earlier release.
on:
release:
types: [published]
workflow_dispatch:
inputs:
tag:
description: "Release tag to build and attach, for example v0.6.0"
required: true
permissions: {}
concurrency:
group: release-assets-${{ inputs.tag || github.event.release.tag_name }}
cancel-in-progress: false
jobs:
build:
name: build and attach
runs-on: ubuntu-latest
permissions:
contents: write
env:
TAG: ${{ inputs.tag || github.event.release.tag_name }}
GH_TOKEN: ${{ github.token }}
steps:
- uses: actions/checkout@v7
with:
# Release branches share their tag's name, so name the tag explicitly.
ref: refs/tags/${{ env.TAG }}
- uses: actions/setup-python@v7
with:
python-version: "3.13"
- name: Check the package version matches the tag
run: |
version=$(python -c "import re, pathlib; print(re.search(r'__version__ = \"([^\"]+)\"', pathlib.Path('tradingagents/__init__.py').read_text()).group(1))")
if [ "v$version" != "$TAG" ]; then
echo "tradingagents/__init__.py says $version, but the tag is $TAG"
exit 1
fi
- name: Build the source archive and wheel
run: |
python -m pip install --upgrade build
python -m build
- name: Install the wheel in a clean environment
run: |
python -m venv /tmp/smoke
/tmp/smoke/bin/pip install dist/*.whl
# From another directory, so the imports come from the wheel, not the checkout.
cd /tmp
/tmp/smoke/bin/python -c "import importlib.resources as r, tradingagents, cli.main; assert (r.files('cli') / 'static' / 'welcome.txt').is_file(); print('wheel install OK', tradingagents.__version__)"
- name: Attach them to the release
run: gh release upload "$TAG" dist/* --clobber --repo "$GITHUB_REPOSITORY"
+155 -3
View File
@@ -4,7 +4,159 @@ 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).
Changes that need action when upgrading are listed first in their release.
Changes that need action when upgrading are listed under "Upgrading from" in their release.
## [0.7.1] — 2026-10-27
Decisions are scored only on final closes and settle across long market holidays, a model's unpadded date no longer reads filings made after the run date, and fixes to portfolios, prices, SEC statements, reports, Azure and Claude settings.
### Upgrading from 0.7.0
- Docker images no longer include `.env.enterprise`. For Azure OpenAI in Docker, put its keys in `.env`.
### Fixed
- A date a model passes without zero padding, such as `2024-7-5`, is read as that date. It could compare as later than a filing made after the run date, and SEC EDGAR then served that filing. (#1488)
- A decision is no longer scored on the bar of a session still trading, and one made before a market closure longer than a week, such as a national holiday, settles once trading resumes instead of staying pending. (#1548, #1539)
- A backtest reports the failures of its last settlement pass, and two started in the same second no longer share one run. (#1557, #1549)
- A holding listed under a broker's spelling (`BTCUSDT`, `700.HK`) is matched to the instrument analyzed, and a portfolio number that is not finite is refused when the file loads. (#1556, #1509)
- Prices keep their significant digits: a sub-cent close no longer prints as 0.00, and a currency pair keeps its pips. (#1567)
- SEC EDGAR statements list one row per period, so a model no longer reads a figure against the wrong quarter across a long history, and a figure under one million no longer prints as 0. (#1517, #1589)
- Saving a report to a folder used before removes the earlier run's sections. (#1566)
- A date window that ends before it starts is sent back to the model instead of returning no data. (#1595)
- A statement frequency other than annual or quarterly is sent back to the model instead of being served annual figures under that word. (#1593)
- The memory's most recent lessons, and the entries rotation keeps, follow decision dates, so a backfill of older dates no longer displaces them. (#1603)
- Prediction-market odds near 0% or 100% show their distance from it to two significant digits. (#1598)
- Azure OpenAI receives `max_tokens` and a configured endpoint. (#1584, #1600)
- Claude's effort setting is decided correctly for dated model IDs such as `claude-sonnet-4-20250514`. (#1585)
- The CLI checks a ticker with the same rule as the run, so `XAUUSD+` is accepted and `..` is refused at the prompt. (#1604)
- Docker images no longer include `.env` files from any folder.
- Tests that failed on Windows and macOS for platform reasons are fixed. (#1506, #1485, #1541)
### Contributors
[@alanfate3](https://github.com/alanfate3), [@aranlucas](https://github.com/aranlucas), [@BichengWang](https://github.com/BichengWang), [@Bortlesboat](https://github.com/Bortlesboat), [@hoffman988](https://github.com/hoffman988), [@jhill-cmd](https://github.com/jhill-cmd), [@muhib-karim](https://github.com/muhib-karim), [@pei711](https://github.com/pei711), [@peiji1981](https://github.com/peiji1981), [@rudycelekli](https://github.com/rudycelekli), [@Shubham-Padkonde](https://github.com/Shubham-Padkonde), [@stevexyz2003](https://github.com/stevexyz2003), [@SuperMarioYL](https://github.com/SuperMarioYL), [@sytfly](https://github.com/sytfly), [@yuv009](https://github.com/yuv009).
## [0.7.0] — 2026-10-16
Runs on your ChatGPT plan, backtests scored from the first close after each decision, a note at start-up when a newer release is out, and a wheel attached to each GitHub release.
### Added
- **Your ChatGPT plan.** The `chatgpt` provider runs TradingAgents on a ChatGPT Plus or Pro plan instead of an API key, through OpenAI's sign-in for open-source apps. Choose "Subscription" in the CLI's provider menu; for unattended runs, Docker and Python (`llm_provider="chatgpt"`), sign in once with `tradingagents login chatgpt`. `tradingagents logout chatgpt` revokes the sign-in. The CLI lists the plan's models, and reasoning effort applies as it does for OpenAI. (#1194, #1475)
- **What's new at start-up.** The interactive CLI mentions a newer release, with the command that upgrades this install when it can tell how TradingAgents was installed, and notices from Tauric Research for the running version. It checks at most once a day in the background, so a run never waits on it; runs without a terminal never check, and `TRADINGAGENTS_NO_UPDATE_CHECK=1` turns it off.
- **Release downloads.** Each GitHub release carries the source archive and a wheel, so a version installs with `pip install` from its release page without cloning.
### Upgrading from 0.6.0
- `cryptography` 42 and `packaging` 24 or later are installed.
- Decisions are now scored from the first close after their date. Outcomes already settled in a memory log keep the earlier entry, the close of the decision date, so a backtest resumed with `run_id` mixes the two; start a new run to compare like with like.
### Fixed
- A decision is no longer scored against news it could not have traded on: a run dated *d* reads news published after the close on *d*, so the memory log and backtests enter it at the first close after *d*, not the close of *d*. (#1518)
- A run without a terminal, such as a scheduled job or CI, no longer contacts the announcements server before it starts.
- A model tier on another provider keeps its configured reasoning effort, thinking level or Claude effort when the main provider has none. (#1440)
### Contributors
[@LeonWTW](https://github.com/LeonWTW), [@OleksanderSS](https://github.com/OleksanderSS), [@sovorn-c](https://github.com/sovorn-c).
## [0.6.0] — 2026-10-03
HTML reports, a provider per model tier, past decisions settled for every ticker while the analysts work, and company news read while Yahoo's news feed is down.
### Added
- **HTML report.** A saved report also includes `complete_report.html`, the report as one page with its sections listed beside the text, that reads well in a browser, on a phone and in print. Answering the save question at the prompt also asks about the page and can open it in your browser; `--no-html` or `save_reports(..., html=False)` skips it. The page is self-contained: it loads nothing and runs nothing. (#1419)
- **A provider per model tier.** The quick and deep models can run on different providers, for example the managers on Claude while the analysts run on OpenAI: set `deep_think_provider` or `quick_think_provider` (`TRADINGAGENTS_DEEP_THINK_PROVIDER`, `TRADINGAGENTS_QUICK_THINK_PROVIDER`) with the tier's model. The report header names each tier's provider. (#1440)
- **Past decisions settle alongside the analysts.** While a run's analysts work, every logged decision whose holding period has passed is settled, for any ticker, not only the one being analyzed. If settling fails, the run goes on and the report header says so. (#1428, #1445)
- **Crypto on Reddit.** For a crypto ticker the Sentiment Analyst reads r/CryptoCurrency and r/CryptoMarkets, plus r/Bitcoin, r/ethereum or r/solana for those coins, instead of the stock subreddits. (#1461)
- `settle_all_pending()` settles every due decision without running an analysis, for a scheduled job; it and `settle_pending()` return the decisions settled and any that could not be. (#1445)
- The report header names the run's rating.
- Euro-area macro series by name: `ecb_deposit_rate`, `ecb_main_refi_rate`, `euro_hicp`, `euro_core_hicp`, `euro_real_gdp`, `germany_10y`, `france_10y` and `eur_usd`. (#1465)
### Models
- A Gemini call times out after 600 seconds, as OpenAI and Anthropic calls do, so a stalled call no longer hangs the run. (#1417)
### Upgrading from 0.5.2
- markdown-it-py 4.0 or later is installed.
- A saved report also writes `complete_report.html`; pass `--no-html`, or `html=False` to `save_reports()`, to keep only the Markdown.
- A run no longer settles its ticker's decisions before it starts; the Memory Log step settles every ticker's during the run.
- `settle_pending()` returns a `Settlement` with `settled` and `failed` (was `None`).
- Checkpoints from 0.5.2 are not resumed.
### Fixed
- Company news is read from Yahoo search while Yahoo's news feed returns nothing. When Yahoo has no article about the symbol, its news is reported unavailable, not absent, and a configured next news vendor is tried. (#1467, #1469)
- A rating quoted from someone else, such as "Consensus rating: Buy", no longer replaces the Portfolio Manager's own. (#1466)
- A Yahoo news article with a null field no longer loses the ticker's news. (#1458)
- A start date a model writes with stray characters is sent back to it to correct, instead of failing the news or price request. (#1476)
- A request Alpha Vantage rejects is reported as unavailable, not served as data; the API key is kept out of every Alpha Vantage error. (#1442)
- Yahoo fundamentals print each money figure in its own currency: London prices in GBp, market cap and per-share figures in GBP, and an ADR's income figures in its reporting currency, such as TWD for TSMC. (#1456)
- Jev screening uses the endpoint `TYPESAFE_BASE_URL` names, so it can run through OpenRouter. (#1416)
- Runs sharing a memory log settle each decision once, and an interrupted settlement keeps the outcomes it finished.
- The report header names the sentiment analyst `sentiment`, as the CLI does.
- `requirements.txt` says the dependencies are declared in `pyproject.toml`.
### Contributors
[@amitbhansali](https://github.com/amitbhansali), [@AyushJain-601](https://github.com/AyushJain-601), [@BichengWang](https://github.com/BichengWang), [@byte7m](https://github.com/byte7m), [@Dangerboi](https://github.com/Dangerboi), [@davidalmeida90](https://github.com/davidalmeida90), [@Jackzigen](https://github.com/Jackzigen), [@jhill-cmd](https://github.com/jhill-cmd), [@Recnelis0](https://github.com/Recnelis0), [@seaaxe](https://github.com/seaaxe), [@vaegev](https://github.com/vaegev).
## [0.5.2] — 2026-09-29
Parallel analysts, unattended CLI runs, reports that record what produced them,
and past runs served only what was known on their date.
### Added
- **Parallel analysts.** The selected analysts run at the same time, so the analyst phase takes about as long as the slowest one; the CLI shows each analyst's progress and time as it finishes, and the debate starts when all reports are in. (#1255, #433)
- **Unattended CLI runs.** Flags answer the per-run questions, and `TRADINGAGENTS_*` variables the rest, so a scheduled job or script asks nothing: `tradingagents --ticker NVDA --date 2026-09-26 --analysts market,news --save --no-show`. Without a terminal, a missing answer stops the run before it starts and names what to set. (#1127, #1133)
- **Reports record what produced them.** Each report opens with the analysis date, version, provider, models, analysts, rounds and data vendors; the state log keeps them as `run_settings`. (#752, #1197)
- **Docker data folder.** `TRADINGAGENTS_DATA_DIR` keeps results, reports and the memory log in a host folder. (#865)
- **A cap on an analyst's tool calls.** After `max_tool_rounds` rounds (default 20, `TRADINGAGENTS_MAX_TOOL_ROUNDS`) the analyst writes its report from what it has. (#1420)
- `tradingagents backtest` shows each cell as it starts and the `--run-id` to continue; `--analysts` accepts `sentiment`.
- Benchmarks for Taiwan, Korea, Singapore and the main European exchanges. (#1392)
- Python 3.14 support; the Docker image runs Python 3.13.
### Models
- `deepseek-flash` is treated as a thinking model, so structured output works. (#1388)
### Upgrading from 0.5.1
- Python 3.11 or later is required; pandas 3 is installed.
- Minimum versions: yfinance 1.7.0, langchain-core 1.6.5, langchain-openai 1.6.6, langchain-anthropic 1.7.4, langchain-google-genai 4.4.0, langgraph 1.2.12, langgraph-checkpoint-sqlite 3.1.1, langchain-aws 1.7.9 (`bedrock` extra).
- Statements default to SEC EDGAR, then Yahoo (`fundamental_data = "sec_edgar,yfinance"`).
- A past-dated run gets no Yahoo or Alpha Vantage statements or insider trades, which carry no filing date, and only the company's current name, marked as such.
- The memory log is the `tradingagents.memory` package (was `tradingagents.decision_log`); settlement and reflection moved there from `tradingagents.graph`, and `Reflector` is no longer exported from `tradingagents.graph`.
- `process_signal` is removed; the rating is `propagate()`'s second value or `final_state["final_rating"]`.
- A rating is read only from its `Rating:` label; a free-text decision without one is `REVIEW`.
- Data-layer functions take `as_of_date=` (was `curr_date=`); `build_instrument_context` and `resolve_instrument_context` take `trade_date=`.
- `VendorRateLimitError` is `VendorUnavailableError`.
- Data tools take the instrument from the run's state; tool calls no longer carry `symbol` or `ticker`.
- State log: `trader_investment_plan` (was `trader_investment_decision`), `judge_decision` removed, `final_rating` and `run_settings` added.
- Checkpoints from 0.5.1, or saved under different settings, are not resumed.
### Fixed
- Data tools serve the run's instrument, even when the model passes another symbol.
- A failed vendor request is reported as unavailable, not as a missing or delisted symbol; one vendor's "no data" no longer speaks for a chain in which another failed. (#1386)
- The rating is the Portfolio Manager's own, not one its thesis quotes (#1383); its line keeps an English label in other output languages (#1435).
- Backtest cells given twice run once (#1415), and settlement compares a decision with its benchmark over the same dates.
- A snapshot for a symbol with no prices no longer ends the run.
- Concurrent runs no longer drop memory log entries.
- SEC EDGAR quarterly figures filed only year to date are served, labelled with their span.
- Yahoo dividend yield and debt-to-equity print as percentages. (#1414)
- The FRED change line names the dates it spans. (#1397)
- `stream_run` serves the graph's own config to its tools.
- The test suite stays off the network and out of the user's files, and passes in any order; integration tests run with `-m integration`. (#1395)
### Contributors
[@1Wizzy](https://github.com/1Wizzy), [@BichengWang](https://github.com/BichengWang), [@Chaoqi31](https://github.com/Chaoqi31), [@davidalmeida90](https://github.com/davidalmeida90), [@djconnexion77](https://github.com/djconnexion77), [@fuzing](https://github.com/fuzing), [@hailampy123](https://github.com/hailampy123), [@hesam-shams](https://github.com/hesam-shams), [@HEYALT](https://github.com/HEYALT), [@Jackzigen](https://github.com/Jackzigen), [@kagura-agent](https://github.com/kagura-agent), [@loulanyue](https://github.com/loulanyue), [@mannubaveja007](https://github.com/mannubaveja007), [@olivergpt](https://github.com/olivergpt), [@rita112025-cpu](https://github.com/rita112025-cpu), [@shuyan-code](https://github.com/shuyan-code), [@SingTheCode](https://github.com/SingTheCode), [@sjq597](https://github.com/sjq597), [@xiaodu55](https://github.com/xiaodu55), [@Youholdme](https://github.com/Youholdme).
## [0.5.1] — 2026-09-24
@@ -16,12 +168,12 @@ fixes to run isolation, SEC EDGAR statements and historical runs.
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`.
- `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`, and `get_scrubbed` and `vendor_reachable` in `dataflows.net`.
- 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.
- Removed: `SignalProcessor` (the rating is parsed by `process_signal`), the `create_social_media_analyst` alias (use `create_sentiment_analyst`), `symbol_utils.is_yahoo_safe`, 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
+5 -3
View File
@@ -1,4 +1,4 @@
FROM python:3.12-slim AS builder
FROM python:3.13-slim AS builder
ENV PYTHONDONTWRITEBYTECODE=1 \
PIP_DISABLE_PIP_VERSION_CHECK=1
@@ -10,10 +10,12 @@ WORKDIR /build
COPY . .
RUN pip install --no-cache-dir .
FROM python:3.12-slim
FROM python:3.13-slim
# TRADINGAGENTS_IN_DOCKER lets an update notice name the rebuild command.
ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1
PYTHONUNBUFFERED=1 \
TRADINGAGENTS_IN_DOCKER=1
COPY --from=builder /opt/venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
+71 -41
View File
@@ -1,46 +1,46 @@
<p align="center">
<img src="assets/TauricResearch.png" style="width: 60%; height: auto;">
<img src="tradingagents/assets/tauric-logo.svg" width="60%" alt="Tauric Research">
</p>
# TradingAgents: Multi-Agents LLM Financial Trading Framework
<div align="center" style="line-height: 1;">
<a href="https://arxiv.org/abs/2412.20138" target="_blank"><img alt="arXiv" src="https://img.shields.io/badge/arXiv-2412.20138-B31B1B?logo=arxiv"/></a>
<a href="https://discord.com/invite/hk9PGKShPK" target="_blank"><img alt="Discord" src="https://img.shields.io/badge/Discord-TradingResearch-7289da?logo=discord&logoColor=white&color=7289da"/></a>
<a href="https://x.com/TauricResearch" target="_blank"><img alt="X Follow" src="https://img.shields.io/badge/X-TauricResearch-white?logo=x&logoColor=white"/></a>
<a href="https://github.com/TauricResearch/" target="_blank"><img alt="Community" src="https://img.shields.io/badge/GitHub_Community-TauricResearch-14C290?logo=discourse"/></a>
</div>
<br>
<div align="center">
<a href="https://github.com/TauricResearch" target="_blank"><img alt="TradingAgents #1 Repository of the Day" src="https://trendshift.io/api/badge/repositories/16192" width="250" height="55"/></a>
</div>
<br>
<div align="center">
<!-- Keep these links. Translations will automatically update with the README. -->
<a href="https://www.readme-i18n.com/TauricResearch/TradingAgents?lang=de">Deutsch</a> |
<a href="https://www.readme-i18n.com/TauricResearch/TradingAgents?lang=es">Español</a> |
<a href="https://www.readme-i18n.com/TauricResearch/TradingAgents?lang=fr">français</a> |
<a href="https://www.readme-i18n.com/TauricResearch/TradingAgents?lang=ja">日本語</a> |
<a href="https://www.readme-i18n.com/TauricResearch/TradingAgents?lang=ko">한국어</a> |
<a href="https://www.readme-i18n.com/TauricResearch/TradingAgents?lang=pt">Português</a> |
<a href="https://www.readme-i18n.com/TauricResearch/TradingAgents?lang=ru">Русский</a> |
<a href="https://www.readme-i18n.com/TauricResearch/TradingAgents?lang=zh">中文</a>
</div>
---
## Latest: [Trading-R1](https://github.com/TauricResearch/Trading-R1) is now in early access
# TradingAgents: Multi-Agents LLM Financial Trading Framework
After so many requests from the community, Trading-R1 has officially launched!
<p align="center">
<a href="https://github.com/TauricResearch/Trading-R1" target="_blank"><img src="https://raw.githubusercontent.com/TauricResearch/Trading-R1/main/assets/trading-r1.gif" alt="Trading-R1 answering a research question in the terminal" width="100%"></a>
</p>
<h3 align="center"><a href="https://github.com/TauricResearch/Trading-R1" target="_blank">Register for early access ↗</a></h3>
## News
<!-- news:start -->
- [2026-09] **TradingAgents v0.5.1** released with a package layout organised by what each module holds (import paths moved), optional Jev screening of social posts, GPT-6 Sol and Luna as the default models, and fixes to run isolation and SEC EDGAR statements.
- [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.
- [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.
Full release notes are in [CHANGELOG.md](CHANGELOG.md).
- [2026-11] **Trading-R1 v0.1.0** released, and [early access](https://github.com/TauricResearch/Trading-R1) is open.
- [2026-10] **TradingAgents v0.7.1** released with decisions scored only on final closes and settled across long market holidays, a fix for model dates that could read filings made after the run date, and fixes to portfolios, prices, SEC statements and reports.
- [2026-10] **TradingAgents v0.7.0** released with runs on your own ChatGPT Plus or Pro plan, backtests scored from the first close after each decision, a note at start-up when a newer release is out, and a wheel attached to each GitHub release.
<details>
<summary>Earlier news</summary>
- [2026-10] **TradingAgents v0.6.0** released with reports saved as one HTML page, a provider per model tier so the managers and analysts can run on different models, past decisions settled for every ticker while the analysts work, and company news read from Yahoo search while Yahoo's news feed is down.
- [2026-09] **TradingAgents v0.5.2** released with parallel analysts for a faster analysis, a CLI that runs without prompts from flags such as `--ticker` and `--date`, the run's settings recorded in every report, and backtests that see only data published by each analysis date.
- [2026-09] **TradingAgents v0.5.1** released with a package layout organised by what each module holds (import paths moved), optional Jev screening of social posts, GPT-6 Sol and Luna as the default models, and fixes to run isolation and SEC EDGAR statements.
- [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.
- [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.
- [2026-06] **TradingAgents v0.3.0** released with a verified data-access contract, an expanded provider registry (NVIDIA, Kimi, Groq, Mistral, Bedrock, and any OpenAI-compatible endpoint), FRED and Polymarket data vendors, a current-generation model catalog, and a CI gate.
- [2026-05] **TradingAgents v0.2.5** released with the grounded Sentiment Analyst, GPT-5.5 etc. model coverage, Qwen/GLM/MiniMax dual-region support, `TRADINGAGENTS_*` env-var configurability with API-key auto-detection, remote Ollama support, non-US alpha benchmarks, and ticker path-traversal hardening.
@@ -81,6 +81,8 @@ Our framework decomposes complex trading tasks into specialized roles.
- News Analyst: Monitors global news and macroeconomic indicators, interpreting the impact of events on market conditions.
- Technical Analyst: Utilizes technical indicators (like MACD and RSI) to detect trading patterns and forecast price movements.
The selected analysts work at the same time, each on its own tools, and the research debate starts once all of their reports are in.
<p align="center">
<img src="assets/analyst.png" width="100%" style="display: inline-block; margin: 0 2%;">
</p>
@@ -117,15 +119,15 @@ git clone https://github.com/TauricResearch/TradingAgents.git
cd TradingAgents
```
Create a virtual environment in any of your favorite environment managers:
TradingAgents needs Python 3.11 or later. Create a virtual environment in any of your favorite environment managers:
```bash
conda create -n tradingagents python=3.12
conda create -n tradingagents python=3.13
conda activate tradingagents
```
Or with [uv](https://docs.astral.sh/uv/):
```bash
uv venv --python 3.12
uv venv --python 3.13
source .venv/bin/activate
```
@@ -144,6 +146,8 @@ docker compose run --rm tradingagents
After updating the repository, rebuild the image with `docker compose build`.
Results, reports, the memory log and the cache live in the `tradingagents_data` volume. To keep them in a folder on the host instead, create the folder and point `TRADINGAGENTS_DATA_DIR` at it, in `.env` or the shell: `mkdir -p data && TRADINGAGENTS_DATA_DIR=./data docker compose run --rm tradingagents`.
For local models with Ollama:
```bash
docker compose --profile ollama run --rm tradingagents-ollama
@@ -159,12 +163,12 @@ export GOOGLE_API_KEY=... # Google (Gemini)
export ANTHROPIC_API_KEY=... # Anthropic (Claude)
export XAI_API_KEY=... # xAI (Grok)
export DEEPSEEK_API_KEY=... # DeepSeek
export DASHSCOPE_API_KEY=... # Qwen — International (dashscope-intl.aliyuncs.com)
export DASHSCOPE_CN_API_KEY=... # Qwen — China (dashscope.aliyuncs.com)
export DASHSCOPE_API_KEY=... # Qwen (international, dashscope-intl.aliyuncs.com)
export DASHSCOPE_CN_API_KEY=... # Qwen (China, dashscope.aliyuncs.com)
export ZHIPU_API_KEY=... # GLM via Z.AI (international)
export ZHIPU_CN_API_KEY=... # GLM via BigModel (China, open.bigmodel.cn)
export MINIMAX_API_KEY=... # MiniMax — Global (api.minimax.io)
export MINIMAX_CN_API_KEY=... # MiniMax — China (api.minimaxi.com)
export MINIMAX_API_KEY=... # MiniMax (global, api.minimax.io)
export MINIMAX_CN_API_KEY=... # MiniMax (China, api.minimaxi.com)
export OPENROUTER_API_KEY=... # OpenRouter
export MISTRAL_API_KEY=... # Mistral
export MOONSHOT_API_KEY=... # Kimi (Moonshot)
@@ -175,15 +179,17 @@ 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.
For Azure OpenAI, copy `.env.enterprise.example` to `.env.enterprise` and fill in your credentials. With Docker, put these keys in `.env` instead: the image does not include `.env` files.
For AWS Bedrock, install the extra with `pip install ".[bedrock]"`, set `llm_provider: "bedrock"`, configure AWS credentials (environment variables, `~/.aws/credentials`, or an IAM role) and `AWS_DEFAULT_REGION`, and use a Bedrock model ID, e.g. `us.anthropic.claude-opus-4-8-v1:0`.
To run on your ChatGPT Plus or Pro plan instead of an API key, choose "Subscription" in the CLI's provider menu, or set `llm_provider: "chatgpt"`. Sign in once with `tradingagents login chatgpt`: it prints an address to open in your browser, which returns to this machine on `127.0.0.1`. When the browser runs on another machine, or TradingAgents runs in Docker (`docker compose run --rm tradingagents login chatgpt`), paste the address the browser ends up on. The sign-in is kept in `~/.tradingagents/chatgpt-auth.json`, and `tradingagents logout chatgpt` revokes it. Runs count toward your plan's usage limits, and the plan does not accept `temperature` or `max_tokens`.
For AWS Bedrock, install the extra with `pip install ".[bedrock]"`, set `llm_provider: "bedrock"`, configure AWS credentials (environment variables, `~/.aws/credentials`, or an IAM role) and `AWS_DEFAULT_REGION`, and use a Bedrock model ID, e.g. `us.anthropic.claude-opus-5-5`.
For local models, configure Ollama with `llm_provider: "ollama"`. The default endpoint is `http://localhost:11434/v1`; set `OLLAMA_BASE_URL` to point at a remote `ollama-serve`. Pull models with `ollama pull <name>`, and pick "Custom model ID" in the CLI for any model not listed by default.
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.
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. To reach Jev through OpenRouter, put an OpenRouter key in `TYPESAFE_API_KEY` and set `TYPESAFE_BASE_URL=https://openrouter.ai/api`.
Alternatively, copy `.env.example` to `.env` and fill in your keys:
```bash
@@ -199,6 +205,18 @@ python -m cli.main # alternative: run directly from source
```
You will see a screen where you can select your desired tickers, analysis date, LLM provider, research depth, and more. Your previous run's answers come back as the defaults, so pressing Enter accepts them. The `TRADINGAGENTS_*` variables in `.env` still skip their step entirely.
To run without questions, for a scheduled job or a script, answer the per-run steps with flags and the rest with `TRADINGAGENTS_*` variables:
```bash
export TRADINGAGENTS_LLM_PROVIDER=openai TRADINGAGENTS_QUICK_THINK_LLM=gpt-6-luna TRADINGAGENTS_DEEP_THINK_LLM=gpt-6-sol
export TRADINGAGENTS_OUTPUT_LANGUAGE=English TRADINGAGENTS_MAX_DEBATE_ROUNDS=1 TRADINGAGENTS_MAX_RISK_ROUNDS=1
tradingagents --ticker NVDA --date 2026-09-23 --analysts market,news,fundamentals --save --no-show
```
Each flag skips only its own question. Run without a terminal, a missing answer stops the run before it starts and names the flag or variable to set.
At start-up the interactive CLI mentions a newer release and notices from Tauric Research. It checks at most once a day, in the background, and sends nothing about your runs; set `TRADINGAGENTS_NO_UPDATE_CHECK=1` to turn it off. Runs without a terminal never check.
A saved report also includes `complete_report.html`, the report as one page with its sections listed beside the text, for reading in a browser, on a phone or in print. Answering the save question at the prompt also asks about the page and can open it in your browser; `--no-html` skips it, and so does `ta.save_reports(state, "NVDA", html=False)` from Python.
### Markets and tickers
TradingAgents works with any market Yahoo Finance covers, using the exchange-suffixed ticker. Company identity and the alpha benchmark resolve automatically per market.
@@ -227,7 +245,7 @@ An interface will appear showing results as they load, letting you track the age
### Implementation Details
We built TradingAgents with LangGraph to ensure flexibility and modularity. The framework supports multiple LLM providers: OpenAI, Google, Anthropic, xAI, DeepSeek, Qwen (Alibaba DashScope, international and China endpoints), GLM (Zhipu), MiniMax (global + China), OpenRouter, Ollama for local models, and Azure OpenAI for enterprise.
We built TradingAgents with LangGraph to ensure flexibility and modularity. The framework supports multiple LLM providers: OpenAI, Google, Anthropic, xAI, DeepSeek, Qwen (Alibaba DashScope, international and China endpoints), GLM (Zhipu), MiniMax (global + China), OpenRouter, Ollama for local models, Azure OpenAI for enterprise, and your own ChatGPT plan.
### Python Usage
@@ -240,8 +258,11 @@ from tradingagents.default_config import DEFAULT_CONFIG
ta = TradingAgentsGraph(debug=True, config=DEFAULT_CONFIG.copy())
# forward propagate
_, decision = ta.propagate("NVDA", "2026-09-01")
state, decision = ta.propagate("NVDA", "2026-09-01")
print(decision)
# the same report tree the CLI saves, under results_dir/reports
ta.save_reports(state, "NVDA")
```
You can also adjust the default configuration to set your own choice of LLMs, debate rounds, etc.
@@ -261,17 +282,24 @@ _, decision = ta.propagate("NVDA", "2026-09-01")
print(decision)
```
The quick model serves the analysts, researchers, debaters and trader; the deep model serves the research and portfolio managers. Each can run on its own provider, for example the managers on Claude while the rest run on OpenAI:
```python
config["deep_think_provider"] = "anthropic"
config["deep_think_llm"] = "claude-opus-5-5"
```
A tier on its own provider uses that provider's key and default endpoint; set `quick_think_backend_url` or `deep_think_backend_url` for a local or relay endpoint. The `TRADINGAGENTS_DEEP_THINK_PROVIDER` and `TRADINGAGENTS_QUICK_THINK_PROVIDER` variables set them for the CLI, together with the tier's model variable.
See `tradingagents/default_config.py` for all configuration options.
### Fundamentals as filed
US company statements can come from SEC EDGAR, which records the date every figure was filed. A run dated in the past then reads the statements exactly as they stood that day: a fiscal year that has ended but has not been filed yet is not served, and a figure restated later still reads as first reported. Apple's 2008 total assets were filed as $39.6B and restated to $36.2B in 2010, so a run dated in between reads $39.6B.
US company statements come from SEC EDGAR, which records the date every figure was filed. A run dated in the past reads the statements exactly as they stood that day: a fiscal year that has ended but has not been filed yet is not served, and a figure restated later still reads as first reported. Apple's 2008 total assets were filed as $39.6B and restated to $36.2B in 2010, so a run dated in between reads $39.6B. EDGAR needs no account or API key.
EDGAR needs no account or API key. Add the vendor to the chain:
Other companies' statements come from Yahoo Finance, which dates a statement by the period it covers rather than by when it was published. A run dated today reads them; a run dated in the past is told they are withheld, since Yahoo cannot say which figures were public by then.
```python
config["data_vendors"]["fundamental_data"] = "sec_edgar,yfinance"
```
Insider trades are dated by when they happened, not when they were filed, so a run dated in the past is told they are withheld as well.
SEC asks callers to identify themselves and refuses requests that carry no contact address, so a default one is sent. Set your own so SEC can reach you rather than the project:
@@ -304,12 +332,14 @@ An empty `positions` list means a flat book, which is different from passing not
TradingAgents persists two kinds of state across runs.
### Decision log
### Memory log
The decision log is always on. Each completed run appends its decision to `~/.tradingagents/memory/trading_memory.md`. On the next run for the same ticker, TradingAgents fetches the realised return (raw, and alpha against the instrument's regional benchmark), generates a one-paragraph reflection, and injects the most recent same-ticker decisions plus recent cross-ticker lessons into the Portfolio Manager prompt, so each analysis carries forward what worked and what didn't.
The memory log is always on. Each completed run appends its decision to `~/.tradingagents/memory/trading_memory.md`. While the analysts of a later run work, TradingAgents settles every logged decision whose holding period has passed: it fetches the realised return (raw, and alpha against the instrument's regional benchmark) and generates a one-paragraph reflection. The Portfolio Manager then reads the most recent decisions for the same ticker plus recent lessons from other tickers, so each analysis carries forward what worked and what didn't. If settling fails, the run goes on and its report says so.
Override the path with `TRADINGAGENTS_MEMORY_LOG_PATH`.
To settle decisions without running an analysis, for a scheduled job, call `ta.settle_all_pending()`; it returns the decisions it settled and any it could not.
### Checkpoint resume
Checkpoint resume is opt-in via `--checkpoint`. When enabled, LangGraph saves state after each node so a crashed or interrupted run resumes from the last successful step instead of starting over. The run view says whether it resumed a saved run or started fresh. Checkpoints are cleared automatically on successful completion.
@@ -330,7 +360,7 @@ _, decision = ta.propagate("NVDA", "2026-09-01")
## Evaluating decisions over time
One run gives one decision, which cannot tell you whether the system decides well. `run_backtest` runs the same pipeline over a grid of tickers and dates, writes to a decision log of its own, and scores the decisions whose holding window has since traded.
One run gives one decision, which cannot tell you whether the system decides well. `run_backtest` runs the same pipeline over a grid of tickers and dates, writes to a memory log of its own, and scores the decisions whose holding window has since traded.
```python
from tradingagents.backtest import iter_grid, run_backtest, summarize
@@ -346,7 +376,7 @@ From the CLI:
tradingagents backtest NVDA,AAPL --start 2026-06-01 --end 2026-08-01 --every 7
```
Each cell is scored on realized alpha against the instrument's regional benchmark, grouped by rating. Your own decision log is never written to, and re-running the same grid with `run_id=result.run_id` skips the cells that already ran, so an interrupted sweep continues where it stopped.
Each cell is scored on realized alpha against the instrument's regional benchmark, grouped by rating. A decision is entered at the first close after its date, because a run reads news published after that day's close. Your own memory log is never written to, and re-running the same grid with `run_id=result.run_id` skips the cells that already ran, so an interrupted sweep continues where it stopped.
## Reproducibility
-52
View File
@@ -1,52 +0,0 @@
import getpass
import requests
from rich.console import Console
from rich.panel import Panel
from cli.config import CLI_CONFIG
def fetch_announcements(url: str = None, timeout: float = None) -> dict:
"""Fetch announcements from endpoint. Returns dict with announcements and settings."""
endpoint = url or CLI_CONFIG["announcements_url"]
timeout = timeout or CLI_CONFIG["announcements_timeout"]
fallback = CLI_CONFIG["announcements_fallback"]
try:
response = requests.get(endpoint, timeout=timeout)
response.raise_for_status()
data = response.json()
return {
"announcements": data.get("announcements", [fallback]),
"require_attention": data.get("require_attention", False),
}
except Exception:
return {
"announcements": [fallback],
"require_attention": False,
}
def display_announcements(console: Console, data: dict) -> None:
"""Display announcements panel. Prompts for Enter if require_attention is True."""
announcements = data.get("announcements", [])
require_attention = data.get("require_attention", False)
if not announcements:
return
content = "\n".join(announcements)
panel = Panel(
content,
border_style="cyan",
padding=(1, 2),
title="Announcements",
)
console.print(panel)
if require_attention:
getpass.getpass("Press Enter to continue...")
else:
console.print()
-6
View File
@@ -1,6 +0,0 @@
CLI_CONFIG = {
# Announcements
"announcements_url": "https://api.tauric.ai/v1/announcements",
"announcements_timeout": 1.0,
"announcements_fallback": "[cyan]For more information, please visit[/cyan] [link=https://github.com/TauricResearch]https://github.com/TauricResearch[/link]",
}
+18 -36
View File
@@ -404,8 +404,8 @@ def display_complete_report(final_state):
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 final_state.get("investment_plan"):
research.append(("Research Manager", final_state["investment_plan"]))
if research:
console.print(Panel("[bold]II. Research Team Decision[/bold]", border_style="magenta"))
for title, content in research:
@@ -431,10 +431,10 @@ def display_complete_report(final_state):
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)))
# V. Portfolio Manager Decision
if final_state.get("final_trade_decision"):
console.print(Panel("[bold]V. Portfolio Manager Decision[/bold]", border_style="green"))
console.print(Panel(Markdown(final_state["final_trade_decision"]), title="Portfolio Manager", border_style="blue", padding=(1, 2)))
def update_research_team_status(status):
@@ -463,22 +463,17 @@ ANALYST_REPORT_MAP = {
def update_analyst_statuses(message_buffer, chunk, wall_time_tracker=None):
"""Update analyst statuses based on accumulated report state.
"""Update analyst statuses from the reports filed so far.
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
The analysts run together: each is in progress until its own report lands.
When every selected analyst has filed, the research debate is 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)
all_filed = True
for analyst_key in ANALYST_ORDER:
if analyst_key not in selected:
continue
@@ -490,20 +485,15 @@ def update_analyst_statuses(message_buffer, chunk, wall_time_tracker=None):
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:
# Status comes from accumulated sections, not just the current chunk.
if message_buffer.report_sections.get(report_key):
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")
message_buffer.update_agent_status(agent_name, "in_progress")
all_filed = False
# When all analysts complete, transition research team to in_progress
if (
not found_active
all_filed
and selected
and message_buffer.agent_status.get("Bull Researcher") == "pending"
):
@@ -624,17 +614,9 @@ def sync_analyst_tracker_from_chunk(
chunk: dict[str, str],
now: float | None = None,
) -> None:
"""The analysts start together; each stops its clock when its report lands."""
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_started(spec.key, started_at=current_time)
if chunk.get(spec.report_key):
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
+74 -6
View File
@@ -1,11 +1,17 @@
import sys
from enum import StrEnum
from typing import Annotated
import typer
from rich.markup import escape
from cli.display import console
from cli.models import AnalystType, AssetType
from cli.prompts import filter_analysts_for_asset_type, parse_analysts
from cli.run import run_analysis
from tradingagents.backtest import iter_grid, run_backtest, summarize
from tradingagents.default_config import DEFAULT_CONFIG
from tradingagents.llm_clients.openai_client import SIGNED_IN_PROVIDERS
from tradingagents.portfolio import load_portfolio
# prompt_toolkit's win32 output module is importable only on Windows (it asserts
@@ -47,8 +53,27 @@ def analyze(
help="JSON file with current holdings and cash, so the trader, risk and "
"portfolio agents size against your actual position.",
),
ticker: str = typer.Option(None, "--ticker", help="Ticker to analyze, e.g. NVDA or 0700.HK; skips the prompt"),
date: str = typer.Option(None, "--date", help="Analysis date, YYYY-MM-DD; skips the prompt"),
analysts: str = typer.Option(
None, "--analysts", help="Comma-separated analysts, e.g. market,news; skips the prompt"
),
save: bool | None = typer.Option(
None, "--save/--no-save", help="Save the report under results_dir without asking"
),
show: bool | None = typer.Option(
None, "--show/--no-show", help="Show the full report at the end without asking"
),
html: bool | None = typer.Option(
None, "--html/--no-html",
help="Save the report as one HTML page too, complete_report.html, without asking (default: yes)",
),
):
"""Run an analysis. This is what a bare `tradingagents` does."""
"""Run an analysis. This is what a bare `tradingagents` does.
Flags answer their questions; with provider, models, depth and language also
set through TRADINGAGENTS_* variables, the run asks nothing.
"""
if ctx.invoked_subcommand is not None:
return
if clear_checkpoints:
@@ -64,7 +89,8 @@ def analyze(
raise typer.Exit(code=1) from None
try:
run_analysis(checkpoint=checkpoint, portfolio=portfolio_context)
flags = {"ticker": ticker, "date": date, "analysts": analysts, "save": save, "show": show, "html": html}
run_analysis(checkpoint=checkpoint, portfolio=portfolio_context, flags=flags)
except _NO_CONSOLE_ERRORS:
# A terminal with no console buffer cannot host the interactive prompts.
# Emit one actionable line on stderr instead of a prompt_toolkit
@@ -85,7 +111,7 @@ def backtest(
end: str = typer.Option(..., "--end", help="Last analysis date, YYYY-MM-DD"),
every: int = typer.Option(7, "--every", help="Days between analysis dates"),
analysts: str = typer.Option(
None, "--analysts", help="Comma-separated analysts to run; omit for all four"
None, "--analysts", help="Comma-separated analysts to run: market, sentiment, news, fundamentals; omit for all the asset type allows"
),
asset_type: str = typer.Option("stock", "--asset-type", help="stock or crypto"),
portfolio: str = typer.Option(
@@ -100,6 +126,11 @@ def backtest(
try:
dates = iter_grid(start, end, every)
book = load_portfolio(portfolio) if portfolio else None
kind = AssetType(asset_type.strip().lower())
# The analysts are named and checked as for an analysis; without a
# choice, every analyst the asset type allows runs.
chosen = (parse_analysts(analysts, kind) if analysts
else filter_analysts_for_asset_type(list(AnalystType), kind))
except ValueError as exc:
console.print(f"[red]{exc}[/red]")
raise typer.Exit(code=1) from None
@@ -109,9 +140,11 @@ def backtest(
console.print("[red]No ticker to analyze; pass them comma-separated, e.g. NVDA,AAPL[/red]")
raise typer.Exit(code=1)
kwargs = {"asset_type": asset_type, "portfolio": book, "run_id": run_id}
if analysts:
kwargs["selected_analysts"] = [a.strip().lower() for a in analysts.split(",") if a.strip()]
def show_progress(done, total, ticker, date):
console.print(f"[dim][{done}/{total}] {ticker} {date}[/dim]")
kwargs = {"asset_type": kind.value, "portfolio": book, "run_id": run_id, "progress": show_progress,
"selected_analysts": [a.value for a in chosen]}
try:
result = run_backtest(names, dates, DEFAULT_CONFIG, **kwargs)
@@ -120,11 +153,46 @@ def backtest(
raise typer.Exit(code=1) from None
console.print(summarize(result).render())
console.print(f"\nRan {result.cells_run} cells, skipped {result.skipped}. Log: {result.log_path}")
console.print(f"Continue or settle this sweep: --run-id {result.run_id}")
for ticker, date, reason in result.failures:
console.print(f"[yellow]failed:[/yellow] {ticker} {date}: {reason}")
for ticker, reason in result.settlement_failures:
console.print(f"[yellow]unsettled:[/yellow] {ticker}: {reason}")
# The plans `login` and `logout` take: the providers signed in to, not keyed.
Plan = StrEnum("Plan", {name: name for name in SIGNED_IN_PROVIDERS})
@app.command()
def login(plan: Annotated[Plan, typer.Argument(help="The plan to sign in with")]):
"""Sign in with your ChatGPT Plus or Pro plan, for the chatgpt provider."""
from tradingagents.llm_clients import chatgpt_auth
try:
# One unwrapped line, so the sign-in address can be copied whole.
email = chatgpt_auth.sign_in(
say=lambda line: console.print(line, soft_wrap=True, markup=False, highlight=False))
except chatgpt_auth.ChatGPTAuthError as exc:
console.print(f"[red]{escape(str(exc))}[/red]")
raise typer.Exit(code=1) from None
console.print(f"[green]Signed in to ChatGPT as {escape(email)}.[/green]")
@app.command()
def logout(plan: Annotated[Plan, typer.Argument(help="The plan to sign out of")]):
"""Sign out of your ChatGPT plan: revoke this machine's access and forget it."""
from tradingagents.llm_clients import chatgpt_auth
outcome = chatgpt_auth.sign_out()
if outcome == "revoked":
console.print("Signed out of ChatGPT.")
elif outcome == "forgotten":
console.print("[yellow]Signed out here, but OpenAI could not be reached to revoke the sign-in; "
"it stays valid at OpenAI until it expires.[/yellow]")
else:
console.print("Not signed in to ChatGPT.")
if __name__ == "__main__":
app()
+3 -3
View File
@@ -1,7 +1,7 @@
from enum import Enum
from enum import StrEnum
class AnalystType(str, Enum):
class AnalystType(StrEnum):
MARKET = "market"
# Wire value stays "social" for saved-config and string-keyed-caller
# back-compat; the user-facing label is "Sentiment Analyst".
@@ -10,6 +10,6 @@ class AnalystType(str, Enum):
FUNDAMENTALS = "fundamentals"
class AssetType(str, Enum):
class AssetType(StrEnum):
STOCK = "stock"
CRYPTO = "crypto"
+7 -5
View File
@@ -21,7 +21,8 @@ import os
from pathlib import Path
from cli.models import AnalystType, AssetType
from cli.prompts import _llm_provider_table, filter_analysts_for_asset_type
from cli.prompts import LISTED_LIVE, _llm_provider_table, filter_analysts_for_asset_type
from tradingagents.dataflows.files import replace_file
from tradingagents.llm_clients.model_catalog import get_model_options
_PREFS_PATH = Path(os.path.expanduser("~")) / ".tradingagents" / "cli_prefs.json"
@@ -52,9 +53,8 @@ def save_last_run(selections: dict) -> None:
kept = {k: v for k, v in kept.items() if v is not None}
try:
_PREFS_PATH.parent.mkdir(parents=True, exist_ok=True)
temp = _PREFS_PATH.with_suffix(".tmp")
temp.write_text(json.dumps(kept, indent=2), encoding="utf-8")
os.replace(temp, _PREFS_PATH) # a concurrent run reads one file or the other
# A concurrent run reads one file or the other.
replace_file(_PREFS_PATH, lambda temp: Path(temp).write_text(json.dumps(kept, indent=2), encoding="utf-8"))
except OSError:
return
@@ -86,6 +86,8 @@ def sanitize(prefs: dict, asset_type) -> dict:
offered = {model for _, model in get_model_options(base, mode)}
except KeyError:
continue
if prefs.get(field) in offered:
# Models listed live are not in the catalog, so any model ID is kept.
listed_live = base in LISTED_LIVE and isinstance(prefs.get(field), str)
if prefs.get(field) in offered or listed_live:
kept[field] = prefs[field]
return kept
+159 -52
View File
@@ -1,13 +1,20 @@
import datetime
import os
import subprocess
import sys
from pathlib import Path
import questionary
import typer
from dotenv import find_dotenv, set_key
from rich.markup import escape
from cli.display import console
from cli.models import AnalystType, AssetType
from tradingagents.dataflows.symbols import safe_ticker_component
from tradingagents.llm_clients.api_key_env import get_api_key_env
from tradingagents.llm_clients.model_catalog import get_model_options
from tradingagents.llm_clients.openai_client import OPENAI_COMPATIBLE_PROVIDERS, SIGNED_IN_PROVIDERS
TICKER_INPUT_EXAMPLES = "SPY, 0700.HK, BTC-USD"
@@ -21,15 +28,28 @@ ANALYST_CHOICES = [
CRYPTO_SUFFIXES = ("-USD", "-USDT", "-USDC", "-BTC", "-ETH")
def is_valid_ticker_input(value: str) -> bool:
"""Whether a ticker entry is acceptable (charset + length).
# The style of every selection menu.
_MENU_STYLE = questionary.Style([
("selected", "fg:magenta noinherit"),
("highlighted", "fg:magenta noinherit"),
("pointer", "fg:magenta noinherit"),
])
Allows the characters Yahoo symbols use, including ``=`` for futures/forex
like ``GC=F`` and ``EURUSD=X`` (#980), and ``^`` for indices. Empty input is
allowed (it defaults to SPY downstream).
def is_valid_ticker_input(value: str) -> bool:
"""Whether a ticker entry names a symbol the run can use.
The symbol it resolves to (``XAUUSD+`` -> ``GC=F``) must pass the data
layer's own check, so the prompt refuses exactly what the run would.
Empty input is allowed (it defaults to SPY downstream).
"""
v = value.strip()
return not v or (all(ch.isalnum() or ch in "._-^=" for ch in v) and len(v) <= 32)
if not value.strip():
return True
try:
safe_ticker_component(normalize_ticker_symbol(value))
except ValueError:
return False
return True
def get_ticker() -> str:
@@ -60,6 +80,42 @@ def get_ticker() -> str:
return normalize_ticker_symbol(ticker) if ticker.strip() else "SPY"
def parse_ticker(value: str) -> str:
"""A ticker given on the command line, canonical; empty or malformed is refused."""
if not value.strip() or not is_valid_ticker_input(value):
raise ValueError(f"not a ticker symbol: {value!r} (e.g. {TICKER_INPUT_EXAMPLES})")
return normalize_ticker_symbol(value)
def parse_analysis_date(value: str) -> str:
"""An analysis date as YYYY-MM-DD, today or earlier."""
try:
day = datetime.datetime.strptime(value.strip(), "%Y-%m-%d").date()
except ValueError:
raise ValueError(f"not a date: {value!r}; use YYYY-MM-DD") from None
if day > datetime.date.today():
raise ValueError(f"{value} is in the future")
return day.isoformat()
def parse_analysts(value: str, asset_type: AssetType) -> list[AnalystType]:
"""Comma-separated analyst names, in the canonical order, checked against the asset."""
# "sentiment" is the name users see; the analyst's key is "social".
names = [{"sentiment": "social"}.get(n, n) for n in (n.strip().lower() for n in value.split(",")) if n]
if not names:
raise ValueError("name at least one analyst")
known = {a.value: a for a in AnalystType}
unknown = [n for n in names if n not in known]
if unknown:
choices = ", ".join("sentiment" if name == "social" else name for name in known)
raise ValueError(f"unknown analyst {', '.join(unknown)}; choose from {choices}")
available = filter_analysts_for_asset_type(list(known.values()), asset_type)
unavailable = [n for n in names if known[n] not in available]
if unavailable:
raise ValueError(f"{', '.join(unavailable)} is not available for {asset_type.value}")
return [a for a in available if a.value in names]
def normalize_ticker_symbol(ticker: str) -> str:
"""Resolve user input to its canonical Yahoo symbol (single source of truth).
@@ -199,6 +255,35 @@ def _fetch_openrouter_models() -> list[tuple[str, str]]:
return []
def select_chatgpt_model(mode: str, default=None) -> str:
"""Select one of the ChatGPT plan's models, or enter a model ID."""
from tradingagents.llm_clients import chatgpt_auth
try:
models = chatgpt_auth.list_models()
except Exception as e:
console.print(f"\n[yellow]Could not list your ChatGPT plan's models: {escape(str(e))}[/yellow]")
models = []
return _select_listed_model(f"Select Your [{mode.title()}-Thinking] ChatGPT Plan Model:",
models, default, _prompt_custom_model_id)
def _select_listed_model(title: str, models, default, custom) -> str:
"""Select from ``models`` ((name, model ID) pairs, listed live) or enter one with ``custom``."""
choices = [questionary.Choice(name, value=mid) for name, mid in models]
choices.append(questionary.Choice("Custom model ID", value="custom"))
choice = questionary.select(
title,
choices=choices,
default=default if any(c.value == default for c in choices) else None,
instruction="\n- Use arrow keys to navigate\n- Press Enter to select",
style=_MENU_STYLE,
).ask()
if choice is None:
console.print("\n[red]No model selected. Exiting...[/red]")
exit(1)
return custom() if choice == "custom" else choice
def _require_text(message: str, hint: str) -> str:
"""Prompt for a required value; exit cleanly if the user cancels.
@@ -216,7 +301,7 @@ def _require_text(message: str, hint: str) -> str:
return response.strip()
def select_openrouter_model(mode: str) -> str:
def select_openrouter_model(mode: str, default=None) -> str:
"""Select an OpenRouter model from the newest available, or enter a custom ID.
``mode`` ("quick"/"deep") labels the prompt so the two consecutive
@@ -231,30 +316,14 @@ def select_openrouter_model(mode: str) -> str:
and mid.split("/", 1)[0] in _OPENROUTER_MAINSTREAM
]
top = (mainstream or models)[:5]
return _select_listed_model(
f"Select Your [{mode.title()}-Thinking] OpenRouter Model (latest available):", top, default,
lambda: _require_text("Enter OpenRouter model ID (e.g. google/gemma-4-26b-a4b-it):",
"Please enter a model ID."))
choices = [questionary.Choice(name, value=mid) for name, mid in top]
choices.append(questionary.Choice("Custom model ID", value="custom"))
choice = questionary.select(
f"Select Your [{mode.title()}-Thinking] OpenRouter Model (latest available):",
choices=choices,
instruction="\n- Use arrow keys to navigate\n- Press Enter to select",
style=questionary.Style([
("selected", "fg:magenta noinherit"),
("highlighted", "fg:magenta noinherit"),
("pointer", "fg:magenta noinherit"),
]),
).ask()
if choice is None:
console.print("\n[red]No model selected. Exiting...[/red]")
exit(1)
if choice == "custom":
return _require_text(
"Enter OpenRouter model ID (e.g. google/gemma-4-26b-a4b-it):",
"Please enter a model ID.",
)
return choice
# Providers whose models are listed live, with the menu that offers them.
LISTED_LIVE = {"openrouter": select_openrouter_model, "chatgpt": select_chatgpt_model}
def _prompt_custom_model_id() -> str:
@@ -264,8 +333,9 @@ def _prompt_custom_model_id() -> str:
def _select_model(provider: str, mode: str, default=None) -> str:
"""Select a model for the given provider and mode (quick/deep)."""
if provider.lower() == "openrouter":
return select_openrouter_model(mode)
listed = LISTED_LIVE.get(provider.lower())
if listed is not None:
return listed(mode, default)
if provider.lower() == "azure":
return _require_text(
@@ -281,13 +351,7 @@ def _select_model(provider: str, mode: str, default=None) -> str:
],
default=_matching_choice(get_model_options(provider, mode), default),
instruction="\n- Use arrow keys to navigate\n- Press Enter to select",
style=questionary.Style(
[
("selected", "fg:magenta noinherit"),
("highlighted", "fg:magenta noinherit"),
("pointer", "fg:magenta noinherit"),
]
),
style=_MENU_STYLE,
).ask()
if choice is None:
@@ -324,6 +388,7 @@ def _llm_provider_table() -> list[tuple[str, str, str | None]]:
("OpenAI", "openai", "https://api.openai.com/v1"),
("Google", "google", None),
("Anthropic", "anthropic", "https://api.anthropic.com/"),
("ChatGPT (Plus or Pro plan)", "chatgpt", "https://api.openai.com/v1"),
("xAI", "xai", "https://api.x.ai/v1"),
("DeepSeek", "deepseek", "https://api.deepseek.com"),
("Qwen", "qwen", "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"),
@@ -380,37 +445,50 @@ def prompt_openai_compatible_url(default=None) -> str:
return url.strip()
# The menu entry that groups the providers used through a personal plan.
_SUBSCRIPTION = ("subscription", None)
def select_llm_provider(default=None) -> tuple[str, str | None]:
"""Select the LLM provider and its API endpoint."""
PROVIDERS = _llm_provider_table()
# A region-specific key (qwen-cn) is chosen in a later prompt; the menu
# lists the base provider.
base = (default or "").split("-cn")[0]
preselected = next(
choices = []
for display, provider_key, url in PROVIDERS:
if provider_key in SIGNED_IN_PROVIDERS:
continue
choices.append(questionary.Choice(display, value=(provider_key, url)))
if provider_key == "anthropic":
choices.append(questionary.Choice("Subscription (use your ChatGPT plan)", value=_SUBSCRIPTION))
preselected = _SUBSCRIPTION if base in SIGNED_IN_PROVIDERS else next(
((key, url) for _, key, url in PROVIDERS if key == base), None
)
choice = questionary.select(
"Select your LLM Provider:",
choices=[
questionary.Choice(display, value=(provider_key, url))
for display, provider_key, url in PROVIDERS
],
choices=choices,
default=preselected,
instruction="\n- Use arrow keys to navigate\n- Press Enter to select",
style=questionary.Style(
[
("selected", "fg:magenta noinherit"),
("highlighted", "fg:magenta noinherit"),
("pointer", "fg:magenta noinherit"),
]
),
style=_MENU_STYLE,
).ask()
if choice is None:
console.print("\n[red]No LLM provider selected. Exiting...[/red]")
exit(1)
if choice == _SUBSCRIPTION:
choice = questionary.select(
"Select your subscription:",
choices=[questionary.Choice(display, value=(key, url))
for display, key, url in PROVIDERS if key in SIGNED_IN_PROVIDERS],
style=_MENU_STYLE,
).ask()
if choice is None:
console.print("\n[red]No subscription selected. Exiting...[/red]")
exit(1)
provider, url = choice
return provider, url
@@ -585,6 +663,32 @@ def confirm_ollama_endpoint(url: str) -> None:
)
def ensure_signed_in(provider: str) -> None:
"""Make sure a plan provider's sign-in works before the run, offering to sign in now.
Signing in runs as its own process (``tradingagents login chatgpt``), so its
read of a pasted address ends with it and never takes a later answer."""
if provider.lower() not in SIGNED_IN_PROVIDERS:
return
from tradingagents.llm_clients import chatgpt_auth # the one signed-in provider
try:
chatgpt_auth.access_token()
except chatgpt_auth.ChatGPTUnreachable as exc:
console.print(f"[red]{escape(str(exc))}[/red]")
raise typer.Exit(code=1) from None
except chatgpt_auth.ChatGPTAuthError as exc:
if not sys.stdin.isatty():
console.print(f"[red]{escape(str(exc))}[/red]")
raise typer.Exit(code=1) from None
console.print(f"\n[yellow]{escape(str(exc))}[/yellow]")
# -P keeps a cli/ package in the working directory from shadowing ours.
login = [sys.executable, "-P", "-m", "cli.main", "login", "chatgpt"]
if subprocess.run(login).returncode != 0:
raise typer.Exit(code=1) from None
console.print(f"[green]✓ Using your ChatGPT plan:[/green] {escape(chatgpt_auth.signed_in_as() or '')}")
def ensure_api_key(provider: str) -> str | None:
"""Make sure the API key for `provider` is available in the environment.
@@ -602,7 +706,6 @@ def ensure_api_key(provider: str) -> str | None:
# Key-optional providers (generic OpenAI-compatible / local servers) read the
# key when present but must never force an interactive prompt.
from tradingagents.llm_clients.openai_client import OPENAI_COMPATIBLE_PROVIDERS
spec = OPENAI_COMPATIBLE_PROVIDERS.get(provider.lower())
if spec is not None and spec.key_optional:
return os.environ.get(env_var)
@@ -611,6 +714,10 @@ def ensure_api_key(provider: str) -> str | None:
if existing:
return existing
if not sys.stdin.isatty():
console.print(f"[red]{env_var} is not set; there is no terminal to ask for it.[/red]")
raise typer.Exit(code=1)
console.print(
f"\n[yellow]{env_var} is not set in your environment.[/yellow]"
)
+113 -42
View File
@@ -1,8 +1,9 @@
"""Running one analysis from the CLI: build the graph, stream it into the live view, save the report."""
import datetime
import os
import sys
import time
import webbrowser
from functools import wraps
from pathlib import Path
@@ -21,16 +22,15 @@ from cli.display import (
update_display,
update_research_team_status,
)
from cli.selections import get_user_selections
from cli.selections import depth_from_env, get_user_selections, unattended_gaps
from cli.stats_handler import StatsCallbackHandler
from tradingagents.agents.rating import is_review
from tradingagents.agents.rating import is_review, run_rating
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:
@@ -66,25 +66,28 @@ def _build_run_config(selections: dict, checkpoint: bool | None) -> dict:
# 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
rounds = (("TRADINGAGENTS_MAX_DEBATE_ROUNDS", "max_debate_rounds"),
("TRADINGAGENTS_MAX_RISK_ROUNDS", "max_risk_discuss_rounds"))
depth_was_asked = not depth_from_env()
for env_var, key in rounds:
if not os.environ.get(env_var):
config[key] = selections["research_depth"]
elif depth_was_asked:
# The depth question 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")
# Provider-specific thinking configuration. Only the main provider's is
# asked; a tier on another provider keeps its configured value (#1440).
for key in ("google_thinking_level", "openai_reasoning_effort", "anthropic_effort"):
if selections.get(key) is not None:
config[key] = selections[key]
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).
@@ -93,9 +96,19 @@ def _build_run_config(selections: dict, checkpoint: bool | None) -> dict:
return config
def run_analysis(checkpoint: bool | None = None, portfolio=None):
# First get all user selections
selections = get_user_selections()
def run_analysis(checkpoint: bool | None = None, portfolio=None, flags=None):
flags = flags or {}
# With no terminal nothing can answer a prompt: name every question still
# open before any model is called, rather than stopping at the first one.
if not (sys.stdin and sys.stdin.isatty()):
gaps = unattended_gaps(flags)
if gaps:
console.print("[red]No terminal to answer the setup questions. Set:[/red]")
for gap in gaps:
console.print(f" {gap}")
raise typer.Exit(code=1)
selections = get_user_selections(flags)
config = _build_run_config(selections, checkpoint)
@@ -189,9 +202,10 @@ def run_analysis(checkpoint: bool | None = None, portfolio=None):
)
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])
# The analysts start together.
for spec in analyst_execution_plan.specs:
message_buffer.update_agent_status(spec.agent_node, "in_progress")
analyst_wall_time_tracker.mark_started(spec.key)
update_display(layout, stats_handler=stats_handler, start_time=start_time)
spinner_text = (
@@ -199,8 +213,9 @@ def run_analysis(checkpoint: bool | None = None, portfolio=None):
)
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.
# The same initial state propagate() builds, with the resolved
# instrument identity; the graph's Memory Log step settles past
# decisions and loads their lessons alongside the analysts.
init_agent_state = graph.create_run_state(
selections["ticker"], selections["analysis_date"], selections["asset_type"], portfolio
)
@@ -223,8 +238,8 @@ def run_analysis(checkpoint: bool | None = None, portfolio=None):
# 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", []):
for messages, chunk in graph.stream_run(graph.checkpoint_input(init_agent_state), **args):
for message in messages:
msg_id = getattr(message, "id", None)
if msg_id is not None:
if msg_id in message_buffer._processed_message_ids:
@@ -242,6 +257,10 @@ def run_analysis(checkpoint: bool | None = None, portfolio=None):
else:
message_buffer.add_tool_call(tool_call.name, tool_call.args)
if chunk is None: # a step inside an analyst's graph: messages only
update_display(layout, stats_handler=stats_handler, start_time=start_time)
continue
update_analyst_statuses(
message_buffer,
chunk,
@@ -253,7 +272,7 @@ def run_analysis(checkpoint: bool | None = None, portfolio=None):
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()
judge = (chunk.get("investment_plan") or "").strip()
# Only update status when there's actual content
if bull_hist or bear_hist:
@@ -288,7 +307,7 @@ def run_analysis(checkpoint: bool | None = None, portfolio=None):
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()
judge = (chunk.get("final_trade_decision") or "").strip()
if agg_hist:
if message_buffer.agent_status.get("Aggressive Analyst") != "completed":
@@ -358,7 +377,7 @@ def run_analysis(checkpoint: bool | None = None, portfolio=None):
# 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", ""))):
if is_review(run_rating(final_state)):
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 "
@@ -366,28 +385,80 @@ def run_analysis(checkpoint: bool | None = None, portfolio=None):
)
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")
_offer_reports(final_state, graph, selections["ticker"],
save=flags.get("save"), show=flags.get("show"), html=flags.get("html"))
def _yes(question: str) -> bool:
return typer.prompt(question, default="Y").strip().upper() in ("Y", "YES", "")
def _graphical_browser():
"""A browser that opens a page in its own window on this machine, or None.
Over SSH the page sits on the remote machine, and a terminal browser (lynx,
w3m, elinks) would take over the terminal, so neither is offered.
"""
if os.environ.get("SSH_CONNECTION") or os.environ.get("SSH_TTY"):
return None
try:
browser = webbrowser.get()
except webbrowser.Error:
return None
if type(browser) is webbrowser.GenericBrowser or isinstance(browser, webbrowser.Elinks):
return None
return browser
def _open_page(page: Path) -> None:
"""Offer to open the saved page in a browser window, and say where it is if opening fails."""
browser = _graphical_browser()
if browser is None or not _yes("Open it in your browser?"):
return
try:
opened = browser.open(page.as_uri())
except (webbrowser.Error, OSError):
opened = False
if not opened:
console.print(f" [dim]Could not open a browser; the page is at:[/dim] {page}")
def _offer_reports(final_state, graph, ticker, save=None, show=None, html=None):
"""Save the report tree and show it; ``save``/``show``/``html`` answer the questions when given.
A saved report includes the HTML page unless ``html`` is False. Someone
answering the save question at the prompt is also asked about the page and
offered to open it; a run whose flags answer the save question asks neither.
"""
asked = save is None
if asked:
save = typer.prompt("Save report?", default="Y").strip().upper() in ("Y", "YES", "")
if save:
# 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)
save_path = graph.default_report_path(ticker)
if asked: # someone at the prompt may pick another folder
save_path = Path(typer.prompt(
"Save path (press Enter for default)", default=str(save_path)
).strip())
if html is None:
html = _yes("Also save it as an HTML page?") if asked else True
saved = False
try:
report_file = write_report_tree(final_state, selections["ticker"], save_path)
report_file = graph.save_reports(final_state, ticker, save_path, html=html)
saved = True
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]")
if saved and html:
page = (save_path / "complete_report.html").resolve()
console.print(f" [dim]HTML report:[/dim] {page.name}")
if asked:
_open_page(page)
# Prompt to display full report
display_choice = typer.prompt("\nDisplay full report on screen?", default="Y").strip().upper()
if display_choice in ("Y", "YES", ""):
if show is None:
show = typer.prompt("\nDisplay full report on screen?", default="Y").strip().upper() in ("Y", "YES", "")
if show:
display_complete_report(final_state)
+118 -50
View File
@@ -8,7 +8,7 @@ import typer
from rich.align import Align
from rich.panel import Panel
from cli.announcements import display_announcements, fetch_announcements
from cli import updates
from cli.display import (
console,
)
@@ -24,7 +24,11 @@ from cli.prompts import (
confirm_ollama_endpoint,
detect_asset_type,
ensure_api_key,
ensure_signed_in,
get_ticker,
parse_analysis_date,
parse_analysts,
parse_ticker,
prompt_openai_compatible_url,
resolve_backend_url,
select_analysts,
@@ -34,17 +38,82 @@ from cli.prompts import (
select_shallow_thinking_agent,
)
from tradingagents.default_config import DEFAULT_CONFIG
from tradingagents.llm_clients.factory import REASONING_EFFORT_PROVIDERS
from tradingagents.llm_clients.openai_client import check_endpoint
def get_user_selections():
def get_user_selections(flags=None):
"""Ask for the run's settings, offering the previous run's answers."""
selections = _prompt_selections(load_last_run())
selections = _prompt_selections(load_last_run(), flags or {})
save_last_run(selections)
return selections
def _prompt_selections(prefs):
"""Walk the selection steps. ``prefs`` prefills, the environment skips."""
def depth_from_env() -> bool:
"""Both round counts come from the environment, so the depth question is skipped."""
return bool(os.environ.get("TRADINGAGENTS_MAX_DEBATE_ROUNDS")
and os.environ.get("TRADINGAGENTS_MAX_RISK_ROUNDS"))
def unattended_gaps(flags) -> list[str]:
"""The flags and environment variables a run with no terminal still needs."""
env = os.environ.get
gaps = [f"--{name}" for name in ("ticker", "date", "analysts") if flags.get(name) is None]
gaps += [f"--{name} or --no-{name}" for name in ("save", "show") if flags.get(name) is None]
if not env("TRADINGAGENTS_OUTPUT_LANGUAGE"):
gaps.append("TRADINGAGENTS_OUTPUT_LANGUAGE")
if not depth_from_env():
gaps.append("TRADINGAGENTS_MAX_DEBATE_ROUNDS and TRADINGAGENTS_MAX_RISK_ROUNDS")
if not env("TRADINGAGENTS_LLM_PROVIDER"):
gaps.append("TRADINGAGENTS_LLM_PROVIDER")
if not (env("TRADINGAGENTS_QUICK_THINK_LLM") or env("TRADINGAGENTS_DEEP_THINK_LLM")):
gaps.append("TRADINGAGENTS_QUICK_THINK_LLM or TRADINGAGENTS_DEEP_THINK_LLM")
return gaps
def _check_tier_providers(main_provider: str, backend_url: str | None = None) -> None:
"""Check each provider the model tiers use (#1440) before the run.
A tier on another provider needs its model from its variable, since the
model question offers the main provider's models. Each provider a tier uses
has its endpoint, sign-in and key checked now, prompting for a missing key,
rather than at its first call, which for the deep tier comes after everything
else has been paid for; a provider no tier uses needs no key.
"""
used = []
for tier in ("quick", "deep"):
provider = (DEFAULT_CONFIG.get(f"{tier}_think_provider") or main_provider).lower()
on_main = provider == main_provider.lower()
if not on_main:
variable = f"TRADINGAGENTS_{tier.upper()}_THINK_LLM"
if not os.environ.get(variable):
console.print(f"[red]The {tier} tier runs on {provider}; set {variable} to one of its models.[/red]")
raise typer.Exit(code=1)
# The tier's endpoint, as create_tier_client resolves it.
url = DEFAULT_CONFIG.get(f"{tier}_think_backend_url") or (backend_url if on_main else None)
try:
check_endpoint(provider, url)
except ValueError as exc:
console.print(f"[red]{exc}[/red]")
raise typer.Exit(code=1) from None
if provider not in used:
used.append(provider)
for provider in used:
ensure_signed_in(provider)
ensure_api_key(provider)
def _from_flag(parse, value, *args):
"""A flag's value through the same check its prompt applies; a bad one ends the run."""
try:
return parse(value, *args)
except ValueError as exc:
console.print(f"[red]{exc}[/red]")
raise typer.Exit(code=1) from None
def _prompt_selections(prefs, flags):
"""Walk the selection steps. ``prefs`` prefills; flags and the environment skip."""
with open(Path(__file__).parent / "static" / "welcome.txt", encoding="utf-8") as f:
welcome_ascii = f.read()
@@ -67,9 +136,11 @@ def _prompt_selections(prefs):
console.print()
console.print() # Add vertical space before announcements
# Fetch and display announcements (silent on failure)
announcements = fetch_announcements()
display_announcements(console, announcements)
# What's new comes from a cache refreshed in the background, and only for
# someone at a terminal: a run never waits on it and unattended runs skip it.
if updates.enabled():
updates.show(console)
updates.start_background_refresh()
def create_question_box(title, prompt, default=None):
box_content = f"[bold]{title}[/bold]\n"
@@ -93,14 +164,18 @@ def _prompt_selections(prefs):
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",
if flags.get("ticker") is not None:
selected_ticker = _from_flag(parse_ticker, flags["ticker"])
console.print(f"[green]✓ Ticker from --ticker:[/green] {selected_ticker}")
else:
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()
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.
@@ -110,15 +185,19 @@ def _prompt_selections(prefs):
)
# 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,
if flags.get("date") is not None:
analysis_date = _from_flag(parse_analysis_date, flags["date"])
console.print(f"[green]✓ Analysis date from --date:[/green] {analysis_date}")
else:
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()
analysis_date = get_analysis_date()
# Step 3: Output language (skipped when set via TRADINGAGENTS_OUTPUT_LANGUAGE)
if os.environ.get("TRADINGAGENTS_OUTPUT_LANGUAGE"):
@@ -136,13 +215,16 @@ def _prompt_selections(prefs):
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"))
if flags.get("analysts") is not None:
selected_analysts = _from_flag(parse_analysts, flags["analysts"], asset_type)
else:
console.print(
create_question_box(
"Step 4: Analysts Team", "Select your LLM analyst agents for the analysis"
)
)
selected_analysts = select_analysts(asset_type, prefs.get("analysts"))
console.print(
f"[green]Selected analysts:[/green] {', '.join(analyst.value for analyst in selected_analysts)}"
)
@@ -151,10 +233,7 @@ def _prompt_selections(prefs):
# 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:
if depth_from_env():
selected_research_depth = DEFAULT_CONFIG["max_debate_rounds"]
console.print(
f"[green]✓ Research depth from environment:[/green] "
@@ -181,8 +260,6 @@ def _prompt_selections(prefs):
)
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(
@@ -219,10 +296,8 @@ def _prompt_selections(prefs):
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)
_check_tier_providers(selected_llm_provider, backend_url)
# 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"):
@@ -266,7 +341,7 @@ def _prompt_selections(prefs):
"Gemini thinking mode", "Step 8: Thinking Mode",
"Configure Gemini thinking mode", ask_gemini_thinking_config,
)
elif provider_lower == "openai":
elif provider_lower in REASONING_EFFORT_PROVIDERS:
reasoning_effort = thinking_value_or_prompt(
"TRADINGAGENTS_OPENAI_REASONING_EFFORT", "openai_reasoning_effort",
"Reasoning effort", "Step 8: Reasoning Effort",
@@ -303,13 +378,6 @@ def get_analysis_date():
"", 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]"
)
return parse_analysis_date(date_str)
except ValueError as exc:
console.print(f"[red]Error: {exc}[/red]")
+220
View File
@@ -0,0 +1,220 @@
"""What's new, for the person at the terminal: a newer release, and notices from Tauric Research.
At most once a day a background thread asks GitHub for the latest release and
the announcements server for notices, and writes the answers to a small cache.
The lines shown at start-up are read from that cache, so a run never waits on
the network and news shows up on the next run. Nothing identifying is sent.
Unattended, scripted and CI runs contact no server; set
TRADINGAGENTS_NO_UPDATE_CHECK=1 to turn the check off.
"""
import importlib.metadata
import json
import os
import re
import shlex
import sys
import threading
import time
from collections.abc import Callable
from datetime import UTC, date, datetime
from pathlib import Path
from urllib.parse import unquote, urlparse
import requests
from packaging.version import InvalidVersion, Version
from tradingagents.dataflows.files import replace_file
from tradingagents.default_config import _TRADINGAGENTS_HOME
RELEASES_URL = "https://api.github.com/repos/TauricResearch/TradingAgents/releases/latest"
NOTICES_URL = "https://api.tauric.ai/v1/announcements"
CACHE = Path(_TRADINGAGENTS_HOME) / "update_check.json"
CHECK_EVERY = 24 * 3600
TIMEOUT = 2.0
SUMMARY_LIMIT = 160
OPT_OUT = "TRADINGAGENTS_NO_UPDATE_CHECK"
# Control characters, C0 and C1, read as spaces; invisible spaces and direction marks are dropped.
CONTROL = re.compile(r"[\x00-\x1f\x7f-\x9f]")
INVISIBLE = re.compile(r"[\u061c\u200b\u200e\u200f\u202a-\u202e\u2066-\u2069\ufeff]")
DATE = re.compile(r"\d{4}-\d{2}-\d{2}")
def enabled() -> bool:
"""Whether a person is at the terminal and has not turned the check off."""
at_a_terminal = bool(sys.stdin and sys.stdin.isatty() and sys.stdout and sys.stdout.isatty())
return at_a_terminal and not os.environ.get("CI") and not os.environ.get(OPT_OUT)
# --- the cache and the check -------------------------------------------------------
def read_cache() -> dict:
"""The cache, keeping only fields of the shape this version writes."""
try:
data = json.loads(CACHE.read_text(encoding="utf-8"))
except (OSError, ValueError):
return {}
if not isinstance(data, dict):
return {}
shapes = {"checked_at": (int, float), "latest": dict, "notices": list}
return {key: data[key] for key, shape in shapes.items() if isinstance(data.get(key), shape)}
def due(cache: dict, now: float) -> bool:
checked = cache.get("checked_at")
return not isinstance(checked, (int, float)) or not 0 <= now - checked < CHECK_EVERY
def summary_of(body: str) -> str:
"""The release's one-line summary: its first paragraph on one line (sanitised when shown)."""
first = re.split(r"\n\s*\n", (body or "").strip(), maxsplit=1)[0]
text = " ".join(first.split())
if len(text) > SUMMARY_LIMIT:
text = text[: SUMMARY_LIMIT - 3].rsplit(" ", 1)[0] + "..."
return text
def parse_notices(payload) -> list | None:
"""The targeted notices in an announcements answer; None when it has no notices list."""
notices = payload.get("notices") if isinstance(payload, dict) else None
return notices if isinstance(notices, list) else None
def _get_json(url: str):
response = requests.get(url, timeout=TIMEOUT)
return response.json() if response.ok else None
def refresh(now: float | None = None) -> None:
"""Ask for the latest release and notices and record the answers. Never raises or prints;
a failed check keeps what was known and is not retried for a day."""
now = time.time() if now is None else now
cache = read_cache()
cache["checked_at"] = now
try:
release = _get_json(RELEASES_URL)
if isinstance(release, dict) and release.get("tag_name"):
cache["latest"] = {
"version": str(release["tag_name"]).removeprefix("v"),
"url": release.get("html_url"),
"summary": summary_of(release.get("body") or ""),
}
except Exception:
pass
try:
notices = parse_notices(_get_json(NOTICES_URL))
if notices is not None:
cache["notices"] = notices
except Exception:
pass
try:
CACHE.parent.mkdir(parents=True, exist_ok=True)
replace_file(CACHE, lambda temp: Path(temp).write_text(json.dumps(cache), encoding="utf-8"))
except Exception:
pass
def start_background_refresh() -> None:
"""Refresh the cache in a daemon thread when a check is due."""
if due(read_cache(), time.time()):
threading.Thread(target=refresh, name="tradingagents-update-check", daemon=True).start()
# --- what is shown ---------------------------------------------------------------
def _version(text) -> Version | None:
try:
return Version(str(text))
except (InvalidVersion, TypeError):
return None
def _plain(text) -> str:
return " ".join(CONTROL.sub(" ", INVISIBLE.sub("", str(text or ""))).split())
def _applies(notice: dict, running: Version, today: date) -> bool:
"""Whether a notice is for this version and unexpired; a bound or date that cannot be read
keeps it hidden. A notice is shown through its ``expires`` date (UTC)."""
low, high = notice.get("min_version"), notice.get("max_version")
if low is not None and ((floor := _version(low)) is None or running < floor):
return False
if high is not None and ((ceiling := _version(high)) is None or running > ceiling):
return False
expires = notice.get("expires")
if expires is None:
return True
try:
return isinstance(expires, str) and bool(DATE.fullmatch(expires)) and date.fromisoformat(expires) >= today
except ValueError:
return False
def messages(cache: dict, running: str, upgrade: Callable[[], str | None] = lambda: None) -> list[str]:
"""The lines to show: a newer release with its upgrade command (``upgrade()``, asked only
when there is one), then the notices for this version."""
current = _version(running)
if current is None:
return []
lines = []
latest = cache.get("latest") or {}
newest = _version(latest.get("version"))
if newest is not None and newest > current:
lines.append(f"TradingAgents {_plain(latest['version'])} is available (you have {_plain(running)}): "
f"{_plain(latest.get('summary'))}")
if latest.get("url"):
lines.append(_plain(latest["url"]))
command = upgrade()
if command:
lines.append(f"Upgrade: {_plain(command)}")
today = datetime.now(UTC).date()
for notice in cache.get("notices") or []:
if not (isinstance(notice, dict) and isinstance(notice.get("message"), str) and _plain(notice["message"])
and _applies(notice, current, today)):
continue
url = notice.get("url")
link = url if isinstance(url, str) and url.lower().startswith(("http://", "https://")) else None
lines.append(_plain(notice["message"]) + (f" {_plain(link)}" if link else ""))
return lines
def upgrade_command(dist=None) -> str | None:
"""The command that upgrades this install, from how pip or uv recorded it; None when unsure."""
if os.environ.get("TRADINGAGENTS_IN_DOCKER"):
return "git pull && docker compose build (on the host)"
if os.name == "nt": # the commands below are POSIX shell
return None
try:
dist = dist or importlib.metadata.distribution("tradingagents")
direct = json.loads(dist.read_text("direct_url.json") or "null")
installer = (dist.read_text("INSTALLER") or "").strip()
except (importlib.metadata.PackageNotFoundError, OSError, ValueError):
return None
if not isinstance(direct, dict) or not direct.get("url"):
return None
python = shlex.quote(sys.executable)
install = f"uv pip install --python {python}" if installer == "uv" else f"{python} -m pip install"
if "vcs_info" in direct:
return f"{install} -U git+{direct['url']}"
parsed = urlparse(direct["url"])
if parsed.scheme != "file":
return None
clone = Path(unquote(parsed.path))
if not (clone / ".git").exists():
return None
editable = (direct.get("dir_info") or {}).get("editable")
target = shlex.quote(str(clone))
return f"git -C {target} pull && {install} {'-e ' if editable else ''}{target}"
def show(console) -> None:
"""Print what's new from the cache, under the welcome panel."""
from rich.panel import Panel
from rich.text import Text
from tradingagents import __version__
lines = messages(read_cache(), running=__version__, upgrade=upgrade_command)
if lines:
console.print(Panel(Text("\n".join(lines)), border_style="cyan", padding=(1, 2), title="What's new"))
console.print()
+2 -2
View File
@@ -4,7 +4,7 @@ services:
env_file:
- .env
volumes:
- tradingagents_data:/home/appuser/.tradingagents
- ${TRADINGAGENTS_DATA_DIR:-tradingagents_data}:/home/appuser/.tradingagents
tty: true
stdin_open: true
@@ -23,7 +23,7 @@ services:
- TRADINGAGENTS_LLM_PROVIDER=ollama
- OLLAMA_BASE_URL=http://ollama:11434/v1
volumes:
- tradingagents_data:/home/appuser/.tradingagents
- ${TRADINGAGENTS_DATA_DIR:-tradingagents_data}:/home/appuser/.tradingagents
depends_on:
- ollama
tty: true
-2
View File
@@ -14,5 +14,3 @@ ta = TradingAgentsGraph(debug=True, config=config)
# forward propagate
_, decision = ta.propagate("NVDA", "2026-09-01")
print(decision)
# Memorize mistakes and reflect
+22 -15
View File
@@ -4,18 +4,21 @@ build-backend = "setuptools.build_meta"
[project]
name = "tradingagents"
version = "0.5.1"
dynamic = ["version"]
description = "TradingAgents: Multi-Agents LLM Financial Trading Framework"
readme = "README.md"
requires-python = ">=3.10"
requires-python = ">=3.11"
dependencies = [
"langchain-core>=0.3.81",
"langchain-anthropic>=0.3.15",
"langchain-google-genai>=4.0.0",
"langchain-openai>=0.3.23",
"langgraph>=0.4.8",
"langgraph-checkpoint-sqlite>=2.0.0",
"pandas>=2.3.0",
"cryptography>=42.0",
"langchain-core>=1.6.5",
"langchain-anthropic>=1.7.4",
"langchain-google-genai>=4.4.0",
"langchain-openai>=1.6.6",
"langgraph>=1.2.12",
"langgraph-checkpoint-sqlite>=3.1.1",
"markdown-it-py>=4.0",
"packaging>=24.0",
"pandas>=3.0.6",
"python-dotenv>=1.0.0",
"pytz>=2025.2",
"questionary>=2.1.0",
@@ -24,36 +27,40 @@ dependencies = [
"typer>=0.21.0",
"stockstats>=0.6.5",
"typing-extensions>=4.14.0",
"yfinance>=1.4.1",
"yfinance>=1.7.0",
]
[project.optional-dependencies]
dev = [
"ruff>=0.15",
"ruff>=0.16",
"pytest>=8.0",
"pytest-subtests>=0.13",
]
# Amazon Bedrock support (AWS SigV4 auth + boto3). Optional so the core install
# stays lean: pip install "tradingagents[bedrock]".
bedrock = [
"langchain-aws>=1.5.0",
"langchain-aws>=1.7.9",
]
[project.scripts]
tradingagents = "cli.main:app"
[tool.setuptools.dynamic]
version = {attr = "tradingagents.__version__"}
[tool.setuptools.packages.find]
include = ["tradingagents*", "cli*"]
[tool.setuptools.package-data]
cli = ["static/*"]
tradingagents = ["assets/*.svg"]
[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-ra --strict-markers"
addopts = "-ra --strict-markers -m \"not integration\""
markers = [
"unit: fast isolated unit tests",
"integration: tests requiring external services",
"integration: tests requiring external services; run only when asked for, with -m integration",
"smoke: quick sanity-check tests",
]
filterwarnings = [
@@ -62,7 +69,7 @@ filterwarnings = [
[tool.ruff]
line-length = 100
target-version = "py310"
target-version = "py311"
extend-exclude = ["results"]
[tool.ruff.lint]
+2
View File
@@ -1 +1,3 @@
# The dependencies are declared in pyproject.toml. From the repository root this
# installs TradingAgents with them, the same as `pip install .`
.
+47 -2
View File
@@ -27,9 +27,33 @@ def _blank_settings_overlay():
_blank_settings_overlay()
def _own_file_locations():
"""Keep the suite's results, cache and memory log in a directory of its own.
Set before the package is imported, whose defaults put them in the user's
home: a test reading the user's cache would see what their runs fetched.
"""
import tempfile
home = tempfile.mkdtemp(prefix="tradingagents-tests-")
os.environ["TRADINGAGENTS_RESULTS_DIR"] = os.path.join(home, "logs")
os.environ["TRADINGAGENTS_CACHE_DIR"] = os.path.join(home, "cache")
os.environ["TRADINGAGENTS_MEMORY_LOG_PATH"] = os.path.join(home, "memory", "trading_memory.md")
_own_file_locations()
def pytest_configure(config):
for marker in ("unit", "integration", "smoke"):
config.addinivalue_line("markers", f"{marker}: {marker}-level tests")
# yfinance caches each symbol's time zone on disk, in the home directory
# by default; the suite keeps it in a directory of its own.
import tempfile
import yfinance
yfinance.set_tz_cache_location(tempfile.mkdtemp(prefix="tradingagents-tests-yf-"))
@pytest.fixture(autouse=True)
@@ -38,11 +62,32 @@ def _no_network(request, monkeypatch):
if request.node.get_closest_marker("integration"):
return
def refuse(self, address):
raise OSError(f"test tried to reach the network: {address}")
def refuse(*args, **kwargs):
raise OSError(f"test tried to reach the network: {args[1:] or kwargs}")
monkeypatch.setattr(socket.socket, "connect", refuse)
monkeypatch.setattr(socket.socket, "connect_ex", refuse)
monkeypatch.setattr(socket, "getaddrinfo", lambda *a, **k: refuse(None, *a))
# yfinance's HTTP client is libcurl, which never touches Python's sockets.
from curl_cffi import requests as curl_requests
monkeypatch.setattr(curl_requests.Session, "request", refuse)
monkeypatch.setattr(curl_requests.AsyncSession, "request", refuse)
@pytest.fixture(autouse=True)
def _at_a_terminal(monkeypatch):
"""Tests of the interactive steps run as if at a terminal; pytest's stdin is
not one. A test of an unattended run sets isatty to False itself."""
import sys
monkeypatch.setattr(sys.stdin, "isatty", lambda: True)
@pytest.fixture(autouse=True)
def _own_cli_prefs(tmp_path, monkeypatch):
"""The CLI keeps the last run's selections in the user's home; tests keep theirs apart."""
monkeypatch.setattr("cli.prefs._PREFS_PATH", tmp_path / "cli_prefs.json")
_API_KEY_ENV_VARS = (
+40 -19
View File
@@ -64,6 +64,45 @@ def test_invalid_key_not_mislabeled_as_rate_limit(monkeypatch):
av._make_api_request("TIME_SERIES_DAILY", {"symbol": "AAPL"})
@pytest.mark.unit
def test_a_rejected_request_is_unavailable_not_data(monkeypatch):
"""Alpha Vantage answers a call it rejects with {"Error Message": ...}, for an
unknown symbol and for a malformed call alike, so it says nothing about the
instrument; served as data it reads as a one-line CSV or as "no data" (#1442)."""
from tradingagents.dataflows import router
from tradingagents.dataflows.config import set_config
from tradingagents.dataflows.errors import VendorUnavailableError
monkeypatch.setenv("ALPHA_VANTAGE_API_KEY", "k-secret")
body = '{"Error Message": "Invalid API call. Please retry or visit the documentation for TIME_SERIES_DAILY."}'
monkeypatch.setattr(net.requests, "get", _patched_get(body))
with pytest.raises(VendorUnavailableError) as raised:
av._make_api_request("TIME_SERIES_DAILY", {"symbol": "ZZZZ"})
assert "k-secret" not in str(raised.value)
set_config({"data_vendors": {"core_stock_apis": "alpha_vantage"}})
out = router.route_to_vendor("get_stock_data", "ZZZZ", "2026-01-02", "2026-01-09")
assert out.startswith("DATA_UNAVAILABLE"), out
@pytest.mark.unit
@pytest.mark.parametrize("body", [
'{"Note": "Thank you for using key k-secret. API call frequency is 5 calls per minute."}',
'{"Information": "the apikey k-secret is invalid or missing."}',
])
def test_the_key_never_reaches_an_error_message(monkeypatch, body):
"""Alpha Vantage can echo the key in its notices; error text reaches logs and reports."""
from tradingagents.dataflows.errors import VendorError
monkeypatch.setenv("ALPHA_VANTAGE_API_KEY", "k-secret")
monkeypatch.setattr(net.requests, "get", _patched_get(body))
with pytest.raises(VendorError) as raised:
av._make_api_request("TIME_SERIES_DAILY", {"symbol": "AAPL"})
assert "k-secret" not in str(raised.value)
_FUNDAMENTALS_JSON = json.dumps({
"symbol": "AAPL",
"annualReports": [
@@ -77,32 +116,14 @@ _FUNDAMENTALS_JSON = json.dumps({
})
@pytest.mark.unit
def test_fundamentals_look_ahead_filter_runs_on_json_string(monkeypatch):
# #1115: the payload arrives as a JSON *string*; the old dict-only guard let
# future-dated fiscal periods leak into historical runs.
monkeypatch.setattr(avf, "_make_api_request", lambda fn, params: _FUNDAMENTALS_JSON)
out = avf.get_balance_sheet("AAPL", curr_date="2024-01-01")
assert isinstance(out, str) # callers still receive a str
parsed = json.loads(out)
assert [r["fiscalDateEnding"] for r in parsed["annualReports"]] == ["2023-12-31"]
assert [r["fiscalDateEnding"] for r in parsed["quarterlyReports"]] == ["2023-09-30"]
@pytest.mark.unit
def test_fundamentals_no_curr_date_passes_through(monkeypatch):
monkeypatch.setattr(avf, "_make_api_request", lambda fn, params: _FUNDAMENTALS_JSON)
assert avf.get_income_statement("AAPL") == _FUNDAMENTALS_JSON
@pytest.mark.unit
def test_fundamentals_non_json_body_unchanged(monkeypatch):
monkeypatch.setattr(avf, "_make_api_request", lambda fn, params: "not-json")
assert avf.get_cashflow("AAPL", curr_date="2024-01-01") == "not-json"
# ---------------------------------------------------------------------------
# Date trim (see the rationale on the unguarded trim in alpha_vantage_common)
# Date trim (see the rationale on the unguarded trim in alpha_vantage.common)
# ---------------------------------------------------------------------------
_DAILY_CSV = (
+2 -2
View File
@@ -11,8 +11,8 @@ class AnalystExecutionPlanTests(unittest.TestCase):
self.assertEqual([spec.key for spec in plan.specs], ["news", "market"])
self.assertEqual(plan.specs[0].agent_node, "News Analyst")
self.assertEqual(plan.specs[0].tool_node, "tools_news")
self.assertEqual(plan.specs[0].clear_node, "Msg Clear News")
self.assertEqual(plan.specs[0].report_key, "news_report")
self.assertFalse(hasattr(plan.specs[0], "clear_node"))
def test_rejects_unknown_analyst_keys(self):
with self.assertRaises(ValueError):
+3 -1
View File
@@ -28,6 +28,8 @@ class TestEffortGate:
"claude-haiku-4-5", "claude-haiku-5-0", "claude-haiku-4-7-preview",
# Sonnet 4.5 (and earlier) 400 on effort — only Sonnet 4.6+ supports it.
"claude-sonnet-4-5", "claude-sonnet-4-0",
# A dated snapshot's date is not its minor version (#1585).
"claude-sonnet-4-20250514", "claude-opus-4-20250514", "claude-sonnet-4-5-20250929",
],
)
def test_unsupported_models_do_not_receive_effort(self, monkeypatch, model):
@@ -39,7 +41,7 @@ class TestEffortGate:
"model",
[
"claude-opus-4-5", "claude-opus-4-6", "claude-opus-4-7",
"claude-sonnet-4-6",
"claude-sonnet-4-6", "claude-opus-4-5-20251101",
],
)
def test_current_opus_and_sonnet_receive_effort(self, monkeypatch, model):
+3 -5
View File
@@ -67,12 +67,10 @@ def test_case_insensitive_lookup():
@pytest.fixture
def prompts(monkeypatch):
"""Import cli.prompts with a fresh environment so module-level state is consistent."""
import importlib
def prompts():
"""cli.prompts, which reads the environment when it is called."""
import cli.prompts as prompts_module
return importlib.reload(prompts_module)
return prompts_module
def test_ensure_api_key_returns_existing(monkeypatch, prompts):
+28
View File
@@ -0,0 +1,28 @@
"""Azure OpenAI takes the run's settings like every other provider."""
from __future__ import annotations
import pytest
from tradingagents.llm_clients.factory import create_llm_client
@pytest.fixture(autouse=True)
def _azure_env(monkeypatch):
monkeypatch.setenv("AZURE_OPENAI_API_KEY", "test-key")
monkeypatch.setenv("AZURE_OPENAI_ENDPOINT", "https://from-env.openai.azure.com/")
monkeypatch.setenv("OPENAI_API_VERSION", "2025-03-01-preview")
monkeypatch.delenv("AZURE_OPENAI_DEPLOYMENT_NAME", raising=False)
@pytest.mark.unit
def test_the_output_token_cap_reaches_the_deployment():
llm = create_llm_client("azure", "gpt-5.5", max_tokens=1234).get_llm()
assert llm.max_tokens == 1234
@pytest.mark.unit
def test_an_explicit_endpoint_wins_over_the_environment():
llm = create_llm_client("azure", "gpt-5.5", base_url="https://deep.openai.azure.com/").get_llm()
assert llm.azure_endpoint == "https://deep.openai.azure.com/"
assert create_llm_client("azure", "gpt-5.5").get_llm().azure_endpoint == "https://from-env.openai.azure.com/"
+93 -3
View File
@@ -1,4 +1,4 @@
"""Backtesting: many single-shot decisions, scored by the decision log.
"""Backtesting: many single-shot decisions, scored by the memory log.
A run already records its rating and later settles it with realized and alpha
return against the regional benchmark. A backtest is that machinery over a grid
@@ -11,7 +11,8 @@ from __future__ import annotations
import pytest
from tradingagents.backtest import iter_grid, run_backtest, summarize
from tradingagents.decision_log import TradingMemoryLog
from tradingagents.memory import TradingMemoryLog
from tradingagents.memory.settlement import Settlement
DECISION = "Rating: Buy\n\nbuy it"
@@ -58,6 +59,7 @@ class _FakeGraph:
def settle_pending(self, ticker):
self.settled.append(ticker)
return Settlement()
@pytest.fixture(autouse=True)
@@ -76,7 +78,7 @@ def _config(tmp_path):
@pytest.mark.unit
def test_the_live_decision_log_is_never_written(tmp_path):
def test_the_live_memory_log_is_never_written(tmp_path):
config = _config(tmp_path)
result = run_backtest(["NVDA"], ["2026-01-05", "2026-01-12"], config)
@@ -153,6 +155,23 @@ def test_the_analyst_set_under_test_is_the_one_that_runs(tmp_path):
assert _FakeGraph.instances[-1].analysts == ["market", "news"]
@pytest.mark.unit
def test_sweeps_started_in_the_same_second_get_their_own_runs(tmp_path, monkeypatch):
import tradingagents.backtest as backtest
class _Frozen(backtest.datetime):
@classmethod
def now(cls, tz=None):
return cls(2026, 1, 20, 9, 30, 0)
monkeypatch.setattr(backtest, "datetime", _Frozen)
first = run_backtest(["NVDA"], ["2026-01-05"], _config(tmp_path))
second = run_backtest(["NVDA"], ["2026-01-05"], _config(tmp_path))
assert first.run_id == "20260120_093000" and second.run_id == "20260120_093000_2"
assert first.cells_run == second.cells_run == 1
@pytest.mark.unit
def test_a_run_id_cannot_escape_the_results_directory(tmp_path):
"""run_id becomes a path segment, so it is validated like a ticker is."""
@@ -172,6 +191,7 @@ def test_a_failed_settlement_does_not_lose_the_remaining_tickers(tmp_path, monke
if ticker == "NVDA":
raise RuntimeError("reflector timed out")
settled.append(ticker)
return Settlement()
monkeypatch.setattr(_FakeGraph, "settle_pending", _settle, raising=False)
result = run_backtest(["NVDA", "AAPL"], ["2026-01-05"], _config(tmp_path))
@@ -181,6 +201,46 @@ def test_a_failed_settlement_does_not_lose_the_remaining_tickers(tmp_path, monke
assert result.settlement_failures == [("NVDA", "reflector timed out")]
@pytest.mark.unit
@pytest.mark.parametrize("failure", ["prices", "reflection"])
def test_handled_settlement_failures_reach_the_backtest_result(tmp_path, monkeypatch, failure):
from types import SimpleNamespace
from tradingagents.memory import settlement
def returns(ticker, *args, **kwargs):
if ticker == "AAPL":
return None, None, None, None # an incomplete window is not a failure
if failure == "prices":
raise RuntimeError("vendor unavailable")
return 0.1, 0.02, 5, "2026-02-01"
def reflect(**kwargs):
raise RuntimeError("reflector timed out")
def settle(self, ticker):
self.settled.append(ticker)
return settlement.settle_pending(
ticker, self.memory_log, SimpleNamespace(reflect_on_final_decision=reflect), self.config,
)
monkeypatch.setattr(settlement, "fetch_returns", returns)
monkeypatch.setattr(_FakeGraph, "settle_pending", settle)
result = run_backtest(
["NVDA", "AAPL"], ["2026-01-05", "2026-01-12"], _config(tmp_path),
)
reason = ("prices unavailable: vendor unavailable" if failure == "prices"
else "reflection failed: reflector timed out")
assert result.settlement_failures == [
("NVDA", f"2026-01-05: {reason}"),
("NVDA", f"2026-01-12: {reason}"),
]
assert _FakeGraph.instances[-1].settled == ["NVDA", "AAPL"]
assert result.cells_run == 4 and not result.failures
assert len(_FakeGraph.instances[-1].memory_log.get_pending_entries()) == 4
@pytest.mark.unit
def test_pending_note_appears_only_when_something_is_pending(tmp_path):
settled = [("NVDA", "2026-01-05", DECISION, (0.1, 0.05))]
@@ -274,3 +334,33 @@ def test_a_result_whose_cells_all_failed_summarizes_as_empty(tmp_path):
result = BacktestResult(run_id="r", log_path=tmp_path / "never-written.md")
assert summarize(result).resolved == 0
@pytest.mark.unit
def test_progress_is_reported_before_each_cell(tmp_path):
seen = []
run_backtest(["NVDA", "AAPL"], ["2026-01-05", "2026-01-12"], _config(tmp_path),
progress=lambda done, total, ticker, date: seen.append((done, total, ticker, date)))
assert seen == [(1, 4, "NVDA", "2026-01-05"), (2, 4, "NVDA", "2026-01-12"),
(3, 4, "AAPL", "2026-01-05"), (4, 4, "AAPL", "2026-01-12")]
@pytest.mark.unit
def test_a_resumed_sweep_reports_only_the_cells_it_runs(tmp_path):
first = run_backtest(["NVDA"], ["2026-01-05"], _config(tmp_path))
seen = []
run_backtest(["NVDA"], ["2026-01-05", "2026-01-12"], _config(tmp_path), run_id=first.run_id,
progress=lambda done, total, ticker, date: seen.append((done, total, date)))
assert seen == [(1, 1, "2026-01-12")]
@pytest.mark.unit
def test_a_ticker_or_date_given_twice_runs_and_settles_once(tmp_path):
run_backtest(["NVDA", "NVDA"], ["2026-01-05", "2026-01-05"], _config(tmp_path))
graph = _FakeGraph.instances[-1]
assert graph.calls == [("NVDA", "2026-01-05")]
assert graph.settled == ["NVDA"]
+164
View File
@@ -0,0 +1,164 @@
"""Cache files are replaced whole: a reader never sees a half-written file, and
concurrent writers (tool calls run in parallel) never share a temp file."""
import os
from pathlib import Path
import pandas as pd
import pytest
from tradingagents.dataflows import files
from tradingagents.dataflows.vendors import sec_edgar
from tradingagents.dataflows.vendors.yahoo import ohlcv
def _recording_replace(monkeypatch):
moves = []
real = os.replace
def replace(src, dst):
moves.append((Path(src), Path(dst)))
real(src, dst)
monkeypatch.setattr(os, "replace", replace)
return moves
@pytest.mark.unit
def test_sec_edgar_writers_never_share_a_temp_file(monkeypatch, tmp_path):
monkeypatch.setattr(sec_edgar, "get_config", lambda: {"data_cache_dir": str(tmp_path)})
monkeypatch.setattr(sec_edgar, "_fetch_json", lambda url: {"url": url})
moves = _recording_replace(monkeypatch)
sec_edgar._cached_json("https://example/a", "facts.json")
(tmp_path / "sec_edgar" / "facts.json").unlink()
sec_edgar._cached_json("https://example/a", "facts.json")
temps = [src for src, _ in moves]
assert len(set(temps)) == 2
assert all(src.parent == dst.parent for src, dst in moves)
@pytest.mark.unit
def test_the_price_cache_is_replaced_whole(monkeypatch, tmp_path):
frame = pd.DataFrame({"Date": pd.bdate_range("2026-01-02", periods=3), "Open": 1.0, "High": 1.0,
"Low": 1.0, "Close": 1.0, "Volume": 1})
monkeypatch.setattr(ohlcv, "get_config", lambda: {"data_cache_dir": str(tmp_path)})
monkeypatch.setattr(ohlcv.yf, "Ticker", lambda s: type("T", (), {"history": lambda self, **k: frame.set_index("Date")})())
moves = _recording_replace(monkeypatch)
ohlcv.load_ohlcv("AAPL", "2026-01-06")
assert [dst.name for _, dst in moves] == ["AAPL-YFin-data.csv"]
assert moves[0][0].parent == tmp_path and moves[0][0] != moves[0][1]
assert not list(tmp_path.glob("*.tmp*"))
@pytest.mark.unit
def test_a_replaced_file_keeps_the_usual_permissions(tmp_path):
from tradingagents.dataflows.files import replace_file
plain = tmp_path / "plain.txt"
plain.write_text("x")
replaced = tmp_path / "replaced.txt"
replace_file(replaced, lambda temp: Path(temp).write_text("x"))
assert replaced.stat().st_mode & 0o777 == plain.stat().st_mode & 0o777
@pytest.mark.unit
def test_a_file_held_open_elsewhere_keeps_its_old_content(monkeypatch, tmp_path):
"""On Windows a file another reader has open cannot be replaced; the cache
write is skipped rather than failing the call that produced the data."""
from tradingagents.dataflows import files
target = tmp_path / "cache.csv"
target.write_text("old")
def locked(src, dst):
raise PermissionError("in use")
monkeypatch.setattr(files.os, "replace", locked)
files.replace_file(target, lambda temp: Path(temp).write_text("new"))
assert target.read_text() == "old"
assert list(tmp_path.iterdir()) == [target]
def _fake_msvcrt(results):
"""msvcrt whose locking() raises the next error in ``results``, or succeeds on None."""
import types
calls = []
def locking(fd, mode, nbytes):
calls.append(mode)
if mode in (1, 2) and results: # LK_NBLCK, LK_LOCK; unlocking always succeeds
error = results.pop(0)
if error is not None:
raise error
return types.SimpleNamespace(LK_LOCK=2, LK_NBLCK=1, LK_UNLCK=0, locking=locking), calls
@pytest.mark.unit
def test_on_windows_the_lock_is_waited_for_while_another_writer_holds_it(tmp_path, monkeypatch):
import errno
import sys
fake, calls = _fake_msvcrt([OSError(errno.EDEADLK, "held"), None])
monkeypatch.setitem(sys.modules, "msvcrt", fake)
with open(tmp_path / "log.md.lock", "a+b") as handle, files._hold_windows(handle):
pass
assert calls == [2, 2, 0]
@pytest.mark.unit
def test_on_windows_a_lock_that_cannot_be_taken_is_reported_not_retried_forever(tmp_path, monkeypatch):
import errno
import sys
fake, _ = _fake_msvcrt([OSError(errno.EINVAL, "bad handle")] * 3)
monkeypatch.setitem(sys.modules, "msvcrt", fake)
with pytest.raises(OSError, match="bad handle"), open(tmp_path / "log.md.lock", "a+b") as handle, \
files._hold_windows(handle):
pass
@pytest.mark.unit
def test_a_lock_held_elsewhere_is_reported_when_not_waiting(tmp_path):
import threading
path = tmp_path / "log.md"
held, release = threading.Event(), threading.Event()
def holder():
with files.locked(path):
held.set()
release.wait(5)
worker = threading.Thread(target=holder)
worker.start()
held.wait(5)
with files.locked(path, wait=False) as acquired:
assert acquired is False
release.set()
worker.join()
with files.locked(path, wait=False) as acquired:
assert acquired is True
@pytest.mark.unit
def test_on_windows_a_held_lock_is_reported_when_not_waiting(tmp_path, monkeypatch):
import errno
import sys
fake, calls = _fake_msvcrt([OSError(errno.EACCES, "held")])
monkeypatch.setitem(sys.modules, "msvcrt", fake)
with open(tmp_path / "log.md.lock", "a+b") as handle, files._hold_windows(handle, wait=False) as acquired:
assert acquired is False
assert calls == [1] # one try, no unlock of a lock it never held
+18
View File
@@ -25,6 +25,17 @@ class TestExactIdMatches:
assert caps.supports_tool_choice is False
assert caps.requires_reasoning_content_roundtrip is True
def test_deepseek_flash_alias_rejects_tool_choice(self):
"""``deepseek-flash`` is what the model picker offers for V4.1 Flash.
It was falling through to _DEFAULT (tool_choice on), so every
structured-output call 400'd with "Thinking mode does not support
this tool_choice" and burned a retry as free text.
"""
caps = get_capabilities("deepseek-flash")
assert caps.supports_tool_choice is False
assert caps.requires_reasoning_content_roundtrip is True
def test_deepseek_v4_pro_rejects_tool_choice(self):
caps = get_capabilities("deepseek-v4-pro")
assert caps.supports_tool_choice is False
@@ -48,6 +59,10 @@ class TestPatternMatches:
caps = get_capabilities("deepseek-reasoner-pro")
assert caps.supports_tool_choice is False
def test_future_flash_variant_inherits_thinking_quirks(self):
caps = get_capabilities("deepseek-flash-lite")
assert caps.supports_tool_choice is False
def test_minimax_m3_inherits_thinking_quirks(self):
caps = get_capabilities("MiniMax-M3")
assert caps.supports_tool_choice is False
@@ -128,6 +143,9 @@ class TestOpenRouterDeepSeekNamespace:
def test_prefixed_reasoner_suppresses_tool_choice(self):
assert get_capabilities("deepseek/deepseek-reasoner").supports_tool_choice is False
def test_prefixed_flash_alias_suppresses_tool_choice(self):
assert get_capabilities("deepseek/deepseek-flash").supports_tool_choice is False
def test_prefixed_chat_selects_deepseek_chat_not_default(self):
# Must resolve to _DEEPSEEK_CHAT, not _DEFAULT: supports_json_schema=False
# is what distinguishes them (both keep tool_choice).
+427
View File
@@ -0,0 +1,427 @@
"""Sign in with ChatGPT: the sign-in is checked, kept private, renewed once, and revoked.
OpenAI is replaced by a fake that signs ID tokens with a key made here, so every
check of the sign-in (signature, issuer, audience, nonce, plan scope) runs for real.
"""
import base64
import json
import os
import socket
import stat
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
import pytest
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding, rsa
from tradingagents.llm_clients import chatgpt_auth as auth
# The suite refuses all connections; the loopback test lets 127.0.0.1 through only.
_CONNECT, _GETADDRINFO = socket.socket.connect, socket.getaddrinfo
KEY = rsa.generate_private_key(public_exponent=65537, key_size=2048)
CLIENT = "oaiapp_test"
SUBJECT = "user-123"
def _b64(raw: bytes) -> str:
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()
def _id_token(key=KEY, **claims) -> str:
payload = {"iss": auth.ISSUER, "aud": CLIENT, "sub": SUBJECT, "email": "a@example.com",
"exp": time.time() + 3600, **claims}
head = _b64(json.dumps({"alg": "RS256", "kid": "k1"}).encode())
body = _b64(json.dumps(payload).encode())
signature = key.sign(f"{head}.{body}".encode(), padding.PKCS1v15(), hashes.SHA256())
return f"{head}.{body}.{_b64(signature)}"
def _jwks():
numbers = KEY.public_key().public_numbers()
return {"keys": [{"kid": "k1", "kty": "RSA", "e": _b64(numbers.e.to_bytes(3, "big")),
"n": _b64(numbers.n.to_bytes(256, "big"))}]}
class _Response:
def __init__(self, body, status=200):
self.body, self.status_code = body, status
def json(self):
return self.body
class FakeOpenAI:
"""Answers the JWKS, token and revoke endpoints and records what was sent."""
def __init__(self, token_body=None, status=200):
self.posts = []
self.token_body = token_body
self.status = status
self.lock = threading.Lock()
self.keys_reachable = True
self.revoke_status = 200
self.post_error = None
def get(self, url, timeout):
assert url == auth.JWKS_URL
if not self.keys_reachable:
raise auth.requests.ConnectionError("down")
return _Response(_jwks())
def post(self, url, timeout, data):
with self.lock:
self.posts.append((url, data))
if url == auth.REVOKE_URL:
return _Response({}, self.revoke_status)
if self.post_error is not None:
raise self.post_error
time.sleep(0.05) # let a racing refresher reach the lock
body = self.token_body(data) if callable(self.token_body) else self.token_body
return _Response(body, self.status)
@pytest.fixture
def home(tmp_path, monkeypatch):
monkeypatch.setattr(auth, "AUTH_FILE", tmp_path / "home" / "chatgpt-auth.json")
monkeypatch.setattr(auth, "_retry_after", 0.0)
return tmp_path
@pytest.fixture
def openai(monkeypatch):
fake = FakeOpenAI()
monkeypatch.setattr(auth.requests, "get", fake.get)
monkeypatch.setattr(auth.requests, "post", fake.post)
return fake
def _signed_in(expires_at, earliest=None, refresh_token="r1"):
auth.AUTH_FILE.parent.mkdir(parents=True, exist_ok=True)
auth._write({"host_id": "urn:uuid:h", "account": {"client_id": CLIENT, "email": "a@example.com",
"subject": SUBJECT},
"tokens": {"access_token": "a1", "refresh_token": refresh_token,
"expires_at": expires_at, "earliest_refresh_at": earliest}})
def _renewal(data):
return {"access_token": "a2", "refresh_token": "r2", "expires_in": 3600,
"id_token": _id_token(), "scope": auth.SCOPE}
# --- the ID token ----------------------------------------------------------------
@pytest.mark.unit
def test_a_genuine_id_token_is_accepted():
assert auth._validated_claims(_id_token(nonce="n"), CLIENT, "n", _jwks()["keys"])["sub"] == SUBJECT
@pytest.mark.unit
@pytest.mark.parametrize("token, nonce", [
(lambda: _id_token(nonce="other"), "n"),
(lambda: _id_token(aud="oaiapp_someone_else", nonce="n"), "n"),
(lambda: _id_token(iss="https://evil.example", nonce="n"), "n"),
(lambda: _id_token(exp=time.time() - 600, nonce="n"), "n"),
])
def test_an_id_token_for_another_sign_in_is_refused(token, nonce):
with pytest.raises(auth.ChatGPTAuthError):
auth._validated_claims(token(), CLIENT, nonce, _jwks()["keys"])
@pytest.mark.unit
def test_an_id_token_signed_by_another_key_is_refused():
stranger = rsa.generate_private_key(public_exponent=65537, key_size=2048)
with pytest.raises(auth.ChatGPTAuthError, match="do not verify"):
auth._validated_claims(_id_token(key=stranger, nonce="n"), CLIENT, "n", _jwks()["keys"])
# --- tokens ----------------------------------------------------------------------
@pytest.mark.unit
def test_nobody_signed_in_is_told_how_to_sign_in(home, openai):
with pytest.raises(auth.ChatGPTAuthError, match="tradingagents login chatgpt"):
auth.credential()
with pytest.raises(auth.ChatGPTAuthError, match="tradingagents login chatgpt"):
auth.access_token()
assert openai.posts == []
@pytest.mark.unit
def test_a_fresh_token_is_used_without_asking_openai(home, openai):
_signed_in(expires_at=time.time() + 3000)
assert auth.credential()() == "a1"
assert openai.posts == []
@pytest.mark.unit
def test_a_token_near_expiry_is_renewed_with_the_stored_refresh_token(home, openai):
_signed_in(expires_at=time.time() + 60)
openai.token_body = _renewal
assert auth.access_token() == "a2"
(url, sent), = openai.posts
assert url == auth.TOKEN_URL and sent["refresh_token"] == "r1" and sent["client_id"] == CLIENT
stored = json.loads(auth.AUTH_FILE.read_text())
assert stored["tokens"]["refresh_token"] == "r2" and stored["account"]["subject"] == SUBJECT
if os.name != "nt": # Windows keeps no POSIX mode; the profile's ACL guards it
assert stat.S_IMODE(auth.AUTH_FILE.stat().st_mode) == 0o600
@pytest.mark.unit
def test_renewal_waits_for_the_time_openai_allows_while_the_token_still_works(home, openai):
now = time.time()
_signed_in(expires_at=now + 200, earliest=now + 100)
assert auth.access_token() == "a1"
assert openai.posts == []
@pytest.mark.unit
def test_concurrent_runs_renew_once_and_never_replay_a_used_refresh_token(home, openai):
_signed_in(expires_at=time.time() + 60)
openai.token_body = _renewal
tokens = []
threads = [threading.Thread(target=lambda: tokens.append(auth.access_token())) for _ in range(4)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
assert tokens == ["a2"] * 4
assert [sent["refresh_token"] for _, sent in openai.posts] == ["r1"]
@pytest.mark.unit
def test_a_refused_renewal_asks_to_sign_in_again_and_keeps_the_file(home, openai):
_signed_in(expires_at=time.time() + 60)
openai.token_body, openai.status = {"error": "invalid_grant"}, 400
with pytest.raises(auth.ChatGPTAuthError, match="invalid_grant.*login chatgpt"):
auth.access_token()
assert json.loads(auth.AUTH_FILE.read_text())["tokens"]["refresh_token"] == "r1"
@pytest.mark.unit
def test_a_renewal_for_another_account_is_refused(home, openai):
_signed_in(expires_at=time.time() + 60)
openai.token_body = lambda data: {**_renewal(data), "id_token": _id_token(sub="someone-else")}
with pytest.raises(auth.ChatGPTAuthError, match="another account"):
auth.access_token()
# --- signing in and out ------------------------------------------------------------
def _nonce_of(printed):
url = next(line for line in printed if line.startswith(auth.AUTHORIZE_URL))
return dict(urllib.parse.parse_qsl(urllib.parse.urlparse(url).query))["nonce"]
def _paster(printed, edit=lambda query: query):
calls = []
def read_line():
calls.append(1)
if len(calls) > 1:
threading.Event().wait()
url = next(line for line in printed if line.startswith(auth.AUTHORIZE_URL))
asked = dict(urllib.parse.parse_qsl(urllib.parse.urlparse(url).query))
query = edit({"code": "c1", "state": asked["state"], "client_id": CLIENT})
return f"{asked['redirect_uri']}?{urllib.parse.urlencode(query)}"
return read_line
@pytest.mark.unit
def test_signing_in_by_pasting_the_redirect_saves_a_private_sign_in(home, openai):
printed = []
def token(data):
assert data["grant_type"] == "authorization_code" and data["client_id"] == CLIENT
assert data["code"] == "c1" and data["code_verifier"]
return {"access_token": "a1", "refresh_token": "r1", "expires_in": 3600,
"id_token": _id_token(nonce=_nonce_of(printed)), "scope": auth.SCOPE}
openai.token_body = token
email = auth.sign_in(say=printed.append, read_line=_paster(printed), timeout=10, port=0)
assert email == "a@example.com"
stored = json.loads(auth.AUTH_FILE.read_text())
assert stored["account"] == {"client_id": CLIENT, "email": "a@example.com", "subject": SUBJECT}
assert stored["host_id"].startswith("urn:uuid:")
if os.name != "nt": # Windows keeps no POSIX mode; the profile's ACL guards it
assert stat.S_IMODE(auth.AUTH_FILE.stat().st_mode) == 0o600
asked = dict(urllib.parse.parse_qsl(urllib.parse.urlparse(printed[1]).query))
assert asked["client_id"] == auth.DYNAMIC_CLIENT_ID and asked["agent_name_hint"] == "TradingAgents"
assert asked["code_challenge_method"] == "S256" and asked["redirect_uri"].startswith("http://127.0.0.1:")
@pytest.mark.unit
def test_an_answer_for_another_sign_in_attempt_is_ignored(home, openai):
printed = []
with pytest.raises(auth.ChatGPTAuthError, match="timed out"):
auth.sign_in(say=printed.append, read_line=_paster(printed, lambda q: {**q, "state": "forged"}),
timeout=1, port=0)
assert any("not the address" in line for line in printed)
assert openai.posts == [] and not auth.AUTH_FILE.exists()
def _status(url):
try:
return urllib.request.urlopen(url, timeout=5).status
except urllib.error.HTTPError as exc:
return exc.code
@pytest.mark.unit
def test_the_browser_answer_reaches_the_loopback_and_strays_are_ignored(home, openai, monkeypatch):
refused_connect, refused_lookup = socket.socket.connect, socket.getaddrinfo
monkeypatch.setattr(socket.socket, "connect", lambda sock, address: (
_CONNECT if address[0] == "127.0.0.1" else refused_connect)(sock, address))
monkeypatch.setattr(socket, "getaddrinfo", lambda host, *a, **k: (
_GETADDRINFO if host == "127.0.0.1" else refused_lookup)(host, *a, **k))
printed = []
openai.token_body = lambda data: {"access_token": "a1", "refresh_token": "r1", "expires_in": 3600,
"id_token": _id_token(nonce=_nonce_of(printed)), "scope": auth.SCOPE}
def browser():
while not any(line.startswith(auth.AUTHORIZE_URL) for line in printed):
time.sleep(0.01)
asked = dict(urllib.parse.parse_qsl(urllib.parse.urlparse(printed[1]).query))
results.append(_status(f"{asked['redirect_uri']}?error=access_denied"))
results.append(_status(f"{asked['redirect_uri']}?code=c1&state={asked['state']}&client_id={CLIENT}"))
results = []
threading.Thread(target=browser, daemon=True).start()
email = auth.sign_in(say=printed.append, read_line=threading.Event().wait, timeout=10, port=0)
assert email == "a@example.com" and results == [400, 200]
@pytest.mark.unit
def test_a_sign_in_without_plan_usage_is_refused(home, openai):
printed = []
openai.token_body = lambda data: {"access_token": "a1", "refresh_token": "r1", "expires_in": 3600,
"id_token": _id_token(nonce=_nonce_of(printed)),
"scope": "openid email offline_access"}
with pytest.raises(auth.ChatGPTAuthError, match="approve plan usage"):
auth.sign_in(say=printed.append, read_line=_paster(printed), timeout=10, port=0)
assert not auth.AUTH_FILE.exists()
@pytest.mark.unit
def test_signing_out_revokes_the_sign_in_and_keeps_only_the_host_id(home, openai):
_signed_in(expires_at=time.time() + 3000)
assert auth.sign_out() == "revoked"
(url, sent), = openai.posts
assert url == auth.REVOKE_URL and sent["token"] == "r1" and sent["client_id"] == CLIENT
assert json.loads(auth.AUTH_FILE.read_text()) == {"host_id": "urn:uuid:h"}
assert auth.signed_in_as() is None
assert auth.sign_out() is None
@pytest.mark.unit
def test_unreachable_keys_stop_a_renewal_before_the_refresh_token_is_spent(home, openai):
_signed_in(expires_at=time.time() - 1)
openai.token_body, openai.keys_reachable = _renewal, False
with pytest.raises(auth.ChatGPTUnreachable, match="Could not reach OpenAI"):
auth.access_token()
assert openai.posts == []
assert json.loads(auth.AUTH_FILE.read_text())["tokens"]["refresh_token"] == "r1"
@pytest.mark.unit
@pytest.mark.parametrize("failure", ["keys", "network", 429, 503])
def test_a_temporary_failure_keeps_a_token_that_still_works(home, openai, failure):
_signed_in(expires_at=time.time() + 60)
openai.token_body = _renewal
if failure == "keys":
openai.keys_reachable = False
elif failure == "network":
openai.post_error = auth.requests.ConnectionError("reset")
else:
openai.token_body, openai.status = {"error": "busy"}, failure
assert auth.access_token() == "a1"
assert json.loads(auth.AUTH_FILE.read_text())["tokens"]["refresh_token"] == "r1"
if failure == "keys":
assert openai.posts == []
@pytest.mark.unit
@pytest.mark.parametrize("failure", ["network", 408, 503])
def test_a_temporary_failure_after_expiry_says_to_try_again_not_to_sign_in(home, openai, failure):
_signed_in(expires_at=time.time() - 1)
if failure == "network":
openai.post_error = auth.requests.Timeout("slow")
else:
openai.token_body, openai.status = {"error": "busy"}, failure
with pytest.raises(auth.ChatGPTUnreachable) as raised:
auth.access_token()
assert "try again" in str(raised.value) and "login" not in str(raised.value)
@pytest.mark.unit
def test_signing_in_again_revokes_the_replaced_sign_in(home, openai):
_signed_in(expires_at=time.time() + 3000, refresh_token="old")
printed = []
openai.token_body = lambda data: {"access_token": "a2", "refresh_token": "r2", "expires_in": 3600,
"id_token": _id_token(nonce=_nonce_of(printed)), "scope": auth.SCOPE}
auth.sign_in(say=printed.append, read_line=_paster(printed), timeout=10, port=0)
assert openai.posts[-1][0] == auth.REVOKE_URL and openai.posts[-1][1]["token"] == "old"
assert json.loads(auth.AUTH_FILE.read_text())["tokens"]["refresh_token"] == "r2"
@pytest.mark.unit
def test_another_account_cannot_replace_the_signed_in_one(home, openai):
_signed_in(expires_at=time.time() + 3000)
printed = []
openai.token_body = lambda data: {"access_token": "a2", "refresh_token": "r2", "expires_in": 3600,
"id_token": _id_token(nonce=_nonce_of(printed), sub="someone-else"),
"scope": auth.SCOPE}
with pytest.raises(auth.ChatGPTAuthError, match="logout chatgpt"):
auth.sign_in(say=printed.append, read_line=_paster(printed), timeout=10, port=0)
assert json.loads(auth.AUTH_FILE.read_text())["tokens"]["refresh_token"] == "r1"
@pytest.mark.unit
def test_signing_out_while_openai_is_unreachable_still_forgets_the_sign_in(home, openai):
_signed_in(expires_at=time.time() + 3000)
openai.revoke_status = 503
assert auth.sign_out() == "forgotten"
assert auth.signed_in_as() is None
@pytest.mark.unit
def test_after_a_temporary_failure_renewal_waits_a_minute_before_trying_again(home, openai):
_signed_in(expires_at=time.time() + 200)
openai.post_error = auth.requests.ConnectionError("reset")
clock = [time.time()]
assert auth.access_token(now=lambda: clock[0]) == "a1"
assert auth.access_token(now=lambda: clock[0] + 30) == "a1"
assert len(openai.posts) == 1
openai.post_error, openai.token_body = None, _renewal
assert auth.access_token(now=lambda: clock[0] + 61) == "a2"
@pytest.mark.unit
def test_after_expiry_a_failed_renewal_is_not_retried_within_the_minute(home, openai):
_signed_in(expires_at=time.time() - 1)
openai.post_error = auth.requests.ConnectionError("reset")
for _ in range(3):
with pytest.raises(auth.ChatGPTUnreachable, match="try again"):
auth.access_token()
assert len(openai.posts) == 1
@pytest.mark.unit
def test_an_unreadable_renewal_answer_keeps_a_token_that_still_works(home, openai):
_signed_in(expires_at=time.time() + 60)
openai.token_body = lambda data: ["not", "a", "token"]
assert auth.access_token() == "a1"
assert json.loads(auth.AUTH_FILE.read_text())["tokens"]["refresh_token"] == "r1"
@pytest.mark.unit
def test_a_network_failure_while_signing_in_is_reported_not_raised_raw(home, openai):
printed = []
openai.post_error = auth.requests.ConnectionError("reset")
with pytest.raises(auth.ChatGPTUnreachable, match="sign you in to ChatGPT.*try again"):
auth.sign_in(say=printed.append, read_line=_paster(printed), timeout=10, port=0)
assert not auth.AUTH_FILE.exists()
+245
View File
@@ -0,0 +1,245 @@
"""The chatgpt provider runs on the person's ChatGPT plan.
It sends their sign-in and nothing else, only to OpenAI, in the shape plan usage
accepts (streamed, unstored, no ``system`` role); the CLI offers it under
"Subscription", checks the sign-in before a run, and lists the plan's models.
"""
import logging
from types import SimpleNamespace
from unittest import mock
import pytest
import typer
from langchain_core.messages import HumanMessage, SystemMessage
import cli.prompts as prompts
import cli.selections as selections
from tradingagents import default_config
from tradingagents.llm_clients import chatgpt_auth, factory
from tradingagents.llm_clients.openai_client import ChatGPTPlanChatOpenAI
@pytest.fixture
def signed_in(monkeypatch):
monkeypatch.setattr(chatgpt_auth, "credential", lambda: (lambda: "plan-token"))
monkeypatch.setattr(chatgpt_auth, "access_token", lambda: "plan-token")
monkeypatch.setattr(chatgpt_auth, "signed_in_as", lambda: "a@example.com")
def _llm(**kwargs):
config = {**default_config.DEFAULT_CONFIG, "llm_provider": "chatgpt", "openai_reasoning_effort": "high", **kwargs}
return factory.create_llm_client("chatgpt", "gpt-5.5", **factory.build_llm_kwargs(config)).get_llm()
# --- the client ------------------------------------------------------------------
@pytest.mark.unit
def test_the_plan_is_reached_with_the_sign_in_never_an_api_key(signed_in, monkeypatch):
monkeypatch.setenv("OPENAI_API_KEY", "sk-should-not-be-used")
llm = _llm()
assert isinstance(llm, ChatGPTPlanChatOpenAI)
assert llm.openai_api_base == "https://api.openai.com/v1"
assert llm.openai_api_key() == "plan-token"
assert (llm.use_responses_api, llm.streaming, llm.store, llm.reasoning_effort) == (True, True, False, "high")
@pytest.mark.unit
def test_system_instructions_go_as_developer_and_refused_settings_are_dropped(signed_in, caplog):
with caplog.at_level(logging.WARNING):
llm = _llm(temperature=0.3, max_tokens=500)
payload = llm._get_request_payload([SystemMessage("Be brief."), HumanMessage("Hi")])
assert [item["role"] for item in payload["input"]] == ["developer", "user"]
assert not {"temperature", "max_output_tokens"} & payload.keys()
assert payload["stream"] is True and payload["store"] is False
assert "does not accept temperature" in caplog.text and "does not accept max_tokens" in caplog.text
@pytest.mark.unit
def test_a_run_without_a_sign_in_stops_before_any_request(monkeypatch, tmp_path):
monkeypatch.setattr(chatgpt_auth, "AUTH_FILE", tmp_path / "chatgpt-auth.json")
with pytest.raises(chatgpt_auth.ChatGPTAuthError, match="tradingagents login chatgpt"):
_llm()
@pytest.mark.unit
def test_a_chatgpt_tier_beside_an_openai_tier_keeps_each_credential(signed_in, monkeypatch):
monkeypatch.setenv("OPENAI_API_KEY", "sk-openai")
config = {**default_config.DEFAULT_CONFIG, "llm_provider": "openai", "backend_url": "https://api.openai.com/v1",
"quick_think_provider": "chatgpt", "quick_think_llm": "gpt-5.5", "deep_think_llm": "gpt-6-sol",
"openai_reasoning_effort": "low"}
quick = factory.create_tier_client(config, "quick").get_llm()
deep = factory.create_tier_client(config, "deep").get_llm()
assert isinstance(quick, ChatGPTPlanChatOpenAI) and quick.reasoning_effort == "low"
assert quick.openai_api_key() == "plan-token"
assert not isinstance(deep, ChatGPTPlanChatOpenAI)
assert deep.openai_api_key.get_secret_value() == "sk-openai"
# --- the CLI ---------------------------------------------------------------------
def _menu(answers):
"""questionary.select stand-in: records each menu and answers in turn."""
shown = []
def select(message, choices, **kwargs):
shown.append((message, [c.title for c in choices], kwargs.get("default")))
return SimpleNamespace(ask=lambda: answers.pop(0)(choices))
return shown, select
@pytest.mark.unit
def test_chatgpt_is_offered_under_subscription_after_anthropic():
shown, select = _menu([lambda cs: next(c.value for c in cs if c.title.startswith("Subscription")),
lambda cs: cs[0].value])
with mock.patch("cli.prompts.questionary.select", select):
provider, url = prompts.select_llm_provider()
titles = shown[0][1]
assert titles.index("Anthropic") + 1 == titles.index(next(t for t in titles if t.startswith("Subscription")))
assert not any(t.startswith("ChatGPT") for t in titles)
assert shown[1][1] == ["ChatGPT (Plus or Pro plan)"]
assert (provider, url) == ("chatgpt", "https://api.openai.com/v1")
@pytest.mark.unit
def test_a_remembered_chatgpt_choice_preselects_subscription():
shown, select = _menu([lambda cs: ("openai", "https://api.openai.com/v1")])
with mock.patch("cli.prompts.questionary.select", select):
prompts.select_llm_provider(default="chatgpt")
assert shown[0][2] == ("subscription", None)
@pytest.mark.unit
def test_a_signed_in_plan_is_named_before_the_run(signed_in, capsys):
prompts.ensure_signed_in("chatgpt")
assert "Using your ChatGPT plan" in capsys.readouterr().out
def _expired(monkeypatch):
def refuse():
raise chatgpt_auth.ChatGPTAuthError("Your ChatGPT sign-in could not be renewed (invalid_grant); "
"run `tradingagents login chatgpt` again.")
monkeypatch.setattr(chatgpt_auth, "access_token", refuse)
@pytest.mark.unit
def test_an_unattended_run_with_a_dead_sign_in_says_how_to_sign_in(monkeypatch, capsys):
_expired(monkeypatch)
monkeypatch.setattr("sys.stdin", SimpleNamespace(isatty=lambda: False))
with pytest.raises(typer.Exit):
prompts.ensure_signed_in("chatgpt")
assert "tradingagents login chatgpt" in " ".join(capsys.readouterr().out.split())
@pytest.mark.unit
def test_an_interactive_run_signs_in_again_through_the_login_command(monkeypatch, capsys):
_expired(monkeypatch)
monkeypatch.setattr(chatgpt_auth, "signed_in_as", lambda: "a@example.com")
monkeypatch.setattr("sys.stdin", SimpleNamespace(isatty=lambda: True))
ran = []
monkeypatch.setattr(prompts.subprocess, "run", lambda argv: ran.append(argv) or SimpleNamespace(returncode=0))
prompts.ensure_signed_in("chatgpt")
assert ran[0][1:] == ["-P", "-m", "cli.main", "login", "chatgpt"]
assert "Using your ChatGPT plan" in capsys.readouterr().out
@pytest.mark.unit
def test_each_tier_s_provider_is_signed_in_or_keyed(monkeypatch):
monkeypatch.setitem(selections.DEFAULT_CONFIG, "quick_think_provider", "chatgpt")
monkeypatch.setitem(selections.DEFAULT_CONFIG, "deep_think_provider", None)
monkeypatch.setenv("TRADINGAGENTS_QUICK_THINK_LLM", "gpt-5.5")
signed, keyed = [], []
monkeypatch.setattr(selections, "ensure_signed_in", signed.append)
monkeypatch.setattr(selections, "ensure_api_key", keyed.append)
selections._check_tier_providers("openai")
assert signed == ["chatgpt", "openai"] and keyed == ["chatgpt", "openai"]
@pytest.mark.unit
def test_the_plan_s_listed_models_are_offered_in_openai_s_order(signed_in, monkeypatch):
monkeypatch.setattr(chatgpt_auth, "access_token", lambda: "plan-token")
body = {"models": [
{"slug": "gpt-5.5", "display_name": "GPT-5.5", "visibility": "list", "priority": 9},
{"slug": "internal", "display_name": "Internal", "visibility": "hide", "priority": 0},
{"slug": "gpt-6-astra", "display_name": "GPT-6-Astra", "visibility": "list", "priority": 2},
]}
response = SimpleNamespace(raise_for_status=lambda: None, json=lambda: body)
with mock.patch("requests.get", return_value=response) as get:
assert chatgpt_auth.list_models() == [("GPT-6-Astra", "gpt-6-astra"), ("GPT-5.5", "gpt-5.5")]
assert get.call_args.kwargs["headers"] == {"Authorization": "Bearer plan-token"}
@pytest.mark.unit
def test_api_organization_and_project_do_not_travel_with_the_sign_in(signed_in, monkeypatch):
monkeypatch.setenv("OPENAI_ORG_ID", "org-for-api-keys")
monkeypatch.setenv("OPENAI_PROJECT_ID", "proj-for-api-keys")
llm = _llm()
for client in (llm.root_client, llm.root_async_client):
sent = {k: v for k, v in client.default_headers.items() if isinstance(v, str)}
assert "OpenAI-Organization" not in sent and "OpenAI-Project" not in sent
@pytest.mark.unit
def test_a_remembered_plan_model_is_offered_again():
from cli.prefs import sanitize
kept = sanitize({"llm_provider": "chatgpt", "quick_think_llm": "gpt-5.5", "deep_think_llm": "gpt-6-astra"}, "stock")
assert (kept["quick_think_llm"], kept["deep_think_llm"]) == ("gpt-5.5", "gpt-6-astra")
@pytest.mark.unit
def test_a_malformed_model_entry_does_not_hide_the_others(signed_in):
body = {"models": [{"display_name": "No slug", "visibility": "list"},
{"slug": "gpt-5.5", "display_name": "GPT-5.5", "visibility": "list"}]}
response = SimpleNamespace(raise_for_status=lambda: None, json=lambda: body)
with mock.patch("requests.get", return_value=response):
assert chatgpt_auth.list_models() == [("GPT-5.5", "gpt-5.5")]
@pytest.mark.unit
def test_an_unreachable_openai_stops_the_run_without_a_new_sign_in(monkeypatch, capsys):
def unreachable():
raise chatgpt_auth.ChatGPTUnreachable("Could not reach OpenAI to renew your ChatGPT sign-in; try again.")
monkeypatch.setattr(chatgpt_auth, "access_token", unreachable)
monkeypatch.setattr("sys.stdin", SimpleNamespace(isatty=lambda: True))
monkeypatch.setattr(prompts.subprocess, "run", lambda argv: pytest.fail("offered a new sign-in"))
with pytest.raises(typer.Exit):
prompts.ensure_signed_in("chatgpt")
assert "try again" in capsys.readouterr().out
@pytest.mark.unit
@pytest.mark.parametrize("main, tier_provider, tier_url, backend_url", [
("chatgpt", None, None, "http://localhost:8000/v1"), # the run's own endpoint
("openai", "chatgpt", "http://relay.example/v1", None), # a chatgpt tier's endpoint
])
def test_a_plan_pointed_at_another_endpoint_stops_before_the_run(monkeypatch, capsys, main, tier_provider,
tier_url, backend_url):
monkeypatch.setitem(selections.DEFAULT_CONFIG, "quick_think_provider", tier_provider)
monkeypatch.setitem(selections.DEFAULT_CONFIG, "quick_think_backend_url", tier_url)
monkeypatch.setitem(selections.DEFAULT_CONFIG, "deep_think_provider", None)
monkeypatch.setenv("TRADINGAGENTS_QUICK_THINK_LLM", "gpt-6-luna")
monkeypatch.setattr(selections, "ensure_signed_in", lambda p: pytest.fail("checked the sign-in first"))
with pytest.raises(typer.Exit):
selections._check_tier_providers(main, backend_url)
assert "only connects to https://api.openai.com/v1" in " ".join(capsys.readouterr().out.split())
@pytest.mark.unit
def test_a_remembered_openrouter_model_is_preselected(monkeypatch):
monkeypatch.setattr(prompts, "_fetch_openrouter_models",
lambda: [("A", "openai/a"), ("B", "anthropic/b")])
shown, select = _menu([lambda cs: cs[1].value])
with mock.patch("cli.prompts.questionary.select", select):
assert prompts.select_openrouter_model("deep", default="anthropic/b") == "anthropic/b"
assert shown[0][2] == "anthropic/b"
@pytest.mark.unit
def test_the_chatgpt_plan_is_the_only_provider_signed_in_to():
# `login`, `logout` and the pre-run check are wired to the ChatGPT sign-in; a
# second signed-in provider needs its own sign-in wired into them first.
from tradingagents.llm_clients.openai_client import SIGNED_IN_PROVIDERS
assert SIGNED_IN_PROVIDERS == ("chatgpt",)
+32
View File
@@ -190,6 +190,34 @@ class TestCheckpointSignature(unittest.TestCase):
# sig1's checkpoint remains untouched.
self.assertIsNotNone(checkpoint_step(self.tmpdir, self.ticker, self.date, sig1))
def test_a_resume_under_other_settings_starts_fresh(self):
"""The report names one provider, model set, language and vendor chain;
a resume must not carry reports another of them produced."""
from tradingagents.graph.trading_graph import TradingAgentsGraph
g = object.__new__(TradingAgentsGraph)
g.selected_analysts = ("market", "news")
base_config = {"max_debate_rounds": 1, "max_risk_discuss_rounds": 1, "llm_provider": "openai",
"quick_think_llm": "q", "deep_think_llm": "d", "output_language": "English",
"data_vendors": {"core_stock_apis": "yfinance"}, "tool_vendors": {}}
g.config = dict(base_config)
base = g._run_signature("stock")
for key, value in (("llm_provider", "google"), ("quick_think_llm", "q2"), ("deep_think_llm", "d2"),
("output_language", "Deutsch"),
("data_vendors", {"core_stock_apis": "alpha_vantage"}),
("tool_vendors", {"get_news": "alpha_vantage"}),
("backend_url", "http://other-endpoint/v1"), ("max_tool_rounds", 30),
("temperature", 0.2), ("openai_reasoning_effort", "high")):
g.config = {**base_config, key: value}
self.assertNotEqual(base, g._run_signature("stock"), key)
# Where a run keeps its files, and how it retries, do not change what it writes.
for key, value in (("results_dir", "/elsewhere"), ("data_cache_dir", "/cache"),
("memory_log_path", "/log.md"), ("checkpoint_enabled", True), ("llm_max_retries", 9)):
g.config = {**base_config, key: value}
self.assertEqual(base, g._run_signature("stock"), key)
g.config = dict(base_config)
self.assertEqual(base, g._run_signature("stock"))
def test_run_signature_captures_graph_shape(self):
from tradingagents.graph.trading_graph import TradingAgentsGraph
@@ -210,6 +238,10 @@ class TestCheckpointSignature(unittest.TestCase):
# Stable for identical inputs.
g.config = {"max_debate_rounds": 1, "max_risk_discuss_rounds": 1}
self.assertEqual(base, g._run_signature("stock"))
# A checkpoint saved by the sequential layout is not resumed on the
# parallel one: its pending node no longer exists, and the join would
# never fire.
self.assertIn("analysts=parallel", base)
if __name__ == "__main__":
+101 -2
View File
@@ -25,7 +25,8 @@ calls: list = []
@pytest.mark.unit
def test_no_arguments_still_runs_an_analysis(runner):
assert runner.invoke(m.app, []).exit_code == 0
assert calls == [("analysis", {"checkpoint": None, "portfolio": None})]
no_flags = {"ticker": None, "date": None, "analysts": None, "save": None, "show": None, "html": None}
assert calls == [("analysis", {"checkpoint": None, "portfolio": None, "flags": no_flags})]
@pytest.mark.unit
@@ -82,12 +83,15 @@ class _Summary:
def test_every_command_is_registered_when_run_as_a_module():
"""README documents `python -m cli.main`, which executes the file top to
bottom, so a command defined after the __main__ block would not exist."""
import os
import re
import subprocess
import sys
# Help draws boxes in UTF-8; read it as such whatever the locale (cp1252 on Windows).
out = subprocess.run([sys.executable, "-m", "cli.main", "backtest", "--help"],
capture_output=True, text=True, timeout=120)
capture_output=True, text=True, encoding="utf-8", errors="replace",
env={**os.environ, "PYTHONIOENCODING": "utf-8"}, timeout=120)
assert out.returncode == 0, out.stderr[-400:]
# Where the terminal takes colour, help styles each option and splits
# "--start" across escape sequences, so read the text without them.
@@ -134,3 +138,98 @@ def test_backtest_reports_a_setup_failure_in_one_line(runner, monkeypatch):
assert result.exit_code == 1
assert "API key" in result.output
assert "Traceback" not in result.output
@pytest.mark.unit
def test_backtest_shows_each_cell_and_how_to_continue(runner, monkeypatch, tmp_path):
def sweep(tickers, dates, config, progress=None, **kw):
for i, date in enumerate(dates, 1):
progress(i, len(dates), tickers[0], date)
return _Result(tmp_path)
monkeypatch.setattr(m, "run_backtest", sweep)
monkeypatch.setattr(m, "summarize", lambda log: _Summary())
result = runner.invoke(m.app, ["backtest", "NVDA", "--start", "2026-06-01", "--end", "2026-06-08"])
assert "[1/2] NVDA 2026-06-01" in result.output and "[2/2] NVDA 2026-06-08" in result.output
assert f"--run-id {_Result(tmp_path).run_id}" in result.output
@pytest.mark.unit
@pytest.mark.parametrize("args, analysts", [
pytest.param(["--analysts", "sentiment,market"], ["market", "social"], id="named_as_in_analyze"),
pytest.param(["--asset-type", "crypto"], ["market", "social", "news"], id="crypto_default"),
])
def test_backtest_takes_its_analysts_as_an_analysis_does(runner, monkeypatch, tmp_path, args, analysts):
swept = []
monkeypatch.setattr(m, "run_backtest", lambda *a, **kw: swept.append(kw) or _Result(tmp_path))
monkeypatch.setattr(m, "summarize", lambda log: _Summary())
result = runner.invoke(m.app, ["backtest", "NVDA", "--start", "2026-06-01", "--end", "2026-06-01", *args])
assert result.exit_code == 0, result.output
assert swept[0]["selected_analysts"] == analysts
@pytest.mark.unit
@pytest.mark.parametrize("args", [
pytest.param(["--analysts", "fundamentals", "--asset-type", "crypto"], id="unavailable_for_crypto"),
pytest.param(["--asset-type", "bond"], id="unknown_asset_type"),
])
def test_backtest_refuses_a_selection_before_the_sweep(runner, monkeypatch, args):
monkeypatch.setattr(m, "run_backtest", lambda *a, **kw: pytest.fail("the sweep started"))
result = runner.invoke(m.app, ["backtest", "NVDA", "--start", "2026-06-01", "--end", "2026-06-01", *args])
assert result.exit_code == 1
@pytest.mark.unit
def test_login_and_logout_chatgpt_do_not_run_an_analysis(runner, monkeypatch):
from tradingagents.llm_clients import chatgpt_auth
monkeypatch.setattr(chatgpt_auth, "sign_in", lambda say: "a@example.com")
monkeypatch.setattr(chatgpt_auth, "sign_out", lambda: "revoked")
signed_in = runner.invoke(m.app, ["login", "chatgpt"])
assert signed_in.exit_code == 0 and "Signed in to ChatGPT as a@example.com" in signed_in.output
signed_out = runner.invoke(m.app, ["logout", "chatgpt"])
assert signed_out.exit_code == 0 and "Signed out of ChatGPT" in signed_out.output
assert runner.invoke(m.app, ["login", "claude"]).exit_code != 0
assert calls == []
@pytest.mark.unit
def test_a_failed_login_exits_with_the_reason(runner, monkeypatch):
from tradingagents.llm_clients import chatgpt_auth
def refuse(say):
raise chatgpt_auth.ChatGPTAuthError("Signing in with ChatGPT timed out")
monkeypatch.setattr(chatgpt_auth, "sign_in", refuse)
result = runner.invoke(m.app, ["login", "chatgpt"])
assert result.exit_code == 1 and "timed out" in result.output
@pytest.mark.unit
@pytest.mark.parametrize("outcome, said", [
(None, "Not signed in"), ("forgotten", "could not be reached to revoke"),
])
def test_logout_says_whether_openai_revoked_the_sign_in(runner, monkeypatch, outcome, said):
from tradingagents.llm_clients import chatgpt_auth
monkeypatch.setattr(chatgpt_auth, "sign_out", lambda: outcome)
result = runner.invoke(m.app, ["logout", "chatgpt"])
assert result.exit_code == 0 and said in " ".join(result.output.split())
@pytest.mark.unit
def test_a_failure_message_with_brackets_is_printed_as_text(runner, monkeypatch):
from tradingagents.llm_clients import chatgpt_auth
def refuse(say):
raise chatgpt_auth.ChatGPTAuthError("ChatGPT sign-in failed ([/bogus]); sign in again.")
monkeypatch.setattr(chatgpt_auth, "sign_in", refuse)
result = runner.invoke(m.app, ["login", "chatgpt"])
assert result.exit_code == 1 and "[/bogus]" in result.output
+12
View File
@@ -105,3 +105,15 @@ def test_a_half_set_round_count_says_which_value_won(capsys, monkeypatch):
assert config["max_risk_discuss_rounds"] == 5
assert any("TRADINGAGENTS_MAX_DEBATE_ROUNDS" in line for line in printed), printed
@pytest.mark.unit
def test_a_tier_s_thinking_setting_survives_a_main_provider_that_has_none(monkeypatch):
"""A run on Google with an OpenAI tier (#1440): the run's selections carry no
OpenAI reasoning effort, so the configured one must reach that tier."""
monkeypatch.setitem(cli_run.DEFAULT_CONFIG, "openai_reasoning_effort", "high")
monkeypatch.setitem(cli_run.DEFAULT_CONFIG, "anthropic_effort", "low")
cfg = cli_run._build_run_config({**SELECTIONS, "llm_provider": "google", "google_thinking_level": "high"},
checkpoint=None)
assert (cfg["openai_reasoning_effort"], cfg["anthropic_effort"], cfg["google_thinking_level"]) == \
("high", "low", "high")
+39 -17
View File
@@ -46,11 +46,11 @@ def _state(ticker, final="评级: 买入"):
"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": final,
"trader_investment_plan": "交易计划", "final_trade_decision": final, "final_rating": "REVIEW",
"investment_debate_state": {"bull_history": "", "bear_history": "", "history": "",
"current_response": "", "judge_decision": "", "count": 0},
"current_response": "", "count": 0},
"risk_debate_state": {"aggressive_history": "", "conservative_history": "",
"neutral_history": "", "history": "", "judge_decision": "",
"neutral_history": "", "history": "",
"latest_speaker": "", "current_aggressive_response": "",
"current_conservative_response": "", "current_neutral_response": "",
"count": 0},
@@ -61,7 +61,10 @@ def _bare_graph(tmp_path):
from tradingagents.graph.trading_graph import TradingAgentsGraph
graph = object.__new__(TradingAgentsGraph)
graph.config = {"results_dir": str(tmp_path)}
graph.config = {"results_dir": str(tmp_path), "llm_provider": "openai", "deep_think_llm": "d",
"quick_think_llm": "q", "max_debate_rounds": 1, "max_risk_discuss_rounds": 1,
"output_language": "English", "data_vendors": {}, "tool_vendors": {}}
graph.selected_analysts = ("market",)
return graph
@@ -76,6 +79,20 @@ def test_the_state_log_keeps_non_ascii_readable(tmp_path):
assert json.loads(written) # still valid JSON
@pytest.mark.unit
def test_the_state_log_names_each_field_as_the_state_does(tmp_path):
"""One name per field: the Trader's plan under its state key, and no second
copy of the managers' decisions under the debate states."""
_bare_graph(tmp_path)._log_state("2026-09-01", _state("NVDA"))
logged = json.loads(next(tmp_path.rglob("full_states_log*.json")).read_text(encoding="utf-8"))
assert logged["trader_investment_plan"] == "交易计划"
assert logged["investment_plan"] == "计划"
assert "trader_investment_decision" not in logged
assert "judge_decision" not in json.dumps(logged)
assert logged["run_settings"]["deep_think_llm"] == "d"
@pytest.mark.unit
def test_the_live_display_does_not_scroll_the_terminal():
"""A layout taller than the window makes rich redraw by scrolling, which
@@ -112,23 +129,28 @@ class AnalystWallTimeTrackerTests(unittest.TestCase):
"Analyst wall time: News 4.00s | Market 2.25s",
)
def test_syncs_wall_time_from_sequential_chunks(self):
def test_analysts_run_together_and_finish_on_their_own_reports(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, {"news_report": "done"}, now=13.0)
self.assertEqual(tracker.format_summary(), "Analyst wall time: News 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")
sync_analyst_tracker_from_chunk(tracker, {"news_report": "done", "market_report": "done"}, now=18.0)
self.assertEqual(tracker.format_summary(), "Analyst wall time: Market 8.00s | News 3.00s")
@pytest.mark.unit
def test_every_selected_analyst_is_in_progress_until_its_report_lands():
from cli.display import MessageBuffer, update_analyst_statuses
buffer = MessageBuffer()
buffer.init_for_analysis(["market", "news", "fundamentals"])
update_analyst_statuses(buffer, {"news_report": "done"})
assert buffer.agent_status["Market Analyst"] == "in_progress"
assert buffer.agent_status["Fundamentals Analyst"] == "in_progress"
assert buffer.agent_status["News Analyst"] == "completed"
+3 -6
View File
@@ -54,8 +54,7 @@ class TestCliSkipsPromptsFromEnv(unittest.TestCase):
with mock.patch.dict(os.environ, env, clear=False), \
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.updates, "enabled", return_value=False), \
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=[]), \
@@ -96,8 +95,7 @@ class TestResearchDepthSkippedFromEnv(unittest.TestCase):
with mock.patch.dict(os.environ, env, clear=False), \
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.updates, "enabled", return_value=False), \
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=[]), \
@@ -125,8 +123,7 @@ class TestReasoningEffortSkippedFromEnv(unittest.TestCase):
with mock.patch.dict(os.environ, env, clear=False), \
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.updates, "enabled", return_value=False), \
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=[]), \
+364
View File
@@ -0,0 +1,364 @@
"""Unattended CLI runs: flags answer the per-run questions, and a run with no
terminal stops up front, naming what to set, instead of waiting on a prompt."""
import datetime
import pytest
import typer
from cli import prompts, run, selections
from cli.models import AnalystType, AssetType
UNATTENDED_ENV = {
"TRADINGAGENTS_OUTPUT_LANGUAGE": "English",
"TRADINGAGENTS_MAX_DEBATE_ROUNDS": "1",
"TRADINGAGENTS_MAX_RISK_ROUNDS": "1",
"TRADINGAGENTS_LLM_PROVIDER": "openai",
"TRADINGAGENTS_QUICK_THINK_LLM": "gpt-6-luna",
}
FLAGS = {"ticker": "NVDA", "date": "2026-09-23", "analysts": "market,news", "save": True, "show": False}
@pytest.mark.unit
class TestFlagValues:
def test_a_ticker_is_normalised_and_an_empty_one_refused(self):
assert prompts.parse_ticker("0700.hk") == "0700.HK"
with pytest.raises(ValueError, match="ticker"):
prompts.parse_ticker(" ")
with pytest.raises(ValueError, match="ticker"):
prompts.parse_ticker("NV DA")
def test_a_date_must_be_a_past_or_present_day(self):
assert prompts.parse_analysis_date("2026-09-23") == "2026-09-23"
tomorrow = (datetime.date.today() + datetime.timedelta(days=1)).isoformat()
with pytest.raises(ValueError, match="future"):
prompts.parse_analysis_date(tomorrow)
with pytest.raises(ValueError, match="YYYY-MM-DD"):
prompts.parse_analysis_date("23/09/2026")
def test_analysts_are_named_and_checked_against_the_asset(self):
assert prompts.parse_analysts(" Market, news ", AssetType.STOCK) == [AnalystType.MARKET, AnalystType.NEWS]
with pytest.raises(ValueError, match="market, sentiment, news, fundamentals"):
prompts.parse_analysts("market,macro", AssetType.STOCK)
with pytest.raises(ValueError, match="crypto"):
prompts.parse_analysts("fundamentals", AssetType.CRYPTO)
with pytest.raises(ValueError, match="at least one"):
prompts.parse_analysts(" , ", AssetType.STOCK)
@pytest.mark.unit
def test_flags_skip_exactly_their_own_steps(monkeypatch):
for name, value in UNATTENDED_ENV.items():
monkeypatch.setenv(name, value)
def no_prompt(*a, **k):
raise AssertionError("prompted although a flag answered the step")
for step in ("get_ticker", "get_analysis_date", "select_analysts"):
monkeypatch.setattr(selections, step, no_prompt)
monkeypatch.setattr(selections.updates, "enabled", lambda: False)
chosen = selections._prompt_selections({}, FLAGS)
assert chosen["ticker"] == "NVDA" and chosen["analysis_date"] == "2026-09-23"
assert chosen["analysts"] == [AnalystType.MARKET, AnalystType.NEWS]
@pytest.mark.unit
def test_without_a_terminal_every_unanswered_question_is_named_before_the_run(monkeypatch, capsys):
for name in UNATTENDED_ENV:
monkeypatch.delenv(name, raising=False)
monkeypatch.setattr(run.sys.stdin, "isatty", lambda: False)
with pytest.raises(typer.Exit):
run.run_analysis(flags={"ticker": "NVDA"})
out = capsys.readouterr().out
for needed in ("--date", "--analysts", "--save", "--show", "TRADINGAGENTS_LLM_PROVIDER"):
assert needed in out
assert "--ticker" not in out
@pytest.mark.unit
def test_nothing_is_missing_when_flags_and_environment_answer_every_step(monkeypatch):
for name, value in UNATTENDED_ENV.items():
monkeypatch.setenv(name, value)
assert selections.unattended_gaps(FLAGS) == []
class _Browser:
def __init__(self):
self.opened = []
def open(self, url):
self.opened.append(url)
return True
@pytest.mark.unit
def test_save_and_show_answer_the_questions_after_the_run(monkeypatch, tmp_path):
def no_prompt(*a, **k):
raise AssertionError("prompted although --save/--show answered")
monkeypatch.setattr(run.typer, "prompt", no_prompt)
monkeypatch.setattr(run, "_graphical_browser", lambda: _Browser()) # even at a desktop
shown = []
monkeypatch.setattr(run, "display_complete_report", lambda state: shown.append(state))
from tradingagents.graph.trading_graph import TradingAgentsGraph
graph = object.__new__(TradingAgentsGraph)
graph.config = {"results_dir": str(tmp_path)}
graph.run_settings = lambda: {}
state = {"market_report": "M", "final_trade_decision": "**Rating**: Hold"}
run._offer_reports(state, graph, "NVDA", save=True, show=False)
assert list(tmp_path.glob("reports/NVDA_*/complete_report.md"))
assert shown == []
@pytest.mark.unit
def test_a_missing_key_without_a_terminal_names_the_variable(monkeypatch, capsys):
monkeypatch.delenv("OPENAI_API_KEY", raising=False)
monkeypatch.setattr(prompts.sys.stdin, "isatty", lambda: False)
with pytest.raises(typer.Exit):
prompts.ensure_api_key("openai")
assert "OPENAI_API_KEY" in capsys.readouterr().out
@pytest.mark.unit
def test_the_command_passes_its_flags_to_the_run(monkeypatch):
from typer.testing import CliRunner
from cli import main as cli_main
seen = {}
monkeypatch.setattr(cli_main, "run_analysis", lambda **kw: seen.update(kw))
result = CliRunner().invoke(cli_main.app, ["--ticker", "NVDA", "--date", "2026-09-23",
"--analysts", "market,news", "--save", "--no-show"])
assert result.exit_code == 0, result.output
assert seen["flags"] == {**FLAGS, "html": None}
@pytest.mark.unit
def test_sentiment_names_the_sentiment_analyst():
assert prompts.parse_analysts("sentiment,market", AssetType.STOCK) == [AnalystType.MARKET, AnalystType.SOCIAL]
@pytest.mark.unit
def test_an_empty_flag_is_checked_like_its_step_not_reported_missing(monkeypatch):
assert "--ticker" not in selections.unattended_gaps(dict(FLAGS, ticker=""))
@pytest.mark.unit
def test_a_closed_stdin_counts_as_no_terminal(monkeypatch, capsys):
monkeypatch.setattr(run.sys, "stdin", None)
with pytest.raises(typer.Exit):
run.run_analysis(flags={})
assert "--ticker" in capsys.readouterr().out
@pytest.mark.unit
def test_rounds_from_the_environment_do_not_claim_a_depth_was_chosen(monkeypatch, capsys):
"""With both round counts set, the depth question never appeared."""
monkeypatch.setenv("TRADINGAGENTS_MAX_DEBATE_ROUNDS", "1")
monkeypatch.setenv("TRADINGAGENTS_MAX_RISK_ROUNDS", "1")
selections = {"research_depth": 3, "quick_think_llm": "q", "deep_think_llm": "d", "backend_url": None,
"llm_provider": "openai", "google_thinking_level": None, "openai_reasoning_effort": None,
"anthropic_effort": None, "output_language": "English"}
run._build_run_config(selections, None)
assert "the research depth you chose" not in capsys.readouterr().out
@pytest.mark.unit
def test_an_unknown_analyst_error_names_the_analysts_as_users_know_them():
with pytest.raises(ValueError) as caught:
prompts.parse_analysts("macro", AssetType.STOCK)
assert "sentiment" in str(caught.value) and "social" not in str(caught.value)
def _selections_with_env(monkeypatch, keys=None):
for name, value in UNATTENDED_ENV.items():
monkeypatch.setenv(name, value)
monkeypatch.setattr(selections.updates, "enabled", lambda: False)
checked = keys if keys is not None else []
monkeypatch.setattr(selections, "ensure_api_key", lambda provider: checked.append(provider))
return checked
@pytest.mark.unit
def test_a_tier_on_another_provider_needs_its_own_model(monkeypatch, capsys):
"""Otherwise the CLI would take the main provider's model for it (#1440)."""
_selections_with_env(monkeypatch)
monkeypatch.setitem(selections.DEFAULT_CONFIG, "deep_think_provider", "anthropic")
monkeypatch.delenv("TRADINGAGENTS_DEEP_THINK_LLM", raising=False)
with pytest.raises(typer.Exit):
selections._prompt_selections({}, FLAGS)
assert "TRADINGAGENTS_DEEP_THINK_LLM" in capsys.readouterr().out
@pytest.mark.unit
def test_each_tier_provider_s_key_is_checked_before_the_run(monkeypatch):
checked = _selections_with_env(monkeypatch)
monkeypatch.setitem(selections.DEFAULT_CONFIG, "deep_think_provider", "anthropic")
monkeypatch.setenv("TRADINGAGENTS_DEEP_THINK_LLM", "claude-opus-5-5")
selections._prompt_selections({}, FLAGS)
assert checked == ["openai", "anthropic"]
def _report_graph(tmp_path):
from tradingagents.graph.trading_graph import TradingAgentsGraph
graph = object.__new__(TradingAgentsGraph)
graph.config = {"results_dir": str(tmp_path)}
graph.run_settings = lambda: {}
return graph
STATE = {"market_report": "M", "final_trade_decision": "**Rating**: Hold"}
@pytest.mark.unit
def test_a_saved_report_includes_the_html_page_unless_declined(monkeypatch, tmp_path):
monkeypatch.setattr(run, "display_complete_report", lambda state: None)
run._offer_reports(STATE, _report_graph(tmp_path / "a"), "NVDA", save=True, show=False)
run._offer_reports(STATE, _report_graph(tmp_path / "b"), "NVDA", save=True, show=False, html=False)
assert list((tmp_path / "a").glob("reports/NVDA_*/complete_report.html"))
assert list((tmp_path / "b").glob("reports/NVDA_*/complete_report.md"))
assert not list((tmp_path / "b").glob("reports/NVDA_*/complete_report.html"))
def _answer(monkeypatch, answers):
asked = []
def prompt(text, default=None, **k):
asked.append(text)
for question, answer in answers.items():
if question in text:
return default if answer is None else answer
raise AssertionError(f"unexpected question: {text}")
monkeypatch.setattr(run.typer, "prompt", prompt)
monkeypatch.setattr(run, "display_complete_report", lambda state: None)
return asked
@pytest.mark.unit
def test_an_interactive_run_asks_for_the_html_page_and_opens_it(monkeypatch, tmp_path):
asked = _answer(monkeypatch, {"Save report": "Y", "Save path": "rel/out", "HTML": "Y",
"browser": "Y", "Display full report": "N"})
browser = _Browser()
monkeypatch.setattr(run, "_graphical_browser", lambda: browser)
monkeypatch.chdir(tmp_path)
run._offer_reports(STATE, _report_graph(tmp_path), "NVDA")
page = tmp_path / "rel" / "out" / "complete_report.html"
assert page.exists() and browser.opened == [page.resolve().as_uri()]
assert [q for q in asked if "HTML" in q] and [q for q in asked if "browser" in q]
@pytest.mark.unit
def test_without_a_browser_window_the_page_is_not_offered_for_opening(monkeypatch, tmp_path):
asked = _answer(monkeypatch, {"Save report": "Y", "Save path": None, "HTML": "Y",
"Display full report": "N"})
monkeypatch.setattr(run, "_graphical_browser", lambda: None)
run._offer_reports(STATE, _report_graph(tmp_path), "NVDA")
assert not [q for q in asked if "browser" in q]
assert list(tmp_path.glob("reports/NVDA_*/complete_report.html"))
@pytest.mark.unit
def test_declining_the_html_page_saves_only_the_markdown(monkeypatch, tmp_path):
asked = _answer(monkeypatch, {"Save report": "Y", "Save path": None, "HTML": "N",
"Display full report": "N"})
monkeypatch.setattr(run, "_graphical_browser", lambda: _Browser())
run._offer_reports(STATE, _report_graph(tmp_path), "NVDA")
assert not list(tmp_path.glob("reports/NVDA_*/complete_report.html"))
assert not [q for q in asked if "browser" in q]
@pytest.mark.unit
@pytest.mark.parametrize("env, browser, offered", [
({}, "background", True),
({"SSH_CONNECTION": "10.0.0.1 22 10.0.0.2 22"}, "background", False), # the page is on the remote
({"SSH_TTY": "/dev/pts/0"}, "background", False),
({}, "terminal", False), # a text browser would take over the terminal
({}, "elinks", False),
({}, None, False), # no browser at all
])
def test_a_page_is_opened_only_in_a_browser_window_on_this_machine(monkeypatch, env, browser, offered):
import webbrowser
for name in ("SSH_CONNECTION", "SSH_TTY"):
monkeypatch.delenv(name, raising=False)
for name, value in env.items():
monkeypatch.setenv(name, value)
def get():
if browser is None:
raise webbrowser.Error("no runnable browser")
return {"background": lambda: webbrowser.BackgroundBrowser("firefox"),
"terminal": lambda: webbrowser.GenericBrowser("lynx"),
"elinks": lambda: webbrowser.Elinks("elinks")}[browser]()
monkeypatch.setattr(run.webbrowser, "get", get)
assert (run._graphical_browser() is not None) is offered
@pytest.mark.unit
@pytest.mark.parametrize("args, expected", [([], None), (["--no-html"], False), (["--html"], True)])
def test_the_html_flag_reaches_the_run(monkeypatch, args, expected):
from typer.testing import CliRunner
from cli import main as cli_main
seen = {}
monkeypatch.setattr(cli_main, "run_analysis", lambda **kw: seen.update(kw))
result = CliRunner().invoke(cli_main.app, ["--ticker", "NVDA", "--save", "--no-show", *args])
assert result.exit_code == 0 and seen["flags"]["html"] is expected
@pytest.mark.unit
def test_only_the_providers_the_tiers_use_need_a_key(monkeypatch):
"""Both tiers on a local Ollama: the main provider's key is not needed."""
checked = _selections_with_env(monkeypatch)
for tier in ("quick", "deep"):
monkeypatch.setitem(selections.DEFAULT_CONFIG, f"{tier}_think_provider", "ollama")
monkeypatch.setenv(f"TRADINGAGENTS_{tier.upper()}_THINK_LLM", "llama3.1")
selections._prompt_selections({}, FLAGS)
assert checked == ["ollama"]
@pytest.mark.unit
def test_a_page_the_browser_cannot_open_is_pointed_to(monkeypatch, tmp_path, capsys):
class Failing(_Browser):
def open(self, url):
return False
_answer(monkeypatch, {"Save report": "Y", "Save path": None, "HTML": "Y", "browser": "Y",
"Display full report": "N"})
monkeypatch.setattr(run, "_graphical_browser", lambda: Failing())
monkeypatch.setattr(run.console, "print", lambda *a, **k: print(*a))
run._offer_reports(STATE, _report_graph(tmp_path), "NVDA")
assert "complete_report.html" in capsys.readouterr().out.split("the page is at:")[-1]
@@ -1,4 +1,4 @@
"""The CLI must use the decision log the same way propagate() does.
"""The CLI must use the memory log the same way propagate() does.
The CLI streams the graph itself instead of calling propagate(), so memory steps
that lived only in propagate() never ran on the primary entry point: pending
@@ -12,8 +12,8 @@ from __future__ import annotations
import pytest
import cli.run as cli_run
from tradingagents.decision_log import TradingMemoryLog
from tradingagents.graph.trading_graph import TradingAgentsGraph
from tradingagents.memory import TradingMemoryLog
def _bare_graph(tmp_path):
@@ -21,30 +21,10 @@ def _bare_graph(tmp_path):
graph = object.__new__(TradingAgentsGraph)
graph.config = {"memory_log_path": str(tmp_path / "trading_memory.md")}
graph.memory_log = TradingMemoryLog(graph.config)
graph._log_state = lambda *a: None # these tests are about the memory log
return graph
@pytest.mark.unit
def test_create_run_state_settles_pending_and_carries_context(tmp_path, monkeypatch):
from tradingagents.graph.propagation import Propagator
graph = _bare_graph(tmp_path)
graph.propagator = Propagator()
settled = []
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")
graph.memory_log.update_with_outcome("NVDA", "2026-01-05", 0.01, 0.005, 5, "great trade", "2026-01-12")
state = graph.create_run_state("NVDA", "2026-02-01")
assert settled == ["NVDA"]
assert "great trade" in state["past_context"]
assert state["instrument_context"] == "id:NVDA"
assert state["company_of_interest"] == "NVDA"
@pytest.mark.unit
def test_record_decision_appends_a_pending_entry(tmp_path):
graph = _bare_graph(tmp_path)
@@ -76,10 +56,6 @@ class _FakeGraph:
self.calls.append(("create_run_state", ticker, trade_date))
return {"messages": [], "company_of_interest": ticker}
def process_signal(self, 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")))
@@ -99,9 +75,9 @@ class _FakeGraph:
def end_checkpoint(self):
pass
def stream(self, graph_input, **kwargs):
yield {"messages": [], "market_report": "M"}
yield {"messages": [], "final_trade_decision": "Rating: Buy\n\nBuy NVDA."}
def stream_run(self, graph_input, **kwargs):
yield [], {"messages": [], "market_report": "M"}
yield [], {"messages": [], "final_trade_decision": "Rating: Buy\n\nBuy NVDA.", "final_rating": "Buy"}
class _NullLive:
@@ -151,7 +127,7 @@ def _run_cli(monkeypatch, tmp_path, fake):
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: {
monkeypatch.setattr(cli_run, "get_user_selections", lambda flags=None: {
"ticker": "NVDA", "analysis_date": "2026-01-10",
"analysts": [AnalystType.MARKET], "asset_type": "stock",
})
@@ -164,7 +140,7 @@ def _run_cli(monkeypatch, tmp_path, fake):
@pytest.mark.unit
def test_cli_run_uses_the_decision_log_like_propagate(tmp_path, monkeypatch):
def test_cli_run_uses_the_memory_log_like_propagate(tmp_path, monkeypatch):
fake = _FakeGraph()
_run_cli(monkeypatch, tmp_path, fake)
@@ -191,3 +167,26 @@ def test_a_run_without_checkpointing_says_nothing_about_resuming(tmp_path, monke
buffer = _run_cli(monkeypatch, tmp_path, _FakeGraph())
assert not any("resum" in text.lower() or "fresh" in text.lower() for _, _, text in buffer.messages)
@pytest.mark.unit
def test_recording_a_run_writes_its_state_log(tmp_path):
"""The CLI records a run through record_decision, so the state log is written there."""
graph = object.__new__(TradingAgentsGraph)
graph.config = {"results_dir": str(tmp_path), "llm_provider": "openai", "deep_think_llm": "d",
"quick_think_llm": "q", "max_debate_rounds": 1, "max_risk_discuss_rounds": 1,
"output_language": "English", "data_vendors": {}, "tool_vendors": {}}
graph.selected_analysts = ("market",)
graph.memory_log = TradingMemoryLog({"memory_log_path": str(tmp_path / "m.md")})
state = {"company_of_interest": "NVDA", "trade_date": "2026-09-23", "market_report": "M",
"sentiment_report": "", "news_report": "", "fundamentals_report": "",
"investment_debate_state": {"bull_history": "", "bear_history": "", "history": "",
"current_response": ""},
"trader_investment_plan": "T", "investment_plan": "P",
"risk_debate_state": {"aggressive_history": "", "conservative_history": "",
"neutral_history": "", "history": ""},
"final_trade_decision": "**Rating**: Hold", "final_rating": "Hold"}
graph.record_decision("NVDA", "2026-09-23", state)
assert list(tmp_path.glob("NVDA/TradingAgentsStrategy_logs/full_states_log_2026-09-23.json"))
+6 -14
View File
@@ -27,12 +27,6 @@ SAVED = {
}
@pytest.fixture(autouse=True)
def _home(tmp_path, monkeypatch):
monkeypatch.setattr("cli.prefs._PREFS_PATH", tmp_path / "cli_prefs.json")
return tmp_path
@pytest.mark.unit
def test_round_trip():
save_last_run(SAVED)
@@ -45,18 +39,18 @@ def test_missing_file_is_not_an_error():
@pytest.mark.unit
def test_a_corrupt_file_degrades_to_no_memory(_home):
(_home / "cli_prefs.json").write_text("{not json")
def test_a_corrupt_file_degrades_to_no_memory(tmp_path):
(tmp_path / "cli_prefs.json").write_text("{not json")
assert load_last_run() == {}
@pytest.mark.unit
def test_a_half_written_file_cannot_be_observed(_home):
def test_a_half_written_file_cannot_be_observed(tmp_path):
"""Two runs finishing together must never leave a torn file behind."""
save_last_run(SAVED)
save_last_run({**SAVED, "research_depth": 5})
assert load_last_run()["research_depth"] == 5
assert list((_home).glob("*.tmp*")) == []
assert list(tmp_path.glob("*.tmp*")) == []
# --- validation against the current choices ---------------------------------
@@ -101,8 +95,7 @@ def _answer_every_prompt(monkeypatch):
"""Drive the real selection flow, answering each prompt with a fixed value."""
import cli.main as m
monkeypatch.setattr(cli_selections, "fetch_announcements", lambda: [])
monkeypatch.setattr(cli_selections, "display_announcements", lambda *a: None)
monkeypatch.setattr(cli_selections.updates, "enabled", lambda: False)
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")
@@ -154,8 +147,7 @@ def test_a_remembered_endpoint_is_offered_back(monkeypatch):
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(cli_selections, "fetch_announcements", lambda: [])
monkeypatch.setattr(cli_selections, "display_announcements", lambda *a: None)
monkeypatch.setattr(cli_selections.updates, "enabled", lambda: False)
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")
+3
View File
@@ -38,6 +38,9 @@ def test_normalize_symbol_crypto_and_passthrough(raw, expected):
("", True), # empty -> defaults to SPY downstream
("bad symbol!", False), # space + '!' rejected
("A" * 40, False), # too long
("XAUUSD+", True), # a broker's CFD spelling of gold, priced as GC=F
("..", False), # names a directory, not an instrument
("\uff21\uff21\uff30\uff2c", False), # full-width letters
])
def test_ticker_input_validation(value, ok):
assert is_valid_ticker_input(value) is ok
+339
View File
@@ -0,0 +1,339 @@
"""What's new reaches the person at a terminal: a newer release and Tauric's notices.
The check runs at most daily in a background thread that only writes a cache; the
notice shown is read from that cache, so a run never waits on the network, and
unattended runs contact no server at all.
"""
import io
import json
import os
from datetime import date
from types import SimpleNamespace
from unittest import mock
import pytest
from packaging.version import Version
from rich.console import Console
import cli.selections as cli_selections
import cli.updates as updates
class _Tty(io.StringIO):
def isatty(self):
return True
# --- who sees it -----------------------------------------------------------------
@pytest.mark.unit
@pytest.mark.parametrize("stdin_tty, stdout_tty, ci, opt_out, expected", [
(True, True, None, None, True),
(False, True, None, None, False),
(True, False, None, None, False),
(True, True, "true", None, False),
(True, True, None, "1", False),
])
def test_only_a_person_at_a_terminal_is_told(monkeypatch, stdin_tty, stdout_tty, ci, opt_out, expected):
monkeypatch.setattr("sys.stdin", _Tty() if stdin_tty else io.StringIO())
monkeypatch.setattr("sys.stdout", _Tty() if stdout_tty else io.StringIO())
for name, value in (("CI", ci), ("TRADINGAGENTS_NO_UPDATE_CHECK", opt_out)):
if value is None:
monkeypatch.delenv(name, raising=False)
else:
monkeypatch.setenv(name, value)
assert updates.enabled() is expected
ENV = {
"TRADINGAGENTS_LLM_PROVIDER": "openai",
"TRADINGAGENTS_DEEP_THINK_LLM": "gpt-6-sol",
"TRADINGAGENTS_QUICK_THINK_LLM": "gpt-6-luna",
"TRADINGAGENTS_OUTPUT_LANGUAGE": "English",
"TRADINGAGENTS_MAX_DEBATE_ROUNDS": "1",
"TRADINGAGENTS_MAX_RISK_ROUNDS": "1",
}
@pytest.mark.unit
def test_an_unattended_run_contacts_no_server(monkeypatch):
monkeypatch.setattr("sys.stdin", io.StringIO()) # no terminal
calls = []
monkeypatch.setattr(updates.requests, "get", lambda *a, **k: calls.append(a))
started = []
monkeypatch.setattr(updates.threading, "Thread", lambda *a, **k: started.append(1))
with mock.patch.dict(os.environ, ENV, clear=False), \
mock.patch.object(cli_selections, "ensure_api_key"):
cli_selections.get_user_selections({"ticker": "AAPL", "date": "2026-09-01", "analysts": "market"})
assert calls == [] and started == []
# --- what it says -----------------------------------------------------------------
LATEST = {"version": "0.7.0", "url": "https://github.com/TauricResearch/TradingAgents/releases/tag/v0.7.0",
"summary": "Update notices and a ChatGPT plan provider."}
@pytest.mark.unit
@pytest.mark.parametrize("running, shown", [
("0.6.0", True), ("0.7.0.dev0", True), # a development build of the release is older than it
("0.7.0", False), ("0.8.0.dev0", False), ("not-a-version", False),
])
def test_a_newer_release_is_announced_once_in_the_notice(running, shown):
lines = updates.messages({"latest": LATEST}, running=running, upgrade=lambda: None)
assert any("0.7.0 is available" in line for line in lines) is shown
if shown:
text = "\n".join(lines)
assert f"you have {running}" in text and LATEST["url"] in text and LATEST["summary"] in text
@pytest.mark.unit
def test_the_notice_names_the_upgrade_command():
lines = updates.messages({"latest": LATEST}, running="0.6.0", upgrade=lambda: "git -C /src pull && pip install /src")
assert "Upgrade: git -C /src pull && pip install /src" in "\n".join(lines)
@pytest.mark.unit
def test_remote_text_cannot_style_or_break_the_terminal():
body = "[bold red]Grab it[/bold red] now\x1b[2J with `--html`, a very long line " + "x" * 400 + "\n\nSecond paragraph."
summary = updates.summary_of(body)
assert "\n" not in summary and "Second paragraph" not in summary and len(summary) <= 160
lines = updates.messages({"latest": {**LATEST, "summary": summary}}, running="0.6.0", upgrade=lambda: None)
shown = "\n".join(lines)
assert "[bold red]Grab it" in shown and "\x1b" not in shown # shown as plain text, controls stripped
@pytest.mark.unit
def test_notices_reach_only_the_versions_they_name():
cache = {"notices": [
{"id": "a", "message": "For everyone", "url": None},
{"id": "b", "message": "Old installs: news is fixed", "max_version": "0.6.0"},
{"id": "c", "message": "New installs only", "min_version": "0.7.0"},
{"id": "d", "message": "Expired", "expires": "2020-01-01"},
{"id": "e", "message": "[link=x]markup[/link]"},
"a bare string is not a notice",
]}
text = "\n".join(updates.messages(cache, running="0.6.0", upgrade=lambda: None))
assert "For everyone" in text and "Old installs" in text
assert "New installs only" not in text and "Expired" not in text
assert "[link=x]markup[/link]" in text and "bare string" not in text
@pytest.mark.unit
def test_a_notice_shows_through_its_bounds_and_date_and_hides_when_they_cannot_be_read():
today = date(2026, 10, 16)
applies = lambda **notice: updates._applies(notice, Version("0.7.0"), today) # noqa: E731
assert applies(min_version="0.7.0", max_version="0.7.0", expires="2026-10-16")
assert applies(expires=None) and applies(min_version=None, max_version=None)
assert not applies(expires="2026-10-15") and not applies(min_version="0.7.1") and not applies(max_version="0.6.9")
for unreadable in ("", "seven", [], False):
assert not applies(min_version=unreadable) and not applies(max_version=unreadable)
for unreadable in ("", "2026-10-16junk", "20261020", "2026-W42-5", "2026-10-16T23:00-08:00", 20261016):
assert not applies(expires=unreadable)
assert not updates._applies({"min_version": "0.7.0"}, Version("0.7.0.dev0"), today)
@pytest.mark.unit
def test_a_notice_is_shown_as_plain_text_with_only_a_web_link():
cache = {"notices": [
{"id": "a", "message": ":warning: [b]x[/b] \u202eev\u200bil", "url": "https://tauric.ai/a"},
{"id": "b", "message": "Local link", "url": "file:///etc/passwd"},
{"id": "e", "message": "Malformed link", "url": "https://[docs"},
{"id": "c", "message": {"not": "text"}},
{"id": "d", "message": "\x1b\x07"},
]}
assert updates.messages(cache, running="0.7.0") == [":warning: [b]x[/b] evil https://tauric.ai/a", "Local link",
"Malformed link https://[docs"]
console = Console(record=True, width=120, color_system=None)
with mock.patch.object(updates, "read_cache", lambda: cache), mock.patch("tradingagents.__version__", "0.7.0"):
updates.show(console)
assert ":warning: [b]x[/b] evil" in console.export_text()
@pytest.mark.unit
def test_notices_are_read_from_their_own_key():
# Notices have their own key, so ``announcements`` stays a list of strings.
payload = {"announcements": ["Plain text for older clients"],
"notices": [{"id": "x", "message": "Targeted", "max_version": "0.6.0"}]}
assert updates.parse_notices(payload) == payload["notices"]
assert updates.parse_notices({"announcements": ["old shape only"]}) is None
assert updates.parse_notices({"notices": []}) == []
# --- how it is checked ---------------------------------------------------------------
@pytest.mark.unit
def test_a_check_is_due_once_a_day():
now = 1_000_000.0
assert updates.due({}, now)
assert not updates.due({"checked_at": now - 3600}, now)
assert updates.due({"checked_at": now - 25 * 3600}, now)
def _response(payload, status=200):
return SimpleNamespace(status_code=status, ok=status < 400, json=lambda: payload)
@pytest.mark.unit
def test_a_check_records_the_latest_release_and_notices(tmp_path, monkeypatch):
cache_file = tmp_path / "update_check.json"
monkeypatch.setattr(updates, "CACHE", cache_file)
def get(url, timeout):
assert timeout <= 3
if "api.github.com" in url:
return _response({"tag_name": "v0.7.0", "html_url": LATEST["url"],
"body": "Update notices and a ChatGPT plan provider.\n\n## Added"})
return _response({"announcements": ["old"], "notices": [{"id": "n", "message": "hi"}]})
monkeypatch.setattr(updates.requests, "get", get)
updates.refresh(now=5000.0)
cache = json.loads(cache_file.read_text())
assert cache["checked_at"] == 5000.0
assert cache["latest"] == {"version": "0.7.0", "url": LATEST["url"], "summary": LATEST["summary"]}
assert cache["notices"] == [{"id": "n", "message": "hi"}]
@pytest.mark.unit
def test_a_failed_check_keeps_what_was_known_and_waits_a_day(tmp_path, monkeypatch, capsys):
cache_file = tmp_path / "update_check.json"
cache_file.write_text(json.dumps({"checked_at": 1.0, "latest": LATEST, "notices": []}))
monkeypatch.setattr(updates, "CACHE", cache_file)
def get(url, timeout):
raise updates.requests.ConnectionError("offline")
monkeypatch.setattr(updates.requests, "get", get)
updates.refresh(now=9000.0) # never raises
cache = json.loads(cache_file.read_text())
assert cache["checked_at"] == 9000.0 and cache["latest"] == LATEST
assert capsys.readouterr() == ("", "") # the check never prints
@pytest.mark.unit
def test_only_a_notices_list_replaces_the_known_notices(tmp_path, monkeypatch):
cache_file = tmp_path / "update_check.json"
known = [{"id": "n", "message": "hi"}]
cache_file.write_text(json.dumps({"checked_at": 1.0, "notices": known}))
monkeypatch.setattr(updates, "CACHE", cache_file)
for answer in (_response({"detail": "Not Found"}, 404), _response({"error": "portal"}), _response(["x"])):
monkeypatch.setattr(updates.requests, "get", lambda url, timeout, answer=answer: answer)
updates.refresh(now=9000.0)
assert json.loads(cache_file.read_text())["notices"] == known
monkeypatch.setattr(updates.requests, "get", lambda url, timeout: _response({"announcements": [], "notices": []}))
updates.refresh(now=99000.0)
assert json.loads(cache_file.read_text())["notices"] == []
@pytest.mark.unit
def test_an_unreadable_cache_is_no_news(tmp_path, monkeypatch):
cache_file = tmp_path / "update_check.json"
cache_file.write_text("{not json")
monkeypatch.setattr(updates, "CACHE", cache_file)
assert updates.read_cache() == {}
# --- the upgrade command for how it was installed ----------------------------------
def _dist(direct=None, installer="pip"):
files = {"direct_url.json": json.dumps(direct) if direct else None, "INSTALLER": installer}
return SimpleNamespace(read_text=lambda name: files.get(name))
@pytest.mark.unit
@pytest.mark.skipif(os.name == "nt", reason="the upgrade commands are POSIX shell")
def test_the_upgrade_command_follows_the_install(tmp_path, monkeypatch):
clone = tmp_path / "TradingAgents"
(clone / ".git").mkdir(parents=True)
monkeypatch.delenv("TRADINGAGENTS_IN_DOCKER", raising=False)
monkeypatch.setattr(updates.sys, "executable", "/venv/bin/python")
url = clone.as_uri()
editable = updates.upgrade_command(_dist({"url": url, "dir_info": {"editable": True}}))
assert editable == f"git -C {clone} pull && /venv/bin/python -m pip install -e {clone}"
local = updates.upgrade_command(_dist({"url": url, "dir_info": {}}, installer="uv"))
assert local == f"git -C {clone} pull && uv pip install --python /venv/bin/python {clone}"
vcs = updates.upgrade_command(_dist({"url": "https://github.com/TauricResearch/TradingAgents.git",
"vcs_info": {"vcs": "git", "commit_id": "abc"}}))
assert vcs == "/venv/bin/python -m pip install -U git+https://github.com/TauricResearch/TradingAgents.git"
@pytest.mark.unit
def test_no_command_is_guessed_without_a_clone(tmp_path, monkeypatch):
monkeypatch.delenv("TRADINGAGENTS_IN_DOCKER", raising=False)
gone = (tmp_path / "deleted-clone").as_uri()
assert updates.upgrade_command(_dist({"url": gone, "dir_info": {}})) is None
assert updates.upgrade_command(_dist(None)) is None
monkeypatch.setenv("TRADINGAGENTS_IN_DOCKER", "1")
assert updates.upgrade_command(_dist(None)) == "git pull && docker compose build (on the host)"
@pytest.mark.unit
def test_whats_new_never_waits_for_the_person(tmp_path, monkeypatch):
cache_file = tmp_path / "update_check.json"
cache_file.write_text(json.dumps({"latest": LATEST, "notices": [{"id": "x", "message": "Notice"}]}))
monkeypatch.setattr(updates, "CACHE", cache_file)
monkeypatch.setattr("builtins.input", lambda *a: (_ for _ in ()).throw(AssertionError("asked for input")))
from rich.console import Console
out = Console(file=io.StringIO(), width=200)
updates.show(out)
assert "Notice" in out.file.getvalue()
@pytest.mark.unit
@pytest.mark.parametrize("stored", [
{"latest": "x"}, {"latest": ["0.9.0"]}, {"notices": 5}, {"notices": {"id": "x"}}, {"checked_at": "today"}, [],
])
def test_a_cache_of_the_wrong_shape_is_no_news(tmp_path, monkeypatch, stored):
cache_file = tmp_path / "update_check.json"
cache_file.write_text(json.dumps(stored))
monkeypatch.setattr(updates, "CACHE", cache_file)
assert updates.messages(updates.read_cache(), running="0.6.0", upgrade=lambda: None) == []
assert updates.due(updates.read_cache(), 1_000_000.0)
@pytest.mark.unit
def test_a_check_dated_in_the_future_is_due():
assert updates.due({"checked_at": 2_000_000.0}, 1_000_000.0)
@pytest.mark.unit
def test_a_notice_with_an_unreadable_expiry_is_not_shown():
cache = {"notices": [{"message": "Bad date", "expires": "next week"},
{"message": "Number", "expires": 20991231},
{"message": "Timestamp", "expires": "2999-01-01T00:00:00Z"},
{"message": "A date", "expires": "2999-01-01"}]}
text = "\n".join(updates.messages(cache, running="0.6.0", upgrade=lambda: None))
assert "Bad date" not in text and "Number" not in text and "Timestamp" not in text and "A date" in text
@pytest.mark.unit
def test_remote_text_cannot_carry_c1_or_direction_controls():
lines = updates.messages({"notices": [{"message": "A\x9b2Jb‮evil"}]}, running="0.6.0", upgrade=lambda: None)
assert lines == ["A 2Jbevil"] # the C1 control reads as a space, the override is dropped
@pytest.mark.unit
@pytest.mark.skipif(os.name == "nt", reason="the upgrade commands are POSIX shell")
def test_a_uv_git_install_is_upgraded_with_uv(monkeypatch):
monkeypatch.delenv("TRADINGAGENTS_IN_DOCKER", raising=False)
monkeypatch.setattr(updates.sys, "executable", "/venv/bin/python")
vcs = updates.upgrade_command(_dist({"url": "https://github.com/TauricResearch/TradingAgents.git",
"vcs_info": {"vcs": "git"}}, installer="uv"))
assert vcs == "uv pip install --python /venv/bin/python -U git+https://github.com/TauricResearch/TradingAgents.git"
@pytest.mark.unit
def test_no_command_is_offered_on_windows(monkeypatch):
monkeypatch.delenv("TRADINGAGENTS_IN_DOCKER", raising=False)
monkeypatch.setattr(updates.os, "name", "nt")
assert updates.upgrade_command(_dist({"url": "https://github.com/TauricResearch/TradingAgents.git",
"vcs_info": {"vcs": "git"}})) is None
@pytest.mark.unit
def test_the_upgrade_command_is_worked_out_only_for_a_newer_release():
asked = []
updates.messages({"latest": LATEST}, running=LATEST["version"], upgrade=lambda: asked.append(1))
assert asked == []
+3 -3
View File
@@ -49,7 +49,7 @@ class DataflowsConfigIsolationTests(unittest.TestCase):
fresh = get_config()
self.assertEqual(fresh["data_vendors"]["core_stock_apis"], "alpha_vantage")
self.assertEqual(fresh["data_vendors"]["technical_indicators"], "yfinance")
self.assertEqual(fresh["data_vendors"]["fundamental_data"], "yfinance")
self.assertEqual(fresh["data_vendors"]["fundamental_data"], "sec_edgar,yfinance")
self.assertEqual(fresh["data_vendors"]["news_data"], "yfinance")
def test_nested_dict_updates_merge_one_level_deep(self):
@@ -95,7 +95,7 @@ def test_a_run_reads_its_own_graphs_vendors_not_the_last_graph_built():
set_config(first) # graph A is built
second = _graph(copy.deepcopy(default_config.DEFAULT_CONFIG))
assert _vendors_seen_by_a_run(second) == ["yfinance"]
assert _vendors_seen_by_a_run(second) == ["sec_edgar,yfinance"]
@pytest.mark.unit
@@ -148,7 +148,7 @@ def test_settling_reads_the_graphs_own_config(monkeypatch):
graph = _graph(config)
graph.memory_log = graph.reflector = None # the settlement below is a stand-in
seen = []
from tradingagents.graph import settlement
from tradingagents.memory import settlement
monkeypatch.setattr(settlement, "settle_pending",
lambda *a: seen.append(get_vendor("core_stock_apis", "get_stock_data")))
+4 -2
View File
@@ -4,6 +4,8 @@ requested end_date (and the current day) is actually included.
Regressions for #986 (current-day OHLCV excluded) and #987 (requested end_date
row omitted).
"""
from types import SimpleNamespace
import pandas as pd
import pytest
@@ -44,7 +46,7 @@ def test_load_ohlcv_requests_inclusive_end(monkeypatch, tmp_path):
set_config({"data_cache_dir": str(tmp_path)})
captured = {}
def fake_download(symbol, start, end, **kwargs):
def fake_history(start, end, **kwargs):
captured["end"] = end
idx = pd.to_datetime([pd.Timestamp.today().normalize()])
return pd.DataFrame(
@@ -53,7 +55,7 @@ def test_load_ohlcv_requests_inclusive_end(monkeypatch, tmp_path):
index=idx,
)
monkeypatch.setattr(ohlcv.yf, "download", fake_download)
monkeypatch.setattr(ohlcv.yf, "Ticker", lambda symbol: SimpleNamespace(history=fake_history))
today = pd.Timestamp.today().strftime("%Y-%m-%d")
ohlcv.load_ohlcv("AAPL", today)
+43 -49
View File
@@ -2,7 +2,6 @@
from __future__ import annotations
import importlib
import os
import pytest
@@ -10,27 +9,27 @@ import pytest
import tradingagents.default_config as default_config_module
def _reload_with_env(monkeypatch, **overrides):
"""Set/clear env vars then reload default_config to re-evaluate DEFAULT_CONFIG."""
def _config_with_env(monkeypatch, **overrides):
"""The defaults as the environment given here would set them."""
for key in list(default_config_module._ENV_OVERRIDES):
monkeypatch.delenv(key, raising=False)
for key, val in overrides.items():
monkeypatch.setenv(key, val)
return importlib.reload(default_config_module)
return default_config_module.build_default_config()
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-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
config = _config_with_env(monkeypatch)
assert config["llm_provider"] == "openai"
assert config["deep_think_llm"] == "gpt-6-sol"
assert config["quick_think_llm"] == "gpt-6-luna"
assert config["backend_url"] is None
assert config["max_debate_rounds"] == 1
assert config["checkpoint_enabled"] is False
def test_string_overrides(monkeypatch):
dc = _reload_with_env(
config = _config_with_env(
monkeypatch,
TRADINGAGENTS_LLM_PROVIDER="google",
TRADINGAGENTS_DEEP_THINK_LLM="gemini-3-pro-preview",
@@ -38,23 +37,23 @@ def test_string_overrides(monkeypatch):
TRADINGAGENTS_LLM_BACKEND_URL="https://example.invalid/v1",
TRADINGAGENTS_OUTPUT_LANGUAGE="Chinese",
)
assert dc.DEFAULT_CONFIG["llm_provider"] == "google"
assert dc.DEFAULT_CONFIG["deep_think_llm"] == "gemini-3-pro-preview"
assert dc.DEFAULT_CONFIG["quick_think_llm"] == "gemini-3-flash-preview"
assert dc.DEFAULT_CONFIG["backend_url"] == "https://example.invalid/v1"
assert dc.DEFAULT_CONFIG["output_language"] == "Chinese"
assert config["llm_provider"] == "google"
assert config["deep_think_llm"] == "gemini-3-pro-preview"
assert config["quick_think_llm"] == "gemini-3-flash-preview"
assert config["backend_url"] == "https://example.invalid/v1"
assert config["output_language"] == "Chinese"
def test_int_coercion(monkeypatch):
dc = _reload_with_env(
config = _config_with_env(
monkeypatch,
TRADINGAGENTS_MAX_DEBATE_ROUNDS="3",
TRADINGAGENTS_MAX_RISK_ROUNDS="2",
)
assert dc.DEFAULT_CONFIG["max_debate_rounds"] == 3
assert isinstance(dc.DEFAULT_CONFIG["max_debate_rounds"], int)
assert dc.DEFAULT_CONFIG["max_risk_discuss_rounds"] == 2
assert isinstance(dc.DEFAULT_CONFIG["max_risk_discuss_rounds"], int)
assert config["max_debate_rounds"] == 3
assert isinstance(config["max_debate_rounds"], int)
assert config["max_risk_discuss_rounds"] == 2
assert isinstance(config["max_risk_discuss_rounds"], int)
@pytest.mark.parametrize(
@@ -65,65 +64,62 @@ def test_int_coercion(monkeypatch):
],
)
def test_bool_coercion(monkeypatch, raw, expected):
dc = _reload_with_env(monkeypatch, TRADINGAGENTS_CHECKPOINT_ENABLED=raw)
assert dc.DEFAULT_CONFIG["checkpoint_enabled"] is expected
config = _config_with_env(monkeypatch, TRADINGAGENTS_CHECKPOINT_ENABLED=raw)
assert config["checkpoint_enabled"] is expected
def test_reasoning_thinking_overrides(monkeypatch):
"""The provider reasoning/thinking knobs are env-configurable (non-interactive runs)."""
dc = _reload_with_env(
config = _config_with_env(
monkeypatch,
TRADINGAGENTS_OPENAI_REASONING_EFFORT="high",
TRADINGAGENTS_GOOGLE_THINKING_LEVEL="minimal",
TRADINGAGENTS_ANTHROPIC_EFFORT="low",
)
assert dc.DEFAULT_CONFIG["openai_reasoning_effort"] == "high"
assert dc.DEFAULT_CONFIG["google_thinking_level"] == "minimal"
assert dc.DEFAULT_CONFIG["anthropic_effort"] == "low"
assert config["openai_reasoning_effort"] == "high"
assert config["google_thinking_level"] == "minimal"
assert config["anthropic_effort"] == "low"
def test_reasoning_effort_defaults_to_none(monkeypatch):
"""Unset reasoning/thinking knobs stay None so each provider uses its own default."""
dc = _reload_with_env(monkeypatch)
assert dc.DEFAULT_CONFIG["openai_reasoning_effort"] is None
assert dc.DEFAULT_CONFIG["google_thinking_level"] is None
assert dc.DEFAULT_CONFIG["anthropic_effort"] is None
config = _config_with_env(monkeypatch)
assert config["openai_reasoning_effort"] is None
assert config["google_thinking_level"] is None
assert config["anthropic_effort"] is None
def test_empty_env_value_is_passthrough(monkeypatch):
"""Empty TRADINGAGENTS_* values must not clobber the built-in default."""
dc = _reload_with_env(
config = _config_with_env(
monkeypatch,
TRADINGAGENTS_LLM_PROVIDER="",
TRADINGAGENTS_MAX_DEBATE_ROUNDS="",
)
assert dc.DEFAULT_CONFIG["llm_provider"] == "openai"
assert dc.DEFAULT_CONFIG["max_debate_rounds"] == 1
assert config["llm_provider"] == "openai"
assert 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(
config = _config_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")
home = default_config_module._TRADINGAGENTS_HOME
assert config["results_dir"] == os.path.join(home, "logs")
assert config["data_cache_dir"] == os.path.join(home, "cache")
assert 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")
with pytest.raises(ValueError, match="TRADINGAGENTS_MAX_DEBATE_ROUNDS"):
importlib.reload(default_config_module)
# Restore module state for subsequent tests in this process
monkeypatch.delenv("TRADINGAGENTS_MAX_DEBATE_ROUNDS", raising=False)
importlib.reload(default_config_module)
default_config_module.build_default_config()
@pytest.mark.parametrize("bad", ["treu", "flase", "maybe", "2", "enabled"])
@@ -131,15 +127,13 @@ def test_invalid_bool_raises(monkeypatch, bad):
"""A misspelled boolean must fail loudly (like ints) instead of silently False."""
monkeypatch.setenv("TRADINGAGENTS_CHECKPOINT_ENABLED", bad)
with pytest.raises(ValueError, match="TRADINGAGENTS_CHECKPOINT_ENABLED"):
importlib.reload(default_config_module)
monkeypatch.delenv("TRADINGAGENTS_CHECKPOINT_ENABLED", raising=False)
importlib.reload(default_config_module)
default_config_module.build_default_config()
def test_unknown_env_var_is_ignored(monkeypatch):
"""Env vars outside _ENV_OVERRIDES must not bleed into DEFAULT_CONFIG."""
dc = _reload_with_env(
config = _config_with_env(
monkeypatch,
TRADINGAGENTS_NONEXISTENT_KEY="oops",
)
assert "nonexistent_key" not in dc.DEFAULT_CONFIG
assert "nonexistent_key" not in config
+31 -10
View File
@@ -58,6 +58,25 @@ class FredResolutionTests(unittest.TestCase):
self.assertEqual(fred._resolve_series_id("Fed Funds Rate"), "FEDFUNDS")
self.assertEqual(fred._resolve_series_id("10y-treasury"), "DGS10")
def test_euro_area_aliases_map_to_series_ids(self):
# Euro-area context for non-US tickers (e.g. Euronext .PA): FRED mirrors
# the ECB policy rates, Eurostat HICP/GDP and OECD long-term yields.
expected = {
"ecb_deposit_rate": "ECBDFR",
"ecb_main_refi_rate": "ECBMRRFR",
"euro_hicp": "CP0000EZ19M086NEST",
"euro_core_hicp": "00XEFDEZ19M086NEST",
"euro_real_gdp": "CLVMNACSCAB1GQEA19",
"germany_10y": "IRLTLT01DEM156N",
"france_10y": "IRLTLT01FRM156N",
"eur_usd": "DEXUSEU",
}
for alias, series_id in expected.items():
with self.subTest(alias=alias):
self.assertEqual(fred._resolve_series_id(alias), series_id)
self.assertEqual(fred._resolve_series_id("ECB Deposit Rate"), "ECBDFR")
self.assertEqual(fred._resolve_series_id("euro-hicp"), "CP0000EZ19M086NEST")
def test_unknown_alias_is_treated_as_raw_series_id(self):
# Power users can pass any FRED series ID; we uppercase by convention.
self.assertEqual(fred._resolve_series_id("dgs30"), "DGS30")
@@ -98,8 +117,10 @@ class FredFormattingTests(unittest.TestCase):
self.assertIn("Units: %", out)
self.assertIn("Frequency: Monthly (SA)", out)
self.assertIn("**Latest:** 4.4 (2025-09-01)", out)
# change over the window: 4.4 - 4.1 = +0.30
self.assertIn("+0.30", out)
# The change names the observations it spans, not the lookback window,
# so a 3-month move on a monthly series cannot read as year on year.
self.assertIn("**Change from 2025-06-01 to 2025-09-01:** +0.30 (+7.32%), from 4.1", out)
self.assertNotIn("Change over window", out)
self.assertIn("| 2025-06-01 | 4.1 |", out)
def test_missing_value_is_skipped(self):
@@ -133,13 +154,13 @@ class FredFormattingTests(unittest.TestCase):
with mock.patch.object(fred, "_request", side_effect=_request_stub(obs=obs)):
out = fred.get_macro_data("unemployment", "2025-12-31", 365)
self.assertIn(f"most recent {fred.MAX_ROWS}", out)
# change-over-window must reference the true first (0) and last value
self.assertIn("from 0 ", out)
# the change must reference the true first (0) and last value
self.assertIn("+49.00, from 0\n", out)
body_rows = [ln for ln in out.splitlines() if ln.startswith("| 2025")]
self.assertEqual(len(body_rows), fred.MAX_ROWS)
def test_window_is_lookahead_safe(self):
# observation_end must equal curr_date so a past date never pulls future data.
# observation_end must equal as_of_date so a past date never pulls future data.
captured = {}
def _capture(path, params):
@@ -154,9 +175,9 @@ class FredFormattingTests(unittest.TestCase):
def test_requests_pin_the_data_vintage(self):
# #1275: both the metadata and observations requests must pin the vintage
# to curr_date (clamped to FRED's today), or FRED serves the latest
# to as_of_date (clamped to FRED's today), or FRED serves the latest
# revision and revision-prone series leak future information. A past
# curr_date sits below FRED's today, so it pins through unchanged.
# as_of_date sits below FRED's today, so it pins through unchanged.
captured = {}
def _capture(path, params):
@@ -172,11 +193,11 @@ class FredFormattingTests(unittest.TestCase):
self.assertEqual(captured[path]["realtime_end"], "2025-09-30", path)
def test_future_curr_date_clamps_vintage_to_fred_today(self):
# #1275 regression: on a live run curr_date is the caller's LOCAL date,
# #1275 regression: on a live run as_of_date is the caller's LOCAL date,
# which can be a day ahead of FRED's US-Central clock. Pinning the vintage
# to that future date 400s, and the routing layer then drops macro data
# silently. The pin must clamp to FRED's today; the observation window
# (future bars can't exist yet) stays at curr_date.
# (future bars can't exist yet) stays at as_of_date.
captured = {}
def _capture(path, params):
@@ -190,7 +211,7 @@ class FredFormattingTests(unittest.TestCase):
for path in ("series", "series/observations"):
self.assertEqual(captured[path]["realtime_start"], "2026-08-31", path)
self.assertEqual(captured[path]["realtime_end"], "2026-08-31", path)
# the observation window still tracks curr_date, not the clamped vintage
# the observation window still tracks as_of_date, not the clamped vintage
self.assertEqual(captured["series/observations"]["observation_end"], "2026-09-01")
+9 -6
View File
@@ -10,7 +10,7 @@ FRED (#1275), social (#1220) and memory (#1251) leaks.
Both vendors withhold on one shared rule (``date_window.withhold_live_profile``)
so switching ``fundamental_data`` between them cannot reintroduce the leak. The
statement tools stay point-in-time by filtering on ``curr_date``, and a live run
statement tools stay point-in-time by filtering on ``as_of_date``, and a live run
is unchanged. All API access is mocked.
"""
from __future__ import annotations
@@ -45,19 +45,19 @@ _LEAKY = ("3500000000000", "34.2", "260.1", "391000000000",
"Apple Inc.", "Technology", "Consumer Electronics")
def _yf(curr_date, info=_INFO, today=_TODAY):
def _yf(as_of_date, info=_INFO, today=_TODAY):
with mock.patch.object(date_window, "get_current_date", return_value=today), \
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)
return yahoo_fundamentals.get_fundamentals("AAPL", as_of_date)
def _av(curr_date, today=_TODAY):
def _av(as_of_date, today=_TODAY):
"""Alpha Vantage path; the API call is mocked so a leak would be visible."""
with mock.patch.object(date_window, "get_current_date", return_value=today), \
mock.patch.object(av, "_make_api_request",
return_value="MarketCapitalization: 3500000000000") as req:
return av.get_fundamentals("AAPL", curr_date), req
return av.get_fundamentals("AAPL", as_of_date), req
@pytest.mark.unit
@@ -125,10 +125,13 @@ class TestLiveRunUnchanged:
@pytest.mark.unit
class TestNoUsableFieldsStillRaises:
def test_stub_payload_raises_no_market_data(self):
def test_stub_payload_raises_no_market_data(self, monkeypatch):
# 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.errors import NoMarketDataError
from tradingagents.dataflows.vendors.yahoo import common
monkeypatch.setattr(common, "vendor_reachable", lambda url: True)
with pytest.raises(NoMarketDataError):
_yf(_TODAY, info={"trailingPegRatio": None})
+79
View File
@@ -0,0 +1,79 @@
"""Yahoo's percent-valued fields say they are percentages (#1414).
``Ticker.info`` gives ``dividendYield`` and ``debtToEquity`` in percent (0.41 is
0.41%; 78.4 is 78.4%, a ratio of 0.78) but margins and returns as fractions
(0.27 is 27%). Printed side by side without a unit, one scale reads as the other.
"""
from unittest import mock
import pytest
from tradingagents.dataflows import date_window
from tradingagents.dataflows.vendors.yahoo import fundamentals
TODAY = "2026-09-26"
def _fundamentals(info):
with mock.patch.object(date_window, "get_current_date", return_value=TODAY), \
mock.patch.object(fundamentals, "yf_retry", lambda fn: info):
return fundamentals.get_fundamentals("AAPL", TODAY)
@pytest.mark.unit
def test_percent_fields_carry_their_unit_and_fractions_are_unchanged():
out = _fundamentals({"longName": "Apple Inc.", "dividendYield": 0.32, "debtToEquity": 78.445,
"profitMargins": 0.27619, "returnOnEquity": 1.4875101})
assert "Dividend Yield: 0.32%" in out
assert "Debt to Equity: 78.445% (0.78x)" in out
assert "Profit Margin: 0.27619" in out
assert "Return on Equity: 1.4875101" in out
@pytest.mark.unit
def test_an_absent_percent_field_is_left_out():
out = _fundamentals({"longName": "JPMorgan Chase & Co.", "profitMargins": 0.35})
assert "Dividend Yield" not in out and "Debt to Equity" not in out
@pytest.mark.unit
def test_each_money_figure_carries_the_currency_it_is_in():
"""Yahoo quotes London in pence but states EPS and market cap in pounds, and
the income figures in the reporting currency (#1456)."""
out = _fundamentals({"longName": "Shell plc", "currency": "GBp", "financialCurrency": "USD",
"marketCap": 203440193536, "trailingEps": 3.42, "bookValue": 29.1,
"fiftyTwoWeekHigh": 3800.0, "fiftyDayAverage": 3500.5,
"totalRevenue": 296600993792, "netIncomeToCommon": 25970999296})
assert "Market Cap: 203440193536 GBP" in out
assert "EPS (TTM): 3.42 GBP" in out and "Book Value: 29.1 GBP" in out
assert "52 Week High: 3800.0 GBp" in out and "50 Day Average: 3500.5 GBp" in out
assert "Revenue (TTM): 296600993792 USD" in out and "Net Income: 25970999296 USD" in out
@pytest.mark.unit
def test_an_adr_quotes_in_dollars_and_reports_in_its_home_currency():
out = _fundamentals({"longName": "TSMC", "currency": "USD", "financialCurrency": "TWD",
"marketCap": 2365000000000, "trailingEps": 13.21, "totalRevenue": 4440492343296})
assert "Market Cap: 2365000000000 USD" in out and "EPS (TTM): 13.21 USD" in out
assert "Revenue (TTM): 4440492343296 TWD" in out
@pytest.mark.unit
def test_a_figure_with_no_stated_currency_is_printed_bare():
out = _fundamentals({"longName": "X", "marketCap": 1000, "totalRevenue": 50})
assert "Market Cap: 1000\n" in out + "\n" and "Revenue (TTM): 50" in out and "None" not in out
@pytest.mark.unit
def test_income_figures_without_a_stated_reporting_currency_are_printed_bare():
"""The quote currency is not evidence of the reporting currency (an ADR quotes
in USD and reports in TWD), so an unknown one is not guessed."""
out = _fundamentals({"longName": "X", "currency": "USD", "marketCap": 1000, "totalRevenue": 50})
assert "Market Cap: 1000 USD" in out and "Revenue (TTM): 50\n" in out + "\n"
+65
View File
@@ -0,0 +1,65 @@
"""``get_scrubbed``: the vendor key must not survive into an error.
FRED and Alpha Vantage authenticate with a query parameter, so requests quotes
the key back in the text of HTTP, connection and timeout errors, and in the
``request`` and ``response`` it attaches (#1324).
"""
from unittest import mock
import pytest
import requests
from tradingagents.dataflows.net import get_scrubbed
# A fabricated value in the shape of a FRED key.
_KEY = "deadbeefdeadbeefdeadbeefdeadbeef"
_LEAK = (
"HTTPSConnectionPool(host='api.stlouisfed.org', port=443): Max retries "
f"exceeded with url: /fred/series?series_id=DGS10&api_key={_KEY}&file_type=json"
)
def _response(status_code):
response = mock.Mock(spec=requests.Response)
response.status_code = status_code
response.raise_for_status.side_effect = requests.HTTPError(_LEAK) if status_code >= 400 else None
return response
def _call(**kwargs):
return get_scrubbed("https://api.stlouisfed.org/fred/series",
params={"api_key": _KEY}, timeout=5, secret=_KEY, **kwargs)
@pytest.mark.unit
@pytest.mark.parametrize("failure", [
{"side_effect": requests.ConnectionError(_LEAK)},
{"return_value": _response(500)},
], ids=["transport", "status"])
def test_the_key_is_masked_in_the_error(failure):
with mock.patch.object(requests, "get", **failure), pytest.raises(requests.RequestException) as caught:
_call()
assert _KEY not in str(caught.value) and _KEY not in repr(caught.value.args)
assert "api_key=***" in str(caught.value)
@pytest.mark.unit
def test_nothing_that_holds_the_url_travels_with_the_error():
"""The request, the response and a chained original each carry the full URL."""
leaky = requests.ConnectionError(_LEAK)
leaky.request = mock.Mock(url=f"https://x.invalid/?api_key={_KEY}")
leaky.response = mock.Mock(url=f"https://x.invalid/?api_key={_KEY}")
with mock.patch.object(requests, "get", side_effect=leaky), pytest.raises(requests.ConnectionError) as caught:
_call()
error = caught.value
assert error.request is None and error.response is None
assert error.__cause__ is None and error.__context__ is None
@pytest.mark.unit
def test_a_passthrough_status_is_returned_for_the_caller():
response = _response(400)
with mock.patch.object(requests, "get", return_value=response):
assert _call(passthrough=(400,)) is response
response.raise_for_status.assert_not_called()
+8
View File
@@ -60,3 +60,11 @@ def test_no_thinking_level_is_omitted():
kw = _captured_kwargs("gemini-3.5-flash")
assert "thinking_level" not in kw
assert "thinking_budget" not in kw
@pytest.mark.unit
def test_a_gemini_call_times_out_like_the_other_providers():
"""The OpenAI and Anthropic SDKs give up after 600s; Gemini's waits forever
unless told otherwise, so a stalled call would hang the run (#1417)."""
assert _captured_kwargs("gemini-3.5-flash")["timeout"] == 600
assert _captured_kwargs("gemini-3.5-flash", timeout=30)["timeout"] == 30
+227 -7
View File
@@ -8,11 +8,12 @@ the wiring: a restructure that drops a node, a tool or an edge fails here.
from __future__ import annotations
import copy
import time
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.messages import AIMessage, HumanMessage, ToolMessage
from langchain_core.outputs import ChatGeneration, ChatResult
from langchain_core.runnables import RunnableLambda
from pydantic import Field
@@ -34,8 +35,10 @@ STRUCTURED = {
schemas.ResearchPlan: schemas.ResearchPlan(
recommendation=schemas.PortfolioRating.OVERWEIGHT, rationale="r", strategic_actions="a"),
schemas.TraderProposal: schemas.TraderProposal(action=schemas.TraderAction.BUY, reasoning="r"),
# The thesis quotes another party's rating; the decision is still the PM's own.
schemas.PortfolioDecision: schemas.PortfolioDecision(
rating=schemas.PortfolioRating.OVERWEIGHT, executive_summary="s", investment_thesis="t"),
rating=schemas.PortfolioRating.OVERWEIGHT, executive_summary="s",
investment_thesis="Street consensus rating: Buy (28 of 35 analysts)."),
schemas.SentimentReport: schemas.SentimentReport(
overall_band=schemas.SentimentBand.NEUTRAL, overall_score=5.0, confidence="low", narrative="n"),
}
@@ -50,6 +53,7 @@ class ScriptedModel(BaseChatModel):
structured: bool = False
tools: tuple = ()
calls: list = Field(default_factory=list) # shared across bound copies
threads: set = Field(default_factory=set) # threads that served a tool-bound call
fail_at: int | None = None # raise on this call, once
@property
@@ -71,6 +75,11 @@ class ScriptedModel(BaseChatModel):
def _generate(self, messages, stop=None, run_manager=None, **kwargs) -> ChatResult:
self._count()
if self.tools:
import threading
import time
self.threads.add(threading.current_thread().name)
time.sleep(0.05) # long enough for concurrent analysts to overlap
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()
@@ -107,16 +116,16 @@ def offline(monkeypatch, tmp_path):
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()
context._identity.cache_clear()
return called
def _graph(tmp_path, monkeypatch, model, **config):
def _graph(tmp_path, monkeypatch, model, debug=False, **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)
monkeypatch.setattr(trading_graph, "create_tier_client", lambda config, tier, **k: _Client(model))
return trading_graph.TradingAgentsGraph(config=cfg, debug=debug)
@pytest.mark.unit
@@ -126,7 +135,7 @@ def test_a_full_run_reaches_a_logged_decision(tmp_path, monkeypatch, offline, st
state, signal = graph.propagate("NVDA", TRADE_DATE)
assert signal == "Overweight"
assert signal == state["final_rating"] == "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
@@ -167,3 +176,214 @@ def test_a_graph_reused_across_runs_keeps_no_run_state(tmp_path, monkeypatch, of
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
@pytest.mark.unit
def test_the_analysts_run_at_the_same_time(tmp_path, monkeypatch, offline):
model = ScriptedModel()
graph = _graph(tmp_path, monkeypatch, model)
assert not [n for n in graph.graph.get_graph().nodes if n.startswith("Msg Clear")]
graph.propagate("NVDA", TRADE_DATE)
assert len(model.threads) > 1
@pytest.mark.unit
def test_a_debug_run_prints_the_analysts_work_and_reaches_the_same_decision(tmp_path, monkeypatch, offline, capsys):
"""Debug mode streams the analysts' own graphs, so their tool calls still print."""
graph = _graph(tmp_path, monkeypatch, ScriptedModel(), debug=True)
state, signal = graph.propagate("NVDA", TRADE_DATE)
assert signal == "Overweight"
assert state["market_report"].strip() and state["fundamentals_report"].strip()
printed = capsys.readouterr().out
assert "get_stock_data" in printed and "get_balance_sheet" in printed
@pytest.mark.unit
def test_each_report_streams_as_soon_as_its_analyst_files_it(tmp_path, monkeypatch, offline):
"""The main state takes the analysts' reports only when the slowest one is
done; the CLI shows each report, and stops each clock, as it lands."""
graph = _graph(tmp_path, monkeypatch, ScriptedModel())
reports = ("market_report", "sentiment_report", "news_report", "fundamentals_report")
first = next(state for _, state in graph.stream_run(graph.create_run_state("NVDA", TRADE_DATE),
**graph.propagator.get_graph_args())
if state and any(state.get(k) for k in reports))
assert sum(bool(first.get(k)) for k in reports) == 1
@pytest.mark.unit
def test_a_streamed_run_reads_its_own_graph_config(tmp_path, monkeypatch, offline):
"""The CLI streams the run; a process-wide config set elsewhere must not reach
its tools, and the graph's config must not reach the caller between steps."""
from tradingagents.dataflows.config import get_config, set_config
graph = _graph(tmp_path, monkeypatch, ScriptedModel(), output_language="French")
set_config({"output_language": "German"})
seen = []
monkeypatch.setitem(router.VENDOR_METHODS["get_stock_data"], "yfinance",
lambda *a, **k: seen.append(get_config()["output_language"]) or "prices")
between = [get_config()["output_language"]
for _ in graph.stream_run(graph.create_run_state("NVDA", TRADE_DATE), **graph.propagator.get_graph_args())]
assert seen and set(seen) == {"French"}
assert set(between) == {"German"}
class LoopingModel(ScriptedModel):
"""Calls a tool on every turn it is offered one (#1420)."""
tool_turns: list = Field(default_factory=list) # shared across bound copies
last_turns: list = Field(default_factory=list) # histories of the turns offered no tools
def _generate(self, messages, stop=None, run_manager=None, **kwargs) -> ChatResult:
if not self.tools:
self.last_turns.append(messages)
return super()._generate(messages, stop, run_manager, **kwargs)
self.tool_turns.append(1)
tool = self.tools[0]
call = {"name": tool.name, "id": f"call_{len(self.tool_turns)}",
"args": {k: v for k, v in ARGS.items()
if k in tool.tool_call_schema.model_json_schema()["properties"]}}
return ChatResult(generations=[ChatGeneration(message=AIMessage(content="", tool_calls=[call]))])
@pytest.mark.unit
def test_an_analyst_that_keeps_calling_tools_writes_its_report_at_the_limit(tmp_path, monkeypatch, offline):
"""A model that does not stop calling tools must not end the run (#1420)."""
model = LoopingModel(structured=True)
graph = _graph(tmp_path, monkeypatch, model, max_tool_rounds=3)
final_state, rating = graph.propagate("NVDA", TRADE_DATE)
assert len(model.tool_turns) == 3 * 3 # three tool-using analysts, three rounds each
for key in ("market_report", "news_report", "fundamentals_report"):
assert final_state[key] == TEXT
assert rating == "Overweight"
@pytest.mark.unit
def test_the_last_turn_is_offered_no_tools_and_reads_its_tool_results_as_text(tmp_path, monkeypatch, offline):
"""Offered tools, a model may call one whatever it is told; a history holding
tool calls may be refused by a provider when no tools are bound."""
model = LoopingModel(structured=True)
graph = _graph(tmp_path, monkeypatch, model, max_tool_rounds=2)
graph.propagate("NVDA", TRADE_DATE)
wrap_ups = [h for h in model.last_turns if isinstance(h[-1], HumanMessage) and "tool round" in h[-1].content]
assert len(wrap_ups) == 3
for history in wrap_ups:
assert not any(isinstance(m, ToolMessage) or getattr(m, "tool_calls", None) for m in history)
assert any("returned]" in str(m.content) for m in history)
assert "tool rounds are spent" in history[0].content # the system prompt lists no tools
@pytest.mark.unit
def test_a_tool_limit_the_recursion_limit_cannot_hold_is_refused(tmp_path, monkeypatch):
with pytest.raises(ValueError, match="max_tool_rounds"):
_graph(tmp_path, monkeypatch, ScriptedModel(), max_tool_rounds=60, max_recur_limit=100)
class TimedModel(ScriptedModel):
"""ScriptedModel that records each call's graph step, prompt and timing."""
seen: list = Field(default_factory=list) # shared across bound copies
def _generate(self, messages, stop=None, run_manager=None, **kwargs) -> ChatResult:
step = (run_manager.metadata or {}).get("langgraph_node") if run_manager else None
started = time.monotonic()
if step in {"Market Analyst", "agent"} or step == "Memory Log":
time.sleep(0.2) # long enough to see what overlaps
result = super()._generate(messages, stop, run_manager, **kwargs)
prompt = "\n".join(str(m.content) for m in messages)
self.seen.append((step, prompt, started, time.monotonic()))
return result
@pytest.mark.unit
def test_past_decisions_settle_alongside_the_analysts(tmp_path, monkeypatch, offline):
from tradingagents.memory import settlement
model = TimedModel()
graph = _graph(tmp_path, monkeypatch, model)
graph.memory_log.store_decision("NVDA", "2025-12-31", "Rating: Buy\n\nBuy NVDA.")
closes = pd.Series([100.0 + i for i in range(10)], index=pd.bdate_range("2026-01-02", periods=10))
monkeypatch.setattr(settlement, "get_closes", lambda *a, **k: closes)
graph.propagate("NVDA", TRADE_DATE)
reflections = [c for c in model.seen if c[0] == "Memory Log"]
assert len(reflections) == 1 # settled once, inside the run
analyst_turns = [c for c in model.seen if c[0] == "agent"]
assert reflections[0][2] < max(c[3] for c in analyst_turns), "settled before the analysts, not alongside"
settled = next(e for e in graph.memory_log.load_entries() if e["date"] == "2025-12-31")
assert not settled["pending"]
lessons = graph.memory_log.get_past_context("NVDA", as_of=TRADE_DATE)
assert lessons
pm_prompt = next(c[1] for c in model.seen if c[0] == "Portfolio Manager")
assert lessons in pm_prompt
@pytest.mark.unit
def test_a_settlement_failure_is_noted_and_the_run_goes_on(tmp_path, monkeypatch, offline):
"""The analysts have spent their tokens by the time the join waits on settlement."""
from tradingagents.reporting import write_report_tree
graph = _graph(tmp_path, monkeypatch, ScriptedModel(structured=True))
def locked():
raise OSError("memory log is locked")
monkeypatch.setattr(graph, "settle_all_pending", locked)
final_state, rating = graph.propagate("NVDA", TRADE_DATE)
assert rating == "Overweight"
assert "could not be settled" in final_state["memory_note"]
report = write_report_tree(final_state, "NVDA", tmp_path / "report").read_text()
assert "Memory log: Past decisions could not be settled" in report
@pytest.mark.unit
def test_the_run_settles_other_tickers_due_decisions_too(tmp_path, monkeypatch, offline):
"""A ticker a scheduler stopped analysing still gets its decisions settled (#1445)."""
from tradingagents.memory import settlement
graph = _graph(tmp_path, monkeypatch, ScriptedModel(structured=True))
graph.memory_log.store_decision("MSFT", "2026-01-02", "Rating: Buy\n\nBuy MSFT.")
closes = pd.Series([100.0 + i for i in range(10)], index=pd.bdate_range("2026-01-02", periods=10))
monkeypatch.setattr(settlement, "get_closes", lambda *a, **k: closes)
graph.propagate("NVDA", TRADE_DATE)
msft = next(e for e in graph.memory_log.load_entries() if e["ticker"] == "MSFT")
assert not msft["pending"]
@pytest.mark.unit
def test_the_memory_step_reads_lessons_as_of_the_trade_date_and_settles_once(tmp_path, monkeypatch, offline):
"""A past-dated run reads only lessons known by its date (#1251); a resumed run
that re-runs the step settles nothing twice."""
from tradingagents.memory import settlement
graph = _graph(tmp_path, monkeypatch, ScriptedModel(structured=True))
graph.memory_log.store_decision("NVDA", "2025-12-31", "Rating: Buy\n\nBuy NVDA.")
closes = pd.Series([100.0 + i for i in range(10)], index=pd.bdate_range("2026-01-02", periods=10))
monkeypatch.setattr(settlement, "get_closes", lambda *a, **k: closes)
asked = []
real = graph.memory_log.get_past_context
monkeypatch.setattr(graph.memory_log, "get_past_context",
lambda ticker, as_of=None, **k: asked.append(as_of) or real(ticker, as_of=as_of, **k))
state = {"company_of_interest": "NVDA", "trade_date": "2026-01-20"}
graph._memory_step(state)
log_after_first = (tmp_path / "log.md").read_text()
graph._memory_step(state)
assert asked == ["2026-01-20", "2026-01-20"]
assert (tmp_path / "log.md").read_text() == log_after_first
+9
View File
@@ -46,6 +46,15 @@ class TestLanguageInstruction:
assert "中文" in out
assert "entire response" in out
def test_the_labelled_lines_stay_as_the_format_gives_them(self):
# The rating is read from its "**Rating**:" line; a translated label
# leaves the reader a translated negation ("不建议卖出 (Sell)") to find
# instead, and a Buy reads as Sell (#1435).
from tradingagents.dataflows.config import set_config
set_config({"output_language": "中文"})
out = get_language_instruction()
assert "**Rating**:" in out and "FINAL TRANSACTION PROPOSAL" in out
@pytest.mark.unit
@pytest.mark.parametrize("rel", REPORT_AGENTS)
+11 -51
View File
@@ -5,11 +5,10 @@ import unittest
from unittest.mock import patch
import pytest
from langchain_core.messages import AIMessage, HumanMessage, RemoveMessage
from tradingagents.agents.context import (
_identity,
build_instrument_context,
create_msg_delete,
get_instrument_context_from_state,
resolve_instrument_identity,
)
@@ -18,7 +17,7 @@ from tradingagents.agents.context import (
@pytest.mark.unit
class ResolveInstrumentIdentityTests(unittest.TestCase):
def setUp(self):
resolve_instrument_identity.cache_clear()
_identity.cache_clear()
def test_resolves_company_metadata_from_yfinance(self):
with patch("tradingagents.dataflows.vendors.yahoo.market.yf.Ticker") as mock:
@@ -56,6 +55,15 @@ class ResolveInstrumentIdentityTests(unittest.TestCase):
):
self.assertEqual(resolve_instrument_identity("TOTDY"), {})
def test_a_failed_lookup_is_asked_again(self):
# A long process (a backtest) must not run every later cell without an
# identity because one request failed.
with patch("tradingagents.dataflows.vendors.yahoo.market.yf.Ticker") as mock:
type(mock.return_value).info = property(lambda self: (_ for _ in ()).throw(TimeoutError()))
self.assertEqual(resolve_instrument_identity("TOTDY"), {})
type(mock.return_value).info = {"longName": "TOTO LTD."}
self.assertEqual(resolve_instrument_identity("TOTDY")["company_name"], "TOTO LTD.")
def test_result_is_cached(self):
with patch("tradingagents.dataflows.vendors.yahoo.market.yf.Ticker") as mock:
mock.return_value.info = {"longName": "TOTO LTD."}
@@ -118,53 +126,5 @@ class GetInstrumentContextFromStateTests(unittest.TestCase):
self.assertIn("crypto asset", context)
@pytest.mark.unit
class ContextAnchoredPlaceholderTests(unittest.TestCase):
"""#888 — the message-clear placeholder must not be a bare 'Continue'."""
def _run(self, state_extra):
state = {
"messages": [
HumanMessage(content="old", id="h1"),
AIMessage(content="reply", id="a1"),
],
**state_extra,
}
return create_msg_delete()(state)
def test_placeholder_is_not_bare_continue(self):
result = self._run(
{"company_of_interest": "EC", "asset_type": "stock", "trade_date": "2026-05-28"}
)
placeholder = result["messages"][-1]
self.assertIsInstance(placeholder, HumanMessage)
self.assertNotEqual(placeholder.content.strip(), "Continue")
def test_placeholder_carries_resolved_identity(self):
result = self._run(
{
"company_of_interest": "EC",
"instrument_context": "The instrument to analyze is `EC`. Resolved identity: Company: Ecopetrol.",
"trade_date": "2026-05-28",
}
)
content = result["messages"][-1].content
self.assertIn("Ecopetrol", content)
self.assertIn("2026-05-28", content)
def test_old_messages_are_removed(self):
result = self._run({"company_of_interest": "EC", "trade_date": "2026-05-28"})
removals = [m for m in result["messages"] if isinstance(m, RemoveMessage)]
humans = [m for m in result["messages"] if isinstance(m, HumanMessage)]
self.assertEqual(len(removals), 2)
self.assertEqual(len(humans), 1)
def test_safe_defaults_when_state_minimal(self):
result = create_msg_delete()({"messages": [], "company_of_interest": "EC"})
placeholder = result["messages"][-1]
self.assertNotEqual(placeholder.content.strip(), "Continue")
self.assertIn("EC", placeholder.content)
if __name__ == "__main__":
unittest.main()
+8 -9
View File
@@ -6,8 +6,6 @@ opt-in llm_max_retries knob forwarded to every provider chat client.
"""
from __future__ import annotations
import importlib
import pytest
import tradingagents.default_config as default_config_module
@@ -74,23 +72,24 @@ def test_invalid_config_value_fails_loudly():
# --- env overlay -----------------------------------------------------------
def _reload_with_env(monkeypatch, **overrides):
def _config_with_env(monkeypatch, **overrides):
"""The defaults as the environment given here would set them."""
for key in list(default_config_module._ENV_OVERRIDES):
monkeypatch.delenv(key, raising=False)
for key, val in overrides.items():
monkeypatch.setenv(key, val)
return importlib.reload(default_config_module)
return default_config_module.build_default_config()
@pytest.mark.unit
def test_default_is_none(monkeypatch):
dc = _reload_with_env(monkeypatch)
assert dc.DEFAULT_CONFIG["llm_max_retries"] is None
config = _config_with_env(monkeypatch)
assert config["llm_max_retries"] is None
@pytest.mark.unit
def test_env_override_sets_config(monkeypatch):
dc = _reload_with_env(monkeypatch, TRADINGAGENTS_LLM_MAX_RETRIES="8")
config = _config_with_env(monkeypatch, TRADINGAGENTS_LLM_MAX_RETRIES="8")
# None-default key: env value arrives as a string and is coerced downstream.
assert dc.DEFAULT_CONFIG["llm_max_retries"] == "8"
assert _coerce_max_retries(dc.DEFAULT_CONFIG["llm_max_retries"]) == 8
assert config["llm_max_retries"] == "8"
assert _coerce_max_retries(config["llm_max_retries"]) == 8
+8 -9
View File
@@ -8,8 +8,6 @@ right key per provider.
"""
from __future__ import annotations
import importlib
import pytest
import tradingagents.default_config as default_config_module
@@ -97,22 +95,23 @@ def test_openai_and_google_clients_accept_the_kwarg():
# --- env overlay -----------------------------------------------------------
def _reload_with_env(monkeypatch, **overrides):
def _config_with_env(monkeypatch, **overrides):
"""The defaults as the environment given here would set them."""
for key in list(default_config_module._ENV_OVERRIDES):
monkeypatch.delenv(key, raising=False)
for key, val in overrides.items():
monkeypatch.setenv(key, val)
return importlib.reload(default_config_module)
return default_config_module.build_default_config()
@pytest.mark.unit
def test_default_is_none(monkeypatch):
dc = _reload_with_env(monkeypatch)
assert dc.DEFAULT_CONFIG["max_tokens"] is None
config = _config_with_env(monkeypatch)
assert config["max_tokens"] is None
@pytest.mark.unit
def test_env_override_sets_config(monkeypatch):
dc = _reload_with_env(monkeypatch, TRADINGAGENTS_MAX_TOKENS="8192")
assert dc.DEFAULT_CONFIG["max_tokens"] == "8192"
assert _coerce_max_tokens(dc.DEFAULT_CONFIG["max_tokens"]) == 8192
config = _config_with_env(monkeypatch, TRADINGAGENTS_MAX_TOKENS="8192")
assert config["max_tokens"] == "8192"
assert _coerce_max_tokens(config["max_tokens"]) == 8192
+400 -18
View File
@@ -7,11 +7,10 @@ import pytest
from tradingagents.agents.managers.portfolio_manager import create_portfolio_manager
from tradingagents.agents.schemas import PortfolioDecision, PortfolioRating
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
from tradingagents.memory import TradingMemoryLog, settlement
from tradingagents.memory.reflection import Reflector
_SEP = TradingMemoryLog._SEPARATOR
@@ -75,7 +74,6 @@ def _make_pm_state(past_context=""):
"aggressive_history": "",
"conservative_history": "",
"neutral_history": "",
"judge_decision": "",
"current_aggressive_response": "",
"current_conservative_response": "",
"current_neutral_response": "",
@@ -302,6 +300,16 @@ class TestTradingMemoryLogCore:
assert "Buy entry 0" not in ctx
assert "Buy entry 5" in ctx
def test_the_most_recent_decisions_are_the_latest_dated_not_the_latest_written(self, tmp_path):
"""A backfill writes January after June; June is still the most recent lesson."""
log = make_log(tmp_path)
_seed_completed(tmp_path, "NVDA", "2026-06-01", "Buy entry June.", "Correct.")
for i in range(5):
_seed_completed(tmp_path, "NVDA", f"2026-01-{i+1:02d}", f"Buy entry {i}.", "Correct.")
ctx = log.get_past_context("NVDA", n_same=5)
assert "Buy entry June" in ctx and "Buy entry 0" not in ctx
assert ctx.index("Buy entry June") < ctx.index("Buy entry 4")
def test_n_cross_limit_respected(self, tmp_path):
"""Only the n_cross most recent cross-ticker entries are included."""
log = make_log(tmp_path)
@@ -343,6 +351,16 @@ class TestTradingMemoryLogCore:
dates = [e["date"] for e in entries]
assert dates == ["2026-01-03", "2026-01-04", "2026-01-05"]
def test_rotation_prunes_the_oldest_dated_not_the_first_written(self, tmp_path):
"""A backfill writes older dates last; rotation still keeps the newest decisions."""
log = TradingMemoryLog({
"memory_log_path": str(tmp_path / "trading_memory.md"),
"memory_log_max_entries": 3,
})
for date in ("2026-06-01", "2026-06-02", "2026-01-01", "2026-01-02", "2026-01-03"):
_resolve_entry(log, "NVDA", date, DECISION_BUY, f"Lesson {date}.")
assert sorted(e["date"] for e in log.load_entries()) == ["2026-01-03", "2026-06-01", "2026-06-02"]
def test_rotation_never_prunes_pending(self, tmp_path):
"""Pending entries (unresolved) are kept regardless of the cap."""
log = TradingMemoryLog({
@@ -514,8 +532,8 @@ class TestDeferredReflection:
# 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]
stock_prices = [100.0, 102.0, 104.0, 103.0, 105.0, 106.0, 107.0]
spy_prices = [400.0, 402.0, 404.0, 403.0, 405.0, 406.0, 407.0]
with patch("yfinance.Ticker") as mock_ticker_cls:
def _make_ticker(sym):
m = MagicMock()
@@ -526,8 +544,8 @@ class TestDeferredReflection:
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
# resolution date = the bar `days` sessions after the trade date (#1251)
assert resolved == "2026-01-10"
# resolution date = the bar `days` sessions after entry, the first close after the decision (#1251)
assert resolved == "2026-01-11"
def test_fetch_returns_too_recent(self):
"""Only 1 data point available → returns all-None, no crash."""
@@ -551,7 +569,7 @@ class TestDeferredReflection:
"""SPY having fewer rows than the stock (but still a full window) must
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
spy_prices = [400.0, 402.0, 403.0, 405.0, 406.0, 407.0, 408.0] # 7 rows
with patch("yfinance.Ticker") as mock_ticker_cls:
def _make_ticker(sym):
m = MagicMock()
@@ -561,7 +579,22 @@ class TestDeferredReflection:
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"
assert resolved == "2026-01-11"
def test_a_decision_is_scored_from_the_first_close_after_its_date(self):
"""#1518: news published after the close on the decision date reaches the
analysts, so the close of that date is not a price they could have traded at."""
stock_prices = [100.0, 150.0, 150.0, 150.0, 150.0, 150.0, 165.0] # jumps on the next close
spy_prices = [400.0] * 7
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 = settlement.fetch_returns("NVDA", "2026-01-05")
assert raw == pytest.approx(0.10) and alpha == pytest.approx(0.10) # 150 -> 165, not 100 -> 150
assert resolved == "2026-01-11"
def test_fetch_returns_incomplete_window_stays_pending(self):
"""#1169: a rerun before the full holding window has traded returns
@@ -628,6 +661,16 @@ class TestDeferredReflection:
"benchmark_map": DEFAULT_CONFIG["benchmark_map"]}
assert settlement.resolve_benchmark("PETR4.SA", config) == "^BVSP"
@pytest.mark.parametrize(("ticker", "index"), [
("2330.TW", "^TWII"), ("6488.TWO", "^TWII"), ("005930.KS", "^KS11"), ("247540.KQ", "^KQ11"), ("D05.SI", "^STI"), ("SAP.DE", "^GDAXI"),
("MC.PA", "^FCHI"), ("ASML.AS", "^AEX"), ("NESN.SW", "^SSMI"), ("ENI.MI", "FTSEMIB.MI"),
])
def test_resolve_benchmark_regional_indexes(self, ticker, index):
"""Taiwan, Korea, Singapore and the main European exchanges 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(ticker, config) == index
def test_resolve_benchmark_us_ticker_defaults_to_spy(self):
"""US tickers (no dotted suffix) take the empty-suffix entry."""
config = {
@@ -863,12 +906,12 @@ class TestLegacyRemoval:
def test_financial_situation_memory_removed(self):
"""FinancialSituationMemory must not be importable from the memory module."""
import tradingagents.decision_log as m
import tradingagents.memory as m
assert not hasattr(m, "FinancialSituationMemory")
def test_bm25_not_imported(self):
"""rank_bm25 must not be present in the memory module namespace."""
import tradingagents.decision_log as m
import tradingagents.memory as m
assert not hasattr(m, "BM25Okapi")
def test_reflect_and_remember_removed(self):
@@ -888,6 +931,7 @@ class TestLegacyRemoval:
fake_state = {
"final_trade_decision": "Rating: Buy\nBuy NVDA.",
"final_rating": "Buy",
"company_of_interest": "NVDA",
"trade_date": "2026-01-10",
"market_report": "",
@@ -896,13 +940,13 @@ class TestLegacyRemoval:
"fundamentals_report": "",
"investment_debate_state": {
"bull_history": "", "bear_history": "", "history": "",
"current_response": "", "judge_decision": "",
"current_response": "",
},
"investment_plan": "",
"trader_investment_plan": "",
"risk_debate_state": {
"aggressive_history": "", "conservative_history": "",
"neutral_history": "", "history": "", "judge_decision": "",
"neutral_history": "", "history": "",
"current_aggressive_response": "", "current_conservative_response": "",
"current_neutral_response": "", "count": 1, "latest_speaker": "",
},
@@ -914,7 +958,6 @@ class TestLegacyRemoval:
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.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(
@@ -934,8 +977,8 @@ 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.decision_log import TradingMemoryLog
from tradingagents.graph.trading_graph import TradingAgentsGraph
from tradingagents.memory import TradingMemoryLog
graph = object.__new__(TradingAgentsGraph)
graph.config = {"memory_log_path": str(tmp_path / "m.md")}
@@ -967,8 +1010,8 @@ 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.decision_log import TradingMemoryLog
from tradingagents.graph.trading_graph import TradingAgentsGraph
from tradingagents.memory import TradingMemoryLog
graph = object.__new__(TradingAgentsGraph)
graph.config = {"memory_log_path": str(tmp_path / "m.md"), "holding_period_days": 21}
@@ -994,7 +1037,7 @@ def test_the_holding_window_is_configurable(tmp_path, monkeypatch):
def test_the_reflection_states_the_window_it_judges():
"""Judging a months-long thesis on a week's alpha, without saying so, turns
a scope mismatch into a lesson that the call was wrong."""
from tradingagents.graph.reflection import Reflector
from tradingagents.memory.reflection import Reflector
prompt = Reflector(None)._system_prompt(holding_days=5)
assert "5" in prompt and "trading day" in prompt
@@ -1021,3 +1064,342 @@ def test_a_longer_window_asks_for_enough_price_history(monkeypatch):
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)
@pytest.mark.unit
def test_concurrent_writers_keep_every_decision_and_outcome(tmp_path):
"""Graphs sharing one log record and settle at the same time; none may lose another's write."""
import threading
path = tmp_path / "memory.md"
tickers = [f"T{i}" for i in range(8)]
dates = [f"2026-01-{day:02d}" for day in range(1, 13)]
errors = []
def work(ticker):
log = TradingMemoryLog({"memory_log_path": str(path)})
try:
for date in dates:
log.store_decision(ticker, date, "**Rating**: Buy")
log.update_with_outcome(ticker, date, 0.01, 0.005, 5, "held up")
except Exception as exc: # noqa: BLE001 — collected for the assertion
errors.append(exc)
threads = [threading.Thread(target=work, args=(t,)) for t in tickers]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
entries = TradingMemoryLog({"memory_log_path": str(path)}).load_entries()
assert errors == []
assert len(entries) == len(tickers) * len(dates)
assert all(not e["pending"] for e in entries)
def _closes(by_symbol):
"""A get_closes stand-in serving each symbol's series between the dates asked."""
def get_closes(symbol, start_date, end_date):
series = by_symbol[symbol]
return series[(series.index >= start_date) & (series.index < end_date)]
return get_closes
@pytest.mark.unit
class TestSettlementWindow:
"""Stock and benchmark are measured over the same dates, whatever their calendars."""
def test_a_seven_day_market_is_scored_against_the_benchmark_over_the_same_dates(self, monkeypatch):
coin = pd.Series([100.0 + i for i in range(10)], index=pd.date_range("2026-01-03", periods=10, freq="D"))
weekdays = pd.bdate_range("2025-12-29", "2026-01-16")
spy = pd.Series([400.0 + 2 * i for i in range(len(weekdays))], index=weekdays)
monkeypatch.setattr(settlement, "get_closes", _closes({"BTC-USD": coin, "SPY": spy}))
raw, alpha, days, resolved = settlement.fetch_returns("BTC-USD", "2026-01-03", 5, "SPY")
# Decided Sat 3, the coin is held Sun 4 -> Fri 9; SPY over the same span is Fri 2 -> Fri 9.
assert resolved == "2026-01-09"
assert raw == pytest.approx(106.0 / 101.0 - 1)
assert alpha == pytest.approx(raw - (spy["2026-01-09"] / spy["2026-01-02"] - 1))
def test_bars_stamped_in_different_time_zones_meet_on_their_dates(self, monkeypatch):
# Yahoo stamps a coin's daily bar at midnight UTC and SPY's at midnight
# New York, five hours later: the same day, not the day after.
coin = pd.Series([100.0 + i for i in range(10)],
index=pd.date_range("2026-01-03", periods=10, freq="D", tz="UTC"))
weekdays = pd.bdate_range("2025-12-29", "2026-01-16", tz="America/New_York")
spy = pd.Series([400.0 + 2 * i for i in range(len(weekdays))], index=weekdays)
monkeypatch.setattr(settlement, "get_closes", _closes({"BTC-USD": coin, "SPY": spy}))
raw, alpha, _, resolved = settlement.fetch_returns("BTC-USD", "2026-01-03", 5, "SPY")
assert resolved == "2026-01-09"
spy_by_day = spy.tz_localize(None)
assert alpha == pytest.approx(raw - (spy_by_day["2026-01-09"] / spy_by_day["2026-01-02"] - 1))
def test_the_outcome_waits_for_the_benchmark_to_trade_through_the_window(self, monkeypatch):
coin = pd.Series([100.0 + i for i in range(10)], index=pd.date_range("2026-01-03", periods=10, freq="D"))
spy = pd.Series([400.0, 401.0, 402.0], index=pd.to_datetime(["2026-01-02", "2026-01-05", "2026-01-06"]))
monkeypatch.setattr(settlement, "get_closes", _closes({"BTC-USD": coin, "SPY": spy}))
assert settlement.fetch_returns("BTC-USD", "2026-01-03", 5, "SPY") == (None, None, None, None)
def test_a_missing_close_is_skipped_not_scored(self, monkeypatch):
idx = pd.bdate_range("2026-01-05", periods=8)
stock = pd.Series([100.0, float("nan"), 101.0, 102.0, 103.0, 104.0, 105.0, 106.0], index=idx)
spy = pd.Series([400.0 + i for i in range(8)], index=idx)
monkeypatch.setattr(settlement, "get_closes", _closes({"NVDA": stock, "SPY": spy}))
raw, alpha, _, resolved = settlement.fetch_returns("NVDA", "2026-01-05", 5, "SPY")
# Entered at the first real close after the decision: Wed 7, past the missing Tue 6.
assert raw == pytest.approx(106.0 / 101.0 - 1)
assert resolved == "2026-01-14"
assert alpha == pytest.approx(raw - (spy["2026-01-14"] / spy["2026-01-07"] - 1))
@pytest.mark.unit
class TestSettlementUsesFinalCloses:
"""A decision settles on closes that are final, whenever the pass runs."""
def test_a_bar_of_a_session_still_trading_is_not_scored(self, monkeypatch):
# 09:12 in Shanghai on Tue 13: Yahoo already serves that day's bar at the live price.
days = pd.bdate_range("2026-01-02", "2026-01-13", tz="Asia/Shanghai")
stock = pd.Series([100.0 + i for i in range(len(days))], index=days)
index = pd.Series([3000.0] * len(days), index=days)
monkeypatch.setattr(settlement, "get_closes", _closes({"600519.SS": stock, "000001.SS": index}))
monkeypatch.setattr(settlement, "_now", lambda: pd.Timestamp("2026-01-13 01:12", tz="UTC"))
# Decided Mon 5: entry Tue 6, exit five sessions later on Tue 13, today.
assert settlement.fetch_returns("600519.SS", "2026-01-05", 5, "000001.SS") == (None, None, None, None)
monkeypatch.setattr(settlement, "_now", lambda: pd.Timestamp("2026-01-14 01:12", tz="UTC"))
assert settlement.fetch_returns("600519.SS", "2026-01-05", 5, "000001.SS")[3] == "2026-01-13"
def test_a_decision_before_a_long_market_closure_settles(self, monkeypatch):
# The exchange is shut Thu 1 to Wed 7 October.
days = pd.bdate_range("2026-09-21", "2026-10-30")
days = days[(days < "2026-10-01") | (days > "2026-10-07")]
stock = pd.Series([100.0 + i for i in range(len(days))], index=days)
index = pd.Series([3000.0 + i for i in range(len(days))], index=days)
monkeypatch.setattr(settlement, "get_closes", _closes({"600519.SS": stock, "000001.SS": index}))
monkeypatch.setattr(settlement, "_now", lambda: pd.Timestamp("2026-11-02 08:00", tz="UTC"))
raw, alpha, days_held, resolved = settlement.fetch_returns("600519.SS", "2026-09-29", 5, "000001.SS")
# Entry Wed 30 September, then five sessions from Thu 8 October.
assert resolved == "2026-10-14" and days_held == 5
def test_a_market_whose_clocks_skip_midnight_still_settles(self, monkeypatch):
# Santiago springs forward at midnight: 2026-09-06 has no 00:00.
days = pd.bdate_range("2026-08-21", "2026-09-04", tz="America/Santiago")
stock = pd.Series([100.0 + i for i in range(len(days))], index=days)
index = pd.Series([6000.0 + i for i in range(len(days))], index=days)
monkeypatch.setattr(settlement, "get_closes", _closes({"SQM-B.SN": stock, "^IPSA": index}))
monkeypatch.setattr(settlement, "_now", lambda: pd.Timestamp("2026-09-06 15:00", tz="UTC"))
assert settlement.fetch_returns("SQM-B.SN", "2026-08-24", 5, "^IPSA")[3] == "2026-09-01"
def test_a_benchmark_shut_past_the_window_is_fetched_again(self, monkeypatch):
days = pd.bdate_range("2026-09-14", "2026-10-30")
stock = pd.Series([100.0 + i for i in range(len(days))], index=days)
shut = days[(days < "2026-09-30") | (days > "2026-10-20")]
index = pd.Series([3000.0 + i for i in range(len(shut))], index=shut)
monkeypatch.setattr(settlement, "get_closes", _closes({"AAPL": stock, "000001.SS": index}))
monkeypatch.setattr(settlement, "_now", lambda: pd.Timestamp("2026-11-02 08:00", tz="UTC"))
assert settlement.fetch_returns("AAPL", "2026-09-29", 5, "000001.SS")[3] == "2026-10-07"
def test_a_series_with_no_usable_close_stays_pending(self, monkeypatch):
# Yahoo can answer with a dated, time-zoned frame whose closes are all missing.
days = pd.bdate_range("2026-01-02", "2026-01-30", tz="America/New_York")
empty = pd.Series([float("nan")] * len(days), index=days)
index = pd.Series([400.0 + i for i in range(len(days))], index=days)
monkeypatch.setattr(settlement, "get_closes", _closes({"NVDA": empty, "SPY": index}))
monkeypatch.setattr(settlement, "_now", lambda: pd.Timestamp("2026-02-02 12:00", tz="UTC"))
assert settlement.fetch_returns("NVDA", "2026-01-05", 5, "SPY") == (None, None, None, None)
def test_a_window_that_cannot_have_traded_asks_for_no_prices(self, monkeypatch):
monkeypatch.setattr(settlement, "_now", lambda: pd.Timestamp("2026-01-08 22:00", tz="UTC"))
monkeypatch.setattr(settlement, "get_closes", lambda *a: pytest.fail("fetched prices"))
assert settlement.fetch_returns("NVDA", "2026-01-05", 5, "SPY") == (None, None, None, None)
@pytest.mark.unit
def test_a_close_that_is_not_a_price_is_skipped_not_scored(monkeypatch):
"""A zero close would score as an infinite return and be written to the memory log."""
idx = pd.bdate_range("2026-01-05", periods=8)
stock = pd.Series([0.0, 100.0, 101.0, 102.0, 103.0, 104.0, 105.0, 106.0], index=idx)
spy = pd.Series([400.0 + i for i in range(8)], index=idx)
monkeypatch.setattr(settlement, "get_closes", _closes({"NVDA": stock, "SPY": spy}))
raw, alpha, _, _ = settlement.fetch_returns("NVDA", "2026-01-02", 5, "SPY")
assert raw == pytest.approx(105.0 / 100.0 - 1) # the window opens on the first real close
@pytest.mark.unit
class TestSettleAll:
"""A scheduler that stops analysing a ticker can still settle its decisions (#1445)."""
def _setup(self, tmp_path, monkeypatch):
log = make_log(tmp_path)
log.store_decision("AAPL", "2026-01-05", DECISION_BUY)
log.store_decision("MSFT", "2026-01-05", DECISION_BUY)
idx = pd.bdate_range("2026-01-02", periods=12)
series = pd.Series([100.0 + i for i in range(12)], index=idx)
monkeypatch.setattr(settlement, "get_closes", _closes({"AAPL": series, "MSFT": series, "SPY": series}))
class _Reflector:
def reflect_on_final_decision(self, **kwargs):
return "Held up."
return log, _Reflector()
def test_every_ticker_with_a_due_decision_is_settled(self, tmp_path, monkeypatch):
log, reflector = self._setup(tmp_path, monkeypatch)
result = settlement.settle_all_pending(log, reflector, {"holding_period_days": 5})
assert sorted(result.settled) == [("AAPL", "2026-01-05"), ("MSFT", "2026-01-05")]
assert result.failed == []
assert not log.get_pending_entries()
def test_a_failed_reflection_is_reported_and_left_pending(self, tmp_path, monkeypatch):
log, _ = self._setup(tmp_path, monkeypatch)
class _Down:
def reflect_on_final_decision(self, **kwargs):
raise RuntimeError("provider down")
result = settlement.settle_pending("AAPL", log, _Down(), {"holding_period_days": 5})
assert result.settled == [] and [f[:2] for f in result.failed] == [("AAPL", "2026-01-05")]
assert {e["ticker"] for e in log.get_pending_entries()} == {"AAPL", "MSFT"}
@pytest.mark.unit
def test_the_graph_settles_every_ticker_under_its_own_config(tmp_path, monkeypatch):
from tradingagents.dataflows.config import get_config
graph = object.__new__(TradingAgentsGraph)
graph.config = {"holding_period_days": 5, "output_language": "Deutsch"}
graph.memory_log, graph.reflector = make_log(tmp_path), object()
seen = []
monkeypatch.setattr(settlement, "settle_all_pending",
lambda log, reflector, config, wait=True: seen.append(get_config()["output_language"])
or settlement.Settlement(settled=[("AAPL", "2026-01-05")]))
assert graph.settle_all_pending().settled == [("AAPL", "2026-01-05")]
assert seen == ["Deutsch"]
@pytest.mark.unit
class TestSettlementOnceAndDurably:
"""Settlement is paid for in reflection calls, so it runs once per decision and
keeps what it finished; what it could not do is reported (#1428, #1445)."""
def _log(self, tmp_path, monkeypatch, *dates):
log = make_log(tmp_path)
for date in dates:
log.store_decision("AAPL", date, DECISION_BUY)
series = pd.Series([100.0 + i for i in range(40)], index=pd.bdate_range("2026-01-02", periods=40))
monkeypatch.setattr(settlement, "get_closes", _closes({"AAPL": series, "SPY": series}))
return log
def test_two_runs_settling_at_once_reflect_once(self, tmp_path, monkeypatch):
import threading
import time
self._log(tmp_path, monkeypatch, "2026-01-05")
calls = []
class _Slow:
def reflect_on_final_decision(self, **kwargs):
calls.append(1)
time.sleep(0.2)
return "Held up."
results = []
threads = [threading.Thread(target=lambda: results.append(
settlement.settle_pending("AAPL", make_log(tmp_path), _Slow(), {"holding_period_days": 5})))
for _ in range(2)]
[t.start() for t in threads]
[t.join() for t in threads]
assert len(calls) == 1
assert sorted(len(r.settled) for r in results) == [0, 1]
def test_an_interrupted_pass_keeps_the_outcomes_it_finished(self, tmp_path, monkeypatch):
log = self._log(tmp_path, monkeypatch, "2026-01-05", "2026-01-12")
class _Interrupted:
calls = 0
def reflect_on_final_decision(self, **kwargs):
_Interrupted.calls += 1
if _Interrupted.calls == 2:
raise KeyboardInterrupt
return "Held up."
with pytest.raises(KeyboardInterrupt):
settlement.settle_pending("AAPL", log, _Interrupted(), {"holding_period_days": 5})
assert [e["date"] for e in log.get_pending_entries()] == ["2026-01-12"]
def test_a_price_request_that_fails_is_reported_not_taken_for_not_due(self, tmp_path, monkeypatch):
from tradingagents.dataflows.errors import VendorUnavailableError
log = self._log(tmp_path, monkeypatch, "2026-01-05")
def down(*args, **kwargs):
raise VendorUnavailableError("Yahoo Finance request failed: TimeoutError")
monkeypatch.setattr(settlement, "get_closes", down)
result = settlement.settle_pending("AAPL", log, object(), {"holding_period_days": 5})
assert result.settled == [] and "prices unavailable" in result.failed[0][2]
@pytest.mark.unit
def test_any_failure_to_price_a_decision_is_reported(tmp_path, monkeypatch):
log = make_log(tmp_path)
log.store_decision("AAPL", "2026-01-05", DECISION_BUY)
def broken(*args, **kwargs):
raise RuntimeError("vendor outage")
monkeypatch.setattr(settlement, "get_closes", broken)
result = settlement.settle_pending("AAPL", log, object(), {"holding_period_days": 5})
assert result.settled == [] and "vendor outage" in result.failed[0][2]
@pytest.mark.unit
def test_a_run_does_not_wait_on_another_settlement_pass(tmp_path):
"""The other pass settles the same log; a run's step goes on without waiting."""
import threading
import time
log = make_log(tmp_path)
log.store_decision("AAPL", "2026-01-05", DECISION_BUY)
held, release = threading.Event(), threading.Event()
def other_pass():
with make_log(tmp_path).settling():
held.set()
release.wait(5)
worker = threading.Thread(target=other_pass)
worker.start()
held.wait(5)
started = time.monotonic()
result = settlement.settle_all_pending(log, object(), {"holding_period_days": 5}, wait=False)
elapsed = time.monotonic() - started
release.set()
worker.join()
assert elapsed < 1 and result.settled == [] and result.failed == []
+1 -1
View File
@@ -10,7 +10,7 @@ from __future__ import annotations
import pytest
from tradingagents.decision_log import TradingMemoryLog
from tradingagents.memory import TradingMemoryLog
def _log(tmp_path):
+7 -7
View File
@@ -1,7 +1,8 @@
"""Guard the news analyst prompt against tool-signature drift (#1116).
The prompt used to advertise ``get_news(query, ...)`` while the tool takes a
``ticker``, tricking the LLM into hallucinating free-text query calls.
The prompt used to advertise ``get_news(query, ...)``, tricking the LLM into
hallucinating free-text query calls. The instrument now comes from the run's
state, so the model passes only the window.
"""
import inspect
@@ -12,14 +13,13 @@ from tradingagents.agents.tools import get_news
@pytest.mark.unit
def test_get_news_takes_ticker_not_query():
arg_names = set(get_news.args.keys())
assert "ticker" in arg_names
assert "query" not in arg_names
def test_get_news_takes_the_window_not_a_query():
arg_names = set(get_news.tool_call_schema.model_json_schema()["properties"])
assert arg_names == {"start_date", "end_date"}
@pytest.mark.unit
def test_news_prompt_matches_get_news_signature():
src = inspect.getsource(na)
assert "get_news(ticker, start_date, end_date)" in src
assert "get_news(start_date, end_date)" in src
assert "get_news(query" not in src
+180 -18
View File
@@ -6,7 +6,7 @@ news injected future articles), #993 (empty-after-filter returned a blank body),
and #1126 (inclusive upper bound leaked the midnight-after article; host-local
timestamp parsing made filtering machine-dependent).
"""
from datetime import datetime, timezone
from datetime import UTC, datetime
import pytest
@@ -16,7 +16,7 @@ from tradingagents.dataflows.date_window import in_window
def _epoch(date_str):
"""Epoch seconds for UTC midnight of ``date_str`` (host-timezone independent)."""
return int(datetime.strptime(date_str, "%Y-%m-%d").replace(tzinfo=timezone.utc).timestamp())
return int(datetime.strptime(date_str, "%Y-%m-%d").replace(tzinfo=UTC).timestamp())
@pytest.mark.unit
@@ -28,7 +28,7 @@ def test_flat_article_publish_time_is_parsed():
)
assert data["pub_date"] is not None
assert data["pub_date"].tzinfo is not None
assert data["pub_date"] == datetime(2025, 5, 9, tzinfo=timezone.utc)
assert data["pub_date"] == datetime(2025, 5, 9, tzinfo=UTC)
@pytest.mark.unit
@@ -45,7 +45,7 @@ def test_window_excludes_future_and_undated_in_backtest():
@pytest.mark.unit
def test_window_keeps_undated_in_live_window():
# Live window (reaches today): undated articles can't be "future", so keep them.
now = datetime.now(timezone.utc)
now = datetime.now(UTC)
assert in_window(None, now, now) is True
@@ -55,8 +55,8 @@ def test_upper_bound_is_exclusive():
# the old inclusive bound; the whole of end_date itself must still be kept.
start = datetime(2025, 5, 1)
end = datetime(2025, 5, 9)
midnight_after = datetime(2025, 5, 10, 0, 0, 0, tzinfo=timezone.utc)
last_moment = datetime(2025, 5, 9, 23, 59, 59, tzinfo=timezone.utc)
midnight_after = datetime(2025, 5, 10, 0, 0, 0, tzinfo=UTC)
last_moment = datetime(2025, 5, 9, 23, 59, 59, tzinfo=UTC)
assert in_window(midnight_after, start, end) is False
assert in_window(last_moment, start, end) is True
@@ -106,7 +106,11 @@ 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):
def _ticker_with(articles, monkeypatch, search_news=(), search_quotes=("AAPL",)):
"""A quote feed answering ``articles``, and a search answering the rest.
By default the search knows the symbol but has no articles, i.e. Yahoo answered.
"""
class FakeTicker:
def __init__(self, *a, **k):
pass
@@ -114,7 +118,17 @@ def _ticker_with(articles, monkeypatch):
def get_news(self, count=20):
return articles
searched = []
class FakeSearch:
def __init__(self, query, **k):
searched.append(query)
self.news = list(search_news)
self.quotes = [{"symbol": s} for s in search_quotes]
monkeypatch.setattr(ynews.yf, "Ticker", FakeTicker)
monkeypatch.setattr(ynews.yf, "Search", FakeSearch)
return searched
@pytest.mark.unit
@@ -146,11 +160,11 @@ def test_ticker_news_covered_but_empty_window_is_a_real_absence(monkeypatch):
@pytest.mark.parametrize("dates, expect_gap", [
([], True), # empty feed: covers at most now
([None], True), # undated only: same
([datetime(2026, 5, 20, tzinfo=timezone.utc)], True), # all after the window
([datetime(2026, 5, 4, tzinfo=timezone.utc)], True), # starts mid-window: partial
([datetime(2026, 5, 1, 18, tzinfo=timezone.utc)], False), # reaches the first day
([datetime(2026, 5, 20, tzinfo=timezone.utc),
datetime(2026, 4, 1, tzinfo=timezone.utc)], False), # coverage reaches back
([datetime(2026, 5, 20, tzinfo=UTC)], True), # all after the window
([datetime(2026, 5, 4, tzinfo=UTC)], True), # starts mid-window: partial
([datetime(2026, 5, 1, 18, tzinfo=UTC)], False), # reaches the first day
([datetime(2026, 5, 20, tzinfo=UTC),
datetime(2026, 4, 1, tzinfo=UTC)], False), # coverage reaches back
])
def test_coverage_gap_boundaries(dates, expect_gap):
from tradingagents.dataflows.date_window import coverage_gap
@@ -163,17 +177,135 @@ def test_coverage_gap_boundaries(dates, expect_gap):
@pytest.mark.unit
def test_ticker_news_empty_feed_for_a_past_window_is_unavailable(monkeypatch):
from tradingagents.dataflows.errors import VendorUnavailableError
_ticker_with([], monkeypatch)
out = ynews.get_news_yfinance("AAPL", "2026-08-07", "2026-08-14")
assert "unavailable" in out and "not an absence" in out
with pytest.raises(VendorUnavailableError):
ynews.get_news_yfinance("AAPL", "2026-08-07", "2026-08-14")
@pytest.mark.unit
def test_ticker_news_null_feed_is_handled(monkeypatch):
# Yahoo can return None instead of a list; that is unavailability, not an error.
# Yahoo can return None instead of a list; that is unavailability, not a crash.
from tradingagents.dataflows.errors import VendorUnavailableError
_ticker_with(None, monkeypatch)
out = ynews.get_news_yfinance("AAPL", "2026-08-07", "2026-08-14")
assert "unavailable" in out and "Error" not in out
with pytest.raises(VendorUnavailableError):
ynews.get_news_yfinance("AAPL", "2026-08-07", "2026-08-14")
def _tagged(title, day, *tickers):
return {"title": title, "publisher": "P", "link": "l",
"providerPublishTime": _epoch(day), "relatedTickers": list(tickers)}
@pytest.mark.unit
def test_an_empty_quote_feed_falls_back_to_the_articles_search_tags_with_the_symbol(monkeypatch):
today = datetime.now(UTC).strftime("%Y-%m-%d")
searched = _ticker_with([], monkeypatch, search_news=[
_tagged("ABOUT AAPL", today, "AAPL", "MSFT"),
_tagged("ABOUT GIS", today, "GIS"),
])
out = ynews.get_news_yfinance("AAPL", today, today)
assert searched == ["AAPL"]
assert "ABOUT AAPL" in out and "ABOUT GIS" not in out
@pytest.mark.unit
def test_a_quote_feed_with_articles_is_not_searched(monkeypatch):
today = datetime.now(UTC).strftime("%Y-%m-%d")
searched = _ticker_with([_tagged("FEED", today)], monkeypatch)
out = ynews.get_news_yfinance("AAPL", today, today)
assert "FEED" in out and searched == []
@pytest.mark.unit
def test_news_neither_yahoo_source_answers_is_a_vendor_outage(monkeypatch):
from tradingagents.dataflows.errors import VendorUnavailableError
today = datetime.now(UTC).strftime("%Y-%m-%d")
_ticker_with([], monkeypatch, search_quotes=())
with pytest.raises(VendorUnavailableError):
ynews.get_news_yfinance("AAPL", today, today)
@pytest.mark.unit
def test_a_yahoo_news_outage_moves_to_the_next_configured_vendor(monkeypatch):
from unittest.mock import patch
from tradingagents.dataflows import router
from tradingagents.dataflows.config import get_config, set_config
_ticker_with([], monkeypatch, search_quotes=())
calls = []
def other_vendor(*a, **k):
calls.append(a)
return "OTHER VENDOR NEWS"
saved = dict(get_config()["data_vendors"])
set_config({"data_vendors": {**saved, "news_data": "yfinance,alpha_vantage"}})
try:
with patch.dict(router.VENDOR_METHODS, {"get_news": {
"yfinance": ynews.get_news_yfinance, "alpha_vantage": other_vendor,
}}):
out = router.route_to_vendor("get_news", "AAPL", "2026-10-01", "2026-10-02")
finally:
set_config({"data_vendors": saved})
assert out == "OTHER VENDOR NEWS" and len(calls) == 1
@pytest.mark.unit
def test_search_results_never_count_as_an_absence_of_news(monkeypatch):
# Search returns a sparse, relevance-picked sample: nothing in a window it
# reaches is still no proof that no news was published.
today = datetime.now(UTC).strftime("%Y-%m-%d")
_ticker_with([], monkeypatch, search_news=[
_tagged("NEWER", today, "AAPL"), _tagged("OLDER", "2026-01-05", "AAPL"),
])
out = ynews.get_news_yfinance("AAPL", "2026-03-01", "2026-03-08")
assert "No news found" not in out
assert "unavailable" in out and "not an absence" in out
assert "NEWER" not in out and "OLDER" not in out
@pytest.mark.unit
def test_a_symbol_yahoo_has_no_articles_for_is_left_to_the_next_vendor(monkeypatch):
# With its quote feed down, Yahoo serving no article about a symbol it knows
# (every non-US listing today) says nothing about the company's news.
from tradingagents.dataflows.errors import VendorUnavailableError
today = datetime.now(UTC).strftime("%Y-%m-%d")
_ticker_with([], monkeypatch, search_quotes=("SHEL.L",),
search_news=[_tagged("ABOUT SHEL", today, "SHEL")])
with pytest.raises(VendorUnavailableError, match="SHEL.L"):
ynews.get_news_yfinance("SHEL.L", today, today)
@pytest.mark.unit
def test_search_tags_are_matched_whatever_their_case(monkeypatch):
today = datetime.now(UTC).strftime("%Y-%m-%d")
_ticker_with([], monkeypatch, search_news=[_tagged("ABOUT AAPL", today, "aapl")])
assert "ABOUT AAPL" in ynews.get_news_yfinance("AAPL", today, today)
@pytest.mark.unit
def test_a_search_with_articles_has_answered_even_without_listing_the_symbol(monkeypatch):
today = datetime.now(UTC).strftime("%Y-%m-%d")
_ticker_with([], monkeypatch, search_quotes=(),
search_news=[_tagged("ABOUT AAPL", today, "AAPL")])
assert "ABOUT AAPL" in ynews.get_news_yfinance("AAPL", today, today)
@pytest.mark.unit
def test_a_search_yahoo_answers_with_not_found_is_an_outage(monkeypatch):
from tradingagents.dataflows.errors import VendorUnavailableError
_ticker_with([], monkeypatch)
monkeypatch.setattr(ynews, "yf_retry", lambda fn: [] if "get_news" in repr(fn.__code__.co_names) else None)
with pytest.raises(VendorUnavailableError):
ynews.get_news_yfinance("AAPL", "2026-10-01", "2026-10-02")
@pytest.mark.unit
@@ -208,7 +340,7 @@ def test_coverage_gap_future_window_is_unavailable():
from datetime import timedelta
from tradingagents.dataflows.date_window import coverage_gap
today = datetime.now(timezone.utc).date()
today = datetime.now(UTC).date()
out = coverage_gap([], str(today), str(today + timedelta(days=3)), "Feed", "items")
assert out is not None and "past today" in out
@@ -255,3 +387,33 @@ def test_the_article_limit_still_caps_what_is_returned(monkeypatch):
out = ynews.get_global_news_yfinance("2025-05-09", look_back_days=7, limit=3)
assert out.count("### ") == 3
@pytest.mark.unit
@pytest.mark.parametrize("field", ["title", "summary", "provider", "canonicalUrl", "pubDate"])
def test_an_article_with_a_null_field_is_read_with_its_default(field):
"""Yahoo sends some fields as null rather than leaving them out (#1458)."""
content = {"title": "T", "summary": "S", "provider": {"displayName": "P"},
"canonicalUrl": {"url": "https://x"}, "pubDate": "2026-09-22T10:00:00Z", field: None}
data = ynews._extract_article_data({"content": content})
assert isinstance(data["title"], str) and isinstance(data["summary"], str)
assert isinstance(data["publisher"], str) and isinstance(data["link"], str)
@pytest.mark.unit
@pytest.mark.parametrize("field", ["title", "summary", "publisher", "link"])
def test_a_flat_article_with_a_null_field_is_read_with_its_default(field):
data = ynews._extract_article_data({"title": "T", "summary": "S", "publisher": "P", "link": "L",
"providerPublishTime": _epoch("2026-09-22"), field: None})
assert all(isinstance(data[k], str) for k in ("title", "summary", "publisher", "link"))
@pytest.mark.unit
def test_one_malformed_article_does_not_lose_the_feed(monkeypatch):
good = {"content": {"title": "Kept", "summary": "", "provider": {"displayName": "Wire"},
"pubDate": "2026-09-22T10:00:00Z"}}
bad = {"content": {"title": "Also kept", "summary": None, "provider": None,
"pubDate": "2026-09-22T11:00:00Z"}}
_ticker_with([good, bad], monkeypatch)
out = ynews.get_news_yfinance("ZS", "2026-09-20", "2026-09-23")
assert "Kept" in out and "Also kept" in out
+9 -8
View File
@@ -16,8 +16,9 @@ import pytest
from tradingagents.dataflows import router
from tradingagents.dataflows.config import set_config
from tradingagents.dataflows.date_window import get_current_date
from tradingagents.dataflows.errors import NoMarketDataError
from tradingagents.dataflows.vendors.yahoo import ohlcv
from tradingagents.dataflows.vendors.yahoo import common, ohlcv
@pytest.mark.unit
@@ -33,19 +34,19 @@ class TestLoadOhlcvNoPoison(unittest.TestCase):
os.rmdir(self._tmp)
def test_empty_download_raises_and_does_not_cache(self):
empty = pd.DataFrame()
empty = mock.Mock(history=mock.Mock(return_value=pd.DataFrame()))
# Yahoo answers, so an empty download means the symbol has no data.
reachable = mock.patch.object(ohlcv, "vendor_reachable", return_value=True)
reachable = mock.patch.object(common, "vendor_reachable", return_value=True)
reachable.start()
self.addCleanup(reachable.stop)
with mock.patch.object(ohlcv.yf, "download", return_value=empty), \
with mock.patch.object(ohlcv.yf, "Ticker", return_value=empty), \
self.assertRaises(NoMarketDataError):
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(ohlcv.yf, "download", return_value=empty) as dl2:
with mock.patch.object(ohlcv.yf, "Ticker", return_value=empty) as dl2:
with self.assertRaises(NoMarketDataError):
ohlcv.load_ohlcv("FAKE", "2026-01-01")
self.assertTrue(dl2.called)
@@ -95,11 +96,11 @@ if __name__ == "__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.errors import VendorUnavailableError
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")
pytest.raises(VendorUnavailableError):
fundamentals.get_insider_transactions("AAPL", as_of_date=get_current_date())
+4 -2
View File
@@ -8,6 +8,7 @@ day (#1330).
from __future__ import annotations
import os
from types import SimpleNamespace
import pandas as pd
import pytest
@@ -35,7 +36,7 @@ def _write(tmp_path, name="AAPL-YFin-data.csv", age_seconds=0.0, last_date="2026
def _load(tmp_path, monkeypatch, curr_date, download):
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)
monkeypatch.setattr(ohlcv.yf, "Ticker", lambda symbol: SimpleNamespace(history=download))
return ohlcv.load_ohlcv("AAPL", curr_date)
@@ -98,7 +99,8 @@ def test_one_cache_file_per_symbol_across_days(tmp_path, monkeypatch):
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(ohlcv.yf, "download", lambda *a, **k: downloads.append(1) or frame.set_index("Date"))
monkeypatch.setattr(ohlcv.yf, "Ticker", lambda symbol: SimpleNamespace(
history=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)
+4 -3
View File
@@ -14,6 +14,7 @@ anywhere counts as no data and the staleness check judges the rest.
from __future__ import annotations
import os
from types import SimpleNamespace
import pandas as pd
import pytest
@@ -105,7 +106,7 @@ def _run_load(monkeypatch, tmp_path, frame, curr_date):
def _fail_download(*a, **k):
raise AssertionError("should use the seeded cache, not download")
monkeypatch.setattr(ohlcv.yf, "download", _fail_download)
monkeypatch.setattr(ohlcv.yf, "Ticker", lambda symbol: SimpleNamespace(history=_fail_download))
return ohlcv.load_ohlcv("AAPL", curr_date)
@@ -198,8 +199,8 @@ def test_the_snapshot_does_not_present_a_filled_price_as_reported(monkeypatch, t
cache = tmp_path / "AAPL-YFin-data.csv"
cache.write_text(frame.to_csv(index=False))
_stamp(cache, today)
monkeypatch.setattr(ohlcv.yf, "download", lambda *a, **k: (_ for _ in ()).throw(
AssertionError("should read the seeded cache")))
monkeypatch.setattr(ohlcv.yf, "Ticker", lambda symbol: SimpleNamespace(
history=lambda *a, **k: (_ for _ in ()).throw(AssertionError("should read the seeded cache"))))
out = snapshot.build_verified_market_snapshot("AAPL", "2026-05-08", 3)
+8 -59
View File
@@ -2,7 +2,6 @@
from __future__ import annotations
import importlib
import re
import pytest
@@ -18,30 +17,12 @@ def _console_out(capsys) -> str:
return _ANSI.sub("", capsys.readouterr().out)
@pytest.fixture(scope="module", autouse=True)
def _resync_reloaded_modules():
"""Restore module state after this file's importlib.reload() calls.
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.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 --------------
def _reload_client():
def _client_module():
import tradingagents.llm_clients.openai_client as mod
return importlib.reload(mod)
return mod
def _base_url(mod, provider, **kwargs):
@@ -50,20 +31,20 @@ def _base_url(mod, provider, **kwargs):
def test_resolver_returns_default_when_env_unset(monkeypatch):
monkeypatch.delenv("OLLAMA_BASE_URL", raising=False)
mod = _reload_client()
mod = _client_module()
assert _base_url(mod, "ollama") == "http://localhost:11434/v1"
def test_resolver_returns_env_when_set(monkeypatch):
monkeypatch.setenv("OLLAMA_BASE_URL", "http://remote-ollama:11434/v1")
mod = _reload_client()
mod = _client_module()
assert _base_url(mod, "ollama") == "http://remote-ollama:11434/v1"
def test_resolver_evaluation_is_call_time(monkeypatch):
"""Setting the env AFTER module import must still take effect."""
monkeypatch.delenv("OLLAMA_BASE_URL", raising=False)
mod = _reload_client()
mod = _client_module()
monkeypatch.setenv("OLLAMA_BASE_URL", "http://late-set:11434/v1")
assert _base_url(mod, "ollama") == "http://late-set:11434/v1"
@@ -71,7 +52,7 @@ def test_resolver_evaluation_is_call_time(monkeypatch):
def test_resolver_does_not_affect_other_providers(monkeypatch):
"""OLLAMA_BASE_URL should NOT leak into xai/deepseek/etc."""
monkeypatch.setenv("OLLAMA_BASE_URL", "http://elsewhere/v1")
mod = _reload_client()
mod = _client_module()
assert _base_url(mod, "xai") == "https://api.x.ai/v1"
assert _base_url(mod, "deepseek") == "https://api.deepseek.com"
@@ -79,7 +60,7 @@ def test_resolver_does_not_affect_other_providers(monkeypatch):
def test_client_get_llm_picks_up_env(monkeypatch):
"""End-to-end: OllamaClient.get_llm() respects OLLAMA_BASE_URL."""
monkeypatch.setenv("OLLAMA_BASE_URL", "http://my-ollama:11434/v1")
mod = _reload_client()
mod = _client_module()
client = mod.OpenAIClient(model="llama3.1", provider="ollama")
llm = client.get_llm()
assert "my-ollama" in str(llm.openai_api_base)
@@ -88,7 +69,7 @@ def test_client_get_llm_picks_up_env(monkeypatch):
def test_explicit_base_url_overrides_env(monkeypatch):
"""An explicit base_url passed to the client wins over the env var."""
monkeypatch.setenv("OLLAMA_BASE_URL", "http://env-set:11434/v1")
mod = _reload_client()
mod = _client_module()
client = mod.OpenAIClient(
model="llama3.1",
provider="ollama",
@@ -99,40 +80,12 @@ def test_explicit_base_url_overrides_env(monkeypatch):
assert "env-set" not in str(llm.openai_api_base)
# ---- 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")
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")
or "http://localhost:11434/v1"
)
assert ollama_url == "http://cli-remote:11434/v1"
def test_cli_dropdown_default_when_unset(monkeypatch):
monkeypatch.delenv("OLLAMA_BASE_URL", raising=False)
from cli import prompts
importlib.reload(prompts)
ollama_url = (
__import__("os").environ.get("OLLAMA_BASE_URL")
or "http://localhost:11434/v1"
)
assert ollama_url == "http://localhost:11434/v1"
# ---- confirm_ollama_endpoint UX -------------------------------------------
def test_confirm_endpoint_shows_default(monkeypatch, capsys):
monkeypatch.delenv("OLLAMA_BASE_URL", raising=False)
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
@@ -143,7 +96,6 @@ 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")
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
@@ -154,7 +106,6 @@ 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")
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
@@ -165,7 +116,6 @@ 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")
from cli import prompts
importlib.reload(prompts)
prompts.confirm_ollama_endpoint("http://remote-host/v1")
out = _console_out(capsys)
assert "port 11434" in out
@@ -175,7 +125,6 @@ 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")
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
+3 -5
View File
@@ -9,18 +9,16 @@ import pytest
from tradingagents.llm_clients.api_key_env import get_api_key_env
from tradingagents.llm_clients.factory import create_llm_client
from tradingagents.llm_clients.openai_client import LocalCompatibleChatOpenAI, OpenAIClient
from tradingagents.llm_clients.validators import validate_model
# Note: assert by class NAME, not isinstance — other tests reload the
# openai_client module, which would otherwise create a second class identity.
@pytest.mark.unit
def test_factory_routes_to_openai_client():
client = create_llm_client(
provider="openai_compatible", model="my-model", base_url="http://localhost:8000/v1"
)
assert type(client).__name__ == "OpenAIClient"
assert isinstance(client, OpenAIClient)
@pytest.mark.unit
@@ -36,7 +34,7 @@ def test_keyless_local_uses_placeholder_and_chat_completions(monkeypatch):
llm = create_llm_client(
provider="openai_compatible", model="qwen2.5", base_url="http://localhost:8000/v1"
).get_llm()
assert type(llm).__name__ == "LocalCompatibleChatOpenAI"
assert isinstance(llm, LocalCompatibleChatOpenAI)
assert str(llm.openai_api_base) == "http://localhost:8000/v1"
# keyless local servers: a placeholder key is sent
key = llm.openai_api_key.get_secret_value() if hasattr(llm.openai_api_key, "get_secret_value") else llm.openai_api_key
+13
View File
@@ -78,6 +78,19 @@ class PolymarketFormatTests(unittest.TestCase):
self.assertIn("resolves 2030-12-31", out)
self.assertIn("1-week -4.5pp", out) # -0.045 -> -4.5pp
def test_a_long_shot_is_not_shown_as_impossible_or_certain(self):
search = {"events": [{"markets": [
_market("Long shot?", 0.003, volume=2_000, end_date="2030-12-31T00:00:00Z"),
_market("Near certain?", 0.997, volume=1_000, end_date="2030-12-31T00:00:00Z"),
_market("Tick from zero?", 0.0005, volume=900, end_date="2030-12-31T00:00:00Z"),
_market("Tick from one?", 0.9995, volume=800, end_date="2030-12-31T00:00:00Z"),
_market("All but settled?", 0.9999999, volume=700, end_date="2030-12-31T00:00:00Z"),
]}]}
with mock.patch.object(polymarket, "_request", return_value=search):
out = polymarket.get_prediction_markets("anything", limit=10)
for odds in ("Yes 0.3%", "Yes 99.7%", "Yes 0.05%", "Yes 99.95%", "Yes 99.99999%"):
self.assertIn(odds, out)
def test_weekly_change_omitted_when_absent(self):
# "Open small?" has wk=None -> no 1-week clause on its line.
with mock.patch.object(polymarket, "_request", return_value=_SEARCH):
+48 -5
View File
@@ -45,6 +45,20 @@ def test_a_ticker_held_under_another_spelling_is_matched():
assert "No current position" not in text and "5" in text
@pytest.mark.unit
@pytest.mark.parametrize("held, analyzed, canonical", [
("BTCUSDT", "BTC-USD", "BTC-USD"),
("XAUUSD+", "GC=F", "GC=F"),
("700.HK", "0700.HK", "0700.HK"),
("0700.HK", "700.HK", "0700.HK"),
])
def test_a_holding_under_a_broker_alias_is_the_analyzed_instrument(held, analyzed, canonical):
book = PortfolioContext.model_validate({"positions": [{"ticker": held, "quantity": 2}, {"ticker": "ethusdt", "quantity": 1}]})
text = book.render(analyzed)
assert f"Current position in {canonical}: 2 units" in text
assert "Other positions: ETHUSDT 1" in text # as listed
@pytest.mark.unit
def test_absent_context_is_reported_as_not_provided():
notice = get_portfolio_context_from_state({"company_of_interest": "AAPL"})
@@ -66,6 +80,36 @@ def test_load_rejects_a_malformed_file_with_a_clear_error(tmp_path):
load_portfolio(bad)
@pytest.mark.unit
def test_one_instrument_held_under_two_spellings_shows_both_holdings():
book = PortfolioContext.model_validate({"positions": [
{"ticker": "BTCUSDT", "quantity": 1}, {"ticker": "BTC-USD", "quantity": 2}]})
text = book.render("BTC-USD")
assert "Current position in BTC-USD: 1 units (listed as BTCUSDT)" in text
assert "Current position in BTC-USD: 2 units" in text and "Other positions" not in text
@pytest.mark.unit
def test_a_holding_keeps_the_instrument_it_was_listed_as():
# WTI is also an alias of crude oil futures; listed beside AAPL it is the stock as written.
text = PortfolioContext.model_validate({"positions": [{"ticker": "WTI", "quantity": 100}]}).render("AAPL")
assert "Other positions: WTI 100" in text and "CL=F" not in text
@pytest.mark.unit
@pytest.mark.parametrize("book", [
'{"cash": NaN}',
'{"positions": [{"ticker": "AAPL", "quantity": Infinity}]}',
'{"positions": [{"ticker": "AAPL", "quantity": 1, "average_price": "nan"}]}',
])
def test_load_rejects_a_number_that_is_not_finite(tmp_path, book):
# Python's json writes NaN and Infinity, and they would reach the agents as "nan units".
bad = tmp_path / "p.json"
bad.write_text(book)
with pytest.raises(ValueError, match="portfolio"):
load_portfolio(bad)
@pytest.mark.unit
def test_load_reads_a_valid_file(tmp_path):
good = tmp_path / "p.json"
@@ -76,9 +120,9 @@ def test_load_reads_a_valid_file(tmp_path):
# --- threading through the graph --------------------------------------------
def _bare_graph(tmp_path):
from tradingagents.decision_log import TradingMemoryLog
from tradingagents.graph.propagation import Propagator
from tradingagents.graph.trading_graph import TradingAgentsGraph
from tradingagents.memory import TradingMemoryLog
graph = object.__new__(TradingAgentsGraph)
graph.config = {"memory_log_path": str(tmp_path / "m.md"), "max_debate_rounds": 1,
@@ -139,11 +183,11 @@ def test_decision_agents_see_the_portfolio(module, factory, monkeypatch):
"news_report": "N", "fundamentals_report": "F", "investment_plan": "P",
"trader_investment_plan": "T", "past_context": "",
"portfolio_context": "PORTFOLIO_BLOCK_MARKER",
"investment_debate_state": {"history": "", "judge_decision": "", "count": 0},
"investment_debate_state": {"history": "", "count": 0},
"risk_debate_state": {"history": "", "latest_speaker": "", "count": 0,
"aggressive_history": "", "conservative_history": "", "neutral_history": "",
"current_aggressive_response": "", "current_conservative_response": "",
"current_neutral_response": "", "judge_decision": ""},
"current_neutral_response": ""},
}
node = getattr(mod, factory)(_LLM())
node(state)
@@ -174,9 +218,8 @@ def test_completed_run_clears_the_checkpoint_it_wrote(tmp_path, monkeypatch):
graph.debug = False
graph._resuming = False
graph.propagator.get_graph_args = lambda callbacks=None: {}
graph.process_signal = lambda d: "Hold"
graph._log_state = lambda *a, **k: None
graph.graph = type("G", (), {"invoke": lambda self, i, **k: {"final_trade_decision": "Rating: Hold\n\nx"}})()
graph.graph = type("G", (), {"invoke": lambda self, i, **k: {"final_trade_decision": "Rating: Hold\n\nx", "final_rating": "Hold"}})()
book = PortfolioContext.model_validate(HOLDING)
written = graph._run_signature("stock", book) # what begin_checkpoint keys on
+21
View File
@@ -45,6 +45,7 @@ def post(monkeypatch):
monkeypatch.setattr(typesafe.time, "sleep", calls.sleeps.append)
monkeypatch.setenv("TYPESAFE_API_KEY", "ts-test")
monkeypatch.delenv("TYPESAFE_DEFAULT_MODEL", raising=False)
monkeypatch.delenv("TYPESAFE_BASE_URL", raising=False)
return calls
@@ -76,6 +77,26 @@ def test_the_model_follows_the_sdk_environment(post, monkeypatch):
assert post[0][1]["json"]["model"] == "jev-1.13.0"
@pytest.mark.unit
@pytest.mark.parametrize("base", ["https://openrouter.ai/api", "https://openrouter.ai/api/"])
def test_the_endpoint_follows_the_sdk_environment(post, monkeypatch, base):
"""TypeSafe's SDKs read TYPESAFE_BASE_URL and append /v1/systemone; OpenRouter
serves Jev at https://openrouter.ai/api with an OpenRouter key (#1416)."""
monkeypatch.setenv("TYPESAFE_BASE_URL", base)
post.queue.append(_ok())
typesafe.system_one("s", QUESTIONS)
assert post[0][0] == "https://openrouter.ai/api/v1/systemone"
@pytest.mark.unit
def test_a_base_url_without_a_key_does_not_turn_screening_on(monkeypatch):
monkeypatch.delenv("TYPESAFE_API_KEY", raising=False)
monkeypatch.setenv("TYPESAFE_BASE_URL", "https://openrouter.ai/api")
assert typesafe.jev_screen("AAPL") is None
@pytest.mark.unit
@pytest.mark.parametrize("transient", [
_Response(429), _Response(529), requests.ConnectionError(), requests.Timeout(),
+2 -2
View File
@@ -74,11 +74,11 @@ def test_a_report_that_was_never_produced_says_so(module, factory):
"market_report": "RSI 61, price 178.", "sentiment_report": "", "news_report": "",
"fundamentals_report": "", "investment_plan": "P", "trader_investment_plan": "T",
"investment_debate_state": {"bull_history": "", "bear_history": "", "history": "",
"current_response": "", "judge_decision": "", "count": 0},
"current_response": "", "count": 0},
"risk_debate_state": {"history": "", "latest_speaker": "", "count": 0,
"aggressive_history": "", "conservative_history": "", "neutral_history": "",
"current_aggressive_response": "", "current_conservative_response": "",
"current_neutral_response": "", "judge_decision": ""},
"current_neutral_response": ""},
}
getattr(mod, factory)(_LLM())(state)
+56
View File
@@ -58,3 +58,59 @@ def test_key_optionality():
assert OPENAI_COMPATIBLE_PROVIDERS["xai"].key_optional is False
# OLLAMA_BASE_URL is the only base-URL env override.
assert OPENAI_COMPATIBLE_PROVIDERS["ollama"].base_url_env == "OLLAMA_BASE_URL"
# --- a provider that signs in: its own credential, its own pinned endpoint ---------
class _Recorder:
"""Stands in for the chat class and records what the client built."""
def __init__(self, **kwargs):
self.kwargs = kwargs
def _signed_in_provider(monkeypatch, token="plan-token"):
from tradingagents.llm_clients import openai_client
spec = openai_client.ProviderSpec(
base_url="https://api.openai.com/v1", pinned_base_url=True, use_responses_api=True,
credential=lambda: (lambda: token), chat_class=_Recorder,
)
monkeypatch.setitem(openai_client.OPENAI_COMPATIBLE_PROVIDERS, "signed-in", spec)
return openai_client
@pytest.mark.unit
def test_a_signed_in_provider_sends_its_own_credential_never_an_api_key(monkeypatch):
openai_client = _signed_in_provider(monkeypatch)
monkeypatch.setenv("OPENAI_API_KEY", "sk-must-not-be-used")
llm = openai_client.OpenAIClient("gpt-x", provider="signed-in").get_llm()
assert callable(llm.kwargs["api_key"]) and llm.kwargs["api_key"]() == "plan-token"
assert llm.kwargs["base_url"] == "https://api.openai.com/v1"
@pytest.mark.unit
@pytest.mark.parametrize("client_kwargs", [
{"base_url": "https://relay.example/v1"}, # backend_url / TRADINGAGENTS_LLM_BACKEND_URL
{"api_key": "sk-explicit"},
])
def test_a_signed_in_provider_refuses_another_endpoint_or_key(monkeypatch, client_kwargs):
openai_client = _signed_in_provider(monkeypatch)
base_url = client_kwargs.pop("base_url", None)
client = openai_client.OpenAIClient("gpt-x", base_url=base_url, provider="signed-in", **client_kwargs)
with pytest.raises(ValueError):
client.get_llm()
@pytest.mark.unit
def test_a_missing_sign_in_fails_before_any_request(monkeypatch):
from tradingagents.llm_clients import openai_client
def not_signed_in():
raise ValueError("Not signed in; run `tradingagents login chatgpt`.")
spec = openai_client.ProviderSpec(base_url="https://api.openai.com/v1", pinned_base_url=True,
credential=not_signed_in, chat_class=_Recorder)
monkeypatch.setitem(openai_client.OPENAI_COMPATIBLE_PROVIDERS, "signed-in", spec)
with pytest.raises(ValueError, match="login chatgpt"):
openai_client.OpenAIClient("gpt-x", provider="signed-in").get_llm()
+105 -14
View File
@@ -41,8 +41,15 @@ def test_prose_naming_several_ratings_without_a_label_needs_review():
@pytest.mark.unit
def test_prose_naming_one_rating_is_taken_as_the_call():
assert extract_rating("On balance we stay Underweight until margins recover.") == "Underweight"
@pytest.mark.parametrize("prose", [
"We would not Sell here; the dip is a chance to add.",
"**评级**:买入\n\n不建议卖出 (Sell)。", # a label in another language, and a negated Sell
"On balance we stay Underweight until margins recover.",
])
def test_a_rating_word_without_a_label_is_not_read_as_the_call(prose):
"""A rating word in prose may be one the text argues against (#1435)."""
assert extract_rating(prose) is None
assert parse_rating(prose) == RATING_REVIEW
@pytest.mark.unit
@@ -64,7 +71,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.decision_log import TradingMemoryLog
from tradingagents.memory import TradingMemoryLog
log = TradingMemoryLog({"memory_log_path": str(tmp_path / "m.md")})
log.store_decision("NVDA", "2026-01-05", REFUSAL)
@@ -76,7 +83,7 @@ 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.rating import parse_rating
from tradingagents.decision_log import TradingMemoryLog
from tradingagents.memory import TradingMemoryLog
log = TradingMemoryLog({"memory_log_path": str(tmp_path / "m.md")})
for text in (INVERTED, REFUSAL, "**Rating**: Buy\n\nAccumulate."):
@@ -91,7 +98,7 @@ def test_the_signal_and_the_log_agree_on_the_same_decision(tmp_path):
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.backtest import summarize
from tradingagents.decision_log import TradingMemoryLog
from tradingagents.memory import TradingMemoryLog
log = TradingMemoryLog({"memory_log_path": str(tmp_path / "m.md")})
log.store_decision("NVDA", "2026-01-05", "**Rating**: Buy\n\nx")
@@ -121,10 +128,6 @@ def test_the_cli_says_when_a_run_produced_no_usable_rating(monkeypatch, tmp_path
def record_decision(self, *a, **k):
pass
def process_signal(self, text):
from tradingagents.agents.rating import parse_rating
return parse_rating(text)
def get_graph_args(self, callbacks=None):
return {}
@@ -140,8 +143,8 @@ def test_the_cli_says_when_a_run_produced_no_usable_rating(monkeypatch, tmp_path
def end_checkpoint(self):
pass
def stream(self, *a, **k):
yield {"messages": [], "final_trade_decision": REFUSAL}
def stream_run(self, *a, **k):
yield [], {"messages": [], "final_trade_decision": REFUSAL, "final_rating": RATING_REVIEW}
fake = _Graph()
fake.graph = fake
@@ -155,7 +158,7 @@ def test_the_cli_says_when_a_run_produced_no_usable_rating(monkeypatch, tmp_path
monkeypatch.setattr(m.console, "print", lambda *a, **k: printed.append(" ".join(str(x) for x in a)))
monkeypatch.setattr(cli_run, "display_complete_report", lambda *a, **k: None)
monkeypatch.setattr(m.typer, "prompt", lambda *a, **k: "N")
monkeypatch.setattr(cli_run, "get_user_selections", lambda: {
monkeypatch.setattr(cli_run, "get_user_selections", lambda flags=None: {
"ticker": "NVDA", "analysis_date": "2026-01-10",
"analysts": [AnalystType.MARKET], "asset_type": "stock",
})
@@ -198,11 +201,11 @@ def test_a_decision_prompt_states_the_shape_of_its_answer(module, factory, must_
"news_report": "N", "fundamentals_report": "F", "investment_plan": "P",
"trader_investment_plan": "T", "past_context": "", "portfolio_context": "",
"investment_debate_state": {"bull_history": "b", "bear_history": "r", "history": "h",
"current_response": "", "judge_decision": "", "count": 2},
"current_response": "", "count": 2},
"risk_debate_state": {"history": "h", "latest_speaker": "", "count": 3,
"aggressive_history": "", "conservative_history": "", "neutral_history": "",
"current_aggressive_response": "", "current_conservative_response": "",
"current_neutral_response": "", "judge_decision": ""},
"current_neutral_response": ""},
}
getattr(mod, factory)(_LLM())(state)
@@ -210,3 +213,91 @@ def test_a_decision_prompt_states_the_shape_of_its_answer(module, factory, must_
assert "## Output" in prompt, "no output-format section in the prompt"
section = prompt.split("## Output", 1)[1]
assert f"**{must_name}**" in section, section[:300]
@pytest.mark.unit
def test_a_state_without_the_typed_rating_reads_it_from_the_decision():
"""A run finished by an older version and resumed from its checkpoint has
no final_rating; every reader falls back the same way instead of one
raising and another reporting REVIEW."""
from tradingagents.agents.rating import run_rating
assert run_rating({"final_rating": "Hold", "final_trade_decision": "**Rating**: Buy"}) == "Hold"
assert run_rating({"final_trade_decision": "**Rating**: Sell\n\nExit."}) == "Sell"
assert run_rating({}) == RATING_REVIEW
@pytest.mark.unit
@pytest.mark.parametrize("quoted", [
"Street consensus rating: Buy (28 of 35 analysts).",
"Moody's affirmed the credit rating: Buy-side demand for the bonds stayed firm.",
"Operating margin: Sell-side estimates sit below guidance.",
])
def test_a_rating_the_text_quotes_does_not_replace_the_decision(quoted):
"""A free-text decision opens with its own rating line; a rating it quotes
as evidence, or a word merely ending in 'rating', is not the call."""
text = f"**Rating**: Hold\n\n**Investment Thesis**: {quoted} We wait for margins."
assert extract_rating(text) == "Hold"
@pytest.mark.unit
@pytest.mark.parametrize("quoted", [
"- Rating: Buy (Goldman Sachs, 12m target 180)",
"| Rating: Buy | Morgan Stanley |",
"> Rating: Buy, per the sell-side note",
"Street consensus rating: Buy",
"Consensus rating: Buy (28 of 35 analysts)",
])
def test_a_quoted_rating_in_a_list_table_or_quote_is_not_the_decision(quoted):
text = f"Our rating: Hold\n\nWhat others say:\n{quoted}\n\nWe wait for margins."
assert extract_rating(text) == "Hold"
@pytest.mark.unit
@pytest.mark.parametrize("text, expected", [
("Consensus rating: Buy\nRating: Sell", "Sell"),
("Analyst rating: Overweight\n**Rating**: Underweight", "Underweight"),
("Previous rating: Buy\n## Final Rating - Hold", "Hold"),
("Street rating: Sell\nOur rating: Buy", "Buy"),
("Credit rating: Sell\nRating: Buy", "Buy"),
("Sell-side consensus rating: Buy\n**Rating**: Hold", "Hold"),
# the decision opens with its rating, as the prompt asks
("- **Rating**: Sell\n\nConsensus rating: Buy", "Sell"),
("- **Rating**: Sell\n- **Investment Thesis**: consensus rating: Buy, we disagree.", "Sell"),
("1. **Rating**: Underweight\n2. **Executive Summary**: Street rating: Buy.", "Underweight"),
("\u2022 **Rating**: Sell\nConsensus rating: Buy", "Sell"),
("## Decision\n\n- **Rating**: Hold\n- Rating: Buy (Goldman Sachs)", "Hold"),
("Recommended rating: Buy\n\nConsensus rating: Sell", "Buy"),
("Updated rating: Sell\nPrevious rating: Buy", "Sell"),
("Our final rating: Sell\nConsensus rating: Buy", "Sell"),
("**Overall Final Rating**: Sell\nConsensus rating: Buy", "Sell"),
# ratings quoted as list items before the decision's own line
("Broker views:\n- Rating: Buy (Morgan Stanley)\n- Rating: Hold (Goldman)\n\n**Rating**: Sell", "Sell"),
("Previous decision recap:\n- **Rating**: Buy (2026-09-01)\n\n**Rating**: Sell", "Sell"),
("Lessons:\n- Rating: Buy was wrong last time\n\n**Rating**: Hold", "Hold"),
])
def test_a_rating_someone_else_gave_does_not_become_the_decision(text, expected):
"""The decision's own rating line is read as the call; another party's
rating, even on a line of its own, is evidence, not the call (#1466)."""
assert extract_rating(text) == expected
@pytest.mark.unit
@pytest.mark.parametrize("text", [
"Trader's proposed rating: Buy\n\nPortfolio Manager's rating: Hold",
"Research Manager rating: Buy\nPortfolio rating: Underweight",
"Trader's rating: Buy\nRisk team rating: Sell\nPortfolio Manager's Final Rating: Hold",
"Risk views:\n- Aggressive analyst rating: Buy\n- Conservative rating: Sell\n\nPM: Rating: Hold",
"PM Rating: Sell\n- Rating: Buy (JPMorgan)",
"Position rating: Underweight\n* Rating: Overweight per Citi",
"Street views:\n- Goldman rating: Buy\n\nWeighing all of this, the Portfolio Manager's rating: Underweight.",
"Analyst views:\n- Rating: Buy (Goldman)\n\nAfter the debate our final call is Sell (Rating: Sell).",
"Lessons:\n- Rating: Buy was wrong last time\n\n- **Rating**: Hold",
"Broker views:\n- Rating: Buy (MS)\n\n- **Rating**: Sell",
"Investment rating: Underweight\nStreet rating: Buy",
"## Street view\n1. Rating: Buy, target $250 (JPM)\n\n## Our call\n**Rating**: Underweight",
])
def test_ratings_that_disagree_with_no_line_of_the_decisions_own_need_review(text):
"""When the text never states its own rating in the decision's shape and the
ratings it names disagree, nobody can tell which is the call (#1170)."""
assert extract_rating(text) is None
+22
View File
@@ -311,3 +311,25 @@ def test_an_unavailable_screen_keeps_every_post_and_says_so():
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
@pytest.mark.unit
@pytest.mark.parametrize("ticker, expected", [
("NVDA", ("wallstreetbets", "stocks", "investing")),
("BTC-USD", ("Bitcoin", "CryptoCurrency", "CryptoMarkets")),
("ETH-USD", ("ethereum", "CryptoCurrency", "CryptoMarkets")),
("SOL-USD", ("solana", "CryptoCurrency", "CryptoMarkets")),
("DOGE-USD", ("CryptoCurrency", "CryptoMarkets")),
])
def test_a_crypto_ticker_is_searched_in_crypto_communities(ticker, expected):
assert reddit.subreddits_for(ticker) == expected
@pytest.mark.unit
def test_a_crypto_pair_is_fetched_from_its_communities_in_one_request():
with patch.object(reddit, "_fetch_subreddit_rss", return_value=[]) as fetch:
out = reddit.fetch_reddit_posts("ETH-USD")
fetch.assert_called_once()
query, subs = fetch.call_args.args[:2]
assert (query, subs) == ("ETH", "ethereum+CryptoCurrency+CryptoMarkets")
assert "r/wallstreetbets" not in out
+174
View File
@@ -0,0 +1,174 @@
"""An optional HTML copy of the report, for readers who do not open Markdown (#1419).
It is one self-contained file: no script, no remote asset, nothing a report's
text can inject; the Markdown report is unchanged.
"""
import re
import pytest
from tradingagents.reporting import write_report_tree
SETTINGS = {"version": "1.2.3", "llm_provider": "openai", "deep_think_llm": "gpt-6-sol",
"quick_think_llm": "gpt-6-luna", "analysts": ["market", "news"], "max_debate_rounds": 1,
"max_risk_discuss_rounds": 1, "data_vendors": {"core_stock_apis": "yfinance"}}
def _state(**overrides):
state = {"trade_date": "2026-09-26",
"market_report": "# Market view\n\nPrice | Level\n--- | ---\nClose | 181.2\n",
"news_report": "News text.",
"final_trade_decision": "**Rating**: Overweight\n\nAdd on weakness."}
state.update(overrides)
return state
def _html(tmp_path, **overrides):
write_report_tree(_state(**overrides), "NVDA", tmp_path, settings=SETTINGS, html=True)
return (tmp_path / "complete_report.html").read_text(encoding="utf-8")
@pytest.mark.unit
def test_the_html_page_is_written_unless_declined(tmp_path):
write_report_tree(_state(), "NVDA", tmp_path / "plain", settings=SETTINGS, html=False)
assert not (tmp_path / "plain" / "complete_report.html").exists()
write_report_tree(_state(), "NVDA", tmp_path / "default", settings=SETTINGS)
assert (tmp_path / "default" / "complete_report.html").exists()
page = _html(tmp_path / "html")
assert "<h1" in page and "NVDA" in page and "Overweight" in page and "2026-09-26" in page
assert '<table>' in page and "181.2" in page
@pytest.mark.unit
def test_the_markdown_report_is_the_same_with_or_without_html(tmp_path):
write_report_tree(_state(), "NVDA", tmp_path / "a", settings=SETTINGS, html=False)
write_report_tree(_state(), "NVDA", tmp_path / "b", settings=SETTINGS)
def undated(path):
return re.sub(r"- Generated: .*\n", "", path.read_text(encoding="utf-8"))
assert undated(tmp_path / "a" / "complete_report.md") == undated(tmp_path / "b" / "complete_report.md")
@pytest.mark.unit
def test_the_page_loads_nothing_and_runs_nothing(tmp_path):
page = _html(tmp_path)
assert "Content-Security-Policy" in page and "default-src 'none'" in page
assert "<script" not in page.lower()
assert not re.search(r'<(img|link|iframe|object|embed)\b', page, re.IGNORECASE)
@pytest.mark.unit
def test_report_text_cannot_inject_markup_or_fetch_anything(tmp_path):
hostile = ("<script>alert(1)</script> <img src=x onerror=alert(1)>\n\n"
"![pixel](https://tracker.example/p.png) [x](javascript:alert(1))")
page = _html(tmp_path, news_report=hostile)
assert "<script>alert" not in page and "<img" not in page.lower()
assert "tracker.example/p.png" not in re.findall(r'(?:src|href)="([^"]*)"', page)
assert 'href="javascript:' not in page
@pytest.mark.unit
def test_header_values_are_escaped(tmp_path):
write_report_tree(_state(), "<b>NV</b>", tmp_path, settings={**SETTINGS, "deep_think_llm": "<i>m</i>"}, html=True)
page = (tmp_path / "complete_report.html").read_text(encoding="utf-8")
assert "<b>NV</b>" not in page and "&lt;b&gt;NV&lt;/b&gt;" in page and "<i>m</i>" not in page
@pytest.mark.unit
def test_an_agent_s_own_headings_sit_below_its_heading(tmp_path):
page = _html(tmp_path)
assert page.count("<h1") == 1 # only the report's title
assert re.search(r"<h4[^>]*>Market view</h4>", page)
def _fields(fragment):
return re.findall(r'<span class="field">([^<]*)</span>', fragment)
@pytest.mark.unit
def test_run_details_show_each_value_as_its_own_field(tmp_path):
settings = {**SETTINGS, "deep_think_provider": "anthropic", "deep_think_llm": "claude-opus-5-5",
"data_vendors": {"core_stock_apis": "yfinance", "fundamental_data": "sec_edgar,yfinance"}}
write_report_tree(_state(), "NVDA", tmp_path, settings=settings, html=True)
page = (tmp_path / "complete_report.html").read_text(encoding="utf-8")
header = page[page.index("<header"):page.index("</header>")]
for value in ("anthropic", "claude-opus-5-5", "openai", "gpt-6-luna", "market", "news",
"sec_edgar", "yfinance"):
assert value in _fields(header)
# Vendors are named by what they serve, and a chain keeps its order.
assert "Prices" in header and "Fundamentals" in header and "fundamental_data" not in header
assert header.index(">sec_edgar<") < header.rindex(">yfinance<")
@pytest.mark.unit
def test_the_contents_name_each_section_once_and_list_its_agents_beneath(tmp_path):
page = _html(tmp_path)
nav = page[page.index('<nav class="contents"'):page.index("</nav>")]
assert "<ol" not in nav # no list numbers beside the sections' own I-V
assert re.search(r'<a href="#s1"><span class="num">I</span>\s*<span class="label">Analyst Team Reports</span></a>', nav)
assert re.search(r'<a href="#s1-1"><span class="bar"></span>\s*<span class="label">Market Analyst</span></a>', nav)
@pytest.mark.unit
def test_the_section_rail_opens_on_hover_and_keyboard_focus(tmp_path):
page = _html(tmp_path)
css = page[page.index("<style>"):page.index("</style>")]
# Wide screens: a rail centred on the left edge whose names are hidden from
# sight only (still read by screen readers) until it is pointed at or focused.
assert "top: 50%" in css and "translateY(-50%)" in css
assert ".contents:hover .label" in css and ".contents:focus-within .label" in css
assert "display: none" not in css.split(".contents .label", 1)[1].split("}", 1)[0]
@pytest.mark.unit
def test_the_sections_stay_within_reach(tmp_path):
page = _html(tmp_path)
nav = page[page.index('<nav class="contents"'):page.index("</nav>")]
assert "<h2" not in nav # the list needs no heading
assert 'id="top"' in page and 'href="#top"' in page # a way back on small screens
assert ".contents { position: fixed;" in page # beside the text on wide ones
@pytest.mark.unit
def test_the_page_heading_is_the_ticker_and_its_rating(tmp_path):
page = _html(tmp_path)
heading = re.search(r"<h1>(.*?)</h1>", page).group(1)
assert re.sub(r"<[^>]+>", "", heading).split() == ["NVDA", "Overweight"]
@pytest.mark.unit
def test_the_header_carries_the_official_logo_unaltered(tmp_path):
from importlib.resources import files
logo = files("tradingagents").joinpath("assets/tauric-logo.svg").read_text(encoding="utf-8").strip()
page = _html(tmp_path)
header = page[page.index("<header"):page.index("</header>")]
assert logo in header # drawn in the page, nothing fetched
assert 'href="https://tauric.ai"' in header and 'aria-label="Tauric Research"' in header
assert header.index('class="logo"') < header.index("<h1") # leads the header, above the title
@pytest.mark.unit
def test_the_page_credits_its_maker_in_a_line_of_text(tmp_path):
page = _html(tmp_path)
footer = page[page.index('<footer class="credit">'):page.index("</footer>")]
assert re.sub(r"<[^>]+>", "", footer).split() == ["TradingAgents", "powered", "by", "Tauric", "Research"]
# The logo already leads to tauric.ai; the credit leads to the project and the org.
assert 'href="https://github.com/TauricResearch/TradingAgents"' in footer
assert 'href="https://github.com/TauricResearch"' in footer and "tauric.ai" not in footer
assert "<svg" not in footer and 'class="brand"' in footer
assert page.index("</main>") < page.index('<footer class="credit">')
@pytest.mark.unit
def test_the_packaged_logo_stays_inert(tmp_path):
# The logo is drawn inside every report, so it may only ever hold shapes:
# no script, event handler, link, embedded document or external reference.
from importlib.resources import files
logo = files("tradingagents").joinpath("assets/tauric-logo.svg").read_text(encoding="utf-8")
tags = set(re.findall(r"<\s*([a-zA-Z][\w:-]*)", logo))
assert tags <= {"svg", "path", "rect", "circle", "g", "defs", "clipPath", "linearGradient", "stop"}
assert not re.search(r"\son\w+\s*=|href|url\(|@import|javascript:|<!entity|<!doctype", logo, re.IGNORECASE)
+131 -6
View File
@@ -1,6 +1,7 @@
"""Report parity: the shared writer produces the report tree for the CLI and the
programmatic API alike (#1037)."""
import re
from types import SimpleNamespace
import pytest
@@ -13,12 +14,19 @@ def _state():
return {
"market_report": "MKT",
"news_report": "NEWS",
"investment_debate_state": {"judge_decision": "RM PLAN"},
"investment_debate_state": {"bull_history": "BULL"},
"investment_plan": "RM PLAN",
"trader_investment_plan": "TRADE",
"risk_debate_state": {"judge_decision": "PM DECISION"},
"risk_debate_state": {"neutral_history": "NEUTRAL"},
"final_trade_decision": "PM DECISION",
}
SETTINGS = {"version": "0.5.2", "llm_provider": "openai", "deep_think_llm": "gpt-6-sol",
"quick_think_llm": "gpt-6-luna", "analysts": ["market", "news"], "max_debate_rounds": 1,
"max_risk_discuss_rounds": 2, "data_vendors": {"core_stock_apis": "yfinance"}}
@pytest.mark.unit
def test_write_report_tree_creates_files(tmp_path):
out = write_report_tree(_state(), "AAPL", tmp_path)
@@ -35,16 +43,133 @@ def test_write_report_tree_creates_files(tmp_path):
@pytest.mark.unit
def test_save_reports_explicit_path(tmp_path):
# Unbound: with an explicit save_path, the method doesn't touch self/config.
out = TradingAgentsGraph.save_reports(None, _state(), "AAPL", save_path=tmp_path)
graph = SimpleNamespace(run_settings=lambda: SETTINGS)
out = TradingAgentsGraph.save_reports(graph, _state(), "AAPL", save_path=tmp_path)
assert (tmp_path / "complete_report.md").exists()
assert out == tmp_path / "complete_report.md"
@pytest.mark.unit
@pytest.mark.parametrize("empty_value", [None, ""])
def test_save_reports_replaces_previous_run_sections(tmp_path, empty_value):
graph = SimpleNamespace(run_settings=lambda: SETTINGS)
first = dict(_state(), trade_date="2026-09-22")
TradingAgentsGraph.save_reports(graph, first, "AAPL", save_path=tmp_path)
(tmp_path / "notes.md").write_text("User notes", encoding="utf-8")
(tmp_path / "1_analysts" / "notes.md").write_text("Analyst notes", encoding="utf-8")
second = {
"trade_date": "2026-09-23",
"market_report": "NEW MARKET",
"news_report": empty_value,
"investment_debate_state": {"bull_history": empty_value},
}
out = TradingAgentsGraph.save_reports(graph, second, "AAPL", save_path=tmp_path)
assert (tmp_path / "1_analysts" / "market.md").read_text() == "NEW MARKET"
for filename in (
"1_analysts/news.md", "2_research/bull.md", "2_research/manager.md",
"3_trading/trader.md", "4_risk/neutral.md", "5_portfolio/decision.md",
):
assert not (tmp_path / filename).exists()
assert (tmp_path / "notes.md").read_text() == "User notes"
assert (tmp_path / "1_analysts" / "notes.md").read_text() == "Analyst notes"
assert "NEW MARKET" in out.read_text(encoding="utf-8")
assert "NEWS" not in out.read_text(encoding="utf-8")
assert "NEWS" not in (tmp_path / "complete_report.html").read_text(encoding="utf-8")
@pytest.mark.unit
def test_empty_report_removes_previous_sections_and_disabled_html(tmp_path):
write_report_tree(_state(), "AAPL", tmp_path)
out = write_report_tree({}, "AAPL", tmp_path, html=False)
assert list(tmp_path.rglob("*.md")) == [out]
assert not (tmp_path / "complete_report.html").exists()
assert "Trading Analysis Report: AAPL" in out.read_text()
@pytest.mark.unit
def test_save_reports_defaults_under_results_dir(tmp_path):
mock_self = SimpleNamespace(config={"results_dir": str(tmp_path)})
out = TradingAgentsGraph.save_reports(mock_self, _state(), "AAPL")
graph = object.__new__(TradingAgentsGraph)
graph.config = {"results_dir": str(tmp_path)}
graph.run_settings = lambda: SETTINGS
out = graph.save_reports(_state(), "AAPL")
assert out.exists()
assert out.parent.parent.name == "reports" # results_dir/reports/AAPL_<stamp>/...
assert out.parent.name.startswith("AAPL_")
@pytest.mark.unit
def test_the_report_names_the_analysis_date_and_what_produced_it(tmp_path):
state = dict(_state(), trade_date="2026-09-23")
header = write_report_tree(state, "NVDA", tmp_path, settings=SETTINGS).read_text().split("## ")[0]
assert "Analysis date: 2026-09-23" in header
assert "TradingAgents 0.5.2" in header
assert "openai, deep gpt-6-sol, quick gpt-6-luna" in header
assert "Analysts: market, news" in header
assert "research debate rounds 1, risk debate rounds 2" in header
assert "core_stock_apis yfinance" in header
@pytest.mark.unit
def test_run_settings_record_the_run_without_endpoints_or_paths():
from tradingagents.graph.trading_graph import TradingAgentsGraph
graph = object.__new__(TradingAgentsGraph)
graph.selected_analysts = ("market", "news")
graph.config = {"llm_provider": "openai", "deep_think_llm": "gpt-6-sol", "quick_think_llm": "gpt-6-luna",
"max_debate_rounds": 1, "max_risk_discuss_rounds": 1, "output_language": "English",
"data_vendors": {"core_stock_apis": "yfinance"}, "tool_vendors": {},
"backend_url": "https://user:secret@relay.example/v1", "results_dir": "/home/me/results"}
settings = graph.run_settings()
assert settings["analysts"] == ["market", "news"]
assert settings["deep_think_llm"] == "gpt-6-sol"
assert "secret" not in str(settings) and "/home/me" not in str(settings)
@pytest.mark.unit
def test_a_partial_settings_dict_still_writes_the_report(tmp_path):
out = write_report_tree(_state(), "AAPL", tmp_path, settings={"llm_provider": "openai"})
assert "openai" in out.read_text()
@pytest.mark.unit
def test_run_settings_name_the_version_of_the_running_code():
import tradingagents
from tradingagents.graph.trading_graph import TradingAgentsGraph
graph = object.__new__(TradingAgentsGraph)
graph.selected_analysts, graph.config = ("market",), {}
assert graph.run_settings()["version"] == tradingagents.__version__
@pytest.mark.unit
@pytest.mark.parametrize("decision, rating", [
("**Rating**: Overweight\n\nAdd on weakness.", "Overweight"),
("Add on weakness.", "REVIEW"), # no readable rating is said, not left out
])
def test_the_report_header_names_the_rating(tmp_path, decision, rating):
state = dict(_state(), final_trade_decision=decision)
header = write_report_tree(state, "NVDA", tmp_path, settings=SETTINGS).read_text().split("## ")[0]
assert f"- Rating: {rating}" in header
@pytest.mark.unit
def test_the_header_names_the_analysts_as_users_select_them(tmp_path):
settings = {**SETTINGS, "analysts": ["market", "social", "news"]}
write_report_tree(_state(), "NVDA", tmp_path, settings=settings, html=True)
markdown = (tmp_path / "complete_report.md").read_text(encoding="utf-8")
assert "market, sentiment, news" in markdown and "social" not in markdown
page = (tmp_path / "complete_report.html").read_text(encoding="utf-8")
fields = re.findall(r'<span class="field">([^<]*)</span>', page)
assert {"market", "sentiment", "news"} <= set(fields) and "social" not in page
+96 -34
View File
@@ -97,9 +97,10 @@ def test_the_quarter_is_not_confused_with_the_year_to_date():
@pytest.mark.unit
def test_a_line_the_filer_does_not_tag_is_named_unavailable():
def test_a_line_the_filer_does_not_tag_is_named_as_such():
out = sec_edgar.get_balance_sheet("AAPL", "annual", "2024-11-15")
assert "Stockholders Equity" in out and "unavailable" in out
untagged = [line for line in out.splitlines() if line.startswith("# Not tagged by this filer:")]
assert len(untagged) == 1 and "Stockholders Equity" in untagged[0]
assert "364980" in out # the rest of the statement still returns
@@ -144,13 +145,13 @@ def test_a_throttle_lets_the_next_vendor_try(monkeypatch):
"""SEC throttles by refusing the request; the router then tries yfinance."""
import requests
from tradingagents.dataflows.errors import VendorRateLimitError
from tradingagents.dataflows.errors import VendorUnavailableError
def _throttled(*a, **k):
raise requests.HTTPError(response=mock.Mock(status_code=429))
monkeypatch.setattr(sec_edgar.requests, "get", _throttled)
with pytest.raises(VendorRateLimitError):
with pytest.raises(VendorUnavailableError):
_REAL_FETCH("https://data.sec.gov/api/xbrl/companyfacts/CIK0000320193.json")
@@ -158,8 +159,7 @@ def test_a_throttle_lets_the_next_vendor_try(monkeypatch):
def test_values_do_not_break_the_columns():
"""Figures run to the billions; a thousands separator would split the field."""
out = sec_edgar.get_balance_sheet("AAPL", "annual", "2024-11-15")
body = [row for row in out.splitlines() if row.startswith("Total Assets")][0]
assert body.count(",") == out.splitlines()[3].count(",")
assert _table(out)[1]["Total Assets"][-1] == "364980"
@pytest.mark.unit
@@ -167,15 +167,12 @@ def test_a_per_share_figure_keeps_its_own_unit():
"""Statements are reported in millions, but EPS is dollars per share: scaling
it the same way prints a real figure as zero."""
out = sec_edgar.get_income_statement("AAPL", "annual", "2024-11-15")
row = [r for r in out.splitlines() if r.startswith("Diluted EPS")][0]
assert "6.08" in row
assert "USD/shares" in row or "per share" in row
assert _table(out)[1]["Diluted EPS (USD/shares)"] == ["6.08"]
@pytest.mark.unit
def test_every_row_has_one_cell_per_period():
"""An untagged line still has to line up with the columns, or the table is
misread by position."""
def test_every_row_has_one_cell_per_column():
"""Every period's row lines up with the header, or the table is misread by position."""
out = sec_edgar.get_balance_sheet("AAPL", "annual", "2024-11-15")
table = [r for r in out.splitlines() if r and not r.startswith("#")]
widths = {row.count(",") for row in table}
@@ -205,8 +202,8 @@ def test_older_periods_fall_back_to_the_tag_the_filer_used_then():
"RevenueFromContractWithCustomerExcludingAssessedTax": {"units": {"USD": [
_fact("2024-09-28", 391_035_000_000, "2024-11-01", start="2023-09-30")]}}}
values, unit = sec_edgar._as_of(facts, ("RevenueFromContractWithCustomerExcludingAssessedTax",
"Revenues"), "2026-01-01", (300, 400))
assert values == {"2015-09-26": 233_715_000_000, "2024-09-28": 391_035_000_000}
"Revenues"), "2026-01-01", ((300, 400),))
assert values == {("2015-09-26", 0): 233_715_000_000, ("2024-09-28", 0): 391_035_000_000}
assert unit == "USD"
@@ -216,27 +213,17 @@ def test_a_period_reported_under_two_tags_takes_the_preferred_one_not_both():
"RevenueFromContractWithCustomerExcludingAssessedTax": {"units": {"USD": [
_fact("2024-09-28", 999, "2024-11-01", start="2023-09-30")]}}}
values, _ = sec_edgar._as_of(facts, ("RevenueFromContractWithCustomerExcludingAssessedTax",
"Revenues"), "2026-01-01", (300, 400))
assert values == {"2024-09-28": 999}
"Revenues"), "2026-01-01", ((300, 400),))
assert values == {("2024-09-28", 0): 999}
@pytest.mark.unit
def test_the_default_identification_tracks_the_installed_version(monkeypatch):
"""A release should identify itself, not a version frozen in the source."""
def test_the_default_identification_names_the_package_version(monkeypatch):
"""SEC asks automated clients to identify themselves; a release names its own version."""
import tradingagents
monkeypatch.delenv("SEC_EDGAR_USER_AGENT", raising=False)
monkeypatch.setattr(sec_edgar.metadata, "version", lambda name: "9.9.9")
assert sec_edgar._user_agent() == "TradingAgents/9.9.9 (contact@example.com)"
@pytest.mark.unit
def test_an_uninstalled_checkout_still_identifies_itself(monkeypatch):
monkeypatch.delenv("SEC_EDGAR_USER_AGENT", raising=False)
def _missing(name):
raise sec_edgar.metadata.PackageNotFoundError(name)
monkeypatch.setattr(sec_edgar.metadata, "version", _missing)
assert "@" in sec_edgar._user_agent()
assert sec_edgar._user_agent() == f"TradingAgents/{tradingagents.__version__} (contact@example.com)"
@pytest.mark.unit
@@ -247,11 +234,18 @@ def test_capital_expenditure_is_found_under_either_tag_filers_use(monkeypatch):
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"]
assert _table(out)[1]["Capital Expenditure"] == ["70"]
def _table(out):
"""(periods, {column: cells by period}) of a statement, one row per period."""
lines = [line for line in out.splitlines() if line and not line.startswith("#")]
header, rows = lines[0].split(","), [line.split(",") for line in lines[1:]]
return [row[0] for row in rows], {name: [row[i] for row in rows] for i, name in enumerate(header) if i}
def _columns(out):
return [line for line in out.splitlines() if line.startswith(",")][0].split(",")[1:]
return _table(out)[0]
@pytest.mark.unit
@@ -289,7 +283,75 @@ def test_a_recast_outside_the_annual_report_still_counts_from_its_filing(monkeyp
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]
return _table(out)[1]["Diluted EPS (USD/shares)"][0]
assert eps("2019-01-01") == "16.97"
assert eps("2020-01-01") == "2.12"
@pytest.mark.unit
def test_a_cash_flow_filed_year_to_date_is_served_with_its_span(monkeypatch):
"""Many filers tag a 10-Q's cash flows only year to date (3, 6, then 9 months):
a quarterly table of discrete quarters alone would stop at each first quarter."""
ytd = [
_fact("2025-12-27", 30_000_000_000, "2026-01-30", form="10-Q", fp="Q1", start="2025-09-28"),
_fact("2026-03-28", 53_000_000_000, "2026-05-01", form="10-Q", fp="Q2", start="2025-09-28"),
_fact("2026-06-27", 81_000_000_000, "2026-08-01", form="10-Q", fp="Q3", start="2025-09-28"),
]
facts = {"facts": {"us-gaap": {"NetCashProvidedByUsedInOperatingActivities": {"units": {"USD": ytd}}}}}
monkeypatch.setattr(sec_edgar, "_fetch_json",
lambda url: TICKER_MAP if "company_tickers" in url else facts)
out = sec_edgar.get_cashflow("AAPL", "quarterly", "2026-09-28")
assert _columns(out) == ["2025-12-27", "2026-03-28 (6 months)", "2026-06-27 (9 months)"]
assert _table(out)[1]["Operating Cash Flow"] == ["30000", "53000", "81000"]
@pytest.mark.unit
def test_a_row_filed_only_year_to_date_keeps_its_figure_beside_a_row_filed_by_quarter(monkeypatch):
facts = {"facts": {"us-gaap": {
"NetCashProvidedByUsedInOperatingActivities": {"units": {"USD": [
_fact("2026-06-30", 120_000_000, "2026-08-01", form="10-Q", fp="Q2", start="2026-01-01")]}},
"PaymentsToAcquirePropertyPlantAndEquipment": {"units": {"USD": [
_fact("2026-06-30", 10_000_000, "2026-08-01", form="10-Q", fp="Q2", start="2026-04-01")]}},
}}}
monkeypatch.setattr(sec_edgar, "_fetch_json",
lambda url: TICKER_MAP if "company_tickers" in url else facts)
out = sec_edgar.get_cashflow("AAPL", "quarterly", "2026-09-28")
assert _columns(out) == ["2026-06-30", "2026-06-30 (6 months)"]
columns = _table(out)[1]
assert columns["Operating Cash Flow"] == ["", "120"]
assert columns["Capital Expenditure"] == ["10", ""]
@pytest.mark.unit
def test_a_statement_serves_every_period_one_row_each(monkeypatch):
"""A filer's whole history in a row per line item ran to 67 columns and was read
a column off (#1517); a row per period keeps each figure beside its date."""
quarters = [
_fact(f"{year}-{month:02d}-30", (year * 10 + month // 3) * 1_000_000, f"{year}-{month + 1:02d}-28",
form="10-Q", fp=f"Q{month // 3}", start=f"{year}-{month - 2:02d}-01")
for year in range(2015, 2026) for month in (3, 6, 9)
]
facts = {"facts": {"us-gaap": {"Revenues": {"units": {"USD": quarters}}}}}
monkeypatch.setattr(sec_edgar, "_fetch_json",
lambda url: TICKER_MAP if "company_tickers" in url else facts)
periods, columns = _table(sec_edgar.get_income_statement("AAPL", "quarterly", "2026-01-15"))
assert periods == [f"{y}-{m:02d}-30" for y in range(2015, 2026) for m in (3, 6, 9)]
assert columns["Revenue"][0] == "20151" and columns["Revenue"][-1] == "20253"
@pytest.mark.unit
def test_a_figure_under_a_million_is_not_printed_as_zero(monkeypatch):
facts = {"facts": {"us-gaap": {"Revenues": {"units": {"USD": [
_fact("2025-12-31", 303_300, "2026-02-20", start="2025-01-01"),
_fact("2024-12-31", -25_000, "2025-02-20", start="2024-01-01")]}}}}}
monkeypatch.setattr(sec_edgar, "_fetch_json",
lambda url: TICKER_MAP if "company_tickers" in url else facts)
assert _table(sec_edgar.get_income_statement("AAPL", "annual", "2026-03-01"))[1]["Revenue"] == ["-0.0250", "0.303"]
-17
View File
@@ -75,20 +75,3 @@ class TestExtractRating:
# The memory log tags an unreadable decision REVIEW, never a tradeable rating.
assert parse_rating("No rating here.") == RATING_REVIEW
assert parse_rating("No rating here.", default="Underweight") == "Underweight"
@pytest.mark.unit
class TestGraphSignalContract:
"""The graph-facing signal (TradingAgentsGraph.process_signal) honors the
documented "5-tier or REVIEW" contract, not just the parser in isolation."""
def _bare_graph(self):
from tradingagents.graph.trading_graph import TradingAgentsGraph
g = object.__new__(TradingAgentsGraph)
return g
def test_graph_surfaces_review(self):
assert self._bare_graph().process_signal("no rating in here") == RATING_REVIEW
def test_graph_returns_rating(self):
assert self._bare_graph().process_signal("**Rating**: Sell") == "Sell"
+9 -9
View File
@@ -8,7 +8,7 @@ as-of date. All three sources share dataflows.date_window.in_window.
from __future__ import annotations
import json
from datetime import datetime, timezone
from datetime import UTC, datetime
import pytest
@@ -38,10 +38,10 @@ class _JsonResp:
def test_in_window_bounds_and_exclusive_upper():
start = datetime(2026, 5, 1)
end = datetime(2026, 5, 9)
assert in_window(datetime(2026, 5, 5, tzinfo=timezone.utc), start, end) is True
assert in_window(datetime(2026, 5, 9, 23, 59, tzinfo=timezone.utc), start, end) is True
assert in_window(datetime(2026, 5, 5, tzinfo=UTC), start, end) is True
assert in_window(datetime(2026, 5, 9, 23, 59, tzinfo=UTC), start, end) is True
# exactly midnight after end -> excluded (no leak)
assert in_window(datetime(2026, 5, 10, 0, 0, tzinfo=timezone.utc), start, end) is False
assert in_window(datetime(2026, 5, 10, 0, 0, tzinfo=UTC), start, end) is False
# offset-aware converted, not truncated: 05-10T01:00+05:00 == 05-09T20:00Z
assert in_window(datetime.fromisoformat("2026-05-10T01:00:00+05:00"), start, end) is True
@@ -50,7 +50,7 @@ def test_in_window_bounds_and_exclusive_upper():
def test_in_window_undated_excluded_in_backtest_kept_live():
old = datetime(2026, 5, 9)
assert in_window(None, datetime(2026, 5, 1), old) is False # historical
now = datetime.now(timezone.utc)
now = datetime.now(UTC)
assert in_window(None, now, now) is True # live
@@ -96,7 +96,7 @@ def test_stocktwits_no_window_is_unfiltered(monkeypatch):
# --- Reddit -----------------------------------------------------------------
def _epoch(date_str):
return int(datetime.strptime(date_str, "%Y-%m-%d").replace(tzinfo=timezone.utc).timestamp())
return int(datetime.strptime(date_str, "%Y-%m-%d").replace(tzinfo=UTC).timestamp())
@pytest.mark.unit
@@ -184,7 +184,7 @@ def test_reddit_window_straddling_the_lookback_is_unavailable(monkeypatch):
# Ten days ago through five days ago: the week-long search never reaches the
# first three days, so an empty result cannot stand for the whole window.
from datetime import timedelta
today = datetime.now(timezone.utc).date()
today = datetime.now(UTC).date()
monkeypatch.setattr(reddit, "_fetch_subreddit_rss", lambda *a, **k: [])
out = reddit.fetch_reddit_posts(
"AAPL", subreddits=("stocks",),
@@ -198,7 +198,7 @@ def test_reddit_standard_week_window_empty_is_a_real_absence(monkeypatch):
# The graph's window is [trade_date - 7, trade_date]; the week-long search
# covers it, so an empty result is genuine silence.
from datetime import timedelta
today = datetime.now(timezone.utc).date()
today = datetime.now(UTC).date()
monkeypatch.setattr(reddit, "_fetch_subreddit_rss", lambda *a, **k: [])
out = reddit.fetch_reddit_posts(
"AAPL", subreddits=("stocks",),
@@ -212,7 +212,7 @@ def test_reddit_full_page_does_not_vouch_for_older_days(monkeypatch):
# 100 posts from today say nothing about five days ago: the page may have
# cut older matches off, so the window stays unavailable.
from datetime import timedelta
today = datetime.now(timezone.utc).date()
today = datetime.now(UTC).date()
ts = _epoch(str(today))
page = [{"title": f"T{i}", "created_utc": ts, "subreddit": "stocks"} for i in range(reddit._FEED_PAGE)]
monkeypatch.setattr(reddit, "_fetch_subreddit_rss", lambda *a, **k: page)
+78
View File
@@ -0,0 +1,78 @@
"""A historical run is served statements only with a known filing time.
SEC EDGAR dates every filing, so it serves a past date as filed. Yahoo and Alpha
Vantage date a statement by the period it covers, which a company publishes weeks
later, so a past run is told they are withheld rather than served figures that may
not yet have been public.
"""
import copy
from unittest import mock
import pytest
from tradingagents import default_config
from tradingagents.dataflows import router
from tradingagents.dataflows.config import set_config
from tradingagents.dataflows.vendors.alpha_vantage import fundamentals as alpha_vantage
from tradingagents.dataflows.vendors.yahoo import fundamentals as yahoo
PAST = "2024-03-14"
@pytest.mark.unit
@pytest.mark.parametrize("statement", [yahoo.get_balance_sheet, yahoo.get_cashflow, yahoo.get_income_statement])
def test_yahoo_withholds_statements_from_a_past_run_without_asking(statement):
with mock.patch.object(yahoo, "yf_retry", side_effect=AssertionError("requested")):
out = statement("SAP.DE", "quarterly", PAST)
assert "withheld" in out and PAST in out and "filing date" in out
@pytest.mark.unit
@pytest.mark.parametrize("statement", [alpha_vantage.get_balance_sheet, alpha_vantage.get_cashflow,
alpha_vantage.get_income_statement])
def test_alpha_vantage_withholds_statements_from_a_past_run_without_asking(statement):
with mock.patch.object(alpha_vantage, "_make_api_request", side_effect=AssertionError("requested")):
out = statement("IBM", "quarterly", PAST)
assert "withheld" in out and PAST in out
@pytest.mark.unit
def test_a_current_run_is_still_served_yahoo_statements():
import pandas as pd
from tradingagents.dataflows.date_window import get_current_date
frame = pd.DataFrame({pd.Timestamp("2026-06-30"): [1.0]}, index=["Total Assets"])
with mock.patch.object(yahoo, "yf_retry", return_value=frame):
out = yahoo.get_balance_sheet("SAP.DE", "quarterly", get_current_date())
assert "Total Assets" in out and "withheld" not in out
@pytest.mark.unit
def test_statements_come_from_sec_edgar_first_by_default():
set_config(copy.deepcopy(default_config.DEFAULT_CONFIG))
served = []
chain = {name: (lambda *a, _n=name, **k: served.append(_n) or f"{_n} statements")
for name in router.VENDOR_METHODS["get_balance_sheet"]}
with mock.patch.dict(router.VENDOR_METHODS, {"get_balance_sheet": chain}):
router.route_to_vendor("get_balance_sheet", "AAPL", "quarterly", PAST)
assert served == ["sec_edgar"]
@pytest.mark.unit
def test_yahoo_withholds_insider_trades_from_a_past_run_without_asking():
"""A trade is dated when it happened; it became public with its Form 4, up to
two business days later, and Yahoo reports no filing date."""
with mock.patch.object(yahoo, "yf_retry", side_effect=AssertionError("requested")):
out = yahoo.get_insider_transactions("AAPL", PAST)
assert "withheld" in out and PAST in out
@pytest.mark.unit
def test_alpha_vantage_withholds_insider_trades_from_a_past_run_without_asking():
from tradingagents.dataflows.vendors.alpha_vantage import news as alpha_vantage_news
with mock.patch.object(alpha_vantage_news, "_make_api_request", side_effect=AssertionError("requested")):
out = alpha_vantage_news.get_insider_transactions("IBM", PAST)
assert "withheld" in out and PAST in out
+21 -1
View File
@@ -72,7 +72,7 @@ def test_research_manager_prompt_states_constraint():
"company_of_interest": "NVDA",
"investment_debate_state": {
"history": "h", "bull_history": "b", "bear_history": "r",
"current_response": "", "judge_decision": "", "count": 1,
"current_response": "", "count": 1,
},
})
assert NO_EXTERNAL_TOOLS in _prompt_text(captured["prompt"])
@@ -146,3 +146,23 @@ def test_constraint_text_is_unambiguous():
# No template braces: it is embedded in ChatPromptTemplate strings, where
# braces would be parsed as input variables.
assert "{" not in NO_EXTERNAL_TOOLS and "}" not in NO_EXTERNAL_TOOLS
@pytest.mark.unit
def test_the_sentiment_prompt_names_the_subreddits_searched(monkeypatch):
from tradingagents.agents.schemas import SentimentBand, SentimentReport
monkeypatch.setattr(sentiment, "fetch_stocktwits_messages", lambda *a, **k: "st")
monkeypatch.setattr(sentiment, "fetch_reddit_posts", lambda *a, **k: "rd")
monkeypatch.setattr(sentiment.get_news, "func", lambda *a, **k: "news", raising=False)
captured = {}
llm = _capturing_llm(captured, SentimentReport(
overall_band=SentimentBand.NEUTRAL, overall_score=5.0, confidence="low", narrative="n",
))
sentiment.create_sentiment_analyst(llm)({
"company_of_interest": "BTC-USD", "trade_date": "2026-01-15",
"asset_type": "crypto", "messages": [],
})
text = _prompt_text(captured["prompt"])
assert "r/Bitcoin, r/CryptoCurrency, r/CryptoMarkets" in text
assert "wallstreetbets" not in text
-1
View File
@@ -292,7 +292,6 @@ def _make_rm_state():
"bull_history": "Bull says...",
"bear_history": "Bear says...",
"current_response": "",
"judge_decision": "",
"count": 1,
},
}
+43 -2
View File
@@ -1,4 +1,4 @@
"""The suite runs the same on any machine: no test reaches the network."""
"""The suite runs the same on any machine: no test reaches the network or the user's files."""
import socket
@@ -9,9 +9,50 @@ import pytest
@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"])
lambda: socket.getaddrinfo("example.com", 443),
# yfinance's HTTP client is libcurl, which never touches Python's sockets.
lambda: __import__("curl_cffi.requests").requests.Session().get("http://192.0.2.1", timeout=1),
], ids=["connect", "connect_ex", "dns", "curl_cffi"])
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()
@pytest.mark.unit
def test_a_test_saves_cli_selections_to_its_own_directory(tmp_path):
"""The CLI remembers the last run's selections in the user's home; a test
that runs the selection flow would otherwise overwrite them."""
from cli import prefs
prefs.save_last_run({"analysts": ["market"]})
assert prefs._PREFS_PATH.is_relative_to(tmp_path)
assert prefs._PREFS_PATH.exists()
@pytest.mark.unit
def test_yfinance_keeps_its_cache_out_of_the_users_home():
"""yfinance caches each symbol's time zone on disk, in the home directory by default.
The suite's own temporary directory may itself sit under the home (``%TEMP%``
on Windows), so the check is that the cache is the suite's, not where it is.
"""
from pathlib import Path
from yfinance.cache import _TzDBManager
assert Path(_TzDBManager.get_location()).name.startswith("tradingagents-tests-yf-")
@pytest.mark.unit
@pytest.mark.parametrize("key", ["results_dir", "data_cache_dir", "memory_log_path"])
def test_the_suite_keeps_its_files_out_of_the_users_home(key):
"""A test that reads the user's cache sees what their runs fetched, and passes
or fails with it; one that writes there changes their data."""
from pathlib import Path
from tradingagents.default_config import DEFAULT_CONFIG
assert not Path(DEFAULT_CONFIG[key]).is_relative_to(Path.home() / ".tradingagents")
+12 -3
View File
@@ -10,7 +10,7 @@ import pandas as pd
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
from tradingagents.memory import settlement
def test_identity_lookup_normalizes_symbol(monkeypatch):
@@ -25,7 +25,7 @@ def test_identity_lookup_normalizes_symbol(monkeypatch):
return {"longName": "Gold Futures", "quoteType": "FUTURE"}
monkeypatch.setattr(yahoo_market.yf, "Ticker", FakeTicker)
au.resolve_instrument_identity.cache_clear()
au._identity.cache_clear()
identity = au.resolve_instrument_identity("XAUUSD")
@@ -54,7 +54,7 @@ def test_fetch_returns_normalizes_symbol(monkeypatch):
assert queried[0] == "GC=F" # stock symbol normalized (#984)
assert queried[1] == "SPY" # benchmark left as the canonical symbol
assert raw is not None and days is not None
assert resolved == "2025-01-07" # resolution date recorded (#1251)
assert resolved == "2025-01-08" # resolution date recorded (#1251)
def test_news_lookup_normalizes_symbol(monkeypatch):
@@ -67,11 +67,20 @@ def test_news_lookup_normalizes_symbol(monkeypatch):
def get_news(self, count):
return []
class FakeSearch:
def __init__(self, query, **k):
seen["searched"] = query
self.news = [{"title": "Gold", "publisher": "P", "link": "l",
"providerPublishTime": 1736150400, "relatedTickers": ["GC=F"]}]
self.quotes = [{"symbol": "GC=F"}]
monkeypatch.setattr(ynews.yf, "Ticker", FakeTicker)
monkeypatch.setattr(ynews.yf, "Search", FakeSearch)
monkeypatch.setattr(ynews, "yf_retry", lambda fn: fn())
out = ynews.get_news_yfinance("XAUUSD", "2025-01-01", "2025-01-10")
assert seen["symbol"] == "GC=F" # news queried with the canonical symbol
assert seen["searched"] == "GC=F"
assert "XAUUSD" in out # the user's ticker stays in the report
assert "GC=F" in out # provenance noted
+4 -8
View File
@@ -4,7 +4,6 @@ Temperature is a cross-provider knob: when set it must reach the underlying
chat client; when unset the provider keeps its own default.
"""
import importlib
import pytest
@@ -45,18 +44,15 @@ class TestTemperatureEnvOverlay:
def test_env_sets_temperature(self, monkeypatch):
import tradingagents.default_config as dc
monkeypatch.setenv("TRADINGAGENTS_TEMPERATURE", "0.2")
importlib.reload(dc)
config = dc.build_default_config()
# Stored on config (string from env is fine; consumed via float()).
assert dc.DEFAULT_CONFIG["temperature"] in ("0.2", 0.2)
assert float(dc.DEFAULT_CONFIG["temperature"]) == 0.2
monkeypatch.delenv("TRADINGAGENTS_TEMPERATURE", raising=False)
importlib.reload(dc)
assert config["temperature"] in ("0.2", 0.2)
assert float(config["temperature"]) == 0.2
def test_default_temperature_is_none(self, monkeypatch):
import tradingagents.default_config as dc
monkeypatch.delenv("TRADINGAGENTS_TEMPERATURE", raising=False)
importlib.reload(dc)
assert dc.DEFAULT_CONFIG["temperature"] is None
assert dc.build_default_config()["temperature"] is None
@pytest.mark.unit
+90
View File
@@ -0,0 +1,90 @@
"""Each model tier can name its own provider (#1440).
The quick tier (analysts, researchers, debaters, trader) and the deep tier
(research and portfolio managers) default to ``llm_provider``. A tier that names
another provider gets that provider's own settings and endpoint, never the main
provider's URL, and the run's settings and report say which provider each used.
"""
import pytest
from tradingagents import default_config
from tradingagents.llm_clients import factory
def _config(**overrides):
config = {**default_config.DEFAULT_CONFIG, "llm_provider": "openai", "backend_url": "https://api.openai.com/v1",
"quick_think_llm": "gpt-6-luna", "deep_think_llm": "gpt-6-sol",
"openai_reasoning_effort": "low", "google_thinking_level": "high"}
config.update(overrides)
return config
def _captured(monkeypatch):
made = []
monkeypatch.setattr(factory, "create_llm_client",
lambda provider, model, base_url=None, **kw: made.append((provider, model, base_url, kw)))
return made
@pytest.mark.unit
def test_a_tier_without_its_own_provider_uses_the_run_s(monkeypatch):
made = _captured(monkeypatch)
factory.create_tier_client(_config(), "deep")
provider, model, base_url, kw = made[0]
assert (provider, model, base_url) == ("openai", "gpt-6-sol", "https://api.openai.com/v1")
assert kw["reasoning_effort"] == "low"
@pytest.mark.unit
def test_a_tier_on_another_provider_gets_that_provider_s_settings_and_not_the_main_url(monkeypatch):
made = _captured(monkeypatch)
factory.create_tier_client(_config(deep_think_provider="google", deep_think_llm="gemini-3.8-flash"), "deep")
provider, model, base_url, kw = made[0]
assert (provider, model) == ("google", "gemini-3.8-flash")
assert base_url is None # the OpenAI URL must not follow it
assert kw["thinking_level"] == "high" and "reasoning_effort" not in kw
@pytest.mark.unit
def test_a_tier_url_is_used_for_that_tier_only(monkeypatch):
made = _captured(monkeypatch)
config = _config(quick_think_provider="openai_compatible", quick_think_backend_url="http://localhost:8000/v1",
quick_think_llm="local-model")
factory.create_tier_client(config, "quick")
factory.create_tier_client(config, "deep")
assert made[0][:3] == ("openai_compatible", "local-model", "http://localhost:8000/v1")
assert made[1][:3] == ("openai", "gpt-6-sol", "https://api.openai.com/v1")
@pytest.mark.unit
def test_the_run_settings_and_report_name_each_tier_s_provider():
from tradingagents.graph.trading_graph import TradingAgentsGraph
from tradingagents.reporting import _header
graph = object.__new__(TradingAgentsGraph)
graph.selected_analysts = ("market",)
graph.config = _config(deep_think_provider="anthropic", deep_think_llm="claude-opus-5-5")
settings = graph.run_settings()
assert settings["quick_think_provider"] == "openai" and settings["deep_think_provider"] == "anthropic"
header = _header("NVDA", {}, settings)
assert "deep anthropic claude-opus-5-5" in header and "quick openai gpt-6-luna" in header
@pytest.mark.unit
def test_the_tier_settings_are_read_from_the_environment(monkeypatch):
monkeypatch.setenv("TRADINGAGENTS_DEEP_THINK_PROVIDER", "anthropic")
monkeypatch.setenv("TRADINGAGENTS_QUICK_THINK_BACKEND_URL", "http://localhost:8000/v1")
config = default_config.build_default_config()
assert config["deep_think_provider"] == "anthropic"
assert config["quick_think_backend_url"] == "http://localhost:8000/v1"
assert config["quick_think_provider"] is None
+78 -7
View File
@@ -28,6 +28,7 @@ TRADE_DATE = "2026-08-14"
(None, TRADE_DATE), # omitted
("Sept 1", TRADE_DATE), # unparseable
("", TRADE_DATE),
("2026-8-1", "2026-08-01"), # unpadded: served in its canonical form
])
def test_as_of_takes_the_earlier_date(requested, expected):
assert as_of(requested, TRADE_DATE) == expected
@@ -36,6 +37,7 @@ def test_as_of_takes_the_earlier_date(requested, expected):
@pytest.mark.unit
def test_as_of_without_a_trade_date_passes_the_request_through():
assert as_of("2026-09-14", "") == "2026-09-14"
assert as_of("2026-9-14", "") == "2026-09-14"
@pytest.mark.unit
@@ -43,6 +45,7 @@ def test_as_of_without_a_trade_date_passes_the_request_through():
("2026-08-01", "2026-09-14", ("2026-08-01", TRADE_DATE)), # end clamped
("2026-08-01", "2026-08-10", ("2026-08-01", "2026-08-10")), # inside: unchanged
("2026-09-01", "2026-09-08", ("2026-08-07", TRADE_DATE)), # wholly later: span kept, moved back
("2026-8-1", "2026-8-10", ("2026-08-01", "2026-08-10")), # unpadded: canonical
])
def test_as_of_window(start, end, expected):
assert as_of_window(start, end, TRADE_DATE) == expected
@@ -68,8 +71,31 @@ def test_trade_date_is_hidden_from_the_model(tool):
assert "trade_date" not in tool.tool_call_schema.model_json_schema()["properties"]
INSTRUMENT_TOOLS = [
tools.get_stock_data, tools.get_indicators, tools.get_verified_market_snapshot,
tools.get_fundamentals, tools.get_balance_sheet, tools.get_cashflow,
tools.get_income_statement, tools.get_news, tools.get_insider_transactions,
]
@pytest.mark.unit
@pytest.mark.parametrize("tool", INSTRUMENT_TOOLS, ids=lambda t: t.name)
def test_the_instrument_is_hidden_from_the_model(tool):
"""The model once passed an indicator name as the symbol ("rsi", "atr" are
real tickers), and another company's data reached the report."""
properties = tool.tool_call_schema.model_json_schema()["properties"]
assert "symbol" not in properties and "ticker" not in properties
@pytest.mark.unit
def test_a_tool_serves_the_run_instrument_whatever_the_model_passes():
args = _run(tools.get_indicators, {"symbol": "RSI", "indicator": "rsi", "curr_date": TRADE_DATE}, tools)
assert args[1] == "NVDA"
class _State(MessagesState):
trade_date: str
company_of_interest: str
def _run(tool, args, module):
@@ -82,28 +108,45 @@ def _run(tool, args, module):
graph.compile().invoke({
"messages": [AIMessage("", tool_calls=[{"name": tool.name, "args": args, "id": "1"}])],
"trade_date": TRADE_DATE,
"company_of_interest": "NVDA",
})
return routed.call_args.args
@pytest.mark.unit
def test_statement_tool_with_omitted_date_uses_the_run_date():
args = _run(tools.get_balance_sheet, {"ticker": "AAPL"}, tools)
args = _run(tools.get_balance_sheet, {}, 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(tools.get_fundamentals,
{"ticker": "AAPL", "curr_date": "2026-09-14"}, tools)
assert args == ("get_fundamentals", "AAPL", TRADE_DATE)
args = _run(tools.get_fundamentals, {"curr_date": "2026-09-14"}, tools)
assert args == ("get_fundamentals", "NVDA", TRADE_DATE)
@pytest.mark.unit
def test_future_window_from_the_model_is_clamped():
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)
args = _run(tools.get_stock_data, {"start_date": "2026-08-01", "end_date": "2026-09-14"}, tools)
assert args == ("get_stock_data", "NVDA", "2026-08-01", TRADE_DATE)
@pytest.mark.unit
def test_an_unpadded_date_reaches_the_vendor_in_canonical_form():
# Vendors compare dates as YYYY-MM-DD text: "2026-07-23" > "2026-7-3" is False,
# so an unpadded date would let a filing made after it through.
args = _run(tools.get_income_statement, {"curr_date": "2026-7-3"}, tools)
assert args[-1] == "2026-07-03"
args = _run(tools.get_news, {"start_date": "2026-7-1", "end_date": "2026-7-3"}, tools)
assert args[-2:] == ("2026-07-01", "2026-07-03")
@pytest.mark.unit
@pytest.mark.parametrize("tool", [tools.get_balance_sheet, tools.get_cashflow, tools.get_income_statement])
def test_a_statement_frequency_is_one_the_vendors_serve(tool):
# Any other word was served annual figures under the word asked for.
schema = tool.tool_call_schema.model_json_schema()["properties"]["freq"]
assert schema["enum"] == ["annual", "quarterly"]
@pytest.mark.unit
@@ -113,6 +156,32 @@ def test_direct_call_without_state_is_unchanged():
assert routed.call_args.args == ("get_news", "AAPL", "2026-09-01", "2026-09-08")
@pytest.mark.unit
@pytest.mark.parametrize("tool", ["get_news", "get_stock_data"])
def test_a_start_date_that_is_not_a_date_is_sent_back_to_the_model(tool):
# A model can append a stray character to a date (#1476). No window can be
# guessed from it, so the vendor is not called and the model is told the form.
with mock.patch.object(tools, "route_to_vendor", return_value="ok") as routed:
out = getattr(tools, tool).func("NVDA", "2026-09-26\u0629", "2026-10-03", trade_date="2026-10-03")
assert not routed.called
assert "YYYY-MM-DD" in out and "start_date" in out
@pytest.mark.unit
def test_a_window_that_ends_before_it_starts_is_sent_back_to_the_model():
# A reversed window reached the vendor, which then reported no data for it.
with mock.patch.object(tools, "route_to_vendor", return_value="ok") as routed:
out = tools.get_stock_data.func("NVDA", "2026-08-12", "2026-08-01", trade_date=TRADE_DATE)
assert not routed.called
assert "start_date" in out and "end_date" in out
@pytest.mark.unit
def test_a_window_whose_start_is_not_a_date_is_refused():
with pytest.raises(ValueError, match="start_date"):
as_of_window("2026-09-26\u0629", "2026-10-03", "2026-10-03")
# --- the run date itself (#1319) -------------------------------------------------
@pytest.mark.unit
@@ -122,6 +191,8 @@ def test_propagate_rejects_a_non_canonical_date(bad):
with pytest.raises(ValueError, match="YYYY-MM-DD"):
object.__new__(TradingAgentsGraph).propagate("AAPL", bad)
with pytest.raises(ValueError, match="YYYY-MM-DD"): # the CLI starts a run here
object.__new__(TradingAgentsGraph).create_run_state("AAPL", bad)
@pytest.mark.unit
+36 -79
View File
@@ -7,15 +7,14 @@ only live odds, so a historical run withholds them.
from __future__ import annotations
import json
from unittest import mock
import pandas as pd
import pytest
from tradingagents.agents import tools
from tradingagents.dataflows.date_window import get_current_date
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,
@@ -36,48 +35,23 @@ def _yf_insider(frame, curr_date):
return yahoo_fundamentals.get_insider_transactions("AAPL", curr_date)
@pytest.mark.unit
def test_yfinance_insider_filings_after_the_date_are_dropped():
out = _yf_insider(_insider_frame("2026-09-08", "2025-06-02", "2025-05-30", "2025-01-10"), "2025-06-01")
assert "2026-09-08" not in out and "2025-06-02" not in out
assert "2025-05-30" in out and "2025-01-10" in out
@pytest.mark.unit
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" not in out # a transaction after the run date
@pytest.mark.unit
def test_yfinance_insider_without_a_date_is_unfiltered():
out = _yf_insider(_insider_frame("2026-09-08", "2025-01-10"), None)
assert "2026-09-08" in out and "2025-01-10" in out
@pytest.mark.unit
def test_alpha_vantage_insider_filings_after_the_date_are_dropped():
body = json.dumps({"data": [
{"transaction_date": "2026-09-08", "executive": "A"},
{"transaction_date": "2025-05-30", "executive": "B"},
]})
with mock.patch.object(alpha_vantage_news, "_make_api_request", return_value=body):
out = json.loads(alpha_vantage_news.get_insider_transactions("AAPL", "2025-06-01"))
assert [t["executive"] for t in out["data"]] == ["B"]
@pytest.mark.unit
def test_polymarket_withholds_live_odds_from_a_historical_run():
with mock.patch.object(polymarket, "_request", side_effect=AssertionError("must not fetch")):
out = polymarket.get_prediction_markets("Fed rate cut", curr_date="2025-06-01")
out = polymarket.get_prediction_markets("Fed rate cut", as_of_date="2025-06-01")
assert "withheld" in out
@pytest.mark.unit
def test_polymarket_serves_a_current_run():
with mock.patch.object(polymarket, "_request", return_value={"events": []}) as req:
polymarket.get_prediction_markets("Fed rate cut", curr_date=polymarket.get_current_date())
polymarket.get_prediction_markets("Fed rate cut", as_of_date=get_current_date())
req.assert_called_once()
@@ -93,19 +67,20 @@ def test_trade_date_is_injected_not_model_visible(tool):
# --- the instrument's identity -------------------------------------------------
@pytest.mark.unit
def test_a_historical_run_is_told_the_identity_is_current(monkeypatch):
"""The company name, sector and industry come from today's vendor profile.
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."""
def test_a_historical_run_gets_the_current_name_only_as_an_identifier(monkeypatch):
"""The profile is today's. The name still tells the company apart from others
(#814), so a past run keeps it, marked as today's; a sector, industry or
exchange that may not have held on the run's date is not given."""
from tradingagents.agents.context import build_instrument_context
identity = {"company_name": "Example Corp", "sector": "Technology",
"industry": "Software", "exchange": "NMS"}
historical = build_instrument_context("EXMP", "stock", identity, curr_date="2024-03-14")
assert "Example Corp" in historical
assert "2024-03-14" in historical and "today" in historical.lower()
historical = build_instrument_context("EXMP", "stock", identity, trade_date="2024-03-14")
assert "Example Corp" in historical and "current name" in historical
assert "2024-03-14" in historical
for later in ("Technology", "Software", "NMS"):
assert later not in historical
@pytest.mark.unit
@@ -114,30 +89,9 @@ def test_a_current_run_is_not_cluttered_with_a_vintage_note(monkeypatch):
from tradingagents.dataflows.date_window import get_current_date
today = build_instrument_context("EXMP", "stock", {"company_name": "Example Corp"},
curr_date=get_current_date())
trade_date=get_current_date())
assert "Example Corp" in today
assert "resolved today" not in today.lower()
@pytest.mark.unit
def test_insider_rows_are_dated_by_the_trade_not_the_filing():
"""yfinance reports the transaction date and carries no filing date. A trade
becomes public when the Form 4 is filed, up to two business days later, so a
run must not be told these rows were public on their transaction date."""
import pandas as pd
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(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
assert "filed" in out.lower() # and that filing comes later
assert "current name" not in today
@pytest.mark.unit
@@ -158,10 +112,11 @@ def test_an_indicator_that_could_not_be_read_is_not_shown_as_a_blank_value():
# A past date withholds the live profile before any request, so the
# fundamentals case is exercised on the date it does fetch.
("get_fundamentals", ("AAPL", None)),
("get_balance_sheet", ("AAPL", "annual", "2026-09-01")),
("get_cashflow", ("AAPL", "annual", "2026-09-01")),
("get_income_statement", ("AAPL", "annual", "2026-09-01")),
("get_insider_transactions", ("AAPL", "2026-09-01")),
# Statements are requested only for a run dated today; a past one withholds them.
("get_balance_sheet", ("AAPL", "annual", get_current_date())),
("get_cashflow", ("AAPL", "annual", get_current_date())),
("get_income_statement", ("AAPL", "annual", get_current_date())),
("get_insider_transactions", ("AAPL", get_current_date())),
])
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
@@ -196,19 +151,19 @@ 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.errors import NoMarketDataError, VendorRateLimitError
from tradingagents.dataflows.vendors.yahoo import ohlcv
from tradingagents.dataflows.errors import NoMarketDataError, VendorUnavailableError
from tradingagents.dataflows.vendors.yahoo import common
empty = mock.Mock(quarterly_balance_sheet=pd.DataFrame(), balance_sheet=pd.DataFrame())
monkeypatch.setattr(yahoo_market.yf, "Ticker", lambda s: empty)
monkeypatch.setattr(ohlcv, "vendor_reachable", lambda url: False)
with pytest.raises(VendorRateLimitError, match="unreachable"):
yahoo_fundamentals.get_balance_sheet("AAPL", "annual", "2026-09-01")
monkeypatch.setattr(common, "vendor_reachable", lambda url: False)
with pytest.raises(VendorUnavailableError, match="unreachable"):
yahoo_fundamentals.get_balance_sheet("AAPL", "annual", get_current_date())
monkeypatch.setattr(ohlcv, "vendor_reachable", lambda url: True)
monkeypatch.setattr(common, "vendor_reachable", lambda url: True)
with pytest.raises(NoMarketDataError):
yahoo_fundamentals.get_balance_sheet("AAPL", "annual", "2026-09-01")
yahoo_fundamentals.get_balance_sheet("AAPL", "annual", get_current_date())
@pytest.mark.unit
@@ -216,11 +171,13 @@ 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 router
from tradingagents.dataflows.errors import VendorRateLimitError
from tradingagents.dataflows.config import set_config
from tradingagents.dataflows.errors import VendorUnavailableError
def _down(*a, **k):
raise VendorRateLimitError("Yahoo Finance is unreachable")
raise VendorUnavailableError("Yahoo Finance is unreachable")
set_config({"data_vendors": {"fundamental_data": "yfinance"}})
monkeypatch.setitem(router.VENDOR_METHODS["get_balance_sheet"], "yfinance", _down)
out = router.route_to_vendor("get_balance_sheet", "AAPL", "annual", "2026-09-01")
@@ -235,16 +192,16 @@ def test_the_price_path_also_tells_an_outage_from_an_unknown_symbol(monkeypatch)
delisted symbol either."""
import pandas as pd
from tradingagents.dataflows.errors import NoMarketDataError, VendorRateLimitError
from tradingagents.dataflows.vendors.yahoo import ohlcv
from tradingagents.dataflows.errors import NoMarketDataError, VendorUnavailableError
from tradingagents.dataflows.vendors.yahoo import common
monkeypatch.setattr(yahoo_market.yf, "Ticker", lambda s: mock.Mock(history=lambda **k: pd.DataFrame()))
monkeypatch.setattr(ohlcv, "vendor_reachable", lambda url: False)
with pytest.raises(VendorRateLimitError, match="unreachable"):
monkeypatch.setattr(common, "vendor_reachable", lambda url: False)
with pytest.raises(VendorUnavailableError, match="unreachable"):
yahoo_market.get_YFin_data_online("AAPL", "2026-09-01", "2026-09-10")
monkeypatch.setattr(ohlcv, "vendor_reachable", lambda url: True)
monkeypatch.setattr(common, "vendor_reachable", lambda url: True)
with pytest.raises(NoMarketDataError):
yahoo_market.get_YFin_data_online("AAPL", "2026-09-01", "2026-09-10")
@@ -297,7 +254,7 @@ def test_an_unavailable_notice_names_no_date_after_the_run():
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"),
build_instrument_context("EXMP", "stock", {"company_name": "Example"}, trade_date="2025-01-07"),
]
for notice in notices:
assert _dates_after(notice, "2025-01-07") == [], notice
+23 -3
View File
@@ -16,7 +16,7 @@ from tradingagents.dataflows.errors import (
NoMarketDataError,
VendorError,
VendorNotConfiguredError,
VendorRateLimitError,
VendorUnavailableError,
)
from tradingagents.dataflows.vendors.alpha_vantage.common import (
AlphaVantageNotConfiguredError,
@@ -28,7 +28,7 @@ from tradingagents.dataflows.vendors.fred import FredNotConfiguredError
@pytest.mark.unit
class HierarchyTests(unittest.TestCase):
def test_all_conditions_derive_from_vendor_error(self):
for cls in (NoMarketDataError, VendorRateLimitError, VendorNotConfiguredError):
for cls in (NoMarketDataError, VendorUnavailableError, VendorNotConfiguredError):
self.assertTrue(issubclass(cls, VendorError))
def test_not_configured_is_still_a_value_error(self):
@@ -36,7 +36,7 @@ class HierarchyTests(unittest.TestCase):
self.assertTrue(issubclass(VendorNotConfiguredError, ValueError))
def test_vendor_named_errors_subclass_the_generic_bases(self):
self.assertTrue(issubclass(AlphaVantageRateLimitError, VendorRateLimitError))
self.assertTrue(issubclass(AlphaVantageRateLimitError, VendorUnavailableError))
self.assertTrue(issubclass(AlphaVantageNotConfiguredError, VendorNotConfiguredError))
self.assertTrue(issubclass(FredNotConfiguredError, VendorNotConfiguredError))
# ... and therefore still ValueErrors
@@ -94,6 +94,26 @@ class RouterHandlesBaseTypesTests(unittest.TestCase):
), self.assertRaises(AlphaVantageNotConfiguredError):
router.route_to_vendor("get_stock_data", "AAPL", "2026-01-01", "2026-01-10")
def test_an_unavailable_vendor_keeps_absence_from_being_claimed(self):
# The throttled vendor's coverage was never learned, so "no usable data
# from any configured vendor" would be a claim nobody checked.
def throttled(*a, **k):
raise VendorUnavailableError("Yahoo HTTP 429")
def timed_out(*a, **k):
raise TimeoutError("read timed out") # a vendor that does not type its failures
def not_covered(*a, **k):
raise NoMarketDataError("AAPL", "AAPL", "not covered")
for chain in ({"yfinance": throttled, "alpha_vantage": not_covered},
{"yfinance": not_covered, "alpha_vantage": throttled},
{"alpha_vantage": timed_out, "yfinance": not_covered}):
set_config({"data_vendors": {"core_stock_apis": ",".join(chain)}})
with mock.patch.dict(router.VENDOR_METHODS, {"get_stock_data": chain}, clear=False):
out = router.route_to_vendor("get_stock_data", "AAPL", "2026-01-01", "2026-01-10")
self.assertTrue(out.startswith("DATA_UNAVAILABLE"), out)
if __name__ == "__main__":
unittest.main()
+4 -3
View File
@@ -72,13 +72,14 @@ class VendorRoutingTests(unittest.TestCase):
self.assertEqual(result, "AV_DATA")
def test_primary_error_is_logged_not_masked(self):
# #989: primary errors + fallback no-data -> NO_DATA, but the failure
# must be visible in logs (broken primary not hidden).
# #989: a broken primary is not hidden behind a fallback's verdict. It
# never said whether it has the symbol, so the answer is unavailable,
# and the failure is in the logs.
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.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)
self.assertTrue(result.startswith("DATA_UNAVAILABLE"), result)
joined = "\n".join(cm.output)
self.assertIn("boom", joined) # the real error surfaced in logs
self.assertIn("yfinance", joined)
+18
View File
@@ -0,0 +1,18 @@
"""The package version has one source, tradingagents.__version__, which the build reads."""
import re
from pathlib import Path
import pytest
import tradingagents
PYPROJECT = (Path(__file__).resolve().parents[1] / "pyproject.toml").read_text(encoding="utf-8")
@pytest.mark.unit
def test_the_build_reads_the_version_from_the_package():
assert re.search(r'^dynamic = \["version"\]', PYPROJECT, re.M)
assert 'version = {attr = "tradingagents.__version__"}' in PYPROJECT
assert not re.search(r'^version = "', PYPROJECT, re.M)
assert re.fullmatch(r"\d+\.\d+\.\d+(\.dev\d+|rc\d+)?", tradingagents.__version__)
+286
View File
@@ -0,0 +1,286 @@
"""A Yahoo rate limit is retried, then reported as a rate limit.
When the limit outlasts the retries, the agent must hear that the vendor is
throttled. "The symbol may be invalid or delisted" is a claim about the company
that nobody checked, and an exception out of a tool ends the run.
"""
import pandas as pd
import pytest
import yfinance as yf
from yfinance.data import YfData
from yfinance.exceptions import YFRateLimitError
from tradingagents.agents.tools import (
get_global_news,
get_indicators,
get_insider_transactions,
get_news,
get_stock_data,
get_verified_market_snapshot,
)
from tradingagents.dataflows import router
from tradingagents.dataflows.config import set_config
from tradingagents.dataflows.date_window import get_current_date
from tradingagents.dataflows.errors import VendorUnavailableError
from tradingagents.dataflows.vendors.yahoo import common, fundamentals, ohlcv
DAY = "2026-09-18"
def _rate_limited(*args, **kwargs):
raise YFRateLimitError()
@pytest.fixture
def yahoo(monkeypatch, tmp_path):
set_config({"data_cache_dir": str(tmp_path)})
monkeypatch.setattr(common.time, "sleep", lambda seconds: None)
for module in (common, fundamentals):
monkeypatch.setattr(module, "vendor_reachable", lambda url: True)
return monkeypatch
@pytest.mark.unit
@pytest.mark.parametrize("tool, args", [
pytest.param(get_stock_data, ("AAPL", "2026-09-10", DAY), id="stock_data"),
pytest.param(get_indicators, ("AAPL", "rsi", DAY, 5), id="indicators"),
pytest.param(get_verified_market_snapshot, ("AAPL", DAY), id="snapshot"),
pytest.param(get_news, ("AAPL", "2026-09-10", DAY), id="news"),
pytest.param(get_global_news, (DAY, 7, 5), id="global_news"),
pytest.param(get_insider_transactions, ("AAPL",), id="insider"),
])
def test_a_rate_limit_that_outlasts_the_retries_is_reported_as_one(yahoo, tool, args):
for name in ("history", "get_news"):
yahoo.setattr(yf.Ticker, name, _rate_limited)
yahoo.setattr(yf.Ticker, "insider_transactions", property(_rate_limited))
yahoo.setattr(yf, "Search", _rate_limited)
# Dated today: a past run is not served insider trades at all.
out = tool.func(*args, trade_date=get_current_date())
assert out.startswith("DATA_UNAVAILABLE"), out
assert "delisted" not in out
@pytest.mark.unit
def test_the_indicator_path_retries_a_rate_limit(yahoo):
"""The prices behind every indicator were fetched with ``yf.download``, which
returns an empty frame for a 429, so they were never retried."""
bar = pd.DataFrame({"Open": [1.0], "High": [1.0], "Low": [1.0], "Close": [1.0],
"Volume": [100]}, index=pd.DatetimeIndex([DAY], name="Date"))
answers = [YFRateLimitError(), bar]
def history(self, **kwargs):
answer = answers.pop(0)
if isinstance(answer, Exception):
raise answer
return answer
yahoo.setattr(yf.Ticker, "history", history)
assert ohlcv.load_ohlcv("AAPL", DAY)["Close"].tolist() == [1.0]
@pytest.mark.unit
def test_yfinance_raises_the_rate_limit_from_history(yahoo):
yahoo.setattr(YfData, "_make_request", _rate_limited)
with pytest.raises(VendorUnavailableError, match="rate limited"):
ohlcv.load_ohlcv("AAPL", DAY)
@pytest.mark.unit
def test_fundamentals_ask_a_new_ticker_after_a_rate_limit(yahoo):
"""A Ticker keeps a failed ``info`` fetch as done, so asking the same one
again reads an empty profile, which looks like a symbol with no data."""
class Ticker:
def __init__(self, symbol):
self.fetched = False
@property
def info(self):
if self.fetched:
return {}
self.fetched = True
raise YFRateLimitError()
yahoo.setattr(yf, "Ticker", Ticker)
out = router.route_to_vendor("get_fundamentals", "AAPL", None)
assert out.startswith("DATA_UNAVAILABLE"), out
@pytest.mark.unit
def test_a_price_request_that_raises_is_unavailable_whether_or_not_yahoo_answers(yahoo):
"""An unknown symbol comes back from ``Ticker.history`` as an empty frame, so
a request that raised failed in transit, and says nothing about the symbol."""
def refused(self, **kwargs):
raise ConnectionError("curl: (7) Failed to connect to query2.finance.yahoo.com")
yahoo.setattr(yf.Ticker, "history", refused)
for reachable in (False, True):
yahoo.setattr(common, "vendor_reachable", lambda url, _r=reachable: _r)
with pytest.raises(VendorUnavailableError, match="request failed"):
ohlcv.load_ohlcv("AAPL", DAY)
@pytest.mark.unit
def test_a_price_request_that_fails_is_unavailable_even_when_yahoo_answers(monkeypatch, tmp_path):
"""A timeout says nothing about the symbol; a reachable host does not make it one."""
def timed_out(**kwargs):
raise TimeoutError("read timed out")
monkeypatch.setattr(ohlcv, "get_config", lambda: {"data_cache_dir": str(tmp_path)})
monkeypatch.setattr(ohlcv.yf, "Ticker", lambda s: type("T", (), {"history": lambda self, **k: timed_out(**k)})())
monkeypatch.setattr(common, "vendor_reachable", lambda url: True)
with pytest.raises(VendorUnavailableError):
ohlcv.load_ohlcv("NVDA", "2026-09-23")
class _Unreachable:
"""A Ticker whose every request fails in transit."""
def __init__(self, *args, **kwargs):
pass
def __getattr__(self, name):
raise TimeoutError("read timed out")
def _yahoo_calls():
from tradingagents.dataflows.date_window import get_current_date
from tradingagents.dataflows.vendors.yahoo import market, news
today = get_current_date()
return [
pytest.param(lambda: fundamentals.get_fundamentals("AAPL", today), id="fundamentals"),
pytest.param(lambda: fundamentals.get_balance_sheet("AAPL", "quarterly", today), id="statement"),
pytest.param(lambda: fundamentals.get_insider_transactions("AAPL", today), id="insider"),
pytest.param(lambda: fundamentals.get_company_profile("AAPL"), id="profile"),
pytest.param(lambda: news.get_news_yfinance("AAPL", "2026-09-10", DAY), id="news"),
pytest.param(lambda: news.get_global_news_yfinance(DAY, 7, 5), id="global_news"),
pytest.param(lambda: market.get_YFin_data_online("AAPL", "2026-09-10", DAY), id="stock_data"),
pytest.param(lambda: market.get_closes("AAPL", "2026-09-10", DAY), id="closes"),
]
@pytest.mark.unit
@pytest.mark.parametrize("call", _yahoo_calls())
def test_a_yahoo_request_that_fails_is_unavailable_not_absent(yahoo, call):
"""An unknown symbol comes back empty, so a request that raised failed in transit."""
yahoo.setattr(yf, "Ticker", _Unreachable)
yahoo.setattr(yf, "Search", _Unreachable)
with pytest.raises(VendorUnavailableError):
call()
@pytest.mark.unit
@pytest.mark.parametrize("frame", [
pytest.param(pd.DataFrame(), id="unknown_symbol"),
pytest.param(pd.DataFrame({"Date": pd.to_datetime(["2026-09-25"]), "Open": [1.0], "High": [1.0],
"Low": [1.0], "Close": [1.0], "Volume": [1]}), id="no_row_by_the_date"),
])
def test_a_snapshot_with_no_rows_is_reported_not_raised(yahoo, frame):
"""An exception out of a tool ends the run; no rows is an answer about the symbol."""
from tradingagents.dataflows.errors import NoMarketDataError
from tradingagents.dataflows.vendors.yahoo import snapshot
def load(symbol, as_of_date, **kwargs):
if frame.empty:
raise NoMarketDataError(symbol, symbol, "no price rows")
return frame
yahoo.setattr(snapshot, "load_ohlcv", load)
out = get_verified_market_snapshot.func("ZZZZ", DAY, trade_date=DAY)
assert out.startswith("NO_DATA_AVAILABLE"), out
def _yahoo_request_raises(yahoo, exc):
"""Every request yfinance makes raises ``exc``, below its own error handling."""
from yfinance.data import YfData
def request(self, *args, **kwargs):
raise exc
yahoo.setattr(YfData, "_make_request", request)
@pytest.mark.unit
@pytest.mark.parametrize("call", _yahoo_calls())
def test_a_request_that_yfinance_would_swallow_is_unavailable(yahoo, call):
"""yfinance answers some failed requests with an empty result; an empty
statement from a Yahoo whose host answers a probe read as "no data"."""
_yahoo_request_raises(yahoo, TimeoutError("read timed out"))
with pytest.raises(VendorUnavailableError):
call()
@pytest.mark.unit
@pytest.mark.parametrize("call", [c for c in _yahoo_calls() if c.id in ("fundamentals", "stock_data", "insider")])
def test_yahoo_answering_not_found_is_no_data(yahoo, call):
"""Yahoo answers an unknown symbol with HTTP 404: an answer about the symbol, not an outage."""
from curl_cffi.requests import Response
from curl_cffi.requests.exceptions import HTTPError
from tradingagents.dataflows.errors import NoMarketDataError
not_found = Response()
not_found.status_code = 404
_yahoo_request_raises(yahoo, HTTPError("HTTP Error 404: ", response=not_found))
try:
out = call()
except NoMarketDataError:
return
assert out.startswith("No insider transactions"), out # an empty filing list is not an error
@pytest.mark.unit
@pytest.mark.parametrize("debug, reason, absent", [
pytest.param(" (1d 2026-09-26 -> 2026-09-27)", None, True, id="a_chart_with_no_prices"),
pytest.param(" (1d 1970-01-01 -> 1970-02-01)", "Data doesn't exist for startDate = 18000, endDate = 2696400",
True, id="yahoo_says_the_data_does_not_exist"),
pytest.param(" (1d 2026-09-21 -> 2026-09-25)(Yahoo status_code = 503)", None, False, id="an_http_error"),
pytest.param(" (1d 2026-09-21 -> 2026-09-25)", "Service temporarily unavailable", False,
id="yahoo_reports_a_service_failure"),
])
def test_only_yahoo_saying_a_window_has_no_prices_is_no_data(yahoo, debug, reason, absent):
"""yfinance raises YFPricesMissingError both when Yahoo answered with no prices
and when its answer was an error; only the first is a fact about the symbol."""
from yfinance.exceptions import YFPricesMissingError
from tradingagents.dataflows.errors import NoMarketDataError
from tradingagents.dataflows.vendors.yahoo import market
def no_prices(self, **kwargs):
raise YFPricesMissingError("AAPL", debug, yahoo_reason=reason)
yahoo.setattr(yf.Ticker, "history", no_prices)
with pytest.raises(NoMarketDataError if absent else VendorUnavailableError):
market.get_YFin_data_online("AAPL", "2026-09-21", "2026-09-25")
@pytest.mark.unit
def test_a_missing_time_zone_is_not_taken_for_an_answer(yahoo):
"""yfinance reports a failed time-zone lookup the same way as a symbol without one."""
from yfinance.exceptions import YFTzMissingError
from tradingagents.dataflows.vendors.yahoo import market
def no_tz(self, **kwargs):
raise YFTzMissingError("AAPL")
yahoo.setattr(yf.Ticker, "history", no_tz)
with pytest.raises(VendorUnavailableError):
market.get_YFin_data_online("AAPL", "2026-09-21", "2026-09-25")
+47 -2
View File
@@ -6,6 +6,7 @@ import pandas as pd
import pytest
import tradingagents.dataflows.vendors.yahoo.snapshot as validator
from tradingagents.dataflows.errors import NoMarketDataError
def _sample_ohlcv() -> pd.DataFrame:
@@ -47,12 +48,12 @@ class TestVerifiedSnapshot:
def test_raises_when_no_rows_on_or_before_date(self, monkeypatch):
monkeypatch.setattr(validator, "load_ohlcv", lambda s, d, fill_gaps=True: _sample_ohlcv())
with pytest.raises(ValueError):
with pytest.raises(NoMarketDataError):
validator.build_verified_market_snapshot("COF", "2020-01-01")
def test_raises_on_empty_data(self, monkeypatch):
monkeypatch.setattr(validator, "load_ohlcv", lambda s, d, fill_gaps=True: pd.DataFrame())
with pytest.raises(ValueError):
with pytest.raises(NoMarketDataError):
validator.build_verified_market_snapshot("COF", "2026-05-13")
def test_look_back_window_capped_at_30(self, monkeypatch):
@@ -72,3 +73,47 @@ class TestTool:
{"symbol": "COF", "curr_date": "2026-05-20"}
)
assert "Verified market data snapshot for COF" in out
@pytest.mark.unit
class TestPricesKeepTheirDigits:
"""A price prints with its significant digits: a sub-cent coin is not 0.00, a rate keeps its pips."""
@pytest.mark.parametrize("value, text", [
(0.00000503123456, "0.00000503123"),
(1.123456, "1.12346"),
(763.960022, "763.96"),
(81074.1875, "81074.19"),
(100.0, "100.00"),
(-0.0012345678, "-0.00123457"),
(0.0, "0.00"),
])
def test_price_text(self, value, text):
from tradingagents.dataflows.vendors.yahoo.common import price_text
assert price_text(value) == text
def test_the_snapshot_shows_a_sub_cent_close(self, monkeypatch):
data = _sample_ohlcv()
for col in ("Open", "High", "Low", "Close"):
data[col] = data[col] * 0.0000001
monkeypatch.setattr(validator, "load_ohlcv", lambda s, d, fill_gaps=True: data)
text = validator.build_verified_market_snapshot("SHIB-USD", "2026-05-20")
assert "| Close | 0.0000135 |" in text and "| Close | 0.00 |" not in text
def test_the_price_table_shows_a_sub_cent_close(self, monkeypatch):
from tradingagents.dataflows.vendors.yahoo import market
days = pd.bdate_range("2026-05-11", "2026-05-15")
frame = pd.DataFrame({"Open": 0.00000501, "High": 0.00000512, "Low": 0.00000499,
"Close": 0.00000503, "Volume": 10**9}, index=days)
class _Ticker:
def __init__(self, symbol):
pass
def history(self, **kwargs):
return frame
monkeypatch.setattr(market.yf, "Ticker", _Ticker)
text = market.get_YFin_data_online("SHIB-USD", "2026-05-11", "2026-05-15")
assert "0.00000503" in text and ",0.0," not in text
+4
View File
@@ -1,3 +1,7 @@
"""TradingAgents: multi-agent LLM financial trading framework."""
__version__ = "0.7.1"
from dotenv import find_dotenv, load_dotenv
# Load .env at package import so DEFAULT_CONFIG's env-var overlay and every LLM
-2
View File
@@ -2,7 +2,6 @@ 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
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
@@ -15,7 +14,6 @@ from .trader.trader import create_trader
__all__ = [
"AgentState",
"create_msg_delete",
"InvestDebateState",
"RiskDebateState",
"create_bear_researcher",
@@ -1,5 +1,6 @@
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from tradingagents.agents.analysts.turn import take_turn
from tradingagents.agents.context import get_instrument_context_from_state, get_language_instruction
from tradingagents.agents.tools import (
get_balance_sheet,
@@ -53,14 +54,7 @@ def create_fundamentals_analyst(llm):
prompt = prompt.partial(current_date=current_date)
prompt = prompt.partial(instrument_context=instrument_context)
chain = prompt | llm.bind_tools(TOOLS)
result = chain.invoke(state["messages"])
report = ""
if len(result.tool_calls) == 0:
report = result.content
result, report = take_turn(prompt, llm, TOOLS, state["messages"])
return {
"messages": [result],
@@ -1,5 +1,6 @@
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from tradingagents.agents.analysts.turn import take_turn
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
@@ -73,14 +74,7 @@ Write a very detailed and nuanced report of the trends you observe. Provide spec
prompt = prompt.partial(current_date=current_date)
prompt = prompt.partial(instrument_context=instrument_context)
chain = prompt | llm.bind_tools(TOOLS)
result = chain.invoke(state["messages"])
report = ""
if len(result.tool_calls) == 0:
report = result.content
result, report = take_turn(prompt, llm, TOOLS, state["messages"])
return {
"messages": [result],
@@ -1,5 +1,6 @@
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from tradingagents.agents.analysts.turn import take_turn
from tradingagents.agents.context import get_instrument_context_from_state, get_language_instruction
from tradingagents.agents.tools import (
get_global_news,
@@ -25,7 +26,7 @@ def create_news_analyst(llm):
instrument_context = get_instrument_context_from_state(state)
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."
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(start_date, end_date) for news about the {asset_label} under analysis, 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."""
+ get_language_instruction()
)
@@ -52,13 +53,7 @@ def create_news_analyst(llm):
prompt = prompt.partial(current_date=current_date)
prompt = prompt.partial(instrument_context=instrument_context)
chain = prompt | llm.bind_tools(TOOLS)
result = chain.invoke(state["messages"])
report = ""
if len(result.tool_calls) == 0:
report = result.content
result, report = take_turn(prompt, llm, TOOLS, state["messages"])
return {
"messages": [result],
@@ -5,7 +5,7 @@ prompt, so the model reports on data it was given rather than inventing posts:
1. News headlines: Yahoo Finance
2. StockTwits messages: the cashtag stream, with Bullish/Bearish tags
3. Reddit posts: r/wallstreetbets, r/stocks, r/investing
3. Reddit posts: r/wallstreetbets, r/stocks, r/investing, or crypto communities for a crypto pair
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
@@ -31,7 +31,12 @@ from tradingagents.agents.structured import (
invoke_structured_or_freetext,
)
from tradingagents.agents.tools import get_news
from tradingagents.dataflows.vendors.reddit import fetch_reddit_posts
from tradingagents.dataflows.vendors.reddit import (
CRYPTO_SUBREDDITS,
DEFAULT_SUBREDDITS,
fetch_reddit_posts,
subreddits_for,
)
from tradingagents.dataflows.vendors.stocktwits import fetch_stocktwits_messages
@@ -65,7 +70,10 @@ def create_sentiment_analyst(llm):
stocktwits_block = fetch_stocktwits_messages(
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, screen=screen)
subreddits = subreddits_for(ticker)
reddit_block = fetch_reddit_posts(
ticker, subreddits, start_date=start_date, end_date=end_date, screen=screen
)
system_message = _build_system_message(
ticker=ticker,
@@ -74,6 +82,7 @@ def create_sentiment_analyst(llm):
news_block=news_block,
stocktwits_block=stocktwits_block,
reddit_block=reddit_block,
subreddits=subreddits,
)
prompt = ChatPromptTemplate.from_messages(
@@ -126,8 +135,15 @@ def _build_system_message(
news_block: str,
stocktwits_block: str,
reddit_block: str,
subreddits: tuple[str, ...] = DEFAULT_SUBREDDITS,
) -> str:
"""Assemble the sentiment-analyst system message with structured data blocks."""
if subreddits == DEFAULT_SUBREDDITS:
character = "r/wallstreetbets is often contrarian/exuberant; r/stocks more measured; r/investing longer-term"
elif len(subreddits) > len(CRYPTO_SUBREDDITS):
character = f"r/{subreddits[0]} leans toward the coin's holders; r/CryptoCurrency and r/CryptoMarkets are broader"
else:
character = "r/CryptoCurrency and r/CryptoMarkets are broad crypto communities"
return f"""You are a financial market sentiment analyst. Your task is to produce a comprehensive sentiment report for {ticker} covering the period from {start_date} to {end_date}, drawing on three complementary data sources that have already been collected for you.
## Data sources (pre-fetched, in this prompt)
@@ -146,8 +162,8 @@ Fast-moving signal. Each message carries a user-labeled sentiment tag (Bullish /
{stocktwits_block}
<end_of_stocktwits>
### Reddit posts — r/wallstreetbets, r/stocks, r/investing (past 7 days)
Community discussion, without vote or comment counts. Subreddit character matters (r/wallstreetbets is often contrarian/exuberant; r/stocks more measured; r/investing longer-term).
### Reddit posts — {", ".join(f"r/{sub}" for sub in subreddits)} (past 7 days)
Community discussion, without vote or comment counts. Subreddit character matters ({character}).
<start_of_reddit>
{reddit_block}
+42
View File
@@ -0,0 +1,42 @@
"""One turn of a tool-using analyst, and its last turn once its tool rounds are spent."""
import json
from langchain_core.messages import AIMessage, HumanMessage, ToolMessage
WRAP_UP = (
"You have used every tool round this report allows. Write your final report "
"now from the tool results above, and say which data you could not retrieve."
)
def take_turn(prompt, llm, tools, messages):
"""The analyst's reply and its report, which stays empty while it calls tools.
Told to wrap up, it answers without tools: a model offered tools may call one
whatever it is told. Its earlier calls and their results reach it as text,
since a provider may refuse a history holding tool calls when none are bound.
"""
if messages and isinstance(messages[-1], HumanMessage) and messages[-1].content == WRAP_UP:
# The prompt lists the tools it offers; a model told of tools it cannot
# call may still try, and some providers then answer with nothing.
prompt = prompt.partial(tool_names="none; your tool rounds are spent")
result = (prompt | llm).invoke(_as_text(messages))
return result, result.content
result = (prompt | llm.bind_tools(tools)).invoke(messages)
return result, "" if result.tool_calls else result.content
def _as_text(messages):
"""The history with its tool calls and tool results written out as plain messages."""
written = []
for message in messages:
if isinstance(message, AIMessage) and message.tool_calls:
said = message.content if isinstance(message.content, str) else ""
calls = "; ".join(f"{c['name']}({json.dumps(c['args'], default=str)})" for c in message.tool_calls)
written.append(AIMessage(content=f"{said}\n[Called {calls}]".strip()))
elif isinstance(message, ToolMessage):
written.append(HumanMessage(content=f"[{message.name or 'Tool'} returned]\n{message.content}"))
else:
written.append(message)
return written
+35 -55
View File
@@ -1,14 +1,11 @@
"""Prompt context shared by the agents: instrument identity, output language,
portfolio, and the message reset between analysts."""
"""Prompt context shared by the agents: instrument identity, output language and portfolio."""
import functools
import logging
from collections.abc import Mapping
from typing import Any
from langchain_core.messages import HumanMessage, RemoveMessage
from tradingagents.dataflows.date_window import get_current_date
from tradingagents.dataflows.date_window import is_historical
from tradingagents.dataflows.vendors.yahoo.fundamentals import get_company_profile
logger = logging.getLogger(__name__)
@@ -27,7 +24,14 @@ def get_language_instruction() -> str:
lang = get_config().get("output_language", "English")
if lang.strip().lower() == "english":
return ""
return f" Write your entire response in {lang}."
# The labelled lines are read by the program, so they keep their English
# label and value: a translated rating line leaves the reader prose to
# search, where a negated rating ("not a Sell") reads as the call (#1435).
return (
f" Write your entire response in {lang}, except the labelled lines the format"
f" asks for (the \"**Rating**:\" line, \"FINAL TRANSACTION PROPOSAL:\"):"
f" keep their label and value in English, exactly as specified."
)
def opponent_argument_or_opening(text: str, opponent: str) -> str:
@@ -54,7 +58,6 @@ def _clean_identity_value(value: Any) -> str | None:
return cleaned
@functools.lru_cache(maxsize=256)
def resolve_instrument_identity(ticker: str) -> dict:
"""Resolve deterministic identity metadata (company name, sector, …) for a ticker.
@@ -66,18 +69,23 @@ def resolve_instrument_identity(ticker: str) -> dict:
Best-effort by design: if yfinance is unavailable, rate-limited, or doesn't
recognise the ticker, we return ``{}`` and the caller falls back to
ticker-only context rather than failing before analysis starts. Cached so
the lookup happens at most once per ticker per process.
ticker-only context rather than failing before analysis starts. An answer
is cached for the process; a failed lookup is asked again next time.
Identity resolves for the same instrument the price path fetches
(``XAUUSD`` -> ``GC=F``, #983).
"""
try:
info = get_company_profile(ticker)
return _identity(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 {}
@functools.lru_cache(maxsize=256)
def _identity(ticker: str) -> dict:
"""The vendor's identity fields for ``ticker``; raises if the lookup fails."""
info = get_company_profile(ticker)
identity: dict[str, str] = {}
company_name = _clean_identity_value(info.get("longName")) or _clean_identity_value(
info.get("shortName")
@@ -100,7 +108,7 @@ def build_instrument_context(
ticker: str,
asset_type: str = "stock",
identity: Mapping[str, str] | None = None,
curr_date: str | None = None,
trade_date: str | None = None,
) -> str:
"""Describe the exact instrument so agents preserve identity and ticker.
@@ -110,23 +118,32 @@ def build_instrument_context(
than pattern-matching the price chart to a wrong one (#814).
That profile carries no historical vintage: it describes the company today.
For a run dated earlier, the context says so, since a company that has since
renamed or been reclassified would otherwise anchor the whole graph to an
identity it did not have on the analysis date.
A run dated earlier gets the current name alone, as a way to tell the
company apart from others rather than as what it was called then; a sector,
industry or exchange it holds today is not given, since it may not have held
on the analysis date.
"""
is_crypto = asset_type == "crypto"
instrument_label = "asset" if is_crypto else "instrument"
context = (
f"The {instrument_label} to analyze is `{ticker}`. "
"Use this exact ticker in every tool call, report, and recommendation, "
"The tools serve this instrument; refer to it by this exact ticker in every report and recommendation, "
"preserving any exchange suffix (e.g. `.TO`, `.L`, `.HK`, `.T`, `-USD`)."
)
identity = identity or {}
name = identity.get("company_name") or identity.get("name")
label = "Name" if is_crypto else "Company"
details = []
if identity:
name = identity.get("company_name") or identity.get("name")
if is_historical(trade_date):
if name:
details.append(f"{'Name' if is_crypto else 'Company'}: {name}")
details.append(
f"{label}: {name} (its current name, given only to identify it; "
f"on {trade_date} it may have been named differently)"
)
else:
if name:
details.append(f"{label}: {name}")
sector, industry = identity.get("sector"), identity.get("industry")
if sector and industry:
details.append(f"Business classification: {sector} / {industry}")
@@ -143,13 +160,6 @@ def build_instrument_context(
"Do not substitute a different company or ticker unless a tool "
"result explicitly disproves this resolved identity."
)
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"not necessarily on {curr_date}: a name or classification changed "
f"since then would read as the current one."
)
if is_crypto:
context += (
@@ -206,33 +216,3 @@ def get_portfolio_context_from_state(state: Mapping[str, Any]) -> str:
"holdings or cash, so do not assume a flat book; give direction and "
"sizing guidance in terms the caller can apply to their own position."
)
def create_msg_delete():
def delete_messages(state):
"""Clear messages and add a context-anchored placeholder.
The placeholder must not be a bare ``"Continue"``: some
OpenAI-compatible providers interpret that literally as the user task
and produce output about the word "continue" instead of analysing the
instrument (#888). Anchoring it to the resolved instrument context and
date keeps the next analyst on-task even if the provider treats the
placeholder as a standalone request.
"""
messages = state["messages"]
removal_operations = [RemoveMessage(id=m.id) for m in messages]
instrument_context = get_instrument_context_from_state(state)
trade_date = state.get("trade_date", "the requested date")
placeholder = HumanMessage(
content=(
f"Proceed with your assigned analysis for this workflow. "
f"{instrument_context} The analysis date is {trade_date}."
)
)
return {"messages": removal_operations + [placeholder]}
return delete_messages
@@ -1,11 +1,11 @@
"""Portfolio Manager: synthesises the risk-analyst debate into the final decision.
Uses LangChain's ``with_structured_output`` so the LLM produces a typed
``PortfolioDecision`` directly, in a single call. The result is rendered
back to markdown for storage in ``final_trade_decision`` so memory log,
CLI display, and saved reports continue to consume the same shape they do
today. When a provider does not expose structured output, the agent falls
back gracefully to free-text generation.
``PortfolioDecision`` directly, in a single call. Its rating is the run's
``final_rating``, and the decision is rendered to markdown as
``final_trade_decision`` for the memory log, CLI display and saved reports.
When a provider does not expose structured output, the agent falls back to
free-text generation and the rating is read from that text.
"""
from __future__ import annotations
@@ -15,12 +15,9 @@ from tradingagents.agents.context import (
get_language_instruction,
get_portfolio_context_from_state,
)
from tradingagents.agents.rating import parse_rating
from tradingagents.agents.schemas import PortfolioDecision, render_pm_decision
from tradingagents.agents.structured import (
NO_EXTERNAL_TOOLS,
bind_structured,
invoke_structured_or_freetext,
)
from tradingagents.agents.structured import NO_EXTERNAL_TOOLS, bind_structured, invoke_structured
def create_portfolio_manager(llm):
@@ -78,16 +75,17 @@ Write these sections, in this order, starting with the rating on its own line:
{NO_EXTERNAL_TOOLS}{get_language_instruction()}"""
final_trade_decision = invoke_structured_or_freetext(
structured_llm,
llm,
prompt,
render_pm_decision,
"Portfolio Manager",
)
# The typed rating is the decision; the rendered text only carries it.
# Read back from text, a rating the thesis quotes could replace it.
decision = invoke_structured(structured_llm, prompt, "Portfolio Manager")
if decision is not None:
final_trade_decision = render_pm_decision(decision)
final_rating = decision.rating.value
else:
final_trade_decision = llm.invoke(prompt).content
final_rating = parse_rating(final_trade_decision)
new_risk_debate_state = {
"judge_decision": final_trade_decision,
"history": risk_debate_state["history"],
"aggressive_history": risk_debate_state["aggressive_history"],
"conservative_history": risk_debate_state["conservative_history"],
@@ -102,6 +100,7 @@ Write these sections, in this order, starting with the rating on its own line:
return {
"risk_debate_state": new_risk_debate_state,
"final_trade_decision": final_trade_decision,
"final_rating": final_rating,
}
return portfolio_manager_node
@@ -59,7 +59,6 @@ Write these sections, in this order, starting with the recommendation on its own
)
new_investment_debate_state = {
"judge_decision": investment_plan,
"history": investment_debate_state.get("history", ""),
"bear_history": investment_debate_state.get("bear_history", ""),
"bull_history": investment_debate_state.get("bull_history", ""),

Some files were not shown because too many files have changed in this diff Show More