stock-bot/libs/calculations/README.md

124 lines
6.6 KiB
Markdown
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.

# 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`)
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`), plus pure Event-Study math (`eventDayIndex`,
`eventStudy`, `EventStudyError`, `DEFAULT_EVENT_PRE_DAYS`, `DEFAULT_EVENT_POST_DAYS`,
`DEFAULT_EVENT_MIN_EVENTS`) with date-clustered Newey-West significance, R-7 CAR
percentile fans, and a sign-preserving post-2023 recency gate, 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):
```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`.
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):
```sh
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`.
Run the fixed-seed Event Study benchmark (`2,000` entities × `5,040` sessions,
`200,000` events, window `-10..+20`, covering full `eventStudy` with benchmark-adjusted
AAR/CAAR, R-7 CAR percentile fans, date-clustered Newey-West HAC, and recency gate):
```sh
bun run test:calculations
```
Observed locally on Bun 1.2.16 (2026-11-28, seed `20260404`):
```text
[event-study benchmark] events=200000 window=-10..+20 elapsedMs=608.09 events/s=328896
```
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.