|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
1 | 3 | # report.py |
2 | 4 | # |
3 | 5 | # Exercise 2.4 |
| 6 | +from fileparse import parse_csv |
| 7 | + |
| 8 | + |
| 9 | +def read_portfolio(filename): |
| 10 | + ''' |
| 11 | + Read a stock portfolio file into a list of dictionaries with keys |
| 12 | + name, shares, and price. |
| 13 | + ''' |
| 14 | + with open(filename) as lines: |
| 15 | + return parse_csv( |
| 16 | + lines, |
| 17 | + select=['name', 'shares', 'price'], |
| 18 | + types=[str, int, float], |
| 19 | + ) |
| 20 | + |
| 21 | + |
| 22 | +def read_prices(filename): |
| 23 | + ''' |
| 24 | + Read a CSV file of price data into a dict mapping names to prices. |
| 25 | + ''' |
| 26 | + with open(filename) as lines: |
| 27 | + return dict(parse_csv(lines, types=[str, float], has_headers=False)) |
| 28 | + |
| 29 | + |
| 30 | +def make_report(portfolio, prices): |
| 31 | + report = [] |
| 32 | + for s in portfolio: |
| 33 | + current_price = prices[s['name']] |
| 34 | + change = current_price - s['price'] |
| 35 | + report.append( |
| 36 | + (s['name'], s['shares'], current_price, change) |
| 37 | + ) |
| 38 | + return report |
| 39 | + |
| 40 | + |
| 41 | +def print_report(report): |
| 42 | + ''' |
| 43 | + Print formatted report. |
| 44 | + ''' |
| 45 | + headers = ('Name', 'Shares', 'Price', 'Change') |
| 46 | + print('%10s %10s %10s %10s' % headers) |
| 47 | + print(('-' * 10 + ' ') * len(headers)) |
| 48 | + for row in report: |
| 49 | + print('%10s %10d %10.2f %10.2f' % row) |
| 50 | + |
| 51 | + |
| 52 | +def portfolio_report(portfolio_file, prices_file): |
| 53 | + ''' |
| 54 | + Make a stock report given portfolio and price data files. |
| 55 | + ''' |
| 56 | + portfolio = read_portfolio(portfolio_file) |
| 57 | + prices = read_prices(prices_file) |
| 58 | + report = make_report(portfolio, prices) |
| 59 | + print_report(report) |
| 60 | + |
| 61 | + |
| 62 | +def main(args): |
| 63 | + if len(args) != 3: |
| 64 | + raise SystemExit(f'Usage: {args[0]} portfolio_file prices_file') |
| 65 | + portfolio_report(args[1], args[2]) |
| 66 | + |
| 67 | +if __name__ == '__main__': |
| 68 | + import sys |
| 69 | + main(sys.argv) |
0 commit comments