@tidal-ts/core 0.2.1 → 0.3.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
@@ -52,10 +52,25 @@ export declare const COMPARE_PREFIX = "cmp_";
52
52
  export type PairOp = 'diff' | 'ratio' | 'logRatio';
53
53
  /** True if `op` takes a second input. */
54
54
  export declare const isPairOp: (op: DeriveOp) => op is PairOp;
55
- /** An input of a spec: a raw source column name, or a **nested spec** (the
55
+ /** ONE output of a multi-output spec, named by its declared suffix —
56
+ * `@pond-ts/process`'s `PickedOutput`, narrowed to Tidal's spec. The engine
57
+ * names it `${id}#${output}` and folds exactly that column, where a bare
58
+ * nested multi-output spec reads its FIRST-declared output: `Middle` for
59
+ * `bollinger`, but `Upper` for `donchian`, with nothing on screen saying so
60
+ * (TDL-STUDYCHAIN, measured 2026-09-26). */
61
+ export interface PickedDeriveOutput {
62
+ readonly from: DeriveSpec;
63
+ /** The output's declared suffix (`'Middle'`, `'Hist'`) — see {@link opOutputs}. */
64
+ readonly output: string;
65
+ }
66
+ /** An input of a spec: a raw source column name, a **nested spec** (the
56
67
  * engine's own recursion — an id string naming another spec is NOT an input;
57
- * the engine reads a string input as a raw column, so composition nests). */
58
- export type DeriveInput = string | DeriveSpec;
68
+ * the engine reads a string input as a raw column, so composition nests), or
69
+ * one picked output of a nested multi-output spec. */
70
+ export type DeriveInput = string | DeriveSpec | PickedDeriveOutput;
71
+ /** True if an input picks one output of a nested spec. Total over persisted
72
+ * state, like {@link isSpecLike}. */
73
+ export declare function isPickedInput(i: unknown): i is PickedDeriveOutput;
59
74
  /** A derive spec — structurally a `@pond-ts/process` plan `Spec`, narrowed to
60
75
  * Tidal's op vocabulary. Content-addressed by the engine: params are
61
76
  * defaulted + key-sorted inside `specId`, so an omitted param and its
@@ -328,6 +343,10 @@ export declare function usesCompare(spec: DeriveSpec): boolean;
328
343
  export interface PartStudy {
329
344
  op: DeriveOp;
330
345
  params?: Readonly<Record<string, number>>;
346
+ /** The ONE output of this study the next step reads, when it has several
347
+ * (a picked input — `sma` of a band's `Middle`). Absent for a single-output
348
+ * study, whose only column is read. */
349
+ output?: string;
331
350
  }
332
351
  /**
333
352
  * One leg of a pair, read back OUT of the pair's spec — the Metric/Part node.
@@ -541,6 +560,25 @@ export declare function opIsBand(op: DeriveOp): boolean;
541
560
  /** Whether an op produces SEVERAL columns that are not a band — drawn as N
542
561
  * lines off one spec (`style: 'lines'`), one per declared output. */
543
562
  export declare function opIsMulti(op: DeriveOp): boolean;
563
+ /**
564
+ * The output a study OF this op reads unless told otherwise — its PRIMARY, or
565
+ * `undefined` for a single-output op (whose column is the input as it stands).
566
+ *
567
+ * `Middle` for a band; else the output the catalog left unnamed (declared as
568
+ * {@link PRIMARY_SUFFIX} — `trix`'s line, not its `Signal`); else the first
569
+ * declared (`macd`'s `Line`, `stochastic`'s `K`). Some studies have no primary
570
+ * at all (`vortex`'s Plus/Minus, `elderRay`'s Bull/Bear, `atrBands`'
571
+ * Upper/Lower): they take the first, and the study's label names the output
572
+ * either way, so the choice is never silent. The rule is ours, not the
573
+ * catalog's — a declared primary is asked for as F-charts-29 (2).
574
+ */
575
+ export declare function primaryOutput(op: DeriveOp): string | undefined;
576
+ /**
577
+ * What a study of `source` reads: the source itself, or — for a multi-output
578
+ * source — its {@link primaryOutput}, PICKED. Never a bare nested multi-output
579
+ * spec, whose reading is whichever output happens to be declared first.
580
+ */
581
+ export declare function studyInputOf(source: string | DeriveSpec): DeriveInput;
544
582
  /**
545
583
  * The ops offerable as a **study** of one series: every single-input,
546
584
  * column-producing op in {@link TIDAL_OPS}. Generated from the registry's own
package/dist/derive.js CHANGED
@@ -1,4 +1,4 @@
1
- import { ADOPTED_STUDIES, BAND_OUTPUTS, catalogOp, OWN_AXIS_STUDIES, studyNeedsColumns, } from './studyCatalog.js';
1
+ import { ADOPTED_STUDIES, BAND_OUTPUTS, catalogOp, OWN_AXIS_STUDIES, PRIMARY_SUFFIX, studyNeedsColumns, } from './studyCatalog.js';
2
2
  import { bollinger, ema, sma } from '@pond-ts/financial';
3
3
  import { bind, columnsOf, createRegistry, int, num, run, specId, explain, } from '@pond-ts/process';
4
4
  /**
@@ -13,6 +13,14 @@ import { bind, columnsOf, createRegistry, int, num, run, specId, explain, } from
13
13
  export const COMPARE_PREFIX = 'cmp_';
14
14
  /** True if `op` takes a second input. */
