Add versioned streaming indicators and share chart calculations
This commit is contained in:
parent
7827220b9b
commit
cca5d71e6e
20 changed files with 1470 additions and 331 deletions
|
|
@ -27,6 +27,12 @@ const risk = returnStatistics(returns);
|
|||
helpers shared with the supported TypeScript strategies. SMA output index 0 belongs
|
||||
to source index `period - 1`; incomplete batch warm-up is `[]`, scalar warm-up is
|
||||
`undefined`. No future data is read. Windows/offsets must be valid integers.
|
||||
Versioned EMA, Wilder RSI and Wilder ATR now have aligned batch output and O(1)
|
||||
streaming implementations with validated JSON restart state. Explicit seed/flat/
|
||||
first-range policies prevent accidental numerical substitutions. Population bands,
|
||||
MACD and stochastic are shared batch compositions used by chart adapters. See the
|
||||
[indicator contracts](docs/indicators.md) for exact alignment, numerical changes,
|
||||
native differences, snapshot guarantees and strategy-version compatibility.
|
||||
- `./market-data`: restored generic OHLCV extraction, returns, SMA, HLC/3 typical price,
|
||||
true range, cumulative VWAP, filtering, grouping and timestamp conversion. SMA and
|
||||
returns delegate to the same core functions. VWAP is `null` until positive cumulative
|
||||
|
|
|
|||
120
libs/calculations/docs/indicators.md
Normal file
120
libs/calculations/docs/indicators.md
Normal file
|
|
@ -0,0 +1,120 @@
|
|||
# Versioned indicator contracts
|
||||
|
||||
These are pure observation-based calculations. They do not read the clock, generate
|
||||
randomness, obtain prices, submit orders or persist state. Use one stream instance per
|
||||
instrument/series, and supply admitted observations in order. The caller owns instrument
|
||||
identity, timestamp ordering, gap policies and timeframe selection; periods count input
|
||||
observations, not elapsed minutes. Missing bars are never invented here.
|
||||
|
||||
## Alignment, initialization and variants
|
||||
|
||||
Batch output is `{ contract, startIndex, values }`: value `i` belongs to input position
|
||||
`startIndex + i`. No leading zero/NaN padding is generated. An incomplete batch has an
|
||||
empty values array but still reports its intended start index. Existing `sma()` retains
|
||||
its earlier array return type; its first output belongs to input `period - 1`.
|
||||
|
||||
| Calculation | Initialization and recurrence | First source index |
|
||||
| ---------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | ------------------ |
|
||||
| `ema`, `seed: 'sma'` (default), `ema/v1` | Seed from the first period's mean, then weight each new observation by `2/(period+1)` | `period - 1` |
|
||||
| `ema`, `seed: 'first'`, `ema/v1` | Seed immediately from the first observation; same subsequent weights | `0` |
|
||||
| `rsi`, `rsi-wilder/v1` | Seed gain/loss averages from the first `period` changes, then apply Wilder smoothing, consuming each change once | `period` |
|
||||
| `atr`, `firstRange: 'previous-close'` (default), `atr-wilder/v1` | Skip the first bar's range; seed from the next `period` true ranges, then apply Wilder smoothing | `period` |
|
||||
| `atr`, `firstRange: 'high-low'`, `atr-wilder/v1` | Include the first bar's high-low range in the seed; same subsequent smoothing | `period - 1` |
|
||||
|
||||
RSI with gains but no losses is 100; losses but no gains is 0. If **both** averages are
|
||||
zero, `flatValue` explicitly chooses 0, 50 or 100; the new core defaults to neutral 50.
|
||||
That flat policy is an application convention, not a claim that all RSI libraries agree.
|
||||
HLC bars must be finite and satisfy `low <= close <= high`. ATR is in input price units.
|
||||
|
||||
Periods must be positive safe integers below `Number.MAX_SAFE_INTEGER`. Non-finite
|
||||
inputs, invalid options and unrepresentable accumulators/results throw. Sparse arrays
|
||||
are not skipped. No missing-price substitution or intermediate decimal rounding occurs.
|
||||
|
||||
The initializer distinction is corroborated by the pinned
|
||||
[TA-Lib EMA implementation](https://github.com/TA-Lib/ta-lib/blob/v0.6.4/src/ta_func/ta_EMA.c).
|
||||
Wilder's seed/recurrence and directional zero handling are described by
|
||||
[StockCharts RSI](https://chartschool.stockcharts.com/table-of-contents/technical-indicators-and-overlays/technical-indicators/relative-strength-index-rsi).
|
||||
The true-range definition and high-low first-bar variant are described by
|
||||
[StockCharts ATR](https://chartschool.stockcharts.com/table-of-contents/technical-indicators-and-overlays/technical-indicators/average-true-range-atr).
|
||||
Our previous-close variant also matches this repository's native ATR. These are formula
|
||||
references, not copied implementations or claims of identical defaults across libraries.
|
||||
|
||||
## Streaming and restart state
|
||||
|
||||
```ts
|
||||
import { AtrIndicator, EmaIndicator, RsiIndicator } from '@stock-bot/calculations/indicators';
|
||||
|
||||
const stream = new RsiIndicator(14, { flatValue: 50 });
|
||||
stream.update(100); // null until the first 14 changes are available
|
||||
const persisted = JSON.parse(JSON.stringify(stream.snapshot()));
|
||||
|
||||
const resumed = new RsiIndicator(14, { flatValue: 50 });
|
||||
resumed.restore(persisted); // validates contract, phase, counters and configuration
|
||||
const value = resumed.update(101);
|
||||
```
|
||||
|
||||
`update()` and `current()` return `number | null`; only warm-up returns null. A legitimate
|
||||
zero is never treated as missing. All three streams use constant-size, finite JSON state
|
||||
and O(1) work/memory per observation. They do not retain the input history. Each snapshot
|
||||
includes its versioned contract string, period, variant settings and observation count:
|
||||
|
||||
- EMA: seed accumulator before readiness, current value afterward.
|
||||
- RSI: previous observation and gain/loss accumulators (sums during seed, averages after).
|
||||
- ATR: previous close, seed accumulator and current smoothed range.
|
||||
|
||||
Snapshots are detached copies. Invalid updates, arithmetic failures and failed restores
|
||||
leave prior state intact. Reset retains configuration and clears all observed history.
|
||||
Unknown fields/contracts, invalid numbers/counters, incompatible configuration and
|
||||
inconsistent warm-up phases are rejected. Counters cannot exceed safe integer precision.
|
||||
|
||||
`fromSnapshot()` constructs a new stream using the snapshot's settings. Use an existing
|
||||
configured instance's `restore()` when settings must match an independently loaded strategy
|
||||
configuration. Structural validation does not establish provenance or prove that the
|
||||
snapshot belongs to a particular instrument. Persist a strategy's cursor, indicator
|
||||
snapshot and financial intents atomically through the existing execution recovery port;
|
||||
do not use this library as a second persistence/accounting authority.
|
||||
|
||||
## Derived chart math
|
||||
|
||||
`bollingerBands` uses population deviation around an unrounded SMA. `macd` composes the
|
||||
explicit EMA seed variant for fast, slow and signal series, returning separate aligned
|
||||
series for MACD, signal and histogram. No timestamp searches are needed. `stochastic`
|
||||
uses SMA smoothing for K/D and defines a flat high/low window as neutral 50, not NaN.
|
||||
These are batch compositions, not new streaming/checkpoint APIs. EMA/RSI/ATR and MACD
|
||||
batch work are linear; population bands and stochastic still scan their trailing windows.
|
||||
|
||||
Chart adapters now only map source timestamps, select variants and round display values.
|
||||
The display contract is `chart-indicators/v2`: chart RSI no longer reuses the seed's final
|
||||
change, uses exact 100 for gain-only data and neutral 50 for flat data; MACD/Bollinger/
|
||||
stochastic no longer feed rounded intermediate chart values back into their calculations.
|
||||
Zero/absent cumulative volume emits no VWAP chart point. Invalid inputs fail explicitly.
|
||||
Those chart numbers can change; no saved trading/strategy contract is implicitly changed.
|
||||
|
||||
## Existing strategies and native compatibility
|
||||
|
||||
`mean-reversion/v2` deliberately retains rolling **simple-average** RSI, reverse summation
|
||||
order, flat=100 and its existing incomplete-warm-up fallback. Its arithmetic is extracted
|
||||
to `trailingSimpleRsi`, not replaced with Wilder RSI. Checkpoint versions and serialized
|
||||
strategy state remain unchanged. Experimental ML and the native `TechnicalAnalysis`
|
||||
adapter also retain their previous contracts; neither is silently switched to this core.
|
||||
|
||||
Native first-seeded EMA, previous-close ATR, first-seeded MACD and compatible mixed-move
|
||||
Wilder RSI paths are checked against the real bindings. Historical native **batch** RSI
|
||||
uses a ratio of 100 for zero losses and then transforms it again, yielding roughly 99.01,
|
||||
while its incremental path uses 100. That difference is pinned/documented, not erased by
|
||||
relabelling a migration. Adopting corrected Wilder RSI in an existing saved/native/ML
|
||||
strategy needs an explicit new strategy/feature contract and deliberate migration.
|
||||
|
||||
## Verification
|
||||
|
||||
- Hand-checked rational EMA/RSI/ATR fixtures are in `test/fixtures/indicators.json`;
|
||||
expected constants are independent of the implementation under test.
|
||||
- Tests cover every JSON restart boundary through warm-up and steady state, reset and
|
||||
detachment, batch/stream equality, prefix invariance (no lookahead), malformed snapshots,
|
||||
invalid inputs, overflow atomicity and bounded state after long histories.
|
||||
- Integration tests cover real native variants, exact mean-reversion-v2 arithmetic,
|
||||
chart offsets/gaps, corrected RSI initialization and display-only rounding.
|
||||
- The browser-bundle check prevents native/server dependency leaks into chart adapters.
|
||||
Calculation lint rules forbid global I/O, wall-clock input and unseeded randomness.
|
||||
|
||||
Run `bun run test:calculations`, `bun run test:integration`, and `bun run check`.
|
||||
|
|
@ -13,6 +13,32 @@ export {
|
|||
sma,
|
||||
trailingMean,
|
||||
trailingPopulationDeviation,
|
||||
ema,
|
||||
EmaIndicator,
|
||||
EMA_CONTRACT,
|
||||
rsi,
|
||||
RsiIndicator,
|
||||
RSI_CONTRACT,
|
||||
atr,
|
||||
AtrIndicator,
|
||||
ATR_CONTRACT,
|
||||
trailingSimpleRsi,
|
||||
bollingerBands,
|
||||
macd,
|
||||
stochastic,
|
||||
} from './indicators';
|
||||
export type {
|
||||
IndicatorSeries,
|
||||
HlcBar,
|
||||
EmaSnapshot,
|
||||
RsiSnapshot,
|
||||
AtrSnapshot,
|
||||
EmaOptions,
|
||||
EmaSeed,
|
||||
RsiOptions,
|
||||
FlatRsi,
|
||||
AtrOptions,
|
||||
AtrFirstRange,
|
||||
} from './indicators';
|
||||
export {
|
||||
calculateLogReturns,
|
||||
|
|
|
|||
149
libs/calculations/src/indicators/atr.ts
Normal file
149
libs/calculations/src/indicators/atr.ts
Normal file
|
|
@ -0,0 +1,149 @@
|
|||
import {
|
||||
collect,
|
||||
configuration,
|
||||
count,
|
||||
finite,
|
||||
nonnegative,
|
||||
optionalNumber,
|
||||
period,
|
||||
snapshot,
|
||||
validateBar,
|
||||
type HlcBar,
|
||||
type IndicatorSeries,
|
||||
} from './contracts';
|
||||
|
||||
export const ATR_CONTRACT = 'atr-wilder/v1';
|
||||
export type AtrFirstRange = 'previous-close' | 'high-low';
|
||||
export interface AtrOptions {
|
||||
firstRange?: AtrFirstRange;
|
||||
}
|
||||
export interface AtrSnapshot {
|
||||
contract: typeof ATR_CONTRACT;
|
||||
period: number;
|
||||
firstRange: AtrFirstRange;
|
||||
count: number;
|
||||
previousClose: number | null;
|
||||
seedSum: number;
|
||||
value: number | null;
|
||||
}
|
||||
|
||||
function firstRange(value: unknown): AtrFirstRange {
|
||||
if (value !== 'previous-close' && value !== 'high-low') {
|
||||
throw new Error('ATR first range must be previous-close or high-low');
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function parse(input: unknown): AtrSnapshot {
|
||||
const value = snapshot(input, [
|
||||
'contract',
|
||||
'period',
|
||||
'firstRange',
|
||||
'count',
|
||||
'previousClose',
|
||||
'seedSum',
|
||||
'value',
|
||||
]);
|
||||
if (value.contract !== ATR_CONTRACT) {
|
||||
throw new Error('Unsupported ATR snapshot contract');
|
||||
}
|
||||
const state: AtrSnapshot = {
|
||||
contract: ATR_CONTRACT,
|
||||
period: period(value.period),
|
||||
firstRange: firstRange(value.firstRange),
|
||||
count: count(value.count),
|
||||
previousClose: optionalNumber(value.previousClose),
|
||||
seedSum: nonnegative(value.seedSum),
|
||||
value: optionalNumber(value.value),
|
||||
};
|
||||
const ranges = state.count - (state.firstRange === 'previous-close' ? 1 : 0);
|
||||
const ready = ranges >= state.period;
|
||||
if (
|
||||
(state.previousClose !== null) !== state.count > 0 ||
|
||||
(state.value !== null) !== ready ||
|
||||
(state.value !== null && state.value < 0) ||
|
||||
((ready || ranges <= 0) && state.seedSum !== 0)
|
||||
) {
|
||||
throw new Error('Inconsistent ATR snapshot phase');
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
/** Wilder ATR with an explicit first-bar policy; finite HLC inputs, O(1) memory. */
|
||||
export class AtrIndicator {
|
||||
private state: AtrSnapshot;
|
||||
constructor(size = 14, options: AtrOptions = {}) {
|
||||
configuration(options, ['firstRange']);
|
||||
this.state = {
|
||||
contract: ATR_CONTRACT,
|
||||
period: period(size),
|
||||
firstRange: firstRange(
|
||||
options.firstRange === undefined ? 'previous-close' : options.firstRange
|
||||
),
|
||||
count: 0,
|
||||
previousClose: null,
|
||||
seedSum: 0,
|
||||
value: null,
|
||||
};
|
||||
}
|
||||
update(bar: HlcBar): number | null {
|
||||
validateBar(bar);
|
||||
const prior = this.state;
|
||||
const next = { ...prior, count: count(prior.count + 1), previousClose: bar.close };
|
||||
if (prior.previousClose !== null || prior.firstRange === 'high-low') {
|
||||
const range = finite(
|
||||
prior.previousClose === null
|
||||
? bar.high - bar.low
|
||||
: Math.max(
|
||||
bar.high - bar.low,
|
||||
Math.abs(bar.high - prior.previousClose),
|
||||
Math.abs(bar.low - prior.previousClose)
|
||||
)
|
||||
);
|
||||
if (prior.value === null) {
|
||||
next.seedSum = nonnegative(prior.seedSum + range);
|
||||
const ranges = next.count - (prior.firstRange === 'previous-close' ? 1 : 0);
|
||||
if (ranges === prior.period) {
|
||||
next.value = nonnegative(next.seedSum / prior.period);
|
||||
next.seedSum = 0;
|
||||
}
|
||||
} else {
|
||||
next.value = nonnegative((prior.value * (prior.period - 1) + range) / prior.period);
|
||||
}
|
||||
}
|
||||
this.state = next;
|
||||
return next.value;
|
||||
}
|
||||
current(): number | null {
|
||||
return this.state.value;
|
||||
}
|
||||
snapshot(): AtrSnapshot {
|
||||
return { ...this.state };
|
||||
}
|
||||
reset(): void {
|
||||
this.state = { ...this.state, count: 0, previousClose: null, seedSum: 0, value: null };
|
||||
}
|
||||
restore(input: unknown): void {
|
||||
const next = parse(input);
|
||||
if (next.period !== this.state.period || next.firstRange !== this.state.firstRange) {
|
||||
throw new Error('ATR snapshot configuration mismatch');
|
||||
}
|
||||
this.state = next;
|
||||
}
|
||||
static fromSnapshot(input: unknown): AtrIndicator {
|
||||
const state = parse(input);
|
||||
const stream = new AtrIndicator(state.period, { firstRange: state.firstRange });
|
||||
stream.restore(state);
|
||||
return stream;
|
||||
}
|
||||
}
|
||||
|
||||
export function atr(bars: readonly HlcBar[], size = 14, options: AtrOptions = {}): IndicatorSeries {
|
||||
const stream = new AtrIndicator(size, options);
|
||||
return collect(
|
||||
bars,
|
||||
stream,
|
||||
ATR_CONTRACT,
|
||||
size - (stream.snapshot().firstRange === 'high-low' ? 1 : 0)
|
||||
);
|
||||
}
|
||||
100
libs/calculations/src/indicators/compositions.ts
Normal file
100
libs/calculations/src/indicators/compositions.ts
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
import { at } from '@stock-bot/invariants';
|
||||
import { count, finite, period, validateBar, type HlcBar, type IndicatorSeries } from './contracts';
|
||||
import { ema, type EmaOptions } from './ema';
|
||||
import { sma } from './sma';
|
||||
|
||||
/** Population bands around unrounded SMA. This is a batch composition, not streaming state. */
|
||||
export function bollingerBands(values: readonly number[], size = 20, deviations = 2) {
|
||||
period(size);
|
||||
if (finite(deviations) < 0) {
|
||||
throw new RangeError('Band deviations must be nonnegative');
|
||||
}
|
||||
const middle = sma(values, size);
|
||||
const upper: number[] = [],
|
||||
lower: number[] = [];
|
||||
for (let i = 0; i < middle.length; i++) {
|
||||
const mean = at(middle, i);
|
||||
let squared = 0;
|
||||
for (let j = i; j < i + size; j++) {
|
||||
squared = finite(squared + (at(values, j) - mean) ** 2);
|
||||
}
|
||||
const spread = finite(Math.sqrt(squared / size) * deviations);
|
||||
upper.push(finite(mean + spread));
|
||||
lower.push(finite(mean - spread));
|
||||
}
|
||||
return { contract: 'bollinger-population/v1', startIndex: size - 1, middle, upper, lower };
|
||||
}
|
||||
|
||||
/** EMA seeds are shared by both price EMAs and the signal EMA; offsets retain exact source alignment. */
|
||||
export function macd(
|
||||
values: readonly number[],
|
||||
fast = 12,
|
||||
slow = 26,
|
||||
signal = 9,
|
||||
options: EmaOptions = {}
|
||||
) {
|
||||
period(fast);
|
||||
period(slow);
|
||||
period(signal);
|
||||
if (fast >= slow) {
|
||||
throw new RangeError('MACD fast period must be below slow period');
|
||||
}
|
||||
const a = ema(values, fast, options),
|
||||
b = ema(values, slow, options);
|
||||
const startIndex = Math.max(a.startIndex, b.startIndex);
|
||||
const difference: number[] = [];
|
||||
for (let i = startIndex; i < values.length; i++) {
|
||||
difference.push(finite(at(a.values, i - a.startIndex) - at(b.values, i - b.startIndex)));
|
||||
}
|
||||
const signalSeries = ema(difference, signal, options);
|
||||
const histogram = signalSeries.values.map((value, i) =>
|
||||
finite(at(difference, signalSeries.startIndex + i) - value)
|
||||
);
|
||||
const contract = 'macd-ema/v1';
|
||||
const signalStart = count(startIndex + signalSeries.startIndex);
|
||||
return {
|
||||
macd: { contract, startIndex, values: difference } satisfies IndicatorSeries,
|
||||
signal: {
|
||||
contract,
|
||||
startIndex: signalStart,
|
||||
values: signalSeries.values,
|
||||
} satisfies IndicatorSeries,
|
||||
histogram: {
|
||||
contract,
|
||||
startIndex: signalStart,
|
||||
values: histogram,
|
||||
} satisfies IndicatorSeries,
|
||||
};
|
||||
}
|
||||
|
||||
/** SMA-smoothed stochastic. A flat high/low window is explicitly neutral (50), never NaN. */
|
||||
export function stochastic(bars: readonly HlcBar[], size = 14, smoothK = 3, smoothD = 3) {
|
||||
period(size);
|
||||
period(smoothK);
|
||||
period(smoothD);
|
||||
for (const bar of bars) {
|
||||
validateBar(bar);
|
||||
}
|
||||
const raw: number[] = [];
|
||||
for (let i = size - 1; i < bars.length; i++) {
|
||||
let low = at(bars, i).low,
|
||||
high = at(bars, i).high;
|
||||
for (let j = i - size + 1; j < i; j++) {
|
||||
low = Math.min(low, at(bars, j).low);
|
||||
high = Math.max(high, at(bars, j).high);
|
||||
}
|
||||
const range = finite(high - low);
|
||||
raw.push(range === 0 ? 50 : finite(((at(bars, i).close - low) / range) * 100));
|
||||
}
|
||||
const k = sma(raw, smoothK),
|
||||
d = sma(k, smoothD);
|
||||
const startIndex = count(size - 1 + smoothK - 1);
|
||||
return {
|
||||
k: { contract: 'stochastic-sma/v1', startIndex, values: k } satisfies IndicatorSeries,
|
||||
d: {
|
||||
contract: 'stochastic-sma/v1',
|
||||
startIndex: count(startIndex + smoothD - 1),
|
||||
values: d,
|
||||
} satisfies IndicatorSeries,
|
||||
};
|
||||
}
|
||||
95
libs/calculations/src/indicators/contracts.ts
Normal file
95
libs/calculations/src/indicators/contracts.ts
Normal file
|
|
@ -0,0 +1,95 @@
|
|||
/** No padding: values[i] belongs to source input startIndex + i. Empty warm-up stays empty. */
|
||||
export interface IndicatorSeries {
|
||||
contract: string;
|
||||
startIndex: number;
|
||||
values: number[];
|
||||
}
|
||||
|
||||
export interface HlcBar {
|
||||
high: number;
|
||||
low: number;
|
||||
close: number;
|
||||
}
|
||||
|
||||
export function finite(value: unknown): number {
|
||||
if (typeof value !== 'number' || !Number.isFinite(value)) {
|
||||
throw new RangeError('Indicator values must be finite numbers');
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
export function period(value: unknown): number {
|
||||
const result = finite(value);
|
||||
if (!Number.isSafeInteger(result) || result < 1 || result >= Number.MAX_SAFE_INTEGER) {
|
||||
throw new RangeError('Indicator period must be a positive safe integer below MAX_SAFE_INTEGER');
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function count(value: unknown): number {
|
||||
const result = finite(value);
|
||||
if (!Number.isSafeInteger(result) || result < 0) {
|
||||
throw new RangeError('Indicator count must be a nonnegative safe integer');
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function nonnegative(value: unknown): number {
|
||||
const result = finite(value);
|
||||
if (result < 0) {
|
||||
throw new RangeError('Indicator accumulator must be nonnegative');
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function optionalNumber(value: unknown): number | null {
|
||||
return value === null ? null : finite(value);
|
||||
}
|
||||
|
||||
export function snapshot(input: unknown, keys: readonly string[]): Record<string, unknown> {
|
||||
if (!input || typeof input !== 'object' || Array.isArray(input)) {
|
||||
throw new Error('Invalid indicator snapshot');
|
||||
}
|
||||
const fields = Object.keys(input);
|
||||
if (fields.length !== keys.length || fields.some(key => !keys.includes(key))) {
|
||||
throw new Error('Invalid indicator snapshot fields');
|
||||
}
|
||||
return input as Record<string, unknown>;
|
||||
}
|
||||
|
||||
export function configuration(input: unknown, keys: readonly string[]): void {
|
||||
if (
|
||||
!input ||
|
||||
typeof input !== 'object' ||
|
||||
Array.isArray(input) ||
|
||||
Object.keys(input).some(key => !keys.includes(key))
|
||||
) {
|
||||
throw new Error('Invalid indicator configuration fields');
|
||||
}
|
||||
}
|
||||
|
||||
export function collect<T>(
|
||||
inputs: readonly T[],
|
||||
stream: { update(input: T): number | null },
|
||||
contract: string,
|
||||
startIndex: number
|
||||
): IndicatorSeries {
|
||||
const values: number[] = [];
|
||||
for (const input of inputs) {
|
||||
const value = stream.update(input);
|
||||
if (value !== null) {
|
||||
values.push(value);
|
||||
}
|
||||
}
|
||||
return { contract, startIndex, values };
|
||||
}
|
||||
|
||||
export function validateBar(bar: HlcBar): void {
|
||||
const high = finite(bar.high);
|
||||
const low = finite(bar.low);
|
||||
const close = finite(bar.close);
|
||||
if (high < low || close < low || close > high) {
|
||||
throw new RangeError('Indicator bar requires low <= close <= high');
|
||||
}
|
||||
finite(high - low);
|
||||
}
|
||||
122
libs/calculations/src/indicators/ema.ts
Normal file
122
libs/calculations/src/indicators/ema.ts
Normal file
|
|
@ -0,0 +1,122 @@
|
|||
import {
|
||||
collect,
|
||||
configuration,
|
||||
count,
|
||||
finite,
|
||||
optionalNumber,
|
||||
period,
|
||||
snapshot,
|
||||
type IndicatorSeries,
|
||||
} from './contracts';
|
||||
|
||||
export const EMA_CONTRACT = 'ema/v1';
|
||||
export type EmaSeed = 'sma' | 'first';
|
||||
export interface EmaOptions {
|
||||
seed?: EmaSeed;
|
||||
}
|
||||
export interface EmaSnapshot {
|
||||
contract: typeof EMA_CONTRACT;
|
||||
period: number;
|
||||
seed: EmaSeed;
|
||||
count: number;
|
||||
value: number | null;
|
||||
seedSum: number;
|
||||
}
|
||||
|
||||
function seed(value: unknown): EmaSeed {
|
||||
if (value !== 'sma' && value !== 'first') {
|
||||
throw new Error('EMA seed must be sma or first');
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function parse(input: unknown): EmaSnapshot {
|
||||
const value = snapshot(input, ['contract', 'period', 'seed', 'count', 'value', 'seedSum']);
|
||||
if (value.contract !== EMA_CONTRACT) {
|
||||
throw new Error('Unsupported EMA snapshot contract');
|
||||
}
|
||||
const state: EmaSnapshot = {
|
||||
contract: EMA_CONTRACT,
|
||||
period: period(value.period),
|
||||
seed: seed(value.seed),
|
||||
count: count(value.count),
|
||||
value: optionalNumber(value.value),
|
||||
seedSum: finite(value.seedSum),
|
||||
};
|
||||
const ready = state.count >= (state.seed === 'first' ? 1 : state.period);
|
||||
if (
|
||||
(state.value !== null) !== ready ||
|
||||
((ready || state.count === 0 || state.seed === 'first') && state.seedSum !== 0)
|
||||
) {
|
||||
throw new Error('Inconsistent EMA snapshot phase');
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
/** O(1) memory. Rejected inputs/restores leave all prior state intact. */
|
||||
export class EmaIndicator {
|
||||
private state: EmaSnapshot;
|
||||
|
||||
constructor(size: number, options: EmaOptions = {}) {
|
||||
configuration(options, ['seed']);
|
||||
this.state = {
|
||||
contract: EMA_CONTRACT,
|
||||
period: period(size),
|
||||
seed: seed(options.seed === undefined ? 'sma' : options.seed),
|
||||
count: 0,
|
||||
value: null,
|
||||
seedSum: 0,
|
||||
};
|
||||
}
|
||||
|
||||
update(input: number): number | null {
|
||||
const value = finite(input);
|
||||
const next = { ...this.state, count: count(this.state.count + 1) };
|
||||
if (next.value !== null) {
|
||||
const alpha = 2 / (next.period + 1);
|
||||
next.value = finite(alpha * value + (1 - alpha) * next.value);
|
||||
} else if (next.seed === 'first') {
|
||||
next.value = value;
|
||||
} else {
|
||||
next.seedSum = finite(next.seedSum + value);
|
||||
if (next.count === next.period) {
|
||||
next.value = finite(next.seedSum / next.period);
|
||||
next.seedSum = 0;
|
||||
}
|
||||
}
|
||||
this.state = next;
|
||||
return next.value;
|
||||
}
|
||||
|
||||
current(): number | null {
|
||||
return this.state.value;
|
||||
}
|
||||
snapshot(): EmaSnapshot {
|
||||
return { ...this.state };
|
||||
}
|
||||
reset(): void {
|
||||
this.state = { ...this.state, count: 0, value: null, seedSum: 0 };
|
||||
}
|
||||
restore(input: unknown): void {
|
||||
const next = parse(input);
|
||||
if (next.period !== this.state.period || next.seed !== this.state.seed) {
|
||||
throw new Error('EMA snapshot configuration mismatch');
|
||||
}
|
||||
this.state = next;
|
||||
}
|
||||
static fromSnapshot(input: unknown): EmaIndicator {
|
||||
const state = parse(input);
|
||||
const stream = new EmaIndicator(state.period, { seed: state.seed });
|
||||
stream.restore(state);
|
||||
return stream;
|
||||
}
|
||||
}
|
||||
|
||||
export function ema(
|
||||
values: readonly number[],
|
||||
size: number,
|
||||
options: EmaOptions = {}
|
||||
): IndicatorSeries {
|
||||
const stream = new EmaIndicator(size, options);
|
||||
return collect(values, stream, EMA_CONTRACT, stream.snapshot().seed === 'first' ? 0 : size - 1);
|
||||
}
|
||||
|
|
@ -4,3 +4,11 @@ export {
|
|||
trailingPopulationDeviation,
|
||||
} from './window-statistics';
|
||||
export { sma } from './sma';
|
||||
export { ema, EmaIndicator, EMA_CONTRACT } from './ema';
|
||||
export type { EmaOptions, EmaSeed, EmaSnapshot } from './ema';
|
||||
export { rsi, RsiIndicator, RSI_CONTRACT, trailingSimpleRsi } from './rsi';
|
||||
export type { FlatRsi, RsiOptions, RsiSnapshot } from './rsi';
|
||||
export { atr, AtrIndicator, ATR_CONTRACT } from './atr';
|
||||
export type { AtrFirstRange, AtrOptions, AtrSnapshot } from './atr';
|
||||
export type { HlcBar, IndicatorSeries } from './contracts';
|
||||
export { bollingerBands, macd, stochastic } from './compositions';
|
||||
|
|
|
|||
175
libs/calculations/src/indicators/rsi.ts
Normal file
175
libs/calculations/src/indicators/rsi.ts
Normal file
|
|
@ -0,0 +1,175 @@
|
|||
import { at } from '@stock-bot/invariants';
|
||||
import {
|
||||
collect,
|
||||
configuration,
|
||||
count,
|
||||
finite,
|
||||
nonnegative,
|
||||
optionalNumber,
|
||||
period,
|
||||
snapshot,
|
||||
type IndicatorSeries,
|
||||
} from './contracts';
|
||||
|
||||
export const RSI_CONTRACT = 'rsi-wilder/v1';
|
||||
export type FlatRsi = 0 | 50 | 100;
|
||||
export interface RsiOptions {
|
||||
flatValue?: FlatRsi;
|
||||
}
|
||||
export interface RsiSnapshot {
|
||||
contract: typeof RSI_CONTRACT;
|
||||
period: number;
|
||||
flatValue: FlatRsi;
|
||||
count: number;
|
||||
previous: number | null;
|
||||
gain: number;
|
||||
loss: number;
|
||||
}
|
||||
|
||||
function flat(value: unknown): FlatRsi {
|
||||
if (value !== 0 && value !== 50 && value !== 100) {
|
||||
throw new Error('Flat RSI value must be 0, 50 or 100');
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function oscillator(gain: number, loss: number, flatValue: FlatRsi): number {
|
||||
if (gain === 0 && loss === 0) {
|
||||
return flatValue;
|
||||
}
|
||||
if (loss === 0) {
|
||||
return 100;
|
||||
}
|
||||
return finite(100 - 100 / (1 + gain / loss));
|
||||
}
|
||||
|
||||
function parse(input: unknown): RsiSnapshot {
|
||||
const value = snapshot(input, [
|
||||
'contract',
|
||||
'period',
|
||||
'flatValue',
|
||||
'count',
|
||||
'previous',
|
||||
'gain',
|
||||
'loss',
|
||||
]);
|
||||
if (value.contract !== RSI_CONTRACT) {
|
||||
throw new Error('Unsupported RSI snapshot contract');
|
||||
}
|
||||
const state: RsiSnapshot = {
|
||||
contract: RSI_CONTRACT,
|
||||
period: period(value.period),
|
||||
flatValue: flat(value.flatValue),
|
||||
count: count(value.count),
|
||||
previous: optionalNumber(value.previous),
|
||||
gain: nonnegative(value.gain),
|
||||
loss: nonnegative(value.loss),
|
||||
};
|
||||
if (
|
||||
(state.previous !== null) !== state.count > 0 ||
|
||||
(state.count <= 1 && (state.gain !== 0 || state.loss !== 0))
|
||||
) {
|
||||
throw new Error('Inconsistent RSI snapshot phase');
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
/** SMA of the first n changes, then Wilder smoothing; the seed change is consumed once. */
|
||||
export class RsiIndicator {
|
||||
private state: RsiSnapshot;
|
||||
constructor(size = 14, options: RsiOptions = {}) {
|
||||
configuration(options, ['flatValue']);
|
||||
this.state = {
|
||||
contract: RSI_CONTRACT,
|
||||
period: period(size),
|
||||
flatValue: flat(options.flatValue === undefined ? 50 : options.flatValue),
|
||||
count: 0,
|
||||
previous: null,
|
||||
gain: 0,
|
||||
loss: 0,
|
||||
};
|
||||
}
|
||||
update(input: number): number | null {
|
||||
const value = finite(input);
|
||||
const prior = this.state;
|
||||
const next = { ...prior, count: count(prior.count + 1), previous: value };
|
||||
if (prior.previous !== null) {
|
||||
const change = finite(value - prior.previous);
|
||||
const gain = Math.max(0, change),
|
||||
loss = Math.max(0, -change);
|
||||
if (prior.count <= prior.period) {
|
||||
next.gain = nonnegative(prior.gain + gain);
|
||||
next.loss = nonnegative(prior.loss + loss);
|
||||
if (prior.count === prior.period) {
|
||||
next.gain /= prior.period;
|
||||
next.loss /= prior.period;
|
||||
}
|
||||
} else {
|
||||
next.gain = nonnegative((prior.gain * (prior.period - 1) + gain) / prior.period);
|
||||
next.loss = nonnegative((prior.loss * (prior.period - 1) + loss) / prior.period);
|
||||
}
|
||||
}
|
||||
const result =
|
||||
next.count > next.period ? oscillator(next.gain, next.loss, next.flatValue) : null;
|
||||
this.state = next;
|
||||
return result;
|
||||
}
|
||||
current(): number | null {
|
||||
return this.state.count > this.state.period
|
||||
? oscillator(this.state.gain, this.state.loss, this.state.flatValue)
|
||||
: null;
|
||||
}
|
||||
snapshot(): RsiSnapshot {
|
||||
return { ...this.state };
|
||||
}
|
||||
reset(): void {
|
||||
this.state = { ...this.state, count: 0, previous: null, gain: 0, loss: 0 };
|
||||
}
|
||||
restore(input: unknown): void {
|
||||
const next = parse(input);
|
||||
if (next.period !== this.state.period || next.flatValue !== this.state.flatValue) {
|
||||
throw new Error('RSI snapshot configuration mismatch');
|
||||
}
|
||||
this.state = next;
|
||||
}
|
||||
static fromSnapshot(input: unknown): RsiIndicator {
|
||||
const state = parse(input);
|
||||
const stream = new RsiIndicator(state.period, { flatValue: state.flatValue });
|
||||
stream.restore(state);
|
||||
return stream;
|
||||
}
|
||||
}
|
||||
|
||||
export function rsi(
|
||||
values: readonly number[],
|
||||
size = 14,
|
||||
options: RsiOptions = {}
|
||||
): IndicatorSeries {
|
||||
return collect(values, new RsiIndicator(size, options), RSI_CONTRACT, size);
|
||||
}
|
||||
|
||||
/** Rolling simple-average RSI, NOT Wilder RSI. Reverse summation preserves mean-reversion/v2 arithmetic. */
|
||||
export function trailingSimpleRsi(
|
||||
values: readonly number[],
|
||||
size = 14,
|
||||
flatValue: FlatRsi = 50
|
||||
): number | undefined {
|
||||
period(size);
|
||||
flat(flatValue);
|
||||
if (values.length < size + 1) {
|
||||
return undefined;
|
||||
}
|
||||
let gain = 0,
|
||||
loss = 0;
|
||||
for (let i = 1; i <= size; i++) {
|
||||
const change = finite(
|
||||
finite(at(values, values.length - i)) - finite(at(values, values.length - i - 1))
|
||||
);
|
||||
if (change > 0) {
|
||||
gain = finite(gain + change);
|
||||
} else {
|
||||
loss = finite(loss + Math.abs(change));
|
||||
}
|
||||
}
|
||||
return oscillator(gain / size, loss / size, flatValue);
|
||||
}
|
||||
69
libs/calculations/test/compositions.test.ts
Normal file
69
libs/calculations/test/compositions.test.ts
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
import { expect, test } from 'bun:test';
|
||||
import { bollingerBands, macd, stochastic } from '@stock-bot/calculations/indicators';
|
||||
|
||||
test('population bands use the unrounded mean and preserve source offsets', () => {
|
||||
const result = bollingerBands([1, 2, 3, 4], 3, 2);
|
||||
expect(result.startIndex).toBe(2);
|
||||
expect(result.middle).toEqual([2, 3]);
|
||||
expect(result.upper[0]).toBeCloseTo(2 + 2 * Math.sqrt(2 / 3), 12);
|
||||
expect(result.lower[1]).toBeCloseTo(3 - 2 * Math.sqrt(2 / 3), 12);
|
||||
expect(bollingerBands([1, 2], 3).middle).toEqual([]);
|
||||
expect(bollingerBands([1, 2, 3], 2, 0).upper).toEqual([1.5, 2.5]);
|
||||
expect(() => bollingerBands([1, 2], 2, -1)).toThrow();
|
||||
expect(() => bollingerBands([1, NaN], 2)).toThrow();
|
||||
});
|
||||
|
||||
test('MACD aligns both EMA seeds, signal warm-up and histogram without time lookups', () => {
|
||||
const result = macd([1, 2, 3, 4, 5, 6], 2, 3, 2);
|
||||
expect(result.macd.startIndex).toBe(2);
|
||||
expect(result.signal.startIndex).toBe(3);
|
||||
expect(result.histogram.startIndex).toBe(3);
|
||||
result.macd.values.forEach(value => expect(value).toBeCloseTo(0.5, 12));
|
||||
result.signal.values.forEach(value => expect(value).toBeCloseTo(0.5, 12));
|
||||
result.histogram.values.forEach(value => expect(value).toBeCloseTo(0, 12));
|
||||
const first = macd([1, 2, 3], 2, 3, 2, { seed: 'first' });
|
||||
expect(first.macd.startIndex).toBe(0);
|
||||
expect(first.signal.startIndex).toBe(0);
|
||||
expect(first.macd.values[2]).toBeCloseTo(11 / 36, 12);
|
||||
expect(first.signal.values[2]).toBeCloseTo(13 / 54, 12);
|
||||
expect(first.histogram.values[2]).toBeCloseTo(7 / 108, 12);
|
||||
expect(macd([1, 2, 3], 2, 3, 5).signal.values).toEqual([]);
|
||||
expect(() => macd([1, 2, 3], 3, 2, 1)).toThrow();
|
||||
expect(() => macd([1, 2], 1, 2, 0)).toThrow();
|
||||
expect(() => macd([], 1, Number.MAX_SAFE_INTEGER - 1, Number.MAX_SAFE_INTEGER - 1)).toThrow();
|
||||
});
|
||||
|
||||
test('stochastic smooths unrounded values and explicitly handles flat windows', () => {
|
||||
const bars = [1, 2, 3, 4, 5, 6].map(close => ({ high: 10, low: 0, close }));
|
||||
const result = stochastic(bars, 2, 2, 2);
|
||||
expect(result.k).toMatchObject({ startIndex: 2, values: [25, 35, 45, 55] });
|
||||
expect(result.d).toMatchObject({ startIndex: 3, values: [30, 40, 50] });
|
||||
expect(stochastic(Array(5).fill({ high: 1, low: 1, close: 1 }), 2, 1, 1).k.values).toEqual([
|
||||
50, 50, 50, 50,
|
||||
]);
|
||||
expect(stochastic(bars.slice(0, 1), 2).k.values).toEqual([]);
|
||||
expect(() => stochastic(bars, 0)).toThrow();
|
||||
expect(() => stochastic([{ high: 1, low: 0, close: 2 }], 1)).toThrow();
|
||||
expect(() => stochastic([], Number.MAX_SAFE_INTEGER - 1, Number.MAX_SAFE_INTEGER - 1)).toThrow();
|
||||
});
|
||||
|
||||
test('composed features are prefix-invariant and do not mutate source inputs', () => {
|
||||
const values = Array.from({ length: 50 }, (_, i) => 10 + Math.sin(i / 2));
|
||||
const bars = values.map(close => ({ high: close + 1, low: close - 1, close }));
|
||||
const original = structuredClone(bars);
|
||||
const fullMacd = macd(values, 3, 7, 4),
|
||||
fullBands = bollingerBands(values, 5),
|
||||
fullStochastic = stochastic(bars, 5, 2, 3);
|
||||
for (let end = 0; end <= values.length; end++) {
|
||||
const prefix = values.slice(0, end);
|
||||
const m = macd(prefix, 3, 7, 4),
|
||||
b = bollingerBands(prefix, 5),
|
||||
s = stochastic(bars.slice(0, end), 5, 2, 3);
|
||||
for (const key of ['macd', 'signal', 'histogram'] as const) {
|
||||
expect(fullMacd[key].values.slice(0, m[key].values.length)).toEqual(m[key].values);
|
||||
}
|
||||
expect(fullBands.lower.slice(0, b.lower.length)).toEqual(b.lower);
|
||||
expect(fullStochastic.d.values.slice(0, s.d.values.length)).toEqual(s.d.values);
|
||||
}
|
||||
expect(bars).toEqual(original);
|
||||
});
|
||||
36
libs/calculations/test/fixtures/indicators.json
vendored
Normal file
36
libs/calculations/test/fixtures/indicators.json
vendored
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
{
|
||||
"provenance": {
|
||||
"method": "Hand-checked rational examples; expected constants are not generated by the implementation under test.",
|
||||
"ema": "https://raw.githubusercontent.com/TA-Lib/ta-lib/v0.6.4/src/ta_func/ta_EMA.c",
|
||||
"rsi": "https://chartschool.stockcharts.com/table-of-contents/technical-indicators-and-overlays/technical-indicators/relative-strength-index-rsi",
|
||||
"atr": "https://chartschool.stockcharts.com/table-of-contents/technical-indicators-and-overlays/technical-indicators/average-true-range-atr",
|
||||
"policies": "Our flat RSI defaults to 50 explicitly; this is not claimed as a universal convention. ATR previous-close seed skips the first bar, while high-low seed includes it."
|
||||
},
|
||||
"ema": {
|
||||
"period": 3,
|
||||
"prices": [1, 2, 3, 4, 5, 6],
|
||||
"smaSeed": [2, 3, 4, 5],
|
||||
"firstSeed": [1, 1.5, 2.25, 3.125, 4.0625, 5.03125]
|
||||
},
|
||||
"rsi": {
|
||||
"period": 3,
|
||||
"prices": [10, 11, 13, 12, 14, 13, 15],
|
||||
"values": [75, 85.71428571428571, 64.86486486486487, 79.6875],
|
||||
"check": "First average gain=1 and loss=1/3. Next three gain/loss ratios are 6, 24/13, 51/13."
|
||||
},
|
||||
"atr": {
|
||||
"period": 3,
|
||||
"bars": [
|
||||
{ "high": 12, "low": 8, "close": 10 },
|
||||
{ "high": 15, "low": 11, "close": 14 },
|
||||
{ "high": 14, "low": 10, "close": 11 },
|
||||
{ "high": 18, "low": 15, "close": 16 },
|
||||
{ "high": 17, "low": 13, "close": 14 },
|
||||
{ "high": 15, "low": 10, "close": 12 }
|
||||
],
|
||||
"trueRanges": [4, 5, 4, 7, 4, 5],
|
||||
"highLowSeed": [4.333333333333333, 5.222222222222222, 4.814814814814815, 4.876543209876543],
|
||||
"previousCloseSeed": [5.333333333333333, 4.888888888888889, 4.925925925925926],
|
||||
"check": "High-low series: 13/3, 47/9, 130/27, 395/81. Previous-close series: 16/3, 44/9, 133/27."
|
||||
}
|
||||
}
|
||||
268
libs/calculations/test/indicators.test.ts
Normal file
268
libs/calculations/test/indicators.test.ts
Normal file
|
|
@ -0,0 +1,268 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import {
|
||||
atr,
|
||||
AtrIndicator,
|
||||
ema,
|
||||
EmaIndicator,
|
||||
rsi,
|
||||
RsiIndicator,
|
||||
trailingSimpleRsi,
|
||||
type HlcBar,
|
||||
type IndicatorSeries,
|
||||
} from '@stock-bot/calculations/indicators';
|
||||
import golden from './fixtures/indicators.json';
|
||||
|
||||
function close(actual: readonly number[], expected: readonly number[]) {
|
||||
expect(actual).toHaveLength(expected.length);
|
||||
actual.forEach((value, i) => expect(value).toBeCloseTo(expected[i]!, 11));
|
||||
}
|
||||
|
||||
interface Stream<T> {
|
||||
update(input: T): number | null;
|
||||
current(): number | null;
|
||||
reset(): void;
|
||||
snapshot(): unknown;
|
||||
restore(input: unknown): void;
|
||||
}
|
||||
|
||||
function restarts<T>(
|
||||
inputs: readonly T[],
|
||||
make: () => Stream<T>,
|
||||
recover: (input: unknown) => Stream<T>,
|
||||
batch: (inputs: readonly T[]) => IndicatorSeries
|
||||
) {
|
||||
const source = structuredClone(inputs);
|
||||
const uninterrupted = make();
|
||||
const values = inputs.map(input => uninterrupted.update(input));
|
||||
expect(values.filter(value => value !== null)).toEqual(batch(inputs).values);
|
||||
for (let cut = 0; cut <= inputs.length; cut++) {
|
||||
const before = make();
|
||||
inputs.slice(0, cut).forEach(input => before.update(input));
|
||||
const serialized = JSON.stringify(before.snapshot());
|
||||
const recovered = recover(JSON.parse(serialized));
|
||||
expect(recovered.current()).toBe(before.current());
|
||||
expect(JSON.stringify(recovered.snapshot())).toBe(serialized);
|
||||
expect(inputs.slice(cut).map(input => recovered.update(input))).toEqual(values.slice(cut));
|
||||
const prefix = batch(inputs.slice(0, cut));
|
||||
expect(batch(inputs).values.slice(0, prefix.values.length)).toEqual(prefix.values);
|
||||
before.reset();
|
||||
expect(before.current()).toBeNull();
|
||||
expect(JSON.stringify(before.snapshot())).toBe(JSON.stringify(make().snapshot()));
|
||||
}
|
||||
expect(inputs).toEqual(source);
|
||||
const isolated = make();
|
||||
const view = isolated.snapshot() as Record<string, unknown>;
|
||||
view.count = 123;
|
||||
expect(isolated.snapshot()).toEqual(make().snapshot());
|
||||
}
|
||||
|
||||
describe('versioned, aligned indicator formulas', () => {
|
||||
test('EMA seeds and offsets are explicit, without rounded intermediates', () => {
|
||||
const g = golden.ema;
|
||||
const sma = ema(g.prices, g.period);
|
||||
expect(sma.contract).toBe('ema/v1');
|
||||
expect(sma.startIndex).toBe(2);
|
||||
close(sma.values, g.smaSeed);
|
||||
const first = ema(g.prices, g.period, { seed: 'first' });
|
||||
expect(first.startIndex).toBe(0);
|
||||
close(first.values, g.firstSeed);
|
||||
expect(ema([1, 2], 3)).toMatchObject({ startIndex: 2, values: [] });
|
||||
expect(ema([], 3, { seed: 'first' })).toMatchObject({ startIndex: 0, values: [] });
|
||||
expect(ema([1, 2, 3], 1).values).toEqual([1, 2, 3]);
|
||||
expect(ema([1, 2, 3], 1, { seed: 'first' }).values).toEqual([1, 2, 3]);
|
||||
expect(ema([0.011, 0.019, 0.021], 2).values[0]).toBe(0.015);
|
||||
});
|
||||
|
||||
test('Wilder RSI consumes the initialization delta once and handles zero losses/flat data', () => {
|
||||
const g = golden.rsi;
|
||||
const result = rsi(g.prices, g.period);
|
||||
expect(result.contract).toBe('rsi-wilder/v1');
|
||||
expect(result.startIndex).toBe(g.period);
|
||||
close(result.values, g.values);
|
||||
expect(rsi(g.prices.slice(0, 3), 3).values).toEqual([]);
|
||||
expect(rsi([1, 2, 3, 4, 5], 3).values).toEqual([100, 100]);
|
||||
expect(rsi([5, 4, 3, 2, 1], 3).values).toEqual([0, 0]);
|
||||
for (const flatValue of [0, 50, 100] as const) {
|
||||
expect(rsi([2, 2, 2, 2, 2], 3, { flatValue }).values).toEqual([flatValue, flatValue]);
|
||||
}
|
||||
expect(rsi([2, 2, 2, 2], 3).values).toEqual([50]);
|
||||
expect(rsi([1, 2, 1, 1], 1).values).toEqual([100, 0, 50]);
|
||||
});
|
||||
|
||||
test('ATR includes gap ranges and distinguishes both first-bar policies', () => {
|
||||
const g = golden.atr;
|
||||
const previous = atr(g.bars, g.period);
|
||||
expect(previous.contract).toBe('atr-wilder/v1');
|
||||
expect(previous.startIndex).toBe(3);
|
||||
close(previous.values, g.previousCloseSeed);
|
||||
const included = atr(g.bars, g.period, { firstRange: 'high-low' });
|
||||
expect(included.startIndex).toBe(2);
|
||||
close(included.values, g.highLowSeed);
|
||||
expect(atr(g.bars.slice(0, 3), 3).values).toEqual([]);
|
||||
expect(atr(g.bars.slice(0, 2), 3, { firstRange: 'high-low' }).values).toEqual([]);
|
||||
expect(atr(g.bars, 1, { firstRange: 'high-low' }).values).toEqual(g.trueRanges);
|
||||
expect(atr(g.bars, 1).values).toEqual(g.trueRanges.slice(1));
|
||||
expect(atr(Array(5).fill({ high: 0, low: 0, close: 0 }), 2).values).toEqual([0, 0, 0]);
|
||||
});
|
||||
|
||||
test('rolling simple RSI preserves the v2 strategy variant, not an alias to Wilder RSI', () => {
|
||||
const g = golden.rsi;
|
||||
expect(trailingSimpleRsi(g.prices, 3)).toBeCloseTo(80);
|
||||
expect(rsi(g.prices, 3).values.at(-1)).toBeCloseTo(79.6875);
|
||||
expect(trailingSimpleRsi([1, 2], 3, 100)).toBeUndefined();
|
||||
expect(trailingSimpleRsi([1, 1, 1, 1], 3, 100)).toBe(100);
|
||||
expect(trailingSimpleRsi([1, 1, 1, 1], 3)).toBe(50);
|
||||
expect(() => trailingSimpleRsi([1, NaN, 3, 4], 3)).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('batch/stream/restart and no-lookahead equivalence', () => {
|
||||
const values = Array.from({ length: 38 }, (_, i) => 100 + Math.sin(i / 2) * 8 + i / 10);
|
||||
const bars = values.map(close => ({ high: close + 1, low: close - 2, close }));
|
||||
test('EMA supports every restart boundary for both seeds', () => {
|
||||
for (const seed of ['first', 'sma'] as const) {
|
||||
restarts(
|
||||
values,
|
||||
() => new EmaIndicator(5, { seed }),
|
||||
EmaIndicator.fromSnapshot,
|
||||
values => ema(values, 5, { seed })
|
||||
);
|
||||
}
|
||||
});
|
||||
test('RSI supports every restart boundary and flat policy', () => {
|
||||
for (const flatValue of [0, 50, 100] as const) {
|
||||
restarts(
|
||||
values,
|
||||
() => new RsiIndicator(5, { flatValue }),
|
||||
RsiIndicator.fromSnapshot,
|
||||
values => rsi(values, 5, { flatValue })
|
||||
);
|
||||
}
|
||||
});
|
||||
test('ATR supports every restart boundary and first-range policy', () => {
|
||||
for (const firstRange of ['previous-close', 'high-low'] as const) {
|
||||
restarts(
|
||||
bars,
|
||||
() => new AtrIndicator(5, { firstRange }),
|
||||
AtrIndicator.fromSnapshot,
|
||||
bars => atr(bars, 5, { firstRange })
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('indicator state/input rejection is atomic', () => {
|
||||
test('bad periods, options, sparse arrays and non-finite observations fail before producing data', () => {
|
||||
for (const size of [0, -1, 1.5, NaN, Infinity, Number.MAX_SAFE_INTEGER]) {
|
||||
expect(() => new EmaIndicator(size)).toThrow();
|
||||
expect(() => new RsiIndicator(size)).toThrow();
|
||||
expect(() => new AtrIndicator(size)).toThrow();
|
||||
}
|
||||
expect(() => ema([1], 2, { seed: 'other' } as never)).toThrow();
|
||||
expect(() => rsi([1], 2, { flatValue: 12 } as never)).toThrow();
|
||||
expect(() => rsi([1], 2, { smoothing: 'simple' } as never)).toThrow();
|
||||
expect(() => atr([], 2, { firstRange: 'other' } as never)).toThrow();
|
||||
expect(() => ema(Array(5), 2)).toThrow();
|
||||
expect(() => rsi(Array(5), 2)).toThrow();
|
||||
expect(() => atr(Array(5), 2)).toThrow();
|
||||
for (const stream of [new EmaIndicator(2), new RsiIndicator(2)]) {
|
||||
stream.update(1);
|
||||
const before = stream.snapshot();
|
||||
for (const invalid of [NaN, Infinity, -Infinity, '2', undefined, null]) {
|
||||
expect(() => stream.update(invalid as number)).toThrow();
|
||||
expect(stream.snapshot()).toEqual(before);
|
||||
}
|
||||
}
|
||||
const range = new AtrIndicator(2);
|
||||
range.update({ high: 2, low: 0, close: 1 });
|
||||
for (const bad of [
|
||||
{ high: 0, low: 2, close: 1 },
|
||||
{ high: 2, low: 0, close: 3 },
|
||||
{ high: Infinity, low: 0, close: 1 },
|
||||
]) {
|
||||
const before = range.snapshot();
|
||||
expect(() => range.update(bad)).toThrow();
|
||||
expect(range.snapshot()).toEqual(before);
|
||||
}
|
||||
});
|
||||
|
||||
test('arithmetic failures cannot poison an otherwise resumable stream', () => {
|
||||
const emaStream = new EmaIndicator(3);
|
||||
emaStream.update(Number.MAX_VALUE);
|
||||
const beforeEma = emaStream.snapshot();
|
||||
expect(() => emaStream.update(Number.MAX_VALUE)).toThrow();
|
||||
expect(emaStream.snapshot()).toEqual(beforeEma);
|
||||
const rsiStream = new RsiIndicator(3);
|
||||
rsiStream.update(-Number.MAX_VALUE);
|
||||
const beforeRsi = rsiStream.snapshot();
|
||||
expect(() => rsiStream.update(Number.MAX_VALUE)).toThrow();
|
||||
expect(rsiStream.snapshot()).toEqual(beforeRsi);
|
||||
const atrStream = new AtrIndicator(3);
|
||||
const beforeAtr = atrStream.snapshot();
|
||||
expect(() =>
|
||||
atrStream.update({ high: Number.MAX_VALUE, low: -Number.MAX_VALUE, close: 0 })
|
||||
).toThrow();
|
||||
expect(atrStream.snapshot()).toEqual(beforeAtr);
|
||||
});
|
||||
|
||||
test('snapshot schemas reject incompatible versions, mismatched configurations and inconsistent phases', () => {
|
||||
const streams: Array<Stream<number> | Stream<HlcBar>> = [
|
||||
new EmaIndicator(3),
|
||||
new RsiIndicator(3),
|
||||
new AtrIndicator(3),
|
||||
];
|
||||
for (const stream of streams) {
|
||||
const original = stream.snapshot() as Record<string, unknown>;
|
||||
for (const bad of [
|
||||
null,
|
||||
[],
|
||||
{},
|
||||
{ ...original, contract: 'future/v99' },
|
||||
{ ...original, count: -1 },
|
||||
{ ...original, count: 0.5 },
|
||||
{ ...original, count: Infinity },
|
||||
{ ...original, period: 4 },
|
||||
{ ...original, unexpected: 1 },
|
||||
]) {
|
||||
expect(() => stream.restore(bad)).toThrow();
|
||||
expect(stream.snapshot()).toEqual(original);
|
||||
}
|
||||
}
|
||||
const e = new EmaIndicator(3);
|
||||
expect(() => e.restore({ ...e.snapshot(), count: 1, value: 1 })).toThrow();
|
||||
expect(() => e.restore({ ...e.snapshot(), seedSum: 1 })).toThrow();
|
||||
expect(() => e.restore({ ...e.snapshot(), count: 3 })).toThrow();
|
||||
expect(() => e.restore({ ...e.snapshot(), seed: 'first' })).toThrow();
|
||||
const r = new RsiIndicator(3);
|
||||
expect(() => r.restore({ ...r.snapshot(), count: 1 })).toThrow();
|
||||
expect(() => r.restore({ ...r.snapshot(), previous: 1 })).toThrow();
|
||||
expect(() => r.restore({ ...r.snapshot(), gain: -1 })).toThrow();
|
||||
expect(() => r.restore({ ...r.snapshot(), count: 1, previous: 1, gain: 1 })).toThrow();
|
||||
expect(() => r.restore({ ...r.snapshot(), flatValue: 100 })).toThrow();
|
||||
const a = new AtrIndicator(3);
|
||||
expect(() => a.restore({ ...a.snapshot(), seedSum: -1 })).toThrow();
|
||||
expect(() => a.restore({ ...a.snapshot(), count: 1, value: 1 })).toThrow();
|
||||
expect(() => a.restore({ ...a.snapshot(), previousClose: 1 })).toThrow();
|
||||
expect(() => a.restore({ ...a.snapshot(), firstRange: 'high-low' })).toThrow();
|
||||
});
|
||||
|
||||
test('long histories keep bounded JSON state and count overflow is rejected atomically', () => {
|
||||
const streams = [new EmaIndicator(5), new RsiIndicator(5)];
|
||||
const range = new AtrIndicator(5);
|
||||
for (let i = 0; i < 10000; i++) {
|
||||
streams.forEach(stream => stream.update(10 + Math.sin(i)));
|
||||
range.update({ high: 12, low: 8, close: 10 });
|
||||
}
|
||||
const cases = [
|
||||
...streams.map(stream => ({ stream, next: () => stream.update(10) })),
|
||||
{ stream: range, next: () => range.update({ high: 12, low: 8, close: 10 }) },
|
||||
];
|
||||
for (const { stream, next } of cases) {
|
||||
expect(JSON.stringify(stream.snapshot()).length).toBeLessThan(300);
|
||||
const state = { ...stream.snapshot(), count: Number.MAX_SAFE_INTEGER };
|
||||
stream.restore(state);
|
||||
expect(next).toThrow();
|
||||
expect(stream.snapshot()).toEqual(state);
|
||||
}
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue