Nanuq dev log · 1 November 2026

Aged 19

A teenager's season, and 130 years of the records he chased.

Explainer · Nanuq 0.3 · built with Nanuq 0.6.1, Polars 2.1.0 and Nim 2.2.4 · rendered with nimib

The code this page talks about is folded under Source files, at the end.

This post was written before the code it shows. We drafted it while Nanuq 0.3 was still being designed, first in Python Polars and then in Nim against the planned API, and used it to decide that API. Now 0.3 is built and the page runs for real: each output below comes from Nanuq, and the page build compares it with the Python one.

Paul Seixas started the 2026 season as a 19-year-old in his second year as a pro. By October he had won the Tour of the Basque Country, the Flèche Wallonne and Il Lombardia, and finished fourth in his first Tour de France. This post follows his season, and 130 years of the records he chased, through what is new in Nanuq 0.3: dates, durations and time zones, string expressions, Parquet, categoricals, and a few conveniences such as glimpse, col.name and a block syntax for small tables.

The data comes from Wikipedia (CC BY-SA): winner lists, stage winners, the Tour start lists of all 113 editions, birth dates, race dates, the 2026 calendar and the Giro standings. Facts and quotes are from inrng, the best reading in pro cycling.

setTblRows(12); setTblCols(10); setTblWidthChars(120); setFmtStrLengths(60)

Four display setters on one line, separated by semicolons. setConfig(tblRows = 12, tblCols = 10, tblWidthChars = 120, fmtStrLengths = 60) does the same in one call, like Python's pl.Config(...), and withConfig (below) changes them for one block only.

The season in one table↑ contents

The 2026 World Tour calendar is small enough to paste into a post as a string. readCsv now takes a stream, so a string goes in through newStringStream, and tryParseDates turns the ISO dates into Date columns. glimpse shows each column on one line.

let season = readCsv(newStringStream(readFile("data/world_tour_2026.csv")),
                     tryParseDates = true)
echo season.glimpse
Rows: 36
Columns: 7
$ race     'Tour Down Under', 'Cadel Evans Great Ocean Road Race', 'UAE Tour', 'Omloop Het Nieuwsblad', 'Strade Bianche', 'Paris–Nice', 'Tirreno–Adriatico', 'Milan–San Remo', 'Volta a Catalunya', 'Tour of Bruges'
$ start   2026-01-20, 2026-02-01, 2026-02-16, 2026-02-28, 2026-03-07, 2026-03-08, 2026-03-09, 2026-03-21, 2026-03-23, 2026-03-25
$ end     2026-01-25, 2026-02-01, 2026-02-22, 2026-02-28, 2026-03-07, 2026-03-15, 2026-03-15, 2026-03-21, 2026-03-29, 2026-03-25
$ winner   'Jay Vine', 'Tobias Lund Andresen', 'Isaac del Toro', 'Mathieu van der Poel', 'Tadej Pogačar', 'Jonas Vingegaard', 'Isaac del Toro', 'Tadej Pogačar', 'Jonas Vingegaard', 'Dylan Groenewegen'
$ nat      'AUS', 'DEN', 'MEX', 'NED', 'SLO', 'DEN', 'MEX', 'SLO', 'DEN', 'NED'
$ second   'Mauro Schmid', 'Matthew Brennan', 'Antonio Tiberi', 'Tim van Dijke', 'Paul Seixas', 'Daniel Martínez', 'Matteo Jorgenson', 'Tom Pidcock', 'Lenny Martinez', 'Jasper Philipsen'
$ third    'Harry Sweeny', 'Brady Gilmore', 'Luke Plapp', 'Florian Vermeersch', 'Isaac del Toro', 'Georg Steinhauser', 'Giulio Pellizzari', 'Wout van Aert', 'Florian Lipowitz', 'Max Kanter'

glimpse shows the types but hides the shape of the season. Printing all 36 rows needs more than the 12-row default, so withConfig lifts the limit for one block only. The days column shows what one row can hide: a stage race is a single row, yet a week or three of racing, with a winner every day.

withConfig(tblRows = 40):
  echo season.select(col.race, col.start, col.winner,
                     ((col.end - col.start).dt.totalDays + 1).alias("days"))
shape: (36, 4)
┌───────────────────────────────────┬────────────┬──────────────────────┬──────┐
│ race                              ┆ start      ┆ winner               ┆ days │
│ ---                               ┆ ---        ┆ ---                  ┆ ---  │
│ str                               ┆ date       ┆ str                  ┆ i64  │
╞═══════════════════════════════════╪════════════╪══════════════════════╪══════╡
│ Tour Down Under                   ┆ 2026-01-20 ┆ Jay Vine             ┆ 6    │
│ Cadel Evans Great Ocean Road Race ┆ 2026-02-01 ┆ Tobias Lund Andresen ┆ 1    │
│ UAE Tour                          ┆ 2026-02-16 ┆ Isaac del Toro       ┆ 7    │
│ Omloop Het Nieuwsblad             ┆ 2026-02-28 ┆ Mathieu van der Poel ┆ 1    │
│ Strade Bianche                    ┆ 2026-03-07 ┆ Tadej Pogačar        ┆ 1    │
│ Paris–Nice                        ┆ 2026-03-08 ┆ Jonas Vingegaard     ┆ 8    │
│ Tirreno–Adriatico                 ┆ 2026-03-09 ┆ Isaac del Toro       ┆ 7    │
│ Milan–San Remo                    ┆ 2026-03-21 ┆ Tadej Pogačar        ┆ 1    │
│ Volta a Catalunya                 ┆ 2026-03-23 ┆ Jonas Vingegaard     ┆ 7    │
│ Tour of Bruges                    ┆ 2026-03-25 ┆ Dylan Groenewegen    ┆ 1    │
│ E3 Saxo Classic                   ┆ 2026-03-27 ┆ Mathieu van der Poel ┆ 1    │
│ Gent–Wevelgem                     ┆ 2026-03-29 ┆ Jasper Philipsen     ┆ 1    │
│ Dwars door Vlaanderen             ┆ 2026-04-01 ┆ Filippo Ganna        ┆ 1    │
│ Tour of Flanders                  ┆ 2026-04-05 ┆ Tadej Pogačar        ┆ 1    │
│ Tour of the Basque Country        ┆ 2026-04-06 ┆ Paul Seixas          ┆ 6    │
│ Paris–Roubaix                     ┆ 2026-04-12 ┆ Wout van Aert        ┆ 1    │
│ Amstel Gold Race                  ┆ 2026-04-19 ┆ Remco Evenepoel      ┆ 1    │
│ La Flèche Wallonne                ┆ 2026-04-22 ┆ Paul Seixas          ┆ 1    │
│ Liège–Bastogne–Liège              ┆ 2026-04-26 ┆ Tadej Pogačar        ┆ 1    │
│ Tour de Romandie                  ┆ 2026-04-28 ┆ Tadej Pogačar        ┆ 6    │
│ Eschborn–Frankfurt                ┆ 2026-05-01 ┆ Georg Zimmermann     ┆ 1    │
│ Giro d'Italia                     ┆ 2026-05-08 ┆ Jonas Vingegaard     ┆ 24   │
│ Tour Auvergne-Rhône-Alpes         ┆ 2026-06-07 ┆ Isaac del Toro       ┆ 8    │
│ Copenhagen Sprint                 ┆ 2026-06-14 ┆ Jasper Philipsen     ┆ 1    │
│ Tour de Suisse                    ┆ 2026-06-17 ┆ Tadej Pogačar        ┆ 5    │
│ Tour de France                    ┆ 2026-07-04 ┆ Tadej Pogačar        ┆ 23   │
│ Clásica de San Sebastián          ┆ 2026-08-01 ┆ Remco Evenepoel      ┆ 1    │
│ Tour de Pologne                   ┆ 2026-08-03 ┆ Marco Brenner        ┆ 7    │
│ Hamburg Cyclassics                ┆ 2026-08-16 ┆ Paul Magnier         ┆ 1    │
│ Renewi Tour                       ┆ 2026-08-19 ┆ Jasper Philipsen     ┆ 5    │
│ Vuelta a España                   ┆ 2026-08-22 ┆ Enric Mas            ┆ 23   │
│ Bretagne Classic                  ┆ 2026-08-30 ┆ Alex Aranburu        ┆ 1    │
│ Grand Prix Cycliste de Québec     ┆ 2026-09-11 ┆ Remco Evenepoel      ┆ 1    │
│ Grand Prix Cycliste de Montréal   ┆ 2026-09-13 ┆ Isaac del Toro       ┆ 1    │
│ Il Lombardia                      ┆ 2026-10-10 ┆ Paul Seixas          ┆ 1    │
│ Tour of Guangxi                   ┆ 2026-10-13 ┆ Jarno Widar          ┆ 6    │
└───────────────────────────────────┴────────────┴──────────────────────┴──────┘

