Maximum value lost after restart (Template Sensor)

Dear Community, I would like to track the maximum value of my solar system and display it as a number. Unfortunately it does not work yet because on restart my already highest value disappears and it takes the current value again. After that it works again as expected and it updates the value only with the highest value. I have already read through some threads here in the forum and added the first line. Unfortunately without success. So how to solve the restart issue? Thank you so much in advance.

- sensor:
      - name: "SolarPeakMax"
        unit_of_measurement: "W"
        state_class: "total_increasing"
        state: >
          {% if states("sensor.grid_power") in ['unknown', 'unavailable', '0', '0.0'] %}
          {% set sensorOutput = states("sensor.SolarPeakMax") %}
          {% else %}
          {% set sensorGrid = states("sensor.grid_power") | int(0)%}
          {% set sensorSolarPeakMax = states("sensor.SolarPeakMax") | int(0)%}
          {% if sensorGrid > sensorSolarPeakMax %}
          {% set sensorOutput = sensorGrid %}
          {% else %}
          {% set sensorOutput = sensorSolarPeakMax %}
          {% endif %}
          {% endif %}
          {{ sensorOutput }}

This was a restart:

Is there a reason you aren’t using the statistics sensor?

Hi Tom, good question :wink: I tried it already but getting some strange values after some hours. How to set up the “value-max” for all measurements? I was not sure about “sampling_size” and “max_age” and how to use it - could you please help? I need the max of all the time.

  - platform: statistics
    name: "Test"
    entity_id: sensor.grid_power
    state_characteristic: value_max

Have you changed your recorder purge_keep_days from the default 10 days?

How often does sensor.grid_power update?

Hi, no, I didn’t change anything in the recorder because it will hit my whole system, right? The sensor updates every two seconds… That’s why I thought it will be the best to track it with a separate sensor.

Actually thinking about it, you cant have this

With the statistics sensor. You need a sample size or time limit.

Do you think I can go with a template sensor? My other idea was to create a helper input number and a automation to track and change the value…