@veyforma/charts 0.0.0-stage → 1.0.0

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.
@@ -0,0 +1,899 @@
1
+ // P&L Attribution – Veyforma Chart Library · https://www.veyforma.com/charts/pnl-attribution
2
+ /*!
3
+ * Veyforma P&L Attribution v1.0.0
4
+ * Explains the gap between front-office hypothetical P&L (HPL) and the risk model's risk-theoretical
5
+ * P&L (RTPL) factor by factor, and runs the FRTB P&L attribution test on the daily totals: Spearman
6
+ * correlation and the Kolmogorov-Smirnov statistic over the last 250 days, with the green, amber and
7
+ * red zones. On top of the test it shows each factor's share of the unexplained P&L volatility (adds up
8
+ * exactly), the test result if each factor's gap were closed, and the shortest path of fixes to green.
9
+ * Original work created for Veyforma. Contains no third-party code.
10
+ * Released under the MIT License. Copyright (c) 2026 Veyforma.
11
+ * https://github.com/veyforma/veyforma-charts
12
+ *
13
+ * Load veyforma-toolkit.js as well to get the chart menu: full screen, print,
14
+ * PNG, JPEG, SVG, PDF, CSV and Excel downloads, copy, notes and the
15
+ * "How to read this chart" box.
16
+ *
17
+ * File layout
18
+ * 1. Settings .......... themes, labels and options
19
+ * 2. Helpers ........... formatting and small utilities
20
+ * 3. Calculation ....... totals, Spearman, KS, zones, factor shares, fixes, path to green
21
+ * 4. Chart instance .... factor, daily and distribution views, tooltips, keyboard
22
+ * 5. Export and notes .. data for the Veyforma Toolkit menu (optional file)
23
+ * 6. Public API ........ window.VeyPlaAttribution
24
+ *
25
+ * Method in one paragraph (see the manual for detail):
26
+ * Daily totals HPL_t = Σ_k HPL_k,t and RTPL_t = Σ_k RTPL_k,t; unexplained U_t = HPL_t − RTPL_t, made of
27
+ * factor gaps g_k,t = HPL_k,t − RTPL_k,t. Over the window: Spearman = Pearson correlation of the ranks
28
+ * (ties get their average rank); KS = largest distance between the two empirical distribution functions.
29
+ * Green if Spearman > 0.80 and KS < 0.09; red if Spearman < 0.70 or KS > 0.12; otherwise amber.
30
+ * Factor share of the unexplained volatility = cov(g_k, U) ÷ sd(U), which adds up exactly to sd(U).
31
+ * "If fixed" re-runs the test with RTPL_k = HPL_k; the path to green adds fixes one at a time, each time
32
+ * taking the factor that brings the desk closest to green.
33
+ */
34
+ (function (root) {
35
+ "use strict";
36
+
37
+ var VERSION = "1.0.0";
38
+ var SVG_NS = "http://www.w3.org/2000/svg";
39
+ var instanceCount = 0;
40
+
41
+ /* ======================================================================
42
+ 1. SETTINGS
43
+ ====================================================================== */
44
+ var BASE_THEME = {
45
+ hpl: "#111827", // front-office hypothetical P&L line
46
+ rtpl: "#c2410c", // risk model P&L line
47
+ unexplained: "#6b7280", // daily HPL − RTPL bars
48
+ contribution: "#a63d16", // factors that add to the unexplained volatility
49
+ offset: "#2f6fed", // factors whose gap offsets the others
50
+ standalone: "#111827", // stand-alone diamonds
51
+ zones: { green: "#15803d", amber: "#b45309", red: "#b91c1c" },
52
+ outside: "#d1d5db", // days outside the test window
53
+ grid: "#ececec",
54
+ axis: "#9ca3af",
55
+ text: "#111827",
56
+ mutedText: "#4b5563",
57
+ axisText: "#4b5563",
58
+ cardBackground: "#f9fafb",
59
+ background: "transparent",
60
+ tooltipBackground: "#111827",
61
+ tooltipText: "#ffffff",
62
+ focus: "#c2410c",
63
+ accent: "#c2410c",
64
+ fontFamily: "inherit",
65
+ fontSize: 12
66
+ };
67
+ var THEMES = {
68
+ veyforma: {},
69
+ mono: { hpl: "#111111", rtpl: "#6b6b6b", unexplained: "#8a8a8a", contribution: "#111111", offset: "#8a8a8a", zones: { green: "#111111", amber: "#4b4b4b", red: "#111111" }, accent: "#111111", focus: "#111111" },
70
+ "colour-safe": { hpl: "#1f2937", rtpl: "#d55e00", unexplained: "#6b7280", contribution: "#cc3311", offset: "#0072b2", zones: { green: "#007a5e", amber: "#a35c00", red: "#b2182b" }, accent: "#0072b2" },
71
+ ocean: { hpl: "#0c3b5e", rtpl: "#0e7490", contribution: "#0c3b5e", offset: "#c2410c", cardBackground: "#eef5f8", accent: "#0e7490" },
72
+ forest: { hpl: "#22311a", rtpl: "#4d6b31", contribution: "#22311a", offset: "#2f6fed", cardBackground: "#f2f4ee", accent: "#4d6b31" },
73
+ corporate: { hpl: "#1e293b", rtpl: "#1d4ed8", contribution: "#1e293b", offset: "#c2410c", cardBackground: "#f1f4f8", accent: "#1d4ed8" },
74
+ midnight: { background: "#111418", hpl: "#f3f4f6", rtpl: "#f08a5d", unexplained: "#8b93a1", contribution: "#f08a5d", offset: "#93c5fd", standalone: "#f3f4f6",
75
+ zones: { green: "#4ade80", amber: "#fbbf24", red: "#fb7185" }, outside: "#374151",
76
+ grid: "#252a31", axis: "#4b5563", text: "#f3f4f6", mutedText: "#a3abb8", axisText: "#a3abb8",
77
+ cardBackground: "#1b2027", tooltipBackground: "#f3f4f6", tooltipText: "#111418", focus: "#93c5fd", accent: "#f08a5d" }
78
+ };
79
+ var THRESHOLDS = { spearmanGreen: 0.80, spearmanRed: 0.70, ksGreen: 0.09, ksRed: 0.12 };
80
+
81
+ var DEFAULT_OPTIONS = {
82
+ data: null, // required: { dates: [...], factors: [{ key, hpl: [...], rtpl: [...] }], … }
83
+ view: "factors", // "factors" | "daily" | "distribution"
84
+ window: 250, // test window in days (the most recent ones)
85
+ fix: null, // factor keys to treat as fixed (RTPL = HPL), e.g. ["EUR 3s6s basis"]
86
+ thresholds: null, // { spearmanGreen, spearmanRed, ksGreen, ksRed }; Basel values by default
87
+ top: 15, // factor rows before the rest are summed into "Other" (0 = all)
88
+ pathSteps: 5, // most fixes tried on the path to green
89
+ theme: "veyforma",
90
+ locale: undefined,
91
+ animate: true,
92
+ summary: true,
93
+ legend: true,
94
+ labels: null,
95
+ ariaLabel: undefined,
96
+ caption: true,
97
+ annotations: null, // notes, e.g. [{ factor: "USD/JPY vol smile", text: "Smile added to the risk model in Q4" }] or { date, text }
98
+ onAnnotationsChange: null,
99
+ onItemClick: null, // function (detail, event): every figure for the factor or day clicked
100
+ exportDays: 20000, // most rows in the daily sheet
101
+ toolbar: true
102
+ };
103
+
104
+ var DEFAULT_LABELS = {
105
+ factors: "Unexplained P&L by risk factor", daily: "HPL and RTPL by day", distribution: "Distribution of HPL and RTPL",
106
+ hpl: "HPL (front office)", rtpl: "RTPL (risk model)", unexplained: "Unexplained (HPL − RTPL)",
107
+ adds: "Adds to unexplained volatility", offsets: "Offsets other gaps", standalone: "Gap on its own",
108
+ test: "PLA test", unexplainedCard: "Unexplained P&L", largest: "Largest driver", path: "Path to green",
109
+ green: "Green", amber: "Amber", red: "Red", na: "n/a", other: "Other {n} factors", unattributed: "Unattributed",
110
+ notModelled: "not in the risk model", ifFixed: "If fixed", outside: "Outside the test window"
111
+ };
112
+ /* ======================================================================
113
+ 2. HELPERS
114
+ ====================================================================== */
115
+ function assign(t) {
116
+ for (var i = 1; i < arguments.length; i++) {
117
+ var s = arguments[i];
118
+ if (s) for (var k in s) if (Object.prototype.hasOwnProperty.call(s, k)) t[k] = s[k];
119
+ }
120
+ return t;
121
+ }
122
+ var warned = {};
123
+ function warn(msg) { if (warned[msg]) return; warned[msg] = 1; if (root.console && console.warn) console.warn("VeyPlaAttribution: " + msg); }
124
+ function fail(msg) { throw new Error("VeyPlaAttribution: " + msg); }
125
+ function clamp(v, lo, hi) { return Math.min(hi, Math.max(lo, v)); }
126
+ function fill(t, map) { return String(t).replace(/\{(\w+)\}/g, function (m, k) { return map[k] != null ? map[k] : m; }); }
127
+ /** A name inside a sentence: "CET1 requirement" stays, "Pillar 1 minimum" becomes "pillar 1 minimum". */
128
+ function lower(t) { t = String(t); return /^[A-Z0-9]{2}/.test(t) ? t : t.charAt(0).toLowerCase() + t.slice(1); }
129
+ function num(v) { return typeof v === "number" ? v : v == null || v === "" ? NaN : +v; }
130
+ function svgEl(tag, attrs, parent) {
131
+ var n = document.createElementNS(SVG_NS, tag);
132
+ if (attrs) for (var k in attrs) if (attrs[k] != null) n.setAttribute(k, attrs[k]);
133
+ if (parent) parent.appendChild(n);
134
+ return n;
135
+ }
136
+ function htmlEl(tag, cls, parent) {
137
+ var n = document.createElement(tag);
138
+ if (cls) n.className = cls;
139
+ if (parent) parent.appendChild(n);
140
+ return n;
141
+ }
142
+ var measureCtx = null;
143
+ function textWidth(text, size, weight, family) {
144
+ if (!measureCtx) { var c = document.createElement("canvas"); measureCtx = c.getContext && c.getContext("2d"); }
145
+ if (!measureCtx) return String(text).length * size * 0.6;
146
+ measureCtx.font = (weight || 400) + " " + size + "px " + family;
147
+ return measureCtx.measureText(String(text)).width;
148
+ }
149
+ function fit(text, max, size, weight, family) {
150
+ text = String(text);
151
+ if (textWidth(text, size, weight, family) <= max) return text;
152
+ while (text.length > 2 && textWidth(text + "…", size, weight, family) > max) text = text.slice(0, -1);
153
+ return text.replace(/\s+$/, "") + "…";
154
+ }
155
+ function hexRgb(c) {
156
+ var m = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(String(c || "").trim());
157
+ if (!m) return null;
158
+ var h = m[1].length === 3 ? m[1].replace(/./g, "$&$&") : m[1], n = parseInt(h, 16);
159
+ return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
160
+ }
161
+ function luminance(rgb) {
162
+ var a = rgb.map(function (v) { v /= 255; return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4); });
163
+ return 0.2126 * a[0] + 0.7152 * a[1] + 0.0722 * a[2];
164
+ }
165
+ function contrast(a, b) {
166
+ var x = hexRgb(a), y = hexRgb(b);
167
+ if (!x || !y) return 21;
168
+ var l1 = luminance(x), l2 = luminance(y);
169
+ return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
170
+ }
171
+ function ensureContrast(col, bg, min) {
172
+ var c = hexRgb(col), b = hexRgb(bg);
173
+ if (!c || !b || contrast(col, bg) >= min) return col;
174
+ var dark = luminance(b) > 0.4, t = 0, out = col;
175
+ while (t <= 1 && contrast(out, bg) < min) {
176
+ t += 0.05;
177
+ out = "#" + c.map(function (v) { var x = dark ? v * (1 - t) : v + (255 - v) * t; return ("0" + Math.round(x).toString(16)).slice(-2); }).join("");
178
+ }
179
+ return out;
180
+ }
181
+ function makeFormatters(data, locale) {
182
+ var decimals = data.decimals != null ? data.decimals : 0, rd = data.ratioDecimals != null ? data.ratioDecimals : 1;
183
+ var prefix = data.prefix || "", suffix = data.suffix || "", cache = {}, brackets = data.negatives === "brackets";
184
+ function nf(d) {
185
+ if (!cache[d]) cache[d] = new Intl.NumberFormat(locale || undefined, { minimumFractionDigits: d, maximumFractionDigits: d });
186
+ return cache[d];
187
+ }
188
+ function value(v, d) {
189
+ if (v == null || !isFinite(v)) return "–";
190
+ if (d == null) d = decimals;
191
+ var r = Number(v.toFixed(d)), body = prefix + nf(d).format(Math.abs(r)) + suffix;
192
+ if (r >= 0) return body;
193
+ return brackets ? "(" + body + ")" : "−" + body;
194
+ }
195
+ function signed(v, d) { var s = value(v, d); return v != null && Number(v.toFixed(d == null ? decimals : d)) > 0 ? "+" + s : s; }
196
+ function ratio(v, d) { return v == null || !isFinite(v) ? "–" : (v < 0 ? "−" : "") + nf(d == null ? rd : d).format(Math.abs(v) * 100) + "%"; }
197
+ function pp(v, d) {
198
+ if (v == null || !isFinite(v)) return "–";
199
+ var dd = d == null ? Math.max(rd, 1) : d, r = Number((v * 100).toFixed(dd));
200
+ return (r > 0 ? "+" : r < 0 ? "−" : "") + nf(dd).format(Math.abs(r)) + " pp";
201
+ }
202
+ function percent(v, d) { return v == null || !isFinite(v) ? "–" : nf(d == null ? 1 : d).format(v * 100) + "%"; }
203
+ return { value: value, signed: signed, ratio: ratio, pp: pp, percent: percent, nf: nf };
204
+ }
205
+
206
+
207
+
208
+ /* ======================================================================
209
+ 3. CALCULATION
210
+ ====================================================================== */
211
+ function finite(v, what) { var x = num(v); if (!isFinite(x)) fail(what + " must be a number."); return x; }
212
+
213
+ /** Ranks 1..n, ties get their average rank. */
214
+ function ranks(a) {
215
+ var n = a.length, idx = new Array(n), r = new Array(n), i, j;
216
+ for (i = 0; i < n; i++) idx[i] = i;
217
+ idx.sort(function (p, q) { return a[p] - a[q]; });
218
+ for (i = 0; i < n; i = j) {
219
+ j = i; while (j < n && a[idx[j]] === a[idx[i]]) j++;
220
+ var avg = (i + j + 1) / 2; // ranks i+1 .. j
221
+ for (var k = i; k < j; k++) r[idx[k]] = avg;
222
+ }
223
+ return r;
224
+ }
225
+ function pearson(x, y) {
226
+ var n = x.length, mx = 0, my = 0, i;
227
+ for (i = 0; i < n; i++) { mx += x[i]; my += y[i]; }
228
+ mx /= n; my /= n;
229
+ var sxy = 0, sxx = 0, syy = 0;
230
+ for (i = 0; i < n; i++) { var dx = x[i] - mx, dy = y[i] - my; sxy += dx * dy; sxx += dx * dx; syy += dy * dy; }
231
+ return sxx > 0 && syy > 0 ? sxy / Math.sqrt(sxx * syy) : null;
232
+ }
233
+ function spearman(x, y) { return pearson(ranks(x), ranks(y)); }
234
+ /** Two-sample Kolmogorov-Smirnov statistic: the largest gap between the two empirical distribution functions. */
235
+ function ksStat(x, y) {
236
+ var a = x.slice().sort(function (p, q) { return p - q; }), b = y.slice().sort(function (p, q) { return p - q; });
237
+ var n = a.length, m = b.length, i = 0, j = 0, d = 0, at = a.length ? a[0] : 0;
238
+ while (i < n && j < m) {
239
+ var v = Math.min(a[i], b[j]);
240
+ while (i < n && a[i] === v) i++;
241
+ while (j < m && b[j] === v) j++;
242
+ var g = Math.abs(i / n - j / m);
243
+ if (g > d + 1e-15) { d = g; at = v; }
244
+ }
245
+ return { d: d, at: at };
246
+ }
247
+ function zoneOf(rho, ks, T) {
248
+ if (rho == null) return "red";
249
+ rho = Math.round(rho * 1e12) / 1e12; ks = Math.round(ks * 1e12) / 1e12; // so a value exactly on a threshold is not tipped over by rounding
250
+ if (rho > T.spearmanGreen && ks < T.ksGreen) return "green";
251
+ if (rho < T.spearmanRed || ks > T.ksRed) return "red";
252
+ return "amber";
253
+ }
254
+ /** How far a result is from green: 0 when green. */
255
+ function distance(t, T) { return Math.max(0, T.spearmanGreen - (t.spearman == null ? -1 : t.spearman)) / 0.1 + Math.max(0, t.ks - T.ksGreen) / 0.03; }
256
+ function test(H, R, T) {
257
+ var rho = spearman(H, R), k = ksStat(H, R);
258
+ return { spearman: rho, ks: k.d, ksAt: k.at, zone: zoneOf(rho, k.d, T) };
259
+ }
260
+ function sdOf(a) { var n = a.length, m = 0, s = 0, i; for (i = 0; i < n; i++) m += a[i]; m /= n; for (i = 0; i < n; i++) s += (a[i] - m) * (a[i] - m); return Math.sqrt(s / n); }
261
+ function meanOf(a) { var s = 0; for (var i = 0; i < a.length; i++) s += a[i]; return a.length ? s / a.length : 0; }
262
+
263
+ function readData(data) {
264
+ if (!data || typeof data !== "object") fail("data is required.");
265
+ var dates = data.dates;
266
+ if (!Array.isArray(dates) || dates.length < 2) fail("data.dates must be an array of at least two days.");
267
+ var n = dates.length;
268
+ var series = function (a, what, allowNull) {
269
+ if (a == null && allowNull) return null;
270
+ if (!Array.isArray(a) || a.length !== n) fail(what + " must be an array with one value per date (" + n + ").");
271
+ return a.map(function (v, i) { return finite(v, what + "[" + i + "]"); });
272
+ };
273
+ if (!Array.isArray(data.factors) || !data.factors.length) fail("data.factors must be a non-empty array of risk factors.");
274
+ var seen = {};
275
+ var fs = data.factors.map(function (x, i) {
276
+ if (!x || typeof x !== "object") fail("data.factors[" + i + "] is not an object.");
277
+ if (x.key == null && x.label == null) fail("data.factors[" + i + "] needs a key or a label.");
278
+ var key = String(x.key != null ? x.key : x.label), w = 'factor "' + key + '"';
279
+ if (seen[key]) fail(w + " is used twice.");
280
+ seen[key] = 1;
281
+ var h = series(x.hpl, w + ": hpl"), r = series(x.rtpl, w + ": rtpl", true);
282
+ return { key: key, label: x.label != null ? String(x.label) : key, group: x.group != null ? String(x.group) : "Other", modelled: r != null, hpl: h, rtpl: r || h.map(function () { return 0; }), index: i };
283
+ });
284
+ var ht = series(data.hplTotal, "data.hplTotal", true), rt = series(data.rtplTotal, "data.rtplTotal", true);
285
+ if (ht || rt) {
286
+ // what the factors do not explain becomes one more row
287
+ var sh = new Array(n), sr = new Array(n), t;
288
+ for (t = 0; t < n; t++) { sh[t] = 0; sr[t] = 0; fs.forEach(function (f) { sh[t] += f.hpl[t]; sr[t] += f.rtpl[t]; }); }
289
+ fs.push({ key: "__unattributed", label: data.unattributedLabel || DEFAULT_LABELS.unattributed, group: "Unattributed", modelled: true, unattributed: true,
290
+ hpl: sh.map(function (v, i) { return ht ? ht[i] - v : 0; }), rtpl: sr.map(function (v, i) { return rt ? rt[i] - v : 0; }), index: fs.length });
291
+ }
292
+ return { dates: dates.map(String), factors: fs, n: n };
293
+ }
294
+
295
+ /** Every figure. opts: { window, fix, thresholds, pathSteps }. */
296
+ function compute(data, opts) {
297
+ opts = opts || {};
298
+ var D = readData(data), n = D.n, fs = D.factors;
299
+ var T = assign({}, THRESHOLDS, opts.thresholds || {});
300
+ var w = opts.window != null ? Math.floor(finite(opts.window, "window")) : 250;
301
+ if (!(w >= 2)) fail("window must be at least 2 days.");
302
+ var short = w > n; if (short) w = n;
303
+ var start = n - w;
304
+ var fix = {};
305
+ (opts.fix || []).forEach(function (k) { if (!fs.some(function (f) { return f.key === String(k); })) warn('fix: there is no factor "' + k + '", so it changes nothing.'); fix[String(k)] = 1; });
306
+ fs.forEach(function (f) { f.fixed = !!fix[f.key]; f.rt = f.fixed ? f.hpl : f.rtpl; f.gap = f.hpl.map(function (v, t) { return v - f.rt[t]; }); });
307
+ var H = new Array(n), R = new Array(n), U = new Array(n), t, k;
308
+ for (t = 0; t < n; t++) { var h = 0, r = 0; for (k = 0; k < fs.length; k++) { h += fs[k].hpl[t]; r += fs[k].rt[t]; } H[t] = h; R[t] = r; U[t] = h - r; }
309
+ var Hw = H.slice(start), Rw = R.slice(start), Uw = U.slice(start);
310
+ var res = { dates: D.dates, hpl: H, rtpl: R, unexplained: U, start: start, window: w, shortWindow: short, thresholds: T, fixed: Object.keys(fix) };
311
+ res.test = test(Hw, Rw, T);
312
+ var sdU = sdOf(Uw), sdH = sdOf(Hw), mU = meanOf(Uw);
313
+ res.sdUnexplained = sdU; res.sdHpl = sdH; res.meanUnexplained = mU;
314
+ res.volRatio = sdH > 0 ? sdU / sdH : null; res.meanRatio = sdH > 0 ? mU / sdH : null; res.varRatio = sdH > 0 ? (sdU * sdU) / (sdH * sdH) : null;
315
+ // factor figures over the window
316
+ fs.forEach(function (f) {
317
+ var g = f.gap.slice(start), mg = meanOf(g), c = 0;
318
+ for (t = 0; t < w; t++) c += (g[t] - mg) * (Uw[t] - mU);
319
+ c /= w;
320
+ f.meanGap = mg; f.sdGap = sdOf(g); f.contribution = sdU > 0 ? c / sdU : 0; f.share = sdU > 0 ? f.contribution / sdU : 0;
321
+ f.hplSum = 0; f.rtplSum = 0; for (t = start; t < n; t++) { f.hplSum += f.hpl[t]; f.rtplSum += f.rt[t]; }
322
+ f.hasGap = f.sdGap > 0 || mg !== 0;
323
+ if (f.hasGap) { var R2 = Rw.map(function (v, i) { return v + g[i]; }); f.ifFixed = test(Hw, R2, T); }
324
+ else f.ifFixed = res.test;
325
+ });
326
+ var order = fs.slice().sort(function (a, b) { return Math.abs(b.contribution) - Math.abs(a.contribution) || a.index - b.index; });
327
+ order.forEach(function (f, i) { f.rank = i + 1; });
328
+ res.factors = fs; res.order = order;
329
+ // shortest path to green: add the fix that brings the desk closest to green, one at a time
330
+ var steps = opts.pathSteps != null ? Math.max(0, Math.floor(opts.pathSteps)) : 5, path = [], cur = Rw.slice(), curT = res.test, used = {};
331
+ while (curT.zone !== "green" && path.length < steps) {
332
+ var best = null;
333
+ fs.forEach(function (f) {
334
+ if (used[f.key] || f.fixed || !f.hasGap) return;
335
+ var g = f.gap.slice(start), R2 = cur.map(function (v, i) { return v + g[i]; }), tt = test(Hw, R2, T), dd = distance(tt, T);
336
+ if (!best || dd < best.d - 1e-12 || (Math.abs(dd - best.d) <= 1e-12 && (tt.spearman || -1) > (best.t.spearman || -1))) best = { f: f, t: tt, d: dd, R: R2 };
337
+ });
338
+ if (!best || best.d >= distance(curT, T) - 1e-12) break; // nothing helps any more
339
+ used[best.f.key] = 1; path.push({ key: best.f.key, label: best.f.label, test: best.t }); cur = best.R; curT = best.t;
340
+ }
341
+ res.path = path; res.pathReachesGreen = res.test.zone === "green" || (path.length > 0 && path[path.length - 1].test.zone === "green");
342
+ res.distribution = { hpl: Hw.slice().sort(function (a, b) { return a - b; }), rtpl: Rw.slice().sort(function (a, b) { return a - b; }) };
343
+ return res;
344
+ }
345
+ /* ======================================================================
346
+ 4. CHART INSTANCE
347
+ ====================================================================== */
348
+ function injectStyles() {
349
+ if (document.getElementById("vpa-styles")) return;
350
+ var css =
351
+ ".vpa{position:relative;color:var(--vpa-text);background:var(--vpa-bg);font-family:var(--vpa-font);line-height:1.4}" +
352
+ ".vpa.vpa-filled{padding:14px 14px 8px;border-radius:10px}" +
353
+ ".vpa-summary{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:8px;margin:0 0 10px}" +
354
+ ".vpa-stat{background:var(--vpa-card);border-radius:8px;padding:9px 12px;min-width:0}" +
355
+ ".vpa-stat .k{font-size:11px;letter-spacing:.04em;text-transform:uppercase;color:var(--vpa-card-muted);font-weight:600;overflow-wrap:anywhere;hyphens:auto}" +
356
+ ".vpa-stat .v{font-size:19px;font-weight:700;font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}" +
357
+ ".vpa-stat .n{font-size:12px;color:var(--vpa-card-muted)}" +
358
+ ".vpa-stat .v.vpa-zone{font-weight:800}" +
359
+ ".vpa-stat .v.vpa-wrap{white-space:normal;overflow-wrap:anywhere;line-height:1.2;font-size:17px}" +
360
+ ".vpa-scope{font-size:12px;color:var(--vpa-muted);margin:0 0 4px}" +
361
+ ".vpa-legend{display:flex;flex-wrap:wrap;gap:4px 14px;font-size:12px;margin:0 0 6px;color:var(--vpa-text)}" +
362
+ ".vpa-legend span{display:inline-flex;align-items:center;gap:6px}" +
363
+ ".vpa-legend i{display:inline-block;width:12px;height:12px;border-radius:3px}" +
364
+ ".vpa-legend i.vpa-tick{width:16px;height:3px;border-radius:1px}" +
365
+ ".vpa-legend i.vpa-ring{background:transparent!important;border:2px solid;border-radius:2px;width:9px;height:9px;transform:rotate(45deg)}" +
366
+ ".vpa-plot{display:block;width:100%;height:auto;overflow:visible;outline:none}" +
367
+ ".vpa-plot:focus-visible{outline:2px solid var(--vpa-focus);outline-offset:4px;border-radius:4px}" +
368
+ ".vpa-animate .vpa-grow{animation:vpa-fade .45s ease both}" +
369
+ "@keyframes vpa-fade{from{opacity:0}to{opacity:1}}" +
370
+ "@media (prefers-reduced-motion:reduce){.vpa-animate .vpa-grow{animation:none}}" +
371
+ ".vpa-tip{position:absolute;left:0;top:0;pointer-events:none;background:var(--vpa-tip-bg);color:var(--vpa-tip-text);" +
372
+ "font-size:12px;line-height:1.45;padding:8px 10px;border-radius:8px;opacity:0;transform:translateY(4px);" +
373
+ "transition:opacity .12s,transform .12s;white-space:nowrap;z-index:5;font-variant-numeric:tabular-nums}" +
374
+ ".vpa-tip.vpa-on{opacity:1;transform:none}.vpa-tip b{font-weight:600}" +
375
+ ".vpa-table{border-collapse:collapse;font-size:12px;font-variant-numeric:tabular-nums;margin:0 0 14px;min-width:100%}" +
376
+ ".vpa-table caption{text-align:left;font-weight:700;padding:0 0 6px}" +
377
+ ".vpa-table th,.vpa-table td{padding:5px 8px;border-bottom:1px solid rgba(127,127,127,.25);text-align:right;white-space:nowrap}" +
378
+ ".vpa-table th:first-child,.vpa-table td:first-child{text-align:left}" +
379
+ ".vpa-table tr.vpa-breach td{color:var(--vpa-hedge);font-weight:600}" +
380
+ "@media (max-width:420px){.vpa-summary{grid-template-columns:repeat(auto-fit,minmax(118px,1fr))}.vpa-stat{padding:8px 10px}.vpa-stat .v{font-size:17px}}";
381
+ var s = htmlEl("style");
382
+ s.id = "vpa-styles";
383
+ s.textContent = css;
384
+ (document.head || document.documentElement).appendChild(s);
385
+ }
386
+ function resolvePaTheme(theme) {
387
+ var t;
388
+ if (theme == null || theme === "") theme = "veyforma";
389
+ if (typeof theme === "string") {
390
+ if (!THEMES.hasOwnProperty(theme)) { warn('Unknown theme "' + theme + '". The "veyforma" theme is used instead.'); theme = "veyforma"; }
391
+ t = assign({}, BASE_THEME, THEMES[theme]);
392
+ } else if (typeof theme === "object") {
393
+ t = assign(theme["extends"] ? resolvePaTheme(theme["extends"]) : assign({}, BASE_THEME), theme);
394
+ delete t["extends"];
395
+ } else { warn("The theme option must be a theme name or an object."); t = assign({}, BASE_THEME); }
396
+ var bg = /^#/.test(t.background) ? t.background : "#ffffff", card = /^#/.test(t.cardBackground) ? t.cardBackground : bg;
397
+ ["axisText", "mutedText"].forEach(function (k) { t[k] = ensureContrast(t[k], bg, 4.5); });
398
+ t.cardMuted = ensureContrast(t.mutedText, card, 4.5);
399
+ t.offsetText = ensureContrast(ensureContrast(t.offset, bg, 4.5), card, 4.5);
400
+ t.zoneText = {};
401
+ ["green", "amber", "red"].forEach(function (z) { t.zoneText[z] = ensureContrast(ensureContrast(t.zones[z], bg, 4.5), card, 4.5); });
402
+ t.accentText = ensureContrast(t.accent, bg, 4.5);
403
+ return t;
404
+ }
405
+
406
+ function Chart(target, options) {
407
+ var container = typeof target === "string" ? document.querySelector(target) : target;
408
+ if (!container || container.nodeType !== 1) fail("container not found (" + target + ").");
409
+ if (!options || !options.data) fail("options.data is required.");
410
+ injectStyles();
411
+ this.id = ++instanceCount;
412
+ this.container = container;
413
+ this.options = assign({}, DEFAULT_OPTIONS, options);
414
+ this.element = htmlEl("div", "vpa");
415
+ this.element.setAttribute("role", "figure");
416
+ this.summaryEl = htmlEl("div", "vpa-summary", this.element);
417
+ this.scopeEl = htmlEl("p", "vpa-scope", this.element);
418
+ this.legendEl = htmlEl("div", "vpa-legend", this.element);
419
+ this.plotHost = htmlEl("div", "vpa-plot-host", this.element);
420
+ this.tipEl = htmlEl("div", "vpa-tip", this.element);
421
+ this.tipEl.setAttribute("role", "tooltip");
422
+ container.appendChild(this.element);
423
+ this._animateNext = !!this.options.animate;
424
+ this._lastWidth = 0;
425
+ this._active = -1;
426
+ var self = this;
427
+ if (root.ResizeObserver) {
428
+ this._observer = new root.ResizeObserver(function () {
429
+ var w = Math.round(self.element.clientWidth);
430
+ if (w && Math.abs(w - self._lastWidth) > 1) self.redraw();
431
+ });
432
+ this._observer.observe(this.element);
433
+ } else {
434
+ this._onResize = function () { self.redraw(); };
435
+ root.addEventListener("resize", this._onResize);
436
+ }
437
+ this._onDocTap = function (e) { if (!self.element.contains(e.target)) self._hideTip(); };
438
+ document.addEventListener("pointerdown", this._onDocTap);
439
+ this.redraw();
440
+ if (this.options.toolbar !== false && root.VeyformaToolkit) this.toolkit = root.VeyformaToolkit.attach(this, this.options.toolbar);
441
+ }
442
+
443
+ Chart.prototype.update = function (partial) {
444
+ if (!partial) return this;
445
+ if (partial.data && partial.data !== this.options.data && this.options.animate) this._animateNext = true;
446
+ if (partial.view && partial.view !== this.options.view && this.options.animate) this._animateNext = true;
447
+ assign(this.options, partial);
448
+ return this.redraw();
449
+ };
450
+ Chart.prototype.setData = function (data) { this._res = null; return this.update({ data: data }); };
451
+ Chart.prototype.setView = function (view) { return this.update({ view: view }); };
452
+ Chart.prototype.setTheme = function (theme) { return this.update({ theme: theme }); };
453
+ Chart.prototype.getTheme = function () { return resolvePaTheme(this.options.theme); };
454
+ Chart.prototype._opts = function () { return { window: this.options.window, fix: this.options.fix, thresholds: this.options.thresholds }; };
455
+ Chart.prototype.getResult = function () { return compute(this.options.data, this._opts()); };
456
+ Chart.prototype.getFactor = function (key) { return this.getResult().factors.filter(function (f) { return f.key === String(key); })[0] || null; };
457
+ Chart.prototype.setFix = function (keys) { return this.update({ fix: keys }); };
458
+ Chart.prototype.setWindow = function (days) { return this.update({ window: days }); };
459
+ Chart.prototype._labels = function () { return assign({}, DEFAULT_LABELS, this.options.labels); };
460
+ Chart.prototype.destroy = function () {
461
+ if (this.toolkit && this.toolkit.destroy) this.toolkit.destroy();
462
+ if (this._observer) this._observer.disconnect();
463
+ if (this._onResize) root.removeEventListener("resize", this._onResize);
464
+ document.removeEventListener("pointerdown", this._onDocTap);
465
+ if (this.element.parentNode) this.element.parentNode.removeChild(this.element);
466
+ };
467
+ Chart.prototype._hideTip = function () { this.tipEl.classList.remove("vpa-on"); if (this._hlEl) this._hlEl.setAttribute("opacity", 0); };
468
+ Chart.prototype._placeTip = function (lines, rect, evt) {
469
+ var tip = this.tipEl;
470
+ tip.textContent = "";
471
+ lines.forEach(function (ln, i) {
472
+ if (i) tip.appendChild(document.createElement("br"));
473
+ var node = i === 0 ? document.createElement("b") : document.createElement("span");
474
+ node.textContent = ln;
475
+ tip.appendChild(node);
476
+ });
477
+ var box = this.element.getBoundingClientRect();
478
+ var px = evt && evt.clientX ? evt.clientX : rect.left + rect.width / 2;
479
+ var py = evt && evt.clientY ? evt.clientY : rect.top + 10;
480
+ tip.classList.add("vpa-on");
481
+ var tw = tip.offsetWidth, th = tip.offsetHeight;
482
+ tip.style.left = clamp(px - box.left - tw / 2, 4, Math.max(4, box.width - tw - 4)) + "px";
483
+ var top = py - box.top - th - 14;
484
+ if (top < 0) top = py - box.top + 18;
485
+ tip.style.top = top + "px";
486
+ };
487
+ /** A "nice" axis from lo to hi with about n ticks. */
488
+ function niceTicks(lo, hi, n) {
489
+ if (!(hi > lo)) { hi = lo + 1; }
490
+ var span = hi - lo, step = Math.pow(10, Math.floor(Math.log(span / n) / Math.LN10)), err = span / n / step;
491
+ if (err >= 7.5) step *= 10; else if (err >= 3.5) step *= 5; else if (err >= 1.5) step *= 2;
492
+ var a = Math.floor(lo / step + 1e-9) * step, b = Math.ceil(hi / step - 1e-9) * step, out = [];
493
+ for (var v = a; v <= b + step / 2; v += step) out.push(Math.round(v / step) * step);
494
+ return { lo: a, hi: b, ticks: out, step: step };
495
+ }
496
+
497
+ function label(g, x, y, text, attrs) {
498
+ var t = svgEl("text", assign({ x: x, y: y }, attrs || {}), g);
499
+ t.textContent = text;
500
+ return t;
501
+ }
502
+
503
+ Chart.prototype._bindInteraction = function (svg, W, H, theme, L, f) {
504
+ var self = this, items = this._items, o = this.options;
505
+ function idxAt(evt) {
506
+ var r = svg.getBoundingClientRect(), x = (evt.clientX - r.left) * (W / r.width), y = (evt.clientY - r.top) * (H / r.height);
507
+ for (var i = 0; i < items.length; i++) { var it = items[i]; if (x >= it.x && x <= it.x + it.w && y >= it.y && y <= it.y + it.h) return i; }
508
+ return -1;
509
+ }
510
+ function show(i, evt) {
511
+ if (i < 0) { self._hideTip(); return; }
512
+ self._active = i;
513
+ var it = items[i], hl = self._hlEl;
514
+ hl.setAttribute("x", it.x - 4); hl.setAttribute("y", it.y); hl.setAttribute("width", it.w + 8); hl.setAttribute("height", it.h); hl.setAttribute("opacity", 1);
515
+ var r = svg.getBoundingClientRect(), sx = r.width / W;
516
+ var rect = { left: r.left + it.px * sx, top: r.top + it.py * (r.height / H), width: 0, height: 0 };
517
+ self._placeTip(self._tipLines(it), rect, evt && evt.clientX ? evt : null);
518
+ }
519
+ svg.addEventListener("pointermove", function (e) { show(idxAt(e), e); });
520
+ svg.addEventListener("pointerleave", function () { self._hideTip(); });
521
+ svg.addEventListener("click", function (e) {
522
+ var i = idxAt(e);
523
+ if (i >= 0 && typeof o.onItemClick === "function") o.onItemClick(self._detail(items[i]), e);
524
+ });
525
+ svg.addEventListener("keydown", function (e) {
526
+ var i = self._active;
527
+ if (e.key === "ArrowRight" || e.key === "ArrowDown") i = Math.min(items.length - 1, i + 1);
528
+ else if (e.key === "ArrowLeft" || e.key === "ArrowUp") i = Math.max(0, i < 0 ? 0 : i - 1);
529
+ else if (e.key === "Home") i = 0;
530
+ else if (e.key === "End") i = items.length - 1;
531
+ else if (e.key === "Escape") { self._hideTip(); return; }
532
+ else if ((e.key === "Enter" || e.key === " ") && i >= 0) {
533
+ if (typeof o.onItemClick === "function") o.onItemClick(self._detail(items[i]), e);
534
+ e.preventDefault(); return;
535
+ } else return;
536
+ e.preventDefault();
537
+ show(i, null);
538
+ });
539
+ svg.addEventListener("blur", function () { self._hideTip(); });
540
+ };
541
+
542
+ Chart.prototype.createTable = function () {
543
+ var ex = this.getExportData(), wrap = htmlEl("div", "vpa-tables");
544
+ ex.sheets.forEach(function (sh) {
545
+ if (sh.name === "Notes") return;
546
+ var tb = htmlEl("table", "vpa-table", wrap);
547
+ htmlEl("caption", null, tb).textContent = sh.name;
548
+ var hr = htmlEl("tr", null, htmlEl("thead", null, tb));
549
+ sh.columns.forEach(function (c) { var th = htmlEl("th", null, hr); th.scope = "col"; th.textContent = c.label; });
550
+ var body = htmlEl("tbody", null, tb);
551
+ sh.text.forEach(function (r, i) {
552
+ var tr = htmlEl("tr", sh.flag && sh.flag[i] ? "vpa-breach" : null, body);
553
+ r.forEach(function (v, j) { var td = htmlEl(j ? "td" : "th", null, tr); if (!j) td.scope = "row"; td.textContent = v; });
554
+ });
555
+ });
556
+ return wrap;
557
+ };
558
+
559
+
560
+ Chart.prototype.redraw = function () {
561
+ var o = this.options, data = o.data, L = this._labels();
562
+ var res = this._res = compute(data, assign(this._opts(), { pathSteps: o.pathSteps }));
563
+ var theme = resolvePaTheme(o.theme), f = makeFormatters(data, o.locale), el = this.element, st = el.style;
564
+ var family = theme.fontFamily === "inherit" ? (root.getComputedStyle ? root.getComputedStyle(this.container).fontFamily : "sans-serif") : theme.fontFamily;
565
+ var filled = theme.background && theme.background !== "transparent", bg = filled ? theme.background : "#ffffff";
566
+ st.setProperty("--vpa-text", theme.text); st.setProperty("--vpa-muted", theme.mutedText);
567
+ st.setProperty("--vpa-bg", filled ? theme.background : "transparent"); st.setProperty("--vpa-font", family);
568
+ st.setProperty("--vpa-card", theme.cardBackground); st.setProperty("--vpa-card-muted", theme.cardMuted);
569
+ st.setProperty("--vpa-tip-bg", theme.tooltipBackground); st.setProperty("--vpa-tip-text", theme.tooltipText);
570
+ st.setProperty("--vpa-focus", theme.focus); st.setProperty("--vpa-hedge", theme.zoneText.red);
571
+ el.classList.toggle("vpa-filled", !!filled);
572
+ el.setAttribute("aria-label", o.ariaLabel || data.title || "P&L attribution");
573
+ var view = o.view;
574
+ if (["factors", "daily", "distribution"].indexOf(view) < 0) { warn('Unknown view "' + view + '". The factor view is shown instead.'); view = "factors"; }
575
+ if (res.shortWindow && !this._warnedShort) { warn("There are fewer days than the " + (o.window || 250) + "-day window; all " + res.window + " are used."); this._warnedShort = true; }
576
+ this._view = view;
577
+ this._renderSummary(res, f, L, theme);
578
+ this.scopeEl.textContent = [L[view], res.window + "-day window", data.unit || null, res.fixed.length ? res.fixed.length + " fix" + (res.fixed.length > 1 ? "es" : "") + " applied" : null].filter(Boolean).join(" · ");
579
+ this._renderLegend(view, theme, L, res);
580
+ var W = Math.max(280, Math.round(this.plotHost.clientWidth || el.clientWidth || 720));
581
+ this._lastWidth = Math.round(el.clientWidth);
582
+ var fs = theme.fontSize || 12;
583
+ this.plotHost.textContent = "";
584
+ var svg = svgEl("svg", { "class": "vpa-plot", role: "img", tabindex: 0, "font-family": family }, this.plotHost);
585
+ svg.style.fontSize = fs + "px";
586
+ var animate = this._animateNext && o.animate; this._animateNext = false;
587
+ if (animate) svg.classList.add("vpa-animate");
588
+ var ctx = { svg: svg, W: W, fs: fs, theme: theme, f: f, L: L, family: family, bg: bg, res: res, items: [], points: {} };
589
+ var H = view === "daily" ? this._drawDaily(ctx) : view === "distribution" ? this._drawDistribution(ctx) : this._drawFactors(ctx);
590
+ svg.setAttribute("viewBox", "0 0 " + W + " " + H);
591
+ svg.setAttribute("width", W); svg.setAttribute("height", H);
592
+ svg.setAttribute("aria-label", (o.ariaLabel || data.title || "P&L attribution") + ". " + this.describe());
593
+ this._items = ctx.items; this._points = ctx.points;
594
+ this._hlEl = svgEl("rect", { x: 0, y: 0, width: 0, height: 0, rx: 4, fill: theme.text, "fill-opacity": 0.06, opacity: 0, "pointer-events": "none" }, svg);
595
+ svg.insertBefore(this._hlEl, svg.firstChild);
596
+ this._bindInteraction(svg, W, H, theme, L, f);
597
+ return this;
598
+ };
599
+
600
+ function num2(v) { return v == null ? "n/a" : v.toFixed(2); }
601
+ Chart.prototype._zoneName = function (z) { var L = this._labels(); return L[z] || z; };
602
+
603
+ Chart.prototype._renderSummary = function (res, f, L, theme) {
604
+ var box = this.summaryEl, o = this.options, self = this;
605
+ box.textContent = "";
606
+ box.style.display = o.summary === false ? "none" : "";
607
+ if (o.summary === false) return;
608
+ function stat(k, v, n, cls, colour) {
609
+ var s = htmlEl("div", "vpa-stat", box);
610
+ htmlEl("div", "k", s).textContent = k;
611
+ var vv = htmlEl("div", cls ? "v " + cls : "v", s); vv.textContent = v; if (colour) vv.style.color = colour;
612
+ if (n) htmlEl("div", "n", s).textContent = n;
613
+ }
614
+ var t = res.test, top = res.order[0];
615
+ stat(L.test, this._zoneName(t.zone), "Spearman " + num2(t.spearman) + " · KS " + num2(t.ks) + " (" + res.window + " days)", "vpa-zone", theme.zoneText[t.zone]);
616
+ stat(L.unexplainedCard, "±" + f.value(res.sdUnexplained), (res.volRatio != null ? f.percent(res.volRatio, 0) + " of HPL volatility · " : "") + "mean " + f.signed(res.meanUnexplained) + " a day");
617
+ stat(L.largest, top.label, f.percent(top.share, 0) + " of the unexplained volatility", "vpa-wrap");
618
+ if (t.zone === "green") stat(L.path, "Already green", "margin: Spearman +" + (t.spearman - res.thresholds.spearmanGreen).toFixed(2) + ", KS −" + (res.thresholds.ksGreen - t.ks).toFixed(2));
619
+ else if (res.pathReachesGreen) stat(L.path, "Fix " + res.path.length + " factor" + (res.path.length > 1 ? "s" : ""), res.path.map(function (p) { return p.label; }).join(", ") + " → Spearman " + num2(res.path[res.path.length - 1].test.spearman) + ", KS " + num2(res.path[res.path.length - 1].test.ks), "vpa-wrap");
620
+ else stat(L.path, res.path.length ? "Not within " + res.path.length + " fix" + (res.path.length > 1 ? "es" : "") : "No single fix helps", res.path.length ? "best reached: " + this._zoneName(res.path[res.path.length - 1].test.zone).toLowerCase() : "the gap is spread across factors");
621
+ Array.prototype.forEach.call(box.querySelectorAll(".vpa-stat .v"), function (v) {
622
+ v.style.fontSize = "";
623
+ var size = parseFloat(root.getComputedStyle ? root.getComputedStyle(v).fontSize : 19) || 19;
624
+ while (v.scrollWidth > v.clientWidth && size > 12) { size -= 1; v.style.fontSize = size + "px"; }
625
+ });
626
+ };
627
+
628
+ Chart.prototype._renderLegend = function (view, theme, L, res) {
629
+ var box = this.legendEl;
630
+ box.textContent = "";
631
+ box.style.display = this.options.legend === false ? "none" : "";
632
+ function item(colour, text, cls) {
633
+ var s = htmlEl("span", null, box), i = htmlEl("i", cls || null, s);
634
+ if (cls === "vpa-ring") i.style.borderColor = colour; else i.style.background = colour;
635
+ s.appendChild(document.createTextNode(text));
636
+ }
637
+ if (view === "factors") { item(theme.contribution, L.adds); item(theme.offset, L.offsets); item(theme.standalone, L.standalone, "vpa-ring"); return; }
638
+ item(theme.hpl, L.hpl, "vpa-tick"); item(theme.rtpl, L.rtpl, "vpa-tick");
639
+ if (view === "daily") { item(theme.unexplained, L.unexplained); if (res.start > 0) item(theme.outside, L.outside); }
640
+ };
641
+
642
+ function rowLayout(c, names) {
643
+ var nameW = Math.min(Math.max.apply(null, names.map(function (n) { return textWidth(n, c.fs, 600, c.family); })) + 12, c.W * 0.34);
644
+ var narrow = c.W - nameW < 300;
645
+ return { nameW: narrow ? 0 : nameW, narrow: narrow };
646
+ }
647
+ function axisTicks(c, g, nt, xs, y, x0, x1, gridTop, gridBottom, fmt) {
648
+ var theme = c.theme, fs = c.fs, fam = c.family, W = c.W, lastRight = -Infinity;
649
+ nt.ticks.forEach(function (t) {
650
+ svgEl("line", { x1: xs(t), x2: xs(t), y1: gridTop, y2: gridBottom, stroke: t === 0 ? theme.axis : theme.grid, "stroke-width": t === 0 ? 1.2 : 1 }, g);
651
+ var tt = fmt(t), tw = textWidth(tt, fs - 1, 400, fam), tx = xs(t), anc = tx - tw / 2 < 0 ? "start" : tx + tw / 2 > W ? "end" : "middle";
652
+ var left = anc === "start" ? tx : anc === "end" ? tx - tw : tx - tw / 2;
653
+ if (left < lastRight + 8) return;
654
+ lastRight = left + tw;
655
+ label(g, tx, y + fs, tt, { "text-anchor": anc, fill: theme.axisText, "font-size": fs - 1, "class": "vpa-tick" });
656
+ });
657
+ }
658
+
659
+ /** Factor view: each factor's share of the unexplained volatility (adds up), stand-alone gap as a diamond, and the zone if fixed. */
660
+ Chart.prototype._drawFactors = function (c) {
661
+ var res = c.res, theme = c.theme, f = c.f, L = c.L, fs = c.fs, fam = c.family, W = c.W, svg = c.svg, self = this;
662
+ var top = +this.options.top > 0 ? Math.floor(+this.options.top) : res.order.length, rest = res.order.slice(top);
663
+ var rows = res.order.slice(0, top).sort(function (a, b) { return b.contribution - a.contribution; }).map(function (x) { return { kind: "factor", obj: x, name: x.label + (x.modelled ? "" : " *"), v: x.contribution, k: x.sdGap }; });
664
+ if (rest.length) { var sv = 0, sk = 0; rest.forEach(function (x) { sv += x.contribution; sk += x.sdGap; }); rows.push({ kind: "other", obj: { count: rest.length, contribution: sv, factors: rest }, name: fill(L.other, { n: rest.length }), v: sv, k: null }); }
665
+ var lay = rowLayout(c, rows.map(function (r) { return r.name; }));
666
+ var zoneW = Math.max(textWidth("→ " + L.amber, fs - 1, 600, fam), textWidth("→ " + L.green, fs - 1, 600, fam), textWidth("→ " + L.red, fs - 1, 600, fam)) + 14;
667
+ var valW = Math.max.apply(null, rows.map(function (r) { return textWidth(f.signed(r.v), fs, 700, fam); })) + 10;
668
+ var x0 = lay.nameW, x1 = W - valW - zoneW, rowH = Math.max(26, fs * 2.1), extra = lay.narrow ? fs + 4 : 0, y = 4;
669
+ var lo = Math.min(0, Math.min.apply(null, rows.map(function (r) { return r.v; }))), hi = Math.max.apply(null, rows.map(function (r) { return Math.max(r.v, r.k || 0); })) || 1;
670
+ var nt = niceTicks(lo, hi, Math.max(2, Math.min(6, Math.floor((x1 - x0) / 90))));
671
+ var xs = function (v) { return x0 + (clamp(v, nt.lo, nt.hi) - nt.lo) / (nt.hi - nt.lo) * (x1 - x0); };
672
+ var gridTop = y + fs + 6, gridBottom = gridTop + rows.length * (rowH + extra), g = svgEl("g", { "class": "vpa-factors" }, svg);
673
+ axisTicks(c, g, nt, xs, y, x0, x1, gridTop, gridBottom, function (v) { return f.value(v); });
674
+ label(g, W, y + fs, L.ifFixed, { "text-anchor": "end", fill: theme.axisText, "font-size": fs - 1, "class": "vpa-tick" });
675
+ rows.forEach(function (r, i) {
676
+ var ry = gridTop + i * (rowH + extra) + extra, bh = rowH * 0.56, by = ry + (rowH - bh) / 2, neg = r.v < 0 && f.value(-r.v) !== f.value(0); // a value that rounds to zero is shown as neutral
677
+ label(g, 0, lay.narrow ? ry - 3 : by + bh / 2 + fs * 0.35, fit(r.name, lay.narrow ? W - zoneW : lay.nameW - 8, fs, r.kind === "other" ? 400 : 600, fam), { fill: r.kind === "other" ? theme.mutedText : theme.text, "font-size": fs, "font-weight": r.kind === "other" ? 400 : 600, "class": "vpa-name" });
678
+ var xa = xs(Math.min(0, r.v)), xb = xs(Math.max(0, r.v));
679
+ svgEl("rect", { x: xa, y: by, width: Math.max(0.8, xb - xa), height: bh, rx: 2, fill: neg ? theme.offset : theme.contribution, "class": "vpa-grow vpa-cbar" + (neg ? " vpa-offset" : "") }, g);
680
+ if (r.k != null) { var kx = xs(r.k), ky = by + bh / 2;
681
+ svgEl("path", { d: "M" + kx + "," + (ky - 5) + "L" + (kx + 5) + "," + ky + "L" + kx + "," + (ky + 5) + "L" + (kx - 5) + "," + ky + "Z", fill: c.bg, stroke: theme.standalone, "stroke-width": 1.6, "class": "vpa-sa" }, g); }
682
+ label(g, W - zoneW, by + bh / 2 + fs * 0.35, f.signed(r.v), { "text-anchor": "end", fill: neg ? theme.offsetText : theme.text, "font-size": fs, "font-weight": 700, "class": "vpa-val" });
683
+ if (r.kind === "factor") {
684
+ var z = r.obj.ifFixed.zone;
685
+ label(g, W, by + bh / 2 + fs * 0.35, "→ " + self._zoneName(z), { "text-anchor": "end", fill: theme.zoneText[z], "font-size": fs - 1, "font-weight": 600, "class": "vpa-zonefix" });
686
+ c.points[r.obj.key] = { x: neg ? xa : xb, y: by };
687
+ }
688
+ c.items.push({ kind: r.kind, obj: r.obj, x: 0, y: ry - extra, w: W, h: rowH + extra, px: neg ? xa : xb, py: by });
689
+ });
690
+ var notes = ["Shares add up to the unexplained volatility of ±" + f.value(res.sdUnexplained) + " a day over " + res.window + " days"];
691
+ if (res.factors.some(function (x) { return !x.modelled; })) notes.push("* " + L.notModelled + " (RTPL taken as zero)");
692
+ notes.push("“" + L.ifFixed + "”: test zone with that factor's RTPL set equal to its HPL");
693
+ var y2 = gridBottom + fs + 8;
694
+ notes.forEach(function (t) { label(svg, 0, y2, fit(t + ".", W, fs - 1, 400, fam), { fill: theme.mutedText, "font-size": fs - 1, "class": "vpa-note" }); y2 += fs + 3; });
695
+ return Math.ceil(y2 - fs + 6);
696
+ };
697
+
698
+ /** Daily view: HPL and RTPL lines with the unexplained P&L as bars; days outside the test window are greyed. */
699
+ Chart.prototype._drawDaily = function (c) {
700
+ var res = c.res, theme = c.theme, f = c.f, L = c.L, fs = c.fs, fam = c.family, W = c.W, svg = c.svg, n = res.dates.length;
701
+ var all = res.hpl.concat(res.rtpl, res.unexplained);
702
+ var nt = niceTicks(Math.min(0, Math.min.apply(null, all)), Math.max(0, Math.max.apply(null, all)), W < 480 ? 4 : 6);
703
+ var tickW = Math.max.apply(null, nt.ticks.map(function (t) { return textWidth(f.value(t), fs - 1, 400, fam); }));
704
+ var x0 = tickW + 10, x1 = W - 4, top = 6, ph = W < 480 ? 220 : 300, bottom = top + ph;
705
+ var xs = function (i) { return x0 + (i + 0.5) / n * (x1 - x0); }, ys = function (v) { return top + (nt.hi - clamp(v, nt.lo, nt.hi)) / (nt.hi - nt.lo) * ph; };
706
+ var g = svgEl("g", { "class": "vpa-daily" }, svg);
707
+ if (res.start > 0) svgEl("rect", { x: x0, y: top, width: xs(res.start) - (x1 - x0) / n / 2 - x0, height: ph, fill: theme.outside, "fill-opacity": 0.35, "class": "vpa-outside" }, g);
708
+ nt.ticks.forEach(function (t) {
709
+ svgEl("line", { x1: x0, x2: x1, y1: ys(t), y2: ys(t), stroke: t === 0 ? theme.axis : theme.grid, "stroke-width": t === 0 ? 1.2 : 1 }, g);
710
+ label(g, x0 - 6, ys(t) + (fs - 1) * 0.35, f.value(t), { "text-anchor": "end", fill: theme.axisText, "font-size": fs - 1, "class": "vpa-tick" });
711
+ });
712
+ var bw = Math.max(0.6, (x1 - x0) / n * 0.7);
713
+ res.unexplained.forEach(function (u, i) { var ya = ys(Math.max(0, u)), yb = ys(Math.min(0, u)); svgEl("rect", { x: xs(i) - bw / 2, y: ya, width: bw, height: Math.max(0.6, yb - ya), fill: theme.unexplained, "fill-opacity": i < res.start ? 0.4 : 0.85, "class": "vpa-grow vpa-ubar" }, g); });
714
+ var path = function (a) { return a.map(function (v, i) { return (i ? "L" : "M") + xs(i).toFixed(2) + "," + ys(v).toFixed(2); }).join(""); };
715
+ svgEl("path", { d: path(res.hpl), fill: "none", stroke: theme.hpl, "stroke-width": 1.6, "stroke-linejoin": "round", "class": "vpa-line vpa-hpl" }, g);
716
+ svgEl("path", { d: path(res.rtpl), fill: "none", stroke: theme.rtpl, "stroke-width": 1.6, "stroke-dasharray": "4 2", "stroke-linejoin": "round", "class": "vpa-line vpa-rtpl" }, g);
717
+ // date labels, thinned
718
+ var lw = textWidth(res.dates[0], fs - 1, 400, fam) + 16, every = Math.max(1, Math.ceil(lw / ((x1 - x0) / n))), lastRight = -Infinity;
719
+ for (var i = 0; i < n; i += every) {
720
+ var tx = xs(i), tw = textWidth(res.dates[i], fs - 1, 400, fam), anc = tx - tw / 2 < 0 ? "start" : tx + tw / 2 > W ? "end" : "middle", left = anc === "start" ? tx : anc === "end" ? tx - tw : tx - tw / 2;
721
+ if (left < lastRight + 8) continue;
722
+ lastRight = left + tw;
723
+ label(g, tx, bottom + fs + 9, res.dates[i], { "text-anchor": anc, fill: theme.axisText, "font-size": fs - 1, "class": "vpa-tick" });
724
+ }
725
+ var step = (x1 - x0) / n;
726
+ res.dates.forEach(function (d, j) {
727
+ c.items.push({ kind: "day", index: j, x: xs(j) - step / 2, y: top, w: step, h: ph, px: xs(j), py: ys(Math.max(res.hpl[j], res.rtpl[j])) });
728
+ c.points["date:" + d] = { x: xs(j), y: ys(Math.max(res.hpl[j], res.rtpl[j])) };
729
+ });
730
+ var notes = ["Unexplained P&L ±" + f.value(res.sdUnexplained) + " a day (" + (res.volRatio != null ? f.percent(res.volRatio, 0) + " of HPL volatility" : "") + ") over the last " + res.window + " days"];
731
+ var y2 = bottom + fs * 2 + 17;
732
+ notes.forEach(function (t) { label(svg, 0, y2, fit(t + ".", W, fs - 1, 400, fam), { fill: theme.mutedText, "font-size": fs - 1, "class": "vpa-note" }); y2 += fs + 3; });
733
+ return Math.ceil(y2 - fs + 6);
734
+ };
735
+
736
+ /** Distribution view: the two empirical distribution functions with the KS distance marked. */
737
+ Chart.prototype._drawDistribution = function (c) {
738
+ var res = c.res, theme = c.theme, f = c.f, L = c.L, fs = c.fs, fam = c.family, W = c.W, svg = c.svg, D = res.distribution, n = D.hpl.length, T = res.thresholds;
739
+ var lo = Math.min(D.hpl[0], D.rtpl[0]), hi = Math.max(D.hpl[n - 1], D.rtpl[n - 1]);
740
+ var nt = niceTicks(lo, hi, W < 480 ? 4 : 6);
741
+ var x0 = textWidth("100%", fs - 1, 400, fam) + 10, x1 = W - 6, top = 8, ph = W < 480 ? 200 : 270, bottom = top + ph;
742
+ var xs = function (v) { return x0 + (clamp(v, nt.lo, nt.hi) - nt.lo) / (nt.hi - nt.lo) * (x1 - x0); }, ys = function (p) { return top + (1 - p) * ph; };
743
+ var g = svgEl("g", { "class": "vpa-dist" }, svg);
744
+ [0, 0.25, 0.5, 0.75, 1].forEach(function (p) {
745
+ svgEl("line", { x1: x0, x2: x1, y1: ys(p), y2: ys(p), stroke: p === 0 ? theme.axis : theme.grid }, g);
746
+ label(g, x0 - 6, ys(p) + (fs - 1) * 0.35, Math.round(p * 100) + "%", { "text-anchor": "end", fill: theme.axisText, "font-size": fs - 1, "class": "vpa-tick" });
747
+ });
748
+ axisTicks(c, g, nt, xs, bottom + 8, x0, x1, top, bottom, function (v) { return f.value(v); });
749
+ var step = function (a) { var d = "M" + xs(nt.lo) + "," + ys(0); a.forEach(function (v, i) { d += "L" + xs(v).toFixed(2) + "," + ys(i / n).toFixed(2) + "L" + xs(v).toFixed(2) + "," + ys((i + 1) / n).toFixed(2); }); return d + "L" + xs(nt.hi) + "," + ys(1); };
750
+ svgEl("path", { d: step(D.hpl), fill: "none", stroke: theme.hpl, "stroke-width": 1.8, "class": "vpa-line vpa-hpl" }, g);
751
+ svgEl("path", { d: step(D.rtpl), fill: "none", stroke: theme.rtpl, "stroke-width": 1.8, "stroke-dasharray": "4 2", "class": "vpa-line vpa-rtpl" }, g);
752
+ var cdf = function (a, v) { var lo2 = 0, hi2 = a.length; while (lo2 < hi2) { var m = (lo2 + hi2) >> 1; if (a[m] <= v) lo2 = m + 1; else hi2 = m; } return lo2 / a.length; };
753
+ var at = res.test.ksAt, p1 = cdf(D.hpl, at), p2 = cdf(D.rtpl, at), kx = xs(at), z = res.test.zone;
754
+ svgEl("line", { x1: kx, x2: kx, y1: ys(p1), y2: ys(p2), stroke: theme.zoneText[z], "stroke-width": 3, "class": "vpa-ksline" }, g);
755
+ var kt = "KS " + num2(res.test.ks), ktw = textWidth(kt, fs, 700, fam), kl = kx + 8 + ktw > W ? kx - 8 : kx + 8;
756
+ svgEl("rect", { x: (kx + 8 + ktw > W ? kl - ktw : kl) - 3, y: (ys(p1) + ys(p2)) / 2 - fs * 0.7, width: ktw + 6, height: fs * 1.4, rx: 3, fill: c.bg, "class": "vpa-lbg" }, g);
757
+ label(g, kl, (ys(p1) + ys(p2)) / 2 + fs * 0.35, kt, { "text-anchor": kx + 8 + ktw > W ? "end" : "start", fill: theme.zoneText[z], "font-size": fs, "font-weight": 700, "class": "vpa-kslabel" });
758
+ for (var i = 0; i <= 20; i++) {
759
+ var v = nt.lo + (nt.hi - nt.lo) * i / 20, wx = (x1 - x0) / 20;
760
+ c.items.push({ kind: "point", value: v, ph: cdf(D.hpl, v), pr: cdf(D.rtpl, v), x: xs(v) - wx / 2, y: top, w: wx, h: ph, px: xs(v), py: ys(Math.max(cdf(D.hpl, v), cdf(D.rtpl, v))) });
761
+ }
762
+ var notes = ["Spearman " + num2(res.test.spearman) + " (green above " + T.spearmanGreen.toFixed(2) + ", red below " + T.spearmanRed.toFixed(2) + ") · KS " + num2(res.test.ks) + " (green below " + T.ksGreen.toFixed(2) + ", red above " + T.ksRed.toFixed(2) + ")",
763
+ "Share of the " + res.window + " days with P&L at or below each value"];
764
+ var y2 = bottom + fs * 2 + 12;
765
+ notes.forEach(function (t) { label(svg, 0, y2, fit(t + ".", W, fs - 1, 400, fam), { fill: theme.mutedText, "font-size": fs - 1, "class": "vpa-note" }); y2 += fs + 3; });
766
+ return Math.ceil(y2 - fs + 6);
767
+ };
768
+
769
+ Chart.prototype._tipLines = function (it) {
770
+ var o = this.options, f = makeFormatters(o.data, o.locale), L = this._labels(), res = this._res, self = this;
771
+ if (it.kind === "other") return [fill(L.other, { n: it.obj.count }), "Together " + f.signed(it.obj.contribution) + " of the unexplained volatility"];
772
+ if (it.kind === "day") {
773
+ var j = it.index, gaps = res.factors.map(function (x) { return { l: x.label, g: x.gap[j] }; }).filter(function (q) { return q.g !== 0; }).sort(function (a, b) { return Math.abs(b.g) - Math.abs(a.g); }).slice(0, 3);
774
+ return [res.dates[j] + (j < res.start ? " · " + L.outside.toLowerCase() : ""), L.hpl + " " + f.signed(res.hpl[j]), L.rtpl + " " + f.signed(res.rtpl[j]), L.unexplained + " " + f.signed(res.unexplained[j])]
775
+ .concat(gaps.length ? ["Largest gaps: " + gaps.map(function (q) { return q.l + " " + f.signed(q.g); }).join(", ")] : []);
776
+ }
777
+ if (it.kind === "point") return ["P&L at or below " + f.signed(it.value), "HPL " + f.percent(it.ph, 0) + " of days · RTPL " + f.percent(it.pr, 0), "Gap " + f.percent(Math.abs(it.ph - it.pr), 0) + " (KS is the largest gap: " + num2(res.test.ks) + ")"];
778
+ var x = it.obj, t = x.ifFixed;
779
+ return [x.label + (x.modelled ? "" : " (" + L.notModelled + ")"), x.group + " · rank " + x.rank + " of " + res.factors.length,
780
+ "Share of unexplained volatility " + f.signed(x.contribution) + " (" + f.percent(x.share, 0) + ")",
781
+ "Gap on its own ±" + f.value(x.sdGap) + " a day · mean " + f.signed(x.meanGap),
782
+ "HPL " + f.signed(x.hplSum) + " · RTPL " + f.signed(x.rtplSum) + " over " + res.window + " days",
783
+ L.ifFixed + ": " + self._zoneName(t.zone).toLowerCase() + " (Spearman " + num2(t.spearman) + ", KS " + num2(t.ks) + ")"];
784
+ };
785
+
786
+ Chart.prototype._detail = function (it) {
787
+ if (!it) return null;
788
+ var res = this._res, view = this._view;
789
+ if (it.kind === "other") return { view: view, kind: "other", count: it.obj.count, contribution: it.obj.contribution, factors: it.obj.factors.map(function (x) { return x.key; }) };
790
+ if (it.kind === "day") { var j = it.index; return { view: view, kind: "day", date: res.dates[j], hpl: res.hpl[j], rtpl: res.rtpl[j], unexplained: res.unexplained[j], inWindow: j >= res.start, gaps: res.factors.map(function (x) { return { key: x.key, gap: x.gap[j] }; }) }; }
791
+ if (it.kind === "point") return { view: view, kind: "point", value: it.value, hplShare: it.ph, rtplShare: it.pr };
792
+ var x = it.obj;
793
+ return { view: view, kind: "factor", key: x.key, label: x.label, group: x.group, modelled: x.modelled, fixed: x.fixed, rank: x.rank, contribution: x.contribution, share: x.share, sdGap: x.sdGap, meanGap: x.meanGap,
794
+ hplSum: x.hplSum, rtplSum: x.rtplSum, ifFixed: { spearman: x.ifFixed.spearman, ks: x.ifFixed.ks, zone: x.ifFixed.zone } };
795
+ };
796
+
797
+ Chart.prototype.howToRead = function () {
798
+ var v = this._view || this.options.view;
799
+ if (v === "daily") return "The dark line is front-office hypothetical P&L (HPL) and the dashed line the risk model's P&L (RTPL), day by day. Grey bars are the difference, the unexplained P&L. Only the most recent days, inside the test window, count for the test.";
800
+ if (v === "distribution") return "Each line shows the share of days with P&L at or below a value, for HPL and for RTPL. If the risk model matched the front office, the two lines would sit on top of each other. The coloured bar marks the largest gap between them, the Kolmogorov-Smirnov (KS) statistic.";
801
+ return "Each bar is one risk factor's share of the unexplained P&L volatility (HPL − RTPL). Shares add up exactly to the total; a bar to the left means the factor's gap offsets other gaps. The diamond is the factor's gap on its own, and the right column shows the test zone the desk would reach if that factor's gap were closed.";
802
+ };
803
+
804
+ Chart.prototype.describe = function () {
805
+ var o = this.options, f = makeFormatters(o.data, o.locale), L = this._labels(), res = this._res || compute(o.data, this._opts()), t = res.test, T = res.thresholds, out = [], self = this;
806
+ var why = [];
807
+ if (t.spearman == null || t.spearman <= T.spearmanGreen) why.push("Spearman " + num2(t.spearman) + (t.spearman != null && t.spearman >= T.spearmanRed ? " is below " + T.spearmanGreen.toFixed(2) : " is below " + T.spearmanRed.toFixed(2)));
808
+ if (t.ks >= T.ksGreen) why.push("KS " + num2(t.ks) + (t.ks <= T.ksRed ? " is above " + T.ksGreen.toFixed(2) : " is above " + T.ksRed.toFixed(2)));
809
+ out.push("Over the last " + res.window + " days the desk is in the " + this._zoneName(t.zone).toLowerCase() + " zone of the P&L attribution test" + (why.length ? ": " + why.join(" and ") + "." : " (Spearman " + num2(t.spearman) + ", KS " + num2(t.ks) + ")."));
810
+ out.push("Unexplained P&L is ±" + f.value(res.sdUnexplained) + " a day" + (res.volRatio != null ? ", " + f.percent(res.volRatio, 0) + " of the front office's P&L volatility" : "") + ".");
811
+ var a = res.order[0], b = res.order[1];
812
+ out.push(a.label + (a.modelled ? "" : ", which is not in the risk model,") + " explains " + f.percent(a.share, 0) + " of it" + (b ? ", followed by " + b.label + " (" + f.percent(b.share, 0) + ")" : "") + ".");
813
+ var off = res.factors.filter(function (x) { return x.share < -0.02; }).sort(function (p, q) { return p.contribution - q.contribution; });
814
+ if (off.length) out.push("The gap on " + off[0].label + " partly offsets the others.");
815
+ if (t.zone !== "green") {
816
+ if (res.pathReachesGreen) { var last = res.path[res.path.length - 1].test; out.push("Closing the gap on " + res.path.map(function (p) { return p.label; }).join(" and ") + " would bring the desk to green (Spearman " + num2(last.spearman) + ", KS " + num2(last.ks) + ")."); }
817
+ else if (res.path.length) out.push("Even closing the gaps on " + res.path.map(function (p) { return p.label; }).join(", ") + " only reaches " + this._zoneName(res.path[res.path.length - 1].test.zone).toLowerCase() + ".");
818
+ }
819
+ if (res.fixed.length) out.push("Fixes applied: " + res.fixed.join(", ") + ".");
820
+ return out.join(" ");
821
+ };
822
+
823
+ /* ======================================================================
824
+ 5. EXPORT AND NOTES
825
+ ====================================================================== */
826
+ Chart.prototype.getExportData = function () {
827
+ var o = this.options, data = o.data, L = this._labels(), f = makeFormatters(data, o.locale), res = this._res || compute(data, this._opts()), self = this, T = res.thresholds;
828
+ var unit = { prefix: data.prefix || "", suffix: data.suffix || "", decimals: data.decimals != null ? data.decimals : 0, negatives: data.negatives };
829
+ var money = function (label) { return { label: label, type: "number", unit: unit }; };
830
+ var ratio = function (label) { return { label: label, type: "number", unit: { decimals: 3 } }; };
831
+ var pct = function (label) { return { label: label, type: "percent", decimals: 1 }; };
832
+ var txt = function (label) { return { label: label, type: "text" }; };
833
+ var sheets = [];
834
+ sheets.push({ name: "Factors", columns: [{ label: "Rank", type: "number", unit: { decimals: 0 } }, txt("Risk factor"), txt("Group"), txt("In risk model"), txt("Fixed"), money("HPL over window"), money("RTPL over window"), money("Mean daily gap"), money("Gap volatility"), money("Share of unexplained volatility"), pct("Share (%)"), ratio("Spearman if fixed"), ratio("KS if fixed"), txt("Zone if fixed")],
835
+ rows: res.order.map(function (x) { return [x.rank, x.label, x.group, x.modelled ? "Yes" : "No", x.fixed ? "Yes" : "No", x.hplSum, x.rtplSum, x.meanGap, x.sdGap, x.contribution, x.share, x.ifFixed.spearman, x.ifFixed.ks, self._zoneName(x.ifFixed.zone)]; }),
836
+ text: res.order.map(function (x) { return [String(x.rank), x.label, x.group, x.modelled ? "Yes" : "No", x.fixed ? "Yes" : "No", f.signed(x.hplSum), f.signed(x.rtplSum), f.signed(x.meanGap), f.value(x.sdGap), f.signed(x.contribution), f.percent(x.share), num2(x.ifFixed.spearman), num2(x.ifFixed.ks), self._zoneName(x.ifFixed.zone)]; }),
837
+ flag: res.order.map(function (x) { return !x.modelled; }) });
838
+ var cap = o.exportDays != null ? o.exportDays : 20000, from = Math.max(0, res.dates.length - cap), idx = [];
839
+ for (var j = from; j < res.dates.length; j++) idx.push(j);
840
+ sheets.push({ name: "Daily", columns: [txt("Date"), money("HPL"), money("RTPL"), money("Unexplained"), txt("In test window")],
841
+ rows: idx.map(function (j) { return [res.dates[j], res.hpl[j], res.rtpl[j], res.unexplained[j], j >= res.start ? "Yes" : "No"]; }),
842
+ text: idx.map(function (j) { return [res.dates[j], f.signed(res.hpl[j]), f.signed(res.rtpl[j]), f.signed(res.unexplained[j]), j >= res.start ? "Yes" : "No"]; }) });
843
+ var tr = [["Spearman correlation", res.test.spearman, "green above " + T.spearmanGreen + ", red below " + T.spearmanRed], ["Kolmogorov-Smirnov statistic", res.test.ks, "green below " + T.ksGreen + ", red above " + T.ksRed],
844
+ ["Unexplained volatility ÷ HPL volatility", res.volRatio, ""], ["Mean unexplained ÷ HPL volatility", res.meanRatio, ""], ["Variance of unexplained ÷ variance of HPL", res.varRatio, ""]];
845
+ res.path.forEach(function (p, i) { tr.push(["Path step " + (i + 1) + ": fix " + p.label + " → Spearman", p.test.spearman, self._zoneName(p.test.zone)], ["Path step " + (i + 1) + ": fix " + p.label + " → KS", p.test.ks, self._zoneName(p.test.zone)]); });
846
+ sheets.push({ name: "Test", columns: [txt("Measure"), ratio("Value"), txt("Note")], rows: tr, text: tr.map(function (r) { return [r[0], r[1] == null ? "n/a" : r[1].toFixed(3), r[2]]; }) });
847
+ var notes = (o.annotations || []).map(function (a, i) { return [String(i + 1), a.factor != null ? String(a.factor) : "Date: " + String(a.date || ""), a.text || ""]; });
848
+ if (notes.length) sheets.push({ name: "Notes", columns: [txt("No."), txt("Factor or date"), txt("Note")], rows: notes });
849
+ return {
850
+ title: data.title || "P&L attribution", subtitle: data.subtitle || "", summary: this.describe(), library: "Veyforma P&L Attribution " + VERSION, sheets: sheets,
851
+ meta: [["Unit", data.unit], ["As of", data.asOf], ["Desk", data.desk], ["Test window", res.window + " days (" + res.dates[res.start] + " to " + res.dates[res.dates.length - 1] + ")"],
852
+ ["PLA test zone", self._zoneName(res.test.zone) + " (Spearman " + num2(res.test.spearman) + ", KS " + num2(res.test.ks) + ")"],
853
+ ["Fixes applied", res.fixed.length ? res.fixed.join(", ") : null],
854
+ ["Method", "Spearman = correlation of the ranks of daily HPL and RTPL (ties averaged); KS = largest gap between their empirical distribution functions; green if Spearman > " + T.spearmanGreen + " and KS < " + T.ksGreen + ", red if Spearman < " + T.spearmanRed + " or KS > " + T.ksRed + ", otherwise amber; factor share = cov(gap, unexplained) ÷ sd(unexplained), adds up to sd(unexplained); \"if fixed\" sets that factor's RTPL equal to its HPL" + (from > 0 ? "; daily sheet limited to the last " + cap + " days" : "")],
855
+ ["Data source", data.source]]
856
+ };
857
+ };
858
+ Chart.prototype._annotationPoint = function (a) {
859
+ var p = this._points || {};
860
+ if (a.factor != null) return p[String(a.factor)] || null;
861
+ if (a.date != null) return p["date:" + String(a.date)] || null;
862
+ return null;
863
+ };
864
+ Chart.prototype._annotationTarget = function (evt) {
865
+ var items = this._items || [], it = null;
866
+ if (!evt) it = items[this._active];
867
+ else {
868
+ var svg = this.plotHost.querySelector("svg"), r = svg.getBoundingClientRect(), vb = svg.viewBox.baseVal;
869
+ var x = (evt.clientX - r.left) * (vb.width / r.width), y = (evt.clientY - r.top) * (vb.height / r.height);
870
+ for (var i = 0; i < items.length; i++) { var q = items[i]; if (x >= q.x && x <= q.x + q.w && y >= q.y && y <= q.y + q.h) { it = q; break; } }
871
+ }
872
+ if (!it) return null;
873
+ if (it.kind === "factor") return { factor: it.obj.key };
874
+ if (it.kind === "day") return { date: this._res.dates[it.index] };
875
+ return null;
876
+ };
877
+ Chart.prototype._annotationLabel = function (a) {
878
+ if (a.date != null) return String(a.date);
879
+ var x = (this._res || this.getResult()).factors.filter(function (q) { return q.key === String(a.factor); })[0];
880
+ return x ? x.label : String(a.factor || "");
881
+ };
882
+
883
+ /* ======================================================================
884
+ 6. PUBLIC API
885
+ ====================================================================== */
886
+ root.VeyPlaAttribution = {
887
+ version: VERSION,
888
+ /** Draws the chart inside a container element or CSS selector. */
889
+ create: function (target, options) { return new Chart(target, options); },
890
+ /** Works out every figure without drawing. opts: { window, fix, thresholds, pathSteps }. */
891
+ compute: function (data, opts) { return compute(data, opts); },
892
+ /** The test on two series of daily P&L: { spearman, ks, zone }. */
893
+ test: function (hpl, rtpl, thresholds) { return test(hpl, rtpl, assign({}, THRESHOLDS, thresholds || {})); },
894
+ thresholds: THRESHOLDS,
895
+ listThemes: function () { return Object.keys(THEMES); },
896
+ getTheme: function (t) { return resolvePaTheme(t); },
897
+ defaults: { options: DEFAULT_OPTIONS, labels: DEFAULT_LABELS, theme: BASE_THEME }
898
+ };
899
+ })(typeof window !== "undefined" ? window : this);