Try each task in your workspace first. Open a solution only when your code runs, or when you have been stuck for a while. Your solution can be different and still right: compare what it prints. The reading tasks and their answers are on the Questions page.
Writing tasks
Task 6 · a dict comprehension
In ONE dict comprehension over ledger.items(), build: each ticker → its change from the first to the last price, in percent, rounded to 2 decimals. Print it.
Show the solution
change = {t: round((d["prices"][-1] - d["prices"][0]) / d["prices"][0] * 100, 2)
for t, d in ledger.items()}
print("Task 6:", change)
It prints:
Task 6: {'AAPL': 2.97, 'NESN': -1.73, 'VOO': 1.39}
Loop part first (for t, d in ledger.items()), then the key: value you keep. Write it as a loop first if the one-liner does not come; both are fine.
Task 7 · sort by yesterday's return
Sort the tickers of ledger by their LAST daily return (last price / the price before it − 1), largest first. Use sorted with key= and a lambda.
Show the solution
order = sorted(ledger, reverse=True,
key=lambda t: ledger[t]["prices"][-1] / ledger[t]["prices"][-2] - 1)
print("Task 7:", order)
It prints:
Task 7: ['AAPL', 'VOO', 'NESN']
sorted(ledger) goes over the keys, the tickers. key= says what to compare for each ticker: here its last return (AAPL +1.22 %, VOO +0.41 %, NESN −0.68 %). reverse=True puts the largest first.
Task 8 · the portfolio on every day, no loop
With broadcasting: compute the value of every position on every day (a 3 × 3 array), then the portfolio total per day (one number per day), then the portfolio's daily return in percent, rounded to 2. No loops. Check one number by hand: AAPL on day 0 is 10 × 185 = 1850.
Show the solution
history = shares[:, None] * prices # (3, 1) × (3, 3): shares stretched across the days
per_day = history.sum(axis=0) # collapse the rows: one total per day
daily_return = (per_day[1:] / per_day[:-1] - 1) * 100
print("Task 8:", per_day, daily_return.round(2))
It prints:
Task 8: [3276.4 3313.8 3338.2] [1.14 0.74]
shares[:, None] makes shares a column, so it multiplies each ROW (position). axis=0 squeezes the rows away: one number per day. The two shifted slices per_day[1:] / per_day[:-1] give each day over the day before. Without [:, None], the shares would multiply the columns (days) instead, silently.
Task 9 · which positions rose every day?
Compute the daily returns of every position (a 3 × 2 array, two shifted slices). Then, with a mask and axis, find the tickers whose return was positive on BOTH days. Print them as a list.
Show the solution
returns = prices[:, 1:] / prices[:, :-1] - 1
up_days = (returns > 0).sum(axis=1) # True counts as 1: up days per position
print("Task 9:", tickers[up_days == 2].tolist())
It prints:
Task 9: ['AAPL', 'VOO']
returns > 0 is a grid of True/False; summing along axis=1 counts the up days of each row: [2, 0, 2]. That comparison is itself a mask, used to pick from tickers. Three lines, no loop.
Task 10 · two pandas questions
(a) The tickers of the TECH positions worth more than 1000 CHF, as a list. Two conditions: use &, with parentheses. (b) The total value per sector, largest first, as a dict.
Show the solution
tech_big = df[(df["sector"] == "tech") & (df["value"] > 1000)]
print("Task 10a:", tech_big["ticker"].tolist())
by_sector = df.groupby("sector")["value"].sum().sort_values(ascending=False)
print("Task 10b:", by_sector.to_dict())
It prints:
Task 10a: ['AAPL', 'MSFT']
Task 10b: {'tech': 3135.0, 'fund': 1024.0, 'food': 409.2}
and fails on a Series (many True/False values, not one); & works element by element, and needs the parentheses because & binds tighter than ==. The chain in (b) reads: group by sector, take value, sum, sort.
★ Harder: classic puzzles
★ Task 11 · Rebase every row to 100 (numpy-100 style)
Divide every row by its own day-0 price and multiply by 100, so each position starts at 100. One line, with broadcasting: the day-0 column must keep its column shape. Round to 2 and print as a list.
Show the solution
rebased = prices / prices[:, [0]] * 100 # [:, [0]] keeps shape (3, 1); [:, 0] would be (3,)
print("Task 11:", rebased.round(2).tolist())
It prints:
Task 11: [[100.0, 101.73, 102.97], [100.0, 98.94, 98.27], [100.0, 100.97, 101.39]]
prices[:, 0] has shape (3,) and would broadcast as a ROW, dividing day by day by the wrong numbers. prices[:, [0]] (a list of one column) or prices[:, 0][:, None] keeps (3, 1), a column. Rebasing to 100 is how every chart compares assets with different prices.
★ Task 12 · Tickers traded more than once (LeetCode pandas: duplicates)
A table of trades. Which tickers appear more than once? Use value_counts() and a mask on the result. Then, as a second line, the net quantity per ticker with groupby.
Show the solution
trades = pd.DataFrame({"ticker": ["AAPL", "NESN", "AAPL", "VOO", "MSFT", "AAPL", "VOO"],
"qty": [5, 2, -3, 1, 4, 2, -1]})
counts = trades["ticker"].value_counts()
print("Task 12:", counts[counts > 1].index.tolist())
print("Task 12:", trades.groupby("ticker")["qty"].sum().to_dict())
It prints:
Task 12: ['AAPL', 'VOO']
Task 12: {'AAPL': 4, 'MSFT': 4, 'NESN': 2, 'VOO': 0}
value_counts() is session 3's counting dict, in one call, sorted by count. A mask on a Series keeps the entries that pass; .index gives their labels. groupby + sum is session 4's net_positions, in one line.
★ Task 13 · Moving average with cumsum (numpy-100 classic)
Session 4's moving_average needed a loop. numpy-100's trick needs none: take np.cumsum of the prices, subtract the cumsum shifted by k, divide by k. Do it for the week's closes with k = 3, round to 2, and compare with session 4's answer [190.5, 188.7, 190.1, 191.7, 194.67].
Show the solution
closes = np.array([190.5, 187.2, 193.8, 185.1, 191.4, 198.6, 194.0])
k = 3
c = np.cumsum(closes)
c[k:] = c[k:] - c[:-k] # sum of each window of k
print("Task 13:", (c[k - 1:] / k).round(2))
It prints:
Task 13: [190.5 188.7 190.1 191.7 194.67]
cumsum[i] is the sum of everything up to day i; subtracting the cumsum k days earlier leaves exactly the last k days. The first full window ends at position k − 1. Same answer as the loop, one pass, no Python loop: that is what "vectorised" buys.
★ Task 14 · Maximum drawdown, vectorised
Session 4's max_drawdown kept the running peak in a loop. np.maximum.accumulate(a) gives the running maximum of an array in one call. Use it to compute the worst drawdown of the closes in one or two lines; print it as a percentage with 2 decimals. It must match session 4: -4.49%.
Show the solution
closes = np.array([190.5, 187.2, 193.8, 185.1, 191.4, 198.6, 194.0])
peak = np.maximum.accumulate(closes) # [190.5 190.5 193.8 193.8 193.8 198.6 198.6]
drawdown = (closes - peak) / peak
print("Task 14:", f"{drawdown.min() * 100:.2f}%")
It prints:
Task 14: -4.49%
The running peak as an array, then the fall from it for every day at once, then the minimum. Reading np.maximum.accumulate from its name and its output is exactly the skill of this session: help(np.maximum.accumulate), or print it.
Extra practice
Practice 1 · apply or np.where
Label each row of df "large" if its value is above 1500, otherwise "small", twice: once with .apply and a lambda (as in the lecture), once with np.where. Check that both give the same list.
Show the solution
a = df["value"].apply(lambda v: "large" if v > 1500 else "small").tolist()
b = np.where(df["value"] > 1500, "large", "small").tolist()
print(a, a == b)
It prints:
['large', 'small', 'small', 'small'] True
.apply calls a Python function once per value; np.where decides for the whole column at once. Same answer; on a million rows, np.where is the one that finishes quickly.
Practice 2 · Positions never traded (LeetCode pandas: customers who never order)
Today's trades were only in AAPL and VOO. Which positions of df were not traded? Use .isin() and ~ (not, element by element).
Show the solution
traded = ["AAPL", "VOO"]
print(df[~df["ticker"].isin(traded)]["ticker"].tolist())
It prints:
['MSFT', 'NESN']
isin gives True where the ticker is in the list; ~ flips it. This is LeetCode's "Customers Who Never Order" in the ledger world.
Practice 3 · Compound the daily returns
From the week's closes, compute the daily returns (two shifted slices), then compound them with np.cumprod(1 + returns). Show that the last value equals last price / first price, and print the week's return in percent.
Show the solution
closes = np.array([190.5, 187.2, 193.8, 185.1, 191.4, 198.6, 194.0])
returns = closes[1:] / closes[:-1] - 1
growth = np.cumprod(1 + returns)
print(round(growth[-1], 6), round(closes[-1] / closes[0], 6), round((growth[-1] - 1) * 100, 2))
It prints:
1.018373 1.018373 1.84
Returns multiply, they do not add: (1 + r1)(1 + r2)… telescopes to last / first. Adding the daily returns would be close, but wrong.