import numpy as np
days, stocks = 2520, 2000
mb = 1_000_000
returns = np.random.default_rng(15).normal(0.0003, 0.02, size=(days, stocks))
print(days * stocks * 8, returns.nbytes, returns.nbytes / mb)40320000 40320000 40.32
After this lesson, you can budget the memory for standardising 2,000 stocks’ daily returns and measure how much extra memory the calculation uses.
A dense matrix of \(d\) days, \(s\) stocks and \(b\) bytes per value takes \(B = d\,s\,b\) bytes, so ten years of 252 days and 2,000 stocks in NumPy’s default float64, 8 bytes per value, take 2,520 × 2,000 × 8 = 40,320,000 bytes, 40.32 MB. returns.nbytes reports the same number once the matrix exists.
\[ B = d \, s \, b \]
The made-up returns are decimals drawn from a normal distribution with a mean of 0.0003 and a standard deviation of 0.02, one row per day and one column per stock. One MB is one million bytes and one GB one billion. A calculation also needs room for its temporary results.
The following box estimates the size and builds the matrix.
(returns - stock_means) / stock_volatilities holds the centred returns and the result at the same time, so its peak adds at least two full matrices, 80.64 MB, while -= and /= on one copy write into the same storage and add less than 1% of one matrix. tracemalloc measures the peak of the memory allocated between .start() and .stop().
\[ z_{t,j} = \frac{r_{t,j} - \bar r_j}{\sigma_j} \]
Here \(\bar r_j\) is stock \(j\)’s mean return and \(\sigma_j\) its standard deviation over all days, and \(z_{t,j}\) the standardised return. get_traced_memory()[1] returns the peak in bytes. The copy for the in-place version costs one matrix, which an overwrite of returns itself would avoid. A forecast estimates the means and standard deviations on its training data only.
The following box measures both versions and checks that they give the same scores.
import tracemalloc
stock_means = returns.mean(axis=0)
stock_volatilities = returns.std(axis=0)
tracemalloc.start()
scores = (returns - stock_means) / stock_volatilities
expression_peak = tracemalloc.get_traced_memory()[1]
tracemalloc.stop()
scores_in_place = returns.copy()
tracemalloc.start()
scores_in_place -= stock_means
scores_in_place /= stock_volatilities
in_place_peak = tracemalloc.get_traced_memory()[1]
tracemalloc.stop()
print(expression_peak >= 2 * returns.nbytes, in_place_peak < returns.nbytes / 100, np.allclose(scores, scores_in_place))True True True
returns.astype(np.float32) stores each value in 4 bytes with about seven significant digits, so the matrix takes 20.16 MB, and the largest change in a return is about \(3.7 \times 10^{-9}\). Small errors can add up in long sums and cumulative returns, where float64 is safer.
During the conversion, both matrices are in memory. tracemalloc sees NumPy’s arrays, and psutil.Process().memory_info().rss reports all the memory the Python process holds, including the libraries.
The following box converts the matrix and measures the largest error.
A price matrix has 500 stock columns and one row per trading minute, 390 minutes a day, 252 days a year, for 10 years, at 8 bytes per price. Print how many GB of a 16 GB budget remain with the matrix and two equally large temporary matrices in memory. You should see 4.21 GB.