MCPcopy Create free account
hub / github.com/dabeaz-course/practical-python / Portfolio

Class Portfolio

Solutions/8_2/portfolio.py:6–47  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

4import stock
5
6class Portfolio:
7 def __init__(self):
8 self._holdings = []
9
10 @classmethod
11 def from_csv(cls, lines, **opts):
12 self = cls()
13 portdicts = fileparse.parse_csv(lines,
14 select=['name','shares','price'],
15 types=[str,int,float],
16 **opts)
17
18 for d in portdicts:
19 self.append(stock.Stock(**d))
20
21 return self
22
23 def append(self, holding):
24 self._holdings.append(holding)
25
26 def __iter__(self):
27 return self._holdings.__iter__()
28
29 def __len__(self):
30 return len(self._holdings)
31
32 def __getitem__(self, index):
33 return self._holdings[index]
34
35 def __contains__(self, name):
36 return any(s.name == name for s in self._holdings)
37
38 @property
39 def total_cost(self):
40 return sum(s.shares * s.price for s in self._holdings)
41
42 def tabulate_shares(self):
43 from collections import Counter
44 total_shares = Counter()
45 for s in self._holdings:
46 total_shares[s.name] += s.shares
47 return total_shares
48
49
50

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected