"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix: finish exact Dhan quantities and four-PR boundary coverage
Haozhe Wua5d47c200f59
diff --git a/agent/src/config/env_schema.py b/agent/src/config/env_schema.pyindex 8e0968bbb..932fbf454 100644--- a/agent/src/config/env_schema.py+++ b/agent/src/config/env_schema.py@@ -80,6 +80,12 @@ def _numeric_type(annotation: Any) -> Any:Handles both ``typing.Optional[int]`` and the ``int | None`` spelling,which produce different ``get_origin`` results (``typing.Union`` vs.``types.UnionType``).++ Args:+ annotation: The field annotation resolved by Pydantic.++ Returns:+ Its numeric type, or ``None`` for annotations needing normal validation."""if annotation is int or annotation is float:return annotationdiff --git a/agent/src/factors/zoo/qlib158/wvma10.py b/agent/src/factors/zoo/qlib158/wvma10.pyindex d789e5d9e..c464dc556 100644--- a/agent/src/factors/zoo/qlib158/wvma10.py+++ b/agent/src/factors/zoo/qlib158/wvma10.py@@ -1,5 +1,5 @@-# Adapted from microsoft/qlib@d5379c520f66a39953bad76234a7019a72796fd0:qlib/contrib/data/handler.py-# (Apache-2.0). Copyright (c) Microsoft Corporation.+# Adapted from microsoft/qlib@be725493eb1a6bbb42bf11b37aa7669f59610ff1:qlib/contrib/data/loader.py+# (MIT). Copyright (c) Microsoft Corporation.# ============================================================# 中文名称: 成交量加权波动 10日# 简要说明: ts_std(|ret|*v, 10) / ts_mean(|ret|*v, 10),成交量加权的价格波动归一化指标。diff --git a/agent/src/factors/zoo/qlib158/wvma20.py b/agent/src/factors/zoo/qlib158/wvma20.pyindex a23923cc0..b5fb244d3 100644--- a/agent/src/factors/zoo/qlib158/wvma20.py+++ b/agent/src/factors/zoo/qlib158/wvma20.py@@ -1,5 +1,5 @@-# Adapted from microsoft/qlib@d5379c520f66a39953bad76234a7019a72796fd0:qlib/contrib/data/handler.py-# (Apache-2.0). Copyright (c) Microsoft Corporation.+# Adapted from microsoft/qlib@be725493eb1a6bbb42bf11b37aa7669f59610ff1:qlib/contrib/data/loader.py+# (MIT). Copyright (c) Microsoft Corporation.# ============================================================# 中文名称: 成交量加权波动 20日# 简要说明: ts_std(|ret|*v, 20) / ts_mean(|ret|*v, 20),成交量加权的价格波动归一化指标。diff --git a/agent/src/factors/zoo/qlib158/wvma30.py b/agent/src/factors/zoo/qlib158/wvma30.pyindex fc593435b..1c872e3dd 100644--- a/agent/src/factors/zoo/qlib158/wvma30.py+++ b/agent/src/factors/zoo/qlib158/wvma30.py@@ -1,5 +1,5 @@-# Adapted from microsoft/qlib@d5379c520f66a39953bad76234a7019a72796fd0:qlib/contrib/data/handler.py-# (Apache-2.0). Copyright (c) Microsoft Corporation.+# Adapted from microsoft/qlib@be725493eb1a6bbb42bf11b37aa7669f59610ff1:qlib/contrib/data/loader.py+# (MIT). Copyright (c) Microsoft Corporation.# ============================================================# 中文名称: 成交量加权波动 30日# 简要说明: ts_std(|ret|*v, 30) / ts_mean(|ret|*v, 30),成交量加权的价格波动归一化指标。diff --git a/agent/src/factors/zoo/qlib158/wvma5.py b/agent/src/factors/zoo/qlib158/wvma5.pyindex 186e76ed1..6d1b16832 100644--- a/agent/src/factors/zoo/qlib158/wvma5.py+++ b/agent/src/factors/zoo/qlib158/wvma5.py@@ -1,5 +1,5 @@-# Adapted from microsoft/qlib@d5379c520f66a39953bad76234a7019a72796fd0:qlib/contrib/data/handler.py-# (Apache-2.0). Copyright (c) Microsoft Corporation.+# Adapted from microsoft/qlib@be725493eb1a6bbb42bf11b37aa7669f59610ff1:qlib/contrib/data/loader.py+# (MIT). Copyright (c) Microsoft Corporation.# ============================================================# 中文名称: 成交量加权波动 5日# 简要说明: ts_std(|ret|*v, 5) / ts_mean(|ret|*v, 5),成交量加权的价格波动归一化指标。diff --git a/agent/src/factors/zoo/qlib158/wvma60.py b/agent/src/factors/zoo/qlib158/wvma60.pyindex 1b8f9ab60..04a4329a5 100644--- a/agent/src/factors/zoo/qlib158/wvma60.py+++ b/agent/src/factors/zoo/qlib158/wvma60.py@@ -1,5 +1,5 @@-# Adapted from microsoft/qlib@d5379c520f66a39953bad76234a7019a72796fd0:qlib/contrib/data/handler.py-# (Apache-2.0). Copyright (c) Microsoft Corporation.+# Adapted from microsoft/qlib@be725493eb1a6bbb42bf11b37aa7669f59610ff1:qlib/contrib/data/loader.py+# (MIT). Copyright (c) Microsoft Corporation.# ============================================================# 中文名称: 成交量加权波动 60日# 简要说明: ts_std(|ret|*v, 60) / ts_mean(|ret|*v, 60),成交量加权的价格波动归一化指标。diff --git a/agent/src/live/mandate/commit.py b/agent/src/live/mandate/commit.pyindex ebb92df10..88fdec9bd 100644--- a/agent/src/live/mandate/commit.py+++ b/agent/src/live/mandate/commit.py@@ -543,7 +543,7 @@ def commit_mandate(def _explicit_float(profile: Mapping[str, Any], key: str) -> float | None:- """Return ``profile[key]`` as a float, or ``None`` if the key is absent.+ """Return ``profile[key]`` as a float, or ``None`` if absent or null.``_resolve_profile`` lets a commit-time adjustment narrow a numeric limitdown to an explicit ``0`` (any value <= the rendered limit is a legal@@ -551,6 +551,13 @@ def _explicit_float(profile: Mapping[str, Any], key: str) -> float | None:``profile.get(key, default)`` with Python's ``x or default`` idiom treatsthat explicit ``0`` the same as "key missing" and silently substitutes ahigher fallback, which is exactly the widening a commit must never do.++ Args:+ profile: Resolved proposal profile.+ key: Numeric limit to read.++ Returns:+ The explicit numeric value, including zero, or ``None`` if unspecified."""value = profile.get(key)return float(value) if value is not None else Nonediff --git a/agent/src/trading/connectors/dhan/sdk.py b/agent/src/trading/connectors/dhan/sdk.pyindex d6fd3f629..71c234574 100644--- a/agent/src/trading/connectors/dhan/sdk.py+++ b/agent/src/trading/connectors/dhan/sdk.py@@ -4,14 +4,15 @@ Wraps ``DhanHQ`` client for account, positions, orders, quotes, and historicaldata. Supports NSE/BSE equities and F&O (NIFTY/BANKNIFTY options).Paper-vs-live: Dhan has no sandbox environment. Paper mode uses the same API-for market data reads but simulates orders locally. Live mode places real orders-through Dhan's production API.+for market data reads but simulates orders locally. Non-paper profiles permit+reads only; order methods refuse them before any SDK call."""from __future__ import annotationsimport jsonfrom dataclasses import asdict, dataclass+from decimal import Decimal, InvalidOperationfrom pathlib import Pathfrom types import ModuleTypefrom typing import Any, Mapping@@ -482,15 +483,18 @@ def place_order(if type_token not in ("MARKET", "LIMIT"):return {"status": "error", "error": "order_type must be 'market' or 'limit'"}- if quantity is None or float(quantity) < 1:+ try:+ amount = Decimal(str(quantity))+ valid_quantity = amount.is_finite() and amount >= 1 and amount == amount.to_integral_value()+ except (InvalidOperation, ValueError):+ valid_quantity = False+ if not valid_quantity:return {"status": "error","error": "quantity must be a positive whole number of shares",}- if float(quantity) != int(float(quantity)):- return {"status": "error", "error": "quantity must be a whole number of shares"}- qty = int(float(quantity))+ qty = int(amount)sec_id = str(security_id or symbol).strip()if type_token == "LIMIT" and limit_price is None:diff --git a/agent/tests/factors/test_qlib158_wvma_abs_numerator.py b/agent/tests/factors/test_qlib158_wvma_abs_numerator.pyindex f4c803aaa..95f9796ce 100644--- a/agent/tests/factors/test_qlib158_wvma_abs_numerator.py+++ b/agent/tests/factors/test_qlib158_wvma_abs_numerator.py@@ -6,10 +6,20 @@ the signed one. This pins that the numerator does use ``|ret|``: with equal-magnitude, alternating-sign returns and constant volume, ``|ret|*v`` isconstant within the window, so its rolling std is exactly zero. A rolling stdof the signed ``ret*v`` series would instead be large and nonzero.++Upstream formula (both operands use Abs):+https://github.com/microsoft/qlib/blob/be725493eb1a6bbb42bf11b37aa7669f59610ff1/qlib/contrib/data/loader.py#L275-L282+The local operators deliberately require complete windows, unlike upstream's+min_periods=1. The scalar oracle below checks the formula on observed windows+without reusing pandas rolling or the production safe_div/std/mean helpers."""from __future__ import annotations+from fractions import Fraction+from statistics import mean, stdev++import numpy as npimport pandas as pdimport pytest@@ -20,6 +30,9 @@ from src.factors.zoo.qlib158.wvma30 import compute as wvma30from src.factors.zoo.qlib158.wvma60 import compute as wvma60+CASES = [(wvma5, 5), (wvma10, 10), (wvma20, 20), (wvma30, 30), (wvma60, 60)]++def _alternating_panel(window: int) -> dict[str, pd.DataFrame]:"""One asset whose daily return alternates +/-2% with constant volume.@@ -38,10 +51,87 @@ def _alternating_panel(window: int) -> dict[str, pd.DataFrame]:@pytest.mark.parametrize("compute,window",- [(wvma5, 5), (wvma10, 10), (wvma20, 20), (wvma30, 30), (wvma60, 60)],+ CASES,)def test_wvma_numerator_uses_absolute_return(compute, window: int) -> None:panel = _alternating_panel(window)out = compute(panel)last = out["AAA"].iloc[-1]assert last == pytest.approx(0.0, abs=1e-9)+++def _varied_panel() -> dict[str, pd.DataFrame]:+ """Mixed signs/magnitudes, ties and zero volume, without price drift."""+ index = pd.date_range("2024-01-01", periods=160, freq="D", name="date")+ close_cycle = [100, 125, 100, 80, 100, 100, 150, 100]+ volume_cycle = [4, 12, 8, 20, 0, 16, 28]+ return {+ "close": pd.DataFrame(+ {symbol: [close_cycle[(i + offset) % 8] for i in range(160)]+ for symbol, offset in (("AAA", 0), ("BBB", 3))},+ index=index, dtype=float,+ ),+ "volume": pd.DataFrame(+ {symbol: [volume_cycle[(i + offset) % 7] for i in range(160)]+ for symbol, offset in (("AAA", 0), ("BBB", 2))},+ index=index, dtype=float,+ ),+ }+++def _scalar_oracle(panel: dict[str, pd.DataFrame], window: int) -> pd.DataFrame:+ """Evaluate exact rational returns, then a scalar sample deviation."""+ close, volume = panel["close"], panel["volume"]+ expected = pd.DataFrame(np.nan, index=close.index, columns=close.columns)+ for symbol in close.columns:+ for end in range(window, len(close)):+ weights = [+ abs(Fraction(close[symbol].iloc[i]) / Fraction(close[symbol].iloc[i - 1]) - 1)+ * Fraction(volume[symbol].iloc[i])+ for i in range(end - window + 1, end + 1)+ ]+ expected.loc[close.index[end], symbol] = float(stdev(weights) / mean(weights))+ return expected++[email protected]("compute,window", CASES)+def test_wvma_nonzero_values_and_warmup_match_independent_oracle(compute, window: int) -> None:+ panel = _varied_panel()+ expected = _scalar_oracle(panel, window)+ actual = compute(panel)++ assert actual.iloc[:window].isna().all().all()+ assert np.isfinite(actual.iloc[window:].to_numpy()).all()+ assert (expected.iloc[window:] > 0).all().all()+ # safe_div adds a small epsilon; this is not a second implementation of it.+ pd.testing.assert_frame_equal(actual, expected, rtol=1e-9, atol=1e-9)++[email protected]("compute,window", CASES)[email protected]("field,extra_bar", [("close", 1), ("volume", 0)])+def test_wvma_gap_masks_exactly_its_reach_and_recovers(+ compute, window: int, field: str, extra_bar: int,+) -> None:+ panel = _varied_panel()+ expected = _scalar_oracle(panel, window)+ gap = 70+ recovery = gap + window + extra_bar+ # A close gap loses two returns; a volume gap loses only its own weight.+ panel[field].loc[panel[field].index[gap], "AAA"] = np.nan+ actual = compute(panel)++ assert np.isfinite(expected.iloc[window:].to_numpy()).all()+ assert actual["AAA"].iloc[gap:recovery].isna().all()+ assert np.isfinite(actual["AAA"].iloc[recovery])+ expected.loc[expected.index[gap:recovery], "AAA"] = np.nan+ # Checks recovery, earlier history, and the unaffected symbol together.+ pd.testing.assert_frame_equal(actual, expected, rtol=1e-9, atol=1e-9)++[email protected]("compute,window", CASES)+def test_wvma_zero_volume_keeps_local_zero_denominator_nan_contract(compute, window: int) -> None:+ panel = _varied_panel()+ panel["volume"].loc[:, "AAA"] = 0.0+ actual = compute(panel)+ assert actual["AAA"].isna().all()+ assert np.isfinite(actual["BBB"].iloc[window:]).all()diff --git a/agent/tests/test_env_schema.py b/agent/tests/test_env_schema.pyindex 696c35a70..531e176a1 100644--- a/agent/tests/test_env_schema.py+++ b/agent/tests/test_env_schema.py@@ -17,8 +17,10 @@ Covers:from __future__ import annotationsimport concurrent.futures+from typing import Optionalimport pytest+from pydantic import Field, ValidationErrorfrom src.config.accessor import (_parse_bool,@@ -36,6 +38,7 @@ from src.config.env_schema import (PathConfig,SwarmConfig,_parse_env_bool,+ _EnvBase,)@@ -222,8 +225,9 @@ class TestEnvConfigTypeCoercion:c = EnvConfig()assert c.agent_tuning.token_threshold == 40000- def test_invalid_optional_int_falls_back_to_default(self, monkeypatch: pytest.MonkeyPatch) -> None:- monkeypatch.setenv("ANTHROPIC_MAX_TOKENS", "not_a_number")+ @pytest.mark.parametrize("value", ["not_a_number", "", "1.5", "NaN", "Infinity"])+ def test_invalid_optional_int_falls_back_to_default(self, monkeypatch: pytest.MonkeyPatch, value: str) -> None:+ monkeypatch.setenv("ANTHROPIC_MAX_TOKENS", value)c = EnvConfig()assert c.llm.anthropic_max_tokens is None@@ -233,6 +237,31 @@ class TestEnvConfigTypeCoercion:assert c.llm.anthropic_max_tokens == 4096assert isinstance(c.llm.anthropic_max_tokens, int)+ @pytest.mark.parametrize("value", ["0", "-1"])+ def test_optional_int_still_enforces_its_positive_constraint(self, monkeypatch, value) -> None:+ monkeypatch.setenv("ANTHROPIC_MAX_TOKENS", value)+ with pytest.raises(ValidationError):+ LLMConfig()++ @pytest.mark.parametrize("field", ["anthropic_max_tokens", "ANTHROPIC_MAX_TOKENS"])+ @pytest.mark.parametrize("value", [None, 4096])+ def test_explicit_optional_value_wins_over_environment(self, monkeypatch, field, value) -> None:+ monkeypatch.setenv("ANTHROPIC_MAX_TOKENS", "8192")+ assert LLMConfig(**{field: value}).anthropic_max_tokens == value++ def test_invalid_explicit_optional_value_is_not_silently_defaulted(self, monkeypatch) -> None:+ monkeypatch.setenv("ANTHROPIC_MAX_TOKENS", "8192")+ with pytest.raises(ValidationError):+ LLMConfig(anthropic_max_tokens="invalid")++ @pytest.mark.parametrize("raw,expected", [("", None), ("invalid", None), ("0", 0.0), ("2.5", 2.5)])+ def test_typing_optional_float_environment_coercion(self, monkeypatch, raw, expected) -> None:+ class OptionalFloatConfig(_EnvBase):+ value: Optional[float] = Field(alias="LANGCHAIN_TEMPERATURE", default=None)++ monkeypatch.setenv("LANGCHAIN_TEMPERATURE", raw)+ assert OptionalFloatConfig().value == expected+def test_bool_coercion_from_env(self, monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setenv("VIBE_TRADING_DATA_CACHE", "true")c = EnvConfig()diff --git a/agent/tests/test_mandate_commit_security.py b/agent/tests/test_mandate_commit_security.pyindex 753d2df51..2eac43c25 100644--- a/agent/tests/test_mandate_commit_security.py+++ b/agent/tests/test_mandate_commit_security.py@@ -9,7 +9,10 @@ from pathlib import Pathimport pytestimport src.live.paths as paths-from src.live.mandate.commit import CommitError, commit_mandate, save_proposal+from src.live.mandate.commit import CommitError, _profile_to_hard_caps, commit_mandate, save_proposal+from src.live.enforcement import OrderIntent, check_mandate+from src.live.mandate.model import InstrumentType+from src.live.mandate.store import load_mandatepytestmark = pytest.mark.unit@@ -115,7 +118,8 @@ def test_commit_mandate_rejects_proposal_id_traversal_to_external_json(live_runtassert not mandate_path.exists()-def test_commit_mandate_persists_an_explicit_zero_exposure_narrowing(live_runtime: Path) -> None:[email protected]("exposure", [0.0, 50.0])+def test_commit_mandate_persists_an_explicit_exposure_narrowing(live_runtime: Path, exposure: float) -> None:"""A legal narrowing to zero exposure must not be widened back on persist._resolve_profile allows an adjustment to narrow max_total_exposure_usd down@@ -131,13 +135,47 @@ def test_commit_mandate_persists_an_explicit_zero_exposure_narrowing(live_runtimresult = commit_mandate(proposal_id=proposal_id,ordinal=1,- adjustments={"max_total_exposure_usd": 0.0},+ adjustments={"max_total_exposure_usd": exposure},consent_ack=True,broker="robinhood",account_ref="acct-zero",)- assert result["resolved_profile"]["max_total_exposure_usd"] == 0.0+ assert result["resolved_profile"]["max_total_exposure_usd"] == exposuremandate_path = live_runtime / "live" / "robinhood" / "mandate.json"mandate = json.loads(mandate_path.read_text(encoding="utf-8"))- assert mandate["hard_caps"]["max_total_exposure_usd"] == 0.0+ assert mandate["hard_caps"]["max_total_exposure_usd"] == exposure++ # Read the persisted contract through the same loader the order gates use.+ committed = load_mandate("robinhood")+ assert committed is not None+ breach = check_mandate(+ committed,+ OrderIntent("AAPL", "buy", 25.0, None, InstrumentType.EQUITY),+ [], {"equity": 500.0},+ broker="robinhood", remote_tool="place_equity_order", daily_count=0,+ )+ if exposure == 0:+ assert breach is not None+ assert breach.limit == "max_total_exposure_usd"+ assert breach.limit_value == 0.0+ else:+ assert breach is None+++ "profile,expected",+ [+ ({}, (0.0, 0.0, 0.0)),+ ({"max_order_usd": 100}, (100.0, 100.0, 100.0)),+ ({"max_order_usd": 100, "max_total_exposure_usd": 0}, (0.0, 100.0, 0.0)),+ ({"max_order_usd": 100, "account_funding_usd": 0}, (0.0, 100.0, 0.0)),+ ({"max_order_usd": 0, "account_funding_usd": 500}, (500.0, 0.0, 500.0)),+ ({"max_order_usd": 100, "account_funding_usd": 500, "max_total_exposure_usd": 0}, (500.0, 100.0, 0.0)),+ ({"max_order_usd": 100, "account_funding_usd": 0, "max_total_exposure_usd": 50}, (0.0, 100.0, 50.0)),+ ({"max_order_usd": None, "account_funding_usd": None, "max_total_exposure_usd": None}, (0.0, 0.0, 0.0)),+ ],+)+def test_cap_mapping_distinguishes_zero_from_an_unspecified_limit(profile, expected) -> None:+ caps = _profile_to_hard_caps(profile)+ assert (caps["account_funding_usd"], caps["max_order_notional_usd"], caps["max_total_exposure_usd"]) == expecteddiff --git a/agent/tests/test_sdk_connectors.py b/agent/tests/test_sdk_connectors.pyindex f61e7aa69..4124b0d0c 100644--- a/agent/tests/test_sdk_connectors.py+++ b/agent/tests/test_sdk_connectors.py@@ -32,7 +32,6 @@ from src.trading.connectors.okx.classification import OKX_TOOL_CLASSfrom src.trading.connectors.shoonya import sdk as shfrom src.trading.connectors.shoonya.classification import SHOONYA_TOOL_CLASSfrom src.trading.connectors.etoro import client as etoro_client-from src.trading.connectors.etoro.classification import ETORO_TOOL_CLASSfrom src.trading.connectors.tiger import sdk as tgfrom src.trading.connectors.tiger.classification import TIGER_TOOL_CLASS@@ -875,7 +874,8 @@ def test_in_broker_paper_place_order_simulated_locally(mod, Config) -> None:assert result["paper_guard"] == "simulated_locally"-def test_dhan_place_order_rejects_fractional_quantity() -> None:[email protected]("quantity", [0.5, 1.5, "1.5", "1.00000000000000001"])+def test_dhan_place_order_rejects_fractional_quantity(quantity) -> None:"""A fractional quantity must not silently truncate to a zero-share fill.Before the fix, ``int(0.5)`` truncated to 0 after the ``> 0`` check had@@ -883,12 +883,34 @@ def test_dhan_place_order_rejects_fractional_quantity() -> None:``quantity: 0`` — a fabricated successful fill for zero shares."""result = dh.place_order(- dh.DhanConfig(profile="paper"), symbol="RELIANCE", side="buy", quantity=0.5+ dh.DhanConfig(profile="paper"), symbol="RELIANCE", side="buy", quantity=quantity)assert result["status"] == "error"assert "whole number" in result["error"][email protected]("quantity", [None, 0, -1, "invalid", "", True, [], float("nan"), float("inf"), "-Infinity"])+def test_dhan_invalid_quantity_returns_an_error(quantity) -> None:+ result = dh.place_order(+ dh.DhanConfig(profile="paper"), symbol="RELIANCE", side="buy", quantity=quantity,+ )++ assert result["status"] == "error"+ assert "quantity" in result["error"]+ assert "order_id" not in result++[email protected]("quantity,expected", [(1, 1), (2.0, 2), ("3.0", 3), ("9007199254740993", 9007199254740993)])+def test_dhan_whole_quantity_is_preserved_in_the_paper_fill(quantity, expected) -> None:+ result = dh.place_order(+ dh.DhanConfig(profile="paper"), symbol="RELIANCE", side="buy", quantity=quantity,+ )++ assert result["status"] == "ok"+ assert result["quantity"] == expected+ assert result["paper_guard"] == "simulated_locally"++@pytest.mark.parametrize("mod, Config", [(dh, dh.DhanConfig), (sh, sh.ShoonyaConfig)])def test_in_broker_paper_cancel_order_simulated(mod, Config) -> None:placed = mod.place_order(Config(profile="paper"), symbol="RELIANCE", side="buy", quantity=10)