Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion apps/api/src/spin2note_api/clickhouse/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@
],
"hand_players": [
"hand_id", "user_id", "tournament_format", "effective_stack_bb", "seat", "is_hero",
"villain_hash", "position", "starting_stack", "hole_cards", "won", "result", "parsed_at",
"villain_hash", "position", "starting_stack", "hole_cards", "won", "result", "chip_ev",
"parsed_at",
],
"actions": [
"hand_id", "user_id", "tournament_format", "effective_stack_bb", "street", "seat",
Expand Down
31 changes: 30 additions & 1 deletion apps/api/src/spin2note_api/clickhouse/queries.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ async def overview(client: AsyncClient, user_id: UUID, fmt: str | None) -> dict[
toUInt16(round(effective_stack_bb / 10)) AS bb,
count() AS hands,
sum(result) AS total_result,
sum(chip_ev) AS total_ev,
countIf(result > 0) / count() AS winrate
FROM hand_players
WHERE user_id = {{u:UUID}} AND is_hero = 1{f_hands}
Expand All @@ -124,11 +125,38 @@ async def overview(client: AsyncClient, user_id: UUID, fmt: str | None) -> dict[
"effective_stack_bb": int(r[0]),
"hands": int(r[1]),
"result": round(float(r[2]), 2),
"winrate": round(float(r[3]), 4),
"result_ev": round(float(r[3]), 2),
"winrate": round(float(r[4]), 4),
}
for r in by_stack.result_rows
]

# Same aggregation grouped by hero position (UTG/HJ/CO/BTN/SB/BB); ordered client-side.
by_position = await client.query(
f"""
SELECT
position,
count() AS hands,
sum(result) AS total_result,
sum(chip_ev) AS total_ev,
countIf(result > 0) / count() AS winrate
FROM hand_players
WHERE user_id = {{u:UUID}} AND is_hero = 1{f_hands}
GROUP BY position
""",
parameters=params,
)
positions = [
{
"position": str(r[0]),
"hands": int(r[1]),
"result": round(float(r[2]), 2),
"result_ev": round(float(r[3]), 2),
"winrate": round(float(r[4]), 4),
}
for r in by_position.result_rows
]

# Cumulative chips P&L over hero hands (time-ordered). Respects the format filter.
chips_series = await client.query(
f"""
Expand Down Expand Up @@ -160,6 +188,7 @@ async def overview(client: AsyncClient, user_id: UUID, fmt: str | None) -> dict[
"total_tournaments": total_tournaments,
"avg_multiplier": avg_multiplier,
"by_stack": stacks,
"by_position": positions,
"chips_timeline": chips_timeline,
"dollars_timeline": dollars_timeline,
}
Expand Down
1 change: 1 addition & 0 deletions apps/api/src/spin2note_api/domain/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ class HandPlayer(BaseModel):
hole_cards: str = ""
won: float = 0.0
result: float = 0.0
chip_ev: float = 0.0 # all-in-adjusted result; == result unless a 2-way all-in reached showdown
parsed_at: datetime = Field(default_factory=_now)


Expand Down
12 changes: 11 additions & 1 deletion apps/api/src/spin2note_api/http/stats.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,16 @@
class StackBucket(BaseModel):
effective_stack_bb: int
hands: int
result: float
result: float # total chips
result_ev: float # total chipEV (all-in adjusted)
winrate: float


class PositionBucket(BaseModel):
position: str
hands: int
result: float # total chips
result_ev: float # total chipEV (all-in adjusted)
winrate: float


Expand All @@ -34,6 +43,7 @@ class Overview(BaseModel):
total_tournaments: int
avg_multiplier: float
by_stack: list[StackBucket]
by_position: list[PositionBucket]
chips_timeline: list[TimelinePoint]
dollars_timeline: list[TimelinePoint]

Expand Down
3 changes: 2 additions & 1 deletion apps/api/src/spin2note_api/parser/mapping.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ def build_hand(parsed: dict[str, Any], user_id: UUID) -> Hand:
hole_cards=p["hole_cards"],
won=p["won"],
result=p["result"],
chip_ev=p["chip_ev"],
)
for p in parsed["players"]
]
Expand Down Expand Up @@ -123,7 +124,7 @@ def build_chunk_rows(
player_rows.append((
hid, user_id, fmt, eff, p["seat"], int(p["is_hero"]), p["villain_hash"],
p["position"], p["starting_stack"], p["hole_cards"], p["won"], p["result"],
parsed_at,
p["chip_ev"], parsed_at,
))
for a in h["actions"]:
action_rows.append((
Expand Down
12 changes: 11 additions & 1 deletion apps/api/tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,14 @@ async def fake_overview(_c: Any, _u: Any, _f: Any) -> dict[str, Any]:
"total_hands": 10,
"total_tournaments": 2,
"avg_multiplier": 2.5,
"by_stack": [{"effective_stack_bb": 15, "hands": 10, "result": 120.0, "winrate": 0.6}],
"by_stack": [
{"effective_stack_bb": 15, "hands": 10, "result": 120.0,
"result_ev": 90.0, "winrate": 0.6}
],
"by_position": [
{"position": "BTN", "hands": 6, "result": 80.0,
"result_ev": 70.0, "winrate": 0.5}
],
"chips_timeline": [{"idx": 1, "at": "2026-01-07T22:54:43", "cumulative": 120.0}],
"dollars_timeline": [{"idx": 1, "at": "2026-01-07T22:54:43", "cumulative": -0.25}],
}
Expand Down Expand Up @@ -59,6 +66,9 @@ def test_overview_requires_shape(client: TestClient) -> None:
body = r.json()
assert body["total_hands"] == 10
assert body["by_stack"][0]["winrate"] == 0.6
assert body["by_stack"][0]["result_ev"] == 90.0
assert body["by_position"][0]["position"] == "BTN"
assert body["by_position"][0]["result_ev"] == 70.0


def test_overview_rejects_bad_format(client: TestClient) -> None:
Expand Down
23 changes: 23 additions & 0 deletions apps/api/tests/test_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,3 +132,26 @@ def test_build_tournament_rows_matches_table_columns() -> None:
# Tuple arity is the contract with TABLE_COLUMNS; hero_prize sits before parsed_at.
assert len(rows[0]) == len(TABLE_COLUMNS["tournaments"])
assert rows[0][TABLE_COLUMNS["tournaments"].index("hero_prize")] == 0.0


def test_chip_ev_present_and_adjusts_allin_showdown() -> None:
# The 3-max sample is a preflop all-in that reaches showdown; chipEV must differ from the
# actual result for the hero (who lost the pot but had equity), and stay within the pot.
h = build_hands(parse(_read("3max/sample.txt")), USER)[0]
hero = next(p for p in h.players if p.is_hero)
assert hero.result == -300.0
assert hero.chip_ev > hero.result
assert hero.chip_ev < 300.0


def test_build_chunk_rows_player_arity_matches_table_columns() -> None:
from datetime import datetime

from spin2note_api.clickhouse.client import TABLE_COLUMNS
from spin2note_api.parser import build_chunk_rows

rows = build_chunk_rows(parse(_read("3max/sample.txt")), USER, datetime(2026, 1, 1))
cols = TABLE_COLUMNS["hand_players"]
assert len(rows["hand_players"][0]) == len(cols)
# chip_ev column carries a float (the all-in-adjusted result).
assert isinstance(rows["hand_players"][0][cols.index("chip_ev")], float)
58 changes: 54 additions & 4 deletions apps/web/app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,55 @@

import * as React from "react";

import { ResultByStack } from "@/components/charts/result-by-stack";
import { CumulativeResult } from "@/components/charts/cumulative-result";
import { MetricByCategory, type CategoryRow } from "@/components/charts/metric-by-category";
import { AppShell } from "@/components/app-shell";
import { Uploader } from "@/components/uploader";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Table, TBody, TD, TH, THead, TR } from "@/components/ui/table";
import { getOverview, getRecentHands, type Overview, type RecentHand } from "@/lib/api";
import {
getOverview,
getRecentHands,
type Overview,
type PositionBucket,
type RecentHand,
type StackBucket,
} from "@/lib/api";
import { useAuth } from "@/lib/auth";
import { formatChips, formatUsd } from "@/lib/utils";

type Format = "3max" | "6max" | undefined;

// Canonical poker order (BTN shown for "BU"); positions absent in 3-max simply don't appear.
const POSITION_ORDER = ["UTG", "HJ", "CO", "BTN", "SB", "BB"];

function toRow(label: string, b: { hands: number; result: number; result_ev: number; winrate: number }): CategoryRow {
const per = (v: number) => (b.hands > 0 ? (v / b.hands) * 100 : 0);
return {
label,
perHundredChips: per(b.result),
perHundredEv: per(b.result_ev),
totalChips: b.result,
totalEv: b.result_ev,
hands: b.hands,
winrate: b.winrate,
};
}

function positionRows(by: PositionBucket[]): CategoryRow[] {
const idx = (p: string) => {
const i = POSITION_ORDER.indexOf(p);
return i === -1 ? POSITION_ORDER.length : i;
};
return [...by].sort((a, b) => idx(a.position) - idx(b.position)).map((b) => toRow(b.position, b));
}

function stackRows(by: StackBucket[]): CategoryRow[] {
return by.map((b) => toRow(`${b.effective_stack_bb}bb`, b));
}

function Stat({ title, value }: { title: string; value: string }) {
return (
<Card>
Expand Down Expand Up @@ -86,11 +121,26 @@ function Dashboard() {

<Card>
<CardHeader>
<CardTitle>Net result by effective stack (BB)</CardTitle>
<CardTitle>By position — chips/100 vs chipEV/100</CardTitle>
<p className="text-xs text-muted-foreground">Where you earn most/least by seat (BU = BTN). chipEV strips all-in variance.</p>
</CardHeader>
<CardContent>
{overview && overview.by_position.length > 0 ? (
<MetricByCategory data={positionRows(overview.by_position)} />
) : (
<p className="py-12 text-center text-sm text-muted-foreground">No hands yet — upload a hand history.</p>
)}
</CardContent>
</Card>

<Card>
<CardHeader>
<CardTitle>By effective stack — chips/100 vs chipEV/100</CardTitle>
<p className="text-xs text-muted-foreground">Where you earn most/least by tournament stage (stack depth in BB).</p>
</CardHeader>
<CardContent>
{overview && overview.by_stack.length > 0 ? (
<ResultByStack data={overview.by_stack} />
<MetricByCategory data={stackRows(overview.by_stack)} />
) : (
<p className="py-12 text-center text-sm text-muted-foreground">No hands yet — upload a hand history.</p>
)}
Expand Down
62 changes: 62 additions & 0 deletions apps/web/src/components/charts/metric-by-category.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
"use client";

import {
Bar,
BarChart,
CartesianGrid,
Legend,
ReferenceLine,
ResponsiveContainer,
Tooltip,
XAxis,
YAxis,
} from "recharts";

import { formatChips, formatPer100 } from "@/lib/utils";

export type CategoryRow = {
label: string;
perHundredChips: number;
perHundredEv: number;
totalChips: number;
totalEv: number;
hands: number;
winrate: number;
};

const CHIPS = "hsl(152 70% 45%)";
const EV = "hsl(210 90% 60%)";

function CategoryTooltip({ active, payload }: { active?: boolean; payload?: { payload: CategoryRow }[] }) {
if (!active || !payload?.length) return null;
const r = payload[0].payload;
return (
<div className="rounded-md border border-border bg-[hsl(222_40%_8%)] px-3 py-2 text-xs text-foreground">
<div className="mb-1 font-semibold">{r.label}</div>
<div>chips/100: <span style={{ color: CHIPS }}>{formatPer100(r.perHundredChips)}</span></div>
<div>chipEV/100: <span style={{ color: EV }}>{formatPer100(r.perHundredEv)}</span></div>
<div className="mt-1 text-muted-foreground">
total {formatChips(r.totalChips)} · EV {formatChips(r.totalEv)}
</div>
<div className="text-muted-foreground">{r.hands.toLocaleString("en-US")} hands · {(r.winrate * 100).toFixed(1)}% won</div>
</div>
);
}

/** Grouped bars per category (position or stack): chips/100 vs chipEV/100. */
export function MetricByCategory({ data }: { data: CategoryRow[] }) {
return (
<ResponsiveContainer width="100%" height={280}>
<BarChart data={data} margin={{ top: 8, right: 8, bottom: 8, left: 8 }}>
<CartesianGrid strokeDasharray="3 3" stroke="hsl(217 33% 17%)" vertical={false} />
<XAxis dataKey="label" tick={{ fill: "hsl(215 20% 65%)", fontSize: 12 }} />
<YAxis tick={{ fill: "hsl(215 20% 65%)", fontSize: 12 }} width={56} />
<ReferenceLine y={0} stroke="hsl(217 33% 30%)" />
<Tooltip cursor={{ fill: "hsl(217 33% 17% / 0.4)" }} content={<CategoryTooltip />} />
<Legend wrapperStyle={{ fontSize: 12 }} />
<Bar name="chips/100" dataKey="perHundredChips" fill={CHIPS} radius={[3, 3, 0, 0]} />
<Bar name="chipEV/100" dataKey="perHundredEv" fill={EV} radius={[3, 3, 0, 0]} />
</BarChart>
</ResponsiveContainer>
);
}
40 changes: 0 additions & 40 deletions apps/web/src/components/charts/result-by-stack.tsx

This file was deleted.

1 change: 1 addition & 0 deletions apps/web/src/lib/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type { components } from "./api/schema";
// Types come straight from the backend OpenAPI spec (regenerate via `npm run generate-client`).
export type Overview = components["schemas"]["Overview"];
export type StackBucket = components["schemas"]["StackBucket"];
export type PositionBucket = components["schemas"]["PositionBucket"];
export type TimelinePoint = components["schemas"]["TimelinePoint"];
export type RecentHand = components["schemas"]["RecentHand"];
export type UploadResult = components["schemas"]["UploadResult"];
Expand Down
Loading
Loading