Skip to main content

predcache

Persistent timestamp-keyed prediction cache and batched inference runner for ML models.

Extracted and generalized from a production neural-network trading system where full-range backtests over 100,000+ bars were dominated by redundant model inference. Storing predictions keyed by bar timestamp (not row index) makes any sub-range replayable without offset alignment — and makes incremental backtests reuse everything previously computed. The result: full-range runs went from hours to minutes.

Why

Typical ML backtesting pipelines recompute model inference for the same bars on every run — every parameter sweep, every range extension, every "what if". predcache decouples the two expensive parts:

  1. Feature-window assembly — building look-back feature rows from an OHLC frame (most-recent-first, warmup-aware), with your domain logic plugged in via row_fn.
  2. Batched inference — scoring rows through any model callable (Keras, PyTorch, ONNX, sklearn) in fixed batches with progress reporting.
  3. Persistent caching — predictions keyed by timestamp, saved atomically, so the next run computes only what's missing.

Install

pip install predcache              # core (numpy only)
pip install predcache[parquet]     # + parquet backend

Quick start

import pandas as pd
from predcache import PredictionCache, BatchedInferenceRunner, FeatureWindowAssembler

# 1. Assemble feature windows (your domain logic stays in row_fn)
assembler = FeatureWindowAssembler(
    window=50, warmup=500,
    row_fn=lambda win: my_feature_logic(win),   # 1-D feature vector per window
)
X, keys = assembler.build(df, key_col="time")   # X: (n_bars - warmup, n_features)

# 2. Batched inference through any model
runner = BatchedInferenceRunner(
    n_samples=len(X),
    inference_fn=lambda s, e: model.predict(X[s:e], verbose=0),
    batch_size=500,
)
preds = runner.run()

# 3. Cache by timestamp — next run computes only missing bars
cache = PredictionCache("predictions.pkl")
out = cache.get_or_compute(
    keys=keys,
    compute_fn=lambda missing: predict_bars(X, keys, missing),
)

Features

  • Timestamp-keyed cache — sub-range extraction without offset alignment; row-index caches silently break on slicing/resampling, timestamp keys don't.
  • Atomic saves — temp file + os.replace; a crash mid-save never corrupts an existing cache.
  • Pluggable backends — pickle (zero-dependency) and parquet ship in the box; register custom backends with register_backend(name, dump, load).
  • Batched inference runner — framework-agnostic (start, stop) -> scores contract, progress callbacks, tuned default batch size (500).
  • OpenTelemetry instrumentation — optional spans + counters for cache hits, computed predictions, batched inference and feature assembly (see below).
  • L-inf normalization helper matching the source system's normalize_vector_absolute.

Observability (OpenTelemetry)

predcache emits spans and counters for every expensive operation. The opentelemetry-api package is optional: without it predcache runs identically with zero overhead; with it installed, signals flow to whatever Tracer/Meter provider your application configured.

pip install predcache[otel]        # pull in opentelemetry-api
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor, ConsoleSpanExporter

trace.set_tracer_provider(TracerProvider())
trace.get_tracer_provider().add_span_processor(
    BatchSpanProcessor(ConsoleSpanExporter())
)

from predcache import PredictionCache

cache = PredictionCache("preds.pkl")
cache.get_or_compute(keys, compute_fn)
# -> span "predcache.get_or_compute" with predcache.requested / .computed /
#    .hits / .elapsed_s attributes, + predictions.computed counter
Signal Name Attributes
span predcache.get_or_compute predcache.requested, .computed, .hits, .elapsed_s
span predcache.inference predcache.rows, .batch_size, .elapsed_s
span predcache.features predcache.windows, .window, .warmup, .elapsed_s
counter predcache.predictions.computed / .hits —
counter predcache.inference.batches / .rows —

Set PREDCACHE_OTEL=0 to disable emission entirely (hot loops, test runs).

Origin

This package is the generalized core of the prediction-serving layer of Neuromomentum's production trading system (three Keras classifiers, MT5 live execution, 2012–2026 backtest range). The original cache manager was 542 lines of domain-specific code; what ships here is the reusable pattern: timestamp-keyed persistence, compute-only-missing, batched scoring, windowed feature assembly.

License

MIT — see LICENSE.

Metadata

Release files for predcache 0.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for predcache 0.2.0
File Size Uploaded Provenance Actions
predcache-0.2.0.tar.gz 16.0 kB With provenance Details for predcache-0.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for predcache 0.2.0
File Interpreter ABI Platform Actions
predcache-0.2.0-py3-none-any.whl Python 3 none any Details for predcache-0.2.0-py3-none-any.whl

Total release size: 29.0 kB

Release files / predcache-0.2.0.tar.gz

Download URL predcache-0.2.0.tar.gz
Size 16.0 kB
Tags Source
SHA-256 checksum
How to use checksums
904ac5645d4e9587303eeb256e06a910fc82eafd79f1c1adcd3d73f8b9896f6d
BLAKE2b-256 checksum
How to use checksums
5d3467acf0167c47496865ec2183e5b32dfa2a73cd8c033d89f7797685274571
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 13, 2026.

Transparency log

Release files / predcache-0.2.0-py3-none-any.whl

Download URL predcache-0.2.0-py3-none-any.whl
Size 13.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
afa34b66239587353068324a5fa6194e47c8c828aa72b396ea18c21f9f3b3be2
BLAKE2b-256 checksum
How to use checksums
ffaf532d3bc0f85874a0f9070786c0f64de993c71f14a117ebf309361b3d28dc
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 13, 2026.

Transparency log

Security for predcache 0.2.0

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.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for predcache-0.2.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 13, 2026.

Transparency log

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.

Release history Release notifications | RSS feed

This release

0.2.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page