I would also like this feature built in to Home Assistant.
Copying some notes here in case this helps anyone.
I tried a few different approaches but kept running into the issue that recorder only keeps 10 days of data by default (recommended), and long-term statistics aren’t accessible for other sensors or templating.
E.g. I was hoping this statistics sensor would work (you could combine with a template sensor that divides this value by 365 for a moving average daily cost, but I decided I liked a moving total instead):
- platform: statistics
name: Total energy cost yearly
entity_id: sensor.total_energy_cost
state_characteristic: change
max_age:
days: 365
But not only did recorder limit the data but there’s an issue with statistics resetting to 0 and requiring reloading which felt hacky and still prone to error.
For short duration moving total/averages this works well.
If you just want to show a moving total in your dashboard, you can use the statistics card. But this can’t be graphed or used in template sensors:
type: statistic
entity: sensor.total_energy_cost
period:
rolling_window:
duration:
days: 365
stat_type: change
Another potential option I was looking at was using a daily utility_meter, and creating a template sensor that calculates its state based on the utility meter’s last_period attribute. Was looking to be a bit messy implementing deque or similar in a template AND ensuring the values persisted across restarts etc.
Cutting to the chase, I’ve found a stable solution that didn’t end up being that hard:
- Install the InfluxDB add-on and configure to record the sensors of interest for an appropriate time period (i.e. 1 year in this case).
- Add an InfluxDB sensor:
- platform: influxdb
host: a0d7b954-influxdb
username: home-assistant
password: !secret influx_password
queries:
- name: Total energy cost yearly
value_template: "{{ (states('sensor.total_energy_cost')|float - value|float)|round(2) }}"
where: '"entity_id" = ''total_energy_cost'' AND time >= now() - 365d'
group_function: first
measurement: '"$"'
unit_of_measurement: $/year
Again, you could just divide by 365 in the above value_template to get a daily moving average instead of total.
Here’s a screenshot of the resulting dashboard I set up (note that some of the sensors have only been available recently so the long-term values aren’t correct until that time has passed):
This is obviously way more work than should be required for something so simple as a long-term moving average sensor. I think building this into Home Assistant in general would be great, not just for the energy dashboard. Until then, if anyone finds a simpler method than the above then please share!