Extract shared calculations and preserve legacy research capabilities

This commit is contained in:
Boki 2026-10-21 20:27:07 -04:00
parent ccce401f72
commit 7827220b9b
82 changed files with 3099 additions and 1994 deletions

View file

@ -19,16 +19,18 @@ bun run check
The root build selects every buildable leaf workspace, including all stock services and the
native engine. `bun run build --dry=json` shows the actual Turbo task plan.
| Command | Scope |
| -------------------------- | ------------------------------------------------------------------------------------------------------- |
| `bun run build:libs` | Build shared libraries in dependency order |
| `bun run build --clean` | Force every workspace build without cached results |
| `bun run typecheck` | Check library, stock application, and tool source directly |
| `bun run test:contracts` | Compile positive and negative service-contract assertions |
| `bun run test:tooling` | Run workspace and service-consumer regression tests without infrastructure |
| `bun run test:integration` | Replay fixed prices through ingestion, storage, and the real native backtest engine |
| `bun run lint:check` | Lint stock applications, libraries, and tools with zero warnings allowed |
| `bun run check` | Run build, type checking, contract tests, tooling/integration tests, and lint; report every failed gate |
| Command | Scope |
| --------------------------- | ---------------------------------------------------------------------------------------------------------- |
| `bun run build:libs` | Build shared libraries in dependency order |
| `bun run build --clean` | Force every workspace build without cached results |
| `bun run typecheck` | Check library, stock application, and tool source directly |
| `bun run test:contracts` | Compile positive and negative service-contract assertions |
| `bun run test:tooling` | Run workspace and service-consumer regression tests without infrastructure |
| `bun run test:utils` | Test HTTP/date/proxy helpers and their handler HTTP consumer without infrastructure |
| `bun run test:calculations` | Test shared math, OHLCV transforms, legacy capability preservation and research snapshots |
| `bun run test:integration` | Replay fixed prices through ingestion, storage, and the real native backtest engine |
| `bun run lint:check` | Lint stock applications, libraries, and tools with zero warnings allowed |
| `bun run check` | Run build, type checking, contracts, tooling, utilities, calculations, integration, native tests, and lint |
`check` exits nonzero if any gate fails. Type/lint errors are not suppressed or baselined.
The larger existing `bun run test` suite is separate:
@ -40,6 +42,35 @@ changing Rust APIs. TensorFlow is loaded only when starting the optional ML stra
Its TypeScript dependency is present for checking; using ML also requires installing its
platform-specific native binding. Dependency install scripts were not enabled for verification.
## Shared calculation and utility boundaries
`@stock-bot/calculations` owns pure reusable math for strategies, data processing and
feature engineering. Its supported subpaths expose reviewed returns, indicators, OHLCV
transforms and the previously tested orchestrator analytics/window math. The orchestrator
now consumes that library; no database, native binding, HTTP or application service is
required to import it. Existing strategy checkpoint versions and financial execution
behavior are unchanged by this relocation.
All 105 formerly active financial calculation functions remain available behind the
explicit `@stock-bot/calculations/legacy` namespace, with unchanged executable bodies.
This is preservation, not a production-correctness endorsement. All seven previously
disabled prototypes, including unique additional indicators, survive as non-executable
source-verified research snapshots. See [the calculation contract](libs/calculations/README.md)
for supported units, undefined values, alignment and the review/promotion path.
`@stock-bot/utils` retains HTTP/user-agent, proxy/sleep and validated UTC date/weekday
helpers through explicit capability subpaths. Deprecated `dateUtils` names are aliases,
not an exchange holiday/session calendar. Assertions belong to `@stock-bot/invariants`,
and domain types to `@stock-bot/types`. The coverage CLI no longer declares an unused
utility dependency, and unused `simple-statistics` is removed.
Only empty placeholder/redundant entry points remain removed; old numerical and Redis
test sources are retained as explicit legacy/research references rather than runnable
backups or claimed passing coverage. [The cleanup audit](docs/cleanup-audit.md) accounts
for every removal in this batch. [The utility contract](libs/utils/README.md) documents
the restored helpers and migration notes. Architecture tests enforce the ownership and
dependency boundaries without forbidding useful shared domain libraries.
## Service contracts
`@stock-bot/types` contains independent domain, job, and handler types.
@ -124,7 +155,7 @@ while native SMA uses 100 shares. Native mean reversion, momentum and pairs reta
accepts configurable lookback/trend/RSI windows, entry/exit thresholds and notional-volume
filter; its optional `quantity` is also shares. Do not transfer backend-only parameters blindly.
`indicators/window-statistics.ts` shares slice-free trailing mean, population deviation
`@stock-bot/calculations/indicators` shares slice-free trailing mean, population deviation
and crossover calculations across TypeScript strategies. A crossover requires `slowPeriod + 1`
bars, including a complete previous window; missing warm-up is not a synthetic zero average.
Tests compare the scalar math with real Rust batch/incremental indicators and exercise

View file

