Wave 2A: offseason data feeds — news wire + quota-disciplined futures

FREE ESPN news wire + championship-winner futures for the never-dark
offseason hub. Both graceful/empty, never fabricate a market value.

- newsService (mirrors injuryService): per-sport ESPN /news FEEDS, pure
  parseNews → { sport, items:[{id,headline,description,published,type,
  athlete?{name,key},team?,href}] }; athlete/team from categories[] only
  (absent when not present). Cache 15m, injectable, offline-tested.
- oddsNormalizer.normalizeOutrights: NEW branch — outrights outcomes are
  {name,price} with no point, so normalizeProps drops them; keeps them with
  best-price-across-allowed-books per selection. + americanToDecimal.
- oddsService.FUTURES_KEYS: separate map (mlb/nba/wnba championship winner),
  OUT of the daily SPORT_KEYS/snapshot budget.
- futuresService: getFutures(sport,deps) → { sport, updated_at, markets:
  [{key,title,selections:[{name,price,prevPrice?,move?}]}] }. One outrights
  call per 12h TTL (quota-disciplined), FUTURES_ENABLED gate. Price-move
  (shortening/drifting/flat) mirrors computeLineDeltas SHAPE on odds not
  line; prev prices persisted inside the futures:{sport} value (no new key).
  linkNewsToMoves pure causal-tie helper.
- Routes /api/news/:sport + /api/futures/:sport (registered) + Next proxies.
- Tests: newsService, futuresService, oddsNormalizerOutrights (fail→pass,
  no network). Full suite green.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Kev
