@tidal-ts/core 0.26.0 → 0.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/derive.d.ts CHANGED
@@ -43,9 +43,10 @@ export type DeriveOp = TidalOp | (string & {});
43
43
  * comparison ticker's series onto the primary (role-bound pair legs,
44
44
  * TDL-PAIR stage 1): `cmp_iv21` is "the compare ticker's iv21". A ROLE, not
45
45
  * an identity — the column keeps its name when the compare ticker changes,
46
- * so a spread's id (and the user's overrides on it) survive the swap. This
47
- * is the consumer-side stand-in for per-input source qualification
48
- * (PND-PROCJOIN — position 5 on pond#543).
46
+ * so a spread's id (and the user's overrides on it) survive the swap. The
47
+ * fold joins the comparison with pond's join node, whose own name for these
48
+ * columns is `cmp_:iv21`; {@link applyDerivedReport} turns them back into this
49
+ * prefix, so the rest of Tidal never sees pond's form.
49
50
  */
50
51
  export declare const COMPARE_PREFIX = "cmp_";
51
52
  /**
@@ -65,6 +66,36 @@ export declare const pinnedPrefix: (symbol: string) => string;
65
66
  * whose reading it is. A column with neither prefix comes back as it is.
66
67
  */
67
68
  export declare function stripOtherSymbol(column: string): string;
69
+ /**
70
+ * The column prefix for **another data source** of the same symbol — a compare
71
+ * on the price source reading a line of the vol source: `~vol_iv21` is the vol
72
+ * source's `iv21`, joined onto the price source's rows (compare node plan,
73
+ * step 6b). It goes AFTER a symbol's prefix, so the comparison's vol is
74
+ * `cmp_~vol_iv21` and a locked symbol's `cmp_@SPY_~vol_iv21`. A raw column of
75
+ * the other source, never a study's: a study on the other side runs on the
76
+ * metric's own rows, as every compare does.
77
+ */
78
+ export declare const sourcePrefix: (source: string) => string;
79
+ /** Whether `source` can name another source's columns: letters and digits
80
+ * only — never `_`, which ends the prefix. */
81
+ export declare const isSourceKey: (source: string) => boolean;
82
+ /**
83
+ * The other-reading prefix a column starts with — the longest one: `cmp_` for
84
+ * `cmp_iv21`, `cmp_@SPY_~vol_` for `cmp_@SPY_~vol_iv21`, `~vol_` for
85
+ * `~vol_iv21` — or `null` for a column of this source on this symbol. The fold
86
+ * joins one series per distinct prefix its configs read.
87
+ */
88
+ export declare function otherPrefixOf(column: string): string | null;
89
+ /**
90
+ * An other-reading prefix read apart: the symbol part (`''` for this symbol,
91
+ * {@link COMPARE_PREFIX}, or a {@link pinnedPrefix}) and the source it names
92
+ * (`undefined` for the source being folded). `null` for a string that is not
93
+ * a whole prefix of that shape. The fold's join reads it.
94
+ */
95
+ export declare function parseOtherPrefix(prefix: string): {
96
+ symbol: string;
97
+ source: string | undefined;
98
+ } | null;
68
99
  /** Whether `symbol` can name a locked symbol's columns: letters, digits and
69
100
  * `.` `-` `^` only — never `_`, which ends the prefix. */
70
101
  export declare const isPinnableSymbol: (symbol: string) => boolean;
@@ -73,7 +104,10 @@ export declare const isPinnableSymbol: (symbol: string) => boolean;
73
104
  * raw column LEAVES, so a nested spec keeps its shape and reads another
74
105
  * symbol's columns — `sma(close)` under `cmp_@SPY_` reads `cmp_@SPY_close`.
75
106
  * A leaf already reading another symbol (any {@link COMPARE_PREFIX} column)
76
- * is left alone: prefixing it again would name a column no join carries.
107
+ * is left alone: prefixing it again would name a column no join carries. So
108
+ * is a leaf already on another source, under a source prefix
109
+ * ({@link sourcePrefix}); a symbol prefix still goes in front of it
110
+ * (`~vol_iv21` under `cmp_` is `cmp_~vol_iv21`).
77
111
  */
78
112
  export declare function underPrefix(input: DeriveInput, prefix: string): DeriveInput;
79
113
  /** Whether any raw column `spec` reads, at any depth, passes `test`. */
