"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix: three defects found by testing the fixes
Haozhe Wuab82e4fb196b
diff --git a/agent/backtest/loaders/tushare.py b/agent/backtest/loaders/tushare.pyindex 22c23dd1e..518ecd2fc 100644--- a/agent/backtest/loaders/tushare.py+++ b/agent/backtest/loaders/tushare.py@@ -5,7 +5,8 @@ Minute data uses ``pro.stk_mins()`` (Tushare points >= 2000)."""import logging-from typing import Dict, List, Optional+import time+from typing import Any, Callable, Dict, List, Optionalimport pandas as pd@@ -14,6 +15,70 @@ from backtest.loaders.base import cached_loader_fetch, validate_date_rangefrom backtest.loaders.cn_adjust import apply_qfqfrom backtest.loaders.registry import register+#: Substrings that identify a Tushare per-minute quota rejection rather than a+#: real failure. Tushare returns these as an ordinary exception message, so the+#: only way to tell "you are going too fast" from "this symbol does not exist"+#: is to read the text.+_RATE_LIMIT_MARKERS: tuple[str, ...] = (+ "每分钟",+ "每天",+ "抽取",+ "访问该接口",+ "频率",+ "rate limit",+ "too many requests",+)++#: Backoff schedule in seconds. The quota window is a minute, so the last wait+#: has to cross one; three attempts totalling ~65s clear it without turning a+#: genuinely broken call into a two-minute hang.+_RATE_LIMIT_BACKOFF_SECONDS: tuple[float, ...] = (5.0, 20.0, 40.0)+++def _is_rate_limited(exc: Exception) -> bool:+ """Return whether an exception is a quota rejection rather than a failure.++ Args:+ exc: The exception raised by a Tushare endpoint call.++ Returns:+ True when the message carries any marker in :data:`_RATE_LIMIT_MARKERS`.+ """+ message = str(exc).lower()+ return any(marker.lower() in message for marker in _RATE_LIMIT_MARKERS)+++def _call_with_backoff(fn: Callable[..., Any], /, **kwargs: Any) -> Any:+ """Call a Tushare endpoint, waiting out a per-minute quota rejection.++ Only quota rejections are retried. Retrying an ordinary failure would turn+ a broken symbol or a bad date range into a silent multi-second stall and+ then the same error anyway, so those propagate on the first attempt.++ Args:+ fn: The endpoint callable, e.g. ``api.daily``.+ **kwargs: Passed straight through.++ Returns:+ Whatever the endpoint returns.++ Raises:+ Exception: The endpoint's own exception, either immediately (not a+ quota issue) or after the backoff schedule is exhausted.+ """+ for delay in _RATE_LIMIT_BACKOFF_SECONDS:+ try:+ return fn(**kwargs)+ except Exception as exc: # noqa: BLE001 - classified immediately below+ if not _is_rate_limited(exc):+ raise+ logger.warning(+ "tushare quota hit (%s); waiting %.0fs before retrying", exc, delay+ )+ time.sleep(delay)+ return fn(**kwargs)++logger = logging.getLogger(__name__)@@ -158,12 +223,12 @@ class DataLoader:adjust = Noneelif _is_hk_equity(code):endpoint_name = "hk_daily"- df = self.api.hk_daily(ts_code=code, start_date=start_date, end_date=end_date)+ df = _call_with_backoff(self.api.hk_daily, ts_code=code, start_date=start_date, end_date=end_date)# Tushare publishes no HK adjustment-factor series.adjust = Noneelse:endpoint_name = "daily"- df = self.api.daily(ts_code=code, start_date=start_date, end_date=end_date)+ df = _call_with_backoff(self.api.daily, ts_code=code, start_date=start_date, end_date=end_date)adjust = getattr(self.api, "adj_factor", None)if df is None or df.empty:@@ -183,7 +248,7 @@ class DataLoader:return ohlcvtry:- factor = adjust(ts_code=code, start_date=start_date, end_date=end_date)+ factor = _call_with_backoff(adjust, ts_code=code, start_date=start_date, end_date=end_date)except Exception as exc: # noqa: BLE001 - one bad fetch must not raiselogger.warning("tushare adjustment-factor fetch failed for %s: %s", code, exc)factor = Nonediff --git a/agent/src/quantlib/options.py b/agent/src/quantlib/options.pyindex 09f320f23..f0b409047 100644--- a/agent/src/quantlib/options.py+++ b/agent/src/quantlib/options.py@@ -51,6 +51,17 @@ _CALL = "call"_PUT = "put"+#: Spellings folded to ``"call"``. Beyond case and padding these are the forms+#: real configs and real chain feeds actually carry: the single letter used in+#: option symbols and most vendor chains, the plural a chain endpoint returns,+#: and the two Chinese terms -- ``认购``/``认沽`` being the official SSE/SZSE+#: wording for exchange-traded options, which an A-share config will use.+_CALL_ALIASES: frozenset[str] = frozenset({"call", "calls", "c", "看涨", "认购"})++#: Spellings folded to ``"put"``. See :data:`_CALL_ALIASES`.+_PUT_ALIASES: frozenset[str] = frozenset({"put", "puts", "p", "看跌", "认沽"})++def normalise_option_type(option_type: str) -> str:"""Fold an option-type string to ``"call"`` or ``"put"``.@@ -59,19 +70,42 @@ def normalise_option_type(option_type: str) -> str:later compares it with ``== "call"`` will price a leg typed ``"Call"`` as acall here and settle it as a put there.+ WHY THIS ACCEPTS ALIASES BUT STILL REFUSES THE UNKNOWN+ -----------------------------------------------------+ There are two different failure modes and they need opposite treatment.++ A config saying ``"C"``, ``"calls"`` or ``"认购"`` is *unambiguous* -- there+ is exactly one thing it can mean, and refusing it breaks a working setup for+ no safety gain. Those are folded (:data:`_CALL_ALIASES`, :data:`_PUT_ALIASES`).++ A config saying ``"cal"`` or ``"kall"`` is a typo, and the only safe answer+ is to stop. The behaviour this replaced defaulted an unrecognised type to+ put, so a mistyped call leg opened priced as a call and settled as a put --+ ten in-the-money contracts settling at zero. Guessing at a typo is how that+ happened, so an unknown string still raises.+Args:- option_type: Caller-supplied option type, any case, may be padded.+ option_type: Caller-supplied option type. Case, surrounding whitespace+ and the aliases above are all accepted.Returns:Either ``"call"`` or ``"put"``.Raises:- ValueError: If the string is neither.+ ValueError: If the string matches no known spelling. The message lists+ what is accepted, so the fix does not need a source read."""folded = str(option_type).strip().lower()- if folded not in (_CALL, _PUT):- raise ValueError(f"option_type must be 'call' or 'put', got {option_type!r}")- return folded+ if folded in _CALL_ALIASES:+ return _CALL+ if folded in _PUT_ALIASES:+ return _PUT+ raise ValueError(+ f"unrecognised option_type {option_type!r}. Accepted (any case): "+ f"{sorted(_CALL_ALIASES)} for a call, {sorted(_PUT_ALIASES)} for a put. "+ "An unrecognised type is not defaulted, because defaulting one is how a "+ "call leg gets settled as a put."+ )def _intrinsic(S: float, K: float, option_type: str) -> float:diff --git a/agent/src/swarm/presets/credit_research_team.yaml b/agent/src/swarm/presets/credit_research_team.yamlindex 05350842e..275d22d00 100644--- a/agent/src/swarm/presets/credit_research_team.yaml+++ b/agent/src/swarm/presets/credit_research_team.yaml@@ -68,9 +68,12 @@ agents:vol / share count from `get_stock_profile` and `get_market_data`. Every modelinput must trace to one of those calls; if a line item is missing, report themodel as not runnable rather than substituting an assumed value.- **There is no rating feed and no market-implied PD service here.** Agency- ratings and rating histories are only usable if you retrieved them via- `read_url` and cite the source. Your "proprietary rating" is your own+ **There is no agency rating feed here.** Agency ratings and rating+ histories are only usable if you retrieved them via `read_url` and cite+ the source. A market-implied PD, by contrast, is not missing: it is+ precisely what the `merton_model` call above produces from equity value,+ equity vol and debt face. Report it as a model output alongside the inputs+ that produced it, never as a vendor figure. Your "proprietary rating" is your ownjudgement mapped from the computed metrics — present it as that, never asan agency-comparable rating.`factor_analysis` computes IC/IR and layered NAV from CSVs you write; it doesdiff --git a/agent/src/swarm/presets/event_driven_task_force.yaml b/agent/src/swarm/presets/event_driven_task_force.yamlindex f4b2d639a..da32e0080 100644--- a/agent/src/swarm/presets/event_driven_task_force.yaml+++ b/agent/src/swarm/presets/event_driven_task_force.yaml@@ -69,19 +69,35 @@ agents:- Hit rate of direction-consistent abnormal returns post-event- Key factors driving persistence or dissipation of abnormal returns- **How to actually produce CAR/CAAR.** No tool computes an event study.- `factor_analysis` computes IC/IR and layered NAV from a factor CSV and a- return CSV you write — it cannot do this. Build it yourself in `bash`:+ **How to actually produce CAR/CAAR.** `src.quantlib.eventstudy.event_study`+ implements this — estimation-window market model, abnormal returns, CAR,+ CAAR, and the three test statistics. Do not hand-roll the arithmetic and+ do not settle for subtracting the benchmark.1. Establish each comparable event's DATE from a retrieved source —`get_stock_news` or `read_url`. An event date you cannot cite is notusable; drop that comparable rather than guessing when it happened.- 2. Pull the security's and the benchmark's daily bars around each event- date with `get_market_data`.- 3. Abnormal return = security return − benchmark return (market-adjusted- model). State that this is the market-adjusted model, not a- risk-adjusted one — there is no estimation-window factor model here.- 4. Cumulate over each window for CAR; average across events for CAAR.- 5. With fewer than ~5 comparable events, report the individual CARs and+ 2. Pull the securities' and the benchmark's daily bars with+ `get_market_data`, convert to simple returns, and assemble a+ date × symbol frame plus a benchmark return series.+ 3. In `bash`:+ `from src.quantlib.eventstudy import event_study` then+ `event_study(returns, market_returns, events, event_window=(-1, 20))`+ where `events` is a list of `(symbol, event_date)` pairs. The default+ `model="market"` fits alpha and beta on a 120-row estimation window+ ending 10 rows before the window opens, so the result is+ RISK-adjusted, not merely market-adjusted. Report which model you used.+ 4. Read `caar_total` for the headline and `caar` for the T+1 / T+5 / T+20 /+ T+60 path — run the study once per horizon by widening `event_window`.+ 5. **Report `bmp_p_value`, not just the mean.** A CAAR without a test+ statistic is an anecdote. When `bmp_p_value` and `patell_p_value`+ disagree, quote BMP and say why: events raise volatility, and Patell+ assumes they do not. Also report `len(result.events)` and+ `result.dropped` — a study over 12 events of which 7 were dropped is+ a different study and the reader must be told.+ 6. If `result.shared_event_dates` is non-empty the events overlap in+ calendar time, the independence the p-values assume is violated, and+ you must say so rather than quoting them as if it were not.+ 7. With fewer than ~5 measurable events, report the individual CARs andsay the sample is too small for a meaningful CAAR. Do not present amean of two observations as an "abnormal return distribution".If you cannot complete steps 1–2, write "historical benchmarking not@@ -100,9 +116,11 @@ agents:Use load_skill("sentiment-analysis") for market sentiment and expectation quantification tools.Use load_skill("valuation-model") for valuation analysis frameworks and tools.`factor_analysis` computes IC/IR and layered NAV from a factor CSV and a return CSV- you write yourself — it does not fetch data and cannot run an event study.+ you write yourself — it does not fetch data and does not run event studies.Event dates come from `get_stock_news` / `read_url`, bars from `get_market_data`,- and the CAR arithmetic from your own `bash` code.+ and the event study itself from `src.quantlib.eventstudy.event_study` — which+ owns the estimation-window model, the CAR arithmetic and the significance+ tests, so none of the three is yours to reimplement.tools: [bash, read_file, write_file, load_skill, factor_analysis, get_market_data, get_stock_news, read_url]skills: [corporate-events, sentiment-analysis, valuation-model]max_iterations: 50diff --git a/agent/src/swarm/presets/fund_selection_panel.yaml b/agent/src/swarm/presets/fund_selection_panel.yamlindex 479ef1eda..755c0ef97 100644--- a/agent/src/swarm/presets/fund_selection_panel.yaml+++ b/agent/src/swarm/presets/fund_selection_panel.yaml@@ -39,7 +39,7 @@ agents:- id: attribution_analystrole: Performance Attribution Analystsystem_prompt: |- You are a senior performance attribution specialist at a top-tier FOF fund, with expertise in the Brinson-Hood-Beebower attribution model, Barra multi-factor style analysis, and excess return decomposition. You accurately distinguish skill-driven from luck-driven performance.+ You are a senior performance attribution specialist at a top-tier FOF fund, with expertise in the Brinson-Hood-Beebower attribution model, cross-sectional style factor analysis, and excess return decomposition. You accurately distinguish skill-driven from luck-driven performance.## TaskConduct deep performance attribution analysis on candidate funds identified by the fund screener, with the objective: {goal}@@ -60,10 +60,24 @@ agents:only a top-N), sector and benchmark return series via `get_market_data`.A fund whose holdings you cannot retrieve gets NO Brinson table; saythe look-through was unavailable and fall back to return-based analysis.- 2. **Barra Style Factor Analysis**- - Key style factor exposures: value (low P/B, P/E) / growth (high ROE growth) / size (large/mid/small cap) / momentum (recent strength) / volatility (low-vol premium) / quality (ROE / financial stability)- - Style factor return decomposition: what proportion of performance comes from style exposure (beta return) vs pure alpha- - Style consistency assessment: magnitude of style factor exposure changes over the past 4 quarters (frequent drift = style inconsistency)+ 2. **Cross-Sectional Style Factor Analysis**+ Implemented — fit it, do not describe it:+ `from src.quantlib.factormodel import build_style_exposures, portfolio_style_exposure, cross_sectional_factor_returns, style_drift, factor_return_attribution`+ - Style exposures come from `STYLE_FACTOR_DEFINITIONS`: size, value,+ growth, momentum, quality, low_volatility, leverage, liquidity. Each+ factor names the raw characteristics it is built from — quote those+ definitions, since an exposure is only as meaningful as its recipe+ - Style factor return decomposition: `cross_sectional_factor_returns`+ gives the factor returns for a date, `factor_return_attribution`+ splits the fund's return into factor contributions plus a `specific`+ residual. The parts sum to the total by construction, so any gap you+ are tempted to report is an arithmetic error, not a finding+ - Style consistency: `style_drift` over the past 4 quarters of exposures.+ Read `max_abs_change`, not just `total_change` — a fund that ends the+ year where it started having been somewhere else in between has+ drifted, and the endpoint difference hides exactly that+ - **This model is not Barra** and must never be labelled as such; see+ output requirement 23. **Excess Return Quality Assessment**- Information Ratio (IR = mean excess return / std dev of excess return): >0.5 is good, >1.0 is excellent- Hit rate (fraction of periods with positive excess return) and consistency of average excess return (cyclicality)@@ -78,20 +92,20 @@ agents:## Output Requirements1. **Brinson Attribution Report** — Three-effect decomposition for each candidate fund from `brinson_fachler`, clearly identifying primary alpha source (allocation ability / stock selection ability); state the holdings report period and return series behind each table- 2. **Barra Style Profile** — There is no Barra factor model in this system and no licensed Barra exposure feed. Build a proxy style profile from the look-through holdings and label it exactly that: a proxy, with the factor definitions you used. Never present a proxy exposure as a Barra number+ 2. **Style Exposure Profile** — Fit it, do not eyeball it. `src.quantlib.factormodel` implements the cross-sectional model: `build_style_exposures(characteristics, market_caps)` standardises the raw characteristics into exposures (cap-weighted mean, equal-weighted dispersion, winsorised tails), then `portfolio_style_exposure(holdings, exposures, benchmark=...)` aggregates the fund's look-through holdings into an ACTIVE exposure per factor. Read the factor list and what each is built from off `STYLE_FACTOR_DEFINITIONS` and state those definitions in the report. Two disclosures are mandatory: the `filled` counts returned by `build_style_exposures` (a factor whose cells were mostly imputed is not a measurement) and `unmatched_weight` (holdings with no exposure data). **This is not Barra.** Barra is a licensed MSCI model with its own definitions and universe; this is a public-definition model that will not agree with it. Call it a style exposure from the stated model and never label a number here a Barra exposure3. **Excess Return Quality Rating** — Composite rating (A/B/C/D) based on IR/hit rate/consistency, distinguishing genuine investment skill from style exposure4. **Up/Down Capture Matrix** — Offensive/defensive profile comparison across candidate funds, identifying funds with balanced attack and defense5. **Style Drift Warnings** — Flag style-inconsistent funds with drift severity, recommend style weight adjustments in FOF construction6. **Shortlist** — Funds recommended for FOF construction phase (typically 60–70% of candidates), with reasons for inclusion and exclusion- Use load_skill("performance-attribution") for the Brinson model and Barra factor analysis framework.+ Use load_skill("performance-attribution") for the Brinson model and the style factor analysis framework.Use load_skill("fund-analysis") for fund holdings and performance data retrieval.Use load_skill("multi-factor") for multi-factor style analysis tools.`factor_analysis` computes IC/IR and layered NAV from a factor CSV and a return CSVyou write yourself; it does not fetch data and does not do Brinson attribution.The attribution decomposition comes from `src.quantlib.attribution`, the holdingsfrom `etf_holdings`, and the return series from `get_market_data`.- tools: [bash, read_file, write_file, load_skill, factor_analysis, etf_holdings, get_market_data]+ tools: [bash, read_file, write_file, load_skill, factor_analysis, etf_holdings, get_market_data, get_stock_profile, get_fundamentals]skills: [performance-attribution, fund-analysis, multi-factor]max_iterations: 50timeout_seconds: 1800@@ -157,7 +171,7 @@ tasks:- id: task-performance-attributionagent_id: attribution_analyst- prompt_template: "Conduct deep performance attribution analysis on candidate funds: Brinson three-effect decomposition via src.quantlib.attribution on retrieved holdings and return series, a clearly-labelled proxy style profile (no Barra model exists here), excess return quality rating, up/down capture rate comparison. Output attribution report and shortlist for FOF construction. Objective: {goal}."+ prompt_template: "Conduct deep performance attribution analysis on candidate funds: Brinson three-effect decomposition via src.quantlib.attribution on retrieved holdings and return series, a fitted cross-sectional style exposure profile via src.quantlib.factormodel (state the factor definitions; this is not Barra and must not be labelled as such), excess return quality rating, up/down capture rate comparison. Output attribution report and shortlist for FOF construction. Objective: {goal}."depends_on: [task-fund-screen]input_from:candidate_funds: task-fund-screendiff --git a/agent/src/swarm/presets/investment_committee.yaml b/agent/src/swarm/presets/investment_committee.yamlindex 6049861d9..0a8cfddd0 100644--- a/agent/src/swarm/presets/investment_committee.yaml+++ b/agent/src/swarm/presets/investment_committee.yaml@@ -94,7 +94,14 @@ agents:(confidence and horizon are arguments — state which you used),`max_drawdown_analysis(equity)` for the drawdown profile, and`fit_gpd_tail(returns)` for the tail beyond the empirical sample.- You have no options tool, so do not report option-implied vol or short cost.+ Option-implied vol is retrievable, not assumable: pull the chain with+ `get_options_chain`, read ATM implied vol off the strike ladder for the+ nearest expiration beyond your horizon, and compare it with the realised+ vol you computed from the bars. A wide IV-over-HV premium is a bear point+ in its own right. The chain is Yahoo-backed and **US-listed only** — if+ {target} is not US-listed, say so and omit the IV section rather than+ substituting a guess. Borrow / short-lending cost has no data source in+ this system: do not report a borrow fee.## Required outputs1. **Bear risk bullets** — 3–5 one-line top bear points, each with severity (high/medium)@@ -106,7 +113,7 @@ agents:7. **What would disprove the bear case** — Signals that would invalidate the bear thesis (i.e., bull-side rebuttal points)Use factor_analysis for risk-factor views; use load_skill for risk frameworks.- tools: [bash, read_file, write_file, load_skill, get_market_data, factor_analysis]+ tools: [bash, read_file, write_file, load_skill, get_market_data, factor_analysis, get_options_chain]skills: [technical-basic, fundamental-filter, yfinance, risk-analysis, volatility]max_iterations: 50timeout_seconds: 1800@@ -152,8 +159,14 @@ agents:scenarios; report the seed and path count so the run is reproducibleName the sample window for each figure. If you could not retrieve bars, saythe risk metrics are unavailable and give a qualitative review — an- unsourced VaR or stop price is worse than none. You have no options tool:- recommend a hedge structure if you wish, but do not price it.+ unsourced VaR or stop price is worse than none. Price the hedge you+ recommend — do not leave it as a shape. `options_payoff` takes the signed+ legs and returns entry debit/credit, analytic breakevens and bounded or+ unbounded max loss, which is what sizing a protective put or a collar+ actually requires; `options_pricing` values a single leg. Source the+ implied vol from `get_options_chain` when the name is US-listed, and when+ it is not, state the vol assumption you used and that it is an assumption.+ A hedge whose cost you did not compute is not a recommendation.### Compliance & concentration- Single-name cap (often 5–10% of NAV)@@ -170,7 +183,7 @@ agents:7. **Risk conditions** — If approval is conditional, state prerequisites (e.g., wait for earnings)Stay independent; do not cheerlead either side; optimize portfolio-level risk.- tools: [bash, read_file, write_file, load_skill, get_market_data]+ tools: [bash, read_file, write_file, load_skill, get_market_data, get_options_chain, options_pricing, options_payoff]skills: [risk-analysis, volatility, correlation-analysis]max_iterations: 50timeout_seconds: 1800diff --git a/agent/src/swarm/presets/risk_committee.yaml b/agent/src/swarm/presets/risk_committee.yamlindex 77234c083..85a801c9f 100644--- a/agent/src/swarm/presets/risk_committee.yaml+++ b/agent/src/swarm/presets/risk_committee.yaml@@ -48,15 +48,16 @@ agents:## Required outputs1. **VaR estimates** — 95%/99% VaR from `src.quantlib.risk.parametric_var` AND `historical_var` on the same return series, reported side by side. 99.9% historical VaR needs roughly 1000+ observations to mean anything: if your sample is shorter, say so and give the parametric figure only2. **CVaR (ES)** — `src.quantlib.risk.historical_cvar` at each confidence level+ 2b. **VaR model validation** — A VaR you did not backtest is a claim, not a measurement. Roll the VaR forward over the sample and run `src.quantlib.var_backtest.var_backtest(returns, var_series, confidence)`. Report the Kupiec p-value (is the breach COUNT right), the Christoffersen independence p-value (did the breaches CLUSTER — this is the one that ends firms, and Kupiec is blind to it), and the Basel traffic-light zone. A model in the yellow or red zone must be reported as failing validation even when its headline VaR looks reasonable3. **Stress tests** — At least three historical crisis scenarios. Define each by its DATE RANGE, pull that window with `get_market_data`, and report the realised loss over it. Do not quote a crisis loss from memory4. **Tail event probability** — `src.quantlib.risk.fit_gpd_tail(returns, threshold_pct)`; report the threshold you used, since the fit depends on it- 5. **Protection ideas** — Qualitative hedge structures. You have no options tool, so describe the structure; do not price it+ 5. **Protection ideas** — Priced hedge structures, not shapes. Build each candidate as signed legs and run `options_payoff` for entry debit/credit, analytic breakevens and max loss; `options_pricing` values a single leg. Take the implied vol from `get_options_chain` when the underlying is US-listed, and when it is not, state the vol you assumed and label it an assumption. Report the cost of protection as a percentage of the notional being protected — an unpriced hedge cannot be compared against the tail loss it is supposed to cover`load_skill` loads methodology documents; it does NOT fetch data — pull returnswith `get_market_data` first. Every figure above must name the sample windowit came from. If the series cannot be retrieved, report the section asunavailable rather than producing an illustrative number.- tools: [bash, read_file, write_file, load_skill, get_market_data]+ tools: [bash, read_file, write_file, load_skill, get_market_data, get_options_chain, options_pricing, options_payoff]skills: [volatility]max_iterations: 50timeout_seconds: 1800@@ -85,9 +86,26 @@ agents:momentum readings, `src.quantlib.timeseries.fit_garch(returns, horizon)` forvolatility persistence, and `src.quantlib.risk.monte_carlo_gbm` +`analyze_mc_results` for the forward path probabilities (state seed and- path count). There is no regime-switching model (HMM or otherwise) in this- system — your regime label is a rule you define on measured inputs, so state- the rule. For historical analogs, name the date range of each and show the+ path count).++ **The regime label is fitted, not asserted.** Run+ `src.quantlib.timeseries.fit_markov_regime(returns, n_regimes=2)`. It returns+ the regimes ordered calmest-first, so `regime_0` is the low-vol state and the+ last is the high-vol one, and it tells you which state the series is in NOW+ via `current_regime` with `current_regime_probability`. Report that+ probability — a regime call at 0.55 confidence is a different statement from+ one at 0.98 and must not be written as though it were the same. Take the+ persistence of the current state from `expected_durations[current_regime]`+ (in trading days) and the odds of leaving it from the matching row of+ `transition_matrix`, where `transition_matrix[i][j]` reads "P(regime j+ tomorrow | regime i today)". That row IS output 3 (transition signals) and+ feeds output 5 (forward look) — quote it rather than narrating around it.+ Check `converged`; if the fit did not converge, say so and fall back to a+ stated rule on measured vol and trend.+ The model gives you a VOLATILITY state, not a direction. Bull / bear / chop+ is your own mapping from that state plus the trend you measured, so state+ the mapping you used.+ For historical analogs, name the date range of each and show themeasured similarity; an analog you did not measure is an anecdote, label it one.tools: [bash, read_file, write_file, load_skill, get_market_data, technical_indicators]skills: [volatility, technical-basic]diff --git a/agent/src/swarm/presets/statistical_arbitrage_desk.yaml b/agent/src/swarm/presets/statistical_arbitrage_desk.yamlindex a39ac1e56..29a075cd6 100644--- a/agent/src/swarm/presets/statistical_arbitrage_desk.yaml+++ b/agent/src/swarm/presets/statistical_arbitrage_desk.yaml@@ -110,11 +110,23 @@ agents:`fixed_slippage` the flat-bps baseline, and `delayed_execution` shows thecost of acting a bar late. Name the model and the coefficient you used andlabel the output an estimate.- **There is no order-book depth or quote feed here** — depth, bid-ask spread- and queue position cannot be measured. Score depth from a stated proxy- (turnover, ADV) and say it is a proxy, or leave it out. Granger causality- between legs comes from `src.quantlib.timeseries.granger_test`.- tools: [bash, read_file, write_file, load_skill, get_market_data]+ **Order-book depth: measurable for crypto, not for equities.** For a crypto+ leg, `orderbook_depth` returns the live L2 ladder — bid/ask spread in bps,+ depth imbalance, and the impact cost of a stated notional walked through+ the real ladder in both directions. Use it instead of a proxy, and read+ three fields before you quote anything from it: `fully_filled` (False means+ the book could not absorb your size — report the shortfall, never the+ partial average as if it were the fill), `timestamp` with+ `timestamp_source` (a book is a snapshot that expires in seconds, and+ `local_fetch_time` means the venue did not stamp it), and the `units` block+ (quantities are base asset, notionals are quote asset — for `ETH-BTC` the+ quote is BTC, not a dollar).+ For an EQUITY leg there is still no depth or quote feed: score depth from a+ stated proxy (turnover, ADV), say it is a proxy, or leave it out. Never+ present a crypto depth measurement and an equity depth proxy in the same+ column without marking which is which.+ Granger causality between legs comes from `src.quantlib.timeseries.granger_test`.+ tools: [bash, read_file, write_file, load_skill, get_market_data, orderbook_depth]skills: [market-microstructure, execution-model]max_iterations: 50timeout_seconds: 1800diff --git a/agent/tests/conftest.py b/agent/tests/conftest.pyindex cf5be8f87..a8b702aaa 100644--- a/agent/tests/conftest.py+++ b/agent/tests/conftest.py@@ -15,8 +15,31 @@ if str(AGENT_DIR) not in sys.path:@pytest.fixture(autouse=True)def _reset_env_config():- """Clear the cached EnvConfig before each test so monkeypatch.setenv works."""+ """Isolate each test from the process environment and the config cache.++ Two things leak between tests otherwise, and the second one bit us:++ 1. The cached ``EnvConfig`` singleton, so ``monkeypatch.setenv`` would have+ no effect on anything already holding the cached instance.+ 2. ``os.environ`` itself. The settings write path deliberately applies a+ written ``.env`` to the running process, which is correct in production+ (settings take effect without a restart) but means a settings TEST+ writing ``TUSHARE_TOKEN=ts-secret-token`` into a temp file leaks that+ value into the process for every test that follows. That is exactly how+ four live-data tests came to fail with "token is wrong" while passing in+ isolation -- and monkeypatch cannot undo it, because the test never went+ through monkeypatch to set it.++ Snapshotting and restoring the whole environment closes the class of bug+ rather than the one instance of it.+ """+ import os+from src.config.accessor import reset_env_config++ saved_environ = dict(os.environ)reset_env_config()yield+ os.environ.clear()+ os.environ.update(saved_environ)reset_env_config()diff --git a/agent/tests/test_tushare_loader.py b/agent/tests/test_tushare_loader.pyindex 3b4718814..345192b18 100644--- a/agent/tests/test_tushare_loader.py+++ b/agent/tests/test_tushare_loader.py@@ -401,3 +401,73 @@ class TestTushareE2E:for code in ["600519.SH", "510050.SH", "000001.SH"]:assert code in resultassert not result[code].empty+++# --- rate-limit backoff (2026-08-06) ---+++class TestRateLimitBackoff:+ """Only a quota rejection is retried; a real failure still fails fast."""++ def test_a_quota_rejection_is_retried_then_succeeds(self, monkeypatch):+ from backtest.loaders import tushare as mod++ monkeypatch.setattr(mod.time, "sleep", lambda _s: None)+ calls = {"n": 0}++ def flaky(**kwargs):+ calls["n"] += 1+ if calls["n"] < 3:+ raise RuntimeError("抱歉,您每分钟最多访问该接口200次")+ return "ok"++ assert mod._call_with_backoff(flaky) == "ok"+ assert calls["n"] == 3++ def test_a_real_failure_is_not_retried(self, monkeypatch):+ from backtest.loaders import tushare as mod++ monkeypatch.setattr(mod.time, "sleep", lambda _s: None)+ calls = {"n": 0}++ def broken(**kwargs):+ calls["n"] += 1+ raise ValueError("ts_code does not exist")++ with pytest.raises(ValueError):+ mod._call_with_backoff(broken)+ # Retrying this would stall for a minute and then fail identically.+ assert calls["n"] == 1++ def test_the_backoff_schedule_crosses_the_quota_window(self):+ from backtest.loaders.tushare import _RATE_LIMIT_BACKOFF_SECONDS++ # The quota window is a minute; the schedule has to be able to outlast it.+ assert sum(_RATE_LIMIT_BACKOFF_SECONDS) >= 60.0++ def test_an_exhausted_schedule_finally_propagates(self, monkeypatch):+ from backtest.loaders import tushare as mod++ monkeypatch.setattr(mod.time, "sleep", lambda _s: None)++ def always_limited(**kwargs):+ raise RuntimeError("每分钟最多访问该接口")++ with pytest.raises(RuntimeError, match="每分钟"):+ mod._call_with_backoff(always_limited)++ @pytest.mark.parametrize(+ "message, limited",+ [+ ("抱歉,您每分钟最多访问该接口200次", True),+ ("您今天最多访问该接口", True),+ ("rate limit exceeded", True),+ ("Too Many Requests", True),+ ("ts_code 格式错误", False),+ ("connection refused", False),+ ],+ )+ def test_classification(self, message, limited):+ from backtest.loaders.tushare import _is_rate_limited++ assert _is_rate_limited(RuntimeError(message)) is limited