Computes the total cost (shares*price) of a portfolio file
(filename)
| 2 | |
| 3 | import csv |
| 4 | def portfolio_cost(filename): |
| 5 | ''' |
| 6 | Computes the total cost (shares*price) of a portfolio file |
| 7 | ''' |
| 8 | total_cost = 0.0 |
| 9 | |
| 10 | with open(filename) as f: |
| 11 | rows = csv.reader(f) |
| 12 | headers = next(rows) |
| 13 | for rowno, row in enumerate(rows, start=1): |
| 14 | record = dict(zip(headers, row)) |
| 15 | try: |
| 16 | nshares = int(record['shares']) |
| 17 | price = float(record['price']) |
| 18 | total_cost += nshares * price |
| 19 | # This catches errors in int() and float() conversions above |
| 20 | except ValueError: |
| 21 | print(f'Row {rowno}: Bad row: {row}') |
| 22 | |
| 23 | return total_cost |
| 24 | |
| 25 | import sys |
| 26 | if len(sys.argv) == 2: |