stock-bot/libs/calculations
2026-11-28 01:59:50 -05:00
..
docs Add versioned streaming indicators and share chart calculations 2026-10-21 22:22:42 -04:00
scripts T-82: M1.4a — Pure signal analyzer math in @stock-bot/calculations: per-date IC / rank-IC, Newey-West t-stat, quantile spreads, turnover and pre/post-2023 recency gate (no I/O) 2026-11-28 01:39:16 -05:00
src T-82: M1.4a — Pure signal analyzer math in @stock-bot/calculations: per-date IC / rank-IC, Newey-West t-stat, quantile spreads, turnover and pre/post-2023 recency gate (no I/O) 2026-11-28 01:53:32 -05:00
test T-82: tests 2026-11-28 01:59:50 -05:00
package.json refactor: pre-M0 cleanup, core library hardening, and isolated dev/QA Docker stack 2026-11-27 00:11:50 -05:00
README.md T-82: M1.4a — Pure signal analyzer math in @stock-bot/calculations: per-date IC / rank-IC, Newey-West t-stat, quantile spreads, turnover and pre/post-2023 recency gate (no I/O) 2026-11-28 01:47:48 -05:00
tsconfig.json Extract shared calculations and preserve legacy research capabilities 2026-10-21 20:27:07 -04:00

Shared calculations

@stock-bot/calculations is a private, pure TypeScript workspace for data processing, strategy features and analytics. It requires no database, HTTP client, logger, native binding or application service container. @stock-bot/types is type-only; invariants are the only runtime workspace dependency.

import { returnStatistics } from '@stock-bot/calculations/analytics';
import { sma, trailingMean } from '@stock-bot/calculations/indicators';
import { calculateVWAP, extractCloses } from '@stock-bot/calculations/market-data';
import { simpleReturns } from '@stock-bot/calculations/returns';

const returns = simpleReturns([100, 110, 99]);
const movingMeans = sma([100, 110, 99], 2);
const risk = returnStatistics(returns);

Supported core

  • ./returns: simple/log returns, explicit percentage-point conversion, CAGR and annualization. Inputs must be finite. Invalid price baselines throw, not return zero. CAGR is null for zero elapsed time, negative ending capital or unrepresentable output. With positive initial capital and elapsed time, zero terminal capital has CAGR −1. Other nonrepresentable outputs throw. Annualization requires an explicit positive number of periods/year.
  • ./indicators: O(n) batch SMA plus trailing mean, population deviation and crossover 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 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 volume exists, never a fabricated price. OHLC features validate used prices/ranges; negative volume and invalid timestamps fail explicitly. Time filters retain the old inclusive [start, end] contract. groupBySymbol is ticker grouping, not listing identity: partition qualified venue/instrument IDs before calculating any feature.
  • ./analytics: the existing tested fraction-based equity/drawdown, observed daily return/factor, closed-trade and performance calculations, moved from the orchestrator. returnStatistics(returns, annualRiskFree, periodsPerYear) supports an explicit frequency and nullable risk-free input; omitted arguments retain the legacy 2%/252 defaults. Null risk-free leaves target-dependent metrics unavailable while preserving independently defined volatility/tail statistics. drawdownAnalysis uses numeric timestamps without UTC grouping; equityAnalysis and legacy performance reporting retain their UTC grouping. Undefined ratios are null, sample deviation uses n−1, and downside deviation uses full-series RMS. Trade holding periods are minutes. Persisted strategy versions and execution/checkpoint behavior are unchanged. The legacy Kelly/leverage fields in performanceAnalysis remain compatibility heuristics, not optimizers. Canonical Deflated Sharpe Ratio (deflatedSharpeRatio, effectiveIndependentTrials, trialMoments, normalCdf, inverseNormalCdf, passesDsrGate, DSR_VALIDATION_GATE) and cross-sectional Signal Analysis (analyzeSignalPanel, crossSectionIc, neweyWestMeanTest, defaultNeweyWestLag, summarizeIcSeries, evaluateRecencyGate, SignalAnalysisError, DEFAULT_MIN_CROSS_SECTION, DEFAULT_QUANTILE_COUNT, RECENCY_SPLIT_DATE, RECENCY_MIN_RATIO) are exported from both ./analytics and the root entry.

Benchmark

Run the fixed-seed DSR + effective-trials benchmark (K = 500 trials × 2,520 daily observations, 124,750 pairs):

bun run libs/calculations/scripts/benchmark-deflated-sharpe.ts

Observed locally on Bun 1.2.16 (2 runs, seed 20260401): 150.18 ms (830,660 pairs/s) and 159.79 ms (780,707 pairs/s), meanCorrelation = 0.071187, nHat = 464.4776.

Run the fixed-seed Signal Analysis benchmark (5,040 dates × 3,000 names, 15,120,000 observations, covering full analyzeSignalPanel with IC, Newey-West HAC, quintile spreads, turnover, and recency gate):

bun run libs/calculations/scripts/benchmark-signal-analysis.ts

Observed locally on Bun 1.2.16 (2 runs, seed 20260402): 1,779.96 ms (2,832 dates/s, 8,494,557 observations/s) and 1,809.95 ms (2,785 dates/s, 8,353,819 observations/s), meanRankIc = 0.057294, rankIcTStat = 218.5078, spreadMean = 0.003369, recencyGatePassed = true.

The root entry exports the supported returns, indicators and market-data helpers. Use subpaths to avoid loading unrelated math. Shared domain types remain owned by @stock-bot/types; HTTP/date/proxy helpers remain in @stock-bot/utils.

The application-level PerformanceAnalyzer remains a reporting facade. The native TechnicalAnalysis adapter still supports its existing Rust indicators; neither is a dependency of this library. Native and legacy indicators can have different seeding, smoothing and warm-up conventions: they are not interchangeable without parity tests.

Verify

bun run test:calculations
bun run test:integration
bun run check

The root gate builds/type-checks this workspace and runs its regressions. The integration suite retains native/window parity, strategy recovery and analytics golden fixtures. Architecture checks keep infrastructure and application adapters out of the library.