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
14 changes: 11 additions & 3 deletions .github/workflows/retrain-corners-cards.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ on:
- "scripts/models/build-euro-dataset.py"
- "scripts/models/train-euro-cups.py"
- "scripts/models/export-euro-runtime.py"
- "scripts/models/train-euro-stats.py"
- "scripts/models/export-euro-stats-runtime.py"
- "scripts/models/build-nt-dataset.py"
- "scripts/models/train-nt.py"
- "scripts/models/export-nt-runtime.py"
Expand All @@ -37,7 +39,7 @@ concurrency:
jobs:
retrain:
runs-on: ubuntu-latest
timeout-minutes: 90
timeout-minutes: 120
steps:
- uses: actions/checkout@v4
with:
Expand Down Expand Up @@ -77,7 +79,7 @@ jobs:
- name: Download euro-cup history — CL/EL/ECL (BSD sports.bzzoiro.com)
env:
BSD_TOKEN: ${{ secrets.BSD_TOKEN }}
run: python scripts/models/download-bsd-euro.py --output-dir data/raw-bsd
run: python scripts/models/download-bsd-euro.py --output-dir data/raw-bsd --with-stats

- name: Build euro-cup dataset (CL + EL + ECL)
run: python scripts/models/build-euro-dataset.py --bsd-dir data/raw-bsd --domestic data/corners_cards_training.csv --output data/euro_cups_training.csv
Expand All @@ -88,6 +90,12 @@ jobs:
- name: Export euro-cup browser runtime model JSON
run: python scripts/models/export-euro-runtime.py --bsd-dir data/raw-bsd

- name: Train and validate euro-cup corners/cards models (split by season)
run: python scripts/models/train-euro-stats.py

- name: Export euro-cup corners/cards browser runtime model JSON
run: python scripts/models/export-euro-stats-runtime.py --bsd-dir data/raw-bsd

- name: Download national-teams history (martj42/international_results, CC0-1.0)
run: |
mkdir -p data/raw-nt
Expand All @@ -114,7 +122,7 @@ jobs:
run: |
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git add data/corners_cards_models.json data/corners_cards_model_validation.json data/goals_markets_models.json data/goals_markets_model_validation.json data/stats_markets_models.json data/stats_markets_model_validation.json data/historical_dataset_report.json data/prediction-ledger/evaluation-internal.json data/euro_cups_model.json data/euro_cups_model_validation.json data/nt_model.json data/nt_model_validation.json
git add data/corners_cards_models.json data/corners_cards_model_validation.json data/goals_markets_models.json data/goals_markets_model_validation.json data/stats_markets_models.json data/stats_markets_model_validation.json data/historical_dataset_report.json data/prediction-ledger/evaluation-internal.json data/euro_cups_model.json data/euro_cups_model_validation.json data/euro_stats_models.json data/euro_stats_model_validation.json data/nt_model.json data/nt_model_validation.json
if git diff --cached --quiet; then
echo "Model artifacts are already current"
else
Expand Down
1 change: 1 addition & 0 deletions coupons.html
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ <h2 id="placed-bets-title">Проставленные ставки</h2>
<script src="stats-internal-model.js"></script>
<script src="nt-internal-model.js"></script>
<script src="euro-internal-model.js"></script>
<script src="euro-stats-internal-model.js"></script>
<script src="express-model.js"></script>
<script src="coupon-confirmation.js"></script>
<script src="daily-board.js"></script>
Expand Down
13 changes: 11 additions & 2 deletions daily-board.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
const statsApi = isNode ? require('./stats-internal-model.js') : root.StatsInternalModel;
const ntApi = isNode ? require('./nt-internal-model.js') : root.NtInternalModel;
const euroApi = isNode ? require('./euro-internal-model.js') : root.EuroInternalModel;
const euroStatsApi = isNode ? require('./euro-stats-internal-model.js') : root.EuroStatsInternalModel;

