Getting last n values of a sensor to create a weighted mean sensor

I switch on (or not) a accumulating heater with a scheduler based on the last 24-hour mean of a temperature sensor.

The problem of that approach is that it has high inertia. For instance, in a cold day after a sunny day, the mean is still high even the actual temperature is not.

I’m thinking of making a weighted mean, where weights decrease with time passed. So, the weight of the last temperature sample would be 1, and decreases linearly until the weight of the -24h sample, which would be 0.

I think this is not implemented in Home Assistant (correct me if I’m wrong please). I’ve been looking at the statistics sensor and there’s no “weighted mean”.

My question is whether there is a simple way to get last n samples of a sensor, or the only way is maintaining a sliding buffer triggered by temperature sensor changes.

Thank you.

The HACS integration Variables+History allows you to save a value in a variable and earlier values as attributes of the variable.

1 Like

I’ll look at it.

Thank you!

I’m thinking that if weights followed a geometric series (with ratio -a- less than 1), it’s enough to store the cummulative weighted sum and when a new term arrives, sum it to the previous cummulative sum multiplied by the ratio.

In that case, the sum of the weights is the sum of a geometric series (1/(1-a)) if it has infinite length or (1-a^(N+1))/(1-a) if it has finite length.

With this approach I don’t have to store all the previous values within a period, and with the ratio parameter, a, I can adjust the inertia of the weigthed thermostat.

I will implement this in the Statistics integration.

@miguelpucela raised the idea in this ticket, for whoever wants to join the discussion: Problem with statistics sensors in core-2021.12.0 · Issue #61624 · home-assistant/core · GitHub

2 Likes

Great news!

Thanks!