Who won what↑ contents

In cycling a win is a win, and there are three kinds. A one-day race (Sanremo, Flanders, Lombardia) has one winner. A stage race has a winner every day, and an overall winner at the end: the leader of the General Classification (GC), the rider with the lowest total time, who often wins no stage at all. So a rider's season is counted in all three: one-day wins, stage wins and GC wins. Team time trials are won by a team, and one Vuelta stage was cancelled by a hailstorm, so those stages have no individual winner.

The stage winners come from each stage race's Wikipedia table. concat stacks the three kinds into one table of victories. The kind is a Nim enum, so the column is a Polars Enum, and a loop over the enum writes one count per kind.

type Kind = enum
  OneDay = "one-day", GC = "GC", Stage = "stage"

let stages = readCsv("data/stages_2026.csv", tryParseDates = true,
                     schemaOverrides = {"stage": String})
let raceKind = choose:
  if col.start == col.end: $OneDay
  else: $GC
let victories = concat([
  season.select(col.winner, col.race.str.replaceAll("–", "-"), raceKind.alias("kind")),
  stages.filter(col.winner.isNotNull)
    .select(col.winner, (col.race.str.replaceAll("–", "-") + " stage " + col.stage).alias("race"),
            lit($Stage).alias("kind")),
]).withColumns(col.kind.cast(Kind))

var perKind: seq[Expr]
for k in Kind:
  perKind.add (col.kind == $k).sum.alias($k)
withConfig(fmtStrLengths = 40):
  echo victories.groupBy(col.winner)
    .agg(@[col.race.count.alias("wins")] & perKind &
         @[col.race.filter(col.kind != $Stage).str.join(", ").alias("races")])
    .filter(col.wins >= 6)
    .sort(["wins", "GC", "winner"], descending = [true, true, false])
shape: (10, 6)
┌──────────────────────┬──────┬─────────┬─────┬───────┬───────────────────────────────────────────┐
│ winner               ┆ wins ┆ one-day ┆ GC  ┆ stage ┆ races                                     │
│ ---                  ┆ ---  ┆ ---     ┆ --- ┆ ---   ┆ ---                                       │
│ str                  ┆ u32  ┆ u32     ┆ u32 ┆ u32   ┆ str                                       │
╞══════════════════════╪══════╪═════════╪═════╪═══════╪═══════════════════════════════════════════╡
│ Tadej Pogačar        ┆ 22   ┆ 4       ┆ 3   ┆ 15    ┆ Strade Bianche, Milan-San Remo, Tour of … │
│ Jonas Vingegaard     ┆ 12   ┆ 0       ┆ 3   ┆ 9     ┆ Paris-Nice, Volta a Catalunya, Giro d'It… │
│ Isaac del Toro       ┆ 10   ┆ 1       ┆ 3   ┆ 6     ┆ UAE Tour, Tirreno-Adriatico, Tour Auverg… │
│ Jonathan Milan       ┆ 9    ┆ 0       ┆ 0   ┆ 9     ┆                                           │
│ Jasper Philipsen     ┆ 7    ┆ 2       ┆ 1   ┆ 4     ┆ Gent-Wevelgem, Copenhagen Sprint, Renewi… │
│ Paul Seixas          ┆ 6    ┆ 2       ┆ 1   ┆ 3     ┆ Tour of the Basque Country, La Flèche Wa… │
│ Mathieu van der Poel ┆ 6    ┆ 2       ┆ 0   ┆ 4     ┆ Omloop Het Nieuwsblad, E3 Saxo Classic    │
│ Matthew Brennan      ┆ 6    ┆ 0       ┆ 0   ┆ 6     ┆                                           │
│ Paul Magnier         ┆ 6    ┆ 1       ┆ 0   ┆ 5     ┆ Hamburg Cyclassics                        │
│ Remco Evenepoel      ┆ 6    ┆ 3       ┆ 0   ┆ 3     ┆ Amstel Gold Race, Clásica de San Sebasti… │
└──────────────────────┴──────┴─────────┴─────┴───────┴───────────────────────────────────────────┘

Pogačar won 22 times: four one-day races, three GCs (Romandie, Suisse, the Tour) and 15 stages. A Tour stage and a stage of the Renewi Tour count the same here, which is why sites like ProCyclingStats also weigh wins with points. Two other profiles stand out. Jonathan Milan won nine stages and nothing else, a sprinter's season. Seixas has an all-rounder's mix in his second pro year: two one-day races (Flèche Wallonne and Lombardia), the Basque Country GC and three of its six stages, the same six wins as Van der Poel and Evenepoel.

Every Monument winner since 1892↑ contents

Five one-day races are called the Monuments: Milano-Sanremo, the Ronde van Vlaanderen, Paris-Roubaix, Liège-Bastogne-Liège and Il Lombardia. They have had 580 winners, and with race dates and birth dates attached that is a table worth keeping in a typed, compressed file. Parquet is new in 0.3, both writing and scanning lazily.

let monuments = readCsv("data/monuments.csv", tryParseDates = true)
  .join(readCsv("data/riders.csv", tryParseDates = true), on = ["wiki"], how = Left)
monuments.writeParquet("monuments.parquet", compression = Zstd)

let lazy = scanParquet("monuments.parquet")
echo lazy.select(col.race.count.alias("rows"),
                 col.year.min.alias("first"), col.year.max.alias("last"),
                 col.date.nullCount.alias("no_date"),
                 col.born.nullCount.alias("no_birth_date")).collect
shape: (1, 5)
┌──────┬───────┬──────┬─────────┬───────────────┐
│ rows ┆ first ┆ last ┆ no_date ┆ no_birth_date │
│ ---  ┆ ---   ┆ ---  ┆ ---     ┆ ---           │
│ u32  ┆ i64   ┆ i64  ┆ u32     ┆ u32           │
╞══════╪═══════╪══════╪═════════╪═══════════════╡
│ 580  ┆ 1892  ┆ 2026 ┆ 15      ┆ 2             │
└──────┴───────┴──────┴─────────┴───────────────┘

Fifteen editions have no date on Wikipedia, and two winners have no birth date. They stay null, and every age below ignores them.

The race column is a small fixed set, which is what a Nim enum is for. Casting to one makes a Polars Enum column whose categories are the enum's strings, in declaration order. Sorting follows the season, Sanremo in March to Lombardia in October, not the alphabet.

type Monument = enum
  MSR = "Milano-Sanremo"
  RVV = "Ronde van Vlaanderen"
  PR = "Paris-Roubaix"
  LBL = "Liège-Bastogne-Liège"
  IL = "Il Lombardia"

