10 Years of Minute Data: Resumable Batch Downloads for US Stocks
A ten-year minute-level download for a single U.S. equity is larger than it first appears.
At 252 trading days per year, one symbol can contain approximately 2.5 million one-minute bars. Pulling 100 symbols across the same period creates more than 250 million records. A naïve script that starts at the beginning, retries failed pages from scratch, and writes every response to a single JSON file will eventually fail during a rate-limit response, network interruption, schema change, or disk exhaustion.
For quant researchers and data engineers, the central problem is therefore not “how do I call an API?” It is how do I design a download that can resume safely after interruption, avoid duplicating records, detect incomplete data, and remain usable when the same workflow runs again next month?
This article examines the engineering requirements of bulk historical market-data downloads using Polygon-style and TickDB-style APIs. The implementation focuses on windowed pagination, bounded concurrency, exponential backoff, local caching, and durable checkpoints.
1. Why Minute-Level History Requires a Download Architecture
Minute-level history is operationally different from daily OHLCV data.
A daily request for 100 symbols might contain only a few hundred records per symbol. A ten-year minute request can contain millions of records for the same symbol, and the volume is large enough that network stability, API throttling, and local storage behavior become first-order design constraints.
1.1 The volume problem
The following table illustrates the approximate size of the uncompressed request and the resulting engineering requirements.
| Scope | Approximate records | Engineering implication |
|---|---|---|
| One symbol, one day, 1-minute bars | 390 bars | A simple HTTP request is sufficient |
| One symbol, one year, 1-minute bars | 63,000 bars | Pagination and retry logic become necessary |
| One symbol, ten years, 1-minute bars | 2,520,000 bars | Large downloads require local storage and checkpoints |
| 100 symbols, ten years, 1-minute bars | 252,000,000 bars | Parallelism, deduplication, and partitioning are required |
The estimate assumes approximately 252 trading days per year and a 390-minute regular trading session. It excludes pre-market, post-market, holidays, early closes, and provider-specific session rules.
1.2 The common failure modes
Most bulk-download failures come from the boundary between network operations and local persistence.
A typical failure sequence looks like this:
- The script successfully downloads the first 300 windows.
- The API returns a rate-limit response.
- The script retries the request without respecting
Retry-After. - The process receives another request, fails during serialization, or is terminated by a deployment system.
- On restart, the script downloads the entire history again.
The result is wasted bandwidth, duplicate records, and an incomplete dataset that looks plausible because the failure occurred after several successful files had already been written.
A reliable downloader should treat every request and every output file as independently recoverable state.
2. Understanding the Two Main Pagination Strategies
There are two practical ways to retrieve historical bars from a market-data API.
2.1 Offset pagination
Offset pagination requests a page using an increasing numeric offset:
GET /bars?symbol=AAPL.US×pan=minute&from=...&to=...&limit=50000&offset=0
GET /bars?bars?symbol=AAPL.US×pan=minute&from=...&to=...&limit=50000&offset=50000
Offset pagination is straightforward, but it has two important weaknesses.
First, the provider may need to scan or reconstruct the entire result set before applying the offset. Large offsets can become progressively slower.
Second, records can shift between pages when the provider modifies or backfills historical data. A record returned on page 2 may also appear on page 3 after an adjustment. The client must therefore deduplicate using a stable key.
2.2 Time-window pagination
Time-window pagination divides the requested period into smaller intervals:
2020-01-01 → 2020-01-31
2020-02-01 → 2020-02-29
2020-03-01 → 2020-03-31
The client then requests each window independently and stores the result under a deterministic identifier.
This approach has several advantages:
- Each window can be retried independently.
- A failed download does not invalidate completed windows.
- The workload can be distributed across multiple workers.
- The partition boundaries remain stable across runs.
- Checkpoints can record progress at meaningful time intervals rather than at an arbitrary page number.
For a multi-year download, time-window pagination is generally the safer foundation.
2.3 A hybrid strategy
The most resilient implementation combines both approaches:
- Split the full request into daily, weekly, or monthly windows.
- Request each window using the provider’s native limit or pagination mechanism.
- Continue from the last timestamp within a window when the provider supports cursor-style pagination.
- Deduplicate records by symbol, interval, and timestamp.
- Write each completed window atomically.
- Commit a checkpoint only after the data has been persisted.
This approach also makes provider migration easier. The application can retain the same internal storage format while changing the request adapter for Polygon, TickDB, or another vendor.
3. Data Provider Boundaries and Comparison
Polygon and TickDB expose different historical-data interfaces and have different operational characteristics. The exact quota, request limits, retention rules, and response schemas should always be verified against the current provider documentation.
The important design point is that the downloader should not depend on undocumented assumptions about any provider.
| Consideration | Polygon-style API | TickDB-style API |
|---|---|---|
| Historical US equity OHLCV | Available through aggregate bar endpoints, subject to plan and provider limits | Historical US equity kline data is available for 10+ years |
| Request style | REST, commonly using symbol, timespan, date bounds, and pagination parameters | REST GET /v1/market/kline with symbol and interval parameters |
| Authentication | Provider-specific API key header | X-API-Key header for REST requests |
| Data shape | Provider-specific response envelope | TickDB responses use a code, data, and message structure |
| Rate-limit handling | Provider-specific status and response behavior | Handle error code 3001 and read the Retry-After header |
| Symbol validation | Provider-specific symbol endpoint | Verify symbols through /v1/symbols/available |
| Historical tick trades for US equities | Do not assume that aggregate bars imply tick-level trades | The TickDB trades endpoint does not support US equities |
| Order-book depth | Depends on the provider and product | TickDB depth supports US L1, but minute kline and depth are different products |
The key distinction is that a provider’s ability to return historical OHLCV does not imply that the same provider offers historical tick trades for that market.
For U.S. equities, a minute-level OHLCV download should be modeled as a bar-data workload. It should not be described as a tick-data acquisition pipeline.
4. Target Architecture
The downloader should separate provider-specific code from the storage and checkpoint layers.
┌──────────────────────────┐
│ Configuration Layer │
│ symbols, dates, workers │
└────────────┬─────────────┘
│
▼
┌──────────────────────────┐
│ Request Planner │
│ split date range into │
│ deterministic windows │
└────────────┬─────────────┘
│
▼
┌──────────────────────────┐
│ Bounded Worker Pool │
│ concurrency + backoff │
└────────────┬─────────────┘
│
▼
┌──────────────────────────┐
│ Provider Adapter │
│ Polygon / TickDB API │
└────────────┬─────────────┘
│
▼
┌──────────────────────────┐
│ Normalization Layer │
│ schema, timestamps, │
│ deduplication │
└────────────┬─────────────┘
│
▼
┌──────────────────────────┐
│ Durable Storage │
│ partitioned files + │
│ SQLite checkpoint DB │
└────────────┬─────────────┘
│
▼
┌──────────────────────────┐
│ Validation Layer │
│ gaps, duplicates, │
│ coverage, schema checks │
└──────────────────────────┘
4.1 Why use both partitioned files and a checkpoint database?
Partitioned files provide efficient storage and downstream scanning. A checkpoint database provides transactional progress tracking.
A practical layout is:
data/
AAPL.US/
1m/
2020-01-01_2020-01-31.jsonl.gz
2020-02-01_2020-02-29.jsonl.gz
state/
download.sqlite
SQLite is sufficient for a single process and many small teams. For a distributed system, replace it with PostgreSQL, Redis-backed job state, or an object-store manifest.
4.2 Checkpoint semantics
A checkpoint should represent a durable fact:
The data for this symbol, interval, and time window has been downloaded, normalized, written, and closed successfully.
Do not write the checkpoint before the data file is complete. Otherwise, a crash can leave a permanent false-positive checkpoint.
A safe sequence is:
- Download the window into a temporary file.
- Validate that the response contains no fatal schema errors.
- Compress the temporary file.
- Atomically rename it to the final path.
- Insert or update the checkpoint in the database.
- Commit the database transaction.
If the process stops between steps 4 and 5, the next run can detect the existing file and verify or repair the checkpoint.
5. Production-Grade TickDB Downloader
The following example uses TickDB’s historical kline endpoint. It demonstrates a provider adapter, time-window partitioning, local caching, bounded concurrency, rate-limit handling, exponential backoff, timeouts, environment-variable authentication, and durable checkpoints.
The implementation assumes that the kline response contains a data collection of bar objects. If your account or SDK returns a different envelope, adapt extract_bars() and leave the rest of the downloader unchanged.
#!/usr/bin/env python3
"""
Production-oriented TickDB minute-bar downloader.
Design goals:
- Split a date range into deterministic windows.
- Use bounded concurrency.
- Respect TickDB rate-limit responses.
- Retry transient failures with exponential backoff and jitter.
- Cache completed windows as compressed JSONL files.
- Record durable checkpoints in SQLite.
- Avoid duplicate records within each output window.
Environment:
export TICKDB_API_KEY="your-api-key"
Run:
python download_tickdb_minutes.py \
--symbols AAPL.US MSFT.US \
--start 2016-01-01 \
--end 2026-01-01 \
--interval 1m \
--workers 4 \
--output ./data \
--state ./state/download.sqlite
"""
import argparse
import gzip
import json
import os
import random
import sqlite3
import tempfile
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import date, datetime, timedelta, timezone
from pathlib import Path
from typing import Any, Iterable
import requests
BASE_URL = "https://api.tickdb.ai"
KLINE_ENDPOINT = f"{BASE_URL}/v1/market/kline"
SYMBOLS_ENDPOINT = f"{BASE_URL}/v1/symbols/available"
API_KEY = os.environ.get("TICKDB_API_KEY")
if not API_KEY:
raise RuntimeError(
"TICKDB_API_KEY is missing. "
"Set it before starting the downloader."
)
class DownloadError(RuntimeError):
"""Raised for a non-retryable provider or validation error."""
class RetryableError(RuntimeError):
"""Raised for a transient network or provider error."""
def utc_now() -> datetime:
return datetime.now(timezone.utc)
def iso_utc(value: datetime) -> str:
return value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
def parse_date(value: str) -> date:
return date.fromisoformat(value)
def iter_month_windows(start: date, end: date) -> Iterable[tuple[date, date]]:
"""Yield inclusive calendar-month windows.
Calendar windows are deterministic and convenient for minute data.
Provider-specific trading calendars can be substituted here.
"""
cursor = start.replace(day=1)
last = end
while cursor <= last:
if cursor.month == 12:
next_month = cursor.replace(year=cursor.year + 1, month=1)
else:
next_month = cursor.replace(month=cursor.month + 1)
window_end = min(next_month - timedelta(days=1), last)
yield cursor, window_end
cursor = next_month
def extract_bars(payload: dict[str, Any]) -> list[dict[str, Any]]:
"""Normalize the provider response into a list of bar dictionaries.
Keep provider-specific parsing in this function. The checkpoint,
storage, and validation layers should not need to know the API
response envelope.
"""
if payload.get("code", 0) != 0:
raise DownloadError(
f"TickDB error {payload.get('code')}: "
f"{payload.get('message', 'unknown error')}"
)
data = payload.get("data", [])
if isinstance(data, dict):
data = data.get("items", data.get("bars", []))
if not isinstance(data, list):
raise DownloadError("Unexpected TickDB kline response shape")
bars = []
for item in data:
if not isinstance(item, dict):
raise DownloadError("TickDB returned a non-object bar")
bars.append(item)
return bars
def request_with_retry(
session: requests.Session,
method: str,
url: str,
*,
params: dict[str, Any] | None = None,
max_attempts: int = 7,
) -> tuple[dict[str, Any], requests.Response]:
"""Send an HTTP request with provider-aware retry handling.
TickDB rate-limit errors use code 3001. We also handle HTTP 429
because upstream gateways or future API versions may use that status.
"""
delay = 1.0
for attempt in range(1, max_attempts + 1):
try:
response = session.request(
method,
url,
params=params,
headers={
"X-API-Key": API_KEY,
"Accept": "application/json",
},
timeout=(3.05, 60),
)
except (
requests.ConnectionError,
requests.Timeout,
requests.exceptions.ChunkedEncodingError,
) as exc:
if attempt == max_attempts:
raise RetryableError(
f"Network failure after {attempt} attempts: {exc}"
) from exc
sleep_for = min(delay + random.uniform(0, delay * 0.1), 60)
time.sleep(sleep_for)
delay = min(delay * 2, 60)
continue
try:
payload = response.json()
except ValueError as exc:
if response.status_code >= 500 and attempt < max_attempts:
time.sleep(delay + random.uniform(0, delay * 0.1))
delay = min(delay * 2, 60)
continue
raise DownloadError(
f"Non-JSON response from {url}: HTTP {response.status_code}"
) from exc
code = payload.get("code", 0)
if code == 0 and response.ok:
return payload, response
if code == 1001 or code == 1002:
raise DownloadError(
"Invalid or missing TickDB API key. "
"Check TICKDB_API_KEY."
)
if code == 2002:
raise DownloadError(
f"Symbol not found: {params.get('symbol') if params else None}"
)
if code == 3001 or response.status_code == 429:
retry_after = response.headers.get("Retry-After")
try:
wait_time = float(retry_after) if retry_after else delay
except ValueError:
wait_time = delay
wait_time = min(max(wait_time, 1.0), 300.0)
if attempt == max_attempts:
raise RetryableError("Rate limit retry budget exhausted")
print(
f"[rate-limit] waiting {wait_time:.1f}s "
f"before attempt {attempt + 1}",
flush=True,
)
time.sleep(wait_time)
delay = min(delay * 2, 60)
continue
if response.status_code >= 500 and attempt < max_attempts:
time.sleep(delay + random.uniform(0, delay * 0.1))
delay = min(delay * 2, 60)
continue
raise DownloadError(
f"TickDB request failed: HTTP {response.status_code}, "
f"code={code}, message={payload.get('message')}"
)
raise RetryableError(f"Retry budget exhausted for {url}")
def download_window(
session: requests.Session,
symbol: str,
interval: str,
window_start: date,
window_end: date,
output_root: Path,
checkpoint_db: sqlite3.Connection,
heartbeat_every: int = 10,
) -> str:
"""Download and persist one symbol/window."""
symbol_dir = output_root / symbol / interval
symbol_dir.mkdir(parents=True, exist_ok=True)
output_path = symbol_dir / (
f"{window_start.isoformat()}_{window_end.isoformat()}.jsonl.gz"
)
checkpoint_key = f"{symbol}|{interval}|{window_start}|{window_end}"
# If the file and checkpoint already exist, the window is complete.
if output_path.exists() and checkpoint_exists(checkpoint_db, checkpoint_key):
return f"skip {checkpoint_key}"
params = {
"symbol": symbol,
"interval": interval,
"start_time": window_start.isoformat(),
"end_time": window_end.isoformat(),
"limit": 50000,
}
payload, _ = request_with_retry(
session,
"GET",
KLINE_ENDPOINT,
params=params,
)
bars = extract_bars(payload)
# Deduplicate by timestamp before writing. Provider corrections can
# create duplicate observations when a window is re-requested.
deduped: dict[str, dict[str, Any]] = {}
for bar in bars:
timestamp = str(
bar.get("timestamp")
or bar.get("time")
or bar.get("t")
)
if timestamp == "None":
raise DownloadError(f"Bar is missing a timestamp: {bar}")
deduped[timestamp] = bar
# Write to a temporary file, then rename atomically.
fd, temp_name = tempfile.mkstemp(
suffix=".tmp",
prefix=f".{window_start.isoformat()}_",
dir=symbol_dir,
)
os.close(fd)
temp_path = Path(temp_name)
try:
with gzip.open(temp_path, "wt", encoding="utf-8") as handle:
for timestamp in sorted(deduped):
handle.write(json.dumps(deduped[timestamp], sort_keys=True))
handle.write("\n")
temp_path.replace(output_path)
upsert_checkpoint(
checkpoint_db,
checkpoint_key,
output_path,
len(deduped),
)
except Exception:
temp_path.unlink(missing_ok=True)
raise
return f"done {checkpoint_key} ({len(deduped)} bars)"
def checkpoint_exists(db: sqlite3.Connection, key: str) -> bool:
row = db.execute(
"SELECT 1 FROM checkpoints WHERE checkpoint_key = ?",
(key,),
).fetchone()
return row is not None
def upsert_checkpoint(
db: sqlite3.Connection,
key: str,
path: Path,
bar_count: int,
) -> None:
db.execute(
"""
INSERT INTO checkpoints
(checkpoint_key, path, bar_count, completed_at)
VALUES (?, ?, ?, ?)
ON CONFLICT(checkpoint_key) DO UPDATE SET
path = excluded.path,
bar_count = excluded.bar_count,
completed_at = excluded.completed_at
""",
(key, str(path), bar_count, iso_utc(utc_now())),
)
db.commit()
def initialize_state(db: sqlite3.Connection) -> None:
db.execute(
"""
CREATE TABLE IF NOT EXISTS checkpoints (
checkpoint_key TEXT PRIMARY KEY,
path TEXT NOT NULL,
bar_count INTEGER NOT NULL,
completed_at TEXT NOT NULL
)
"""
)
db.commit()
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--symbols", nargs="+", required=True)
parser.add_argument("--start", required=True)
parser.add_argument("--end", required=True)
parser.add_argument("--interval", default="1m")
parser.add_argument("--workers", type=int, default=4)
parser.add_argument("--output", default="./data")
parser.add_argument("--state", default="./state/download.sqlite")
parser.add_argument("--heartbeat-every", type=int, default=10)
args = parser.parse_args()
if args.workers < 1 or args.workers > 16:
raise SystemExit("--workers must be between 1 and 16")
start = parse_date(args.start)
end = parse_date(args.end)
if end < start:
raise SystemExit("--end must be on or after --start")
output_root = Path(args.output)
state_path = Path(args.state)
output_root.mkdir(parents=True, exist_ok=True)
state_path.parent.mkdir(parents=True, exist_ok=True)
db = sqlite3.connect(state_path, timeout=30)
initialize_state(db)
windows = list(iter_month_windows(start, end))
jobs = [
(symbol, args.interval, window_start, window_end)
for symbol in args.symbols
for window_start, window_end in windows
]
print(
f"Planned {len(jobs)} windows across {len(args.symbols)} symbols "
f"with {args.workers} workers.",
flush=True,
)
# A Session is shared only by this process. The worker threads use
# the same adapter, but provider-specific rate limits still apply.
session = requests.Session()
completed = 0
failures: list[str] = []
try:
with ThreadPoolExecutor(max_workers=args.workers) as executor:
futures = {
executor.submit(
download_window,
session,
symbol,
interval,
window_start,
window_end,
output_root,
db,
args.heartbeat_every,
): (symbol, window_start, window_end)
for symbol, interval, window_start, window_end in jobs
}
for future in as_completed(futures):
symbol, window_start, window_end = futures[future]
try:
message = future.result()
completed += 1
if completed % args.heartbeat_every == 0:
print(
f"[heartbeat] {completed}/{len(jobs)} windows complete",
flush=True,
)
if message.startswith("done"):
print(message, flush=True)
except Exception as exc:
key = f"{symbol}|{window_start}|{window_end}"
failures.append(f"{key}: {exc}")
print(f"[failed] {key}: {exc}", flush=True)
finally:
session.close()
db.close()
print(f"Completed {completed - len(failures)}/{len(jobs)} windows.")
if failures:
print("Failed windows:")
for failure in failures:
print(f" - {failure}")
raise SystemExit(1)
if __name__ == "__main__":
main()
5.1 Why the checkpoint database uses SQLite
SQLite provides a transactional boundary for the checkpoint update. If the process terminates while writing a checkpoint, the database either commits the complete record or does not commit it.
The checkpoint table contains:
| Field | Purpose |
|---|---|
checkpoint_key |
Unique symbol, interval, and date-window identity |
path |
Location of the completed output file |
bar_count |
Number of normalized records written |
completed_at |
UTC completion timestamp |
The checkpoint key should remain stable across executions. Do not include worker IDs, random UUIDs, or pagination counters in the final identity.
5.2 Why the temporary-file pattern matters
Writing directly to the final filename creates a partially written file if the process dies during compression or serialization.
The temporary-file pattern avoids that state:
.2020-01-01_abc123.tmp → 2020-01-01_2020-01-31.jsonl.gz
The final rename is atomic on most local filesystems when source and destination reside on the same filesystem.
5.3 A note on “heartbeat”
A REST batch downloader does not have the same heartbeat requirement as a long-lived WebSocket connection. Its equivalent operational signal is periodic progress logging, shown by the [heartbeat] output.
The request path still includes:
- bounded retries;
- exponential backoff;
- jitter;
- request timeouts;
- rate-limit handling;
- environment-variable authentication;
- progress and failure reporting.
For a real-time WebSocket implementation, use an explicit application-level ping command and reconnect with backoff rather than assuming the TCP connection remains healthy indefinitely.
6. Handling Concurrency Without Triggering Rate Limits
Concurrency is useful only when it stays below the provider’s sustainable request rate.
A common mistake is to set 100 workers and interpret a high rate of HTTP 429 responses as a reason to add more retries. That pattern increases load on the provider and can make recovery slower.
6.1 Use a bounded worker pool
The example uses a configurable worker count. The appropriate value depends on:
- provider quotas;
- response size;
- network latency;
- local disk throughput;
- whether the process shares a quota with other jobs.
Start with two to four workers, observe the response rate, and increase gradually. Treat the provider’s documented rate limit as a hard constraint, not as a target.
6.2 Coordinate rate limits across workers
The example handles a rate-limit response inside each worker. In a larger system, a shared token bucket or rate limiter is preferable.
A token bucket provides:
request permitted when:
available_tokens >= 1
on each request:
available_tokens = min(capacity, available_tokens + elapsed_time * refill_rate)
available_tokens -= 1
This avoids having every worker independently retry at the same moment. A global limiter also makes the download rate easier to explain and audit.
6.3 Respect Retry-After
When the provider returns a rate-limit response, the Retry-After value is an instruction, not merely diagnostic metadata.
The implementation above handles both:
- TickDB error code
3001; and - HTTP status
429.
The client waits for the specified interval, then resumes. If the response does not provide a usable header, the client falls back to exponential backoff with jitter.
6.4 Avoid retry storms
Do not retry all failures at the same delay. A retry storm can occur when:
- many workers encounter the same rate limit;
- the process restarts repeatedly;
- a timeout is too short for large responses;
- the provider returns a temporary
5xxerror.
Use jitter and a maximum delay. Also add a process-level failure budget so that a persistent outage does not generate unlimited requests.
7. Designing Checkpoint Recovery
A robust checkpoint system must distinguish four states:
| State | Meaning | Recovery action |
|---|---|---|
| Not started | No output or checkpoint exists | Download the window |
| In progress | Temporary data may exist | Delete temporary data and restart |
| Completed | Output file and checkpoint exist | Skip the window |
| Verification failed | Output exists but fails validation | Quarantine and redownload |
7.1 Restart behavior
On startup, the downloader should:
- Query the checkpoint database.
- Build the list of required windows.
- Verify that each checkpoint points to an existing file.
- Remove stale temporary files.
- Requeue only missing or invalid windows.
- Continue until the requested scope is complete.
A simple status query can be used operationally:
SELECT
checkpoint_key,
bar_count,
completed_at
FROM checkpoints
ORDER BY completed_at DESC;
7.2 Checkpoint frequency
Checkpoint every completed window, not every individual record.
A checkpoint after every bar would increase database writes dramatically and provide little benefit. A checkpoint after every window gives a useful recovery boundary without turning the database into the primary data store.
7.3 Idempotency
The download operation should be idempotent:
- Running the same command twice should not create duplicate logical records.
- Re-downloading an existing window should produce the same canonical content.
- The checkpoint should be updated without creating a second checkpoint row.
The INSERT ... ON CONFLICT DO UPDATE statement in the example provides this behavior.
8. Local Cache and Storage Format
The local cache serves two purposes:
- It prevents repeated downloads of already completed windows.
- It provides a fast local source for research and backtesting workflows.
8.1 JSONL versus Parquet
JSONL.gz is easy to inspect and stream, but Parquet is usually more efficient for large analytical workloads.
| Format | Advantages | Disadvantages |
|---|---|---|
| JSONL.gz | Simple, inspectable, naturally append-friendly, low implementation overhead | Slower columnar analytics, larger files, weaker schema enforcement |
| Parquet | Columnar compression, efficient filtering, strong analytical integrations | Requires a schema and a dedicated writer |
| CSV | Familiar and portable | Type ambiguity, poor schema control, expensive for large datasets |
| SQLite | Convenient transactional storage | Less suitable for large-scale columnar analysis |
A practical two-stage design is:
API response
↓
JSONL.gz raw or normalized cache
↓
Compaction or conversion
↓
Parquet partitions
If the project only needs a one-time research download, JSONL.gz may be sufficient. If the dataset will be queried repeatedly, convert it to Parquet after ingestion.
8.2 Data normalization
Normalize fields before writing them to disk. A stable internal schema might look like this:
{
"symbol": "AAPL.US",
"interval": "1m",
"timestamp": "2024-01-03T14:31:00Z",
"open": 184.22,
"high": 184.31,
"low": 184.19,
"close": 184.27,
"volume": 128430,
"source": "tickdb"
}
Normalizing provider-specific field names prevents downstream code from depending on API response details.
It also allows a provider adapter to change without rewriting the entire analytics pipeline.
8.3 Timestamp normalization
Store timestamps in UTC and retain the market session identifier if the data includes pre-market or post-market bars.
A timestamp without a timezone is not sufficient for cross-provider comparison. For example, 09:30 may mean the local market open, while a Unix timestamp always represents an absolute instant.
9. Validation: Detecting “Successful” but Incomplete Data
A successful HTTP response does not guarantee complete data.
The validation layer should check at least the following:
9.1 Coverage checks
For each symbol and window:
- Did the response contain any records?
- Did the first timestamp fall within the requested range?
- Did the last timestamp fall within the requested range?
- Are large gaps consistent with weekends, holidays, or a non-trading day?
A weekend gap is not automatically an error. The validator should use an exchange calendar rather than assuming that every minute should contain a bar.
9.2 Duplicate checks
Use the following logical key:
symbol + interval + timestamp
A duplicate can arise from:
- overlapping pagination windows;
- provider backfills;
- retrying a request after a timeout;
- incorrectly configured cursor logic.
Deduplication during normalization prevents duplicates from reaching the final dataset.
9.3 Schema checks
Check that every record contains the required fields and that numeric fields can be parsed. Do not silently convert malformed records into null values. Quarantine them for inspection instead.
9.4 Sanity checks
Useful sanity checks include:
low <= open <= high
low <= close <= high
volume >= 0
timestamp <= next timestamp
These checks do not prove that the data is economically correct, but they detect many ingestion and transformation defects.
9.5 Expected volume and session-aware checks
The number of bars for a regular U.S. equity session is usually close to 390, but the exact expected count depends on:
- exchange calendar;
- half-day sessions;
- early closes;
- provider treatment of the closing auction;
- pre-market and post-market inclusion;
- symbol-specific trading halts.
The validator should therefore compare against a calendar-derived expectation rather than hard-code 390 for every window.
10. Common Pitfalls in Polygon and TickDB Workflows
Pitfall 1: Treating a large request as one transaction
A single request spanning ten years may fail because of response size, server limits, or a temporary network interruption.
Fix: Partition the date range into windows.
Pitfall 2: Retrying without preserving the request boundary
If the client retries a failed request but advances the cursor anyway, the dataset silently loses records.
Fix: Advance the cursor only after a response has been validated and persisted.
Pitfall 3: Assuming the last page contains the last timestamp
The final response may be empty, duplicated, or contain a timestamp equal to the previous page boundary.
Fix: Compare the new cursor with the previous cursor and detect non-advancing pagination.
Pitfall 4: Ignoring provider corrections
Historical data may be revised after the initial download.
Fix: Store a source timestamp or ingestion timestamp, and define a refresh policy for recently downloaded windows.
Pitfall 5: Using the wrong endpoint for the task
Historical kline data and real-time latest kline data serve different purposes.
Fix: Use the historical kline endpoint for completed periods and the latest endpoint for live dashboard updates.
Pitfall 6: Confusing OHLCV with tick trades
Minute bars do not contain individual trade prints, order-level events, or a reconstructable trade tape.
Fix: Document the data granularity precisely. If order-flow research requires trades or depth, choose a market and data product that explicitly supports those records.
Pitfall 7: Running unrestricted parallel workers
Parallelism without a quota-aware limiter can trigger rate limits and increase total failure time.
Fix: Use bounded workers, shared rate limiting, and jittered retries.
Pitfall 8: Storing all results in memory
A ten-year minute dataset can exceed available memory even when the final compressed file fits comfortably on disk.
Fix: Stream responses to temporary files and process records incrementally.
Pitfall 9: Assuming the provider’s symbol format matches another provider’s format
A symbol such as AAPL.US may map differently across vendors.
Fix: Maintain a provider-specific symbol mapping and validate symbols before starting a large job.
Pitfall 10: Reporting completion without coverage validation
A job can exit successfully while producing empty or incomplete windows.
Fix: Compare the checkpoint count, file count, bar counts, and date coverage against the requested scope.
11. Operational Runbook
A production download should expose enough state to answer three questions quickly:
- What has completed?
- What is currently running?
- What failed and why?
11.1 Start with a small validation scope
Before launching a full ten-year job, test:
- one liquid symbol;
- one recent month;
- one older month;
- a holiday boundary;
- an early-close session;
- a symbol with a temporary halt or sparse trading.
This step catches provider-parameter and schema issues without committing the team to a multi-hour run.
11.2 Monitor the right metrics
Useful operational metrics include:
| Metric | Purpose |
|---|---|
| Windows completed per minute | Throughput monitoring |
| HTTP requests per second | Quota monitoring |
| Rate-limit responses | Backpressure detection |
| Retry count | Reliability signal |
| Bars per file | Completeness signal |
| Failed windows | Recovery queue |
| Duplicate records detected | Data-quality signal |
| Checkpoint age | Job-health signal |
11.3 Use controlled retries
A retry policy should distinguish:
- authentication errors: stop immediately;
- invalid symbols: stop or quarantine;
- rate limits: wait and retry;
- transient network errors: retry with backoff;
- malformed responses: quarantine and investigate;
- persistent server failures: stop after the retry budget.
Retrying an invalid API key only creates noise.
11.4 Preserve the original response
For forensic analysis, retain a short-lived raw-response archive for failed windows. After normalization and validation, the durable cache can store the canonical representation.
This is useful when a provider changes a field name or a transformation bug is discovered. It also avoids making a second network request merely to diagnose a failed batch.
12. When to Use a Different Download Strategy
The monthly-window strategy is appropriate for a first implementation, but the optimal partition depends on the workload.
| Workload | Recommended partition |
|---|---|
| One symbol, ten years, occasional research | Daily or weekly windows |
| 100 symbols, ten years, initial ingestion | Daily or weekly windows |
| Continuous daily refresh | One-day windows for recent data and larger windows for historical data |
| Parallel cluster ingestion | Calendar-month or daily windows with a shared job manifest |
| Intraday research during the session | Intraday windows with a separate live-tail process |
| Incremental refresh after a provider correction | Re-fetch the affected day or week, not the entire history |
For daily refresh workflows, a common design is:
Historical bulk:
daily/monthly windows
checkpointed
immutable historical partitions
Recent refresh:
previous trading day
overwritten or versioned
checkpointed separately
Do not mix the two policies in the same path unless the storage format makes version replacement explicit.
13. Final Recommendations
A reliable bulk downloader should follow six principles.
Partition the request
Use time windows as the primary unit of recovery. Offset pagination can remain an implementation detail inside a window.
Bound concurrency
Start with a small worker pool and coordinate rate limits globally.
Persist before checkpointing
Write to a temporary file, validate it, atomically rename it, and only then commit the checkpoint.
Normalize early
Store UTC timestamps, a stable schema, source metadata, and a deterministic record key.
Validate coverage
A successful process exit does not prove that the requested history is present.
Make the operation repeatable
Running the same command twice should skip completed work, repair missing windows, and produce the same canonical dataset.
For Polygon, the adapter must account for the provider’s aggregate-bar parameters, pagination behavior, and quota policy. For TickDB, the historical kline path provides 10+ years of cleaned and aligned U.S. equity OHLCV data, with authentication through X-API-Key and rate-limit responses represented by code 3001. Both implementations should use the same windowing, checkpointing, caching, and validation architecture.
Next Steps
If you are building a one-time research dataset, start with one symbol and one month, validate the output, then increase the scope gradually.
If you want to run this workflow yourself:
- Create an API key in the TickDB dashboard.
- Set
TICKDB_API_KEYin your environment. - Start with four or fewer workers.
- Run the script against a single symbol and a short date range.
- Inspect the compressed output and checkpoint table before launching the full history.
If you need institutional-scale historical data or coordinated multi-symbol ingestion, contact [email protected] for a deployment and storage design discussion.
If you use AI coding assistants, search for and install the tickdb-market-data SKILL in your AI tool’s marketplace.
This article does not constitute investment advice. Markets involve risk; past performance does not guarantee future results.