TemporalSeries: Designing a Time-Series Library in Rust

Introduction

A few months ago I started going deeper into Rust internals, and I was looking for a project that would really push my ability to write idiomatic, high-performance Rust to the limit. Coincidentally, I was working on some projects that processed large volumes of financial data in an environment where resources are constrained and latency must be bounded. The timing was perfect. The result is TemporalSeries, a Rust library for quantitative time-series analysis, available on crates.io with documentation on docs.rs.

With this project I have three main goals:

A quick look

Add it to a project with cargo add temporalseries. Here is a short example: daily returns and a 3-day momentum signal for one asset, then the average for several assets at once.

use temporalseries::panel::Panel;
use temporalseries::series::TimeSeries;

fn main() {
    // A single series: an integer index (e.g. Unix seconds) and its values.
    let index: Vec<i64> = (1..=6).collect();
    let prices = TimeSeries::new(
        index.clone(),
        vec![100.0, 101.5, 99.8, 102.3, 103.1, 104.0],
    )
    .unwrap();

    let returns = prices.pct_change().unwrap(); // value[t] / value[t-1] - 1
    let momentum = returns.rolling(3).mean().unwrap(); // lazy rolling window
    println!("momentum: {:?}", momentum.values);
    println!("volatility: {:.4}", returns.std_deviation());

    // Several series sharing one index: every method works the same way.
    let panel = Panel::new(
        index,
        vec!["AAPL".into(), "MSFT".into()],
        vec![
            vec![150.0, 152.0, 149.0, 153.0, 155.0, 154.0],
            vec![300.0, 305.0, 298.0, 310.0, 308.0, 312.0],
        ],
    )
    .unwrap();
    println!("mean price per symbol: {:?}", panel.mean());
}

More examples (rolling statistics, panels, CSV and Parquet I/O, statistical tests) are in the repository’s examples/ folder.

Some initial architecture decisions

So far, I have made the following architecture decisions. I’ll discuss some of them in depth in future articles, expanding the reasoning with experiments I’ll share here (with links to everything).

TemporalSeries architecturePanel delegates column by column to TimeSeries, which owns all the analytical logic. TemporalSeries also delegates to TimeSeries and is backed by the StorageBackend trait, which is implemented by ColumnarBackend, RowBackend and ChunkedBackend.Panelnamed columns on a shared indexdelegates column by columnTimeSeriesVec<i64> index + Vec<f64> valuesowns all the analytical logicdelegates toTemporalSeries<f64, B>generic over any storage backendbacked bytrait StorageBackend<T>ColumnarBackendVec<T>column scansRowBackendVec<RowRecord<T>>record ingestionChunkedBackendVec<Vec<T>>fast appends
How the pieces fit: Panel and TemporalSeries delegate to TimeSeries, and storage sits behind a single trait.
  1. Time is an i64 with a unit, not a datetime type.

    • The index is a list of plain integers (Vec<i64>) tagged with a TimeUnit (seconds, milliseconds, microseconds or nanoseconds).
    • chrono is only converted to and from at the edges, behind an optional feature.
    • Why: integers are cheap to compare, store and serialise, and the core library stays free of dependencies.
    • The trade-off: nanoseconds in an i64 only cover roughly the years 1677 to 2262, which is why from_datetime can panic on overflow.
  2. Storage sits behind a trait (StorageBackend<T>).

    • There are three implementations:
      • ColumnarBackend (one contiguous Vec<T>): best for scans and aggregations.
      • RowBackend (timestamp and value per record): natural for ingesting one record at a time.
      • ChunkedBackend (fixed-size chunks): lets you append without reallocating the whole buffer.
    • This trait is the core of the library, and it’s where I’ll plug in a memory-mapped backend later.
  3. A generic type (TemporalSeries<T, B>) alongside a concrete one (TimeSeries).

    • All the analysis lives in exactly one place, TimeSeries. TemporalSeries and Panel only pass work through to it.
    • The trade-off: TemporalSeries copies its values into a Vec<f64> (iter().copied().collect()) before each calculation, and always returns a columnar series. I chose to keep a single copy of each algorithm over zero-copy performance.
  4. iter() returns a boxed iterator (Box<dyn Iterator>).

    • This keeps the trait easy to implement and usable as a trait object, but every value goes through a dynamic call, which blocks inlining and vectorisation.
    • The alternative is an associated iterator type, which lets the compiler see through the abstraction.
  5. Invalid state is rejected at construction.

    • new rejects an index and values of different lengths, and after that every method trusts the data.
    • One gap: the index is documented as monotonically increasing, but nothing checks it (yet). Slicing and resampling, which are next on the roadmap, depend on that ordering, so whether to enforce it at construction is still an open question.
  6. One error type and “no panics in library code”.

    • Everything returns a single error type (TemporalSeriesError), and each error variant is tested on its own.
    • To be honest, the rule doesn’t fully hold yet: there are two known gaps (#9 and #10), listed under Future work.
  7. Rolling windows are lazy handles.

    • series.rolling(n) returns a lightweight handle that borrows the series, so you can call .mean(), .sum(), .min() and so on without copying.
    • Each window is currently recomputed from scratch, which costs O(n⋅w)O(n \cdot w) for a series of length nn and a window of size ww.
  8. Small core, optional features.

    • chrono, serde and parquet are all optional, so the default build has zero runtime dependencies.
    • That means faster compiles, smaller binaries and less third-party code to audit, which matters in the constrained environments I described in the introduction.
  9. Designed to be tested.

    • The test tree mirrors the source tree: there’s one test file per method, and all tests compile into a single binary.
    • Panel tests only check that it hands each column to TimeSeries correctly, not the maths again.
    • Finding the tests for any method is a predictable path lookup, never a search.

Future work

Here is some of the future work I plan to do and share. I’ll link the articles and experiments here as soon as they’re ready:

I also want to fix these known bugs, tracked on GitHub:

Related