Multiply sensor value with another value

Thank you for the help @mobile.andrew.jones
I see what you mean about “usd”. In this particular case it is part of the entity_id… I should have probably taken that off for the example.

This is the dev_tools shot (Showing the entity_id & attributes):

*You were 100% accurate about the state of the sensor… I need to define the attribute I want to get, to then multiply it by the quantity desired.

I have modified the template as below, and a few other variations of it, however I still can’t get calculation;

  - platform: template
    sensors:
      cardano_holding:
        friendly_name: Cardano Holding's Value
        value_template: "{{ state_attr('sensor.yahoofinance_ada_usd', 'regular_market_price') | float * 5000 | round(0) }}"

Can you see where I am going wrong here?

Thank you again!

In this particular example - the place where you are going wrong, is in the attributes. I see why you think there needs to be underscores and lowercase, but you are asking for the attribute and you can already see in dev tools that it doesn’t have any underscores and is stored with a name using upper and lowercase. You want regularMarketPrice

1 Like

perfect thank you. yes i was trying variations to make sure it wasn’t a syntax issue with HA. I have changed it to the specific attribute designation as you confirmed.

Since I still have not gotten the price to print, I am taking it down to simpler steps to try and just at least get the ticker’s attribute to print (removing the formula);

  - platform: template
    sensors:
      cardano_holding:
        friendly_name: Cardano Holding's Value
        value_template: "{{ state_attr('sensor.yahoofinance_ada_usd', 'regularMarketPrice') }}"

That template sensor yields an “On” output instead of the market price…

image

I have also tried the test with int / num / float objects as permutations however none of them provide the market price atribute.

I have also tried the adding “monetary (ISO 4217) unit of measurement” but that just gives an error.

Question:
The fact that I get an on/off output, instead of the value from the outlined attribute… is there something I am missing on the value_template?

The only thing I am wondering - is if you have this template under the binary_sensor: component and not the sensor: component in your configuration?

What is the entity_id you are using in the Lovelace dashboard?

Also, it won’t make a lot of difference right now - but we are transitioning away from doing platform template sensors - to the actual template component -

So your configuration would look like this:

template:
  - sensor:
    - name: "Cardano Holding's Value"
      state: >
        {{ state_attr('sensor.yahoofinance_ada_usd', 'regular_market_price') | float * 5000 | round(0) }}

Under the new way of doing things.

EDIT: Docs - Template - Home Assistant

1 Like

BROTHER THANK YOU!
That was it. I will look into the template component.

Thank you
Thank you
Thank you

1 Like

Binary sensor will class any number above 0 as being true, so that would be why it was always just saying on.

1 Like

Thank you for catching that… you are the MAN!

Yeah I was banging my head for 5 hours before I threw up the gloves… got up this morning and went right back to it :man_facepalming:t5:.

Thank you again Andrew!

1 Like

Don’t you think that the final answer should also use ‘regularMarketPrice’ (as listed on line 14 of the screenshot) instead of ‘regular_market_price’ (non-existent)?
Just for others not to fall in the same trap…

I need to multiply a sensor value by -1
I had gotten a no unique-id error and now I just get “unavailable”

template:
  - sensor:
      name: "Power-W4"
      unit_of_measurement: "W"
      device_class: energy
      state_class: total
      state: '{{ ((sensor.Power-CT1 | float) * -1) }}'
      unique_id: "power-W4"

is there anywhere else I can get an error code?

I do mine like this


#--------------------------------------------------------------------------------------------------
# Power to Grid - Make Positive
#--------------------------------------------------------------------------------------------------
template:
  - sensor:
    - name: "Power to Grid"
      unique_id: "Power to Grid"
      state: >-
        {% if states('sensor.powerwall_site_now') | float(0) < -0.0001 %}
          {{ states('sensor.powerwall_site_now') | float(0) | abs}} 
        {% else %}
          0.000
        {% endif %}
      unit_of_measurement: "kW"

Sorry, I’m a code noob, but If I take yours and make a slight tweak, it doesn’t work.
If I use your exact code, I get 0.000 because of the else, but I don’t understand what triggered the else effect.

  - sensor:
    - name: "Power-CT2-inv"
      unique_id: "Power to Grid2"
      state: >-
        {% if states('sensor.Power-CT2') | float(0) * -1.000}
          {{ states('sensor.Power-CT2') | float(0) | abs}} 
        {% else %}
          0.000
        {% endif %}
      unit_of_measurement: "kW"
      device_class: energy
      state_class: total

