repo
stringclasses
454 values
file_path
stringlengths
5
201
extension
stringclasses
1 value
content
stringlengths
8
509k
num_lines
int64
3
16.9k
size_bytes
int64
8
511k
Vibe-Trading
agent/backtest/engines/global_equity.py
.py
"""Global equity (US / HK / Canada) backtest engine. Market rules: US: - T+0, long/short allowed - Zero commission (retail brokers) - Fractional shares supported (round to 0.01) - Low slippage (high liquidity) HK: - T+0, long/short allowed - Stamp tax 0.1% bilateral + levies - Lot-size ...
124
4,961
Vibe-Trading
agent/backtest/engines/base.py
.py
"""Base backtest engine with shared bar-by-bar execution loop. All market engines inherit from BaseEngine and override market-rule methods. The shared run_backtest() handles: data loading → signal generation → pre-compute target weights (with optimizer) → bar-by-bar execution with market rule enforcement → metrics → a...
1,812
72,548
Vibe-Trading
agent/backtest/engines/india_equity.py
.py
"""India equity (NSE / BSE) backtest engine. Models the Indian cash-equity **delivery** segment on daily bars. Intraday (MIS) mechanics are not represented by a daily-bar engine, so the defaults reflect overnight delivery rules; the knobs below let advanced users approximate intraday behaviour. Market rules: - T+1 ...
142
6,115
Vibe-Trading
agent/backtest/engines/forex.py
.py
"""Forex (FX spot / CFD) backtest engine. Market rules: - 24x5 (Mon Sydney open to Fri NYC close) - Spread replaces explicit commission (bid-ask) - Leverage: 50:1 to 500:1 (configurable) - Standard lot = 100,000 units of base currency - Swap (overnight rollover interest) at daily close - No price limits, n...
137
5,049
Vibe-Trading
agent/backtest/engines/crypto.py
.py
"""Crypto perpetual-contract backtest engine. Market rules: - 24/7 trading, no restrictions on direction - Maker/Taker fee separation - Funding fee settlement every 8 hours (00:00/08:00/16:00 UTC) - Forced liquidation when maintenance margin ratio <= 100% - Fractional position sizes allowed """ from __futur...
615
25,236
Vibe-Trading
agent/backtest/optimizers/equal_volatility.py
.py
"""Equal-volatility (inverse-volatility) weighting. Higher weight on lower-volatility names so each asset contributes similar vol. """ from typing import Any, Dict, List import numpy as np import pandas as pd from backtest.optimizers.base import BaseOptimizer class EqualVolatilityOptimizer(BaseOptimizer): """...
48
1,307
Vibe-Trading
agent/backtest/optimizers/__init__.py
.py
"""Portfolio optimizer package. Provides five weighting schemes: - equal_volatility: inverse-volatility weights - risk_parity: equal risk contribution (Spinu-style) - mean_variance: max Sharpe via scipy - max_diversification: maximize diversification ratio - turnover_aware: mean-variance utility with an L1 turnover pe...
13
473
Vibe-Trading
agent/backtest/optimizers/risk_parity.py
.py
"""Long-only risk parity: equalize marginal risk contributions.""" from typing import Any, Dict import numpy as np import pandas as pd from backtest.optimizers.base import BaseOptimizer class RiskParityOptimizer(BaseOptimizer): """Equal-risk-contribution weights on the long-only simplex.""" def _calc_weig...
60
1,815
Vibe-Trading
agent/backtest/optimizers/turnover_aware.py
.py
"""Turnover-aware optimizer: mean-variance utility with an L1 turnover penalty. Solves, per rebalance date:: min -w'mu + lambda * w'Sigma w + gamma * ||w - w_prev||_1 s.t. w >= 0, sum(w) = 1 w_i <= max_per_name (per-name cap) sum_{i in group_g} w_i <= max_per_group[...
251
10,636
Vibe-Trading
agent/backtest/optimizers/max_diversification.py
.py
"""Maximum diversification ratio: maximize (w' sigma) / sqrt(w' Sigma w). ``sigma`` is the vector of asset volatilities; ``Sigma`` is the covariance matrix. Higher DR means more diversification per unit of risk. """ from typing import Any, Dict import numpy as np import pandas as pd from backtest.optimizers.base im...
59
1,697
Vibe-Trading
agent/backtest/optimizers/mean_variance.py
.py
"""Mean-variance (max Sharpe) optimizer: max (w'mu - r_f) / sqrt(w'Sigma w), w>=0, sum(w)=1.""" from typing import Any, Dict, List import numpy as np import pandas as pd from backtest.optimizers.base import BaseOptimizer class MeanVarianceOptimizer(BaseOptimizer): """Maximize Sharpe ratio subject to long-only ...
70
2,082
Vibe-Trading
agent/backtest/optimizers/base.py
.py
"""Shared base class for portfolio optimizers. Handles preprocessing, rolling covariance windows, and weight normalization; subclasses implement ``_calc_weights``. """ from abc import ABC, abstractmethod from typing import Dict, Any, List import numpy as np import pandas as pd class BaseOptimizer(ABC): """Abst...
145
4,588
Vibe-Trading
agent/backtest/loaders/sec_frames.py
.py
"""Shared period-frame selection for SEC XBRL ``companyfacts`` rows. ``companyfacts`` interleaves several kinds of fact row that can share an ``end`` date: * **instant** facts (balance-sheet concepts) carry no ``start`` at all; * **true-quarter** duration frames span roughly 90 days; * **year-to-date** duration frame...
129
4,553
Vibe-Trading
agent/backtest/loaders/finnhub_loader.py
.py
"""Finnhub loader: key-gated US-equity OHLCV via the public stock-candle API. Finnhub (https://finnhub.io) serves daily stock candles from a single REST endpoint, gated by a free API key passed as the ``token`` query parameter: https://finnhub.io/api/v1/stock/candle?symbol=AAPL&resolution=D&from=...&to=...&token=.....
280
10,291
Vibe-Trading
agent/backtest/loaders/tencent_loader.py
.py
"""Tencent Finance loader: free, no-auth A-share / HK data via HTTP API. Uses Tencent's ifzq.gtimg.cn API which is not blocked by eastmoney's CDN. Covers: A-shares (SH/SZ) and HK equities. No API token required. API format: https://web.ifzq.gtimg.cn/appstock/app/fqkline/get?param=sh601595,day,2026-06-01,2026-06-13...
164
5,308
Vibe-Trading
agent/backtest/loaders/yfinance_loader.py
.py
"""yfinance-backed loader for HK/US equity OHLCV data.""" from __future__ import annotations import logging from collections import defaultdict from typing import Dict, List, Optional, Union import pandas as pd import yfinance as yf logger = logging.getLogger(__name__) from backtest.loaders.base import ( loade...
346
11,210
Vibe-Trading
agent/backtest/loaders/_symbol_utils.py
.py
"""Shared symbol-type detection utilities for loaders. Exchange-listed ETF / LOF prefix codes (same pattern across loaders): SH: 50/51/52/56/58 (ETFs), SZ: 15/16 (ETFs + LOFs). """ from __future__ import annotations _ETF_PREFIXES = frozenset({"15", "16", "50", "51", "52", "56", "58"}) def _is_etf_listed(code: st...
21
643
Vibe-Trading
agent/backtest/loaders/qveris_loader.py
.py
"""QVeris loader: explicit, key-gated OHLCV fetches through QVeris tools. This loader is intentionally self-contained for the QVeris integration parcel: it reads the shared ``~/.vibe-trading/qveris.json`` config schema, applies the ``QVERIS_API_KEY`` / ``QVERIS_BASE_URL`` environment overrides, and embeds the small HT...
685
23,485
Vibe-Trading
agent/backtest/loaders/tiingo_loader.py
.py
"""Tiingo loader: US-equity daily OHLCV via the Tiingo REST API (key-gated). Tiingo serves end-of-day US-equity bars from a documented public endpoint: GET https://api.tiingo.com/tiingo/daily/{symbol}/prices ?startDate=YYYY-MM-DD&endDate=YYYY-MM-DD&token={KEY} The response is a JSON array of per-day objects,...
246
8,804
Vibe-Trading
agent/backtest/loaders/fmp_loader.py
.py
"""Financial Modeling Prep (FMP) loader: key-gated US-equity OHLCV via HTTP. FMP exposes a daily historical-price endpoint that, like other free quote providers, rate-limits by source IP and must be throttled. Every request here routes through :mod:`backtest.loaders._http` so calls share one process-wide minimum-spaci...
222
7,519
Vibe-Trading
agent/backtest/loaders/india_broker_loader.py
.py
"""India broker data bridge: feed Shoonya / Dhan history into the backtest layer. The Shoonya (Finvasia) and Dhan connectors already expose live-account market data via ``get_historical_bars`` (read path). This loader adapts that envelope into the standard OHLCV frame so a user's *broker* history can back the same bac...
195
7,299
Vibe-Trading
agent/backtest/loaders/binance_loader.py
.py
"""Binance spot / USD-M perpetual OHLCV loader (via CCXT). Dedicated source name ``binance`` so it can sit **alongside** ``okx`` in the crypto auto-fallback chain — not as a replacement. Public market data only; no API key required. Use explicitly with ``source="binance"``, or let ``source="auto"`` fall through to Bi...
45
1,346
Vibe-Trading
agent/backtest/loaders/eastmoney_loader.py
.py
"""Eastmoney loader: free, no-auth OHLCV across A-share, HK and US equities. Eastmoney's ``push2his`` quote endpoints are free and require no token, but the service rate-limits aggressively by source IP. All HTTP goes through the shared :mod:`backtest.loaders.eastmoney_client`, which routes every call through the per-...
183
6,641
Vibe-Trading
agent/backtest/loaders/longbridge.py
.py
"""LongPort (Longbridge) OpenAPI-backed loader for US and HK equity OHLCV data. Wraps the ``longbridge`` SDK :class:`~longbridge.openapi.QuoteContext` to fetch historical candlesticks for backtesting. Supports US and HK equities. Auth requires the three LongPort credentials declared in ``src.config.env_schema.DataCon...
412
14,706
Vibe-Trading
agent/backtest/loaders/rsshub_events.py
.py
"""RSSHub event/sentiment provider with point-in-time safeguards. A news / announcement / sentiment provider that runs parallel to the Tushare fundamental layer (:mod:`backtest.loaders.tushare_fundamentals`). It pulls feeds from a self-hosted `RSSHub <https://docs.rsshub.app>`_ instance, normalises each item into the ...
569
21,075
Vibe-Trading
agent/backtest/loaders/sec_edgar_client.py
.py
"""Shared SEC EDGAR REST client: ticker->CIK mapping + filings/facts fetch. The U.S. SEC publishes free, no-auth JSON endpoints for company filings and XBRL financial facts. Three public facts drive this module: * ``https://www.sec.gov/files/company_tickers.json`` maps every reporting ticker to its numeric CIK (Cen...
235
8,291
Vibe-Trading
agent/backtest/loaders/sina_loader.py
.py
"""Sina Finance loader: free, no-auth US daily OHLCV via the JSONP K-line API. Sina exposes US daily candles through a JSONP endpoint that wraps a JSON array of ``{d,o,h,l,c,v}`` bars in a JavaScript variable assignment. We request it, strip the JSONP wrapper, and reshape into the loader's standard OHLCV frame. API f...
201
6,831
Vibe-Trading
agent/backtest/loaders/cn_adjust.py
.py
"""Corporate-action adjustment for Tushare A-share and fund bars. Tushare's ``daily`` and ``fund_daily`` endpoints return *unadjusted* prices, so a close-to-close return taken across an ex-date spans the mechanical price drop of a split, bonus issue or dividend rather than the instrument's actual move. Measured agains...
78
3,467
Vibe-Trading
agent/backtest/loaders/fundamentals_loader.py
.py
"""Translate sparse SEC facts into PIT-safe daily fundamental panels. The loader's core invariant is point-in-time safety: values become visible on their SEC ``filed`` date, never on ``period_end``. Phase 1 implements the SEC branch only. ``freq="ttm"`` uses a pragmatic Phase-1 approximation: known income-statement an...
501
17,474
Vibe-Trading
agent/backtest/loaders/okx.py
.py
"""OKX spot candle loader (crypto). Uses OKX V5 public REST API (no auth). Endpoints --------- - ``/market/candles`` — recent bars only (limited depth; not enough for multi-year backtests). - ``/market/history-candles`` — multi-year history; used whenever the requested range is older than a few months or recent e...
373
12,671
Vibe-Trading
agent/backtest/loaders/akshare_loader.py
.py
"""AKShare loader: free, no-auth data for A-shares, US, HK, futures, forex, macro. AKShare (https://github.com/akfamily/akshare) is a completely free financial data aggregator covering Chinese and global markets. No API token required. """ from __future__ import annotations import logging from typing import Dict, L...
297
10,864
Vibe-Trading
agent/backtest/loaders/futu.py
.py
"""Futu OpenAPI-backed loader for HK and China A-share OHLCV data.""" from __future__ import annotations import logging from typing import Dict, List, Optional import pandas as pd from backtest.loaders.base import ( NoAvailableSourceError, loader_cache_get, loader_cache_put, validate_date_range, ) f...
253
7,890
Vibe-Trading
agent/backtest/loaders/registry.py
.py
"""Loader registry with market-level fallback chains. Loaders self-register via the ``@register`` decorator when their module is first imported. The ``_ensure_registered()`` helper lazily imports every known loader module so that callers of ``resolve_loader`` / ``get_loader_cls_with_fallback`` never see an empty regi...
256
9,690
Vibe-Trading
agent/backtest/loaders/local_loader.py
.py
"""Local data loader: reads CSV, Parquet, and DuckDB files from user config. Configuration lives at ``~/.vibe-trading/data-bridge/config.yaml``. Each entry maps a symbol to a data file with optional column-name overrides, date format, and (for DuckDB) an SQL query. Example config:: sources: - symbol: "AAPL...
354
11,446
Vibe-Trading
agent/backtest/loaders/yahoo_loader.py
.py
"""Yahoo Finance loader: free, no-auth US/HK equity OHLCV via direct HTTP. Wraps the shared :mod:`backtest.loaders.yahoo_client` (the public v8 chart endpoint) rather than the ``yfinance`` package, so it pulls in no new dependency and shares the process-wide throttle/session that keeps Yahoo from IP-rate-limiting us. ...
275
10,228
Vibe-Trading
agent/backtest/loaders/baostock_loader.py
.py
"""BaoStock loader: free, no-auth A-share data via TCP protocol. BaoStock (http://baostock.com) uses its own TCP protocol (not HTTP), bypassing CDN IP blocks that affect HTTP-based data sources like eastmoney.com. Completely free, no API token required. Covers: A-shares (SH/SZ), does NOT cover HK/US/crypto. """ fro...
174
5,706
Vibe-Trading
agent/backtest/loaders/ccxt_loader.py
.py
"""CCXT loader: unified crypto exchange data (100+ exchanges). Uses the CCXT library to fetch OHLCV candles from any supported exchange. Defaults to Binance; configurable via CCXT_EXCHANGE env var. No API key required for public market data. """ from __future__ import annotations import hashlib import json import lo...
502
19,420
Vibe-Trading
agent/backtest/loaders/pykrx_loader.py
.py
"""pykrx loader: free, no-auth KRX (KOSPI/KOSDAQ) EOD OHLCV. Fetches Korean equity **daily** bars through the `pykrx <https://github.com/sharebook-kr/pykrx>`_ package. No API key. Provenance caveat (be precise about what this data is): ``pykrx`` exposes both a raw KRX path and an adjusted-price path, and ``stock.get_...
194
7,471
Vibe-Trading
agent/backtest/loaders/tickerall_loader.py
.py
"""TickerAll hosted MetaTrader 5 data loader - forex/metals/CFD OHLCV over HTTP. TickerAll (https://tickerall.com) is a hosted MetaTrader 5 API: it serves a broker account's own candle history over REST, so backtests can pull forex, metals, and index/CFD bars with the broker's exact symbols and session times WITHOUT a...
458
20,241
Vibe-Trading
agent/backtest/loaders/alphavantage_loader.py
.py
"""Alpha Vantage loader: US-equity daily OHLCV via the free key-gated REST API. Alpha Vantage serves daily bars at ``/query?function=TIME_SERIES_DAILY`` and gates access behind a free API key (env ``ALPHAVANTAGE_API_KEY``). The endpoint rate-limits per IP, so every request routes through :mod:`backtest.loaders._http` ...
260
9,296
Vibe-Trading
agent/backtest/loaders/stooq_loader.py
.py
"""Stooq loader: free, no-auth US-equity EOD OHLCV via CSV download. Stooq publishes free end-of-day bars from a plain CSV endpoint (``https://stooq.com/q/d/l/``) with no API key. Like other free quote providers it rate-limits by source IP and must be throttled, so every request routes through :mod:`backtest.loaders._...
202
6,990
Vibe-Trading
agent/backtest/loaders/tushare_fundamentals.py
.py
"""Tushare fundamental data provider with point-in-time safeguards.""" from __future__ import annotations from dataclasses import dataclass from typing import Any, Iterable import pandas as pd TUSHARE_TOKEN_PLACEHOLDERS = {"", "your-tushare-token"} class DataProviderError(Exception): """Base error for fundame...
380
15,094
Vibe-Trading
agent/backtest/loaders/_http.py
.py
"""Shared HTTP helpers for direct-API loaders: per-host throttling + JSON/CSV GET. Several free providers — Eastmoney most notably — rate-limit by source IP and will temporarily ban a client that bursts requests. Rather than scatter sleep calls across loaders, every ban-prone call routes through :func:`throttled_get` ...
201
7,701
Vibe-Trading
agent/backtest/loaders/tushare.py
.py
"""Tushare loader for A-share daily and intraday bars plus optional fundamentals. Supports ``interval``: 1D (default) / 1m / 5m / 15m / 30m / 1H. Minute data uses ``pro.stk_mins()`` (Tushare points >= 2000). """ import logging import time from typing import Any, Callable, Dict, List, Optional import pandas as pd fr...
386
14,453
Vibe-Trading
agent/backtest/loaders/mootdx_loader.py
.py
"""Mootdx loader: A-share OHLCV via TCP-direct 通达信 servers (no IP ban). Mootdx (https://github.com/mootdx/mootdx) talks the native 通达信 binary protocol over TCP and is not subject to the HTTP scraping rate limits that periodically break the akshare → East Money path. Public market data only, no token required, no per-I...
258
9,645
Vibe-Trading
agent/backtest/loaders/base.py
.py
"""DataLoader Protocol, shared exceptions, retry helpers, and loader cache. The retry/budget helpers are the canonical pattern for any loader that calls a flaky external API: a wall-clock deadline plus a small backoff schedule applied only to a declared transient exception class. New loaders should import :func:`check...
657
23,731
Vibe-Trading
agent/backtest/loaders/eastmoney_client.py
.py
"""Shared Eastmoney HTTP client: secid resolution + push2his kline fetch. Eastmoney exposes free, no-auth quote endpoints but rate-limits aggressively by source IP and will temporarily ban a bursting client, so every request here routes through :mod:`backtest.loaders._http` for per-host throttling and session reuse. T...
325
10,476
Vibe-Trading
agent/backtest/loaders/mt5_loader.py
.py
"""MetaTrader 5 data loader — forex/metals history from a local MT5 terminal. Feeds backtests and ``get_market_data`` from the user's own broker feed (e.g. Exness), with the broker's exact symbols and session times. Requires Windows, the optional ``MetaTrader5`` package (``pip install "vibe-trading-ai[mt5]"``), and a ...
251
10,036
Vibe-Trading
agent/backtest/loaders/_fundamental_schema.py
.py
"""Unified fundamental field schema and SEC XBRL concept aliases. This module is deliberately metadata-only. Callers use ``SEC_CONCEPT_MAP`` to extract sparse reported facts; when no concept hits, the caller must emit NaN for that field and log the missing alias coverage. This module does not log or fabricate fallback...
227
7,870
Vibe-Trading
agent/backtest/loaders/yahoo_client.py
.py
"""Shared Yahoo Finance public-API client: chart, quote summary, options, search. Yahoo Finance exposes several unauthenticated JSON endpoints (the same ones the finance.yahoo.com site itself calls) that, like other free quote providers, rate-limit by source IP and must be throttled. Every request here routes through ...
419
15,970
Vibe-Trading
agent/tests/test_default_deny_unknown_robinhood_tool.py
.py
"""Default-deny / fail-closed classification gate (SPEC §7.3 threat (d), §7.4). Stands up a MOCK MCP server (reusing the ``client_factory`` seam in ``src.tools.mcp``) exposing the four classification-critical shapes: * a genuine READ tool in the curated map, * a genuine WRITE tool in the curated map, * an UNKNOWN too...
165
6,164
Vibe-Trading
agent/tests/mcp_http_test_helpers.py
.py
"""Shared helpers for HTTP-based MCP integration tests.""" from __future__ import annotations import json import os import socket import subprocess import sys import tempfile import time from contextlib import contextmanager from dataclasses import dataclass from pathlib import Path from typing import Any, Callable, ...
413
13,611
Vibe-Trading
agent/tests/test_swarm_error_surfacing.py
.py
"""Regression tests for P04 — a misconfigured LLM provider must surface a diagnosable error from the swarm read boundaries. The swarm already captures ``SwarmTask.error`` on disk; the bug was that every read-side projection hand-maintained a field allowlist that omitted it, so the caller saw ``status="failed"`` with n...
94
3,350
Vibe-Trading
agent/tests/test_api_live_runtime.py
.py
"""API regressions for the live-trading runtime wiring (R6: C1 + C2 + runner control). Covers the open-file integration seam the orchestrator and parcel R6 own: - C1: a ``propose_mandate_profiles`` tool_result is translated into a top-level ``mandate.proposal`` SSE frame WITHOUT touching the protected ``src/agent/lo...
449
17,296
Vibe-Trading
agent/tests/test_sec_period_frames.py
.py
"""Regression tests for SEC XBRL period-frame selection. SEC ``companyfacts`` files the true quarter and the year-to-date frame for the same ``end`` date under the same ``fy``/``fp``/``form``/``accn``, so a consumer keying on anything narrower than the ``(start, end)`` span silently lets one overwrite the other. Repro...
252
10,281
Vibe-Trading
agent/tests/test_longbridge_credentials.py
.py
"""Tests for atomic Longbridge credential resolution.""" from __future__ import annotations import json import pytest from src.config.accessor import reset_env_config from src.trading.connectors.longbridge.credentials import ( LongbridgeCredentialError, LongbridgeCredentials, require_longbridge_credenti...
265
9,280
Vibe-Trading
agent/tests/test_swarm_runs_root_and_shell_tools.py
.py
"""Regression tests for P03-A (run-root / store single source of truth) and P03-B (MCP swarm wrapper must thread include_shell_tools; the filtered registry must not silently drop a requested tool). P03-A: the swarm store location and the run-dir sandbox allow-list were each derived independently as ``<agent_root>/.swa...
80
3,475
Vibe-Trading
agent/tests/test_session_tool_trail.py
.py
"""Session history regressions for completed-attempt tool trails.""" from __future__ import annotations import asyncio from pathlib import Path from fastapi.testclient import TestClient import api_server from src.session.events import EventBus from src.session.models import Attempt, Message, Session from src.sessio...
207
6,484
Vibe-Trading
agent/tests/test_serve_bind.py
.py
"""Tests for the API server bind default and non-loopback warning. Covers the secure-by-default behavior added for #333: - `_is_loopback_bind_host` classification (IPv4 / IPv6 / hostname / edge) - `serve_main` defaults the bind address to loopback (127.0.0.1) - binding a non-loopback address without API_AUTH_KEY...
133
4,095
Vibe-Trading
agent/tests/test_mcp_host_origin_guard.py
.py
"""Tests for the network MCP transport DNS-rebinding guard (GHSA-p3c9). The stdio transport is a private pipe and is not touched. The network transports (``--transport sse`` / ``http``) bind a TCP port, so fastmcp 3.2.4 (which ships no host/origin protection) is wrapped with a Host + Origin allow-list before the MCP s...
218
9,074
Vibe-Trading
agent/tests/test_perpetual_risk.py
.py
from __future__ import annotations import json from dataclasses import FrozenInstanceError import pandas as pd import pytest from backtest.perpetual_risk import ( AccountState, CrossMarginRiskModel, ExecutionFrame, MaintenanceBracket, MaintenanceSchedule, MarketRiskFrame, PositionRisk, ...
540
20,020
Vibe-Trading
agent/tests/test_swarm_worker_stream_retry.py
.py
"""Tests for the single stream retry on ProviderStreamError in run_worker. ``ChatLLM.stream_chat`` used to silently fall back to non-streaming ``chat()`` on any exception; it now raises ``ProviderStreamError``. A swarm worker that previously survived a transient mid-stream hiccup (connection reset) via the silent fall...
192
6,537
Vibe-Trading
agent/tests/test_akshare_daily_aliases.py
.py
"""AKShare daily map must accept connector-style lowercase 1d/1w aliases.""" from __future__ import annotations from backtest.loaders.akshare_loader import _INTERVAL_MAP_DAILY def test_lowercase_1d_and_1w_map_like_project_tokens() -> None: assert _INTERVAL_MAP_DAILY["1d"] == _INTERVAL_MAP_DAILY["1D"] == "daily"...
16
546
Vibe-Trading
agent/tests/test_options_portfolio_correctness.py
.py
"""Focused accounting and metric regressions for the options engine.""" from __future__ import annotations import json import numpy as np import pandas as pd import pytest from backtest.engines.options_portfolio import _calc_options_metrics def test_empty_equity_returns_json_safe_undefined_metrics() -> None: ...
135
4,780
Vibe-Trading
agent/tests/test_global_equity_engine.py
.py
"""Tests for GlobalEquityEngine (US / HK / Canada) market rules. Validates: - US: zero commission, fractional shares, low slippage - HK: stamp tax bilateral, 100-share lots, levies - Canada: whole shares, configurable broker cost, TSX/TSXV tick grid - Same-session trading for all three markets - Both directi...
223
8,008
Vibe-Trading
agent/tests/test_price_limit_lookahead.py
.py
"""Price-limit bands must be judged at execution time, not from the bar's close. ``BaseEngine`` calls ``can_execute`` before filling at the CURRENT bar's open, so a limit check derived from that bar's close is lookahead. It was wrong in both directions: a name that opened locked but drifted back by the close was allow...
190
8,305
Vibe-Trading
agent/tests/test_runner_env.py
.py
"""Regression tests for generated backtest subprocess environment handling.""" from __future__ import annotations import os from pathlib import Path import pytest from src.core import runner as runner_mod from src.core.runner import ( Runner, _make_rlimit_preexec, _prepare_sandbox_home, _resolve_san...
319
10,993
Vibe-Trading
agent/tests/test_baostock_interval_reject.py
.py
"""BaoStock must reject non-daily intervals instead of silently returning day bars.""" from __future__ import annotations from unittest.mock import MagicMock, patch from backtest.loaders.baostock_loader import DataLoader def test_unsupported_interval_does_not_login_or_fetch() -> None: """Runner ``1H`` must not...
31
1,101
Vibe-Trading
agent/tests/test_url_target_security.py
.py
"""Regression tests for the SSRF URL guard and QQ outbound-media fetch. Covers two previously-untested gaps: - ``validate_url_target`` / ``_is_private`` must block non-globally-routable ranges, including RFC 6598 ``100.64.0.0/10`` (CGNAT / the default Tailscale mesh range). ``ipaddress.is_private`` is ``False`` f...
152
5,301
Vibe-Trading
agent/tests/test_mootdx_loader.py
.py
"""Tests for the mootdx A-share OHLCV loader.""" from __future__ import annotations from types import SimpleNamespace import pandas as pd import pytest import backtest.loaders.mootdx_loader as ml from backtest.loaders.mootdx_loader import DataLoader, _is_a_share, _is_bj # -----------------------------------------...
243
8,885
Vibe-Trading
agent/tests/test_settings_api.py
.py
"""Regression tests for local settings API endpoints.""" from __future__ import annotations import os from pathlib import Path import pytest from fastapi.testclient import TestClient import api_server from src.api import settings_routes @pytest.fixture def client(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -...
634
21,342
Vibe-Trading
agent/tests/test_local_loader_interval_case.py
.py
"""Local loader resample rules must accept connector-style hour aliases.""" from __future__ import annotations import pandas as pd from backtest.loaders.local_loader import _RESAMPLE_RULES, _resample_to_interval def _hourly_frame() -> pd.DataFrame: idx = pd.date_range("2024-01-01", periods=8, freq="h") ret...
36
1,042
Vibe-Trading
agent/tests/test_agent_loop_thought_signature.py
.py
"""Regression coverage for Gemini thought_signature replay in AgentLoop history.""" from __future__ import annotations import json from langchain_core.messages import AIMessage, convert_to_messages from src.agent.context import ContextBuilder from src.agent.loop import _attach_tool_call_thought_signatures from src....
144
4,681
Vibe-Trading
agent/tests/test_eastmoney_loader.py
.py
"""Tests for the Eastmoney OHLCV loader. These never touch the network: the cross-market path mocks the shared client (:mod:`backtest.loaders.eastmoney_client`), and the end-to-end path mocks the HTTP boundary (``throttled_get_json``) so the real client parsing runs while no request leaves the process. """ from __fut...
192
6,841
Vibe-Trading
agent/tests/test_swarm_m2_registry_assembly.py
.py
"""M2 — SWARM external MCP tools: registry assembly regression tests. Covers requirements R-01, R-02, R-03 and tests T-04, T-05, T-06, T-07 in ``docs/2026-05-25_swarm_mcp_tools_tdd.md``. M2 introduces ``build_swarm_registry`` — the per-worker registry-builder that merges local tools with remote MCP wrappers from ``age...
287
11,427
Vibe-Trading
agent/tests/test_agent_guide_paths.py
.py
"""Guard the AI contributor guide against silent path rot. ``AGENT_CONTRIBUTOR_GUIDE.md`` names specific test files, entry points, and directories so agent-assisted contributors run the right targeted checks. Those references rot silently when files are renamed or moved, leaving the guide quietly wrong. This test pars...
51
2,087
Vibe-Trading
agent/tests/test_alpha_bench_meta_survivorship.py
.py
"""``alpha bench`` must forward result["meta"] (issue #797). bench_runner.run_bench forwards the sp500 loader's survivorship_bias flag as result["meta"], and alpha_routes._result_for_wire already keeps it for the SSE/frontend path. cmd_alpha_bench's own JSON envelope and HTML report context were built from hand-enumer...
139
3,878
Vibe-Trading
agent/tests/test_bench_parallel.py
.py
"""Tests for parallel bench runner (ProcessPoolExecutor path).""" from __future__ import annotations import sys from unittest.mock import MagicMock, patch import numpy as np import pandas as pd import pytest from src.factors.bench_runner import _compute_single_alpha, _init_bench_worker def _make_mock_panel(n_symb...
156
5,888
Vibe-Trading
agent/tests/test_trade_journal_parser_slash_crypto.py
.py
"""Regression test for _infer_market_from_symbol handling slash-delimited crypto symbols in trade_journal_parsers. Locks out a bug where _infer_market_from_symbol returned "other" instead of "crypto" for slash-formatted crypto trading pairs (e.g. "ETH/USDT" or "BTC/USD"). """ from src.tools.trade_journal_parsers impo...
18
846
Vibe-Trading
agent/tests/test_alpha_compare_tool.py
.py
"""Tests for the ``alpha_compare`` agent tool. Covers id coercion, the tool's JSON-Schema contract, ``execute`` happy/error paths (with ``compare_alphas`` stubbed so no bench/network runs), and that the tool is auto-discovered into the default registry. """ from __future__ import annotations import json from typing ...
129
4,850
Vibe-Trading
agent/tests/test_no_set_mandate_tool.py
.py
"""Structural guarantee: nothing the agent can reach writes the mandate store. Mirrors the BROKERS.md method-name-regex gate. Two checks: 1. **Name-regex AST scan** over ``src/live/`` (and ``src/tools/``): no function or method matches the forbidden self-authorization regex. The single legitimate writer (the co...
114
5,228
Vibe-Trading
agent/tests/test_agent_loop_content_filter.py
.py
"""AgentLoop content-filter skip-and-continue behavior. When the LLM returns a content-filtered response (content_filter_triggered=True), the agent loop should skip that iteration and continue instead of breaking. """ from __future__ import annotations from pathlib import Path from typing import Any, Callable impor...
271
9,032
Vibe-Trading
agent/tests/test_session_store_messages_corrupt.py
.py
"""Schema-bad messages.jsonl lines must be skipped like JSONDecodeError lines.""" from __future__ import annotations import json from pathlib import Path from src.session.models import Message, Session from src.session.store import SessionStore def _seed(store: SessionStore, session_id: str) -> Path: store.cre...
73
2,028
Vibe-Trading
agent/tests/test_options_partial_close.py
.py
"""Regression (#577): options close honors a partial-close quantity. The options engine's ``close`` branch used to compute cash/PnL from the full matched lot and remove the whole position, ignoring the leg's requested ``qty``. A partial close therefore flattened the entire lot. These tests pin the new behavior: an exp...
120
3,785
Vibe-Trading
agent/tests/test_onboard_partial_env.py
.py
"""POSIX permission and durability tests for the onboarding ``.env.partial``. ``.env.partial`` holds half-entered onboarding answers, which include API keys, so it must never be world-readable and must never be destroyed by a failed write — it exists precisely to survive a crash mid-onboarding. """ from __future__ im...
92
3,146
Vibe-Trading
agent/tests/test_signal_table_edge_columns.py
.py
"""Signal markdown tables must keep empty leading/trailing columns.""" from __future__ import annotations from src.channels.signal import _sig_render_table def test_sig_render_table_keeps_trailing_empty_column() -> None: box = _sig_render_table( [ "|Name|Qty||", "|---|---|---|", ...
35
936
Vibe-Trading
agent/tests/test_technical_indicator_tool.py
.py
"""Tests for the technical indicator tool.""" import json import pandas as pd import pytest from src.tools.technical_indicator_tool import ( TechnicalIndicatorTool, _compute_bollinger, _compute_ema, _compute_macd, _compute_rsi, _compute_sma, ) class TestSMA: def test_sma_normal(self): ...
451
17,268
Vibe-Trading
agent/tests/test_cli_init.py
.py
from __future__ import annotations from pathlib import Path from unittest.mock import patch import cli def _provider_choice_number(provider: str) -> int: """Return the rendered one-based menu number for a provider.""" return next( index for index, choice in enumerate(cli._PROVIDER_CHOICES, s...
144
5,486
Vibe-Trading
agent/tests/test_mcp_factor_analysis_contract.py
.py
"""Regression tests for issue #635 — MCP ``factor_analysis`` contract mismatch. Pre-fix: the MCP wrapper forwarded ``codes``/``factor_name``/``start_date``/ ``end_date``/``source``/``top_n``/``bottom_n``, but the registered ``FactorAnalysisTool`` requires ``factor_csv``/``return_csv``/``output_dir`` — every MCP call d...
115
3,784
Vibe-Trading
agent/tests/test_run_card_strict_json.py
.py
"""Regression tests for strict run card JSON output.""" from __future__ import annotations import json from pathlib import Path from backtest.run_card import write_run_card def test_run_card_replaces_non_finite_metrics_with_null(tmp_path: Path) -> None: run_dir = tmp_path / "run" card = write_run_card( ...
48
1,331
Vibe-Trading
agent/tests/test_cli_memory.py
.py
"""Tests for the `vibe-trading memory` CLI subcommands.""" from __future__ import annotations from pathlib import Path from unittest.mock import patch import pytest import cli from src.memory.persistent import PersistentMemory def _seed(tmp_path: Path) -> PersistentMemory: """Populate a tmp memory dir with on...
255
10,960
Vibe-Trading
agent/tests/test_metrics_calc_integer_index.py
.py
"""Regression test for calc_metrics on equity curves with integer or non-datetime index. Locks out a bug where calc_metrics raised AttributeError: 'int' object has no attribute 'days' when bars_per_year=None (auto-detect mode) and equity_curve's index was non-datetime (e.g. RangeIndex or Int64Index). """ import panda...
24
1,044
Vibe-Trading
agent/tests/test_longbridge_period_hour_case.py
.py
"""Longbridge connector period map must treat 1H/4H like the loader.""" from __future__ import annotations from src.trading.connectors.longbridge import sdk as lb def test_period_map_accepts_project_hour_tokens() -> None: assert lb._PERIOD_MAP["1H"] == "Min_60" assert lb._PERIOD_MAP["4H"] == "Min_60" as...
32
891
Vibe-Trading
agent/tests/test_remember_tool.py
.py
"""Tests for RememberTool: save / recall / forget via PersistentMemory.""" from __future__ import annotations import json from pathlib import Path import pytest from src.memory.persistent import PersistentMemory from src.tools.remember_tool import RememberTool @pytest.fixture() def tool(tmp_path: Path) -> Remembe...
143
5,863
Vibe-Trading
agent/tests/test_generic_stringified_excel_serial.py
.py
"""Generic journal datetime cells must normalize Excel serials from dtype=str loads.""" from __future__ import annotations import tempfile from pathlib import Path import pandas as pd from src.tools.trade_journal_parsers import ( load_dataframe, parse_file, parse_generic, records_to_dataframe, ) d...
47
1,270
Vibe-Trading
agent/tests/test_composite_currency_guard.py
.py
"""Regression tests for the composite engine's single-currency requirement. ``CompositeEngine`` keeps one shared capital pool: a single cash scalar and one equity curve. Before this guard a code set spanning CNY, USD, HKD, INR, KRW and CAD was summed into that curve as if the units matched, and every metric derived fr...
114
4,333
Vibe-Trading
agent/tests/test_provider_header_isolation.py
.py
"""Regression tests for provider-scoped HTTP header isolation.""" from __future__ import annotations import asyncio import json import os from unittest.mock import patch import httpx import pytest from src.config.accessor import reset_env_config from src.providers.llm import ChatOpenAIWithReasoning, build_llm, prov...
243
8,637
Vibe-Trading
agent/tests/test_tickerall_loader.py
.py
"""Tests for tickerall_loader: the four review-contract guarantees plus parsing. All HTTP is mocked at :func:`backtest.loaders._http.throttled_get_json` (imported into the loader module), so no test touches a live TickerAll endpoint. The four contract points these tests pin down: 1. Explicit-only - registered as a...
420
18,631
Vibe-Trading
agent/tests/test_metrics.py
.py
"""Tests for backtest metrics calculation. Validates: - bars_per_year annualization - win_rate_and_stats - by_symbol_stats / by_exit_reason_stats - calc_metrics (Sharpe, drawdown, Sortino, Calmar, etc.) """ from __future__ import annotations import math import numpy as np import pandas as pd import pytest ...
586
23,810
Vibe-Trading
agent/tests/test_swarm_m4_e2e.py
.py
"""M4 — SWARM external MCP tools: end-to-end worker integration tests. Covers requirements R-04, R-07, R-10 and tests T-12, T-13, T-14, T-15 in ``docs/2026-05-25_swarm_mcp_tools_tdd.md``. M4 is the milestone that makes the contract from M1+M2+M3 *visible to the operator at run time*: a worker that calls a remote MCP t...
615
23,304