let races = lazy.withColumns(col.race.cast(Monument)).collect
echo races.filter(col.year == 2026).sort("race").select(col("race", "date", "winner", "nat"))
shape: (5, 4)
┌──────────────────────┬────────────┬───────────────┬─────┐
│ race                 ┆ date       ┆ winner        ┆ nat │
│ ---                  ┆ ---        ┆ ---           ┆ --- │
│ enum                 ┆ date       ┆ str           ┆ str │
╞══════════════════════╪════════════╪═══════════════╪═════╡
│ Milano-Sanremo       ┆ 2026-03-21 ┆ Tadej Pogačar ┆ SLO │
│ Ronde van Vlaanderen ┆ 2026-04-05 ┆ Tadej Pogačar ┆ SLO │
│ Paris-Roubaix        ┆ 2026-04-12 ┆ Wout van Aert ┆ BEL │
│ Liège-Bastogne-Liège ┆ 2026-04-26 ┆ Tadej Pogačar ┆ SLO │
│ Il Lombardia         ┆ 2026-10-10 ┆ Paul Seixas   ┆ FRA │
└──────────────────────┴────────────┴───────────────┴─────┘

The honour roll, as Wikipedia prints it: one column per Monument, first and latest win, and a rank that shares places on ties. There is no pivot. Each Monument column is a conditional sum, and a Nim loop over the enum writes the five expressions, naming each column after the enum symbol. rank(Min) gives tied riders the same place.

var perRace: seq[Expr]
for m in Monument:
  perRace.add (col.race == $m).sum.alias(symbolName(m))
let roll = races.groupBy(col.winner)
  .agg(@[col.nat.first, col.year.min.alias("first"), col.year.max.alias("latest")] &
       perRace & @[col.race.count.alias("total")])
  .withColumns(col.total.rank(Min, descending = true).alias("rank"))
  .sort(["total", "first"], descending = [true, false])
withConfig(tblCols = 12):
  echo roll.select(col.rank, all().exclude("rank")).head(12)
shape: (12, 11)
┌──────┬──────────────────────┬─────┬───────┬────────┬─────┬─────┬─────┬─────┬─────┬───────┐
│ rank ┆ winner               ┆ nat ┆ first ┆ latest ┆ MSR ┆ RVV ┆ PR  ┆ LBL ┆ IL  ┆ total │
│ ---  ┆ ---                  ┆ --- ┆ ---   ┆ ---    ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ ---   │
│ u32  ┆ str                  ┆ str ┆ i64   ┆ i64    ┆ u32 ┆ u32 ┆ u32 ┆ u32 ┆ u32 ┆ u32   │
╞══════╪══════════════════════╪═════╪═══════╪════════╪═════╪═════╪═════╪═════╪═════╪═══════╡
│ 1    ┆ Eddy Merckx          ┆ BEL ┆ 1966  ┆ 1976   ┆ 7   ┆ 2   ┆ 3   ┆ 5   ┆ 2   ┆ 19    │
│ 2    ┆ Tadej Pogačar        ┆ SLO ┆ 2021  ┆ 2026   ┆ 1   ┆ 3   ┆ 0   ┆ 4   ┆ 5   ┆ 13    │
│ 3    ┆ Roger De Vlaeminck   ┆ BEL ┆ 1970  ┆ 1979   ┆ 3   ┆ 1   ┆ 4   ┆ 1   ┆ 2   ┆ 11    │
│ 4    ┆ Costante Girardengo  ┆ ITA ┆ 1918  ┆ 1928   ┆ 6   ┆ 0   ┆ 0   ┆ 0   ┆ 3   ┆ 9     │
│ 4    ┆ Fausto Coppi         ┆ ITA ┆ 1946  ┆ 1954   ┆ 3   ┆ 0   ┆ 1   ┆ 0   ┆ 5   ┆ 9     │
│ 4    ┆ Sean Kelly           ┆ IRL ┆ 1983  ┆ 1992   ┆ 2   ┆ 0   ┆ 2   ┆ 2   ┆ 3   ┆ 9     │
│ 7    ┆ Rik Van Looy         ┆ BEL ┆ 1958  ┆ 1965   ┆ 1   ┆ 2   ┆ 3   ┆ 1   ┆ 1   ┆ 8     │
│ 7    ┆ Mathieu van der Poel ┆ NLD ┆ 2020  ┆ 2025   ┆ 2   ┆ 3   ┆ 3   ┆ 0   ┆ 0   ┆ 8     │
│ 9    ┆ Gino Bartali         ┆ ITA ┆ 1936  ┆ 1950   ┆ 4   ┆ 0   ┆ 0   ┆ 0   ┆ 3   ┆ 7     │
│ 9    ┆ Tom Boonen           ┆ BEL ┆ 2005  ┆ 2012   ┆ 0   ┆ 3   ┆ 4   ┆ 0   ┆ 0   ┆ 7     │
│ 9    ┆ Fabian Cancellara    ┆ SUI ┆ 2006  ┆ 2014   ┆ 1   ┆ 3   ┆ 3   ┆ 0   ┆ 0   ┆ 7     │
│ 12   ┆ Henri Pélissier      ┆ FRA ┆ 1911  ┆ 1921   ┆ 1   ┆ 0   ┆ 2   ┆ 0   ┆ 3   ┆ 6     │
└──────┴──────────────────────┴─────┴───────┴────────┴─────┴─────┴─────┴─────┴─────┴───────┘

Gerbi or Seixas?↑ contents

inrng, after Lombardia: "Seixas becomes the youngest ever winner of Lombardia, pipping Giovanni Gerbi who was also 20 when he won the inaugural edition in 1905." Both were 20, so years can't separate them. Subtracting two Date columns gives a Duration, and totalDays settles it.

let age = (col.date - col.born).alias("age")
echo races.filter(col.winner.isIn(["Giovanni Gerbi", "Paul Seixas"]))
  .select(col.year, col.winner, col.born, col.date, age, age.dt.totalDays.alias("days"))
shape: (2, 6)
┌──────┬────────────────┬────────────┬────────────┬──────────────┬──────┐
│ year ┆ winner         ┆ born       ┆ date       ┆ age          ┆ days │
│ ---  ┆ ---            ┆ ---        ┆ ---        ┆ ---          ┆ ---  │
│ i64  ┆ str            ┆ date       ┆ date       ┆ duration[μs] ┆ i64  │
╞══════╪════════════════╪════════════╪════════════╪══════════════╪══════╡
│ 1905 ┆ Giovanni Gerbi ┆ 1885-05-20 ┆ 1905-11-12 ┆ 7480d        ┆ 7480 │
│ 2026 ┆ Paul Seixas    ┆ 2006-09-24 ┆ 2026-10-10 ┆ 7321d        ┆ 7321 │
└──────┴────────────────┴────────────┴────────────┴──────────────┴──────┘

159 days younger.

The youngest, everywhere↑ contents

The youngest winner of each Monument is a window: keep the rows whose age equals the smallest age in their race. Then the youngest winners of all.

let withAge = races.withColumns(age.dt.totalDays.alias("days")).dropNulls("days")
echo withAge.filter(col.days == col.days.min.over("race"))
  .sort("race").select(col("race", "year", "winner", "days"))
echo withAge.sort("days").head(5).select(col("race", "year", "winner", "days"))
shape: (5, 4)
┌──────────────────────┬──────┬─────────────────────┬──────┐
│ race                 ┆ year ┆ winner              ┆ days │
│ ---                  ┆ ---  ┆ ---                 ┆ ---  │
│ enum                 ┆ i64  ┆ str                 ┆ i64  │
╞══════════════════════╪══════╪═════════════════════╪══════╡
│ Milano-Sanremo       ┆ 1914 ┆ Ugo Agostoni        ┆ 7556 │
│ Ronde van Vlaanderen ┆ 1944 ┆ Rik Van Steenbergen ┆ 7145 │
│ Paris-Roubaix        ┆ 1899 ┆ Albert Champion     ┆ 7667 │
│ Liège-Bastogne-Liège ┆ 1909 ┆ Victor Fastre       ┆ 6936 │
│ Il Lombardia         ┆ 2026 ┆ Paul Seixas         ┆ 7321 │
└──────────────────────┴──────┴─────────────────────┴──────┘
shape: (5, 4)
┌──────────────────────┬──────┬─────────────────────┬──────┐
│ race                 ┆ year ┆ winner              ┆ days │
│ ---                  ┆ ---  ┆ ---                 ┆ ---  │
│ enum                 ┆ i64  ┆ str                 ┆ i64  │
╞══════════════════════╪══════╪═════════════════════╪══════╡
│ Liège-Bastogne-Liège ┆ 1909 ┆ Victor Fastre       ┆ 6936 │
│ Liège-Bastogne-Liège ┆ 1925 ┆ Georges Ronsse      ┆ 7042 │
│ Ronde van Vlaanderen ┆ 1944 ┆ Rik Van Steenbergen ┆ 7145 │
│ Il Lombardia         ┆ 2026 ┆ Paul Seixas         ┆ 7321 │
│ Liège-Bastogne-Liège ┆ 1927 ┆ Maurice Raes        ┆ 7388 │
└──────────────────────┴──────┴─────────────────────┴──────┘

