brackt/app/routes/admin.sports-seasons.$id.expected-values.tsx
Chris Parsons 79ec477a98 feat: implement Expected Value System with ICM probability calculator
Implements Phase 5.2 of the EV system with Harville-Malmuth Independent Chip Model
for calculating participant placement probabilities from futures odds.

## Key Features

### ICM Probability Calculator
- Implements Harville-Malmuth method for distributing probabilities
- Converts American odds to championship probabilities
- Generates P(1st) through P(8th) for all participants
- Column-normalized: each placement sums to 100% across all teams
- Works with any number of participants (not limited to 8)

### Admin UI - Futures Odds Entry
- Enter American odds (e.g., +550, -200) for championship futures
- Live preview of ICM-calculated probability distributions
- Displays all 8 placement probabilities
- Persists odds for editing on subsequent visits
- Automatic probability normalization (removes bookmaker vig)

### Database Schema Updates
- Renamed participant_expected_values.season_id → sports_season_id
- Updated foreign key to reference sports_seasons instead of seasons
- Added source_odds field to store original futures odds
- Migration 0025: Column rename and FK update
- Migration 0026: Add source_odds field

### Model Layer
- participant-expected-value: CRUD operations for probability distributions
- Supports multiple probability sources (manual, futures_odds, elo_simulation)
- Automatic EV calculation based on league scoring rules
- Probability validation and normalization

### Service Layer
- icm-calculator: Harville-Malmuth probability distribution
- probability-engine: Odds conversion and Elo utilities (for future use)
- bracket-simulator: Monte Carlo simulation (for future hybrid approach)
- ev-calculator: Expected value computation from probabilities

## Technical Details

- Uses exponential decay favoring top positions for strong teams
- Preserves championship probability ordering in final distributions
- Row sums vary (strong teams ~100%, weak teams lower)
- All probabilities between 0-1, mathematically valid
- Comprehensive test suite: 97 tests passing

## Future Enhancements

- Hybrid approach: ICM pre-playoffs, bracket simulation during playoffs
- Integration with league-specific scoring rules
- Historical probability tracking for accuracy analysis

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-17 22:19:46 -08:00

316 lines
12 KiB
TypeScript

