How do I keep returns right across chunk boundaries?

Compute returns and rolling means on a file read in chunks by carrying the last rows of each chunk into the next, and check the result against the whole file.

After this lesson, you can compute one-minute returns, 20-row moving averages and running peaks on a file read in chunks, without losing the history a new chunk needs.

What goes wrong when each chunk starts over?

A return needs the previous price, so a chunk that computes its returns on its own leaves its first return missing, and five chunks give five missing returns where the whole file has one. The return at minute 200000, the first row of the second chunk, is lost, although the price of minute 199999 is in the file.

\[ r_t = \frac{P_t}{P_{t-1}} - 1 \]

The made-up file holds a million minute prices of CCC in dollars per share, about ten years of 390-minute sessions, one stock in time order. chunksize=200_000 reads it in five chunks, as in the lesson on CSV chunks, and the full read serves only as the check.

Code: the made-up minute prices
import shutil
from pathlib import Path

import numpy as np
import pandas as pd

demo = Path("boundary_demo")
shutil.rmtree(demo, ignore_errors=True)
demo.mkdir()
prices_file = demo / "ccc_minutes.csv"
n = 1_000_000
pd.DataFrame({"minute": np.arange(n), "price": (410 * np.cumprod(1 + np.random.default_rng(13).normal(0, 0.0005, n))).round(4)}).to_csv(prices_file, index=False)
whole_price = pd.read_csv(prices_file)["price"]

The following box computes the returns chunk by chunk without history and compares them with the whole file.

alone = pd.concat([chunk["price"].pct_change(fill_method=None) for chunk in pd.read_csv(prices_file, chunksize=200_000)])
whole_returns = whole_price.pct_change(fill_method=None)
print(alone.isna().sum(), whole_returns.isna().sum(), alone.equals(whole_returns))
5 1 False

How do I carry the history into the next chunk?

Putting the last rows of the previous chunk in front of each new chunk gives the calculation the history it needs, and dropping their results afterwards keeps one result per new row. A return needs one carried price and a 20-row moving average needs 19, so chunked(prices_file, calculate, history_rows) takes the number of rows as an argument.

pd.concat([history, chunk["price"]]) joins the carried prices and the chunk, .iloc[len(history):] keeps the results of the new rows, and .tail(history_rows).copy() keeps the last rows without holding on to the whole chunk. The return at minute 200000 is 370.8404 / 370.9744 − 1, about −0.000361, as in the whole file. Restarting a rolling mean changes only the last digits of a few results through rounding, so np.allclose compares within a tolerance. A window counts rows, so a file with absent minutes or several sessions needs its history reset at each open, and several stocks need one history each.

The following box defines chunked and checks the returns and the moving averages against the whole file.

def chunked(path, calculate, history_rows, chunksize=200_000):
    pieces, history = [], pd.Series(dtype="float64")
    for chunk in pd.read_csv(path, chunksize=chunksize):
        price = pd.concat([history, chunk["price"]])
        pieces.append(calculate(price).iloc[len(history):])
        history = price.tail(history_rows).copy()
    return pd.concat(pieces)

carried_returns = chunked(prices_file, lambda price: price.pct_change(fill_method=None), history_rows=1)
carried_means = chunked(prices_file, lambda price: price.rolling(20).mean(), history_rows=19)
print(carried_returns.iloc[199999:200001])
print(carried_returns.equals(whole_returns), np.allclose(carried_means, whole_price.rolling(20).mean(), equal_nan=True))
199999    0.000868
200000   -0.000361
dtype: float64
True True

Your turn

Compute the running peak, the highest price so far, in chunks of 200,000 rows by carrying the highest price seen into each new chunk. Print the peak at minute 200000 and whether all peaks match the whole file. You should see 437.876 and True.

.clip(lower=peak) keeps each chunk’s running maximum at least as high as the carried peak.

pieces, peak = [], -np.inf
for chunk in pd.read_csv(prices_file, chunksize=200_000):
    running = chunk["price"].cummax().clip(lower=peak)
    pieces.append(running)
    peak = running.max()
chunked_peak = pd.concat(pieces)
print(chunked_peak.iloc[200_000], chunked_peak.equals(whole_price.cummax()))
437.876 True