forked from dabeaz-course/practical-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreport.py
More file actions
55 lines (45 loc) · 1.32 KB
/
report.py
File metadata and controls
55 lines (45 loc) · 1.32 KB
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
47
48
49
50
51
52
53
54
55
# report.py
import csv
def read_portfolio(filename):
'''
Read a stock portfolio file into a list of dictionaries with keys
name, shares, and price.
'''
portfolio = []
with open(filename) as f:
rows = csv.reader(f)
headers = next(rows)
for row in rows:
stock = {
'name' : row[0],
'shares' : int(row[1]),
'price' : float(row[2])
}
portfolio.append(stock)
return portfolio
def read_prices(filename):
'''
Read a CSV file of price data into a dict mapping names to prices.
'''
prices = {}
with open(filename) as f:
rows = csv.reader(f)
for row in rows:
try:
prices[row[0]] = float(row[1])
except IndexError:
pass
return prices
portfolio = read_portfolio('../../Work/Data/portfolio.csv')
prices = read_prices('../../Work/Data/prices.csv')
# Calculate the total cost of the portfolio
total_cost = 0.0
for s in portfolio:
total_cost += s['shares']*s['price']
print('Total cost', total_cost)
# Compute the current value of the portfolio
total_value = 0.0
for s in portfolio:
total_value += s['shares']*prices[s['name']]
print('Current value', total_value)
print('Gain', total_value - total_cost)