Only three Monument winners were ever younger than Seixas, and the most recent of them won in 1944.

Teenagers at the Tour↑ contents

inrng's Tour preview: Seixas is "the youngest rider to start the Tour de France since 1937". To check that, we need every starter, not only the winners. Wikipedia has a start list for each of the 113 editions: 16,438 starters, with a birth date for 94% of them (almost all since 1930; the early Tours are patchy). Join each starter with the first day of the race, subtract, and sort.

let starters = readCsv("data/starters/starters.csv", tryParseDates = true,
                       schemaOverrides = {"no": String})
let editions = readCsv("data/starters/editions.csv", tryParseDates = true)
let ages = starters.filter(col.dns == 0)
  .join(editions.select(col.year, col.start_date), on = ["year"])
  .withColumns((col.start_date - col.born).dt.totalDays.alias("age"))
echo ages.filter(col.year >= 1930).sort("age", nullsLast = true)
  .select(col("year", "name", "born", "age")).head(5)
shape: (5, 4)
┌──────┬──────────────────┬────────────┬──────┐
│ year ┆ name             ┆ born       ┆ age  │
│ ---  ┆ ---              ┆ ---        ┆ ---  │
│ i64  ┆ str              ┆ date       ┆ i64  │
╞══════╪══════════════════╪════════════╪══════╡
│ 1931 ┆ Fabio Battesini  ┆ 1912-02-19 ┆ 7071 │
│ 2026 ┆ Paul Seixas      ┆ 2006-09-24 ┆ 7223 │
│ 1932 ┆ Georg Umbenhauer ┆ 1912-09-20 ┆ 7229 │
│ 2013 ┆ Danny van Poppel ┆ 1993-07-26 ┆ 7278 │
│ 1931 ┆ Jean Fontenay    ┆ 1911-07-23 ┆ 7282 │
└──────┴──────────────────┴────────────┴──────┘

The start lists say since 1931, not 1937: Fabio Battesini rode the 1931 Tour at 7,071 days old, 152 days younger than Seixas. Then the nulls speak. Before 1940, a few starters per edition have no birth date on Wikipedia, and one of them may be the rider inrng had in mind.

echo ages.filter(col.year.isBetween(1931, 1939))
  .groupBy(col.year).agg(col.name.count.alias("starters"),
                         col.born.nullCount.alias("no_birth_date"))
  .sort("year")
shape: (9, 3)
┌──────┬──────────┬───────────────┐
│ year ┆ starters ┆ no_birth_date │
│ ---  ┆ ---      ┆ ---           │
│ i64  ┆ u32      ┆ u32           │
╞══════╪══════════╪═══════════════╡
│ 1931 ┆ 81       ┆ 4             │
│ 1932 ┆ 80       ┆ 1             │
│ 1933 ┆ 80       ┆ 0             │
│ 1934 ┆ 60       ┆ 0             │
│ 1935 ┆ 93       ┆ 1             │
│ 1936 ┆ 90       ┆ 4             │
│ 1937 ┆ 97       ┆ 1             │
│ 1938 ┆ 96       ┆ 3             │
│ 1939 ┆ 80       ┆ 0             │
└──────┴──────────┴───────────────┘

Before 1930 teenagers were common: 43 starters under 20, the youngest Camille Fily in 1904 at 17 years and 50 days. Since then there have been six, and Seixas is the youngest of them. He finished fourth.

Faster than ever↑ contents

Wikipedia lists every Tour's distance and winning time as text, such as 73h 56′ 26″. str.extract pulls out the numbers, the new duration expression builds a Duration, and the average speed follows. Two lessons from real data come with it. CSV inference reads the first rows, guesses integers for the distance and then fails on 3660.5, so the column gets a schema override. And some Tours have no time at all. 1905 to 1912 were decided on points, and 1999 to 2005 have no winner since Armstrong's results were struck out.

var tours = readCsv("data/tour_winners.csv", schemaOverrides = {"distance_km": Float64})

proc raceTime(c: string): Expr =
  proc part(unit: string): Expr =
    col(c).str.extract(r"(\d+)" & unit, 1).cast(int64).fillNull(0)
  choose:
    if col(c).isNotNull: duration(hours = part("h"), minutes = part("′"), seconds = part("″"))

tours = tours
  .withColumns(raceTime("time").alias("time"), raceTime("margin").alias("margin"))
  .withColumns((col.distance_km / (col.time.dt.totalSeconds / 3600)).round(3).alias("speed"))
echo tours.sort("speed", descending = true, nullsLast = true).head(5)
  .select(col("year", "winner", "distance_km", "time", "speed"))
shape: (5, 5)
┌──────┬──────────────────┬─────────────┬────────────────┬────────┐
│ year ┆ winner           ┆ distance_km ┆ time           ┆ speed  │
│ ---  ┆ ---              ┆ ---         ┆ ---            ┆ ---    │
│ i64  ┆ str              ┆ f64         ┆ duration[μs]   ┆ f64    │
╞══════╪══════════════════╪═════════════╪════════════════╪════════╡
│ 2026 ┆ Tadej Pogačar    ┆ 3245.0      ┆ 3d 1h 56m 26s  ┆ 43.887 │
│ 2025 ┆ Tadej Pogačar    ┆ 3320.0      ┆ 3d 4h 32s      ┆ 43.679 │
│ 2022 ┆ Jonas Vingegaard ┆ 3328.0      ┆ 3d 7h 32m 29s  ┆ 41.84  │
│ 2024 ┆ Tadej Pogačar    ┆ 3498.0      ┆ 3d 11h 38m 56s ┆ 41.818 │
│ 1998 ┆ Marco Pantani    ┆ 3875.0      ┆ 3d 20h 49m 46s ┆ 41.743 │
└──────┴──────────────────┴─────────────┴────────────────┴────────┘

totalSeconds is an integer column, and since 0.3 / is a true division, as in Nim and Python Polars: totalSeconds / 3600 gives fractional hours. Before 0.3 it truncated the way Rust Polars does; div is there when whole hours are what you want.

43.887 km/h is a record, but inrng's Tour review gives the record as 43.227 km/h. At 43.227 km/h, 73h 56′ 26″ covers 3,196 km, not the 3,245 km Wikipedia lists. Race reports confirm it: the riders covered 3,197 km (the route was planned at 3,333 km), so the table's distance is wrong, not the clock.

echo tours.filter(col.year == 2026)
  .select((lit(43.227) * col.time.dt.totalSeconds / 3600).round(1).alias("km_at_43.227"))
shape: (1, 1)
┌──────────────┐
│ km_at_43.227 │
│ ---          │
│ f64          │
╞══════════════╡
│ 3196.2       │
└──────────────┘

4′ 23″↑ contents

Polars prints 73h 56′ 26″ as 3d 1h 56m 26s. Cycling writes time its own way, so the post builds a formatter from expressions: integer division with div and mod, and format to put the pieces together. Vingegaard won Paris-Nice by 4′ 23″, the fourth largest margin ever (the three wider ones were all in the 1930s). Tour margins get much smaller.

proc gap(c: string): Expr =
  let s = col(c).dt.totalSeconds
  proc two(e: Expr): Expr = e.cast(string).str.zfill(2)
  choose:
    if s >= 3600: format("{}h {}′ {}″", s div 3600, two(s mod 3600 div 60), two(s mod 60))
    else: format("{}′ {}″", s div 60, two(s mod 60))

