Skip to content

Commit

Permalink
Support for trending icons
Browse files Browse the repository at this point in the history
  • Loading branch information
iprak committed Oct 29, 2020
1 parent e188ad4 commit 565e523
Show file tree
Hide file tree
Showing 4 changed files with 128 additions and 100 deletions.
22 changes: 11 additions & 11 deletions .devcontainer/configuration.yaml
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
default_config:
logger:
default: error
logs:
custom_components.yahoofinance: debug


sensor:
platform: yahoofinance
use_trending_icon: True
symbols:
default_config:
logger:
default: error
logs:
custom_components.yahoofinance: debug


sensor:
platform: yahoofinance
show_trending_icon: True
symbols:
- ISTNX
75 changes: 38 additions & 37 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,38 +1,39 @@
# Summary
A custom component to get stock updates from Yahoo finance.

# Installation

This can be installed by copying all the files from `custom_components/yahoofinance/` to `<config directory>/custom_components/yahoofinance/`.

Next you would define the symbols to be tracked in `configuration.yaml`

Example:

```yaml
sensor:
platform: yahoofinance
scan_interval:
hours: 4
symbols:
- ISTNX

```

The above configuration will generate an entity with the id `yahoofinance.istnx` and current value as the state along with these attributes:

```
attribution: Data provided by Yahoo Finance
currencySymbol: $
symbol: ISTNX
fiftyDayAverage: ...
previousClose: ...
unit_of_measurement: USD
friendly_name: Ivy Science & Technology Fund C
icon: mdi:currency-usd
```

`scan_interval` is optional and the default value is 6 hours.


# Summary
A custom component to get stock updates from Yahoo finance.

# Installation

This can be installed by copying all the files from `custom_components/yahoofinance/` to `<config directory>/custom_components/yahoofinance/`.

Next you would define the symbols to be tracked in `configuration.yaml`

Example:

```yaml
sensor:
platform: yahoofinance
show_trending_icon: true
scan_interval:
hours: 4
symbols:
- ISTNX

```

The above configuration will generate an entity with the id `yahoofinance.istnx` and current value as the state along with these attributes:

```
attribution: Data provided by Yahoo Finance
currencySymbol: $
symbol: ISTNX
fiftyDayAverage: ...
previousClose: ...
unit_of_measurement: USD
friendly_name: Ivy Science & Technology Fund C
icon: mdi:currency-usd
```

`scan_interval` is optional and the default value is 6 hours. Trending icon (up, down or neutral) can be used instead of currency based
icon by specifying `show_trending_icon`.

The component also exposes the service `yahoofinance.refresh_symbols` which will refresh all the data.
75 changes: 38 additions & 37 deletions custom_components/yahoofinance/const.py
Original file line number Diff line number Diff line change
@@ -1,37 +1,38 @@
"""Constants for Yahoo Finance sensor."""

ATTR_CURRENCY_SYMBOL = "currencySymbol"
ATTR_FIFTY_DAY_AVERAGE = "fiftyDayAverage"
ATTR_FIFTY_DAY_SYMBOL = "symbol"
ATTR_PREVIOUS_CLOSE = "previousClose"
ATTRIBUTION = "Data provided by Yahoo Finance"
BASE = "https://query1.finance.yahoo.com/v7/finance/quote?symbols="
CONF_SYMBOLS = "symbols"
DEFAULT_CURRENCY = "USD"
DEFAULT_CURRENCY_SYMBOL = "$"
DEFAULT_ICON = "mdi:currency-usd"
DOMAIN = "yahoofinance"
SERVICE_REFRESH = "refresh_symbols"

CURRENCY_CODES = {
"bdt": "৳",
"brl": "R$",
"btc": "₿",
"cny": "¥",
"eth": "Ξ",
"eur": "€",
"gbp": "£",
"ils": "₪",
"inr": "₹",
"jpy": "¥",
"krw": "₩",
"kzt": "лв",
"ngn": "₦",
"php": "₱",
"rial": "﷼",
"rub": "₽",
"sign": "",
"try": "₺",
"twd": "$",
"usd": "$",
}
"""Constants for Yahoo Finance sensor."""

ATTR_CURRENCY_SYMBOL = "currencySymbol"
ATTR_FIFTY_DAY_AVERAGE = "fiftyDayAverage"
ATTR_FIFTY_DAY_SYMBOL = "symbol"
ATTR_PREVIOUS_CLOSE = "previousClose"
ATTRIBUTION = "Data provided by Yahoo Finance"
BASE = "https://query1.finance.yahoo.com/v7/finance/quote?symbols="
CONF_SHOW_TRENDING_ICON = "show_trending_icon"
CONF_SYMBOLS = "symbols"
DEFAULT_CURRENCY = "USD"
DEFAULT_CURRENCY_SYMBOL = "$"
DEFAULT_ICON = "mdi:currency-usd"
DOMAIN = "yahoofinance"
SERVICE_REFRESH = "refresh_symbols"

