-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstock-quote
executable file
·46 lines (37 loc) · 1.29 KB
/
stock-quote
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
#!/usr/bin/python3
#
# Usage: stock-quote FOO [BAR]
# retrieve the given stock quote from Google
# https://finance.google.com/finance/getprices?q=FOO&p=2d&i=60
#
from __future__ import print_function
import re
import requests
import sys
def print_google_quote(stock):
params = {
'q': stock,
'p': '2d', # Period: 2 days
'i': '60', # Interval: 60 seconds
}
r = requests.get('https://finance.google.com/finance/getprices', params=params)
lines = r.text.split()
# Get the previous close.
# We match the openings that are identified by a Unix timestamp
# preceded by a 'a' character and read the last tick before the
# last opening.
openings = [(idx, line) for (idx, line) in enumerate(lines) if re.match('a\d+,.*', line)]
if not openings:
print('{}: no data'.format(stock))
return
assert len(openings) == 2
idx = int(openings[-1][0]) - 1
previous = float(lines[idx].split(',')[1])
# Get the latest tick (the last line)
current = float(lines[-1].split(',')[1])
delta = current - previous
delta_percent = delta / previous * 100
print('{}: {} ({:+.2f}, {:+.2f}%)'.format(stock, current, delta, delta_percent))
if __name__ == '__main__':
for stock in sys.argv[1:]:
print_google_quote(stock)