"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(shadow): model short lots in FIFO pairing and restate legs across corporate actions
Yufeng He27ecc6509d4a
diff --git a/agent/src/shadow_account/backtester.py b/agent/src/shadow_account/backtester.pyindex 769f1bc77..9473681a9 100644--- a/agent/src/shadow_account/backtester.py+++ b/agent/src/shadow_account/backtester.py@@ -33,7 +33,7 @@ from src.shadow_account.models import ()from src.shadow_account.storage import runs_dirfrom src.tools.trade_journal_parsers import parse_file, records_to_dataframe-from src.tools.trade_journal_tool import pair_trades_fifo+from src.tools.trade_journal_tool import build_frame_adjust, pair_trades_fifologger = logging.getLogger(__name__)@@ -266,11 +266,22 @@ def run_shadow_backtest(if headline_points:equity_curves["combined"] = headline_points+ # Restate journal legs to one price caliber where the run's own adjusted+ # frames cover the symbol; uncovered symbols stay raw (see #15).+ adjust_frames: dict[str, pd.DataFrame] = {}+ for currency, _, _, _ in group_results:+ artifacts_dir = base_dir / currency / "artifacts"+ if artifacts_dir.is_dir():+ for ohlcv_csv in artifacts_dir.glob("ohlcv_*.csv"):+ symbol = ohlcv_csv.stem.removeprefix("ohlcv_")+ frame = pd.read_csv(ohlcv_csv, index_col=0, parse_dates=True)+ adjust_frames.setdefault(symbol, frame)attribution, shadow_pnl, real_pnl = _attribution_or_zero(profile=profile,journal_path=journal_path,combined=combined,initial_capital=initial_capital,+ adjust=build_frame_adjust(adjust_frames) if adjust_frames else None,)result = ShadowBacktestResult(@@ -494,6 +505,7 @@ def _attribution_or_zero(journal_path: str | Path | None,combined: dict[str, float],initial_capital: float,+ adjust=None,) -> tuple[AttributionBreakdown, float | None, float]:"""Compute attribution if the journal is available, else return zeros."""shadow_pnl = _shadow_pnl_from_metrics(combined, initial_capital)@@ -508,7 +520,7 @@ def _attribution_or_zero(try:_, records = parse_file(path)trades_df = records_to_dataframe(records)- roundtrips = pair_trades_fifo(trades_df)+ roundtrips = pair_trades_fifo(trades_df, adjust=adjust)except Exception as exc:logger.warning("Attribution skipped — journal parse failed: %s", exc)return _zero_attribution(), shadow_pnl, 0.0diff --git a/agent/src/tools/trade_journal_tool.py b/agent/src/tools/trade_journal_tool.pyindex 70bb6d516..ffa55aab0 100644--- a/agent/src/tools/trade_journal_tool.py+++ b/agent/src/tools/trade_journal_tool.py@@ -28,47 +28,158 @@ from src.tools.trade_journal_parsers import (logger = logging.getLogger(__name__)+# (symbol, from_dt, to_dt) -> factor turning a from_dt price into to_dt's+# caliber, or None when the symbol has no coverage. See pair_trades_fifo.+CaliberAdjust = Any+++def build_frame_adjust(frames: dict[str, pd.DataFrame]):+ """Build a :data:`CaliberAdjust` from OHLCV frames with adjusted closes.++ The factor between two dates is ``close(to_dt) / close(from_dt)`` on the+ frame's (adjusted) close, using the last bar on or before each date when+ the exact date has no bar. Returns ``None`` for symbols or dates the+ frames do not cover, which leaves that leg raw in the pairing. The frames+ the shadow run writes are already split/dividend-adjusted on every loader+ path, so this restates both legs of a roundtrip to one caliber (#15).+ """++ def _close_on_or_before(frame: pd.DataFrame, dt: pd.Timestamp) -> float | None:+ if frame is None or frame.empty or "close" not in frame.columns:+ return None+ idx = frame.index+ pos = idx.searchsorted(dt, side="right") - 1+ if pos < 0:+ return None+ value = frame["close"].iloc[pos]+ return float(value) if pd.notna(value) and float(value) > 0 else None++ def adjust(symbol: str, from_dt, to_dt) -> float | None:+ frame = frames.get(symbol)+ if frame is None:+ return None+ start = _close_on_or_before(frame, pd.Timestamp(from_dt))+ end = _close_on_or_before(frame, pd.Timestamp(to_dt))+ if start is None or end is None:+ return None+ return end / start++ return adjust++_ALLOWED_EXT = {".csv", ".xlsx", ".xls"}-def pair_trades_fifo(df: pd.DataFrame) -> list[dict[str, Any]]:+def pair_trades_fifo(+ df: pd.DataFrame,+ adjust: "CaliberAdjust | None" = None,+) -> list[dict[str, Any]]:"""Pair buys and sells per symbol using FIFO to compute per-roundtrip PnL.+ Long lots and short lots are both modelled: a sell that finds no open+ long lot opens a short lot, and a buy first covers open shorts before+ queueing as a long (#16). Short PnL is (entry - cover) x qty.++ When ``adjust`` is given, each matched leg is restated to the sell (or+ cover) date's price caliber before PnL, so a split or dividend between+ the two dates no longer books as a fake loss or vanishes (#15). The+ callback returns the factor that turns a price at the earlier date into+ the later date's caliber, or ``None`` when no data covers the symbol,+ which leaves that leg raw. Without ``adjust`` the pairing is byte-for-byte+ the legacy raw behavior.+Args:df: Standardized DataFrame (datetime-sorted).+ adjust: Optional ``(symbol, from_dt, to_dt) -> factor | None``.Returns:List of dicts: symbol, buy_dt, sell_dt, qty, buy_price, sell_price,hold_days, pnl, pnl_pct. Unmatched positions are ignored."""- queues: dict[str, deque] = defaultdict(deque)+ longs: dict[str, deque] = defaultdict(deque)+ shorts: dict[str, deque] = defaultdict(deque)roundtrips: list[dict[str, Any]] = []+ def _factor(symbol: str, from_dt: Any, to_dt: Any) -> float | None:+ if adjust is None:+ return None+ try:+ factor = adjust(symbol, from_dt, to_dt)+ except Exception: # an adjuster miss must not break pairing+ return None+ if factor is None or factor <= 0:+ return None+ return float(factor)+for row in df.itertuples(index=False):if row.side == "buy":- queues[row.symbol].append({- "dt": row.datetime,- "qty": row.quantity,- "price": row.price,- "fee": row.fee,- })+ # Cover open shorts first, then queue any remainder as a long lot.+ remaining = row.quantity+ sq = shorts[row.symbol]+ while remaining > 1e-9 and sq:+ lot = sq[0]+ take = min(lot["qty"], remaining)+ cover_dt = pd.to_datetime(row.datetime)+ entry_dt = pd.to_datetime(lot["dt"])+ hold = (cover_dt - entry_dt).total_seconds() / 86400.0 if pd.notna(cover_dt) and pd.notna(entry_dt) else 0.0+ factor = _factor(row.symbol, entry_dt, cover_dt)+ entry_price = lot["price"] * (1.0 / factor) if factor else lot["price"]+ gross = (entry_price - row.price) * take+ entry_fee = lot["fee"] * (take / lot["qty"]) if lot["qty"] else 0.0+ cover_fee = row.fee * (take / row.quantity) if row.quantity else 0.0+ pnl = gross - entry_fee - cover_fee+ cost = entry_price * take+ pnl_pct = pnl / cost if cost else 0.0+ roundtrips.append({+ "symbol": row.symbol,+ "buy_dt": lot["dt"],+ "sell_dt": row.datetime,+ "qty": take,+ "buy_price": lot["price"],+ "sell_price": row.price,+ "hold_days": round(hold, 2),+ "pnl": round(pnl, 2),+ "pnl_pct": round(pnl_pct, 4),+ "side": "short",+ })+ lot["fee"] -= entry_fee+ lot["qty"] -= take+ remaining -= take+ if lot["qty"] <= 1e-9:+ sq.popleft()+ if remaining > 1e-9:+ longs[row.symbol].append({+ "dt": row.datetime,+ "qty": remaining,+ "price": row.price,+ "fee": row.fee,+ })continue- # sell: match against oldest buys+ # sell: match against oldest longs; anything left opens a short lot.remaining = row.quantity- q = queues[row.symbol]+ q = longs[row.symbol]while remaining > 1e-9 and q:lot = q[0]- take = min(lot["qty"], remaining)sell_dt = pd.to_datetime(row.datetime)buy_dt = pd.to_datetime(lot["dt"])+ factor = _factor(row.symbol, buy_dt, sell_dt)+ # Restate the lot to the sell date's caliber: a 1:2 split turns a+ # pre-split lot of 10@100 into 20@50, so the post-split sell+ # matches the whole position instead of half plus a phantom+ # short (#15).+ factor = factor or 1.0+ lot_qty_here = lot["qty"] / factor+ lot_price_here = lot["price"] * factor+ take = min(lot_qty_here, remaining)hold = (sell_dt - buy_dt).total_seconds() / 86400.0 if pd.notna(sell_dt) and pd.notna(buy_dt) else 0.0- gross = (row.price - lot["price"]) * take- # Proportional fee allocation- buy_fee = lot["fee"] * (take / lot["qty"]) if lot["qty"] else 0.0+ gross = (row.price - lot_price_here) * take+ # Proportional fee allocation (in original-caliber shares)+ consumed = take * factor+ buy_fee = lot["fee"] * (consumed / lot["qty"]) if lot["qty"] else 0.0sell_fee = row.fee * (take / row.quantity) if row.quantity else 0.0pnl = gross - buy_fee - sell_fee- cost = lot["price"] * take+ cost = lot_price_here * takepnl_pct = pnl / cost if cost else 0.0roundtrips.append({"symbol": row.symbol,@@ -80,12 +191,20 @@ def pair_trades_fifo(df: pd.DataFrame) -> list[dict[str, Any]]:"hold_days": round(hold, 2),"pnl": round(pnl, 2),"pnl_pct": round(pnl_pct, 4),+ "side": "long",})lot["fee"] -= buy_fee- lot["qty"] -= take+ lot["qty"] -= consumedremaining -= takeif lot["qty"] <= 1e-9:q.popleft()+ if remaining > 1e-9:+ shorts[row.symbol].append({+ "dt": row.datetime,+ "qty": remaining,+ "price": row.price,+ "fee": row.fee,+ })return roundtripsdiff --git a/agent/tests/test_trade_journal_fifo.py b/agent/tests/test_trade_journal_fifo.pynew file mode 100644index 000000000..5e96ed36b--- /dev/null+++ b/agent/tests/test_trade_journal_fifo.py@@ -0,0 +1,77 @@+"""FIFO short lots (#16) and corporate-action caliber restatement (#15).++Short sales used to vanish: the queue only modelled buy-first, so a sell+with no open long was skipped and the later cover queued as a phantom long+lot that poisoned every later match. And a split between buy and sell+fabricated a large fake loss, with cash dividends never entering fills.+"""++from __future__ import annotations++import pandas as pd++from src.tools.trade_journal_tool import build_frame_adjust, pair_trades_fifo+++def _df(rows: list[tuple]) -> pd.DataFrame:+ frame = pd.DataFrame(+ rows,+ columns=["datetime", "symbol", "name", "side", "quantity", "price", "amount", "fee"],+ )+ return frame+++def test_short_sale_and_cover_is_a_roundtrip_not_a_phantom_long() -> None:+ df = _df([+ ("2026-01-02 09:30:00", "AAPL.US", "Apple", "sell", 10.0, 100.0, 1000.0, 1.0),+ ("2026-01-05 09:30:00", "AAPL.US", "Apple", "buy", 10.0, 90.0, 900.0, 1.0),+ ])+ rts = pair_trades_fifo(df)+ assert len(rts) == 1+ rt = rts[0]+ assert rt["side"] == "short"+ # (100 - 90) * 10 - fees+ assert rt["pnl"] == 98.0+ assert rt["hold_days"] == 3.0+++def test_cover_after_long_and_short_keeps_books_separate() -> None:+ df = _df([+ ("2026-01-02 09:30:00", "AAPL.US", "Apple", "buy", 5.0, 50.0, 250.0, 0.0),+ ("2026-01-03 09:30:00", "AAPL.US", "Apple", "sell", 10.0, 100.0, 1000.0, 0.0),+ ("2026-01-04 09:30:00", "AAPL.US", "Apple", "buy", 10.0, 90.0, 900.0, 0.0),+ ])+ rts = pair_trades_fifo(df)+ # 5-share long closed at 100, then a 5-share short covered at 90.+ assert len(rts) == 2+ assert rts[0]["side"] == "long" and rts[0]["pnl"] == 250.0+ assert rts[1]["side"] == "short" and rts[1]["pnl"] == 50.0+++def _frames() -> dict[str, pd.DataFrame]:+ # 1:2 split between 2026-01-03 and 2026-01-06: the adjusted close halves+ # on the first post-split bar, so the factor from pre to post is 0.5.+ idx = pd.to_datetime(["2026-01-02", "2026-01-03", "2026-01-06"])+ return {"AAPL.US": pd.DataFrame({"close": [100.0, 100.0, 50.0]}, index=idx)}+++def test_split_between_legs_no_longer_fabricates_a_loss() -> None:+ df = _df([+ ("2026-01-03 09:30:00", "AAPL.US", "Apple", "buy", 10.0, 100.0, 1000.0, 0.0),+ ("2026-01-06 09:30:00", "AAPL.US", "Apple", "sell", 20.0, 50.0, 1000.0, 0.0),+ ])+ raw = pair_trades_fifo(df)+ assert raw[0]["pnl"] == -500.0 # the fake loss this issue is about++ adjusted = pair_trades_fifo(df, adjust=build_frame_adjust(_frames()))+ # Buy leg restated to the post-split caliber: 100 * 0.5 = 50, pnl = 0.+ assert adjusted[0]["pnl"] == 0.0+++def test_uncovered_symbol_stays_raw() -> None:+ df = _df([+ ("2026-01-03 09:30:00", "MSFT.US", "Microsoft", "buy", 10.0, 100.0, 1000.0, 0.0),+ ("2026-01-06 09:30:00", "MSFT.US", "Microsoft", "sell", 10.0, 50.0, 500.0, 0.0),+ ])+ rts = pair_trades_fifo(df, adjust=build_frame_adjust({}))+ assert rts[0]["pnl"] == -500.0