How do I cache downloads so a rerun does not fetch them again?
Save every downloaded file in a cache folder under a name computed from the request, reuse it on the next run, and keep a small record of what each file holds.
After this lesson, you can rerun an analysis from a saved download and see which request produced it.
How do I give the same request the same file name?
A hash of the request’s settings gives each request its own file name, and sorting the setting names before hashing gives the same name to the same settings typed in another order. {"ticker": "XYZ", "start": "2026-03-09"} and {"start": "2026-03-09", "ticker": "XYZ"} have different texts but the same 64-character name.
json.dumps turns the settings into text, sort_keys=True sorts their names, and hashlib.sha256(...).hexdigest() computes the hash as 64 characters from 0 to 9 and a to f. A different ticker gives a different name. The cache is the folder cache_demo, emptied at the start of the page, and the simulated download returns three made-up daily closes in dollars per share after a pause of a quarter of a second, counting each call in downloads.
Code: the cache folder and the simulated download
import shutilimport timefrom pathlib import Pathcache = Path("cache_demo")shutil.rmtree(cache, ignore_errors=True)cache.mkdir()downloads = []def download(params): downloads.append(params) time.sleep(0.25) rows ="".join(f"2026-03-{day:02d},{params['ticker']},{50+ day *0.25:.2f}\n"for day in (9, 10, 11))return ("date,ticker,close\n"+ rows).encode("utf-8")
The following box computes the name of both requests.
When does the cache download, and when does it read?
fetch downloads only when the saved CSV or its record is missing, and otherwise reads the CSV from disk, so the first fetch of XYZ makes one download and the second, with the settings in another order, makes none. The record, a small JSON file beside the CSV, holds the request’s settings and the time of the download.
The download goes to a temporary .part file, the record follows, and only then does .replace() give the CSV its final name, so a run that stops halfway leaves no CSV without a record. datetime.now(timezone.utc) gives the current time in UTC. With a live API, the access code stays out of the record, and a backtest that needs the prices known on an earlier date keeps dated copies, because providers revise data.
The following box defines fetch, fetches XYZ twice and reads the record.