Objective
Research code spends most of its time applying the same arithmetic to millions of numbers. NumPy is fast because an ndarray is one contiguous block of memory holding values of one type, and its operations run as compiled loops over that block. A Python for loop instead handles one boxed object per iteration, with type checks and reference counting each time. Vectorising means expressing the computation as whole-array operations so the loop runs in C. By the end you should be able to predict the shape of any broadcast, say whether an expression copies data, and explain why a rewrite is or is not faster.
Arrays and dtypes
An array is a data pointer plus dtype, shape and strides (bytes to step along each axis). The dtype is fixed for the whole array, which has consequences:
import numpy as np
a = np.array([1, 2, 3])
print(a.dtype, (a / 2).dtype, (a // 2).dtype) # int64 float64 int64
print(np.array([1, 2.5]).dtype) # float64: ints are upcast
print(np.array([1, "a"]).dtype) # <U21: everything became a string
x = np.array([2**62], dtype=np.int64)
print(x * 2, x * 4) # [-9223372036854775808] [0]
- Fixed-width integers wrap silently. Unlike a Python
int, anint64element overflows past with no error. Share counts times prices in nanodollars, or products of large integer IDs, can hit this. - Mixed input is upcast to a type that holds everything; one string turns a numeric array into a string array, and
dtype=objectarrays lose all the speed. - Booleans are numbers:
mask.sum()countsTruevalues andmask.mean()gives a fraction. - Memory is
size × itemsize: a 10,000-day by 5,000-stockfloat64panel is bytes = 400 MB, and every temporary in an expression costs the same again.
Broadcasting rules
When two arrays meet in an elementwise operation, NumPy compares their shapes from the last axis backwards:
- If one array has fewer dimensions, its shape is padded with 1s on the left.
- Along each axis the sizes must be equal, or one of them must be 1.
- An axis of size 1 is stretched (without copying) to match the other.
So (5, 1) + (3,) becomes (5, 1) + (1, 3), giving (5, 3). That is useful for outer operations (v - v[:, None] is the matrix of all pairwise differences) and dangerous when you meant an elementwise operation between a column and a row: a length- vector minus an column is an matrix, not an error.
Axis arguments
axis=k means "collapse axis ". For a returns matrix R of shape (T, N), days by assets, R.mean(axis=0) has shape (N,) (one mean per asset over time) and R.mean(axis=1) has shape (T,) (one cross-sectional mean per day).
R = np.arange(12.0).reshape(4, 3) # 4 days, 3 assets
print(R.mean(axis=0)) # [4.5 5.5 6.5]
print(R.mean(axis=1)) # [ 1. 4. 7. 10.]
R - R.mean(axis=0) # (4, 3) - (3,): fine, demeans each column
R - R.mean(axis=1) # ValueError: shapes (4,3) (4,) do not broadcast
R - R.mean(axis=1, keepdims=True) # (4, 3) - (4, 1): demeans each row
Subtracting per-column statistics works by accident of the rules (the trailing axis lines up); per-row statistics need keepdims=True or [:, None]. A square matrix is the worst case: with the wrong version broadcasts without error and silently subtracts row means from columns.
Worked example
cross-sectional z-scores and portfolio returns
R holds 3 days of returns for 4 stocks. Compute each day's cross-sectional z-score (subtract that day's mean across stocks, divide by that day's standard deviation) without a loop, then the daily return of a portfolio with weights [0.4, 0.3, 0.2, 0.1].
R = np.array([[ 0.01, 0.03, -0.02, 0.00],
[ 0.02, -0.01, 0.01, 0.04],
[-0.03, 0.00, 0.02, 0.01]])
Show solutionHide solution
The statistics are per day, so they collapse the stock axis (axis=1), and they must stay as (3, 1) columns to broadcast back against (3, 4):
mu = R.mean(axis=1, keepdims=True) # shape (3, 1)
sd = R.std(axis=1, ddof=1, keepdims=True) # shape (3, 1)
Z = (R - mu) / sd # (3, 4) op (3, 1) -> (3, 4)
print(Z.round(3))
# [[ 0.24 1.201 -1.201 -0.24 ]
# [ 0.24 -1.201 -0.24 1.201]
# [-1.389 -0. 0.926 0.463]]
print(Z.std(axis=1, ddof=1)) # [1. 1. 1.]
w = np.array([0.4, 0.3, 0.2, 0.1])
print(R @ w) # [ 0.009 0.011 -0.007]
Check day 1 by hand: the mean is , deviations are , the sample variance is , so and the first z-score is . Each row of Z has mean 0 and sample standard deviation 1, as it must.
The portfolio return is a matrix–vector product: R @ w is (3, 4) @ (4,) -> (3,). Day 1: . Writing (R * w).sum(axis=1) gives the same numbers but builds a (3, 4) temporary; @ calls BLAS directly.
(The -0. on day 3 is a rounding residue: that day's computed mean is rather than exactly 0, so the zero return gets a z-score of about . It is harmless.)
Views versus copies
Basic slicing (a[1:4], a[:, 0], a[::2]) returns a view: a new header over the same memory, so writes through it change the original. Fancy indexing (an integer list or array) and boolean masks return copies. reshape and .T return views when the memory layout allows it.
a = np.arange(6)
s = a[1:4]; s[0] = 100 # view: a is now [0 100 2 3 4 5]
f = a[[1, 2]]; f[0] = -1 # copy: a is unchanged
print(np.shares_memory(a, s), np.shares_memory(a, f)) # True False
The asymmetry matters in both directions. A view of one column of a large array keeps the whole array alive in memory, and modifying a "slice for a quick experiment" corrupts the source data. Call .copy() when you need independence. Note the one exception for masks: assignment through a mask, a[a > 3] = 0, does write into a; it is extraction, b = a[a > 3], that copies.
Boolean masks
Masks replace if inside loops. np.where(cond, x, y) is the vectorised ternary, r[r > 0].mean() averages the up days, and np.select handles several conditions. Combine masks with &, | and ~, with parentheses: & binds tighter than >, so x > 1 & x < 4 parses as the chained comparison x > (1 & x) < 4 and raises "truth value of an array is ambiguous". Write (x > 1) & (x < 4). Python's and/or do not work on arrays at all.
Worked example
maximum drawdown without a loop
The maximum drawdown of a price path is . Write it as a loop and vectorised, check both on [100, 110, 99, 105, 120, 90, 95], and compare speed on a million prices.
Show solutionHide solution
The running maximum is a cumulative operation, and every ufunc has an .accumulate method: np.maximum.accumulate is the vectorised running peak.
import timeit
import numpy as np
def max_drawdown_loop(prices):
peak, worst = prices[0], 0.0
for p in prices:
peak = max(peak, p)
worst = min(worst, p / peak - 1)
return worst
def max_drawdown_vec(prices):
peak = np.maximum.accumulate(prices)
return (prices / peak - 1).min()
p = np.array([100, 110, 99, 105, 120, 90, 95])
print(max_drawdown_loop(p), max_drawdown_vec(p)) # -0.25 -0.25
rng = np.random.default_rng(0)
prices = 100 * np.exp(np.cumsum(rng.normal(0, 0.01, 1_000_000)))
t_loop = min(timeit.repeat(lambda: max_drawdown_loop(prices), number=1, repeat=3))
t_vec = min(timeit.repeat(lambda: max_drawdown_vec(prices), number=1, repeat=3))
print(f"loop {t_loop*1e3:.0f} ms, vectorised {t_vec*1e3:.1f} ms")
# loop 205 ms, vectorised 6.6 ms (one laptop; about 30x)
On the small path the running peak is [100, 110, 110, 110, 120, 120, 120], and the worst ratio is . On a million prices the vectorised version was about 30 times faster on one machine. The exact ratio depends on hardware; the order of magnitude does not. Iterating over a NumPy array element by element is no faster than over a list, because each element is boxed into a new scalar object.
Not every loop vectorises. A recursion whose state depends nonlinearly on its previous value (an EWMA with a reset rule, a stop-loss that changes position) has no whole-array form. Options are scipy.signal.lfilter for linear recursions, a compiled loop (Numba, Cython, C++), or accepting the Python loop over a small dimension while vectorising over a large one (loop over 250 days, vectorise over 3,000 stocks).
Reasoning about performance
For large arrays, simple elementwise operations are limited by memory bandwidth, not arithmetic. The cost of a * b + c is roughly the bytes read and written, and it allocates a full-size temporary for a * b before adding c. Useful rules:
- Count passes over memory. A chain of five elementwise operations makes five passes and four temporaries. In-place forms (
x *= 2,np.multiply(a, b, out=a)) avoid allocation when the inputs may be overwritten. - Never grow an array in a loop.
np.appendcopies the whole array each time, so building elements costs . Preallocate withnp.empty(n)or collect a list and convert once. - Vectorise the big dimension. Loop overhead is about tens of nanoseconds per Python-level step; it is irrelevant over 10 iterations and dominant over .
- Mind the layout. Arrays are row-major (C order) by default, so reducing along the last axis reads contiguous memory. Strided access across a huge first axis is slower.
- Use the right primitive.
@andnp.linalgcall optimised multithreaded BLAS;np.searchsorted,np.cumsum,np.bincountandufunc.accumulate/.reduceatcover most "loops with state" in research code. - Measure with
timeit(taking the minimum of repeats) before and after; guesses about speed are often wrong.
Knowledge check
What is the shape of np.zeros((5, 1)) + np.zeros(3)?
Knowledge check
a = np.arange(10). Which of these creates a new array whose modification will NOT change a?
Knowledge check
R has shape (250, 500): 250 days by 500 stocks. Which expression gives each stock's mean return over time?
Knowledge check
A loop builds a signal array of length n with sig = np.append(sig, value) at each step. What is the total cost, and the fix?
Key takeaways
- An array has one dtype;
int64wraps silently, mixed inputs are upcast, andobjectarrays are slow. - Broadcasting aligns shapes from the right; size-1 axes stretch. Use
keepdims=Trueor[:, None]for per-row statistics, and beware square matrices that hide mistakes. axis=kcollapses axis : for a(T, N)panel,axis=0is per asset,axis=1is per day.- Slices are views; fancy and boolean indexing return copies; mask assignment writes in place.
- Combine masks with
&,|,~and parentheses. Useufunc.accumulatefor running maxima and minima. - Large elementwise work is memory-bound: count passes and temporaries, preallocate, vectorise the big dimension, and measure.
Practice problems
Finished reading?
Answer the 4 knowledge checks to complete this lesson (0 done).