Custom Component Avanza Stock

I have two triggers. The first also uses the workday sensor to only send me notifications when the stockmarket is open

  trigger:
    - platform: time
      at: '18:00:00'

  condition:
    condition: state
    entity_id: binary_sensor.workday
    state: 'on'

The other one is triggered by a telegram command.

  trigger:
    - platform: event
      event_type: telegram_command
      event_data:
        command: /stock

I created a new script based on your idea to generate a lot of config, if you log in to Avanza and navigate to an account it lets you generate all your stocks with shares and everything as a long list of sensors. Was actually quite nice to have if/when you sell and buy stocks, to always have your sensors up to date! :slight_smile:

Script location:

1 Like

Nice, I run the script in the browser?
What do you have configured in the component, ie
Dividend date etc?

Tried to run it in console in Chrome on avanza site. But that doesnt seem to be how to do it. How to get it to work?

Thanks.

Ah, you have to run it through tampermonkey (https://www.tampermonkey.net/). It will install as a ChromeExtension. When installed, go to the tempermonkey icon, click dashboard in the menu, then the + next to installed scripts and paste the code. Hit CTRL-S to save and then browse to avanza. You will see a red icon with a 1 on top of the tampermonkey icon to indicate that there is 1 running script :slight_smile:

My tampermonkey dashboard looks like this:

Thanks! Works great.

1 Like

Getting the following error when running the script.

Mon Aug 26 2019 14:21:53 GMT+0200 (centraleuropeisk sommartid)
Error executing script: ‘NoneType’ object is not subscriptable
Traceback (most recent call last):
File “/usr/src/homeassistant/homeassistant/components/python_script/init.py”, line 182, in execute
exec(compiled.code, restricted_globals, local)
File “telegram_dividend.py”, line 9, in
File “/usr/local/lib/python3.7/site-packages/RestrictedPython/Eval.py”, line 35, in default_guarded_getitem
return ob[index]
TypeError: ‘NoneType’ object is not subscriptable

Do you have all the required monitored_conditions?

  • tickerSymbol
  • dividends
  • shares

P.S. You can’t call the script directly without arguments.

Works! Redid all of it. I dont know the specific error but might have been a typo on my part. Works great now.

So, not getting any output from the script, error message is

Error executing script: 'NoneType' object is not subscriptable
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/components/python_script/__init__.py", line 194, in execute
    exec(compiled.code, restricted_globals, local)
  File "telegram_dividend.py", line 9, in <module>
  File "/usr/local/lib/python3.7/site-packages/RestrictedPython/Eval.py", line 35, in default_guarded_getitem
    return ob[index]
TypeError: 'NoneType' object is not subscriptable

Why is this?
Is it when stocks have the following it does occur.
dividend0_amountPerShare: unknown

EDIT: One stock was still in the notification, but sensor was missing.
BR

If you are using my script above I would guess that attributes = entity.attributes returns None, which would indicate that the entity has no attributes or the entity id is wrong. I would suggest to try and debug the script using logger.info(
)

Hello @claha and thanks for this custom component.

I had a few problems geting this to work as I would, so I’m just describing my findings for future readers I also have a suggestion at the end of my post.

I have the following config in my configuration.yaml

sensor:
- platform: avanza_stock
    name: Spiltan Aktiefond Investmentbolag
    stock: 325406
  - platform: avanza_stock
    name: AMF Aktiefond SmÄbolag   
    stock: 2801  
  - platform: avanza_stock
    name: Handelsbanken USA    
    stock: 315115
  - platform: avanza_stock
    name: ICA Gruppen
    stock: 31607

Unfortunately, I could not find anything named avanza, neither in my states, nor in the error logfile.

Instead, I had to look for stock or the fund name. That was not obvious.

Suggestion: Is it possible for you to add “avanza_[stock-number]_” to the name of each sensor, such as:

sensor.avanza_325406_spiltan_aktiefond_investmentbolag

This would also make it very much easier to iterate trough all the avanza sensors.

Ok, this would probably cause problems for some of the current installations, another suggestion could be to add an attribute to each sensor, such as:

“Avanza stock id: 325406”

It would really make things easier if there was an easy way to sort out all avanza sensors from the rest of the entities.

Finally, thanks again for a very useful sensor!

Hi @ibennani! Happy that you like and use the component :slight_smile:

Using monitiored_conditions you can add both an id attribute and name attribute. If you don’t specify a name for the sensor it will be named sensor.avanza_1234. Please let me know if this is not enough for your needs and I will have a look to see what could possibly be updated.

Unfortunantily, googling for home assistant monitiored_conditions did not result in any useful info.

@claha , perhaps you could provide me with a useful code sniplet?

@ibennani There is an example in the github README https://github.com/claha/sensor.avanza_stock :slight_smile:

Hello again @claha.
Looked at the github readme and I’d love to have all the sensors named sensor.avanza_stock_ by default. Now when I have this config:

sensor:
- platform: avanza_stock
    name: Spiltan Aktiefond Investmentbolag
    stock: 325406

the corresponding sensor I have is:

sensor.spiltan_aktiefond_investmentbolag

Instead, I’d love to have my sensor named like this:

sensor.avanza_stock_325406

This “naming issue” occurs with all my stock sensors by default. Is there some way I can get that desired sensor name by default?

As stated in the readme, name is optional and if not given then sensor will be named avanza_stock_{stock}

sensor:
  - platform: avanza_stock
    stock: 325406
    monitored_conditions:
      - name

Will give sensor.avanza_stock_325406 that has an attribute name which I think will be “Spiltan Aktiefond Investmentbolag”

1 Like

Thanks allot! Your last example really made it easy to understand.

This custom component is really interesting and useful! Good work!

1 Like

After asking a lot, it’s finally CONTRIBUTION TIME!

Here’s my MVP/quick-and-dirty example of a script that reads out the stockchange attributes in all the defined stocks and funds into one specific Google Home speaker. This requires that the Google Home has already been setup in your HA installation.

This also requires that the changePercent attribute is enabled, like this:

sensor:
- platform: avanza_stock
    stock: 325406
    monitored_conditions:
      - changePercent

Here’s my script.

my_stock:
    alias: "My Stock"
    sequence:
      - service: tts.google_translate_say
        data_template:
          entity_id: media_player.googlehome_kitchen
          message: >
            Here are the latest stock info. 
            {%- for device in states %}
              {%- if 'avanza_stock' in device.entity_id %}
                {%- set stockchange = device.attributes.changePercent %}
                {{ device.attributes.name }}: 
                {%- if stockchange > 0 %} Up {{ stockchange | replace("."," point ") }} percent.
                {%- elif stockchange < 0 %} Down {{ stockchange | replace("."," point ") }} percent.
                {%- elif stockchange == 0 %} Unchanged.
              {%- endif %}
            {%- endif %}
          {%- endfor %}
        language: 'en'
        cache: false

@claha, is there some reason why all the available attributes are not enabled by default? I’m sure there is such a reason, I’m just curious. :smiley:

1 Like

@ibennani I looked at other components which has a lot of attributes, like Weather, and thoose all seemed to follow the pattern to have a monitored_conditions (the name monitored_conditioms should probably change for this platform
).

Love the script, will definetly try it out. I send myself a telegram message after the stock market closes with a summary of todays changes.

2 Likes