Skip to content
LeetQuant
QD02 Python Software Engineering

QD02 · Python Software Engineering · Lesson 5 of 5

Scientific Computing Libraries

What NumPy, pandas and SciPy are each for in an engineered codebase, memory layout and strides, avoiding hidden copies at library boundaries, and when to drop to Numba, Cython or C++.

16 min

Objective

This lesson takes the developer's view of the scientific stack: which library owns which job in a codebase, how array memory layout decides speed, where copies hide when data crosses a library boundary, and how to decide whether a hot loop should move to compiled code. It assumes the NumPy, pandas and SciPy basics (broadcasting, views versus copies, rolling windows, optimisers) from the QR01 module. Outputs are from NumPy 2.4, pandas 3.1 and SciPy 1.17.

Who does what

LibraryOwnsCost model
NumPytyped n-dimensional arrays, ufuncs, reductions, BLAS/LAPACK linear algebra, random generatorseach call has microseconds of fixed overhead, then runs a compiled loop
pandaslabelled data: time indexes, alignment on join, groupby, resampling, missing data, file I/Omore overhead per call than NumPy (index handling, dtype checks); fast on whole columns, very slow row by row
SciPyalgorithms on arrays: optimize, stats, signal, sparse, interpolate, integrate, linalgcompiled (Fortran, C, C++) underneath

An engineering rule follows from the cost column: use pandas at the edges and NumPy in the kernels. Load, align, clean and label with pandas; hand contiguous NumPy arrays to the numerical core; wrap the result back in a Series or DataFrame with the original index. The core then has typed, testable signatures (NDArray[np.float64] in, out) and no hidden alignment.

Memory layout and strides

An array is a pointer to a block of memory plus a dtype, a shape and strides: how many bytes to step to move one position along each axis.

import numpy as np

a = np.arange(12, dtype=np.float64).reshape(3, 4)
print(a.strides, a.flags["C_CONTIGUOUS"])
print(a.T.strides, a.T.flags["C_CONTIGUOUS"], a.T.flags["F_CONTIGUOUS"])
print(a[:, 1].strides)

t = a.T.reshape(-1)
print(np.shares_memory(a, t), np.shares_memory(a, a.reshape(-1)))
(32, 8) True
(8, 32) False True
(32,)
False True

The default is C order (row-major): moving along a row steps 8 bytes, moving down a column steps a whole row of 32 bytes. Transposing swaps the strides and copies nothing, giving an F-order (column-major) view. A column slice is a view with stride 32, so it is not contiguous. Flattening the original is a view, but flattening the transpose must produce elements in an order that no single stride can describe, so reshape silently copies.

Strides matter because memory is fetched in cache lines of 64 bytes. Reading contiguously uses all eight doubles in each line; reading with a stride of a full row uses one and wastes seven.

Worked example

the same sum, five to eight times slower

A 4,000 × 4,000 float64 matrix (128 MB) is summed one row at a time, and separately one column at a time, in both C and F order. Predict which combinations are fast.

import timeit

import numpy as np

rng = np.random.default_rng(0)
c = rng.standard_normal((4000, 4000))      # C order: rows contiguous
f = np.asfortranarray(c)                   # same values, columns contiguous

def by_rows(x):
    return sum(x[i, :].sum() for i in range(x.shape[0]))

def by_cols(x):
    return sum(x[:, j].sum() for j in range(x.shape[1]))

for name, fn, x in [("C rows", by_rows, c), ("C cols", by_cols, c),
                    ("F rows", by_rows, f), ("F cols", by_cols, f)]:
    t = min(timeit.repeat(lambda: fn(x), number=3, repeat=5)) / 3
    print(f"{name}: {t * 1e3:6.1f} ms")
Show solution
C rows:    7.0 ms
C cols:   54.0 ms
F rows:   60.1 ms
F cols:    7.7 ms

The work is identical (16 million additions); only the access pattern differs. Iterating along the contiguous axis (rows of a C array, columns of an F array) is about 7 to 8 times faster than striding across it. Across repeated runs the slow cases were 5 to 8 times slower, depending on cache state.

