1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
//! # tickbar
//!
//! High-performance tick-to-bar aggregator for financial market data.
//!
//! Converts raw trade/quote ticks into OHLCV bars with configurable
//! time alignment, gap filling, VWAP, and corporate action adjustments.
//! Processes up to **119M ticks/second** from native Rust.
//!
//! # Install
//!
//! ```toml
//! [dependencies]
//! tickbar = "0.1"
//! ```
//!
//! Optional feature flags:
//!
//! ```toml
//! [dependencies]
//! tickbar = { version = "0.1", default-features = false } # no Python bindings
//! tickbar = { version = "0.1", features = ["arrow-export"] } # + Arrow IPC
//! tickbar = { version = "0.1", features = ["polars-export"] } # + Polars DataFrame
//! ```
//!
//! # Core concepts
//!
//! tickbar models tick-to-bar aggregation in three layers:
//!
//! - **Tick ingestion** — [`Tick`] is a 32-byte `repr(C)` struct holding
//! `timestamp_nanos`, fixed-point `price`, fixed-point `volume`, and
//! `flags`. Use [`TickBuffer`] for batched ingestion with ordering
//! and dedup policies. Use [`MmapTickReader`] for memory-mapped I/O
//! from binary tick files.
//!
//! - **Bar aggregation** — [`TickAggregator`] is a one-pass state machine
//! built via its [`TickAggregatorBuilder`]. It advances bar boundaries
//! on each tick, optionally fills gaps, and tracks per-bar VWAP.
//! [`BarAggregator`] is the lower-level engine. Use [`aggregate_parallel`]
//! for multi-symbol parallelism.
//!
//! - **Output** — [`BarSeries`] holds completed [`Bar`]s for one symbol.
//! Export to CSV, Arrow IPC, or Polars DataFrame. Resample to a wider
//! interval. Apply split/dividend adjustments.
//!
//! # Quick start
//!
//! ```rust
//! use tickbar::{TickAggregator, Tick};
//! use std::time::Duration;
//!
//! let mut agg = TickAggregator::builder()
//! .interval(Duration::from_secs(60))
//! .symbol("AAPL")
//! .build()?;
//!
//! agg.push_tick(Tick::from_trade(0, 100.0, 1000.0))?;
//! agg.push_tick(Tick::from_trade(1_000_000_000, 100.5, 500.0))?;
//! agg.push_tick(Tick::from_trade(2_000_000_000, 101.0, 750.0))?;
//!
//! let bars = agg.finalize();
//! assert_eq!(bars.as_slice().len(), 1);
//! assert_eq!(bars.as_slice()[0].tick_count, 3);
//! # Ok::<_, tickbar::Error>(())
//! ```
//!
//! # Batch processing
//!
//! Use [`TickBuffer`] to collect ticks with configurable ordering
//! and duplicate policies, then ingest as a batch:
//!
//! ```rust
//! use tickbar::{TickAggregator, Tick, TickBuffer, DuplicatePolicy};
//! use std::time::Duration;
//!
//! let mut buf = TickBuffer::new("MSFT")
//! .with_allow_unordered(false)
//! .with_duplicate_policy(DuplicatePolicy::Last);
//!
//! buf.push(Tick::from_trade(0, 100.0, 1000.0))?;
//! buf.push(Tick::from_trade(1_000_000_000, 100.5, 500.0))?;
//! buf.push(Tick::from_trade(2_000_000_000, 101.0, 750.0))?;
//!
//! let mut agg = TickAggregator::builder()
//! .interval(Duration::from_secs(60))
//! .symbol("MSFT")
//! .build()?;
//!
//! agg.push_ticks(buf.as_slice())?;
//! let bars = agg.finalize();
//! assert_eq!(bars.as_slice().len(), 1);
//! # Ok::<_, tickbar::Error>(())
//! ```
//!
//! # Gap filling
//!
//! Enable gap filling on the builder to produce empty bars for
//! periods with no trading activity:
//!
//! ```rust
//! use tickbar::{TickAggregator, Tick};
//! use std::time::Duration;
//!
//! let mut agg = TickAggregator::builder()
//! .interval(Duration::from_secs(60))
//! .fill_gaps(true)
//! .symbol("GOOG")
//! .build()?;
//!
//! // Tick at T=0s, next tick at T=300s — four 60s gaps in between
//! agg.push_tick(Tick::from_trade(0, 100.0, 1000.0))?;
//! agg.push_tick(Tick::from_trade(300_000_000_000, 101.0, 500.0))?;
//!
//! let bars = agg.finalize();
//! // 2 real bars + 4 gap-filled bars = 6 total
//! assert_eq!(bars.as_slice().len(), 6);
//! # Ok::<_, tickbar::Error>(())
//! ```
//!
//! # Parallel multi-symbol
//!
//! Distribute ticks by symbol, then aggregate in parallel:
//!
//! ```rust
//! use std::collections::HashMap;
//! use tickbar::{Tick, AggregatorConfig, TimeAlignment, aggregate_parallel};
//!
//! let mut ticks_by_symbol: HashMap<String, Vec<Tick>> = HashMap::new();
//! ticks_by_symbol.insert(
//! "AAPL".into(),
//! vec![Tick::from_trade(0, 100.0, 1000.0),
//! Tick::from_trade(1_000_000_000, 100.5, 500.0)],
//! );
//! ticks_by_symbol.insert(
//! "MSFT".into(),
//! vec![Tick::from_trade(0, 200.0, 2000.0),
//! Tick::from_trade(2_000_000_000, 201.0, 1000.0)],
//! );
//!
//! let config = AggregatorConfig {
//! interval_nanos: 60_000_000_000,
//! alignment: TimeAlignment::UTC,
//! fill_gaps: false,
//! forward_fill: false,
//! price_decimals: 8,
//! volume_decimals: 6,
//! };
//!
//! let results = aggregate_parallel(ticks_by_symbol, config);
//! for (symbol, result) in &results {
//! let series = result.as_ref().unwrap();
//! println!("{symbol}: {} bars", series.as_slice().len());
//! }
//! ```
//!
//! # Adjustments
//!
//! Apply stock splits and dividend adjustments to a completed bar series.
//! Bars with timestamps *before* an event's timestamp are adjusted backward:
//!
//! ```rust
//! use tickbar::{BarSeries, Bar, AdjustmentEvent, AdjustmentType};
//!
//! let mut series = BarSeries::new("AAPL", 60_000_000_000);
//! series.push(Bar {
//! timestamp_nanos: 0,
//! open: 10_000_000_000,
//! high: 10_100_000_000,
//! low: 9_900_000_000,
//! close: 10_050_000_000,
//! volume: 100_000,
//! tick_count: 10,
//! vwap: 10_020_000_000,
//! });
//!
//! // Event timestamp must be strictly after the bars it adjusts
//! let events = vec![AdjustmentEvent {
//! timestamp: 60_000_000_000,
//! adjustment_type: AdjustmentType::Split(4.0),
//! }];
//!
//! series.apply_adjustments(&events);
//! // Prices are divided by 4, volume multiplied by 4
//! assert_eq!(series.as_slice()[0].open, 2_500_000_000); // 10_000_000_000 / 4
//! assert_eq!(series.as_slice()[0].volume, 400_000); // 100_000 * 4
//! ```
//!
//! # Python
//!
//! ```python
//! from tickbar import TickAggregator, Tick
//!
//! agg = TickAggregator(interval_secs=60)
//! agg.push_tick(Tick(0, 100.0, 1000.0))
//! bars = agg.finalize()
//! ```
//!
//! # Memory-mapped file reader
//!
//! Read packed `Tick` binary files via `mmap`:
//!
//! ```rust
//! use tickbar::{MmapTickReader, BarAggregator, TimeAlignment};
//!
//! // Assuming /tmp/ticks.bin exists with packed 32-byte Tick records
//! if let Ok(reader) = MmapTickReader::open("/tmp/ticks.bin") {
//! let ticks: Vec<_> = reader.collect();
//! let mut agg = BarAggregator::new(
//! 60_000_000_000, TimeAlignment::UTC, 8, 0,
//! false, false,
//! ticks.first().map(|t| t.timestamp_nanos).unwrap_or(0),
//! );
//! agg.ingest_ticks_unchecked(&ticks);
//! let bars = agg.finalize();
//! println!("{} bars from mmap", bars.as_slice().len());
//! }
//! ```
//!
//! # CSV export
//!
//! Write bars to CSV format:
//!
//! ```rust
//! use tickbar::{BarSeries, Bar};
//!
//! let mut series = BarSeries::new("AAPL", 60_000_000_000);
//! series.push(Bar {
//! timestamp_nanos: 0, open: 10000, high: 10100, low: 9900,
//! close: 10050, volume: 100000, tick_count: 10, vwap: 10020,
//! });
//!
//! let mut buf = Vec::new();
//! let mut wtr = csv::Writer::from_writer(&mut buf);
//! series.to_csv(&mut wtr)?;
//! drop(wtr);
//! let output = String::from_utf8(buf)?;
//! assert!(output.contains("10000")); // open price in CSV
//! # Ok::<_, Box<dyn std::error::Error>>(())
//! ```
//!
//! # Trading calendar
//!
//! Filter ticks outside of trading hours:
//!
//! ```rust
//! use tickbar::{TradingCalendar, Tick};
//!
//! let cal = TradingCalendar::new(vec![
//! (9 * 3_600_000_000_000, 16 * 3_600_000_000_000), // 9:00-16:00 UTC
//! ]);
//!
//! let tick = Tick::from_trade(10 * 3_600_000_000_000, 100.0, 1000.0); // 10:00 UTC
//! assert!(cal.is_trading_time(tick.timestamp_nanos));
//!
//! let tick = Tick::from_trade(20 * 3_600_000_000_000, 100.0, 1000.0); // 20:00 UTC
//! assert!(!cal.is_trading_time(tick.timestamp_nanos));
//! ```
//!
//! # Performance
//!
//! | Path | Throughput | vs pandas |
//! |------|-----------|-----------|
//! | Rust native | 119M ticks/s | 25× |
//! | Python buffer (PEP 3118) | 6.7M ticks/s | 1.4× |
//! | Python numpy | 6.5M ticks/s | 1.4× |
//! | pandas resample | 4.7M ticks/s | 1.0× |
//!
//! Benchmarked on 70K synthetic ticks from 9 S&P tickers via yfinance.
//!
//! # Feature flags
//!
//! | Feature | Description | Default |
//! |---------|-------------|---------|
//! | `python` | PyO3 bindings for maturin | yes |
//! | `arrow-export` | Arrow IPC export via `to_arrow()` | no |
//! | `polars-export` | Polars DataFrame export + arrow | no |
//!
//! # Quality and CI guarantees
//!
//! The repository CI enforces:
//!
//! - `cargo test --workspace` (25 unit + 9 integration + 1 doc test)
//! - `cargo clippy --all-features` (zero warnings)
//! - `RUSTFLAGS="-D missing_docs" cargo doc --no-deps` (100% docs coverage)
//! - `cargo-semver-checks` on release candidates
//!
//! # Support
//!
//! - Issues: <https://github.com/gregorian-09/tickbar/issues>
//! - Repository: <https://github.com/gregorian-09/tickbar>
//! - Crates.io: <https://crates.io/crates/tickbar>
//! - PyPI: <https://pypi.org/project/tickbar/>
/// Foreign function interface bindings.
/// Utility modules for fixed-point conversion and time handling.
pub use ;
pub use ;
pub use TimeAlignment;
pub use ;
pub use ;
use Error;
/// Errors that can occur during tick aggregation.
/// Alias for `Result<T, tickbar::Error>`.
pub type Result<T> = Result;