Skip to content

Commit 436884c

Browse files
author
Peter
committed
Work before 6
1 parent 2787a7d commit 436884c

13 files changed

Lines changed: 602 additions & 3 deletions

File tree

Solutions/3_2/report.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -74,5 +74,5 @@ def portfolio_report(portfoliofile,pricefile):
7474
# Print it out
7575
print_report(report)
7676

77-
portfolio_report('../../Work/Data/portfolio.csv',
78-
'../../Work/Data/prices.csv')
77+
portfolio_report('Work/Data/portfolio.csv',
78+
'Work/Data/prices.csv')

Work/fileparse01.py

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# fileparse.py
2+
import csv
3+
4+
def parse_csv(filename, select=None, types=None, has_header=True, delimiter=',', silence_errors=False):
5+
'''
6+
Parse a CSV file into a list of records
7+
'''
8+
9+
# with open(filename) as f:
10+
headers = []
11+
indices = []
12+
records = []
13+
rows = csv.reader(filename, delimiter=delimiter)
14+
15+
if select and has_header==False:
16+
raise RuntimeError('select argument requires column headers')
17+
else:
18+
if has_header:
19+
# Read the file headers
20+
headers = next(rows)
21+
22+
# if a column selector was given, find indices of the specified columns.
23+
# Also narrow the set of headers used for resulting dictionaries
24+
if select:
25+
indices = [headers.index(colname) for colname in select]
26+
headers = select
27+
# else:
28+
# indices = []
29+
30+
for lineno, row in enumerate(rows):
31+
if not row:
32+
continue
33+
34+
try:
35+
# Types assignment
36+
if types:
37+
row = [func(val) for func, val in zip(types, row)]
38+
except Exception as err:
39+
if silence_errors==False:
40+
print('Row %s %s'% (lineno, err))
41+
42+
# Filter the row if specific columns were selected
43+
if indices:
44+
row = [row[index] for index in indices]
45+
46+
# Make a dictionary
47+
if has_header:
48+
record = dict(zip(headers, row))
49+
else:
50+
record = tuple(row)
51+
52+
records.append(record)
53+
54+
return records
55+

Work/foo.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
# foo.py
2+
3+
4+
class Foo(object):
5+
6+
x = 42
7+
8+
def __init__(self, b):
9+
self.b = b
10+
11+
def bar():
12+
return
13+
14+
15+
def spam():
16+
return

Work/pcost.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ def portfolio_cost(filename):
2323
if len(sys.argv) == 2:
2424
filename = sys.argv[1]
2525
else:
26-
filename = 'G:\GettingStarted_Can_Delete\practical-python\Work\Data\portfolio.csv'
26+
filename = 'Work\Data\portfolio.csv'
2727

2828
cost = portfolio_cost(filename)
2929
print('Total cost:', cost)

Work/pcost0.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# pcost0.py
2+
#
3+
# Exercise 1.27
4+
import csv
5+
import sys
6+
7+
def portfolio_cost(filename):
8+
'''Computes the total cost (shares*price) of a portfolio file'''
9+
total_cost = 0.0
10+
11+
with open(filename, 'rt') as f:
12+
rows = csv.reader(f)
13+
headers = next(rows)
14+
for rowno, row in enumerate(rows, start=1):
15+
record = dict(zip(headers, row))
16+
try:
17+
nshares = int(record['sharesim'])
18+
price = float(record['price'])
19+
total_cost += nshares * price
20+
except ValueError:
21+
print(f'Row {rowno}: Bad row: {row}')
22+
return total_cost
23+
24+
if len(sys.argv) == 2:
25+
filename = sys.argv[1]
26+
else:
27+
filename = 'Work\Data\portfolio.csv'
28+
29+
cost = portfolio_cost(filename)
30+
print('Total cost:', cost)

Work/report-c0.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import csv
2+
3+
def read_portfolio(filename):
4+
'''
5+
Read a stock portfolio file into a list of dictionaries with keys
6+
name, shares, and price
7+
'''
8+
9+
portfolio = []
10+
with open(filename) as f:
11+
rows = csv.reader(f)
12+
headers = next(rows)
13+
14+
for row in rows:
15+
record = dict(zip(headers, row))
16+
stock = {
17+
'name': record['name'],
18+
'shares': int(record['shares']),
19+
'price': float(record['price'])
20+
}
21+
portfolio.append(stock)
22+
return portfolio
23+
24+
ports = read_portfolio('work/data/portfolio.csv')
25+
for row in ports:
26+
# print(len(row))
27+
# print(row)
28+
# print(len(ports[0]))
29+
# print(len(row[1]))
30+
# print('%1s %10d %10f' % (row['name'], row['shares'], row['price']))
31+
print('%1s %10d %10f' % (row))

