Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat: trade journal analyzer — profile + behavior diagnostics

warren6182b0a775db0dc
diff --git a/.gitignore b/.gitignore
index 16984e30b..65a0df2f0 100644
--- a/.gitignore
+++ b/.gitignore
@@ -16,6 +16,7 @@ agent/sessions/
agent/runs/
agent/.ui_runtime/
agent/.tasks/
+agent/uploads/
agent/tests/*_result.json
.ruff_cache/
frontend/dist/
diff --git a/agent/src/agent/context.py b/agent/src/agent/context.py
index 03972e71c..d06ac00ac 100644
--- a/agent/src/agent/context.py
+++ b/agent/src/agent/context.py
@@ -52,6 +52,12 @@ Decide which workflow to use based on the request:
**Document / web** — user provides a PDF or URL:
- `read_document(path=...)` for PDFs, `read_url(url=...)` for web pages.
+**Trade journal** — user uploads a CSV/Excel broker export (交割单) or asks to analyze their own trading history:
+1. `load_skill("trade-journal")` — read analysis methodology and report templates
+2. `analyze_trade_journal(file_path=..., analysis_type="full")` — parse + profile
+3. Present results as the markdown report in the skill. Offer follow-ups: time-slice, symbol deep-dive, market split.
+4. Behavior diagnostics + strategy extraction are Phase 4b — tell the user they're coming, don't fabricate.
+
## Guidelines
- Load the relevant skill BEFORE starting any task. Skills contain the exact API contracts and examples.
diff --git a/agent/src/skills/trade-journal/SKILL.md b/agent/src/skills/trade-journal/SKILL.md
new file mode 100644
index 000000000..ec62eda4f
--- /dev/null
+++ b/agent/src/skills/trade-journal/SKILL.md
@@ -0,0 +1,213 @@
+---
+name: trade-journal
+description: Analyze a user's trade journal (CSV/Excel broker export). Parses 同花顺/东方财富/富途/generic formats, produces a trading profile and 4 behavior diagnostics (disposition effect, overtrading, chasing, anchoring). Use the `analyze_trade_journal` tool.
+category: tool
+---
+# Trade Journal Analysis
+
+## Purpose
+
+Users upload broker exports (交割单) and get an honest, data-grounded portrait
+of their own trading. Two layers are live:
+
+- **Profile** — holding days, frequency, win rate, PnL ratio, cumulative PnL,
+ max drawdown, top symbols, market/hourly distribution.
+- **Behavior diagnostics** — 4 biases, each with severity (low/medium/high)
+ and numeric evidence: disposition effect, overtrading, chasing momentum,
+ anchoring.
+
+Strategy extraction → backtest bridge lands in Phase 4c.
+
+Supported formats (auto-detected):
+- **同花顺** (Tonghuashun) — A-share CSV, typically GBK-encoded
+- **东方财富** (Eastmoney) — A-share CSV, typically GBK-encoded
+- **富途** (Futu) — HK/US CSV, UTF-8
+- **Generic** — any CSV with columns like `datetime/symbol/side/qty/price`
+
+## Usage
+
+**Call the `analyze_trade_journal` tool directly. Never run Python from bash.**
+
+```
+analyze_trade_journal(file_path="uploads/xxx.csv")
+analyze_trade_journal(file_path="uploads/xxx.csv", analysis_type="profile")
+analyze_trade_journal(file_path="uploads/xxx.csv", filter_expr="2026-01 to 2026-03")
+analyze_trade_journal(file_path="uploads/xxx.csv", filter_expr="symbol=600519.SH")
+analyze_trade_journal(file_path="uploads/xxx.csv", filter_expr="market=china_a")
+```
+
+`analysis_type`:
+- `full` (default) — profile + behavior (strategy still placeholder)
+- `profile` — profile metrics only (fastest)
+- `behavior` — 4 behavior diagnostics only
+- `strategy` — Phase 4c placeholder
+
+`filter_expr` (optional):
+- Date range: `"YYYY-MM to YYYY-MM"` or `"YYYY-MM-DD to YYYY-MM-DD"`
+- Symbol: `"symbol=600519.SH"` (exact match on qualified symbol)
+- Market: `"market=china_a|us|hk|crypto"`
+
+## Return shape (profile subset)
+
+```json
+{
+ "status": "ok",
+ "file": "xxx.csv",
+ "format_detected": "tonghuashun",
+ "total_records": 326,
+ "date_range": "2026-01-06 ~ 2026-03-28",
+ "symbols_count": 42,
+ "market": "china_a",
+ "profile": {
+ "total_trades": 326,
+ "total_roundtrips": 118,
+ "avg_holding_days": 3.2,
+ "trade_frequency_per_week": 4.1,
+ "win_rate": 0.48,
+ "profit_loss_ratio": 1.35,
+ "total_pnl": 18240.55,
+ "max_drawdown": -9820.10,
+ "top_symbols": [{"symbol": "600519.SH", "trades": 14, "total_amount": 1.02e6}, ...],
+ "market_distribution": {"china_a": 326},
+ "hourly_distribution": {9: 52, 10: 84, ...},
+ "roundtrips_sample": [{"symbol": "600519.SH", "buy_dt": "...", "sell_dt": "...", "pnl": 3400.1, "pnl_pct": 0.021, "hold_days": 2.5}, ...]
+ }
+}
+```
+
+Note: PnL uses FIFO lot matching; unmatched open positions are excluded from
+win rate / PnL ratio (only closed round-trips count).
+
+## Presenting results to the user
+
+Produce a **single markdown report** in the user's language. Lead with the
+top-line numbers, then section-by-section. Keep it dense — this is retail
+readers skimming on a phone.
+
+### Report template
+
+```
+## 你的交易画像 — {date_range}
+
+**总体**
+- 交易笔数:{total_trades}(完整来回 {total_roundtrips} 次)
+- 平均持仓:{avg_holding_days} 天
+- 交易频率:{trade_frequency_per_week} 次/周
+- 胜率:{win_rate:.0%}
+- 盈亏比:{profit_loss_ratio}
+- 累计盈亏:{total_pnl}
+- 最大回撤:{max_drawdown}
+
+**最常交易的标的**(前 5 名)
+| 标的 | 笔数 | 成交额 |
+|------|------|--------|
+| ... | ... | ... |
+
+**市场分布**
+{market_distribution}
+
+**交易时段**
+{hourly_distribution — highlight peak hours}
+
+**一句话观察**
+(根据数据写 1-2 句:过度交易?只做窄范围标的?集中在某时段?)
+```
+
+Guidance:
+- If `win_rate < 0.4` AND `profit_loss_ratio < 1.0` → explicit warning: losing
+ on both win rate and payoff. Ask whether they want behavior diagnostics
+ (Phase 4b) or a cooling-off reality check.
+- If `avg_holding_days < 1` AND `trade_frequency_per_week > 15` → flag
+ intraday-heavy pattern, note that minute-level backtest would be better.
+- If `symbols_count <= 3` → concentration risk; ask if they want a sector-
+ diversification check.
+
+## Follow-up dialogue
+
+After the initial report, users typically ask:
+- **Time-slice**: "3 月份表现怎么样" → re-call with `filter_expr="2026-03-01 to 2026-03-31"`.
+- **Symbol deep-dive**: "茅台这只赚了多少" → `filter_expr="symbol=600519.SH"`.
+- **Market split**: "港股和美股分开看" → two calls, `market=hk` and `market=us`.
+- **Hypothetical** ("如果我严格止损 -5%") → Phase 4b feature; for now tell the
+ user this is on the roadmap.
+
+Do NOT re-upload — the file path is still valid for subsequent tool calls
+in the same session.
+
+## Error handling
+
+- `File not found` / `Unsupported extension` — ask user to re-upload.
+- `Unrecognized trade journal format` — share the detected columns back to
+ the user and ask them to rename the key columns to: `datetime, symbol,
+ side, quantity, price, amount, fee` (generic fallback).
+- `No trade records parsed` — likely empty file or header-only; ask user to
+ confirm the export contains actual fills.
+
+## Behavior diagnostics (shape)
+
+Under `result["behavior"]`:
+
+```json
+{
+ "disposition_effect": {
+ "severity": "high",
+ "ratio_loss_to_win_hold": 1.69,
+ "avg_winner_hold_days": 7.4,
+ "avg_loser_hold_days": 12.5,
+ "evidence": "Losing roundtrips held 12.5d vs winning 7.4d (ratio 1.69). Classic disposition pattern."
+ },
+ "overtrading": {
+ "severity": "high",
+ "busy_day_avg_pnl": -2632,
+ "quiet_day_avg_pnl": 759,
+ "evidence": "On busy days (≥3 trades) avg PnL -2632; on quiet days (≤1) avg PnL +759. High activity hurts returns."
+ },
+ "chasing_momentum": {
+ "severity": "medium",
+ "chase_ratio": 0.5,
+ "buys_evaluated": 4,
+ "evidence": "2/4 buys (50%) came after a >3% price run-up in the same symbol. Some chasing tendency."
+ },
+ "anchoring": {
+ "severity": "high",
+ "anchored_symbol_ratio": 0.83,
+ "symbols_evaluated": 6,
+ "anchored_symbols": [...],
+ "evidence": "5/6 frequently-traded symbols stayed in a narrow price band (CV<5%). Strong anchoring."
+ }
+}
+```
+
+### Detection logic (for user-facing explanation)
+
+| Bias | Metric | Medium | High |
+|------|--------|--------|------|
+| **Disposition effect** | avg_loser_hold / avg_winner_hold | ≥ 1.2 | ≥ 1.5 |
+| **Overtrading** | (quiet − busy) / \|quiet\| day-PnL gap | ≥ 0.3 | ≥ 1.0 |
+| **Chasing** | fraction of buys after 3-trade rolling +3% move | ≥ 40% | ≥ 60% |
+| **Anchoring** | fraction of ≥5-trade symbols with price CV < 5% | ≥ 33% | ≥ 66% |
+
+### Report section (Chinese)
+
+```
+## 行为偏差诊断
+
+| 偏差 | 严重程度 | 核心证据 |
+|------|----------|----------|
+| 处置效应 | {high/medium/low} | {evidence} |
+| 过度交易 | {...} | {...} |
+| 追涨杀跌 | {...} | {...} |
+| 锚定效应 | {...} | {...} |
+
+**改进建议**(根据检测到的 high/medium 项生成):
+- 处置效应 high → 写死止损(例如 -8%),盈利持仓不要过早兑现
+- 过度交易 high → 每日交易次数 <= N 的硬约束
+- 追涨杀跌 high → 改买回调而不是新高,设置"涨幅 X% 以上当日不追"规则
+- 锚定效应 high → 扩宽价格带,不要死守某个"心理价"
+```
+
+## Phase 4c preview (not yet implemented)
+
+Strategy extraction → SignalEngine code gen → auto-backtest lands in Phase 4c.
+When the user asks for it, respond honestly and offer the behavior diagnostics
+instead (they're live).
diff --git a/agent/src/tools/trade_journal_parsers.py b/agent/src/tools/trade_journal_parsers.py
new file mode 100644
index 000000000..f586d0237
--- /dev/null
+++ b/agent/src/tools/trade_journal_parsers.py
@@ -0,0 +1,366 @@
+"""Trade journal format adapters.
+
+Each parser normalizes one broker export format into a list of TradeRecord.
+Supported: Tonghuashun (同花顺), Eastmoney (东方财富), Futu (富途), generic CSV.
+
+Encoding fallback order for CSV: utf-8 → utf-8-sig → gbk → gb2312.
+Excel (.xlsx/.xls) always opens as utf-8 internally via openpyxl/xlrd.
+"""
+
+from __future__ import annotations
+
+from dataclasses import asdict, dataclass
+from pathlib import Path
+from typing import Any
+
+import pandas as pd
+
+FormatName = str # "tonghuashun" | "eastmoney" | "futu" | "generic" | "unknown"
+
+_A_SHARE_EXCHANGE_MAP = {
+ # prefix → suffix; Shanghai Main + STAR, Shenzhen Main + SME + ChiNext, BSE
+ ("6",): ".SH",
+ ("0", "3"): ".SZ",
+ ("4", "8"): ".BJ",
+}
+
+_BUY_TOKENS = {"buy", "b", "买入", "证券买入", "融资买入", "做多", "long"}
+_SELL_TOKENS = {"sell", "s", "卖出", "证券卖出", "融券卖出", "做空", "short"}
+
+
+@dataclass(frozen=True)
+class TradeRecord:
+ """Standardized trade record (immutable).
+
+ Attributes:
+ 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".
+ quantity: Filled quantity.
+ price: Filled price.
+ amount: Gross amount (quantity * price, pre-fee).
+ fee: Total fees (commission + stamp + transfer).
+ market: "china_a" / "us" / "hk" / "crypto" / "other".
+ """
+
+ datetime: str
+ symbol: str
+ name: str
+ side: str
+ quantity: float
+ price: float
+ amount: float
+ fee: float
+ market: str
+
+
+# ---------------- File loading ----------------
+
+def load_dataframe(path: str | Path) -> pd.DataFrame:
+ """Load a CSV/Excel file into a DataFrame with encoding fallback.
+
+ Args:
+ path: Path to the file (.csv/.xlsx/.xls).
+
+ Returns:
+ Parsed DataFrame with raw column names (no normalization).
+
+ Raises:
+ FileNotFoundError: File does not exist.
+ ValueError: Unsupported extension or all encodings failed.
+ """
+ p = Path(path)
+ if not p.exists():
+ raise FileNotFoundError(f"File not found: {p}")
+
+ ext = p.suffix.lower()
+ if ext in {".xlsx", ".xls"}:
+ return pd.read_excel(p, dtype=str)
+ if ext != ".csv":
+ raise ValueError(f"Unsupported extension: {ext}")
+
+ last_err: Exception | None = None
+ for enc in ("utf-8", "utf-8-sig", "gbk", "gb2312"):
+ try:
+ return pd.read_csv(p, dtype=str, encoding=enc)
+ except UnicodeDecodeError as exc:
+ last_err = exc
+ raise ValueError(f"Failed to decode CSV with utf-8/gbk/gb2312: {last_err}")
+
+
+# ---------------- Format detection ----------------
+
+def detect_format(df: pd.DataFrame) -> FormatName:
+ """Detect broker format by column-name signature.
+
+ Args:
+ df: Raw DataFrame from load_dataframe.
+
+ Returns:
+ Format identifier; "unknown" when nothing matches (caller may still
+ try GenericCSVParser).
+ """
+ cols = set(df.columns.astype(str))
+
+ if {"成交时间", "证券代码", "操作"}.issubset(cols):
+ return "tonghuashun"
+ if {"买卖标志", "股票代码"}.issubset(cols) or {"买卖标志", "成交均价"}.issubset(cols):
+ return "eastmoney"
+ if {"Date", "Symbol", "Side"}.issubset(cols) or {"Date", "Symbol", "Direction"}.issubset(cols):
+ return "futu"
+
+ # Generic: any subset containing time/symbol/side hints
+ lowered = {c.lower() for c in cols}
+ if any(c in lowered for c in ("datetime", "time", "date")) and any(
+ c in lowered for c in ("symbol", "ticker", "code")
+ ):
+ return "generic"
+ return "unknown"
+
+
+# ---------------- Parsers ----------------
+
+def _normalize_side(raw: Any) -> str:
+ """Return 'buy'/'sell', falling back to 'buy'."""
+ s = str(raw).strip().lower()
+ if s in _SELL_TOKENS or any(tok in s for tok in _SELL_TOKENS):
+ return "sell"
+ return "buy"
+
+
+def _qualify_a_share(code: str) -> str:
+ """Append .SH/.SZ/.BJ suffix to a bare A-share ticker."""
+ code = str(code).strip().zfill(6)
+ if "." in code:
+ return code.upper()
+ first = code[0]
+ for prefixes, suffix in _A_SHARE_EXCHANGE_MAP.items():
+ if first in prefixes:
+ return code + suffix
+ return code
+
+
+def _to_float(val: Any, default: float = 0.0) -> float:
+ """Safely cast to float; return default on failure."""
+ if val is None:
+ return default
+ try:
+ s = str(val).replace(",", "").strip()
+ return float(s) if s else default
+ except (ValueError, TypeError):
+ return default
+
+
+def parse_tonghuashun(df: pd.DataFrame) -> list[TradeRecord]:
+ """Parse 同花顺 exports.
+
+ Expected columns: 成交时间, 证券代码, 证券名称, 操作, 成交数量, 成交价格,
+ 成交金额, 手续费, 印花税, 过户费.
+ """
+ records: list[TradeRecord] = []
+ for _, row in df.iterrows():
+ qty = _to_float(row.get("成交数量"))
+ price = _to_float(row.get("成交价格"))
+ amount = _to_float(row.get("成交金额")) or qty * price
+ fee = _to_float(row.get("手续费")) + _to_float(row.get("印花税")) + _to_float(row.get("过户费"))
+ records.append(TradeRecord(
+ datetime=str(row.get("成交时间", "")).strip(),
+ symbol=_qualify_a_share(row.get("证券代码", "")),
+ name=str(row.get("证券名称", "")).strip(),
+ side=_normalize_side(row.get("操作")),
+ quantity=qty,
+ price=price,
+ amount=amount,
+ fee=fee,
+ market="china_a",
+ ))
+ return records
+
+
+def parse_eastmoney(df: pd.DataFrame) -> list[TradeRecord]:
+ """Parse 东方财富 exports.
+
+ Expected columns: 成交日期 (YYYYMMDD), 成交时间 (HH:MM:SS), 股票代码,
+ 股票名称, 买卖标志 (B/S), 成交数量, 成交均价, 成交金额, 佣金, 印花税.
+ """
+ records: list[TradeRecord] = []
+ for _, row in df.iterrows():
+ raw_date = str(row.get("成交日期", "")).strip()
+ raw_time = str(row.get("成交时间", "")).strip()
+ if len(raw_date) == 8 and raw_date.isdigit():
+ iso_date = f"{raw_date[:4]}-{raw_date[4:6]}-{raw_date[6:8]}"
+ else:
+ iso_date = raw_date
+ dt = f"{iso_date} {raw_time}".strip()
+ qty = _to_float(row.get("成交数量"))
+ price = _to_float(row.get("成交均价"))
+ amount = _to_float(row.get("成交金额")) or qty * price
+ fee = _to_float(row.get("佣金")) + _to_float(row.get("印花税"))
+ records.append(TradeRecord(
+ datetime=dt,
+ symbol=_qualify_a_share(row.get("股票代码", "")),
+ name=str(row.get("股票名称", "")).strip(),
+ side=_normalize_side(row.get("买卖标志")),
+ quantity=qty,
+ price=price,
+ amount=amount,
+ fee=fee,
+ market="china_a",
+ ))
+ return records
+
+
+def _futu_market(symbol: str, market_hint: str) -> str:
+ """Infer market from symbol/market column."""
+ hint = market_hint.strip().lower()
+ if hint in {"hk", "us", "cn"}:
+ return {"hk": "hk", "us": "us", "cn": "china_a"}[hint]
+ if symbol.endswith(".HK"):
+ return "hk"
+ if symbol.isalpha() or "." not in symbol:
+ return "us"
+ return "other"
+
+
+def parse_futu(df: pd.DataFrame) -> list[TradeRecord]:
+ """Parse 富途 exports (English headers, HK+US mix).
+
+ Expected columns: Date, Time, Symbol, Name, Side, Quantity, Price,
+ Amount, Commission, Platform Fee, Market (optional).
+ """
+ records: list[TradeRecord] = []
+ for _, row in df.iterrows():
+ date = str(row.get("Date", "")).strip()
+ time = str(row.get("Time", "")).strip()
+ dt = f"{date} {time}".strip()
+ symbol = str(row.get("Symbol", "")).strip().upper()
+ qty = _to_float(row.get("Quantity"))
+ price = _to_float(row.get("Price"))
+ amount = _to_float(row.get("Amount")) or qty * price
+ fee = _to_float(row.get("Commission")) + _to_float(row.get("Platform Fee"))
+ records.append(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")),
+ quantity=qty,
+ price=price,
+ amount=amount,
+ fee=fee,
+ market=_futu_market(symbol, str(row.get("Market", ""))),
+ ))
+ return records
+
+
+def parse_generic(df: pd.DataFrame) -> list[TradeRecord]:
+ """Parse a generic CSV with lowercase English headers.
+
+ Matches columns case-insensitively. Expected (any alias in parens):
+ datetime (time/date+time), symbol (ticker/code), name, side (direction),
+ quantity (qty/size), price, amount (value/notional), fee (commission).
+ """
+ colmap: dict[str, str] = {}
+ for col in df.columns:
+ key = str(col).strip().lower()
+ colmap[key] = col
+
+ def pick(*names: str) -> str | None:
+ for n in names:
+ if n in colmap:
+ return colmap[n]
+ return None
+
+ dt_col = pick("datetime", "time")
+ date_col = pick("date")
+ sym_col = pick("symbol", "ticker", "code")
+ name_col = pick("name", "instrument")
+ side_col = pick("side", "direction", "action")
+ qty_col = pick("quantity", "qty", "size", "volume")
+ price_col = pick("price")
+ amount_col = pick("amount", "value", "notional")
+ fee_col = pick("fee", "commission", "fees")
+
+ records: list[TradeRecord] = []
+ for _, row in df.iterrows():
+ if dt_col:
+ dt = str(row.get(dt_col, "")).strip()
+ elif date_col:
+ dt = str(row.get(date_col, "")).strip()
+ else:
+ dt = ""
+ symbol = str(row.get(sym_col, "")).strip() if sym_col else ""
+ qty = _to_float(row.get(qty_col)) if qty_col else 0.0
+ price = _to_float(row.get(price_col)) if price_col else 0.0
+ amount = _to_float(row.get(amount_col)) if amount_col else qty * price
+ fee = _to_float(row.get(fee_col)) if fee_col else 0.0
+ market = _infer_market_from_symbol(symbol)
+ records.append(TradeRecord(
+ datetime=dt,
+ symbol=symbol.upper(),
+ name=str(row.get(name_col, "")).strip() if name_col else "",
+ side=_normalize_side(row.get(side_col) if side_col else "buy"),
+ quantity=qty,
+ price=price,
+ amount=amount or qty * price,
+ fee=fee,
+ market=market,
+ ))
+ return records
+
+
+def _infer_market_from_symbol(symbol: str) -> str:
+ """Best-effort market inference from a symbol string."""
+ s = symbol.upper()
+ if s.endswith(".HK"):
+ return "hk"
+ if s.endswith(".SH") or s.endswith(".SZ") or s.endswith(".BJ"):
+ return "china_a"
+ if "-" in s and any(quote in s for quote in ("USDT", "USDC", "BTC", "USD")):
+ return "crypto"
+ if s.isalpha():
+ return "us"
+ return "other"
+
+
+_PARSERS = {
+ "tonghuashun": parse_tonghuashun,
+ "eastmoney": parse_eastmoney,
+ "futu": parse_futu,
+ "generic": parse_generic,
+}
+
+
+def parse_file(path: str | Path) -> tuple[FormatName, list[TradeRecord]]:
+ """End-to-end: load file, detect format, parse.
+
+ Args:
+ path: File path.
+
+ Returns:
+ (format_name, records). Falls back to generic if detection is unknown
+ but columns look parsable; otherwise raises ValueError.
+
+ Raises:
+ ValueError: Unknown format with no usable columns.
+ """
+ df = load_dataframe(path)
+ fmt = detect_format(df)
+ if fmt == "unknown":
+ try:
+ records = parse_generic(df)
+ if records and records[0].symbol:
+ return "generic", records
+ except Exception:
+ pass
+ raise ValueError(f"Unrecognized trade journal format. Columns: {list(df.columns)}")
+ return fmt, _PARSERS[fmt](df)
+
+
+def records_to_dataframe(records: list[TradeRecord]) -> pd.DataFrame:
+ """Convert records to a standardized DataFrame (datetime column parsed)."""
+ if not records:
+ return pd.DataFrame(columns=[f.name for f in TradeRecord.__dataclass_fields__.values()])
+ df = pd.DataFrame([asdict(r) for r in records])
+ df["datetime"] = pd.to_datetime(df["datetime"], errors="coerce")
+ return df.sort_values("datetime").reset_index(drop=True)
diff --git a/agent/src/tools/trade_journal_tool.py b/agent/src/tools/trade_journal_tool.py
new file mode 100644
index 000000000..c1cdf85f4
--- /dev/null
+++ b/agent/src/tools/trade_journal_tool.py
@@ -0,0 +1,512 @@
+"""Trade Journal Analyzer tool.
+
+Parses a broker CSV/Excel export and produces:
+ - profile: holding days, trade frequency, win rate, PnL ratio, cumulative
+ PnL, max drawdown, top symbols, market/hourly distribution
+ - behavior (Phase 4b): disposition effect, overtrading, chasing momentum,
+ anchoring — each with severity + numeric evidence
+
+Strategy extraction → backtest bridge still pending (Phase 4c).
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+from collections import defaultdict, deque
+from pathlib import Path
+from typing import Any
+
+import pandas as pd
+
+from src.agent.tools import BaseTool
+from src.tools.trade_journal_parsers import (
+ TradeRecord,
+ parse_file,
+ records_to_dataframe,
+)
+
+logger = logging.getLogger(__name__)
+
+_ALLOWED_EXT = {".csv", ".xlsx", ".xls"}
+
+
+def _pair_trades_fifo(df: pd.DataFrame) -> list[dict[str, Any]]:
+ """Pair buys and sells per symbol using FIFO to compute per-roundtrip PnL.
+
+ Args:
+ df: Standardized DataFrame (datetime-sorted).
+
+ 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)
+ roundtrips: list[dict[str, Any]] = []
+
+ 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,
+ })
+ continue
+
+ # sell: match against oldest buys
+ remaining = row.quantity
+ q = queues[row.symbol]
+ while remaining > 1e-9 and q:
+ lot = q[0]
+ take = min(lot["qty"], remaining)
+ hold = (row.datetime - lot["dt"]).total_seconds() / 86400.0
+ gross = (row.price - lot["price"]) * take
+ # Proportional fee allocation
+ buy_fee = lot["fee"] * (take / lot["qty"]) if lot["qty"] else 0.0
+ sell_fee = row.fee * (take / row.quantity) if row.quantity else 0.0
+ pnl = gross - buy_fee - sell_fee
+ cost = lot["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),
+ })
+ lot["qty"] -= take
+ remaining -= take
+ if lot["qty"] <= 1e-9:
+ q.popleft()
+ return roundtrips
+
+
+def _safe_div(a: float, b: float) -> float:
+ return float(a) / float(b) if b else 0.0
+
+
+def _compute_profile(df: pd.DataFrame) -> dict[str, Any]:
+ """Build the trading profile dict.
+
+ Args:
+ df: Standardized DataFrame (datetime parsed, sorted).
+
+ 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.
+ """
+ if df.empty:
+ return {"error": "empty trade journal"}
+
+ rts = _pair_trades_fifo(df)
+ rts_df = pd.DataFrame(rts)
+
+ total_trades = len(df)
+ span_days = max(1, (df["datetime"].max() - df["datetime"].min()).days)
+ freq_per_week = round(total_trades / span_days * 7, 2)
+
+ if not rts_df.empty:
+ wins = rts_df[rts_df["pnl"] > 0]
+ losses = rts_df[rts_df["pnl"] < 0]
+ avg_win = wins["pnl"].mean() if len(wins) else 0.0
+ avg_loss = losses["pnl"].mean() if len(losses) else 0.0
+ 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.0
+ avg_hold = round(rts_df["hold_days"].mean(), 2)
+ total_pnl = round(rts_df["pnl"].sum(), 2)
+ # Cumulative PnL → max drawdown
+ cum = 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.0
+ else:
+ win_rate = pnl_ratio = avg_hold = total_pnl = max_drawdown = 0.0
+
+ top_symbols = (
+ df.groupby("symbol")
+ .agg(trades=("symbol", "count"), total_amount=("amount", "sum"))
+ .sort_values("total_amount", ascending=False)
+ .head(10)
+ .round(2)
+ .reset_index()
+ .to_dict(orient="records")
+ )
+
+ market_dist = df["market"].value_counts().to_dict()
+ hourly_dist = 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()
+ if not sample.empty:
+ sample["buy_dt"] = sample["buy_dt"].astype(str)
+ sample["sell_dt"] = sample["sell_dt"].astype(str)
+ roundtrips_sample = sample.to_dict(orient="records")
+ else:
+ roundtrips_sample = []
+
+ return {
+ "total_trades": total_trades,
+ "total_roundtrips": len(rts_df),
+ "avg_holding_days": avg_hold,
+ "trade_frequency_per_week": freq_per_week,
+ "win_rate": win_rate,
+ "profit_loss_ratio": pnl_ratio,
+ "total_pnl": total_pnl,
+ "max_drawdown": max_drawdown,
+ "top_symbols": top_symbols,
+ "market_distribution": market_dist,
+ "hourly_distribution": hourly_dist,
+ "roundtrips_sample": roundtrips_sample,
+ }
+
+
+def _severity(score: float, thresholds: tuple[float, float]) -> str:
+ """Map a numeric score to low/medium/high given (med_cutoff, high_cutoff)."""
+ med, high = thresholds
+ if score >= high:
+ return "high"
+ if score >= med:
+ return "medium"
+ return "low"
+
+
+def _disposition_effect(rts_df: pd.DataFrame) -> dict[str, Any]:
+ """Detect disposition effect: holding losers longer than winners.
+
+ Metric = avg_loss_hold / avg_win_hold. A ratio > 1 means the user holds
+ losing positions longer than winning ones — the classic disposition bias.
+ """
+ if rts_df.empty:
+ return {"severity": "low", "evidence": "no closed roundtrips"}
+ wins = rts_df[rts_df["pnl"] > 0]
+ losses = rts_df[rts_df["pnl"] < 0]
+ if wins.empty or losses.empty:
+ return {
+ "severity": "low",
+ "evidence": "not enough winners and losers to compare holding times",
+ }
+ win_hold = float(wins["hold_days"].mean())
+ loss_hold = float(losses["hold_days"].mean())
+ ratio = loss_hold / win_hold if win_hold > 0 else float("inf")
+ severity = _severity(ratio, (1.2, 1.5))
+ return {
+ "severity": severity,
+ "ratio_loss_to_win_hold": round(ratio, 2),
+ "avg_winner_hold_days": round(win_hold, 2),
+ "avg_loser_hold_days": round(loss_hold, 2),
+ "evidence": (
+ f"Losing roundtrips held {loss_hold:.1f}d vs winning "
+ f"{win_hold:.1f}d (ratio {ratio:.2f}). "
+ + ("Classic disposition pattern." if severity == "high"
+ else "Mild hold-losers-longer tendency." if severity == "medium"
+ else "Hold times roughly symmetric.")
+ ),
+ }
+
+
+def _overtrading(df: pd.DataFrame, rts_df: pd.DataFrame) -> dict[str, Any]:
+ """Detect overtrading: high-activity days produce worse PnL.
+
+ Buckets trading days into top-quartile (busy) and bottom-quartile (quiet)
+ by trade count, then compares the realized PnL of roundtrips whose sell
+ lands on each bucket.
+ """
+ if df.empty or rts_df.empty:
+ return {"severity": "low", "evidence": "insufficient data"}
+
+ daily_trades = df.groupby(df["datetime"].dt.date).size()
+ if len(daily_trades) < 4:
+ return {"severity": "low", "evidence": "fewer than 4 trading days"}
+
+ busy_cut = daily_trades.quantile(0.75)
+ quiet_cut = daily_trades.quantile(0.25)
+ busy_days = set(daily_trades[daily_trades >= busy_cut].index)
+ quiet_days = set(daily_trades[daily_trades <= quiet_cut].index)
+
+ rts_df = rts_df.copy()
+ rts_df["sell_date"] = pd.to_datetime(rts_df["sell_dt"]).dt.date
+ busy_pnl = rts_df[rts_df["sell_date"].isin(busy_days)]["pnl"]
+ quiet_pnl = rts_df[rts_df["sell_date"].isin(quiet_days)]["pnl"]
+ if busy_pnl.empty or quiet_pnl.empty:
+ return {"severity": "low", "evidence": "roundtrips not spread across busy/quiet days"}
+
+ busy_avg = float(busy_pnl.mean())
+ quiet_avg = float(quiet_pnl.mean())
+
+ # severity rule: busy-day PnL must be meaningfully worse than quiet-day
+ gap = quiet_avg - busy_avg
+ base = abs(quiet_avg) if quiet_avg != 0 else 1.0
+ severity = _severity(gap / base, (0.3, 1.0)) if busy_avg < quiet_avg else "low"
+
+ return {
+ "severity": severity,
+ "busy_day_avg_pnl": round(busy_avg, 2),
+ "quiet_day_avg_pnl": round(quiet_avg, 2),
+ "busy_day_trade_threshold": round(float(busy_cut), 1),
+ "evidence": (
+ f"On busy days (≥{busy_cut:.0f} trades) avg PnL {busy_avg:+.0f}; "
+ f"on quiet days (≤{quiet_cut:.0f}) avg PnL {quiet_avg:+.0f}. "
+ + ("High activity hurts returns." if severity == "high"
+ else "Some drag from busy-day trading." if severity == "medium"
+ else "Activity level does not materially hurt PnL.")
+ ),
+ }
+
+
+def _chasing_momentum(df: pd.DataFrame) -> dict[str, Any]:
+ """Detect chasing: buys concentrated after recent price rises in the same symbol.
+
+ For each BUY, look at the user's own last 3 trades of that symbol. If the
+ price trended upward (last trade price > 3rd-prior by > 3%), count the buy
+ as a chase. Ratio of chasing buys → severity.
+ """
+ buys = df[df["side"] == "buy"].sort_values(["symbol", "datetime"]).copy()
+ if buys.empty:
+ return {"severity": "low", "evidence": "no buys"}
+
+ buys["prev3_price"] = buys.groupby("symbol")["price"].shift(3)
+ matured = buys.dropna(subset=["prev3_price"])
+ if matured.empty:
+ return {
+ "severity": "low",
+ "evidence": "not enough repeat buys per symbol to evaluate chasing",
+ }
+ chased = matured[matured["price"] > matured["prev3_price"] * 1.03]
+ ratio = len(chased) / len(matured)
+ severity = _severity(ratio, (0.4, 0.6))
+ return {
+ "severity": severity,
+ "chase_ratio": round(ratio, 3),
+ "buys_evaluated": int(len(matured)),
+ "evidence": (
+ f"{len(chased)}/{len(matured)} buys ({ratio:.0%}) came after a >3% "
+ "price run-up in the same symbol. "
+ + ("Strong chasing pattern." if severity == "high"
+ else "Some chasing tendency." if severity == "medium"
+ else "No clear chasing bias.")
+ ),
+ }
+
+
+def _anchoring(df: pd.DataFrame) -> dict[str, Any]:
+ """Detect price anchoring: repeated trades cluster in a narrow price band.
+
+ For each symbol with ≥5 trades, compute σ(price)/mean(price). A low ratio
+ (<0.05) means the user consistently trades the same price area, suggesting
+ they are anchored to a reference price rather than reacting to moves.
+ """
+ grouped = df.groupby("symbol")
+ rows: list[dict[str, Any]] = []
+ for sym, sub in grouped:
+ if len(sub) < 5:
+ continue
+ mean = float(sub["price"].mean())
+ std = float(sub["price"].std())
+ if mean == 0:
+ continue
+ cv = std / mean
+ rows.append({"symbol": sym, "trades": len(sub), "mean_price": round(mean, 2), "cv": round(cv, 4)})
+
+ if not rows:
+ return {"severity": "low", "evidence": "no symbol has ≥5 trades to evaluate anchoring"}
+
+ anchored = [r for r in rows if r["cv"] < 0.05]
+ ratio = len(anchored) / len(rows)
+ severity = _severity(ratio, (0.33, 0.66))
+ return {
+ "severity": severity,
+ "anchored_symbol_ratio": round(ratio, 3),
+ "symbols_evaluated": len(rows),
+ "anchored_symbols": anchored[:5],
+ "evidence": (
+ f"{len(anchored)}/{len(rows)} frequently-traded symbols stayed in a "
+ "narrow price band (CV<5%). "
+ + ("Strong anchoring — repeated trades at the same price." if severity == "high"
+ else "Some anchoring on select symbols." if severity == "medium"
+ else "Prices vary naturally across repeat trades.")
+ ),
+ }
+
+
+def _compute_behavior(df: pd.DataFrame) -> dict[str, Any]:
+ """Run all 4 behavior diagnostics.
+
+ Args:
+ df: Standardized DataFrame (datetime-sorted).
+
+ Returns:
+ Dict with disposition_effect / overtrading / chasing_momentum /
+ anchoring keys, each {severity, evidence, ...metrics}.
+ """
+ if df.empty:
+ return {"error": "empty trade journal"}
+ 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),
+ }
+
+
+def _apply_filter(df: pd.DataFrame, expr: str) -> pd.DataFrame:
+ """Filter DataFrame by a simple expression.
+
+ Supports:
+ - "YYYY-MM to YYYY-MM" or "YYYY-MM-DD to YYYY-MM-DD" (date range)
+ - "symbol=XXX" (exact match)
+ - "market=china_a|us|hk|crypto"
+
+ Args:
+ df: Standardized DataFrame.
+ expr: Filter expression.
+
+ Returns:
+ Filtered DataFrame (may be empty).
+ """
+ expr = expr.strip()
+ if not expr:
+ return df
+
+ if " to " in expr:
+ try:
+ lo_raw, hi_raw = (p.strip() for p in expr.split(" to ", 1))
+ lo = pd.to_datetime(lo_raw)
+ hi = pd.to_datetime(hi_raw) + pd.Timedelta(days=1)
+ return df[(df["datetime"] >= lo) & (df["datetime"] < hi)]
+ except Exception as exc:
+ logger.warning("filter date parse failed: %s", exc)
+ return df
+
+ if "=" in expr:
+ key, val = (p.strip() for p in expr.split("=", 1))
+ if key in df.columns:
+ return df[df[key].astype(str).str.upper() == val.upper()]
+ return df
+
+
+def analyze_trade_journal(file_path: str, analysis_type: str = "full", filter_expr: str = "") -> str:
+ """Parse a trade journal and return a JSON analysis.
+
+ Args:
+ file_path: Path to CSV/Excel file.
+ analysis_type: "full" | "profile" | "behavior" | "strategy".
+ "profile" and "behavior" are fully implemented; "strategy" still
+ returns a Phase 4c placeholder.
+ filter_expr: Optional filter. Examples: "2026-01 to 2026-03",
+ "symbol=600519.SH", "market=china_a".
+
+ Returns:
+ JSON string. Keys: status, file, format_detected, total_records,
+ date_range, market, profile / behavior (when applicable).
+ """
+ path = Path(file_path)
+ if not path.exists():
+ return json.dumps({"status": "error", "error": f"File not found: {file_path}"}, ensure_ascii=False)
+ if path.suffix.lower() not in _ALLOWED_EXT:
+ return json.dumps(
+ {"status": "error", "error": f"Unsupported extension {path.suffix}. Expected .csv/.xlsx/.xls"},
+ ensure_ascii=False,
+ )
+
+ try:
+ fmt, records = parse_file(path)
+ except (ValueError, FileNotFoundError) as exc:
+ return json.dumps({"status": "error", "error": str(exc)}, ensure_ascii=False)
+
+ if not records:
+ return json.dumps(
+ {"status": "error", "error": "No trade records parsed"}, ensure_ascii=False
+ )
+
+ df = records_to_dataframe(records)
+ filtered = _apply_filter(df, filter_expr)
+
+ result: dict[str, Any] = {
+ "status": "ok",
+ "file": path.name,
+ "format_detected": fmt,
+ "total_records": len(filtered),
+ "date_range": _format_range(filtered),
+ "symbols_count": int(filtered["symbol"].nunique()) if not filtered.empty else 0,
+ "market": _pick_dominant_market(filtered),
+ }
+ if filter_expr:
+ result["filter_applied"] = filter_expr
+
+ if analysis_type in {"full", "profile"}:
+ result["profile"] = _compute_profile(filtered)
+
+ if analysis_type in {"full", "behavior"}:
+ result["behavior"] = _compute_behavior(filtered)
+
+ if analysis_type in {"full", "strategy"}:
+ result["strategy_features"] = {
+ "status": "pending",
+ "note": "Strategy extraction → backtest bridging lands in Phase 4c.",
+ }
+
+ return json.dumps(result, ensure_ascii=False, default=str)
+
+
+def _format_range(df: pd.DataFrame) -> str:
+ """Return 'YYYY-MM-DD ~ YYYY-MM-DD' or empty."""
+ if df.empty:
+ return ""
+ return f"{df['datetime'].min().date()} ~ {df['datetime'].max().date()}"
+
+
+def _pick_dominant_market(df: pd.DataFrame) -> str:
+ """Return the most-traded market; empty when df is empty."""
+ if df.empty:
+ return ""
+ return df["market"].value_counts().idxmax()
+
+
+class TradeJournalTool(BaseTool):
+ """Trade journal analyzer tool (registered via auto-discovery)."""
+
+ name = "analyze_trade_journal"
+ description = (
+ "Analyze a user's trade journal (CSV/Excel broker export). "
+ "Parses 同花顺/东方财富/富途/generic formats. Returns: "
+ "(1) trading profile — holding days, frequency, win rate, PnL ratio, "
+ "top symbols, market/hourly distribution; "
+ "(2) behavior diagnostics — disposition effect, overtrading, chasing "
+ "momentum, anchoring (each with severity + numeric evidence)."
+ )
+ parameters = {
+ "type": "object",
+ "properties": {
+ "file_path": {
+ "type": "string",
+ "description": "Path to the uploaded CSV/Excel file.",
+ },
+ "analysis_type": {
+ "type": "string",
+ "enum": ["full", "profile", "behavior", "strategy"],
+ "description": "Which analysis to run. 'full' = profile (behavior/strategy are Phase 4b placeholders).",
+ "default": "full",
+ },
+ "filter_expr": {
+ "type": "string",
+ "description": "Optional filter, e.g. '2026-01 to 2026-03', 'symbol=600519.SH', 'market=china_a'.",
+ "default": "",
+ },
+ },
+ "required": ["file_path"],
+ }
+ repeatable = True
+
+ def execute(self, **kwargs: Any) -> str:
+ return analyze_trade_journal(
+ file_path=kwargs["file_path"],
+ analysis_type=kwargs.get("analysis_type", "full"),
+ filter_expr=kwargs.get("filter_expr", ""),
+ )
diff --git a/agent/tests/test_doc_reader.py b/agent/tests/test_doc_reader.py
index eb7d82c95..2fca8558c 100644
--- a/agent/tests/test_doc_reader.py
+++ b/agent/tests/test_doc_reader.py
@@ -10,8 +10,6 @@ import pytest
from src.tools.doc_reader_tool import read_document
-FIXTURES = Path(__file__).parent / "fixtures" / "trade_journal"
-
def _call(path: Path, pages: str = "") -> dict:
return json.loads(read_document(str(path), pages))
@@ -68,11 +66,13 @@ def test_unknown_extension_treated_as_text(tmp_path: Path) -> None:
assert result["text"] == "abc"
-def test_csv_read_as_text() -> None:
- result = _call(FIXTURES / "futu_hk_us.csv")
+def test_csv_read_as_text(tmp_path: Path) -> None:
+ csv_path = tmp_path / "sample.csv"
+ csv_path.write_text("a,b,c\n1,2,3\n4,5,6\n", encoding="utf-8")
+ result = _call(csv_path)
assert result["status"] == "ok"
assert result["format"] == "text"
- assert result["char_count"] > 0
+ assert "a,b,c" in result["text"]
# ---------------- DOCX ----------------