@tidal-ts/core 0.1.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/LICENSE +21 -0
- package/dist/aggregate.d.ts +193 -0
- package/dist/aggregate.js +288 -0
- package/dist/columnar.d.ts +61 -0
- package/dist/columnar.js +63 -0
- package/dist/derive.d.ts +555 -0
- package/dist/derive.js +740 -0
- package/dist/expirations.d.ts +85 -0
- package/dist/expirations.js +151 -0
- package/dist/extent.d.ts +20 -0
- package/dist/extent.js +44 -0
- package/dist/fixture.d.ts +64 -0
- package/dist/fixture.js +116 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +16 -0
- package/dist/join.d.ts +31 -0
- package/dist/join.js +36 -0
- package/dist/regrid.d.ts +22 -0
- package/dist/regrid.js +85 -0
- package/dist/sessions.d.ts +141 -0
- package/dist/sessions.js +232 -0
- package/dist/studyCatalog.d.ts +129 -0
- package/dist/studyCatalog.js +361 -0
- package/dist/timeZone.d.ts +51 -0
- package/dist/timeZone.js +80 -0
- package/dist/types.d.ts +20 -0
- package/dist/types.js +12 -0
- package/dist/vol.d.ts +160 -0
- package/dist/vol.js +252 -0
- package/package.json +50 -0
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* **Standard monthly option expirations**, derived from the trading calendar.
|
|
3
|
+
*
|
|
4
|
+
* The rule is two clauses: the **third Friday** of the calendar month, and if the
|
|
5
|
+
* market is closed that day, the **previous trading day**. Nothing else — no
|
|
6
|
+
* dataset, no per-instrument lookup. A monthly expiration is a fact about the
|
|
7
|
+
* calendar, and `TDL-CALAXIS` already put the calendar in the terminal's hands,
|
|
8
|
+
* so this is free where a data load would not be.
|
|
9
|
+
*
|
|
10
|
+
* An early design proposed sourcing expirations from a per-row listed-expiry
|
|
11
|
+
* count instead. That is a **count of listed
|
|
12
|
+
* expiries per row**, not a date: it rises when a new expiry gets listed and
|
|
13
|
+
* falls when one rolls off, so recovering the expiration dates from it means
|
|
14
|
+
* inferring events from a noisy difference — and the column is not in our load
|
|
15
|
+
* anyway. The calendar answers the question exactly.
|
|
16
|
+
*
|
|
17
|
+
* ## Why the naive version is wrong
|
|
18
|
+
*
|
|
19
|
+
* "The third Friday that is a trading day" is **not** the rule, and the
|
|
20
|
+
* difference is not hypothetical — measured against an exchange trading calendar, it
|
|
21
|
+
* misfires whenever an *earlier* Friday in the month was a holiday, because
|
|
22
|
+
* dropping that Friday shifts the count forward:
|
|
23
|
+
*
|
|
24
|
+
* | month | third *trading* Friday | actual expiration |
|
|
25
|
+
* | ------- | ---------------------- | ---------------------------- |
|
|
26
|
+
* | 2025-04 | 2025-04-25 ✗ | 2025-04-17 — the 18th was Good Friday |
|
|
27
|
+
* | 2025-07 | 2025-07-25 ✗ | 2025-07-18 — Jul 4 fell on a Friday |
|
|
28
|
+
*
|
|
29
|
+
* So the third Friday is counted on the **calendar**, and only then adjusted. And
|
|
30
|
+
* when it *is* the closed day, expiration moves **back** to the Thursday, never
|
|
31
|
+
* forward to the next Friday — the contract cannot outlive its own expiry.
|
|
32
|
+
*
|
|
33
|
+
* Over 2015–2026 that back-step fires exactly **four** times in 144 months:
|
|
34
|
+
* Good Friday in 2019, 2022 and 2025, plus **2026-06-19, Juneteenth** — which is
|
|
35
|
+
* the reason this reads the calendar instead of hard-coding Easter. A holiday
|
|
36
|
+
* list is not static; the market's own calendar is the only thing that keeps up.
|
|
37
|
+
*
|
|
38
|
+
* ## What this is and is not
|
|
39
|
+
*
|
|
40
|
+
* These are the **regular monthly** expirations and nothing else — exactly 12 a
|
|
41
|
+
* year over 2012–2026, verified. Deliberately absent: **weeklies** (the other
|
|
42
|
+
* Fridays, plus Monday/Wednesday series), **end-of-month**, and anything
|
|
43
|
+
* product-specific. The quarterly "triple witching" months are *not* missing —
|
|
44
|
+
* March / June / September / December land on third Fridays, so they come through
|
|
45
|
+
* as a subset of these.
|
|
46
|
+
*
|
|
47
|
+
* **The pre-2015 nuance, and it covers a third of our span.** Until the OCC moved
|
|
48
|
+
* it (effective with the early-2015 cycle), an equity option's formal expiration
|
|
49
|
+
* *date* was the **Saturday following** the third Friday; the Friday was the last
|
|
50
|
+
* *trading* day. Our archive starts 2012-03, so roughly the first three years
|
|
51
|
+
* predate the change.
|
|
52
|
+
*
|
|
53
|
+
* This returns the **Friday** throughout, which is the right answer for a chart
|
|
54
|
+
* and the wrong one for a settlement calendar. A trading axis has no x-position
|
|
55
|
+
* for a Saturday — it is not a session — so marking one would be marking a point
|
|
56
|
+
* the plot cannot show. What the marker means is therefore "the last session on
|
|
57
|
+
* which the expiring series traded", which is the same date as expiration from
|
|
58
|
+
* 2015 on and one day before it prior to that. Anything reconciling an actual
|
|
59
|
+
* pre-2015 expiration must not read these as settlement dates.
|
|
60
|
+
*
|
|
61
|
+
* **Not cross-checked against the feed.** No expiry-bearing dataset is loaded, so
|
|
62
|
+
* these dates are derived from the rule and validated against the trading
|
|
63
|
+
* calendar, not reconciled against the exchange's own expiry list.
|
|
64
|
+
*/
|
|
65
|
+
/**
|
|
66
|
+
* The third Friday of `year`/`month` (0-based month) as a UTC-midnight instant —
|
|
67
|
+
* pure date arithmetic, deliberately independent of any calendar. The first
|
|
68
|
+
* Friday falls on day `1 + ((5 - dow(1st) + 7) % 7)`; the third is 14 days later,
|
|
69
|
+
* which is always inside the month.
|
|
70
|
+
*/
|
|
71
|
+
export declare function thirdFriday(year: number, month: number): number;
|
|
72
|
+
/**
|
|
73
|
+
* Standard monthly expirations within `[from, to]`, ascending.
|
|
74
|
+
*
|
|
75
|
+
* `tradingDays` is the market's sessions as UTC-midnight instants — the same
|
|
76
|
+
* array the axis takes (`Repository.calendar`), **ascending**. A month whose
|
|
77
|
+
* third Friday is closed resolves to the previous session; a month with no
|
|
78
|
+
* session before it at all (the calendar's leading edge) is skipped rather than
|
|
79
|
+
* guessed at.
|
|
80
|
+
*
|
|
81
|
+
* Returns `[]` for an empty calendar — an expiration we cannot place is not an
|
|
82
|
+
* expiration we should draw, and inventing one from bare date arithmetic would
|
|
83
|
+
* put a marker on a day the market was shut.
|
|
84
|
+
*/
|
|
85
|
+
export declare function monthlyExpirations(tradingDays: readonly number[], from: number, to: number): number[];
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* **Standard monthly option expirations**, derived from the trading calendar.
|
|
3
|
+
*
|
|
4
|
+
* The rule is two clauses: the **third Friday** of the calendar month, and if the
|
|
5
|
+
* market is closed that day, the **previous trading day**. Nothing else — no
|
|
6
|
+
* dataset, no per-instrument lookup. A monthly expiration is a fact about the
|
|
7
|
+
* calendar, and `TDL-CALAXIS` already put the calendar in the terminal's hands,
|
|
8
|
+
* so this is free where a data load would not be.
|
|
9
|
+
*
|
|
10
|
+
* An early design proposed sourcing expirations from a per-row listed-expiry
|
|
11
|
+
* count instead. That is a **count of listed
|
|
12
|
+
* expiries per row**, not a date: it rises when a new expiry gets listed and
|
|
13
|
+
* falls when one rolls off, so recovering the expiration dates from it means
|
|
14
|
+
* inferring events from a noisy difference — and the column is not in our load
|
|
15
|
+
* anyway. The calendar answers the question exactly.
|
|
16
|
+
*
|
|
17
|
+
* ## Why the naive version is wrong
|
|
18
|
+
*
|
|
19
|
+
* "The third Friday that is a trading day" is **not** the rule, and the
|
|
20
|
+
* difference is not hypothetical — measured against an exchange trading calendar, it
|
|
21
|
+
* misfires whenever an *earlier* Friday in the month was a holiday, because
|
|
22
|
+
* dropping that Friday shifts the count forward:
|
|
23
|
+
*
|
|
24
|
+
* | month | third *trading* Friday | actual expiration |
|
|
25
|
+
* | ------- | ---------------------- | ---------------------------- |
|
|
26
|
+
* | 2025-04 | 2025-04-25 ✗ | 2025-04-17 — the 18th was Good Friday |
|
|
27
|
+
* | 2025-07 | 2025-07-25 ✗ | 2025-07-18 — Jul 4 fell on a Friday |
|
|
28
|
+
*
|
|
29
|
+
* So the third Friday is counted on the **calendar**, and only then adjusted. And
|
|
30
|
+
* when it *is* the closed day, expiration moves **back** to the Thursday, never
|
|
31
|
+
* forward to the next Friday — the contract cannot outlive its own expiry.
|
|
32
|
+
*
|
|
33
|
+
* Over 2015–2026 that back-step fires exactly **four** times in 144 months:
|
|
34
|
+
* Good Friday in 2019, 2022 and 2025, plus **2026-06-19, Juneteenth** — which is
|
|
35
|
+
* the reason this reads the calendar instead of hard-coding Easter. A holiday
|
|
36
|
+
* list is not static; the market's own calendar is the only thing that keeps up.
|
|
37
|
+
*
|
|
38
|
+
* ## What this is and is not
|
|
39
|
+
*
|
|
40
|
+
* These are the **regular monthly** expirations and nothing else — exactly 12 a
|
|
41
|
+
* year over 2012–2026, verified. Deliberately absent: **weeklies** (the other
|
|
42
|
+
* Fridays, plus Monday/Wednesday series), **end-of-month**, and anything
|
|
43
|
+
* product-specific. The quarterly "triple witching" months are *not* missing —
|
|
44
|
+
* March / June / September / December land on third Fridays, so they come through
|
|
45
|
+
* as a subset of these.
|
|
46
|
+
*
|
|
47
|
+
* **The pre-2015 nuance, and it covers a third of our span.** Until the OCC moved
|
|
48
|
+
* it (effective with the early-2015 cycle), an equity option's formal expiration
|
|
49
|
+
* *date* was the **Saturday following** the third Friday; the Friday was the last
|
|
50
|
+
* *trading* day. Our archive starts 2012-03, so roughly the first three years
|
|
51
|
+
* predate the change.
|
|
52
|
+
*
|
|
53
|
+
* This returns the **Friday** throughout, which is the right answer for a chart
|
|
54
|
+
* and the wrong one for a settlement calendar. A trading axis has no x-position
|
|
55
|
+
* for a Saturday — it is not a session — so marking one would be marking a point
|
|
56
|
+
* the plot cannot show. What the marker means is therefore "the last session on
|
|
57
|
+
* which the expiring series traded", which is the same date as expiration from
|
|
58
|
+
* 2015 on and one day before it prior to that. Anything reconciling an actual
|
|
59
|
+
* pre-2015 expiration must not read these as settlement dates.
|
|
60
|
+
*
|
|
61
|
+
* **Not cross-checked against the feed.** No expiry-bearing dataset is loaded, so
|
|
62
|
+
* these dates are derived from the rule and validated against the trading
|
|
63
|
+
* calendar, not reconciled against the exchange's own expiry list.
|
|
64
|
+
*/
|
|
65
|
+
/** Friday, in `Date#getUTCDay()` terms (0 = Sunday). */
|
|
66
|
+
const FRIDAY = 5;
|
|
67
|
+
/**
|
|
68
|
+
* The third Friday of `year`/`month` (0-based month) as a UTC-midnight instant —
|
|
69
|
+
* pure date arithmetic, deliberately independent of any calendar. The first
|
|
70
|
+
* Friday falls on day `1 + ((5 - dow(1st) + 7) % 7)`; the third is 14 days later,
|
|
71
|
+
* which is always inside the month.
|
|
72
|
+
*/
|
|
73
|
+
export function thirdFriday(year, month) {
|
|
74
|
+
const first = Date.UTC(year, month, 1);
|
|
75
|
+
const shift = (FRIDAY - new Date(first).getUTCDay() + 7) % 7;
|
|
76
|
+
return Date.UTC(year, month, 1 + shift + 14);
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Standard monthly expirations within `[from, to]`, ascending.
|
|
80
|
+
*
|
|
81
|
+
* `tradingDays` is the market's sessions as UTC-midnight instants — the same
|
|
82
|
+
* array the axis takes (`Repository.calendar`), **ascending**. A month whose
|
|
83
|
+
* third Friday is closed resolves to the previous session; a month with no
|
|
84
|
+
* session before it at all (the calendar's leading edge) is skipped rather than
|
|
85
|
+
* guessed at.
|
|
86
|
+
*
|
|
87
|
+
* Returns `[]` for an empty calendar — an expiration we cannot place is not an
|
|
88
|
+
* expiration we should draw, and inventing one from bare date arithmetic would
|
|
89
|
+
* put a marker on a day the market was shut.
|
|
90
|
+
*/
|
|
91
|
+
export function monthlyExpirations(tradingDays, from, to) {
|
|
92
|
+
if (tradingDays.length === 0 || to < from)
|
|
93
|
+
return [];
|
|
94
|
+
const open = new Set(tradingDays);
|
|
95
|
+
const out = [];
|
|
96
|
+
// Walk whole months from `from`'s month through `to`'s. The third Friday can
|
|
97
|
+
// fall outside [from, to] at either end, so each candidate is range-checked
|
|
98
|
+
// after resolution, not before — a back-stepped expiration can cross out of the
|
|
99
|
+
// window that its own Friday sat inside.
|
|
100
|
+
const start = new Date(from);
|
|
101
|
+
const end = new Date(to);
|
|
102
|
+
let year = start.getUTCFullYear();
|
|
103
|
+
let month = start.getUTCMonth();
|
|
104
|
+
const lastYear = end.getUTCFullYear();
|
|
105
|
+
const lastMonth = end.getUTCMonth();
|
|
106
|
+
// The calendar's last session. `previousSession` cannot tell "the market was
|
|
107
|
+
// shut that Friday" from "the calendar stops before that Friday", so without
|
|
108
|
+
// this a partial trailing month back-steps onto the final session and emits it
|
|
109
|
+
// as an expiration. Reproduced with a calendar ending 2025-03-10: March's third
|
|
110
|
+
// Friday is 03-21, which the calendar never reaches, and 03-10 came out as
|
|
111
|
+
// "March's expiration". Latent with today's data only because the loaded
|
|
112
|
+
// calendar runs to 2029.
|
|
113
|
+
const lastSession = tradingDays[tradingDays.length - 1];
|
|
114
|
+
while (year < lastYear || (year === lastYear && month <= lastMonth)) {
|
|
115
|
+
const friday = thirdFriday(year, month);
|
|
116
|
+
const expiry = friday > lastSession
|
|
117
|
+
? null
|
|
118
|
+
: open.has(friday)
|
|
119
|
+
? friday
|
|
120
|
+
: previousSession(tradingDays, friday);
|
|
121
|
+
if (expiry !== null && expiry >= from && expiry <= to)
|
|
122
|
+
out.push(expiry);
|
|
123
|
+
month += 1;
|
|
124
|
+
if (month > 11) {
|
|
125
|
+
month = 0;
|
|
126
|
+
year += 1;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
return out;
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* The latest session strictly before `t`, or `null` if the calendar starts later.
|
|
133
|
+
* Binary search — this runs once per month over a calendar of ~4,000 sessions,
|
|
134
|
+
* and a linear scan per month is quadratic in the range.
|
|
135
|
+
*/
|
|
136
|
+
function previousSession(days, t) {
|
|
137
|
+
let lo = 0;
|
|
138
|
+
let hi = days.length - 1;
|
|
139
|
+
let found = null;
|
|
140
|
+
while (lo <= hi) {
|
|
141
|
+
const mid = (lo + hi) >> 1;
|
|
142
|
+
if (days[mid] < t) {
|
|
143
|
+
found = days[mid];
|
|
144
|
+
lo = mid + 1;
|
|
145
|
+
}
|
|
146
|
+
else {
|
|
147
|
+
hi = mid - 1;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
return found;
|
|
151
|
+
}
|
package/dist/extent.d.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { SeriesSchema, TimeSeries } from 'pond-ts';
|
|
2
|
+
/** The erased-schema series the extent reads (like derive.ts / join.ts). */
|
|
3
|
+
type ExtentSeries = TimeSeries<SeriesSchema>;
|
|
4
|
+
/**
|
|
5
|
+
* The min/max of one numeric column, optionally limited to a time `range`
|
|
6
|
+
* (`[from, to]` epoch ms, inclusive) — the **natural extent** an axis-panel
|
|
7
|
+
* member row shows next to its axis's shared range, and the approximation of
|
|
8
|
+
* an axis's auto fit (the union of its members' extents; pond's own fit adds
|
|
9
|
+
* padding on top, which a readout doesn't need to reproduce).
|
|
10
|
+
*
|
|
11
|
+
* Columnar throughout: `bisect` finds the index bounds (O(log N), no Event
|
|
12
|
+
* allocations), `readNumericColumn` walks the packed buffer between them.
|
|
13
|
+
* Gaps (`undefined`/non-finite cells) are skipped; a column that is absent or
|
|
14
|
+
* all-gap in the window yields `null`.
|
|
15
|
+
*/
|
|
16
|
+
export declare function columnExtent(series: ExtentSeries, column: string, range?: readonly [number, number] | null): {
|
|
17
|
+
min: number;
|
|
18
|
+
max: number;
|
|
19
|
+
} | null;
|
|
20
|
+
export {};
|
package/dist/extent.js
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { readNumericColumn } from './derive.js';
|
|
2
|
+
/**
|
|
3
|
+
* The min/max of one numeric column, optionally limited to a time `range`
|
|
4
|
+
* (`[from, to]` epoch ms, inclusive) — the **natural extent** an axis-panel
|
|
5
|
+
* member row shows next to its axis's shared range, and the approximation of
|
|
6
|
+
* an axis's auto fit (the union of its members' extents; pond's own fit adds
|
|
7
|
+
* padding on top, which a readout doesn't need to reproduce).
|
|
8
|
+
*
|
|
9
|
+
* Columnar throughout: `bisect` finds the index bounds (O(log N), no Event
|
|
10
|
+
* allocations), `readNumericColumn` walks the packed buffer between them.
|
|
11
|
+
* Gaps (`undefined`/non-finite cells) are skipped; a column that is absent or
|
|
12
|
+
* all-gap in the window yields `null`.
|
|
13
|
+
*/
|
|
14
|
+
export function columnExtent(series, column, range) {
|
|
15
|
+
const col = readNumericColumn(series, column);
|
|
16
|
+
if (!col)
|
|
17
|
+
return null;
|
|
18
|
+
let lo = 0;
|
|
19
|
+
let hi = col.length;
|
|
20
|
+
if (range) {
|
|
21
|
+
// `bisect` returns the LOWER-BOUND insertion index (first key ≥ the
|
|
22
|
+
// probe), so [bisect(from), bisect(to + 1)) covers exactly the rows with
|
|
23
|
+
// from ≤ t ≤ to. NOT `bisect(to) + 1`: on an unaligned `to` (every
|
|
24
|
+
// pan/zoom window) that lands on the first sample PAST the window and +1
|
|
25
|
+
// would include it — an off-screen spike then poisons the extent (PR #132
|
|
26
|
+
// review, MEDIUM). Keys are epoch-ms integers, so +1 is the exact
|
|
27
|
+
// exclusive bound for an inclusive `to`.
|
|
28
|
+
const s = series;
|
|
29
|
+
lo = Math.max(0, s.bisect(range[0]));
|
|
30
|
+
hi = Math.min(col.length, s.bisect(range[1] + 1));
|
|
31
|
+
}
|
|
32
|
+
let min = Infinity;
|
|
33
|
+
let max = -Infinity;
|
|
34
|
+
for (let i = lo; i < hi; i += 1) {
|
|
35
|
+
const v = col.read(i);
|
|
36
|
+
if (v == null || !Number.isFinite(v))
|
|
37
|
+
continue;
|
|
38
|
+
if (v < min)
|
|
39
|
+
min = v;
|
|
40
|
+
if (v > max)
|
|
41
|
+
max = v;
|
|
42
|
+
}
|
|
43
|
+
return min <= max ? { min, max } : null;
|
|
44
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { TimeSeries } from 'pond-ts';
|
|
2
|
+
import { type BarInterval, type Instrument } from './types.js';
|
|
3
|
+
export interface PriceSeriesOptions {
|
|
4
|
+
/** Number of bars to generate. */
|
|
5
|
+
bars?: number;
|
|
6
|
+
/** Bar interval (spacing). Default daily. */
|
|
7
|
+
interval?: BarInterval;
|
|
8
|
+
/** Timestamp (ms) of the LAST bar; earlier bars step back by the interval.
|
|
9
|
+
* Defaults to a fixed epoch so series are fully deterministic (no clock). */
|
|
10
|
+
endMs?: number;
|
|
11
|
+
/** Opening price of the first bar. */
|
|
12
|
+
startPrice?: number;
|
|
13
|
+
/** Per-bar return volatility (std-dev of the log return). Default 2%. */
|
|
14
|
+
volatility?: number;
|
|
15
|
+
/** Per-bar drift (mean log return). Default slight positive. */
|
|
16
|
+
drift?: number;
|
|
17
|
+
/** PRNG seed. Same seed ⇒ identical series. Defaults from the symbol. */
|
|
18
|
+
seed?: number;
|
|
19
|
+
}
|
|
20
|
+
/** The schema of every Tidal price series — `time`-keyed OHLCV. Shared by the
|
|
21
|
+
* fixture and the HTTP data source so both produce identically-shaped series
|
|
22
|
+
* the chart layer can consume without branching. */
|
|
23
|
+
export declare const PRICE_SCHEMA: readonly [{
|
|
24
|
+
readonly name: "time";
|
|
25
|
+
readonly kind: "time";
|
|
26
|
+
}, {
|
|
27
|
+
readonly name: "open";
|
|
28
|
+
readonly kind: "number";
|
|
29
|
+
}, {
|
|
30
|
+
readonly name: "high";
|
|
31
|
+
readonly kind: "number";
|
|
32
|
+
}, {
|
|
33
|
+
readonly name: "low";
|
|
34
|
+
readonly kind: "number";
|
|
35
|
+
}, {
|
|
36
|
+
readonly name: "close";
|
|
37
|
+
readonly kind: "number";
|
|
38
|
+
}, {
|
|
39
|
+
readonly name: "volume";
|
|
40
|
+
readonly kind: "number";
|
|
41
|
+
}];
|
|
42
|
+
/** A row of a price series in column order: `[time, open, high, low, close,
|
|
43
|
+
* volume]`. The wire format the data layer normalizes into. */
|
|
44
|
+
export type PriceRow = [number, number, number, number, number, number];
|
|
45
|
+
/** A Tidal price series — a `time`-keyed OHLCV pond `TimeSeries`. The single
|
|
46
|
+
* carrier type the data layer returns and the chart layer renders. */
|
|
47
|
+
export type PriceSeries = TimeSeries<typeof PRICE_SCHEMA>;
|
|
48
|
+
/** Build a {@link PriceSeries} from raw OHLCV rows. The one place the price
|
|
49
|
+
* `TimeSeries` is constructed — fixture, HTTP source, and the real ticker-history
|
|
50
|
+
* adapter all funnel through here. Uses the **columnar** ingress (gap-tolerant,
|
|
51
|
+
* `sort:true`) so a non-finite cell reads as a gap rather than being rejected —
|
|
52
|
+
* real data can carry the occasional missing OHLCV cell. */
|
|
53
|
+
export declare function buildPriceSeries(name: string, rows: readonly PriceRow[]): PriceSeries;
|
|
54
|
+
/**
|
|
55
|
+
* Generate a deterministic OHLCV price series for an instrument as a pond
|
|
56
|
+
* `TimeSeries` (schema: `time`, `open`, `high`, `low`, `close`, `volume`).
|
|
57
|
+
* Close-to-close follows a seeded geometric random walk; each bar's high/low
|
|
58
|
+
* bracket its open/close with a little intrabar noise, and volume scales with
|
|
59
|
+
* the bar's range.
|
|
60
|
+
*/
|
|
61
|
+
export declare function generatePriceSeries(instrument: Instrument, options?: PriceSeriesOptions): PriceSeries;
|
|
62
|
+
/** A small demo universe — enough to populate the instrument switcher and the
|
|
63
|
+
* dashboard before the real data API is wired. */
|
|
64
|
+
export declare const DEMO_INSTRUMENTS: Instrument[];
|
package/dist/fixture.js
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { TimeSeries } from 'pond-ts';
|
|
2
|
+
import { BAR_INTERVAL_MS } from './types.js';
|
|
3
|
+
/**
|
|
4
|
+
* Deterministic price fixtures. Until the real data API lands (Tidal pulls bars
|
|
5
|
+
* over HTTP — see `@tidal/app`), the app charts synthetic OHLCV generated by a
|
|
6
|
+
* **seeded** random walk so the same `(symbol, seed)` always yields the same
|
|
7
|
+
* series. That keeps stories, tests, and the dev app showing stable data, and
|
|
8
|
+
* gives the chart layer something realistic to render. Returns a pond
|
|
9
|
+
* `TimeSeries` — the same carrier the HTTP data source will hand back, so the
|
|
10
|
+
* UI never knows whether prices are real or generated.
|
|
11
|
+
*/
|
|
12
|
+
/** mulberry32 — a tiny, fast, seedable PRNG. Deterministic per seed so fixtures
|
|
13
|
+
* are reproducible (real randomness would make tests flaky and stories drift). */
|
|
14
|
+
function mulberry32(seed) {
|
|
15
|
+
let a = seed >>> 0;
|
|
16
|
+
return () => {
|
|
17
|
+
a |= 0;
|
|
18
|
+
a = (a + 0x6d2b79f5) | 0;
|
|
19
|
+
let t = Math.imul(a ^ (a >>> 15), 1 | a);
|
|
20
|
+
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
|
21
|
+
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
/** A standard-normal sample (Box–Muller) from a uniform generator — daily
|
|
25
|
+
* returns are roughly Gaussian, so the walk reads like a real price path. */
|
|
26
|
+
function gaussian(rng) {
|
|
27
|
+
let u = 0;
|
|
28
|
+
let v = 0;
|
|
29
|
+
while (u === 0)
|
|
30
|
+
u = rng();
|
|
31
|
+
while (v === 0)
|
|
32
|
+
v = rng();
|
|
33
|
+
return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v);
|
|
34
|
+
}
|
|
35
|
+
/** A stable seed derived from a symbol, so `AAPL` always looks like `AAPL`
|
|
36
|
+
* without the caller tracking seeds. */
|
|
37
|
+
function symbolSeed(symbol) {
|
|
38
|
+
let h = 2166136261;
|
|
39
|
+
for (let i = 0; i < symbol.length; i++) {
|
|
40
|
+
h ^= symbol.charCodeAt(i);
|
|
41
|
+
h = Math.imul(h, 16777619);
|
|
42
|
+
}
|
|
43
|
+
return h >>> 0;
|
|
44
|
+
}
|
|
45
|
+
/** A fixed reference epoch (2024-01-01T00:00:00Z) so generated series don't
|
|
46
|
+
* depend on the wall clock — reproducible across machines and CI. */
|
|
47
|
+
const REFERENCE_EPOCH_MS = 1_704_067_200_000;
|
|
48
|
+
/** The schema of every Tidal price series — `time`-keyed OHLCV. Shared by the
|
|
49
|
+
* fixture and the HTTP data source so both produce identically-shaped series
|
|
50
|
+
* the chart layer can consume without branching. */
|
|
51
|
+
export const PRICE_SCHEMA = [
|
|
52
|
+
{ name: 'time', kind: 'time' },
|
|
53
|
+
{ name: 'open', kind: 'number' },
|
|
54
|
+
{ name: 'high', kind: 'number' },
|
|
55
|
+
{ name: 'low', kind: 'number' },
|
|
56
|
+
{ name: 'close', kind: 'number' },
|
|
57
|
+
{ name: 'volume', kind: 'number' },
|
|
58
|
+
];
|
|
59
|
+
/** Build a {@link PriceSeries} from raw OHLCV rows. The one place the price
|
|
60
|
+
* `TimeSeries` is constructed — fixture, HTTP source, and the real ticker-history
|
|
61
|
+
* adapter all funnel through here. Uses the **columnar** ingress (gap-tolerant,
|
|
62
|
+
* `sort:true`) so a non-finite cell reads as a gap rather than being rejected —
|
|
63
|
+
* real data can carry the occasional missing OHLCV cell. */
|
|
64
|
+
export function buildPriceSeries(name, rows) {
|
|
65
|
+
return TimeSeries.fromColumns({
|
|
66
|
+
name,
|
|
67
|
+
schema: PRICE_SCHEMA,
|
|
68
|
+
columns: {
|
|
69
|
+
time: rows.map((r) => r[0]),
|
|
70
|
+
open: rows.map((r) => r[1]),
|
|
71
|
+
high: rows.map((r) => r[2]),
|
|
72
|
+
low: rows.map((r) => r[3]),
|
|
73
|
+
close: rows.map((r) => r[4]),
|
|
74
|
+
volume: rows.map((r) => r[5]),
|
|
75
|
+
},
|
|
76
|
+
sort: true,
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Generate a deterministic OHLCV price series for an instrument as a pond
|
|
81
|
+
* `TimeSeries` (schema: `time`, `open`, `high`, `low`, `close`, `volume`).
|
|
82
|
+
* Close-to-close follows a seeded geometric random walk; each bar's high/low
|
|
83
|
+
* bracket its open/close with a little intrabar noise, and volume scales with
|
|
84
|
+
* the bar's range.
|
|
85
|
+
*/
|
|
86
|
+
export function generatePriceSeries(instrument, options = {}) {
|
|
87
|
+
const { bars = 180, interval = '1d', endMs = REFERENCE_EPOCH_MS, startPrice = instrument.kind === 'crypto' ? 30000 : instrument.kind === 'fx' ? 1.1 : 150, volatility = instrument.kind === 'crypto' ? 0.04 : 0.02, drift = 0.0004, seed = symbolSeed(instrument.symbol), } = options;
|
|
88
|
+
const stepMs = BAR_INTERVAL_MS[interval];
|
|
89
|
+
const rng = mulberry32(seed);
|
|
90
|
+
const rows = [];
|
|
91
|
+
let close = startPrice;
|
|
92
|
+
for (let i = bars - 1; i >= 0; i--) {
|
|
93
|
+
const time = endMs - i * stepMs;
|
|
94
|
+
const open = close;
|
|
95
|
+
const ret = drift + volatility * gaussian(rng);
|
|
96
|
+
close = Math.max(0.01, open * Math.exp(ret));
|
|
97
|
+
const hi = Math.max(open, close) * (1 + Math.abs(volatility * gaussian(rng)) * 0.5);
|
|
98
|
+
const lo = Math.min(open, close) * (1 - Math.abs(volatility * gaussian(rng)) * 0.5);
|
|
99
|
+
const range = hi - lo;
|
|
100
|
+
const volume = Math.round((1 + range / open) * 1_000_000 * (0.5 + rng()));
|
|
101
|
+
rows.push([time, round2(open), round2(hi), round2(lo), round2(close), volume]);
|
|
102
|
+
}
|
|
103
|
+
return buildPriceSeries(instrument.symbol, rows);
|
|
104
|
+
}
|
|
105
|
+
function round2(n) {
|
|
106
|
+
return Math.round(n * 100) / 100;
|
|
107
|
+
}
|
|
108
|
+
/** A small demo universe — enough to populate the instrument switcher and the
|
|
109
|
+
* dashboard before the real data API is wired. */
|
|
110
|
+
export const DEMO_INSTRUMENTS = [
|
|
111
|
+
{ symbol: 'AAPL', name: 'Apple Inc.', kind: 'equity' },
|
|
112
|
+
{ symbol: 'MSFT', name: 'Microsoft Corp.', kind: 'equity' },
|
|
113
|
+
{ symbol: 'BTC-USD', name: 'Bitcoin / US Dollar', kind: 'crypto' },
|
|
114
|
+
{ symbol: 'EUR-USD', name: 'Euro / US Dollar', kind: 'fx' },
|
|
115
|
+
{ symbol: 'SPX', name: 'S&P 500 Index', kind: 'index' },
|
|
116
|
+
];
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export { BAR_INTERVAL_MS, type Instrument, type InstrumentKind, type BarInterval, } from './types.js';
|
|
2
|
+
export { generatePriceSeries, buildPriceSeries, DEMO_INSTRUMENTS, PRICE_SCHEMA, type PriceSeriesOptions, type PriceSeries, type PriceRow, } from './fixture.js';
|
|
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
|
+
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';
|
|
6
|
+
export { joinUnderPrefix } from './join.js';
|
|
7
|
+
export { columnExtent } from './extent.js';
|
|
8
|
+
export { snapshotToTimeSeries, appendToRows, type PondSnapshot, type PondAppend, type PondValue, type WireColumnSpec, } from './columnar.js';
|
|
9
|
+
export { exactSessionSegments, inferBarMs, sessionOpenLine, sessionSegments, shiftKeys, type Segment, type SessionSegmentOptions, } from './sessions.js';
|
|
10
|
+
export { monthlyExpirations, thirdFriday } from './expirations.js';
|
|
11
|
+
export { holdVolAcrossGrid } from './regrid.js';
|
|
12
|
+
export { ADOPTED_STUDIES, adoptable, isBandShape, outputMark, studyNeedsColumns, } from './studyCatalog.js';
|
|
13
|
+
export { DATA_TIME_ZONE, LOCAL_ZONE, TIME_ZONE_CHOICES, resolveTimeZone, timeZoneLabel, type TimeZoneChoice, } from './timeZone.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export { BAR_INTERVAL_MS, } from './types.js';
|
|
2
|
+
export { generatePriceSeries, buildPriceSeries, DEMO_INSTRUMENTS, PRICE_SCHEMA, } from './fixture.js';
|
|
3
|
+
export { generateVolSeries, buildVolSeries, VOL_SCHEMA, VOL_TENORS, DEFAULT_VOL_TENOR, impliedCol, hvCol, rvCol, rvCenCol, skewCol, } from './vol.js';
|
|
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';
|
|
6
|
+
export { joinUnderPrefix } from './join.js';
|
|
7
|
+
export { columnExtent } from './extent.js';
|
|
8
|
+
export { snapshotToTimeSeries, appendToRows, } from './columnar.js';
|
|
9
|
+
export { exactSessionSegments, inferBarMs, sessionOpenLine, sessionSegments, shiftKeys, } from './sessions.js';
|
|
10
|
+
export { monthlyExpirations, thirdFriday } from './expirations.js';
|
|
11
|
+
export { holdVolAcrossGrid } from './regrid.js';
|
|
12
|
+
// The corpus adoption (TDL-STUDYCAT). `ADOPTED_STUDIES` is exported so the
|
|
13
|
+
// count is assertable and a widening of `adoptable` is a visible edit.
|
|
14
|
+
export { ADOPTED_STUDIES, adoptable, isBandShape, outputMark, studyNeedsColumns, } from './studyCatalog.js';
|
|
15
|
+
// The two zones: what the data IS, and what the axis reads in (TDL-TZAXIS).
|
|
16
|
+
export { DATA_TIME_ZONE, LOCAL_ZONE, TIME_ZONE_CHOICES, resolveTimeZone, timeZoneLabel, } from './timeZone.js';
|
package/dist/join.d.ts
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { SeriesSchema, TimeSeries } from 'pond-ts';
|
|
2
|
+
/** The erased-schema series the join reads/writes (like derive.ts). */
|
|
3
|
+
type JoinedSeries = TimeSeries<SeriesSchema>;
|
|
4
|
+
/**
|
|
5
|
+
* Join `other`'s value columns onto `primary` with every one renamed under
|
|
6
|
+
* `prefix` (default {@link COMPARE_PREFIX}) — a **left exact-key join** whose
|
|
7
|
+
* output keeps the primary's column names untouched. This is what carries the
|
|
8
|
+
* compare ticker's columns onto the primary series so a role-bound pair leg
|
|
9
|
+
* (`cmp_iv21`) can fold (TDL-PAIR stage 1), and it is the consumer-side
|
|
10
|
+
* stand-in for per-input source qualification (PND-PROCJOIN).
|
|
11
|
+
*
|
|
12
|
+
* Deliberately rename-then-join, NOT pond's `join(…, { onConflict: 'prefix' })`:
|
|
13
|
+
* pond inserts an implicit `_` separator (`prefixes: ['', 'cmp_']` yields
|
|
14
|
+
* `_iv21` / `cmp__iv21`), which destroys the primary's names — an empty prefix
|
|
15
|
+
* cannot mean "keep the name" (CHARTS_FRICTION F-charts-14).
|
|
16
|
+
*
|
|
17
|
+
* Exact-key caveat: rows join on identical timestamps. Aligned daily grids
|
|
18
|
+
* (both a fixture and a daily feed) match. An intraday feed does NOT — two
|
|
19
|
+
* symbols don't print in the same minutes — and every unmatched primary row
|
|
20
|
+
* leaves its `cmp_*` columns null, which a derive then propagates.
|
|
21
|
+
*
|
|
22
|
+
* The fix is a pre-step, not a different join: `fill(…, { maxGap })` to cap how
|
|
23
|
+
* far a gap may be carried (all-or-nothing, so a real outage stays a gap), then
|
|
24
|
+
* `align(Sequence.every(grain), { method: 'hold' })` on both series so a point
|
|
25
|
+
* exists on every boundary and this join matches by construction. `'hold'`
|
|
26
|
+
* carries the last print; `'linear'` would invent trades between them. Note
|
|
27
|
+
* `align` CREATES ROWS, so a series aligned for rendering is not automatically
|
|
28
|
+
* safe as a derive input — see `TDL-CMPGAP` and F-charts-19.
|
|
29
|
+
*/
|
|
30
|
+
export declare function joinUnderPrefix(primary: JoinedSeries, other: JoinedSeries, prefix?: string): JoinedSeries;
|
|
31
|
+
export {};
|
package/dist/join.js
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { COMPARE_PREFIX } from './derive.js';
|
|
2
|
+
/**
|
|
3
|
+
* Join `other`'s value columns onto `primary` with every one renamed under
|
|
4
|
+
* `prefix` (default {@link COMPARE_PREFIX}) — a **left exact-key join** whose
|
|
5
|
+
* output keeps the primary's column names untouched. This is what carries the
|
|
6
|
+
* compare ticker's columns onto the primary series so a role-bound pair leg
|
|
7
|
+
* (`cmp_iv21`) can fold (TDL-PAIR stage 1), and it is the consumer-side
|
|
8
|
+
* stand-in for per-input source qualification (PND-PROCJOIN).
|
|
9
|
+
*
|
|
10
|
+
* Deliberately rename-then-join, NOT pond's `join(…, { onConflict: 'prefix' })`:
|
|
11
|
+
* pond inserts an implicit `_` separator (`prefixes: ['', 'cmp_']` yields
|
|
12
|
+
* `_iv21` / `cmp__iv21`), which destroys the primary's names — an empty prefix
|
|
13
|
+
* cannot mean "keep the name" (CHARTS_FRICTION F-charts-14).
|
|
14
|
+
*
|
|
15
|
+
* Exact-key caveat: rows join on identical timestamps. Aligned daily grids
|
|
16
|
+
* (both a fixture and a daily feed) match. An intraday feed does NOT — two
|
|
17
|
+
* symbols don't print in the same minutes — and every unmatched primary row
|
|
18
|
+
* leaves its `cmp_*` columns null, which a derive then propagates.
|
|
19
|
+
*
|
|
20
|
+
* The fix is a pre-step, not a different join: `fill(…, { maxGap })` to cap how
|
|
21
|
+
* far a gap may be carried (all-or-nothing, so a real outage stays a gap), then
|
|
22
|
+
* `align(Sequence.every(grain), { method: 'hold' })` on both series so a point
|
|
23
|
+
* exists on every boundary and this join matches by construction. `'hold'`
|
|
24
|
+
* carries the last print; `'linear'` would invent trades between them. Note
|
|
25
|
+
* `align` CREATES ROWS, so a series aligned for rendering is not automatically
|
|
26
|
+
* safe as a derive input — see `TDL-CMPGAP` and F-charts-19.
|
|
27
|
+
*/
|
|
28
|
+
export function joinUnderPrefix(primary, other, prefix = COMPARE_PREFIX) {
|
|
29
|
+
// Structural, like readNumericColumn: the join runs in the erased schema
|
|
30
|
+
// while pond's rename/join are schema-narrowed.
|
|
31
|
+
const o = other;
|
|
32
|
+
const mapping = Object.fromEntries(o.schema.filter((col) => col.kind !== 'time').map((col) => [col.name, `${prefix}${col.name}`]));
|
|
33
|
+
const renamed = o.rename(mapping);
|
|
34
|
+
const p = primary;
|
|
35
|
+
return p.join(renamed, { type: 'left' });
|
|
36
|
+
}
|
package/dist/regrid.d.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { type VolSeries } from './vol.js';
|
|
2
|
+
/**
|
|
3
|
+
* Re-key `coarse` onto `times`, holding each source row across every target
|
|
4
|
+
* timestamp that falls on its day.
|
|
5
|
+
*
|
|
6
|
+
* `times` must be ascending (the price series' own keys). A target day the coarse
|
|
7
|
+
* series has no row for yields `NaN` across that day, which the chart reads as a
|
|
8
|
+
* gap rather than as zero — correct, since "no vol published for this session" is
|
|
9
|
+
* not "vol was nothing".
|
|
10
|
+
*
|
|
11
|
+
* Returns the coarse series unchanged when there is **nothing to hold** — an empty
|
|
12
|
+
* target grid, or an empty source.
|
|
13
|
+
*
|
|
14
|
+
* It does NOT short-circuit a source that is already as dense as the target; an
|
|
15
|
+
* earlier version of this sentence claimed it did, and did not. Today that path is
|
|
16
|
+
* unreachable (`volGrains` is `['1d']` everywhere, so the fallback grain is always
|
|
17
|
+
* coarser), but `resolveGrain` does not guarantee it: a source declaring
|
|
18
|
+
* `volGrains: ['30m']` answers a `1d` request with `'30m'` via its
|
|
19
|
+
* last-resort branch, and this would then re-key a 30-minute series onto a daily
|
|
20
|
+
* grid, silently keeping each day's LAST intraday value.
|
|
21
|
+
*/
|
|
22
|
+
export declare function holdVolAcrossGrid(coarse: VolSeries, times: readonly number[], name?: string): VolSeries;
|