15
15
  export const isPairOp = (op) => op === 'diff' || op === 'ratio' || op === 'logRatio';
16
+ /** True if an input picks one output of a nested spec. Total over persisted
17
+ * state, like {@link isSpecLike}. */
18
+ export function isPickedInput(i) {
19
+ return (typeof i === 'object' &&
20
+ i !== null &&
21
+ typeof i.output === 'string' &&
22
+ isSpecLike(i.from));
23
+ }
16
24
  /** The default bar-count period a study uses when none is given. */
17
25
  export const DEFAULT_PERIOD = 20;
18
26
  /**
@@ -301,7 +309,16 @@ export function deriveLineage(spec) {
301
309
  export function inputNames(spec) {
302
310
  // `?? []`: persisted state is untyped at this boundary — an old-shape spec
303
311
  // (pre-`inputs`) must degrade to "no edges", never a TypeError mid-render.
304
- return (spec.inputs ?? []).map((i) => (typeof i === 'string' ? i : deriveId(i)));
312
+ return (spec.inputs ?? []).map(inputName);
313
+ }
314
+ /** The column one input names for the dependency walks. A PICKED output names
315
+ * its source's column — a multi-output config's `column` is its spec id (the
316
+ * prefix its outputs hang off), and that config is the parent being walked,
317
+ * whichever of its outputs is read. */
318
+ function inputName(i) {
319
+ if (typeof i === 'string')
320
+ return i;
321
+ return deriveId(isPickedInput(i) ? i.from : i);
305
322
  }
306
323
  /**
307
324
  * Rewrite every reference to the column `from`, at any depth, to `to` — the
@@ -325,6 +342,20 @@ export function substituteInput(spec, from, to) {
325
342
  changed = true;
326
343
  return to;
327
344
  }
345
+ // A pick follows its source and KEEPS its output: retuning a band re-points
346
+ // a study of its `Lower` at the new band's `Lower`. Only a spec can be
347
+ // picked from, so a replacement that isn't one takes the input whole.
348
+ if (isPickedInput(i)) {
349
+ if (deriveId(i.from) === from) {
350
+ changed = true;
351
+ return typeof to === 'string' || isPickedInput(to) ? to : { from: to, output: i.output };
352
+ }
353
+ const sub = substituteInput(i.from, from, to);
354
+ if (sub === i.from)
355
+ return i;
356
+ changed = true;
357
+ return { from: sub, output: i.output };
358
+ }
328
359
  if (deriveId(i) === from) {
329
360
  changed = true;
330
361
  return to;
@@ -346,12 +377,25 @@ export function substituteInput(spec, from, to) {
346
377
  */
347
378
  export function isValidSpec(spec) {
348
379
  try {
349
- return !isBrokenId(deriveId(spec));
380
+ return !isBrokenId(deriveId(spec)) && picksDeclared(spec);
350
381
  }
351
382
  catch {
352
383
  return false;
353
384
  }
354
385
  }
