| .. | ||
| src | ||
| tests | ||
| Cargo.toml | ||
| README.md | ||
curate-etl
Dedicated zero-dependency Rust crate for the M1.2a split-factor lookup table / bar un-adjustment core, the M1.2b pure adj_factors builder, the M1.2c pure corporate_actions event-log builder, the M1.2d pure bars_1d daily bar builder + qmPrices.sharevolume cross-check, and the M1.2e pure fx_1d USD/CAD builder + carry-forward lookup.
Scope & Sign Conventions
Aligned with design/DATA-CONTRACTS.md (§1 qmSplits, eodPrices, eodIntraday1M):
- Split ratio:
ratio = new_shares / old_shares.- Forward split
10:1(e.g., NVDA on2024-06-10) →ratio = 10.0. - Reverse split
1:20(e.g., NEXM.V on2025-06-18) →ratio = 0.05. - No-op rows (
ratio == 1.0) are dropped duringSplitTable::from_events. - Duplicate events on the same
ex_dateare multiplied (and dropped if reciprocal pairs cancel to1.0). - Non-finite or
<= 0.0ratios and compounding overflow/underflow return a typedSplitErrorrather than panicking.
- Forward split
- Ex-date boundary (strict
>):cum_factor_after(key, bar_date)returns the product of all split ratios withex_date > bar_date. A bar dated on an ex-date excludes that day's split (it is already post-split for that event) while still including any later splits (for example, NVDA on its2021-07-204:1 ex-date still hasfactor = 10.0from the later2024-06-1010:1 split). Unknown keys and dates with no later splits return1.0. eodPrices(daily bars): OHLC is raw and only volume is retroactively split-adjusted:raw_volume = unadjust_volume(adj_volume, factor) = adj_volume / factor
eodIntraday1M(1m bars, reused in M2): both OHLC and volume are retroactively split-adjusted:raw_price = unadjust_price(adj_price, factor) = adj_price * factorraw_volume = unadjust_volume(adj_volume, factor) = adj_volume / factorunadjust_ohlcv(bar, factor)applies both so dollar volume (raw_close * raw_volume == adj_close * adj_volume) is invariant.
adj_factors Builder (M1.2b)
build_adj_factors (src/adj.rs) turns split (qmSplits) and cash-dividend (qmDividends) event streams into sorted, unique per-(key, ex_date) rows matching the adj_factors/part.parquet columns in design/DATA-CONTRACTS.md (listing_id, ex_date, split_factor, div_cash, div_currency, cum_split_factor, cum_total_factor), omitting usdFxRate per contract.
Contract interpretation note:
design/DATA-CONTRACTS.mdnamessplit_factor,div_cash,div_currency,cum_split_factor, andcum_total_factorwithout writing formulas. Rules 3–5 below document this crate's back-adjustment divisor definitions so downstream consumers and reviewers can verify parity withSplitTable::cum_factor_after.
Rules:
- Split normalization: Drop
ratio == 1.0no-ops (counted instats.split_noops_dropped). Multiply same-day splits inf64::total_cmporder; if they cancel back to1.0(e.g.2.0 * 0.5), drop the split component (and omit the row if no dividend is present on that date). - Dividend normalization: Drop
cash == 0.0events (counted instats.dividend_zero_cash_dropped). Sum same-day same-currency cash dividends inf64::total_cmporder intodiv_cash. Split-only rows carrydiv_cash = 0.0anddiv_currency = None; dividend-only rows carrysplit_factor = 1.0. Two different dividend currencies on the same(key, ex_date)returnAdjError::ConflictingDividendCurrency. cum_split_factor(back-adjustment divisor): Product ofsplit_factorover this row and all later rows of the same key (inclusive of the row's ownex_date). For any bar datedd, the first row withex_date > d(adj_factors_after(rows, key, d).0) matchesSplitTable::cum_factor_after(key, d)bitwise.- Per-row dividend factor:
prev_close / (prev_close - div_cash)whenprev_close(the raw close of the last session strictly beforeex_date) is present, finite,> div_cash > 0.0, andprev_close_currency == div_currency. Otherwise falls back to1.0in strict priority order while preservingdiv_cashanddiv_currencyon the row and incrementing the matching counter:dividends_missing_prev_close(prev_closeisNoneor non-finite)dividends_currency_mismatch(prev_close_currency != Some(div_currency))dividends_not_below_prev_close(prev_close <= div_cash)
cum_total_factor:cum_split_factormultiplied by the product of per-row dividend factors over this row and all later rows of the same key (inclusive of the row's ownex_date).- Validation & overflow guards: Non-finite or
<= 0.0split ratios (InvalidSplitRatio), non-finite or< 0.0dividend cash (InvalidDividendCash), empty/whitespace currency on positive cash (EmptyDividendCurrency), conflicting same-day dividend currencies (ConflictingDividendCurrency), and overflow/underflow of any combined or cumulative factor (FactorOverflow) return a typedAdjErrorwithout panicking.
Deferred out of src/adj.rs: cross-currency dividend FX conversion (waits for fx_1d). Point-in-time known_at clamping and delisting / Shumway rows live in src/corporate_actions.rs.
corporate_actions Builder (M1.2c)
build_corporate_actions (src/corporate_actions.rs) turns split (qmSplits), cash-dividend (qmDividends), and Pass 6 delisting outcome streams into a deterministically sorted event log matching the corporate_actions/part.parquet columns in design/DATA-CONTRACTS.md (listing_id, ex_date, declared_date, kind, ratio, cash_amount, currency, successor_listing_id, terminal_return, known_at, known_at_source).
Rules:
- Splits (
kind = "split"): Sameratio = new_shares / old_sharesconvention assrc/split.rs.ratio == 1.0no-ops are dropped and counted instats.split_noops_dropped. Non-finite or<= 0.0ratios returnCorporateActionError::InvalidSplitRatio. - Dividends (
kind = "dividend"): Localcurrencyandcashare preserved unchanged (deliberately omittingusdFxRate).cash == 0.0events are dropped and counted instats.dividend_zero_cash_dropped. Multiple dividends on the same(key, ex_date)remain separate event-log rows. Non-finite or< 0.0cash returnsInvalidDividendCash; empty/whitespace currency on positive cash returnsEmptyDividendCurrency. - Point-in-time
known_atclamping: Usesdeclared_datewhen present and<= ex_date(known_at_source = "declared_date"). Otherwise falls back toex_date(known_at_source = "ex_date_fallback"), preserving the rawdeclared_dateon the row and countingdeclared_date > ex_dateinstats.declared_after_ex_datesoknown_at_date <= ex_datealways holds. - Delistings (Pass 6):
successor_key = Some(s), terminal_return = None→ oneotc_delist_transferrow (ex_date = known_at_date = delist_date,known_at_source = "delist_date"). Callers must pass the Pass 6 continuityeffectiveDate(the successor's first observed OTC trading date) asdelist_date, not the primary listing's last exchange print / halt date.successor_key = None, terminal_return = Some(r)→ onedelistingrow (rmust be finite and in[-1.0, 0.0], normalizing-0.0to0.0, elseInvalidTerminalReturn).- Both
None→ dropped and counted instats.delist_without_outcome. - Both
Some→CorporateActionError::ConflictingDelistingOutcome.
- Determinism & accounting: Output rows are sorted by
(key, ex_date, kind, declared_date, ratio_bits, cash_bits, currency, successor_key, terminal_return_bits, known_at_date, known_at_source)so any input permutation yields byte-identical output, andstatssatisfiesin == out + droppedper kind andknown_at_declared_date + known_at_ex_date_fallback + known_at_delist_date == rows_out.
bars_1d Builder (M1.2d)
build_bars_1d (src/bars.rs) turns raw eodPrices daily bars (EodDailyBar<K>) into sorted, unique per-(key, session_date) Bar1dRow<K> rows matching the contract sort (listing_id, session_date) in design/DATA-CONTRACTS.md, un-adjusting share volume via &SplitTable<K> and cross-checking against optional qmPrices.sharevolume observations (QmRawVolume<K>).
Rules:
- Raw OHLC & un-adjusted volume:
eodPricesOHLC is passed through bit-for-bit;volume = unadjust_volume(adj_volume, factor)wherefactor = splits.cum_factor_after(&key, session_date)(computed via a per-key monotonic cursor oversplits.splits_for(&key)that matchescum_factor_afterbitwise under the strictex_date > session_dateboundary). - Bad-row resilience (never aborts on single-row errors): Invalid bars are dropped and counted in strict priority order:
dropped_invalid_ohlc: any OHLC field non-finite or<= 0.0.dropped_inconsistent_ohlc:high < low, oropen/closeoutside[low, high].dropped_invalid_volume:adj_volumenon-finite or< 0.0, or post-unadjustmentvolumenon-finite or< 0.0(e.g. extreme reverse-split overflow). Zero volume (0.0/-0.0normalized to0.0) is valid and kept.
- Deduplication: After filtering bad bars, bitwise-identical duplicate
(key, session_date)rows collapse to one (duplicate_collapsed += n - 1). Conflicting duplicates for the same(key, session_date)drop the entire group (duplicate_conflict_dropped += n). - Caller errors (
BarsError): Reserved strictly for caller configuration errors (BarsError::InvalidTolerancewhenrel_toleranceis non-finite or< 0.0). Invalid/duplicate/conflictingqmPricesrows are filtered and compacted intoqm_invalid_volume_dropped,qm_duplicate_collapsed, andqm_duplicate_conflict_droppedwithout aborting. qmPrices.sharevolumecross-check (read-only): Never modifies emitted bars; EOD remains the row source. For each output row with a unique QM partner on(key, session_date):- Both
0.0→rel = 0.0(match);share_volume == 0.0withvolume > 0.0→rel = INFINITY(mismatch); otherwiserel = |volume - share_volume| / share_volume(within iffrel <= rel_tolerance). - Retains up to
MAX_MISMATCH_SAMPLES(100) worst mismatches sorted deterministically by(rel DESC, key ASC, session_date ASC).
- Both
- Determinism & accounting invariants: Any permutation of
barsorqm_volumesproduces bitwise-identicalrows,stats, andmismatch_samples, and:bars_in == rows_out + dropped_invalid_ohlc + dropped_inconsistent_ohlc + dropped_invalid_volume + duplicate_collapsed + duplicate_conflict_droppedvolume_checked + volume_unchecked == rows_outandvolume_within_tolerance + volume_mismatched == volume_checkedqm_rows_in == qm_unique_partners + qm_invalid_volume_dropped + qm_duplicate_collapsed + qm_duplicate_conflict_dropped
fx_1d Builder (M1.2e)
build_fx_1d (src/fx.rs) merges CAD.FOREX daily bars (FxSource::EodCadForex, "eod_cad_forex", 1971–2025) and teMarketData.USDCAD daily bars (FxSource::TeUsdCad, "te_usdcad", through 2026+) into a single sorted, unique USDCAD series (Fx1dRow) matching the fx_1d/part.parquet value columns in design/DATA-CONTRACTS.md (excluding ts/known_at timestamps, which belong to the later writer task).
Rules:
- Quote convention: Both inputs are USD/CAD quotes (CAD per 1 USD); no inversion is performed in this module (
CADUSD.FOREXinversion is out of scope). - Per-source filtering (strict priority, never panics or aborts):
dropped_invalid_ohlc: any OHLC field non-finite or<= 0.0.dropped_inconsistent_ohlc:high < low, oropen/closeoutside[low, high].
- Per-source deduplication on
session_date: Bitwise-identical duplicates collapse to one (duplicate_collapsed += n - 1); conflicting duplicate groups drop entirely (duplicate_conflict_dropped += n). - Merge precedence:
EodCadForexwins on overlapping dates (te_superseded_by_eod += 1);TeUsdCadfills interior gaps and all dates after EOD's last date (as well as dates where EOD dropped an invalid or conflicting group). - Read-only overlap cross-check: On every date where both sources survive, evaluates
|eod.close - te.close| / eod.close <= FX_OVERLAP_REL_TOLERANCE(0.01, 1% inclusive with a small IEEE-754 rounding slack so exact decimal 1% pairs like1.4000vs.1.4140are not falsely flagged), countsoverlap_checked,overlap_within_tolerance, andoverlap_mismatched, and tracks rawmax_overlap_relwithout modifying emitted rows. - No-look-ahead lookup (
fx_rate_on_or_before): Binary-searches sortedFx1dRowslices for the latest row withsession_date <= dateanddate - session_date <= max_stale_days. Carries forward across weekends/holidays withinmax_stale_days, returnsNonebefore the first row or when stale, and never returns a later date. - Determinism & accounting invariants: Any permutation of
eodorteyields bitwise-identicalrowsandstats, and:- Per source:
rows_in == rows_kept + dropped_invalid_ohlc + dropped_inconsistent_ohlc + duplicate_collapsed + duplicate_conflict_dropped - Merge:
rows_out == eod.rows_kept + te.rows_kept - te_superseded_by_eod == eod_rows_out + te_rows_out - Overlap:
overlap_within_tolerance + overlap_mismatched == overlap_checked == te_superseded_by_eod
- Per source:
Deferred out of src/fx.rs: ts/known_at timestamp derivation (later writer task), CADUSD.FOREX inversion, fx_1m intraday FX, and wiring FX into src/adj.rs cross-currency dividends.
Local Benchmarks
bench-split
Fixed-seed (std-only SplitMix64), zero-allocation hot-loop benchmark over 20,000 symbol keys and 19,000 forward/reverse split events spanning 1990-01-01..=2025-12-31 (default 10,000,000 bar lookups + unadjust_volume):
cargo run --release -p curate-etl --offline -- bench-split [rows]
Command: cargo run --release -p curate-etl --offline -- bench-split
- Table:
keys=20000,keys_with_splits=12153,events=18999,build=1.73 ms - Run:
rows=10000000,elapsed=367.40 ms,throughput=27218476 rows/s,latency=36.74 ns/row,checksum=259124314244145.531
bench-adj
Fixed-seed (std-only SplitMix64) benchmark over 20,000 i32 listing_id keys spanning 1990-01-01..=2025-12-31 with ~4% splits and ~96% dividends (default 1,000,000 mixed events), timing only build_adj_factors:
cargo run --release -p curate-etl --offline -- bench-adj [events]
Command: cargo run --release -p curate-etl --offline -- bench-adj
- Input:
events=1000000,splits=39861,dividends=960139,keys=20000 - Build:
rows_out=986702,keys_out=20000,elapsed=242.94 ms,throughput=4116183 events/s,latency=242.94 ns/event,checksum=17888280.062 (0x41710f4180ff5d60)(bitwise identical across back-to-back runs) - Stats:
split_noops=1988,zero_div=9527,missing_prev_close=19089,currency_mismatch=19147,not_below_prev_close=9693
bench-corporate-actions
Fixed-seed (std-only SplitMix64) benchmark over 20,000 i32 listing_id keys spanning 1990-01-01..=2025-12-31 with ~4% splits, ~92% USD/CAD dividends, and ~4% delisting outcomes (default 1,000,000 mixed events), timing only build_corporate_actions:
cargo run --release -p curate-etl --offline -- bench-corporate-actions [events]
Command: cargo run --release -p curate-etl --offline -- bench-corporate-actions
- Input:
events=1000000,splits=39872,dividends=920134,delistings=39994,keys=20000 - Build:
rows_out=980694,keys_out=20000,elapsed=107.48 ms,throughput=9303979 events/s,latency=107.48 ns/event,checksum=0xbfd2ceda373762f5(identical across back-to-back runs) - Stats:
split_noops=1963,zero_div=9302,delist_no_outcome=8041,otc_transfers=11942,delistings=20011,declared=758098,ex_fallback=190643,declared_after_ex=19108,delist_date=31953
bench-bars
Fixed-seed (std-only SplitMix64) benchmark over 20,000 i32 listing_id keys and 19,000 splits spanning 1990-01-01..=2025-12-31 (default 10,000,000 daily bars with a small share of invalid/duplicate rows and ~50% qmPrices.sharevolume partners), timing only build_bars_1d:
cargo run --release -p curate-etl --offline -- bench-bars [rows]
Command: cargo run --release -p curate-etl --offline -- bench-bars
- Input:
rows=10000000,qm_rows=4912050,splits=18998,keys=20000 - Build:
rows_out=9488072,keys_out=20000,elapsed=842.38 ms,throughput=11871057 rows/s,latency=84.24 ns/row,checksum=0x25fae7ad0816891b(identical across back-to-back runs) - Stats:
invalid_ohlc=20006,inconsistent_ohlc=19818,invalid_vol=19812,dup_collapsed=47627,dup_conflict=404665,checked=4721305,within_tol=4673885,mismatched=47420,unchecked=4766767,max_rel_diff=0.130435,samples=100
bench-fx
Fixed-seed (std-only SplitMix64) benchmark over ~20,000 daily USD/CAD rows (~80% CAD.FOREX, ~20% teMarketData.USDCAD with an overlap window, interior gaps, post-EOD tail, injected bad/duplicate rows, and ~5% overlap mismatches), timing build_fx_1d plus 1,000,000 zero-allocation fx_rate_on_or_before lookups:
cargo run --release -p curate-etl --offline -- bench-fx [rows]
Command: cargo run --release -p curate-etl --offline -- bench-fx
- Input:
rows=20000,eod_rows=16000,te_rows=4000 - Build:
rows_out=17172,eod_out=15336,te_out=1836,elapsed=0.741 ms,throughput=26993285 rows/s,latency=37.05 ns/row - Lookup:
lookups=1000000,hits=999224,elapsed=25.68 ms,throughput=38946650 lookups/s,latency=25.68 ns/lookup,checksum=0x21e746bd53f3e7ff(identical across back-to-back runs) - Stats:
eod_invalid=164,eod_inconsistent=170,eod_dup_collapsed=165,eod_dup_conflict=165,te_invalid=21,te_inconsistent=23,te_dup_collapsed=21,te_dup_conflict=34,te_superseded=2065,overlap_checked=2065,within_tol=1954,mismatched=111,max_overlap_rel=0.025000
Deferred Follow-Ups (M1.2f+ / M2)
This crate currently uses std only so it builds strictly offline. Follow-up tasks (IO wiring and crates.io dependencies) will add:
bars_1dandfx_1dschema metadata columns (ts,known_at,currency,source,vwap) requiring exchange session/timezone and listing metadataCADUSD.FOREXinversion,fx_1mintraday FX, and wiringfx_1dintosrc/adj.rscross-currency dividendsyear=YYYYpartitioning, Zstd-compressed Parquet writer for curated daily/intraday datasets, andqmPricesOHLC cross-check- Read-only MongoDB
RawDocumentBufstreaming cursors (eodPrices,eodIntraday1M,qmSplits) - PostgreSQL
provider_mappingpreload keyed bylisting_id: i32(supported via genericSplitTable<K>) rayonparallel sharding across symbol/date partitions- QuestDB ILP v2 writer for time-series ingestion