Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(journal): combine separate generic date and time columns

Rix48c82aee2ab1
diff --git a/README.md b/README.md
index ac25e9cca..d047f5042 100644
--- a/README.md
+++ b/README.md
@@ -1471,6 +1471,11 @@ an opposite position, its fee is split by quantity between the two legs.
Profile win rate and the average-win/average-loss ratio use the resulting net
PnL of FIFO matched portions; those portions are not necessarily whole orders.
+Generic journals accept a complete `datetime` column or separate `date` and
+`time` columns (case-insensitive). Split columns are combined before sorting
+and FIFO matching; Excel date serials and time fractions are supported.
+A complete `datetime` column takes precedence when all three are present.
+
### Market Research
```bash
diff --git a/agent/src/tools/trade_journal_parsers.py b/agent/src/tools/trade_journal_parsers.py
index 7eacbd72b..5106bbd75 100644
--- a/agent/src/tools/trade_journal_parsers.py
+++ b/agent/src/tools/trade_journal_parsers.py
@@ -586,8 +586,9 @@ def parse_generic(df: pd.DataFrame) -> list[TradeRecord]:
return colmap[n]
return None
- dt_col = pick("datetime", "time")
+ dt_col = pick("datetime")
date_col = pick("date")
+ time_col = pick("time")
sym_col = pick("symbol", "ticker", "code")
name_col = pick("name", "instrument")
side_col = pick("side", "direction", "action")
@@ -610,9 +611,13 @@ def parse_generic(df: pd.DataFrame) -> list[TradeRecord]:
if dt_col:
raw_dt = row.get(dt_col, "")
dt = _generic_datetime_cell(raw_dt)
+ elif date_col and time_col:
+ dt = _generic_split_datetime(row.get(date_col), row.get(time_col))
elif date_col:
raw_dt = row.get(date_col, "")
dt = _generic_datetime_cell(raw_dt)
+ elif time_col:
+ dt = _generic_datetime_cell(row.get(time_col))
else:
dt = ""
symbol = str(row.get(sym_col, "")).strip() if sym_col else ""
@@ -639,6 +644,26 @@ def parse_generic(df: pd.DataFrame) -> list[TradeRecord]:
return records
+def _generic_split_datetime(date_val: Any, time_val: Any) -> str:
+ """Combine a generic date with a clock string or Excel day fraction."""
+ date = _generic_datetime_cell(date_val)
+ day = pd.to_datetime(date, errors="coerce")
+ # Never let a clock alone replace a missing/invalid date with today.
+ if pd.isna(day) or time_val is None or pd.isna(time_val):
+ return date
+ time = str(time_val).strip()
+ if not time:
+ return date
+ try:
+ fraction = float(time)
+ except ValueError:
+ fraction = None
+ if fraction is not None and 0 <= fraction < 1:
+ combined = day.normalize() + pd.to_timedelta(fraction, unit="D")
+ return combined.strftime("%Y-%m-%d %H:%M:%S")
+ return _generic_datetime_cell(f"{day:%Y-%m-%d} {time}")
+
+
def _generic_datetime_cell(val: Any) -> str:
"""Normalize a generic datetime/date cell; Excel serials become ISO datetime."""
if val is None or (isinstance(val, float) and pd.isna(val)):
diff --git a/agent/tests/test_generic_split_datetime.py b/agent/tests/test_generic_split_datetime.py
new file mode 100644
index 000000000..13e03edcc
--- /dev/null
+++ b/agent/tests/test_generic_split_datetime.py
@@ -0,0 +1,97 @@
+"""Separate date/time columns must preserve chronology and FIFO economics."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pandas as pd
+import pytest
+
+from src.tools.trade_journal_parsers import parse_generic
+from src.tools.trade_journal_tool import analyze_trade_journal
+
+
+def _record(**dates):
+ frame = pd.DataFrame(
+ [{"symbol": "AAPL", "side": "buy", "quantity": 1, "price": 100, **dates}]
+ )
+ return parse_generic(frame)[0]
+
+
+ "date,time,expected",
+ [
+ ("2024-01-30", "09:30:15", "2024-01-30 09:30:15"),
+ ("45321", "09:30:15", "2024-01-30 09:30:15"),
+ (45321, 0.375, "2024-01-30 09:00:00"),
+ ("45321.0", "0.375", "2024-01-30 09:00:00"),
+ ("2024-01-30", "0.375", "2024-01-30 09:00:00"),
+ ("2024-01-30", 0.0, "2024-01-30 00:00:00"),
+ ("2024-01-30", "", "2024-01-30 00:00:00"),
+ ("2024-01-30", None, "2024-01-30 00:00:00"),
+ ("2024-01-30", float("nan"), "2024-01-30 00:00:00"),
+ ],
+)
+def test_split_date_time_cells(date, time, expected):
+ assert _record(date=date, time=time).datetime == expected
+
+
+def test_complete_datetime_takes_priority_over_date_and_time():
+ record = _record(datetime="2024-01-30 14:25:00", date="2020-01-01", time="09:30:00")
+ assert record.datetime == "2024-01-30 14:25:00"
+
+
[email protected]("column", ["datetime", "date", "time"])
+def test_single_datetime_columns_keep_existing_behavior(column):
+ assert _record(**{column: "2024-01-30 14:25:00"}).datetime == (
+ "2024-01-30 14:25:00"
+ )
+
+
[email protected]("date", ["", "not-a-date"])
+def test_bad_split_date_does_not_turn_clock_into_todays_date(date):
+ assert pd.isna(
+ pd.to_datetime(_record(date=date, time="09:30:00").datetime, errors="coerce")
+ )
+
+
[email protected]("reverse_rows", [False, True])
+def test_split_csv_preserves_net_winners_and_date_filters(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, reverse_rows: bool
+):
+ monkeypatch.setenv("VIBE_TRADING_ALLOWED_FILE_ROOTS", str(tmp_path))
+ rows = [
+ "2026-01-01,15:00:00,AAPL,buy,1,100,1",
+ "2026-01-02,09:00:00,AAPL,sell,1,105,1",
+ "2026-01-03,10:00:00,AAPL,buy,1,110,1",
+ "2026-01-04,11:00:00,AAPL,sell,1,120,1",
+ "2026-01-05,12:00:00,MSFT,buy,1,50,1",
+ "2026-01-06,13:00:00,MSFT,sell,1,48,1",
+ ]
+ path = tmp_path / "journal.csv"
+ path.write_text(
+ "Date,Time,Symbol,Side,Qty,Price,Fee\n"
+ + "\n".join(reversed(rows) if reverse_rows else rows)
+ + "\n",
+ encoding="utf-8",
+ )
+
+ result = json.loads(analyze_trade_journal(str(path), "profile"))
+ assert result["status"] == "ok"
+ assert result["format_detected"] == "generic"
+ assert result["date_range"] == "2026-01-01 ~ 2026-01-06"
+ profile = result["profile"]
+ # Hand calculation: (105-100)-2=3; (120-110)-2=8; (48-50)-2=-4.
+ assert [r["pnl"] for r in profile["roundtrips_sample"]] == [3, 8, -4]
+ assert all(r["side"] == "long" for r in profile["roundtrips_sample"])
+ assert profile["total_pnl"] == 7
+ assert profile["win_rate"] == 0.6667
+ assert profile["profit_loss_ratio"] == 1.38 # ((3 + 8) / 2) / 4
+ assert [r["hold_days"] for r in profile["roundtrips_sample"]] == [0.75, 1.04, 1.04]
+
+ filtered = json.loads(
+ analyze_trade_journal(str(path), "profile", "2026-01 to 2026-01")
+ )
+ assert filtered["total_records"] == 6
+ assert filtered["profile"]["win_rate"] == 0.6667