386
+ /** True if every pick, at any depth, names an output its op DECLARES. The
387
+ * engine only finds out at run time (a generic error, not a plan-layer code),
388
+ * so a persisted pick of `Nope` would otherwise pass as valid and then skip
389
+ * with nothing for a chip to classify it by. */
390
+ function picksDeclared(spec) {
391
+ return (spec.inputs ?? []).every((i) => {
392
+ if (typeof i === 'string')
393
+ return true;
394
+ if (isPickedInput(i))
395
+ return opOutputs(i.from.op).includes(i.output) && picksDeclared(i.from);
396
+ return picksDeclared(i);
397
+ });
398
+ }
355
399
  /**
356
400
  * True if the value is a readable spec node — an object naming an op.
357
401
  *
@@ -380,20 +424,24 @@ export function hasPairOp(spec) {
380
424
  if (!isSpecLike(spec))
381
425
  return false;
382
426
  return (isPairOp(spec.op) ||
383
- (spec.inputs ?? []).some((i) => typeof i !== 'string' && hasPairOp(i)));
427
+ (spec.inputs ?? []).some((i) => typeof i !== 'string' && hasPairOp(isPickedInput(i) ? i.from : i)));
384
428
  }
385
429
  /** True if any input (recursively) reads a compare-role column — the host
386
430
  * must join the comparison series on before folding such a spec. */
387
431
  export function usesCompare(spec) {
388
432
  if (!isSpecLike(spec))
389
433
  return false;
390
- return (spec.inputs ?? []).some((i) => typeof i === 'string' ? i.startsWith(COMPARE_PREFIX) : usesCompare(i));
434
+ return (spec.inputs ?? []).some((i) => typeof i === 'string'
435
+ ? i.startsWith(COMPARE_PREFIX)
436
+ : usesCompare(isPickedInput(i) ? i.from : i));
391
437
  }
392
438
  /** Strip the compare rebind from an input's leaves — the inverse of the host's
393
439
  * `underCompare`, used to name a leg independently of the role it reads. */
