"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(agent): parse cash-dividend journal rows and book them in shadow real PnL
Yufeng Hec70d77713451
diff --git a/agent/src/shadow_account/backtester.py b/agent/src/shadow_account/backtester.pyindex 7ec69ca6c..3203c2402 100644--- a/agent/src/shadow_account/backtester.py+++ b/agent/src/shadow_account/backtester.py@@ -284,6 +284,7 @@ def run_shadow_backtest(initial_capital=initial_capital,pool_currency=headline_currency,adjust=build_frame_adjust(adjust_frames) if adjust_frames else None,+ covered_symbols=frozenset(adjust_frames),)result = ShadowBacktestResult(@@ -538,6 +539,7 @@ def _attribution_or_zero(initial_capital: float,pool_currency: str | None = None,adjust=None,+ covered_symbols: frozenset[str] = frozenset(),) -> tuple[AttributionBreakdown, float | None, float]:"""Compute attribution if the journal is available, else return zeros."""shadow_pnl = _shadow_pnl_from_metrics(combined, initial_capital)@@ -560,14 +562,46 @@ def _attribution_or_zero(if not roundtrips:return _zero_attribution(), shadow_pnl, 0.0+ dividend_cash = _dividend_cash(+ trades_df, covered_symbols=covered_symbols, pool_currency=pool_currency,+ )return _compute_attribution(profile=profile,roundtrips=roundtrips,shadow_pnl=shadow_pnl,pool_currency=pool_currency,+ extra_real_pnl=dividend_cash,)+def _dividend_cash(+ trades_df: pd.DataFrame,+ *,+ covered_symbols: frozenset[str],+ pool_currency: str | None,+) -> float:+ """Sum cash-dividend rows the adjusted frames do not already capture.++ When the run's adjusted frames cover a symbol, the dividend is embedded in+ the adjusted-close caliber the roundtrip legs are restated through (#1311),+ so booking the cash as well would count it twice; only dividends on+ uncovered symbols add to real PnL here. Rows settling in a currency other+ than the pool's are excluded exactly like the roundtrips are (#14).+ """+ if trades_df.empty or "side" not in trades_df.columns:+ return 0.0+ total = 0.0+ for row in trades_df.itertuples(index=False):+ if row.side != "dividend":+ continue+ if row.symbol in covered_symbols:+ continue+ if pool_currency is not None and code_currency(row.symbol) != pool_currency:+ continue+ total += float(row.amount)+ return total++def _zero_attribution() -> AttributionBreakdown:return AttributionBreakdown(missed_signals_pnl=0.0,@@ -585,6 +619,7 @@ def _compute_attribution(roundtrips: list[dict[str, Any]],shadow_pnl: float,pool_currency: str | None = None,+ extra_real_pnl: float = 0.0,) -> tuple[AttributionBreakdown, float, float]:"""Attribute the delta between user's real PnL and shadow PnL.@@ -609,6 +644,10 @@ def _compute_attribution(are excluded from ``real_pnl`` and counted in``AttributionBreakdown.excluded_currencies`` instead of being summedagainst it (#14).++ ``extra_real_pnl`` carries real cash the roundtrips do not capture (cash+ dividends on symbols the run's adjusted frames do not cover). It is added+ into ``real_pnl`` so the ``missed`` residual stays balanced."""rule_hold_lo, rule_hold_hi = _aggregate_holding_range(profile)noise = 0.0@@ -625,7 +664,7 @@ def _compute_attribution(currency = code_currency(rt["symbol"])if currency != pool_currency:excluded_currencies[currency] = excluded_currencies.get(currency, 0) + 1- real_pnl = 0.0+ real_pnl = float(extra_real_pnl)counterfactuals: list[dict[str, Any]] = []for rt in pool_roundtrips:diff --git a/agent/src/tools/trade_journal_parsers.py b/agent/src/tools/trade_journal_parsers.pyindex eae0b4875..8e23dbf58 100644--- a/agent/src/tools/trade_journal_parsers.py+++ b/agent/src/tools/trade_journal_parsers.py@@ -58,6 +58,41 @@ _SELL_TOKENS = {"做空","short",}+# Cash dividend events (同花顺 红利入账, 富途 Side=Dividend, ...). They bring+# cash into the account without moving shares, so they parse as+# side="dividend" records whose `amount` carries the cash received.+_DIVIDEND_TOKENS = {+ "dividend",+ "cash dividend",+ "红利入账",+ "红利",+ "分红",+ "分红入账",+ "派息",+ "股息入账",+ "股息",+ "现金分红",+}+# Non-trade corporate-action rows are dropped outright instead of parsed:+# bonus-share / conversion credits and splits only move share counts (the+# frame-caliber adjustment from #1311 already restates split effects on+# covered symbols, and we do not model bonus shares), rights issues are a+# separate subscription flow, and 利息 entries are interest settlements, not+# trade PnL. The English tokens cover Futu/generic exports of the same events.+_SKIP_SIDE_TOKENS = {+ "红股入账",+ "转股入账",+ "配股缴款",+ "配股上市",+ "利息归本",+ "利息",+ "stock dividend",+ "bonus issue",+ "stock split",+ "reverse split",+ "rights issue",+ "interest",+}@dataclass(frozen=True)@@ -68,7 +103,7 @@ class TradeRecord:datetime: ISO8601 timestamp, e.g. "2026-01-15 09:35:00".symbol: Exchange-qualified symbol, e.g. "600519.SH" / "AAPL" / "BTC-USDT".name: Human-readable instrument name.- side: "buy" or "sell".+ side: "buy", "sell" or "dividend" (cash payout; amount is the cash).quantity: Filled quantity.price: Filled price.amount: Gross amount (quantity * price, pre-fee).@@ -155,7 +190,7 @@ def detect_format(df: pd.DataFrame) -> FormatName:# ---------------- Parsers ----------------def _normalize_side(raw: Any) -> str:- """Return ``buy`` or ``sell`` for an exact supported direction alias.+ """Return ``buy``/``sell``/``dividend`` for an exact supported direction alias.Raises:ValueError: Direction is missing or unsupported.@@ -169,9 +204,23 @@ def _normalize_side(raw: Any) -> str:return "buy"if s in _SELL_TOKENS:return "sell"+ if s in _DIVIDEND_TOKENS:+ return "dividend"raise ValueError(f"Unsupported trade side: {raw!r}")+def _is_skippable_side(raw: Any) -> bool:+ """True for known non-trade corporate-action rows; callers drop the row."""+ if raw is None:+ return False+ try:+ if pd.isna(raw):+ return False+ except (TypeError, ValueError):+ pass+ return str(raw).strip().lower() in _SKIP_SIDE_TOKENS++def _is_empty_code(raw: Any) -> bool:"""True for None/NaN/blank securities codes from CSV/Excel cells."""if raw is None:@@ -232,6 +281,8 @@ def parse_tonghuashun(df: pd.DataFrame) -> list[TradeRecord]:raw_code = row.get("证券代码", "")if _is_empty_code(raw_code):continue+ if _is_skippable_side(row.get("操作")):+ continueqty = _to_float(row.get("成交数量"))price = _to_float(row.get("成交价格"))amount = _to_float(row.get("成交金额")) or qty * price@@ -289,6 +340,8 @@ def parse_eastmoney(df: pd.DataFrame) -> list[TradeRecord]:raw_code = row.get("股票代码", "")if _is_empty_code(raw_code):continue+ if _is_skippable_side(row.get("买卖标志")):+ continueraw_date = str(row.get("成交日期", "")).strip()# Excel numeric YYYYMMDD cells stringify as "20260115.0".# Day-count serials (dtype=str load) arrive as "44941" / "44941.0".@@ -410,6 +463,9 @@ def parse_futu(df: pd.DataFrame) -> list[TradeRecord]:raw_symbol = row.get("Symbol", "")if _is_empty_code(raw_symbol):continue+ side_raw = row.get("Side") if "Side" in df.columns else row.get("Direction")+ if _is_skippable_side(side_raw):+ continuedt = _futu_datetime(row.get("Date", ""), row.get("Time", ""))symbol = str(raw_symbol).strip().upper()qty = _to_float(row.get("Quantity"))@@ -420,7 +476,7 @@ def parse_futu(df: pd.DataFrame) -> list[TradeRecord]:datetime=dt,symbol=symbol,name=str(row.get("Name", "")).strip(),- side=_normalize_side(row.get("Side") if "Side" in df.columns else row.get("Direction")),+ side=_normalize_side(side_raw),quantity=qty,price=price,amount=amount,@@ -467,6 +523,8 @@ def parse_generic(df: pd.DataFrame) -> list[TradeRecord]:for _, row in df.iterrows():if sym_col and _is_empty_code(row.get(sym_col)):continue+ if _is_skippable_side(row.get(side_col)):+ continueif dt_col:raw_dt = row.get(dt_col, "")dt = _generic_datetime_cell(raw_dt)diff --git a/agent/src/tools/trade_journal_tool.py b/agent/src/tools/trade_journal_tool.pyindex 8670e0954..eae9be958 100644--- a/agent/src/tools/trade_journal_tool.py+++ b/agent/src/tools/trade_journal_tool.py@@ -112,6 +112,9 @@ def pair_trades_fifo(return float(factor)for row in df.itertuples(index=False):+ # Dividend cash rows and other non-trade events carry no position change.+ if row.side not in ("buy", "sell"):+ continueif row.side == "buy":# Cover open shorts first, then queue any remainder as a long lot.remaining = row.quantity@@ -224,12 +227,15 @@ def _compute_profile(df: pd.DataFrame) -> dict[str, Any]:"""Build the trading profile dict.Args:- df: Standardized DataFrame (datetime parsed, sorted).+ df: Standardized DataFrame (datetime parsed, sorted). May carry+ dividend cash rows; those are summed into ``total_dividends`` and+ ``total_pnl`` but never counted as trades.Returns:Dict with avg_holding_days, trade_frequency_per_week, win_rate,- profit_loss_ratio, total_pnl, max_drawdown, top_symbols,- market_distribution, hourly_distribution, roundtrips_sample.+ profit_loss_ratio, total_pnl, total_dividends, max_drawdown,+ top_symbols, market_distribution, hourly_distribution,+ roundtrips_sample."""if df.empty:return {"error": "empty trade journal"}@@ -237,7 +243,11 @@ def _compute_profile(df: pd.DataFrame) -> dict[str, Any]:rts = pair_trades_fifo(df)rts_df = pd.DataFrame(rts)- total_trades = len(df)+ trades_df = df[df["side"].isin(("buy", "sell"))]+ dividend_amounts = df.loc[df["side"] == "dividend", "amount"]+ total_dividends = round(float(dividend_amounts.sum()), 2)++ total_trades = len(trades_df)span_days = max(1, (df["datetime"].max() - df["datetime"].min()).days)freq_per_week = round(total_trades / span_days * 7, 2)@@ -249,14 +259,15 @@ def _compute_profile(df: pd.DataFrame) -> dict[str, Any]:win_rate = round(len(wins) / len(rts_df), 4)pnl_ratio = round(_safe_div(avg_win, abs(avg_loss)), 2) if avg_loss else float("inf") if avg_win else 0.0avg_hold = round(rts_df["hold_days"].mean(), 2)- total_pnl = round(rts_df["pnl"].sum(), 2)+ total_pnl = round(rts_df["pnl"].sum() + total_dividends, 2)# Cumulative PnL → max drawdowncum = rts_df.sort_values("sell_dt")["pnl"].cumsum()running_max = cum.cummax()drawdown = (cum - running_max).min()max_drawdown = round(float(drawdown), 2) if pd.notna(drawdown) else 0.0else:- win_rate = pnl_ratio = avg_hold = total_pnl = max_drawdown = 0.0+ win_rate = pnl_ratio = avg_hold = max_drawdown = 0.0+ total_pnl = total_dividendstop_symbols = (df.groupby("symbol")@@ -268,8 +279,8 @@ def _compute_profile(df: pd.DataFrame) -> dict[str, Any]:.to_dict(orient="records"))- market_dist = df["market"].value_counts().to_dict()- hourly_dist = df["datetime"].dt.hour.value_counts().sort_index().to_dict()+ market_dist = trades_df["market"].value_counts().to_dict()+ hourly_dist = trades_df["datetime"].dt.hour.value_counts().sort_index().to_dict()hourly_dist = {int(h): int(c) for h, c in hourly_dist.items()}sample = rts_df.head(5).copy()@@ -288,6 +299,7 @@ def _compute_profile(df: pd.DataFrame) -> dict[str, Any]:"win_rate": win_rate,"profit_loss_ratio": pnl_ratio,"total_pnl": total_pnl,+ "total_dividends": total_dividends,"max_drawdown": max_drawdown,"top_symbols": top_symbols,"market_distribution": market_dist,@@ -468,7 +480,8 @@ def _compute_behavior(df: pd.DataFrame) -> dict[str, Any]:"""Run all 4 behavior diagnostics.Args:- df: Standardized DataFrame (datetime-sorted).+ df: Standardized DataFrame (datetime-sorted). Diagnostics run on the+ buy/sell rows only; dividend cash rows are not trading behavior.Returns:Dict with disposition_effect / overtrading / chasing_momentum /@@ -476,12 +489,13 @@ def _compute_behavior(df: pd.DataFrame) -> dict[str, Any]:"""if df.empty:return {"error": "empty trade journal"}+ trades_df = df[df["side"].isin(("buy", "sell"))]rts_df = pd.DataFrame(pair_trades_fifo(df))return {"disposition_effect": _disposition_effect(rts_df),- "overtrading": _overtrading(df, rts_df),- "chasing_momentum": _chasing_momentum(df),- "anchoring": _anchoring(df),+ "overtrading": _overtrading(trades_df, rts_df),+ "chasing_momentum": _chasing_momentum(trades_df),+ "anchoring": _anchoring(trades_df),}diff --git a/agent/tests/test_shadow_account.py b/agent/tests/test_shadow_account.pyindex e6af61928..2a826fb41 100644--- a/agent/tests/test_shadow_account.py+++ b/agent/tests/test_shadow_account.py@@ -759,6 +759,116 @@ def test_all_currency_groups_failure(assert all(row == {} for row in result.per_market.values())+# ---------------- M3c: cash dividends in the journal ----------------++def _journal_with_dividend(path: Path, *, include_dividend: bool = True) -> Path:+ """One 600519 roundtrip plus (optionally) a 500-yuan 红利入账 cash row."""+ rows = _make_tonghuashun_rows([+ ("2026-01-02 10:30:00", "600519", "buy", 100.0, 10.0),+ ("2026-01-05 14:15:00", "600519", "sell", 100.0, 10.2),+ ])+ if include_dividend:+ rows.append({+ "成交时间": "2026-01-10 09:00:00",+ "证券代码": "600519",+ "证券名称": "标的600519",+ "操作": "红利入账",+ "成交数量": 0.0,+ "成交价格": 0.0,+ "成交金额": 500.0,+ "手续费": 0.0,+ "印花税": 0.0,+ "过户费": 0.0,+ })+ return _write_journal(path, rows)+++def _dividend_scenario_run(+ profile: ShadowProfile, journal: Path, *, with_frame: bool,+) -> ShadowBacktestResult:+ """Run the shadow backtest over a dividend journal with a stub runner.++ With ``with_frame`` the CNY pool also emits an ohlcv artifact for+ 600519.SH (constant closes, so the caliber factor is 1.0 and roundtrip+ PnL is unchanged), which marks the symbol as frame-covered.+ """+ metrics = {+ "CNY": {"total_return_abs": 1000.0, "sharpe": 1.0},+ "HKD": {"total_return_abs": 200.0, "sharpe": 2.0},+ "USD": {"total_return_abs": 300.0, "sharpe": 3.0},+ }++ def stub(run_dir_str: str) -> str:+ run_path = Path(run_dir_str)+ artifacts_dir = run_path / "artifacts"+ artifacts_dir.mkdir(parents=True, exist_ok=True)+ metrics_path = artifacts_dir / "metrics.json"+ metrics_path.write_text(+ json.dumps(metrics[run_path.name]), encoding="utf-8",+ )+ if with_frame and run_path.name == "CNY":+ (artifacts_dir / "ohlcv_600519.SH.csv").write_text(+ "date,close\n"+ "2026-01-01,10.0\n2026-01-02,10.0\n"+ "2026-01-05,10.0\n2026-01-10,10.0\n",+ encoding="utf-8",+ )+ return json.dumps({+ "status": "ok", "exit_code": 0,+ "artifacts": {"metrics.json": str(metrics_path)},+ })++ return run_shadow_backtest(+ profile,+ window_start="2026-01-01",+ window_end="2026-06-30",+ journal_path=journal,+ run_backtest_fn=stub,+ )+++def test_uncovered_symbol_dividend_raises_real_pnl_and_shrinks_missed(+ profitable_journal: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("HOME", str(tmp_path))+ monkeypatch.setenv("USERPROFILE", str(tmp_path))+ profile = extract_shadow_profile(profitable_journal)+ plain = _journal_with_dividend(tmp_path / "journal_plain.csv", include_dividend=False)+ with_div = _journal_with_dividend(tmp_path / "journal_div.csv")++ baseline = _dividend_scenario_run(profile, plain, with_frame=False)+ treated = _dividend_scenario_run(profile, with_div, with_frame=False)++ assert treated.real_total_pnl == pytest.approx(baseline.real_total_pnl + 500.0)+ # The roundtrip decomposition is untouched; only the residual absorbs it.+ assert treated.attribution.noise_trades_pnl == baseline.attribution.noise_trades_pnl+ assert treated.attribution.early_exit_pnl == baseline.attribution.early_exit_pnl+ assert treated.attribution.missed_signals_pnl == pytest.approx(+ baseline.attribution.missed_signals_pnl - 500.0+ )+++def test_frame_covered_symbol_dividend_is_not_double_counted(+ profitable_journal: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("HOME", str(tmp_path))+ monkeypatch.setenv("USERPROFILE", str(tmp_path))+ profile = extract_shadow_profile(profitable_journal)+ with_div = _journal_with_dividend(tmp_path / "journal_div.csv")++ uncovered = _dividend_scenario_run(profile, with_div, with_frame=False)+ covered = _dividend_scenario_run(profile, with_div, with_frame=True)++ # The dividend is already embedded in the adjusted price caliber for a+ # frame-covered symbol, so the cash must not be added on top of it.+ assert covered.real_total_pnl == pytest.approx(uncovered.real_total_pnl - 500.0)+ assert covered.attribution.missed_signals_pnl == pytest.approx(+ uncovered.attribution.missed_signals_pnl + 500.0+ )++# ---------------- M4: Reporter ----------------def _stub_backtest_result(profile: ShadowProfile) -> ShadowBacktestResult:diff --git a/agent/tests/test_trade_journal.py b/agent/tests/test_trade_journal.pyindex 91f91ae23..620221059 100644--- a/agent/tests/test_trade_journal.py+++ b/agent/tests/test_trade_journal.py@@ -113,6 +113,49 @@ def test_normalize_side_rejects_missing_or_unknown(raw: object) -> None:_normalize_side(raw)+ "raw",+ [+ "红利入账",+ "红利",+ "分红",+ "分红入账",+ "派息",+ "股息入账",+ "股息",+ "现金分红",+ "Dividend",+ " Cash Dividend ",+ ],+)+def test_normalize_side_dividend_tokens(raw: str) -> None:+ assert _normalize_side(raw) == "dividend"+++ "raw", ["红股入账", "转股入账", "配股缴款", "配股上市", "利息归本", "利息"]+)+def test_tonghuashun_corporate_action_rows_are_skipped(raw: str) -> None:+ """Known non-trade corporate-action rows drop out instead of raising."""+ df = pd.DataFrame([{+ "成交时间": "2026-01-10 09:00:00", "证券代码": "600519", "证券名称": "贵州茅台",+ "操作": raw, "成交数量": "100", "成交价格": "", "成交金额": "",+ "手续费": "", "印花税": "", "过户费": "",+ }])+ assert parse_tonghuashun(df) == []+++ "raw", ["stock dividend", "stock split", "bonus issue", "rights issue", "interest"]+)+def test_generic_corporate_action_rows_are_skipped(raw: str) -> None:+ df = pd.DataFrame([{+ "datetime": "2026-01-10 09:00:00", "symbol": "AAPL",+ "side": raw, "quantity": "", "price": "",+ }])+ assert parse_generic(df) == []++@pytest.mark.parametrize("symbol,expected",[@@ -206,6 +249,46 @@ def test_parse_file_tonghuashun_csv(tmp_path: Path) -> None:assert records[1].fee == pytest.approx(5 + 180 + 0.1)+def test_parse_file_tonghuashun_dividend_and_bonus_rows(tmp_path: Path) -> None:+ """A 红利入账 row used to kill the whole parse with "Unsupported trade side"."""+ csv = tmp_path / "ths_dividend.csv"+ csv.write_text(+ "成交时间,证券代码,证券名称,操作,成交数量,成交价格,成交金额,手续费,印花税,过户费\n"+ "2026-01-02 09:35:00,600519,贵州茅台,买入,100,1700,170000,5,0,0.1\n"+ "2026-01-10 09:00:00,600519,贵州茅台,红利入账,,,500,0,0,0\n"+ "2026-01-12 09:00:00,600519,贵州茅台,红股入账,10,,,0,0,0\n",+ encoding="utf-8",+ )+ fmt, records = parse_file(csv)+ assert fmt == "tonghuashun"+ # The bonus-share row is dropped; the dividend row keeps its cash in amount.+ assert [r.side for r in records] == ["buy", "dividend"]+ dividend = records[1]+ assert dividend.symbol == "600519.SH"+ assert dividend.amount == 500.0+ assert dividend.quantity == 0.0+++def test_parse_futu_dividend_row_carries_cash_amount() -> None:+ df = pd.DataFrame([+ {+ "Date": "2026-01-02", "Time": "10:00:00", "Symbol": "AAPL",+ "Name": "Apple", "Side": "Buy", "Quantity": "10", "Price": "180",+ "Amount": "1800", "Commission": "1", "Platform Fee": "0",+ },+ {+ "Date": "2026-01-10", "Time": "", "Symbol": "AAPL",+ "Name": "Apple", "Side": "Dividend", "Quantity": "", "Price": "",+ "Amount": "25.5", "Commission": "", "Platform Fee": "",+ },+ ])+ records = parse_futu(df)+ assert [r.side for r in records] == ["buy", "dividend"]+ assert records[1].amount == 25.5+ assert records[1].quantity == 0.0+ assert records[1].market == "us"++def test_parse_file_unknown_raises(tmp_path: Path) -> None:csv = tmp_path / "weird.csv"csv.write_text("foo,bar\n1,2\n", encoding="utf-8")@@ -355,6 +438,52 @@ def test_compute_profile_win_rate_and_pnl() -> None:assert profile["total_pnl"] == -300.0 # 200 - 500+def _dividend_rec(dt: str, symbol: str, amount: float, market: str = "china_a") -> TradeRecord:+ return TradeRecord(+ datetime=dt,+ symbol=symbol,+ name="",+ side="dividend",+ quantity=0.0,+ price=0.0,+ amount=amount,+ fee=0.0,+ market=market,+ )+++def test_compute_profile_dividend_rows() -> None:+ profile = _compute_profile(+ _df(+ [+ _rec("2026-01-01 10:00:00", "A.SH", "buy", 100, 10),+ _rec("2026-01-05 10:00:00", "A.SH", "sell", 100, 12), # +200 win+ _dividend_rec("2026-01-10 09:00:00", "A.SH", 500.0),+ ]+ )+ )+ assert profile["total_trades"] == 2 # the dividend row is not a trade+ assert profile["total_roundtrips"] == 1+ assert profile["total_dividends"] == 500.0+ assert profile["total_pnl"] == 700.0 # 200 roundtrip + 500 dividend+ # A 09:00 dividend row must not leak into the trading-activity stats.+ assert profile["market_distribution"] == {"china_a": 2}+ assert profile["hourly_distribution"] == {10: 2}+++def test_compute_profile_without_dividends_is_unchanged() -> None:+ profile = _compute_profile(+ _df(+ [+ _rec("2026-01-01 10:00:00", "A.SH", "buy", 100, 10),+ _rec("2026-01-05 10:00:00", "A.SH", "sell", 100, 12),+ ]+ )+ )+ assert profile["total_dividends"] == 0.0+ assert profile["total_pnl"] == 200.0++def test_compute_profile_empty() -> None:assert _compute_profile(records_to_dataframe([])) == {"error": "empty trade journal"}diff --git a/agent/tests/test_trade_journal_fifo.py b/agent/tests/test_trade_journal_fifo.pyindex dfc985744..1f2a33eaf 100644--- a/agent/tests/test_trade_journal_fifo.py+++ b/agent/tests/test_trade_journal_fifo.py@@ -114,3 +114,35 @@ def test_short_without_adjust_is_unchanged() -> None:rt = pair_trades_fifo(df)[0]assert rt["side"] == "short"assert rt["pnl"] == 200.0 # (100 - 80) * 10+++def test_dividend_rows_do_not_open_or_close_positions() -> None:+ """A dividend cash row between the legs leaves the roundtrip untouched."""+ df = _df([+ ("2026-01-02 09:30:00", "AAPL.US", "Apple", "buy", 10.0, 100.0, 1000.0, 0.0),+ ("2026-01-03 09:30:00", "AAPL.US", "Apple", "dividend", 0.0, 0.0, 25.0, 0.0),+ ("2026-01-05 09:30:00", "AAPL.US", "Apple", "sell", 10.0, 110.0, 1100.0, 0.0),+ ])+ rts = pair_trades_fifo(df)+ assert len(rts) == 1+ assert rts[0]["side"] == "long"+ assert rts[0]["pnl"] == 100.0 # (110 - 100) * 10+++def test_dividend_row_does_not_cover_an_open_short() -> None:+ df = _df([+ ("2026-01-02 09:30:00", "AAPL.US", "Apple", "sell", 10.0, 100.0, 1000.0, 0.0),+ ("2026-01-03 09:30:00", "AAPL.US", "Apple", "dividend", 0.0, 0.0, 25.0, 0.0),+ ("2026-01-05 09:30:00", "AAPL.US", "Apple", "buy", 10.0, 90.0, 900.0, 0.0),+ ])+ rts = pair_trades_fifo(df)+ assert len(rts) == 1+ assert rts[0]["side"] == "short"+ assert rts[0]["pnl"] == 100.0 # (100 - 90) * 10+++def test_dividend_only_journal_yields_no_roundtrips() -> None:+ df = _df([+ ("2026-01-03 09:30:00", "AAPL.US", "Apple", "dividend", 0.0, 0.0, 25.0, 0.0),+ ])+ assert pair_trades_fifo(df) == []