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
|
|
@ -29,6 +29,13 @@ not an incremental O(1) indicator implementation.
|
||||||
|
|
||||||
## Native batch and incremental indicators
|
## Native batch and incremental indicators
|
||||||
|
|
||||||
|
Portable reviewed EMA, Wilder RSI and Wilder ATR (batch and restartable streaming),
|
||||||
|
plus derived chart calculations, are available from `@stock-bot/calculations/indicators`.
|
||||||
|
See [the versioned contracts](../../../../libs/calculations/docs/indicators.md) before
|
||||||
|
choosing a seed, flat-data policy or ATR first range. They are not drop-in aliases for
|
||||||
|
every historical native behavior. Mean-reversion v2 keeps its rolling simple RSI;
|
||||||
|
adopting Wilder RSI for an existing strategy requires a deliberate new version.
|
||||||
|
|
||||||
Rust implementations live in `apps/stock/engine/src/indicators/`, exposed by
|
Rust implementations live in `apps/stock/engine/src/indicators/`, exposed by
|
||||||
`@stock-bot/engine`. Build the native engine before importing the binding.
|
`@stock-bot/engine`. Build the native engine before importing the binding.
|
||||||
`src/indicators/TechnicalAnalysis.ts` provides typed batch wrappers for SMA, EMA, RSI,
|
`src/indicators/TechnicalAnalysis.ts` provides typed batch wrappers for SMA, EMA, RSI,
|
||||||
|
|
|
||||||
|
|
@ -1,9 +1,13 @@
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
import {
|
||||||
|
trailingMean,
|
||||||
|
trailingPopulationDeviation,
|
||||||
|
trailingSimpleRsi,
|
||||||
|
} from '@stock-bot/calculations/indicators';
|
||||||
import { at, defined } from '@stock-bot/invariants';
|
import { at, defined } from '@stock-bot/invariants';
|
||||||
import { getLogger } from '@stock-bot/logger';
|
import { getLogger } from '@stock-bot/logger';
|
||||||
import type { MeanReversionParameters } from '../../contracts/strategies';
|
import type { MeanReversionParameters } from '../../contracts/strategies';
|
||||||
import type { ModeManager } from '../../core/ModeManager';
|
import type { ModeManager } from '../../core/ModeManager';
|
||||||
import { trailingMean, trailingPopulationDeviation } from '@stock-bot/calculations/indicators';
|
|
||||||
import type { ExecutionService } from '../../services/ExecutionService';
|
import type { ExecutionService } from '../../services/ExecutionService';
|
||||||
import type { StrategyConfig } from '../../types';
|
import type { StrategyConfig } from '../../types';
|
||||||
import { type MarketData } from '../../types';
|
import { type MarketData } from '../../types';
|
||||||
|
|
@ -209,34 +213,8 @@ export class MeanReversionStrategy extends BaseStrategy {
|
||||||
}
|
}
|
||||||
|
|
||||||
private calculateRSI(prices: number[], period: number = 14): number {
|
private calculateRSI(prices: number[], period: number = 14): number {
|
||||||
if (prices.length < period + 1) {
|
// v2 uses rolling simple averages and flat=100, NOT the new Wilder contract.
|
||||||
return 50;
|
return trailingSimpleRsi(prices, period, 100) ?? 50;
|
||||||
}
|
|
||||||
|
|
||||||
let gains = 0;
|
|
||||||
let losses = 0;
|
|
||||||
|
|
||||||
// Calculate initial average gain/loss
|
|
||||||
for (let i = 1; i <= period; i++) {
|
|
||||||
const change = at(prices, prices.length - i) - at(prices, prices.length - i - 1);
|
|
||||||
if (change > 0) {
|
|
||||||
gains += change;
|
|
||||||
} else {
|
|
||||||
losses += Math.abs(change);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const avgGain = gains / period;
|
|
||||||
const avgLoss = losses / period;
|
|
||||||
|
|
||||||
if (avgLoss === 0) {
|
|
||||||
return 100;
|
|
||||||
}
|
|
||||||
|
|
||||||
const rs = avgGain / avgLoss;
|
|
||||||
const rsi = 100 - 100 / (1 + rs);
|
|
||||||
|
|
||||||
return rsi;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
protected override onStart(): void {
|
protected override onStart(): void {
|
||||||
|
|
|
||||||
|
|
@ -10,6 +10,7 @@
|
||||||
"type-check": "tsc --noEmit"
|
"type-check": "tsc --noEmit"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@stock-bot/calculations": "workspace:*",
|
||||||
"@headlessui/react": "^1.7.17",
|
"@headlessui/react": "^1.7.17",
|
||||||
"@heroicons/react": "^2.0.18",
|
"@heroicons/react": "^2.0.18",
|
||||||
"@hookform/resolvers": "^3.3.4",
|
"@hookform/resolvers": "^3.3.4",
|
||||||
|
|
|
||||||
|
|
@ -1,321 +1,80 @@
|
||||||
|
import {
|
||||||
|
atr,
|
||||||
|
bollingerBands,
|
||||||
|
ema,
|
||||||
|
macd,
|
||||||
|
rsi,
|
||||||
|
sma,
|
||||||
|
stochastic,
|
||||||
|
} from '@stock-bot/calculations/indicators';
|
||||||
|
import { calculateVWAP as vwap } from '@stock-bot/calculations/market-data';
|
||||||
import { at } from '@stock-bot/invariants';
|
import { at } from '@stock-bot/invariants';
|
||||||
import type { CandlestickData, LineData } from '../types';
|
import type { CandlestickData, LineData } from '../types';
|
||||||
|
|
||||||
// Simple Moving Average
|
/** Corrected chart math is a new display contract, not a persisted strategy migration. */
|
||||||
|
export const CHART_INDICATOR_CONTRACT = 'chart-indicators/v2';
|
||||||
|
|
||||||
|
function lines(
|
||||||
|
data: readonly CandlestickData[],
|
||||||
|
values: readonly number[],
|
||||||
|
startIndex: number
|
||||||
|
): LineData[] {
|
||||||
|
return values.map((value, i) => ({
|
||||||
|
time: at(data, startIndex + i).time,
|
||||||
|
value: Number(value.toFixed(2)),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
const closes = (data: readonly CandlestickData[]): number[] => Array.from(data, bar => bar.close);
|
||||||
|
|
||||||
export function calculateSMA(data: CandlestickData[], period: number): LineData[] {
|
export function calculateSMA(data: CandlestickData[], period: number): LineData[] {
|
||||||
const result: LineData[] = [];
|
return lines(data, sma(closes(data), period), period - 1);
|
||||||
|
|
||||||
for (let i = period - 1; i < data.length; i++) {
|
|
||||||
let sum = 0;
|
|
||||||
for (let j = 0; j < period; j++) {
|
|
||||||
const item = data[i - j];
|
|
||||||
if (item) {
|
|
||||||
sum += item.close;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const current = data[i];
|
|
||||||
if (current) {
|
|
||||||
result.push({
|
|
||||||
time: current.time,
|
|
||||||
value: parseFloat((sum / period).toFixed(2)),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Exponential Moving Average
|
|
||||||
export function calculateEMA(data: CandlestickData[], period: number): LineData[] {
|
export function calculateEMA(data: CandlestickData[], period: number): LineData[] {
|
||||||
const result: LineData[] = [];
|
const result = ema(closes(data), period, { seed: 'sma' });
|
||||||
const multiplier = 2 / (period + 1);
|
return lines(data, result.values, result.startIndex);
|
||||||
|
|
||||||
// Start with SMA for the first period
|
|
||||||
let sum = 0;
|
|
||||||
for (let i = 0; i < period; i++) {
|
|
||||||
const item = data[i];
|
|
||||||
if (item) {
|
|
||||||
sum += item.close;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let ema = sum / period;
|
|
||||||
|
|
||||||
const firstItem = data[period - 1];
|
|
||||||
if (firstItem) {
|
|
||||||
result.push({
|
|
||||||
time: firstItem.time,
|
|
||||||
value: parseFloat(ema.toFixed(2)),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Calculate EMA for the rest
|
|
||||||
for (let i = period; i < data.length; i++) {
|
|
||||||
const current = data[i];
|
|
||||||
if (current) {
|
|
||||||
ema = (current.close - ema) * multiplier + ema;
|
|
||||||
result.push({
|
|
||||||
time: current.time,
|
|
||||||
value: parseFloat(ema.toFixed(2)),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
}
|
||||||
|
export function calculateBollingerBands(data: CandlestickData[], period = 20, stdDev = 2) {
|
||||||
// Bollinger Bands
|
const result = bollingerBands(closes(data), period, stdDev);
|
||||||
export function calculateBollingerBands(
|
return {
|
||||||
data: CandlestickData[],
|
middle: lines(data, result.middle, result.startIndex),
|
||||||
period: number = 20,
|
upper: lines(data, result.upper, result.startIndex),
|
||||||
stdDev: number = 2
|
lower: lines(data, result.lower, result.startIndex),
|
||||||
) {
|
};
|
||||||
const sma = calculateSMA(data, period);
|
|
||||||
const upper: LineData[] = [];
|
|
||||||
const lower: LineData[] = [];
|
|
||||||
|
|
||||||
for (let i = period - 1; i < data.length; i++) {
|
|
||||||
let sumSquaredDiff = 0;
|
|
||||||
const smaItem = sma[i - (period - 1)];
|
|
||||||
if (!smaItem) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
const smaValue = smaItem.value;
|
|
||||||
|
|
||||||
for (let j = 0; j < period; j++) {
|
|
||||||
const item = data[i - j];
|
|
||||||
if (item) {
|
|
||||||
const diff = item.close - smaValue;
|
|
||||||
sumSquaredDiff += diff * diff;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const standardDeviation = Math.sqrt(sumSquaredDiff / period);
|
|
||||||
const upperBand = smaValue + standardDeviation * stdDev;
|
|
||||||
const lowerBand = smaValue - standardDeviation * stdDev;
|
|
||||||
|
|
||||||
const current = data[i];
|
|
||||||
if (current) {
|
|
||||||
upper.push({
|
|
||||||
time: current.time,
|
|
||||||
value: parseFloat(upperBand.toFixed(2)),
|
|
||||||
});
|
|
||||||
|
|
||||||
lower.push({
|
|
||||||
time: current.time,
|
|
||||||
value: parseFloat(lowerBand.toFixed(2)),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return { upper, middle: sma, lower };
|
|
||||||
}
|
}
|
||||||
|
export function calculateRSI(data: CandlestickData[], period = 14): LineData[] {
|
||||||
// Relative Strength Index (RSI)
|
const result = rsi(closes(data), period, { flatValue: 50 });
|
||||||
export function calculateRSI(data: CandlestickData[], period: number = 14): LineData[] {
|
return lines(data, result.values, result.startIndex);
|
||||||
const result: LineData[] = [];
|
}
|
||||||
|
export function calculateATR(data: CandlestickData[], period = 14): LineData[] {
|
||||||
if (data.length < period + 1) {
|
const result = atr(data, period, { firstRange: 'previous-close' });
|
||||||
return result;
|
return lines(data, result.values, result.startIndex);
|
||||||
}
|
|
||||||
|
|
||||||
// Calculate initial average gain/loss
|
|
||||||
let avgGain = 0;
|
|
||||||
let avgLoss = 0;
|
|
||||||
|
|
||||||
for (let i = 1; i <= period; i++) {
|
|
||||||
const current = data[i];
|
|
||||||
const prev = data[i - 1];
|
|
||||||
if (current && prev) {
|
|
||||||
const change = current.close - prev.close;
|
|
||||||
if (change > 0) {
|
|
||||||
avgGain += change;
|
|
||||||
} else {
|
|
||||||
avgLoss += Math.abs(change);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
avgGain /= period;
|
|
||||||
avgLoss /= period;
|
|
||||||
|
|
||||||
// Calculate RSI for each period
|
|
||||||
for (let i = period; i < data.length; i++) {
|
|
||||||
const current = data[i];
|
|
||||||
const prev = data[i - 1];
|
|
||||||
if (!current || !prev) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
const change = current.close - prev.close;
|
|
||||||
const gain = change > 0 ? change : 0;
|
|
||||||
const loss = change < 0 ? Math.abs(change) : 0;
|
|
||||||
|
|
||||||
avgGain = (avgGain * (period - 1) + gain) / period;
|
|
||||||
avgLoss = (avgLoss * (period - 1) + loss) / period;
|
|
||||||
|
|
||||||
const rs = avgLoss === 0 ? 100 : avgGain / avgLoss;
|
|
||||||
const rsi = 100 - 100 / (1 + rs);
|
|
||||||
|
|
||||||
result.push({
|
|
||||||
time: current.time,
|
|
||||||
value: parseFloat(rsi.toFixed(2)),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// MACD (Moving Average Convergence Divergence)
|
|
||||||
export function calculateMACD(
|
export function calculateMACD(
|
||||||
data: CandlestickData[],
|
data: CandlestickData[],
|
||||||
fastPeriod: number = 12,
|
fastPeriod = 12,
|
||||||
slowPeriod: number = 26,
|
slowPeriod = 26,
|
||||||
signalPeriod: number = 9
|
signalPeriod = 9
|
||||||
) {
|
) {
|
||||||
const emaFast = calculateEMA(data, fastPeriod);
|
const result = macd(closes(data), fastPeriod, slowPeriod, signalPeriod, { seed: 'sma' });
|
||||||
const emaSlow = calculateEMA(data, slowPeriod);
|
return {
|
||||||
|
macdLine: lines(data, result.macd.values, result.macd.startIndex),
|
||||||
const macdLine: LineData[] = [];
|
signalLine: lines(data, result.signal.values, result.signal.startIndex),
|
||||||
const macdData: number[] = [];
|
histogram: lines(data, result.histogram.values, result.histogram.startIndex),
|
||||||
|
};
|
||||||
// Calculate MACD line
|
|
||||||
for (let i = 0; i < Math.min(emaFast.length, emaSlow.length); i++) {
|
|
||||||
const fastIdx = emaFast.findIndex(d => d.time === at(emaSlow, i).time);
|
|
||||||
if (fastIdx !== -1) {
|
|
||||||
const macdValue = at(emaFast, fastIdx).value - at(emaSlow, i).value;
|
|
||||||
macdLine.push({
|
|
||||||
time: at(emaSlow, i).time,
|
|
||||||
value: parseFloat(macdValue.toFixed(2)),
|
|
||||||
});
|
|
||||||
macdData.push(macdValue);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Calculate signal line (EMA of MACD)
|
|
||||||
const signalLine: LineData[] = [];
|
|
||||||
if (macdData.length >= signalPeriod) {
|
|
||||||
const multiplier = 2 / (signalPeriod + 1);
|
|
||||||
let ema = macdData.slice(0, signalPeriod).reduce((a, b) => a + b, 0) / signalPeriod;
|
|
||||||
|
|
||||||
const firstMacd = macdLine[signalPeriod - 1];
|
|
||||||
if (firstMacd) {
|
|
||||||
signalLine.push({
|
|
||||||
time: firstMacd.time,
|
|
||||||
value: parseFloat(ema.toFixed(2)),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
for (let i = signalPeriod; i < macdData.length; i++) {
|
|
||||||
ema = (at(macdData, i) - ema) * multiplier + ema;
|
|
||||||
const macdItem = macdLine[i];
|
|
||||||
if (macdItem) {
|
|
||||||
signalLine.push({
|
|
||||||
time: macdItem.time,
|
|
||||||
value: parseFloat(ema.toFixed(2)),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Calculate histogram
|
|
||||||
const histogram: LineData[] = [];
|
|
||||||
for (let i = 0; i < signalLine.length; i++) {
|
|
||||||
const macdIdx = macdLine.findIndex(d => d.time === at(signalLine, i).time);
|
|
||||||
if (macdIdx !== -1) {
|
|
||||||
histogram.push({
|
|
||||||
time: at(signalLine, i).time,
|
|
||||||
value: parseFloat((at(macdLine, macdIdx).value - at(signalLine, i).value).toFixed(2)),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return { macdLine, signalLine, histogram };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Volume Weighted Average Price (VWAP)
|
|
||||||
export function calculateVWAP(data: CandlestickData[]): LineData[] {
|
export function calculateVWAP(data: CandlestickData[]): LineData[] {
|
||||||
const result: LineData[] = [];
|
const values = vwap(data.map(bar => ({ ...bar, volume: bar.volume ?? 0 })));
|
||||||
let cumulativeTPV = 0; // Cumulative Typical Price × Volume
|
return values.flatMap((value, i) => (value === null ? [] : lines(data, [value], i)));
|
||||||
let cumulativeVolume = 0;
|
|
||||||
|
|
||||||
for (let i = 0; i < data.length; i++) {
|
|
||||||
const current = data[i];
|
|
||||||
if (!current) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
const typicalPrice = (current.high + current.low + current.close) / 3;
|
|
||||||
const volume = current.volume || 0;
|
|
||||||
|
|
||||||
cumulativeTPV += typicalPrice * volume;
|
|
||||||
cumulativeVolume += volume;
|
|
||||||
|
|
||||||
if (cumulativeVolume > 0) {
|
|
||||||
result.push({
|
|
||||||
time: current.time,
|
|
||||||
value: parseFloat((cumulativeTPV / cumulativeVolume).toFixed(2)),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Stochastic Oscillator
|
|
||||||
export function calculateStochastic(
|
export function calculateStochastic(
|
||||||
data: CandlestickData[],
|
data: CandlestickData[],
|
||||||
period: number = 14,
|
period = 14,
|
||||||
smoothK: number = 3,
|
smoothK = 3,
|
||||||
smoothD: number = 3
|
smoothD = 3
|
||||||
) {
|
) {
|
||||||
const kValues: LineData[] = [];
|
const result = stochastic(data, period, smoothK, smoothD);
|
||||||
|
return {
|
||||||
// Calculate %K
|
k: lines(data, result.k.values, result.k.startIndex),
|
||||||
for (let i = period - 1; i < data.length; i++) {
|
d: lines(data, result.d.values, result.d.startIndex),
|
||||||
const current = data[i];
|
};
|
||||||
if (!current) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let lowestLow = current.low;
|
|
||||||
let highestHigh = current.high;
|
|
||||||
|
|
||||||
for (let j = 1; j < period; j++) {
|
|
||||||
const prev = data[i - j];
|
|
||||||
if (!prev) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
lowestLow = Math.min(lowestLow, prev.low);
|
|
||||||
highestHigh = Math.max(highestHigh, prev.high);
|
|
||||||
}
|
|
||||||
|
|
||||||
const k = ((current.close - lowestLow) / (highestHigh - lowestLow)) * 100;
|
|
||||||
kValues.push({
|
|
||||||
time: current.time,
|
|
||||||
value: parseFloat(k.toFixed(2)),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Smooth %K if needed
|
|
||||||
const smoothedK = smoothK > 1 ? calculateSMAFromLineData(kValues, smoothK) : kValues;
|
|
||||||
|
|
||||||
// Calculate %D (SMA of %K)
|
|
||||||
const smoothedD = calculateSMAFromLineData(smoothedK, smoothD);
|
|
||||||
|
|
||||||
return { k: smoothedK, d: smoothedD };
|
|
||||||
}
|
|
||||||
|
|
||||||
// Helper function to calculate SMA from LineData
|
|
||||||
function calculateSMAFromLineData(data: LineData[], period: number): LineData[] {
|
|
||||||
const result: LineData[] = [];
|
|
||||||
|
|
||||||
for (let i = period - 1; i < data.length; i++) {
|
|
||||||
let sum = 0;
|
|
||||||
for (let j = 0; j < period; j++) {
|
|
||||||
sum += at(data, i - j).value;
|
|
||||||
}
|
|
||||||
result.push({
|
|
||||||
time: at(data, i).time,
|
|
||||||
value: parseFloat((sum / period).toFixed(2)),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
1
bun.lock
1
bun.lock
|
|
@ -190,6 +190,7 @@
|
||||||
"@headlessui/react": "^1.7.17",
|
"@headlessui/react": "^1.7.17",
|
||||||
"@heroicons/react": "^2.0.18",
|
"@heroicons/react": "^2.0.18",
|
||||||
"@hookform/resolvers": "^3.3.4",
|
"@hookform/resolvers": "^3.3.4",
|
||||||
|
"@stock-bot/calculations": "workspace:*",
|
||||||
"@stock-bot/invariants": "workspace:*",
|
"@stock-bot/invariants": "workspace:*",
|
||||||
"@stock-bot/types": "workspace:*",
|
"@stock-bot/types": "workspace:*",
|
||||||
"@tanstack/react-table": "^8.21.3",
|
"@tanstack/react-table": "^8.21.3",
|
||||||
|
|
|
||||||
|
|
@ -78,6 +78,36 @@ export default [
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|
||||||
|
// Pure calculation modules may not obtain hidden input or perform global I/O.
|
||||||
|
{
|
||||||
|
files: ['libs/calculations/src/**/*.ts'],
|
||||||
|
rules: {
|
||||||
|
'no-restricted-globals': [
|
||||||
|
'error',
|
||||||
|
'fetch',
|
||||||
|
'Bun',
|
||||||
|
'process',
|
||||||
|
'console',
|
||||||
|
'WebSocket',
|
||||||
|
'Worker',
|
||||||
|
'setTimeout',
|
||||||
|
'setInterval',
|
||||||
|
],
|
||||||
|
'no-restricted-properties': [
|
||||||
|
'error',
|
||||||
|
{ object: 'Math', property: 'random', message: 'Pass deterministic input explicitly.' },
|
||||||
|
{ object: 'Date', property: 'now', message: 'Pass observation time explicitly.' },
|
||||||
|
],
|
||||||
|
'no-restricted-syntax': [
|
||||||
|
'error',
|
||||||
|
{
|
||||||
|
selector: "NewExpression[callee.name='Date'][arguments.length=0]",
|
||||||
|
message: 'Pass observation time explicitly; wall-clock input is not pure math.',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
// Handler files configuration
|
// Handler files configuration
|
||||||
{
|
{
|
||||||
files: ['**/*.handler.ts'],
|
files: ['**/*.handler.ts'],
|
||||||
|
|
|
||||||
|
|
@ -27,6 +27,12 @@ const risk = returnStatistics(returns);
|
||||||
helpers shared with the supported TypeScript strategies. SMA output index 0 belongs
|
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
|
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.
|
`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,
|
- `./market-data`: restored generic OHLCV extraction, returns, SMA, HLC/3 typical price,
|
||||||
true range, cumulative VWAP, filtering, grouping and timestamp conversion. SMA and
|
true range, cumulative VWAP, filtering, grouping and timestamp conversion. SMA and
|
||||||
returns delegate to the same core functions. VWAP is `null` until positive cumulative
|
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,
|
sma,
|
||||||
trailingMean,
|
trailingMean,
|
||||||
trailingPopulationDeviation,
|
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';
|
} from './indicators';
|
||||||
export {
|
export {
|
||||||
calculateLogReturns,
|
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,
|
trailingPopulationDeviation,
|
||||||
} from './window-statistics';
|
} from './window-statistics';
|
||||||
export { sma } from './sma';
|
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);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -126,6 +126,22 @@ describe('shared library boundaries', () => {
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('chart indicator adapters can be bundled for browsers without native or server dependencies', async () => {
|
||||||
|
const file = join(root, 'apps/stock/web-app/src/features/charts/utils/indicators.ts');
|
||||||
|
expect(runtimeImports(file).sort()).toEqual([
|
||||||
|
'@stock-bot/calculations/indicators',
|
||||||
|
'@stock-bot/calculations/market-data',
|
||||||
|
'@stock-bot/invariants',
|
||||||
|
]);
|
||||||
|
const bundle = await Bun.build({ entrypoints: [file], target: 'browser', write: false });
|
||||||
|
expect(bundle.success).toBe(true);
|
||||||
|
const code = await bundle.outputs[0]?.text();
|
||||||
|
expect(code).toBeDefined();
|
||||||
|
expect(code).not.toContain('engine.node');
|
||||||
|
expect(code).not.toContain('PostgresClient');
|
||||||
|
expect(code).not.toContain('legacy/technical-indicators');
|
||||||
|
});
|
||||||
|
|
||||||
it('library source and tests contain no disabled or backup copies', () => {
|
it('library source and tests contain no disabled or backup copies', () => {
|
||||||
const files = [...new Bun.Glob('**/*').scanSync({ cwd: join(root, 'libs') })];
|
const files = [...new Bun.Glob('**/*').scanSync({ cwd: join(root, 'libs') })];
|
||||||
const backups = files.filter(
|
const backups = files.filter(
|
||||||
|
|
|
||||||
173
test/integration/indicator-contracts.test.ts
Normal file
173
test/integration/indicator-contracts.test.ts
Normal file
|
|
@ -0,0 +1,173 @@
|
||||||
|
import { expect, test } from 'bun:test';
|
||||||
|
import { atr, ema, macd, rsi, trailingSimpleRsi } from '@stock-bot/calculations/indicators';
|
||||||
|
import { IncrementalEMA, IncrementalRSI, TechnicalIndicators } from '@stock-bot/engine';
|
||||||
|
import { MeanReversionStrategy } from '../../apps/stock/orchestrator/src/strategies/builtin/MeanReversionStrategy';
|
||||||
|
import {
|
||||||
|
calculateATR,
|
||||||
|
calculateBollingerBands,
|
||||||
|
calculateEMA,
|
||||||
|
calculateMACD,
|
||||||
|
calculateRSI,
|
||||||
|
calculateSMA,
|
||||||
|
calculateStochastic,
|
||||||
|
calculateVWAP,
|
||||||
|
CHART_INDICATOR_CONTRACT,
|
||||||
|
} from '../../apps/stock/web-app/src/features/charts/utils/indicators';
|
||||||
|
import golden from '../../libs/calculations/test/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]!, 10));
|
||||||
|
}
|
||||||
|
function candles(values: number[]) {
|
||||||
|
return values.map((value, i) => ({
|
||||||
|
time: 1700000000 + i * i * 60,
|
||||||
|
open: value,
|
||||||
|
high: value + 1,
|
||||||
|
low: value - 1,
|
||||||
|
close: value,
|
||||||
|
volume: 10,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
test('shared first-seeded EMA matches real native batch and incremental output', () => {
|
||||||
|
const native = new TechnicalIndicators();
|
||||||
|
const values = Array.from({ length: 80 }, (_, i) => 100 + Math.sin(i / 2) * 7);
|
||||||
|
for (const period of [1, 3, 14]) {
|
||||||
|
const batch = ema(values, period, { seed: 'first' });
|
||||||
|
close(batch.values, native.calculateEma(values, period));
|
||||||
|
const stream = new IncrementalEMA(period);
|
||||||
|
close(
|
||||||
|
values.map(value => stream.update(value)!),
|
||||||
|
batch.values
|
||||||
|
);
|
||||||
|
}
|
||||||
|
// The SMA seed is deliberately a separate contract parameter, not a native alias.
|
||||||
|
expect(ema(values, 3).startIndex).toBe(2);
|
||||||
|
expect(ema(values, 3, { seed: 'first' }).startIndex).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Wilder RSI matches compatible native paths; historical zero-loss differences stay explicit', () => {
|
||||||
|
const native = new TechnicalIndicators();
|
||||||
|
const { prices, period } = golden.rsi;
|
||||||
|
close(rsi(prices, period).values, native.calculateRsi(prices, period));
|
||||||
|
const stream = new IncrementalRSI(period);
|
||||||
|
const streaming = prices
|
||||||
|
.map(value => stream.update(value))
|
||||||
|
.filter(value => value !== null && value !== undefined);
|
||||||
|
close(streaming, rsi(prices, period).values);
|
||||||
|
const rising = [1, 2, 3, 4, 5];
|
||||||
|
expect(native.calculateRsi(rising, 3)[0]).toBeCloseTo(100 - 100 / 101, 12);
|
||||||
|
expect(rsi(rising, 3).values).toEqual([100, 100]);
|
||||||
|
expect(rsi([1, 1, 1, 1], 3).values).toEqual([50]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('previous-close ATR and first-seeded MACD match their real native variants', () => {
|
||||||
|
const native = new TechnicalIndicators();
|
||||||
|
const { bars, period } = golden.atr;
|
||||||
|
close(
|
||||||
|
atr(bars, period).values,
|
||||||
|
native.calculateAtr(
|
||||||
|
bars.map(bar => bar.high),
|
||||||
|
bars.map(bar => bar.low),
|
||||||
|
bars.map(bar => bar.close),
|
||||||
|
period
|
||||||
|
)
|
||||||
|
);
|
||||||
|
const prices = Array.from({ length: 40 }, (_, i) => 10 + Math.sin(i));
|
||||||
|
const expected = JSON.parse(native.calculateMacd(prices, 3, 7, 4));
|
||||||
|
const result = macd(prices, 3, 7, 4, { seed: 'first' });
|
||||||
|
close(result.macd.values, expected.macd);
|
||||||
|
close(result.signal.values, expected.signal);
|
||||||
|
close(result.histogram.values, expected.histogram);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('mean-reversion/v2 keeps exact rolling-RSI arithmetic and checkpoint identity', () => {
|
||||||
|
function priorV2(values: number[], period: number): number {
|
||||||
|
if (values.length < period + 1) {
|
||||||
|
return 50;
|
||||||
|
}
|
||||||
|
let gain = 0,
|
||||||
|
loss = 0;
|
||||||
|
for (let i = 1; i <= period; i++) {
|
||||||
|
const change = values[values.length - i]! - values[values.length - i - 1]!;
|
||||||
|
if (change > 0) {
|
||||||
|
gain += change;
|
||||||
|
} else {
|
||||||
|
loss += Math.abs(change);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const averageGain = gain / period,
|
||||||
|
averageLoss = loss / period;
|
||||||
|
if (averageLoss === 0) {
|
||||||
|
return 100;
|
||||||
|
}
|
||||||
|
return 100 - 100 / (1 + averageGain / averageLoss);
|
||||||
|
}
|
||||||
|
const values = Array.from({ length: 80 }, (_, i) => 100 + Math.sin(i / 2) * 8 + i / 10);
|
||||||
|
for (const period of [1, 2, 3, 14]) {
|
||||||
|
for (let end = 0; end <= values.length; end++) {
|
||||||
|
const prefix = values.slice(0, end);
|
||||||
|
expect(trailingSimpleRsi(prefix, period, 100) ?? 50).toBe(priorV2(prefix, period));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
expect(trailingSimpleRsi([1, 1, 1, 1], 3, 100)).toBe(100);
|
||||||
|
expect(MeanReversionStrategy.prototype.getCheckpointVersion()).toBe('mean-reversion/v2');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('chart adapters map real source timestamps, warm-up and final rounding only', () => {
|
||||||
|
const data = candles(golden.ema.prices);
|
||||||
|
const original = structuredClone(data);
|
||||||
|
expect(CHART_INDICATOR_CONTRACT).toBe('chart-indicators/v2');
|
||||||
|
expect(calculateSMA(data, 3).map(point => point.time)).toEqual(
|
||||||
|
data.slice(2).map(bar => bar.time)
|
||||||
|
);
|
||||||
|
expect(calculateEMA(data, 3)).toEqual(
|
||||||
|
data.slice(2).map((bar, i) => ({ time: bar.time, value: golden.ema.smaSeed[i] }))
|
||||||
|
);
|
||||||
|
const rs = candles(golden.rsi.prices);
|
||||||
|
expect(calculateRSI(rs, 3)).toEqual(
|
||||||
|
rs
|
||||||
|
.slice(3)
|
||||||
|
.map((bar, i) => ({ time: bar.time, value: Number(golden.rsi.values[i]!.toFixed(2)) }))
|
||||||
|
);
|
||||||
|
const ranges = golden.atr.bars.map((bar, i) => ({
|
||||||
|
...bar,
|
||||||
|
open: bar.close,
|
||||||
|
time: 1000 + i * 900,
|
||||||
|
}));
|
||||||
|
expect(calculateATR(ranges, 3).map(point => point.time)).toEqual(
|
||||||
|
ranges.slice(3).map(bar => bar.time)
|
||||||
|
);
|
||||||
|
expect(calculateEMA(data.slice(0, 2), 3)).toEqual([]);
|
||||||
|
expect(calculateRSI(rs.slice(0, 3), 3)).toEqual([]);
|
||||||
|
expect(calculateATR(ranges.slice(0, 3), 3)).toEqual([]);
|
||||||
|
expect(data).toEqual(original);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('corrected chart RSI has no duplicated seed delta, synthetic 99 RSI, or flat NaN', () => {
|
||||||
|
expect(calculateRSI(candles([1, 2, 3, 4]), 3)[0]?.value).toBe(100);
|
||||||
|
expect(calculateRSI(candles([1, 1, 1, 1]), 3)[0]?.value).toBe(50);
|
||||||
|
expect(calculateRSI(candles(golden.rsi.prices), 3)[0]?.value).toBe(75);
|
||||||
|
expect(
|
||||||
|
calculateStochastic(
|
||||||
|
Array(4).fill({ time: 1, open: 1, high: 1, low: 1, close: 1 }),
|
||||||
|
2,
|
||||||
|
1,
|
||||||
|
1
|
||||||
|
).k.every(point => point.value === 50)
|
||||||
|
).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('chart compositions do not round intermediates, and missing volume produces no fake VWAP', () => {
|
||||||
|
const bands = calculateBollingerBands(candles([0.011, 0.019, 0.021]), 2, 2);
|
||||||
|
expect(bands.lower[0]?.value).toBe(0.01);
|
||||||
|
const result = calculateMACD(candles([1.01, 1.03, 1.02, 1.07, 1.03]), 2, 3, 2);
|
||||||
|
expect(result.signalLine[0]?.value).toBe(0);
|
||||||
|
const data = candles([10, 11, 12]);
|
||||||
|
data[0]!.volume = 0;
|
||||||
|
expect(calculateVWAP(data)[0]?.time).toBe(data[1]?.time);
|
||||||
|
expect(calculateVWAP(data.map(bar => ({ ...bar, volume: undefined })))).toEqual([]);
|
||||||
|
expect(() => calculateEMA(candles([1, 2]), 0)).toThrow();
|
||||||
|
expect(() => calculateRSI(candles([1, NaN, 3, 4]), 3)).toThrow();
|
||||||
|
});
|
||||||
Loading…
Add table
Add a link
Reference in a new issue