How do I make my tested trading loop faster with Numba?

Compile a trading loop that already gives the right answer with Numba’s njit, check that the compiled loop gives the same signals, and compare the two times on a million closes.

After this lesson, you can compile a trading loop with Numba and check that the compiled loop gives the same signals.

How do I compile the loop?

njit(trailing_signal) returns a compiled version of the function, which gives the same signals as the Python loop on the eight closes. Compiling translates the loop into machine instructions that the processor runs directly, so a loop over many rows runs much faster.

The loop is the trailing stop from the lesson on stateful rules, already checked by hand on eight closes of one made-up stock. The first call of the compiled function compiles it for the argument types, here an array of floats and an array of 64-bit integers, and later calls with the same types reuse the machine code. dtype=np.int64 fixes the integer type, because NumPy 1.26 on Windows makes 32-bit integers by default. Numba compiles loops over NumPy arrays with arithmetic and conditions, so pandas operations stay outside the function.

This lesson uses Numba 0.61.2 and NumPy 1.26.4.

The following box compiles the loop and prints both versions’ signals.

import numpy as np
from time import perf_counter
from numba import njit

def trailing_signal(close, entry, stop=0.95):
    signal = np.zeros(len(close), dtype=np.int8)
    peak = np.full(len(close), np.nan)
    on = False
    highest = 0.0
    for t in range(len(close)):
        if on:
            highest = max(highest, close[t])
            peak[t] = highest
            on = close[t] > stop * highest
        elif entry[t] == 1:
            on = True
            highest = close[t]
            peak[t] = highest
        signal[t] = on
    return signal, peak

close = np.array([100.0, 110.0, 104.0, 100.0, 104.0, 98.0, 99.0, 106.0])
entry = np.array([1, 0, 0, 1, 0, 0, 1, 0], dtype=np.int64)

fast_signal = njit(trailing_signal)
print(trailing_signal(close, entry)[0])
print(fast_signal(close, entry)[0])
[1 1 0 1 1 0 1 1]
[1 1 0 1 1 0 1 1]

Both loops turn off on the third and sixth closes.

Do the two loops agree on a million closes?

Both loops give the same signal on all one million simulated closes, and the compiled loop takes a small fraction of the Python loop’s time.

The million closes are one made-up stock’s prices, one per minute, from normal returns with a mean of 0 and a standard deviation of 0.08%. As in the lesson on cumulative returns, np.cumprod compounds the returns into prices. The entry flag is 1 when the close is above the close 20 minutes earlier. perf_counter() reads a clock in seconds, so the difference between two readings is the time of the call between them. np.array_equal checks that two arrays have the same shape and agree on every row.

The following box runs both loops and prints the check and the two times in seconds.

rng = np.random.default_rng(5)
minute_close = 100 * np.cumprod(1 + rng.normal(0.0, 0.0008, 1_000_000))
minute_entry = np.zeros(len(minute_close), dtype=np.int64)
minute_entry[20:] = minute_close[20:] > minute_close[:-20]

start = perf_counter()
python_signal, python_peak = trailing_signal(minute_close, minute_entry)
python_seconds = perf_counter() - start

start = perf_counter()
numba_signal, numba_peak = fast_signal(minute_close, minute_entry)
numba_seconds = perf_counter() - start

print(np.array_equal(python_signal, numba_signal), round(python_seconds, 4), round(numba_seconds, 4))
True 0.8547 0.0044

True says that the two loops agree on every minute. The times vary by machine and run, and the compiled call is faster because the first call on the eight closes already compiled the loop.

Your turn

Run both loops with a stop at 90% of the peak on the million closes and check that they agree. You should see True.

stop=0.90 goes to both versions in the same way.

python_90, _ = trailing_signal(minute_close, minute_entry, stop=0.90)
numba_90, _ = fast_signal(minute_close, minute_entry, stop=0.90)
print(np.array_equal(python_90, numba_90))
True