Work/report-c2.py

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
# pcost.py
2+
3+
import csv
4+
5+
def read_portfolio(filename):
6+
'''Compute the total cost (shares*price) of a portfolio file'''
7+
portfolio = []
8+
holding = {}
9+
10+
with open(filename, 'rt') as f:
11+
rows = csv.reader(f)
12+
headers = next(rows)
13+
for rowno, row in enumerate(rows, start=1):
14+
record = dict(zip(headers, row))
15+
try:
16+
holding = {
17+
'name': record['name'],
18+
'shares': int(record['shares']),
19+
'price': float(record['price'])
20+
}
21+
portfolio.append(holding)
22+
except ValueError:
23+
print(f'Row {rowno}: Bad row: {row}')
24+
25+
return portfolio
26+
27+
def read_prices(filename):
28+
29+
out = {}
30+
f=open(filename, 'r')
31+
rows = csv.reader(f)
32+
for row in rows:
33+
if len(row)>1 :
34+
out[row[0]] = float(row[1])
35+
36+
return out
37+
38+
def make_report(ports, price):
39+
sval = 0
40+
cval = 0
41+
report = []
42+
43+
# ports = read_portfolio(folioname)
44+
# price = read_prices(pricename)
45+
46+
for port in ports:
47+
stkval = port['shares'] * port['price']
48+
sval += stkval
49+
curval = price[port['name']] * port['shares']
50+
cval += curval
51+
# **using tuple
52+
lineval = (
53+
port['name'],
54+
port['shares'],
55+
port['price'],
56+
float(curval - stkval)
57+
)
58+
59+
# **using dict
60+
# lineval = {
61+
# 'name': port['name'],
62+
# 'shares': port['shares'],
63+
# 'price': port['price'],
64+
# 'change': float(curval - stkval)
65+
# }
66+
report.append(lineval)
67+
68+
return report
69+
70+
def print_report(report):
71+
72+
# report=cal_curr_price(folio_file, price_file)
73+
headers = ('Name', 'Shares', 'Price', 'Change')
74+
print('%10s %10s %10s %10s' %headers)
75+
print(('-' * 10 + ' ') * len(headers))
76+
for row in report:
77+
# **using tuple
78+
print('%10s %10d $%9.2f %10.2f' % row)
79+
80+
# **using dict
81+
# print('%10s %10d %10.2f %10.2f' %
82+
# (row['name'], row['shares'], row['price'], row['change']))
83+
return
84+
85+
portfolio = read_portfolio('work/data/portfolio.csv')
86+
prices = read_prices('work/data/prices.csv')
87+
report = make_report(portfolio, prices)
88+
print_report(report)
89+
# portfolio_report('work/data/portfolio.csv', 'work/data/prices.csv')
90+
91+

Work/reportc2.py

Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
# pcost.py
2+
3+
import csv
4+
import gzip
5+
from fileparse01 import parse_csv
6+
7+
#def read_portfolio(filename):
8+
# '''Compute the total cost (shares*price) of a portfolio file'''
9+
# portfolio = []
10+
# holding = {}
11+
#
12+
# with open(filename, 'rt') as f:
13+
# rows = csv.reader(f)
14+
# headers = next(rows)
15+
# for rowno, row in enumerate(rows, start=1):
16+
# record = dict(zip(headers, row))
17+
# try:
18+
# holding = {
19+
# 'name': record['name'],
20+
# 'shares': int(record['shares']),
21+
# 'price': float(record['price'])
22+
# }
23+
# portfolio.append(holding)
24+
# except ValueError:
25+
# print(f'Row {rowno}: Bad row: {row}')
26+
#
27+
# return portfolio
28+
#
29+
#
30+
#def read_prices(filename):
31+
#
32+
# out = {}
33+
# f=open(filename, 'r')
34+
# rows = csv.reader(f)
35+
# for row in rows:
36+
# if len(row)>1 :
37+
# out[row[0]] = float(row[1])
38+
#
39+
# return out
40+
41+
def make_report(ports, price):
42+
sval = 0
43+
cval = 0
44+
curval = 0
45+
report = []
46+
47+
# ports = read_portfolio(folioname)
48+
# price = read_prices(pricename)
49+
for port in ports:
50+
stkval = port['shares'] * port['price']
51+
sval += stkval
52+
53+
skey = port['name']
54+
rid = 0
55+
for idx, key in enumerate(price):
56+
if key[0] == skey:
57+
rid == idx
58+
break
59+
60+
curval = price[idx][1] * port['shares']
61+
cval += curval
62+
# **using tuple e
63+
lineval = (
64+
port['name'],
65+
port['shares'],
66+
port['price'],
67+
float(curval - stkval)
68+
)
69+
70+
# **using dict
71+
# lineval = {
72+
# 'name': port['name'],
73+
# 'shares': port['shares'],
74+
# 'price': port['price'],
75+
# 'change': float(curval - stkval)
76+
# }
77+
report.append(lineval)
78+
79+
return report
80+
81+
def print_report(report):
82+
83+
# report=cal_curr_price(folio_file, price_file)
84+
headers = ('Name', 'Shares', 'Price', 'Change')
85+
print('%10s %10s %10s %10s' %headers)
86+
print(('-' * 10 + ' ') * len(headers))
87+
for row in report:
88+
# **using tuple
89+
print('%10s %10d $%9.2f %10.2f' % row)
90+
91+
# **using dict
92+
# print('%10s %10d %10.2f %10.2f' %
93+
# (row['name'], row['shares'], row['price'], row['change']))
94+
return
95+
96+
def pf_report(portfile, pricefile):
97+
# portfolio = parse_csv(portfile, select=['name','shares','price'], types=[str, int, float])
98+
# prices = parse_csv(pricefile, types=[str, float], has_header=False)
99+
100+
with open(portfile, 'rt') as pf1:
101+
portfolio = parse_csv(pf1, select=['name','shares','price'], types=[str, int, float])
102+
103+
with open(pricefile, 'r') as pf2:
104+
prices = parse_csv(pf2, types=[str, float], has_header=False)
105+
106+
report = make_report(portfolio, prices)
107+
print_report(report)
108+
# portfolio_report('work/data/portfolio.csv', 'work/data/prices.csv')
109+
110+
def main(args):
111+
if len(args) != 3:
112+
raise SystemExit('Usage: %s portfile pricefile' % args[0])
113+
pf_report(args[1], args[2])
114+
115+
if __name__ == '__main__':
116+
import sys
117+
main(sys.argv)

0 commit comments

Comments
 (0)