33# Exercise 2.4 - 2.12
44import csv
55from pprint import pprint
6+ from fileparse import parse_csv
7+
8+
69
710def read_prices (filename ):
811 """Reads stock prices from a CSV file and returns a dictionary mapping stock names to prices."""
9- prices = {}
10- with open (filename , 'rt' ) as f :
11- rows = csv .reader (f )
12+ # prices = {}
13+ # with open(filename, 'rt') as f:
14+ # rows = csv.reader(f)
1215
13- for row in rows :
14- if not row : # Skip empty rows
15- continue
16+ # for row in rows:
17+ # if not row: # Skip empty rows
18+ # continue
1619
17- prices [row [0 ]] = float (row [1 ])
20+ # prices[row[0]] = float(row[1])
21+ prices = parse_csv (filename , types = [str ,float ], has_headers = False )
1822
19- return prices
23+ return dict ( prices )
2024
2125def read_portfolio (filename ):
2226 """Reads a stock portfolio from a CSV file with handling for missing files."""
23- value = 0.0
24- data_list = []
27+ # value = 0.0
28+ # data_list = []
2529
26- try :
27-
28- with open (filename , 'rt' ) as f :
29- rows = csv .reader (f )
30- headers = next (rows ) # skip the header line
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 } ' )
30+ # try:
31+
32+ # with open(filename, 'rt') as f:
33+ # rows = csv.reader(f)
34+ # headers = next(rows) # skip the header line
35+
36+ # for rownum, row in enumerate(rows, start=2):
37+ # # data_dict = {
38+ # # 'name': row[0],
39+ # # 'shares': int(row[1]),
40+ # # 'price': float(row[2])
41+ # # }
42+ # record = dict(zip(headers, row))
43+ # try:
44+ # record['shares'] = int(record['shares'])
45+ # record['price'] = float(record['price'])
46+ # # value += num_shares * price
47+ # data_list.append(record)
48+
49+ # except ValueError:
50+ # print(f'Line {rownum}: Bad line: {row}')
4751
48- return data_list , headers
52+ # return data_list, headers
4953
50- except FileNotFoundError :
51- print (f'Error: The file { filename } was not found.' )
52- return None
54+ # except FileNotFoundError:
55+ # print(f'Error: The file {filename} was not found.')
56+ # return None
57+ portfolio = parse_csv (filename , types = [str , int , float ])
58+ return portfolio
5359
5460def make_report (portfolio , prices ):
5561 """Generates a report of the portfolio with current prices and gain/loss."""
@@ -73,65 +79,21 @@ def print_report(report):
7379
7480def portfolio_report (portfolio_file , prices_file ):
7581 """Generates and prints a portfolio report from given files."""
82+
7683 curr_prices = read_prices (prices_file )
77- portfolio_data = read_portfolio (portfolio_file )
84+ portfolio = read_portfolio (portfolio_file )
7885
79- if portfolio_data is None :
86+ if portfolio is None :
8087 return # Exit if portfolio file was not found
8188
82- portfolio , headers = portfolio_data
8389 report = make_report (portfolio , curr_prices )
8490 print_report (report )
8591
8692# portfolio_report('.\\Data\\portfoliodate.csv', '.\\Data\\prices.csv')
8793
88- files = ['.\\ Data\\ portfolio.csv' , '.\\ Data\\ portfolio2.csv' ]
89- for file in files :
90- print (f'{ file :-^43s} ' )
91- portfolio_report (file , '.\\ Data\\ prices.csv' )
92- print ()
94+
9395
9496# curr_prices = read_prices('.\\Data\\prices.csv')
9597# portfolio_data = read_portfolio('.\\Data\\portfoliodate.csv')
9698# report = make_report(portfolio_data[0], curr_prices)
9799# print_report(report)
98-
99-
100-
101- '''
102- pf_data = portfolio[0]
103- headers = portfolio[1]
104-
105- for h in headers:
106- print('%10s' % h, end=' ')
107- print()
108- print(('-' * 10 + ' ') * len(headers))
109-
110- # for r in report:
111- # print('%10s %10d %10.2f %10.2f' % r)
112-
113- # for name, shares, price, change in report:
114- # dollar_price = f'${price:0.2f}'
115- # print(f'{name:>10s} {shares:>10d} {dollar_price:>10s} {change:>10.2f}')
116-
117- for row in pf_data:
118- # for i,j in row.items():
119- # print(f'{j:>10s}', end=' ')
120- # print()
121- for i in list(row.values()):
122- print(f'{i:>10}', end=' ')
123- print()
124- '''
125-
126-
127-
128-
129-
130-
131-
132-
133-
134-
135-
136-
137-
0 commit comments