bumblebee-status/modules/contrib/stock.py

61 lines
1.8 KiB
Python
Raw Normal View History

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)
"""
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
class Module(core.module.Module):
@core.decorators.every(hours=1)
def __init__(self, config, theme):
super().__init__(config, theme, core.widget.Widget(self.value))
2020-04-19 09:49:06 +02:00
self.__symbols = self.parameter('symbols', '')
self.__change = util.format.asbool(self.parameter('change', True))
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-04-19 09:44:25 +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
for symbol in data['quoteResponse']['result']:
2020-04-19 09:49:06 +02:00
valkey = 'regularMarketChange' if self.__change else 'regularMarketPrice'
sym = symbol.get('symbol', 'n/a')
currency = symbol.get('currency', 'USD')
2020-04-19 09:44:25 +02:00
val = 'n/a' if not valkey in symbol else '{:.2f}'.format(symbol[valkey])
results.append('{} {} {}'.format(sym, val, currency))
return u' '.join(results)
def fetch(self):
2020-04-19 09:49:06 +02:00
if self.__symbols:
2020-04-19 09:44:25 +02:00
url = 'https://query1.finance.yahoo.com/v7/finance/quote?symbols='
2020-04-19 09:49:06 +02:00
url += self.__symbols + '&fields=regularMarketPrice,currency,regularMarketChange'
return urllib.request.urlopen(url).read().strip()
2020-04-19 09:44:25 +02:00
else:
logging.error('unable to retrieve stock exchange rate')
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
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4