CURRENCY_CODES = {
"bdt": "৳",
"brl": "R$",
"btc": "₿",
"cny": "¥",
"eth": "Ξ",
"eur": "€",
"gbp": "£",
"ils": "₪",
"inr": "₹",
"jpy": "¥",
"krw": "₩",
"kzt": "лв",
"ngn": "₦",
"php": "₱",
"rial": "﷼",
"rub": "₽",
"sign": "",
"try": "₺",
"twd": "$",
"usd": "$",
}
56 changes: 41 additions & 15 deletions custom_components/yahoofinance/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
ATTR_PREVIOUS_CLOSE,
ATTRIBUTION,
BASE,
CONF_SHOW_TRENDING_ICON,
CONF_SYMBOLS,
CURRENCY_CODES,
DEFAULT_CURRENCY,
Expand All @@ -42,27 +43,38 @@
ENTITY_ID_FORMAT = DOMAIN + ".{}"
SCAN_INTERVAL = timedelta(hours=6)
DEFAULT_TIMEOUT = 10

DEFAULT_CONF_SHOW_TRENDING_ICON = False

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_SYMBOLS): vol.All(cv.ensure_list, [cv.string]),
vol.Optional(CONF_SCAN_INTERVAL, default=SCAN_INTERVAL): cv.time_period,
vol.Optional(
CONF_SHOW_TRENDING_ICON, default=DEFAULT_CONF_SHOW_TRENDING_ICON
): cv.boolean,
}
)


async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): # pylint: disable=unused-argument
async def async_setup_platform(
hass, config, async_add_entities, discovery_info=None
): # pylint: disable=unused-argument
"""Set up the Yahoo Finance sensors."""
symbols = config.get(CONF_SYMBOLS, [])
show_trending_icon = config.get(
CONF_SHOW_TRENDING_ICON, DEFAULT_CONF_SHOW_TRENDING_ICON
)

coordinator = YahooSymbolUpdateCoordinator(
symbols, hass, config.get(CONF_SCAN_INTERVAL)
)
await coordinator.async_refresh()

sensors = []
for symbol in symbols:
sensors.append(YahooFinanceSensor(coordinator, symbol, hass))
sensors.append(
YahooFinanceSensor(hass, coordinator, symbol, show_trending_icon)
)

# The True param fetches data first time before being written to HA
async_add_entities(sensors, True)
Expand All @@ -73,7 +85,9 @@ async def handle_refresh_symbols(_call):
await coordinator.async_request_refresh()

hass.services.async_register(
DOMAIN, SERVICE_REFRESH, handle_refresh_symbols,
DOMAIN,
SERVICE_REFRESH,
handle_refresh_symbols,
)

_LOGGER.info("Added sensors for %s", symbols)
Expand All @@ -92,13 +106,12 @@ class YahooFinanceSensor(Entity):
_state = None
_symbol = None

def __init__(self, coordinator, symbol, hass) -> None:
def __init__(self, hass, coordinator, symbol, show_trending_icon) -> None:
"""Initialize the sensor."""
self._symbol = symbol
self._coordinator = coordinator
self.entity_id = async_generate_entity_id(
ENTITY_ID_FORMAT, symbol, hass=hass
)
self.entity_id = async_generate_entity_id(ENTITY_ID_FORMAT, symbol, hass=hass)
self.show_trending_icon = show_trending_icon
_LOGGER.debug("Created %s", self.entity_id)

@property
Expand Down Expand Up @@ -161,9 +174,19 @@ def fetch_data(self) -> None:

self._currency = currency.upper()
lower_currency = self._currency.lower()
self._icon = "mdi:currency-" + lower_currency
if lower_currency in CURRENCY_CODES:

# Fall back to currency based icon if there is no _previous_close value
if self.show_trending_icon and not (self._previous_close is None):
if self._state > self._previous_close:
self._icon = "mdi:trending-up"
elif self._state < self._previous_close:
self._icon = "mdi:trending-down"
else:
self._icon = "mdi:trending-neutral"
else:
self._icon = "mdi:currency-" + lower_currency

if lower_currency in CURRENCY_CODES:
self._currency_symbol = CURRENCY_CODES[lower_currency]

@property
Expand Down Expand Up @@ -196,7 +219,10 @@ def __init__(self, symbols, hass, update_interval) -> None:
self.websession = async_get_clientsession(hass)

super().__init__(
hass, _LOGGER, name=DOMAIN, update_interval=update_interval,
hass,
_LOGGER,
name=DOMAIN,
update_interval=update_interval,
)

async def _async_update_data(self):
Expand All @@ -212,9 +238,7 @@ async def get_json(self):
json = None
try:
async with async_timeout.timeout(DEFAULT_TIMEOUT, loop=self.loop):
response = await self.websession.get(
BASE + ",".join(self._symbols)
)
response = await self.websession.get(BASE + ",".join(self._symbols))
json = await response.json()

_LOGGER.debug("Data = %s", json)
Expand Down Expand Up @@ -251,7 +275,9 @@ async def update(self):
"financialCurrency": item.get("financialCurrency"),
}
_LOGGER.debug(
"Updated %s=%s", symbol, data[symbol]["regularMarketPrice"],
"Updated %s=%s",
symbol,
data[symbol]["regularMarketPrice"],
)

self.data = data
Expand Down

0 comments on commit 565e523

Please sign in to comment.