Practical consequences:

  • Lay out data so the hot loop runs along the last axis of a C array. For a panel of TT days by NN stocks, cross-sectional operations (across stocks on each day) are contiguous in a (T, N) C array; per-stock time-series operations are contiguous in (N, T).
  • A pandas DataFrame stores each column contiguously, so df.to_numpy() on a single-dtype frame is an F-order array; per-column work is the fast direction.
  • Compiled code (a C extension, Numba, BLAS) often requires or assumes contiguity. np.ascontiguousarray(x) returns x unchanged if it is already C-contiguous and copies otherwise, so call it once at the boundary rather than letting each call copy.
  • Halving the dtype to float32 halves memory traffic (128 MB to 64 MB here) and is common for large ML feature matrices, at the cost of precision; keep prices, P&L and accumulations in float64.

Hidden copies at library boundaries

Most performance and memory surprises in a well-vectorised codebase come from copies nobody asked for. The ones to know:

import numpy as np
import pandas as pd

a = np.zeros(1_000_000)
print(np.shares_memory(a, np.asarray(a)), np.shares_memory(a, np.array(a)))
print(np.shares_memory(a, a.astype(np.float64)), np.shares_memory(a, a.astype(np.float64, copy=False)))

df = pd.DataFrame({"x": np.ones(5), "y": np.zeros(5)})
v = df.to_numpy()
print(v.flags["F_CONTIGUOUS"], v.flags["WRITEABLE"], np.shares_memory(v, df["x"].to_numpy()))
print(pd.DataFrame({"x": np.ones(3), "n": np.arange(3)}).to_numpy().dtype)
True False
False True
True False True
float64
  • np.asarray passes an existing array through; np.array copies by default. Use asarray at function entry to accept lists or arrays without copying arrays.
  • astype copies even when the dtype already matches, unless you pass copy=False.
  • df.to_numpy() on a single-dtype frame is a read-only view in pandas 3 (Copy-on-Write protects the frame), and it is F-ordered. Writing into it raises; ask for to_numpy(copy=True) if you need a writable array.
  • A frame with mixed dtypes cannot be one view: to_numpy() builds a new array in a common dtype (here the integers become float64; mixing in strings gives object, which is slow everywhere).
  • Chained elementwise expressions allocate a full-size temporary per operation; for very large arrays, out= arguments and in-place operators avoid that, as QR01 described.

A useful habit in code review: for every array that crosses a function or library boundary, ask "is this a view or a copy, and is it contiguous?" np.shares_memory and .flags answer it in tests.

When to drop below NumPy

Some loops have no whole-array form: a recursion whose next state depends on the previous one (an EWMA, a position with a stop-loss, an order-book update), or a branchy algorithm over each element. Work down this ladder and stop at the first rung that is fast enough:

  1. A better algorithm. An O(nw)O(n w) rolling window recomputed each step becomes O(n)O(n) with running sums.
  2. An existing compiled primitive. np.cumsum, np.maximum.accumulate, np.searchsorted, scipy.signal.lfilter (any linear recursion), scipy.ndimage filters. Often the "unvectorisable" loop is one of these in disguise.
  3. Numba. Decorate a plain-Python numeric function with @numba.njit and it is compiled through LLVM on first call to machine code that runs at roughly C speed. Best for loops over NumPy arrays and scalars; it does not speed up code that uses pandas, dicts of objects or arbitrary libraries, and the first call pays the compile time.
  4. Cython. Python with C type declarations, compiled ahead of time into an extension module. Good for wrapping an existing C library or shipping a compiled package without a JIT dependency, at the cost of a build step.
  5. C++ with pybind11 or nanobind. Write the kernel in C++ and expose it to Python. Choose this when the same code must also run inside a C++ production system (one implementation for research and trading), when you need fine control of memory and threads, or for latency-critical paths.

The cost of each rung is build complexity, a second language to review, and harder debugging. Moving one kernel down is common; moving orchestration code down rarely pays, because by Amdahl's law it is not where the time is.

Worked example

