forked from dabeaz-course/python-mastery
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstock.py
102 lines (82 loc) · 2.57 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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# stock.py
from decimal import Decimal
class Stock:
_types = (str, int, float)
def __init__(self, name, shares, price):
name, shares, price = [func(val) for func, val in zip(self._types, [name, shares, price])]
self.name = name
self._shares = shares
self._price = price
@property
def shares(self):
return self._shares
@shares.setter
def shares(self, value):
if not isinstance(value, int):
raise TypeError('Expected int')
if value < 0:
raise ValueError('Shares must be >= 0')
self._shares = value
@property
def price(self):
return self._price
@price.setter
def price(self, value):
if not isinstance(value, float):
raise TypeError('Expected float')
if value < 0:
raise ValueError('Price must be >= 0')
self._price = value
@classmethod
def from_row(cls, row):
values = [func(val) for func, val in zip(cls._types, row)]
return cls(*values)
@property
def cost(self):
return self.shares * self.price
def sell(self, nshares):
self.shares -= nshares
# new subclass that inherits from Stock class
class DStock(Stock):
@property
def cost(self):
TWOPLACES = Decimal('0.01')
return Decimal(self.shares * self.price).quantize(TWOPLACES)
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[0], int(row[1]), float(row[2])))
portfolio.append(record)
return portfolio
# exercise C) modify to create objects using a class other than `Stock`
def read_portfolio_cust(filename, stock=Stock):
'''
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[0], row[1], row[2]))
portfolio.append(record)
return portfolio
def print_portfolio(portfolio):
'''
Make a nicely formatted table showing stock data
'''
print('%10s %10s %10s' % ('name', 'shares', 'price'))
print(('-' * 10 + ' ') * 3)
for s in portfolio:
print('%10s %10d %10.2f' % (s.name, s.shares, s.price))
if __name__ == '__main__':
portfolio = read_portfolio('Data/portfolio.csv')
print_portfolio(portfolio)