Overview: focus|radar pairing, selectable radar, performance chart
Deploy / lint (push) Successful in 7s
Deploy / test (push) Successful in 1m9s
Deploy / deploy (push) Successful in 36s

Layout regrouped by relationship, not size: the setup-in-focus card
and the radar sit side by side (they are one decision surface), the
four account ribbons move directly above the open positions they
describe, and a new performance chart closes the page.

- Radar rows are selectable: clicking one swaps the focus card to that
  setup - including below-gate rows, whose card shows a muted
  "rank N / below gate" badge and the disqualify reason in the footer,
  with a "back to top pick" reset. The row currently in focus is
  highlighted; ticker links still deep-link without selecting.
- Performance chart (the mockup's missing piece): new
  GET /paper-trades/equity-curve computes, per benchmark trading day
  since the first paper trade, the book's cumulative P&L (realized +
  mark-to-market from stored OHLCV) vs the same cost basis riding SPY
  over each trade's window (benchmark_prices). Pure curve math in
  paper_trade_service with unit tests; hidden until there are 2+
  points of data. Frontend renders both lines with crosshair readout,
  zero baseline, and direct end labels.

Backend unit suite: 501 passed.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
2026-07-10 18:09:31 +02:00
co-authored by Claude Fable 5
parent b0b691da9c
commit 06fdd92faa
7 changed files with 538 additions and 110 deletions
+11
View File
@@ -54,6 +54,17 @@ async def read_exit_policy(
return APIEnvelope(status="success", data=await paper_trade_service.get_exit_policy(db))
@router.get("/paper-trades/equity-curve", response_model=APIEnvelope)
async def paper_trade_equity_curve(
user: User = Depends(require_access),
db: AsyncSession = Depends(get_db),
) -> APIEnvelope:
"""Daily cumulative P&L of the paper book vs the same dollars riding SPY."""
return APIEnvelope(
status="success", data=await paper_trade_service.equity_curve(db, user.id)
)
@router.put("/paper-trades/exit-policy", response_model=APIEnvelope)
async def write_exit_policy(
body: ExitPolicyUpdate,
+117
View File
@@ -2,6 +2,7 @@
from __future__ import annotations
import bisect
from datetime import date, datetime, timezone
from sqlalchemy import and_, func, select
@@ -588,3 +589,119 @@ async def resolve_open_trades(db: AsyncSession) -> int:
if closed:
await db.commit()
return closed
# ---------------------------------------------------------------------------
# Equity curve — the paper book's cumulative P&L vs the same dollars in SPY.
def _value_on_or_before(
dates_sorted: list[date], closes: dict[date, float], target: date
) -> float | None:
"""Close on the nearest trading day at or before ``target`` (None if before history)."""
idx = bisect.bisect_right(dates_sorted, target) - 1
return closes[dates_sorted[idx]] if idx >= 0 else None
def build_equity_curve(
trades: list,
ticker_closes: dict[int, dict[date, float]],
benchmark_closes: dict[date, float],
) -> list[dict]:
"""Daily cumulative P&L of the paper book vs a benchmark counterfactual.
For every benchmark trading day since the first trade opened:
book_pnl = Σ realized P&L of trades closed by then
+ Σ mark-to-market P&L of trades still open (ticker close
on/before that day)
benchmark_pnl = Σ per trade: the SAME cost basis (entry x shares) riding
the benchmark over the SAME window (open → close/now).
Long-benchmark regardless of trade direction — the
question is "what if this money had just sat in SPY".
Pure function so the math is unit-testable; trades are duck-typed
(ticker_id, direction, entry_price, shares, status, opened_at, closed_at,
close_price). Trades opened before the stored benchmark history contribute
to book_pnl but not to benchmark_pnl (no baseline close to measure from).
"""
if not trades or not benchmark_closes:
return []
first = min(t.opened_at.date() for t in trades)
bench_dates = sorted(benchmark_closes)
days = [d for d in bench_dates if d >= first]
if not days:
return []
ticker_dates_sorted = {tid: sorted(c) for tid, c in ticker_closes.items()}
out: list[dict] = []
for d in days:
book = 0.0
bench = 0.0
any_priced = False
for t in trades:
opened = t.opened_at.date()
if opened > d:
continue
closed_on = (
t.closed_at.date()
if (t.status == "closed" and t.closed_at is not None)
else None
)
window_end = min(d, closed_on) if closed_on is not None else d
if closed_on is not None and closed_on <= d and t.close_price is not None:
ref = float(t.close_price)
else:
closes = ticker_closes.get(t.ticker_id) or {}
ref_val = _value_on_or_before(
ticker_dates_sorted.get(t.ticker_id) or [], closes, d
)
if ref_val is None:
continue
ref = ref_val
per_share = (
ref - t.entry_price if t.direction == "long" else t.entry_price - ref
)
book += per_share * t.shares
any_priced = True
s0 = _value_on_or_before(bench_dates, benchmark_closes, opened)
s1 = _value_on_or_before(bench_dates, benchmark_closes, window_end)
if s0 and s1:
bench += (t.entry_price * t.shares) * (s1 - s0) / s0
if any_priced:
out.append(
{
"date": d.isoformat(),
"book_pnl": round(book, 2),
"benchmark_pnl": round(bench, 2),
}
)
return out
async def equity_curve(db: AsyncSession, user_id: int) -> list[dict]:
"""Equity-curve series for a user's paper book (empty without benchmark data)."""
trades = (
(await db.execute(select(PaperTrade).where(PaperTrade.user_id == user_id)))
.scalars()
.all()
)
if not trades:
return []
benchmark_closes = await benchmark_service.load_benchmark_closes(db)
if not benchmark_closes:
return []
first = min(t.opened_at.date() for t in trades)
ticker_ids = {t.ticker_id for t in trades}
rows = await db.execute(
select(OHLCVRecord.ticker_id, OHLCVRecord.date, OHLCVRecord.close).where(
OHLCVRecord.ticker_id.in_(ticker_ids),
OHLCVRecord.date >= first,
)
)
ticker_closes: dict[int, dict[date, float]] = {}
for tid, day, close in rows.all():
ticker_closes.setdefault(tid, {})[day] = float(close)
return build_equity_curve(list(trades), ticker_closes, benchmark_closes)