How to export today's energy cost to InfluxDB?

Maybe someone knows how to do this. I’m already exporting several other sensors to InfluxDB for longer term storage. I would also like to include energy cost as one of the data points being exported.

This InfluxDB query gives me an ever-increasing line showing total kWh consumed for all time:

from(bucket: "homeassistant")
  |> range(start: v.timeRangeStart, stop: v.timeRangeStop)
  |> filter(fn: (r) => r["_measurement"] == "kWh")
  |> filter(fn: (r) => r["_field"] == "value")
  |> aggregateWindow(every: v.windowPeriod, fn: mean, createEmpty: false)
  |> yield(name: "mean")

But what I want is to take the delta between the start and stop times, multiply that by the cost per kWh, and output the value. This number will ultimate go onto a Grafana dashboard along with other metrics.

I created this query, which I think is working. At least the numbers seem reasonable.

import "array"

costPerKwh = 0.199

data = from(bucket: "homeassistant")
  |> range(start: v.timeRangeStart, stop: v.timeRangeStop)
  |> filter(fn: (r) => r["_measurement"] == "kWh")
  |> filter(fn: (r) => r["_field"] == "value")
  |> filter(fn: (r) => r["friendly_name"] == "shellypro3em total active energy")

start = data |> first() |> findColumn(fn: (key) => true, column: "_value")

stop = data |> last() |> findColumn(fn: (key) => true, column: "_value")

totalKwh = stop[0] - start[0]

totalCost = totalKwh * costPerKwh

array.from(rows: [{cost: totalCost}]) |> yield(name: "cost")