portfolio.py changed on this slide
1# portfolio.py — the ledger, organised into functions
2import math
3
4def position_value(shares, price):
5 """Value of one position, in CHF."""
6 print(shares * price)Shows the value, returns None
7
8def total_value(tickers, shares, price):
9 total = 0.0
10 for i in range(len(tickers)):
11 total += position_value(shares[i], price[tickers[i]])
12 return total
13
14def years_to_double(rate=0.05):
15 return math.ceil(math.log(2) / math.log(1 + rate))
16
17tickers = ["AAPL", "NESN", "VOO"]
18shares = [10, 4, 2]
19price = {"AAPL": 190.5, "NESN": 102.3, "VOO": 512.0}
20
21total = total_value(tickers, shares, price)
22print(f"total {total:,.2f}", round(total, 1))
23print(years_to_double(), years_to_double(rate=0.07))
24print(position_value(price=102.3, shares=4), sum(shares))
25print(", ".join(tickers).lower(), type(total_value))
$ python portfolio.py
1905.0
Traceback (most recent call last):
File "portfolio.py", line 21, in <module>
total = total_value(tickers, shares, price)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "portfolio.py", line 11, in total_value
total += position_value(shares[i], price[tickers[i]])
TypeError: unsupported operand type(s) for +=: 'float' and 'NoneType'