- Remove ~44k LOC of dead code, legacy v1 TS simulator/strategy stack, event-bus, analytics FastAPI prototype, legacy calculation archives, and unused deps (data-ingestion provider API handlers untouched) - Extract @stock-bot/di/http-security and isolate @stock-bot/browser to data-ingestion via ServiceContainerBuilder.withRegistrations() - Harden @stock-bot/mongodb read-only proxies, flatten @stock-bot/postgres with unified master+research migrations, and fix @stock-bot/config EnvLoader, ServiceApplication worker lifecycle, NamespacedCache.clear(), and BatchProcessor error propagation - Flatten workspace root (remove apps/stock/package.json) and collapse orchestrator re-export shims - Pin all Docker image versions, add shm_size/nofile/RAM caps and docker-compose.quant.yml, fix 05-add-visible-column.sql view recreation, and decouple dev/QA Compose project names for side-by-side execution - Update PLATFORM-PLAN, DATA-CONTRACTS (bars_1m PARTITION BY MONTH, Rust bulk ETL, DuckDB limits), MILESTONES, and servers docs
75 lines
4.5 KiB
Markdown
75 lines
4.5 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, 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.
|
||
|
||
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.
|