@@ -495,12 +529,22 @@ export interface DeriveNodeTiming {
495
529
  * and `skipped` are pure + deterministic (memo-friendly); the `ms` in `nodes`
496
530
  * is wall-clock.
497
531
  *
532
+ * **Other symbols' series** (`others`) are joined on by `@pond-ts/process`'s
533
+ * join node, as of each of `series`' rows: for every row the latest row of the
534
+ * other series at or before it, so two symbols that print at different minutes
535
+ * still pair (an exact-time join left those cells empty). Each is keyed by the
536
+ * column prefix its columns carry here — {@link COMPARE_PREFIX} for the bar's
537
+ * comparison, {@link pinnedPrefix} for a locked symbol, {@link sourcePrefix}
538
+ * for another data source, after a symbol's prefix for that source on another
539
+ * symbol — and comes out under it: `cmp_close`, `cmp_@SPY_close`, `~vol_iv21`,
540
+ * `cmp_~vol_iv21`. A key of any other shape is ignored.
541
+ *
498
542
  * Deliberately a **cold bind per fold** for now — same cost shape as the local
499
543
  * fold it replaced, kept simple while semantics settle. The warm long-lived
500
544
  * graph (a `Host` keyed by source, `setSourceFrom` on live appends, ranged
501
545
  * recompute) is the follow-up where the engine's caching starts paying.
502
546
  */
503
- export declare function applyDerivedReport(series: DerivedSeries, specs: readonly DeriveSpec[], units?: Units): {
547
+ export declare function applyDerivedReport(input: DerivedSeries, specs: readonly DeriveSpec[], units?: Units, others?: Readonly<Record<string, DerivedSeries>>): {
504
548
  series: DerivedSeries;
505
549
  skipped: DeriveSkip[];
506
550
  nodes: DeriveNodeTiming[];
@@ -508,7 +552,7 @@ export declare function applyDerivedReport(series: DerivedSeries, specs: readonl
508
552
  /** {@link applyDerivedReport} without the report — the fold most render paths
509
553
  * want (the chart's column-absence handling is the render half of the skip
510
554
  * contract). */
511
- export declare function applyDerived(series: DerivedSeries, specs: readonly DeriveSpec[], units?: Units): DerivedSeries;
555
+ export declare function applyDerived(series: DerivedSeries, specs: readonly DeriveSpec[], units?: Units, others?: Readonly<Record<string, DerivedSeries>>): DerivedSeries;
512
556
  /** One op the study menu can offer, straight from the registry — so a new op
513
557
  * appears in the picker by being defined, never by being listed twice. */
514
558
  export interface StudyOption {
package/dist/derive.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { joinUnderPrefix } from './join.js';
1
2
  import { ADOPTED_STUDIES, BAND_OUTPUTS, catalogOp, OWN_AXIS_STUDIES, PRIMARY_SUFFIX, studyNeedsColumns, } from './studyCatalog.js';
2
3
  import { bollinger, ema, sma } from '@pond-ts/financial';
3
4
  import { bind, columnsOf, createRegistry, int, num, run, specId, explain, } from '@pond-ts/process';
@@ -6,9 +7,10 @@ import { bind, columnsOf, createRegistry, int, num, run, specId, explain, } from
6
7
  * comparison ticker's series onto the primary (role-bound pair legs,
7
8
  * TDL-PAIR stage 1): `cmp_iv21` is "the compare ticker's iv21". A ROLE, not
8
9
  * an identity — the column keeps its name when the compare ticker changes,
9
- * so a spread's id (and the user's overrides on it) survive the swap. This
10
- * is the consumer-side stand-in for per-input source qualification
11
- * (PND-PROCJOIN — position 5 on pond#543).
10
+ * so a spread's id (and the user's overrides on it) survive the swap. The
11
+ * fold joins the comparison with pond's join node, whose own name for these
12
+ * columns is `cmp_:iv21`; {@link applyDerivedReport} turns them back into this
13
+ * prefix, so the rest of Tidal never sees pond's form.
12
14
  */
13
15
  export const COMPARE_PREFIX = 'cmp_';
14
16
  /**
@@ -28,14 +30,95 @@ export const pinnedPrefix = (symbol) => `${COMPARE_PREFIX}@${symbol}_`;
28
30
  * whose reading it is. A column with neither prefix comes back as it is.
29
31
  */
30
32
  export function stripOtherSymbol(column) {
31
- if (!column.startsWith(COMPARE_PREFIX))
33
+ let rest = column;
34
+ if (rest.startsWith(COMPARE_PREFIX)) {
35
+ rest = rest.slice(COMPARE_PREFIX.length);
36
+ if (rest.startsWith('@')) {
37
+ // A pinnable symbol never holds `_`, so the first one ends the prefix.
38
+ const end = rest.indexOf('_');
39
+ if (end > 1)
40
+ rest = rest.slice(end + 1);
41
+ }
42
+ }
43
+ // Then another source's prefix, which comes after the symbol's.
44
+ return stripSource(rest);
45
+ }
46
+ /** The start of every other-source prefix: `~vol_`. A source key never starts
47
+ * a raw column with it, and `~` is not a character a symbol may hold. */
48
+ const SOURCE_START = '~';
49
+ /**
50
+ * The column prefix for **another data source** of the same symbol — a compare
51
+ * on the price source reading a line of the vol source: `~vol_iv21` is the vol
52
+ * source's `iv21`, joined onto the price source's rows (compare node plan,
53
+ * step 6b). It goes AFTER a symbol's prefix, so the comparison's vol is
54
+ * `cmp_~vol_iv21` and a locked symbol's `cmp_@SPY_~vol_iv21`. A raw column of
55
+ * the other source, never a study's: a study on the other side runs on the
56
+ * metric's own rows, as every compare does.
57
+ */
58
+ export const sourcePrefix = (source) => `${SOURCE_START}${source}_`;
59
+ /** Whether `source` can name another source's columns: letters and digits
60
+ * only — never `_`, which ends the prefix. */
61
+ export const isSourceKey = (source) => /^[A-Za-z0-9]{1,32}$/.test(source);
62
+ /** A column with an other-source prefix (`~vol_`) taken off, if it has one. */
63
+ function stripSource(column) {
64
+ if (!column.startsWith(SOURCE_START))
32
65
  return column;
33
- const rest = column.slice(COMPARE_PREFIX.length);
34
- if (!rest.startsWith('@'))
35
- return rest;
36
- // A pinnable symbol never holds `_`, so the first one ends the prefix.
37
- const end = rest.indexOf('_');
38
- return end > 1 ? rest.slice(end + 1) : rest;
66
+ const end = column.indexOf('_');
67
+ return end > 1 && isSourceKey(column.slice(1, end)) ? column.slice(end + 1) : column;
68
+ }
69
+ /**
70
+ * The other-reading prefix a column starts with — the longest one: `cmp_` for
71
+ * `cmp_iv21`, `cmp_@SPY_~vol_` for `cmp_@SPY_~vol_iv21`, `~vol_` for
72
+ * `~vol_iv21` — or `null` for a column of this source on this symbol. The fold
73
+ * joins one series per distinct prefix its configs read.
74
+ */
75
+ export function otherPrefixOf(column) {
76
+ let at = 0;
77
+ if (column.startsWith(COMPARE_PREFIX)) {
78
+ at = COMPARE_PREFIX.length;
79
+ if (column[at] === '@') {
80
+ const end = column.indexOf('_', at);
81
+ if (end > at + 1 && isPinnableSymbol(column.slice(at + 1, end)))
82
+ at = end + 1;
83
+ else
84
+ return null;
85
+ }
86
+ }
87
+ if (column.startsWith(SOURCE_START, at)) {
88
+ const end = column.indexOf('_', at);
89
+ if (end > at + 1 && isSourceKey(column.slice(at + 1, end)))
90
+ at = end + 1;
91
+ else
92
+ return at > 0 ? column.slice(0, at) : null;
93
+ }
94
+ return at > 0 ? column.slice(0, at) : null;
95
+ }
96
+ /**
97
+ * An other-reading prefix read apart: the symbol part (`''` for this symbol,
98
+ * {@link COMPARE_PREFIX}, or a {@link pinnedPrefix}) and the source it names
99
+ * (`undefined` for the source being folded). `null` for a string that is not
100
+ * a whole prefix of that shape. The fold's join reads it.
101
+ */
102
+ export function parseOtherPrefix(prefix) {
103
+ let rest = prefix;
104
+ let symbol = '';
105
+ if (rest.startsWith(COMPARE_PREFIX)) {
106
+ rest = rest.slice(COMPARE_PREFIX.length);
107
+ symbol = COMPARE_PREFIX;
108
+ if (rest.startsWith('@')) {
109
+ const end = rest.indexOf('_');
110
+ if (end < 0 || !isPinnableSymbol(rest.slice(1, end)))
111
+ return null;
112
+ symbol = `${COMPARE_PREFIX}${rest.slice(0, end + 1)}`;
113
+ rest = rest.slice(end + 1);
114
+ }
115
+ }
116
+ if (rest === '')
117
+ return symbol ? { symbol, source: undefined } : null;
118
+ if (!rest.startsWith(SOURCE_START) || !rest.endsWith('_'))
119
+ return null;
120
+ const source = rest.slice(SOURCE_START.length, -1);
121
+ return isSourceKey(source) ? { symbol, source } : null;
39
122
  }
40
123
  /** Whether `symbol` can name a locked symbol's columns: letters, digits and
41
124
  * `.` `-` `^` only — never `_`, which ends the prefix. */
@@ -45,11 +128,21 @@ export const isPinnableSymbol = (symbol) => /^[A-Za-z0-9.^-]{1,32}$/.test(symbol
45
128
  * raw column LEAVES, so a nested spec keeps its shape and reads another
46
129
  * symbol's columns — `sma(close)` under `cmp_@SPY_` reads `cmp_@SPY_close`.
47
130
  * A leaf already reading another symbol (any {@link COMPARE_PREFIX} column)
48
- * is left alone: prefixing it again would name a column no join carries.
131
+ * is left alone: prefixing it again would name a column no join carries. So
132
+ * is a leaf already on another source, under a source prefix
133
+ * ({@link sourcePrefix}); a symbol prefix still goes in front of it
134
+ * (`~vol_iv21` under `cmp_` is `cmp_~vol_iv21`).
49
135
  */
50
136
  export function underPrefix(input, prefix) {
51
- if (typeof input === 'string')
52
- return input.startsWith(COMPARE_PREFIX) ? input : `${prefix}${input}`;
137
+ if (typeof input === 'string') {
138
+ if (input.startsWith(COMPARE_PREFIX))
139
+ return input;
140
+ // A source prefix onto a leaf already on another source would name a
141
+ // source of a source, which nothing joins.
142
+ if (prefix.startsWith(SOURCE_START) && parseOtherPrefix(otherPrefixOf(input) ?? '')?.source)
143
+ return input;
144
+ return `${prefix}${input}`;
145
+ }
53
146
  if (isPickedInput(input))
54
147
  return { from: underPrefix(input.from, prefix), output: input.output };
55
148
  return { ...input, inputs: (input.inputs ?? []).map((i) => underPrefix(i, prefix)) };
@@ -635,12 +728,41 @@ function outputUnit(spec, index, unitOf) {
635
728
  * and `skipped` are pure + deterministic (memo-friendly); the `ms` in `nodes`
636
729
  * is wall-clock.
637
730
  *
731
+ * **Other symbols' series** (`others`) are joined on by `@pond-ts/process`'s
732
+ * join node, as of each of `series`' rows: for every row the latest row of the
733
+ * other series at or before it, so two symbols that print at different minutes
734
+ * still pair (an exact-time join left those cells empty). Each is keyed by the
735
+ * column prefix its columns carry here — {@link COMPARE_PREFIX} for the bar's
736
+ * comparison, {@link pinnedPrefix} for a locked symbol, {@link sourcePrefix}
737
+ * for another data source, after a symbol's prefix for that source on another
738
+ * symbol — and comes out under it: `cmp_close`, `cmp_@SPY_close`, `~vol_iv21`,
739
+ * `cmp_~vol_iv21`. A key of any other shape is ignored.
740
+ *
638
741
  * Deliberately a **cold bind per fold** for now — same cost shape as the local
639
742
  * fold it replaced, kept simple while semantics settle. The warm long-lived
640
743
  * graph (a `Host` keyed by source, `setSourceFrom` on live appends, ranged
641
744
  * recompute) is the follow-up where the engine's caching starts paying.
642
745
  */
643
- export function applyDerivedReport(series, specs, units) {
746
+ export function applyDerivedReport(input, specs, units, others) {
747
+ let series = input;
748
+ const prefixes = Object.keys(others ?? {}).filter(isOtherPrefix);
749
+ if (prefixes.length > 0) {
750
+ const joined = applyJoinedReport(series, specs, units, others, prefixes);
751
+ if (joined)
752
+ return joined;
753
+ // Pond refused the join (a column kind it cannot carry, on either side) or
754
+ // its columns would not name back without colliding (a refold of a folded
755
+ // series). Join exactly instead, as before 0.27.0, so the other symbols
756
+ // still arrive; the fold below then skips what cannot fold.
757
+ for (const prefix of [...prefixes].sort()) {
758
+ try {
759
+ series = joinUnderPrefix(series, others[prefix], prefix);
760
+ }
761
+ catch {
762
+ // Already carries that symbol's columns (a refold): read those.
763
+ }
764
+ }
765
+ }
644
766
  if (specs.length === 0)
645
767
  return { series, skipped: [], nodes: [] };
646
768
  // NOT idempotent over an already-folded series: an output column that
@@ -688,11 +810,177 @@ export function applyDerivedReport(series, specs, units) {
688
810
  }));
689
811
  return { series: result.series ?? series, skipped: [...skipped.values()], nodes };
690
812
  }
813
+ /** Whether `prefix` names another reading's columns: the comparison's, a
814
+ * locked symbol's, another source's, or another source's on either symbol
815
+ * ({@link parseOtherPrefix}). */
816
+ const isOtherPrefix = (prefix) => parseOtherPrefix(prefix) !== null;
817
+ /** The join's key for this symbol's own series. Pond names a joined column
818
+ * `<key>:<column>`, this one included (CHARTS_FRICTION F-charts-45). */
819
+ const BASE_KEY = 'p';
820
+ /** The join's key for another reading's prefix: the prefix itself, which
821
+ * never holds `:` and is never {@link BASE_KEY} (every one ends in `_`). */
822
+ const keyOfPrefix = (prefix) => prefix;
823
+ /** Rewrite every raw column leaf of a spec, at any depth. A shape that is not
824
+ * a spec (untyped persisted state) passes through untouched, for the engine
825
+ * to skip and report as it would have. */
826
+ function mapLeaves(input, leaf) {
827
+ if (typeof input === 'string')
828
+ return leaf(input);
829
+ if (isPickedInput(input))
830
+ return { from: mapLeaves(input.from, leaf), output: input.output };
831
+ if (!isSpecLike(input) || !Array.isArray(input.inputs))
832
+ return input;
833
+ return { ...input, inputs: input.inputs.map((i) => mapLeaves(i, leaf)) };
834
+ }
835
+ /** Every spec in `spec`, nested ones included, outermost first. */
836
+ function specsWithin(spec, out = []) {
837
+ if (!isSpecLike(spec))
838
+ return out;
839
+ out.push(spec);
840
+ if (!Array.isArray(spec.inputs))
841
+ return out;
842
+ for (const i of spec.inputs) {
843
+ if (typeof i === 'string')
844
+ continue;
845
+ specsWithin(isPickedInput(i) ? i.from : i, out);
846
+ }
847
+ return out;
848
+ }
849
+ /** `deriveId`, never throwing — the BELT in {@link applyDerivedReport}. */
850
+ function safeId(spec) {
851
+ try {
852
+ return deriveId(spec);
853
+ }
854
+ catch {
855
+ return `${BROKEN_ID_PREFIX}${JSON.stringify(spec) ?? 'unnameable'}`;
856
+ }
857
+ }
858
+ /**
859
+ * {@link applyDerivedReport} over a joined binding: `series` and the other
860
+ * symbols' series behind one as-of join node, `series` the base.
861
+ *
862
+ * Pond qualifies every joined column with its source's key, the base's too
863
+ * (`p:close`, `cmp_:close`), and a spec id names the columns it reads, so the
864
+ * fold works in pond's names and hands back Tidal's: going in, every raw
865
+ * leaf is rewritten (`close` → `p:close`, `cmp_close` → `cmp_:close`,
866
+ * `cmp_@SPY_close` → `cmp_@SPY_:close`); coming out, the columns, the node report
867
+ * and the skips are named back, so a caller sees exactly the columns and ids
868
+ * a single-series fold would give. This is the one place the two naming
869
+ * schemes meet; it shrinks to the other symbols alone if pond leaves the
870
+ * base's names unqualified (F-charts-45).
871
+ *
872
+ * `undefined` when pond refuses the binding (a column of a kind a join cannot
873
+ * carry, on the base as much as on another symbol) or when the columns would
874
+ * not name back without two colliding (refolding a folded series): the caller
875
+ * then joins exactly, as before, and folds that.
876
+ */
877
+ function applyJoinedReport(series, specs, units, others, prefixes) {
878
+ // Longest first, so `cmp_@SPY_close` is SPY's even with the comparison
879
+ // joined too. A leaf under no joined prefix is the base's — a comparison
880
+ // column with no comparison joined then names a column that is not there,
881
+ // and skips, as it did before.
882
+ const byLength = [...prefixes].sort((a, b) => b.length - a.length);
883
+ const toPond = (column) => {
884
+ const prefix = byLength.find((p) => column.startsWith(p));
885
+ return prefix
886
+ ? `${keyOfPrefix(prefix)}:${column.slice(prefix.length)}`
887
+ : `${BASE_KEY}:${column}`;
888
+ };
889
+ const back = new Map([[BASE_KEY, '']]);
890
+ for (const prefix of prefixes)
891
+ back.set(keyOfPrefix(prefix), prefix);
892
+ let graph;
893
+ try {
894
+ const sources = { [BASE_KEY]: series };
895
+ for (const prefix of prefixes)
896
+ sources[keyOfPrefix(prefix)] = others[prefix];
897
+ const pondUnits = units
898
+ ? Object.fromEntries(Object.entries(units).map(([col, unit]) => [toPond(col), unit]))
899
+ : undefined;
900
+ graph = bind(sources, {
901
+ registry: TIDAL_OPS,
902
+ units: pondUnits,
903
+ join: { how: 'asof', base: BASE_KEY },
904
+ });
905
+ }
906
+ catch {
907
+ return undefined;
908
+ }
909
+ // Each spec in pond's names, and the id map back. Nested specs too: the
910
+ // node report names every step, and a nested id is a column a later step
911
+ // reads.
912
+ const translated = specs.map((s) => mapLeaves(s, toPond));
913
+ const ids = new Map();
914
+ for (const spec of specs)
915
+ for (const inner of specsWithin(spec))
916
+ ids.set(safeId(mapLeaves(inner, toPond)), safeId(inner));
917
+ // Longest first, so an id that starts another id is not taken for it.
918
+ const pondIds = [...ids.keys()].sort((a, b) => b.length - a.length);
919
+ const fromPond = (column) => {
920
+ const exact = ids.get(column);
921
+ if (exact !== undefined)
922
+ return exact;
923
+ // A multi-output step's columns are its id plus the output's suffix.
924
+ const id = pondIds.find((i) => column.startsWith(i));
925
+ if (id !== undefined)
926
+ return `${ids.get(id)}${column.slice(id.length)}`;
927
+ const at = column.indexOf(':');
928
+ const prefix = at > 0 ? back.get(column.slice(0, at)) : undefined;
929
+ return prefix === undefined ? column : `${prefix}${column.slice(at + 1)}`;
930
+ };
931
+ const named = (s) => {
932
+ const mapping = {};
933
+ for (const col of s.schema.slice(1)) {
934
+ const name = fromPond(col.name);
935
+ if (name !== col.name)
936
+ mapping[col.name] = name;
937
+ }
938
+ return s.rename(mapping);
939
+ };
940
+ if (specs.length === 0) {
941
+ try {
942
+ return { series: named(graph.series), skipped: [], nodes: [] };
943
+ }
944
+ catch {
945
+ return undefined;
946
+ }
947
+ }
948
+ const result = run(graph, {
949
+ plan: translated,
950
+ select: translated.map((s) => ({ on: s })),
951
+ onError: 'skip',
952
+ });
953
+ const skipped = new Map();
954
+ for (const s of result.skipped) {
955
+ const spec = (s.spec ?? s.select?.on);
956
+ if (!spec)
957
+ continue;
958
+ const pondId = safeId(spec);
959
+ const id = ids.get(pondId) ?? pondId;
960
+ if (!skipped.has(id))
961
+ skipped.set(id, { id, code: s.code, reason: s.reason });
962
+ }
963
+ const nodes = result.nodes.map(({ id, pulled, cached, ms, inputs }) => ({
964
+ id: fromPond(id),
965
+ pulled,
966
+ cached,
967
+ ms,
968
+ inputs: inputs.map(fromPond),
969
+ }));
970
+ let out;
971
+ try {
972
+ out = named(result.series ?? graph.series);
973
+ }
974
+ catch {
975
+ return undefined;
976
+ }
977
+ return { series: out, skipped: [...skipped.values()], nodes };
978
+ }
691
979
  /** {@link applyDerivedReport} without the report — the fold most render paths
692
980
  * want (the chart's column-absence handling is the render half of the skip
693
981
  * contract). */
694
- export function applyDerived(series, specs, units) {
695
- return applyDerivedReport(series, specs, units).series;
982
+ export function applyDerived(series, specs, units, others) {
983
+ return applyDerivedReport(series, specs, units, others).series;
696
984
  }
697
985
  /** Whether an op declares a `period` param — i.e. whether it is WINDOWED, and
698
986
  * so whether a study of it should carry one. Stamping `{period}` onto an op
package/dist/index.d.ts CHANGED
@@ -2,12 +2,12 @@ export { BAR_INTERVAL_MS, type Instrument, type InstrumentKind, type BarInterval
2
2
  export { generatePriceSeries, buildPriceSeries, DEMO_INSTRUMENTS, PRICE_SCHEMA, type PriceSeriesOptions, type PriceSeries, type PriceRow, } from './fixture.js';
3
3
  export { generateVolSeries, buildVolSeries, VOL_SCHEMA, VOL_TENORS, DEFAULT_VOL_TENOR, impliedCol, hvCol, rvCol, rvCenCol, skewCol, type VolSeries, type VolColumns, type VolTenor, type VolSeriesOptions, } from './vol.js';
4
4
  export { aggregateColumn, floorToWindow, liveWindowMs, ohlcWindow, sessionGrid, WINDOW_MS, WINDOW_LADDER, MIN_BAR_PX, autoBarWindow, type BarReducer, type SeriesWindow, } from './aggregate.js';
5
- export { applyDerived, applyDerivedReport, COMPARE_PREFIX, pinnedPrefix, isPinnableSymbol, underPrefix, readsPrefix, readsColumn, stripOtherSymbol, deriveId, deriveLineage, inputNames, substituteInput, hasPairOp, isBrokenId, isPairOp, isValidSpec, opHasPeriod, PERIOD_BOUNDS, readNumericColumn, partStudyLabel, readPart, readPairParts, specUnit, studyCatalog, TIDAL_OPS, BAND_OUTPUTS, opParams, isStudyOp, studyTag, opIsBand, opInputs, opIsMulti, opOutputs, primaryOutput, studyInputOf, studyPick, fanPick, withFanOutput, withStudyOutput, studyColumn, BAR_PRICE_COLUMNS, withStudyColumn, type StudyPick, isPickedInput, opNeedsColumns, TARGET_ROLES, opSharesSourceAxis, type OpParam, usesCompare, type DeriveSkip, type DeriveNodeTiming, type PairPart, type PartStudy, type StudyOption, type NumericColumnReader, DEFAULT_PERIOD, type DeriveInput, type PickedDeriveOutput, type DeriveSpec, type DeriveOp, type TidalOp, type PairOp, } from './derive.js';
5
+ export { applyDerived, applyDerivedReport, COMPARE_PREFIX, pinnedPrefix, isPinnableSymbol, underPrefix, readsPrefix, readsColumn, stripOtherSymbol, sourcePrefix, isSourceKey, parseOtherPrefix, otherPrefixOf, deriveId, deriveLineage, inputNames, substituteInput, hasPairOp, isBrokenId, isPairOp, isValidSpec, opHasPeriod, PERIOD_BOUNDS, readNumericColumn, partStudyLabel, readPart, readPairParts, specUnit, studyCatalog, TIDAL_OPS, BAND_OUTPUTS, opParams, isStudyOp, studyTag, opIsBand, opInputs, opIsMulti, opOutputs, primaryOutput, studyInputOf, studyPick, fanPick, withFanOutput, withStudyOutput, studyColumn, BAR_PRICE_COLUMNS, withStudyColumn, type StudyPick, isPickedInput, opNeedsColumns, TARGET_ROLES, opSharesSourceAxis, type OpParam, usesCompare, type DeriveSkip, type DeriveNodeTiming, type PairPart, type PartStudy, type StudyOption, type NumericColumnReader, DEFAULT_PERIOD, type DeriveInput, type PickedDeriveOutput, type DeriveSpec, type DeriveOp, type TidalOp, type PairOp, } from './derive.js';
6
6
  export { joinUnderPrefix } from './join.js';
7
7
  export { columnExtent } from './extent.js';
8
8
  export { snapshotToTimeSeries, appendToRows, type PondSnapshot, type PondAppend, type PondValue, type WireColumnSpec, } from './columnar.js';
9
9
  export { exactSessionSegments, inferBarMs, sessionOpenLine, sessionSegments, shiftKeys, sliceBySegments, type Segment, type SessionSegmentOptions, } from './sessions.js';
10
10
  export { monthlyExpirations, thirdFriday } from './expirations.js';
11
- export { holdAcrossGrid, holdVolAcrossGrid, type HeldSchema } from './regrid.js';
11
+ export { holdAcrossGrid, holdVolAcrossGrid, lastInEachGrain, type HeldSchema } from './regrid.js';
12
12
  export { ADOPTED_STUDIES, adoptable, isBandShape, outputMark, studyLevels, studyNeedsColumns, } from './studyCatalog.js';
13
13
  export { DATA_TIME_ZONE, LOCAL_ZONE, TIME_ZONE_CHOICES, resolveTimeZone, timeZoneLabel, type TimeZoneChoice, } from './timeZone.js';
package/dist/index.js CHANGED
@@ -2,13 +2,13 @@ export { BAR_INTERVAL_MS, } from './types.js';
2
2
  export { generatePriceSeries, buildPriceSeries, DEMO_INSTRUMENTS, PRICE_SCHEMA, } from './fixture.js';
3
3
  export { generateVolSeries, buildVolSeries, VOL_SCHEMA, VOL_TENORS, DEFAULT_VOL_TENOR, impliedCol, hvCol, rvCol, rvCenCol, skewCol, } from './vol.js';
4
4
  export { aggregateColumn, floorToWindow, liveWindowMs, ohlcWindow, sessionGrid, WINDOW_MS, WINDOW_LADDER, MIN_BAR_PX, autoBarWindow, } from './aggregate.js';
5
- export { applyDerived, applyDerivedReport, COMPARE_PREFIX, pinnedPrefix, isPinnableSymbol, underPrefix, readsPrefix, readsColumn, stripOtherSymbol, deriveId, deriveLineage, inputNames, substituteInput, hasPairOp, isBrokenId, isPairOp, isValidSpec, opHasPeriod, PERIOD_BOUNDS, readNumericColumn, partStudyLabel, readPart, readPairParts, specUnit, studyCatalog, TIDAL_OPS, BAND_OUTPUTS, opParams, isStudyOp, studyTag, opIsBand, opInputs, opIsMulti, opOutputs, primaryOutput, studyInputOf, studyPick, fanPick, withFanOutput, withStudyOutput, studyColumn, BAR_PRICE_COLUMNS, withStudyColumn, isPickedInput, opNeedsColumns, TARGET_ROLES, opSharesSourceAxis, usesCompare, DEFAULT_PERIOD, } from './derive.js';
5
+ export { applyDerived, applyDerivedReport, COMPARE_PREFIX, pinnedPrefix, isPinnableSymbol, underPrefix, readsPrefix, readsColumn, stripOtherSymbol, sourcePrefix, isSourceKey, parseOtherPrefix, otherPrefixOf, deriveId, deriveLineage, inputNames, substituteInput, hasPairOp, isBrokenId, isPairOp, isValidSpec, opHasPeriod, PERIOD_BOUNDS, readNumericColumn, partStudyLabel, readPart, readPairParts, specUnit, studyCatalog, TIDAL_OPS, BAND_OUTPUTS, opParams, isStudyOp, studyTag, opIsBand, opInputs, opIsMulti, opOutputs, primaryOutput, studyInputOf, studyPick, fanPick, withFanOutput, withStudyOutput, studyColumn, BAR_PRICE_COLUMNS, withStudyColumn, isPickedInput, opNeedsColumns, TARGET_ROLES, opSharesSourceAxis, usesCompare, DEFAULT_PERIOD, } from './derive.js';
6
6
  export { joinUnderPrefix } from './join.js';
7
7
  export { columnExtent } from './extent.js';
8
8
  export { snapshotToTimeSeries, appendToRows, } from './columnar.js';
9
9
  export { exactSessionSegments, inferBarMs, sessionOpenLine, sessionSegments, shiftKeys, sliceBySegments, } from './sessions.js';
10
10
  export { monthlyExpirations, thirdFriday } from './expirations.js';
11
- export { holdAcrossGrid, holdVolAcrossGrid } from './regrid.js';
11
+ export { holdAcrossGrid, holdVolAcrossGrid, lastInEachGrain } from './regrid.js';
12
12
  // The corpus adoption (TDL-STUDYCAT). `ADOPTED_STUDIES` is exported so the
13
13
  // count is assertable and a widening of `adoptable` is a visible edit.
14
14
  export { ADOPTED_STUDIES, adoptable, isBandShape, outputMark, studyLevels, studyNeedsColumns, } from './studyCatalog.js';
package/dist/join.d.ts CHANGED
@@ -9,6 +9,11 @@ type JoinedSeries = TimeSeries<SeriesSchema>;
9
9
  * (`cmp_iv21`) can fold (TDL-PAIR stage 1), and it is the consumer-side
10
10
  * stand-in for per-input source qualification (PND-PROCJOIN).
11
11
  *
12
+ * **The fold uses this only as a fallback** (0.27.0): `applyDerivedReport`'s `others`
13
+ * joins the other symbols with `@pond-ts/process`'s join node, as of each row,
14
+ * which also answers the exact-key caveat below. Kept for a caller that wants
15
+ * the exact-key join itself.
16
+ *
12
17
  * Deliberately rename-then-join, NOT pond's `join(…, { onConflict: 'prefix' })`:
13
18
  * pond inserts an implicit `_` separator (`prefixes: ['', 'cmp_']` yields
14
19
  * `_iv21` / `cmp__iv21`), which destroys the primary's names — an empty prefix
package/dist/join.js CHANGED
@@ -7,6 +7,11 @@ import { COMPARE_PREFIX } from './derive.js';
7
7
  * (`cmp_iv21`) can fold (TDL-PAIR stage 1), and it is the consumer-side
8
8
  * stand-in for per-input source qualification (PND-PROCJOIN).
9
9
  *
10
+ * **The fold uses this only as a fallback** (0.27.0): `applyDerivedReport`'s `others`
11
+ * joins the other symbols with `@pond-ts/process`'s join node, as of each row,
12
+ * which also answers the exact-key caveat below. Kept for a caller that wants
13
+ * the exact-key join itself.
14
+ *
10
15
  * Deliberately rename-then-join, NOT pond's `join(…, { onConflict: 'prefix' })`:
11
16
  * pond inserts an implicit `_` separator (`prefixes: ['', 'cmp_']` yields
12
17
  * `_iv21` / `cmp__iv21`), which destroys the primary's names — an empty prefix
package/dist/regrid.d.ts CHANGED
@@ -58,6 +58,18 @@ export type HeldSchema<S extends SeriesSchema> = readonly [
58
58
  * column, rather than dropping it.
59
59
  */
60
60
  export declare function holdAcrossGrid<S extends SeriesSchema>(coarse: TimeSeries<S>, grid: ArrayLike<number>, grainMs: number): TimeSeries<HeldSchema<S>>;
61
+ /**
62
+ * The reverse of {@link holdAcrossGrid}: a **finer** series read at a coarse
63
+ * series' keys. For each key `K` in `keys`, the last row of `fine` in
64
+ * `[K, K + grainMs)`, keyed at `K`; a key with no such row is a gap. So a
65
+ * one-minute price series read on the daily vol rows gives each day its last
66
+ * minute, keyed where that day's vol row is, and a join on those keys pairs
67
+ * the two days exactly. Joining the minutes as they are would pair each day
68
+ * with the last minute BEFORE its key, which is the previous day's.
69
+ *
70
+ * `keys` must be ascending. Number and string columns only, like the hold.
71
+ */
72
+ export declare function lastInEachGrain(fine: TimeSeries<SeriesSchema>, keys: ArrayLike<number>, grainMs: number): TimeSeries<SeriesSchema>;
61
73
  /**
62
74
  * Re-key `coarse` onto `times`, holding each source row across every target
63
75
  * timestamp that falls on its day.
package/dist/regrid.js CHANGED
@@ -135,6 +135,69 @@ export function holdAcrossGrid(coarse, grid, grainMs) {
135
135
  columns: columns,
136
136
  });
137
137
  }
138
+ /**
139
+ * The reverse of {@link holdAcrossGrid}: a **finer** series read at a coarse
140
+ * series' keys. For each key `K` in `keys`, the last row of `fine` in
141
+ * `[K, K + grainMs)`, keyed at `K`; a key with no such row is a gap. So a
142
+ * one-minute price series read on the daily vol rows gives each day its last
143
+ * minute, keyed where that day's vol row is, and a join on those keys pairs
144
+ * the two days exactly. Joining the minutes as they are would pair each day
145
+ * with the last minute BEFORE its key, which is the previous day's.
146
+ *
147
+ * `keys` must be ascending. Number and string columns only, like the hold.
148
+ */
149
+ export function lastInEachGrain(fine, keys, grainMs) {
150
+ const [keySpec, ...valueSpecs] = fine.schema;
151
+ if (keySpec.kind !== 'time')
152
+ throw new Error(`lastInEachGrain: "${fine.name}" is keyed by ${keySpec.kind}, not time`);
153
+ if (!(grainMs > 0))
154
+ throw new Error(`lastInEachGrain: grainMs must be a positive number of ms, not ${grainMs}`);
155
+ const fineKeys = fine.keyColumn().begin;
156
+ const n = fine.length;
157
+ const rows = new Int32Array(keys.length);
158
+ let j = -1;
159
+ let prev = -Infinity;
160
+ for (let i = 0; i < keys.length; i += 1) {
161
+ const k = keys[i];
162
+ if (!(k >= prev))
163
+ throw new Error(`lastInEachGrain: keys must be ascending; key ${i} (${k}) follows ${prev}`);
164
+ prev = k;
165
+ // The last fine row before the grain ends...
166
+ while (j + 1 < n && fineKeys[j + 1] < k + grainMs)
167
+ j += 1;
168
+ // ...and only if it falls in the grain.
169
+ rows[i] = j >= 0 && fineKeys[j] >= k ? j : -1;
170
+ }
171
+ const columns = {
172
+ [keySpec.name]: Float64Array.from(keys),
173
+ };
174
+ for (const spec of valueSpecs) {
175
+ const src = fine.column(spec.name);
176
+ if (spec.kind === 'number') {
177
+ const out = new Float64Array(keys.length);
178
+ for (let i = 0; i < keys.length; i += 1) {
179
+ const v = rows[i] < 0 ? undefined : src.at(rows[i]);
180
+ out[i] = typeof v === 'number' ? v : NaN;
181
+ }
182
+ columns[spec.name] = out;
183
+ }
184
+ else if (spec.kind === 'string') {
185
+ const out = new Array(keys.length);
186
+ for (let i = 0; i < keys.length; i += 1)
187
+ out[i] = rows[i] < 0 ? undefined : src.at(rows[i]);
188
+ columns[spec.name] = out;
189
+ }
190
+ else {
191
+ throw new Error(`lastInEachGrain: column "${spec.name}" of "${fine.name}" is ${spec.kind}; only number and string columns can be read`);
192
+ }
193
+ }
194
+ const schema = [keySpec, ...valueSpecs.map((c) => ({ ...c, required: false }))];
195
+ return TimeSeries.fromColumns({
196
+ name: fine.name,
197
+ schema: schema,
198
+ columns: columns,
199
+ });
200
+ }
138
201
  /**
139
202
  * Re-key `coarse` onto `times`, holding each source row across every target
140
203
  * timestamp that falls on its day.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tidal-ts/core",
3
- "version": "0.26.0",
3
+ "version": "0.28.0",
4
4
  "private": false,
5
5
  "description": "Financial time-series vocabulary on pond-ts: the study/derive seam, the vol schema, bar windows, the columnar adapter and session helpers.",
6
6
  "license": "MIT",