# 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. ```ts 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](docs/indicators.md) for exact alignment, numerical changes, native differences, snapshot guarantees and strategy-version compatibility. - `./market-data`: restored generic OHLCV extraction, returns, SMA, HLC/3 typical price, true range, cumulative VWAP, filtering, grouping and timestamp conversion. SMA and returns delegate to the same core functions. VWAP is `null` until positive cumulative 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`) is 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): ```sh 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`. 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 ```sh 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.