- list comprehension
- filter
- sorted
- enumerate
- momentum
- SMA
List Comprehensions — Concise Financial Filters
Scene: 7:58 am on the equity desk. Two minutes to the open, and the PM leans over: "Which names are trading above their 20-day average, ranked by momentum — go." The junior who reaches for a 12-line for-loop is still typing when the bell rings. The one who knows list comprehensions answers in one line.
A list comprehension is Python's most powerful one-liner. It replaces verbose for-loops with clean, readable expressions.
Syntax
Python# Basic comprehension squares = [x**2 for x in range(10)] # With filter (the "if" clause) evens = [x for x in range(10) if x % 2 == 0]
🧠 The mental model: a comprehension is a SQL query
If you have ever written a SQL query — and in finance, you will — you already know how to read a comprehension:
| SQL clause | Comprehension part | In this lesson |
|---|---|---|
| SELECT expression | (ticker, price / sma - 1) | what each result looks like |
| FROM table | for ticker, price, sma in stocks | where the rows come from |
| WHERE condition | if price > sma | which rows survive the screen |
Read it aloud: "give me ticker and momentum, for every stock, if it trades above its SMA." SELECT–FROM–WHERE, in Python clothes. One crucial rule follows: the filtering if comes after the for — and a comprehension without one is a screen with no criteria: every row gets through, bearish names included.
Finance Use Cases
Filter stocks above their SMA (buy signal):
Pythonbuy_candidates = [ticker for ticker, price, sma in stocks if price > sma]
Compute momentum (price / sma − 1) for each stock:
Pythonmomentum = [(ticker, price / sma - 1) for ticker, price, sma in stocks if price > sma]
Notice the second example does both jobs in one expression — transform every surviving row and screen out the bearish ones. That is the pattern professional stock screens are built on.
sorted() with a key function
Pythonranked = sorted(momentum, key=lambda x: x[1], reverse=True)
The key tells sorted() what to compare — here x[1], the momentum score inside each tuple — and reverse=True puts the strongest name first.
enumerate() — index + value together
Pythonfor rank, (ticker, mom) in enumerate(ranked, start=1): print(f"#{rank} {ticker}: {mom:.2%}")
Your Task
Six stocks, each priced against its 20-day SMA. The starter builds the momentum table, sorts it, and prints a ranked buy list — but the comprehension at its heart is missing its filter, so the "buy list" happily recommends stocks in a downtrend.
Predict before you run: scan the data — MSFT trades at 415.30 against an SMA of 418.90, and AMZN at 198.60 against 201.30. How many of the 6 stocks should survive a price > sma screen, and which name should top the ranking? Now run the starter as-is and watch the unfiltered screen flag 6 of 6 as bullish — then add the one clause that fixes it.