an EWMA variance three ways

The RiskMetrics variance estimate is st=λst−1+(1−λ)rt2s_t = \lambda s_{t-1} + (1 - \lambda) r_t^2 with λ=0.94\lambda = 0.94. Compute it for a million returns with a Python loop, then without one, and compare with a compiled loop.

Show solution

Rearranged, st−λst−1=(1−λ)rt2s_t - \lambda s_{t-1} = (1 - \lambda) r_t^2: a first-order linear filter with numerator [1 - lam] and denominator [1, -lam], which is exactly what lfilter computes. Its initial-state argument zi contributes λs0\lambda s_0 to the first output, which gives s1=λs0+(1−λ)r12s_1 = \lambda s_0 + (1 - \lambda) r_1^2 as required.

import timeit

import numpy as np
from scipy.signal import lfilter

rng = np.random.default_rng(1)
r = 0.01 * rng.standard_normal(1_000_000)
lam = 0.94


def ewma_loop(r: np.ndarray, lam: float, s0: float) -> np.ndarray:
    out = np.empty_like(r)
    s = s0
    for t in range(len(r)):
        s = lam * s + (1 - lam) * r[t] ** 2
        out[t] = s
    return out


def ewma_lfilter(r: np.ndarray, lam: float, s0: float) -> np.ndarray:
    out, _ = lfilter([1 - lam], [1, -lam], r**2, zi=[lam * s0])
    return out


s0 = float(r[:100].var())
a, b = ewma_loop(r, lam, s0), ewma_lfilter(r, lam, s0)
print(np.max(np.abs(a - b) / a))
for fn in (ewma_loop, ewma_lfilter):
    t = min(timeit.repeat(lambda: fn(r, lam, s0), number=1, repeat=3))
    print(f"{fn.__name__:13s} {t * 1e3:8.1f} ms")
8.809291523524647e-16
ewma_loop        280.2 ms
ewma_lfilter       7.1 ms

The two agree to a relative error of 9×10−169 \times 10^{-16}, a few units of rounding, and lfilter is about 40× faster. The same loop written in C++ and compiled with -O2:

void ewma(const double* r, double* out, std::size_t n, double lam, double s) {
    for (std::size_t t = 0; t < n; ++t) {
        s = lam * s + (1.0 - lam) * r[t] * r[t];
        out[t] = s;
    }
}

runs a million steps in about 1.5 ms in a standalone benchmark, roughly 190× the Python loop. That is the speed Numba or a pybind11 extension would approach for this kernel. The decision, said out loud: this recursion is linear, so rung 2 (lfilter) gets within a factor of five of compiled code with no new dependency, and that is where to stop unless the profile says this kernel still dominates. If the recursion had a nonlinear rule, such as resetting sts_t after a volatility spike, lfilter no longer applies and Numba is the natural next step.

Knowledge check

x = np.zeros((1000, 50)) (float64, C order). What are x.T.strides, and does x.T.reshape(-1) copy?

Knowledge check

In pandas 3, a function receives a float-only DataFrame, calls arr = df.to_numpy() and then does arr -= arr.mean(axis=0). What happens?

Knowledge check

A position-tracking loop with a nonlinear stop-loss rule over 10 million ticks dominates a research job's profile. The team has no C++ build pipeline. What is the most sensible first step?

Key takeaways

  • pandas for labels, alignment and I/O at the edges; NumPy arrays in the numerical core; SciPy for the algorithms.
  • Strides define layout: C order makes rows contiguous, F order columns; striding across the contiguous axis was 5–8× slower here.
  • Transposes and basic slices are views; reshaping non-contiguous data, np.array, astype and mixed-dtype to_numpy() copy; pandas 3 hands out read-only views.
  • Climb the ladder only as far as needed: better algorithm, existing primitive (lfilter, cumsum, accumulate), Numba, Cython, C++ with pybind11.
  • Keep the slow, obvious Python version as the oracle in tests when you move a kernel to compiled code.

Practice problems

Finished reading?

Answer the 3 knowledge checks to complete this lesson (0 done).