Compute daily return with flux

Hi all, I’m trying to build a Grafana dashboard for price data stored in InfluxDB and need a way to compute daily returns via flux. I’ve tried both derivative() and aggregate.rate() but they do not seem to perform what I need, namely x[i] / x[i-1] - 1. Any tip welcome.

Hello @gio,
Welcome!
I think this might do what you want:

original = from(bucket: "system")
  |> range(start: v.timeRangeStart, stop: v.timeRangeStop)
  |> filter(fn: (r) => r["_measurement"] == "cpu")
  |> filter(fn: (r) => r["_field"] == "usage_system")
  |> filter(fn: (r) => r["cpu"] == "cpu-total")
  |> limit(n: 3)
  |> yield(name: "original")

shifted = original 
  |> timeShift(duration: 10s, columns: ["_time"])

join(tables: {shifted: shifted, original: original}, on: ["_stop", "_start","_time", "_field", "_measurement", "cpu", "host"], method: "inner")
|> map(fn: (r) => ({ r with _value: r._value_shifted/r._value_original + 1.0 }))
|> yield(name:"joined")
1 Like

Fantastic, thank you @Anaisdg!
I wish there was a handbook or a repo of flux queries with more complex examples than the few I found around, flux looks so powerful. Thank you again.

Hello @gio,
No problem! Yes it is quite powerful. We’re testing a knowledge base internally, and if it goes well we hope to share it with the community soon.

1 Like