@tidal-ts/core 0.26.0 → 0.27.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 `c: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
  /**
@@ -495,12 +496,20 @@ export interface DeriveNodeTiming {
495
496
  * and `skipped` are pure + deterministic (memo-friendly); the `ms` in `nodes`
496
497
  * is wall-clock.
497
498
  *
499
+ * **Other symbols' series** (`others`) are joined on by `@pond-ts/process`'s
500
+ * join node, as of each of `series`' rows: for every row the latest row of the
501
+ * other series at or before it, so two symbols that print at different minutes
502
+ * still pair (an exact-time join left those cells empty). Each is keyed by the
503
+ * column prefix its columns carry here — {@link COMPARE_PREFIX} for the bar's
504
+ * comparison, {@link pinnedPrefix} for a locked symbol — and comes out under
505
+ * it: `cmp_close`, `cmp_@SPY_close`. A key that is neither is ignored.
506
+ *
498
507
  * Deliberately a **cold bind per fold** for now — same cost shape as the local
499
508
  * fold it replaced, kept simple while semantics settle. The warm long-lived
500
509
  * graph (a `Host` keyed by source, `setSourceFrom` on live appends, ranged
501
510
  * recompute) is the follow-up where the engine's caching starts paying.
502
511
  */
503
- export declare function applyDerivedReport(series: DerivedSeries, specs: readonly DeriveSpec[], units?: Units): {
512
+ export declare function applyDerivedReport(input: DerivedSeries, specs: readonly DeriveSpec[], units?: Units, others?: Readonly<Record<string, DerivedSeries>>): {
504
513
  series: DerivedSeries;
505
514
  skipped: DeriveSkip[];
506
515
  nodes: DeriveNodeTiming[];
@@ -508,7 +517,7 @@ export declare function applyDerivedReport(series: DerivedSeries, specs: readonl
508
517
  /** {@link applyDerivedReport} without the report — the fold most render paths
509
518
  * want (the chart's column-absence handling is the render half of the skip
510
519
  * contract). */
511
- export declare function applyDerived(series: DerivedSeries, specs: readonly DeriveSpec[], units?: Units): DerivedSeries;
520
+ export declare function applyDerived(series: DerivedSeries, specs: readonly DeriveSpec[], units?: Units, others?: Readonly<Record<string, DerivedSeries>>): DerivedSeries;
512
521
  /** One op the study menu can offer, straight from the registry — so a new op
513
522
  * appears in the picker by being defined, never by being listed twice. */
514
523
  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 `c: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
  /**
@@ -635,12 +637,39 @@ function outputUnit(spec, index, unitOf) {
635
637
  * and `skipped` are pure + deterministic (memo-friendly); the `ms` in `nodes`
636
638
  * is wall-clock.
637
639
  *
640
+ * **Other symbols' series** (`others`) are joined on by `@pond-ts/process`'s
641
+ * join node, as of each of `series`' rows: for every row the latest row of the
642
+ * other series at or before it, so two symbols that print at different minutes
643
+ * still pair (an exact-time join left those cells empty). Each is keyed by the
644
+ * column prefix its columns carry here — {@link COMPARE_PREFIX} for the bar's
645
+ * comparison, {@link pinnedPrefix} for a locked symbol — and comes out under
646
+ * it: `cmp_close`, `cmp_@SPY_close`. A key that is neither is ignored.
647
+ *
638
648
  * Deliberately a **cold bind per fold** for now — same cost shape as the local
639
649
  * fold it replaced, kept simple while semantics settle. The warm long-lived
640
650
  * graph (a `Host` keyed by source, `setSourceFrom` on live appends, ranged
641
651
  * recompute) is the follow-up where the engine's caching starts paying.
642
652
  */
643
- export function applyDerivedReport(series, specs, units) {
653
+ export function applyDerivedReport(input, specs, units, others) {
654
+ let series = input;
655
+ const prefixes = Object.keys(others ?? {}).filter(isOtherPrefix);
656
+ if (prefixes.length > 0) {
657
+ const joined = applyJoinedReport(series, specs, units, others, prefixes);
658
+ if (joined)
659
+ return joined;
660
+ // Pond refused the join (a column kind it cannot carry, on either side) or
661
+ // its columns would not name back without colliding (a refold of a folded
662
+ // series). Join exactly instead, as before 0.27.0, so the other symbols
663
+ // still arrive; the fold below then skips what cannot fold.
664
+ for (const prefix of [...prefixes].sort()) {
665
+ try {
666
+ series = joinUnderPrefix(series, others[prefix], prefix);
667
+ }
668
+ catch {
669
+ // Already carries that symbol's columns (a refold): read those.
670
+ }
671
+ }
672
+ }
644
673
  if (specs.length === 0)
645
674
  return { series, skipped: [], nodes: [] };
646
675
  // NOT idempotent over an already-folded series: an output column that
@@ -688,11 +717,181 @@ export function applyDerivedReport(series, specs, units) {
688
717
  }));
