2020-04-19 09:44:25 +02:00
|
|
|
# -*- coding: UTF-8 -*-
|
|
|
|
# pylint: disable=C0111,R0903
|
|
|
|
|
|
|
|
"""Display a stock quote from worldtradingdata.com
|
|
|
|
|
|
|
|
Requires the following python packages:
|
|
|
|
* requests
|
|
|
|
|
|
|
|
Parameters:
|
|
|
|
* stock.symbols : Comma-separated list of symbols to fetch
|
|
|
|
* stock.change : Should we fetch change in stock value (defaults to True)
|
2020-05-08 20:58:35 +02:00
|
|
|
|
|
|
|
|
|
|
|
contributed by `msoulier <https://github.com/msoulier>`_ - many thanks!
|
2020-04-19 09:44:25 +02:00
|
|
|
"""
|
|
|
|
|
|
|
|
import json
|
2020-04-19 09:49:06 +02:00
|
|
|
import urllib.request
|
2020-04-19 09:44:25 +02:00
|
|
|
|
|
|
|
import logging
|
|
|
|
|
2020-04-19 09:49:06 +02:00
|
|
|
import core.module
|
|
|
|
import core.widget
|
|
|
|
import core.decorators
|
|
|
|
|
|
|
|
import util.format
|
|
|
|
|
2020-05-03 11:15:52 +02:00
|
|
|
|
2020-04-19 09:49:06 +02:00
|
|
|
class Module(core.module.Module):
|
|
|
|
@core.decorators.every(hours=1)
|
2020-04-26 16:39:24 +02:00
|
|
|
def __init__(self, config, theme):
|
|
|
|
super().__init__(config, theme, core.widget.Widget(self.value))
|
2020-04-19 09:49:06 +02:00
|
|
|
|
2020-05-03 11:15:52 +02:00
|
|
|
self.__symbols = self.parameter("symbols", "")
|
|
|
|
self.__change = util.format.asbool(self.parameter("change", True))
|
2020-04-19 09:49:06 +02:00
|
|
|
self.__value = None
|
2020-04-19 09:44:25 +02:00
|
|
|
|
|
|
|
def value(self, widget):
|
|
|
|
results = []
|
2020-04-19 09:49:06 +02:00
|
|
|
if not self.__value:
|
2020-05-03 11:15:52 +02:00
|
|
|
return "n/a"
|
2020-04-19 09:49:06 +02:00
|
|
|
data = json.loads(self.__value)
|
2020-04-19 09:44:25 +02:00
|
|
|
|
2020-05-03 11:15:52 +02:00
|
|
|
for symbol in data["quoteResponse"]["result"]:
|
|
|
|
valkey = "regularMarketChange" if self.__change else "regularMarketPrice"
|
|
|
|
sym = symbol.get("symbol", "n/a")
|
|
|
|
currency = symbol.get("currency", "USD")
|
|
|
|
val = "n/a" if not valkey in symbol else "{:.2f}".format(symbol[valkey])
|
|
|
|
results.append("{} {} {}".format(sym, val, currency))
|
|
|
|
return " ".join(results)
|
2020-04-19 09:44:25 +02:00
|
|
|
|
|
|
|
def fetch(self):
|
2020-04-19 09:49:06 +02:00
|
|
|
if self.__symbols:
|
2020-05-03 11:15:52 +02:00
|
|
|
url = "https://query1.finance.yahoo.com/v7/finance/quote?symbols="
|
|
|
|
url += (
|
|
|
|
self.__symbols
|
|
|
|
+ "&fields=regularMarketPrice,currency,regularMarketChange"
|
|
|
|
)
|
2020-04-19 09:49:06 +02:00
|
|
|
return urllib.request.urlopen(url).read().strip()
|
2020-04-19 09:44:25 +02:00
|
|
|
else:
|
2020-05-03 11:15:52 +02:00
|
|
|
logging.error("unable to retrieve stock exchange rate")
|
2020-04-19 09:44:25 +02:00
|
|
|
return None
|
|
|
|
|
2020-04-19 09:49:06 +02:00
|
|
|
def update(self):
|
|
|
|
self.__value = self.fetch()
|
2020-04-19 09:44:25 +02:00
|
|
|
|
2020-05-03 11:15:52 +02:00
|
|
|
|
2020-04-19 09:44:25 +02:00
|
|
|
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
|