|
| 1 | +# ticker.py |
| 2 | + |
| 3 | +from follow import follow |
| 4 | +import csv |
| 5 | +import report |
| 6 | +import tableformat |
| 7 | + |
| 8 | +def select_columns(rows, indices): |
| 9 | + for row in rows: |
| 10 | + yield [ row[index] for index in indices ] |
| 11 | + |
| 12 | + |
| 13 | +def convert_types(rows, types): |
| 14 | + for row in rows: |
| 15 | + yield [func(val) for func, val in zip(types, row)] |
| 16 | + |
| 17 | + |
| 18 | +def make_dicts(rows, headers): |
| 19 | + for row in rows: |
| 20 | + yield dict(zip(headers, row)) |
| 21 | + |
| 22 | + |
| 23 | +def filter_symbols(rows, names): |
| 24 | + for row in rows: |
| 25 | + if row['name'] in names: |
| 26 | + yield row |
| 27 | + |
| 28 | + |
| 29 | +def parse_stock_data(lines): |
| 30 | + rows = csv.reader(lines) |
| 31 | + rows = select_columns(rows, [0, 1, 4]) |
| 32 | + rows = convert_types(rows, [str, float, float]) |
| 33 | + rows = make_dicts(rows, ['name', 'price', 'change']) |
| 34 | + return rows |
| 35 | + |
| 36 | + |
| 37 | +def ticker(portfile, logfile, fmt): |
| 38 | + portfolio = report.read_portfolio(portfile) |
| 39 | + lines = follow(logfile) |
| 40 | + rows = parse_stock_data(lines) |
| 41 | + rows = filter_symbols(rows, portfolio) |
| 42 | + formatter = tableformat.create_formatter(fmt) |
| 43 | + formatter.headings(['Name', 'Price', 'Change']) |
| 44 | + for row in rows: |
| 45 | + formatter.row([ row['name'], f"{row['price']:0.2f}", f"{row['change']:0.2f}"]) |
| 46 | + |
| 47 | + |
| 48 | + |
| 49 | +if __name__ == '__main__': |
| 50 | + |
| 51 | + portfolio = report.read_portfolio('Data/portfolio.csv') |
| 52 | + rows = parse_stock_data(follow('Data/stocklog.csv')) |
| 53 | + rows = filter_symbols(rows, portfolio) |
| 54 | + for row in rows: |
| 55 | + print(row) |
0 commit comments