-- Exchange fix, pass 2: best bettable price per exchange stream, minute by minute, for one kickoff day. -- Tokens: @S@ (nfl_cross | cfb_cross), @K@ (kick_day) -- Output: xtop/kick_day=@K@/ in the stage1 row shape (one row per run of an unchanged best price), so -- the crosses step reads it in place of the exchanges' stage1 rows and the other studies build on it. SET memory_limit='12GB'; SET threads=4; -- 1. Each offer / price level is live from its row until its next row (an update, or a delete = NULL eff). -- 4caster re-logs its whole book every 60 s, so an offer not re-logged within 90 s is gone. CREATE TEMP TABLE iv AS SELECT matchKey, market, book, contract, side, line, start_ms, home, away, eff, mx, ts // 60000 AS m0, (CASE WHEN book = '4caster' THEN least(coalesce(nxt, start_ms), ts + 90000) ELSE coalesce(nxt, start_ms) END - 1) // 60000 AS m1 FROM (SELECT *, lead(ts) OVER (PARTITION BY matchKey, market, book, contract, lvl, side, line ORDER BY ts) AS nxt FROM read_parquet('/home/stats/@S@/xraw/kick_day=@K@/*.parquet')) WHERE eff IS NOT NULL; -- 2. Best live price (and the stake behind it) in every minute any offer was live. CREATE TEMP TABLE top AS SELECT matchKey, market, book, contract, side, line, m, max(eff) AS eff, arg_max(mx, eff) AS mx, any_value(start_ms) start_ms, any_value(home) home, any_value(away) away FROM (SELECT *, unnest(range(m0, m1 + 1)) AS m FROM iv WHERE m1 >= m0) GROUP BY matchKey, market, book, contract, side, line, m; -- 3. Runs of an unchanged best price; a minute with nothing live ends the run with a NULL row. CREATE TEMP TABLE runs AS WITH g AS ( SELECT *, lag(eff) OVER w AS prev_eff, lag(m) OVER w AS prev_m FROM top WINDOW w AS (PARTITION BY matchKey, market, book, contract, side, line ORDER BY m)), c AS (SELECT *, CASE WHEN prev_m = m - 1 AND prev_eff = eff THEN 0 ELSE 1 END AS chg FROM g), r AS (SELECT *, sum(chg) OVER (PARTITION BY matchKey, market, book, contract, side, line ORDER BY m ROWS UNBOUNDED PRECEDING) AS run FROM c) SELECT matchKey, market, book, contract, side, line, run, min(m) m_first, max(m) m_last, any_value(eff) eff, arg_min(mx, m) mx, any_value(start_ms) start_ms, any_value(home) home, any_value(away) away FROM r GROUP BY matchKey, market, book, contract, side, line, run; COPY ( SELECT matchKey, market, book, contract, side, line, m_first * 60000 AS ts, m_last * 60000 AS ts_last, start_ms, home, away, eff, false AS del, mx, '@K@' AS kick_day FROM runs UNION ALL -- nothing live the minute after this run (and the next run doesn't start right away) SELECT matchKey, market, book, contract, side, line, (m_last + 1) * 60000, (m_last + 1) * 60000, start_ms, home, away, NULL, false, NULL, '@K@' FROM (SELECT *, lead(m_first) OVER (PARTITION BY matchKey, market, book, contract, side, line ORDER BY m_first) nxt FROM runs) WHERE coalesce(nxt, 9e18) > m_last + 1 AND (m_last + 1) * 60000 < start_ms ) TO '/home/stats/@S@/xtop/kick_day=@K@/xtop.parquet' (FORMAT parquet, COMPRESSION zstd);