11# report.py
22#
3- # Exercise 2.4
3+ # Exercise 2.4 - 2.12
44import csv
55from pprint import pprint
66
@@ -18,53 +18,89 @@ def read_prices(filename):
1818
1919 return prices
2020
21-
2221def read_portfolio (filename ):
2322 """Reads a stock portfolio from a CSV file with handling for missing files."""
23+ value = 0.0
2424 data_list = []
2525
2626 try :
2727
2828 with open (filename , 'rt' ) as f :
2929 rows = csv .reader (f )
3030 headers = next (rows ) # skip the header line
31- for row in rows :
32- data_dict = {
33- 'name' : row [0 ],
34- 'shares' : int (row [1 ]),
35- 'price' : float (row [2 ])
36- }
37- data_list .append (data_dict )
38- return data_list
31+
32+ for rownum , row in enumerate (rows , start = 2 ):
33+ # data_dict = {
34+ # 'name': row[0],
35+ # 'shares': int(row[1]),
36+ # 'price': float(row[2])
37+ # }
38+ record = dict (zip (headers , row ))
39+ try :
40+ record ['shares' ] = int (record ['shares' ])
41+ record ['price' ] = float (record ['price' ])
42+ # value += num_shares * price
43+ data_list .append (record )
44+
45+ except ValueError :
46+ print (f'Line { rownum } : Bad line: { row } ' )
47+
48+ return data_list , headers
3949
4050 except FileNotFoundError :
4151 print (f'Error: The file { filename } was not found.' )
4252 return None
4353
54+ def make_report (portfolio , prices ):
55+ """Generates a report of the portfolio with current prices and gain/loss."""
56+ report = []
57+ for stock in portfolio :
58+ name = stock ['name' ]
59+ shares = int (stock ['shares' ])
60+ purchase_price = float (stock ['price' ])
61+ current_price = prices .get (name , 0.0 )
62+ gain_loss = (current_price - purchase_price )
63+ report .append ((name , shares , current_price , gain_loss ))
64+ return report
65+
66+
4467curr_prices = read_prices ('.\\ Data\\ prices.csv' )
45- portfolio = read_portfolio ('.\\ Data\\ portfolio.csv' )
46- # portfolio = read_portfolio('.\\Data\\missing.csv')
68+ portfolio = read_portfolio ('.\\ Data\\ portfoliodate.csv' )
69+ # print(portfolio[0])
70+ # print(portfolio[1])
71+ pf_data = portfolio [0 ]
72+ headers = portfolio [1 ]
73+
74+ report = make_report (pf_data , curr_prices )
75+
76+ for h in headers :
77+ print ('%10s' % h , end = ' ' )
78+ print ()
79+ print (('-' * 10 + ' ' ) * len (headers ))
4780
48- total_cost = 0.0
49- total_gain_loss = 0.0
50- curr_value = 0.0
81+ # for r in report:
82+ # print('%10s %10d %10.2f %10.2f' % r)
5183
52- for s in portfolio : # loop through list of dictionaries
53- if s ['name' ] in curr_prices :
54- print (f"Updating { s ['name' ]} price from { s ['price' ]} to { curr_prices [s ['name' ]]} " )
55- s ['current_price' ] = curr_prices [s ['name' ]]
56- s ['gain_loss' ] = (curr_prices [s ['name' ]] - s ['price' ]) * s ['shares' ]
57- curr_value += curr_prices [s ['name' ]] * s ['shares' ]
58-
59- total_gain_loss += s ['gain_loss' ]
60- total_cost += s ['shares' ] * s ['price' ]
84+ # for name, shares, price, change in report:
85+ # dollar_price = f'${price:0.2f}'
86+ # print(f'{name:>10s} {shares:>10d} {dollar_price:>10s} {change:>10.2f}')
6187
62- pprint (portfolio )
88+ for row in pf_data :
89+ # for i,j in row.items():
90+ # print(f'{j:>10s}', end=' ')
91+ # print()
92+ for i in list (row .values ()):
93+ print (f'{ i :>10} ' , end = ' ' )
94+ print ()
6395
64- print (f'Total cost of portfolio: ${ total_cost :0.2f} ${ total_gain_loss :0.2f} gain/loss Current value: ${ curr_value :0.2f} \n ' )
6596
66- for s in portfolio :
67- print (f"{ s ['name' ]:6s} : { s ['shares' ]:<6} shares at ${ s ['price' ]:0.2f} Current price: ${ s ['current_price' ]:<6} Gain/Loss: ${ s ['gain_loss' ]:0.2f} " )
97+
98+
99+
100+
101+
102+
103+
68104
69105
70106
0 commit comments