-
Notifications
You must be signed in to change notification settings - Fork 1
/
stock.py
executable file
·58 lines (46 loc) · 1.67 KB
/
stock.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#!/usr/bin/env python3
from sys import argv
from urllib.request import urlopen
from urllib.parse import urlencode
from urllib.error import URLError
import re
BASE_URL = 'http://finance.yahoo.com/d/quotes.csv?'
FORMAT = ['s', 'l1', 'c']
INDEX = {'NASDAQ': '^IXIC', 'S&P': '^GSPC'}
def main(*symbols):
print(get_quote(*symbols))
def Plugin:
def __init__(self, bot, handler):
self.bot = bot
self.conn = bot.conn
self.handler = handler
self.hooks = [
{'type': 'command', 'key': '!stock', 'func': self.stock}
]
def stock(self, data):
sym = data.tokens.pop(0)
s, p, c = self.get_quote(sym)[0]
self.conn.say('{}: {} ({})'.format(s, p, c), data.to)
def get_csv(self, *symbols):
"""Query the website and fetch the CSV containing the data."""
symbols = [INDEX.get(s.upper(), s) for s in symbols]
query = (('s', '+'.join(symbols)), ('f', ''.join(FORMAT)))
args = urlencode(query)
csv = urlopen(BASE_URL+args)
csv = csv.readlines()
return [line.decode().strip('\r\n') for line in csv]
def parse_csv(self, csv):
"""Parse the CSV to extract the relevant data, and return it
in an appropriate format."""
data = []
for line in csv:
sym, price, change = [w.strip('"') for w in line.split(',')]
change = change.split(' ')[-1]
data.append([sym, price, change])
return data
def get_quote(self, *symbols):
csv = self.get_csv(*symbols)
data = self.parse_csv(csv)
return data
if __name__ == '__main__':
main(*argv[1:])