689
718
  return { series: result.series ?? series, skipped: [...skipped.values()], nodes };
690
719
  }
720
+ /** Whether `prefix` names another symbol's columns: the comparison's, or a
721
+ * locked symbol's with a symbol {@link isPinnableSymbol} accepts. */
722
+ const isOtherPrefix = (prefix) => prefix === COMPARE_PREFIX ||
723
+ (prefix.startsWith(PINNED_START) &&
724
+ prefix.endsWith('_') &&
725
+ isPinnableSymbol(prefix.slice(PINNED_START.length, -1)));
726
+ /** The start every locked symbol's prefix shares (`cmp_@`). */
727
+ const PINNED_START = `${COMPARE_PREFIX}@`;
728
+ /** The join's key for this symbol's own series. Pond names a joined column
729
+ * `<key>:<column>`, this one included (CHARTS_FRICTION F-charts-45). */
730
+ const BASE_KEY = 'p';
731
+ /** The join's key for another symbol's prefix: `c` for the comparison,
732
+ * `@SPY` for a locked symbol. Neither can be {@link BASE_KEY} or hold `:`. */
733
+ const keyOfPrefix = (prefix) => prefix === COMPARE_PREFIX ? 'c' : prefix.slice(COMPARE_PREFIX.length, -1);
734
+ /** Rewrite every raw column leaf of a spec, at any depth. A shape that is not
735
+ * a spec (untyped persisted state) passes through untouched, for the engine
736
+ * to skip and report as it would have. */
737
+ function mapLeaves(input, leaf) {
738
+ if (typeof input === 'string')
739
+ return leaf(input);
740
+ if (isPickedInput(input))
741
+ return { from: mapLeaves(input.from, leaf), output: input.output };
742
+ if (!isSpecLike(input) || !Array.isArray(input.inputs))
743
+ return input;
744
+ return { ...input, inputs: input.inputs.map((i) => mapLeaves(i, leaf)) };
745
+ }
746
+ /** Every spec in `spec`, nested ones included, outermost first. */
747
+ function specsWithin(spec, out = []) {
748
+ if (!isSpecLike(spec))
749
+ return out;
750
+ out.push(spec);
751
+ if (!Array.isArray(spec.inputs))
752
+ return out;
753
+ for (const i of spec.inputs) {
754
+ if (typeof i === 'string')
755
+ continue;
756
+ specsWithin(isPickedInput(i) ? i.from : i, out);
757
+ }
758
+ return out;
759
+ }
760
+ /** `deriveId`, never throwing — the BELT in {@link applyDerivedReport}. */
761
+ function safeId(spec) {
762
+ try {
763
+ return deriveId(spec);
764
+ }
765
+ catch {
766
+ return `${BROKEN_ID_PREFIX}${JSON.stringify(spec) ?? 'unnameable'}`;
767
+ }
768
+ }
769
+ /**
770
+ * {@link applyDerivedReport} over a joined binding: `series` and the other
771
+ * symbols' series behind one as-of join node, `series` the base.
772
+ *
773
+ * Pond qualifies every joined column with its source's key, the base's too
774
+ * (`p:close`, `c:close`), and a spec id names the columns it reads, so the
775
+ * fold works in pond's names and hands back Tidal's: going in, every raw
776
+ * leaf is rewritten (`close` → `p:close`, `cmp_close` → `c:close`,
777
+ * `cmp_@SPY_close` → `@SPY:close`); coming out, the columns, the node report
778
+ * and the skips are named back, so a caller sees exactly the columns and ids
779
+ * a single-series fold would give. This is the one place the two naming
780
+ * schemes meet; it shrinks to the other symbols alone if pond leaves the
781
+ * base's names unqualified (F-charts-45).
782
+ *
783
+ * `undefined` when pond refuses the binding (a column of a kind a join cannot
784
+ * carry, on the base as much as on another symbol) or when the columns would
785
+ * not name back without two colliding (refolding a folded series): the caller
786
+ * then joins exactly, as before, and folds that.
787
+ */
788
+ function applyJoinedReport(series, specs, units, others, prefixes) {
789
+ // Longest first, so `cmp_@SPY_close` is SPY's even with the comparison
790
+ // joined too. A leaf under no joined prefix is the base's — a comparison
791
+ // column with no comparison joined then names a column that is not there,
792
+ // and skips, as it did before.
793
+ const byLength = [...prefixes].sort((a, b) => b.length - a.length);
794
+ const toPond = (column) => {
795
+ const prefix = byLength.find((p) => column.startsWith(p));
796
+ return prefix
797
+ ? `${keyOfPrefix(prefix)}:${column.slice(prefix.length)}`
798
+ : `${BASE_KEY}:${column}`;
799
+ };
800
+ const back = new Map([[BASE_KEY, '']]);
801
+ for (const prefix of prefixes)
802
+ back.set(keyOfPrefix(prefix), prefix);
803
+ let graph;
804
+ try {
805
+ const sources = { [BASE_KEY]: series };
806
+ for (const prefix of prefixes)
807
+ sources[keyOfPrefix(prefix)] = others[prefix];
808
+ const pondUnits = units
809
+ ? Object.fromEntries(Object.entries(units).map(([col, unit]) => [toPond(col), unit]))
810
+ : undefined;
811
+ graph = bind(sources, {
812
+ registry: TIDAL_OPS,
813
+ units: pondUnits,
814
+ join: { how: 'asof', base: BASE_KEY },
815
+ });
816
+ }
817
+ catch {
818
+ return undefined;
819
+ }
820
+ // Each spec in pond's names, and the id map back. Nested specs too: the
821
+ // node report names every step, and a nested id is a column a later step
822
+ // reads.
823
+ const translated = specs.map((s) => mapLeaves(s, toPond));
824
+ const ids = new Map();
825
+ for (const spec of specs)
826
+ for (const inner of specsWithin(spec))
827
+ ids.set(safeId(mapLeaves(inner, toPond)), safeId(inner));
828
+ // Longest first, so an id that starts another id is not taken for it.
829
+ const pondIds = [...ids.keys()].sort((a, b) => b.length - a.length);
830
+ const fromPond = (column) => {
831
+ const exact = ids.get(column);
832
+ if (exact !== undefined)
833
+ return exact;
834
+ // A multi-output step's columns are its id plus the output's suffix.
835
+ const id = pondIds.find((i) => column.startsWith(i));
836
+ if (id !== undefined)
837
+ return `${ids.get(id)}${column.slice(id.length)}`;
838
+ const at = column.indexOf(':');
839
+ const prefix = at > 0 ? back.get(column.slice(0, at)) : undefined;
840
+ return prefix === undefined ? column : `${prefix}${column.slice(at + 1)}`;
841
+ };
842
+ const named = (s) => {
843
+ const mapping = {};
844
+ for (const col of s.schema.slice(1)) {
845
+ const name = fromPond(col.name);
846
+ if (name !== col.name)
847
+ mapping[col.name] = name;
848
+ }
849
+ return s.rename(mapping);
850
+ };
851
+ if (specs.length === 0) {
852
+ try {
853
+ return { series: named(graph.series), skipped: [], nodes: [] };
854
+ }
855
+ catch {
856
+ return undefined;
857
+ }
858
+ }
859
+ const result = run(graph, {
860
+ plan: translated,
861
+ select: translated.map((s) => ({ on: s })),
862
+ onError: 'skip',
863
+ });
864
+ const skipped = new Map();
865
+ for (const s of result.skipped) {
866
+ const spec = (s.spec ?? s.select?.on);
867
+ if (!spec)
868
+ continue;
869
+ const pondId = safeId(spec);
870
+ const id = ids.get(pondId) ?? pondId;
871
+ if (!skipped.has(id))
872
+ skipped.set(id, { id, code: s.code, reason: s.reason });
873
+ }
874
+ const nodes = result.nodes.map(({ id, pulled, cached, ms, inputs }) => ({
875
+ id: fromPond(id),
876
+ pulled,
877
+ cached,
878
+ ms,
879
+ inputs: inputs.map(fromPond),
880
+ }));
881
+ let out;
882
+ try {
883
+ out = named(result.series ?? graph.series);
884
+ }
885
+ catch {
886
+ return undefined;
887
+ }
888
+ return { series: out, skipped: [...skipped.values()], nodes };
889
+ }
691
890
  /** {@link applyDerivedReport} without the report — the fold most render paths
692
891
  * want (the chart's column-absence handling is the render half of the skip
693
892
  * contract). */
694
- export function applyDerived(series, specs, units) {
695
- return applyDerivedReport(series, specs, units).series;
893
+ export function applyDerived(series, specs, units, others) {
894
+ return applyDerivedReport(series, specs, units, others).series;
696
895
  }
697
896
  /** Whether an op declares a `period` param — i.e. whether it is WINDOWED, and
698
897
  * so whether a study of it should carry one. Stamping `{period}` onto an op
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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tidal-ts/core",
3
- "version": "0.26.0",
3
+ "version": "0.27.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",