echo tours.dropNulls("margin").sort("margin").head(5)
  .select(col.year, col.winner, gap("margin").alias("margin"), gap("time").alias("time"))
let parisNice = newDataFrame:
  paris_nice: [initDuration(minutes = 4, seconds = 23)]
echo parisNice.select(gap("paris_nice"))
shape: (5, 4)
┌──────┬──────────────────┬────────┬──────────────┐
│ year ┆ winner           ┆ margin ┆ time         │
│ ---  ┆ ---              ┆ ---    ┆ ---          │
│ i64  ┆ str              ┆ str    ┆ str          │
╞══════╪══════════════════╪════════╪══════════════╡
│ 1989 ┆ Greg LeMond      ┆ 0′ 08″ ┆ 87h 38′ 35″  │
│ 2007 ┆ Alberto Contador ┆ 0′ 23″ ┆ 91h 00′ 26″  │
│ 2006 ┆ Óscar Pereiro    ┆ 0′ 32″ ┆ 89h 40′ 27″  │
│ 1968 ┆ Jan Janssen      ┆ 0′ 38″ ┆ 133h 49′ 42″ │
│ 1987 ┆ Stephen Roche    ┆ 0′ 40″ ┆ 115h 27′ 42″ │
└──────┴──────────────────┴────────┴──────────────┘
shape: (1, 1)
┌────────────┐
│ paris_nice │
│ ---        │
│ str        │
╞════════════╡
│ 4′ 23″     │
└────────────┘

The same band every night↑ contents

The Giro's general classification after every stage. The leader's row holds a total time and everyone else's holds a gap (+ 5' 22"), so the gap is built with choose. Vingegaard took the pink jersey on stage 14 and kept it. Behind him the band took a while to settle: Eulálio first, then Gall, with Arensman third until Hindley took the place on stage 19.

let gapToLeader = choose:
  if col.rank == 1: duration(seconds = 0)
  else: duration(minutes = col.time.str.extract(r"(\d+)'", 1).cast(int64).fillNull(0),
                 seconds = col.time.str.extract("(\\d+)\"", 1).cast(int64).fillNull(0))
let giro = readCsv("data/giro_gc_2026.csv")
  .withColumns(col.date.str.toDate("%d %B %Y"), gapToLeader.alias("gap"))

echo giro.filter(col.rank <= 3).sort(["stage", "rank"])
  .groupBy(col.stage, col.date).agg(col.rider.str.join(" / ").alias("podium"))
  .sort("stage").tail(10)
echo giro.filter(col.rider.isIn(["Felix Gall", "Jai Hindley"]) and col.stage >= 12)
  .groupBy(col.rider)
  .agg(col.rank.min.alias("best"), col.rank.max.alias("worst"),
       gap("gap").last.alias("final_gap"))
  .sort("rider")
shape: (10, 3)
┌───────┬────────────┬─────────────────────────────────────────────────────┐
│ stage ┆ date       ┆ podium                                              │
│ ---   ┆ ---        ┆ ---                                                 │
│ i64   ┆ date       ┆ str                                                 │
╞═══════╪════════════╪═════════════════════════════════════════════════════╡
│ 12    ┆ 2026-05-21 ┆ Afonso Eulálio / Jonas Vingegaard / Thymen Arensman │
│ 13    ┆ 2026-05-22 ┆ Afonso Eulálio / Jonas Vingegaard / Thymen Arensman │
│ 14    ┆ 2026-05-23 ┆ Jonas Vingegaard / Afonso Eulálio / Felix Gall      │
│ 15    ┆ 2026-05-24 ┆ Jonas Vingegaard / Afonso Eulálio / Felix Gall      │
│ 16    ┆ 2026-05-26 ┆ Jonas Vingegaard / Felix Gall / Thymen Arensman     │
│ 17    ┆ 2026-05-27 ┆ Jonas Vingegaard / Felix Gall / Thymen Arensman     │
│ 18    ┆ 2026-05-28 ┆ Jonas Vingegaard / Felix Gall / Thymen Arensman     │
│ 19    ┆ 2026-05-29 ┆ Jonas Vingegaard / Felix Gall / Jai Hindley         │
│ 20    ┆ 2026-05-30 ┆ Jonas Vingegaard / Felix Gall / Jai Hindley         │
│ 21    ┆ 2026-05-31 ┆ Jonas Vingegaard / Felix Gall / Jai Hindley         │
└───────┴────────────┴─────────────────────────────────────────────────────┘
shape: (2, 4)
┌─────────────┬──────┬───────┬───────────┐
│ rider       ┆ best ┆ worst ┆ final_gap │
│ ---         ┆ ---  ┆ ---   ┆ ---       │
│ str         ┆ i64  ┆ i64   ┆ str       │
╞═════════════╪══════╪═══════╪═══════════╡
│ Felix Gall  ┆ 2    ┆ 4     ┆ 5′ 22″    │
│ Jai Hindley ┆ 3    ┆ 6     ┆ 6′ 25″    │
└─────────────┴──────┴───────┴───────────┘

Set your alarm↑ contents

The season starts in Adelaide. inrng's preview lists each stage's finish in local time, CET and US Eastern, and points out that stage 1 is due at 2.03pm, not 2pm. With tryParseDates, "14:03" becomes a time of day (TimeOfDay in Nim). dt.combine joins it to the date, replaceTimeZone says it is Adelaide time, and convertTimeZone checks inrng's arithmetic.

let tdu = readCsv(newStringStream("""stage,date,finish,inrng_cet,inrng_est
Prologue,2026-01-20,20:30,11:00,05:00
1,2026-01-21,14:03,16:33,22:32
2,2026-01-22,15:02,05:32,23:32
4,2026-01-24,13:22,03:52,21:52
"""), tryParseDates = true)

let finish = col.date.dt.combine(col.finish).dt.replaceTimeZone("Australia/Adelaide")
let cet = finish.dt.convertTimeZone("Europe/Paris")
let est = finish.dt.convertTimeZone("America/New_York")
echo tdu.select(col.stage, cet.alias("cet"), (cet.dt.time == col.inrng_cet).alias("cet_ok"),
                est.alias("est"), (est.dt.time == col.inrng_est).alias("est_ok"))
shape: (4, 5)
┌──────────┬────────────────────────────┬────────┬────────────────────────────────┬────────┐
│ stage    ┆ cet                        ┆ cet_ok ┆ est                            ┆ est_ok │
│ ---      ┆ ---                        ┆ ---    ┆ ---                            ┆ ---    │
│ str      ┆ datetime[μs, Europe/Paris] ┆ bool   ┆ datetime[μs, America/New_York] ┆ bool   │
╞══════════╪════════════════════════════╪════════╪════════════════════════════════╪════════╡
│ Prologue ┆ 2026-01-20 11:00:00 CET    ┆ true   ┆ 2026-01-20 05:00:00 EST        ┆ true   │
│ 1        ┆ 2026-01-21 04:33:00 CET    ┆ false  ┆ 2026-01-20 22:33:00 EST        ┆ false  │
│ 2        ┆ 2026-01-22 05:32:00 CET    ┆ true   ┆ 2026-01-21 23:32:00 EST        ┆ true   │
│ 4        ┆ 2026-01-24 03:52:00 CET    ┆ true   ┆ 2026-01-23 21:52:00 EST        ┆ true   │
└──────────┴────────────────────────────┴────────┴────────────────────────────────┴────────┘

Stage 1's CET time should read 4.33am, not 4.33pm, and its US time is a minute off. The prologue and the other stages check out.

The smudged result sheet↑ contents

Not every source writes dates the same way. A strict parse stops at the first odd row and raises a specific error type, which the post catches. A lenient parse turns the odd row into null.

let smudged = newDataFrame:
  race: ["Paris-Roubaix", "Amstel Gold Race", "La Flèche Wallonne"]
  date: ["12 April 2026", "19 April 2026", "22/04/2026"]
try:
  discard smudged.withColumns(col.date.str.toDate("%d %B %Y"))