You are not testing for negative number. Your if statement was just multiplying by -1. This will not usually lead to a true statement.

 - sensor:
    - name: "Power-CT2-inv"
      unique_id: "Power to Grid2"
      state: >-
        {% if states('sensor.Power-CT2') | float(0) < -0.0001}  <-- check to see if CT2 is < 0 with roundoff
          {{ states('sensor.Power-CT2') | float(0) | abs}} <---- Remove the negative sign
        {% else %}
          0.000      <--- else the value is 0.
        {% endif %}
      unit_of_measurement: "kW"
      device_class: energy
      state_class: total

You will also need a power from grid that is done the same only with a >= on the if statement. You can keep the abs but you can also remove as it is a positive number.

Hi Friends!

I’m stuck with my code. I wanna modify the openweather 5 days temperature forecast. I need it because i live in a specify location where forecast is not so good, but i find the difference between forecast and current temperature is nearly constant (it is around 31% difference) so i write this:

  - platform: template
    sensors:
      tempmax_1:
        value_template: "{{ state_attr('weather.forecast_otthon', 'forecast')[0].temperature | float * 1.31 }}"
        unit_of_measurement: "°C"

I have two problems and ask your advice:

  1. with this i cen get only 1 day forecast and if i need all five days i have to use 5 times more code. I beleive there is a better solution
  2. with this code i can not get the datetime value from the weather.forecast sensor so i can not really use it.

How can i get the datetime value within the same code and is it possible to use a shorter code for all 5 days or i must write it for day by day?

Assuming your weather entity is like mine, this should work, using the modern template configuration:

template:
  - sensor:
      - name: weather31
        state: "{{ states('weather.forecast_otthon') }}"
        attributes:
          temperature: "{{ (state_attr('weather.forecast_otthon', 'temperature') * 1.31)|round(0) }}"
          humidity: "{{ state_attr('weather.forecast_otthon', 'humidity') }}"
          forecast: >
            {% set forecast = states.weather.forecast_otthon.attributes.forecast %}
            {% set ns = namespace(fore31=[]) %}
            {% for item in forecast %}
              {% set ns.fore31 = ns.fore31 + 
                                 [dict(item, **{'temperature': (item['temperature']*1.31)|round(0)})] %}
            {% endfor %}
            {{ ns.fore31 }}

That makes a copy of your weather entity as a sensor, with the top-level temperature and each forecast temperature multiplied by 1.31. You’ll have to add any other top-level attributes you need: I’ve added humidity as an example, but different weather sources provide different attributes.

Curious about the 31% difference though: does that apply above and below 0°C?

Thank you so much Troon i can not find it out alone. And it is exactly as i imagine, short, elegant, great!
Work as a dreem :slight_smile:

Very good question, no. In low temp forecast wich is going down (templow) the needed modification is aboute -40% difference. The positiv difference is +31 as you put in the code.

I just do not want to be cheeky and ask for the full solution. I think i can find out the templow part but no, it is not working.
I can not set up the templow script and i can not figure how to work with negative or positive numbers. The difference is -40% but i can not use the same math for + and - forecasts…

This shows you how to add additional attributes to both the “top level” and to the forecast, but if you can work out a formula to apply to the temperature to correct it based on its value, I can help build that in if you can’t work out how to do that.

Perhaps give us a list of selected forecast temperatures across the full range you’re likely to see, and what you’d like them to come out as.

template:
  - sensor:
      - name: weather_adjusted
        state: "{{ states('weather.forecast_otthon') }}"
        attributes:
          temperature: "{{ (state_attr('weather.forecast_otthon', 'temperature') * 1.31)|round(0) }}"
          temp_high: "{{ (state_attr('weather.forecast_otthon', 'temperature') * 1.31)|round(0) }}"
          temp_low: "{{ (state_attr('weather.forecast_otthon', 'temperature') * 0.6)|round(0) }}"
          humidity: "{{ state_attr('weather.forecast_otthon', 'humidity') }}"
          forecast: >
            {% set forecast = states.weather.forecast_otthon.attributes.forecast %}
            {% set ns = namespace(fore_adj=[]) %}
            {% for item in forecast %}
              {% set ns.fore_adj = ns.fore_adj + 
                                 [dict(item,
                                       **{'temp_high': (item['temperature']*1.31)|round(0),
                                          'temp_low': (item['temperature']*0.6)|round(0)})] %}
            {% endfor %}
            {{ ns.fore_adj }}