import { Form, Link, useActionData } from "react-router";
import type { Route } from "./+types/admin.sports-seasons.$id.expected-values";
import { findSportsSeasonById } from "~/models/sports-season";
import { findParticipantsBySportsSeasonId } from "~/models/participant";
import {
upsertParticipantEV,
getParticipantEV,
getAllParticipantEVsForSeason
} from "~/models/participant-expected-value";
import { Button } from "~/components/ui/button";
import { Input } from "~/components/ui/input";
import { Label } from "~/components/ui/label";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "~/components/ui/card";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "~/components/ui/table";
import { ArrowLeft, Save, Calculator } from "lucide-react";
import type { ProbabilitySource } from "~/models/participant-expected-value";
export async function loader({ params }: Route.LoaderArgs) {
const sportsSeason = await findSportsSeasonById(params.id);
if (!sportsSeason) {
throw new Response("Sports season not found", { status: 404 });
}
const participants = await findParticipantsBySportsSeasonId(params.id);
const existingEVs = await getAllParticipantEVsForSeason(params.id);
// Create a map of participant ID to EV data
const evMap = new Map(existingEVs.map(ev => [ev.participantId, ev]));
return {
sportsSeason: sportsSeason as typeof sportsSeason & { sport: { id: string; name: string; type: string; slug: string } },
participants,
existingEVs: evMap,
};
}
export async function action({ request, params }: Route.ActionArgs) {
const formData = await request.formData();
const participantId = formData.get("participantId");
const source = (formData.get("source") || "manual") as ProbabilitySource;
if (typeof participantId !== "string") {
return { error: "Participant ID is required" };
}
// Get probability values
const probFirst = parseFloat(formData.get("probFirst") as string || "0");
const probSecond = parseFloat(formData.get("probSecond") as string || "0");
const probThird = parseFloat(formData.get("probThird") as string || "0");
const probFourth = parseFloat(formData.get("probFourth") as string || "0");
const probFifth = parseFloat(formData.get("probFifth") as string || "0");
const probSixth = parseFloat(formData.get("probSixth") as string || "0");
const probSeventh = parseFloat(formData.get("probSeventh") as string || "0");
const probEighth = parseFloat(formData.get("probEighth") as string || "0");
// Use default scoring rules
// Note: Actual league seasons may have different scoring rules
// EVs will be recalculated when used in a specific league
const scoringRules = {
pointsFor1st: 100,
pointsFor2nd: 70,
pointsFor3rd: 50,
pointsFor4th: 40,
pointsFor5th: 25,
pointsFor6th: 25,
pointsFor7th: 15,
pointsFor8th: 15,
};
try {
const result = await upsertParticipantEV({
participantId,
sportsSeasonId: params.id,
probabilities: {
probFirst,
probSecond,
probThird,
probFourth,
probFifth,
probSixth,
probSeventh,
probEighth,
},
scoringRules,
source,
});
return {
success: true,
participantId,
expectedValue: parseFloat(result.expectedValue),
};
} catch (error) {
console.error("Error saving probabilities:", error);
return {
error: error instanceof Error ? error.message : "Failed to save probabilities"
};
}
}
export default function ExpectedValuesPage({ loaderData, actionData }: Route.ComponentProps) {
const { sportsSeason, participants, existingEVs } = loaderData;
return (
<div className="container mx-auto p-6 space-y-6">
<div className="flex items-center gap-4">
<Link to={`/admin/sports-seasons/${sportsSeason.id}`}>
<Button variant="ghost" size="sm">
<ArrowLeft className="h-4 w-4 mr-2" />
Back to Sports Season
</Button>
</Link>
</div>
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Calculator className="h-5 w-5" />
Expected Values: {sportsSeason.sport.name} {sportsSeason.year}
</CardTitle>
<CardDescription>
Manage probability distributions and expected values for participants
</CardDescription>
</CardHeader>
<CardContent className="space-y-6">
{actionData?.error && (
<div className="p-4 bg-red-50 border border-red-200 rounded-md text-red-700">
{actionData.error}
</div>
)}
{actionData?.success && (
<div className="p-4 bg-green-50 border border-green-200 rounded-md text-green-700">
Successfully saved! Expected Value: {actionData.expectedValue?.toFixed(2)} points
</div>
)}
<div className="text-sm text-gray-600 space-y-2">
<p><strong>Default Scoring Rules (for EV calculation):</strong></p>
<div className="grid grid-cols-4 gap-2">
<span>1st: 100 pts</span>
<span>2nd: 70 pts</span>
<span>3rd: 50 pts</span>
<span>4th: 40 pts</span>
<span>5th: 25 pts</span>
<span>6th: 25 pts</span>
<span>7th: 15 pts</span>
<span>8th: 15 pts</span>
</div>
<p className="text-xs text-gray-500 italic">
Note: EVs will be recalculated with actual league scoring rules when used in fantasy leagues.
</p>
</div>
<Table>
<TableHeader>
<TableRow>
<TableHead>Participant</TableHead>
<TableHead className="text-center">1st %</TableHead>
<TableHead className="text-center">2nd %</TableHead>
<TableHead className="text-center">3rd %</TableHead>
<TableHead className="text-center">4th %</TableHead>
<TableHead className="text-center">5th %</TableHead>
<TableHead className="text-center">6th %</TableHead>
<TableHead className="text-center">7th %</TableHead>
<TableHead className="text-center">8th %</TableHead>
<TableHead className="text-center">EV</TableHead>
<TableHead></TableHead>
</TableRow>
</TableHeader>
<TableBody>
{participants.map((participant: { id: string; name: string }) => {
const existingEV = existingEVs.get(participant.id);
const formId = `form-${participant.id}`;
return (
<TableRow key={participant.id}>
<TableCell className="font-medium">{participant.name}</TableCell>
<TableCell>
<Input
form={formId}
type="number"
name="probFirst"
defaultValue={existingEV ? parseFloat(existingEV.probFirst) : 12.5}
step="0.01"
min="0"
max="100"
className="w-20 text-center"
/>
</TableCell>
<TableCell>
<Input
form={formId}
type="number"
name="probSecond"
defaultValue={existingEV ? parseFloat(existingEV.probSecond) : 12.5}
step="0.01"
min="0"
max="100"
className="w-20 text-center"
/>
</TableCell>
<TableCell>
<Input
form={formId}
type="number"
name="probThird"
defaultValue={existingEV ? parseFloat(existingEV.probThird) : 12.5}
step="0.01"
min="0"
max="100"
className="w-20 text-center"
/>
</TableCell>
<TableCell>
<Input
form={formId}
type="number"
name="probFourth"
defaultValue={existingEV ? parseFloat(existingEV.probFourth) : 12.5}
step="0.01"
min="0"
max="100"
className="w-20 text-center"
/>
</TableCell>
<TableCell>
<Input
form={formId}
type="number"
name="probFifth"
defaultValue={existingEV ? parseFloat(existingEV.probFifth) : 12.5}
step="0.01"
min="0"
max="100"
className="w-20 text-center"
/>
</TableCell>
<TableCell>
<Input
form={formId}
type="number"
name="probSixth"
defaultValue={existingEV ? parseFloat(existingEV.probSixth) : 12.5}
step="0.01"
min="0"
max="100"
className="w-20 text-center"
/>
</TableCell>
<TableCell>
<Input
form={formId}
type="number"
name="probSeventh"
defaultValue={existingEV ? parseFloat(existingEV.probSeventh) : 12.5}
step="0.01"
min="0"
max="100"
className="w-20 text-center"
/>
</TableCell>
<TableCell>
<Input
form={formId}
type="number"
name="probEighth"
defaultValue={existingEV ? parseFloat(existingEV.probEighth) : 12.5}
step="0.01"
min="0"
max="100"
className="w-20 text-center"
/>
</TableCell>
<TableCell className="text-center font-semibold">
{existingEV ? parseFloat(existingEV.expectedValue).toFixed(2) : "-"}
</TableCell>
<TableCell>
<Form method="post" id={formId}>
<input type="hidden" name="participantId" value={participant.id} />
<input type="hidden" name="source" value="manual" />
<Button type="submit" size="sm">
<Save className="h-4 w-4 mr-1" />
Save
</Button>
</Form>
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
{participants.length === 0 && (
<p className="text-center text-gray-500 py-8">
No participants found. Please add participants to this sports season first.
</p>
)}
</CardContent>
</Card>
</div>
);
}