except InvalidOperationError as e:
  echo "InvalidOperationError - ", e.msg.splitLines[0]
echo smudged.withColumns(col.date.str.toDate("%d %B %Y", strict = false))
InvalidOperationError - conversion from `str` to `date` failed in column 'date' for 1 out of 3 values: ["22/04/2026"]
shape: (3, 2)
┌────────────────────┬────────────┐
│ race               ┆ date       │
│ ---                ┆ ---        │
│ str                ┆ date       │
╞════════════════════╪════════════╡
│ Paris-Roubaix      ┆ 2026-04-12 │
│ Amstel Gold Race   ┆ 2026-04-19 │
│ La Flèche Wallonne ┆ null       │
└────────────────────┴────────────┘

Finale: one season, one strip↑ contents

inrng counted "only 49 days of racing" for Seixas this year, across World Tour and smaller races. These tables can't recount that: they list winners, not start lists. What they can show is the World Tour around him. dateRange gives one row per day of 2026, and a cross join keeps the days that fall between a race's start and end: the racing days of the calendar, month by month. Next to them, the days each rider won something: a one-day race or a stage.

let year2026 = newDataFrame().select(
  dateRange(date(2026, 1, 1), date(2026, 12, 31), 1.days).alias("day"))
let days = year2026.join(season, how = Cross).filter(col.day.isBetween(col.start, col.end))
let won = concat([
  season.filter(col.start == col.end).select(col.winner, col.start.alias("day")),
  stages.select(col.winner, col.date.alias("day")),
])
echo days.groupBy(col.day.dt.month.alias("month")).agg(col.day.count.alias("race_days"))
  .join(won.groupBy(col.day.dt.month.alias("month")).agg(
          (col.winner == "Paul Seixas").sum.alias("seixas_wins"),
          (col.winner == "Tadej Pogačar").sum.alias("pogacar_wins")),
        on = ["month"], how = Left)
  .sort("month")
echo days.select(col.day.count.alias("world_tour_race_days"),
                 col.day.nUnique.alias("calendar_days"))
shape: (10, 4)
┌───────┬───────────┬─────────────┬──────────────┐
│ month ┆ race_days ┆ seixas_wins ┆ pogacar_wins │
│ ---   ┆ ---       ┆ ---         ┆ ---          │
│ i8    ┆ u32       ┆ u32         ┆ u32          │
╞═══════╪═══════════╪═════════════╪══════════════╡
│ 1     ┆ 6         ┆ 0           ┆ 0            │
│ 2     ┆ 9         ┆ 0           ┆ 0            │
│ 3     ┆ 27        ┆ 0           ┆ 2            │
│ 4     ┆ 15        ┆ 4           ┆ 4            │
│ 5     ┆ 28        ┆ 0           ┆ 2            │
│ 6     ┆ 14        ┆ 0           ┆ 3            │
│ 7     ┆ 23        ┆ 0           ┆ 5            │
│ 8     ┆ 25        ┆ 0           ┆ 3            │
│ 9     ┆ 15        ┆ 0           ┆ 0            │
│ 10    ┆ 7         ┆ 1           ┆ 0            │
└───────┴───────────┴─────────────┴──────────────┘
shape: (1, 2)
┌──────────────────────┬───────────────┐
│ world_tour_race_days ┆ calendar_days │
│ ---                  ┆ ---           │
│ u32                  ┆ u32           │
╞══════════════════════╪═══════════════╡
│ 169                  ┆ 152           │
└──────────────────────┴───────────────┘

Pogačar won the Tour, three Monuments and 15 stages, with wins in six straight months, March to August. Seixas won a Monument at 20 years and 16 days, and finished fourth in his first Tour at 19. inrng closes its Lombardia review with the question everyone is asking: is the goal now to dethrone Pogačar? Next season's data will tell.

What this post used from Nanuq 0.3↑ contents

The Python twin of this post, which recorded the outputs it is checked against, is blog/aged19/aged19.py. How these APIs were chosen is in Designing Nanuq 0.3.

Source files↑ contents

Every source file this page mentions, folded: tap one to read it. A file's name in the text leads here.

docs/blog/aged19/aged19.py 370 lines
# %% [markdown]
# # Aged 19
#
# *The Python Polars version (py-polars 2.1) of the Nanuq 0.3 explainer
# (docs/blog/aged_19.nim). It was written first, to design the 0.3 API; each code cell
# matches one Nim block, and expected.py saves its outputs, which the Nim post must print.*
#
# Paul Seixas started the 2026 season as a 19-year-old in his second pro year. By
# October he had won the Tour of the Basque Country, the Flèche Wallonne and Il
# Lombardia, and finished fourth in the Tour de France. This post walks through his
# season, and through 130 years of the records he chased, with Nanuq 0.3's new tools:
# dates and durations, time zones, string expressions, Parquet and categoricals.
#
# Data: Wikipedia (CC BY-SA) for winner lists, stage winners, the Tour start lists of all
# 113 editions, birth dates, race dates, the 2026 calendar and the Giro standings; facts
# and quotes from [inrng](https://inrng.com).

# %%
# id: setup
import datetime as dt
import io

import polars as pl

pl.Config(tbl_rows=12, tbl_cols=10, tbl_width_chars=120, fmt_str_lengths=60);

# %% [markdown]
# ## 1. The season in one table
#
# The 2026 World Tour calendar fits in a CSV small enough to paste into a post. Nanuq
# 0.3 reads CSV from a string through a stream, and `tryParseDates` turns the ISO dates
# into real `Date` columns. `glimpse` shows every column on one line.

# %%
# id: s01_glimpse
season_csv = open("data/world_tour_2026.csv").read()
season = pl.read_csv(io.StringIO(season_csv), try_parse_dates=True)
print(season.glimpse(return_type="string"))

# %% [markdown]
# `glimpse` shows the types but hides the shape of the season. Printing all 36 rows
# needs more than the 12-row default, so the table is printed inside a config block that
# lifts the limit for one print only. The `days` column shows what one row can hide: a
# stage race is a single row, yet a week or three of racing, with a winner every day.

# %%
# id: s01_calendar
with pl.Config(tbl_rows=40):
    print(season.select("race", "start", "winner",
                        days=(pl.col("end") - pl.col("start")).dt.total_days() + 1))

# %% [markdown]
# ## 2. Who won what
#
# In cycling a win is a win, and there are three kinds. A one-day race (Sanremo,
# Flanders, Lombardia) has one winner. A stage race has a winner every day, and an
# overall winner at the end: the leader of the General Classification (GC), the rider
# with the lowest total time, who often wins no stage at all. So a rider's season is
# counted in all three: one-day wins, stage wins and GC wins. Team time trials are won by a team, and one Vuelta stage was
# cancelled by a hailstorm, so those stages have no individual winner.
#
# The stage winners come from each stage race's Wikipedia table. `concat` stacks the
# three kinds into one table of victories, with the kind as a small `Enum` column.

# %%
# id: s02_wins
Kind = pl.Enum(["one-day", "GC", "stage"])
stages = pl.read_csv("data/stages_2026.csv", try_parse_dates=True,
                     schema_overrides={"stage": pl.String})
victories = pl.concat([
    season.select("winner", race=pl.col("race").str.replace_all("–", "-"),
                  kind=pl.when(pl.col("start") == pl.col("end"))
                         .then(pl.lit("one-day")).otherwise(pl.lit("GC"))),
    stages.filter(pl.col("winner").is_not_null())
          .select("winner", race=pl.col("race").str.replace_all("–", "-") + " stage "
                  + pl.col("stage"), kind=pl.lit("stage")),
]).with_columns(pl.col("kind").cast(Kind))
with pl.Config(fmt_str_lengths=40):
  print(victories.group_by("winner")
      .agg(pl.len().alias("wins"),
           *[(pl.col("kind") == k).sum().alias(k) for k in Kind.categories],
           pl.col("race").filter(pl.col("kind") != "stage").str.join(", ").alias("races"))
      .filter(pl.col("wins") >= 6)
      .sort("wins", "GC", "winner", descending=[True, True, False]))

