Skip to content

Commit 4236e47

Browse files
committed
Updated to Exercise 2.7: Finding out if you can retire
1 parent 5eed2dc commit 4236e47

File tree

1 file changed

+36
-17
lines changed

1 file changed

+36
-17
lines changed

Work/report.py

Lines changed: 36 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -7,25 +7,44 @@
77

88
def read_portfolio(filename):
99
portfolio = []
10-
f = open(filename)
11-
headers = next(f)
12-
rows = csv.reader(f)
13-
for row in rows:
14-
d = {
15-
'name': row[0],
16-
'shares': int(row[1]),
17-
'price': float(row[2])
18-
}
19-
portfolio.append(d)
20-
f.close()
10+
with open(filename, 'r') as f:
11+
rows = csv.reader(f)
12+
headers = next(f)
13+
for row in rows:
14+
d = {
15+
'name': row[0],
16+
'shares': int(row[1]),
17+
'price': float(row[2])
18+
}
19+
portfolio.append(d)
2120
return portfolio
2221

2322

24-
if len(sys.argv) == 2:
25-
filename = sys.argv[1]
26-
else:
27-
filename = 'Data/portfolio.csv'
23+
def read_prices(filename):
24+
prices = {}
25+
with open(filename, 'r') as f:
26+
rows = csv.reader(f)
27+
for row in rows:
28+
try:
29+
prices[row[0]] = float(row[1])
30+
except IndexError:
31+
pass
32+
return prices
2833

29-
portfolio = read_portfolio(filename)
30-
print(portfolio)
3134

35+
portfolio = read_portfolio('Data/portfolio.csv')
36+
prices = read_prices('Data/prices.csv')
37+
38+
portfolio_value = 0
39+
current_value = 0
40+
41+
for stock in portfolio:
42+
portfolio_value += stock['shares'] * stock['price']
43+
current_value += stock['shares'] * prices[stock['name']]
44+
45+
total_value = current_value - portfolio_value
46+
47+
print(f'Old value: {portfolio_value}')
48+
print(f'Current value: {current_value}')
49+
50+
print(f'Gain: {total_value:0.2f}' if total_value > 0 else f'Loss: {-total_value:0.2f}')

0 commit comments

Comments
 (0)