11import csv
2+ import sys
3+ import argparse
4+ import logging
25from statistics import mean
6+ from collections import defaultdict
37
8+ logging .basicConfig (filename = "app.log" , level = logging .DEBUG , format = '%(asctime)s - %(levelname)s - %(message)s' )
49
510def parse_csv (path ):
6- data_list = []
11+ stock_details = defaultdict ( list )
712 try :
813 with open (path , 'r' ) as file :
914 csv_reader = csv .DictReader (file )
1015 for row in csv_reader :
11- data_list .append (row )
12- return data_list
16+ stock_details [ row [ 'Name' ]] .append (row [ 'close' ] )
17+ return stock_details
1318 except FileNotFoundError as e :
14- print (e )
19+ logging .debug (f"file not found at { path } " )
20+ sys .exit (1 )
1521 except IOError as e :
1622 print (e )
1723 except Exception as e :
@@ -20,7 +26,7 @@ def parse_csv(path):
2026
2127def write_to_csv (file_path , price_list , header_list ):
2228 try :
23- with open (file_path , 'w' ) as file :
29+ with open (file_path , 'w' , newline = '' ) as file :
2430 field_names = header_list
2531 csv_writer = csv .DictWriter (file , fieldnames = field_names )
2632 csv_writer .writeheader ()
@@ -29,47 +35,49 @@ def write_to_csv(file_path, price_list, header_list):
2935 #print(row)
3036 csv_writer .writerow (row )
3137 except FileNotFoundError as e :
32- print (e )
38+ logging .debug (f"file not found at { file_path } " )
39+ sys .exit (1 )
3340 except IOError as e :
3441 print (e )
3542
43+ def calculate_stocks (stock_details ):
44+ try :
45+ price_list = []
46+ for name , stock_price in stock_details .items ():
47+ try :
48+ price = list (map (float , stock_price ))
49+ except ValueError :
50+ logging .debug (f"There is some problem with { price } " )
51+ continue
52+ price_dict = {
53+ "Name" : name ,
54+ "Total" : sum (price ),
55+ 'Average' : round (mean (price ),2 ),
56+ 'Maximum' : max (price ),
57+ 'Minimum' :min (price )
58+ }
3659
37- def main ():
38- file_path = "all_stocks_5yr.csv"
39- final_csv = "result.csv"
40- stock_details = parse_csv (file_path )
41- #print(stock_details)
60+ price_list .append (price_dict )
61+ return price_list
62+ except TypeError as e :
63+ print (e )
4264
43- companies = set ()
44- for row in stock_details :
45- companies .add (row ['Name' ])
4665
47- companies_list = sorted (list (companies ))
48- price_list = []
66+ def main ():
4967
50- for cname in companies_list :
51- prices = []
52- for details in stock_details :
53- #print(details)
54- if details ['Name' ] == cname :
55- prices .append (float (details ['close' ]))
56- #print(prices)
57- #print(f"{cname} : Total: {sum(prices)}, Average: {round(mean(prices),2)}, Maximum: {max(prices)}, Minimum: {min(prices)} ")
68+ parser = argparse .ArgumentParser (description = 'parse stock csv and calculate stats' )
69+ parser .add_argument ("input" )
70+ parser .add_argument ("output" )
5871
59- price_dict = {
60- "Name" : cname ,
61- "Total" : sum (prices ),
62- 'Average' : round (mean (prices ),2 ),
63- 'Maximum' : max (prices ),
64- 'Minimum' :min (prices )
65- }
72+ args = parser .parse_args ()
73+ logging .info (args )
6674
67- price_list .append (price_dict )
68- #print(price_list)
69- header_list = list (price_dict .keys ())
70- write_to_csv (final_csv , price_list , header_list )
75+ stock_details = parse_csv (args .input )
76+ header_list = ['Name' , 'Total' ,'Average' ,'Minimum' ,'Maximum' ]
7177
72- if __name__ == "__main__" :
73- main ( )
78+ stock_stats_list = calculate_stocks ( stock_details )
79+ write_to_csv ( args . output , stock_stats_list , header_list )
7480
7581
82+ if __name__ == "__main__" :
83+ main ()
0 commit comments