Thank you for your work Troon, it is great and working perfect.

I attach a picture aboute the weather temperature here. Red is the forecast by openweather, cyan is the exact value measured by a weather station in the field. Hope with this it is clear why i wanna get better datas for the future. Here the temperature can be -25 to +30 celsius within in a period of year.
Here is the last week:

I know there is more difference than 31% and 40% but it is early spring and in the summer there is much lower differences. Theese percentages are yearly averages.

The last thing is to work with negative numbers.
If the temperature forecast is -10 i can not work with multiplication but i have to work with share
( -10 / 0.6 = -16.6) to get correct value.

So your code need to examine the number (from openweather forecast) and if it is lower than 0 have to use share " / 0.6" or " / 1.31". If the number above 0 can use the multiply.

The two attributes comes from openweather are “temperature” and “templow” and i will use your suggestion for the output, “temp_high” and “temp_low”.

It is obvious i am not a programmer but i think it is something like this:

          {% if temperature > 0  %}
            {% set temp_high = temperature * 1.31 %}
          {% else %}
            {% set temp_high = temperature / 1.31 %}
          {% if templow > 0  %}
            {% set temp_low = templow * 0.6 %}
          {% else %}
            {% set temp_low = templow / 0.6 %}
          {% endif %}

just have no clue how to put it in your code. I try, but of course this is not working.

I do not know i am the only one who wanna get better forecast or live in a so special rural region but i think it is a common problem and looks like it has a proper solution.

Looking at that graph, there isn’t a nice conversion to get what you want. Look at where the red line is at zero: the first time, the cyan is at -5; next time 0; next time (just below) +3. It seems to need “expanding outwards” from a variable centre line and I don’t know how you’re going to do that. There isn’t a simple formula that turns a single openweather forecast number into the number you need: you’d need something much more complicated that looks at the whole forecast.

I didn’t realise templow was an attribute already: I thought you’d made that up.

The way to deal with that is to convert °C to K (Kelvin, which doesn’t have negative values), do your adjustment, then convert back. That won’t help with the problem that there isn’t a straight conversion from one number to another though.

I’ve included your code (compacted) below just to show how to use it: I’ve also included the unadjusted temperature and templow as ow_temperature and ow_templow.

template:
  - sensor:
      - name: weather_adjusted
        state: "{{ states('weather.forecast_otthon') }}"
        attributes:
          temperature: >
            {% set owt = state_attr('weather.forecast_otthon', 'temperature') %}
            {{ (owt*1.31 if owt > 0 else owt/1.31)|round(0) }}
          humidity: "{{ state_attr('weather.forecast_otthon', 'humidity') }}"
          forecast: >
            {% set forecast = states.weather.forecast_otthon.attributes.forecast %}
            {% set ns = namespace(fore_adj=[]) %}
            {% for item in forecast %}
              {% set owt, owtl = item['temperature'], item['templow'] %}
              {% set ns.fore_adj = ns.fore_adj + 
                                 [dict(item,
                                       **{'ow_temperature': owt,
                                          'ow_templow': owtl,
                                          'temperature': (owt*1.31 if owt > 0 else owt/1.31)|round(0),
                                          'templow': (owtl*0.6 if owtl > 0 else owtl/0.6)|round(0)})] %}
            {% endfor %}
            {{ ns.fore_adj }}

Dear Troon!

It is absolutely what i need.

Anyway you are wright aboute there is no perfect solution (as in meteorology there is no 100% sure forecast) but what you have done is much more precisious than the original.
Right now i do not try the kelvin conversation (you are right aboute too, but i get lot of help already and do not want to ask your time if it will work) just give a month to test the new sensor. I think it is fair enough but i’ll see.
I will write here after a month (or earlyer if it is not working).

Thank you so much for your work!!!

And here is the current forecasts result:
237

numbers: percitipation
green: openweather max temp
cyan: openweather min temp
red: Troon max temp
blue: Troon min temp

Going to test and write back :wink:

As i promise,

I’m happy with this solution. The kelvin conversation is a pretty good idea and can give more accurate forecast but i can use this one.

Thank you again Troon!

1 Like