# %% [markdown]
# Pogačar won 22 times: four one-day races, three GCs (Romandie, Suisse,
# the Tour) and 15 stages. A Tour stage and a stage of the Renewi Tour count the same
# here, which is why sites like ProCyclingStats also weigh wins with points. Two other
# profiles stand out. Jonathan Milan won nine stages and nothing else, a sprinter's
# season. Seixas has an all-rounder's mix in his second pro year: two one-day races (Flèche Wallonne and
# Lombardia), the Basque Country GC and three of its six stages, the same six wins
# as Van der Poel and Evenepoel.

# %% [markdown]
#
# ## 3. Every Monument winner since 1892
#
# Five one-day races are called the Monuments. Their winners, 580 of them, with race
# dates and birth dates, are a good fit for Parquet: typed, compressed, read back
# lazily. Writing and scanning are new in 0.3.

# %%
# id: s03_parquet
monuments = pl.read_csv("data/monuments.csv", try_parse_dates=True).join(
    pl.read_csv("data/riders.csv", try_parse_dates=True), on="wiki", how="left"
)
monuments.write_parquet("monuments.parquet", compression="zstd")
lazy = pl.scan_parquet("monuments.parquet")
print(lazy.select(pl.len().alias("rows"), pl.col("year").min().alias("first"), pl.col("year").max().alias("last"),
                  pl.col("date").null_count().alias("no_date"),
                  pl.col("born").null_count().alias("no_birth_date")).collect())

# %% [markdown]
# Races are a fixed set, so they become a categorical. An `Enum` keeps the season's
# order, Sanremo in March to Lombardia in October, which sorting will respect. In Nim
# this is a plain `enum Monument`.

# %%
# id: s03_enum
Monument = pl.Enum(["Milano-Sanremo", "Ronde van Vlaanderen", "Paris-Roubaix",
                    "Liège-Bastogne-Liège", "Il Lombardia"])
races = lazy.with_columns(pl.col("race").cast(Monument)).collect()
print(races.filter(pl.col("year") == 2026).sort("race").select("race", "date", "winner", "nat"))

# %% [markdown]
# The honour roll, as Wikipedia prints it: one column per Monument, first and latest
# win, and a rank that shares places on ties. There is no pivot here: each Monument
# column is a conditional sum, one expression per race, built in a loop over the
# categories. `rank("min")` gives tied riders the same place.

# %%
# id: s03_roll
short = {"Milano-Sanremo": "MSR", "Ronde van Vlaanderen": "RVV", "Paris-Roubaix": "PR",
         "Liège-Bastogne-Liège": "LBL", "Il Lombardia": "IL"}
roll = (races.group_by("winner")
        .agg(pl.col("nat").first(), pl.col("year").min().alias("first"),
             pl.col("year").max().alias("latest"),
             *[(pl.col("race") == m).sum().alias(short[m]) for m in Monument.categories],
             pl.len().alias("total"))
        .with_columns(pl.col("total").rank("min", descending=True).alias("rank"))
        .sort("total", "first", descending=[True, False]))
with pl.Config(tbl_cols=12):
    print(roll.select("rank", pl.exclude("rank")).head(12))

# %% [markdown]
# ## 4. Gerbi or Seixas?
#
# [inrng](https://inrng.com/2026/10/lombardia-2026-review/): "Seixas becomes the youngest ever winner of Lombardia, pipping Giovanni Gerbi
# who was also 20 when he won the inaugural edition in 1905." Both were 20. Subtracting
# two dates gives a `Duration`, and `totalDays` settles it.

# %%
# id: s04_gerbi
age = (pl.col("date") - pl.col("born")).alias("age")
print(races.filter(pl.col("winner").is_in(["Giovanni Gerbi", "Paul Seixas"]))
      .select("year", "winner", "born", "date", age, age.dt.total_days().alias("days")))

# %% [markdown]
# ## 5. The youngest, everywhere
#
# The youngest winner of each Monument, using a window over the race. Seixas is the
# youngest winner of any Monument since Rik Van Steenbergen in 1944.

# %%
# id: s05_youngest
with_age = races.with_columns(days=age.dt.total_days()).drop_nulls("days")
print(with_age.filter(pl.col("days") == pl.col("days").min().over("race"))
      .sort("race").select("race", "year", "winner", "days"))
print(with_age.sort("days").head(5).select("race", "year", "winner", "days"))

# %% [markdown]
# ## 6. Teenagers at the Tour
#
# [inrng's Tour preview](https://inrng.com/2026/07/tour-de-france-preview-2026/): Seixas is "the youngest rider to start the Tour de France since 1937". To check
# that, we need every starter, not only the winners. Wikipedia has a start list for each
# of the 113 editions: 16,438 starters, with a birth date for 94% of them (almost all
# since 1930; the early Tours are patchy). Join each starter with the first day of the
# race, subtract, and sort.

# %%
# id: s06_tour
starters = pl.read_csv("data/starters/starters.csv", try_parse_dates=True,
                       schema_overrides={"no": pl.String})
editions = pl.read_csv("data/starters/editions.csv", try_parse_dates=True)
ages = (starters.filter(pl.col("dns") == 0)
        .join(editions.select("year", "start_date"), on="year")
        .with_columns(age=(pl.col("start_date") - pl.col("born")).dt.total_days()))
print(ages.filter(pl.col("year") >= 1930).sort("age", nulls_last=True)
      .select("year", "name", "born", "age").head(5))

# %% [markdown]
# The start lists say since 1931, not 1937: Fabio Battesini rode the 1931 Tour at
# 7,071 days old, 152 days younger than Seixas. Then the nulls speak. Before 1940, a few
# starters per edition have no birth date on Wikipedia, and one of them may be the
# rider inrng had in mind.

# %%
# id: s06_nulls
print(ages.filter(pl.col("year").is_between(1931, 1939))
      .group_by("year").agg(pl.len().alias("starters"),
                            pl.col("born").null_count().alias("no_birth_date"))
      .sort("year"))

# %% [markdown]
# Before 1930 teenagers were common: 43 starters under 20, the youngest Camille Fily in
# 1904 at 17 years and 50 days. Since then there have been six, and Seixas is the
# youngest of them. He finished fourth.

# %% [markdown]
# ## 7. Faster than ever
#
# Wikipedia lists every Tour's distance and winning time as text, like `73h 56′ 26″`.
# String expressions pull the numbers out, a `duration` expression builds the time, and
# the average speed follows. Two surprises on the way: CSV inference guesses integers
# for the distance until it meets `3660.5`, and the early Tours have no time at all
# (they were decided on points), nor do 1999-2005, whose winner was stripped.

# %%
# id: s07_speed
tours = pl.read_csv("data/tour_winners.csv", schema_overrides={"distance_km": pl.Float64})

def race_time(c):
    part = lambda unit: pl.col(c).str.extract(r"(\d+)" + unit, 1).cast(pl.Int64).fill_null(0)
    return pl.when(pl.col(c).is_not_null()).then(
        pl.duration(hours=part("h"), minutes=part("′"), seconds=part("″")))

tours = tours.with_columns(time=race_time("time"), margin=race_time("margin")).with_columns(
    speed=(pl.col("distance_km") / (pl.col("time").dt.total_seconds() / 3600)).round(3))
print(tours.sort("speed", descending=True, nulls_last=True).head(5)
      .select("year", "winner", "distance_km", "time", "speed"))

# %% [markdown]
# 43.887 km/h is a record, but [inrng's Tour review](https://inrng.com/2026/07/tour-de-france-2026-review/) says the record is 43.227 km/h. At 43.227 km/h,
# 73h 56′ 26″ covers 3,196 km, not the 3,245 km Wikipedia lists. Race reports confirm it:
# the riders covered 3,197 km (the route was planned at 3,333 km), so the table's distance
# is wrong, not the clock.

# %%
# id: s07_check
print(tours.filter(pl.col("year") == 2026).select(
    (pl.lit(43.227) * pl.col("time").dt.total_seconds() / 3600).round(1).alias("km_at_43.227")))

