I came across this incredibly simple sensor, ‘billigaste_energi_hushallsmaskiner’ designed to run the washing machine at the absolute lowest cost. The algorithm is, of course, well-documented and so easy to understand that even a toddler could code it blindfolded.
This also demonstrates just how incredibly well-structured and purposeful YAML is for the development of ‘templates,’ especially when dealing with complex algorimts.
sensors:
billigaste_energi_hushallsmaskiner:
device_class: timestamp
friendly_name: billigaste energi hushallsmaskiner
value_template: >
{%- set numberOfSequentialHours = states(‘input_number.num_timmar_till_hushallsmaskiner’) | int() -%}
{%- set lastHour = 24 -%}
{%- set firstHour = ((as_timestamp(now() ) | timestamp_custom(‘%H’)) | int() ) -%}
{%- if state_attr(‘sensor.el_spotpris’, ‘tomorrow_valid’) == true and now().hour >=13-%}
{%- set ns = namespace(counter=0, list=[], cheapestHour=today_at(“00:00”) + timedelta( hours = (24)), cheapestPrice=999.00) -%}
{%- for i in range(firstHour + numberOfSequentialHours, lastHour +9 ) -%}
{%- set ns.counter = 0.0 -%}
{%- for j in range(i-numberOfSequentialHours, i) -%}
{%- if j < 24 -%}
{%- set ns.counter = ns.counter + state_attr('sensor.el_spotpris', 'today')[j] -%}
{%- else -%}
{%- set ns.counter = ns.counter + state_attr('sensor.el_spotpris', '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.el_spotpris', '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 -%}