How to get spread between mean(top(n: X)) and mean(bottom(n: Y))?

I am calculating the daily spread in energy prices. I would like, at the end, to get a single table with multiple data columns, where the spread is calculated on pure top and bottom, then top(2) and bottom(2) values, up to 5.

Right now I came up with:

import "influxdata/influxdb/schema"

data = from(bucket: "home_assistant/autogen")
  |> range(start: v.timeRangeStart, stop: v.timeRangeStop)
  |> filter(fn: (r) => r["_measurement"] == "€/kWh")
  |> filter(fn: (r) => r["entity_id"] == "current_electricity_market_price")
  |> filter(fn: (r) => r["_field"] == "value")
  |> aggregateWindow(every: 1h, fn: mean, createEmpty: false)
  |> drop(columns: ["domain", "entity_id", "source", "friendly_name"])

spread_1h = data
|> aggregateWindow(every: 1d, fn: spread, createEmpty: false)
|> set(key: "aggType", value: "spread_1h")

spread_2h_top = data
  |> aggregateWindow(
      column: "_value",
      every: 1d,
      fn: (column, tables=<-) => tables |> top(n: 2) |> mean(),
  )

spread_2h_bottom = data
  |> aggregateWindow(
      column: "_value",
      every: 1d,
      fn: (column, tables=<-) => tables |> bottom(n: 2) |> mean(),
  )

spread_2h = union(tables: [spread_2h_top, spread_2h_bottom])
|> aggregateWindow(every: 1d, fn: spread, createEmpty: false)
|> set(key: "aggType", value: "spread_2h")

union(tables: [spread_1h, spread_2h])
|> drop(columns: ["_start", "_stop"])
|> pivot(rowKey: ["_time"], columnKey: ["aggType"], valueColumn: "_value")

so for 1h it’s easy, but for the 2h I first get mean(top(2)), mean(bottom(2)), then I “union” and calculate spread.

It’s seems more complex than it could be, but I’m very novice so I ask you if you could help me make it more compact and, possibly, efficient to run.

Thank you

Also, I used “preformatted text” for the code but I see no highlighting. How to enable it?