const MOSCOW_OFFSET_MS = 180 * 60000;
const MIN_PROBABILITY = 0.75;
Expand Down Expand Up @@ -243,6 +244,11 @@
}),
...nationsCandidates(models.nations, predictions, day, now),
...euroCandidates(models.euro, predictions, day, now),
// Еврокубковые угловые/ЖК: та же форма prediction[market].lines, что у
// клубной модели, поэтому используется общий перебор clubMarketCandidates.
...clubMarketCandidates(euroStatsApi, models.euroStats, predictions, day, now, {
corners: 'Угловые', yellowCards: 'ЖК',
}),
];
return rows.sort((a, b) => (a.time - b.time) || (b.probability - a.probability) || a.label.localeCompare(b.label, 'ru'));
}
Expand Down Expand Up @@ -819,19 +825,22 @@
$('daily-board-status').textContent = 'Загрузка модельного снимка…';
$('daily-board-status').className = 'daily-board__status is-loading';
try {
const [data, goals, cornersCards, stats, nations, euro] = await Promise.all([
const [data, goals, cornersCards, stats, nations, euro, euroStats] = await Promise.all([
fetchJson('./data.json'),
fetchJson('./data/goals_markets_models.json'),
fetchJson('./data/corners_cards_models.json'),
fetchJson('./data/stats_markets_models.json'),
fetchJson('./data/nt_model.json'),
fetchJson('./data/euro_cups_model.json'),
// Файл появляется после первого переобучения с евро-статистикой;
// до этого доска работает без него.
fetchJson('./data/euro_stats_models.json').catch(() => null),
]);
const now = Date.now();
const currentGameDay = gameDayKeyMsk(now);
const isCurrent = data.date === currentGameDay;
const candidates = isCurrent
? buildCandidates(data, { goals, cornersCards, stats, nations, euro }, now)
? buildCandidates(data, { goals, cornersCards, stats, nations, euro, euroStats }, now)
: [];
renderCandidates(candidates, isCurrent
? 'На оставшуюся часть игрового дня нет модельных рынков с вероятностью от 75%.'
Expand Down
16 changes: 14 additions & 2 deletions docs/PROJECT_DOCUMENTATION.md

Large diffs are not rendered by default.

221 changes: 221 additions & 0 deletions euro-stats-internal-model.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,221 @@
/* Еврокубковые внутренние модели статистики: угловые и жёлтые карточки
* (Лига чемпионов, Лига Европы, Лига Конференций).
*
* Чистый рантайм: вероятности считаются из data/euro_stats_models.json
* (экспорт scripts/models/export-euro-stats-runtime.py). Импьютинг, скейлинг
* и коэффициенты воспроизводят sklearn-пайплайн экспортёра; распределение —
* Poisson или NB2 по решению валидации; изотонная калибровка применяется,
* если была внедрена. Гейтинг по турнирам — по списку competitions из самого
* JSON; вероятности не выдумываются: неизвестный турнир или команда -> null.
*
* Форма ответа predict() совпадает с клубной моделью (internal-model.js):
* prediction.corners / prediction.yellowCards = { lambda, distribution,
* lines: [{line, over, under}] } — поэтому контур дня использует общий
* clubMarketCandidates.
*/
(function (root, factory) {
if (typeof module === 'object' && module.exports) {
module.exports = factory();
} else {
root.EuroStatsInternalModel = factory();
}
}(typeof self !== 'undefined' ? self : this, function () {
'use strict';

function norm(value) {
return String(value || '')
.normalize('NFKD').replace(/[̀-ͯ]/g, '')
.toLowerCase()
.replace(/[^a-z0-9]+/g, ' ')
.trim();
}

function competitionCatalog(model) {
return (model && Array.isArray(model.competitions)) ? model.competitions : [];
}

// Сопоставляет название лиги из фида с турниром модели; неизвестный
// турнир -> null (вероятности не выдумываются).
function resolveCompetition(model, leagueName) {
const n = norm(leagueName);
if (!n) return null;
const catalog = competitionCatalog(model);
for (let i = 0; i < catalog.length; i++) {
const comp = catalog[i];
const names = comp.names || [];
for (let j = 0; j < names.length; j++) {
if (norm(names[j]) === n) return { code: comp.code, name: comp.name || comp.code };
}
}
return null;
}

function resolveTeam(model, name) {
const key = (model.teamAliases || {})[norm(name)];
return key ? { key, team: (model.teams || {})[key] } : null;
}

// Контекст признаков: те же имена, что генерирует feature_columns()
// train-euro-stats.py. Отсутствующие значения — null (уйдут в медиану
// импьютера с индикатором пропуска).
function buildContext(model, comp, home, away) {
const hE = home.team.euro || {};
const aE = away.team.euro || {};
const hD = home.team.domestic || null;
const aD = away.team.domestic || null;
const ctx = {
home_euro_elo: hE.euroElo != null ? hE.euroElo : null,
away_euro_elo: aE.euroElo != null ? aE.euroElo : null,
home_euro_gf: hE.euroGf != null ? hE.euroGf : null,
home_euro_ga: hE.euroGa != null ? hE.euroGa : null,
away_euro_gf: aE.euroGf != null ? aE.euroGf : null,
away_euro_ga: aE.euroGa != null ? aE.euroGa : null,
comp_is_el: comp.code === 'EL' ? 1 : 0,
comp_is_ecl: comp.code === 'ECL' ? 1 : 0,
home_dom_missing: hD ? 0 : 1,
away_dom_missing: aD ? 0 : 1,
};
const groups = ['corners', 'cards'];
for (const group of groups) {
const compAvg = model.compAverages && model.compAverages[comp.code];
ctx[`comp_${group}_avg`] = compAvg && compAvg[group] != null ? compAvg[group] : null;
for (const [side, euro, dom] of [['home', hE, hD], ['away', aE, aD]]) {
for (const kind of ['for', 'against']) {
for (const window of [5, 10]) {
const euroKey = `euro_${group}_${kind}_avg${window}`;
ctx[`${side}_${euroKey}`] = euro[euroKey] != null ? euro[euroKey] : null;
const domKey = `${group}_${kind}_avg${window}`;
ctx[`${side}_dom_${domKey}`] = dom && dom[domKey] != null ? dom[domKey] : null;
}
}
const gamesKey = `euro_${group}_games`;
ctx[`${side}_${gamesKey}`] = euro[gamesKey] != null ? euro[gamesKey] : null;
}
}
return ctx;
}

// Воспроизводит SimpleImputer(median, add_indicator, keep_empty_features)
// + StandardScaler по экспортированным параметрам.
function transform(spec, ctx) {
return spec.features.map((name, i) => {
let raw;
if (name.endsWith('__missing')) {
raw = ctx[name.slice(0, -'__missing'.length)] == null ? 1 : 0;
} else {
raw = ctx[name] != null && Number.isFinite(Number(ctx[name]))
? Number(ctx[name]) : spec.imputerMedian[i];
}
return (raw - spec.scalerMean[i]) / (spec.scalerScale[i] || 1);
});
}

function predictLambda(spec, vector) {
let z = spec.intercept;
for (let i = 0; i < spec.coefficients.length; i++) z += spec.coefficients[i] * vector[i];
return Math.min(40, Math.max(0.01, Math.exp(z)));
}

const factorial = [1];
for (let i = 1; i <= 60; i++) factorial[i] = factorial[i - 1] * i;

function poissonOver(lambda, line) {
// P(X > line) с целым порогом floor(line); линии оканчиваются на .5.
const k = Math.floor(line);
let cumulative = 0;
for (let i = 0; i <= k; i++) {
cumulative += Math.exp(-lambda) * Math.pow(lambda, i) / factorial[i];
}
return Math.min(1, Math.max(0, 1 - cumulative));
}

// NB2-хвост: Var = mean + alpha * mean^2, size r = 1/alpha; рекуррентность
// PMF совпадает с scipy nbinom(n=r, p=r/(r+mean)) — как в клубной модели.
function nbOver(lambda, line, alpha) {
const a = Math.max(alpha || 0.01, 0.0001);
const r = 1 / a;
const p0 = r / (r + lambda);
let pmf = Math.pow(p0, r);
let cumulative = pmf;
const k = Math.floor(line);
for (let i = 1; i <= k; i++) {
pmf *= (r + i - 1) / i * (1 - p0);
cumulative += pmf;
}
return Math.min(1, Math.max(0, 1 - cumulative));
}

function overProbability(spec, lambda, line) {
return spec && spec.type === 'nb2' ? nbOver(lambda, line, spec.nbAlpha) : poissonOver(lambda, line);
}

// Узлы изотонного калибратора: кусочно-линейная интерполяция с зажимом.
function calibrate(p, knots) {
if (!knots || !knots.x || !knots.x.length) return p;
const x = knots.x, y = knots.y;
if (p <= x[0]) return y[0];
const last = x.length - 1;
if (p >= x[last]) return y[last];
let lo = 0, hi = last;
while (hi - lo > 1) {
const mid = (lo + hi) >> 1;
if (x[mid] <= p) lo = mid; else hi = mid;
}
const span = x[hi] - x[lo];
const t = span > 1e-12 ? (p - x[lo]) / span : 0;
return y[lo] + t * (y[hi] - y[lo]);
}

function marketPrediction(spec, ctx) {
const lambda = predictLambda(spec, transform(spec, ctx));
const calibrators = spec.calibration || null;
return {
lambda,
distribution: spec.type === 'nb2' ? 'nb2' : 'poisson',
lines: (spec.lines || []).map((line) => {
let over = overProbability(spec, lambda, line);
if (calibrators && calibrators[String(line)]) over = calibrate(over, calibrators[String(line)]);
over = Math.min(1, Math.max(0, over));
return { line, over, under: 1 - over };
}),
};
}

function predict(model, leagueName, homeName, awayName) {
if (!model || model.schemaVersion !== 1 || !model.models) return null;
const comp = resolveCompetition(model, leagueName);
if (!comp) return null;
const home = resolveTeam(model, homeName);
const away = resolveTeam(model, awayName);
if (!home || !away || !home.team || !away.team) return null;
const ctx = buildContext(model, comp, home, away);
const out = {
league: leagueName,
leagueLabel: comp.name,
competition: comp,
homeModel: home.team.fdoName || home.team.name,
awayModel: away.team.fdoName || away.team.name,
trainingThrough: model.trainingThrough,
};
if (model.models.corners) out.corners = marketPrediction(model.models.corners, ctx);
if (model.models.yellowCards) out.yellowCards = marketPrediction(model.models.yellowCards, ctx);
return out;
}

// Дедуп-ключ: варианты имени одного матча схлопываются в модельную
// идентичность (турнир + канонические ключи команд); вне покрытия — сырые
// нормализованные имена.
function canonicalFixtureKey(model, leagueName, homeName, awayName) {
const comp = model ? resolveCompetition(model, leagueName) : null;
if (comp) {
const home = resolveTeam(model, homeName);
const away = resolveTeam(model, awayName);
if (home && away) return `eurostats|${comp.code}|${home.key}|${away.key}`;
}
return 'raw|' + norm(homeName) + '|' + norm(awayName);
}

return { norm, resolveCompetition, resolveTeam, buildContext, transform,
predictLambda, poissonOver, nbOver, overProbability, calibrate,
marketPrediction, predict, canonicalFixtureKey };
}));
13 changes: 13 additions & 0 deletions scripts/lines/build_daily_coupons.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ const cornersApi = require('../../internal-model.js');
const statsApi = require('../../stats-internal-model.js');
const ntApi = require('../../nt-internal-model.js');
const euroApi = require('../../euro-internal-model.js');
const euroStatsApi = require('../../euro-stats-internal-model.js');

const BOOKMAKERS = ['Fonbet', 'Marathonbet', 'Winline'];
const SINGLE_LIMIT = 5;
Expand Down Expand Up @@ -203,6 +204,12 @@ function fixtureModelKeys(fixture, models) {
if (euroCompetition && euroHome && euroAway) {
keys.add(`${euroCompetition.code}|${euroHome.key}|${euroAway.key}`);
}
const esCompetition = models.euroStats ? euroStatsApi.resolveCompetition(models.euroStats, fixture.league) : null;
const esHome = models.euroStats ? euroStatsApi.resolveTeam(models.euroStats, fixture.home) : null;
const esAway = models.euroStats ? euroStatsApi.resolveTeam(models.euroStats, fixture.away) : null;
if (esCompetition && esHome && esAway) {
keys.add(`eurostats|${esCompetition.code}|${esHome.key}|${esAway.key}`);
}
return [...keys];
}

Expand Down Expand Up @@ -485,13 +492,19 @@ function readJson(file) {
return JSON.parse(fs.readFileSync(file, 'utf8'));
}

function readJsonOptional(file) {
return fs.existsSync(file) ? readJson(file) : null;
}

function loadModels(projectRoot) {
return {
goals: readJson(path.join(projectRoot, 'data/goals_markets_models.json')),
cornersCards: readJson(path.join(projectRoot, 'data/corners_cards_models.json')),
stats: readJson(path.join(projectRoot, 'data/stats_markets_models.json')),
nations: readJson(path.join(projectRoot, 'data/nt_model.json')),
euro: readJson(path.join(projectRoot, 'data/euro_cups_model.json')),
// Появляется после первого переобучения с евро-статистикой.
euroStats: readJsonOptional(path.join(projectRoot, 'data/euro_stats_models.json')),
};
}

Expand Down
6 changes: 6 additions & 0 deletions scripts/lines/filter_model_fixtures.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ const corners = require('../../internal-model.js');
const stats = require('../../stats-internal-model.js');
const nt = require('../../nt-internal-model.js');
const euro = require('../../euro-internal-model.js');
const euroStats = require('../../euro-stats-internal-model.js');

function fixtureRows(payload) {
if (Array.isArray(payload)) return payload;
Expand All @@ -30,6 +31,7 @@ function coverage(fixture, models) {
['stats', stats, models.stats],
['nt', nt, models.nt],
['euro', euro, models.euro],
['euroStats', euroStats, models.euroStats],
]) {
if (model && api.predict(model, ...args)) return label;
}
Expand Down Expand Up @@ -81,6 +83,10 @@ function loadModels(projectRoot) {
stats: JSON.parse(fs.readFileSync(path.join(projectRoot, 'data/stats_markets_models.json'), 'utf8')),
nt: JSON.parse(fs.readFileSync(path.join(projectRoot, 'data/nt_model.json'), 'utf8')),
euro: JSON.parse(fs.readFileSync(path.join(projectRoot, 'data/euro_cups_model.json'), 'utf8')),
// Появляется после первого переобучения с евро-статистикой.
euroStats: fs.existsSync(path.join(projectRoot, 'data/euro_stats_models.json'))
? JSON.parse(fs.readFileSync(path.join(projectRoot, 'data/euro_stats_models.json'), 'utf8'))
: null,
};
}

Expand Down
Loading