2026-07-13 23:33:26 -04:00
parent a4b6255bed
commit f0752b804b
12 changed files with 920 additions and 1 deletions
+161
View File
@@ -0,0 +1,161 @@
'use strict';
const {
getFutures, priceMove, attachMoves, linkNewsToMoves,
} = require('../../src/services/futuresService');
const outrightEvents = [
{
id: 'evt-ws',
sport_key: 'baseball_mlb_world_series_winner',
sport_title: 'MLB World Series Winner',
bookmakers: [
{
key: 'draftkings',
markets: [{ key: 'outrights', outcomes: [
{ name: 'Los Angeles Dodgers', price: 300 },
{ name: 'New York Yankees', price: 500 },
] }],
},
],
},
];
describe('priceMove (pure)', () => {
test('shortening when payout drops (+400 → +300)', () => {
expect(priceMove(400, 300)).toBe('shortening');
});
test('drifting when payout rises (+300 → +450)', () => {
expect(priceMove(300, 450)).toBe('drifting');
});
test('flat within epsilon / unusable prices', () => {
expect(priceMove(300, 300)).toBe('flat');
expect(priceMove(null, 300)).toBe('flat');
expect(priceMove(300, null)).toBe('flat');
});
test('sign correct across the +/- american boundary', () => {
// +120 (dec 2.2) → -110 (dec 1.909): payout dropped → shortening
expect(priceMove(120, -110)).toBe('shortening');
// -110 → +120: payout rose → drifting
expect(priceMove(-110, 120)).toBe('drifting');
});
});
describe('attachMoves (pure)', () => {
const cur = [{ key: 'k', title: 'K', selections: [
{ name: 'A', price: 300 }, { name: 'B', price: 500 },
] }];
test('first fetch (no prev) → move:flat, no prevPrice', () => {
const out = attachMoves(cur, undefined);
expect(out[0].selections[0]).toEqual({ name: 'A', price: 300, move: 'flat' });
});
test('diffs against prev cached markets → prevPrice + move', () => {
const prev = [{ key: 'k', selections: [{ name: 'A', price: 400 }, { name: 'B', price: 500 }] }];
const out = attachMoves(cur, prev);
const a = out[0].selections.find((s) => s.name === 'A');
expect(a.prevPrice).toBe(400);
expect(a.move).toBe('shortening'); // 400 → 300
const b = out[0].selections.find((s) => s.name === 'B');
expect(b.prevPrice).toBe(500);
expect(b.move).toBe('flat'); // unchanged
});
});
describe('linkNewsToMoves (pure causal tie)', () => {
const news = [
{ headline: 'Dodgers acquire ace at deadline', published: '2026-07-30T12:00:00Z' },
{ headline: 'Unrelated older story', published: '2026-06-01T12:00:00Z' },
];
test('matches a move to the most-recent PRECEDING headline in window', () => {
const moves = [{ key: 'k', name: 'Los Angeles Dodgers', at: '2026-07-31T00:00:00Z' }];
const links = linkNewsToMoves(news, moves, 48);
expect(links).toEqual([{ moveKey: 'k|Los Angeles Dodgers', headline: 'Dodgers acquire ace at deadline' }]);
});
test('no headline within window → no cause (never invents)', () => {
const moves = [{ key: 'k', name: 'X', at: '2026-08-15T00:00:00Z' }];
expect(linkNewsToMoves(news, moves, 48)).toEqual([]);
});
test('headline AFTER the move is not a cause', () => {
const moves = [{ key: 'k', name: 'X', at: '2026-07-29T00:00:00Z' }];
expect(linkNewsToMoves(news, moves, 48)).toEqual([]);
});
});
describe('getFutures (injectable, offline)', () => {
const baseDeps = { apiKey: 'test', cacheGet: async () => null, cacheSet: async () => {} };
test('unknown sport → { markets: [] }, no fetch', async () => {
const axios = { get: jest.fn() };
const out = await getFutures('cricket', { ...baseDeps, axios });
expect(out.markets).toEqual([]);
expect(out.sport).toBe('cricket');
expect(axios.get).not.toHaveBeenCalled();
});
test('quota gate OFF (enabled:false) → { markets: [] }, no fetch', async () => {
const axios = { get: jest.fn() };
const out = await getFutures('mlb', { ...baseDeps, axios, enabled: false });
expect(out.markets).toEqual([]);
expect(axios.get).not.toHaveBeenCalled();
});
test('cold cache + enabled → fetches once, normalizes markets', async () => {
const axios = { get: jest.fn().mockResolvedValue({ data: outrightEvents, headers: {} }) };
const cacheSet = jest.fn(async () => {});
const out = await getFutures('mlb', { ...baseDeps, axios, enabled: true, ttl: 3600, cacheSet });
expect(axios.get).toHaveBeenCalledTimes(1);
// single outrights call
expect(axios.get.mock.calls[0][1].params.markets).toBe('outrights');
expect(out.markets).toHaveLength(1);
expect(out.markets[0].key).toBe('baseball_mlb_world_series_winner');
const dodgers = out.markets[0].selections.find((s) => s.name === 'Los Angeles Dodgers');
expect(dodgers.price).toBe(300);
expect(dodgers.move).toBe('flat'); // no prev
expect(cacheSet).toHaveBeenCalled();
});
test('price move shortening from a prev-price cache', async () => {
const prevCache = {
updated_at: '2000-01-01T00:00:00Z', // ancient → stale → refetch
markets: [{ key: 'baseball_mlb_world_series_winner', selections: [
{ name: 'Los Angeles Dodgers', price: 450 }, // was +450, now +300 → shortening
] }],
};
const axios = { get: jest.fn().mockResolvedValue({ data: outrightEvents, headers: {} }) };
const out = await getFutures('mlb', {
apiKey: 'test', axios, enabled: true, ttl: 3600,
cacheGet: async () => prevCache, cacheSet: async () => {},
});
const dodgers = out.markets[0].selections.find((s) => s.name === 'Los Angeles Dodgers');
expect(dodgers.prevPrice).toBe(450);
expect(dodgers.move).toBe('shortening');
});
test('fresh cache → served without fetching', async () => {
const fresh = {
updated_at: new Date().toISOString(),
markets: [{ key: 'baseball_mlb_world_series_winner', title: 'WS', selections: [{ name: 'A', price: 100 }] }],
};
const axios = { get: jest.fn() };
const out = await getFutures('mlb', {
apiKey: 'test', axios, enabled: true, ttl: 3600,
cacheGet: async () => fresh, cacheSet: async () => {},
});
expect(axios.get).not.toHaveBeenCalled();
expect(out.markets).toEqual(fresh.markets);
});
test('fetch failure → empty (never throws, never fabricates)', async () => {
const axios = { get: jest.fn().mockRejectedValue(new Error('boom')) };
const out = await getFutures('mlb', { ...baseDeps, axios, enabled: true, ttl: 3600 });
expect(out.markets).toEqual([]);
});
test('empty board with no prior cache → { markets: [] }', async () => {
const axios = { get: jest.fn().mockResolvedValue({ data: [], headers: {} }) };
const out = await getFutures('mlb', { ...baseDeps, axios, enabled: true, ttl: 3600 });
expect(out.markets).toEqual([]);
});
});
+107
View File
@@ -0,0 +1,107 @@
'use strict';
const { parseNews, getNews } = require('../../src/services/newsService');
const espnFixture = {
header: 'MLB News',
articles: [
{
id: 45735348,
type: 'Story',
headline: 'Aaron Judge homers twice in Yankees win',
description: 'The captain went deep in the seventh and ninth.',
published: '2026-07-14T03:08:19Z',
links: { web: { href: 'https://www.espn.com/mlb/story/_/id/45735348/judge' } },
categories: [
{ type: 'league', description: 'MLB', sportId: 10 },
{ type: 'athlete', description: 'Aaron Judge', athleteId: 33192, athlete: { id: 33192, description: 'Aaron Judge' } },
{ type: 'team', description: 'New York Yankees', teamId: 10, team: { id: 10, description: 'New York Yankees', abbreviation: 'NYY' } },
],
},
{
id: 45735111,
type: 'HeadlineNews',
headline: 'Commissioner addresses expansion timeline',
description: 'League office weighs in on the next two cities.',
published: '2026-07-13T20:00:00Z',
links: { web: { href: 'https://www.espn.com/mlb/story/_/id/45735111/expansion' } },
categories: [
{ type: 'league', description: 'MLB', sportId: 10 }, // NO athlete, NO team
],
},
],
};
describe('parseNews (pure)', () => {
test('maps ESPN articles → the contract items[]', () => {
const items = parseNews(espnFixture);
expect(items).toHaveLength(2);
const a = items[0];
expect(a.id).toBe('45735348');
expect(a.headline).toMatch(/Aaron Judge/);
expect(a.type).toBe('Story');
expect(a.published).toBe('2026-07-14T03:08:19Z');
expect(a.href).toBe('https://www.espn.com/mlb/story/_/id/45735348/judge');
});
test('extracts athlete + team from categories where present', () => {
const [a] = parseNews(espnFixture);
expect(a.athlete).toEqual({ name: 'Aaron Judge', key: expect.any(String) });
expect(a.athlete.key).toBe('aaron judge');
expect(a.team).toBe('New York Yankees');
});
test('missing athlete/team → fields ABSENT, never invented', () => {
const items = parseNews(espnFixture);
const noEntity = items.find((i) => i.headline.includes('expansion'));
expect(noEntity).toBeTruthy();
expect('athlete' in noEntity).toBe(false);
expect('team' in noEntity).toBe(false);
});
test('sorts newest first by published', () => {
const items = parseNews(espnFixture);
expect(items[0].published > items[1].published).toBe(true);
});
test('empty / malformed input → []', () => {
expect(parseNews({})).toEqual([]);
expect(parseNews(null)).toEqual([]);
expect(parseNews({ articles: 'nope' })).toEqual([]);
// Article with no headline is dropped.
expect(parseNews({ articles: [{ id: 1, description: 'x' }] })).toEqual([]);
});
});
describe('getNews (injectable, offline)', () => {
test('unknown sport → { sport, items: [] } without fetching', async () => {
const axios = { get: jest.fn() };
const out = await getNews('cricket', { axios, cacheGet: async () => null, cacheSet: async () => {} });
expect(out).toEqual({ sport: 'cricket', items: [] });
expect(axios.get).not.toHaveBeenCalled();
});
test('cache miss → fetches, parses, caches', async () => {
const axios = { get: jest.fn().mockResolvedValue({ data: espnFixture }) };
const cacheSet = jest.fn(async () => {});
const out = await getNews('mlb', { axios, cacheGet: async () => null, cacheSet });
expect(out.sport).toBe('mlb');
expect(out.items).toHaveLength(2);
expect(axios.get).toHaveBeenCalledTimes(1);
expect(cacheSet).toHaveBeenCalledWith('news:mlb', { items: expect.any(Array) }, expect.any(Number));
});
test('cache hit → serves cache, no fetch', async () => {
const axios = { get: jest.fn() };
const cached = { items: [{ id: '1', headline: 'cached', published: '2026-07-14T00:00:00Z', type: 'Story', href: null, description: '' }] };
const out = await getNews('mlb', { axios, cacheGet: async () => cached, cacheSet: async () => {} });
expect(out.items).toEqual(cached.items);
expect(axios.get).not.toHaveBeenCalled();
});
test('fetch failure → empty feed (never throws)', async () => {
const axios = { get: jest.fn().mockRejectedValue(new Error('network')) };
const out = await getNews('nba', { axios, cacheGet: async () => null, cacheSet: async () => {} });
expect(out).toEqual({ sport: 'nba', items: [] });
});
});
@@ -0,0 +1,91 @@
'use strict';
const { normalizeOutrights, normalizeProps, americanToDecimal } = require('../../src/utils/oddsNormalizer');
const outrightEvents = [
{
id: 'evt-ws',
sport_key: 'baseball_mlb_world_series_winner',
sport_title: 'MLB World Series Winner',
commence_time: '2026-10-20T00:00:00Z',
bookmakers: [
{
key: 'draftkings',
title: 'DraftKings',
markets: [
{
key: 'outrights',
outcomes: [
{ name: 'Los Angeles Dodgers', price: 350 },
{ name: 'New York Yankees', price: 450 },
],
},
],
},
{
key: 'fanduel',
title: 'FanDuel',
markets: [
{
key: 'outrights',
outcomes: [
{ name: 'Los Angeles Dodgers', price: 400 }, // better payout than DK's 350
{ name: 'New York Yankees', price: 420 },
],
},
],
},
{
key: 'bovada', // NOT allowed → skipped
markets: [{ key: 'outrights', outcomes: [{ name: 'Los Angeles Dodgers', price: 9999 }] }],
},
],
},
];
describe('normalizeOutrights', () => {
test('normalizes outright outcomes (name+price, no point) into markets', () => {
const markets = normalizeOutrights(outrightEvents);
expect(markets).toHaveLength(1);
const m = markets[0];
expect(m.key).toBe('baseball_mlb_world_series_winner');
expect(m.title).toBe('MLB World Series Winner');
expect(m.selections).toHaveLength(2);
});
test('picks the BEST (highest decimal payout) price per selection across allowed books', () => {
const [m] = normalizeOutrights(outrightEvents);
const dodgers = m.selections.find((s) => s.name === 'Los Angeles Dodgers');
// FanDuel +400 beats DraftKings +350; Bovada is not an allowed book.
expect(dodgers.price).toBe(400);
expect(dodgers.book).toBe('fanduel');
const yankees = m.selections.find((s) => s.name === 'New York Yankees');
// DraftKings +450 beats FanDuel +420.
expect(yankees.price).toBe(450);
expect(yankees.book).toBe('draftkings');
});
test('normalizeProps would DROP these outright outcomes (no point) — the reason a new branch exists', () => {
// Feed the SAME events through the player-prop normalizer: outrights have
// no `point` and no Over/Under, so normalizeProps yields nothing.
const props = normalizeProps(outrightEvents);
expect(props).toEqual([]);
// ...while normalizeOutrights keeps them.
expect(normalizeOutrights(outrightEvents)[0].selections.length).toBeGreaterThan(0);
});
test('never fabricates: empty / malformed input → empty array', () => {
expect(normalizeOutrights([])).toEqual([]);
expect(normalizeOutrights(null)).toEqual([]);
expect(normalizeOutrights([{ sport_key: 'x', bookmakers: [] }])).toEqual([]);
expect(normalizeOutrights([{ sport_key: 'x', bookmakers: [{ key: 'draftkings', markets: [{ key: 'outrights', outcomes: [{ name: 'A', price: null }] }] }] }])).toEqual([]);
});
test('americanToDecimal: +150→2.5, -200→1.5, junk→null', () => {
expect(americanToDecimal(150)).toBeCloseTo(2.5, 5);
expect(americanToDecimal(-200)).toBeCloseTo(1.5, 5);
expect(americanToDecimal(0)).toBeNull();
expect(americanToDecimal(null)).toBeNull();
expect(americanToDecimal('150')).toBeNull();
});
});