Average max values of a sensor

I d like to store Max temp each day, for 7 days, but then take the average of that numbers.

Chat gpt told me that i should create 7 sensors, each will track max value of a specific day:

sensor:
  - platform: history_stats
    name: Max Value Day 1
    entity_id: sensor.your_sensor
    type: max
    duration: '24:00:00'
    end: "{{ now() - timedelta(days=0) }}"

  - platform: history_stats
    name: Max Value Day 2
    entity_id: sensor.your_sensor
    type: max
    duration: '24:00:00'
    end: "{{ now() - timedelta(days=1) }}"

  - platform: history_stats
    name: Max Value Day 3
    entity_id: sensor.your_sensor
    type: max
    duration: '24:00:00'
    end: "{{ now() - timedelta(days=2) }}"

  - platform: history_stats
    name: Max Value Day 4
    entity_id: sensor.your_sensor
    type: max
    duration: '24:00:00'
    end: "{{ now() - timedelta(days=3) }}"

  - platform: history_stats
    name: Max Value Day 5
    entity_id: sensor.your_sensor
    type: max
    duration: '24:00:00'
    end: "{{ now() - timedelta(days=4) }}"

  - platform: history_stats
    name: Max Value Day 6
    entity_id: sensor.your_sensor
    type: max
    duration: '24:00:00'
    end: "{{ now() - timedelta(days=5) }}"

  - platform: history_stats
    name: Max Value Day 7
    entity_id: sensor.your_sensor
    type: max
    duration: '24:00:00'
    end: "{{ now() - timedelta(days=6) }}"

And create a template sesnor that will do math:

sensor:
  - platform: template
    sensors:
      average_max_value:
        friendly_name: "Average of Last 7 Max Values"
        value_template: >
          {% set values = [
            states('sensor.max_value_day_1') | float,
            states('sensor.max_value_day_2') | float,
            states('sensor.max_value_day_3') | float,
            states('sensor.max_value_day_4') | float,
            states('sensor.max_value_day_5') | float,
            states('sensor.max_value_day_6') | float,
            states('sensor.max_value_day_7') | float
          ] %}
          {% set valid_values = values | select('is_number') | list %}
          {% if valid_values | length > 0 %}
            {{ (valid_values | sum / valid_values | length) | round(2) }}
          {% else %}
            0
          {% endif %}

Is any better approach?

Avoid bullshit engines. They are very bad at Home Assistant… often producing configurations with issues that are difficult for new users to recognize because they seem plausible.

The valid options for type can be found in the History Stats docs… “max” is not among them.


One way to achieve your goal is as follows:

  1. Combine the states of all your sensors to track the current max. That can be done with a Helper > Combine the state of several sensors or a state-based template sensor.

  2. Why does one trigger template sensor work, and the other not? - #4 by Didgeridrew