@ -1,4 +1,4 @@
import { getRandomUserAgent } from '@stock-bot/utils';
import { getRandomUserAgent } from '@stock-bot/utils/user-agent';
import type { CeoHandler } from '../ceo.handler';
export async function getChannels(this: CeoHandler, payload: number | undefined): Promise<unknown> {

View file

@ -1,4 +1,4 @@
import { getRandomUserAgent } from '@stock-bot/utils';
import { getRandomUserAgent } from '@stock-bot/utils/user-agent';
import type { CeoHandler } from '../ceo.handler';
export async function getPosts(

View file

@ -1,4 +1,4 @@
import { getRandomUserAgent } from '@stock-bot/utils';
import { getRandomUserAgent } from '@stock-bot/utils/user-agent';
import type { CeoHandler } from '../ceo.handler';
export async function getShorts(

View file

@ -1,4 +1,4 @@
import { at } from '@stock-bot/utils';
import { at } from '@stock-bot/invariants';
import type { EodHandler } from '../eod.handler';
import { EOD_CONFIG } from '../shared';

View file

@ -1,4 +1,4 @@
import { at } from '@stock-bot/utils';
import { at } from '@stock-bot/invariants';
import type { EodHandler } from '../eod.handler';
import { EOD_CONFIG } from '../shared';

View file

@ -2,7 +2,7 @@
* Shared configuration for QM operations
*/
import { getRandomUserAgent } from "@stock-bot/utils";
import { getRandomUserAgent } from "@stock-bot/utils/user-agent";
// QM Session IDs for different endpoints
export const QM_SESSION_IDS = {
@ -141,4 +141,4 @@ export function getWeekEnd(dateInput: Date | string): Date {
// Set to end of day
date.setHours(23, 59, 59, 999);
return date;
}
}

View file

@ -1,5 +1,5 @@
import * as cheerio from 'cheerio';
import { getRandomUserAgent } from '@stock-bot/utils';
import { getRandomUserAgent } from '@stock-bot/utils/user-agent';
import { TE_CONFIG } from '../shared/config';
import type { TeHandler } from '../te.handler';

View file

@ -1,5 +1,5 @@
import * as cheerio from 'cheerio';
import { getRandomUserAgent } from '@stock-bot/utils';
import { getRandomUserAgent } from '@stock-bot/utils/user-agent';
import { TE_CONFIG } from '../shared/config';
import type { TeHandler } from '../te.handler';

View file

@ -1,5 +1,6 @@
import * as cheerio from 'cheerio';
import { at, getRandomUserAgent } from '@stock-bot/utils';
import { at } from '@stock-bot/invariants';
import { getRandomUserAgent } from '@stock-bot/utils/user-agent';
import { TE_CONFIG } from '../shared/config';
import type { TeHandler } from '../te.handler';

View file

@ -1,4 +1,4 @@
import { at } from '@stock-bot/utils';
import { at } from '@stock-bot/invariants';
import { TRADINGVIEW_CONFIG } from '../shared/config';
import { type TradingViewExchange } from '../shared/types';
import type { TradingViewHandler } from '../tradingview.handler';

View file

@ -3,7 +3,7 @@ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync } from 'fs';
import { join } from 'path';
import * as cheerio from 'cheerio';
import { defined } from '@stock-bot/invariants';
import { getRandomUserAgent } from '@stock-bot/utils';
import { getRandomUserAgent } from '@stock-bot/utils/user-agent';
import type { TtHandler } from '../tt.handler';
const BASE_URL = 'https://www.turtletrader.com';

View file

@ -4,7 +4,7 @@ import type { Document } from 'mongodb';
*/
import type { Logger, MongoDBClient } from '@stock-bot/services';
import { at } from '@stock-bot/utils';
import { at } from '@stock-bot/invariants';
import { BaseOperationProvider } from './BaseOperationProvider';
import { OperationTracker } from './OperationTracker';
import type {

View file

@ -4,7 +4,7 @@ import { MongoServerError, type Document, type Filter } from 'mongodb';
*/
import type { Logger, MongoDBClient } from '@stock-bot/services';
import { at } from '@stock-bot/utils';
import { at } from '@stock-bot/invariants';
import type { BaseOperationProvider } from './BaseOperationProvider';
import type {
BulkOperationUpdate,

View file

@ -51,7 +51,7 @@ still applies; this layout cleanup introduces no additional version change.
2. Validate configuration at construction and inactive edits. Use explicit units, finite values
and bounded periods. Existing built-in contracts reject unsupported keys instead of ignoring them.
3. Implement bounded per-instrument indicator state in `updateIndicators` and return a
`Signal | null` from `generateSignal`. Reuse `indicators/window-statistics.ts` for trailing
`Signal | null` from `generateSignal`. Reuse `@stock-bot/calculations/indicators` for trailing
scalar SMA/deviation/crossovers, or the documented native indicator wrapper for other math.
4. For paper execution, provide a version string and complete finite-JSON capture/restore
contract for custom state. Version changes and changed configurations require deliberate

View file

@ -5,7 +5,7 @@ values; they do not own cash, positions, order submission, account risk or recov
## TypeScript trailing-window math
`src/indicators/window-statistics.ts` supplies the scalar operations used by the supported
`@stock-bot/calculations/indicators` supplies the scalar operations used by the supported
TypeScript SMA and mean-reversion strategies:
```ts
@ -13,7 +13,7 @@ import {
movingAverageCrossover,
trailingMean,
trailingPopulationDeviation,
} from '../src/indicators/window-statistics';
} from '@stock-bot/calculations/indicators';
const prices = [3, 2, 1, 4];
const mean = trailingMean(prices, 3);

View file

@ -15,6 +15,7 @@
"build:rust": "cd ../engine && cargo build --release && napi build --platform --release"
},
"dependencies": {
"@stock-bot/calculations": "workspace:*",
"decimal.js-light": "2.5.1",
"@stock-bot/engine": "*",
"@stock-bot/cache": "*",
@ -25,14 +26,12 @@
"@stock-bot/queue": "*",
"@stock-bot/shutdown": "*",
"@stock-bot/stock-config": "*",
"@stock-bot/utils": "*",
"hono": "^4.0.0",
"socket.io": "^4.7.2",
"socket.io-client": "^4.7.2",
"zod": "^3.22.0",
"uuid": "^9.0.0",
"axios": "^1.6.0",
"simple-statistics": "^7.8.3",
"@stock-bot/services": "workspace:*",
"@stock-bot/mongodb": "workspace:*",
"@stock-bot/postgres": "workspace:*",

View file

@ -1,6 +1,10 @@
import { finite, type EquityPoint } from './equity';
import { formatStatistic, performanceAnalysis } from './performance';
import { factorStatistics } from './return-statistics';
import {
factorStatistics,
finite,
formatStatistic,
performanceAnalysis,
type EquityPoint,
} from '@stock-bot/calculations/analytics';
export interface Trade {
entryTime: Date;

View file

@ -1,5 +1,5 @@
import { getLogger } from '@stock-bot/logger';
import { at } from '@stock-bot/utils';
import { at } from '@stock-bot/invariants';
import {
type Bar,
type MarketData,

View file

@ -1,4 +1,4 @@
import { formatStatistic } from '../analytics/performance';
import { formatStatistic } from '@stock-bot/calculations/analytics';
import type { PerformanceMetrics } from '../analytics/PerformanceAnalyzer';
import type { ClosedTrade } from './native-result';

View file

@ -4,7 +4,7 @@ import {
IncrementalSMA,
TechnicalIndicators,
} from '@stock-bot/engine';
import { at } from '@stock-bot/utils';
import { at } from '@stock-bot/invariants';
export interface MacdResult {
macd: number[];

View file

@ -3,7 +3,7 @@ import { at, defined } from '@stock-bot/invariants';
import { getLogger } from '@stock-bot/logger';
import type { MeanReversionParameters } from '../../contracts/strategies';
import type { ModeManager } from '../../core/ModeManager';
import { trailingMean, trailingPopulationDeviation } from '../../indicators/window-statistics';
import { trailingMean, trailingPopulationDeviation } from '@stock-bot/calculations/indicators';
import type { ExecutionService } from '../../services/ExecutionService';
import type { StrategyConfig } from '../../types';
import { type MarketData } from '../../types';

View file

@ -2,7 +2,7 @@ import { defined } from '@stock-bot/invariants';
import { getLogger } from '@stock-bot/logger';
import type { SmaParameters } from '../../contracts/strategies';
import type { ModeManager } from '../../core/ModeManager';
import { movingAverageCrossover } from '../../indicators/window-statistics';
import { movingAverageCrossover } from '@stock-bot/calculations/indicators';
import type { ExecutionService, StrategyFill } from '../../services/ExecutionService';
import type { StrategyConfig } from '../../types';
import { type MarketData } from '../../types';

View file

@ -1,7 +1,6 @@
import type * as tf from '@tensorflow/tfjs-node';
import { defined } from '@stock-bot/invariants';
import { at, defined } from '@stock-bot/invariants';
import { getLogger } from '@stock-bot/logger';
import { at } from '@stock-bot/utils';
import { TechnicalAnalysis } from '../../indicators/TechnicalAnalysis';
import type { StrategyConfig } from '../../types';
import { type MarketData } from '../../types';

View file

@ -126,6 +126,7 @@
"version": "0.1.0",
"dependencies": {
"@stock-bot/cache": "*",
"@stock-bot/calculations": "workspace:*",
"@stock-bot/config": "*",
"@stock-bot/di": "*",
"@stock-bot/engine": "*",
@ -140,11 +141,9 @@
"@stock-bot/shutdown": "*",
"@stock-bot/stock-config": "*",
"@stock-bot/types": "workspace:*",
"@stock-bot/utils": "*",
"axios": "^1.6.0",
"decimal.js-light": "2.5.1",
"hono": "^4.0.0",
"simple-statistics": "^7.8.3",
"socket.io": "^4.7.2",
"socket.io-client": "^4.7.2",
"uuid": "^9.0.0",
@ -223,6 +222,18 @@
"vite": "^4.4.5",
},
},
"libs/calculations": {
"name": "@stock-bot/calculations",
"version": "1.0.0",
"dependencies": {
"@stock-bot/invariants": "workspace:*",
"@stock-bot/types": "workspace:*",
},
"devDependencies": {
"bun-types": "^1.2.15",
"typescript": "^5.3.0",
},
},
"libs/core/cache": {
"name": "@stock-bot/cache",
"version": "1.0.0",
@ -483,11 +494,8 @@
"name": "@stock-bot/utils",
"version": "1.0.0",
"dependencies": {
"@stock-bot/cache": "workspace:*",
"@stock-bot/config": "workspace:*",
"@stock-bot/invariants": "workspace:*",
"@stock-bot/logger": "workspace:*",
"@stock-bot/types": "workspace:*",
},
"devDependencies": {
"@types/node": "^20.11.0",
@ -503,7 +511,6 @@
},
"dependencies": {
"@stock-bot/invariants": "workspace:*",
"@stock-bot/utils": "workspace:*",
"chalk": "^5.3.0",
"commander": "^11.1.0",
"glob": "^10.3.10",
@ -953,6 +960,8 @@
"@stock-bot/cache": ["@stock-bot/cache@workspace:libs/core/cache"],
"@stock-bot/calculations": ["@stock-bot/calculations@workspace:libs/calculations"],
"@stock-bot/config": ["@stock-bot/config@workspace:libs/core/config"],
"@stock-bot/coverage-cli": ["@stock-bot/coverage-cli@workspace:tools/coverage-cli"],
@ -2431,8 +2440,6 @@
"simple-oauth2": ["simple-oauth2@5.1.0", "", { "dependencies": { "@hapi/hoek": "^11.0.4", "@hapi/wreck": "^18.0.0", "debug": "^4.3.4", "joi": "^17.6.4" } }, "sha512-gWDa38Ccm4MwlG5U7AlcJxPv3lvr80dU7ARJWrGdgvOKyzSj1gr3GBPN1rABTedAYvC/LsGYoFuFxwDBPtGEbw=="],
"simple-statistics": ["simple-statistics@7.8.8", "", {}, "sha512-CUtP0+uZbcbsFpqEyvNDYjJCl+612fNgjT8GaVuvMG7tBuJg8gXGpsP5M7X658zy0IcepWOZ6nPBu1Qb9ezA1w=="],
"slash": ["slash@3.0.0", "", {}, "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q=="],
"slice-ansi": ["slice-ansi@4.0.0", "", { "dependencies": { "ansi-styles": "^4.0.0", "astral-regex": "^2.0.0", "is-fullwidth-code-point": "^3.0.0" } }, "sha512-qMCMfhY040cVHT43K9BFygqYbUPFZKHOg7K73mtTWJRb8pyP3fzf4Ixd5SzdEJQ6MRUg/WBnOLxghZtKKurENQ=="],

50
docs/cleanup-audit.md Normal file
View file

@ -0,0 +1,50 @@
# Shared-library cleanup: preservation and removal audit
This records the shared-library cleanup following `ccce401`. It does not
claim to audit every deletion from the earlier execution/strategy refactors. The first
pass inferred that no current imports meant no future value; that was too broad for a
trading/feature-engineering repository. This revision separates capabilities by ownership
and readiness instead of deleting them on usage alone.
| Previously removed item | Current disposition |
| ------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Active basic calculations, technical indicators, risk and performance modules | All 105 exported functions preserved in `libs/calculations/src/legacy/`, with original executable bodies. Explicit `@stock-bot/calculations/legacy` entry; not endorsed as reviewed core. |
| Tested orchestrator equity/return/trade/performance and window math | Moved into supported `@stock-bot/calculations/analytics` and `/indicators`; report/strategy consumers migrated. No strategy checkpoint/version changes. |
| Generic OHLCV extraction, features, grouping/filtering and timestamps | All 13 helpers restored to `@stock-bot/calculations/market-data`. SMA/return formulas delegate to reviewed core; invalid-input, VWAP and grouping behavior hardened as documented. |
| Seven `.disabled` math modules | Full original sources preserved as verified Markdown research snapshots, including unique indicators and numerical prototypes. Not activated or silently labeled production-ready. |
| `POSITION_SIZING_FIXES.md` | Preserved as historical research notes with an explicit warning that its correctness/production claims were not independently verified. |
| Proxy URL and sleep helpers | Restored to `@stock-bot/utils/common` and named root exports. |
| Date helpers | Restored to `@stock-bot/utils/dates`: validated UTC weekday/date functions; old `dateUtils` names retained as deprecated aliases. Not an exchange/holiday calendar. UTC semantics replace the old environment-dependent local calendar arithmetic. |
| `utils` assertion facade | Remains removed. `at`/`defined` are unchanged in `@stock-bot/invariants`; all consumers import the actual owner. This removes a duplicate entry point, not the functionality. |
| Domain-type re-exports through the calculation barrel | Domain types remain unchanged in `@stock-bot/types`; callers import the owner, rather than maintaining another re-export layer. |
| Empty `analyzePortfolio` API | Remains removed: it returned empty objects and implemented no calculation. Real legacy/research portfolio functions are preserved above. |
| Old generic utility test file | Its 21 existing cases were split into 13 market-data tests and 8 common/date tests at the owning packages, with UTC assertions and new boundary tests. No executed behavior coverage was discarded merely for being unused by apps. |
| `connection-manager.test.ts.old` and `redis-cache.test.ts.old` | Remain removed as `.old` files; full source/scenarios preserved in cache test references. These were not run by the test runner. They contain 27 and 47 cases, respectively, and are not all equivalent to the active tests. Some target absent APIs; the connection-manager suite is skipped and has broken mock names. No passing coverage is claimed. |
| Old handler-registry singleton implementation | Remains removed. The metadata/configuration/service/scheduling registry lives in `@stock-bot/handler-registry`; no imports used the `.old` singleton. Reintroducing it would create another registry authority. |
| `simple-statistics`, unused utility dependencies/references in orchestrator/coverage CLI, and config/cache/type dependencies in general utilities | Remain removed. No live imports required them. The orchestrator now declares the actual calculation workspace; the calculation package has no infrastructure/native dependencies. |
## Preservation evidence and readiness
[The calculation inventory](../libs/calculations/migration-audit.json) records every
previously exported math function, source provenance, legacy AST hashes and research
source hashes. Tests verify all 105 legacy exports and their unchanged executable bodies,
and all seven research snapshots. This proves source/capability preservation, **not**
algorithmic correctness. The reviewed core is tested separately; legacy functions can
still contain zero/Infinity fallbacks, inconsistent conventions or incomplete formulas.
[The calculation contract](../libs/calculations/README.md) specifies supported units,
warm-up/alignment, invalid-result policies and the promotion path for legacy/research
functions. [Research concerns](../libs/calculations/research/README.md) identify known
limitations before reuse. Supported stock application code cannot import the legacy
tier, and no supported math module can load it transitively.
The retired Redis test sources are retained as
[connection-manager scenarios](../libs/core/cache/test/references/connection-manager-tests.md)
and [cache scenarios](../libs/core/cache/test/references/redis-cache-tests.md). Their
valid assertions should be ported with correct public contracts and isolated fixtures;
archived source is deliberately not counted in any test totals.
This revision does not change cache production code, trading/execution behavior,
persisted data, environment files or WCAG. General date helpers and OHLCV edge-case
contracts are the explicit behavior corrections noted above; old legacy math remains
unchanged and opt-in.

View file

@ -0,0 +1,96 @@
# 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.
- `./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.

View file

@ -0,0 +1,408 @@
{
"sourceCommit": "ccce401",
"modules": [
{
"original": "libs/utils/src/calculations/basic-calculations.ts",
"status": "legacy-api",
"destination": "src/legacy/basic-calculations.ts",
"sourceSha256": "366b46cd207316409bcb281b62cadac92792a97981b40fc31f65c59513149d7a",
"astSha256": "68b64fcb0a00367d16a92f8f39eef6f4856c04bdc2fa8f070252d3e4c002c506",
"functions": [
"accruedInterest",
"annualizeReturn",
"annualizeVolatility",
"bondConvexity",
"bondPrice",
"bondYield",
"cagr",
"capitalAssetPricingModel",
"cleanPrice",
"compoundInterest",
"degreeOfFinancialLeverage",
"degreeOfOperatingLeverage",
"degreeOfTotalLeverage",
"dirtyPrice",
"dividendDiscountModel",
"dollarDuration",
"economicValueAdded",
"effectiveAnnualRate",
"futureValue",
"hurdleRate",
"internalRateOfReturn",
"logReturn",
"macaulayDuration",
"modifiedDuration",
"netPresentValue",
"paybackPeriod",
"percentageChange",
"presentValue",
"simpleReturn",
"weightedAverageCostOfCapital"
]
},
{
"original": "libs/utils/src/calculations/technical-indicators.ts",
"status": "legacy-api",
"destination": "src/legacy/technical-indicators.ts",
"sourceSha256": "7792daec5b77cc5f6c5e5f8735e1d8798f9b00090e103a837e4eb187e6a4f38e",
"astSha256": "d3e84dde74368e641e6b05df0a189e8d1451c42991e6c9e30aac638f5b8d17d9",
"functions": [
"accumulationDistribution",
"adx",
"aroon",
"atr",
"balanceOfPower",
"bollingerBands",
"cci",
"chaikinMoneyFlow",
"chandeMomentumOscillator",
"coppockCurve",
"donchianChannels",
"easeOfMovement",
"ema",
"ichimoku",
"keltnerChannels",
"klingerVolumeOscillator",
"macd",
"massIndex",
"mfi",
"momentum",
"obv",
"parabolicSAR",
"pivotPoints",
"priceOscillator",
"roc",
"rsi",
"sma",
"stochastic",
"stochasticRSI",
"tema",
"trix",
"ultimateOscillator",
"vortexIndicator",
"vwma",
"williamsR",
"wma"
]
},
{
"original": "libs/utils/src/calculations/risk-metrics.ts",
"status": "legacy-api",
"destination": "src/legacy/risk-metrics.ts",
"sourceSha256": "7916a60801b0ea57b6f258d1137f41ce78b4acce91e64e54399cb5146b764220",
"astSha256": "12a636e2dd2c4768389fafedac8102967321869add25eecae2ff9271e9593139",
"functions": [
"alpha",
"annualizedVolatility",
"beta",
"calculateRiskMetrics",
"conditionalValueAtRisk",
"downsideDeviation",
"kurtosis",
"maxDrawdown",
"parametricVaR",
"riskAdjustedReturn",
"riskContribution",
"sharpeRatio",
"skewness",
"trackingError",
"treynorRatio",
"ulcerIndex",
"valueAtRisk",
"volatility"
]
},
{
"original": "libs/utils/src/calculations/performance-metrics.ts",
"status": "legacy-api",
"destination": "src/legacy/performance-metrics.ts",
"sourceSha256": "3333c4a285a94ab40ca1fb537166ef8f820431cfdd7afeb3bcf74d64d40f861f",
"astSha256": "dd39e4a594d06d752263c4ecc5e90e816c87ac32b825e6da11dcc3ffb2c707ea",
"functions": [
"analyzeDrawdowns",
"analyzeReturns",
"analyzeTradePerformance",
"calculateRollingAlpha",
"calculateRollingBeta",
"calculateRollingMetrics",
"calculateStrategyMetrics",
"calmarRatio",
"captureRatio",
"gainToPainRatio",
"informationRatio",
"jensensAlpha",
"martinRatio",
"moneyWeightedRateOfReturn",
"omegaRatio",
"sortinoRatio",
"sterlingRatio",
"strategyPerformanceAttribution",
"tailRatio",
"timeWeightedRateOfReturn",
"ulcerPerformanceIndex"
]
},
{
"original": "libs/utils/src/calculations/correlation-analysis.ts.disabled",
"status": "research-reference",
"destination": "research/correlation-analysis.md",
"sourceSha256": "5add7ae799098f19502a57a14682f2207fffe568d96584c28cc896439354b4df",
"functions": [
"autocorrelation",
"correlationMatrix",
"correlationRegimeAnalysis",
"covarianceMatrix",
"crossCorrelation",
"dccModel",
"distanceCorrelation",
"grangerCausalityTest",
"kendallTau",
"mutualInformation",
"partialCorrelation",
"pearsonCorrelation",
"rollingCorrelation",
"spearmanCorrelation",
"tailCorrelation"
]
},
{
"original": "libs/utils/src/calculations/market-statistics.ts.disabled",
"status": "research-reference",
"destination": "research/market-statistics.md",
"sourceSha256": "4bd442052d2d2997f9f78b884b3ccb4793df4ec5eb512f824fddad013920318b",
"functions": [
"ImplementationShortfall",
"IntradayPatterns",
"LiquidityMetrics",
"MarketImpact",
"MarketStress",
"OrderBookImbalance",
"PriceDiscovery",
"RealizedSpread",
"TWAP",
"VWAP",
"adverseSelectionComponent",
"amihudIlliquidity",
"amihudIlliquidityHFT",
"cumulativeVolumeDelta",
"deltaNeutralHedgingRatio",
"gammaScalpingRange",
"garmanKlassVolatility",
"identifyMarketRegime",
"inventoryRiskComponent",
"kyleLambda",
"marketOrderRatio",
"optimalOrderSize",
"probabilityInformedTrading",
"quoteAge",
"rollSpreadEstimator",
"tickRule",
"tradeClassification",
"volumeConcentrationHHI",
"volumeOrderImbalance",
"volumeProfile",
"yangZhangVolatility"
]
},
{
"original": "libs/utils/src/calculations/options-pricing.ts.disabled",
"status": "research-reference",
"destination": "research/options-pricing.md",
"sourceSha256": "199004579a57c196c87230684717a559b1c95c6ef1e6c7cda7ab33852abfcb52",
"functions": [
"binomialOptionPricing",
"blackScholes",
"blackScholesWithGreeks",
"butterfly",
"calculateGreeks",
"calculateImpliedVolatility",
"calculateOptionPortfolioRisk",
"calculateStrategyGreeks",
"callBreakeven",
"callProbabilityOfProfit",
"condor",
"impliedVolatility",
"interpolateVolatilitySurface",
"monteCarloOptionPricing",
"putBreakeven",
"putProbabilityOfProfit",
"straddle",
"strangle"
]
},
{
"original": "libs/utils/src/calculations/portfolio-analytics.ts.disabled",
"status": "research-reference",
"destination": "research/portfolio-analytics.md",
"sourceSha256": "547b7df19c8fffc73736a6a5e6080f7de81bdfb6132080565b728651ae9e4bf2",
"functions": [
"blackLittermanOptimization",
"calculateEfficientFrontier",
"calculatePortfolioMetrics",
"calculatePortfolioReturns",
"calculatePortfolioVariance",
"calculateRebalancing",
"calculateRiskContributions",
"famaFrenchAnalysis",
"findMinimumVariancePortfolio",
"markowitzOptimization",
"performanceAttribution",
"riskParityOptimization"
]
},
{
"original": "libs/utils/src/calculations/position-sizing.ts.disabled",
"status": "research-reference",
"destination": "research/position-sizing.md",
"sourceSha256": "23815464ab33ebed0e597e2b3c35499c59ed3d2788d9e06bcd3a4878fda540f1",
"functions": [
"atrBasedPositionSize",
"calculatePortfolioHeat",
"correlationAdjustedPositionSize",
"dynamicPositionSize",
"equalWeightPositionSize",
"expectancyPositionSize",
"fixedFractionalPositionSize",
"fixedRiskPositionSize",
"fractionalKellyPositionSize",
"kellyPositionSize",
"liquidityConstrainedPositionSize",
"monteCarloPositionSize",
"multiTimeframePositionSize",
"optimalFPositionSize",
"riskParityPositionSize",
"secureFPositionSize",
"sharpeOptimizedPositionSize",
"validatePositionSize",
"volatilityAdjustedPositionSize",
"volatilityTargetPositionSize"
]
},
{
"original": "libs/utils/src/calculations/technical-indicators.ts.disabled",
"status": "research-reference",
"destination": "research/technical-indicators.md",
"sourceSha256": "603ef0b619c52e7388e1121993d628821e9c65e30e5d28cb34a1fd6f60eeeacc",
"functions": [
"accumulationDistribution",
"adx",
"aroon",
"atr",
"atrTrailingStops",
"balanceOfPower",
"bollingerBands",
"cci",
"centerOfGravity",
"chaikinADRange",
"chaikinMoneyFlow",
"chaikinOscillator",
"chandeMomentumOscillator",
"chandelierExit",
"coppockCurve",
"coppockRange",
"correlationCoefficient",
"deMarker",
"detrendedPriceOscillator",
"directionalMovementIndex",
"donchianChannels",
"donchianWidth",
"easeOfMovement",
"elderDisk",
"elderRay",
"eldersCloud",
"eldersForceIndex",
"eldersSafeZoneStops",
"eldersThermometer",
"ema",
"forceIndex",
"fractalChaosBands",
"fractalEfficiency",
"guppyMultipleMovingAverage",
"highLowIndex",
"highLowRange",
"hilbertTransformInstantaneousTrendline",
"historicalVolatility",
"ichimokuCloud",
"intradayIntensityIndex",
"kama",
"keltnerChannels",
"klingerOscillator",
"knowSureThing",
"linearRegressionIndicator",
"macd",
"marketFacilitationIndex",
"massIndex",
"medianPrice",
"medianPriceRange",
"mfi",
"momentum",
"momentumFromCurrentPrice",
"moneyFlowChaikinOscillator",
"moneyFlowIndexRange",
"moneyFlowMultiplier",
"movingAverageEnvelope",
"negativeVolumeIndex",
"normalizedAverageTrueRange",
"obv",
"onBalanceVolumeMean",
"onBalanceVolumeOscillator",
"parabolicSAR",
"percentagePriceOscillator",
"pivotPoints",
"positiveVolumeIndex",
"prettyGoodOscillator",
"priceVolumeTrend",
"primeNumberOscillator",
"projectionBands",
"projectionOscillator",
"qStick",
"rainbowOscillator",
"rangeActionVerificationIndex",
"relativeStrength",
"relativeVigorIndex",
"relativeVolatilityIndex",
"roc",
"rocFromCurrentPrice",
"rsi",
"schaffTrendCycle",
"sma",
"standardDeviation",
"stochRSIFast",
"stochRSIFull",
"stochastic",
"stochasticRSI",
"trix",
"trueStrengthIndex",
"twiggsMoneyFlow",
"typicalPrice",
"typicalPriceRange",
"ultimateMovingAverage",
"ultimateOscillator",
"verticalHorizontalFilter",
"volumeOscillator",
"volumeRateOfChange",
"vwma",
"williamsR"
]
},
{
"original": "libs/utils/src/calculations/volatility-models.ts.disabled",
"status": "research-reference",
"destination": "research/volatility-models.md",
"sourceSha256": "c84b4088b9251ecbc6e8a6306d90db78b2beebd82bdcfd5b21e009225cd4e0f8",
"functions": [
"calculateEWMAVolatility",
"calculateRealizedVolatility",
"calculateVolatilityRisk",
"calculateVolatilitySmile",
"calculateVolatilityTermStructure",
"calculateYangZhangVolatility",
"estimateGARCH",
"estimateHestonParameters",
"forecastVolatilityEWMA",
"identifyVolatilityRegimes",
"parkinsonVolatility"
]
}
]
}

View file

@ -0,0 +1,30 @@
{
"name": "@stock-bot/calculations",
"version": "1.0.0",
"private": true,
"type": "module",
"description": "Pure calculations shared by strategies, processing and feature engineering",
"main": "./src/index.ts",
"types": "./src/index.ts",
"exports": {
".": "./src/index.ts",
"./analytics": "./src/analytics/index.ts",
"./indicators": "./src/indicators/index.ts",
"./market-data": "./src/market-data.ts",
"./returns": "./src/returns.ts",
"./legacy": "./src/legacy/index.ts"
},
"scripts": {
"build": "tsc",
"test": "bun test",
"clean": "rimraf dist"
},
"dependencies": {
"@stock-bot/invariants": "workspace:*",
"@stock-bot/types": "workspace:*"
},
"devDependencies": {
"bun-types": "^1.2.15",
"typescript": "^5.3.0"
}
}

View file

@ -0,0 +1,26 @@
# Research references, not runtime APIs
These source snapshots preserve **all seven previously disabled calculation modules**
from `ccce401`, including functions not present in the active indicator module. Markdown
keeps their former non-executable status explicit. Their source hashes are verified by
the calculation preservation tests; this does not validate their algorithms.
| Snapshot | Review concerns before promotion |
| ------------------------------------------------ | ------------------------------------------------------------------------------- |
| [Correlation analysis](correlation-analysis.md) | Random permutation tests and approximate inference/matrix methods |
| [Market statistics](market-statistics.md) | Hard-coded market cap/stress estimates and simplified microstructure outputs |
| [Options pricing](options-pricing.md) | Unseeded Monte Carlo, convergence fallbacks and logging |
| [Portfolio analytics](portfolio-analytics.md) | Equal-weight optimizer baselines, zero factor estimates, incomplete attribution |
| [Position sizing](position-sizing.md) | Unseeded simulation/search; old production-readiness claims were unsupported |
| [Additional indicators](technical-indicators.md) | Duplicates plus unique indicators and a placeholder Hilbert transform |
| [Volatility models](volatility-models.md) | Simplified Yang–Zhang/Heston estimates and random shocks |
[Historical position-sizing notes](position-sizing-notes.md) retain the old formula and
validation discussion without endorsing its production-readiness claims.
To promote a function: define its inputs, units, undefined-result policy and temporal
alignment; remove synthetic results, implicit clock access and unseeded randomness;
add an independently checked fixture and edge-case tests; then expose a deliberate
supported subpath. Keep approximate research explicitly labeled rather than treating
an importable function as proof of correctness. Supported code must not depend on these
references or the legacy namespace.

View file

@ -1,3 +1,14 @@
# correlation-analysis research snapshot
Source: `ccce401:libs/utils/src/calculations/correlation-analysis.ts.disabled`.
Contains random permutation tests and simplified statistical/numerical approximations.
This preserves previously disabled research, not a supported or executable package API.
Review formulas, contracts, determinism and fixtures before porting any function into `src/`.
The code below is the original source, unchanged.
```ts
/**
* Correlation Analysis Module
*
@ -1267,3 +1278,4 @@ function fCDF(f: number, df1: number, df2: number): number {
const x = df2 / (df2 + df1 * f);
return 1 - betaIncomplete(df2 / 2, df1 / 2, x);
}
```

View file

@ -1,3 +1,14 @@
# market-statistics research snapshot
Source: `ccce401:libs/utils/src/calculations/market-statistics.ts.disabled`.
Contains fixed correlation stress, estimated market cap, and simplified spread/impact outputs.
This preserves previously disabled research, not a supported or executable package API.
Review formulas, contracts, determinism and fixtures before porting any function into `src/`.
The code below is the original source, unchanged.
```ts
/**
* Market Statistics and Microstructure Analysis
* Tools for analyzing market behavior, liquidity, and trading patterns
@ -1024,3 +1035,4 @@ function calculateCovariance(x: number[], y: number[]): number {
return x.reduce((sum, val, i) => sum + (val - meanX) * (y[i] - meanY), 0) / (n - 1);
}
```

View file

@ -1,3 +1,14 @@
# options-pricing research snapshot
Source: `ccce401:libs/utils/src/calculations/options-pricing.ts.disabled`.
Contains unseeded Monte Carlo sampling and volatility-convergence fallbacks/logging.
This preserves previously disabled research, not a supported or executable package API.
Review formulas, contracts, determinism and fixtures before porting any function into `src/`.
The code below is the original source, unchanged.
```ts
/**
* Options Pricing Models
* Implementation of various options pricing models and Greeks calculations
@ -808,3 +819,4 @@ export function putProbabilityOfProfit(
(volatility * Math.sqrt(timeToExpiry));
return 1 - normalCDF(d1);
}
```

View file

@ -1,3 +1,14 @@
# portfolio-analytics research snapshot
Source: `ccce401:libs/utils/src/calculations/portfolio-analytics.ts.disabled`.
Contains equal-weight optimization baselines, zero factor estimates and incomplete attribution.
This preserves previously disabled research, not a supported or executable package API.
Review formulas, contracts, determinism and fixtures before porting any function into `src/`.
The code below is the original source, unchanged.
```ts
/**
* Portfolio Analytics
* Advanced portfolio analysis and optimization tools
@ -590,3 +601,4 @@ function findMinimumVarianceWeights(
return weights;
}
```

View file

@ -1,97 +1,109 @@
# Position Sizing Calculations - Fixed Issues Summary
## Issues Identified and Fixed:
### 1. **Duplicate Kelly Function** ✅ FIXED
- **Problem**: Two different `kellyPositionSize` functions with conflicting signatures
- **Solution**: Removed the duplicate and kept the version with proper `KellyParams` interface
### 2. **Incorrect Kelly Criterion Formula** ✅ FIXED
- **Problem**: Formula was implemented as `winRate - ((1 - winRate) / winLossRatio)`
- **Solution**: Corrected to `(winRate * winLossRatio - lossRate) / winLossRatio`
- **Mathematical Validation**: Kelly formula is `f = (bp - q) / b` where b = win/loss ratio, p = win rate, q = loss rate
### 3. **Missing Input Validation** ✅ FIXED
- **Problem**: Functions didn't validate inputs (zero/negative values)
- **Solution**: Added comprehensive input validation to all functions
- **Examples**:
- Check for `accountSize <= 0`, `riskPercentage <= 0`
- Validate `winRate` is between 0 and 1
- Ensure prices and volatilities are positive
### 4. **ATR Position Sizing Units Error** ✅ FIXED
- **Problem**: Function returned risk amount instead of shares
- **Solution**: Changed to return `Math.floor(riskAmount / stopDistance)` (shares)
### 5. **Flawed Monte Carlo Simulation** ✅ FIXED
- **Problem**: Simulation applied returns to entire portfolio instead of position-sized returns
- **Solution**: Rewritten to test different position fractions and optimize based on Sharpe ratio
### 6. **Redundant Liquidity Calculations** ✅ FIXED
- **Problem**: Unnecessary conversions between shares and dollar values
- **Solution**: Simplified to directly compare `desiredPositionSize` with `maxShares`
### 7. **Risk Parity Not Using Target Risk** ✅ FIXED
- **Problem**: `targetRisk` parameter was ignored in calculations
- **Solution**: Incorporated target risk into weight calculations: `weight * (targetRisk / asset.volatility)`
### 8. **Missing Safety Constraints** ✅ FIXED
- **Problem**: No caps on leverage or volatility ratios
- **Solution**: Added reasonable caps:
- Volatility targeting: max 2x leverage
- Volatility adjustment: max 3x leverage
- Kelly fraction: max 25% with safety factor
### 9. **Correlation Risk Calculation Error** ✅ FIXED
- **Problem**: Correlation risk calculation didn't consider relative position sizes
- **Solution**: Weight correlations by relative position sizes for more accurate risk assessment
### 10. **Integer Share Handling** ✅ FIXED
- **Problem**: Functions returned fractional shares
- **Solution**: Added `Math.floor()` to return whole shares where appropriate
## Mathematical Validation Examples:
### Fixed Risk Position Sizing:
```
Account: $100,000, Risk: 2%, Entry: $100, Stop: $95
Risk Amount: $100,000 × 0.02 = $2,000
Risk Per Share: |$100 - $95| = $5
Position Size: $2,000 ÷ $5 = 400 shares ✅
```
### Kelly Criterion (Corrected):
```
Win Rate: 60%, Avg Win: $150, Avg Loss: $100
Win/Loss Ratio: $150 ÷ $100 = 1.5
Kelly Fraction: (1.5 × 0.6 - 0.4) ÷ 1.5 = 0.333
With Safety Factor (25%): 0.333 × 0.25 = 0.083
Position: $100,000 × 0.083 = $8,333 ✅
```
### Volatility Targeting:
```
Price: $100, Asset Vol: 20%, Target Vol: 10%
Volatility Ratio: 10% ÷ 20% = 0.5
Position Value: $100,000 × 0.5 = $50,000
Position Size: $50,000 ÷ $100 = 500 shares ✅
```
## Edge Cases Now Handled:
- ✅ Zero or negative account sizes
- ✅ Equal entry and stop loss prices
- ✅ Zero volatility assets
- ✅ Negative expectancy strategies
- ✅ Extreme correlation values
- ✅ Division by zero scenarios
- ✅ Invalid win rates (≤0 or ≥1)
## Additional Improvements:
- ✅ Consistent return types (whole shares vs. dollar amounts)
- ✅ Proper TypeScript interfaces for all parameters
- ✅ Comprehensive JSDoc documentation
- ✅ Mathematical formulas verified against financial literature
- ✅ Safety factors to prevent over-leveraging
- ✅ Portfolio-level risk management functions
All position sizing calculations are now mathematically correct, properly validated, and production-ready!
# Historical position-sizing notes
Original: `ccce401:libs/utils/POSITION_SIZING_FIXES.md`.
The following notes are retained as research context. Their claims of mathematical
correctness and production readiness were not independently established and are not
endorsements. The implementation remains in the non-executable position-sizing snapshot.
Use the package promotion checklist before adopting any formula or validation claim.
---
# Position Sizing Calculations - Fixed Issues Summary
## Issues Identified and Fixed:
### 1. **Duplicate Kelly Function** ✅ FIXED
- **Problem**: Two different `kellyPositionSize` functions with conflicting signatures
- **Solution**: Removed the duplicate and kept the version with proper `KellyParams` interface
### 2. **Incorrect Kelly Criterion Formula** ✅ FIXED
- **Problem**: Formula was implemented as `winRate - ((1 - winRate) / winLossRatio)`
- **Solution**: Corrected to `(winRate * winLossRatio - lossRate) / winLossRatio`
- **Mathematical Validation**: Kelly formula is `f = (bp - q) / b` where b = win/loss ratio, p = win rate, q = loss rate
### 3. **Missing Input Validation** ✅ FIXED
- **Problem**: Functions didn't validate inputs (zero/negative values)
- **Solution**: Added comprehensive input validation to all functions
- **Examples**:
- Check for `accountSize <= 0`, `riskPercentage <= 0`
- Validate `winRate` is between 0 and 1
- Ensure prices and volatilities are positive
### 4. **ATR Position Sizing Units Error** ✅ FIXED
- **Problem**: Function returned risk amount instead of shares
- **Solution**: Changed to return `Math.floor(riskAmount / stopDistance)` (shares)
### 5. **Flawed Monte Carlo Simulation** ✅ FIXED
- **Problem**: Simulation applied returns to entire portfolio instead of position-sized returns
- **Solution**: Rewritten to test different position fractions and optimize based on Sharpe ratio
### 6. **Redundant Liquidity Calculations** ✅ FIXED
- **Problem**: Unnecessary conversions between shares and dollar values
- **Solution**: Simplified to directly compare `desiredPositionSize` with `maxShares`
### 7. **Risk Parity Not Using Target Risk** ✅ FIXED
- **Problem**: `targetRisk` parameter was ignored in calculations
- **Solution**: Incorporated target risk into weight calculations: `weight * (targetRisk / asset.volatility)`
### 8. **Missing Safety Constraints** ✅ FIXED
- **Problem**: No caps on leverage or volatility ratios
- **Solution**: Added reasonable caps:
- Volatility targeting: max 2x leverage
- Volatility adjustment: max 3x leverage
- Kelly fraction: max 25% with safety factor
### 9. **Correlation Risk Calculation Error** ✅ FIXED
- **Problem**: Correlation risk calculation didn't consider relative position sizes
- **Solution**: Weight correlations by relative position sizes for more accurate risk assessment
### 10. **Integer Share Handling** ✅ FIXED
- **Problem**: Functions returned fractional shares
- **Solution**: Added `Math.floor()` to return whole shares where appropriate
## Mathematical Validation Examples:
### Fixed Risk Position Sizing:
```
Account: $100,000, Risk: 2%, Entry: $100, Stop: $95
Risk Amount: $100,000 × 0.02 = $2,000
Risk Per Share: |$100 - $95| = $5
Position Size: $2,000 ÷ $5 = 400 shares ✅
```
### Kelly Criterion (Corrected):
```
Win Rate: 60%, Avg Win: $150, Avg Loss: $100
Win/Loss Ratio: $150 ÷ $100 = 1.5
Kelly Fraction: (1.5 × 0.6 - 0.4) ÷ 1.5 = 0.333
With Safety Factor (25%): 0.333 × 0.25 = 0.083
Position: $100,000 × 0.083 = $8,333 ✅
```
### Volatility Targeting:
```
Price: $100, Asset Vol: 20%, Target Vol: 10%
Volatility Ratio: 10% ÷ 20% = 0.5
Position Value: $100,000 × 0.5 = $50,000
Position Size: $50,000 ÷ $100 = 500 shares ✅
```
## Edge Cases Now Handled:
- ✅ Zero or negative account sizes
- ✅ Equal entry and stop loss prices
- ✅ Zero volatility assets
- ✅ Negative expectancy strategies
- ✅ Extreme correlation values
- ✅ Division by zero scenarios
- ✅ Invalid win rates (≤0 or ≥1)
## Additional Improvements:
- ✅ Consistent return types (whole shares vs. dollar amounts)
- ✅ Proper TypeScript interfaces for all parameters
- ✅ Comprehensive JSDoc documentation
- ✅ Mathematical formulas verified against financial literature
- ✅ Safety factors to prevent over-leveraging
- ✅ Portfolio-level risk management functions
All position sizing calculations are now mathematically correct, properly validated, and production-ready!

View file

@ -1,3 +1,14 @@
# position-sizing research snapshot
Source: `ccce401:libs/utils/src/calculations/position-sizing.ts.disabled`.
Contains unseeded Monte Carlo search and unqualified production-ready claims in its old notes.
This preserves previously disabled research, not a supported or executable package API.
Review formulas, contracts, determinism and fixtures before porting any function into `src/`.
The code below is the original source, unchanged.
```ts
/**
* Position Sizing Calculations
* Risk-based position sizing methods for trading strategies
@ -579,3 +590,4 @@ export function secureFPositionSize(
return accountSize * secureF;
}
```

View file

@ -1,3 +1,14 @@
# technical-indicators research snapshot
Source: `ccce401:libs/utils/src/calculations/technical-indicators.ts.disabled`.
Contains additional indicator prototypes as well as duplicate indicators and a placeholder Hilbert transform.
This preserves previously disabled research, not a supported or executable package API.
Review formulas, contracts, determinism and fixtures before porting any function into `src/`.
The code below is the original source, unchanged.
```ts
/**
* Technical Indicators
* Comprehensive set of technical analysis indicators
@ -2506,3 +2517,4 @@ export function rocFromCurrentPrice(prices: number[], period: number = 10): numb
return result;
}
```

View file

@ -1,3 +1,14 @@
# volatility-models research snapshot
Source: `ccce401:libs/utils/src/calculations/volatility-models.ts.disabled`.
Contains simplified Yang–Zhang/Heston estimates and unseeded random shocks.
This preserves previously disabled research, not a supported or executable package API.
Review formulas, contracts, determinism and fixtures before porting any function into `src/`.
The code below is the original source, unchanged.
```ts
/**
* Volatility Models
* Advanced volatility modeling and forecasting tools
@ -619,3 +630,4 @@ export function forecastVolatilityEWMA(
}
return forecast;
}
```

View file

@ -0,0 +1,6 @@
export { dayMs, equityAnalysis, finite, nullable, ratio } from './equity';
export type { DrawdownPeriod, EquityPoint } from './equity';
export { factorStatistics, mean, returnStatistics, sampleDeviation } from './return-statistics';
export { tradeStatistics } from './trade-statistics';
export type { TradeObservation } from './trade-statistics';
export { formatStatistic, performanceAnalysis } from './performance';

View file

@ -0,0 +1,31 @@
export {
annualizeReturn,
annualizeVolatility,
cagr,
logReturn,
logReturns,
percentageChange,
simpleReturn,
simpleReturns,
} from './returns';
export {
movingAverageCrossover,
sma,
trailingMean,
trailingPopulationDeviation,
} from './indicators';
export {
calculateLogReturns,
calculateReturns,
calculateSMA,
calculateTrueRange,
calculateTypicalPrice,
calculateVWAP,
convertTimestamps,
extractCloses,
extractOHLC,
extractVolumes,
filterBySymbol,
filterByTimeRange,
groupBySymbol,
} from './market-data';

View file

@ -0,0 +1,6 @@
export {
movingAverageCrossover,
trailingMean,
trailingPopulationDeviation,
} from './window-statistics';
export { sma } from './sma';

View file

@ -0,0 +1,22 @@
import { at } from '@stock-bot/invariants';
import { finite } from '../analytics/equity';
/** Trailing-only SMA in O(n). Output 0 belongs to input period - 1; no warm-up zeros. */
export function sma(values: readonly number[], period: number): number[] {
if (!Number.isSafeInteger(period) || period < 1) {
throw new RangeError('Indicator period must be a positive integer');
}
const result: number[] = [];
let sum = 0;
for (const [index, value] of values.entries()) {
finite(value);
if (index >= period) {
sum -= finite(at(values, index - period));
}
sum = finite(sum + value);
if (index >= period - 1) {
result.push(finite(sum / period));
}
}
return result;
}

View file

@ -1,3 +1,4 @@
/** Legacy calculation API retained for migration/research; see ../../README.md before use. */
/**
* Basic Financial Calculations
* Core mathematical functions for financial analysis

View file

@ -0,0 +1,5 @@
/** Opt-in historical APIs, not aliases for the reviewed core. See the package migration notes. */
export * as basic from './basic-calculations';
export * as indicators from './technical-indicators';
export * as risk from './risk-metrics';
export * as performance from './performance-metrics';

View file

@ -1,3 +1,4 @@
/** Legacy calculation API retained for migration/research; see ../../README.md before use. */
import { ulcerIndex } from './risk-metrics';
/**

View file

@ -1,3 +1,4 @@
/** Legacy calculation API retained for migration/research; see ../../README.md before use. */
/**
* Risk Metrics and Analysis
* Comprehensive risk measurement tools for portfolio and trading analysis

View file

@ -1,3 +1,4 @@
/** Legacy calculation API retained for migration/research; see ../../README.md before use. */
import { defined } from '@stock-bot/invariants';
/**
* Technical Indicators

View file

@ -5,13 +5,32 @@ import { defined } from '@stock-bot/invariants';
*/
import type { HasClose, HasOHLC, HasVolume, OHLCV } from '@stock-bot/types';
import { finite } from './analytics/equity';
import { sma } from './indicators/sma';
import { logReturns, simpleReturns } from './returns';
function priceRange(item: HasOHLC): number {
const range = finite(finite(item.high) - finite(item.low));
if (range < 0) {
throw new RangeError('High must be at least low');
}
if (finite(item.close) < item.low || item.close > item.high) {
throw new RangeError('Close must be within high and low');
}
return range;
}
function typicalPrice(item: HasOHLC): number {
priceRange(item);
return finite((item.high + item.low + item.close) / 3);
}
/**
* Extract close prices from any data structure that has a close field
* Works with OHLCV, MarketData, or any custom type with close price
*/
export function extractCloses<T extends HasClose>(data: T[]): number[] {
return data.map(item => item.close);
return Array.from(data, item => finite(item.close));
}
/**
@ -25,6 +44,10 @@ export function extractOHLC<T extends HasOHLC>(
lows: number[];
closes: number[];
} {
for (const item of data) {
priceRange(item);
finite(item.open);
}
return {
opens: data.map(item => item.open),
highs: data.map(item => item.high),
@ -37,29 +60,21 @@ export function extractOHLC<T extends HasOHLC>(
* Extract volumes from any data structure that has a volume field
*/
export function extractVolumes<T extends HasVolume>(data: T[]): number[] {
return data.map(item => item.volume);
return Array.from(data, item => finite(item.volume));
}
/**
* Calculate simple moving average using close prices from any compatible data type
*/
export function calculateSMA<T extends HasClose>(data: T[], period: number): number[] {
const closes = extractCloses(data);
const result: number[] = [];
for (let i = period - 1; i < closes.length; i++) {
const sum = closes.slice(i - period + 1, i + 1).reduce((a, b) => a + b, 0);
result.push(sum / period);
}
return result;
return sma(extractCloses(data), period);
}
/**
* Calculate typical price (HLC/3) from any OHLC compatible data
*/
export function calculateTypicalPrice<T extends HasOHLC>(data: T[]): number[] {
return data.map(item => (item.high + item.low + item.close) / 3);
return Array.from(data, typicalPrice);
}
/**
@ -69,6 +84,7 @@ export function calculateTrueRange<T extends HasOHLC>(data: T[]): number[] {
const result: number[] = [];
for (let i = 0; i < data.length; i++) {
priceRange(defined(data[i]));
if (i === 0) {
result.push(defined(data[i]).high - defined(data[i]).low);
} else {
@ -79,7 +95,7 @@ export function calculateTrueRange<T extends HasOHLC>(data: T[]): number[] {
Math.abs(current.high - previous.close),
Math.abs(current.low - previous.close)
);
result.push(tr);
result.push(finite(tr));
}
}
@ -90,59 +106,36 @@ export function calculateTrueRange<T extends HasOHLC>(data: T[]): number[] {
* Calculate returns from close prices
*/
export function calculateReturns<T extends HasClose>(data: T[]): number[] {
const closes = extractCloses(data);
const returns: number[] = [];
for (let i = 1; i < closes.length; i++) {
const current = defined(closes[i]);
const previous = defined(closes[i - 1]);
if (previous > 0) {
returns.push((current - previous) / previous);
} else {
returns.push(0);
}
}
return returns;
return simpleReturns(extractCloses(data));
}
/**
* Calculate log returns from close prices
*/
export function calculateLogReturns<T extends HasClose>(data: T[]): number[] {
const closes = extractCloses(data);
const logReturns: number[] = [];
for (let i = 1; i < closes.length; i++) {
const current = defined(closes[i]);
const previous = defined(closes[i - 1]);
if (previous > 0 && current > 0) {
logReturns.push(Math.log(current / previous));
} else {
logReturns.push(0);
}
}
return logReturns;
return logReturns(extractCloses(data));
}
/**
* Calculate volume-weighted average price (VWAP) from OHLC + Volume data
*/
export function calculateVWAP<T extends HasOHLC & HasVolume>(data: T[]): number[] {
const result: number[] = [];
export function calculateVWAP<T extends HasOHLC & HasVolume>(data: T[]): Array<number | null> {
const result: Array<number | null> = [];
let cumulativeVolumePrice = 0;
let cumulativeVolume = 0;
for (const item of data) {
const typicalPrice = (item.high + item.low + item.close) / 3;
cumulativeVolumePrice += typicalPrice * item.volume;
cumulativeVolume += item.volume;
const price = typicalPrice(item);
if (finite(item.volume) < 0) {
throw new RangeError('Volume must be nonnegative');
}
cumulativeVolumePrice = finite(cumulativeVolumePrice + price * item.volume);
cumulativeVolume = finite(cumulativeVolume + item.volume);
if (cumulativeVolume > 0) {
result.push(cumulativeVolumePrice / cumulativeVolume);
result.push(finite(cumulativeVolumePrice / cumulativeVolume));
} else {
result.push(typicalPrice);
result.push(null);
}
}
@ -160,14 +153,17 @@ export function filterBySymbol(data: OHLCV[], symbol: string): OHLCV[] {
* Filter OHLCV data by time range
*/
export function filterByTimeRange(data: OHLCV[], startTime: number, endTime: number): OHLCV[] {
return data.filter(item => item.timestamp >= startTime && item.timestamp <= endTime);
if (finite(startTime) > finite(endTime)) {
throw new RangeError('Invalid time range');
}
return data.filter(item => finite(item.timestamp) >= startTime && item.timestamp <= endTime);
}
/**
* Group OHLCV data by symbol
*/
export function groupBySymbol(data: OHLCV[]): Record<string, OHLCV[]> {
const grouped: Record<string, OHLCV[]> = {};
const grouped: Record<string, OHLCV[]> = Object.create(null);
for (const item of data) {
if (!grouped[item.symbol]) {
@ -183,8 +179,11 @@ export function groupBySymbol(data: OHLCV[]): Record<string, OHLCV[]> {
* Convert timestamp to Date for OHLCV data
*/
export function convertTimestamps(data: OHLCV[]): Array<OHLCV & { date: Date }> {
return data.map(item => ({
...item,
date: new Date(item.timestamp),
}));
return data.map(item => {
const date = new Date(finite(item.timestamp));
if (!Number.isFinite(date.getTime())) {
throw new RangeError('Invalid timestamp');
}
return { ...item, date };
});
}

View file

@ -0,0 +1,80 @@
import { finite, nullable } from './analytics/equity';
/** Fractional return. A zero/negative baseline is undefined, not a zero return. */
export function simpleReturn(initial: number, final: number): number {
if (finite(initial) <= 0) {
throw new RangeError('Return baseline must be positive');
}
return finite(finite(final) / initial - 1);
}
/** Percentage points, explicitly distinguished from the fraction-based functions. */
export function percentageChange(initial: number, final: number): number {
return finite(simpleReturn(initial, final) * 100);
}
export function logReturn(initial: number, final: number): number {
if (finite(initial) <= 0 || finite(final) <= 0) {
throw new RangeError('Log return prices must be positive');
}
return finite(Math.log(final) - Math.log(initial));
}
function series(values: readonly number[], calculate: (initial: number, final: number) => number) {
const result: number[] = [];
let previous: number | undefined;
for (const value of values) {
finite(value);
if (previous !== undefined) {
result.push(calculate(previous, value));
}
previous = value;
}
return result;
}
/** Result i belongs to input i + 1. No observations are skipped or forward-filled. */
export function simpleReturns(values: readonly number[]): number[] {
return series(values, simpleReturn);
}
export function logReturns(values: readonly number[]): number[] {
for (const value of values) {
if (finite(value) <= 0) {
throw new RangeError('Log return prices must be positive');
}
}
return series(values, logReturn);
}
export function cagr(start: number, end: number, years: number): number | null {
if (finite(start) <= 0) {
throw new RangeError('Initial capital must be positive');
}
finite(end);
if (finite(years) < 0) {
throw new RangeError('Years must be nonnegative');
}
return years === 0 || end <= 0
? null
: nullable(Math.expm1((Math.log(end) - Math.log(start)) / years));
}
export function annualizeReturn(periodicReturn: number, periodsPerYear: number): number {
if (finite(periodicReturn) < -1) {
throw new RangeError('Periodic return must be at least -1');
}
if (finite(periodsPerYear) <= 0) {
throw new RangeError('Periods per year must be positive');
}
return finite(Math.expm1(Math.log1p(periodicReturn) * periodsPerYear));
}
export function annualizeVolatility(volatility: number, periodsPerYear: number): number {
if (finite(volatility) < 0) {
throw new RangeError('Volatility must be nonnegative');
}
if (finite(periodsPerYear) <= 0) {
throw new RangeError('Periods per year must be positive');
}
return finite(volatility * Math.sqrt(periodsPerYear));
}

View file

@ -0,0 +1,125 @@
import { describe, expect, test } from 'bun:test';
import { equityAnalysis, mean, returnStatistics } from '@stock-bot/calculations/analytics';
import {
movingAverageCrossover,
sma,
trailingMean,
trailingPopulationDeviation,
} from '@stock-bot/calculations/indicators';
import {
calculateReturns,
calculateTrueRange,
calculateVWAP,
convertTimestamps,
extractCloses,
filterByTimeRange,
groupBySymbol,
} from '@stock-bot/calculations/market-data';
import {
annualizeReturn,
annualizeVolatility,
cagr,
logReturn,
logReturns,
percentageChange,
simpleReturn,
simpleReturns,
} from '@stock-bot/calculations/returns';
const bar = { open: 10, high: 12, low: 8, close: 10, volume: 10, symbol: 'ABC.US', timestamp: 0 };
describe('reviewed shared calculation contracts', () => {
test('returns keep fractions distinct from percentage points and reject fabricated baselines', () => {
expect(simpleReturn(100, 110)).toBeCloseTo(0.1);
expect(percentageChange(100, 110)).toBeCloseTo(10);
expect(simpleReturn(100, -10)).toBeCloseTo(-1.1);
expect(logReturn(100, 110)).toBeCloseTo(Math.log(1.1));
expect(simpleReturns([100, 110, 99])).toEqual([simpleReturn(100, 110), simpleReturn(110, 99)]);
expect(logReturns([100, 110])).toEqual([logReturn(100, 110)]);
expect(simpleReturns([])).toEqual([]);
expect(logReturns([100])).toEqual([]);
for (const value of [0, -1, NaN, Infinity]) {
expect(() => simpleReturn(value, 10)).toThrow();
expect(() => logReturn(10, value)).toThrow();
}
expect(() => simpleReturns([100, 0, 110])).toThrow('baseline');
expect(() => calculateReturns([{ close: 100 }, { close: 0 }, { close: 110 }])).toThrow();
expect(() => simpleReturns(Array(2))).toThrow('finite');
expect(Number.isFinite(logReturn(Number.MIN_VALUE, Number.MAX_VALUE))).toBe(true);
});
test('annualization has explicit undefined CAGR and validates sampling units', () => {
expect(cagr(100, 121, 2)).toBeCloseTo(0.1);
expect(cagr(100, 110, 0)).toBeNull();
expect(cagr(100, 0, 1)).toBeNull();
expect(cagr(100, -10, 1)).toBeNull();
expect(cagr(1, 2, Number.MIN_VALUE)).toBeNull();
expect(() => cagr(0, 10, 1)).toThrow();
expect(() => cagr(100, 110, -1)).toThrow();
expect(() => cagr(100, NaN, 1)).toThrow();
expect(annualizeReturn(0.01, 12)).toBeCloseTo(1.01 ** 12 - 1);
expect(annualizeReturn(-1, 252)).toBe(-1);
expect(annualizeVolatility(0.1, 4)).toBeCloseTo(0.2);
for (const periods of [0, -1, NaN, Infinity]) {
expect(() => annualizeReturn(0.01, periods)).toThrow();
expect(() => annualizeVolatility(0.1, periods)).toThrow();
}
expect(() => annualizeReturn(-1.1, 12)).toThrow();
expect(() => annualizeVolatility(-0.1, 12)).toThrow();
const curve = equityAnalysis(
[
{ timestamp: 0, value: 100 },
{ timestamp: 365 * 86400000, value: 110 },
],
100
);
expect(curve.annualizedReturn).toBeCloseTo(cagr(100, 110, 1)!);
});
test('trailing features have explicit offsets and never read future bars', () => {
const prices = [3, 2, 1, 4, 6, 5, 7, 8];
expect(sma(prices, 3)).toEqual([2, 7 / 3, 11 / 3, 5, 6, 20 / 3]);
expect(sma([1, 2], 3)).toEqual([]);
expect(trailingMean([1, 2], 3)).toBeUndefined();
expect(trailingPopulationDeviation([1, 2, 3], 3)).toBeCloseTo(Math.sqrt(2 / 3));
for (let end = 1; end <= prices.length; end++) {
const prefix = prices.slice(0, end);
expect(sma(prices, 3).slice(0, Math.max(0, end - 2))).toEqual(sma(prefix, 3));
expect(trailingMean(prefix, 3)).toBe(sma(prefix, 3).at(-1));
}
expect(movingAverageCrossover([3, 2, 1, 4], 2, 3)?.goldenCross).toBe(true);
expect(() => sma([1, 2], 0)).toThrow();
expect(() => sma([1, NaN], 2)).toThrow('finite');
expect(() => sma(Array(3), 2)).toThrow('finite');
expect(() => sma([Number.MAX_VALUE, Number.MAX_VALUE], 2)).toThrow('finite');
expect(() => movingAverageCrossover(prices, 3, 2)).toThrow();
});
test('OHLCV features preserve alignment without inventing volume or prices', () => {
expect(calculateVWAP([{ ...bar, volume: 0 }, bar])).toEqual([null, 10]);
expect(calculateVWAP([bar, { ...bar, close: 12, volume: 30 }])[1]).toBeCloseTo(10.5);
expect(calculateTrueRange([bar, { ...bar, low: 11, high: 15, close: 12 }])).toEqual([4, 5]);
expect(() => calculateVWAP([{ ...bar, volume: -1 }])).toThrow();
expect(() => calculateVWAP([{ ...bar, high: 7 }])).toThrow();
expect(() => calculateTrueRange([{ ...bar, close: 20 }])).toThrow();
expect(() => extractCloses([{ close: Infinity }])).toThrow();
expect(() => convertTimestamps([{ ...bar, timestamp: Infinity }])).toThrow();
expect(() => convertTimestamps([{ ...bar, timestamp: 1e30 }])).toThrow();
expect(filterByTimeRange([bar], 0, 0)).toEqual([bar]);
expect(() => filterByTimeRange([bar], 1, 0)).toThrow();
const grouped = groupBySymbol([
{ ...bar, symbol: '__proto__' },
{ ...bar, symbol: 'constructor' },
]);
expect(grouped['__proto__']).toHaveLength(1);
expect(grouped['constructor']).toHaveLength(1);
expect(Object.getPrototypeOf(grouped)).toBeNull();
});
test('analytics remains reusable without an application/native runtime', () => {
expect(mean([1, 2, 3])).toBe(2);
expect(mean([])).toBeNull();
expect(returnStatistics([0, 0]).sharpeRatio).toBeNull();
expect(() => returnStatistics([NaN])).toThrow('finite');
});
});

View file

@ -7,97 +7,15 @@ import {
calculateTypicalPrice,
calculateVWAP,
convertTimestamps,
// Common utilities
createProxyUrl,
// Date utilities
dateUtils,
// Generic functions
extractCloses,
extractOHLC,
extractVolumes,
filterBySymbol,
filterByTimeRange,
groupBySymbol,
sleep,
} from '../src/index';
describe('Utility Functions', () => {
describe('common utilities', () => {
it('should create proxy URL with auth', () => {
const proxy = {
protocol: 'http',
host: '192.168.1.1',
port: 8080,
username: 'user',
password: 'pass',
};
const url = createProxyUrl(proxy);
expect(url).toBe('http://user:pass@192.168.1.1:8080');
});
it('should create proxy URL without auth', () => {
const proxy = {
protocol: 'socks5',
host: '192.168.1.1',
port: 1080,
};
const url = createProxyUrl(proxy);
expect(url).toBe('socks5://192.168.1.1:1080');
});
it('should sleep for specified milliseconds', async () => {
const start = Date.now();
await sleep(100);
const elapsed = Date.now() - start;
expect(elapsed).toBeGreaterThanOrEqual(90);
expect(elapsed).toBeLessThan(200);
});
});
describe('date utilities', () => {
it('should check if date is trading day', () => {
const monday = new Date('2023-12-25'); // Monday
const saturday = new Date('2023-12-23'); // Saturday
const sunday = new Date('2023-12-24'); // Sunday
expect(dateUtils.isTradingDay(monday)).toBe(true);
expect(dateUtils.isTradingDay(saturday)).toBe(false);
expect(dateUtils.isTradingDay(sunday)).toBe(false);
});
it('should get next trading day', () => {
const friday = new Date('2023-12-22'); // Friday
const nextDay = dateUtils.getNextTradingDay(friday);
expect(nextDay.getDay()).toBe(1); // Monday
});
it('should get previous trading day', () => {
const monday = new Date('2023-12-25'); // Monday
const prevDay = dateUtils.getPreviousTradingDay(monday);
expect(prevDay.getDay()).toBe(5); // Friday
});
it('should format date as YYYY-MM-DD', () => {
const date = new Date('2023-12-25T10:30:00Z');
const formatted = dateUtils.formatDate(date);
expect(formatted).toBe('2023-12-25');
});
it('should parse date from string', () => {
const date = dateUtils.parseDate('2023-12-25');
expect(date.getFullYear()).toBe(2023);
expect(date.getMonth()).toBe(11); // 0-based
expect(date.getDate()).toBe(25);
});
});
} from '@stock-bot/calculations/market-data';
describe('restored market-data utilities', () => {
describe('generic functions', () => {
const testData = [
{ open: 100, high: 105, low: 98, close: 103, volume: 1000 },

View file

@ -0,0 +1,55 @@
import { createHash } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { describe, expect, test } from 'bun:test';
import ts from 'typescript';
import * as legacy from '@stock-bot/calculations/legacy';
import audit from '../migration-audit.json';
const root = join(import.meta.dir, '..');
const namespaces: Record<string, object> = {
'basic-calculations.ts': legacy.basic,
'technical-indicators.ts': legacy.indicators,
'risk-metrics.ts': legacy.risk,
'performance-metrics.ts': legacy.performance,
};
const hash = (value: string) => createHash('sha256').update(value).digest('hex');
describe('calculation capability preservation', () => {
test('all 105 previously active functions remain available with unchanged legacy bodies', () => {
let count = 0;
for (const module of audit.modules.filter(module => module.status === 'legacy-api')) {
const name = module.original.split('/').at(-1)!;
expect(Object.keys(namespaces[name]!).sort()).toEqual(module.functions);
const source = readFileSync(join(root, module.destination), 'utf8');
const ast = ts.createSourceFile(name, source, ts.ScriptTarget.Latest, true);
expect(hash(ts.createPrinter({ removeComments: true }).printFile(ast))).toBe(
module.astSha256!
);
count += module.functions.length;
}
expect(count).toBe(105);
// Legacy behavior is preserved, not silently relabeled as validated core behavior.
expect(legacy.basic.simpleReturn(0, 100)).toBe(0);
expect(legacy.indicators.sma([1, 2, 3], 2)).toEqual([1.5, 2.5]);
expect(legacy.risk.maxDrawdown([100, 80, 100])).toBeCloseTo(0.2);
expect(
legacy.performance.analyzeTradePerformance([{ pnl: 1, date: new Date(0) }]).profitFactor
).toBe(Infinity);
});
test('all seven disabled prototypes survive as non-executable, source-verified references', () => {
const modules = audit.modules.filter(module => module.status === 'research-reference');
expect(modules).toHaveLength(7);
for (const module of modules) {
const reference = readFileSync(join(root, module.destination), 'utf8');
const start = reference.indexOf('```ts\n') + 6;
const end = reference.lastIndexOf('```');
expect(start).toBeGreaterThan(5);
expect(end).toBeGreaterThan(start);
expect(hash(reference.slice(start, end).replaceAll('\r\n', '\n').trimEnd())).toBe(
module.sourceSha256
);
}
});
});

View file

@ -0,0 +1,9 @@
{
"extends": "../../tsconfig.lib.json",
"compilerOptions": { "rootDir": "src", "outDir": "dist", "composite": true },
"include": ["src/**/*.ts"],
"references": [
{ "path": "../core/invariants" },
{ "path": "../core/types" }
]
}

View file

@ -10,8 +10,7 @@ import type {
IHandler,
JobHandler,
} from '@stock-bot/types';
import type { FetchOptions } from '@stock-bot/utils';
import { fetch } from '@stock-bot/utils';
import { fetch, type FetchOptions } from '@stock-bot/utils/fetch';
// Handler registry is now injected, not imported
import { createJobHandler } from '../utils/create-job-handler';

View file

@ -1,184 +0,0 @@
/**
* Handler Registry - Runtime registry for queue handlers
* Properly located in handlers package instead of types
*/
import type {
HandlerConfig,
HandlerConfigWithSchedule,
JobHandler,
ScheduledJob,
} from '@stock-bot/types';
import { getLogger } from '@stock-bot/logger';
class HandlerRegistry {
private readonly logger = getLogger('handler-registry');
private handlers = new Map<string, HandlerConfig>();
private handlerSchedules = new Map<string, ScheduledJob[]>();
private handlerServices = new Map<string, string>(); // Maps handler to service name
/**
* Register a handler with its operations (simple config)
*/
register(handlerName: string, config: HandlerConfig, serviceName?: string): void {
this.logger.info(`Registering handler: ${handlerName}`, {
operations: Object.keys(config),
service: serviceName,
});
this.handlers.set(handlerName, config);
// Track service ownership if provided
if (serviceName) {
this.handlerServices.set(handlerName, serviceName);
}
}
/**
* Register a handler with scheduled jobs (enhanced config)
*/
registerWithSchedule(config: HandlerConfigWithSchedule, serviceName?: string): void {
this.logger.info(`Registering handler with schedule: ${config.name}`, {
operations: Object.keys(config.operations),
scheduledJobs: config.scheduledJobs?.length || 0,
service: serviceName,
});
this.handlers.set(config.name, config.operations);
if (config.scheduledJobs && config.scheduledJobs.length > 0) {
this.handlerSchedules.set(config.name, config.scheduledJobs);
}
// Track service ownership if provided
if (serviceName) {
this.handlerServices.set(config.name, serviceName);
}
}
/**
* Get a specific handler's configuration
*/
getHandler(handlerName: string): HandlerConfig | undefined {
return this.handlers.get(handlerName);
}
/**
* Get all registered handlers
*/
getAllHandlers(): Map<string, HandlerConfig> {
return new Map(this.handlers);
}
/**
* Get scheduled jobs for a handler
*/
getScheduledJobs(handlerName: string): ScheduledJob[] {
return this.handlerSchedules.get(handlerName) || [];
}
/**
* Get all handlers with their scheduled jobs
*/
getAllHandlersWithSchedule(): Map<
string,
{ operations: HandlerConfig; scheduledJobs: ScheduledJob[] }
> {
const result = new Map<string, { operations: HandlerConfig; scheduledJobs: ScheduledJob[] }>();
for (const [name, operations] of this.handlers) {
result.set(name, {
operations,
scheduledJobs: this.handlerSchedules.get(name) || [],
});
}
return result;
}
/**
* Get a specific operation from a handler
*/
getOperation(handlerName: string, operationName: string): JobHandler | undefined {
const handler = this.handlers.get(handlerName);
if (!handler) {
return undefined;
}
return handler[operationName];
}
/**
* Check if a handler is registered
*/
hasHandler(handlerName: string): boolean {
return this.handlers.has(handlerName);
}
/**
* Get list of all registered handler names
*/
getHandlerNames(): string[] {
return Array.from(this.handlers.keys());
}
/**
* Get registry statistics
*/
getStats(): { handlers: number; operations: number; scheduledJobs: number } {
let operationCount = 0;
let scheduledJobCount = 0;
for (const [_, config] of this.handlers) {
operationCount += Object.keys(config).length;
}
for (const [_, jobs] of this.handlerSchedules) {
scheduledJobCount += jobs.length;
}
return {
handlers: this.handlers.size,
operations: operationCount,
scheduledJobs: scheduledJobCount,
};
}
/**
* Get the service that owns a handler
*/
getHandlerService(handlerName: string): string | undefined {
return this.handlerServices.get(handlerName);
}
/**
* Get all handlers for a specific service
*/
getServiceHandlers(serviceName: string): string[] {
const handlers: string[] = [];
for (const [handler, service] of this.handlerServices) {
if (service === serviceName) {
handlers.push(handler);
}
}
return handlers;
}
/**
* Set service ownership for a handler (used during auto-discovery)
*/
setHandlerService(handlerName: string, serviceName: string): void {
this.handlerServices.set(handlerName, serviceName);
}
/**
* Clear all registrations (useful for testing)
*/
clear(): void {
this.handlers.clear();
this.handlerSchedules.clear();
this.handlerServices.clear();
}
}
// Export singleton instance
export const handlerRegistry = new HandlerRegistry();

View file

@ -1,6 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, mock, spyOn } from 'bun:test';
import type { IServiceContainer } from '@stock-bot/services';
import * as utils from '@stock-bot/utils';
import * as utils from '@stock-bot/utils/fetch';
import { BaseHandler } from '../src/base/BaseHandler';
// Mock fetch
@ -54,7 +54,7 @@ describe('BaseHandler HTTP Methods', () => {
});
afterEach(() => {
// spyOn automatically restores
mock.restore();
});
describe('GET requests', () => {

View file

@ -1,34 +1,79 @@
# Utils Library
Common utility functions shared across services in the stock-bot project.
## Included Utilities
### Date Utilities
Helper functions for working with market dates:
```typescript
import { dateUtils } from '@stock-bot/utils';
// Check if a date is a trading day
const isTradingDay = dateUtils.isTradingDay(new Date());
// Get the next trading day
const nextTradingDay = dateUtils.getNextTradingDay(new Date());
```
### Financial Utilities
Mathematical functions for financial calculations:
```typescript
import { calculateCAGR, calculateSharpeRatio } from '@stock-bot/utils';
// Calculate compound annual growth rate
const returns = [0.05, 0.03, -0.01, 0.04, 0.02];
const cagr = calculateCAGR(startValue, endValue, years);
// Calculate Sharpe ratio
const sharpeRatio = calculateSharpeRatio(returns, 0.02);
```
# General utilities
`@stock-bot/utils` is a private workspace package for infrastructure-neutral general
helpers. Financial/feature calculations belong to `@stock-bot/calculations`, not here.
## Supported capabilities
- `@stock-bot/utils/fetch`: `fetch` and the type-only `FetchOptions`.
- `@stock-bot/utils/user-agent`: `getRandomUserAgent` selects from a fixed local list.
- `@stock-bot/utils/common`: `createProxyUrl` encodes proxy credentials; `sleep`
returns a timer-backed promise.
- `@stock-bot/utils/dates`: `utcDates` supplies `isWeekday`, `nextWeekday`,
`previousWeekday`, strict `parseDate` (`YYYY-MM-DD`) and `formatDate`.
The root explicitly exports these six runtime values (`fetch`, `getRandomUserAgent`,
`createProxyUrl`, `sleep`, `utcDates`, `dateUtils`) plus the `FetchOptions` type.
Capability subpaths avoid loading unrelated helpers. There are no wildcard/deep exports.
```ts
import { utcDates } from '@stock-bot/utils/dates';
import { fetch, type FetchOptions } from '@stock-bot/utils/fetch';
import { getRandomUserAgent } from '@stock-bot/utils/user-agent';
const options: FetchOptions = {
headers: { 'User-Agent': getRandomUserAgent() },
timeout: 5_000,
};
const response = await fetch('https://example.com/data', options);
const next = utcDates.nextWeekday(utcDates.parseDate('2024-03-08'));
```
Fetch keeps its existing logging, Bun proxy, timeout and original-`Response` behavior.
Non-OK statuses are returned, not thrown. Timeout cancellation and caller cancellation
are not composed: a configured timeout currently replaces the supplied signal. The
user-agent list is not fingerprinting or a guarantee of provider access.
Date arithmetic is explicitly UTC, validates inputs and does not mutate the supplied
date. Weekdays are **not** exchange sessions: holidays, exchange time zones and trading
hours are not modeled. The deprecated `dateUtils` names (`isTradingDay`,
`getNextTradingDay`, `getPreviousTradingDay`, `formatDate`, `parseDate`) remain
as aliases for migration, not as verified trading-calendar APIs. This replaces the old
environment-dependent local weekday arithmetic; use `utcDates` in new code.
`@stock-bot/invariants` is the only runtime workspace dependency. `LoggerLike`
from `@stock-bot/logger` is type-only. No databases, configuration initialization,
application service containers or mandatory native bindings may be added here.
## Calculation migration and removals
The financial modules and OHLCV helpers were **relocated/preserved**, not discarded:
- Reviewed returns/analytics/window math and OHLCV processing:
`@stock-bot/calculations` and its explicit capability subpaths.
- All 105 formerly active calculation functions with their original bodies:
`@stock-bot/calculations/legacy`, an opt-in historical API, not reviewed core.
- All seven disabled numerical/indicator prototypes:
non-executable source-verified snapshots in `libs/calculations/research/`.
See [the calculation contract](../calculations/README.md) and
[the complete cleanup audit](../../docs/cleanup-audit.md) for readiness, preserved test
scenarios and deliberate removals. The empty `analyzePortfolio` placeholder remains
removed because it calculated nothing.
Import assertions directly from `@stock-bot/invariants`; the redundant utility assertion
facade was removed, not its functionality. Import domain types from `@stock-bot/types`.
No finance compatibility re-export is added to the general utility package.
## Verify
From the repository root:
```sh
bun run test:utils
bun run test:calculations
bun run check
```
The root gate includes general-utility and handler HTTP-consumer tests, calculation
regressions and architecture checks for the explicit APIs and dependency boundaries.

View file

@ -1,7 +1,8 @@
{
"name": "@stock-bot/utils",
"version": "1.0.0",
"description": "Common utility functions for stock-bot services",
"private": true,
"description": "General HTTP, date and asynchronous helpers for stock-bot services",
"main": "./src/index.ts",
"types": "./src/index.ts",
"scripts": {
@ -10,10 +11,7 @@
"test": "bun test"
},
"dependencies": {
"@stock-bot/config": "workspace:*",
"@stock-bot/logger": "workspace:*",
"@stock-bot/cache": "workspace:*",
"@stock-bot/types": "workspace:*",
"@stock-bot/invariants": "workspace:*"
},
"devDependencies": {
@ -23,6 +21,9 @@
},
"exports": {
".": "./src/index.ts",
"./assertions": "./src/assertions.ts"
"./fetch": "./src/fetch.ts",
"./user-agent": "./src/user-agent.ts",
"./common": "./src/common.ts",
"./dates": "./src/dateUtils.ts"
}
}

View file

@ -1 +0,0 @@
export { at, defined } from '@stock-bot/invariants';

View file

@ -1,104 +0,0 @@
/**
* Financial Calculations Library
*
* This module provides a core set of financial calculations for trading and investment analysis.
* Focuses on basic calculations and standardized type exports.
*/
// Re-export all standardized types from @stock-bot/types
export type {
OHLCV,
OHLCVWithMetadata,
PortfolioPosition,
PortfolioAnalysis,
AssetAllocation,
TradeExecution,
TradePerformance,
RiskMetrics,
DrawdownAnalysis,
ReturnAnalysis,
OptionParameters,
OptionPricing,
GreeksCalculation,
MarketData,
LiquidityMetrics,
MarketRegime,
PositionSizeParams,
KellyParams,
BalanceSheet,
IncomeStatement,
CashFlowStatement,
TechnicalIndicators,
CorrelationResult,
CorrelationMatrix,
VolatilityEstimates,
GARCHParameters,
BacktestResults,
HasClose,
HasOHLC,
HasVolume,
HasTimestamp,
} from '@stock-bot/types';
// Export working calculation functions
export * from './basic-calculations';
// Export working technical indicators (building one by one)
export {
sma,
ema,
rsi,
macd,
bollingerBands,
atr,
obv,
stochastic,
williamsR,
cci,
mfi,
vwma,
momentum,
roc,
accumulationDistribution,
aroon,
adx,
parabolicSAR,
chaikinMoneyFlow,
pivotPoints,
ichimoku,
ultimateOscillator,
easeOfMovement,
tema,
wma,
keltnerChannels,
donchianChannels,
klingerVolumeOscillator,
priceOscillator,
chandeMomentumOscillator,
stochasticRSI,
vortexIndicator,
balanceOfPower,
trix,
massIndex,
coppockCurve,
} from './technical-indicators';
export * from './risk-metrics';
export * from './performance-metrics';
// Convenience function for comprehensive portfolio analysis
export function analyzePortfolio(
_returns: number[],
_equityCurve: Array<{ value: number; date: Date }>,
_benchmarkReturns?: number[],
_riskFreeRate: number = 0.02
): {
performance: Record<string, unknown>;
risk: Record<string, unknown>;
} {
// Note: Implementation depends on performance-metrics and risk-metrics
// This is a placeholder for the full implementation
return {
performance: {},
risk: {},
};
}

View file

@ -1,56 +1,48 @@
/**
* Date and time utilities for working with market data
*/
export const dateUtils = {
/**
* Check if a date is a trading day (Monday-Friday, non-holiday)
* This is a simplified implementation - a real version would check market holidays
*/
isTradingDay(date: Date): boolean {
const day = date.getDay();
return day > 0 && day < 6; // Mon-Fri
},
function valid(date: Date): Date {
if (!Number.isFinite(date.getTime())) {
throw new RangeError('Invalid UTC date');
}
return date;
}
/**
* Get the next trading day from a given date
*/
getNextTradingDay(date: Date): Date {
const nextDay = new Date(date);
nextDay.setDate(nextDay.getDate() + 1);
/** Weekdays in UTC, NOT an exchange calendar: holidays and venue sessions are not modeled. */
function isWeekday(date: Date): boolean {
const day = valid(date).getUTCDay();
return day > 0 && day < 6;
}
while (!this.isTradingDay(nextDay)) {
nextDay.setDate(nextDay.getDate() + 1);
}
function shiftWeekday(date: Date, direction: 1 | -1): Date {
const result = new Date(valid(date).getTime());
do {
result.setUTCDate(result.getUTCDate() + direction);
} while (!isWeekday(result));
return result;
}
return nextDay;
},
function parseDate(value: string): Date {
if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) {
throw new RangeError('Expected YYYY-MM-DD');
}
const date = valid(new Date(`${value}T00:00:00.000Z`));
if (date.toISOString().slice(0, 10) !== value) {
throw new RangeError('Invalid calendar date');
}
return date;
}
/**
* Get the previous trading day from a given date
*/
getPreviousTradingDay(date: Date): Date {
const prevDay = new Date(date);
prevDay.setDate(prevDay.getDate() - 1);
while (!this.isTradingDay(prevDay)) {
prevDay.setDate(prevDay.getDate() - 1);
}
return prevDay;
},
/**
* Format a date as YYYY-MM-DD
*/
formatDate(date: Date): string {
const parts = date.toISOString().split('T');
return parts[0] ?? '';
},
/**
* Parse a date string in YYYY-MM-DD format
*/
parseDate(dateStr: string): Date {
return new Date(dateStr);
},
export const utcDates = {
isWeekday,
nextWeekday: (date: Date): Date => shiftWeekday(date, 1),
previousWeekday: (date: Date): Date => shiftWeekday(date, -1),
formatDate: (date: Date): string => valid(date).toISOString().slice(0, 10),
parseDate,
};
/** @deprecated Compatibility names only. These are UTC weekdays, never verified trading sessions. */
export const dateUtils = {
isTradingDay: utcDates.isWeekday,
getNextTradingDay: utcDates.nextWeekday,
getPreviousTradingDay: utcDates.previousWeekday,
formatDate: utcDates.formatDate,
parseDate: utcDates.parseDate,
};

View file

@ -5,7 +5,7 @@ import type { LoggerLike } from '@stock-bot/logger';
* Drop-in replacement for native fetch with additional features
*/
export interface BunRequestInit extends RequestInit {
interface BunRequestInit extends RequestInit {
proxy?: string;
}

View file

@ -1,7 +1,5 @@
export * from './calculations/index';
export * from './assertions';
export * from './common';
export * from './dateUtils';
export * from './generic-functions';
export * from './fetch';
export * from './user-agent';
export { fetch } from './fetch';
export type { FetchOptions } from './fetch';
export { getRandomUserAgent } from './user-agent';
export { createProxyUrl, sleep } from './common';
export { dateUtils, utcDates } from './dateUtils';

View file

@ -0,0 +1,117 @@
import { describe, expect, it } from 'bun:test';
import { createProxyUrl, sleep } from '@stock-bot/utils/common';
import { dateUtils, utcDates } from '@stock-bot/utils/dates';
describe('restored general utilities', () => {
describe('common utilities', () => {
it('should create proxy URL with auth', () => {
const proxy = {
protocol: 'http',
host: '192.168.1.1',
port: 8080,
username: 'user',
password: 'pass',
};
const url = createProxyUrl(proxy);
expect(url).toBe('http://user:pass@192.168.1.1:8080');
});
it('should create proxy URL without auth', () => {
const proxy = {
protocol: 'socks5',
host: '192.168.1.1',
port: 1080,
};
const url = createProxyUrl(proxy);
expect(url).toBe('socks5://192.168.1.1:1080');
});
it('should sleep for specified milliseconds', async () => {
const start = Date.now();
await sleep(100);
const elapsed = Date.now() - start;
expect(elapsed).toBeGreaterThanOrEqual(90);
});
it('UTC weekday helpers preserve the supplied instant time and never mutate inputs', () => {
const friday = new Date('2024-03-08T23:30:00.000Z');
expect(utcDates.nextWeekday(friday).toISOString()).toBe('2024-03-11T23:30:00.000Z');
expect(friday.toISOString()).toBe('2024-03-08T23:30:00.000Z');
expect(utcDates.previousWeekday(new Date('2024-03-11T23:30:00Z')).toISOString()).toBe(
'2024-03-08T23:30:00.000Z'
);
// Christmas is a weekday, not a promise that any particular exchange is open.
expect(utcDates.isWeekday(new Date('2023-12-25T00:00:00Z'))).toBe(true);
const detached = utcDates.nextWeekday;
expect(detached(friday).getUTCDay()).toBe(1);
});
it('strict UTC dates reject invalid inputs and impossible calendar dates', () => {
expect(utcDates.parseDate('2024-02-29').toISOString()).toBe('2024-02-29T00:00:00.000Z');
for (const value of ['2023-02-29', '2024-02-30', '2024-13-01', '2024-01-01T00:00:00Z', '']) {
expect(() => utcDates.parseDate(value)).toThrow();
}
expect(() => utcDates.nextWeekday(new Date(NaN))).toThrow();
expect(() => utcDates.formatDate(new Date(NaN))).toThrow();
});
it('proxy credentials remain encoded and sleep remains asynchronous', async () => {
expect(
createProxyUrl({
protocol: 'http',
host: 'localhost',
port: 8080,
username: 'a@b',
password: 'p:/?',
})
).toBe('http://a%40b:p%3A%2F%3F@localhost:8080');
const wait = sleep(0);
expect(wait).toBeInstanceOf(Promise);
await wait;
});
});
describe('date utilities', () => {
it('should check if date is trading day', () => {
const monday = new Date('2023-12-25'); // Monday
const saturday = new Date('2023-12-23'); // Saturday
const sunday = new Date('2023-12-24'); // Sunday
expect(dateUtils.isTradingDay(monday)).toBe(true);
expect(dateUtils.isTradingDay(saturday)).toBe(false);
expect(dateUtils.isTradingDay(sunday)).toBe(false);
});
it('should get next trading day', () => {
const friday = new Date('2023-12-22'); // Friday
const nextDay = dateUtils.getNextTradingDay(friday);
expect(nextDay.getUTCDay()).toBe(1); // Monday
});
it('should get previous trading day', () => {
const monday = new Date('2023-12-25'); // Monday
const prevDay = dateUtils.getPreviousTradingDay(monday);
expect(prevDay.getUTCDay()).toBe(5); // Friday
});
it('should format date as YYYY-MM-DD', () => {
const date = new Date('2023-12-25T10:30:00Z');
const formatted = dateUtils.formatDate(date);
expect(formatted).toBe('2023-12-25');
});
it('should parse date from string', () => {
const date = dateUtils.parseDate('2023-12-25');
expect(date.getUTCFullYear()).toBe(2023);
expect(date.getUTCMonth()).toBe(11); // 0-based
expect(date.getUTCDate()).toBe(25);
});
});
});

View file

@ -1,13 +1,15 @@
import { afterEach, beforeEach, describe, expect, it, mock } from 'bun:test';
import { fetch } from '../src/fetch';
import { fetch } from '@stock-bot/utils/fetch';
describe('Enhanced Fetch', () => {
let originalFetch: typeof globalThis.fetch;
let originalDebug: typeof console.debug;
let mockFetch: any;
let mockLogger: any;
beforeEach(() => {
originalFetch = globalThis.fetch;
originalDebug = console.debug;
mockFetch = mock(() => Promise.resolve(new Response('test')));
globalThis.fetch = mockFetch;
@ -20,6 +22,7 @@ describe('Enhanced Fetch', () => {
afterEach(() => {
globalThis.fetch = originalFetch;
console.debug = originalDebug;
});
describe('basic fetch', () => {
@ -209,8 +212,6 @@ describe('Enhanced Fetch', () => {
await fetch('https://api.example.com/data');
expect(consoleSpy).toHaveBeenCalledTimes(2); // Request and response
console.debug = originalFetch as any;
});
});

View file

@ -1,5 +1,5 @@
import { describe, expect, it } from 'bun:test';
import { getRandomUserAgent } from '../src/user-agent';
import { getRandomUserAgent } from '@stock-bot/utils/user-agent';
describe('User Agent', () => {
describe('getRandomUserAgent', () => {

View file

@ -10,20 +10,11 @@
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"],
"references": [
{
"path": "../core/types"
},
{
"path": "../core/cache"
},
{
"path": "../core/config"
},
{
"path": "../core/logger"
},
{
"path": "../../libs/core/invariants"
"path": "../core/invariants"
}
]
}

View file

@ -13,6 +13,8 @@
"typecheck": "tsc --project tsconfig.check.json --noEmit",
"check": "bun run scripts/check.ts",
"test:tooling": "bun test scripts/test/",
"test:utils": "bun test libs/utils/test/ libs/core/handlers/test/base-handler-http.test.ts",
"test:calculations": "bun test libs/calculations/test/",
"test:contracts": "tsc --project tsconfig.contracts.json --noEmit",
"test": "turbo run test --filter=!@stock-bot/stock-app",
"test:watch": "bun test --watch",

View file

@ -7,6 +7,8 @@ export const checks = [
'typecheck',
'test:contracts',
'test:tooling',
'test:utils',
'test:calculations',
'test:integration',
'test:native',
'lint:check',

View file

@ -0,0 +1,60 @@
import { readFileSync } from 'node:fs';
import ts from 'typescript';
/** Runtime edges only: type imports and type re-exports cannot initialize a module. */
export function runtimeImports(file: string, sourceText = readFileSync(file, 'utf8')): string[] {
const source = ts.createSourceFile(file, sourceText, ts.ScriptTarget.Latest, true);
const imports = new Set<string>();
function visit(node: ts.Node) {
if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier)) {
const clause = node.importClause;
const bindings = clause?.namedBindings;
const typesOnly =
clause?.isTypeOnly ||
(clause &&
!clause.name &&
bindings &&
ts.isNamedImports(bindings) &&
bindings.elements.length > 0 &&
bindings.elements.every(item => item.isTypeOnly));
if (!typesOnly) imports.add(node.moduleSpecifier.text);
}
if (
ts.isExportDeclaration(node) &&
!node.isTypeOnly &&
node.moduleSpecifier &&
ts.isStringLiteral(node.moduleSpecifier)
) {
const clause = node.exportClause;
if (
!clause ||
!ts.isNamedExports(clause) ||
!clause.elements.length ||
clause.elements.some(item => !item.isTypeOnly)
) {
imports.add(node.moduleSpecifier.text);
}
}
if (
ts.isCallExpression(node) &&
(node.expression.kind === ts.SyntaxKind.ImportKeyword ||
(ts.isIdentifier(node.expression) && node.expression.text === 'require')) &&
node.arguments[0] &&
ts.isStringLiteral(node.arguments[0])
) {
imports.add(node.arguments[0].text);
}
if (
ts.isImportEqualsDeclaration(node) &&
!node.isTypeOnly &&
ts.isExternalModuleReference(node.moduleReference) &&
node.moduleReference.expression &&
ts.isStringLiteral(node.moduleReference.expression)
) {
imports.add(node.moduleReference.expression.text);
}
ts.forEachChild(node, visit);
}
visit(source);
return [...imports];
}

View file

@ -3,63 +3,11 @@ import { dirname, join, relative, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { describe, expect, it } from 'bun:test';
import ts from 'typescript';
import { runtimeImports } from '../runtime-imports';
const root = fileURLToPath(new URL('../../apps/stock/orchestrator/src/', import.meta.url));
const files = [...new Bun.Glob('**/*.ts').scanSync({ cwd: root })].map(file => join(root, file));
/** Include static imports/re-exports and lazy imports; type-only edges do not load code. */
function runtimeImports(file: string): string[] {
const source = ts.createSourceFile(
file,
readFileSync(file, 'utf8'),
ts.ScriptTarget.Latest,
true
);
const imports = new Set<string>();
function visit(node: ts.Node) {
if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier)) {
const clause = node.importClause;
const bindings = clause?.namedBindings;
const typesOnly =
clause?.isTypeOnly ||
(clause &&
!clause.name &&
bindings &&
ts.isNamedImports(bindings) &&
bindings.elements.length > 0 &&
bindings.elements.every(item => item.isTypeOnly));
if (!typesOnly) imports.add(node.moduleSpecifier.text);
}
if (
ts.isExportDeclaration(node) &&
!node.isTypeOnly &&
node.moduleSpecifier &&
ts.isStringLiteral(node.moduleSpecifier)
) {
const clause = node.exportClause;
if (
!clause ||
!ts.isNamedExports(clause) ||
!clause.elements.length ||
clause.elements.some(item => !item.isTypeOnly)
) {
imports.add(node.moduleSpecifier.text);
}
}
if (
ts.isCallExpression(node) &&
node.expression.kind === ts.SyntaxKind.ImportKeyword &&
node.arguments[0] &&
ts.isStringLiteral(node.arguments[0])
) {
imports.add(node.arguments[0].text);
}
ts.forEachChild(node, visit);
}
visit(source);
return [...imports];
}
const imports = new Map(files.map(file => [file, runtimeImports(file)]));
function localFile(from: string, specifier: string): string | undefined {
if (!specifier.startsWith('.')) return undefined;
@ -256,14 +204,14 @@ describe('orchestrator architecture boundaries', () => {
expect(dependencies).toEqual(['backtest/BacktestPlayback.ts', 'backtest/execution-engine.ts']);
});
it('shared analytics math is pure and cannot load report facades or application adapters', () => {
it('reviewed analytics and window math live in the shared calculations library', () => {
for (const entry of ['equity', 'performance', 'return-statistics', 'trade-statistics']) {
for (const file of reachable(join(root, 'analytics/' + entry + '.ts'))) {
expect(relative(root, file)).toMatch(/^analytics\//);
expect(relative(root, file)).not.toBe('analytics/PerformanceAnalyzer.ts');
expect((imports.get(file) ?? []).every(specifier => specifier.startsWith('.'))).toBe(true);
}
expect(existsSync(join(root, 'analytics/' + entry + '.ts'))).toBe(false);
}
expect(existsSync(join(root, 'indicators/window-statistics.ts'))).toBe(false);
expect(imports.get(join(root, 'analytics/PerformanceAnalyzer.ts'))).toEqual([
'@stock-bot/calculations/analytics',
]);
});
it('backtest reports are independent of run control, native engines, data loading and financial mutation', () => {
@ -276,9 +224,12 @@ describe('orchestrator architecture boundaries', () => {
for (const specifier of imports.get(file) ?? []) {
expect(
specifier.startsWith('.') ||
['simple-statistics', 'zod', '@stock-bot/invariants', '@stock-bot/logger'].includes(
specifier
)
[
'zod',
'@stock-bot/invariants',
'@stock-bot/logger',
'@stock-bot/calculations/analytics',
].includes(specifier)
).toBe(true);
}
}

View file

@ -0,0 +1,204 @@
import { readFileSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { describe, expect, it } from 'bun:test';
import * as utils from '@stock-bot/utils';
import { fetch } from '@stock-bot/utils/fetch';
import { getRandomUserAgent } from '@stock-bot/utils/user-agent';
import { checks } from '../check';
import { runtimeImports } from '../runtime-imports';
const root = fileURLToPath(new URL('../../', import.meta.url));
const utilsRoot = join(root, 'libs/utils');
const manifest = JSON.parse(readFileSync(join(utilsRoot, 'package.json'), 'utf8'));
const sourceFiles = [...new Bun.Glob('src/**/*.ts').scanSync({ cwd: utilsRoot })].map(file =>
join(utilsRoot, file)
);
describe('shared library boundaries', () => {
it('utils exposes general helpers without a financial framework', () => {
expect(Object.keys(utils).sort()).toEqual([
'createProxyUrl',
'dateUtils',
'fetch',
'getRandomUserAgent',
'sleep',
'utcDates',
]);
expect(utils.fetch).toBe(fetch);
expect(utils.getRandomUserAgent).toBe(getRandomUserAgent);
expect(manifest.private).toBe(true);
expect(manifest.exports).toEqual({
'.': './src/index.ts',
'./fetch': './src/fetch.ts',
'./user-agent': './src/user-agent.ts',
'./common': './src/common.ts',
'./dates': './src/dateUtils.ts',
});
for (const retired of ['assertions', 'calculations', 'src/fetch', 'dateUtils']) {
expect(() => Bun.resolveSync(`@stock-bot/utils/${retired}`, root)).toThrow();
}
});
it('utils cannot load infrastructure adapters or grow another domain-math API', () => {
expect(Object.keys(manifest.dependencies).sort()).toEqual([
'@stock-bot/invariants',
'@stock-bot/logger',
]);
const config = JSON.parse(readFileSync(join(utilsRoot, 'tsconfig.json'), 'utf8'));
expect(config.references.map((ref: { path: string }) => ref.path).sort()).toEqual([
'../core/invariants',
'../core/logger',
]);
for (const file of sourceFiles) {
expect(file).not.toContain('/calculations/');
for (const specifier of runtimeImports(file)) {
if (specifier.startsWith('.')) {
const local = resolve(dirname(file), specifier);
expect(
sourceFiles.some(
target => target === `${local}.ts` || target === join(local, 'index.ts')
)
).toBe(true);
} else {
// Logger is a type-only capability; only invariants may be loaded at runtime.
expect(specifier).toBe('@stock-bot/invariants');
}
}
}
});
it('calculations is a portable pure library, with legacy code isolated from supported exports', () => {
const directory = join(root, 'libs/calculations');
const pkg = JSON.parse(readFileSync(join(directory, 'package.json'), 'utf8'));
expect(Object.keys(pkg.dependencies).sort()).toEqual([
'@stock-bot/invariants',
'@stock-bot/types',
]);
expect(pkg.private).toBe(true);
const sources = [...new Bun.Glob('src/**/*.ts').scanSync({ cwd: directory })].map(file =>
join(directory, file)
);
for (const file of sources) {
for (const specifier of runtimeImports(file)) {
if (!specifier.startsWith('.')) {
expect(specifier).toBe('@stock-bot/invariants');
continue;
}
const target = resolve(dirname(file), specifier);
const dependency = sources.find(
source => source === `${target}.ts` || source === join(target, 'index.ts')
);
expect(dependency).toBeDefined();
if (!file.includes('/legacy/')) expect(dependency).not.toContain('/legacy/');
}
}
expect(Object.keys(pkg.exports).sort()).toEqual([
'.',
'./analytics',
'./indicators',
'./legacy',
'./market-data',
'./returns',
]);
for (const path of [
'research',
'src/legacy/basic-calculations',
'legacy/technical-indicators',
]) {
expect(() => Bun.resolveSync(`@stock-bot/calculations/${path}`, root)).toThrow();
}
expect(runtimeImports(join(root, 'libs/core/invariants/src/index.ts'))).toEqual([]);
});
it('stock applications use reviewed calculation contracts, not archived prototypes or legacy math', () => {
const directory = join(root, 'apps/stock');
const files = [...new Bun.Glob('*/src/**/*.ts').scanSync({ cwd: directory })];
for (const file of files) {
for (const specifier of runtimeImports(join(directory, file))) {
expect(specifier).not.toMatch(/^@stock-bot\/calculations\/(legacy|research)/);
if (specifier.startsWith('.')) {
const target = resolve(dirname(join(directory, file)), specifier);
expect(target).not.toContain('/libs/calculations/src/legacy/');
expect(target).not.toContain('/libs/calculations/research/');
}
}
}
});
it('library source and tests contain no disabled or backup copies', () => {
const files = [...new Bun.Glob('**/*').scanSync({ cwd: join(root, 'libs') })];
const backups = files.filter(
file =>
!file.split('/').some(part => ['node_modules', 'dist'].includes(part)) &&
/\.(old|disabled|bak|orig)$/.test(file)
);
expect(backups).toEqual([]);
});
it('the root gate runs utility and HTTP-consumer regressions', () => {
expect(checks).toContain('test:utils');
expect(checks).toContain('test:calculations');
const pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'));
expect(pkg.scripts['test:utils']).toBe(
'bun test libs/utils/test/ libs/core/handlers/test/base-handler-http.test.ts'
);
for (const path of ['apps/stock/orchestrator', 'tools/coverage-cli']) {
const consumer = JSON.parse(readFileSync(join(root, path, 'package.json'), 'utf8'));
expect(consumer.dependencies).not.toHaveProperty('@stock-bot/utils');
expect(consumer.dependencies).not.toHaveProperty('simple-statistics');
}
});
});
describe('runtime dependency inspection', () => {
it('ignores erased type-only imports and re-exports', () => {
expect(
runtimeImports(
'fixture.ts',
`
import type { Logger } from 'logger';
import { type Cache } from 'cache';
import type * as DB from 'database';
export type { Portfolio } from 'finance';
export { type Model } from 'models';
type Lazy = typeof import('type-query');
import type Legacy = require('legacy-type');
`
)
).toEqual([]);
});
it('detects static, mixed, side-effect, lazy and CommonJS runtime edges', () => {
expect(
runtimeImports(
'fixture.ts',
`
import { run, type Options } from 'mixed';
import fallback, { type Shape } from 'default';
import 'side-effect';
export { execute, type Input } from 're-export';
export * from 'star';
export * as ns from 'namespace';
import {} from 'empty-import';
export {} from 'empty-export';
const module = await import('lazy');
const cjs = require('commonjs');
import legacy = require('import-equals');
`
)
).toEqual([
'mixed',
'default',
'side-effect',
're-export',
'star',
'namespace',
'empty-import',
'empty-export',
'lazy',
'commonjs',
'import-equals',
]);
});
});

View file

@ -1,12 +1,13 @@
import { describe, expect, test } from 'bun:test';
import { dayMs, equityAnalysis } from '../../apps/stock/orchestrator/src/analytics/equity';
import { performanceAnalysis } from '../../apps/stock/orchestrator/src/analytics/performance';
import { PerformanceAnalyzer } from '../../apps/stock/orchestrator/src/analytics/PerformanceAnalyzer';
import {
dayMs,
equityAnalysis,
factorStatistics,
performanceAnalysis,
returnStatistics,
} from '../../apps/stock/orchestrator/src/analytics/return-statistics';
import { tradeStatistics } from '../../apps/stock/orchestrator/src/analytics/trade-statistics';
tradeStatistics,
} from '@stock-bot/calculations/analytics';
import { PerformanceAnalyzer } from '../../apps/stock/orchestrator/src/analytics/PerformanceAnalyzer';
import golden from '../fixtures/analytics-golden.json';
const start = Date.parse('2024-01-01T00:00:00Z');

View file

@ -24,7 +24,7 @@ import {
movingAverageCrossover,
trailingMean,
trailingPopulationDeviation,
} from '../../apps/stock/orchestrator/src/indicators/window-statistics';
} from '@stock-bot/calculations/indicators';
import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService';
import { MeanReversionStrategy } from '../../apps/stock/orchestrator/src/strategies/builtin/MeanReversionStrategy';
import { SmaCrossoverStrategy } from '../../apps/stock/orchestrator/src/strategies/builtin/SmaCrossoverStrategy';

View file

@ -18,7 +18,6 @@
"handlebars": "^4.7.8",
"lcov-parse": "^1.0.0",
"table": "^6.8.1",
"@stock-bot/utils": "workspace:*",
"@stock-bot/invariants": "workspace:*"
},
"devDependencies": {