@veyforma/charts 0.0.0-stage → 1.0.2
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/LICENSE +21 -0
- package/README.md +186 -2
- package/dist/veyforma-charts.cjs +2952 -0
- package/dist/veyforma-charts.js +2945 -0
- package/dist/veyforma-charts.min.js +2 -0
- package/dist/veyforma-charts.mjs +2952 -0
- package/dist/veyforma-heatmap.js +1104 -0
- package/dist/veyforma-heatmap.min.js +2 -0
- package/dist/veyforma-pla.js +899 -0
- package/dist/veyforma-pla.min.js +2 -0
- package/dist/veyforma-tornado.js +912 -0
- package/dist/veyforma-tornado.min.js +2 -0
- package/package.json +51 -4
- package/src/veyforma-charts.js +26 -0
- package/src/veyforma-heatmap.js +1104 -0
- package/src/veyforma-pla.js +899 -0
- package/src/veyforma-tornado.js +912 -0
|
@@ -0,0 +1,912 @@
|
|
|
1
|
+
// Risk-Factor Tornado – Veyforma Chart Library · https://www.veyforma.com/charts/risk-factor-tornado
|
|
2
|
+
/*!
|
|
3
|
+
* Veyforma Risk-Factor Tornado v1.0.0
|
|
4
|
+
* Ranks the risk factors that move P&L, economic value or capital the most, for a down and
|
|
5
|
+
* an up shock to each factor. Impacts come from full revaluation or from delta and gamma
|
|
6
|
+
* (Taylor), and can be rescaled to any shock size. On top of the classic tornado it shows the
|
|
7
|
+
* convexity of each factor (how unequal the up and down results are), breaches of a loss
|
|
8
|
+
* limit, how much the top factors explain, groups such as risk classes, the interaction when
|
|
9
|
+
* every factor is shocked together, and each factor's share of the combined move once the
|
|
10
|
+
* factors' correlations are taken into account, so hedges become visible.
|
|
11
|
+
* Original work created for Veyforma. Contains no third-party code.
|
|
12
|
+
* Released under the MIT License. Copyright (c) 2026 Veyforma.
|
|
13
|
+
* https://github.com/veyforma/veyforma-charts
|
|
14
|
+
*
|
|
15
|
+
* Load veyforma-toolkit.js as well to get the chart menu: full screen, print,
|
|
16
|
+
* PNG, JPEG, SVG, PDF, CSV and Excel downloads, copy, notes and the
|
|
17
|
+
* "How to read this chart" box.
|
|
18
|
+
*
|
|
19
|
+
* File layout
|
|
20
|
+
* 1. Settings .......... themes, labels and options
|
|
21
|
+
* 2. Helpers ........... formatting and small utilities
|
|
22
|
+
* 3. Calculation ....... impacts, ranking, convexity, groups, correlated contributions
|
|
23
|
+
* 4. Chart instance .... factor, group and contribution views, tooltips, keyboard
|
|
24
|
+
* 5. Export and notes .. data for the Veyforma Toolkit menu (optional file)
|
|
25
|
+
* 6. Public API ........ window.VeyRiskTornado
|
|
26
|
+
*
|
|
27
|
+
* Method in one paragraph (see the manual for detail):
|
|
28
|
+
* Each factor has a down and an up impact, given directly or as Δ·s + ½Γ·s² for the shock s.
|
|
29
|
+
* Swing = |up − down|; the linear part is L = (up − down) ÷ 2 and the convexity C = (up + down) ÷ 2,
|
|
30
|
+
* so a shock k times larger moves the result by about L·k + C·k². Factors are ranked by swing (or by
|
|
31
|
+
* their worst result). Combined move σ = √(Lᵀ ρ L) with ρ the factor correlations; factor k's share of it
|
|
32
|
+
* is L_k (ρL)_k ÷ σ, which adds up exactly to σ; a negative share means the factor hedges the others.
|
|
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
|
+
down: "#4b5563", // bars for the down shock
|
|
46
|
+
up: "#c2410c", // bars for the up shock
|
|
47
|
+
hedge: "#2f6fed", // contributions that lower the combined move
|
|
48
|
+
contribution: "#a63d16", // contributions that add to it
|
|
49
|
+
convexity: "#111827", // convexity marker (midpoint of the two results)
|
|
50
|
+
limit: "#b91c1c", // loss limit line and breaches
|
|
51
|
+
grid: "#ececec",
|
|
52
|
+
axis: "#9ca3af",
|
|
53
|
+
text: "#111827",
|
|
54
|
+
mutedText: "#4b5563",
|
|
55
|
+
axisText: "#4b5563",
|
|
56
|
+
cardBackground: "#f9fafb",
|
|
57
|
+
background: "transparent",
|
|
58
|
+
tooltipBackground: "#111827",
|
|
59
|
+
tooltipText: "#ffffff",
|
|
60
|
+
focus: "#c2410c",
|
|
61
|
+
accent: "#c2410c",
|
|
62
|
+
fontFamily: "inherit",
|
|
63
|
+
fontSize: 12
|
|
64
|
+
};
|
|
65
|
+
var THEMES = {
|
|
66
|
+
veyforma: {},
|
|
67
|
+
mono: { down: "#8a8a8a", up: "#111111", hedge: "#8a8a8a", contribution: "#111111", convexity: "#111111", limit: "#111111", accent: "#111111", focus: "#111111" },
|
|
68
|
+
"colour-safe": { down: "#2166ac", up: "#b2182b", hedge: "#1b7837", contribution: "#762a83", limit: "#b2182b", accent: "#2166ac" },
|
|
69
|
+
ocean: { down: "#64748b", up: "#0c6e8f", hedge: "#c2410c", contribution: "#0c3b5e", cardBackground: "#eef5f8", accent: "#0c6e8f" },
|
|
70
|
+
forest: { down: "#78716c", up: "#4d6b31", hedge: "#2f6fed", contribution: "#22311a", cardBackground: "#f2f4ee", accent: "#4d6b31" },
|
|
71
|
+
corporate: { down: "#64748b", up: "#1d4ed8", hedge: "#c2410c", contribution: "#1e293b", cardBackground: "#f1f4f8", accent: "#1d4ed8" },
|
|
72
|
+
midnight: { background: "#111418", down: "#a3abb8", up: "#f08a5d", hedge: "#93c5fd", contribution: "#f08a5d", convexity: "#f3f4f6", limit: "#fb7185",
|
|
73
|
+
grid: "#252a31", axis: "#4b5563", text: "#f3f4f6", mutedText: "#a3abb8", axisText: "#a3abb8",
|
|
74
|
+
cardBackground: "#1b2027", tooltipBackground: "#f3f4f6", tooltipText: "#111418", focus: "#93c5fd", accent: "#f08a5d" }
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
var DEFAULT_OPTIONS = {
|
|
78
|
+
data: null, // required: { factors: [...], … }
|
|
79
|
+
view: "factors", // "factors" | "groups" | "contribution"
|
|
80
|
+
sort: "swing", // rank factors by "swing" (|up − down|) or by their "worst" result
|
|
81
|
+
top: 15, // rows shown before the rest are summed into one "Other" row (0 = all)
|
|
82
|
+
shockScale: 1, // multiply every shock size, e.g. 2 for twice the shock
|
|
83
|
+
whatIf: null, // scale positions by factor or group key, e.g. { "EUR 10Y": 0, "FX": 0.5 }
|
|
84
|
+
theme: "veyforma",
|
|
85
|
+
locale: undefined,
|
|
86
|
+
animate: true,
|
|
87
|
+
summary: true,
|
|
88
|
+
legend: true,
|
|
89
|
+
labels: null,
|
|
90
|
+
ariaLabel: undefined,
|
|
91
|
+
caption: true,
|
|
92
|
+
annotations: null, // notes, e.g. [{ factor: "EUR 10Y", text: "Hedge rolled in March" }] or { group, text }
|
|
93
|
+
onAnnotationsChange: null,
|
|
94
|
+
onItemClick: null, // function (detail, event): every figure for the factor or group clicked
|
|
95
|
+
exportRows: 20000, // the factor sheet keeps the largest swings above this many rows
|
|
96
|
+
toolbar: true
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
var DEFAULT_LABELS = {
|
|
100
|
+
factors: "Impact by risk factor", groups: "Impact by group", contribution: "Share of the combined move",
|
|
101
|
+
down: "Down shock", up: "Up shock", swing: "Swing", worst: "Worst result", convexity: "Convexity", linear: "Linear part",
|
|
102
|
+
limit: "Limit", largest: "Largest driver", worstShock: "Worst single shock", topShare: "Top {n} factors", combined: "Combined move",
|
|
103
|
+
contributionAdds: "Adds to the combined move", hedge: "Hedges (lowers it)", standalone: "Stand-alone", other: "Other {n} factors",
|
|
104
|
+
whatIf: "What-if", interaction: "Interaction", noData: "n/a"
|
|
105
|
+
};
|
|
106
|
+
/* ======================================================================
|
|
107
|
+
2. HELPERS
|
|
108
|
+
====================================================================== */
|
|
109
|
+
function assign(t) {
|
|
110
|
+
for (var i = 1; i < arguments.length; i++) {
|
|
111
|
+
var s = arguments[i];
|
|
112
|
+
if (s) for (var k in s) if (Object.prototype.hasOwnProperty.call(s, k)) t[k] = s[k];
|
|
113
|
+
}
|
|
114
|
+
return t;
|
|
115
|
+
}
|
|
116
|
+
var warned = {};
|
|
117
|
+
function warn(msg) { if (warned[msg]) return; warned[msg] = 1; if (root.console && console.warn) console.warn("VeyRiskTornado: " + msg); }
|
|
118
|
+
function fail(msg) { throw new Error("VeyRiskTornado: " + msg); }
|
|
119
|
+
function clamp(v, lo, hi) { return Math.min(hi, Math.max(lo, v)); }
|
|
120
|
+
function fill(t, map) { return String(t).replace(/\{(\w+)\}/g, function (m, k) { return map[k] != null ? map[k] : m; }); }
|
|
121
|
+
/** A name inside a sentence: "CET1 requirement" stays, "Pillar 1 minimum" becomes "pillar 1 minimum". */
|
|
122
|
+
function lower(t) { t = String(t); return /^[A-Z0-9]{2}/.test(t) ? t : t.charAt(0).toLowerCase() + t.slice(1); }
|
|
123
|
+
function num(v) { return typeof v === "number" ? v : v == null || v === "" ? NaN : +v; }
|
|
124
|
+
function svgEl(tag, attrs, parent) {
|
|
125
|
+
var n = document.createElementNS(SVG_NS, tag);
|
|
126
|
+
if (attrs) for (var k in attrs) if (attrs[k] != null) n.setAttribute(k, attrs[k]);
|
|
127
|
+
if (parent) parent.appendChild(n);
|
|
128
|
+
return n;
|
|
129
|
+
}
|
|
130
|
+
function htmlEl(tag, cls, parent) {
|
|
131
|
+
var n = document.createElement(tag);
|
|
132
|
+
if (cls) n.className = cls;
|
|
133
|
+
if (parent) parent.appendChild(n);
|
|
134
|
+
return n;
|
|
135
|
+
}
|
|
136
|
+
var measureCtx = null;
|
|
137
|
+
function textWidth(text, size, weight, family) {
|
|
138
|
+
if (!measureCtx) { var c = document.createElement("canvas"); measureCtx = c.getContext && c.getContext("2d"); }
|
|
139
|
+
if (!measureCtx) return String(text).length * size * 0.6;
|
|
140
|
+
measureCtx.font = (weight || 400) + " " + size + "px " + family;
|
|
141
|
+
return measureCtx.measureText(String(text)).width;
|
|
142
|
+
}
|
|
143
|
+
function fit(text, max, size, weight, family) {
|
|
144
|
+
text = String(text);
|
|
145
|
+
if (textWidth(text, size, weight, family) <= max) return text;
|
|
146
|
+
while (text.length > 2 && textWidth(text + "…", size, weight, family) > max) text = text.slice(0, -1);
|
|
147
|
+
return text.replace(/\s+$/, "") + "…";
|
|
148
|
+
}
|
|
149
|
+
function hexRgb(c) {
|
|
150
|
+
var m = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(String(c || "").trim());
|
|
151
|
+
if (!m) return null;
|
|
152
|
+
var h = m[1].length === 3 ? m[1].replace(/./g, "$&$&") : m[1], n = parseInt(h, 16);
|
|
153
|
+
return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
|
|
154
|
+
}
|
|
155
|
+
function luminance(rgb) {
|
|
156
|
+
var a = rgb.map(function (v) { v /= 255; return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4); });
|
|
157
|
+
return 0.2126 * a[0] + 0.7152 * a[1] + 0.0722 * a[2];
|
|
158
|
+
}
|
|
159
|
+
function contrast(a, b) {
|
|
160
|
+
var x = hexRgb(a), y = hexRgb(b);
|
|
161
|
+
if (!x || !y) return 21;
|
|
162
|
+
var l1 = luminance(x), l2 = luminance(y);
|
|
163
|
+
return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
|
|
164
|
+
}
|
|
165
|
+
function ensureContrast(col, bg, min) {
|
|
166
|
+
var c = hexRgb(col), b = hexRgb(bg);
|
|
167
|
+
if (!c || !b || contrast(col, bg) >= min) return col;
|
|
168
|
+
var dark = luminance(b) > 0.4, t = 0, out = col;
|
|
169
|
+
while (t <= 1 && contrast(out, bg) < min) {
|
|
170
|
+
t += 0.05;
|
|
171
|
+
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("");
|
|
172
|
+
}
|
|
173
|
+
return out;
|
|
174
|
+
}
|
|
175
|
+
function makeFormatters(data, locale) {
|
|
176
|
+
var decimals = data.decimals != null ? data.decimals : 0, rd = data.ratioDecimals != null ? data.ratioDecimals : 1;
|
|
177
|
+
var prefix = data.prefix || "", suffix = data.suffix || "", cache = {}, brackets = data.negatives === "brackets";
|
|
178
|
+
function nf(d) {
|
|
179
|
+
if (!cache[d]) cache[d] = new Intl.NumberFormat(locale || undefined, { minimumFractionDigits: d, maximumFractionDigits: d });
|
|
180
|
+
return cache[d];
|
|
181
|
+
}
|
|
182
|
+
function value(v, d) {
|
|
183
|
+
if (v == null || !isFinite(v)) return "–";
|
|
184
|
+
if (d == null) d = decimals;
|
|
185
|
+
var r = Number(v.toFixed(d)), body = prefix + nf(d).format(Math.abs(r)) + suffix;
|
|
186
|
+
if (r >= 0) return body;
|
|
187
|
+
return brackets ? "(" + body + ")" : "−" + body;
|
|
188
|
+
}
|
|
189
|
+
function signed(v, d) { var s = value(v, d); return v != null && Number(v.toFixed(d == null ? decimals : d)) > 0 ? "+" + s : s; }
|
|
190
|
+
function ratio(v, d) { return v == null || !isFinite(v) ? "–" : (v < 0 ? "−" : "") + nf(d == null ? rd : d).format(Math.abs(v) * 100) + "%"; }
|
|
191
|
+
function pp(v, d) {
|
|
192
|
+
if (v == null || !isFinite(v)) return "–";
|
|
193
|
+
var dd = d == null ? Math.max(rd, 1) : d, r = Number((v * 100).toFixed(dd));
|
|
194
|
+
return (r > 0 ? "+" : r < 0 ? "−" : "") + nf(dd).format(Math.abs(r)) + " pp";
|
|
195
|
+
}
|
|
196
|
+
function percent(v, d) { return v == null || !isFinite(v) ? "–" : nf(d == null ? 1 : d).format(v * 100) + "%"; }
|
|
197
|
+
return { value: value, signed: signed, ratio: ratio, pp: pp, percent: percent, nf: nf };
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
/* ======================================================================
|
|
202
|
+
3. CALCULATION
|
|
203
|
+
====================================================================== */
|
|
204
|
+
function finite(v, what) { var x = num(v); if (!isFinite(x)) fail(what + " must be a number."); return x; }
|
|
205
|
+
function corrOf(v, what) { var x = finite(v, what); if (x < -1 || x > 1) fail(what + " must be between −1 and 1."); return x; }
|
|
206
|
+
|
|
207
|
+
/** Reads the factors and works out each one's down and up impact for the shock scale and what-if. */
|
|
208
|
+
function readFactors(data, k, whatIf) {
|
|
209
|
+
var list = data.factors;
|
|
210
|
+
if (!Array.isArray(list) || !list.length) fail("data.factors must be a non-empty array of risk factors.");
|
|
211
|
+
var seen = {};
|
|
212
|
+
return list.map(function (x, i) {
|
|
213
|
+
if (!x || typeof x !== "object") fail("data.factors[" + i + "] is not an object.");
|
|
214
|
+
if (x.key == null && x.label == null) fail("data.factors[" + i + "] needs a key or a label.");
|
|
215
|
+
var key = String(x.key != null ? x.key : x.label), w = 'factor "' + key + '"';
|
|
216
|
+
if (seen[key]) fail(w + " is used twice.");
|
|
217
|
+
seen[key] = 1;
|
|
218
|
+
var group = x.group != null ? String(x.group) : "Other";
|
|
219
|
+
var sd = x.shockDown != null ? finite(x.shockDown, w + ": shockDown") : x.shock != null ? -Math.abs(finite(x.shock, w + ": shock")) : null;
|
|
220
|
+
var su = x.shockUp != null ? finite(x.shockUp, w + ": shockUp") : x.shock != null ? Math.abs(finite(x.shock, w + ": shock")) : null;
|
|
221
|
+
var down, up, source;
|
|
222
|
+
if (x.delta != null) {
|
|
223
|
+
// Taylor: impact = Δ·s + ½·Γ·s² at the (scaled) shock
|
|
224
|
+
var d = finite(x.delta, w + ": delta"), g = x.gamma != null ? finite(x.gamma, w + ": gamma") : 0;
|
|
225
|
+
if (sd == null || su == null) fail(w + ": delta needs shockDown and shockUp (or shock).");
|
|
226
|
+
var a = sd * k, b = su * k;
|
|
227
|
+
down = d * a + 0.5 * g * a * a; up = d * b + 0.5 * g * b * b; source = "taylor";
|
|
228
|
+
} else {
|
|
229
|
+
if (x.down == null || x.up == null) fail(w + " needs down and up impacts, or delta (and gamma) with a shock.");
|
|
230
|
+
var dn = finite(x.down, w + ": down"), u = finite(x.up, w + ": up");
|
|
231
|
+
if (k === 1) { down = dn; up = u; }
|
|
232
|
+
else { var L = (u - dn) / 2, C = (u + dn) / 2; down = -L * k + C * k * k; up = L * k + C * k * k; } // two-point fit, exact at k = 1
|
|
233
|
+
source = "revaluation";
|
|
234
|
+
}
|
|
235
|
+
var m = 1;
|
|
236
|
+
if (whatIf) {
|
|
237
|
+
if (whatIf[key] != null) m *= finite(whatIf[key], "whatIf." + key);
|
|
238
|
+
if (whatIf[group] != null && group !== key) m *= finite(whatIf[group], "whatIf." + group);
|
|
239
|
+
}
|
|
240
|
+
return { key: key, label: x.label != null ? String(x.label) : key, group: group, unit: x.unit != null ? String(x.unit) : "",
|
|
241
|
+
shockDown: sd == null ? null : sd * k, shockUp: su == null ? null : su * k, down: down * m, up: up * m, source: source, index: i };
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/** (ρL)_k for every factor: one pass for within/across correlations, a full product for a matrix. */
|
|
246
|
+
function corrTimes(fs, corr, Lv) {
|
|
247
|
+
var n = fs.length, out = new Array(n), i, j;
|
|
248
|
+
if (corr && corr.matrix) {
|
|
249
|
+
var M = corr.matrix;
|
|
250
|
+
for (i = 0; i < n; i++) { var s = 0, row = M[i]; for (j = 0; j < n; j++) s += (i === j ? 1 : row[j]) * Lv[j]; out[i] = s; }
|
|
251
|
+
return out;
|
|
252
|
+
}
|
|
253
|
+
var wi = corr ? corr.within : 0, ac = corr ? corr.across : 0, G = {}, T = 0;
|
|
254
|
+
for (i = 0; i < n; i++) { G[fs[i].group] = (G[fs[i].group] || 0) + Lv[i]; T += Lv[i]; }
|
|
255
|
+
for (i = 0; i < n; i++) { var gs = G[fs[i].group]; out[i] = Lv[i] + wi * (gs - Lv[i]) + ac * (T - gs); }
|
|
256
|
+
return out;
|
|
257
|
+
}
|
|
258
|
+
function readCorr(data, n) {
|
|
259
|
+
var c = data.correlation;
|
|
260
|
+
if (c == null) return null;
|
|
261
|
+
if (typeof c !== "object") fail("data.correlation must be { within, across } or { matrix }.");
|
|
262
|
+
if (c.matrix) {
|
|
263
|
+
var M = c.matrix;
|
|
264
|
+
if (!Array.isArray(M) || M.length !== n || M.some(function (r) { return !Array.isArray(r) || r.length !== n; })) fail("data.correlation.matrix must be square with one row per factor.");
|
|
265
|
+
M.forEach(function (r, i) { r.forEach(function (v, j) { corrOf(v, "data.correlation.matrix[" + i + "][" + j + "]"); }); });
|
|
266
|
+
return { matrix: M };
|
|
267
|
+
}
|
|
268
|
+
return { within: c.within != null ? corrOf(c.within, "data.correlation.within") : 0, across: c.across != null ? corrOf(c.across, "data.correlation.across") : 0 };
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** Every figure. opts: { shockScale, whatIf, sort }. */
|
|
272
|
+
function compute(data, opts) {
|
|
273
|
+
opts = opts || {};
|
|
274
|
+
if (!data || typeof data !== "object") fail("data is required.");
|
|
275
|
+
var k = opts.shockScale != null ? finite(opts.shockScale, "shockScale") : 1;
|
|
276
|
+
if (!(k > 0)) fail("shockScale must be more than 0.");
|
|
277
|
+
var wi = opts.whatIf && Object.keys(opts.whatIf).length ? opts.whatIf : null;
|
|
278
|
+
var fs = readFactors(data, k, wi), n = fs.length;
|
|
279
|
+
if (wi) Object.keys(wi).forEach(function (key) { if (!fs.some(function (f) { return f.key === key || f.group === key; })) warn('whatIf: there is no factor or group "' + key + '", so it changes nothing.'); });
|
|
280
|
+
var hib = data.higherIsBetter !== false;
|
|
281
|
+
var bad = function (v) { return hib ? -v : v; };
|
|
282
|
+
var limit = data.limit != null ? Math.abs(finite(data.limit, "data.limit")) : null;
|
|
283
|
+
var corr = readCorr(data, n);
|
|
284
|
+
var Lv = fs.map(function (f) { return (f.up - f.down) / 2; });
|
|
285
|
+
var RL = corrTimes(fs, corr, Lv), q = 0, i;
|
|
286
|
+
for (i = 0; i < n; i++) q += Lv[i] * RL[i];
|
|
287
|
+
var sigma = Math.sqrt(Math.max(0, q)), totalSwing = 0, sumDown = 0, sumUp = 0, standalone = 0;
|
|
288
|
+
fs.forEach(function (f, j) {
|
|
289
|
+
f.swing = Math.abs(f.up - f.down);
|
|
290
|
+
f.linear = Lv[j];
|
|
291
|
+
f.convexity = (f.up + f.down) / 2;
|
|
292
|
+
f.asymmetry = Math.abs(f.linear) + Math.abs(f.convexity) > 0 ? Math.abs(f.convexity) / (Math.abs(f.linear) + Math.abs(f.convexity)) : 0;
|
|
293
|
+
f.worst = bad(f.down) >= bad(f.up) ? "down" : "up";
|
|
294
|
+
f.worstValue = f[f.worst];
|
|
295
|
+
f.best = f.worst === "down" ? "up" : "down";
|
|
296
|
+
f.breach = limit != null && bad(f.worstValue) > limit + 1e-12 * Math.max(1, limit);
|
|
297
|
+
f.standalone = Math.abs(Lv[j]);
|
|
298
|
+
f.contribution = sigma > 0 ? Lv[j] * RL[j] / sigma : 0;
|
|
299
|
+
totalSwing += f.swing; sumDown += f.down; sumUp += f.up; standalone += f.standalone;
|
|
300
|
+
});
|
|
301
|
+
var order = fs.slice().sort(opts.sort === "worst"
|
|
302
|
+
? function (a, b) { return bad(b.worstValue) - bad(a.worstValue) || a.index - b.index; }
|
|
303
|
+
: function (a, b) { return b.swing - a.swing || a.index - b.index; });
|
|
304
|
+
var cum = 0;
|
|
305
|
+
order.forEach(function (f, r) { f.rank = r + 1; f.share = totalSwing > 0 ? f.swing / totalSwing : 0; cum += f.share; f.cumShare = cum; });
|
|
306
|
+
// Groups, in the order they first appear
|
|
307
|
+
var gm = {}, groups = [];
|
|
308
|
+
fs.forEach(function (f, j) {
|
|
309
|
+
var g = gm[f.group];
|
|
310
|
+
if (!g) { g = gm[f.group] = { key: f.group, label: f.group, factors: [], idx: [], down: 0, up: 0, contribution: 0, standaloneSum: 0 }; groups.push(g); }
|
|
311
|
+
g.factors.push(f.key); g.idx.push(j); g.down += f.down; g.up += f.up; g.contribution += f.contribution; g.standaloneSum += f.standalone;
|
|
312
|
+
});
|
|
313
|
+
groups.forEach(function (g) {
|
|
314
|
+
g.swing = Math.abs(g.up - g.down); g.linear = (g.up - g.down) / 2; g.convexity = (g.up + g.down) / 2;
|
|
315
|
+
g.worst = bad(g.down) >= bad(g.up) ? "down" : "up"; g.worstValue = g[g.worst];
|
|
316
|
+
g.breach = limit != null && bad(g.worstValue) > limit + 1e-12 * Math.max(1, limit);
|
|
317
|
+
g.share = totalSwing > 0 ? g.swing / totalSwing : 0;
|
|
318
|
+
// the group's own combined move, with the correlations between its factors
|
|
319
|
+
var sub = g.idx.map(function (j) { return fs[j]; }), subL = g.idx.map(function (j) { return Lv[j]; }), sc = corr && corr.matrix ? { matrix: g.idx.map(function (a) { return g.idx.map(function (b) { return corr.matrix[a][b]; }); }) } : corr;
|
|
320
|
+
var r2 = corrTimes(sub, sc, subL), qq = 0; for (var t = 0; t < subL.length; t++) qq += subL[t] * r2[t];
|
|
321
|
+
g.standalone = Math.sqrt(Math.max(0, qq));
|
|
322
|
+
delete g.idx;
|
|
323
|
+
});
|
|
324
|
+
var topN = n >= 10 ? 5 : Math.max(1, Math.ceil(n / 2)); // short lists: about half of them
|
|
325
|
+
var top5 = order.slice(0, topN).reduce(function (a, f) { return a + f.share; }, 0);
|
|
326
|
+
var res = { factors: fs, order: order, groups: groups, higherIsBetter: hib, limit: limit, base: data.base != null ? finite(data.base, "data.base") : null,
|
|
327
|
+
totalSwing: totalSwing, sumDown: sumDown, sumUp: sumUp, sigma: sigma, standalone: standalone, diversification: standalone - sigma,
|
|
328
|
+
correlated: !!corr, topN: topN, topShare: top5, breaches: fs.filter(function (f) { return f.breach; }).length, shockScale: k, whatIf: wi };
|
|
329
|
+
res.worstFactor = fs.slice().sort(function (a, b) { return bad(b.worstValue) - bad(a.worstValue) || a.index - b.index; })[0];
|
|
330
|
+
// Joint revaluation: all factors shocked together, only valid at the base shocks and positions
|
|
331
|
+
if (data.joint && (data.joint.down != null || data.joint.up != null)) {
|
|
332
|
+
if (k === 1 && !wi) {
|
|
333
|
+
res.joint = { down: data.joint.down != null ? finite(data.joint.down, "data.joint.down") : null, up: data.joint.up != null ? finite(data.joint.up, "data.joint.up") : null };
|
|
334
|
+
res.interaction = { down: res.joint.down != null ? res.joint.down - sumDown : null, up: res.joint.up != null ? res.joint.up - sumUp : null };
|
|
335
|
+
} else res.jointHidden = true;
|
|
336
|
+
}
|
|
337
|
+
if (wi) {
|
|
338
|
+
var b0 = compute(data, { shockScale: k, sort: opts.sort });
|
|
339
|
+
res.baseline = { totalSwing: b0.totalSwing, sigma: b0.sigma, worstValue: b0.worstFactor.worstValue, worstFactor: b0.worstFactor.key };
|
|
340
|
+
}
|
|
341
|
+
return res;
|
|
342
|
+
}
|
|
343
|
+
/* ======================================================================
|
|
344
|
+
4. CHART INSTANCE
|
|
345
|
+
====================================================================== */
|
|
346
|
+
function injectStyles() {
|
|
347
|
+
if (document.getElementById("vtr-styles")) return;
|
|
348
|
+
var css =
|
|
349
|
+
".vtr{position:relative;color:var(--vtr-text);background:var(--vtr-bg);font-family:var(--vtr-font);line-height:1.4}" +
|
|
350
|
+
".vtr.vtr-filled{padding:14px 14px 8px;border-radius:10px}" +
|
|
351
|
+
".vtr-summary{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:8px;margin:0 0 10px}" +
|
|
352
|
+
".vtr-stat{background:var(--vtr-card);border-radius:8px;padding:9px 12px;min-width:0}" +
|
|
353
|
+
".vtr-stat .k{font-size:11px;letter-spacing:.04em;text-transform:uppercase;color:var(--vtr-card-muted);font-weight:600;overflow-wrap:anywhere;hyphens:auto}" +
|
|
354
|
+
".vtr-stat .v{font-size:19px;font-weight:700;font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}" +
|
|
355
|
+
".vtr-stat .n{font-size:12px;color:var(--vtr-card-muted)}" +
|
|
356
|
+
".vtr-stat .v.vtr-wrap{white-space:normal;overflow-wrap:anywhere;line-height:1.2;font-size:17px}" +
|
|
357
|
+
".vtr-scope{font-size:12px;color:var(--vtr-muted);margin:0 0 4px}" +
|
|
358
|
+
".vtr-legend{display:flex;flex-wrap:wrap;gap:4px 14px;font-size:12px;margin:0 0 6px;color:var(--vtr-text)}" +
|
|
359
|
+
".vtr-legend span{display:inline-flex;align-items:center;gap:6px}" +
|
|
360
|
+
".vtr-legend i{display:inline-block;width:12px;height:12px;border-radius:3px}" +
|
|
361
|
+
".vtr-legend i.vtr-tick{width:3px;height:14px;border-radius:1px}" +
|
|
362
|
+
".vtr-legend i.vtr-ring{background:transparent!important;border:2px solid;border-radius:2px;width:9px;height:9px;transform:rotate(45deg)}" +
|
|
363
|
+
".vtr-plot{display:block;width:100%;height:auto;overflow:visible;outline:none}" +
|
|
364
|
+
".vtr-plot:focus-visible{outline:2px solid var(--vtr-focus);outline-offset:4px;border-radius:4px}" +
|
|
365
|
+
".vtr-animate .vtr-grow{animation:vtr-fade .45s ease both}" +
|
|
366
|
+
"@keyframes vtr-fade{from{opacity:0}to{opacity:1}}" +
|
|
367
|
+
"@media (prefers-reduced-motion:reduce){.vtr-animate .vtr-grow{animation:none}}" +
|
|
368
|
+
".vtr-tip{position:absolute;left:0;top:0;pointer-events:none;background:var(--vtr-tip-bg);color:var(--vtr-tip-text);" +
|
|
369
|
+
"font-size:12px;line-height:1.45;padding:8px 10px;border-radius:8px;opacity:0;transform:translateY(4px);" +
|
|
370
|
+
"transition:opacity .12s,transform .12s;white-space:nowrap;z-index:5;font-variant-numeric:tabular-nums}" +
|
|
371
|
+
".vtr-tip.vtr-on{opacity:1;transform:none}.vtr-tip b{font-weight:600}" +
|
|
372
|
+
".vtr-table{border-collapse:collapse;font-size:12px;font-variant-numeric:tabular-nums;margin:0 0 14px;min-width:100%}" +
|
|
373
|
+
".vtr-table caption{text-align:left;font-weight:700;padding:0 0 6px}" +
|
|
374
|
+
".vtr-table th,.vtr-table td{padding:5px 8px;border-bottom:1px solid rgba(127,127,127,.25);text-align:right;white-space:nowrap}" +
|
|
375
|
+
".vtr-table th:first-child,.vtr-table td:first-child{text-align:left}" +
|
|
376
|
+
".vtr-table tr.vtr-breach td{color:var(--vtr-hedge);font-weight:600}" +
|
|
377
|
+
"@media (max-width:420px){.vtr-summary{grid-template-columns:repeat(auto-fit,minmax(118px,1fr))}.vtr-stat{padding:8px 10px}.vtr-stat .v{font-size:17px}}";
|
|
378
|
+
var s = htmlEl("style");
|
|
379
|
+
s.id = "vtr-styles";
|
|
380
|
+
s.textContent = css;
|
|
381
|
+
(document.head || document.documentElement).appendChild(s);
|
|
382
|
+
}
|
|
383
|
+
function resolveTrTheme(theme) {
|
|
384
|
+
var t;
|
|
385
|
+
if (theme == null || theme === "") theme = "veyforma";
|
|
386
|
+
if (typeof theme === "string") {
|
|
387
|
+
if (!THEMES.hasOwnProperty(theme)) { warn('Unknown theme "' + theme + '". The "veyforma" theme is used instead.'); theme = "veyforma"; }
|
|
388
|
+
t = assign({}, BASE_THEME, THEMES[theme]);
|
|
389
|
+
} else if (typeof theme === "object") {
|
|
390
|
+
t = assign(theme["extends"] ? resolveTrTheme(theme["extends"]) : assign({}, BASE_THEME), theme);
|
|
391
|
+
delete t["extends"];
|
|
392
|
+
} else { warn("The theme option must be a theme name or an object."); t = assign({}, BASE_THEME); }
|
|
393
|
+
var bg = /^#/.test(t.background) ? t.background : "#ffffff", card = /^#/.test(t.cardBackground) ? t.cardBackground : bg;
|
|
394
|
+
["axisText", "mutedText"].forEach(function (k) { t[k] = ensureContrast(t[k], bg, 4.5); });
|
|
395
|
+
t.cardMuted = ensureContrast(t.mutedText, card, 4.5);
|
|
396
|
+
t.hedgeText = ensureContrast(ensureContrast(t.hedge, bg, 4.5), card, 4.5);
|
|
397
|
+
t.limitText = ensureContrast(ensureContrast(t.limit, bg, 4.5), card, 4.5);
|
|
398
|
+
t.accentText = ensureContrast(t.accent, bg, 4.5);
|
|
399
|
+
return t;
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
function Chart(target, options) {
|
|
403
|
+
var container = typeof target === "string" ? document.querySelector(target) : target;
|
|
404
|
+
if (!container || container.nodeType !== 1) fail("container not found (" + target + ").");
|
|
405
|
+
if (!options || !options.data) fail("options.data is required.");
|
|
406
|
+
injectStyles();
|
|
407
|
+
this.id = ++instanceCount;
|
|
408
|
+
this.container = container;
|
|
409
|
+
this.options = assign({}, DEFAULT_OPTIONS, options);
|
|
410
|
+
this.element = htmlEl("div", "vtr");
|
|
411
|
+
this.element.setAttribute("role", "figure");
|
|
412
|
+
this.summaryEl = htmlEl("div", "vtr-summary", this.element);
|
|
413
|
+
this.scopeEl = htmlEl("p", "vtr-scope", this.element);
|
|
414
|
+
this.legendEl = htmlEl("div", "vtr-legend", this.element);
|
|
415
|
+
this.plotHost = htmlEl("div", "vtr-plot-host", this.element);
|
|
416
|
+
this.tipEl = htmlEl("div", "vtr-tip", this.element);
|
|
417
|
+
this.tipEl.setAttribute("role", "tooltip");
|
|
418
|
+
container.appendChild(this.element);
|
|
419
|
+
this._animateNext = !!this.options.animate;
|
|
420
|
+
this._lastWidth = 0;
|
|
421
|
+
this._active = -1;
|
|
422
|
+
var self = this;
|
|
423
|
+
if (root.ResizeObserver) {
|
|
424
|
+
this._observer = new root.ResizeObserver(function () {
|
|
425
|
+
var w = Math.round(self.element.clientWidth);
|
|
426
|
+
if (w && Math.abs(w - self._lastWidth) > 1) self.redraw();
|
|
427
|
+
});
|
|
428
|
+
this._observer.observe(this.element);
|
|
429
|
+
} else {
|
|
430
|
+
this._onResize = function () { self.redraw(); };
|
|
431
|
+
root.addEventListener("resize", this._onResize);
|
|
432
|
+
}
|
|
433
|
+
this._onDocTap = function (e) { if (!self.element.contains(e.target)) self._hideTip(); };
|
|
434
|
+
document.addEventListener("pointerdown", this._onDocTap);
|
|
435
|
+
this.redraw();
|
|
436
|
+
if (this.options.toolbar !== false && root.VeyformaToolkit) this.toolkit = root.VeyformaToolkit.attach(this, this.options.toolbar);
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
Chart.prototype.update = function (partial) {
|
|
440
|
+
if (!partial) return this;
|
|
441
|
+
if (partial.data && partial.data !== this.options.data && this.options.animate) this._animateNext = true;
|
|
442
|
+
if (partial.view && partial.view !== this.options.view && this.options.animate) this._animateNext = true;
|
|
443
|
+
assign(this.options, partial);
|
|
444
|
+
return this.redraw();
|
|
445
|
+
};
|
|
446
|
+
Chart.prototype.setData = function (data) { this._res = null; return this.update({ data: data }); };
|
|
447
|
+
Chart.prototype.setView = function (view) { return this.update({ view: view }); };
|
|
448
|
+
Chart.prototype.setTheme = function (theme) { return this.update({ theme: theme }); };
|
|
449
|
+
Chart.prototype.getTheme = function () { return resolveTrTheme(this.options.theme); };
|
|
450
|
+
Chart.prototype._opts = function () { return { shockScale: this.options.shockScale, whatIf: this.options.whatIf, sort: this.options.sort }; };
|
|
451
|
+
Chart.prototype.getResult = function () { return compute(this.options.data, this._opts()); };
|
|
452
|
+
Chart.prototype.getFactor = function (key) { return this.getResult().factors.filter(function (f) { return f.key === String(key); })[0] || null; };
|
|
453
|
+
Chart.prototype.setWhatIf = function (whatIf) { return this.update({ whatIf: whatIf }); };
|
|
454
|
+
Chart.prototype.setShockScale = function (k) { return this.update({ shockScale: k }); };
|
|
455
|
+
Chart.prototype._labels = function () { return assign({}, DEFAULT_LABELS, this.options.labels); };
|
|
456
|
+
Chart.prototype.destroy = function () {
|
|
457
|
+
if (this.toolkit && this.toolkit.destroy) this.toolkit.destroy();
|
|
458
|
+
if (this._observer) this._observer.disconnect();
|
|
459
|
+
if (this._onResize) root.removeEventListener("resize", this._onResize);
|
|
460
|
+
document.removeEventListener("pointerdown", this._onDocTap);
|
|
461
|
+
if (this.element.parentNode) this.element.parentNode.removeChild(this.element);
|
|
462
|
+
};
|
|
463
|
+
Chart.prototype._hideTip = function () { this.tipEl.classList.remove("vtr-on"); if (this._hlEl) this._hlEl.setAttribute("opacity", 0); };
|
|
464
|
+
Chart.prototype._placeTip = function (lines, rect, evt) {
|
|
465
|
+
var tip = this.tipEl;
|
|
466
|
+
tip.textContent = "";
|
|
467
|
+
lines.forEach(function (ln, i) {
|
|
468
|
+
if (i) tip.appendChild(document.createElement("br"));
|
|
469
|
+
var node = i === 0 ? document.createElement("b") : document.createElement("span");
|
|
470
|
+
node.textContent = ln;
|
|
471
|
+
tip.appendChild(node);
|
|
472
|
+
});
|
|
473
|
+
var box = this.element.getBoundingClientRect();
|
|
474
|
+
var px = evt && evt.clientX ? evt.clientX : rect.left + rect.width / 2;
|
|
475
|
+
var py = evt && evt.clientY ? evt.clientY : rect.top + 10;
|
|
476
|
+
tip.classList.add("vtr-on");
|
|
477
|
+
var tw = tip.offsetWidth, th = tip.offsetHeight;
|
|
478
|
+
tip.style.left = clamp(px - box.left - tw / 2, 4, Math.max(4, box.width - tw - 4)) + "px";
|
|
479
|
+
var top = py - box.top - th - 14;
|
|
480
|
+
if (top < 0) top = py - box.top + 18;
|
|
481
|
+
tip.style.top = top + "px";
|
|
482
|
+
};
|
|
483
|
+
/** A "nice" axis from lo to hi with about n ticks. */
|
|
484
|
+
function niceTicks(lo, hi, n) {
|
|
485
|
+
if (!(hi > lo)) { hi = lo + 1; }
|
|
486
|
+
var span = hi - lo, step = Math.pow(10, Math.floor(Math.log(span / n) / Math.LN10)), err = span / n / step;
|
|
487
|
+
if (err >= 7.5) step *= 10; else if (err >= 3.5) step *= 5; else if (err >= 1.5) step *= 2;
|
|
488
|
+
var a = Math.floor(lo / step + 1e-9) * step, b = Math.ceil(hi / step - 1e-9) * step, out = [];
|
|
489
|
+
for (var v = a; v <= b + step / 2; v += step) out.push(Math.round(v / step) * step);
|
|
490
|
+
return { lo: a, hi: b, ticks: out, step: step };
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
function label(g, x, y, text, attrs) {
|
|
494
|
+
var t = svgEl("text", assign({ x: x, y: y }, attrs || {}), g);
|
|
495
|
+
t.textContent = text;
|
|
496
|
+
return t;
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
Chart.prototype._bindInteraction = function (svg, W, H, theme, L, f) {
|
|
500
|
+
var self = this, items = this._items, o = this.options;
|
|
501
|
+
function idxAt(evt) {
|
|
502
|
+
var r = svg.getBoundingClientRect(), x = (evt.clientX - r.left) * (W / r.width), y = (evt.clientY - r.top) * (H / r.height);
|
|
503
|
+
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; }
|
|
504
|
+
return -1;
|
|
505
|
+
}
|
|
506
|
+
function show(i, evt) {
|
|
507
|
+
if (i < 0) { self._hideTip(); return; }
|
|
508
|
+
self._active = i;
|
|
509
|
+
var it = items[i], hl = self._hlEl;
|
|
510
|
+
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);
|
|
511
|
+
var r = svg.getBoundingClientRect(), sx = r.width / W;
|
|
512
|
+
var rect = { left: r.left + it.px * sx, top: r.top + it.py * (r.height / H), width: 0, height: 0 };
|
|
513
|
+
self._placeTip(self._tipLines(it), rect, evt && evt.clientX ? evt : null);
|
|
514
|
+
}
|
|
515
|
+
svg.addEventListener("pointermove", function (e) { show(idxAt(e), e); });
|
|
516
|
+
svg.addEventListener("pointerleave", function () { self._hideTip(); });
|
|
517
|
+
svg.addEventListener("click", function (e) {
|
|
518
|
+
var i = idxAt(e);
|
|
519
|
+
if (i >= 0 && typeof o.onItemClick === "function") o.onItemClick(self._detail(items[i]), e);
|
|
520
|
+
});
|
|
521
|
+
svg.addEventListener("keydown", function (e) {
|
|
522
|
+
var i = self._active;
|
|
523
|
+
if (e.key === "ArrowRight" || e.key === "ArrowDown") i = Math.min(items.length - 1, i + 1);
|
|
524
|
+
else if (e.key === "ArrowLeft" || e.key === "ArrowUp") i = Math.max(0, i < 0 ? 0 : i - 1);
|
|
525
|
+
else if (e.key === "Home") i = 0;
|
|
526
|
+
else if (e.key === "End") i = items.length - 1;
|
|
527
|
+
else if (e.key === "Escape") { self._hideTip(); return; }
|
|
528
|
+
else if ((e.key === "Enter" || e.key === " ") && i >= 0) {
|
|
529
|
+
if (typeof o.onItemClick === "function") o.onItemClick(self._detail(items[i]), e);
|
|
530
|
+
e.preventDefault(); return;
|
|
531
|
+
} else return;
|
|
532
|
+
e.preventDefault();
|
|
533
|
+
show(i, null);
|
|
534
|
+
});
|
|
535
|
+
svg.addEventListener("blur", function () { self._hideTip(); });
|
|
536
|
+
};
|
|
537
|
+
|
|
538
|
+
Chart.prototype.createTable = function () {
|
|
539
|
+
var ex = this.getExportData(), wrap = htmlEl("div", "vtr-tables");
|
|
540
|
+
ex.sheets.forEach(function (sh) {
|
|
541
|
+
if (sh.name === "Notes") return;
|
|
542
|
+
var tb = htmlEl("table", "vtr-table", wrap);
|
|
543
|
+
htmlEl("caption", null, tb).textContent = sh.name;
|
|
544
|
+
var hr = htmlEl("tr", null, htmlEl("thead", null, tb));
|
|
545
|
+
sh.columns.forEach(function (c) { var th = htmlEl("th", null, hr); th.scope = "col"; th.textContent = c.label; });
|
|
546
|
+
var body = htmlEl("tbody", null, tb);
|
|
547
|
+
sh.text.forEach(function (r, i) {
|
|
548
|
+
var tr = htmlEl("tr", sh.flag && sh.flag[i] ? "vtr-breach" : null, body);
|
|
549
|
+
r.forEach(function (v, j) { var td = htmlEl(j ? "td" : "th", null, tr); if (!j) td.scope = "row"; td.textContent = v; });
|
|
550
|
+
});
|
|
551
|
+
});
|
|
552
|
+
return wrap;
|
|
553
|
+
};
|
|
554
|
+
|
|
555
|
+
function shockText(v, unit, locale) {
|
|
556
|
+
if (v == null || !isFinite(v)) return "";
|
|
557
|
+
var body = Number(Math.abs(v).toFixed(4)).toLocaleString(locale || undefined, { maximumFractionDigits: 4 });
|
|
558
|
+
return (v > 0 ? "+" : v < 0 ? "−" : "") + body + (unit ? (unit === "%" ? "%" : " " + unit) : "");
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
Chart.prototype.redraw = function () {
|
|
562
|
+
var o = this.options, data = o.data, L = this._labels();
|
|
563
|
+
var res = this._res = compute(data, this._opts());
|
|
564
|
+
var theme = resolveTrTheme(o.theme), f = makeFormatters(data, o.locale), el = this.element, st = el.style;
|
|
565
|
+
var family = theme.fontFamily === "inherit" ? (root.getComputedStyle ? root.getComputedStyle(this.container).fontFamily : "sans-serif") : theme.fontFamily;
|
|
566
|
+
var filled = theme.background && theme.background !== "transparent", bg = filled ? theme.background : "#ffffff";
|
|
567
|
+
st.setProperty("--vtr-text", theme.text); st.setProperty("--vtr-muted", theme.mutedText);
|
|
568
|
+
st.setProperty("--vtr-bg", filled ? theme.background : "transparent"); st.setProperty("--vtr-font", family);
|
|
569
|
+
st.setProperty("--vtr-card", theme.cardBackground); st.setProperty("--vtr-card-muted", theme.cardMuted);
|
|
570
|
+
st.setProperty("--vtr-tip-bg", theme.tooltipBackground); st.setProperty("--vtr-tip-text", theme.tooltipText);
|
|
571
|
+
st.setProperty("--vtr-focus", theme.focus); st.setProperty("--vtr-hedge", theme.limitText);
|
|
572
|
+
el.classList.toggle("vtr-filled", !!filled);
|
|
573
|
+
el.setAttribute("aria-label", o.ariaLabel || data.title || "Risk-factor tornado");
|
|
574
|
+
var view = o.view;
|
|
575
|
+
if (["factors", "groups", "contribution"].indexOf(view) < 0) { warn('Unknown view "' + view + '". The factor view is shown instead.'); view = "factors"; }
|
|
576
|
+
if (o.sort !== "swing" && o.sort !== "worst") warn('Unknown sort "' + o.sort + '". Factors are ranked by swing instead.');
|
|
577
|
+
this._view = view;
|
|
578
|
+
this._renderSummary(res, f, L);
|
|
579
|
+
var scope = [L[view], o.shockScale != null && +o.shockScale !== 1 ? "shocks ×" + (+o.shockScale) : null, data.unit || null, res.whatIf ? L.whatIf + " applied" : null].filter(Boolean).join(" · ");
|
|
580
|
+
this.scopeEl.textContent = scope;
|
|
581
|
+
this._renderLegend(view, theme, L, res);
|
|
582
|
+
var W = Math.max(280, Math.round(this.plotHost.clientWidth || el.clientWidth || 720));
|
|
583
|
+
this._lastWidth = Math.round(el.clientWidth);
|
|
584
|
+
var fs = theme.fontSize || 12;
|
|
585
|
+
this.plotHost.textContent = "";
|
|
586
|
+
var svg = svgEl("svg", { "class": "vtr-plot", role: "img", tabindex: 0, "font-family": family }, this.plotHost);
|
|
587
|
+
svg.style.fontSize = fs + "px";
|
|
588
|
+
var animate = this._animateNext && o.animate; this._animateNext = false;
|
|
589
|
+
if (animate) svg.classList.add("vtr-animate");
|
|
590
|
+
var ctx = { svg: svg, W: W, fs: fs, theme: theme, f: f, L: L, family: family, bg: bg, res: res, items: [], points: {} };
|
|
591
|
+
var H = view === "contribution" ? this._drawContribution(ctx) : this._drawRows(ctx, view);
|
|
592
|
+
svg.setAttribute("viewBox", "0 0 " + W + " " + H);
|
|
593
|
+
svg.setAttribute("width", W); svg.setAttribute("height", H);
|
|
594
|
+
svg.setAttribute("aria-label", (o.ariaLabel || data.title || "Risk-factor tornado") + ". " + this.describe());
|
|
595
|
+
this._items = ctx.items; this._points = ctx.points;
|
|
596
|
+
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);
|
|
597
|
+
svg.insertBefore(this._hlEl, svg.firstChild);
|
|
598
|
+
this._bindInteraction(svg, W, H, theme, L, f);
|
|
599
|
+
return this;
|
|
600
|
+
};
|
|
601
|
+
|
|
602
|
+
Chart.prototype._shockNames = function () {
|
|
603
|
+
var L = this._labels(), s = this.options.data.shockLabels || {};
|
|
604
|
+
return { down: s.down || L.down, up: s.up || L.up };
|
|
605
|
+
};
|
|
606
|
+
|
|
607
|
+
Chart.prototype._renderSummary = function (res, f, L) {
|
|
608
|
+
var box = this.summaryEl, o = this.options;
|
|
609
|
+
box.textContent = "";
|
|
610
|
+
box.style.display = o.summary === false ? "none" : "";
|
|
611
|
+
if (o.summary === false) return;
|
|
612
|
+
function stat(k, v, n, wrap) {
|
|
613
|
+
var s = htmlEl("div", "vtr-stat", box);
|
|
614
|
+
htmlEl("div", "k", s).textContent = k;
|
|
615
|
+
htmlEl("div", wrap ? "v vtr-wrap" : "v", s).textContent = v;
|
|
616
|
+
if (n) htmlEl("div", "n", s).textContent = n;
|
|
617
|
+
}
|
|
618
|
+
var SN = this._shockNames(), top = res.order[0], w = res.worstFactor;
|
|
619
|
+
stat(L.largest, top.label, L.swing.toLowerCase() + " " + f.value(top.swing) + " · " + f.percent(top.share, 0) + " of the total", true);
|
|
620
|
+
stat(L.worstShock, f.signed(w.worstValue), w.label + ", " + SN[w.worst].toLowerCase() + (res.limit != null ? (res.breaches ? " · " + res.breaches + " beyond the limit" : " · within the limit") : "") +
|
|
621
|
+
(res.baseline ? " · was " + f.signed(res.baseline.worstValue) : ""));
|
|
622
|
+
stat(fill(L.topShare, { n: res.topN }), f.percent(res.topShare, 0), "of the total swing across " + res.factors.length + " factors");
|
|
623
|
+
stat(L.combined, "±" + f.value(res.sigma), res.baseline ? L.whatIf + ": was ±" + f.value(res.baseline.sigma)
|
|
624
|
+
: res.correlated ? (res.standalone > 0 ? f.percent(res.diversification / res.standalone, 0) + " below the sum of stand-alone moves" : "") : "factors treated as independent");
|
|
625
|
+
Array.prototype.forEach.call(box.querySelectorAll(".vtr-stat .v"), function (v) {
|
|
626
|
+
v.style.fontSize = "";
|
|
627
|
+
var size = parseFloat(root.getComputedStyle ? root.getComputedStyle(v).fontSize : 19) || 19;
|
|
628
|
+
while (v.scrollWidth > v.clientWidth && size > 12) { size -= 1; v.style.fontSize = size + "px"; }
|
|
629
|
+
});
|
|
630
|
+
};
|
|
631
|
+
|
|
632
|
+
Chart.prototype._renderLegend = function (view, theme, L, res) {
|
|
633
|
+
var box = this.legendEl, SN = this._shockNames();
|
|
634
|
+
box.textContent = "";
|
|
635
|
+
box.style.display = this.options.legend === false ? "none" : "";
|
|
636
|
+
function item(colour, text, cls) {
|
|
637
|
+
var s = htmlEl("span", null, box), i = htmlEl("i", cls || null, s);
|
|
638
|
+
if (cls === "vtr-ring") i.style.borderColor = colour; else i.style.background = colour;
|
|
639
|
+
s.appendChild(document.createTextNode(text));
|
|
640
|
+
}
|
|
641
|
+
if (view === "contribution") { item(theme.contribution, L.contributionAdds); item(theme.hedge, L.hedge); item(theme.convexity, L.standalone, "vtr-ring"); return; }
|
|
642
|
+
item(theme.down, SN.down); item(theme.up, SN.up);
|
|
643
|
+
if (res.factors.some(function (x) { return x.asymmetry >= 0.1; })) item(theme.convexity, L.convexity + " (midpoint)", "vtr-ring");
|
|
644
|
+
if (res.limit != null) item(theme.limit, L.limit, "vtr-tick");
|
|
645
|
+
};
|
|
646
|
+
|
|
647
|
+
function rowLayout(c, names) {
|
|
648
|
+
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);
|
|
649
|
+
var narrow = c.W - nameW < 260;
|
|
650
|
+
return { nameW: narrow ? 0 : nameW, narrow: narrow };
|
|
651
|
+
}
|
|
652
|
+
/** Axis ticks along the top, thinned so no two labels touch. */
|
|
653
|
+
function topTicks(c, g, nt, xs, y, x0, x1, gridTop, gridBottom) {
|
|
654
|
+
var theme = c.theme, fs = c.fs, fam = c.family, W = c.W, f = c.f, lastRight = -Infinity;
|
|
655
|
+
var tickW = Math.max.apply(null, nt.ticks.map(function (t) { return textWidth(f.value(t), fs - 1, 400, fam); }));
|
|
656
|
+
var every = Math.max(1, Math.ceil((tickW + 10) / ((x1 - x0) / Math.max(1, nt.ticks.length - 1))));
|
|
657
|
+
nt.ticks.forEach(function (t, ti) {
|
|
658
|
+
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);
|
|
659
|
+
if (ti % every) return;
|
|
660
|
+
var tt = f.value(t), tw = textWidth(tt, fs - 1, 400, fam), w2 = tw / 2, tx = xs(t), anc = tx - w2 < 0 ? "start" : tx + w2 > W ? "end" : "middle";
|
|
661
|
+
var left = anc === "start" ? tx : anc === "end" ? tx - tw : tx - w2;
|
|
662
|
+
if (left < lastRight + 8) return;
|
|
663
|
+
lastRight = left + tw;
|
|
664
|
+
label(g, tx, y + fs, tt, { "text-anchor": anc, fill: theme.axisText, "font-size": fs - 1, "class": "vtr-tick" });
|
|
665
|
+
});
|
|
666
|
+
}
|
|
667
|
+
/** Factor rows (ranked, top N plus "Other") or group rows. */
|
|
668
|
+
Chart.prototype._rowsFor = function (res, view, L) {
|
|
669
|
+
if (view === "groups") return res.groups.slice().sort(function (a, b) { return b.swing - a.swing; }).map(function (g) { return { kind: "group", obj: g, name: g.label, down: g.down, up: g.up, breach: g.breach, convexity: g.convexity, asym: Math.abs(g.linear) + Math.abs(g.convexity) > 0 ? Math.abs(g.convexity) / (Math.abs(g.linear) + Math.abs(g.convexity)) : 0 }; });
|
|
670
|
+
var top = +this.options.top > 0 ? Math.floor(+this.options.top) : res.order.length;
|
|
671
|
+
var rows = res.order.slice(0, top).map(function (x) { return { kind: "factor", obj: x, name: x.rank + ". " + x.label, down: x.down, up: x.up, breach: x.breach, convexity: x.convexity, asym: x.asymmetry }; });
|
|
672
|
+
var rest = res.order.slice(top);
|
|
673
|
+
if (rest.length) {
|
|
674
|
+
var d = 0, u = 0, sw = 0; rest.forEach(function (x) { d += x.down; u += x.up; sw += x.swing; });
|
|
675
|
+
rows.push({ kind: "other", obj: { count: rest.length, down: d, up: u, swing: sw, share: res.totalSwing > 0 ? sw / res.totalSwing : 0, factors: rest }, name: fill(L.other, { n: rest.length }), down: d, up: u, breach: false, convexity: (d + u) / 2, asym: 0 });
|
|
676
|
+
}
|
|
677
|
+
return rows;
|
|
678
|
+
};
|
|
679
|
+
Chart.prototype._drawRows = function (c, view) {
|
|
680
|
+
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, hib = res.higherIsBetter;
|
|
681
|
+
var rows = this._rowsFor(res, view, L);
|
|
682
|
+
var lay = rowLayout(c, rows.map(function (r) { return r.name; }));
|
|
683
|
+
var limX = res.limit != null ? (hib ? -res.limit : res.limit) : null;
|
|
684
|
+
var vals = []; rows.forEach(function (r) { vals.push(r.down, r.up); });
|
|
685
|
+
var lo = Math.min.apply(null, vals.concat([0, limX != null ? limX : 0])), hi = Math.max.apply(null, vals.concat([0, limX != null ? limX : 0]));
|
|
686
|
+
var lw = function (v) { return textWidth(f.signed(v), fs - 1, 600, fam) + 6; };
|
|
687
|
+
var padL = Math.max.apply(null, [4].concat(vals.filter(function (v) { return v < 0; }).map(lw)));
|
|
688
|
+
var padR = Math.max.apply(null, [4].concat(vals.filter(function (v) { return v >= 0; }).map(lw)));
|
|
689
|
+
var x0 = lay.nameW + padL, x1 = W - padR;
|
|
690
|
+
var nt = niceTicks(lo, hi, Math.max(2, Math.min(6, Math.floor((x1 - x0) / 90))));
|
|
691
|
+
var xs = function (v) { return x0 + (clamp(v, nt.lo, nt.hi) - nt.lo) / (nt.hi - nt.lo) * (x1 - x0); };
|
|
692
|
+
var y = 4, rowH = Math.max(36, fs * 3), extra = lay.narrow ? fs + 4 : 0, gridTop = y + fs + 6, gridBottom = gridTop + rows.length * (rowH + extra);
|
|
693
|
+
var g = svgEl("g", { "class": "vtr-rows" }, svg);
|
|
694
|
+
topTicks(c, g, nt, xs, y, x0, x1, gridTop, gridBottom);
|
|
695
|
+
var gb = svgEl("g", null, g), gc = svgEl("g", { "class": "vtr-cvx-layer" }, g), gl = svgEl("g", null, g); // bars, then diamonds, then labels on top
|
|
696
|
+
if (limX != null) svgEl("line", { x1: xs(limX), x2: xs(limX), y1: gridTop - 2, y2: gridBottom, stroke: theme.limit, "stroke-width": 1.6, "stroke-dasharray": "5 3", "class": "vtr-limit" }, gc);
|
|
697
|
+
var SN = this._shockNames(), self = this;
|
|
698
|
+
rows.forEach(function (r, i) {
|
|
699
|
+
var ry = gridTop + i * (rowH + extra) + extra, bh = Math.max(rowH * 0.32, fs), by = ry + (rowH - 2 * bh - 3) / 2;
|
|
700
|
+
var nameFill = r.breach ? theme.limitText : r.kind === "other" ? theme.mutedText : theme.text;
|
|
701
|
+
var nm = fit(r.name, lay.narrow ? W : lay.nameW - 8, fs, r.kind === "other" ? 400 : 600, fam);
|
|
702
|
+
if (lay.narrow) svgEl("rect", { x: 0, y: ry - 3 - fs * 0.95, width: textWidth(nm, fs, 600, fam) + 4, height: fs * 1.25, fill: c.bg, "class": "vtr-lbg" }, gl);
|
|
703
|
+
label(gl, 0, lay.narrow ? ry - 3 : ry + rowH / 2 + fs * 0.35, fit(r.name, lay.narrow ? W : lay.nameW - 8, fs, r.kind === "other" ? 400 : 600, fam), { fill: nameFill, "font-size": fs, "font-weight": r.kind === "other" ? 400 : 600, "class": "vtr-name" });
|
|
704
|
+
[["down", by], ["up", by + bh + 3]].forEach(function (p) {
|
|
705
|
+
var v = r[p[0]], xa = xs(Math.min(0, v)), xb = xs(Math.max(0, v)), isWorst = r.kind !== "other" && r.obj.worst === p[0];
|
|
706
|
+
svgEl("rect", { x: xa, y: p[1], width: Math.max(0.8, xb - xa), height: bh, rx: 2, fill: theme[p[0]], "class": "vtr-grow vtr-bar", "data-shock": p[0] }, gb);
|
|
707
|
+
var lbreach = r.breach && isWorst;
|
|
708
|
+
var vt = f.signed(v), vw = textWidth(vt, fs - 1, lbreach ? 700 : 400, fam), vx = v < 0 ? xa - 4 - vw : xb + 4;
|
|
709
|
+
svgEl("rect", { x: vx - 2, y: p[1] + bh / 2 - (fs - 1) * 0.6, width: vw + 4, height: (fs - 1) * 1.2, fill: c.bg, "class": "vtr-lbg" }, gl);
|
|
710
|
+
label(gl, v < 0 ? xa - 4 : xb + 4, p[1] + bh / 2 + (fs - 1) * 0.35, f.signed(v), { "text-anchor": v < 0 ? "end" : "start", fill: lbreach ? theme.limitText : theme.text, "font-size": fs - 1, "font-weight": lbreach ? 700 : 400, "class": "vtr-val" });
|
|
711
|
+
});
|
|
712
|
+
if (r.asym >= 0.1) {
|
|
713
|
+
var cx = xs(r.convexity), cy = by + bh + 1.5;
|
|
714
|
+
svgEl("path", { d: "M" + cx + "," + (cy - 4) + "L" + (cx + 4) + "," + cy + "L" + cx + "," + (cy + 4) + "L" + (cx - 4) + "," + cy + "Z", fill: c.bg, stroke: theme.convexity, "stroke-width": 1.5, "class": "vtr-cvx" }, gc);
|
|
715
|
+
}
|
|
716
|
+
var endX = xs(Math.max(0, r.down, r.up));
|
|
717
|
+
if (r.kind === "factor") c.points[r.obj.key] = { x: endX, y: by };
|
|
718
|
+
if (r.kind === "group") c.points["group:" + r.obj.key] = { x: endX, y: by };
|
|
719
|
+
c.items.push({ kind: r.kind, obj: r.obj, x: 0, y: ry - extra, w: W, h: rowH + extra, px: endX, py: by });
|
|
720
|
+
});
|
|
721
|
+
if (view === "groups") res.factors.forEach(function (x) { if (!c.points[x.key]) c.points[x.key] = c.points["group:" + x.group]; });
|
|
722
|
+
var notes = [];
|
|
723
|
+
if (limX != null) notes.push(L.limit + " " + f.signed(limX) + (res.breaches ? ": " + res.breaches + " factor" + (res.breaches > 1 ? "s" : "") + " beyond it" : ": no factor beyond it"));
|
|
724
|
+
if (view === "factors") {
|
|
725
|
+
var shown = rows.filter(function (r) { return r.kind === "factor"; }).length;
|
|
726
|
+
notes.push("Each factor shocked alone" + (shown < res.factors.length ? "; top " + shown + " of " + res.factors.length + ", the rest summed" : ""));
|
|
727
|
+
if (res.interaction) {
|
|
728
|
+
var it = res.interaction, parts = [];
|
|
729
|
+
if (it.down != null) parts.push(SN.down.toLowerCase() + " together " + f.signed(res.joint.down) + " vs sum " + f.signed(res.sumDown));
|
|
730
|
+
if (it.up != null) parts.push(SN.up.toLowerCase() + " together " + f.signed(res.joint.up) + " vs sum " + f.signed(res.sumUp));
|
|
731
|
+
notes.push("All factors " + parts.join(", "));
|
|
732
|
+
}
|
|
733
|
+
} else notes.push("Every factor in the group shocked the same way at once (sum of single shocks)");
|
|
734
|
+
var y2 = gridBottom + fs + 8;
|
|
735
|
+
notes.forEach(function (t) { label(svg, 0, y2, fit(t + ".", W, fs - 1, 400, fam), { fill: theme.mutedText, "font-size": fs - 1, "class": "vtr-note" }); y2 += fs + 3; });
|
|
736
|
+
return Math.ceil(y2 - fs + 6);
|
|
737
|
+
};
|
|
738
|
+
|
|
739
|
+
/** Contribution view: each factor's share of the combined (correlated) move, hedges to the left, stand-alone move as a diamond. */
|
|
740
|
+
Chart.prototype._drawContribution = function (c) {
|
|
741
|
+
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;
|
|
742
|
+
var srt = res.factors.slice().sort(function (a, b) { return Math.abs(b.contribution) - Math.abs(a.contribution) || a.index - b.index; });
|
|
743
|
+
var top = +this.options.top > 0 ? Math.floor(+this.options.top) : srt.length, rest = srt.slice(top);
|
|
744
|
+
var rows = srt.slice(0, top).sort(function (a, b) { return b.contribution - a.contribution; }).map(function (x) { return { kind: "factor", obj: x, name: x.label, v: x.contribution, k: x.standalone }; });
|
|
745
|
+
if (rest.length) { var sv = 0, sk = 0; rest.forEach(function (x) { sv += x.contribution; sk += x.standalone; }); rows.push({ kind: "other", obj: { count: rest.length, contribution: sv, standalone: sk, factors: rest }, name: fill(L.other, { n: rest.length }), v: sv, k: null }); }
|
|
746
|
+
var lay = rowLayout(c, rows.map(function (r) { return r.name; }));
|
|
747
|
+
var valW = Math.max.apply(null, rows.map(function (r) { return textWidth(f.signed(r.v), fs, 700, fam); })) + 10;
|
|
748
|
+
var x0 = lay.nameW, x1 = W - valW, rowH = Math.max(24, fs * 2), extra = lay.narrow ? fs + 4 : 0, y = 4;
|
|
749
|
+
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;
|
|
750
|
+
var nt = niceTicks(lo, hi, Math.max(2, Math.min(6, Math.floor((x1 - x0) / 90))));
|
|
751
|
+
var xs = function (v) { return x0 + (clamp(v, nt.lo, nt.hi) - nt.lo) / (nt.hi - nt.lo) * (x1 - x0); };
|
|
752
|
+
var gridTop = y + fs + 6, gridBottom = gridTop + rows.length * (rowH + extra), g = svgEl("g", { "class": "vtr-contrib" }, svg);
|
|
753
|
+
topTicks(c, g, nt, xs, y, x0, x1, gridTop, gridBottom);
|
|
754
|
+
rows.forEach(function (r, i) {
|
|
755
|
+
var ry = gridTop + i * (rowH + extra) + extra, bh = rowH * 0.56, by = ry + (rowH - bh) / 2, neg = r.v < 0;
|
|
756
|
+
label(g, 0, lay.narrow ? ry - 3 : by + bh / 2 + fs * 0.35, fit(r.name, lay.narrow ? W - valW : 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": "vtr-name" });
|
|
757
|
+
var xa = xs(Math.min(0, r.v)), xb = xs(Math.max(0, r.v));
|
|
758
|
+
svgEl("rect", { x: xa, y: by, width: Math.max(0.8, xb - xa), height: bh, rx: 2, fill: neg ? theme.hedge : theme.contribution, "class": "vtr-grow vtr-cbar" + (neg ? " vtr-hedge" : "") }, g);
|
|
759
|
+
if (r.k != null) { var kx = xs(r.k), ky = by + bh / 2;
|
|
760
|
+
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.convexity, "stroke-width": 1.6, "class": "vtr-sa" }, g); }
|
|
761
|
+
label(g, W, by + bh / 2 + fs * 0.35, f.signed(r.v), { "text-anchor": "end", fill: neg ? theme.hedgeText : theme.text, "font-size": fs, "font-weight": 700, "class": "vtr-val" });
|
|
762
|
+
if (r.kind === "factor") c.points[r.obj.key] = { x: neg ? xa : xb, y: by };
|
|
763
|
+
c.items.push({ kind: r.kind, obj: r.obj, contrib: true, x: 0, y: ry - extra, w: W, h: rowH + extra, px: neg ? xa : xb, py: by });
|
|
764
|
+
});
|
|
765
|
+
var corrText = !res.correlated ? "no correlations given, so factors are treated as independent and none can hedge another"
|
|
766
|
+
: this.options.data.correlation.matrix ? "with the correlation matrix given" : "with correlations of " + f.percent(this.options.data.correlation.within || 0, 0) + " within groups and " + f.percent(this.options.data.correlation.across || 0, 0) + " across";
|
|
767
|
+
var notes = ["Shares add up to the combined move of ±" + f.value(res.sigma) + "; stand-alone moves add up to " + f.value(res.standalone), "Combined " + corrText];
|
|
768
|
+
var y2 = gridBottom + fs + 8;
|
|
769
|
+
notes.forEach(function (t) { label(svg, 0, y2, fit(t + ".", W, fs - 1, 400, fam), { fill: theme.mutedText, "font-size": fs - 1, "class": "vtr-note" }); y2 += fs + 3; });
|
|
770
|
+
return Math.ceil(y2 - fs + 6);
|
|
771
|
+
};
|
|
772
|
+
|
|
773
|
+
Chart.prototype._tipLines = function (it) {
|
|
774
|
+
var o = this.options, f = makeFormatters(o.data, o.locale), L = this._labels(), res = this._res, SN = this._shockNames(), loc = o.locale;
|
|
775
|
+
var lvl = function (v) { return res.base != null ? " → " + f.value(res.base + v) : ""; };
|
|
776
|
+
if (it.kind === "other") {
|
|
777
|
+
var q = it.obj;
|
|
778
|
+
return it.contrib ? [fill(L.other, { n: q.count }), "Shares together " + f.signed(q.contribution)]
|
|
779
|
+
: [fill(L.other, { n: q.count }), SN.down + " (sum) " + f.signed(q.down), SN.up + " (sum) " + f.signed(q.up), L.swing + " together " + f.value(q.swing) + " (" + f.percent(q.share, 0) + " of the total)"];
|
|
780
|
+
}
|
|
781
|
+
if (it.kind === "group") {
|
|
782
|
+
var g = it.obj;
|
|
783
|
+
return [g.label + " · " + g.factors.length + " factor" + (g.factors.length > 1 ? "s" : ""), SN.down + " " + f.signed(g.down) + lvl(g.down), SN.up + " " + f.signed(g.up) + lvl(g.up),
|
|
784
|
+
L.swing + " " + f.value(g.swing) + " (" + f.percent(g.share, 0) + " of the total)", "Combined move of the group ±" + f.value(g.standalone) + " · share of the total ±" + f.value(res.sigma) + ": " + f.signed(g.contribution)]
|
|
785
|
+
.concat(g.breach ? [L.worst + " beyond the limit"] : []);
|
|
786
|
+
}
|
|
787
|
+
var x = it.obj;
|
|
788
|
+
var lines = [x.label, x.group + " · rank " + x.rank + " of " + res.factors.length,
|
|
789
|
+
SN.down + (x.shockDown != null ? " (" + shockText(x.shockDown, x.unit, loc) + ")" : "") + " " + f.signed(x.down) + lvl(x.down),
|
|
790
|
+
SN.up + (x.shockUp != null ? " (" + shockText(x.shockUp, x.unit, loc) + ")" : "") + " " + f.signed(x.up) + lvl(x.up),
|
|
791
|
+
L.swing + " " + f.value(x.swing) + " · " + f.percent(x.share, 0) + " of the total (top " + x.rank + ": " + f.percent(x.cumShare, 0) + ")",
|
|
792
|
+
L.linear + " ±" + f.value(Math.abs(x.linear)) + " · " + L.convexity.toLowerCase() + " " + f.signed(x.convexity),
|
|
793
|
+
"Share of the combined move " + f.signed(x.contribution) + " (stand-alone " + f.value(x.standalone) + ")"];
|
|
794
|
+
if (x.breach) lines.push(SN[x.worst] + " is beyond the limit of " + f.value(res.limit));
|
|
795
|
+
return lines;
|
|
796
|
+
};
|
|
797
|
+
|
|
798
|
+
Chart.prototype._detail = function (it) {
|
|
799
|
+
if (!it) return null;
|
|
800
|
+
var view = this._view;
|
|
801
|
+
if (it.kind === "other") return { view: view, kind: "other", count: it.obj.count, down: it.obj.down, up: it.obj.up, swing: it.obj.swing, contribution: it.obj.contribution, factors: it.obj.factors.map(function (x) { return x.key; }) };
|
|
802
|
+
if (it.kind === "group") { var g = it.obj; return { view: view, kind: "group", key: g.key, label: g.label, factors: g.factors.slice(), down: g.down, up: g.up, swing: g.swing, share: g.share, linear: g.linear, convexity: g.convexity, worst: g.worst, worstValue: g.worstValue, breach: g.breach, contribution: g.contribution, standalone: g.standalone }; }
|
|
803
|
+
var x = it.obj;
|
|
804
|
+
return { view: view, kind: "factor", key: x.key, label: x.label, group: x.group, unit: x.unit, shockDown: x.shockDown, shockUp: x.shockUp, down: x.down, up: x.up, swing: x.swing, share: x.share, cumShare: x.cumShare, rank: x.rank,
|
|
805
|
+
linear: x.linear, convexity: x.convexity, asymmetry: x.asymmetry, worst: x.worst, worstValue: x.worstValue, breach: x.breach, contribution: x.contribution, standalone: x.standalone, source: x.source };
|
|
806
|
+
};
|
|
807
|
+
|
|
808
|
+
Chart.prototype.howToRead = function () {
|
|
809
|
+
var v = this._view || this.options.view;
|
|
810
|
+
if (v === "contribution") return "Each bar is one factor's share of the combined move when all factors move together with their correlations. Shares add up exactly to the combined move; a bar to the left means the factor hedges the others. The diamond marks the factor's move on its own, so the gap between the diamond and the bar is diversification.";
|
|
811
|
+
if (v === "groups") return "Each row is one group of factors, such as a risk class, with every factor in it shocked down (upper bar) and up (lower bar) at the same time. Rows are sorted by swing, the distance between the two results.";
|
|
812
|
+
return "Each row is one risk factor, shocked down (upper bar) and up (lower bar) on its own while everything else stays put. Rows are ranked by swing, the distance between the two results, so the factors that matter most are at the top. A diamond marks the midpoint of the two results when they are clearly unequal (convexity)" + (this._res && this._res.limit != null ? "; the dashed line is the loss limit." : ".");
|
|
813
|
+
};
|
|
814
|
+
|
|
815
|
+
Chart.prototype.describe = function () {
|
|
816
|
+
var o = this.options, f = makeFormatters(o.data, o.locale), L = this._labels(), res = this._res || compute(o.data, this._opts()), SN = this._shockNames(), out = [];
|
|
817
|
+
var t = res.order[0];
|
|
818
|
+
out.push("The largest driver is " + t.label + ": " + SN.down.toLowerCase() + " gives " + f.signed(t.down) + " and " + SN.up.toLowerCase() + " " + f.signed(t.up) + ", a swing of " + f.value(t.swing) + " (" + f.percent(t.share, 0) + " of the total swing).");
|
|
819
|
+
if (res.factors.length > res.topN) out.push("The top " + res.topN + " of " + res.factors.length + " factors explain " + f.percent(res.topShare, 0) + ".");
|
|
820
|
+
var w = res.worstFactor;
|
|
821
|
+
out.push("The worst single shock is " + w.label + " " + SN[w.worst].toLowerCase() + " at " + f.signed(w.worstValue) + (res.limit != null ? (res.breaches ? ", beyond the limit of " + f.value(res.limit) + " (" + res.breaches + " factor" + (res.breaches > 1 ? "s" : "") + " in all)" : ", within the limit of " + f.value(res.limit)) : "") + ".");
|
|
822
|
+
var cv = res.factors.filter(function (x) { return x.asymmetry >= 0.25 && x.swing > 0; }).sort(function (a, b) { return Math.abs(b.convexity) - Math.abs(a.convexity); });
|
|
823
|
+
if (cv.length) out.push(cv.length + " factor" + (cv.length > 1 ? "s are" : " is") + " strongly asymmetric, led by " + cv[0].label + " (convexity " + f.signed(cv[0].convexity) + "), so a bigger shock would cost more than in proportion.");
|
|
824
|
+
if (res.correlated) {
|
|
825
|
+
var cs = res.factors.slice().sort(function (a, b) { return b.contribution - a.contribution; }), hedges = res.factors.filter(function (x) { return x.contribution < 0; }).sort(function (a, b) { return a.contribution - b.contribution; });
|
|
826
|
+
out.push("Moving together with their correlations, the factors give a combined move of ±" + f.value(res.sigma) + ", " + f.percent(res.standalone > 0 ? res.diversification / res.standalone : 0, 0) + " less than the sum of their stand-alone moves; " + cs[0].label + " contributes most (" + f.signed(cs[0].contribution) + ")" + (hedges.length ? " and " + hedges[0].label + " hedges the most (" + f.signed(hedges[0].contribution) + ")" : "") + ".");
|
|
827
|
+
}
|
|
828
|
+
if (res.interaction && res.interaction.down != null) out.push("Shocked all at once, the down case gives " + f.signed(res.joint.down) + " against " + f.signed(res.sumDown) + " for the sum of single shocks, an interaction of " + f.signed(res.interaction.down) + ".");
|
|
829
|
+
if (res.baseline) out.push("The what-if changes the worst single shock from " + f.signed(res.baseline.worstValue) + " to " + f.signed(w.worstValue) + ".");
|
|
830
|
+
return out.join(" ");
|
|
831
|
+
};
|
|
832
|
+
|
|
833
|
+
/* ======================================================================
|
|
834
|
+
5. EXPORT AND NOTES
|
|
835
|
+
====================================================================== */
|
|
836
|
+
Chart.prototype.getExportData = function () {
|
|
837
|
+
var o = this.options, data = o.data, L = this._labels(), f = makeFormatters(data, o.locale), res = this._res || compute(data, this._opts()), SN = this._shockNames(), loc = o.locale;
|
|
838
|
+
var unit = { prefix: data.prefix || "", suffix: data.suffix || "", decimals: data.decimals != null ? data.decimals : 0, negatives: data.negatives };
|
|
839
|
+
var money = function (label) { return { label: label, type: "number", unit: unit }; };
|
|
840
|
+
var plain = function (label) { return { label: label, type: "number", unit: { decimals: 4 } }; };
|
|
841
|
+
var pct = function (label) { return { label: label, type: "percent", decimals: 1 }; };
|
|
842
|
+
var txt = function (label) { return { label: label, type: "text" }; };
|
|
843
|
+
var sheets = [];
|
|
844
|
+
var limit = o.exportRows != null ? o.exportRows : 20000, order = res.order, cut = order.length > limit;
|
|
845
|
+
if (cut) order = order.slice(0, limit);
|
|
846
|
+
var fr = order.map(function (x) { return [x.rank, x.label, x.group, x.unit, x.shockDown, x.shockUp, x.down, x.up, x.swing, x.share, x.cumShare, x.linear, x.convexity, SN[x.worst], x.worstValue, x.breach ? "Yes" : "No", x.contribution, x.standalone]; });
|
|
847
|
+
sheets.push({ name: "Factors", columns: [{ label: "Rank", type: "number", unit: { decimals: 0 } }, txt("Risk factor"), txt("Group"), txt("Shock unit"), plain("Shock down"), plain("Shock up"), money(SN.down), money(SN.up), money(L.swing), pct("Share of total swing"), pct("Cumulative share"), money(L.linear), money(L.convexity), txt("Worst shock"), money(L.worst), txt("Beyond limit"), money("Share of combined move"), money("Stand-alone move")],
|
|
848
|
+
rows: fr, text: order.map(function (x) { return [String(x.rank), x.label, x.group, x.unit, shockText(x.shockDown, "", loc) || "–", shockText(x.shockUp, "", loc) || "–", f.signed(x.down), f.signed(x.up), f.value(x.swing), f.percent(x.share), f.percent(x.cumShare), f.signed(x.linear), f.signed(x.convexity), SN[x.worst], f.signed(x.worstValue), x.breach ? "Yes" : "No", f.signed(x.contribution), f.value(x.standalone)]; }),
|
|
849
|
+
flag: order.map(function (x) { return x.breach; }) });
|
|
850
|
+
sheets.push({ name: "Groups", columns: [txt("Group"), { label: "Factors", type: "number", unit: { decimals: 0 } }, money(SN.down + " (sum)"), money(SN.up + " (sum)"), money(L.swing), pct("Share of total swing"), money(L.worst), txt("Beyond limit"), money("Share of combined move"), money("Group combined move")],
|
|
851
|
+
rows: res.groups.map(function (g) { return [g.label, g.factors.length, g.down, g.up, g.swing, g.share, g.worstValue, g.breach ? "Yes" : "No", g.contribution, g.standalone]; }),
|
|
852
|
+
text: res.groups.map(function (g) { return [g.label, String(g.factors.length), f.signed(g.down), f.signed(g.up), f.value(g.swing), f.percent(g.share), f.signed(g.worstValue), g.breach ? "Yes" : "No", f.signed(g.contribution), f.value(g.standalone)]; }),
|
|
853
|
+
flag: res.groups.map(function (g) { return g.breach; }) });
|
|
854
|
+
var sm = [["Total swing", res.totalSwing], ["Sum of " + SN.down.toLowerCase() + " impacts", res.sumDown], ["Sum of " + SN.up.toLowerCase() + " impacts", res.sumUp]];
|
|
855
|
+
if (res.joint) {
|
|
856
|
+
if (res.joint.down != null) sm.push(["All factors " + SN.down.toLowerCase() + " together", res.joint.down], [L.interaction + " (" + SN.down.toLowerCase() + ")", res.interaction.down]);
|
|
857
|
+
if (res.joint.up != null) sm.push(["All factors " + SN.up.toLowerCase() + " together", res.joint.up], [L.interaction + " (" + SN.up.toLowerCase() + ")", res.interaction.up]);
|
|
858
|
+
}
|
|
859
|
+
sm.push([L.combined + " (±)", res.sigma], ["Sum of stand-alone moves", res.standalone], ["Diversification", res.diversification]);
|
|
860
|
+
if (res.limit != null) sm.push([L.limit, res.limit]);
|
|
861
|
+
sheets.push({ name: "Summary", columns: [txt("Item"), money("Amount")], rows: sm, text: sm.map(function (r) { return [r[0], /Sum|Interaction|together/.test(r[0]) ? f.signed(r[1]) : f.value(r[1])]; }) });
|
|
862
|
+
var notes = (o.annotations || []).map(function (a, i) { return [String(i + 1), a.factor != null ? String(a.factor) : "Group: " + String(a.group || ""), a.text || ""]; });
|
|
863
|
+
if (notes.length) sheets.push({ name: "Notes", columns: [txt("No."), txt("Factor or group"), txt("Note")], rows: notes });
|
|
864
|
+
var c = data.correlation;
|
|
865
|
+
return {
|
|
866
|
+
title: data.title || "Risk-factor tornado", subtitle: data.subtitle || "", summary: this.describe(), library: "Veyforma Risk-Factor Tornado " + VERSION, sheets: sheets,
|
|
867
|
+
meta: [["Unit", data.unit], ["As of", data.asOf], ["Desk", data.desk], ["Measure", res.higherIsBetter ? "Higher is better (for example P&L)" : "Lower is better (for example capital)"],
|
|
868
|
+
["Ranking", o.sort === "worst" ? "By worst result" : "By swing"], ["Shocks", SN.down + " / " + SN.up + (res.shockScale !== 1 ? ", scaled ×" + res.shockScale : "")],
|
|
869
|
+
["What-if", res.whatIf ? Object.keys(res.whatIf).map(function (k) { return k + " × " + res.whatIf[k]; }).join(", ") : null],
|
|
870
|
+
["Correlation", !c ? "None given (independent factors)" : c.matrix ? "Matrix given" : "Within groups " + (c.within || 0) + ", across " + (c.across || 0)],
|
|
871
|
+
["Limit", res.limit != null ? f.value(res.limit) + " (" + res.breaches + " beyond)" : null],
|
|
872
|
+
["Method", "Impact = given down/up result, or Δ·s + ½Γ·s²; swing = |up − down|; linear part L = (up − down) ÷ 2, convexity C = (up + down) ÷ 2; a shock k times larger ≈ L·k + C·k²; combined move σ = √(Lᵀ ρ L); factor share = L_k (ρL)_k ÷ σ (Euler allocation, adds up to σ)" + (cut ? "; factor sheet limited to the " + limit + " largest swings" : "")],
|
|
873
|
+
["Data source", data.source]]
|
|
874
|
+
};
|
|
875
|
+
};
|
|
876
|
+
Chart.prototype._annotationPoint = function (a) {
|
|
877
|
+
var p = this._points || {};
|
|
878
|
+
if (a.factor != null) return p[String(a.factor)] || null;
|
|
879
|
+
if (a.group != null) return p["group:" + String(a.group)] || null;
|
|
880
|
+
return null;
|
|
881
|
+
};
|
|
882
|
+
Chart.prototype._annotationTarget = function (evt) {
|
|
883
|
+
var items = this._items || [], it = null;
|
|
884
|
+
if (!evt) it = items[this._active];
|
|
885
|
+
else {
|
|
886
|
+
var svg = this.plotHost.querySelector("svg"), r = svg.getBoundingClientRect(), vb = svg.viewBox.baseVal;
|
|
887
|
+
var x = (evt.clientX - r.left) * (vb.width / r.width), y = (evt.clientY - r.top) * (vb.height / r.height);
|
|
888
|
+
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; } }
|
|
889
|
+
}
|
|
890
|
+
if (!it || it.kind === "other") return null;
|
|
891
|
+
return it.kind === "group" ? { group: it.obj.key } : { factor: it.obj.key };
|
|
892
|
+
};
|
|
893
|
+
Chart.prototype._annotationLabel = function (a) {
|
|
894
|
+
if (a.group != null) return String(a.group);
|
|
895
|
+
var x = (this._res || this.getResult()).factors.filter(function (q) { return q.key === String(a.factor); })[0];
|
|
896
|
+
return x ? x.label : String(a.factor || "");
|
|
897
|
+
};
|
|
898
|
+
|
|
899
|
+
/* ======================================================================
|
|
900
|
+
6. PUBLIC API
|
|
901
|
+
====================================================================== */
|
|
902
|
+
root.VeyRiskTornado = {
|
|
903
|
+
version: VERSION,
|
|
904
|
+
/** Draws the chart inside a container element or CSS selector. */
|
|
905
|
+
create: function (target, options) { return new Chart(target, options); },
|
|
906
|
+
/** Works out every figure without drawing. opts: { shockScale, whatIf, sort }. */
|
|
907
|
+
compute: function (data, opts) { return compute(data, opts); },
|
|
908
|
+
listThemes: function () { return Object.keys(THEMES); },
|
|
909
|
+
getTheme: function (t) { return resolveTrTheme(t); },
|
|
910
|
+
defaults: { options: DEFAULT_OPTIONS, labels: DEFAULT_LABELS, theme: BASE_THEME }
|
|
911
|
+
};
|
|
912
|
+
})(typeof window !== "undefined" ? window : this);
|