Name a price, a ticker and a share count, then value a position and a three-stock portfolio.
A variable is a name for a value. You create one with =, putting the name on the left and the value on the right.
Every value has a type. type(x) tells you which one. In this lesson I name three values, check their types, and then use them to price a single position and a portfolio of three holdings.
Step 1. Name a price, a ticker and a share count
Three values, three names. The three types here are float (a number with a decimal point), str (text in quotes) and int (a whole number).
price =185.40# a float: it has a decimal pointticker ="AAA"# a str: text, always in quotesshares =10# an int: a whole numberprint(price) # -> 185.4print(ticker) # -> AAAprint(shares) # -> 10print(type(price)) # -> <class 'float'>print(type(ticker)) # -> <class 'str'>print(type(shares)) # -> <class 'int'>
Python prints 185.4, not 185.40. Python drops the trailing zero.
The type decides what an operator does. * multiplies numbers and repeats text.
print(shares * price) # -> 1854.0print(type(shares * price)) # -> <class 'float'>shares_text ="10"# the same digits, but as textprint(shares_text *2) # -> 1010 <- text repeated, not doubledprint(type(shares_text *2)) # -> <class 'str'>
1854.0
<class 'float'>
1010
<class 'str'>
Mixing an int and a float gives a float. Repeating a str gives a longer str.
Step 2. Value a position, then a portfolio
A position is worth price times shares. Name the product too.
price =185.40# quoted price per shareshares =10# how many of them I holdposition = price * shares # what the holding is worth todayprint(position) # -> 1854.0
1854.0
A portfolio is the same calculation once per holding, plus a sum.
aapl_price =185.40# two names per holding: a priceaapl_shares =10# and a share countmsft_price =410.20# the dearest share of the threemsft_shares =4nvda_price =128.75# the cheapest sharenvda_shares =20# but the largest number heldaapl_value = aapl_price * aapl_shares # one position value per holdingmsft_value = msft_price * msft_sharesnvda_value = nvda_price * nvda_sharesprint(aapl_value) # -> 1854.0print(msft_value) # -> 1640.8print(nvda_value) # -> 2575.0total = aapl_value + msft_value + nvda_value # the three positions added upprint(total) # -> 6069.8
1854.0
1640.8
2575.0
6069.8
Divide each holding by the total to get its weight. Weights are fractions of one, so they add to 1.
DDD has the lowest price of the three and the largest weight, because I hold the most shares of it.
Your turn
Buy 15 shares of EEE at 178.30. Add the position to the portfolio above, then print the new total and EEE’s weight rounded to four decimals.
TipShow answer
amzn_price =178.30# the new holdingamzn_shares =15amzn_value = amzn_price * amzn_shares # priced the same way as the othersprint(amzn_value) # -> 2674.5new_total = total + amzn_value # total already holds the first threeprint(new_total) # -> 8744.3print(round(amzn_value / new_total, 4)) # -> 0.3059