MCPcopy Create free account
hub / github.com/dabeaz-course/practical-python / portfolio_cost

Function portfolio_cost

Solutions/2_16/pcost.py:4–23  ·  view source on GitHub ↗

Computes the total cost (shares*price) of a portfolio file

(filename)

Source from the content-addressed store, hash-verified

2
3import csv
4def 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
25import sys
26if len(sys.argv) == 2:

Callers 1

pcost.pyFile · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected