@adaptic/utils 0.0.989 → 0.0.991
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +754 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.mjs +750 -2
- package/dist/index.mjs.map +1 -1
- package/dist/types/__tests__/atr.test.d.ts +2 -0
- package/dist/types/__tests__/atr.test.d.ts.map +1 -0
- package/dist/types/__tests__/index.test.d.ts +2 -0
- package/dist/types/__tests__/index.test.d.ts.map +1 -0
- package/dist/types/__tests__/risk-metrics.test.d.ts +2 -0
- package/dist/types/__tests__/risk-metrics.test.d.ts.map +1 -0
- package/dist/types/__tests__/strategy-metrics.test.d.ts +2 -0
- package/dist/types/__tests__/strategy-metrics.test.d.ts.map +1 -0
- package/dist/types/__tests__/volatility.test.d.ts +2 -0
- package/dist/types/__tests__/volatility.test.d.ts.map +1 -0
- package/dist/types/atr.d.ts +30 -0
- package/dist/types/atr.d.ts.map +1 -0
- package/dist/types/index.d.ts +41 -2
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/misc-utils.d.ts +37 -0
- package/dist/types/misc-utils.d.ts.map +1 -1
- package/dist/types/risk-metrics.d.ts +58 -0
- package/dist/types/risk-metrics.d.ts.map +1 -0
- package/dist/types/strategy-metrics.d.ts +65 -0
- package/dist/types/strategy-metrics.d.ts.map +1 -0
- package/dist/types/trading-policy/schemas/effective-policy.schema.d.ts +4 -4
- package/dist/types/trading-policy/schemas/execution-prefs.schema.d.ts +4 -4
- package/dist/types/trading-policy/schemas/policy-mutation.schema.d.ts +6 -6
- package/dist/types/volatility.d.ts +65 -0
- package/dist/types/volatility.d.ts.map +1 -0
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -6042,6 +6042,202 @@ async function createLimitOrder(auth, params = {
|
|
|
6042
6042
|
}
|
|
6043
6043
|
|
|
6044
6044
|
// Utility function for debug logging
|
|
6045
|
+
/** Sliding-window size (number of recent outcomes tracked per host). */
|
|
6046
|
+
const CIRCUIT_WINDOW_SIZE = 20;
|
|
6047
|
+
/** Maximum age (ms) of an outcome before it is dropped from the window. */
|
|
6048
|
+
const CIRCUIT_WINDOW_TTL_MS = 30_000;
|
|
6049
|
+
/**
|
|
6050
|
+
* Failure ratio (0..1) at which the breaker trips when the window
|
|
6051
|
+
* is full (i.e. CIRCUIT_WINDOW_SIZE outcomes recorded).
|
|
6052
|
+
*
|
|
6053
|
+
* Tuned to be permissive enough that a few transient failures during
|
|
6054
|
+
* normal operation do not trip the breaker, but tight enough that a
|
|
6055
|
+
* persistent upstream outage (where >= half of recent calls are
|
|
6056
|
+
* failing) is detected quickly. With WINDOW=20 and threshold=0.6 we
|
|
6057
|
+
* need 12 failures within the most recent 20 attempts to trip.
|
|
6058
|
+
*/
|
|
6059
|
+
const CIRCUIT_TRIP_FAILURE_RATIO = 0.6;
|
|
6060
|
+
/**
|
|
6061
|
+
* Minimum number of recent outcomes required before the failure-ratio
|
|
6062
|
+
* gate is even evaluated. Without this guard, a single failure on a
|
|
6063
|
+
* cold host would give a 100 % ratio and trip the breaker on the
|
|
6064
|
+
* second attempt — which would be useless protection while also being
|
|
6065
|
+
* highly destructive.
|
|
6066
|
+
*/
|
|
6067
|
+
const CIRCUIT_MIN_SAMPLES = 8;
|
|
6068
|
+
/**
|
|
6069
|
+
* How long the breaker stays open before transitioning to half-open
|
|
6070
|
+
* (i.e. allowing the next request through as a probe). The next
|
|
6071
|
+
* outcome — success or failure — fully recloses or re-opens the
|
|
6072
|
+
* breaker. 5 s aligns with typical upstream recovery times and is
|
|
6073
|
+
* short enough that the next caller drives the probe.
|
|
6074
|
+
*/
|
|
6075
|
+
const CIRCUIT_OPEN_COOLDOWN_MS = 5_000;
|
|
6076
|
+
/**
|
|
6077
|
+
* Fail-fast latency. We sleep a short, deterministic amount before
|
|
6078
|
+
* rejecting so the upstream caller's outer timeout (commonly 10–25 s)
|
|
6079
|
+
* sees a clean rejection rather than a synchronous reject-storm that
|
|
6080
|
+
* could starve other event-loop work. 100 ms aligns with the user's
|
|
6081
|
+
* G1 analysis target: "cap per-symbol fallback latency at 100 ms
|
|
6082
|
+
* during outages — eliminating the 25 s × N-concurrent-symbols
|
|
6083
|
+
* event-loop hog."
|
|
6084
|
+
*/
|
|
6085
|
+
const CIRCUIT_FAIL_FAST_LATENCY_MS = 100;
|
|
6086
|
+
const circuitStates = new Map();
|
|
6087
|
+
function getCircuitState(host) {
|
|
6088
|
+
let state = circuitStates.get(host);
|
|
6089
|
+
if (!state) {
|
|
6090
|
+
state = {
|
|
6091
|
+
host,
|
|
6092
|
+
recent: [],
|
|
6093
|
+
openedAt: 0,
|
|
6094
|
+
lastTripFailureRatio: 0,
|
|
6095
|
+
};
|
|
6096
|
+
circuitStates.set(host, state);
|
|
6097
|
+
}
|
|
6098
|
+
return state;
|
|
6099
|
+
}
|
|
6100
|
+
function pruneStaleSamples(state, now) {
|
|
6101
|
+
const cutoff = now - CIRCUIT_WINDOW_TTL_MS;
|
|
6102
|
+
// Remove entries older than the TTL. Window is small so a simple
|
|
6103
|
+
// filter is fine — no need for a deque structure.
|
|
6104
|
+
if (state.recent.length === 0)
|
|
6105
|
+
return;
|
|
6106
|
+
let firstFreshIndex = 0;
|
|
6107
|
+
while (firstFreshIndex < state.recent.length &&
|
|
6108
|
+
state.recent[firstFreshIndex].atMs < cutoff) {
|
|
6109
|
+
firstFreshIndex += 1;
|
|
6110
|
+
}
|
|
6111
|
+
if (firstFreshIndex > 0) {
|
|
6112
|
+
state.recent.splice(0, firstFreshIndex);
|
|
6113
|
+
}
|
|
6114
|
+
}
|
|
6115
|
+
function recordOutcome(host, ok) {
|
|
6116
|
+
const now = Date.now();
|
|
6117
|
+
const state = getCircuitState(host);
|
|
6118
|
+
pruneStaleSamples(state, now);
|
|
6119
|
+
state.recent.push({ atMs: now, ok });
|
|
6120
|
+
if (state.recent.length > CIRCUIT_WINDOW_SIZE) {
|
|
6121
|
+
state.recent.shift();
|
|
6122
|
+
}
|
|
6123
|
+
// If we are in the open or half-open window and just received an
|
|
6124
|
+
// outcome, decide whether to close or re-open.
|
|
6125
|
+
if (state.openedAt > 0) {
|
|
6126
|
+
if (now - state.openedAt >= CIRCUIT_OPEN_COOLDOWN_MS) {
|
|
6127
|
+
// Half-open probe outcome arrived.
|
|
6128
|
+
if (ok) {
|
|
6129
|
+
// Recovered. Close the breaker.
|
|
6130
|
+
state.openedAt = 0;
|
|
6131
|
+
state.lastTripFailureRatio = 0;
|
|
6132
|
+
getLogger().info(`Circuit breaker for ${host} closed — upstream recovered`, { host });
|
|
6133
|
+
}
|
|
6134
|
+
else {
|
|
6135
|
+
// Probe failed. Re-open the breaker for another cooldown.
|
|
6136
|
+
state.openedAt = now;
|
|
6137
|
+
}
|
|
6138
|
+
return;
|
|
6139
|
+
}
|
|
6140
|
+
// Still inside the cooldown window — outcomes are recorded for
|
|
6141
|
+
// statistics but the breaker stays open regardless.
|
|
6142
|
+
return;
|
|
6143
|
+
}
|
|
6144
|
+
// Closed breaker — evaluate whether the failure ratio has tripped.
|
|
6145
|
+
if (state.recent.length < CIRCUIT_MIN_SAMPLES)
|
|
6146
|
+
return;
|
|
6147
|
+
const failures = state.recent.reduce((acc, entry) => acc + (entry.ok ? 0 : 1), 0);
|
|
6148
|
+
const ratio = failures / state.recent.length;
|
|
6149
|
+
if (ratio >= CIRCUIT_TRIP_FAILURE_RATIO) {
|
|
6150
|
+
state.openedAt = now;
|
|
6151
|
+
state.lastTripFailureRatio = ratio;
|
|
6152
|
+
getLogger().warn(`Circuit breaker for ${host} opened — ${failures}/${state.recent.length} recent attempts failed (${(ratio * 100).toFixed(0)}%); fail-fast for ${CIRCUIT_OPEN_COOLDOWN_MS}ms`, {
|
|
6153
|
+
host,
|
|
6154
|
+
recentFailures: failures,
|
|
6155
|
+
recentSamples: state.recent.length,
|
|
6156
|
+
failureRatio: ratio,
|
|
6157
|
+
cooldownMs: CIRCUIT_OPEN_COOLDOWN_MS,
|
|
6158
|
+
});
|
|
6159
|
+
}
|
|
6160
|
+
}
|
|
6161
|
+
function isCircuitOpen(host, now) {
|
|
6162
|
+
const state = circuitStates.get(host);
|
|
6163
|
+
if (!state || state.openedAt === 0)
|
|
6164
|
+
return false;
|
|
6165
|
+
pruneStaleSamples(state, now);
|
|
6166
|
+
return now - state.openedAt < CIRCUIT_OPEN_COOLDOWN_MS;
|
|
6167
|
+
}
|
|
6168
|
+
/**
|
|
6169
|
+
* Error thrown by {@link fetchWithRetry} when the per-host circuit
|
|
6170
|
+
* breaker is open and fail-fast suppression is in effect.
|
|
6171
|
+
*
|
|
6172
|
+
* Carries the host, the failure ratio that tripped the breaker, and
|
|
6173
|
+
* the remaining cooldown so callers can render an actionable log.
|
|
6174
|
+
*/
|
|
6175
|
+
class CircuitOpenError extends Error {
|
|
6176
|
+
code = "MASSIVE_CIRCUIT_OPEN";
|
|
6177
|
+
host;
|
|
6178
|
+
tripFailureRatio;
|
|
6179
|
+
cooldownRemainingMs;
|
|
6180
|
+
constructor(host, tripFailureRatio, cooldownRemainingMs) {
|
|
6181
|
+
super(`Circuit open for ${host} — fail-fast (recent failure ratio ${(tripFailureRatio * 100).toFixed(0)}%, retry in ${cooldownRemainingMs}ms)`);
|
|
6182
|
+
this.name = "CircuitOpenError";
|
|
6183
|
+
this.host = host;
|
|
6184
|
+
this.tripFailureRatio = tripFailureRatio;
|
|
6185
|
+
this.cooldownRemainingMs = cooldownRemainingMs;
|
|
6186
|
+
}
|
|
6187
|
+
}
|
|
6188
|
+
/**
|
|
6189
|
+
* Force-close the breaker for a given host. Exposed for tests and
|
|
6190
|
+
* operator-runbook scripts so a stuck-open breaker can be reset
|
|
6191
|
+
* without bouncing the process. Not intended for hot-path use.
|
|
6192
|
+
*
|
|
6193
|
+
* @param host The hostname whose breaker should be reset.
|
|
6194
|
+
*/
|
|
6195
|
+
function resetCircuitBreaker(host) {
|
|
6196
|
+
const state = circuitStates.get(host);
|
|
6197
|
+
if (!state)
|
|
6198
|
+
return;
|
|
6199
|
+
state.openedAt = 0;
|
|
6200
|
+
state.lastTripFailureRatio = 0;
|
|
6201
|
+
state.recent = [];
|
|
6202
|
+
}
|
|
6203
|
+
/**
|
|
6204
|
+
* Snapshot of all known per-host circuit-breaker states. Intended for
|
|
6205
|
+
* an operational-truth / status endpoint to surface upstream health.
|
|
6206
|
+
*
|
|
6207
|
+
* @returns Map of host → {open, openedAt, recentSamples, failureRatio,
|
|
6208
|
+
* lastTripFailureRatio}.
|
|
6209
|
+
*/
|
|
6210
|
+
function getCircuitBreakerSnapshot() {
|
|
6211
|
+
const now = Date.now();
|
|
6212
|
+
const snapshot = {};
|
|
6213
|
+
for (const [host, state] of circuitStates) {
|
|
6214
|
+
pruneStaleSamples(state, now);
|
|
6215
|
+
const failures = state.recent.reduce((acc, entry) => acc + (entry.ok ? 0 : 1), 0);
|
|
6216
|
+
const ratio = state.recent.length > 0 ? failures / state.recent.length : 0;
|
|
6217
|
+
snapshot[host] = {
|
|
6218
|
+
open: state.openedAt > 0 && now - state.openedAt < CIRCUIT_OPEN_COOLDOWN_MS,
|
|
6219
|
+
openedAt: state.openedAt,
|
|
6220
|
+
cooldownRemainingMs: state.openedAt > 0
|
|
6221
|
+
? Math.max(0, CIRCUIT_OPEN_COOLDOWN_MS - (now - state.openedAt))
|
|
6222
|
+
: 0,
|
|
6223
|
+
recentSamples: state.recent.length,
|
|
6224
|
+
failureRatio: ratio,
|
|
6225
|
+
lastTripFailureRatio: state.lastTripFailureRatio,
|
|
6226
|
+
};
|
|
6227
|
+
}
|
|
6228
|
+
return snapshot;
|
|
6229
|
+
}
|
|
6230
|
+
function hostnameFromUrl(url) {
|
|
6231
|
+
try {
|
|
6232
|
+
return new URL(url).hostname;
|
|
6233
|
+
}
|
|
6234
|
+
catch {
|
|
6235
|
+
return null;
|
|
6236
|
+
}
|
|
6237
|
+
}
|
|
6238
|
+
function sleep(ms) {
|
|
6239
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
6240
|
+
}
|
|
6045
6241
|
/**
|
|
6046
6242
|
* Debug logging utility that respects environment debug flags.
|
|
6047
6243
|
* Logs messages through the configured structured logger when LUMIC_DEBUG
|
|
@@ -6153,9 +6349,46 @@ function hideApiKeyFromurl(url) {
|
|
|
6153
6349
|
* @throws Will throw an error if the fetch fails after the specified number of retries.
|
|
6154
6350
|
*/
|
|
6155
6351
|
async function fetchWithRetry(url, options = {}, retries = 3, initialBackoff = 1000) {
|
|
6352
|
+
// Per-host circuit-breaker check. When upstream is failing
|
|
6353
|
+
// pervasively (e.g. Massive REST in an outage), short-circuit to a
|
|
6354
|
+
// 100 ms fail-fast rejection so the caller's outer timeout (25 s,
|
|
6355
|
+
// 10 s, etc.) does not pile concurrent symbol fetches against a
|
|
6356
|
+
// dead host. Without this, an upstream outage during a screener tick
|
|
6357
|
+
// can lock up the event loop for up to (timeout × N-concurrent-symbols).
|
|
6358
|
+
const host = hostnameFromUrl(url);
|
|
6359
|
+
if (host) {
|
|
6360
|
+
const now = Date.now();
|
|
6361
|
+
if (isCircuitOpen(host, now)) {
|
|
6362
|
+
const state = getCircuitState(host);
|
|
6363
|
+
const cooldownRemainingMs = Math.max(0, CIRCUIT_OPEN_COOLDOWN_MS - (now - state.openedAt));
|
|
6364
|
+
await sleep(CIRCUIT_FAIL_FAST_LATENCY_MS);
|
|
6365
|
+
throw new CircuitOpenError(host, state.lastTripFailureRatio, cooldownRemainingMs);
|
|
6366
|
+
}
|
|
6367
|
+
}
|
|
6156
6368
|
return withRetry(async () => {
|
|
6157
|
-
|
|
6369
|
+
let response;
|
|
6370
|
+
try {
|
|
6371
|
+
response = await fetch(url, options);
|
|
6372
|
+
}
|
|
6373
|
+
catch (networkError) {
|
|
6374
|
+
// Network failure (e.g. DNS, connection refused, TLS abort).
|
|
6375
|
+
// Record against the breaker so a sustained outage trips it
|
|
6376
|
+
// for subsequent calls; then re-throw so withRetry handles
|
|
6377
|
+
// its own retry policy.
|
|
6378
|
+
if (host)
|
|
6379
|
+
recordOutcome(host, false);
|
|
6380
|
+
throw networkError;
|
|
6381
|
+
}
|
|
6158
6382
|
if (!response.ok) {
|
|
6383
|
+
// Classify the outcome for the circuit breaker. 5xx and 429
|
|
6384
|
+
// are upstream-health signals (record as failure). 4xx client
|
|
6385
|
+
// errors are caller-side and should NOT affect the breaker —
|
|
6386
|
+
// a request with a bad API key shouldn't trip the host's
|
|
6387
|
+
// breaker for everyone else.
|
|
6388
|
+
const upstreamUnhealthy = response.status === 429 ||
|
|
6389
|
+
(response.status >= 500 && response.status < 600);
|
|
6390
|
+
if (host)
|
|
6391
|
+
recordOutcome(host, !upstreamUnhealthy);
|
|
6159
6392
|
// Enhanced HTTP error handling with specific error types
|
|
6160
6393
|
if (response.status === 429) {
|
|
6161
6394
|
// Check for Retry-After header
|
|
@@ -6187,6 +6420,10 @@ async function fetchWithRetry(url, options = {}, retries = 3, initialBackoff = 1
|
|
|
6187
6420
|
error.response = response;
|
|
6188
6421
|
throw error;
|
|
6189
6422
|
}
|
|
6423
|
+
// Success — record against the breaker so a healthy upstream
|
|
6424
|
+
// closes any half-open state cleanly.
|
|
6425
|
+
if (host)
|
|
6426
|
+
recordOutcome(host, true);
|
|
6190
6427
|
return response;
|
|
6191
6428
|
}, {
|
|
6192
6429
|
maxRetries: retries,
|
|
@@ -7802,6 +8039,81 @@ const fetchTickerNews = async (ticker, options = {
|
|
|
7802
8039
|
});
|
|
7803
8040
|
};
|
|
7804
8041
|
|
|
8042
|
+
/**
|
|
8043
|
+
* Wilder ATR + EWMA-smoothed + multi-timespan variants.
|
|
8044
|
+
*
|
|
8045
|
+
* All functions are pure: same inputs → same output, no I/O, no time-dependence.
|
|
8046
|
+
*/
|
|
8047
|
+
/**
|
|
8048
|
+
* Classic Wilder ATR (single value).
|
|
8049
|
+
* @returns ATR for the most recent `period` bars, or null when insufficient bars.
|
|
8050
|
+
*/
|
|
8051
|
+
function calculateATR(highs, lows, closes, period) {
|
|
8052
|
+
if (period < 1 || !Number.isInteger(period)) {
|
|
8053
|
+
throw new Error("ATR: period must be a positive integer");
|
|
8054
|
+
}
|
|
8055
|
+
if (highs.length !== lows.length || highs.length !== closes.length) {
|
|
8056
|
+
throw new Error("ATR: highs, lows, closes must have equal length");
|
|
8057
|
+
}
|
|
8058
|
+
if (highs.length < period + 1)
|
|
8059
|
+
return null;
|
|
8060
|
+
const trs = [];
|
|
8061
|
+
for (let i = 1; i < highs.length; i++) {
|
|
8062
|
+
const tr = Math.max(highs[i] - lows[i], Math.abs(highs[i] - closes[i - 1]), Math.abs(lows[i] - closes[i - 1]));
|
|
8063
|
+
trs.push(tr);
|
|
8064
|
+
}
|
|
8065
|
+
// Wilder smoothing: first ATR = simple mean of first `period` TRs
|
|
8066
|
+
let atr = trs.slice(0, period).reduce((a, b) => a + b, 0) / period;
|
|
8067
|
+
for (let i = period; i < trs.length; i++) {
|
|
8068
|
+
atr = (atr * (period - 1) + trs[i]) / period;
|
|
8069
|
+
}
|
|
8070
|
+
return atr;
|
|
8071
|
+
}
|
|
8072
|
+
/**
|
|
8073
|
+
* Returns the EWMA-smoothed ATR series (one ATR per bar, leading nulls until `period` bars).
|
|
8074
|
+
*/
|
|
8075
|
+
function calculateATREMA(highs, lows, closes, period) {
|
|
8076
|
+
if (period < 1 || !Number.isInteger(period)) {
|
|
8077
|
+
throw new Error("ATR: period must be a positive integer");
|
|
8078
|
+
}
|
|
8079
|
+
if (highs.length !== lows.length || highs.length !== closes.length) {
|
|
8080
|
+
throw new Error("ATREMA: highs, lows, closes must have equal length");
|
|
8081
|
+
}
|
|
8082
|
+
const out = highs.map(() => null);
|
|
8083
|
+
if (highs.length < period + 1)
|
|
8084
|
+
return out;
|
|
8085
|
+
// Index 0 is a placeholder so trs[i] aligns with bar i (i >= 1); TR is undefined for the first bar (no prior close).
|
|
8086
|
+
const trs = [0];
|
|
8087
|
+
for (let i = 1; i < highs.length; i++) {
|
|
8088
|
+
trs.push(Math.max(highs[i] - lows[i], Math.abs(highs[i] - closes[i - 1]), Math.abs(lows[i] - closes[i - 1])));
|
|
8089
|
+
}
|
|
8090
|
+
let atr = trs.slice(1, period + 1).reduce((a, b) => a + b, 0) / period;
|
|
8091
|
+
out[period] = atr;
|
|
8092
|
+
for (let i = period + 1; i < trs.length; i++) {
|
|
8093
|
+
atr = (atr * (period - 1) + trs[i]) / period;
|
|
8094
|
+
out[i] = atr;
|
|
8095
|
+
}
|
|
8096
|
+
return out;
|
|
8097
|
+
}
|
|
8098
|
+
/**
|
|
8099
|
+
* Wrapper that accepts AtrBar[] (timespan-tagged); identical math, the timespan tag is
|
|
8100
|
+
* carried through for consumer-side logic only.
|
|
8101
|
+
*
|
|
8102
|
+
* @param bars - All bars must share the same timespan; the tag is metadata only
|
|
8103
|
+
* and is not validated. Mixed-timespan input produces a meaningless ATR.
|
|
8104
|
+
* @param period - Wilder lookback period (positive integer).
|
|
8105
|
+
*/
|
|
8106
|
+
function calculateATRMultiTimespan(bars, period) {
|
|
8107
|
+
return calculateATR(bars.map((b) => b.high), bars.map((b) => b.low), bars.map((b) => b.close), period);
|
|
8108
|
+
}
|
|
8109
|
+
|
|
8110
|
+
var atrNs = /*#__PURE__*/Object.freeze({
|
|
8111
|
+
__proto__: null,
|
|
8112
|
+
calculateATR: calculateATR,
|
|
8113
|
+
calculateATREMA: calculateATREMA,
|
|
8114
|
+
calculateATRMultiTimespan: calculateATRMultiTimespan
|
|
8115
|
+
});
|
|
8116
|
+
|
|
7805
8117
|
const ALPACA_API_BASE = MARKET_DATA_API.CRYPTO;
|
|
7806
8118
|
/**
|
|
7807
8119
|
* Fetches cryptocurrency bars for the specified parameters.
|
|
@@ -10851,6 +11163,335 @@ async function fetchPerformanceMetrics({ params, client, accountId, alpacaAccoun
|
|
|
10851
11163
|
}
|
|
10852
11164
|
}
|
|
10853
11165
|
|
|
11166
|
+
/**
|
|
11167
|
+
* VaR, Expected Shortfall (CVaR), conditional drawdown, rolling drawdown, Sortino, Calmar.
|
|
11168
|
+
*
|
|
11169
|
+
* Convention: VaR and ES are returned as the actual quantile value (typically negative
|
|
11170
|
+
* for losses). Drawdowns from `calculateConditionalDrawdown` are returned as non-negative
|
|
11171
|
+
* magnitudes (e.g., 0.05 = 5% drawdown). Drawdowns from `calculateRollingDrawdown` are
|
|
11172
|
+
* non-positive (e.g., -0.05 = 5% below rolling peak, 0 = at or above peak).
|
|
11173
|
+
*
|
|
11174
|
+
* All public functions reject non-finite inputs (NaN, Infinity) by throwing. Callers
|
|
11175
|
+
* must pre-validate or filter their inputs.
|
|
11176
|
+
*/
|
|
11177
|
+
function assertAlpha(alpha) {
|
|
11178
|
+
if (!(alpha > 0 && alpha < 1)) {
|
|
11179
|
+
throw new Error(`alpha must be in (0,1), got ${alpha}`);
|
|
11180
|
+
}
|
|
11181
|
+
}
|
|
11182
|
+
function assertFiniteArray$1(name, arr) {
|
|
11183
|
+
for (let i = 0; i < arr.length; i++) {
|
|
11184
|
+
if (!Number.isFinite(arr[i])) {
|
|
11185
|
+
throw new Error(`${name}: input contains non-finite value at index ${i}: ${arr[i]}`);
|
|
11186
|
+
}
|
|
11187
|
+
}
|
|
11188
|
+
}
|
|
11189
|
+
/**
|
|
11190
|
+
* Historical-bootstrap VaR at confidence `alpha`.
|
|
11191
|
+
* E.g., alpha=0.95 returns the 5%-quantile of returns (the loss at the 5th percentile).
|
|
11192
|
+
*
|
|
11193
|
+
* @returns The quantile value (typically negative), or null on empty input.
|
|
11194
|
+
*/
|
|
11195
|
+
function calculateVaRHistorical(returns, alpha) {
|
|
11196
|
+
assertAlpha(alpha);
|
|
11197
|
+
if (returns.length === 0)
|
|
11198
|
+
return null;
|
|
11199
|
+
assertFiniteArray$1("calculateVaRHistorical", returns);
|
|
11200
|
+
const sorted = [...returns].sort((a, b) => a - b);
|
|
11201
|
+
const idx = Math.max(0, Math.floor((1 - alpha) * sorted.length) - 1);
|
|
11202
|
+
return sorted[idx];
|
|
11203
|
+
}
|
|
11204
|
+
/**
|
|
11205
|
+
* Gaussian parametric VaR: μ + zα·σ where zα is the (1-alpha) standard-normal quantile.
|
|
11206
|
+
*
|
|
11207
|
+
* @returns The Gaussian quantile, or null when fewer than 2 samples.
|
|
11208
|
+
*/
|
|
11209
|
+
function calculateVaRParametric(returns, alpha) {
|
|
11210
|
+
assertAlpha(alpha);
|
|
11211
|
+
if (returns.length < 2)
|
|
11212
|
+
return null;
|
|
11213
|
+
assertFiniteArray$1("calculateVaRParametric", returns);
|
|
11214
|
+
const mean = returns.reduce((a, b) => a + b, 0) / returns.length;
|
|
11215
|
+
const variance = returns.reduce((a, b) => a + (b - mean) ** 2, 0) / (returns.length - 1);
|
|
11216
|
+
const sigma = Math.sqrt(variance);
|
|
11217
|
+
const z = inverseStdNormal(1 - alpha);
|
|
11218
|
+
return mean + z * sigma;
|
|
11219
|
+
}
|
|
11220
|
+
/**
|
|
11221
|
+
* Expected Shortfall (Conditional VaR): average of returns below the (1-alpha) quantile.
|
|
11222
|
+
*
|
|
11223
|
+
* @returns The mean tail return (typically negative), or null on empty input.
|
|
11224
|
+
*/
|
|
11225
|
+
function calculateExpectedShortfall(returns, alpha) {
|
|
11226
|
+
assertAlpha(alpha);
|
|
11227
|
+
if (returns.length === 0)
|
|
11228
|
+
return null;
|
|
11229
|
+
assertFiniteArray$1("calculateExpectedShortfall", returns);
|
|
11230
|
+
const sorted = [...returns].sort((a, b) => a - b);
|
|
11231
|
+
const cutoff = Math.max(1, Math.floor((1 - alpha) * sorted.length));
|
|
11232
|
+
const tail = sorted.slice(0, cutoff);
|
|
11233
|
+
return tail.reduce((a, b) => a + b, 0) / tail.length;
|
|
11234
|
+
}
|
|
11235
|
+
/**
|
|
11236
|
+
* Conditional Drawdown at Risk (CDaR): average of drawdowns in the worst (1-alpha) tail.
|
|
11237
|
+
* Drawdowns are computed as (peak - equity) / peak so they are non-negative.
|
|
11238
|
+
*
|
|
11239
|
+
* @returns A non-negative magnitude (0 = no drawdowns), or null for fewer than 2 samples.
|
|
11240
|
+
*/
|
|
11241
|
+
function calculateConditionalDrawdown(equity, alpha) {
|
|
11242
|
+
assertAlpha(alpha);
|
|
11243
|
+
if (equity.length < 2)
|
|
11244
|
+
return null;
|
|
11245
|
+
assertFiniteArray$1("calculateConditionalDrawdown", equity);
|
|
11246
|
+
let peak = equity[0];
|
|
11247
|
+
const drawdowns = [];
|
|
11248
|
+
for (const e of equity) {
|
|
11249
|
+
if (e > peak)
|
|
11250
|
+
peak = e;
|
|
11251
|
+
drawdowns.push(peak > 0 ? (peak - e) / peak : 0);
|
|
11252
|
+
}
|
|
11253
|
+
if (drawdowns.every((d) => d === 0))
|
|
11254
|
+
return 0;
|
|
11255
|
+
const sorted = [...drawdowns].sort((a, b) => b - a); // descending (worst first)
|
|
11256
|
+
const cutoff = Math.max(1, Math.floor((1 - alpha) * sorted.length));
|
|
11257
|
+
const tail = sorted.slice(0, cutoff);
|
|
11258
|
+
return tail.reduce((a, b) => a + b, 0) / tail.length;
|
|
11259
|
+
}
|
|
11260
|
+
/**
|
|
11261
|
+
* Rolling-window drawdown series: for each index, drawdown = (current - rollingPeak) / rollingPeak.
|
|
11262
|
+
* Non-positive values; 0 when at or above the rolling peak. Window measured in samples.
|
|
11263
|
+
*
|
|
11264
|
+
* @returns An array the same length as `equity`.
|
|
11265
|
+
*/
|
|
11266
|
+
function calculateRollingDrawdown(equity, windowSize) {
|
|
11267
|
+
if (windowSize < 1 || !Number.isInteger(windowSize)) {
|
|
11268
|
+
throw new Error("calculateRollingDrawdown: windowSize must be a positive integer");
|
|
11269
|
+
}
|
|
11270
|
+
assertFiniteArray$1("calculateRollingDrawdown", equity);
|
|
11271
|
+
return equity.map((_, i) => {
|
|
11272
|
+
const start = Math.max(0, i - windowSize + 1);
|
|
11273
|
+
const slice = equity.slice(start, i + 1);
|
|
11274
|
+
const peak = Math.max(...slice);
|
|
11275
|
+
return peak > 0 ? (equity[i] - peak) / peak : 0;
|
|
11276
|
+
});
|
|
11277
|
+
}
|
|
11278
|
+
/**
|
|
11279
|
+
* Sortino ratio: (mean excess return) / downside deviation.
|
|
11280
|
+
* Returns +Infinity when there are no downside returns.
|
|
11281
|
+
* Returns null when fewer than 2 samples.
|
|
11282
|
+
*/
|
|
11283
|
+
function calculateSortino(returns, riskFreeRate) {
|
|
11284
|
+
if (returns.length < 2)
|
|
11285
|
+
return null;
|
|
11286
|
+
assertFiniteArray$1("calculateSortino", returns);
|
|
11287
|
+
const excess = returns.map((r) => r - riskFreeRate);
|
|
11288
|
+
const meanExcess = excess.reduce((a, b) => a + b, 0) / excess.length;
|
|
11289
|
+
const downside = excess.filter((r) => r < 0);
|
|
11290
|
+
if (downside.length === 0)
|
|
11291
|
+
return Number.POSITIVE_INFINITY;
|
|
11292
|
+
const dd = Math.sqrt(downside.reduce((a, b) => a + b * b, 0) / downside.length);
|
|
11293
|
+
return meanExcess / dd;
|
|
11294
|
+
}
|
|
11295
|
+
/**
|
|
11296
|
+
* Calmar ratio: CAGR / |max drawdown|.
|
|
11297
|
+
*
|
|
11298
|
+
* @returns null when there is no drawdown (division by zero), fewer than 2 samples,
|
|
11299
|
+
* or `equity[0] <= 0` (CAGR undefined).
|
|
11300
|
+
*/
|
|
11301
|
+
function calculateCalmar(equity, periodsPerYear) {
|
|
11302
|
+
if (equity.length < 2)
|
|
11303
|
+
return null;
|
|
11304
|
+
if (equity[0] <= 0)
|
|
11305
|
+
return null;
|
|
11306
|
+
if (periodsPerYear <= 0) {
|
|
11307
|
+
throw new Error("calculateCalmar: periodsPerYear must be > 0");
|
|
11308
|
+
}
|
|
11309
|
+
assertFiniteArray$1("calculateCalmar", equity);
|
|
11310
|
+
const total = equity[equity.length - 1] / equity[0];
|
|
11311
|
+
const years = (equity.length - 1) / periodsPerYear;
|
|
11312
|
+
const cagr = years > 0 ? Math.pow(total, 1 / years) - 1 : 0;
|
|
11313
|
+
let peak = equity[0];
|
|
11314
|
+
let maxDd = 0;
|
|
11315
|
+
for (const e of equity) {
|
|
11316
|
+
if (e > peak)
|
|
11317
|
+
peak = e;
|
|
11318
|
+
const dd = peak > 0 ? (peak - e) / peak : 0;
|
|
11319
|
+
if (dd > maxDd)
|
|
11320
|
+
maxDd = dd;
|
|
11321
|
+
}
|
|
11322
|
+
return maxDd === 0 ? null : cagr / maxDd;
|
|
11323
|
+
}
|
|
11324
|
+
/**
|
|
11325
|
+
* Beasley-Springer-Moro approximation of the inverse standard normal CDF.
|
|
11326
|
+
* Accurate to ~1e-9 across the full domain; sufficient for VaR work.
|
|
11327
|
+
*/
|
|
11328
|
+
function inverseStdNormal(p) {
|
|
11329
|
+
if (p <= 0 || p >= 1)
|
|
11330
|
+
throw new Error("p must be in (0,1)");
|
|
11331
|
+
const a = [-39.69683028665376, 2.209460984245205e2, -275.9285104469687,
|
|
11332
|
+
1.38357751867269e2, -30.66479806614716, 2.506628277459239];
|
|
11333
|
+
const b = [-54.47609879822406, 1.615858368580409e2, -155.6989798598866,
|
|
11334
|
+
6.680131188771972e1, -13.28068155288572];
|
|
11335
|
+
const c = [-0.007784894002430293, -0.3223964580411365, -2.400758277161838,
|
|
11336
|
+
-2.549732539343734, 4.374664141464968, 2.938163982698783];
|
|
11337
|
+
const d = [7.784695709041462e-3, 3.224671290700398e-1, 2.445134137142996,
|
|
11338
|
+
3.754408661907416];
|
|
11339
|
+
const pLow = 0.02425;
|
|
11340
|
+
const pHigh = 1 - pLow;
|
|
11341
|
+
let q, r;
|
|
11342
|
+
if (p < pLow) {
|
|
11343
|
+
q = Math.sqrt(-2 * Math.log(p));
|
|
11344
|
+
return (((((c[0] * q + c[1]) * q + c[2]) * q + c[3]) * q + c[4]) * q + c[5]) /
|
|
11345
|
+
((((d[0] * q + d[1]) * q + d[2]) * q + d[3]) * q + 1);
|
|
11346
|
+
}
|
|
11347
|
+
if (p <= pHigh) {
|
|
11348
|
+
q = p - 0.5;
|
|
11349
|
+
r = q * q;
|
|
11350
|
+
return (((((a[0] * r + a[1]) * r + a[2]) * r + a[3]) * r + a[4]) * r + a[5]) * q /
|
|
11351
|
+
(((((b[0] * r + b[1]) * r + b[2]) * r + b[3]) * r + b[4]) * r + 1);
|
|
11352
|
+
}
|
|
11353
|
+
q = Math.sqrt(-2 * Math.log(1 - p));
|
|
11354
|
+
return -(((((c[0] * q + c[1]) * q + c[2]) * q + c[3]) * q + c[4]) * q + c[5]) /
|
|
11355
|
+
((((d[0] * q + d[1]) * q + d[2]) * q + d[3]) * q + 1);
|
|
11356
|
+
}
|
|
11357
|
+
|
|
11358
|
+
var riskNs = /*#__PURE__*/Object.freeze({
|
|
11359
|
+
__proto__: null,
|
|
11360
|
+
calculateCalmar: calculateCalmar,
|
|
11361
|
+
calculateConditionalDrawdown: calculateConditionalDrawdown,
|
|
11362
|
+
calculateExpectedShortfall: calculateExpectedShortfall,
|
|
11363
|
+
calculateRollingDrawdown: calculateRollingDrawdown,
|
|
11364
|
+
calculateSortino: calculateSortino,
|
|
11365
|
+
calculateVaRHistorical: calculateVaRHistorical,
|
|
11366
|
+
calculateVaRParametric: calculateVaRParametric
|
|
11367
|
+
});
|
|
11368
|
+
|
|
11369
|
+
/**
|
|
11370
|
+
* Per-strategy rolling metrics and backtest-divergence z-score.
|
|
11371
|
+
*
|
|
11372
|
+
* Conventions:
|
|
11373
|
+
* - tradePnls / tradeReturns is an array of per-trade realised P&L or return
|
|
11374
|
+
* (positive = win, negative = loss, zero = breakeven).
|
|
11375
|
+
* - All "rolling*" functions return null when fewer than `windowSize` trades exist.
|
|
11376
|
+
* - All public functions reject non-finite inputs (NaN, Infinity) by throwing.
|
|
11377
|
+
* Callers must pre-validate or filter their inputs.
|
|
11378
|
+
*/
|
|
11379
|
+
function assertWindowSize(name, windowSize) {
|
|
11380
|
+
if (windowSize < 1 || !Number.isInteger(windowSize)) {
|
|
11381
|
+
throw new Error(`${name}: windowSize must be a positive integer`);
|
|
11382
|
+
}
|
|
11383
|
+
}
|
|
11384
|
+
function assertFiniteArray(name, arr) {
|
|
11385
|
+
for (let i = 0; i < arr.length; i++) {
|
|
11386
|
+
if (!Number.isFinite(arr[i])) {
|
|
11387
|
+
throw new Error(`${name}: input contains non-finite value at index ${i}: ${arr[i]}`);
|
|
11388
|
+
}
|
|
11389
|
+
}
|
|
11390
|
+
}
|
|
11391
|
+
/**
|
|
11392
|
+
* Rolling expectancy: mean P&L over the most-recent `windowSize` trades.
|
|
11393
|
+
*
|
|
11394
|
+
* @param tradePnls - Array of per-trade realised P&L values.
|
|
11395
|
+
* @param windowSize - Number of most-recent trades to include. Must be a positive integer.
|
|
11396
|
+
* @returns Mean P&L of the last `windowSize` trades, or null when fewer than `windowSize` exist.
|
|
11397
|
+
* @throws When `windowSize` is not a positive integer or any input is non-finite.
|
|
11398
|
+
*/
|
|
11399
|
+
function calculateRollingExpectancy(tradePnls, windowSize) {
|
|
11400
|
+
assertWindowSize("calculateRollingExpectancy", windowSize);
|
|
11401
|
+
if (tradePnls.length < windowSize)
|
|
11402
|
+
return null;
|
|
11403
|
+
assertFiniteArray("calculateRollingExpectancy", tradePnls);
|
|
11404
|
+
const slice = tradePnls.slice(-windowSize);
|
|
11405
|
+
return slice.reduce((a, b) => a + b, 0) / windowSize;
|
|
11406
|
+
}
|
|
11407
|
+
/**
|
|
11408
|
+
* Rolling hit-rate: fraction of strictly-positive P&L trades in the most-recent
|
|
11409
|
+
* `windowSize` trades. Zero P&L counts as non-win.
|
|
11410
|
+
*
|
|
11411
|
+
* @param tradePnls - Array of per-trade realised P&L values.
|
|
11412
|
+
* @param windowSize - Number of most-recent trades to include. Must be a positive integer.
|
|
11413
|
+
* @returns Fraction of winning trades in the window, or null when fewer than `windowSize` exist.
|
|
11414
|
+
* @throws When `windowSize` is not a positive integer or any input is non-finite.
|
|
11415
|
+
*/
|
|
11416
|
+
function calculateRollingHitRate(tradePnls, windowSize) {
|
|
11417
|
+
assertWindowSize("calculateRollingHitRate", windowSize);
|
|
11418
|
+
if (tradePnls.length < windowSize)
|
|
11419
|
+
return null;
|
|
11420
|
+
assertFiniteArray("calculateRollingHitRate", tradePnls);
|
|
11421
|
+
const slice = tradePnls.slice(-windowSize);
|
|
11422
|
+
const wins = slice.filter((p) => p > 0).length;
|
|
11423
|
+
return wins / windowSize;
|
|
11424
|
+
}
|
|
11425
|
+
/**
|
|
11426
|
+
* Rolling profit factor: sum(wins) / |sum(losses)| over the most-recent `windowSize` trades.
|
|
11427
|
+
*
|
|
11428
|
+
* Edge cases:
|
|
11429
|
+
* - no losses and at least one win → +Infinity
|
|
11430
|
+
* - no wins and no losses (all zeros) → 0
|
|
11431
|
+
* - fewer than windowSize trades → null
|
|
11432
|
+
*
|
|
11433
|
+
* @param tradePnls - Array of per-trade realised P&L values.
|
|
11434
|
+
* @param windowSize - Number of most-recent trades to include. Must be a positive integer.
|
|
11435
|
+
* @returns Profit factor for the rolling window, or null when fewer than `windowSize` exist.
|
|
11436
|
+
* @throws When `windowSize` is not a positive integer or any input is non-finite.
|
|
11437
|
+
*/
|
|
11438
|
+
function calculateRollingProfitFactor(tradePnls, windowSize) {
|
|
11439
|
+
assertWindowSize("calculateRollingProfitFactor", windowSize);
|
|
11440
|
+
if (tradePnls.length < windowSize)
|
|
11441
|
+
return null;
|
|
11442
|
+
assertFiniteArray("calculateRollingProfitFactor", tradePnls);
|
|
11443
|
+
const slice = tradePnls.slice(-windowSize);
|
|
11444
|
+
const wins = slice.filter((p) => p > 0).reduce((a, b) => a + b, 0);
|
|
11445
|
+
const losses = slice.filter((p) => p < 0).reduce((a, b) => a + Math.abs(b), 0);
|
|
11446
|
+
if (losses === 0)
|
|
11447
|
+
return wins > 0 ? Number.POSITIVE_INFINITY : 0;
|
|
11448
|
+
return wins / losses;
|
|
11449
|
+
}
|
|
11450
|
+
/**
|
|
11451
|
+
* Rolling Sortino: delegate to `calculateSortino` over the most-recent `windowSize` returns.
|
|
11452
|
+
*
|
|
11453
|
+
* @param tradeReturns - Array of per-trade return values.
|
|
11454
|
+
* @param windowSize - Number of most-recent trades to include. Must be a positive integer.
|
|
11455
|
+
* @param riskFreeRate - Risk-free rate to subtract from returns (default 0).
|
|
11456
|
+
* @returns Sortino ratio for the rolling window, or null when fewer than `windowSize` exist.
|
|
11457
|
+
* @throws When `windowSize` is not a positive integer or any input is non-finite.
|
|
11458
|
+
*/
|
|
11459
|
+
function calculateRollingSortino(tradeReturns, windowSize, riskFreeRate = 0) {
|
|
11460
|
+
assertWindowSize("calculateRollingSortino", windowSize);
|
|
11461
|
+
if (tradeReturns.length < windowSize)
|
|
11462
|
+
return null;
|
|
11463
|
+
assertFiniteArray("calculateRollingSortino", tradeReturns);
|
|
11464
|
+
return calculateSortino(tradeReturns.slice(-windowSize), riskFreeRate);
|
|
11465
|
+
}
|
|
11466
|
+
/**
|
|
11467
|
+
* Z-score of live-expectancy vs backtest-expectancy, scaled by the backtest stddev.
|
|
11468
|
+
* Positive Z = live outperforming; negative Z = live underperforming.
|
|
11469
|
+
*
|
|
11470
|
+
* @param liveExpectancy - Mean P&L per trade in the live window.
|
|
11471
|
+
* @param backtestExpectancy - Mean P&L per trade from the calibration backtest.
|
|
11472
|
+
* @param backtestStddev - Stddev of per-trade P&L in the backtest. Must be > 0.
|
|
11473
|
+
* @returns Z-score measuring divergence between live and backtest performance.
|
|
11474
|
+
* @throws When any input is non-finite or `backtestStddev` is not positive.
|
|
11475
|
+
*/
|
|
11476
|
+
function calculateBacktestDivergenceZ(liveExpectancy, backtestExpectancy, backtestStddev) {
|
|
11477
|
+
if (!Number.isFinite(liveExpectancy) || !Number.isFinite(backtestExpectancy) || !Number.isFinite(backtestStddev)) {
|
|
11478
|
+
throw new Error("calculateBacktestDivergenceZ: inputs must be finite numbers");
|
|
11479
|
+
}
|
|
11480
|
+
if (backtestStddev <= 0) {
|
|
11481
|
+
throw new Error("calculateBacktestDivergenceZ: stddev must be > 0");
|
|
11482
|
+
}
|
|
11483
|
+
return (liveExpectancy - backtestExpectancy) / backtestStddev;
|
|
11484
|
+
}
|
|
11485
|
+
|
|
11486
|
+
var strategyNs = /*#__PURE__*/Object.freeze({
|
|
11487
|
+
__proto__: null,
|
|
11488
|
+
calculateBacktestDivergenceZ: calculateBacktestDivergenceZ,
|
|
11489
|
+
calculateRollingExpectancy: calculateRollingExpectancy,
|
|
11490
|
+
calculateRollingHitRate: calculateRollingHitRate,
|
|
11491
|
+
calculateRollingProfitFactor: calculateRollingProfitFactor,
|
|
11492
|
+
calculateRollingSortino: calculateRollingSortino
|
|
11493
|
+
});
|
|
11494
|
+
|
|
10854
11495
|
/**
|
|
10855
11496
|
* Calculates Bollinger Bands for a given set of price data.
|
|
10856
11497
|
* Bollinger Bands consist of a middle band (SMA) and two outer bands
|
|
@@ -11477,6 +12118,98 @@ var Types = /*#__PURE__*/Object.freeze({
|
|
|
11477
12118
|
__proto__: null
|
|
11478
12119
|
});
|
|
11479
12120
|
|
|
12121
|
+
/**
|
|
12122
|
+
* Realized and EWMA volatility + regime classifier + annualisation helper.
|
|
12123
|
+
* All functions pure.
|
|
12124
|
+
*/
|
|
12125
|
+
/**
|
|
12126
|
+
* Sample standard deviation (Bessel-corrected) of returns over the most recent
|
|
12127
|
+
* `window` samples.
|
|
12128
|
+
* @returns null when fewer than `window` samples.
|
|
12129
|
+
*/
|
|
12130
|
+
function calculateRealizedVolatility(returns, window) {
|
|
12131
|
+
if (window < 2 || !Number.isInteger(window)) {
|
|
12132
|
+
throw new Error("calculateRealizedVolatility: window must be an integer >= 2");
|
|
12133
|
+
}
|
|
12134
|
+
if (returns.length < window)
|
|
12135
|
+
return null;
|
|
12136
|
+
const slice = returns.slice(-window);
|
|
12137
|
+
const mean = slice.reduce((a, b) => a + b, 0) / window;
|
|
12138
|
+
const variance = slice.reduce((a, b) => a + (b - mean) ** 2, 0) / (window - 1);
|
|
12139
|
+
return Math.sqrt(variance);
|
|
12140
|
+
}
|
|
12141
|
+
/**
|
|
12142
|
+
* EWMA volatility (RiskMetrics-style). λ ∈ (0,1); higher = longer memory.
|
|
12143
|
+
* Default usage: λ = 0.94 for daily returns.
|
|
12144
|
+
*
|
|
12145
|
+
* For a single-element input, the function returns `|returns[0]|` (the seed)
|
|
12146
|
+
* since no smoothing iterations are possible.
|
|
12147
|
+
*
|
|
12148
|
+
* @param returns - Period returns (e.g., log returns or simple returns).
|
|
12149
|
+
* @param lambda - Decay factor in (0,1).
|
|
12150
|
+
* @returns EWMA standard deviation, or null on empty input.
|
|
12151
|
+
* @throws when `lambda` is outside (0,1).
|
|
12152
|
+
*/
|
|
12153
|
+
function calculateEWMAVolatility(returns, lambda) {
|
|
12154
|
+
if (lambda <= 0 || lambda >= 1) {
|
|
12155
|
+
throw new Error("calculateEWMAVolatility: lambda must be in (0,1)");
|
|
12156
|
+
}
|
|
12157
|
+
if (returns.length === 0)
|
|
12158
|
+
return null;
|
|
12159
|
+
let variance = returns[0] ** 2;
|
|
12160
|
+
for (let i = 1; i < returns.length; i++) {
|
|
12161
|
+
variance = lambda * variance + (1 - lambda) * returns[i] ** 2;
|
|
12162
|
+
}
|
|
12163
|
+
return Math.sqrt(variance);
|
|
12164
|
+
}
|
|
12165
|
+
/**
|
|
12166
|
+
* Classify a volatility value into one of four regimes.
|
|
12167
|
+
*
|
|
12168
|
+
* Bands are checked in the order: crisis (≥crisisMin) → elevated (≥elevatedMax)
|
|
12169
|
+
* → calm (≤calmMax) → normal (otherwise).
|
|
12170
|
+
*
|
|
12171
|
+
* @throws when bands are not strictly ordered (calmMax < elevatedMax < crisisMin).
|
|
12172
|
+
*/
|
|
12173
|
+
function detectVolatilityRegime(volatility, bands) {
|
|
12174
|
+
if (!(bands.calmMax < bands.elevatedMax && bands.elevatedMax < bands.crisisMin)) {
|
|
12175
|
+
throw new Error(`detectVolatilityRegime: bands must satisfy calmMax < elevatedMax < crisisMin (got ${JSON.stringify(bands)})`);
|
|
12176
|
+
}
|
|
12177
|
+
if (volatility >= bands.crisisMin)
|
|
12178
|
+
return "crisis";
|
|
12179
|
+
if (volatility >= bands.elevatedMax)
|
|
12180
|
+
return "elevated";
|
|
12181
|
+
if (volatility <= bands.calmMax)
|
|
12182
|
+
return "calm";
|
|
12183
|
+
return "normal";
|
|
12184
|
+
}
|
|
12185
|
+
/**
|
|
12186
|
+
* Annualise a volatility computed at the given cadence by multiplying by
|
|
12187
|
+
* the square root of the periods per year.
|
|
12188
|
+
*
|
|
12189
|
+
* - daily → sqrt(252) (252 trading days per year)
|
|
12190
|
+
* - hourly → sqrt(252 × 6.5) (6.5 RTH hours per trading day)
|
|
12191
|
+
* - minute → sqrt(252 × 6.5 × 60) (60 minutes per RTH hour)
|
|
12192
|
+
*
|
|
12193
|
+
* @param volatility - Per-period volatility (stddev).
|
|
12194
|
+
* @param cadence - The cadence at which `volatility` was sampled.
|
|
12195
|
+
* @returns The annualised volatility.
|
|
12196
|
+
*/
|
|
12197
|
+
function annualiseVolatility(volatility, cadence) {
|
|
12198
|
+
switch (cadence) {
|
|
12199
|
+
case "daily": return volatility * Math.sqrt(252);
|
|
12200
|
+
case "hourly": return volatility * Math.sqrt(252 * 6.5);
|
|
12201
|
+
case "minute": return volatility * Math.sqrt(252 * 6.5 * 60);
|
|
12202
|
+
}
|
|
12203
|
+
}
|
|
12204
|
+
|
|
12205
|
+
var volatilityNs = /*#__PURE__*/Object.freeze({
|
|
12206
|
+
__proto__: null,
|
|
12207
|
+
annualiseVolatility: annualiseVolatility,
|
|
12208
|
+
calculateEWMAVolatility: calculateEWMAVolatility,
|
|
12209
|
+
calculateRealizedVolatility: calculateRealizedVolatility,
|
|
12210
|
+
detectVolatilityRegime: detectVolatilityRegime
|
|
12211
|
+
});
|
|
12212
|
+
|
|
11480
12213
|
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
|
|
11481
12214
|
|
|
11482
12215
|
function getDefaultExportFromCjs (x) {
|
|
@@ -68695,6 +69428,10 @@ const createAlpacaMarketDataAPI = () => {
|
|
|
68695
69428
|
};
|
|
68696
69429
|
const adaptic = {
|
|
68697
69430
|
types: Types,
|
|
69431
|
+
atr: atrNs,
|
|
69432
|
+
risk: riskNs,
|
|
69433
|
+
strategy: strategyNs,
|
|
69434
|
+
volatility: volatilityNs,
|
|
68698
69435
|
backend: {
|
|
68699
69436
|
fetchAssetOverview: fetchAssetOverview,
|
|
68700
69437
|
getApolloClient: getSharedApolloClient,
|
|
@@ -68877,6 +69614,17 @@ const adaptic = {
|
|
|
68877
69614
|
logIfDebug: logIfDebug,
|
|
68878
69615
|
fetchWithRetry: fetchWithRetry,
|
|
68879
69616
|
validateMassiveApiKey: validateMassiveApiKey,
|
|
69617
|
+
/**
|
|
69618
|
+
* Force-close a stuck-open per-host circuit breaker. Operator
|
|
69619
|
+
* runbook utility — see {@link misc.resetCircuitBreaker}.
|
|
69620
|
+
*/
|
|
69621
|
+
resetCircuitBreaker: resetCircuitBreaker,
|
|
69622
|
+
/**
|
|
69623
|
+
* Read-only snapshot of all per-host circuit-breaker states for
|
|
69624
|
+
* use in operational-truth endpoints. See
|
|
69625
|
+
* {@link misc.getCircuitBreakerSnapshot}.
|
|
69626
|
+
*/
|
|
69627
|
+
getCircuitBreakerSnapshot: getCircuitBreakerSnapshot,
|
|
68880
69628
|
},
|
|
68881
69629
|
rateLimiter: {
|
|
68882
69630
|
TokenBucketRateLimiter,
|
|
@@ -68885,5 +69633,5 @@ const adaptic = {
|
|
|
68885
69633
|
};
|
|
68886
69634
|
const adptc = adaptic;
|
|
68887
69635
|
|
|
68888
|
-
export { API_RETRY_CONFIGS, AVNewsArticleSchema, AVNewsResponseSchema, AdapticUtilsError, AlpacaAccountDetailsSchema, AlpacaApiError, AlpacaBarSchema, AlpacaClient, AlpacaCryptoBarsResponseSchema, AlpacaHistoricalBarsResponseSchema, AlpacaLatestBarsResponseSchema, AlpacaLatestQuotesResponseSchema, AlpacaLatestTradesResponseSchema, AlpacaMarketDataAPI, AlpacaNewsArticleSchema, AlpacaNewsResponseSchema, AlpacaOrderSchema, AlpacaOrdersArraySchema, AlpacaPortfolioHistoryResponseSchema, AlpacaPositionSchema, AlpacaPositionsArraySchema, AlpacaQuoteSchema, AlpacaTradeSchema, AlpacaTradingAPI, AlphaVantageError, AlphaVantageQuoteResponseSchema, AssetAllocationEngine, AuthenticationError, AutonomyMode, BTC_PAIRS, BarError, CryptoDataError, CryptoOrderError, DEFAULT_CACHE_OPTIONS, DEFAULT_RISK_FREE_RATE, DEFAULT_TIMEOUTS, DEFAULT_TRADING_POLICY, DataFormatError, DecisionMemoryOutcome, DecisionOutcome, DecisionRecordStatus, HttpClientError, HttpServerError, KEEP_ALIVE_DEFAULTS, LlmProvider, MARKET_DATA_API, MassiveAggregatesResponseSchema, MassiveApiError, MassiveDailyOpenCloseSchema, MassiveErrorResponseSchema, MassiveGroupedDailyResponseSchema, MassiveLastTradeResponseSchema, MassiveTickerDetailsResponseSchema, MassiveTickerInfoSchema, MassiveTradeSchema as MassiveTradeZodSchema, MassiveTradesResponseSchema, NetworkError, NewsError, OptionStrategyError, OptionsDataError, OverlaySeverity, OverlayStatus, OverlayType, QuoteError, RISK_FREE_RATE_TTL_MS, RateLimitError, RawMassivePriceDataSchema, StampedeProtectedCache, TRADING_API, TimeoutError, TokenBucketRateLimiter, TradeError, TrailingStopValidationError, USDC_PAIRS, USDT_PAIRS, USD_PAIRS, ValidationError, ValidationResponseError, WEBSOCKET_STREAMS, WebSocketError, account, adaptic, adptc, alpaca, analyzeBars, approximateImpliedVolatility, bracketOrders, buildOCCSymbol, buildOptionSymbol, buyCryptoNotional, buyToClose, buyToOpen, buyWithStopLoss, buyWithTrailingStop, calculateMoneyness, calculateOrderValue, calculatePeriodPerformance, calculatePutCallRatio, calculateTotalFilledValue, cancelAllCryptoOrders, cancelOCOOrder, cancelOTOOrder, cancelTrailingStop, cancelTrailingStopsForSymbol, checkTradingEligibility, clearClientCache, clock, closeAllOptionPositions, closeOptionPosition, createAlpacaClient, createAlpacaMarketDataAPI, createAlpacaTradingAPI, createBracketOrder, createButterflySpread, createClientFromEnv, createCoveredCall, createCryptoLimitOrder, createCryptoMarketOrder, createCryptoOrder, createCryptoStopLimitOrder, createCryptoStopOrder, createExecutorFromTradingAPI, createIronCondor$1 as createIronCondor, createIronCondor as createIronCondorAdvanced, createMultiLegOptionOrder, createOCOOrder, createOTOOrder, createOptionOrder, createPortfolioTrailingStops, createProtectiveBracket, createStampedeProtectedCache, createStraddle$1 as createStraddle, createStraddle as createStraddleAdvanced, createStrangle$1 as createStrangle, createStrangle as createStrangleAdvanced, createStreamManager, createTimeoutSignal, createTrailingStop, createVerticalSpread$1 as createVerticalSpread, createVerticalSpread as createVerticalSpreadAdvanced, entryWithPercentStopLoss, exerciseOption, extractGreeks, filterByExpiration, filterByStrike, filterByType, filterOrdersByDateRange, findATMOptions, findATMStrikes, findNearestExpiration, findOptionsByDelta, formatOrderForLog, formatOrderSummary, generateOptimalAllocation, getAccountConfiguration, getAccountDetails, getAccountSummary, getAgentPoolStatus, getAllOrders, getAlpacaCalendar, getAlpacaClock, getAverageDailyVolume, getBars, getBuyingPower, getCachedRiskFreeRateSync, getCachedRiskFreeRateSyncWithProvenance, getCrypto24HourChange, getCryptoBars, getCryptoDailyPrices, getCryptoPairsByQuote, getCryptoPrice, getCryptoSnapshots, getCryptoSpread, getCryptoStreamUrl, getCryptoTrades, getCurrentPrice, getCurrentPrices, getDailyPrices, getDailyReturns, getDaysToExpiration, getDefaultRiskProfile, getEquityCurve, getExpirationDates, getFilledOrders, getGroupedOptionChain, getHistoricalOptionsBars, getHistoricalTrades, getIntradayPrices, getLatestBars, getLatestCryptoQuotes, getLatestCryptoTrades, getLatestNews, getLatestOptionsQuotes, getLatestOptionsTrades, getLatestQuote, getLatestQuotes, getLatestTrade, getLatestTrades, getLogger, getMarginInfo, getNews, getNewsForSymbols, getOCOOrderStatus, getOTOOrderStatus, getOpenCryptoOrders, getOpenOrders$1 as getOpenOrdersQuery, getOpenTrailingStops, getOptionChain, getOptionContract, getOptionContracts, getOptionSpread, getOptionsChain, getOptionsSnapshots, getOptionsStreamUrl, getOptionsTradingLevel, getOrderHistory, getOrdersBySymbol, getPDTStatus, getPopularCryptoPairs, getPortfolioHistory, getPreviousClose, getPriceRange, getRiskFreeRate, getRiskFreeRateWithProvenance, getSpread, getSpreads, getStockStreamUrl, getStrikePrices, getSupportedCryptoPairs, getSymbolSentiment, getTimeout, getTradeVolume, getTradingApiUrl, getTradingWebSocketUrl, getTrailingStopHWM, groupOrdersByStatus, groupOrdersBySymbol, hasActiveTrailingStop, hasGoodLiquidity as hasOptionLiquidity, hasGoodLiquidity$1 as hasStockLiquidity, hasSufficientVolume, httpAgent, httpsAgent, isContractTradable, isCryptoPair, isExpiringWithin, isMarginAccount, isOptionOrderCancelable, isOptionOrderTerminal, isOrderFillable, isOrderFilled, isOrderOpen, isOrderTerminal$1 as isOrderTerminalStatus, isSupportedCryptoPair, isTransientNetworkError, index$1 as legacyApi, limitBuyWithTakeProfit, ocoOrders, orderUtils, otoOrders, paginate, paginateAll, parseOCCSymbol, protectLongPosition, protectShortPosition, rateLimiters, resetLogger, resetRiskFreeRateCache, rollOptionPosition, roundPriceForAlpaca$3 as roundPriceForAlpaca, roundPriceForAlpacaNumber, safeValidateResponse, searchNews, sellAllCrypto, sellCryptoNotional, sellToClose, sellToOpen, setLogger, setRiskFreeRate, shortWithStopLoss, sortOrdersByDate, index as tradingPolicy, trailingStops, updateAccountConfiguration, updateTrailingStop, validateAlpacaCredentials, validateAlphaVantageApiKey, validateMassiveApiKey$1 as validateMassiveApiKey, validateMultiLegOrder, validateResponse, verifyFetchKeepAlive, waitForOrderFill, withRetry, withTimeout };
|
|
69636
|
+
export { API_RETRY_CONFIGS, AVNewsArticleSchema, AVNewsResponseSchema, AdapticUtilsError, AlpacaAccountDetailsSchema, AlpacaApiError, AlpacaBarSchema, AlpacaClient, AlpacaCryptoBarsResponseSchema, AlpacaHistoricalBarsResponseSchema, AlpacaLatestBarsResponseSchema, AlpacaLatestQuotesResponseSchema, AlpacaLatestTradesResponseSchema, AlpacaMarketDataAPI, AlpacaNewsArticleSchema, AlpacaNewsResponseSchema, AlpacaOrderSchema, AlpacaOrdersArraySchema, AlpacaPortfolioHistoryResponseSchema, AlpacaPositionSchema, AlpacaPositionsArraySchema, AlpacaQuoteSchema, AlpacaTradeSchema, AlpacaTradingAPI, AlphaVantageError, AlphaVantageQuoteResponseSchema, AssetAllocationEngine, AuthenticationError, AutonomyMode, BTC_PAIRS, BarError, CircuitOpenError, CryptoDataError, CryptoOrderError, DEFAULT_CACHE_OPTIONS, DEFAULT_RISK_FREE_RATE, DEFAULT_TIMEOUTS, DEFAULT_TRADING_POLICY, DataFormatError, DecisionMemoryOutcome, DecisionOutcome, DecisionRecordStatus, HttpClientError, HttpServerError, KEEP_ALIVE_DEFAULTS, LlmProvider, MARKET_DATA_API, MassiveAggregatesResponseSchema, MassiveApiError, MassiveDailyOpenCloseSchema, MassiveErrorResponseSchema, MassiveGroupedDailyResponseSchema, MassiveLastTradeResponseSchema, MassiveTickerDetailsResponseSchema, MassiveTickerInfoSchema, MassiveTradeSchema as MassiveTradeZodSchema, MassiveTradesResponseSchema, NetworkError, NewsError, OptionStrategyError, OptionsDataError, OverlaySeverity, OverlayStatus, OverlayType, QuoteError, RISK_FREE_RATE_TTL_MS, RateLimitError, RawMassivePriceDataSchema, StampedeProtectedCache, TRADING_API, TimeoutError, TokenBucketRateLimiter, TradeError, TrailingStopValidationError, USDC_PAIRS, USDT_PAIRS, USD_PAIRS, ValidationError, ValidationResponseError, WEBSOCKET_STREAMS, WebSocketError, account, adaptic, adptc, alpaca, analyzeBars, approximateImpliedVolatility, atrNs as atr, bracketOrders, buildOCCSymbol, buildOptionSymbol, buyCryptoNotional, buyToClose, buyToOpen, buyWithStopLoss, buyWithTrailingStop, calculateMoneyness, calculateOrderValue, calculatePeriodPerformance, calculatePutCallRatio, calculateTotalFilledValue, cancelAllCryptoOrders, cancelOCOOrder, cancelOTOOrder, cancelTrailingStop, cancelTrailingStopsForSymbol, checkTradingEligibility, clearClientCache, clock, closeAllOptionPositions, closeOptionPosition, createAlpacaClient, createAlpacaMarketDataAPI, createAlpacaTradingAPI, createBracketOrder, createButterflySpread, createClientFromEnv, createCoveredCall, createCryptoLimitOrder, createCryptoMarketOrder, createCryptoOrder, createCryptoStopLimitOrder, createCryptoStopOrder, createExecutorFromTradingAPI, createIronCondor$1 as createIronCondor, createIronCondor as createIronCondorAdvanced, createMultiLegOptionOrder, createOCOOrder, createOTOOrder, createOptionOrder, createPortfolioTrailingStops, createProtectiveBracket, createStampedeProtectedCache, createStraddle$1 as createStraddle, createStraddle as createStraddleAdvanced, createStrangle$1 as createStrangle, createStrangle as createStrangleAdvanced, createStreamManager, createTimeoutSignal, createTrailingStop, createVerticalSpread$1 as createVerticalSpread, createVerticalSpread as createVerticalSpreadAdvanced, entryWithPercentStopLoss, exerciseOption, extractGreeks, filterByExpiration, filterByStrike, filterByType, filterOrdersByDateRange, findATMOptions, findATMStrikes, findNearestExpiration, findOptionsByDelta, formatOrderForLog, formatOrderSummary, generateOptimalAllocation, getAccountConfiguration, getAccountDetails, getAccountSummary, getAgentPoolStatus, getAllOrders, getAlpacaCalendar, getAlpacaClock, getAverageDailyVolume, getBars, getBuyingPower, getCachedRiskFreeRateSync, getCachedRiskFreeRateSyncWithProvenance, getCrypto24HourChange, getCryptoBars, getCryptoDailyPrices, getCryptoPairsByQuote, getCryptoPrice, getCryptoSnapshots, getCryptoSpread, getCryptoStreamUrl, getCryptoTrades, getCurrentPrice, getCurrentPrices, getDailyPrices, getDailyReturns, getDaysToExpiration, getDefaultRiskProfile, getEquityCurve, getExpirationDates, getFilledOrders, getGroupedOptionChain, getHistoricalOptionsBars, getHistoricalTrades, getIntradayPrices, getLatestBars, getLatestCryptoQuotes, getLatestCryptoTrades, getLatestNews, getLatestOptionsQuotes, getLatestOptionsTrades, getLatestQuote, getLatestQuotes, getLatestTrade, getLatestTrades, getLogger, getMarginInfo, getNews, getNewsForSymbols, getOCOOrderStatus, getOTOOrderStatus, getOpenCryptoOrders, getOpenOrders$1 as getOpenOrdersQuery, getOpenTrailingStops, getOptionChain, getOptionContract, getOptionContracts, getOptionSpread, getOptionsChain, getOptionsSnapshots, getOptionsStreamUrl, getOptionsTradingLevel, getOrderHistory, getOrdersBySymbol, getPDTStatus, getPopularCryptoPairs, getPortfolioHistory, getPreviousClose, getPriceRange, getRiskFreeRate, getRiskFreeRateWithProvenance, getSpread, getSpreads, getStockStreamUrl, getStrikePrices, getSupportedCryptoPairs, getSymbolSentiment, getTimeout, getTradeVolume, getTradingApiUrl, getTradingWebSocketUrl, getTrailingStopHWM, groupOrdersByStatus, groupOrdersBySymbol, hasActiveTrailingStop, hasGoodLiquidity as hasOptionLiquidity, hasGoodLiquidity$1 as hasStockLiquidity, hasSufficientVolume, httpAgent, httpsAgent, isContractTradable, isCryptoPair, isExpiringWithin, isMarginAccount, isOptionOrderCancelable, isOptionOrderTerminal, isOrderFillable, isOrderFilled, isOrderOpen, isOrderTerminal$1 as isOrderTerminalStatus, isSupportedCryptoPair, isTransientNetworkError, index$1 as legacyApi, limitBuyWithTakeProfit, ocoOrders, orderUtils, otoOrders, paginate, paginateAll, parseOCCSymbol, protectLongPosition, protectShortPosition, rateLimiters, resetLogger, resetRiskFreeRateCache, riskNs as risk, rollOptionPosition, roundPriceForAlpaca$3 as roundPriceForAlpaca, roundPriceForAlpacaNumber, safeValidateResponse, searchNews, sellAllCrypto, sellCryptoNotional, sellToClose, sellToOpen, setLogger, setRiskFreeRate, shortWithStopLoss, sortOrdersByDate, strategyNs as strategy, index as tradingPolicy, trailingStops, updateAccountConfiguration, updateTrailingStop, validateAlpacaCredentials, validateAlphaVantageApiKey, validateMassiveApiKey$1 as validateMassiveApiKey, validateMultiLegOrder, validateResponse, verifyFetchKeepAlive, volatilityNs as volatility, waitForOrderFill, withRetry, withTimeout };
|
|
68889
69637
|
//# sourceMappingURL=index.mjs.map
|