How do I avoid calculating with invalid numbers?

See where inf and NaN come from, see why np.where does not stop a division by zero, compute a ratio only on the rows where its inputs are valid, and count the rows behind an average.

After this lesson, you can compute a ratio only where its inputs make sense and say how many values stand behind an average.

Where do inf and nan come from?

Dividing a positive number by zero gives inf, infinity, and zero by zero or any calculation with a missing number gives nan, so dividing each trade’s value by its size gives one usable price out of five. NumPy issues a RuntimeWarning for the divisions by zero and goes on, so the bad values flow into later results. A close of 50.40 divided by an infinite price gives a return of −100%.

The trades are five made-up trades of one stock, with values in dollars and sizes in shares, and np.nan marks a missing number. np.errstate(divide="ignore", invalid="ignore") silences the warnings inside its block, so the page shows only the results.

The following box divides every value by its size.

import numpy as np

value = np.array([5012.0, 2506.0, np.nan, 1253.0, 0.0])
size = np.array([100.0, 0.0, 50.0, np.nan, 0.0])
with np.errstate(divide="ignore", invalid="ignore"):
    raw_price = value / size
print(raw_price)
print(50.40 / raw_price[1] - 1)
[50.12   inf   nan   nan   nan]
-1.0

np.where(size > 0, value / size, np.nan) does not prevent the division, because Python computes value / size for all five trades before np.where picks the results.

How do I divide only the valid trades?

A mask that requires both inputs to be finite and above zero selects the valid trades, and dividing only the selected values, value[valid] / size[valid], leaves the other trades missing without any division by zero. Only the first trade, 5,012 dollars for 100 shares, gives a price, 50.12 dollars.

np.isfinite rejects nan, inf and -inf, and zero needs its own test. np.full(len(value), np.nan) starts five missing prices, and price[valid] = ... fills the valid places. np.nanmean averages while skipping nan, and valid.sum() counts the prices behind the average.

The following box computes the prices of the valid trades and their average.

valid = np.isfinite(value) & np.isfinite(size) & (value > 0) & (size > 0)
price = np.full(len(value), np.nan)
price[valid] = value[valid] / size[valid]
print(price)
print(valid.sum(), "of", len(valid), np.nanmean(price))
[50.12   nan   nan   nan   nan]
1 of 5 50.12

price.mean() would give nan, because one missing value makes the plain mean missing.

Your turn

From the closes 50.12, 0.0, 50.40, nan and 50.25, compute each day’s return only when both closes are finite, the earlier one is positive and the later one is not negative. You should see [-1.0, nan, nan, nan].

closes[1:] and closes[:-1] pair each close with the one before.

closes = np.array([50.12, 0.0, 50.40, np.nan, 50.25])
today, prior = closes[1:], closes[:-1]
ok = np.isfinite(today) & np.isfinite(prior) & (today >= 0) & (prior > 0)
day_returns = np.full(len(today), np.nan)
day_returns[ok] = today[ok] / prior[ok] - 1
print(day_returns.tolist())
[-1.0, nan, nan, nan]