# %% [markdown]
# ## 8. 4′ 23″
#
# Polars prints 73h 56′ 26″ as `3d 1h 56m 26s`. Cycling writes time gaps its own way, so
# here is a formatter built from expressions. Vingegaard won Paris-Nice by 4′ 23″, the
# fourth largest margin ever (the three wider ones were all in the 1930s). Tour margins
# can be much smaller.

# %%
# id: s08_gaps
def gap(c):
    s = pl.col(c).dt.total_seconds()
    two = lambda e: e.cast(pl.String).str.zfill(2)
    hms = pl.format("{}h {}′ {}″", s // 3600, two(s % 3600 // 60), two(s % 60))
    ms = pl.format("{}′ {}″", s // 60, two(s % 60))
    return pl.when(s >= 3600).then(hms).otherwise(ms)

print(tours.drop_nulls("margin").sort("margin").head(5)
      .select("year", "winner", gap("margin").alias("margin"), gap("time").alias("time")))
print(pl.select(paris_nice=pl.duration(minutes=4, seconds=23)).select(gap("paris_nice")))

# %% [markdown]
# ## 9. The same band every night
#
# The Giro's general classification after every stage, from Wikipedia. The leader's line
# holds a total time, everyone else's a gap (`+ 5' 22"`). Vingegaard took pink on stage
# 14 and kept it; behind him the band took a while to settle: Eulálio, then Gall, with
# Arensman and finally Hindley third. Gall's final gap: 5′ 22″.

# %%
# id: s09_giro
giro = pl.read_csv("data/giro_gc_2026.csv")
giro = giro.with_columns(
    date=pl.col("date").str.to_date("%d %B %Y"),
    gap=pl.when(pl.col("rank") == 1).then(pl.duration(seconds=0)).otherwise(
        pl.duration(minutes=pl.col("time").str.extract(r"(\d+)'", 1).cast(pl.Int64).fill_null(0),
                    seconds=pl.col("time").str.extract(r"(\d+)\"", 1).cast(pl.Int64).fill_null(0))),
)
podium = (giro.filter(pl.col("rank") <= 3).sort("stage", "rank")
          .group_by("stage", "date").agg(pl.col("rider").str.join(" / ").alias("podium"))
          .sort("stage"))
print(podium.tail(10))
print(giro.filter(pl.col("rider").is_in(["Felix Gall", "Jai Hindley"]), pl.col("stage") >= 12)
      .group_by("rider").agg(pl.col("rank").min().alias("best"), pl.col("rank").max().alias("worst"),
                             gap("gap").last().alias("final_gap")).sort("rider"))

# %% [markdown]
# ## 10. Set your alarm
#
# The season starts in Adelaide. [inrng's preview](https://inrng.com/2026/01/2026-tour-down-under-preview/) gives each stage's finish time in local
# time, CET and US Eastern, and admits that stage 1 is scheduled for 2.03pm, not 2pm.
# With `tryParseDates`, "14:03" becomes a time of day; combining it with the date and an
# IANA zone gives a real instant, and converting zones checks inrng's arithmetic.

# %%
# id: s10_alarm
tdu = pl.read_csv(io.StringIO("""stage,date,finish,inrng_cet,inrng_est
Prologue,2026-01-20,20:30,11:00,05:00
1,2026-01-21,14:03,16:33,22:32
2,2026-01-22,15:02,05:32,23:32
4,2026-01-24,13:22,03:52,21:52
"""), try_parse_dates=True)
finish = pl.col("date").dt.combine(pl.col("finish")).dt.replace_time_zone("Australia/Adelaide")
print(tdu.select(
    "stage",
    finish.dt.convert_time_zone("Europe/Paris").alias("cet"),
    (finish.dt.convert_time_zone("Europe/Paris").dt.time() == pl.col("inrng_cet")).alias("cet_ok"),
    finish.dt.convert_time_zone("America/New_York").alias("est"),
    (finish.dt.convert_time_zone("America/New_York").dt.time() == pl.col("inrng_est")).alias("est_ok"),
))

# %% [markdown]
# Stage 1's CET time is a typo for 4.33am, and its US time is a minute off. Prologue and
# the other stages check out.
#
# ## 11. The smudged result sheet
#
# Not every source writes dates the same way. A strict parse stops at the first odd
# row with a specific error, which the post catches; a lenient one turns it into null.

# %%
# id: s11_smudged
smudged = pl.DataFrame({"race": ["Paris-Roubaix", "Amstel Gold Race", "La Flèche Wallonne"],
                        "date": ["12 April 2026", "19 April 2026", "22/04/2026"]})
try:
    smudged.with_columns(pl.col("date").str.to_date("%d %B %Y"))
except pl.exceptions.InvalidOperationError as e:
    print(type(e).__name__, "-", str(e).splitlines()[0])
print(smudged.with_columns(pl.col("date").str.to_date("%d %B %Y", strict=False)))

# %% [markdown]
# *(Nim note: Polars raises `InvalidOperationError` here, not `ComputeError` as the API
# doc guessed. The error type is whatever Polars says; the post shows the real one.)*
#
# ## 12. Finale: one season, one strip
#
# [inrng](https://inrng.com/2026/10/lombardia-2026-review/) counted "only 49 days of racing" for Seixas this year, across World Tour and
# smaller races. Our tables can't recount that: they list winners, not start lists. What
# they can show is the World Tour around him. A `dateRange` gives one row per day of 2026,
# and a cross join keeps the days that fall between a race's start and end: the racing
# days of the calendar, month by month. Next to them, the days each rider won something:
# a one-day race or a stage.

# %%
# id: s12_strip
year = pl.select(day=pl.date_range(dt.date(2026, 1, 1), dt.date(2026, 12, 31), "1d"))
days = year.join(season, how="cross").filter(pl.col("day").is_between("start", "end"))
won = pl.concat([
    season.filter(pl.col("start") == pl.col("end")).select("winner", day="start"),
    stages.select("winner", day="date"),
])
per_month = (
    days.group_by(pl.col("day").dt.month().alias("month")).agg(pl.len().alias("race_days"))
    .join(won.group_by(pl.col("day").dt.month().alias("month")).agg(
              (pl.col("winner") == "Paul Seixas").sum().alias("seixas_wins"),
              (pl.col("winner") == "Tadej Pogačar").sum().alias("pogacar_wins")),
          on="month", how="left")
    .sort("month"))
print(per_month)
print(days.select(pl.len().alias("world_tour_race_days"), pl.col("day").n_unique().alias("calendar_days")))

# %% [markdown]
# Pogačar won the Tour, three Monuments and 15 stages, with wins in six straight months,
# March to August. Seixas won one Monument at 20
# years and 16 days, and finished fourth in his first Tour at 19. [inrng](https://inrng.com/2026/10/lombardia-2026-review/) ends its
# Lombardia review on the question everyone is asking: is the goal now to dethrone
# Pogačar? Next season's data will tell.

docs/blog/aged19/aged19.py

docs/blog/aged19/expected.py 18 lines
"""Runs aged19.py cell by cell and writes each code cell's stdout to expected/<id>.txt.

docs/blog/aged_19.nim compares each of its blocks with these files, and rendering the
post fails when an output differs.
Run from this folder: python3 -I expected.py"""
import contextlib, io, os, re
os.chdir(os.path.dirname(os.path.abspath(__file__)))
os.makedirs("expected", exist_ok=True)
src = open("aged19.py").read()
ns = {}
for cell in src.split("\n# %%")[1:]:
    if cell.startswith(" [markdown]"): continue
    m = re.match(r"\n# id: (\S+)", cell)
    buf = io.StringIO()
    with contextlib.redirect_stdout(buf):
        exec(compile(cell, m.group(1), "exec"), ns)
    open(f"expected/{m.group(1)}.txt", "w").write(buf.getvalue().rstrip("\n") + "\n")
    print(m.group(1), len(buf.getvalue().splitlines()), "lines")

docs/blog/aged19/expected.py