"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(data): weekly and monthly bars, built from daily ones (#1479)
Haozhe Wu6ca364f75744
diff --git a/README.md b/README.mdindex 93d22d1d5..3ac5e502f 100644--- a/README.md+++ b/README.md@@ -694,7 +694,7 @@ Run `vibe-trading alpha list` to browse, `vibe-trading alpha show <id>` for form| **Composite** | cross-market | one shared capital pool across markets (`source="auto"`) || **options_portfolio** | options | multi-leg, Greeks, payoff/scenario |-Intraday bars: 1m / 5m / 15m / 30m / 1H / 4H / 1D. 15 metrics + benchmark comparison, **5 portfolio optimizers** (equal-volatility / risk-parity / mean-variance / max-diversification / turnover-aware), and 3 validation tools (Monte Carlo / Bootstrap / Walk-Forward).+Bars: 1m / 5m / 15m / 30m / 1H / 4H / 1D, plus weekly / monthly (1W / 1M, built from daily bars). 15 metrics + benchmark comparison, **5 portfolio optimizers** (equal-volatility / risk-parity / mean-variance / max-diversification / turnover-aware), and 3 validation tools (Monte Carlo / Bootstrap / Walk-Forward).</details>diff --git a/README_ar.md b/README_ar.mdindex c5bdfb7ce..d67d7e01c 100644--- a/README_ar.md+++ b/README_ar.md@@ -653,7 +653,7 @@ LONGBRIDGE_ACCESS_TOKEN=...| **Composite** | عبر الأسواق | تجمّع رأس مال مشترك واحد عبر الأسواق (`source="auto"`) || **options_portfolio** | الخيارات | متعدد الأرجل، وGreeks، وpayoff/scenario |-أشرطة داخل اليوم: 1m / 5m / 15m / 30m / 1H / 4H / 1D. 15 مقياساً + مقارنة معيارية، و**5 محسّنات محفظة** (equal-volatility / risk-parity / mean-variance / max-diversification / turnover-aware)، و3 أدوات تحقق (Monte Carlo / Bootstrap / Walk-Forward).+الأشرطة: 1m / 5m / 15m / 30m / 1H / 4H / 1D، إضافةً إلى الأسبوعية / الشهرية (1W / 1M، مبنية من الأشرطة اليومية). 15 مقياساً + مقارنة معيارية، و**5 محسّنات محفظة** (equal-volatility / risk-parity / mean-variance / max-diversification / turnover-aware)، و3 أدوات تحقق (Monte Carlo / Bootstrap / Walk-Forward).</details>diff --git a/README_es.md b/README_es.mdindex ad38dba1b..d7ee3af54 100644--- a/README_es.md+++ b/README_es.md@@ -658,7 +658,7 @@ Ejecuta `vibe-trading alpha list` para explorar, `vibe-trading alpha show <id>`| **Composite** | cross-market | un único pool de capital compartido entre mercados (`source="auto"`) || **options_portfolio** | opciones | multi-leg, greeks, payoff/escenario |-Barras intradía: 1m / 5m / 15m / 30m / 1H / 4H / 1D. 15 métricas + comparación con benchmark, **5 optimizadores de cartera** (volatilidad-igual / risk-parity / media-varianza / máxima diversificación / con conciencia de turnover), y 3 herramientas de validación (Monte Carlo / Bootstrap / Walk-Forward).+Barras: 1m / 5m / 15m / 30m / 1H / 4H / 1D, más semanales / mensuales (1W / 1M, construidas a partir de barras diarias). 15 métricas + comparación con benchmark, **5 optimizadores de cartera** (volatilidad-igual / risk-parity / media-varianza / máxima diversificación / con conciencia de turnover), y 3 herramientas de validación (Monte Carlo / Bootstrap / Walk-Forward).</details>diff --git a/README_id.md b/README_id.mdindex 808dbb069..c25120439 100644--- a/README_id.md+++ b/README_id.md@@ -819,7 +819,7 @@ Jalankan `vibe-trading alpha list` untuk menjelajah, `vibe-trading alpha show <i| **Composite** | cross-market | one shared capital pool across markets (`source="auto"`) || **options_portfolio** | options | multi-leg, Greeks, payoff/scenario |-Bar intraday: 1m / 5m / 15m / 30m / 1H / 4H / 1D. 15 metrik + perbandingan benchmark, **5 optimizer portofolio** (equal-volatility / risk-parity / mean-variance / max-diversification / turnover-aware), dan 3 tool validasi (Monte Carlo / Bootstrap / Walk-Forward).+Bar: 1m / 5m / 15m / 30m / 1H / 4H / 1D, plus mingguan / bulanan (1W / 1M, dibangun dari bar harian). 15 metrik + perbandingan benchmark, **5 optimizer portofolio** (equal-volatility / risk-parity / mean-variance / max-diversification / turnover-aware), dan 3 tool validasi (Monte Carlo / Bootstrap / Walk-Forward).</details>diff --git a/README_ja.md b/README_ja.mdindex 759fe7269..a04352ea2 100644--- a/README_ja.md+++ b/README_ja.md@@ -653,7 +653,7 @@ Paper-vs-live is a **structural per-broker runtime guard** (account-id format, h| **Composite** | cross-market | one shared capital pool across markets (`source="auto"`) || **options_portfolio** | options | multi-leg, Greeks, payoff/scenario |-Intraday bars: 1m / 5m / 15m / 30m / 1H / 4H / 1D. 15 metrics + benchmark comparison, **5 portfolio optimizers** (equal-volatility / risk-parity / mean-variance / max-diversification / turnover-aware), and 3 validation tools (Monte Carlo / Bootstrap / Walk-Forward).+Bars: 1m / 5m / 15m / 30m / 1H / 4H / 1D, plus weekly / monthly (1W / 1M, built from daily bars). 15 metrics + benchmark comparison, **5 portfolio optimizers** (equal-volatility / risk-parity / mean-variance / max-diversification / turnover-aware), and 3 validation tools (Monte Carlo / Bootstrap / Walk-Forward).</details>diff --git a/README_ko.md b/README_ko.mdindex bdc63aed7..7592c333e 100644--- a/README_ko.md+++ b/README_ko.md@@ -653,7 +653,7 @@ Paper-vs-live는 **구조적 브로커별 런타임 가드**(account-id 형식,| **Composite** | cross-market | one shared capital pool across markets (`source="auto"`) || **options_portfolio** | options | multi-leg, Greeks, payoff/scenario |-Intraday bars: 1m / 5m / 15m / 30m / 1H / 4H / 1D. 15 metrics + benchmark comparison, **5 portfolio optimizers** (equal-volatility / risk-parity / mean-variance / max-diversification / turnover-aware), and 3 validation tools (Monte Carlo / Bootstrap / Walk-Forward).+Bars: 1m / 5m / 15m / 30m / 1H / 4H / 1D, plus weekly / monthly (1W / 1M, built from daily bars). 15 metrics + benchmark comparison, **5 portfolio optimizers** (equal-volatility / risk-parity / mean-variance / max-diversification / turnover-aware), and 3 validation tools (Monte Carlo / Bootstrap / Walk-Forward).</details>diff --git a/README_zh.md b/README_zh.mdindex bb420d1d0..931f22749 100644--- a/README_zh.md+++ b/README_zh.md@@ -666,7 +666,7 @@ LONGBRIDGE_ACCESS_TOKEN=...| **Composite** | 跨市场 | 跨市场共享单一资金池(`source="auto"`) || **options_portfolio** | 期权 | 多腿、Greeks、payoff/scenario |-日内 bar:1m / 5m / 15m / 30m / 1H / 4H / 1D。15 项指标 + benchmark 对比,**5 个组合优化器**(equal-volatility / risk-parity / mean-variance / max-diversification / turnover-aware),以及 3 个验证工具(Monte Carlo / Bootstrap / Walk-Forward)。+Bar 周期:1m / 5m / 15m / 30m / 1H / 4H / 1D,以及由日线合成的周线 / 月线(1W / 1M)。15 项指标 + benchmark 对比,**5 个组合优化器**(equal-volatility / risk-parity / mean-variance / max-diversification / turnover-aware),以及 3 个验证工具(Monte Carlo / Bootstrap / Walk-Forward)。</details>diff --git a/agent/backtest/benchmark.py b/agent/backtest/benchmark.pyindex dd236f88d..8658c5d35 100644--- a/agent/backtest/benchmark.py+++ b/agent/backtest/benchmark.py@@ -11,6 +11,7 @@ from typing import Any, Optionalimport pandas as pd+from backtest.loaders.base import resample_bars, source_intervalfrom backtest.loaders.yfinance_loader import DataLoader as YfinanceLoaderfrom backtest.metrics import bar_returns, buy_and_hold_return@@ -79,7 +80,7 @@ def resolve_benchmark(source: Data source name (tushare / yfinance / okx / akshare / ccxt).start_date: Backtest start date.end_date: Backtest end date.- interval: Bar interval (1m / 5m / 15m / 30m / 1H / 4H / 1D).+ interval: Bar interval (1m / 5m / 15m / 30m / 1H / 4H / 1D / 1W / 1M).explicit: Override ticker (e.g. "SPY" passed via config).loader: Loader of the configured data source. When given, thebenchmark is fetched through it first, falling back to@@ -200,24 +201,26 @@ def _fetch_benchmark(Tries the configured source's loader first (when given). Falls back toyfinance (single symbol, no auth) when no loader is given or it yieldsno data — unless ``allow_fallback`` is False (offline sources fail- closed instead of making a network request).+ closed instead of making a network request). Weekly and monthly bars are+ built from daily ones the way the strategy's are (#1479)."""+ fetch_as = source_interval(interval)if loader is not None:try:df = _extract_frame(- loader.fetch([ticker], start_date, end_date, interval=interval),+ loader.fetch([ticker], start_date, end_date, interval=fetch_as),ticker,)except Exception:df = pd.DataFrame()if not df.empty:- return df+ return resample_bars(df, interval)if not allow_fallback:return pd.DataFrame()- result = YfinanceLoader().fetch([ticker], start_date, end_date, interval=interval)- return _extract_frame(result, ticker)+ result = YfinanceLoader().fetch([ticker], start_date, end_date, interval=fetch_as)+ return resample_bars(_extract_frame(result, ticker), interval)def _extract_frame(result: Any, ticker: str) -> pd.DataFrame:diff --git a/agent/backtest/engines/_market_hooks.py b/agent/backtest/engines/_market_hooks.pyindex 071baefb4..e1b9239de 100644--- a/agent/backtest/engines/_market_hooks.py+++ b/agent/backtest/engines/_market_hooks.py@@ -316,13 +316,21 @@ _TIER_TABLE = [FUNDING_HOURS = {0, 8, 16}+#: Spans of the calendar-period bars the runner builds from daily ones+#: (#1479). A month is the mean one, 365.25 / 12 days, so a monthly bar settles+#: 91 funding periods whether the month has 28 days or 31.+_PERIOD_SPAN_HOURS = {"1W": 168.0, "1M": 730.5}++def _interval_span_hours(interval: str) -> float | None:"""Bar span in hours for a runner interval token, ``None`` when unknown.- The runner accepts only 1m/5m/15m/30m/1H/4H/1D, so ``m`` is minutes here- (there is no monthly token to confuse it with).+ ``1M`` is a month and ``1m`` a minute; the period tokens are looked up+ whole before any suffix is read, so the two never meet."""token = str(interval).strip()+ if token in _PERIOD_SPAN_HOURS:+ return _PERIOD_SPAN_HOURS[token]for suffix, scale in (("m", 1 / 60), ("H", 1.0), ("D", 24.0)):if token.endswith(suffix) and token[: -len(suffix)].isdigit():return int(token[: -len(suffix)]) * scalediff --git a/agent/backtest/engines/crypto.py b/agent/backtest/engines/crypto.pyindex 49fc75605..8bfcf6b40 100644--- a/agent/backtest/engines/crypto.py+++ b/agent/backtest/engines/crypto.py@@ -87,8 +87,9 @@ class CryptoEngine(BaseEngine):def _validate_strict_resolution(self, config: dict[str, Any]) -> None:if not self.perpetual_strict or self.default_leverage < 100:return- interval = str(config.get("interval", "1D")).strip().lower()- if interval not in {"1m", "5m", "15m", "30m", "1h"}:+ # Compared case-exact: lowercasing would read the monthly "1M" as "1m".+ interval = str(config.get("interval", "1D")).strip()+ if interval not in {"1m", "5m", "15m", "30m", "1H", "1h"}:raise ValueError("strict 100x requires a supported interval <= 1H ""(1m/5m/15m/30m/1H); 1H is only a resolution boundary, "diff --git a/agent/backtest/loaders/base.py b/agent/backtest/loaders/base.pyindex ce3f5abb5..25482d9b8 100644--- a/agent/backtest/loaders/base.py+++ b/agent/backtest/loaders/base.py@@ -208,6 +208,83 @@ DEFAULT_BACKOFF: tuple[float, ...] = (0.5, 1.5, 4.0)DEFAULT_MAX_RETRIES = 3+#: Bar sizes built from daily bars instead of asked of a loader (#1479). Every+#: source serves daily bars; few serve weekly or monthly, and those that do+#: disagree on where a week ends and how its bar is adjusted, so one resample+#: here keeps a weekly bar the same thing whichever source served the days. A+#: bar covers one calendar week (Monday to Sunday) or month.+RESAMPLED_INTERVALS = {"1W": "W-SUN", "1M": "M"}++#: Columns a period bar sums. ``vwap`` is weighted by volume (NaN without a+#: volume column), ``funding_rate`` (a per-settlement rate) is averaged,+#: ``open``/``high``/``low`` take their own rule, and every other column is a+#: level and takes the period's last value.+_SUMMED_COLUMNS = frozenset({"volume", "amount"})+++def source_interval(interval: str) -> str:+ """Return the bar size to request from a loader when serving ``interval``.++ Args:+ interval: The bar size the caller asked for.++ Returns:+ ``"1D"`` for a resampled interval, otherwise ``interval`` unchanged.+ """+ return "1D" if interval in RESAMPLED_INTERVALS else interval+++def resample_bars(frame: pd.DataFrame, interval: str) -> pd.DataFrame:+ """Aggregate daily bars into ``interval`` bars.++ Each bar is stamped with the last trading day inside its period, which is+ when its close becomes known, so a signal on it never sees a later day and+ a partial first or last period stays a bar dated inside that period.++ Args:+ frame: Daily bars on a ``DatetimeIndex``.+ interval: A key of :data:`RESAMPLED_INTERVALS`; any other interval+ returns ``frame`` unchanged.++ Returns:+ One row per period: first open, highest high, lowest low, last close,+ summed volume and amount, volume-weighted vwap, mean funding rate, last+ value of any other column. Frame attributes (quote currency) are kept.+ """+ if interval not in RESAMPLED_INTERVALS or frame.empty:+ return frame+ index = pd.DatetimeIndex(frame.index)+ naive = index.tz_localize(None) if index.tz is not None else index+ periods = naive.to_period(RESAMPLED_INTERVALS[interval])+ grouped = frame.groupby(periods)+ columns = {}+ for column in frame.columns:+ values = grouped[column]+ if column == "open":+ columns[column] = values.first()+ elif column == "high":+ columns[column] = values.max()+ elif column == "low":+ columns[column] = values.min()+ elif column in _SUMMED_COLUMNS:+ columns[column] = values.sum(min_count=1)+ elif column == "funding_rate":+ columns[column] = values.mean()+ elif column == "vwap":+ if "volume" in frame.columns:+ traded = (frame["vwap"] * frame["volume"]).groupby(periods).sum(min_count=1)+ columns[column] = traded / grouped["volume"].sum(min_count=1)+ else:+ columns[column] = values.first() * float("nan")+ else:+ columns[column] = values.last()+ out = pd.DataFrame(columns, columns=frame.columns)+ stamps = pd.Series(index, index=periods).groupby(level=0).max()+ out.index = pd.DatetimeIndex(stamps.loc[out.index], name=frame.index.name)+ out.attrs = dict(frame.attrs)+ return out++def positive_env_int(name: str, default: int) -> int:"""Read a positive integer env var, warning and falling back on invalid values."""raw = os.getenv(name) # noqa: env-gate — generic env var helperdiff --git a/agent/backtest/metrics.py b/agent/backtest/metrics.pyindex e84ebf11b..9f50d2ffa 100644--- a/agent/backtest/metrics.py+++ b/agent/backtest/metrics.py@@ -140,6 +140,10 @@ _BARS_PER_DAY = {},}+# Weekly and monthly bars count calendar periods, whatever the market's+# trading days: every week and every month holds one bar (#1479).+_CALENDAR_BARS_PER_YEAR = {"1W": 52, "1M": 12}+# Runner/loaders also emit these aliases; map them onto the table keys above._SOURCE_ALIASES = {"yahoo": "yfinance", "binance": "ccxt"}@@ -149,10 +153,15 @@ def _normalize_interval(interval: str) -> str:Minute bars stay lowercase (``1m``); hour/day use the uppercase keys thetable already stores (``1H`` / ``4H`` / ``1D``). Loaders accept both cases- after the interval-map fixes; annualisation must too.+ after the interval-map fixes; annualisation must too. ``1M`` is a month and+ is matched before the case fold, which would read it as a minute (#1479)."""token = str(interval or "1D").strip()+ if token == "1M":+ return tokenlower = token.lower()+ if lower == "1w":+ return "1W"if lower in ("1m", "5m", "15m", "30m"):return lowerif lower in ("1h", "4h", "1d"):@@ -164,8 +173,9 @@ def calc_bars_per_year(interval: str = "1D", source: str = "tushare") -> int:"""Number of bars per year for annualisation.Args:- interval: Bar size (1m / 5m / 15m / 30m / 1H / 4H / 1D), case-insensitive- like loaders accept (``1h`` → ``1H``, ``4h`` → ``4H``, ``1d`` → ``1D``).+ interval: Bar size (1m / 5m / 15m / 30m / 1H / 4H / 1D / 1W / 1M),+ case-insensitive like loaders accept (``1h`` → ``1H``, ``4h`` →+ ``4H``, ``1d`` → ``1D``) except ``1M``, which is a month.source: Data source (any VALID_SOURCES entry). Defaults to 252 days, 1 bar/daywhen source is missing from the table.@@ -173,6 +183,8 @@ def calc_bars_per_year(interval: str = "1D", source: str = "tushare") -> int:Bars per year."""interval_key = _normalize_interval(interval)+ if interval_key in _CALENDAR_BARS_PER_YEAR:+ return _CALENDAR_BARS_PER_YEAR[interval_key]source_key = str(source or "").strip().lower()source_key = _SOURCE_ALIASES.get(source_key, source_key)trading_days = _TRADING_DAYS.get(source_key, 252)diff --git a/agent/backtest/runner.py b/agent/backtest/runner.pyindex a62d14b3a..b151f0446 100644--- a/agent/backtest/runner.py+++ b/agent/backtest/runner.py@@ -1,7 +1,8 @@"""Fixed backtest entrypoint: read config.json, select loader by source, import signal_engine, run engine.Supports ``source="auto"`` to route codes to loaders by symbol format.-Supports ``interval`` for bar size (1m/5m/15m/30m/1H/4H/1D, default 1D).+Supports ``interval`` for bar size (1m/5m/15m/30m/1H/4H/1D/1W/1M, default 1D;+1W and 1M are built from daily bars, see ``loaders.base.resample_bars``).Supports ``engine`` for backtest engine (daily/options, default daily).Usage: ``python -m backtest.runner <run_dir>``@@ -32,7 +33,12 @@ from backtest.loaders.registry import (price_caliber,resolve_loader,)-from backtest.loaders.base import NoAvailableSourceError, validate_ohlc+from backtest.loaders.base import (+ NoAvailableSourceError,+ resample_bars,+ source_interval,+ validate_ohlc,+)# Symbol classification lives in ``_market_hooks`` so runner.py and# composite.py share a single source of truth (audit-2026-05-18 B1+C1+C2).# ``_detect_market`` is also re-exported here for back-compat with@@ -48,7 +54,7 @@ from backtest.rebalance_mask import RebalanceMask, validate_rebalance_masklogger = logging.getLogger(__name__)-_VALID_INTERVALS = {"1m", "5m", "15m", "30m", "1H", "4H", "1D"}+_VALID_INTERVALS = {"1m", "5m", "15m", "30m", "1H", "4H", "1D", "1W", "1M"}_VALID_ENGINES = {"daily", "options"}_PRICE_PANEL_COLUMNS = ("open", "high", "low", "close", "volume", "vwap", "amount")_FUND_PREFIX = "fund:"@@ -1320,6 +1326,10 @@ _INTERVAL_SECONDS: dict[str, float] = {"1H": 3_600.0,"4H": 14_400.0,"1D": 86_400.0,+ "1W": 604_800.0,+ # A mean month (365.25 / 12 days): a calendar month runs 28 to 31, so a+ # monthly series' median spacing sits within 1.1x of it either way.+ "1M": 2_629_800.0,}#: How far the served bar spacing may sit from the declared interval's spacing@@ -1334,10 +1344,11 @@ _SPACING_MISMATCH_RATIO = 1.5#: (``[1, 1, 3]`` -> 1 day); two do not (``[1, 3]`` -> 2 days)._MIN_BARS_FOR_SPACING = 4-#: Spacing at least this many times a day is a weekly or monthly series, not a-#: daily one with gaps: a daily index over a holiday week measures a median of-#: two or three days, a weekly file seven. Such a series has no trading-day-#: table to look up and needs none -- its bars per year is the calendar's.+#: Spacing at least this many times a day that matches no supported interval+#: (a fortnightly or quarterly file) is a coarse series, not a daily one with+#: gaps: a daily index over a holiday week measures a median of two or three+#: days. Such a series has no trading-day table to look up and needs none --+#: its bars per year is the calendar's._WIDER_THAN_DAILY_RATIO = 4.0_CALENDAR_YEAR_SECONDS = 365.25 * 86_400.0@@ -1394,8 +1405,9 @@ def _annualisation_bars(:func:`~backtest.metrics.calc_bars_per_year` -- looked up with the intervalthe spacing actually matches -- so the per-source trading-day table keepsproducing the number and a run card never picks up a window-dependent one.- Bars spaced wider than any supported interval (a weekly or monthly file)- are annualised from the calendar instead, 52 for a weekly series; a+ A weekly or monthly file declared ``1D`` matches ``1W`` / ``1M`` (52 / 12).+ Bars spaced wider than daily that match no supported interval (a quarterly+ file) are annualised from the calendar instead, 4 for a quarterly series; aspacing that matches nothing in either direction keeps the declaration.Args:@@ -1723,7 +1735,10 @@ def fetch_data_map(config: dict) -> DataFetchResult:config = copy.deepcopy(config)source = str(config.get("source") or "tushare")codes = list(config.get("codes") or [])- interval = str(config.get("interval") or "1D")+ # Weekly and monthly bars are built from daily ones after the fetch, so+ # every loader below is asked for daily bars (#1479).+ requested_interval = str(config.get("interval") or "1D")+ interval = source_interval(requested_interval)# ``local:`` picks the loader; the instrument is the bare symbol. Everything# downstream (engine, signals, artifacts, run card) sees the bare symbol, so@@ -1854,7 +1869,10 @@ def fetch_data_map(config: dict) -> DataFetchResult:f"incomplete data for source={primary_source}; missing symbols: {missing}")- data_map = _sanitize_data_map(data_map)+ data_map = {+ code: resample_bars(frame, requested_interval)+ for code, frame in _sanitize_data_map(data_map).items()+ }caliber_stamps = {code: stamp for code, stamp in caliber_stamps.items() if code in data_map}diff --git a/agent/mcp_server.py b/agent/mcp_server.pyindex 3a3e5fed0..92b31f7d8 100644--- a/agent/mcp_server.py+++ b/agent/mcp_server.py@@ -1809,7 +1809,7 @@ def get_market_data(end_date: End date (YYYY-MM-DD).source: Data source. Prefer ``auto``; ``yahoo``/``yfinance`` serveCanada, US, and HK equities.- interval: Bar size (1m/5m/15m/30m/1H/4H/1D, default "1D").+ interval: Bar size (1m/5m/15m/30m/1H/4H/1D/1W/1M, default "1D"; 1W and 1M are built from daily bars).max_rows: Per-symbol row cap (default 250) so the response stayswithin the MCP token budget. A symbol exceeding it returns aneven-stride downsample (every step-th bar, last bar pinned)diff --git a/agent/src/api/attribution_core.py b/agent/src/api/attribution_core.pyindex f4b3995a1..fe2093dc7 100644--- a/agent/src/api/attribution_core.py+++ b/agent/src/api/attribution_core.py@@ -51,6 +51,7 @@ _ATTRIBUTION_BARS_PER_YEAR_BY_INTERVAL = {"1d": 252,"d": 252,"daily": 252,+ "1w": 52,"1wk": 52,"w": 52,"weekly": 52,@@ -95,9 +96,11 @@ def _attribution_bars_per_year(interval: Any) -> int:"""Infer the annualization factor from the run's bar interval label."""if not interval:return _ATTRIBUTION_DEFAULT_BARS_PER_YEAR- return _ATTRIBUTION_BARS_PER_YEAR_BY_INTERVAL.get(- str(interval).strip().lower(), _ATTRIBUTION_DEFAULT_BARS_PER_YEAR- )+ label = str(interval).strip()+ # The runner's monthly token; lower-cased it would read as one minute.+ if label == "1M":+ return 12+ return _ATTRIBUTION_BARS_PER_YEAR_BY_INTERVAL.get(label.lower(), _ATTRIBUTION_DEFAULT_BARS_PER_YEAR)def _attribution_downsample(diff --git a/agent/src/market_data.py b/agent/src/market_data.pyindex 3aa1cd9b6..ec05d88ef 100644--- a/agent/src/market_data.py+++ b/agent/src/market_data.py@@ -203,7 +203,7 @@ def fetch_market_data(consumers must read this field instead of assuming a unit."""from backtest.engines._market_hooks import _detect_market- from backtest.loaders.base import NoAvailableSourceError+ from backtest.loaders.base import NoAvailableSourceError, resample_bars, source_intervalfrom backtest.loaders.registry import (FALLBACK_CHAINS,_NO_NETWORK_FALLBACK_SOURCES,@@ -315,7 +315,14 @@ def fetch_market_data(continuetry:loader = loader_cls()- partial = loader.fetch(remaining, start_date, end_date, interval=interval)+ # Weekly and monthly bars are built from daily ones (#1479).+ partial = loader.fetch(+ remaining, start_date, end_date, interval=source_interval(interval)+ )+ partial = {+ code: resample_bars(frame, interval) if hasattr(frame, "groupby") else frame+ for code, frame in (partial or {}).items()+ }except Exception as exc: # noqa: BLE001 — contained per-symbol fallbacklogger.error("market-data loader %r failed for %s; trying next source in chain: %s",diff --git a/agent/src/skills/strategy-generate/SKILL.md b/agent/src/skills/strategy-generate/SKILL.mdindex e4829cc03..fd1bb8132 100644--- a/agent/src/skills/strategy-generate/SKILL.md+++ b/agent/src/skills/strategy-generate/SKILL.md@@ -138,7 +138,7 @@ Self-check after writing `signal_engine.py`:- `source`: `"auto"` (recommended, auto-select by code format) / `"tushare"` / `"yfinance"` / `"okx"` / `"akshare"` / `"ccxt"`- `"auto"` supports mixed instruments. For example, `["000001.SZ", "BTC-USDT"]` will be automatically routed to `tushare` and `okx`- Futures codes (e.g. `"IF2406.CFFEX"`, `"ESZ4"`) and forex pairs (e.g. `"EUR/USD"`) are also auto-routed-- `interval`: candlestick interval, default `"1D"`. Supported values: `"1m"` / `"5m"` / `"15m"` / `"30m"` / `"1H"` / `"4H"` / `"1D"`+- `interval`: candlestick interval, default `"1D"`. Supported values: `"1m"` / `"5m"` / `"15m"` / `"30m"` / `"1H"` / `"4H"` / `"1D"` / `"1W"` / `"1M"` (weekly and monthly bars are built from daily ones; `"1M"` is a month, `"1m"` a minute)- The annualization factor for minute backtests is inferred automatically from `source` (252 trading days for China A-shares, 365 calendar days for crypto)- Minute backtests can be very data-heavy. Recommended limits are no more than 30 days for `1m`, or 1 year for `1H`- `warmup_bars`: how many leading bars exist only to prime the indicators. They are loaded and fed to `SignalEngine.generate()`, then excluded from trades, the equity curve, the benchmark and every metric. Default `0` grades the whole loaded window.diff --git a/agent/src/tools/market_data_tool.py b/agent/src/tools/market_data_tool.pyindex d3504e9cf..3a07edd18 100644--- a/agent/src/tools/market_data_tool.py+++ b/agent/src/tools/market_data_tool.py@@ -14,34 +14,26 @@ from backtest.loaders.registry import VALID_SOURCESfrom backtest.runner import _VALID_INTERVALS# Canonical-case lookup. ``_VALID_INTERVALS`` mixes cases ("1m" minutes vs-# "1H" hours), so a plain ``.upper()`` fold is unsafe: it maps the universal-# monthly spelling "1M" onto "1m" (one minute), silently answering a monthly-# question with minute bars (#1480). ``_canonicalize_interval`` resolves a-# case-exact match first and only then falls back to this fold for the-# unambiguous case variants ("1d" -> "1D", "30M" -> "30m").-_INTERVAL_CANON = {v.upper(): v for v in _VALID_INTERVALS}--# Spellings that read as a request for a bar size this tool does not serve and-# must never be case-folded onto a minute interval. "1M" is the near-universal-# monthly convention (pandas ``resample('1M')``, ccxt / TradingView "1M"); "1W"-# is weekly. Folding "1M" -> "1m" (one minute) is the #1480 footgun: the caller-# receives minute bars labelled as the answer to a monthly question. These are-# rejected with a pointed message instead of being silently mis-served. The-# minute spellings "5M" / "15M" / "30M" deliberately keep folding to "5m" /-# "15m" / "30m" — multi-month bars are not a convention anyone requests, and-# that fold is the documented behaviour pinned by the regression tests.-_UNSUPPORTED_PERIOD_SPELLINGS = {"1M": "one month", "1W": "one week"}+# "1M" months, "1H" hours), so a plain ``.upper()`` fold is unsafe: it maps+# "1m" and "1M" onto one key, and before monthly bars existed it answered a+# monthly question with minute bars (#1480). A case-exact match wins first in+# ``_canonicalize_interval``; this fold only serves the unambiguous variants+# ("1d" -> "1D", "30M" -> "30m", "1w" -> "1W"), and a minute token whose upper+# case is itself an interval ("1m" -> "1M") is left out of it.+_INTERVAL_CANON = {+ v.upper(): v for v in _VALID_INTERVALS if v.upper() == v or v.upper() not in _VALID_INTERVALS+}+# The yfinance spellings the technical-indicator tool has always documented.+_INTERVAL_CANON.update({"1WK": "1W", "1MO": "1M"})def _canonicalize_interval(raw: str) -> str | None:"""Resolve a user interval spelling to the canonical loader form.A case-exact match against ``_VALID_INTERVALS`` wins first, so the minute- interval ``"1m"`` and the monthly spelling ``"1M"`` are never conflated by- the case fold (#1480). Falls back to ``_INTERVAL_CANON`` for unambiguous- case variants (``"1d"`` -> ``"1D"``, ``"30M"`` -> ``"30m"``). Month/week- spellings that are not served resolve to ``None`` rather than folding onto- a minute interval.+ interval ``"1m"`` and the monthly ``"1M"`` are never conflated by the case+ fold (#1480). Falls back to ``_INTERVAL_CANON`` for unambiguous case+ variants (``"1d"`` -> ``"1D"``, ``"30M"`` -> ``"30m"``, ``"1wk"`` -> ``"1W"``).Args:raw: Interval string as supplied by the caller.@@ -52,10 +44,7 @@ def _canonicalize_interval(raw: str) -> str | None:token = raw.strip()if token in _VALID_INTERVALS:return token- folded = token.upper()- if folded in _UNSUPPORTED_PERIOD_SPELLINGS:- return None- return _INTERVAL_CANON.get(folded)+ return _INTERVAL_CANON.get(token.upper())# Source allow-list derived from the shared loader registry (the same set the@@ -148,7 +137,10 @@ class MarketDataTool(BaseTool):},"interval": {"type": "string",- "description": "Bar size, e.g. 1D, 1H, 4H, 30m.",+ "description": (+ "Bar size: 1m/5m/15m/30m/1H/4H/1D, or 1W/1M for weekly/monthly "+ "bars built from daily ones (1M is a month, 1m a minute)."+ ),"default": "1D",},"max_rows": {@@ -204,26 +196,11 @@ class MarketDataTool(BaseTool):if not isinstance(interval, str):return _error("interval must be a string like '1D', '1H', '4H', '30m'")interval_token = interval.strip()- # Reject the month/week spellings the case fold would otherwise map onto- # a minute interval: "1M" (one month) must never silently become "1m"- # (one minute) (#1480). A case-exact served spelling is allowed through- # first, so this stays correct if monthly/weekly bars are ever added to- # ``_VALID_INTERVALS`` (#1479).- folded = interval_token.upper()- if (- interval_token not in _VALID_INTERVALS- and folded in _UNSUPPORTED_PERIOD_SPELLINGS- ):- return _error(- f"interval {interval_token!r} ({_UNSUPPORTED_PERIOD_SPELLINGS[folded]}) "- f"is not supported; supported: {sorted(_VALID_INTERVALS)}. "- f"Note '1m' (lowercase) is one minute."- )normalized_interval = _canonicalize_interval(interval_token)if normalized_interval is None:return _error(- f"interval must be one of {sorted(_VALID_INTERVALS)} "- f"(case-insensitive); got {interval!r}"+ f"interval must be one of {sorted(_VALID_INTERVALS)} (case-insensitive, "+ f"except that 1m is one minute and 1M one month); got {interval!r}")max_rows = kwargs.get("max_rows", DEFAULT_MAX_ROWS)diff --git a/agent/src/tools/technical_indicator_tool.py b/agent/src/tools/technical_indicator_tool.pyindex baf97f281..e63d85211 100644--- a/agent/src/tools/technical_indicator_tool.py+++ b/agent/src/tools/technical_indicator_tool.py@@ -16,6 +16,7 @@ import pandas as pdfrom src.agent.tools import BaseToolfrom src.market_data import fetch_market_data+from src.tools.market_data_tool import _canonicalize_intervallogger = logging.getLogger(__name__)@@ -30,6 +31,10 @@ _SMA_PERIODS = (20, 50, 200)_EMA_PERIOD = 20_DEFAULT_LOOKBACK = 200_MAX_LOOKBACK = 500+#: Calendar days fetched per requested bar. Two covers weekends and holidays+#: for daily bars; a weekly or monthly bar needs its whole period, or 200+#: weekly bars would be asked for over 400 days and come back as 57 (#1479).+_CALENDAR_DAYS_PER_BAR = {"1W": 7, "1M": 31}_CLOSE_KEYS = ("close", "Close", "CLOSE", "adj_close")@@ -206,11 +211,18 @@ class TechnicalIndicatorTool(BaseTool):def execute(self, **kwargs: Any) -> str:symbol = str(kwargs.get("symbol", "")).strip()- interval = str(kwargs.get("interval", "1d")).strip()+ requested_interval = str(kwargs.get("interval", "1d")).strip()lookback_raw = kwargs.get("lookback", _DEFAULT_LOOKBACK)if not symbol:return json.dumps({"ok": False, "error": "symbol is required"})+ # The documented 1d / 1wk / 1mo spellings used to reach the loaders+ # verbatim, and most of them know neither weekly spelling.+ interval = _canonicalize_interval(requested_interval)+ if interval is None:+ return json.dumps(+ {"ok": False, "error": f"unsupported interval {requested_interval!r}; use 1d, 1wk or 1mo"}+ )try:lookback = int(lookback_raw)@@ -220,7 +232,8 @@ class TechnicalIndicatorTool(BaseTool):# Fetch enough bars to cover the longest indicator window + buffer.end_date = datetime.now().strftime("%Y-%m-%d")- start_date = (datetime.now() - timedelta(days=lookback * 2)).strftime("%Y-%m-%d")+ days = lookback * _CALENDAR_DAYS_PER_BAR.get(interval, 2)+ start_date = (datetime.now() - timedelta(days=days)).strftime("%Y-%m-%d")try:data = fetch_market_data(diff --git a/agent/tests/test_cross_market_annualization.py b/agent/tests/test_cross_market_annualization.pyindex 27c9557ae..f0b8203c1 100644--- a/agent/tests/test_cross_market_annualization.py+++ b/agent/tests/test_cross_market_annualization.py@@ -251,14 +251,14 @@ class TestSingleMarketAnnualisationChecksTheServedData:)assert _annualisation_bars("1D", "tushare", data, ["600519.SH"]) == 252- # --- spacing wider than any supported interval (review point 2) ---+ # --- weekly / monthly files, and spacing wider than any supported interval ---@pytest.mark.parametrize("declared", ["1D", "1H"])- def test_weekly_bars_are_annualised_from_the_calendar(self, declared, caplog):- """A weekly file has no trading-day table and needs none: 52 a year.+ def test_a_weekly_file_is_annualised_as_weekly(self, declared, caplog):+ """A weekly file declared finer is read as ``1W``: 52 a year.- Keeping the declaration was the same bug one step coarser -- a weekly- file declared ``1H`` annualised at 1,764 bars a year.+ Keeping the declaration was the bug -- a weekly file declared ``1H``+ annualised at 1,764 bars a year."""from backtest.runner import _annualisation_bars@@ -267,7 +267,7 @@ class TestSingleMarketAnnualisationChecksTheServedData:resolved = _annualisation_bars(declared, "tushare", data, ["600519.SH"])assert resolved == 52- assert any("wider than any supported interval" in r.getMessage() for r in caplog.records)+ assert any("annualising as 1W (52 bars/year)" in r.getMessage() for r in caplog.records)def test_monthly_bars_are_twelve_a_year(self):from backtest.runner import _annualisation_bars@@ -275,6 +275,30 @@ class TestSingleMarketAnnualisationChecksTheServedData:data = self._frame(pd.date_range("2020-01-01", periods=48, freq="MS"))assert _annualisation_bars("1D", "yahoo", data, ["600519.SH"]) == 12+ @pytest.mark.parametrize(("declared", "freq"), [("1W", "W-FRI"), ("1M", "BME")])+ def test_a_declared_weekly_or_monthly_run_keeps_its_count_silently(self, declared, freq, caplog):+ """Weekly and monthly are intervals now (#1479): no mismatch report."""+ from backtest.runner import _annualisation_bars++ data = self._frame(pd.date_range("2020-01-01", periods=60, freq=freq))+ with caplog.at_level("WARNING", logger="backtest.runner"):+ resolved = _annualisation_bars(declared, "tushare", data, ["600519.SH"])++ assert resolved == {"1W": 52, "1M": 12}[declared]+ assert caplog.records == []++ def test_a_quarterly_file_is_annualised_from_the_calendar(self, caplog):+ """Wider than every supported interval: four bars a year, from the+ spacing, since no interval has a count to look up."""+ from backtest.runner import _annualisation_bars++ data = self._frame(pd.date_range("2015-03-31", periods=40, freq="QE"))+ with caplog.at_level("WARNING", logger="backtest.runner"):+ resolved = _annualisation_bars("1D", "tushare", data, ["600519.SH"])++ assert resolved == 4+ assert any("wider than any supported interval" in r.getMessage() for r in caplog.records)+def test_a_daily_series_over_a_holiday_week_is_not_read_as_weekly(self, caplog):"""Five daily bars around Christmas measure a two-day median: thedeclaration stands, the report states the spacings, and the count isdiff --git a/agent/tests/test_crypto_engine.py b/agent/tests/test_crypto_engine.pyindex 888d29ec7..0fd8adeae 100644--- a/agent/tests/test_crypto_engine.py+++ b/agent/tests/test_crypto_engine.py@@ -557,7 +557,8 @@ class TestHistoricalFundingRate:class TestStrictPerpetualLifecycle:- @pytest.mark.parametrize("interval", ["3m", "60m", "4H", "1D"])+ # "1M" is a month: the old lower-cased comparison read it as "1m" (#1479).+ @pytest.mark.parametrize("interval", ["3m", "60m", "4H", "1D", "1W", "1M"])def test_strict_100x_rejects_unsupported_or_coarse_intervals(self, interval: str) -> None:diff --git a/agent/tests/test_market_data_tool.py b/agent/tests/test_market_data_tool.pyindex 0ffdb83b8..3b3de01da 100644--- a/agent/tests/test_market_data_tool.py+++ b/agent/tests/test_market_data_tool.py@@ -465,36 +465,35 @@ def test_market_data_tool_accepts_minute_intervals():assert [c["interval"] for c in calls] == ["1m", "5m", "15m", "30m", "30m", "1H", "1D"]-def test_market_data_tool_rejects_month_and_week_spellings():- """'1M' (one month) must never case-fold to '1m' (one minute) (#1480)."""+def test_market_data_tool_serves_month_and_week_spellings():+ """'1M' is one month and '1m' one minute; neither folds onto the other+ (#1480), and weekly/monthly bars reach the fetch as 1W / 1M (#1479)."""import src.tools.market_data_tool as modfrom unittest import mockwith mock.patch.object(mod, "fetch_market_data_json", return_value="{}") as fetch:- for interval, meaning in (("1M", "one month"), ("1W", "one week")):- out = json.loads(- mod.MarketDataTool().execute(- codes=["AAPL.US"],- start_date="2026-08-20",- end_date="2026-08-21",- interval=interval,- )+ for interval, canonical in (+ ("1M", "1M"), ("1mo", "1M"), ("1W", "1W"), ("1w", "1W"), ("1wk", "1W"), ("1m", "1m")+ ):+ fetch.reset_mock()+ mod.MarketDataTool().execute(+ codes=["AAPL.US"],+ start_date="2026-08-20",+ end_date="2026-08-21",+ interval=interval,)- assert out["ok"] is False- assert meaning in out["error"]- assert "one minute" in out["error"]- assert interval in out["error"]- # Silence is the failure mode (#1480): the fold must never reach a loader.- fetch.assert_not_called()+ assert fetch.call_args.kwargs["interval"] == canonical, interval-def test_canonicalize_interval_keeps_minute_and_refuses_month():- """_canonicalize_interval resolves '1m' but refuses '1M'/'1W' (#1480)."""- from src.tools.market_data_tool import _canonicalize_interval+def test_canonicalize_interval_keeps_minute_and_month_apart():+ """_canonicalize_interval never maps '1m' and '1M' onto each other (#1480)."""+ from src.tools.market_data_tool import _INTERVAL_CANON, _canonicalize_intervalassert _canonicalize_interval("1m") == "1m"- assert _canonicalize_interval("1M") is None- assert _canonicalize_interval("1W") is None+ assert _canonicalize_interval("1M") == "1M"+ assert _canonicalize_interval("1W") == "1W"assert _canonicalize_interval("1d") == "1D"assert _canonicalize_interval("30M") == "30m"assert _canonicalize_interval("1h") == "1H"+ assert _canonicalize_interval("2W") is None+ assert _INTERVAL_CANON["1M"] == "1M"diff --git a/agent/tests/test_weekly_monthly_bars.py b/agent/tests/test_weekly_monthly_bars.pynew file mode 100644index 000000000..b9836e7d7--- /dev/null+++ b/agent/tests/test_weekly_monthly_bars.py@@ -0,0 +1,211 @@+"""Weekly and monthly bars, built from daily ones at the fetch boundary (#1479)."""++from __future__ import annotations++import json+from datetime import datetime, timedelta++import numpy as np+import pandas as pd+import pytest++from backtest import runner+from backtest.benchmark import _fetch_benchmark+from backtest.engines._market_hooks import _interval_span_hours+from backtest.loaders.base import resample_bars, source_interval+from backtest.metrics import calc_bars_per_year+from src.api.attribution_core import _attribution_bars_per_year+from src.market_data import fetch_market_data+++def _daily(start: str, end: str, *, freq: str = "B") -> pd.DataFrame:+ index = pd.DatetimeIndex(pd.date_range(start, end, freq=freq), name="trade_date")+ step = np.arange(len(index), dtype=float)+ return pd.DataFrame(+ {+ "open": 100.0 + step,+ "high": 101.0 + step,+ "low": 99.0 + step,+ "close": 100.5 + step,+ "volume": 10.0 + step,+ },+ index=index,+ )+++class TestResampleBars:+ def test_a_week_runs_monday_to_sunday_and_is_stamped_with_its_last_trading_day(self):+ frame = _daily("2024-01-03", "2024-01-19") # Wed 3rd .. Fri 19th+ weekly = resample_bars(frame, "1W")++ assert list(weekly.index.strftime("%Y-%m-%d")) == ["2024-01-05", "2024-01-12", "2024-01-19"]+ first = frame.loc["2024-01-03":"2024-01-05"]+ assert weekly.iloc[0]["open"] == first["open"].iloc[0]+ assert weekly.iloc[0]["high"] == first["high"].max()+ assert weekly.iloc[0]["low"] == first["low"].min()+ assert weekly.iloc[0]["close"] == first["close"].iloc[-1]+ assert weekly.iloc[0]["volume"] == first["volume"].sum()++ def test_a_seven_day_market_closes_its_week_on_sunday(self):+ weekly = resample_bars(_daily("2024-01-01", "2024-01-14", freq="D"), "1W")+ assert list(weekly.index.strftime("%a %Y-%m-%d")) == ["Sun 2024-01-07", "Sun 2024-01-14"]++ def test_a_month_is_a_calendar_month_and_a_partial_last_one_stays_inside_it(self):+ monthly = resample_bars(_daily("2024-01-15", "2024-03-06"), "1M")++ assert list(monthly.index.strftime("%Y-%m-%d")) == ["2024-01-31", "2024-02-29", "2024-03-06"]+ assert monthly.loc["2024-02-29", "open"] == _daily("2024-01-15", "2024-03-06").loc["2024-02-01", "open"]++ def test_vwap_is_weighted_by_volume_and_funding_is_averaged(self):+ frame = _daily("2024-01-01", "2024-01-02")+ frame["vwap"] = [10.0, 20.0]+ frame["volume"] = [1.0, 3.0]+ frame["funding_rate"] = [0.0001, 0.0003]+ frame["pe"] = [5.0, 6.0]++ bar = resample_bars(frame, "1W").iloc[0]++ assert bar["vwap"] == pytest.approx(17.5)+ assert bar["funding_rate"] == pytest.approx(0.0002)+ assert bar["pe"] == 6.0++ def test_a_vwap_without_volume_is_unknown_not_the_last_day(self):+ frame = _daily("2024-01-01", "2024-01-02").drop(columns="volume")+ frame["vwap"] = [10.0, 20.0]+ assert np.isnan(resample_bars(frame, "1W").iloc[0]["vwap"])++ def test_missing_volume_stays_missing(self):+ frame = _daily("2024-01-01", "2024-01-05")+ frame["volume"] = np.nan+ assert np.isnan(resample_bars(frame, "1W").iloc[0]["volume"])++ def test_timezone_and_attributes_are_kept(self):+ frame = _daily("2024-01-01", "2024-01-10", freq="D")+ frame.index = frame.index.tz_localize("Asia/Shanghai")+ frame.attrs["quote_currency"] = "CNY"++ weekly = resample_bars(frame, "1W")++ assert str(weekly.index.tz) == "Asia/Shanghai"+ assert weekly.attrs == {"quote_currency": "CNY"}++ def test_resampling_twice_changes_nothing(self):+ weekly = resample_bars(_daily("2024-01-01", "2024-03-01"), "1W")+ pd.testing.assert_frame_equal(resample_bars(weekly, "1W"), weekly)++ @pytest.mark.parametrize("interval", ["1D", "1H", "1m"])+ def test_other_intervals_pass_through(self, interval):+ frame = _daily("2024-01-01", "2024-01-10")+ assert resample_bars(frame, interval) is frame+ assert source_interval(interval) == interval++ def test_the_period_intervals_are_fetched_daily(self):+ assert source_interval("1W") == source_interval("1M") == "1D"+++class _RecordingLoader:+ name = "yahoo"+ asked: list[str] = []++ def is_available(self) -> bool:+ return True++ def fetch(self, codes, start_date, end_date, fields=None, interval="1D"): # noqa: ANN001, ANN201+ type(self).asked.append(interval)+ return {code: _daily("2024-01-01", "2024-03-29") for code in codes}+++def recording_loader():+ _RecordingLoader.asked = []+ return _RecordingLoader+++class TestFetchPaths:+ @pytest.mark.parametrize(("interval", "bars"), [("1W", 13), ("1M", 3)])+ def test_a_backtest_asks_for_daily_bars_and_gets_period_bars(+ self, monkeypatch, recording_loader, interval, bars+ ):+ monkeypatch.setattr(runner, "_get_loader", lambda source: recording_loader)+ result = runner.fetch_data_map(+ {"source": "yahoo", "codes": ["AAPL.US"], "start_date": "2024-01-01", "end_date": "2024-03-29", "interval": interval}+ )++ assert recording_loader.asked == ["1D"]+ assert len(result.data_map["AAPL.US"]) == bars++ def test_the_auto_route_asks_for_daily_bars_too(self, monkeypatch, recording_loader):+ monkeypatch.setattr(runner, "resolve_loader", lambda market: recording_loader())+ monkeypatch.setattr(runner, "LOADER_REGISTRY", {})+ result = runner.fetch_data_map(+ {"source": "auto", "codes": ["AAPL.US"], "start_date": "2024-01-01", "end_date": "2024-03-29", "interval": "1M"}+ )++ assert recording_loader.asked == ["1D"]+ assert list(result.data_map["AAPL.US"].index.strftime("%Y-%m-%d")) == ["2024-01-31", "2024-02-29", "2024-03-29"]++ def test_get_market_data_asks_for_daily_bars(self, recording_loader):+ out = fetch_market_data(+ codes=["AAPL.US"],+ start_date="2024-01-01",+ end_date="2024-03-29",+ source="yahoo",+ interval="1M",+ max_rows=0,+ loader_resolver=lambda source: recording_loader,+ )++ assert recording_loader.asked == ["1D"]+ rows = out["AAPL.US"]+ assert [row["trade_date"][:10] for row in rows] == ["2024-01-31", "2024-02-29", "2024-03-29"]++ def test_the_benchmark_is_built_the_same_way(self, recording_loader):+ frame = _fetch_benchmark("SPY", "2024-01-01", "2024-03-29", "1W", loader=recording_loader())++ assert recording_loader.asked == ["1D"]+ assert len(frame) == 13++ def test_the_config_accepts_both(self):+ for interval in ("1W", "1M"):+ runner.BacktestConfigSchema(codes=["AAPL.US"], start_date="2024-01-01", end_date="2024-03-29", interval=interval)+ with pytest.raises(ValueError):+ runner.BacktestConfigSchema(codes=["AAPL.US"], start_date="2024-01-01", end_date="2024-03-29", interval="1w")+++class TestAnnualisation:+ @pytest.mark.parametrize("source", ["tushare", "yahoo", "okx", "mt5"])+ def test_a_week_and_a_month_are_calendar_counts(self, source):+ assert calc_bars_per_year("1W", source) == 52+ assert calc_bars_per_year("1w", source) == 52+ assert calc_bars_per_year("1M", source) == 12++ def test_a_minute_is_still_a_minute(self):+ assert calc_bars_per_year("1m", "yahoo") == 252 * 390++ def test_the_funding_span_of_a_period_bar(self):+ assert _interval_span_hours("1W") == 168.0+ assert _interval_span_hours("1M") == 730.5+ assert _interval_span_hours("1m") == pytest.approx(1 / 60)++ def test_attribution_reads_1M_as_a_month(self):+ assert _attribution_bars_per_year("1M") == 12+ assert _attribution_bars_per_year("1m") == 98280+ assert _attribution_bars_per_year("1W") == 52+++def test_the_indicator_tool_fetches_whole_periods(monkeypatch):+ import src.tools.technical_indicator_tool as mod++ seen = {}++ def _fake_fetch(**kwargs):+ seen.update(kwargs)+ return {kwargs["codes"][0]: _daily("2020-01-01", "2024-03-29")}++ monkeypatch.setattr(mod, "fetch_market_data", _fake_fetch)+ out = json.loads(mod.TechnicalIndicatorTool().execute(symbol="AAPL.US", interval="1wk", lookback=100))++ assert seen["interval"] == "1W"+ start = datetime.strptime(seen["start_date"], "%Y-%m-%d")+ assert datetime.now() - start >= timedelta(days=699)+ assert out["interval"] == "1W"