I have spent a lot of hours today to try to figure out how to calculate the average price of 3 consecutive hours from Nordpool energy prices.
I am looking to compare the average price of the 3 hours our boiler is expected to be heating the water to the current price if selling our overproduction of solar energy to the grid. The goal is to automatically turn on the boiler if the production exceeds the needed power consumption and the pay of current hour is lower than the average cost price of the 3 hours.
The sensor giving me the start-time looks like this and I would like to use this sensor to calculate the average price ( (price[sensor_start_time] + (price[sensor_start_time + 1] ) + (price[sensor_start_time + 2]) / 3 ):
sensor_vvb_cheapest_hours_start:
device_class: timestamp
friendly_name: Sensor - VVB Cheapest hours start
value_template: >
{% set numberOfSequentialHours = 3 %}
{% set lastHour = 5 %}
{% set firstHour = 20 %}
{% if state_attr('sensor.nordpool_kwh_se3_sek_1_10_025', 'tomorrow_valid') == true and state_attr('sensor.nordpool_kwh_se3_sek_1_10_025', 'tomorrow') [1] is number == true %}
{% set ns = namespace(counter=0, list=[], cheapestHour=today_at("00:00") + timedelta( hours = (24)), cheapestPrice=999.00) %}
{% for i in range(firstHour + numberOfSequentialHours, lastHour +25 ) %}
{% set ns.counter = 0.0 %}
{% for j in range(i-numberOfSequentialHours, i) %}
{% if j < 24 %}
{% set ns.counter = ns.counter + state_attr('sensor.nordpool_kwh_se3_sek_1_10_025', 'today')[j] %}
{% else %}
{% set ns.counter = ns.counter + state_attr('sensor.nordpool_kwh_se3_sek_1_10_025', 'tomorrow')[j-24] %}
{% endif %}
{% endfor %}
{% set ns.list = ns.list + [ns.counter] %}
{% if ns.counter < ns.cheapestPrice %}
{% set ns.cheapestPrice = ns.counter %}
{% set ns.cheapestHour=today_at("00:00") + timedelta( hours = (i - numberOfSequentialHours )) %}
{% endif %}
{% endfor %}
{{ ns.cheapestHour }}
{% set ns.cheapestPrice = (ns.cheapestPrice / numberOfSequentialHours) %}
{% else %}
{% set ns = namespace(counter=0, list=[], cheapestHour=today_at("00:00") + timedelta( hours = (24)), cheapestPrice=999.00) %}
{% for i in range(firstHour + numberOfSequentialHours, lastHour + 1) %}
{% set ns.counter = 0.0 %}
{% for j in range(i-numberOfSequentialHours, i) %}
{% set ns.counter = ns.counter + state_attr('sensor.nordpool_kwh_se3_sek_1_10_025', 'today')[j] %}
{% endfor %}
{% set ns.list = ns.list + [ns.counter] %}
{% if ns.counter < ns.cheapestPrice %}
{% set ns.cheapestPrice = ns.counter %}
{% set ns.cheapestHour = today_at("00:00") + timedelta( hours = (i - numberOfSequentialHours )) %}
{% endif %}
{% endfor %}
{{ ns.cheapestHour }}
{% set ns.cheapestPrice = (ns.cheapestPrice / numberOfSequentialHours) %}
{% endif %}