br-py-duckdb-cache
DuckDB-backed windowed cache with Parquet/ZSTD storage, gap-aware regeneration, and Iceberg datastore integration.
Installation
From PyPI
pip install br-py-duckdb-cache
From source
git clone https://github.com/b-raisdana/br_py_duckdb_cache.git
cd br_py_duckdb_cache
pip install .
Development install
pip install -e ".[dev]"
This installs the package in editable mode along with all development dependencies (pytest, ruff, mypy, pre-commit, etc.).
Requirements
- Python >= 3.12
- See
requirements.txtfor runtime dependencies
Usage
Core API
duckdb_cache — caching decorator
The main entry point. Decorate a data generator function to add automatic DuckDB-backed caching with gap detection and on-demand regeneration.
from duckdb_cache import duckdb_cache
from duckdb_cache_registry import DatastoreRegistry
registry = DatastoreRegistry()
@duckdb_cache(
datastore_registry=registry,
boundary_arg="time_range_str",
freqs=("1min", "5min"),
)
def my_generator(*, time_range_str: str, freqs: tuple[str, ...]) -> pd.DataFrame:
"""Your data generation logic here."""
...
result = my_generator(time_range_str="20-01-01.00-00T20-01-01.01-00")
Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
datastore_registry |
DatastoreRegistry |
required | Registry for Iceberg/Parquet storage backends |
boundary_arg |
str |
"time_range_str" |
Name of the time boundary argument |
freqs |
tuple[str, ...] |
None |
Timeframe frequencies for this dataset |
post_fetch |
Callable |
None |
Post-processing hook applied to the final result |
nan_means |
Literal |
"not-cached" |
How to treat NaN-mean gaps |
drop_not_cacheable |
Callable |
_drop_not_finished_candles |
Filter to drop non-cacheable rows |
read_duckdb — batched Parquet reads
Read and concatenate multiple Parquet/ZSTD cache files in a single DuckDB query with date-column filtering.
from duckdb_reader import read_duckdb
from pathlib import Path
from datetime import datetime
paths = [Path("data/file1.parquet"), Path("data/file2.parquet")]
df = read_duckdb(
paths=paths,
data_frame_type="market_data",
start=datetime(2024, 1, 1, tzinfo=timezone.utc),
end=datetime(2024, 1, 2, tzinfo=timezone.utc),
)
Parquet normalization
Utilities to ensure Parquet files conform to the flat-frame on-disk convention (no date/timeframe index levels).
from parquet_normalization import flatten_index_to_columns, has_non_default_index
if has_non_default_index(df):
df = flatten_index_to_columns(df)
pandera_validate — output dumping
dump_output=True writes what a validated function returned to disk, so a surprising frame can be opened and compared instead of guessed. Off by default; validation behaviour is identical either way.
from helper.pandera import pandera_validate
@pandera_validate(allow_pandas_dataframe=True, dump_output=True)
def load(*, symbol: str) -> pd.DataFrame:
...
Files are content-addressed: every name ends with a 7-character CRC-32 of the bytes written, so the same output reuses one file while a changed output lands beside the previous version.
| Returned value | Files written |
|---|---|
| one DataFrame / 1-D or 2-D ndarray | src.app.model.load.<hash>.parquet |
| class method | src.app.model.Loader=load.<hash>.parquet |
| tuple / list / dict | ...<path>.<hash>.parquet per frame, plus one .json describing the whole output |
Nested paths use dict keys and 1-based tuple/list indices: a frame inside {"d": {"f": (x, y, frame)}} is dumped as src.app.model.load.d=f=3.<hash>.parquet and referenced from the JSON as {"output_dump_reference": {"parquet": "...", "type": "DataFrame", "shape": [3, 2]}}. The JSON never holds frame data.
The folder defaults to <git root of the decorated function's file>/logs/output_dump/, so a PyPI install dumps into the importing project — never into site-packages and never relative to the process working directory. Override it once at start-up:
from helper import configure_pandera_dump_folder
configure_pandera_dump_folder("var/debug_frames") # relative -> <git root>/var/debug_frames
configure_pandera_dump_folder("/var/tmp/frames") # absolute -> used as is
configure_pandera_dump_folder(None) # back to the default
The folder is created on first use. A dumping failure (unwritable path, a frame no Parquet encoder accepts) is logged and swallowed, so debugging never changes what the function returns or raises.
Registry
DatastoreRegistry defines named storage namespaces derived from configuration (market, symbol, exchange):
from duckdb_cache_registry import DatastoreRegistry
registry = DatastoreRegistry.UnifiedNoNAN # or DatastoreRegistry.Tick
table_name = registry.get_auto_table_name()
Configuration
Runtime settings are managed via app_config (Pydantic BaseSettings). There are three ways to override defaults:
1. Programmatic override (must be called before first app_config access)
from config import configure, app_config
configure(
timeframes=("1min", "5min", "1h"),
under_process_market="crypto",
under_process_symbol="BTC",
under_process_exchange="binance",
)
print(app_config.timeframes) # ('1min', '5min', '1h')
print(app_config.under_process_market) # 'crypto'
2. Environment variables (DLF_ prefix)
export DLF_TIMEFRAMES="1min,5min,1h"
export DLF_UNDER_PROCESS_MARKET="crypto"
export DLF_UNDER_PROCESS_SYMBOL="BTC"
export DLF_UNDER_PROCESS_EXCHANGE="binance"
from config import app_config
print(app_config.timeframes) # ('1min', '5min', '1h')
3. .env file
Create a .env file in your project root:
DLF_TIMEFRAMES=1min,5min,1h
DLF_UNDER_PROCESS_MARKET=crypto
DLF_UNDER_PROCESS_SYMBOL=BTC
DLF_UNDER_PROCESS_EXCHANGE=binance
Available settings:
| Field | Type | Default | Env var | Description |
|---|---|---|---|---|
timeframes |
tuple[str, ...] |
("1min", "5min", "15min", "1h", "4h", "1D", "1W") |
DLF_TIMEFRAMES |
Comma-separated timeframe strings |
under_process_market |
str |
"" |
DLF_UNDER_PROCESS_MARKET |
Market identifier (e.g., "crypto", "forex") |
under_process_symbol |
str |
"" |
DLF_UNDER_PROCESS_SYMBOL |
Symbol/ticker (e.g., "BTC", "EURUSD") |
under_process_exchange |
str |
"" |
DLF_UNDER_PROCESS_EXCHANGE |
Exchange identifier (e.g., "binance", "oanda") |
Note: The configure() function must be called before the first access to app_config. Once app_config is accessed, the configuration is frozen and further calls to configure() will raise a RuntimeError.
Project Structure
src/
├── config/ # Runtime configuration (Pydantic)
│ └── Config.py
├── helper/ # Shared helpers
│ ├── pandera.py # Pandera validation decorator
│ ├── output_dump.py # Content-addressed dumping of decorated-function output
│ ├── dump_folder.py # Dump folder configuration
│ ├── content_hash.py # 7-character content hashes for dump names
│ └── repo_root.py # Git root detection for the decorated function
├── duckdb_cache.py # Main caching decorator
├── duckdb_cache_helpers.py # Schema/model helper utilities
├── duckdb_cache_registry.py # Datastore namespace registry
├── duckdb_reader.py # Batched DuckDB Parquet reads
├── duckdb_retention.py # Overlapping range removal
└── parquet_normalization.py # DataFrame index flattening
Development
Running tests
pytest -m unit
Linting & type checking
ruff check src/ tests/
mypy src/
Pre-commit
pre-commit install
pre-commit run --all-files
Publishing
See br_pypi_publisher for the release workflow.
License
MIT
Metadata
Release files for br-py-duckdb-cache 0.6.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| br_py_duckdb_cache-0.6.1.tar.gz | 14.0 kB | Without provenance | Details for br_py_duckdb_cache-0.6.1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| br_py_duckdb_cache-0.6.1-py3-none-any.whl | Python 3 | none | any | Details for br_py_duckdb_cache-0.6.1-py3-none-any.whl |
Total release size: 29.0 kB
Release files / br_py_duckdb_cache-0.6.1.tar.gz
| Download URL | br_py_duckdb_cache-0.6.1.tar.gz |
|---|---|
| Size | 14.0 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
1c382810278ed9154940c9edf6892da7c96787946a95d87926e4de80951ae934
|
|
BLAKE2b-256 checksum How to use checksums |
6fb6f2c5717825b4c736adaeb46c7f0d8692f1786e8d954c151bafcd78bdd844
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.12.8
|
Release files / br_py_duckdb_cache-0.6.1-py3-none-any.whl
| Download URL | br_py_duckdb_cache-0.6.1-py3-none-any.whl |
|---|---|
| Size | 15.0 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
7add7cbef71ee4b93c0e5eb5a4ffd3b0787ebcdf164995e8a30abbd26de71b93
|
|
BLAKE2b-256 checksum How to use checksums |
fef5414c6654dd77fb9fefe89e9ff60ef20048f92dbb501e0572bd4e87a448d1
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.12.8
|
Security for br-py-duckdb-cache 0.6.1
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.