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:
- Push my skills at writing high-performance code as far as possible, under the time, latency and computational constraints of the problems the library solves.
- Learn to write more idiomatic Rust.
- Build a tool I can actually use: the interfaces must be simple, logical, and adaptable enough for different use cases without becoming a mess.
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).
Panel and TemporalSeries delegate to TimeSeries, and storage sits behind a single trait.-
Time is an
i64with a unit, not a datetime type.- The index is a list of plain integers (
Vec<i64>) tagged with aTimeUnit(seconds, milliseconds, microseconds or nanoseconds). chronois 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
i64only cover roughly the years 1677 to 2262, which is whyfrom_datetimecan panic on overflow.
- The index is a list of plain integers (
-
Storage sits behind a trait (
StorageBackend<T>).- There are three implementations:
ColumnarBackend(one contiguousVec<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.
- There are three implementations:
-
A generic type (
TemporalSeries<T, B>) alongside a concrete one (TimeSeries).- All the analysis lives in exactly one place,
TimeSeries.TemporalSeriesandPanelonly pass work through to it. - The trade-off:
TemporalSeriescopies its values into aVec<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.
- All the analysis lives in exactly one place,
-
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.
-
Invalid state is rejected at construction.
newrejects 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.
-
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.
- Everything returns a single error type (
-
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 for a series of length and a window of size .
-
Small core, optional features.
chrono,serdeandparquetare 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.
-
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.
Paneltests only check that it hands each column toTimeSeriescorrectly, 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:
- Incremental rolling windows: replace the from-scratch recomputation with incremental algorithms (a running sum, Welford’s algorithm for the standard deviation, a monotonic queue for min and max) to bring rolling windows down from to , keeping them numerically stable on long series.
- A memory-mapped backend: a
StorageBackendover a memory-mapped file, so series larger than RAM can be analysed without loading them first. - Storage backends head to head: benchmark
ColumnarBackend,RowBackendandChunkedBackendon the workloads each one is meant for (full scans, record-at-a-time ingestion and high-frequency appends) and see where each layout wins or loses. - Single algorithm vs. zero-copy: measure what
TemporalSeriespays for copying its values into aVec<f64>before every calculation, and explore running the algorithms directly over anyStorageBackend(generic iterators or slices) without giving up a single implementation of each method. - Boxed vs. static iterators: benchmark
iter()returning aBox<dyn Iterator>against an associated iterator type (type Iter<'a>: Iterator<Item = &'a T>) with criterion, and measure how much the dynamic dispatch really costs on long scans.
I also want to fix these known bugs, tracked on GitHub:
- Invalid rolling windows (#9):
RollingSeries::mean,sum,minandmaxshould returnInvalidWindowinstead of panicking (or silently returningNaN) when the window is0or larger than the series. - Out-of-range timestamps (#10):
TimeUnit::from_datetimeandTemporalSeries::from_datetimesshould return an error instead of panicking when a date doesn’t fit in ani64of nanoseconds.