A column of 6,700 prices sits in one block of memory. The slow way to compute returns is to pull the prices out into Python objects and loop. The fast way is to hand the whole block to a function written in compiled code that walks it in one go. Arrow ships hundreds of those functions, called kernels, and using them is the difference between code that keeps up with the data and code that does not.
The idea in plain words
Where we are. Topic 2 produced tables and batches; this one computes on them. The kernels here are the same ones DuckDB, Polars and pandas call underneath when they hold Arrow data, so what you learn is also what those libraries do for you. Topic 4 looks at the memory that makes these loops so fast.
A function in compiled code that takes whole arrays and returns a whole array or a scalar, handling nulls itself. One call replaces a Python loop and runs over contiguous memory, so it is typically far faster.
Whole columns in, whole columns out
To get a return you need each price next to the previous one. Slicing does that without copying: close.slice(1) is the prices from the second on, close.slice(0, n - 1) is the prices up to the second to last, and the two line up element by element. One divide and one subtract then produce the whole return column. The result is one element shorter than the input, because the first price has no predecessor.
# KO's closing prices in, KO's daily returns out, in a handful of kernel callsreturns = daily_returns(ko["close"])print("prices:", len(ko["close"]), "| returns:", len(returns))print("best day :", round(pc.max(returns).as_py(), 4))print("worst day:", round(pc.min(returns).as_py(), 4))print("mean :", round(pc.mean(returns).as_py(), 6))
prices: 6699 | returns: 6698 best day : 0.1387 worst day: -0.1006 mean : 0.000313
Filter, group and sort are kernels too
Selecting rows is a two-step: a comparison kernel makes a boolean mask, and filter keeps the rows where it is true. Grouping and sorting follow the same style. above finds the heavy trading days, total_by adds volume per symbol, and top_rows picks the biggest prices. Each is a few lines and none of them touches a Python value until the small answer is read at the end.
# Heavy days, volume per symbol, and the three highest closesprint("days above 500M shares:", above(table, "volume", 500_000_000).num_rows)print(total_by(table, "symbol", "volume"))top = top_rows(table, "close", 3)print(list(zip(top["symbol"].to_pylist(), top["close"].to_pylist())))
days above 500M shares: 2055
{'AAPL': 2863818765894, 'JNJ': 76321726041, 'JPM': 163036003862, 'KO': 127779316463, 'XOM': 167184796142}
[('JPM', 365.18), ('JPM', 363.25), ('JPM', 363.11)]for p in close.to_pylist() copies every value into a Python object first, so even a correct loop pays for the copy and then the loop. If a calculation seems to need one, look for the kernel that does it, or build it from slices and arithmetic as daily_returns does. Check pc. completions before writing a loop.
What the tasks ask
- 1`daily_returns`
pc.subtract(pc.divide(close.slice(1), close.slice(0, n - 1)), 1.0). - 2`above` and `top_rows`
table.filter(pc.greater(table[column], threshold));table.sort_by([(column, "descending")]).slice(0, n). - 3`total_by`
table.group_by(key).aggregate([(value, "sum")]), sort by the key, then read the two columns into a dict.
daily_returns written with close.slice(1) and close.slice(0, n - 1) instead of a loop over positions?Lab · what's graded
4 tasks · 100 pts- Returns from prices:
daily_returns25 pts - Filter with a mask:
above25 pts - Group and total:
total_by25 pts - The largest rows:
top_rows25 pts