Files

110 lines
4.3 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Тесты этапа 2: сдвинутая корреляция (src/relations.ts).
* Синтетические ряды с ЗАРАНЕЕ известным лагом: движок обязан найти, кто
* ведёт и на сколько. Запуск: npm run test (в backend/).
*/
import assert from 'node:assert/strict';
import { computeRelations } from '../src/relations.js';
import type { Candle } from '../src/types.js';
/** Детерминированный PRNG — одинаковый результат между запусками. */
function mulberry32(seed: number): () => number {
let a = seed >>> 0;
return () => {
a |= 0;
a = (a + 0x6d2b79f5) | 0;
let t = Math.imul(a ^ (a >>> 15), 1 | a);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
const DAY_MS = 86_400_000;
function candles(closes: number[], startMs: number): Candle[] {
return closes.map((close, i) => ({
time: new Date(startMs + i * DAY_MS).toISOString(),
open: close,
high: close,
low: close,
close,
volume: 0,
}));
}
/** Цены из AR(1)-доходностей: r[i] = k*r[i-1] + шум — сигнал с убывающей автокорреляцией. */
function arCloses(n: number, k: number, sigma: number, seed: number): number[] {
const rnd = mulberry32(seed);
const closes: number[] = [100];
let r = 0;
for (let i = 1; i < n; i++) {
r = k * r + (rnd() * 2 - 1) * sigma;
closes.push(closes[i - 1]! * Math.exp(r));
}
return closes;
}
let passed = 0;
function test(name: string, fn: () => void): void {
fn();
passed += 1;
console.log(` ok — ${name}`);
}
test('A ведёт B на 3 шага: bestLag=+3, leader=A', () => {
const closesA = arCloses(200, 0.5, 0.02, 42);
// B повторяет A с опозданием 3: closesB[i] = closesA[i-3]
const closesB = closesA.map((_, i) => closesA[Math.max(0, i - 3)]!);
const res = computeRelations(candles(closesA, 0), candles(closesB, 0), 15);
assert.equal(res.ok, true);
assert.equal(res.bestLag, 3);
assert.equal(res.leader, 'A');
assert.ok(Math.abs((res.bestCorr ?? 0) - 1) < 5e-3); // на идеальном сдвиге corr ~ 1
assert.ok(res.pearson !== null && res.pearson < 0.99); // без сдвига связь слабее
});
test('B ведёт A на 2 шага: bestLag=-2, leader=B', () => {
const closesB = arCloses(200, 0.5, 0.02, 7);
const closesA = closesB.map((_, i) => closesB[Math.max(0, i - 2)]!);
const res = computeRelations(candles(closesA, 0), candles(closesB, 0), 15);
assert.equal(res.bestLag, -2);
assert.equal(res.leader, 'B');
});
test('синхронное движение: bestLag=0, лидера нет', () => {
const closesA = arCloses(200, 0.5, 0.02, 11);
const res = computeRelations(candles(closesA, 0), candles(closesA, 0), 15);
assert.equal(res.bestLag, 0);
assert.equal(res.leader, null);
assert.ok(Math.abs((res.bestCorr ?? 0) - 1) < 1e-6);
});
test('мало общих свечей -> ok=false с сообщением', () => {
const closesA = arCloses(20, 0.5, 0.02, 3);
const res = computeRelations(candles(closesA, 0), candles(closesA, 0), 15);
assert.equal(res.ok, false);
assert.ok(res.message !== undefined);
});
test('выравнивание по времени: дыры в одном ряду не ломают расчёт', () => {
const closesA = arCloses(200, 0.5, 0.02, 5);
const full = candles(closesA, 0);
const sparse = full.filter((_, i) => i % 5 !== 3); // выкинули каждый пятый день
const res = computeRelations(full, sparse, 15);
assert.equal(res.ok, true);
assert.equal(res.points, sparse.length);
assert.equal(res.bestLag, 0); // ряды одинаковы на общих датах
assert.equal(res.leader, null);
});
test('seriesBShifted: длина меньше на |lag|, значения сдвинуты', () => {
const closesA = arCloses(200, 0.5, 0.02, 42);
const closesB = closesA.map((_, i) => closesA[Math.max(0, i - 3)]!);
const res = computeRelations(candles(closesA, 0), candles(closesB, 0), 15);
assert.ok(res.seriesBShifted);
assert.equal(res.seriesBShifted!.length, res.seriesB.length - 3);
assert.equal(res.seriesBShifted![0]!.value, res.seriesB[3]!.value);
});
console.log(`\n${passed}/6 тестов отношений пройдено`);