| 1 | # portfolio.py |
| 2 | |
| 3 | class Portfolio: |
| 4 | def __init__(self, holdings): |
| 5 | self._holdings = holdings |
| 6 | |
| 7 | def __iter__(self): |
| 8 | return self._holdings.__iter__() |
| 9 | |
| 10 | def __len__(self): |
| 11 | return len(self._holdings) |
| 12 | |
| 13 | def __getitem__(self, index): |
| 14 | return self._holdings[index] |
| 15 | |
| 16 | def __contains__(self, name): |
| 17 | return any(s.name == name for s in self._holdings) |
| 18 | |
| 19 | @property |
| 20 | def total_cost(self): |
| 21 | return sum(s.shares * s.price for s in self._holdings) |
| 22 | |
| 23 | def tabulate_shares(self): |
| 24 | from collections import Counter |
| 25 | total_shares = Counter() |
| 26 | for s in self._holdings: |
| 27 | total_shares[s.name] += s.shares |
| 28 | return total_shares |
| 29 | |
| 30 | |
| 31 | |