bushido-tradingview-mcp 0.1.13 → 0.1.14
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/README.md +2 -1
- package/build/featureOutcomeRelationships.js +1 -10
- package/build/forecastLossComparison.js +427 -0
- package/build/forecastLossJournal.js +177 -0
- package/build/forecastSet.js +294 -0
- package/build/forecastSetCli.js +37 -0
- package/build/leadLagRelationships.js +1 -10
- package/build/numerics.js +153 -0
- package/build/researchPeriodUsage.js +47 -17
- package/build/seededRandom.js +15 -0
- package/build/server.js +74 -1
- package/build/syntheticNullSeries.js +3 -14
- package/package.json +3 -1
package/README.md
CHANGED
|
@@ -148,7 +148,7 @@ With TradingView running in debug mode, ask your AI agent:
|
|
|
148
148
|
|
|
149
149
|
The agent can combine tools such as `get_chart_context` (what is displayed), `get_chart_screenshot` (visual evidence), and `get_ohlcv` (numeric evidence).
|
|
150
150
|
|
|
151
|
-
## Tools (
|
|
151
|
+
## Tools (108 Total)
|
|
152
152
|
|
|
153
153
|
The AI selects the appropriate tools automatically; you do not need to memorize them.
|
|
154
154
|
|
|
@@ -379,6 +379,7 @@ This enables a read -> modify -> save -> backtest improvement loop:
|
|
|
379
379
|
| `get_strategy_report` | Reads net profit, win rate, PF, drawdown, and recent trades for the active strategy |
|
|
380
380
|
| `get_strategy_trade_ledger` | Pages the full Strategy Tester ledger in batches of up to 500, binds it to a SHA-256 ID, rejects cross-page recomputation, exposes available costs/run-up/drawdown/inputs/Pine version, and separates the trailing mark-to-market open row |
|
|
381
381
|
| `summarize_backtest_ledger` | Recomputes PF/net bps, sample break-even round-trip cost and cost headroom; compares full/selected/excluded populations. Optional `research_id` records local exploration and automatic full-ledger period usage; `usage_access_id` supports period-record retries. Otherwise explicitly untracked. No chart access. See [ledger import contract](docs/BACKTEST_LEDGERS.md) |
|
|
382
|
+
| `compare_forecast_losses` | Compares two variance/covariance forecasts under QLIKE or MSE with the Diebold-Mariano test (Newey-West HAC) and a fixed robustness battery: fixed sub-periods, a 1% trim with worst-case own nulls, breakdown count, a distinct secondary proxy and a bootstrap. `no_listed_conflict` is never superiority. Input is an imported set or an inline scalar set. Optional `research_id` records period usage and search counts. See [forecast loss contract](docs/FORECAST_LOSS_COMPARISON.md) |
|
|
382
383
|
| `record_research_period_usage` | Records reported data access intervals with explicit confirmation; retries are idempotent, conflicting access IDs fail. See [period usage contract](docs/RESEARCH_PERIOD_USAGE.md) |
|
|
383
384
|
| `record_research_period_usage_batch` | Records 1-20 access reports in one call; the whole batch is validated and capacity-checked before any write; a retry resumes after complete lines, while a torn line fails closed. `summary_only` returns counts instead of every overlap. See [batch](docs/RESEARCH_PERIOD_USAGE.md#batch) |
|
|
384
385
|
| `check_research_period_usage` | Finds prior interval use across research IDs and revisions of the same series; absence of records never proves unused OOS. See [period usage contract](docs/RESEARCH_PERIOD_USAGE.md) |
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
2
|
import { estimateEffectiveMultiplicity } from "./effectiveMultiplicity.js";
|
|
3
|
+
import { createRandom } from "./seededRandom.js";
|
|
3
4
|
import { computeMarketRegimes, marketRegimeResolutionMilliseconds, } from "./marketRegimes.js";
|
|
4
5
|
const FEATURE_BUCKETS = {
|
|
5
6
|
atr_compression: ["compressed", "normal", "expanded"],
|
|
@@ -328,16 +329,6 @@ function classify(rows, features, horizons, confidenceLevel, bonferroni, empiric
|
|
|
328
329
|
}))];
|
|
329
330
|
}));
|
|
330
331
|
}
|
|
331
|
-
function createRandom(seed) {
|
|
332
|
-
let state = seed >>> 0;
|
|
333
|
-
return () => {
|
|
334
|
-
state = (state + 0x6d2b79f5) >>> 0;
|
|
335
|
-
let value = state;
|
|
336
|
-
value = Math.imul(value ^ (value >>> 15), value | 1);
|
|
337
|
-
value ^= value + Math.imul(value ^ (value >>> 7), value | 61);
|
|
338
|
-
return ((value ^ (value >>> 14)) >>> 0) / 4_294_967_296;
|
|
339
|
-
};
|
|
340
|
-
}
|
|
341
332
|
function absoluteStudentizedMean(values) {
|
|
342
333
|
if (values.length < 2)
|
|
343
334
|
return null;
|
|
@@ -0,0 +1,427 @@
|
|
|
1
|
+
import { largestCommonScaleGroup } from "./forecastSet.js";
|
|
2
|
+
import { allFinite, cholesky, frobeniusInner, inverseFromCholesky, logDeterminantFromCholesky, normalCdf, positiveSemidefinite, spearman, symmetricWithin, symmetrize, } from "./numerics.js";
|
|
3
|
+
import { createRandom } from "./seededRandom.js";
|
|
4
|
+
/**
|
|
5
|
+
* compare_forecast_losses, the computation (docs/FORECAST_LOSS_COMPARISON_DESIGN.md rev 4.1 and
|
|
6
|
+
* docs/FORECAST_LOSS_COMPARISON_PLAN.md section 7). Pure: no I/O, no clock. The server adds the
|
|
7
|
+
* exploration search and the input-path limitation.
|
|
8
|
+
*/
|
|
9
|
+
export const FORECAST_LOSS_CONTRACT = "forecast_loss_comparison_v1";
|
|
10
|
+
export const BOOTSTRAP_SEED = 20_260_928;
|
|
11
|
+
export const BOOTSTRAP_DRAWS = 2_000;
|
|
12
|
+
export const BOOTSTRAP_MEAN_BLOCK = 20;
|
|
13
|
+
export const MIN_USED_DAYS = 100;
|
|
14
|
+
export const MAX_DROPPED_SHARE = 0.05;
|
|
15
|
+
export const FAVOURED_P = 0.05;
|
|
16
|
+
export const DISTINCT_RHO = 0.99;
|
|
17
|
+
/**
|
|
18
|
+
* A secondary that is one common scaling of the primary on more than this share of jointly nonzero
|
|
19
|
+
* days is not distinct (code review M2). A majority, because coarse-tick or floored proxies that are
|
|
20
|
+
* genuinely different share one exact scale on up to about 11% of days (code review R-L1).
|
|
21
|
+
*/
|
|
22
|
+
export const NEAR_COPY_SHARE = 0.5;
|
|
23
|
+
const SYMMETRY_TOLERANCE = 1e-12;
|
|
24
|
+
/** Every battery outcome, in the design's first-match order. */
|
|
25
|
+
export const BATTERY_OUTCOMES = [
|
|
26
|
+
"not_evaluable", "not_applicable", "conflicts_found", "blocked_by_dropped_days",
|
|
27
|
+
"not_assessed_secondary_proxy_absent", "not_assessed_secondary_proxy_not_distinct",
|
|
28
|
+
"no_listed_conflict_untracked", "no_listed_conflict",
|
|
29
|
+
];
|
|
30
|
+
const asMatrix = (value) => typeof value === "number" ? [[value]] : value;
|
|
31
|
+
const mean = (values) => values.reduce((sum, x) => sum + x, 0) / values.length;
|
|
32
|
+
const meanOrNull = (values) => values.length ? mean(values) : null;
|
|
33
|
+
/**
|
|
34
|
+
* The power of two at or below max|x| (1 for an all-zero series). Dividing by it is exact, so results
|
|
35
|
+
* in the normal range are bit-identical, while sums and squares of very large or very small values
|
|
36
|
+
* stay in range (external review EXT-2b, LOW-1, LOW-2).
|
|
37
|
+
*/
|
|
38
|
+
function powerOfTwoScale(values) {
|
|
39
|
+
const largest = values.reduce((max, x) => Math.max(max, Math.abs(x)), 0);
|
|
40
|
+
// log2 rounds to 1024 in the top binade; 2^1024 would be Infinity (diff check nit).
|
|
41
|
+
return largest > 0 && Number.isFinite(largest) ? 2 ** Math.min(1023, Math.floor(Math.log2(largest))) : 1;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* A nonzero loss below the smallest normal double is quantized to multiples of 2^-1074, so d and DM
|
|
45
|
+
* lose all meaning; rescaling d cannot recover it (diff check LOW-A).
|
|
46
|
+
*/
|
|
47
|
+
const belowNormalRange = (x) => x !== 0 && Math.abs(x) < 2 ** -1022;
|
|
48
|
+
const scaledMeanOrNull = (values) => {
|
|
49
|
+
if (!values.length)
|
|
50
|
+
return null;
|
|
51
|
+
const unit = powerOfTwoScale(values);
|
|
52
|
+
return mean(values.map((x) => x / unit)) * unit;
|
|
53
|
+
};
|
|
54
|
+
const sign = (x) => (x > 0 ? 1 : x < 0 ? -1 : 0);
|
|
55
|
+
/** Forecast validity: finite, symmetric within 1e-12·max|S|, Cholesky positive-definite. */
|
|
56
|
+
function forecast(value) {
|
|
57
|
+
if (value === null)
|
|
58
|
+
return null;
|
|
59
|
+
const m = asMatrix(value);
|
|
60
|
+
if (!allFinite(m) || !symmetricWithin(m, SYMMETRY_TOLERANCE))
|
|
61
|
+
return null;
|
|
62
|
+
const s = symmetrize(m);
|
|
63
|
+
const l = cholesky(s);
|
|
64
|
+
if (!l)
|
|
65
|
+
return null;
|
|
66
|
+
return { s, inverse: inverseFromCholesky(l), logDet: logDeterminantFromCholesky(l) };
|
|
67
|
+
}
|
|
68
|
+
/** Proxy validity: finite, symmetric within tolerance, PSD within 1e-12·max|P| (plan section 7). */
|
|
69
|
+
function proxy(value) {
|
|
70
|
+
if (value === null)
|
|
71
|
+
return null;
|
|
72
|
+
const m = asMatrix(value);
|
|
73
|
+
if (!allFinite(m) || !symmetricWithin(m, SYMMETRY_TOLERANCE) || !positiveSemidefinite(m))
|
|
74
|
+
return null;
|
|
75
|
+
return symmetrize(m);
|
|
76
|
+
}
|
|
77
|
+
/** Lower is better. qlike: log det S + tr(S⁻¹P); mse: ‖S − P‖²_F. */
|
|
78
|
+
function lossOf(f, p, loss) {
|
|
79
|
+
if (loss === "qlike")
|
|
80
|
+
return f.logDet + frobeniusInner(f.inverse, p);
|
|
81
|
+
return f.s.reduce((sum, row, i) => sum + row.reduce((acc, x, j) => acc + (x - p[i][j]) ** 2, 0), 0);
|
|
82
|
+
}
|
|
83
|
+
/** One day's loss under the design's validity rules; null when the forecast or proxy is invalid. */
|
|
84
|
+
export function evaluateLoss(forecastValue, proxyValue, loss) {
|
|
85
|
+
const f = forecast(forecastValue), p = proxy(proxyValue);
|
|
86
|
+
return f && p ? lossOf(f, p, loss) : null;
|
|
87
|
+
}
|
|
88
|
+
/** The proxy-dependent part ⟨G, P⟩ of d = c + ⟨G, P⟩ (design M3). */
|
|
89
|
+
function proxyPart(a, b, p, loss) {
|
|
90
|
+
if (loss === "qlike")
|
|
91
|
+
return frobeniusInner(a.inverse, p) - frobeniusInner(b.inverse, p);
|
|
92
|
+
return -2 * (frobeniusInner(a.s, p) - frobeniusInner(b.s, p));
|
|
93
|
+
}
|
|
94
|
+
/** Newey-West long-run variance: Bartlett weights 1 − l/(L+1), divisor T, L = min(T − 1, ⌊4(T/100)^(2/9)⌋). */
|
|
95
|
+
export function neweyWest(d) {
|
|
96
|
+
const T = d.length;
|
|
97
|
+
const L = Math.min(T - 1, Math.floor(4 * (T / 100) ** (2 / 9)));
|
|
98
|
+
const dbar = mean(d);
|
|
99
|
+
const e = d.map((x) => x - dbar);
|
|
100
|
+
const gamma = (lag) => {
|
|
101
|
+
let sum = 0;
|
|
102
|
+
for (let t = lag; t < T; t++)
|
|
103
|
+
sum += e[t] * e[t - lag];
|
|
104
|
+
return sum / T;
|
|
105
|
+
};
|
|
106
|
+
let S = gamma(0);
|
|
107
|
+
for (let lag = 1; lag <= L; lag++)
|
|
108
|
+
S += 2 * (1 - lag / (L + 1)) * gamma(lag);
|
|
109
|
+
return { dbar, S, L, T };
|
|
110
|
+
}
|
|
111
|
+
/** Four contiguous blocks of equal count in date order; the first T mod 4 blocks get one more day. */
|
|
112
|
+
export function blockBounds(T, blocks = 4) {
|
|
113
|
+
const base = Math.floor(T / blocks), extra = T % blocks;
|
|
114
|
+
const bounds = [];
|
|
115
|
+
let start = 0;
|
|
116
|
+
for (let i = 0; i < blocks; i++) {
|
|
117
|
+
const size = base + (i < extra ? 1 : 0);
|
|
118
|
+
bounds.push([start, start + size]);
|
|
119
|
+
start += size;
|
|
120
|
+
}
|
|
121
|
+
return bounds;
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Stationary bootstrap (plan section 7): one createRandom(seed) stream across R draws in order.
|
|
125
|
+
* First index floor(u·T); then, per position, draw u: if u < 1/block the next index is floor(u′·T)
|
|
126
|
+
* with a fresh draw, else (previous + 1) mod T. Centred, unstudentized one-sided p for side s.
|
|
127
|
+
*/
|
|
128
|
+
export function stationaryBootstrap(d, s, draws = BOOTSTRAP_DRAWS, block = BOOTSTRAP_MEAN_BLOCK, seed = BOOTSTRAP_SEED) {
|
|
129
|
+
const T = d.length;
|
|
130
|
+
const dbar = mean(d);
|
|
131
|
+
const random = createRandom(seed);
|
|
132
|
+
let extreme = 0;
|
|
133
|
+
for (let r = 0; r < draws; r++) {
|
|
134
|
+
let index = Math.floor(random() * T);
|
|
135
|
+
let sum = d[index];
|
|
136
|
+
for (let t = 1; t < T; t++) {
|
|
137
|
+
index = random() < 1 / block ? Math.floor(random() * T) : (index + 1) % T;
|
|
138
|
+
sum += d[index];
|
|
139
|
+
}
|
|
140
|
+
if (s * (sum / T - dbar) <= s * dbar)
|
|
141
|
+
extreme++;
|
|
142
|
+
}
|
|
143
|
+
const p = (1 + extreme) / (1 + draws);
|
|
144
|
+
return { p, mc_se: Math.sqrt(p * (1 - p) / draws), draws, mean_block: block, seed };
|
|
145
|
+
}
|
|
146
|
+
const crosses = (x, side) => (side === "A" ? x >= 0 : x <= 0);
|
|
147
|
+
/**
|
|
148
|
+
* The mean after removing the j values most favourable to side (smallest first for A, largest first
|
|
149
|
+
* for B), for every j, from one suffix-sum pass. The decisive trim and k* both read this array, so
|
|
150
|
+
* they never disagree through different summation orders (code review L1).
|
|
151
|
+
*/
|
|
152
|
+
function trimmedMeans(sample, side) {
|
|
153
|
+
const ordered = [...sample].sort((x, y) => (side === "A" ? x - y : y - x));
|
|
154
|
+
const means = new Array(ordered.length);
|
|
155
|
+
let rest = 0;
|
|
156
|
+
for (let j = ordered.length - 1; j >= 0; j--) {
|
|
157
|
+
rest += ordered[j];
|
|
158
|
+
means[j] = rest / (ordered.length - j);
|
|
159
|
+
}
|
|
160
|
+
return means;
|
|
161
|
+
}
|
|
162
|
+
/** k*: the fewest most-favourable removals whose remaining mean crosses zero; null if none does. */
|
|
163
|
+
export function breakdownCount(sample, side) {
|
|
164
|
+
const found = trimmedMeans(sample, side).findIndex((x) => crosses(x, side));
|
|
165
|
+
return found < 0 ? null : found;
|
|
166
|
+
}
|
|
167
|
+
/** Mean after removing the k values most favourable to side (smallest for A, largest for B). */
|
|
168
|
+
export function trimFavourable(sample, k, side) {
|
|
169
|
+
return trimmedMeans(sample, side)[k];
|
|
170
|
+
}
|
|
171
|
+
export const LIMITATIONS = [
|
|
172
|
+
"no_listed_conflict_is_not_evidence_of_superiority",
|
|
173
|
+
"battery_checks_sign_not_significance",
|
|
174
|
+
"battery_items_are_not_independent_tests",
|
|
175
|
+
"proxy_noise_can_reverse_rankings",
|
|
176
|
+
"one_historical_path_no_forward_evidence",
|
|
177
|
+
"pairwise_only_no_correction_across_multiple_benchmarks",
|
|
178
|
+
"dm_normal_approximation_weak_under_heavy_tailed_d",
|
|
179
|
+
"forecast_units_and_variance_vs_volatility_are_caller_asserted",
|
|
180
|
+
"not_a_trading_or_risk_management_result",
|
|
181
|
+
"secondary_proxy_independence_is_caller_asserted",
|
|
182
|
+
"secondary_proxy_mean_not_imputed_for_own_nulls",
|
|
183
|
+
"distinctness_measure_shares_forecast_difference_factor",
|
|
184
|
+
"search_counts_cover_this_journal_only",
|
|
185
|
+
];
|
|
186
|
+
export function compareForecastLosses(set, options) {
|
|
187
|
+
const { loss, tracked } = options;
|
|
188
|
+
const N = set.dates.length;
|
|
189
|
+
const drops = { N, used: 0, proxy_invalid: 0, both_null: 0, a_only_null: 0, b_only_null: 0 };
|
|
190
|
+
const d = [], usedDates = [], usedLabels = [], lossA = [], lossB = [];
|
|
191
|
+
const bOnANull = [], aOnBNull = [];
|
|
192
|
+
let subnormalLosses = 0;
|
|
193
|
+
const secondary = { d: [], primaryD: [], partP: [], partP2: [],
|
|
194
|
+
rawP: [], rawP2: [] };
|
|
195
|
+
for (let t = 0; t < N; t++) {
|
|
196
|
+
const p = proxy(set.primary[t]);
|
|
197
|
+
const a = forecast(set.a[t]), b = forecast(set.b[t]);
|
|
198
|
+
// Drop causes in design order (N9): proxy first, then both, then one side.
|
|
199
|
+
if (!p) {
|
|
200
|
+
drops.proxy_invalid++;
|
|
201
|
+
continue;
|
|
202
|
+
}
|
|
203
|
+
if (!a && !b) {
|
|
204
|
+
drops.both_null++;
|
|
205
|
+
continue;
|
|
206
|
+
}
|
|
207
|
+
if (!a) {
|
|
208
|
+
drops.a_only_null++;
|
|
209
|
+
bOnANull.push(lossOf(b, p, loss));
|
|
210
|
+
continue;
|
|
211
|
+
}
|
|
212
|
+
if (!b) {
|
|
213
|
+
drops.b_only_null++;
|
|
214
|
+
aOnBNull.push(lossOf(a, p, loss));
|
|
215
|
+
continue;
|
|
216
|
+
}
|
|
217
|
+
const la = lossOf(a, p, loss), lb = lossOf(b, p, loss);
|
|
218
|
+
if (belowNormalRange(la) || belowNormalRange(lb))
|
|
219
|
+
subnormalLosses++;
|
|
220
|
+
lossA.push(la);
|
|
221
|
+
lossB.push(lb);
|
|
222
|
+
d.push(la - lb);
|
|
223
|
+
usedDates.push(set.dates[t]);
|
|
224
|
+
if (set.labels)
|
|
225
|
+
usedLabels.push(set.labels[t]);
|
|
226
|
+
if (set.secondary) {
|
|
227
|
+
const p2 = proxy(set.secondary[t]);
|
|
228
|
+
const l2a = p2 ? lossOf(a, p2, loss) : NaN, l2b = p2 ? lossOf(b, p2, loss) : NaN;
|
|
229
|
+
const d2 = l2a - l2b;
|
|
230
|
+
const part = p2 ? proxyPart(a, b, p, loss) : NaN, part2 = p2 ? proxyPart(a, b, p2, loss) : NaN;
|
|
231
|
+
// A loss that overflows (code review M1) or falls below the normal range (LOW-A) leaves the day
|
|
232
|
+
// without a secondary d, like an invalid proxy.
|
|
233
|
+
if (p2 && Number.isFinite(d2) && Number.isFinite(part) && Number.isFinite(part2)
|
|
234
|
+
&& !belowNormalRange(l2a) && !belowNormalRange(l2b)) {
|
|
235
|
+
secondary.d.push(d2);
|
|
236
|
+
secondary.primaryD.push(la - lb);
|
|
237
|
+
secondary.partP.push(part);
|
|
238
|
+
secondary.partP2.push(part2);
|
|
239
|
+
secondary.rawP.push(set.primary[t]);
|
|
240
|
+
secondary.rawP2.push(set.secondary[t]);
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
const T = d.length;
|
|
245
|
+
drops.used = T;
|
|
246
|
+
// Every d-level statistic runs on d divided by a power of two near max|d| and is reported back in the
|
|
247
|
+
// input units. The division is exact, so normal-range results are bit-identical. Unscaled, HAC
|
|
248
|
+
// underflowed for tiny losses (EXT-2b), and the block, trimmed, label and bootstrap means rounded to 0
|
|
249
|
+
// when d was within a few multiples of 2^-1074, raising false reversals (external review EXT-4).
|
|
250
|
+
const finite = d.every(Number.isFinite);
|
|
251
|
+
const unit = finite ? powerOfTwoScale(d) : 1;
|
|
252
|
+
const scaled = d.map((x) => x / unit);
|
|
253
|
+
const hardDays = {
|
|
254
|
+
b_loss_on_a_only_null_days: scaledMeanOrNull(bOnANull), b_loss_on_used_days: scaledMeanOrNull(lossB),
|
|
255
|
+
a_loss_on_b_only_null_days: scaledMeanOrNull(aOnBNull), a_loss_on_used_days: scaledMeanOrNull(lossA),
|
|
256
|
+
};
|
|
257
|
+
// The secondary proxy: evaluated on used days where it is valid; > 5% of them dropped = not evaluable.
|
|
258
|
+
const secondaryDropped = T - secondary.d.length;
|
|
259
|
+
const secondaryUnit = powerOfTwoScale(secondary.d);
|
|
260
|
+
const secondaryScaledMean = secondary.d.length ? mean(secondary.d.map((x) => x / secondaryUnit)) : null;
|
|
261
|
+
const secondaryMean = secondaryScaledMean === null ? null : secondaryScaledMean * secondaryUnit;
|
|
262
|
+
// Backstop (code review R-L2): with the rescaled mean, finite days cannot give a non-finite mean.
|
|
263
|
+
const secondaryStatus = !set.secondary ? "absent"
|
|
264
|
+
: (T === 0 || secondary.d.length === 0 || secondaryDropped / T > MAX_DROPPED_SHARE || !Number.isFinite(secondaryMean)
|
|
265
|
+
? "not_evaluable" : "evaluable");
|
|
266
|
+
const rho = set.secondary ? spearman(secondary.partP, secondary.partP2) : null;
|
|
267
|
+
const group = set.secondary ? largestCommonScaleGroup(secondary.rawP, secondary.rawP2) : null;
|
|
268
|
+
const nearCopyShare = group && group.jointly_nonzero >= 2 ? group.largest_group / group.jointly_nonzero : null;
|
|
269
|
+
// Judged whenever a secondary is present, so row 6 is listed even when row 5 wins (code review L2).
|
|
270
|
+
const distinct = set.secondary
|
|
271
|
+
? rho !== null && rho <= DISTINCT_RHO && !(nearCopyShare !== null && nearCopyShare > NEAR_COPY_SHARE) : null;
|
|
272
|
+
const secondaryResult = {
|
|
273
|
+
status: secondaryStatus,
|
|
274
|
+
mean: secondaryMean,
|
|
275
|
+
used: secondary.d.length,
|
|
276
|
+
dropped: set.secondary ? secondaryDropped : null,
|
|
277
|
+
spearman_rho: rho,
|
|
278
|
+
near_copy_share: nearCopyShare,
|
|
279
|
+
sign_change_share: secondary.d.length
|
|
280
|
+
? secondary.d.filter((x, i) => sign(x) !== sign(secondary.primaryD[i])).length / secondary.d.length : null,
|
|
281
|
+
distinct,
|
|
282
|
+
};
|
|
283
|
+
// Side-independent withheld reasons (rows 5-7).
|
|
284
|
+
const sideIndependent = [
|
|
285
|
+
...(secondaryStatus !== "evaluable" ? ["not_assessed_secondary_proxy_absent"] : []),
|
|
286
|
+
...(distinct === false ? ["not_assessed_secondary_proxy_not_distinct"] : []),
|
|
287
|
+
...(!tracked ? ["no_listed_conflict_untracked"] : []),
|
|
288
|
+
];
|
|
289
|
+
const labelStats = set.labels ? [...new Set(usedLabels)].sort().map((label) => {
|
|
290
|
+
const values = scaled.filter((_, i) => usedLabels[i] === label);
|
|
291
|
+
return { label, days: values.length, scaledMean: mean(values) };
|
|
292
|
+
}) : null;
|
|
293
|
+
const labelMeans = labelStats ? labelStats.map(({ label, days, scaledMean }) => ({ label, days, mean: scaledMean * unit })) : null;
|
|
294
|
+
const base = {
|
|
295
|
+
contract: FORECAST_LOSS_CONTRACT,
|
|
296
|
+
loss,
|
|
297
|
+
candidateEligible: false,
|
|
298
|
+
statistical_calibration: "not_assessed",
|
|
299
|
+
limitations: [...LIMITATIONS],
|
|
300
|
+
};
|
|
301
|
+
// Evaluability of the primary. A loss that overflows makes d non-finite; nothing else is computable (code review M1).
|
|
302
|
+
let reason = null;
|
|
303
|
+
if (!finite)
|
|
304
|
+
reason = "non_finite_loss";
|
|
305
|
+
else if (subnormalLosses)
|
|
306
|
+
reason = "loss_below_normal_range";
|
|
307
|
+
else if (N === 0 || (N - T) / N > MAX_DROPPED_SHARE)
|
|
308
|
+
reason = "more_than_5_percent_of_dates_dropped";
|
|
309
|
+
else if (T < MIN_USED_DAYS)
|
|
310
|
+
reason = "fewer_than_100_used_days";
|
|
311
|
+
// HAC and DM on the rescaled d (EXT-2b); d̄ and S are reported in the input units.
|
|
312
|
+
const scaledHac = finite && T >= 2 ? neweyWest(scaled) : null;
|
|
313
|
+
const hac = scaledHac ? { ...scaledHac, dbar: scaledHac.dbar * unit, S: scaledHac.S * unit * unit } : null;
|
|
314
|
+
const scaledDM = scaledHac ? scaledHac.dbar / Math.sqrt(scaledHac.S / T) : NaN;
|
|
315
|
+
// Reported in input units, S can still overflow for losses near 1e154; that is not evaluable (EXT-2).
|
|
316
|
+
if (!reason && hac && !(Number.isFinite(hac.S) && Number.isFinite(hac.dbar)))
|
|
317
|
+
reason = "hac_variance_not_finite";
|
|
318
|
+
if (!reason && scaledHac && (!(scaledHac.S > 0) || scaledHac.S < 1e-12 * mean(scaled.map((x) => x * x)))) {
|
|
319
|
+
reason = "hac_variance_not_positive";
|
|
320
|
+
}
|
|
321
|
+
// Backstop only: after the two checks above, the rescaled S is at least 1e-12/T, so DM is finite.
|
|
322
|
+
if (!reason && !Number.isFinite(scaledDM))
|
|
323
|
+
reason = "hac_variance_not_finite";
|
|
324
|
+
// Statistics follow the design's field order in every branch.
|
|
325
|
+
if (reason) {
|
|
326
|
+
return {
|
|
327
|
+
...base,
|
|
328
|
+
status: { evaluable: false, reason },
|
|
329
|
+
battery_outcome: "not_evaluable",
|
|
330
|
+
robustness_conflicts: [],
|
|
331
|
+
withheld_reasons: sideIndependent,
|
|
332
|
+
withheld_reasons_scope: "side_independent_only",
|
|
333
|
+
non_decisive_disagreements: [],
|
|
334
|
+
dm: hac ? { dbar: hac.dbar, S: hac.S, L: hac.L, DM: null, p_a: null, p_b: null, T } : null,
|
|
335
|
+
mean_favours: null,
|
|
336
|
+
mean_favours_test: "two_sided_10_percent",
|
|
337
|
+
drops, hard_days: hardDays, sub_periods: null, trimmed: null, breakdown: null,
|
|
338
|
+
secondary: secondaryResult, bootstrap: null, caller_label_means: labelMeans,
|
|
339
|
+
};
|
|
340
|
+
}
|
|
341
|
+
const { dbar, S, L } = hac;
|
|
342
|
+
const DM = scaledDM;
|
|
343
|
+
const pA = normalCdf(DM), pB = normalCdf(-DM);
|
|
344
|
+
const favours = pA < FAVOURED_P ? "A" : pB < FAVOURED_P ? "B" : "neither";
|
|
345
|
+
const k = Math.floor((T + 99) / 100); // ceil(T/100) in integers
|
|
346
|
+
const blocks = blockBounds(T);
|
|
347
|
+
const blockMeans = blocks.map(([from, to]) => mean(scaled.slice(from, to))); // rescaled
|
|
348
|
+
const subPeriods = blocks.map(([from, to], i) => ({
|
|
349
|
+
from_date: usedDates[from], to_date: usedDates[to - 1], days: to - from, mean: blockMeans[i] * unit,
|
|
350
|
+
}));
|
|
351
|
+
const sorted = [...scaled].sort((x, y) => x - y);
|
|
352
|
+
const bothTails = mean(sorted.slice(k, T - k)); // rescaled
|
|
353
|
+
const dm = { dbar, S, L, DM, p_a: pA, p_b: pB, T };
|
|
354
|
+
if (favours === "neither") {
|
|
355
|
+
// The side the mean leans to, in the favoured branch's convention: d̄ < 0 leans to A, s = +1. Read from
|
|
356
|
+
// the rescaled d̄: the reported d̄ can round to 0 at tiny scale and skip the bootstrap (external review).
|
|
357
|
+
const s = -sign(scaledHac.dbar);
|
|
358
|
+
return {
|
|
359
|
+
...base,
|
|
360
|
+
status: { evaluable: true, reason: null },
|
|
361
|
+
battery_outcome: "not_applicable",
|
|
362
|
+
robustness_conflicts: [],
|
|
363
|
+
withheld_reasons: sideIndependent,
|
|
364
|
+
withheld_reasons_scope: "side_independent_only",
|
|
365
|
+
non_decisive_disagreements: [],
|
|
366
|
+
dm, mean_favours: favours, mean_favours_test: "two_sided_10_percent",
|
|
367
|
+
drops, hard_days: hardDays, sub_periods: subPeriods,
|
|
368
|
+
trimmed: { k, decisive: null, both_tails: bothTails * unit,
|
|
369
|
+
a_tail_removed: trimFavourable(scaled, k, "A") * unit, b_tail_removed: trimFavourable(scaled, k, "B") * unit },
|
|
370
|
+
breakdown: null,
|
|
371
|
+
secondary: secondaryResult,
|
|
372
|
+
bootstrap: s === 0 ? null : stationaryBootstrap(scaled, s),
|
|
373
|
+
caller_label_means: labelMeans,
|
|
374
|
+
};
|
|
375
|
+
}
|
|
376
|
+
const side = favours;
|
|
377
|
+
const reverses = (x) => crosses(x, side);
|
|
378
|
+
// D′: used d plus m copies of the least favourable observed d (design M1).
|
|
379
|
+
const m = side === "A" ? drops.a_only_null : drops.b_only_null;
|
|
380
|
+
const worst = side === "A" ? sorted[T - 1] : sorted[0];
|
|
381
|
+
const means = trimmedMeans([...scaled, ...new Array(m).fill(worst)], side); // rescaled
|
|
382
|
+
const decisive = means[k];
|
|
383
|
+
const found = means.findIndex(reverses);
|
|
384
|
+
const kStar = found < 0 ? null : found;
|
|
385
|
+
const bootstrap = stationaryBootstrap(scaled, side === "A" ? 1 : -1);
|
|
386
|
+
const conflicts = [
|
|
387
|
+
...blockMeans.flatMap((blockMean, i) => (reverses(blockMean) ? [`sub_period_${i + 1}_reverses`] : [])),
|
|
388
|
+
// Through k*, so the conflict and k* ≤ k are the same test (L1). Removing a most-favourable value
|
|
389
|
+
// never moves the mean toward the favoured side, so this is the decisive trimmed mean reversing.
|
|
390
|
+
...(kStar !== null && kStar <= k ? ["trimmed_mean_reverses"] : []),
|
|
391
|
+
...(secondaryStatus === "evaluable" && secondaryScaledMean !== null && reverses(secondaryScaledMean) ? ["secondary_proxy_reverses"] : []),
|
|
392
|
+
];
|
|
393
|
+
const withheld = [
|
|
394
|
+
...(m > k ? ["blocked_by_dropped_days"] : []),
|
|
395
|
+
...sideIndependent,
|
|
396
|
+
];
|
|
397
|
+
const nonDecisive = [
|
|
398
|
+
...(reverses(bothTails) ? ["both_tail_trimmed_mean_reverses"] : []),
|
|
399
|
+
...(bootstrap.p >= FAVOURED_P ? ["bootstrap_p_not_below_0.05_while_favoured_dm_p_is"] : []),
|
|
400
|
+
...(labelStats ?? []).filter((l) => reverses(l.scaledMean)).map((l) => `caller_label_reverses:${l.label}`),
|
|
401
|
+
...(secondaryStatus === "not_evaluable" && secondaryScaledMean !== null && reverses(secondaryScaledMean)
|
|
402
|
+
? ["non_evaluable_secondary_mean_reverses"] : []),
|
|
403
|
+
];
|
|
404
|
+
const outcome = conflicts.length ? "conflicts_found"
|
|
405
|
+
: m > k ? "blocked_by_dropped_days"
|
|
406
|
+
: secondaryStatus !== "evaluable" ? "not_assessed_secondary_proxy_absent"
|
|
407
|
+
: distinct === false ? "not_assessed_secondary_proxy_not_distinct"
|
|
408
|
+
: !tracked ? "no_listed_conflict_untracked"
|
|
409
|
+
: "no_listed_conflict";
|
|
410
|
+
return {
|
|
411
|
+
...base,
|
|
412
|
+
status: { evaluable: true, reason: null },
|
|
413
|
+
battery_outcome: outcome,
|
|
414
|
+
robustness_conflicts: conflicts,
|
|
415
|
+
withheld_reasons: withheld,
|
|
416
|
+
withheld_reasons_scope: "all",
|
|
417
|
+
non_decisive_disagreements: nonDecisive,
|
|
418
|
+
dm, mean_favours: favours, mean_favours_test: "two_sided_10_percent",
|
|
419
|
+
drops, hard_days: hardDays, sub_periods: subPeriods,
|
|
420
|
+
trimmed: { k, decisive: { mean: decisive * unit, own_nulls_imputed_worst_case: m }, both_tails: bothTails * unit },
|
|
421
|
+
breakdown: { k_star: kStar, fraction: kStar === null ? null : kStar / (T + m),
|
|
422
|
+
k_star_status: kStar === null ? "no_crossing" : "crossed" },
|
|
423
|
+
secondary: secondaryResult,
|
|
424
|
+
bootstrap,
|
|
425
|
+
caller_label_means: labelMeans,
|
|
426
|
+
};
|
|
427
|
+
}
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import { homedir } from "node:os";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { BACKTEST_LEDGER_MAX_BYTES, readBacktestLedgerFile } from "./backtestLedger.js";
|
|
5
|
+
import { AppendOnlyFirstSeenLog, isCalendarDate, isCanonicalTimestamp } from "./firstSeenStore.js";
|
|
6
|
+
import { BATTERY_OUTCOMES, FORECAST_LOSS_CONTRACT } from "./forecastLossComparison.js";
|
|
7
|
+
import { FORECAST_SET_MAX_DIMENSION, forecastSetComponentHashes } from "./forecastSet.js";
|
|
8
|
+
export const FORECAST_LOSS_JOURNAL_NAMESPACE = "forecast_loss_comparison_exploration";
|
|
9
|
+
/**
|
|
10
|
+
* The framing check reads through readBacktestLedgerFile, which is capped at the ledger limit, so the
|
|
11
|
+
* log's own cap must not exceed it: a larger cap let one append cross the reader's limit and fail
|
|
12
|
+
* every later call (code review L6).
|
|
13
|
+
*/
|
|
14
|
+
export const FORECAST_LOSS_JOURNAL_MAX_BYTES = BACKTEST_LEDGER_MAX_BYTES;
|
|
15
|
+
const identifier = z.string().regex(/^[A-Za-z0-9_.:-]{1,120}$/);
|
|
16
|
+
const hash = z.string().regex(/^sha256:[a-f0-9]{64}$/);
|
|
17
|
+
const optionalHash = z.union([hash, z.literal("absent")]);
|
|
18
|
+
const timestamp = z.string().refine(isCanonicalTimestamp);
|
|
19
|
+
const recordSchema = z.object({
|
|
20
|
+
schema_version: z.literal("1.0"),
|
|
21
|
+
namespace: z.literal(FORECAST_LOSS_JOURNAL_NAMESPACE),
|
|
22
|
+
sequence: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),
|
|
23
|
+
observation_date: z.string().refine(isCalendarDate),
|
|
24
|
+
first_seen_at: timestamp,
|
|
25
|
+
contract: z.literal(FORECAST_LOSS_CONTRACT),
|
|
26
|
+
loss: z.enum(["qlike", "mse"]),
|
|
27
|
+
research_id: identifier,
|
|
28
|
+
artifact_id: hash,
|
|
29
|
+
component_hashes: z.object({
|
|
30
|
+
dates: hash, a: hash, b: hash, primary: hash, secondary: optionalHash, labels: optionalHash,
|
|
31
|
+
}).strict(),
|
|
32
|
+
source_hash: hash,
|
|
33
|
+
underlying_series_ids: z.array(identifier).min(1).max(FORECAST_SET_MAX_DIMENSION),
|
|
34
|
+
envelope: z.object({ from: timestamp, to: timestamp }).strict(),
|
|
35
|
+
battery_outcome: z.enum(BATTERY_OUTCOMES),
|
|
36
|
+
}).strict();
|
|
37
|
+
function validateRecord(value) {
|
|
38
|
+
const record = recordSchema.parse(value);
|
|
39
|
+
const ids = record.underlying_series_ids;
|
|
40
|
+
if (JSON.stringify(ids) !== JSON.stringify([...new Set(ids)].sort())) {
|
|
41
|
+
throw new Error("forecast loss journal series IDs must be sorted and unique");
|
|
42
|
+
}
|
|
43
|
+
if (!(record.envelope.from < record.envelope.to) || record.observation_date !== record.first_seen_at.slice(0, 10)) {
|
|
44
|
+
throw new Error("invalid forecast loss journal envelope or date");
|
|
45
|
+
}
|
|
46
|
+
return record;
|
|
47
|
+
}
|
|
48
|
+
/** The evaluation envelope: the earliest window start to the latest window end, over every date, dropped ones included. */
|
|
49
|
+
export function forecastSetEnvelope(set) {
|
|
50
|
+
return {
|
|
51
|
+
from: set.windows.reduce((min, w) => (w.from < min ? w.from : min), set.windows[0].from),
|
|
52
|
+
to: set.windows.reduce((max, w) => (w.to > max ? w.to : max), set.windows[0].to),
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
export const FORECAST_LOSS_JOURNAL_LIMITATIONS = [
|
|
56
|
+
"local_recorded_calls_only",
|
|
57
|
+
"prior_and_external_exploration_is_not_tracked",
|
|
58
|
+
"research_id_is_an_exploration_namespace_not_a_preregistered_hypothesis",
|
|
59
|
+
"overlap_key_is_caller_supplied_series_ids_and_windows",
|
|
60
|
+
"retries_increment_call_counts",
|
|
61
|
+
"content_hash_is_integrity_not_source_authentication",
|
|
62
|
+
];
|
|
63
|
+
export const resolveForecastLossJournalPath = (configuredPath = process.env.TRADINGVIEW_MCP_FORECAST_LOSS_JOURNAL_PATH) => configuredPath?.trim() || join(homedir(), ".tradingview-mcp", "forecast-loss-journal.jsonl");
|
|
64
|
+
const distinct = (records, key) => new Set(records.map(key)).size;
|
|
65
|
+
const overlaps = (x, y) => x.underlying_series_ids.some((id) => y.underlying_series_ids.includes(id))
|
|
66
|
+
&& x.envelope.from < y.envelope.to && y.envelope.from < x.envelope.to;
|
|
67
|
+
/** Separate exploration namespace; recording does not register or reference a hypothesis. */
|
|
68
|
+
export class ForecastLossJournalStore {
|
|
69
|
+
filePath;
|
|
70
|
+
log;
|
|
71
|
+
constructor(filePath = resolveForecastLossJournalPath()) {
|
|
72
|
+
this.filePath = filePath;
|
|
73
|
+
this.log = new AppendOnlyFirstSeenLog(filePath, "forecast loss journal", validateRecord, { maxFileBytes: FORECAST_LOSS_JOURNAL_MAX_BYTES, maxRecordBytes: 16 * 1024 });
|
|
74
|
+
}
|
|
75
|
+
async record(exposure) {
|
|
76
|
+
const components = forecastSetComponentHashes(exposure.set);
|
|
77
|
+
const draft = validateRecord({
|
|
78
|
+
schema_version: "1.0", namespace: FORECAST_LOSS_JOURNAL_NAMESPACE, sequence: 1,
|
|
79
|
+
observation_date: "1970-01-01", first_seen_at: "1970-01-01T00:00:00.000Z",
|
|
80
|
+
contract: FORECAST_LOSS_CONTRACT, loss: exposure.loss, research_id: exposure.research_id,
|
|
81
|
+
artifact_id: exposure.artifact_id,
|
|
82
|
+
component_hashes: { dates: components.dates, a: components.a, b: components.b, primary: components.primary,
|
|
83
|
+
secondary: components.secondary, labels: components.labels },
|
|
84
|
+
source_hash: components.source,
|
|
85
|
+
underlying_series_ids: [...exposure.set.underlying_series_ids].sort(),
|
|
86
|
+
envelope: forecastSetEnvelope(exposure.set),
|
|
87
|
+
battery_outcome: exposure.battery_outcome,
|
|
88
|
+
});
|
|
89
|
+
return this.log.serialize(async () => {
|
|
90
|
+
try {
|
|
91
|
+
const text = (await readBacktestLedgerFile(this.filePath, true)).toString("utf8");
|
|
92
|
+
if (!text.endsWith("\n") || text.slice(0, -1).split("\n").some((line) => !line.trim())) {
|
|
93
|
+
throw new Error("invalid forecast loss journal JSONL framing");
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
catch (error) {
|
|
97
|
+
if (error.code !== "ENOENT")
|
|
98
|
+
throw error;
|
|
99
|
+
}
|
|
100
|
+
const records = await this.log.readAllUnlocked();
|
|
101
|
+
// One artifact ID names one content: a record that disagrees means the journal or a hash is wrong.
|
|
102
|
+
const describe = (r) => JSON.stringify([r.component_hashes, r.source_hash, r.underlying_series_ids, r.envelope]);
|
|
103
|
+
const artifacts = new Map();
|
|
104
|
+
for (const record of [...records, draft]) {
|
|
105
|
+
const previous = artifacts.get(record.artifact_id);
|
|
106
|
+
if (previous !== undefined && previous !== describe(record))
|
|
107
|
+
throw new Error("forecast loss journal artifact metadata mismatch");
|
|
108
|
+
artifacts.set(record.artifact_id, describe(record));
|
|
109
|
+
}
|
|
110
|
+
const recordedAt = new Date().toISOString();
|
|
111
|
+
if (records.length && records[records.length - 1].first_seen_at > recordedAt) {
|
|
112
|
+
throw new Error("forecast loss journal clock moved backwards");
|
|
113
|
+
}
|
|
114
|
+
const record = validateRecord({ ...draft, sequence: records.length + 1,
|
|
115
|
+
first_seen_at: recordedAt, observation_date: recordedAt.slice(0, 10) });
|
|
116
|
+
await this.log.appendUnlocked(record);
|
|
117
|
+
return search(records, record);
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
function search(earlier, current) {
|
|
122
|
+
const c = current.component_hashes;
|
|
123
|
+
const own = [...earlier.filter((r) => r.research_id === current.research_id), current];
|
|
124
|
+
const sameBase = own.filter((r) => r.component_hashes.b === c.b && r.component_hashes.primary === c.primary
|
|
125
|
+
&& r.component_hashes.dates === c.dates);
|
|
126
|
+
const overlapping = [...earlier.filter((r) => overlaps(r, current)), current];
|
|
127
|
+
const listedPass = (r) => r.battery_outcome === "no_listed_conflict";
|
|
128
|
+
return {
|
|
129
|
+
status: "tracked",
|
|
130
|
+
research_id: current.research_id,
|
|
131
|
+
sequence: current.sequence,
|
|
132
|
+
recorded_at: current.first_seen_at,
|
|
133
|
+
this_research_id: {
|
|
134
|
+
calls: own.length,
|
|
135
|
+
distinct_a_for_same_b_primary_dates: distinct(sameBase, (r) => r.component_hashes.a),
|
|
136
|
+
distinct_label_sets: distinct(own, (r) => r.component_hashes.labels),
|
|
137
|
+
distinct_secondaries: distinct(own, (r) => r.component_hashes.secondary),
|
|
138
|
+
distinct_losses: distinct(own, (r) => r.loss),
|
|
139
|
+
earlier_no_listed_conflict: own.slice(0, -1).filter(listedPass).length,
|
|
140
|
+
},
|
|
141
|
+
overlapping_data: {
|
|
142
|
+
key: "shared_underlying_series_id_and_envelope_overlap",
|
|
143
|
+
calls: overlapping.length,
|
|
144
|
+
distinct_research_ids: distinct(overlapping, (r) => r.research_id),
|
|
145
|
+
earlier_no_listed_conflict: overlapping.slice(0, -1).filter(listedPass).length,
|
|
146
|
+
distinct_unordered_ab_pairs: distinct(overlapping, (r) => [r.component_hashes.a, r.component_hashes.b].sort().join("|")),
|
|
147
|
+
distinct_b: distinct(overlapping, (r) => r.component_hashes.b),
|
|
148
|
+
distinct_dates: distinct(overlapping, (r) => r.component_hashes.dates),
|
|
149
|
+
distinct_primary: distinct(overlapping, (r) => r.component_hashes.primary),
|
|
150
|
+
},
|
|
151
|
+
limitations: [...FORECAST_LOSS_JOURNAL_LIMITATIONS],
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
export const PRIOR_OVERLAP_RESEARCH_ID_CAP = 100;
|
|
155
|
+
/**
|
|
156
|
+
* The period records' prior_overlap in summary form (design P3): counts per series ID, with the
|
|
157
|
+
* forecast-set-source record as its own entry, and the union of research IDs across the records.
|
|
158
|
+
* Each assessment carries at most its first 100 matches, so the union is flagged truncated when any
|
|
159
|
+
* record's matches were, and when the union itself exceeds the returned cap.
|
|
160
|
+
*/
|
|
161
|
+
export function summarizePriorOverlap(records) {
|
|
162
|
+
const union = new Set(records.flatMap((record) => record.prior_overlap.matches.map((match) => match.research_id)));
|
|
163
|
+
const ids = [...union].sort();
|
|
164
|
+
return {
|
|
165
|
+
scope: "prior_recorded_access_reports",
|
|
166
|
+
per_series: records.map(({ series_id, prior_overlap: p }) => ({
|
|
167
|
+
series_id, status: p.status, overlapping_records: p.overlapping_records,
|
|
168
|
+
exploration_records: p.exploration_records, validation_records: p.validation_records,
|
|
169
|
+
})),
|
|
170
|
+
overlapping_research_ids: ids.slice(0, PRIOR_OVERLAP_RESEARCH_ID_CAP),
|
|
171
|
+
overlapping_research_ids_seen: ids.length,
|
|
172
|
+
overlapping_research_ids_truncated: records.some((record) => record.prior_overlap.truncated)
|
|
173
|
+
|| ids.length > PRIOR_OVERLAP_RESEARCH_ID_CAP,
|
|
174
|
+
limitations: [...new Set([...records.flatMap((record) => record.prior_overlap.limitations),
|
|
175
|
+
"summary_omits_matching_records_use_full_check_for_detail"])],
|
|
176
|
+
};
|
|
177
|
+
}
|