forked from dabeaz-course/python-mastery
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstock.py
40 lines (34 loc) · 1.04 KB
/
stock.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# stock.py
class Stock:
types = (str, int, float)
def __init__(self, name, shares, price):
self.name = name
self.shares = shares
self.price = price
@classmethod
def from_row(cls, row):
values = [func(val) for func, val in zip(cls.types, row)]
return cls(*values)
def cost(self):
return self.shares * self.price
def sell(self, nshares):
self.shares -= nshares
def read_portfolio(filename):
'''
Read a CSV file of stock data into a list of Stocks
'''
import csv
portfolio = []
with open(filename) as f:
rows = csv.reader(f)
headers = next(rows)
for row in rows:
record = Stock.from_row(row)
portfolio.append(record)
return portfolio
if __name__ == '__main__':
import tableformat
import reader
# portfolio = read_portfolio('../../Data/portfolio.csv')
portfolio = reader.read_csv_as_instances('../../Data/portfolio.csv', Stock)
tableformat.print_table(portfolio, ['name', 'shares', 'price'])