102 lines
5.7 KiB
Markdown
102 lines
5.7 KiB
Markdown
# 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, nonpositive ending capital or unrepresentable
|
|
output. Other nonrepresentable outputs throw. Annualization requires an explicit
|
|
positive number of periods/year; return statistics below intentionally use daily data.
|
|
- `./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.
|
|
Daily statistics use 252 periods/year, UTC grouping, sample volatility and explicit
|
|
`null` for undefined ratios. 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.
|
|
|
|
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.
|
|
|
|
## Preserved legacy APIs
|
|
|
|
All **105 previously active calculation functions** are retained, not deleted, behind
|
|
one explicit opt-in entry:
|
|
|
|
```ts
|
|
import { basic, indicators, performance, risk } from '@stock-bot/calculations/legacy';
|
|
```
|
|
|
|
The four original modules are preserved with unchanged executable bodies and their
|
|
original function names. These are migration/research APIs, **not newly validated
|
|
production APIs**. Known concerns include zero/Infinity fallbacks, incompatible ratio
|
|
units, different indicator seeding/smoothing, drawdown definitions and simplified
|
|
attribution/MWRR. Do not introduce these into supported stock execution. Prefer the
|
|
reviewed core, and promote additional functions with documented contracts and golden,
|
|
invalid-input, warm-up/alignment and batch/incremental parity tests as applicable.
|
|
|
|
[migration-audit.json](migration-audit.json) inventories every original exported function,
|
|
its disposition and source provenance (`ccce401`). Regression tests verify the legacy
|
|
AST hashes and export lists; that proves preservation, not financial correctness.
|
|
|
|
## Preserved research
|
|
|
|
All seven formerly `.disabled` modules are retained as source-verified Markdown research
|
|
snapshots in [research/](research/README.md), including their unique indicators. They
|
|
were never active package exports and are not activated by this change. Some contain
|
|
placeholders, unseeded randomness or partial numerical methods. They are not compiled,
|
|
published or importable code. Extract and validate useful functions before promotion.
|
|
|
|
The empty `analyzePortfolio` convenience placeholder was not restored. Removing a
|
|
placeholder API does not remove the real portfolio/research implementations above.
|
|
|
|
## 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,
|
|
and prevent supported app code from loading the legacy/research tier.
|