A quant platform does not fail because its strategy is wrong. It fails because the data layer cannot keep up with the strategy.
At 09:30:00, a backtest requests three years of intraday bars for 4,000 instruments. The request competes with a live position-monitor query, an ingestion job, and a dashboard aggregation. One minute later, the dashboard is stale, the backtest times out, and the ingestion worker is retrying against a database that is already saturated.
Choosing a time-series database is therefore not a matter of choosing the “fastest” option. It is a capacity-planning problem involving write throughput, compression, query latency, operational complexity, and the shape of the data you actually need to retain.
This article compares ClickHouse, TimescaleDB, and SQLite across those dimensions. It also provides a reproducible benchmark harness and a practical decision framework for different scales: local research, single-user backtesting, multi-user research infrastructure, and production market-data pipelines.
After the first three paragraphs, the article connects database selection to a concrete market-data ingestion workflow. The example uses US equity OHLCV data because it provides a useful mixture of historical depth, frequent reads, and high write volume without confusing storage design with tick-level trade analysis.
1. The workload behind the database choice
Time-series databases optimize for a narrow but important pattern: data arrives continuously, records are queried by time, and recent data receives more attention than old data.
That pattern sounds simple, but quantitative systems often create several competing workloads.
| Workload | Typical operation | Main demand |
|---|---|---|
| Historical bars | Insert completed 1-minute or 1-hour candles | Sustained write throughput |
| Live monitoring | Query the latest candle and recent order-flow metrics | Low read latency |
| Research backtests | Scan multiple instruments over years | Scan efficiency and compression |
| Feature generation | Aggregate bars into rolling statistics | Vectorized or parallel execution |
| Event studies | Join price data with corporate events | Time-aligned relational queries |
| Dashboard reporting | Group by instrument, day, and strategy bucket | Flexible SQL and concurrency |
| Raw-data retention | Preserve source payloads for later replay | Storage efficiency and auditability |
The important distinction is that “time-series data” is not a sufficient workload specification. A database that ingests one million daily candles behaves differently from one that ingests 500 million one-minute candles. A system with 10 concurrent readers also creates a different bottleneck from a system with two.
1.1 A representative capacity model
The following workload is useful as a baseline for local testing. It is not a vendor benchmark; it defines the test conditions under which the later comparisons should be interpreted.
| Dimension | Baseline |
|---|---|
| Instruments | 4,000 US equities and ETFs |
| History | 3 years |
| Candle interval | 1 minute |
| Approximate rows | 6.3 billion at 252 trading days per year |
| Raw CSV size | 500–800 GB |
| Daily ingest | 250 million candles after incremental update |
| Historical query | 100 instruments × 1 year |
| Live query | Latest candle for 500 instruments |
| Concurrent users | 1–20, depending on deployment tier |
| Required freshness | Historical data within 5 minutes; live data within 1 second |
The raw estimate is not the final storage requirement. Compressed columnar storage can reduce the footprint substantially, while indexes, replication, retention policies, and write-ahead logs add their own overhead.
The operational questions are therefore:
- How many rows can the system ingest per minute without sustained queue growth?
- How much historical data can it retain per unit of disk?
- How quickly can it answer the queries that sit on the strategy’s critical path?
- What operational burden does the system impose on a small quant team?
- Can the database recover cleanly from an interrupted ingestion run?
1.2 Why a local database is often the right starting point
A local database is not necessarily a temporary compromise. For a researcher testing one strategy against a few years of daily or hourly data, a local deployment can provide better iteration speed than a remote service.
The local approach removes several recurring costs:
- network round trips;
- API quotas;
- managed-service pricing;
- connection-pool configuration;
- regional latency;
- dependency on an external control plane.
For daily bars, SQLite may be sufficient. For minute bars, the answer depends on the number of instruments, the query concurrency, and whether the system must ingest continuously while serving research queries.
The correct baseline is not “SQLite versus a distributed database.” It is “SQLite versus the minimum operational complexity required to solve the workload.”
2. Architecture overview: from market data to query
A practical quant data platform usually separates raw ingestion, normalized storage, derived features, and research access.
┌─────────────────────────┐
│ Market data source │
│ REST / WebSocket / file │
└────────────┬────────────┘
│
│ Authenticated requests
│ retries + rate-limit handling
▼
┌─────────────────────────┐
│ Ingestion service │
│ validation / batching │
│ deduplication / upsert │
└────────────┬────────────┘
│
┌──────────────────┼──────────────────┐
▼ ▼ ▼
┌────────────┐ ┌────────────┐ ┌────────────┐
│ SQLite │ │ TimescaleDB│ │ ClickHouse │
│ local file │ │ PostgreSQL │ │ columnar │
│ WAL mode │ │ hypertable │ │ MergeTree │
└──────┬─────┘ └──────┬─────┘ └──────┬─────┘
│ │ │
└──────────────────┼──────────────────┘
▼
┌─────────────────────────┐
│ Research / backtest │
│ feature generation │
│ monitoring / alerts │
└─────────────────────────┘
The architecture suggests an important selection rule. Choose the database according to the dominant access pattern:
- SQLite favors local simplicity and small-to-medium analytical workloads.
- TimescaleDB favors relational semantics, joins, transactions, and a gradual path from local development to a PostgreSQL-based service.
- ClickHouse favors large-scale columnar ingestion and broad analytical scans.
These are tendencies, not absolutes. A sufficiently large SQLite dataset can become slow, and a carefully partitioned TimescaleDB schema can serve a demanding research workload. The differences become decisive when the workload scales beyond the operating assumptions of each system.
3. Database capability comparison
The following table summarizes the practical trade-offs.
| Dimension | SQLite | TimescaleDB | ClickHouse |
|---|---|---|---|
| Primary model | Embedded relational database | PostgreSQL extension with hypertables | Distributed columnar analytical database |
| Storage layout | File-based B-tree pages | PostgreSQL tables, indexes, TOAST, WAL | Immutable column-oriented parts with background merges |
| Best fit | Local research, prototypes, small datasets | Transactional systems and moderate-to-large time-series workloads | High-volume ingestion and analytical queries |
| Compression | Page-level and schema dependent | PostgreSQL storage plus Timescale compression | Column and codec compression; strongest for numeric columns |
| Transaction model | Strong local ACID transactions | Full PostgreSQL transactions | Designed primarily for large analytical batches, not high-frequency transactional updates |
| Joins | Supported | Strong relational and time-series join support | Supported, but optimized for analytical joins |
| Updates and deletes | Supported, but frequent modifications can fragment pages | Supported with transactional semantics | Supported but expensive for large parts; usually modeled with replacement or versioning patterns |
| Horizontal scaling | Not intended | Possible through PostgreSQL ecosystem and distributed extensions | Native distributed ingestion and query architecture |
| Operational burden | Low | Medium | Medium to high |
| Connection model | Local file access | PostgreSQL network service | HTTP, native protocol, or client libraries |
| Hardware scaling | Primarily vertical | Primarily vertical, with ecosystem-specific options | Horizontal and vertical |
| Time partitioning | Manual indexes and schema design | Native hypertable partitioning | Native partitioning keys and ordered MergeTree tables |
| Best local deployment | One research workstation | Dedicated database host or managed PostgreSQL | Dedicated server or managed ClickHouse cluster |
3.1 SQLite: the local workhorse
SQLite is a complete database engine embedded directly into the application process. It does not require a separate server, which makes it unusually attractive for research workflows.
Its strengths are operational rather than merely economic:
- no server installation;
- no network configuration;
- no separate authentication or connection pool;
- trivial backup by copying a file, provided the backup process is coordinated correctly;
- excellent support from Python, R, Rust, Go, C, and most other application languages.
SQLite also provides transactions, foreign keys, indexes, and a mature query planner. For daily bars, it can be more than adequate.
The limitation appears with concurrent analytical workloads. SQLite serializes writers, and the default single-writer model becomes restrictive when an ingestion process must run while multiple queries read the same database.
Common mitigation techniques include:
- WAL mode for better reader/writer concurrency;
- batch inserts inside one transaction;
- separate read-only connections;
- a bounded ingestion queue;
- pre-aggregated tables for common queries;
- avoiding repeated DDL and index maintenance during large loads.
A typical SQLite schema for OHLCV data looks like this:
PRAGMA journal_mode = WAL;
PRAGMA synchronous = NORMAL;
CREATE TABLE IF NOT EXISTS bars (
symbol TEXT NOT NULL,
ts INTEGER NOT NULL,
interval_ms INTEGER NOT NULL,
open REAL NOT NULL,
high REAL NOT NULL,
low REAL NOT NULL,
close REAL NOT NULL,
volume REAL NOT NULL,
source TEXT NOT NULL DEFAULT 'tickdb',
updated_at INTEGER NOT NULL DEFAULT (unixepoch()),
PRIMARY KEY (symbol, interval_ms, ts)
) WITHOUT ROWID;
CREATE INDEX IF NOT EXISTS idx_bars_symbol_ts
ON bars (symbol, ts);
The composite primary key enforces deduplication naturally. A repeated write for the same instrument, interval, and timestamp updates the existing row instead of creating a duplicate.
SQLite is a strong default when all of the following are true:
- one researcher or a small number of users;
- one local machine;
- daily, hourly, or relatively modest minute-bar history;
- limited concurrent ingestion and querying;
- a preference for operational simplicity.
3.2 TimescaleDB: relational discipline with time-aware operations
TimescaleDB extends PostgreSQL with hypertables. A hypertable partitions time-series data internally while preserving PostgreSQL’s relational model.
That design matters because quantitative data rarely lives alone. Bars may need to be joined with:
- instrument metadata;
- corporate actions;
- exchange calendars;
- sector classifications;
- strategy positions;
- economic releases;
- feature tables;
- labeling or prediction targets.
TimescaleDB retains ordinary SQL joins, views, constraints, and transaction semantics. That makes it easier to fit into an existing PostgreSQL-backed application or data platform.
The hypertable schema resembles a normal PostgreSQL table:
CREATE TABLE IF NOT EXISTS bars (
symbol TEXT NOT NULL,
ts TIMESTAMPTZ NOT NULL,
interval_ms INTEGER NOT NULL,
open DOUBLE PRECISION NOT NULL,
high DOUBLE PRECISION NOT NULL,
low DOUBLE PRECISION NOT NULL,
close DOUBLE PRECISION NOT NULL,
volume DOUBLE PRECISION NOT NULL,
source TEXT NOT NULL DEFAULT 'tickdb',
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (symbol, ts, interval_ms)
);
SELECT create_hypertable(
'bars',
'ts',
chunk_time_interval => INTERVAL '30 days',
if_not_exists => TRUE
);
The design trade-off is flexibility. PostgreSQL-compatible semantics reduce integration friction, but the database retains the characteristics of a general-purpose relational system. Compression, vacuum behavior, index overhead, write amplification, and partition maintenance require active management for large datasets.
TimescaleDB works particularly well when:
- the system needs both time-series and relational data;
- transactions and row-level updates matter;
- the team already operates PostgreSQL;
- the workload is moderate enough that a single database service is sufficient;
- query patterns include joins, metadata filtering, and precise transactional writes.
3.3 ClickHouse: an analytical engine for large volumes
ClickHouse stores data in immutable column-oriented parts. Each part contains sorted rows grouped by its partition key and sorting key. Queries read only the required columns, which is a major advantage for analytical workloads.
For OHLCV data, a typical table might look like this:
CREATE TABLE bars
(
symbol LowCardinality(String),
ts DateTime64(3, 'UTC'),
interval_ms UInt32,
open Float64,
high Float64,
low Float64,
close Float64,
volume Float64,
source LowCardinality(String),
updated_at DateTime64(3, 'UTC')
)
ENGINE = MergeTree
PARTITION BY toYYYYMM(ts)
ORDER BY (symbol, ts);
The ordering key determines query efficiency. A query filtering by symbol and scanning a time range benefits from the (symbol, ts) order because ClickHouse can skip granules whose key ranges cannot match.
ClickHouse also provides codecs for numeric data, including compression schemes such as Gorilla and Delta. These are particularly relevant for price and volume columns because adjacent values often share patterns.
The main trade-off is operational and transactional. ClickHouse excels at append-heavy analytical ingestion, but frequent small updates can create parts that require merging. Replacing a row by partition and sorting key is often simpler than modeling it as an in-place mutation.
ClickHouse is usually the better fit when:
- daily ingest reaches tens of millions or billions of rows;
- queries scan broad historical ranges;
- many analytical queries run concurrently;
- the platform is explicitly an analytical data store;
- the team can manage partitions, schemas, merges, backups, and cluster operations.
4. Write throughput: ingestion is a queueing problem
Database benchmarks often report rows per second from a synthetic client. Production results differ because the ingestion path includes network latency, serialization, validation, deduplication, index maintenance, compaction, and backpressure.
The useful metric is not peak throughput. It is sustained throughput at an acceptable queue delay.
arrival rate = instruments × bars_per_instrument × update_frequency
sustainable throughput >= arrival rate × headroom_factor
A practical headroom factor is 1.5–3.0 for a research environment and can be higher for a production system with bursty event traffic.
4.1 Batch size matters more than most benchmark headlines
A request that inserts one row per transaction spends more time on round trips and transaction boundaries than on the actual row.
| Operation | Typical relative overhead | Practical improvement |
|---|---|---|
| One insert per HTTP request | Highest | Batch rows |
| One transaction per batch | Medium | Increase batch size carefully |
| Bulk insert or server-side file load | Lowest | Use for historical imports |
| Repeated updates to identical keys | Variable | Prefer staging plus replacement semantics |
| Unbounded batch size | Memory risk | Apply a byte and row limit |
4.2 Ingestion behavior by database
SQLite performs best when writes are batched into a small number of transactions. A single writer means that concurrent ingestion jobs should be coordinated rather than allowed to compete.
TimescaleDB benefits from PostgreSQL-style bulk loading, prepared statements, and carefully sized chunks. Its write path benefits from a partitioning strategy that avoids repeatedly modifying the same chunk.
ClickHouse is most effective when ingestion is append-oriented and batches are aligned with the table’s sorting key. Poorly ordered data increases merge work and can create many small parts.
4.3 Operational metrics to monitor
A production ingestion system should expose at least the following metrics:
| Metric | Why it matters |
|---|---|
| Rows accepted per second | Raw ingestion capacity |
| Rows committed per second | Durable throughput |
| Batch latency | Delay between receipt and persistence |
| Queue depth | Backlog visible to operations |
| Merge or vacuum backlog | Maintenance pressure |
| Failed batches | Data-quality or availability issues |
| Duplicate-key rate | Upsert and source behavior |
| Disk write amplification | Storage efficiency |
| Part or chunk count | ClickHouse and TimescaleDB health |
5. Compression and storage economics
Compression determines how much history fits on local storage. This matters even when the database runs on a single workstation because large datasets quickly become expensive to move, back up, and query.
5.1 Why compression differs
The databases use different storage models:
- SQLite compresses pages and records according to its page format and value encoding.
- TimescaleDB uses PostgreSQL storage, indexes, TOAST, and Timescale-specific columnar compression features.
- ClickHouse compresses individual columns with codecs selected for their data type.
A fair comparison must measure the entire database footprint, not only the logical table size.
Measure at least:
logical_bytes = sum(estimated row bytes)
physical_bytes = database files + WAL or journal + temporary files
+ indexes + metadata + replication overhead
compression_ratio = logical_bytes / physical_bytes
Do not compare a freshly imported ClickHouse table with a TimescaleDB table that still has uncompressed historical chunks, or compare only one index from SQLite with the full system.
5.2 Practical expectations
The following directional expectations are more useful than a universal multiplier:
| Data and behavior | SQLite | TimescaleDB | ClickHouse |
|---|---|---|---|
| Numeric columns with repeated or adjacent values | Moderate compression | Moderate to strong with compressed chunks | Strong with numeric codecs |
| Index overhead | Can become significant | Can become significant | Usually smaller relative to analytical footprint |
| Many small updates | Can increase page fragmentation | Bloat and vacuum pressure | Extra parts and merge work |
| Long historical retention | Fine for modest datasets | Good with chunk management | Strongest for very large analytical datasets |
| Operational simplicity | Highest | Medium | Lower |
The correct conclusion is not that one database always uses less disk. It is that ClickHouse provides more control over analytical compression, while SQLite and TimescaleDB are often easier to operate for smaller or more transactional workloads.
5.3 A storage test that avoids false confidence
Run the storage test at three dataset sizes:
- 100,000 rows;
- 10 million rows;
- the largest size you expect to operate.
Small datasets often fit in memory and do not reveal merge, cache, or compaction behavior. A one-million-row benchmark can make every system look excellent.
For each size, report:
- logical bytes;
- physical bytes;
- compression ratio;
- ingestion throughput;
- peak resident memory;
- query latency;
- time required to restart the service;
- time required to complete a backup or export.
6. Query performance: optimize for the real question
“Query performance” is not one metric. Quant workloads have distinct query classes.
| Query class | Example | Main performance driver |
|---|---|---|
| Point lookup | Latest bar for one symbol | Index locality and cache behavior |
| Range scan | One year of bars for 100 symbols | Partition pruning and column locality |
| Aggregation | Average return by symbol and month | Scan efficiency and vectorized execution |
| Multi-symbol query | Compare 4,000 instruments | Parallelism and partition distribution |
| Join | Bars joined to instrument metadata | Join strategy and data layout |
| Latest-state query | Most recent row per symbol | Sorting key, pre-aggregation, or specialized state |
| Bulk export | Download a research dataset | Sequential I/O and export format |
6.1 Recommended benchmark queries
A benchmark should include at least four queries.
-- 1. Point lookup
SELECT *
FROM bars
WHERE symbol = 'AAPL.US'
AND ts >= '2025-01-01'
ORDER BY ts DESC
LIMIT 1;
-- 2. Narrow range scan
SELECT ts, close
FROM bars
WHERE symbol = 'AAPL.US'
AND ts >= '2025-01-01'
AND ts < '2025-02-01'
ORDER BY ts;
-- 3. Multi-symbol aggregation
SELECT symbol,
count() AS observations,
avg(close) AS mean_close
FROM bars
WHERE ts >= '2025-01-01'
AND ts < '2025-02-01'
AND symbol IN ('AAPL.US', 'MSFT.US', 'NVDA.US')
GROUP BY symbol;
-- 4. Date-bucketed rollup
SELECT toStartOfInterval(ts, INTERVAL 1 DAY) AS day,
symbol,
sum(volume) AS total_volume
FROM bars
WHERE ts >= '2025-01-01'
AND ts < '2025-04-01'
GROUP BY day, symbol
ORDER BY day, symbol;
The fourth query may require a different table or materialized view in ClickHouse, such as a daily aggregate table. Pre-aggregation is often more valuable than micro-optimizing a repeatedly executed scan.
6.2 Explain before optimizing
Use each database’s query planner before changing schemas.
| Database | Diagnostic tool | What to inspect |
|---|---|---|
| SQLite | EXPLAIN QUERY PLAN |
Index usage, scan type, temporary B-tree |
| TimescaleDB | EXPLAIN (ANALYZE, BUFFERS) |
Index scans, chunk pruning, heap fetches, I/O |
| ClickHouse | EXPLAIN indexes = 1 and query logs |
Parts scanned, granules skipped, memory use, threads |
A query that scans one partition is not equivalent to one that scans every partition and filters afterward. A query that reads 20 columns when it needs two also creates unnecessary I/O, especially in a columnar engine.
6.3 Read-path design is part of database selection
Before choosing a system, list the five most frequent queries. If they all read the same instrument and time range, a well-designed single-node database may be sufficient. If they repeatedly scan broad cross-sectional histories, ClickHouse’s analytical execution model becomes more compelling.
The most common design mistake is selecting a database from a synthetic ingestion benchmark while ignoring the actual read path.
7. Production-grade ingestion implementation
The following Python example loads completed US equity OHLCV candles from an authenticated market-data endpoint into SQLite, TimescaleDB, or ClickHouse.
The example demonstrates three design requirements that apply regardless of the selected database:
- credentials remain in environment variables;
- retries use exponential backoff with jitter;
- batches commit atomically, so an interrupted run does not leave partial application of a batch.
Install the driver for the target you plan to use:
pip install requests clickhouse-connect psycopg[binary]
Set the relevant environment variables:
export TICKDB_API_KEY="your-api-key"
export TICKDB_BASE_URL="https://api.tickdb.ai"
# Required for the timescaledb target
export PG_DSN="postgresql://user:password@localhost:5432/quant"
# Required for the clickhouse target
export CLICKHOUSE_HOST="localhost"
export CLICKHOUSE_PORT="9000"
export CLICKHOUSE_USER="default"
export CLICKHOUSE_PASSWORD=""
export CLICKHOUSE_DATABASE="quant"
The implementation assumes that the API response contains a data collection and that each record contains symbol, ts, open, high, low, close, and volume. The normalization layer isolates that assumption from the database adapters.
from __future__ import annotations
import argparse
import json
import os
import random
import sqlite3
import time
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Iterable
import requests
API_KEY = os.environ.get("TICKDB_API_KEY")
BASE_URL = os.environ.get("TICKDB_BASE_URL", "https://api.tickdb.ai").rstrip("/")
if not API_KEY:
raise RuntimeError(
"TICKDB_API_KEY is required. Store the API key in an environment variable."
)
@dataclass(frozen=True)
class Bar:
symbol: str
ts: datetime
open: float
high: float
low: float
close: float
volume: float
class ApiError(RuntimeError):
def __init__(self, message: str, retry_after: int | None = None):
super().__init__(message)
self.retry_after = retry_after
def parse_timestamp(value: Any) -> datetime:
"""Normalize common API timestamp representations to UTC."""
if isinstance(value, (int, float)):
seconds = value / 1000 if value > 10_000_000_000 else value
return datetime.fromtimestamp(seconds, tz=timezone.utc)
if isinstance(value, str):
text = value.replace("Z", "+00:00")
parsed = datetime.fromisoformat(text)
if parsed.tzinfo is None:
parsed = parsed.replace(tzinfo=timezone.utc)
return parsed.astimezone(timezone.utc)
raise ValueError(f"Unsupported timestamp value: {value!r}")
def normalize_bars(payload: dict[str, Any]) -> list[Bar]:
"""Convert the API payload into the internal bar representation."""
records = payload.get("data", payload)
if not isinstance(records, list):
raise ValueError("Expected a list of bar records in the API response")
bars: list[Bar] = []
for record in records:
bars.append(
Bar(
symbol=str(record["symbol"]),
ts=parse_timestamp(record["ts"]),
open=float(record["open"]),
high=float(record["high"]),
low=float(record["low"]),
close=float(record["close"]),
volume=float(record.get("volume", 0)),
)
)
return bars
def fetch_bars(symbol: str, interval: str, limit: int = 5_000) -> list[Bar]:
"""Fetch completed bars with timeout, backoff, jitter, and rate-limit handling."""
headers = {"X-API-Key": API_KEY}
params = {
"symbol": symbol,
"interval": interval,
"limit": limit,
}
url = f"{BASE_URL}/v1/market/kline"
for attempt in range(6):
try:
response = requests.get(
url,
headers=headers,
params=params,
timeout=(3.05, 30),
)
if response.status_code == 429:
retry_after = int(response.headers.get("Retry-After", "5"))
raise ApiError("Rate limit exceeded", retry_after=retry_after)
response.raise_for_status()
payload = response.json()
# TickDB application-level rate-limit code.
if payload.get("code") == 3001:
retry_after = int(response.headers.get("Retry-After", "5"))
raise ApiError("Application rate limit exceeded", retry_after=retry_after)
if payload.get("code", 0) != 0:
raise RuntimeError(
f"API error {payload.get('code')}: {payload.get('message')}"
)
return normalize_bars(payload)
except (requests.Timeout, requests.ConnectionError, ApiError) as exc:
if attempt == 5:
raise
if isinstance(exc, ApiError) and exc.retry_after is not None:
delay = exc.retry_after
else:
delay = min(2 ** attempt, 30)
delay += random.uniform(0, delay * 0.1)
time.sleep(delay)
raise RuntimeError("Unreachable retry state")
class SqliteSink:
def __init__(self, path: str):
self.path = Path(path)
self.path.parent.mkdir(parents=True, exist_ok=True)
self.connection = sqlite3.connect(self.path, timeout=30)
self.connection.execute("PRAGMA journal_mode=WAL")
self.connection.execute("PRAGMA synchronous=NORMAL")
self.connection.execute(
"""
CREATE TABLE IF NOT EXISTS bars (
symbol TEXT NOT NULL,
ts INTEGER NOT NULL,
open REAL NOT NULL,
high REAL NOT NULL,
low REAL NOT NULL,
close REAL NOT NULL,
volume REAL NOT NULL,
PRIMARY KEY (symbol, ts)
) WITHOUT ROWID
"""
)
def write(self, bars: Iterable[Bar]) -> int:
rows = [
(
bar.symbol,
int(bar.ts.timestamp() * 1000),
bar.open,
bar.high,
bar.low,
bar.close,
bar.volume,
)
for bar in bars
]
with self.connection:
self.connection.executemany(
"""
INSERT INTO bars (symbol, ts, open, high, low, close, volume)
VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(symbol, ts) DO UPDATE SET
open=excluded.open,
high=excluded.high,
low=excluded.low,
close=excluded.close,
volume=excluded.volume
""",
rows,
)
return len(rows)
def close(self) -> None:
self.connection.close()
class TimescaleSink:
def __init__(self, dsn: str):
import psycopg
self.connection = psycopg.connect(dsn, autocommit=False)
self.connection.execute(
"""
CREATE TABLE IF NOT EXISTS bars (
symbol TEXT NOT NULL,
ts TIMESTAMPTZ NOT NULL,
open DOUBLE PRECISION NOT NULL,
high DOUBLE PRECISION NOT NULL,
low DOUBLE PRECISION NOT NULL,
close DOUBLE PRECISION NOT NULL,
volume DOUBLE PRECISION NOT NULL,
PRIMARY KEY (symbol, ts)
)
"""
)
self.connection.commit()
def write(self, bars: Iterable[Bar]) -> int:
rows = [
(
bar.symbol,
bar.ts,
bar.open,
bar.high,
bar.low,
bar.close,
bar.volume,
)
for bar in bars
)
with self.connection.cursor() as cursor:
cursor.executemany(
"""
INSERT INTO bars (symbol, ts, open, high, low, close, volume)
VALUES (%s, %s, %s, %s, %s, %s, %s)
ON CONFLICT (symbol, ts) DO UPDATE SET
open=EXCLUDED.open,
high=EXCLUDED.high,
low=EXCLUDED.low,
close=EXCLUDED.close,
volume=EXCLUDED.volume
""",
rows,
)
self.connection.commit()
return len(rows)
def close(self) -> None:
self.connection.close()
class ClickHouseSink:
def __init__(self) -> None:
import clickhouse_connect
self.client = clickhouse_connect.get_client(
host=os.environ["CLICKHOUSE_HOST"],
port=int(os.environ.get("CLICKHOUSE_PORT", "9000")),
username=os.environ.get("CLICKHOUSE_USER", "default"),
password=os.environ.get("CLICKHOUSE_PASSWORD", ""),
database=os.environ.get("CLICKHOUSE_DATABASE", "quant"),
connect_timeout=10,
send_receive_timeout=60,
)
self.client.command(
"""
CREATE TABLE IF NOT EXISTS bars (
symbol LowCardinality(String),
ts DateTime64(3, 'UTC'),
open Float64,
high Float64,
low Float64,
close Float64,
volume Float64
)
ENGINE = MergeTree
PARTITION BY toYYYYMM(ts)
ORDER BY (symbol, ts)
"""
)
def write(self, bars: Iterable[Bar]) -> int:
rows = [
[
bar.symbol,
bar.ts,
bar.open,
bar.high,
bar.low,
bar.close,
bar.volume,
]
for bar in bars
]
self.client.insert(
"bars",
rows,
column_names=[
"symbol",
"ts",
"open",
"high",
"low",
"close",
"volume",
],
database=os.environ.get("CLICKHOUSE_DATABASE", "quant"),
)
return len(rows)
def close(self) -> None:
self.client.close()
def build_sink(target: str):
if target == "sqlite":
return SqliteSink(os.environ.get("SQLITE_PATH", "quant.db"))
if target == "timescaledb":
return TimescaleSink(os.environ["PG_DSN"])
if target == "clickhouse":
return ClickHouseSink()
raise ValueError(f"Unknown target: {target}")
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument(
"--target",
required=True,
choices=["sqlite", "timescaledb", "clickhouse"],
)
parser.add_argument("--symbol", required=True)
parser.add_argument("--interval", default="1m")
parser.add_argument("--limit", type=int, default=5_000)
args = parser.parse_args()
bars = fetch_bars(args.symbol, args.interval, args.limit)
sink = build_sink(args.target)
try:
count = sink.write(bars)
print(json.dumps({"target": args.target, "rows_written": count}))
finally:
sink.close()
if __name__ == "__main__":
main()
Run the same ingestion job against each backend:
python ingest.py --target sqlite --symbol AAPL.US --interval 1m
python ingest.py --target timescaledb --symbol AAPL.US --interval 1m
python ingest.py --target clickhouse --symbol AAPL.US --interval 1m
The code intentionally separates the source request from the sink adapters. A production pipeline should add schema validation, exchange-calendar checks, missing-bar detection, and a durable job queue.
One data boundary deserves emphasis. A historical OHLCV endpoint is appropriate for bar-based research, but it does not make a US-equity system tick-complete. If the strategy requires individual trade prints or full order-book events, verify that the source supports those data types. Historical bars and tick-level order-flow research are different storage and research problems.
8. Benchmark design and reproducibility
A useful benchmark measures the entire pipeline rather than issuing isolated INSERT statements from a Python loop.
8.1 Benchmark harness
The following utility can compare query latency after the three backends contain equivalent data:
from __future__ import annotations
import statistics
import time
from dataclasses import dataclass
from typing import Callable
@dataclass
class QueryResult:
name: str
median_ms: float
p95_ms: float
rows_returned: int
def benchmark_query(
name: str,
query: Callable[[], list],
repetitions: int = 30,
warmup: int = 3,
) -> QueryResult:
"""Measure query latency after a short warmup."""
for _ in range(warmup):
query()
durations: list[float] = []
row_count = 0
for _ in range(repetitions):
started = time.perf_counter()
rows = query()
elapsed = (time.perf_counter() - started) * 1_000
durations.append(elapsed)
row_count = len(rows)
durations.sort()
p95_index = min(len(durations) - 1, int(len(durations) * 0.95))
return QueryResult(
name=name,
median_ms=statistics.median(durations),
p95_ms=durations[p95_index],
rows_returned=row_count,
)
Use identical data ranges and equivalent transformations. If SQLite retrieves an integer timestamp while ClickHouse returns a DateTime64, normalize both before calculating derived values.
8.2 Required benchmark matrix
| Test | SQLite | TimescaleDB | ClickHouse |
|---|---|---|---|
| Initial 1-million-row import | Measure | Measure | Measure |
| Incremental 100,000-row update | Measure | Measure | Measure |
| Restart and recovery | Measure | Measure | Measure |
| Single-symbol year scan | Measure | Measure | Measure |
| 100-symbol cross-sectional scan | Measure | Measure | Measure |
| Latest-value lookup | Measure | Measure | Measure |
| Daily aggregation | Measure | Measure | Measure |
| Metadata join | Measure | Measure | Measure |
| Concurrent reader test | Measure | Measure | Measure |
| Disk footprint | Measure | Measure | Measure |
Report median and p95 latency. Averages hide tail behavior, and the tail is where dashboards and backtests fail.
8.3 Avoid benchmark contamination
Four mistakes can invalidate a comparison:
- Different data ranges. One database may contain compressed historical chunks while another contains uncompressed data.
- Different freshness. Comparing an empty table with a fully populated table produces meaningless results.
- Warm-cache bias. Run a defined warmup phase and report both cold-start and warm-cache behavior.
- Client overhead dominance. For small queries, network latency may dominate the database measurement.
A controlled report should publish the hardware, operating-system configuration, database versions, schema, dataset size, query text, cache state, and result row counts.
9. Choosing a database by operational scale
9.1 Individual researcher: one workstation
Recommended default: SQLite
A reasonable starting stack is:
| Layer | Choice |
|---|---|
| Ingestion | Batched Python job or local scheduled process |
| Storage | SQLite in WAL mode |
| Research | DuckDB or a direct SQLite connector |
| Backup | Filesystem snapshot or coordinated file backup |
| Live monitoring | Read-only connection and a small latest-value table |
This configuration works well when the data set fits comfortably on local disk and ingestion does not need to compete with heavy concurrent research.
When local SQLite no longer feels simple, do not immediately migrate to a distributed platform. First apply the intermediate optimizations:
- move daily or weekly tables;
- aggregate minute bars into hourly bars;
- store only the columns required by active research;
- split live and historical datasets;
- use a separate process for ingestion;
- remove unused indexes;
- vacuum and analyze during maintenance windows.
9.2 Small quant team: shared research server
Recommended default: TimescaleDB
At this stage, shared access, metadata joins, transactions, and predictable SQL semantics usually matter more than extreme scan throughput.
| Requirement | TimescaleDB response |
|---|---|
| Multiple users | PostgreSQL role and connection management |
| Instrument metadata | Standard relational joins |
| Concurrent research | Server-side pooling and workload isolation |
| Historical partitions | Time chunks and retention policies |
| Transactional corrections | PostgreSQL transaction semantics |
| Deployment | Single host, replication, or managed PostgreSQL |
Use separate schemas or databases for research, paper trading, and production when contamination would affect results.
9.3 Institutional or high-volume platform
Recommended default: ClickHouse, possibly alongside PostgreSQL
Large analytical platforms often need both systems:
PostgreSQL / TimescaleDB
├── users, permissions, strategies, positions
├── job metadata and audit records
└── transactional reference data
ClickHouse
├── high-volume bars
├── feature history
├── research scans
└── cross-sectional aggregates
This separation avoids forcing one engine to perform two unrelated jobs well.
9.4 Decision matrix
| Requirement | SQLite | TimescaleDB | ClickHouse |
|---|---|---|---|
| Zero-service local setup | ● | ○ | ○ |
| Single-user research | ● | ● | ○ |
| Relational joins and transactions | ● | ● | ○ |
| Existing PostgreSQL ecosystem | ○ | ● | ○ |
| Large append-only ingestion | ○ | ● | ● |
| Broad multi-year analytical scans | ○ | ● | ● |
| Horizontal data distribution | ○ | ○ | ● |
| Simple backup and recovery | ● | ○ | ○ |
| Operational maturity for large clusters | ○ | ○ | ● |
Legend: ● strong fit; ○ workable; ○ context-dependent. The table should inform a benchmark, not replace one.
10. Deployment guide by scenario
Scenario A: daily strategy research
database: sqlite
mode: wal
retention: full
symbols: 500
interval: 1d
expected_rows: 500000
concurrency: 1
backup: daily_snapshot
This configuration prioritizes reproducibility and low operational overhead. A strategy can be backtested from one machine without a database service.
Scenario B: intraday research on a shared host
database: timescaledb
schema: research
chunk_interval: 30d
retention: 5_years
symbols: 5000
interval: 1m
expected_rows: 6000000000
concurrency: 10
backup: continuous_archive_plus_daily_snapshot
Before loading six billion rows, verify chunk sizing, query plans, disk headroom, backup duration, and maintenance windows. The configuration describes the target state; it does not replace a staged load test.
Scenario C: multi-user analytical platform
database: clickhouse
cluster_nodes: 3
partition: month
order_by: [symbol, ts]
retention: 7_years
compression: numeric_codecs
replication: 2
ingestion_batching: true
query_cache: selective
Test the failure modes before increasing capacity:
- loss of one replica;
- network interruption during a large insert;
- delayed background merges;
- skew caused by a small number of high-volume symbols;
- behavior during a full disk;
- restoration time from backup.
Scenario D: hybrid architecture
hot_store: sqlite
historical_store: clickhouse
operational_store: postgresql
refresh_interval: 15m
The hybrid design can keep fast local development independent from the centralized historical store. The main cost is synchronization logic and the need to define which source is authoritative.
11. Common failure modes
11.1 Selecting by headline ingestion rate
A benchmark may load data in an order that favors one engine. Real ingestion includes late-arriving bars, corrections, retries, and overlapping updates. Measure end-to-end commit latency and recovery behavior.
11.2 Treating compression as a free benefit
Compression can improve scans and reduce disk use, but it introduces maintenance behavior. Compression jobs, merges, and vacuum operations can compete with foreground queries.
11.3 Indexing every column
Quant tables often contain a small number of important dimensions and many rarely filtered measures. An index on every symbol, timestamp, and metric combination consumes space and increases write cost.
Start with the primary access pattern:
- one symbol across time;
- many symbols across one date range;
- latest row per symbol;
- date-bucketed aggregation.
Add secondary indexes only after examining actual query plans.
11.4 Ignoring result correctness
A faster database is irrelevant if it silently drops corrections or stores timestamps in inconsistent time zones.
Store all timestamps in UTC, define the interval explicitly, and test:
- daylight-saving transitions;
- overnight sessions;
- exchange holidays;
- duplicate timestamps;
- missing bars;
- late corrections;
- daylight and overnight session labels.
A time-series schema should distinguish the event timestamp from the ingestion timestamp when late data matters.
11.5 Measuring only a single user
Interactive research often begins with one user and ends with multiple notebooks, dashboards, and scheduled jobs running together. Test concurrent readers during ingestion, not only after ingestion has stopped.
12. Recommended selection process
Use the following sequence rather than selecting a database from feature descriptions.
Step 1: Write the five most important queries
Include expected row counts, date ranges, instruments, and expected latency. Include the most expensive dashboard query, not just the easiest lookup.
Step 2: Define the write model
Specify:
- rows per day;
- peak rows per minute;
- average and maximum batch size;
- duplicate-key behavior;
- correction frequency;
- retention policy;
- freshness target.
Step 3: Generate representative synthetic data
Synthetic data should preserve the distributions of the production dataset. Uniform random bars are easier to compress than real market data and can produce misleading storage results.
Step 4: Load a small set of realistic datasets
Test at 1%, 10%, and 100% of expected volume. Observe whether performance scales linearly or whether maintenance and compaction create nonlinear costs.
Step 5: Benchmark cold and warm states
Record both:
- cold-cache latency after restart;
- warm-cache latency after repeated access.
A production system experiences both states.
Step 6: Test failure and recovery
Interrupt ingestion, restart the service, simulate a full disk, restore a backup, and verify deduplication. Recovery time is part of database performance.
Step 7: Estimate three-year operating cost
Include:
- storage;
- backups;
- compute or hosting;
- monitoring;
- maintenance labor;
- engineering time;
- migration and recovery procedures.
A free local database can be more expensive if every researcher must maintain a custom file pipeline.
Step 8. Choose the simplest system that passes the workload
The best database is not the one with the highest benchmark result. It is the one that meets the measured requirements with the least operational complexity.
13. Final recommendation
The first lesson of database selection is that scale changes the answer.
SQLite is not merely a “small database.” It is an effective local analytical engine when the dataset, concurrency, and maintenance burden remain bounded. Its file-based deployment removes an entire class of infrastructure failures and gives a researcher a reproducible environment in seconds.
TimescaleDB becomes attractive when the system needs to preserve relational behavior while managing time-partitioned data. Its PostgreSQL foundation makes it a practical choice for teams that need joins, transactions, metadata, and a conventional operational model.
ClickHouse becomes appropriate when the dominant problem is ingesting and scanning large analytical volumes. Its column-oriented storage, compression controls, partitioning, and distributed execution model provide the necessary headroom for large cross-sectional research and multi-user analytics.
The practical selection path is straightforward:
- Choose SQLite for local research and modest workloads.
- Choose TimescaleDB for shared, relational, transactional systems.
- Choose ClickHouse for large-scale append-heavy analytical workloads.
- Use a hybrid design when operational metadata and analytical history have fundamentally different requirements.
Before committing, reproduce the five critical queries, measure sustained ingestion, record the full physical footprint, and test recovery. The database that passes those tests under your own workload is the correct answer—even if it is not the database that leads a generic benchmark.
This article does not constitute investment advice. Markets involve risk; past performance does not guarantee future results.