Skip to content
🐍Portfolio as a Dictionary

Portfolio as a Dictionary

beginner Python 12 mindict.items()list comprehensions
What you'll learn
  • dict
  • .items()
  • list comprehensions
  • portfolio weights
  • concentration report

Data Structures - The Portfolio Dict

Scene: 9:02 am, your first week on the portfolio-management desk. The PM pings you: "Send me the current book - every ticker, its weight, its dollar allocation on our $100,000 sleeve, and flag anything at 20% or more. Five minutes." No spreadsheet is open. Good news: Python's dict was born for exactly this job.

Real portfolio management systems store positions in structured data. In Python, a dict naturally maps ticker β†’ weight.

🧠 The mental model: the fund's coat check

A dict is a coat check: hand over a tag ("AAPL") and you get back exactly one coat (0.30) - instantly, whether the rack holds five coats or five million. Five moves cover 90% of daily dict work:

You want...CodeFor our book
One position's weightportfolio["AAPL"]0.30
All tickersportfolio.keys()AAPL, MSFT, JPM, GS, SPY
All weightsportfolio.values()0.30, 0.25, 0.20, 0.15, 0.10
Ticker AND weight pairsportfolio.items()what your for loop needs
Total investedsum(portfolio.values())1.0 - fully invested

The one that trips up beginners: looping over a bare dict gives you keys only. When you need both the ticker and its weight, loop over .items() and unpack two variables: for ticker, weight in portfolio.items():.

Portfolio weights - the golden rule

For a fully-invested, unlevered fund, the weights must sum to 1:

code
Ξ£α΅’ wα΅’ = 1.0
Python
portfolio = {"AAPL": 0.30, "MSFT": 0.25, "JPM": 0.20, "GS": 0.15, "SPY": 0.10}
total = sum(portfolio.values())  # should be 1.0

And turning any weight into money takes one multiplication:

code
dollarsα΅’ = wα΅’ Γ— AUM        e.g. 0.30 Γ— 100,000 = 30,000

That tiny formula is the beating heart of every rebalancing system: a weight is a fraction of the pot; dollars are the fraction times the pot. Confusing the two is the classic units bug on trading desks.

List Comprehensions

Compact, readable, and fast:

Python
big_positions = [t for t, w in portfolio.items() if w >= 0.20]

Read it like a sentence: "for each ticker–weight pair in the book, if the weight is at least 20%, keep the ticker." Risk desks call this output a concentration report.


πŸ“œ Harry Markowitz and the 15 Pages That Changed Finance

1952: Harry Markowitz, a 25-year-old PhD student at the University of Chicago, published a 15-page paper titled "Portfolio Selection" in the Journal of Finance (vol. 7, pp. 77–91). It introduced a single revolutionary insight that every portfolio dictionary you will ever build is built upon:

"The return of a portfolio is the weighted average of its components' returns. But the risk of a portfolio is NOT the weighted average of their risks - it depends on correlations."

In other words: diversification has mathematical value. Before 1952, investors knew intuitively not to "put all eggs in one basket," but no one had proven it rigorously or quantified exactly how much risk diversification eliminates.

Markowitz's framework - now called Modern Portfolio Theory (MPT) - defined:

  • Expected return as the weighted average: ΞΌβ‚š = Ξ£ wα΅’ ΞΌα΅’
  • Portfolio variance as: Οƒβ‚šΒ² = Ξ£α΅’ Ξ£β±Ό wα΅’ wβ±Ό Οƒα΅’β±Ό (the cross-term captures correlations)
  • The efficient frontier: the set of portfolios with maximum return for a given risk

1958 - James Tobin (Nobel 1981) added the Separation Theorem: every rational investor holds the same risky portfolio - the tangency portfolio - blended with a risk-free asset in whatever mix suits their risk appetite. Which portfolio the tangency one is, Tobin did not say.

1964 - CAPM (Capital Asset Pricing Model, Sharpe/Lintner/Mossin) answered that: in equilibrium, when everyone runs Markowitz + Tobin, the tangency portfolio must be the whole market, cap-weighted. This equilibrium result - not Markowitz's 1952 frontier alone - is why passive index funds are the mathematical consequence of the theory, and why cap-weighting is optimal rather than lazy.

1990 - Nobel Prize jointly awarded to Markowitz, Sharpe, and Miller.

When you write {"AAPL": 0.30, "MSFT": 0.25}, you are implementing the core data structure of the theory that won a Nobel Prize and underpins the $15 trillion passive investment industry.


Your Task

The starter already prints the whole report - the weight check, the table, the TOTAL row and the concentration report all run. But look at the Allocation column when you execute it: every position shows $0. The placeholder line books each position's weight as if it were dollars - exactly the units bug described above.

Fix the single πŸ‘‰ YOUR TURN line so each row shows real money.

Predict before you run: JPM carries a 0.20 weight on $100,000 of AUM. After your one-line fix, what dollar figure should its row show? Do the mental arithmetic (0.20 Γ— 100,000), then run and confirm - and check that AAPL's 30% lands on exactly $30,000.