394
440
  function unCompare(input) {
395
441
  if (typeof input === 'string')
396
442
  return input.startsWith(COMPARE_PREFIX) ? input.slice(COMPARE_PREFIX.length) : input;
443
+ if (isPickedInput(input))
444
+ return { from: unCompare(input.from), output: input.output };
397
445
  if (!isSpecLike(input))
398
446
  return input; // pathological persisted node — leave it
399
447
  return { ...input, inputs: (input.inputs ?? []).map(unCompare) };
@@ -413,11 +461,25 @@ function unCompare(input) {
413
461
  export function readPart(input) {
414
462
  const studies = [];
415
463
  let cur = input;
416
- while (isSpecLike(cur) && opHasPeriod(cur.op)) {
417
- const inputs = cur.inputs ?? [];
464
+ for (;;) {
465
+ // A PICK is one output of a study: step through it as that study, noting
466
+ // which output the chain reads on from it (`BOLLINGER(20, 2) · Middle`).
467
+ const picked = isPickedInput(cur) ? cur : undefined;
468
+ const node = picked ? picked.from : cur;
469
+ if (!isSpecLike(node) || !opHasPeriod(node.op)) {
470
+ // A pick of an unwindowed op has no name as a part: refuse, as below.
471
+ if (picked)
472
+ return null;
473
+ break;
474
+ }
475
+ const inputs = node.inputs ?? [];
418
476
  if (inputs.length !== 1)
419
477
  return null; // windowed but multi-input: not a chain
420
- studies.unshift({ op: cur.op, params: cur.params });
478
+ studies.unshift({
479
+ op: node.op,
480
+ params: node.params,
481
+ ...(picked ? { output: picked.output } : {}),
482
+ });
421
483
  cur = inputs[0];
422
484
  }
423
485
  // Anything that isn't a plain column or a single-input metric node has no
@@ -448,8 +510,9 @@ export const partStudyLabel = (st) =>
448
510
  // `studyTag`, which reads the op's DECLARED params in order and defaults each
449
511
  // — so a band leg reads `BOLLINGER(20, 2)`. Hand-built off `params.period` it
450
512
  // read `BOLLINGER(20)`, and two bands differing only in `stdDev` produced
451
- // identical leg rows (PR #181 review, HIGH).
452
- studyTag({ op: st.op, inputs: [], params: st.params });
513
+ // identical leg rows (PR #181 review, HIGH). A picked output follows it, the
514
+ // same way a study's label names it.
515
+ studyTag({ op: st.op, inputs: [], params: st.params }) + (st.output ? ` · ${st.output}` : '');
453
516
  /** A pair spec's two legs as parts, or **null** if this isn't a pair op or
454
517
  * either leg doesn't decompose. Pairs are strictly binary, so anything else
455
518
  * is a shape we didn't write. */
@@ -475,14 +538,27 @@ export function readPairParts(spec) {
475
538
  * this collapses to reading the graph's answer.
476
539
  */
477
540
  export function specUnit(spec, unitOf) {
541
+ return outputUnit(spec, 0, unitOf);
542
+ }
543
+ /** {@link specUnit} for one declared output, by index — a PICKED input reads
544
+ * in its own output's unit, which need not be output 0's. */
545
+ function outputUnit(spec, index, unitOf) {
478
546
  if (!isSpecLike(spec))
479
547
  return ''; // total over persisted garbage — see isSpecLike
480
- const declared = TIDAL_OPS.describe().find((d) => d.name === spec.op)?.outputs?.[0]?.unit;
548
+ const declared = TIDAL_OPS.describe().find((d) => d.name === spec.op)?.outputs?.[index]?.unit;
481
549
  if (declared == null)
482
550
  return '';
483
551
  if (declared !== 'inherit')
484
552
  return declared;
485
- const units = (spec.inputs ?? []).map((i) => typeof i === 'string' ? unitOf(i) : specUnit(i, unitOf));
553
+ const units = (spec.inputs ?? []).map((i) => {
554
+ if (typeof i === 'string')
555
+ return unitOf(i);
556
+ if (isPickedInput(i)) {
557
+ const at = opOutputs(i.from.op).indexOf(i.output);
558
+ return at < 0 ? '' : outputUnit(i.from, at, unitOf);
559
+ }
560
+ return specUnit(i, unitOf);
561
+ });
486
562
  const first = units[0];
487
563
  return first != null && units.every((u) => u === first) ? first : '';
488
564
  }
@@ -702,6 +778,39 @@ export function opIsBand(op) {
702
778
  export function opIsMulti(op) {
703
779
  return opOutputs(op).length > 1 && !opIsBand(op);
704
780
  }
781
+ /**
782
+ * The output a study OF this op reads unless told otherwise — its PRIMARY, or
783
+ * `undefined` for a single-output op (whose column is the input as it stands).
784
+ *
785
+ * `Middle` for a band; else the output the catalog left unnamed (declared as
786
+ * {@link PRIMARY_SUFFIX} — `trix`'s line, not its `Signal`); else the first
787
+ * declared (`macd`'s `Line`, `stochastic`'s `K`). Some studies have no primary
788
+ * at all (`vortex`'s Plus/Minus, `elderRay`'s Bull/Bear, `atrBands`'
789
+ * Upper/Lower): they take the first, and the study's label names the output
790
+ * either way, so the choice is never silent. The rule is ours, not the
791
+ * catalog's — a declared primary is asked for as F-charts-29 (2).
792
+ */
793
+ export function primaryOutput(op) {
794
+ const outs = opOutputs(op);
795
+ if (outs.length < 2)
796
+ return undefined;
797
+ if (outs.includes('Middle'))
798
+ return 'Middle';
799
+ if (outs.includes(PRIMARY_SUFFIX))
800
+ return PRIMARY_SUFFIX;
801
+ return outs[0];
802
+ }
803
+ /**
804
+ * What a study of `source` reads: the source itself, or — for a multi-output
805
+ * source — its {@link primaryOutput}, PICKED. Never a bare nested multi-output
806
+ * spec, whose reading is whichever output happens to be declared first.
807
+ */
808
+ export function studyInputOf(source) {
809
+ if (typeof source === 'string')
810
+ return source;
811
+ const output = primaryOutput(source.op);
812
+ return output === undefined ? source : { from: source, output };
813
+ }
705
814
  /** `sma` → `SMA`; `realizedVol` → `Realized vol`. Acronym-ish short names go
706
815
  * upper, longer camelCase names read as a sentence. */
707
816
  function opLabel(name) {
package/dist/index.d.ts CHANGED
@@ -2,7 +2,7 @@ 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, deriveId, deriveLineage, inputNames, substituteInput, hasPairOp, isBrokenId, isPairOp, isValidSpec, opHasPeriod, PERIOD_BOUNDS, readNumericColumn, partStudyLabel, readPart, readPairParts, specUnit, studyCatalog, TIDAL_OPS, BAND_OUTPUTS, opParams, studyTag, opIsBand, opInputs, opIsMulti, opOutputs, opNeedsColumns, TARGET_ROLES, opSharesSourceAxis, type OpParam, usesCompare, type DeriveSkip, type PairPart, type PartStudy, type StudyOption, type NumericColumnReader, DEFAULT_PERIOD, type DeriveInput, type DeriveSpec, type DeriveOp, type TidalOp, type PairOp, } from './derive.js';
5
+ export { applyDerived, applyDerivedReport, COMPARE_PREFIX, deriveId, deriveLineage, inputNames, substituteInput, hasPairOp, isBrokenId, isPairOp, isValidSpec, opHasPeriod, PERIOD_BOUNDS, readNumericColumn, partStudyLabel, readPart, readPairParts, specUnit, studyCatalog, TIDAL_OPS, BAND_OUTPUTS, opParams, studyTag, opIsBand, opInputs, opIsMulti, opOutputs, primaryOutput, studyInputOf, isPickedInput, opNeedsColumns, TARGET_ROLES, opSharesSourceAxis, type OpParam, usesCompare, type DeriveSkip, 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';
package/dist/index.js CHANGED
@@ -2,7 +2,7 @@ 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, deriveId, deriveLineage, inputNames, substituteInput, hasPairOp, isBrokenId, isPairOp, isValidSpec, opHasPeriod, PERIOD_BOUNDS, readNumericColumn, partStudyLabel, readPart, readPairParts, specUnit, studyCatalog, TIDAL_OPS, BAND_OUTPUTS, opParams, studyTag, opIsBand, opInputs, opIsMulti, opOutputs, opNeedsColumns, TARGET_ROLES, opSharesSourceAxis, usesCompare, DEFAULT_PERIOD, } from './derive.js';
5
+ export { applyDerived, applyDerivedReport, COMPARE_PREFIX, deriveId, deriveLineage, inputNames, substituteInput, hasPairOp, isBrokenId, isPairOp, isValidSpec, opHasPeriod, PERIOD_BOUNDS, readNumericColumn, partStudyLabel, readPart, readPairParts, specUnit, studyCatalog, TIDAL_OPS, BAND_OUTPUTS, opParams, studyTag, opIsBand, opInputs, opIsMulti, opOutputs, primaryOutput, studyInputOf, 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';
@@ -50,6 +50,23 @@ export declare function studyNeedsColumns(d: Descriptor): string[];
50
50
  * times and squashes the series the study was meant to explain.
51
51
  */
52
52
  export declare const sharesSourceAxis: (d: Descriptor) => boolean;
53
+ /**
54
+ * The suffix the PRIMARY output is declared under when the catalog leaves it
55
+ * empty.
56
+ *
57
+ * `@pond-ts/financial`'s catalog and `@pond-ts/process`'s registry disagree
58
+ * here, and the registry is the stricter of the two: 12 studies declare an
59
+ * unnamed primary beside a named secondary (`trix` is `['', 'Signal']`), and
60
+ * `define` refuses that outright — _"every output needs a suffix — '' would
61
+ * collide with the spec id"_. It is right to refuse: with two outputs, one of
62
+ * them cannot also BE the id.
63
+ *
64
+ * So the registry sees `Value`/`Signal` where the catalog said `''`/`Signal`.
65
+ * The lists are deliberately different and must not be conflated:
66
+ * {@link catalogRun} reads the CORPUS by the catalog's own suffix, while the
67
+ * engine names OUR column off the registry's. Logged as F-charts-27.
68
+ */
69
+ export declare const PRIMARY_SUFFIX = "Value";
53
70
  /** How one declared output should be drawn. `'line'` unless the overlay says
54
71
  * otherwise — see {@link OUTPUT_MARKS}. */
55
72
  export declare function outputMark(op: string, suffix: string): 'line' | 'bar';
@@ -109,7 +109,7 @@ export const sharesSourceAxis = (d) => d.outputs.every((o) => o.unit === 'inheri
109
109
  * {@link catalogRun} reads the CORPUS by the catalog's own suffix, while the
110
110
  * engine names OUR column off the registry's. Logged as F-charts-27.
111
111
  */
112
- const PRIMARY_SUFFIX = 'Value';
112
+ export const PRIMARY_SUFFIX = 'Value';
113
113
  /** The suffixes to DECLARE for a descriptor — the catalog's, except that a
114
114
  * multi-output op's empty primary is named (see {@link PRIMARY_SUFFIX}). */
115
115
  function declaredSuffixes(d) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tidal-ts/core",
3
- "version": "0.2.1",
3
+ "version": "0.3.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",