@sybilion/uilib 1.8.4 → 1.8.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent-glossary/content-prompt.generated.ts +27 -0
- package/dist/agent-glossary/content.generated.ts +27 -0
- package/dist/agent-glossary/content.index.md +1 -0
- package/dist/agent-glossary/content.md +27 -0
- package/dist/agent-glossary/content.prompt.md +27 -0
- package/dist/agent-glossary/workspace.generated.ts +1 -0
- package/dist/agent-glossary/workspace.index.md +1 -0
- package/dist/agent-glossary/workspace.md +1 -0
- package/dist/esm/src/components/ui/Chart/components/BaseChartWrapper.js +3 -1
- package/dist/esm/src/components/ui/Chart/components/SeriesLegend/SeriesLegend.js +5 -1
- package/dist/esm/src/components/ui/Chart/components/SeriesLegend/SeriesLegend.styl.js +2 -2
- package/dist/esm/src/components/ui/ChartAreaInteractive/ChartLines.js +15 -5
- package/dist/esm/src/components/ui/StackedAreaChart/StackedAreaChart.js +24 -1
- package/dist/esm/src/components/ui/StackedAreaChart/StackedAreaChart.styl.js +2 -2
- package/dist/esm/src/components/widgets/BacktestChart/BacktestChart.js +113 -0
- package/dist/esm/src/components/widgets/BacktestChart/BacktestChart.styl.js +7 -0
- package/dist/esm/src/components/widgets/BacktestChart/backtestChart.helpers.js +134 -0
- package/dist/esm/src/index.js +3 -1
- package/dist/esm/types/src/components/ui/Chart/components/BaseChartWrapper.d.ts +3 -2
- package/dist/esm/types/src/components/ui/Chart/components/SeriesLegend/SeriesLegend.d.ts +2 -0
- package/dist/esm/types/src/components/ui/ChartAreaInteractive/ChartLines.d.ts +16 -1
- package/dist/esm/types/src/components/ui/StackedAreaChart/StackedAreaChart.types.d.ts +5 -0
- package/dist/esm/types/src/components/widgets/BacktestChart/BacktestChart.d.ts +37 -0
- package/dist/esm/types/src/components/widgets/BacktestChart/backtestChart.helpers.d.ts +61 -0
- package/dist/esm/types/src/components/widgets/BacktestChart/index.d.ts +2 -0
- package/dist/esm/types/src/docs/pages/BacktestChartPage.d.ts +1 -0
- package/dist/esm/types/src/index.d.ts +1 -0
- package/dist/esm/types/tests/backtestChart.test.d.ts +1 -0
- package/package.json +1 -1
- package/src/components/ui/Chart/components/BaseChartWrapper.tsx +6 -2
- package/src/components/ui/Chart/components/SeriesLegend/SeriesLegend.styl +4 -0
- package/src/components/ui/Chart/components/SeriesLegend/SeriesLegend.styl.d.ts +1 -0
- package/src/components/ui/Chart/components/SeriesLegend/SeriesLegend.tsx +7 -1
- package/src/components/ui/ChartAreaInteractive/ChartLines.tsx +30 -4
- package/src/components/ui/StackedAreaChart/AGENT.md +1 -0
- package/src/components/ui/StackedAreaChart/StackedAreaChart.styl +3 -0
- package/src/components/ui/StackedAreaChart/StackedAreaChart.styl.d.ts +1 -0
- package/src/components/ui/StackedAreaChart/StackedAreaChart.tsx +44 -1
- package/src/components/ui/StackedAreaChart/StackedAreaChart.types.ts +5 -0
- package/src/components/widgets/BacktestChart/AGENT.md +24 -0
- package/src/components/widgets/BacktestChart/BacktestChart.styl +23 -0
- package/src/components/widgets/BacktestChart/BacktestChart.styl.d.ts +9 -0
- package/src/components/widgets/BacktestChart/BacktestChart.tsx +247 -0
- package/src/components/widgets/BacktestChart/backtestChart.helpers.ts +172 -0
- package/src/components/widgets/BacktestChart/index.ts +8 -0
- package/src/docs/pages/BacktestChartPage.tsx +94 -0
- package/src/docs/pages/StackedAreaChartPage.tsx +30 -0
- package/src/docs/registry.ts +6 -0
- package/src/index.ts +1 -0
|
@@ -3,6 +3,33 @@ export const CONTENT_AGENT_UI_PROMPT = `# Sybilion page content glossary (embedd
|
|
|
3
3
|
|
|
4
4
|
Component usage for report/dashboard LLM prompts. Paths are relative to \`@sybilion/uilib\` package root.
|
|
5
5
|
|
|
6
|
+
## BacktestChart
|
|
7
|
+
|
|
8
|
+
BacktestChart shows how a forecast did in the past against the simplest baseline, the last known value held flat. It draws the actual values (solid), and from each past month a forecast was made in (an origin) the forecast out to one horizon (dashed, with a dot where it lands) and the origin's value held flat over the same months (dotted grey). Under the chart, one line per window says how much of the baseline's error the forecast removes, with both mean absolute percentage errors (MAPE).
|
|
9
|
+
|
|
10
|
+
## When to use
|
|
11
|
+
|
|
12
|
+
- To show that a forecast beats knowing only the last price, for one horizon at a time.
|
|
13
|
+
|
|
14
|
+
## When not to use
|
|
15
|
+
|
|
16
|
+
- For the latest forecast with its range; use ChartAreaInteractive.
|
|
17
|
+
- For every horizon of every vintage at once; use PerformanceChart's spaghetti view.
|
|
18
|
+
|
|
19
|
+
## Do
|
|
20
|
+
|
|
21
|
+
- Cut each origin's \`forecast\` to the horizon shown: its last point is the landing month the scores use.
|
|
22
|
+
- Set an origin's \`value\` to the actual value at the origin month (the last price known when the forecast was made), and leave out an origin with none.
|
|
23
|
+
- \`windows\` (default 24 and 12) are the last N calendar months up to the latest actual; a window longer than the actuals, or with no landing in it, has no line.
|
|
24
|
+
- Dates are matched by month (\`2024-03-01\` and \`2024-03-28\` are one month), and the chart has one column per month, missing months included.
|
|
25
|
+
- \`backtestScore(actuals, origins, months)\` is the same computation, for a score shown elsewhere.
|
|
26
|
+
- Only forecasts are dashed: the baseline is dotted and the actuals solid.
|
|
27
|
+
|
|
28
|
+
## Requires
|
|
29
|
+
|
|
30
|
+
- \`actuals\`: one point per month, ISO dates (\`2024-03-01\`); a date that does not start \`YYYY-MM\` is left out.
|
|
31
|
+
- \`origins\`: \`{ date, value, forecast: [{ date, value }] }\`, forecast in date order.
|
|
32
|
+
|
|
6
33
|
## ButtonGroup
|
|
7
34
|
|
|
8
35
|
ButtonGroup is a layout wrapper for two or more adjacent buttons. It removes gaps and inner corner radii so outline and secondary actions read as a single segmented control while each button keeps its own click handler.
|
|
@@ -3,6 +3,33 @@ export const CONTENT_AGENT_UI_GLOSSARY = `# Sybilion page content glossary (embe
|
|
|
3
3
|
|
|
4
4
|
Component usage for report/dashboard LLM prompts. Paths are relative to \`@sybilion/uilib\` package root.
|
|
5
5
|
|
|
6
|
+
## BacktestChart
|
|
7
|
+
|
|
8
|
+
BacktestChart shows how a forecast did in the past against the simplest baseline, the last known value held flat. It draws the actual values (solid), and from each past month a forecast was made in (an origin) the forecast out to one horizon (dashed, with a dot where it lands) and the origin's value held flat over the same months (dotted grey). Under the chart, one line per window says how much of the baseline's error the forecast removes, with both mean absolute percentage errors (MAPE).
|
|
9
|
+
|
|
10
|
+
## When to use
|
|
11
|
+
|
|
12
|
+
- To show that a forecast beats knowing only the last price, for one horizon at a time.
|
|
13
|
+
|
|
14
|
+
## When not to use
|
|
15
|
+
|
|
16
|
+
- For the latest forecast with its range; use ChartAreaInteractive.
|
|
17
|
+
- For every horizon of every vintage at once; use PerformanceChart's spaghetti view.
|
|
18
|
+
|
|
19
|
+
## Do
|
|
20
|
+
|
|
21
|
+
- Cut each origin's \`forecast\` to the horizon shown: its last point is the landing month the scores use.
|
|
22
|
+
- Set an origin's \`value\` to the actual value at the origin month (the last price known when the forecast was made), and leave out an origin with none.
|
|
23
|
+
- \`windows\` (default 24 and 12) are the last N calendar months up to the latest actual; a window longer than the actuals, or with no landing in it, has no line.
|
|
24
|
+
- Dates are matched by month (\`2024-03-01\` and \`2024-03-28\` are one month), and the chart has one column per month, missing months included.
|
|
25
|
+
- \`backtestScore(actuals, origins, months)\` is the same computation, for a score shown elsewhere.
|
|
26
|
+
- Only forecasts are dashed: the baseline is dotted and the actuals solid.
|
|
27
|
+
|
|
28
|
+
## Requires
|
|
29
|
+
|
|
30
|
+
- \`actuals\`: one point per month, ISO dates (\`2024-03-01\`); a date that does not start \`YYYY-MM\` is left out.
|
|
31
|
+
- \`origins\`: \`{ date, value, forecast: [{ date, value }] }\`, forecast in date order.
|
|
32
|
+
|
|
6
33
|
## ButtonGroup
|
|
7
34
|
|
|
8
35
|
ButtonGroup is a layout wrapper for two or more adjacent buttons. It removes gaps and inner corner radii so outline and secondary actions read as a single segmented control while each button keeps its own click handler.
|
|
@@ -12,6 +12,7 @@ Entry point for report/dashboard agents using `@sybilion/uilib`. Open linked AGE
|
|
|
12
12
|
|
|
13
13
|
## Widgets
|
|
14
14
|
|
|
15
|
+
- [BacktestChart](src/components/widgets/BacktestChart/AGENT.md) — BacktestChart shows how a forecast did in the past against the simplest baseline, the last known value held flat. It …
|
|
15
16
|
- [DriverMap](src/components/widgets/DriverMap/AGENT.md) — DriverMap renders a world map with regional driver badges, a bottom strip for world-level drivers, and selection high…
|
|
16
17
|
- [DriversComparisonChart](src/components/widgets/DriversComparisonChart/AGENT.md) — DriversComparisonChart plots a normalized target line against the normalized series of its drivers, with a table of d…
|
|
17
18
|
- [PerformanceChart](src/components/widgets/PerformanceChart/AGENT.md) — PerformanceChart is a widget for evaluating forecast accuracy. It plots per-horizon and spaghetti views of model and …
|
|
@@ -2,6 +2,33 @@
|
|
|
2
2
|
|
|
3
3
|
Component usage for report/dashboard LLM prompts. Paths are relative to `@sybilion/uilib` package root.
|
|
4
4
|
|
|
5
|
+
## BacktestChart
|
|
6
|
+
|
|
7
|
+
BacktestChart shows how a forecast did in the past against the simplest baseline, the last known value held flat. It draws the actual values (solid), and from each past month a forecast was made in (an origin) the forecast out to one horizon (dashed, with a dot where it lands) and the origin's value held flat over the same months (dotted grey). Under the chart, one line per window says how much of the baseline's error the forecast removes, with both mean absolute percentage errors (MAPE).
|
|
8
|
+
|
|
9
|
+
## When to use
|
|
10
|
+
|
|
11
|
+
- To show that a forecast beats knowing only the last price, for one horizon at a time.
|
|
12
|
+
|
|
13
|
+
## When not to use
|
|
14
|
+
|
|
15
|
+
- For the latest forecast with its range; use ChartAreaInteractive.
|
|
16
|
+
- For every horizon of every vintage at once; use PerformanceChart's spaghetti view.
|
|
17
|
+
|
|
18
|
+
## Do
|
|
19
|
+
|
|
20
|
+
- Cut each origin's `forecast` to the horizon shown: its last point is the landing month the scores use.
|
|
21
|
+
- Set an origin's `value` to the actual value at the origin month (the last price known when the forecast was made), and leave out an origin with none.
|
|
22
|
+
- `windows` (default 24 and 12) are the last N calendar months up to the latest actual; a window longer than the actuals, or with no landing in it, has no line.
|
|
23
|
+
- Dates are matched by month (`2024-03-01` and `2024-03-28` are one month), and the chart has one column per month, missing months included.
|
|
24
|
+
- `backtestScore(actuals, origins, months)` is the same computation, for a score shown elsewhere.
|
|
25
|
+
- Only forecasts are dashed: the baseline is dotted and the actuals solid.
|
|
26
|
+
|
|
27
|
+
## Requires
|
|
28
|
+
|
|
29
|
+
- `actuals`: one point per month, ISO dates (`2024-03-01`); a date that does not start `YYYY-MM` is left out.
|
|
30
|
+
- `origins`: `{ date, value, forecast: [{ date, value }] }`, forecast in date order.
|
|
31
|
+
|
|
5
32
|
## ButtonGroup
|
|
6
33
|
|
|
7
34
|
ButtonGroup is a layout wrapper for two or more adjacent buttons. It removes gaps and inner corner radii so outline and secondary actions read as a single segmented control while each button keeps its own click handler.
|
|
@@ -2,6 +2,33 @@
|
|
|
2
2
|
|
|
3
3
|
Component usage for report/dashboard LLM prompts. Paths are relative to `@sybilion/uilib` package root.
|
|
4
4
|
|
|
5
|
+
## BacktestChart
|
|
6
|
+
|
|
7
|
+
BacktestChart shows how a forecast did in the past against the simplest baseline, the last known value held flat. It draws the actual values (solid), and from each past month a forecast was made in (an origin) the forecast out to one horizon (dashed, with a dot where it lands) and the origin's value held flat over the same months (dotted grey). Under the chart, one line per window says how much of the baseline's error the forecast removes, with both mean absolute percentage errors (MAPE).
|
|
8
|
+
|
|
9
|
+
## When to use
|
|
10
|
+
|
|
11
|
+
- To show that a forecast beats knowing only the last price, for one horizon at a time.
|
|
12
|
+
|
|
13
|
+
## When not to use
|
|
14
|
+
|
|
15
|
+
- For the latest forecast with its range; use ChartAreaInteractive.
|
|
16
|
+
- For every horizon of every vintage at once; use PerformanceChart's spaghetti view.
|
|
17
|
+
|
|
18
|
+
## Do
|
|
19
|
+
|
|
20
|
+
- Cut each origin's `forecast` to the horizon shown: its last point is the landing month the scores use.
|
|
21
|
+
- Set an origin's `value` to the actual value at the origin month (the last price known when the forecast was made), and leave out an origin with none.
|
|
22
|
+
- `windows` (default 24 and 12) are the last N calendar months up to the latest actual; a window longer than the actuals, or with no landing in it, has no line.
|
|
23
|
+
- Dates are matched by month (`2024-03-01` and `2024-03-28` are one month), and the chart has one column per month, missing months included.
|
|
24
|
+
- `backtestScore(actuals, origins, months)` is the same computation, for a score shown elsewhere.
|
|
25
|
+
- Only forecasts are dashed: the baseline is dotted and the actuals solid.
|
|
26
|
+
|
|
27
|
+
## Requires
|
|
28
|
+
|
|
29
|
+
- `actuals`: one point per month, ISO dates (`2024-03-01`); a date that does not start `YYYY-MM` is left out.
|
|
30
|
+
- `origins`: `{ date, value, forecast: [{ date, value }] }`, forecast in date order.
|
|
31
|
+
|
|
5
32
|
## ButtonGroup
|
|
6
33
|
|
|
7
34
|
ButtonGroup is a layout wrapper for two or more adjacent buttons. It removes gaps and inner corner radii so outline and secondary actions read as a single segmented control while each button keeps its own click handler.
|
|
@@ -84,6 +84,7 @@ Entry point for \`@sybilion/uilib\`. Open linked AGENT.md before using a compone
|
|
|
84
84
|
|
|
85
85
|
## Widgets
|
|
86
86
|
|
|
87
|
+
- [BacktestChart](src/components/widgets/BacktestChart/AGENT.md) — BacktestChart shows how a forecast did in the past against the simplest baseline, the last known value held flat. It …
|
|
87
88
|
- [DriverMap](src/components/widgets/DriverMap/AGENT.md) — DriverMap renders a world map with regional driver badges, a bottom strip for world-level drivers, and selection high…
|
|
88
89
|
- [DriversComparisonChart](src/components/widgets/DriversComparisonChart/AGENT.md) — DriversComparisonChart plots a normalized target line against the normalized series of its drivers, with a table of d…
|
|
89
90
|
- [PerformanceChart](src/components/widgets/PerformanceChart/AGENT.md) — PerformanceChart is a widget for evaluating forecast accuracy. It plots per-horizon and spaghetti views of model and …
|
|
@@ -83,6 +83,7 @@ Entry point for `@sybilion/uilib`. Open linked AGENT.md before using a component
|
|
|
83
83
|
|
|
84
84
|
## Widgets
|
|
85
85
|
|
|
86
|
+
- [BacktestChart](src/components/widgets/BacktestChart/AGENT.md) — BacktestChart shows how a forecast did in the past against the simplest baseline, the last known value held flat. It …
|
|
86
87
|
- [DriverMap](src/components/widgets/DriverMap/AGENT.md) — DriverMap renders a world map with regional driver badges, a bottom strip for world-level drivers, and selection high…
|
|
87
88
|
- [DriversComparisonChart](src/components/widgets/DriversComparisonChart/AGENT.md) — DriversComparisonChart plots a normalized target line against the normalized series of its drivers, with a table of d…
|
|
88
89
|
- [PerformanceChart](src/components/widgets/PerformanceChart/AGENT.md) — PerformanceChart is a widget for evaluating forecast accuracy. It plots per-horizon and spaghetti views of model and …
|
|
@@ -83,6 +83,7 @@ Entry point for `@sybilion/uilib`. Open linked AGENT.md before using a component
|
|
|
83
83
|
|
|
84
84
|
## Widgets
|
|
85
85
|
|
|
86
|
+
- [BacktestChart](src/components/widgets/BacktestChart/AGENT.md) — BacktestChart shows how a forecast did in the past against the simplest baseline, the last known value held flat. It …
|
|
86
87
|
- [DriverMap](src/components/widgets/DriverMap/AGENT.md) — DriverMap renders a world map with regional driver badges, a bottom strip for world-level drivers, and selection high…
|
|
87
88
|
- [DriversComparisonChart](src/components/widgets/DriversComparisonChart/AGENT.md) — DriversComparisonChart plots a normalized target line against the normalized series of its drivers, with a table of d…
|
|
88
89
|
- [PerformanceChart](src/components/widgets/PerformanceChart/AGENT.md) — PerformanceChart is a widget for evaluating forecast accuracy. It plots per-horizon and spaghetti views of model and …
|
|
@@ -252,6 +252,7 @@ const BaseChartWrapperContent = forwardRef((props, ref) => {
|
|
|
252
252
|
// tooltip: item.tooltip,
|
|
253
253
|
dimmed: item.dimmed,
|
|
254
254
|
updated_at: item.updated_at,
|
|
255
|
+
lineStyle: item.lineStyle,
|
|
255
256
|
}));
|
|
256
257
|
}, [forecastData, excludeLegendIds, showLegend]);
|
|
257
258
|
// The plain legend: every line in `legendOrder` (else histories, then
|
|
@@ -282,7 +283,8 @@ const BaseChartWrapperContent = forwardRef((props, ref) => {
|
|
|
282
283
|
dataKey: p.dataKey,
|
|
283
284
|
label: p.value,
|
|
284
285
|
color: p.color,
|
|
285
|
-
dashed: forecastLineStyle === 'dashed',
|
|
286
|
+
dashed: (p.lineStyle ?? forecastLineStyle) === 'dashed',
|
|
287
|
+
dotted: (p.lineStyle ?? forecastLineStyle) === 'dotted',
|
|
286
288
|
})),
|
|
287
289
|
];
|
|
288
290
|
if (!legendOrder)
|
|
@@ -12,7 +12,11 @@ function SeriesLegend({ items, hiddenSeries, onToggle, className, }) {
|
|
|
12
12
|
return null;
|
|
13
13
|
return (jsx("div", { className: cn(ChartS.legendContainer, S.root, className), children: items.map(item => {
|
|
14
14
|
const dimmed = hiddenSeries?.has(item.dataKey) ?? false;
|
|
15
|
-
const content = (jsxs(Fragment, { children: [jsx("span", { className: cn(S.swatch, item.square
|
|
15
|
+
const content = (jsxs(Fragment, { children: [jsx("span", { className: cn(S.swatch, item.square
|
|
16
|
+
? S.square
|
|
17
|
+
: item.dotted
|
|
18
|
+
? S.dotted
|
|
19
|
+
: item.dashed && S.dashed), style: { color: item.color }, "aria-hidden": true }), item.label] }));
|
|
16
20
|
return onToggle ? (jsx("button", { type: "button", className: cn(ChartS.legendItem, S.button, dimmed && S.dimmed), "aria-pressed": !dimmed, onClick: () => onToggle(item.dataKey), children: content }, item.dataKey)) : (jsx("span", { className: ChartS.legendItem, children: content }, item.dataKey));
|
|
17
21
|
}) }));
|
|
18
22
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import styleInject from 'style-inject';
|
|
2
2
|
|
|
3
|
-
var css_248z = ".SeriesLegend_root__5W8Ao{flex-wrap:wrap;margin-top:.75rem;row-gap:.5rem}.SeriesLegend_button__F5-RK{-webkit-appearance:none;-moz-appearance:none;appearance:none;background:none;border:0;color:inherit;cursor:pointer;font:inherit;padding:0}.SeriesLegend_dimmed__I8twS{opacity:.4}.SeriesLegend_swatch__kZTb2{border-top:2px solid;flex-shrink:0;height:0;width:14px}.SeriesLegend_dashed__tqWnl{border-top-style:dashed}.SeriesLegend_square__4EzP7{background:currentColor;border-radius:2px;border-top:0;height:.5rem;width:.5rem}";
|
|
4
|
-
var S = {"root":"SeriesLegend_root__5W8Ao","button":"SeriesLegend_button__F5-RK","dimmed":"SeriesLegend_dimmed__I8twS","swatch":"SeriesLegend_swatch__kZTb2","dashed":"SeriesLegend_dashed__tqWnl","square":"SeriesLegend_square__4EzP7"};
|
|
3
|
+
var css_248z = ".SeriesLegend_root__5W8Ao{flex-wrap:wrap;margin-top:.75rem;row-gap:.5rem}.SeriesLegend_button__F5-RK{-webkit-appearance:none;-moz-appearance:none;appearance:none;background:none;border:0;color:inherit;cursor:pointer;font:inherit;padding:0}.SeriesLegend_dimmed__I8twS{opacity:.4}.SeriesLegend_swatch__kZTb2{border-top:2px solid;flex-shrink:0;height:0;width:14px}.SeriesLegend_dashed__tqWnl{border-top-style:dashed}.SeriesLegend_dotted__C1E36{border-top-style:dotted}.SeriesLegend_square__4EzP7{background:currentColor;border-radius:2px;border-top:0;height:.5rem;width:.5rem}";
|
|
4
|
+
var S = {"root":"SeriesLegend_root__5W8Ao","button":"SeriesLegend_button__F5-RK","dimmed":"SeriesLegend_dimmed__I8twS","swatch":"SeriesLegend_swatch__kZTb2","dashed":"SeriesLegend_dashed__tqWnl","dotted":"SeriesLegend_dotted__C1E36","square":"SeriesLegend_square__4EzP7"};
|
|
5
5
|
styleInject(css_248z);
|
|
6
6
|
|
|
7
7
|
export { S as default };
|
|
@@ -3,6 +3,14 @@ import { memo, useMemo } from 'react';
|
|
|
3
3
|
import { DefaultZIndexes, Line } from 'recharts';
|
|
4
4
|
import { HISTORY_SERIES_KEY, historySeriesKey } from './chartHistories.js';
|
|
5
5
|
|
|
6
|
+
/** The stroke pattern for a line style. */
|
|
7
|
+
function lineStyleDasharray(style) {
|
|
8
|
+
if (style === 'dashed')
|
|
9
|
+
return '4 2';
|
|
10
|
+
if (style === 'dotted')
|
|
11
|
+
return '1 3';
|
|
12
|
+
return '0';
|
|
13
|
+
}
|
|
6
14
|
const ANIMATION_DURATION = 300;
|
|
7
15
|
// Colors for different forecast series
|
|
8
16
|
const FORECAST_COLORS_MAP = {
|
|
@@ -112,7 +120,7 @@ const ChartLines = memo(({ chartData, forecastData, historyData, hiddenSeries, i
|
|
|
112
120
|
// `dotLonePoints`) on any point the line leaves alone, which would
|
|
113
121
|
// otherwise not show: no value in the rows on either side, or, for a line
|
|
114
122
|
// drawn across gaps, no other value at all.
|
|
115
|
-
const renderDot = (props, lastIndex, dataKey, color, connected) => {
|
|
123
|
+
const renderDot = (props, lastIndex, dataKey, color, connected, endDot = showEndDots) => {
|
|
116
124
|
const i = props.index;
|
|
117
125
|
if (typeof i !== 'number' ||
|
|
118
126
|
chartData[i]?.[dataKey] == null ||
|
|
@@ -120,7 +128,7 @@ const ChartLines = memo(({ chartData, forecastData, historyData, hiddenSeries, i
|
|
|
120
128
|
props.cx == null) {
|
|
121
129
|
return null;
|
|
122
130
|
}
|
|
123
|
-
const isEnd =
|
|
131
|
+
const isEnd = endDot && lastIndex >= 0 && i === lastIndex;
|
|
124
132
|
const isAlone = dotLonePoints &&
|
|
125
133
|
(connected
|
|
126
134
|
? valueCounts?.[dataKey] === 1
|
|
@@ -152,12 +160,14 @@ const ChartLines = memo(({ chartData, forecastData, historyData, hiddenSeries, i
|
|
|
152
160
|
const { id, name, color = FORECAST_LINE_COLORS[index % FORECAST_LINE_COLORS.length], } = data;
|
|
153
161
|
const dataKey = `forecast_${id}`;
|
|
154
162
|
const connected = data.connectNulls ?? connectForecastNulls;
|
|
155
|
-
|
|
156
|
-
|
|
163
|
+
const endDot = data.endDot ?? showEndDots;
|
|
164
|
+
const lineStyle = data.lineStyle ?? forecastLineStyle;
|
|
165
|
+
return (jsx(Line, { type: "monotone", dataKey: dataKey, stroke: color, strokeWidth: 1, strokeDasharray: lineStyleDasharray(lineStyle), strokeLinecap: lineStyle === 'dotted' ? 'round' : undefined, dot: endDot || dotLonePoints
|
|
166
|
+
? props => renderDot(props, lastForecastIndices[id] ?? -1, dataKey, color, connected, endDot)
|
|
157
167
|
: false, activeDot: activeDotForecast(color), name: `${name || `${id}`}`, legendType: showLegend === false ? 'none' : undefined, connectNulls: connected, hide: hiddenSeries?.has(dataKey), isAnimationActive: forecastAnimationActive, animationDuration: animationDuration, animateNewValues: valueAnimationEnabled, animationBegin: 0, animationEasing: "ease-out", className: data.status === 'pending' ? 'chart-line-blinking' : undefined }, `forecast-${id}`));
|
|
158
168
|
});
|
|
159
169
|
return (jsxs(Fragment, { children: [historyElements, forecastElements] }));
|
|
160
170
|
});
|
|
161
171
|
ChartLines.displayName = 'ChartLines';
|
|
162
172
|
|
|
163
|
-
export { ChartLines, FORECAST_COLORS_MAP, FORECAST_LINE_COLORS, getForecastColor, getForecastQuantileBandColor, getHistoryColor, resolveHistoryLines, resolveQuantileBandFillForForecastLine };
|
|
173
|
+
export { ChartLines, FORECAST_COLORS_MAP, FORECAST_LINE_COLORS, getForecastColor, getForecastQuantileBandColor, getHistoryColor, lineStyleDasharray, resolveHistoryLines, resolveQuantileBandFillForForecastLine };
|
|
@@ -36,6 +36,7 @@ const AXIS_LINE = { stroke: 'var(--border)', strokeWidth: 1 };
|
|
|
36
36
|
const X_AXIS_HEIGHT_WITH_LABEL = 44;
|
|
37
37
|
const layerColor = (layer, index) => layer.color ?? getChartSeriesColor(index);
|
|
38
38
|
const overlayColor = (overlay) => overlay.color ?? DEFAULT_OVERLAY_COLOR;
|
|
39
|
+
const LONE_DOT_RADIUS = 3;
|
|
39
40
|
function LegendEntry({ swatch, label, extra, dimmed, onClick, }) {
|
|
40
41
|
const content = (jsxs(Fragment, { children: [swatch, label, extra != null && jsx("span", { className: S.legendExtra, children: extra })] }));
|
|
41
42
|
return onClick ? (jsx("button", { type: "button", className: cn(ChartS.legendItem, S.legendButton, dimmed && S.dimmed), "aria-pressed": !dimmed, onClick: onClick, children: content })) : (jsx("span", { className: ChartS.legendItem, children: content }));
|
|
@@ -68,6 +69,18 @@ const StackedAreaChart = forwardRef(({ className, data, xKey, layers, overlays =
|
|
|
68
69
|
// does not change them.
|
|
69
70
|
const weights = useMemo(() => (showWeights ? stackWeights(data, visibleKeys) : undefined), [showWeights, data, visibleKeys]);
|
|
70
71
|
const asBars = rows.length < barsBelow;
|
|
72
|
+
// How many values each overlay has: a bridged line with one value draws
|
|
73
|
+
// nothing, so `dotLonePoints` dots it.
|
|
74
|
+
const overlayValueCounts = useMemo(() => {
|
|
75
|
+
const counts = {};
|
|
76
|
+
for (const overlay of overlays) {
|
|
77
|
+
counts[overlay.key] = data.filter(row => {
|
|
78
|
+
const value = row[overlay.key];
|
|
79
|
+
return typeof value === 'number' && Number.isFinite(value);
|
|
80
|
+
}).length;
|
|
81
|
+
}
|
|
82
|
+
return counts;
|
|
83
|
+
}, [data, overlays]);
|
|
71
84
|
const compareKey = overlays.find(o => o.compare)?.key;
|
|
72
85
|
const zonesOn = compareKey != null && !hidden.has(compareKey);
|
|
73
86
|
const zones = useMemo(() => {
|
|
@@ -120,7 +133,17 @@ const StackedAreaChart = forwardRef(({ className, data, xKey, layers, overlays =
|
|
|
120
133
|
width: yAxisLabel ? 72 : 56, tickLine: false, axisLine: AXIS_LINE, children: yAxisLabel && (jsx(Label, { value: yAxisLabel, angle: -90, position: "insideLeft" })) }), showTooltip && (jsx(ChartPlacedTooltip, { content: tooltip => (jsx(StackedTooltip, { active: tooltip.active, payload: tooltip.payload, label: tooltip.label, config: config, valueFormatter: tooltipValueFormatter, labelFormatter: tooltipLabelFormatter })) })), zones.map(zone => (jsx(ReferenceArea, { x1: zone.x1, x2: zone.x2, fill: ZONE_FILL[zone.kind], fillOpacity: 1, stroke: "none", ifOverflow: "hidden", zIndex: ZONE_Z_INDEX }, `${zone.kind}-${String(zone.x1)}`))), layers.map((layer, index) => asBars ? (jsx(Bar, { dataKey: layer.key, name: layer.key, fill: layerColor(layer, index), maxBarSize: 96, hide: hidden.has(layer.key), ...stackProps }, layer.key)) : (jsx(Area, { type: "monotone", dataKey: layer.key, name: layer.key, fill: layerColor(layer, index), fillOpacity: 1, hide: hidden.has(layer.key), ...stackProps }, layer.key))), margin &&
|
|
121
134
|
(asBars ? (jsx(Bar, { dataKey: MARGIN_KEY, name: MARGIN_KEY, fill: marginColor, maxBarSize: 96, hide: !marginOn, ...stackProps }, MARGIN_KEY)) : (jsx(Area, { type: "monotone", dataKey: MARGIN_KEY, name: MARGIN_KEY, fill: marginColor, fillOpacity: 1, hide: !marginOn, ...stackProps }, MARGIN_KEY))), overlays.map(overlay => {
|
|
122
135
|
const color = overlayColor(overlay);
|
|
123
|
-
|
|
136
|
+
const lone = !asBars &&
|
|
137
|
+
overlay.dotLonePoints &&
|
|
138
|
+
overlayValueCounts[overlay.key] === 1;
|
|
139
|
+
return (jsx(Line, { type: "linear", dataKey: overlay.key, name: overlay.key, stroke: color, strokeWidth: 1.75, dot: asBars
|
|
140
|
+
? { r: 4, fill: color, stroke: color }
|
|
141
|
+
: lone
|
|
142
|
+
? (props) => typeof props.value === 'number' &&
|
|
143
|
+
Number.isFinite(props.value) &&
|
|
144
|
+
props.cx != null &&
|
|
145
|
+
props.cy != null ? (jsx("circle", { className: S.loneDot, cx: props.cx, cy: props.cy, r: LONE_DOT_RADIUS, fill: color }, `lone-${overlay.key}-${props.index}`)) : (jsx("g", {}, `lone-${overlay.key}-${props.index}`))
|
|
146
|
+
: false, activeDot: false, connectNulls: true, isAnimationActive: false, hide: hidden.has(overlay.key) }, overlay.key));
|
|
124
147
|
})] }) }), showLegend && (jsxs("div", { className: cn(ChartS.legendContainer, S.legend), children: [layers.map((layer, index) => (jsx(LegendEntry, { swatch: jsx("span", { className: ChartS.legendIndicator, style: { backgroundColor: layerColor(layer, index) } }), label: layer.label ?? layer.key, extra: weights && !hidden.has(layer.key)
|
|
125
148
|
? `${weights[layer.key] ?? 0}%`
|
|
126
149
|
: undefined, dimmed: hidden.has(layer.key), onClick: toggle && (() => toggle(layer.key)) }, layer.key))), marginOn && (jsx(LegendEntry, { swatch: jsx("span", { className: ChartS.legendIndicator, style: { backgroundColor: marginColor } }), label: marginLabel })), overlays.map(overlay => (jsx(LegendEntry, { swatch: jsx("span", { className: S.legendLine, style: { backgroundColor: overlayColor(overlay) } }), label: overlay.label ?? overlay.key, dimmed: hidden.has(overlay.key), onClick: toggle && (() => toggle(overlay.key)) }, overlay.key))), zoneKinds.map(kind => (jsx(LegendEntry, { swatch: jsx("span", { className: cn(ChartS.legendIndicator, S.legendZone), style: { backgroundColor: ZONE_FILL[kind] } }), label: zoneLabels[kind] }, kind)))] }))] }));
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import styleInject from 'style-inject';
|
|
2
2
|
|
|
3
|
-
var css_248z = ".StackedAreaChart_root__BkxHH{width:100%}.StackedAreaChart_legend__JVlx8{flex-wrap:wrap;margin-top:.75rem;row-gap:.5rem}.StackedAreaChart_legendButton__-nJsf{-webkit-appearance:none;-moz-appearance:none;appearance:none;background:none;border:0;color:inherit;cursor:pointer;font:inherit;padding:0}.StackedAreaChart_dimmed__L-fX7{opacity:.4}.StackedAreaChart_legendExtra__xGgeV{color:var(--muted-foreground);font-feature-settings:\"tnum\";font-variant-numeric:tabular-nums}.StackedAreaChart_legendLine__UDtNb{border-radius:1px;flex-shrink:0;height:2px;width:14px}.StackedAreaChart_legendZone__-47oB{border:1px solid var(--border)}";
|
|
4
|
-
var S = {"root":"StackedAreaChart_root__BkxHH","legend":"StackedAreaChart_legend__JVlx8","legendButton":"StackedAreaChart_legendButton__-nJsf","dimmed":"StackedAreaChart_dimmed__L-fX7","legendExtra":"StackedAreaChart_legendExtra__xGgeV","legendLine":"StackedAreaChart_legendLine__UDtNb","legendZone":"StackedAreaChart_legendZone__-47oB"};
|
|
3
|
+
var css_248z = ".StackedAreaChart_root__BkxHH{width:100%}.StackedAreaChart_legend__JVlx8{flex-wrap:wrap;margin-top:.75rem;row-gap:.5rem}.StackedAreaChart_legendButton__-nJsf{-webkit-appearance:none;-moz-appearance:none;appearance:none;background:none;border:0;color:inherit;cursor:pointer;font:inherit;padding:0}.StackedAreaChart_dimmed__L-fX7{opacity:.4}.StackedAreaChart_legendExtra__xGgeV{color:var(--muted-foreground);font-feature-settings:\"tnum\";font-variant-numeric:tabular-nums}.StackedAreaChart_legendLine__UDtNb{border-radius:1px;flex-shrink:0;height:2px;width:14px}.StackedAreaChart_loneDot__08-V7{pointer-events:none}.StackedAreaChart_legendZone__-47oB{border:1px solid var(--border)}";
|
|
4
|
+
var S = {"root":"StackedAreaChart_root__BkxHH","legend":"StackedAreaChart_legend__JVlx8","legendButton":"StackedAreaChart_legendButton__-nJsf","dimmed":"StackedAreaChart_dimmed__L-fX7","legendExtra":"StackedAreaChart_legendExtra__xGgeV","legendLine":"StackedAreaChart_legendLine__UDtNb","loneDot":"StackedAreaChart_loneDot__08-V7","legendZone":"StackedAreaChart_legendZone__-47oB"};
|
|
5
5
|
styleInject(css_248z);
|
|
6
6
|
|
|
7
7
|
export { S as default };
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { jsxs, jsx, Fragment } from 'react/jsx-runtime';
|
|
2
|
+
import cn from 'classnames';
|
|
3
|
+
import { useState, useCallback, useMemo } from 'react';
|
|
4
|
+
import { BaseChartWrapper } from '../../ui/Chart/components/BaseChartWrapper.js';
|
|
5
|
+
import { SeriesLegend } from '../../ui/Chart/components/SeriesLegend/SeriesLegend.js';
|
|
6
|
+
import { HISTORY_SERIES_KEY } from '../../ui/ChartAreaInteractive/chartHistories.js';
|
|
7
|
+
import S from './BacktestChart.styl.js';
|
|
8
|
+
import { buildBacktestRows, backtestBaselineId, backtestForecastId, backtestForecastKey, backtestBaselineKey, backtestScore } from './backtestChart.helpers.js';
|
|
9
|
+
|
|
10
|
+
const DEFAULT_WINDOWS = [24, 12];
|
|
11
|
+
const PERCENT = new Intl.NumberFormat('en-GB', { maximumFractionDigits: 1 });
|
|
12
|
+
const defaultFormatPercent = (v) => `${PERCENT.format(v)}%`;
|
|
13
|
+
/**
|
|
14
|
+
* A backtest: the actual values (solid), and from each origin the forecast
|
|
15
|
+
* out to its horizon (dashed, with a dot where it lands) and the last value
|
|
16
|
+
* held flat over the same months (dotted, the baseline). Under it, for each
|
|
17
|
+
* window, how much of the baseline's error the forecast removes.
|
|
18
|
+
*/
|
|
19
|
+
function BacktestChart({ actuals, origins, windows = DEFAULT_WINDOWS, actualLabel = 'Actual', forecastLabel = 'Forecast', baselineLabel = 'Last price held flat', actualColor, forecastColor = 'var(--sb-cyan-400)', baselineColor = 'var(--sb-gray-400)', renderScore, formatPercent = defaultFormatPercent, formatNumber, formatDate, height = 300, disableAnimation = false, isDarkTheme = false, renderId = 'backtest', className, }) {
|
|
20
|
+
const [hiddenGroups, setHiddenGroups] = useState(() => new Set());
|
|
21
|
+
const toggle = useCallback((group) => {
|
|
22
|
+
setHiddenGroups(prev => {
|
|
23
|
+
const next = new Set(prev);
|
|
24
|
+
if (next.has(group))
|
|
25
|
+
next.delete(group);
|
|
26
|
+
else
|
|
27
|
+
next.add(group);
|
|
28
|
+
return next;
|
|
29
|
+
});
|
|
30
|
+
}, []);
|
|
31
|
+
const chartData = useMemo(() => buildBacktestRows(actuals, origins), [actuals, origins]);
|
|
32
|
+
const historyColor = actualColor ?? (isDarkTheme ? '#ffffff' : '#000000');
|
|
33
|
+
const forecastData = useMemo(() => origins.flatMap((_, i) => [
|
|
34
|
+
// The baseline first, so each forecast is drawn over it.
|
|
35
|
+
{
|
|
36
|
+
id: backtestBaselineId(i),
|
|
37
|
+
name: baselineLabel,
|
|
38
|
+
color: baselineColor,
|
|
39
|
+
lineStyle: 'dotted',
|
|
40
|
+
endDot: false,
|
|
41
|
+
},
|
|
42
|
+
{
|
|
43
|
+
id: backtestForecastId(i),
|
|
44
|
+
name: forecastLabel,
|
|
45
|
+
color: forecastColor,
|
|
46
|
+
lineStyle: 'dashed',
|
|
47
|
+
endDot: true,
|
|
48
|
+
},
|
|
49
|
+
]), [origins, baselineLabel, baselineColor, forecastLabel, forecastColor]);
|
|
50
|
+
// The chart hides lines by data key; the legend hides whole groups.
|
|
51
|
+
const hiddenSeries = useMemo(() => {
|
|
52
|
+
const keys = new Set();
|
|
53
|
+
if (hiddenGroups.has('actual'))
|
|
54
|
+
keys.add(HISTORY_SERIES_KEY);
|
|
55
|
+
origins.forEach((_, i) => {
|
|
56
|
+
if (hiddenGroups.has('forecast'))
|
|
57
|
+
keys.add(backtestForecastKey(i));
|
|
58
|
+
if (hiddenGroups.has('baseline'))
|
|
59
|
+
keys.add(backtestBaselineKey(i));
|
|
60
|
+
});
|
|
61
|
+
return keys;
|
|
62
|
+
}, [hiddenGroups, origins]);
|
|
63
|
+
const legend = useMemo(() => [
|
|
64
|
+
{ dataKey: 'actual', label: actualLabel, color: historyColor },
|
|
65
|
+
{
|
|
66
|
+
dataKey: 'forecast',
|
|
67
|
+
label: forecastLabel,
|
|
68
|
+
color: forecastColor,
|
|
69
|
+
dashed: true,
|
|
70
|
+
},
|
|
71
|
+
{
|
|
72
|
+
dataKey: 'baseline',
|
|
73
|
+
label: baselineLabel,
|
|
74
|
+
color: baselineColor,
|
|
75
|
+
dotted: true,
|
|
76
|
+
},
|
|
77
|
+
], [
|
|
78
|
+
actualLabel,
|
|
79
|
+
historyColor,
|
|
80
|
+
forecastLabel,
|
|
81
|
+
forecastColor,
|
|
82
|
+
baselineLabel,
|
|
83
|
+
baselineColor,
|
|
84
|
+
]);
|
|
85
|
+
const scores = useMemo(() => [...new Set(windows)]
|
|
86
|
+
.map(months => backtestScore(actuals, origins, months))
|
|
87
|
+
.filter((s) => s !== null), [windows, actuals, origins]);
|
|
88
|
+
const scoreLine = renderScore ??
|
|
89
|
+
((s) => defaultScoreLine(s, formatPercent, baselineLabel));
|
|
90
|
+
return (jsxs("div", { className: cn(S.root, className), children: [jsx(BaseChartWrapper, { className: S.chart, chartData: chartData, historicalLineColor: historyColor, forecastData: forecastData, hiddenSeries: hiddenSeries,
|
|
91
|
+
// Each origin's lines share a month with its neighbours': a tooltip
|
|
92
|
+
// would list them all.
|
|
93
|
+
showTooltip: false, showLegend: false, showEndDots: false, connectHistoryNulls: true, connectForecastNulls: true, renderId: renderId, hasCombinedData: chartData.length > 0, loading: false, isDarkTheme: isDarkTheme, height: height, disableAnimation: disableAnimation, formatNumber: formatNumber, formatDate: formatDate }), chartData.length > 0 ? (jsx(SeriesLegend, { items: legend, hiddenSeries: hiddenGroups, onToggle: toggle })) : null, scores.length > 0 ? (jsx("ul", { className: S.scores, children: scores.map(s => (jsx("li", { children: scoreLine(s) }, s.months))) })) : null] }));
|
|
94
|
+
}
|
|
95
|
+
function defaultScoreLine(s, formatPercent, baselineLabel) {
|
|
96
|
+
// Mid-sentence: the first letter drops its capital, unless the label
|
|
97
|
+
// starts with an acronym ("EUR spot held flat").
|
|
98
|
+
const baseline = /^.[A-Z]/.test(baselineLabel)
|
|
99
|
+
? baselineLabel
|
|
100
|
+
: baselineLabel.charAt(0).toLowerCase() + baselineLabel.slice(1);
|
|
101
|
+
const head = s.errorRemoved === null
|
|
102
|
+
? s.forecastError > 0
|
|
103
|
+
? `more error than the ${baseline}`
|
|
104
|
+
: null
|
|
105
|
+
: formatPercent(Math.abs(s.errorRemoved)) === formatPercent(0)
|
|
106
|
+
? `about the same error as the ${baseline}`
|
|
107
|
+
: s.errorRemoved > 0
|
|
108
|
+
? `removes ${formatPercent(s.errorRemoved)} of the error`
|
|
109
|
+
: `${formatPercent(-s.errorRemoved)} more error than the ${baseline}`;
|
|
110
|
+
return (jsxs(Fragment, { children: [jsxs("strong", { children: ["Last ", s.months, " months:"] }), " ", head ? `${head} · ` : null, "MAPE ", formatPercent(s.forecastError), " forecast,", ' ', formatPercent(s.baselineError), " ", baseline, " (", s.count, ' ', s.count === 1 ? 'forecast' : 'forecasts', ")"] }));
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export { BacktestChart };
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import styleInject from 'style-inject';
|
|
2
|
+
|
|
3
|
+
var css_248z = ".BacktestChart_root__g4-xw{display:flex;flex-direction:column;width:100%}.BacktestChart_scores__dcYZ-{color:var(--muted-foreground);display:flex;flex-direction:column;font-size:.875rem;gap:.25rem;list-style:none;margin:.75rem 0 0;padding:0}.BacktestChart_scores__dcYZ- strong{color:var(--foreground);font-weight:500}.BacktestChart_root__g4-xw .BacktestChart_chart__Ma2JS{min-height:0}";
|
|
4
|
+
var S = {"root":"BacktestChart_root__g4-xw","scores":"BacktestChart_scores__dcYZ-","chart":"BacktestChart_chart__Ma2JS"};
|
|
5
|
+
styleInject(css_248z);
|
|
6
|
+
|
|
7
|
+
export { S as default };
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { HISTORY_SERIES_KEY } from '../../ui/ChartAreaInteractive/chartHistories.js';
|
|
2
|
+
|
|
3
|
+
/** The data key of origin `index`'s forecast line. */
|
|
4
|
+
const backtestForecastKey = (index) => `forecast_${backtestForecastId(index)}`;
|
|
5
|
+
/** The data key of origin `index`'s held-flat line. */
|
|
6
|
+
const backtestBaselineKey = (index) => `forecast_${backtestBaselineId(index)}`;
|
|
7
|
+
const backtestForecastId = (index) => index * 2;
|
|
8
|
+
const backtestBaselineId = (index) => index * 2 + 1;
|
|
9
|
+
/** A date's calendar month as a number (year × 12 + month), or NaN. */
|
|
10
|
+
function monthIndex(date) {
|
|
11
|
+
const m = /^(\d{4})-(\d{2})/.exec(date);
|
|
12
|
+
const month = m ? Number(m[2]) : 0;
|
|
13
|
+
return m && month >= 1 && month <= 12
|
|
14
|
+
? Number(m[1]) * 12 + month - 1
|
|
15
|
+
: Number.NaN;
|
|
16
|
+
}
|
|
17
|
+
/** The first day of month `index` (monthIndex's inverse). */
|
|
18
|
+
function monthStart(index) {
|
|
19
|
+
const y = Math.floor(index / 12);
|
|
20
|
+
const m = (index % 12) + 1;
|
|
21
|
+
return `${String(y).padStart(4, '0')}-${String(m).padStart(2, '0')}-01`;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* The chart's rows, one per calendar month from the first to the last, keyed
|
|
25
|
+
* `YYYY-MM-01` (a month with no value has a row of its own, so the x axis
|
|
26
|
+
* spaces months evenly): the actuals under `historical`, and for each origin
|
|
27
|
+
* its forecast (from the origin's value through every forecast month) and its
|
|
28
|
+
* baseline (the origin's value on the same months), each under its own key.
|
|
29
|
+
* A date that is not `YYYY-MM…` is left out.
|
|
30
|
+
*/
|
|
31
|
+
function buildBacktestRows(actuals, origins) {
|
|
32
|
+
const byMonth = new Map();
|
|
33
|
+
const row = (date) => {
|
|
34
|
+
const i = monthIndex(date);
|
|
35
|
+
if (!Number.isFinite(i))
|
|
36
|
+
return undefined;
|
|
37
|
+
let r = byMonth.get(i);
|
|
38
|
+
if (!r) {
|
|
39
|
+
r = { date: monthStart(i) };
|
|
40
|
+
byMonth.set(i, r);
|
|
41
|
+
}
|
|
42
|
+
return r;
|
|
43
|
+
};
|
|
44
|
+
for (const a of actuals) {
|
|
45
|
+
if (!Number.isFinite(a.value))
|
|
46
|
+
continue;
|
|
47
|
+
const r = row(a.date);
|
|
48
|
+
if (r)
|
|
49
|
+
r[HISTORY_SERIES_KEY] = a.value;
|
|
50
|
+
}
|
|
51
|
+
origins.forEach((o, i) => {
|
|
52
|
+
if (o.forecast.length === 0)
|
|
53
|
+
return;
|
|
54
|
+
const fKey = backtestForecastKey(i);
|
|
55
|
+
const bKey = backtestBaselineKey(i);
|
|
56
|
+
const start = row(o.date);
|
|
57
|
+
if (start) {
|
|
58
|
+
start[fKey] = o.value;
|
|
59
|
+
start[bKey] = o.value;
|
|
60
|
+
}
|
|
61
|
+
for (const p of o.forecast) {
|
|
62
|
+
const r = row(p.date);
|
|
63
|
+
if (!r)
|
|
64
|
+
continue;
|
|
65
|
+
r[fKey] = p.value;
|
|
66
|
+
r[bKey] = o.value;
|
|
67
|
+
}
|
|
68
|
+
});
|
|
69
|
+
if (byMonth.size === 0)
|
|
70
|
+
return [];
|
|
71
|
+
const first = Math.min(...byMonth.keys());
|
|
72
|
+
const last = Math.max(...byMonth.keys());
|
|
73
|
+
const rows = [];
|
|
74
|
+
for (let i = first; i <= last; i++) {
|
|
75
|
+
rows.push(byMonth.get(i) ?? { date: monthStart(i) });
|
|
76
|
+
}
|
|
77
|
+
return rows;
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* The scores for the last `months` calendar months up to the latest actual:
|
|
81
|
+
* every origin whose forecast lands in one of them, against that month's
|
|
82
|
+
* actual. Dates match by calendar month (`2024-03-01` and `2024-03-31` are
|
|
83
|
+
* one month). Null when the actuals span fewer months than the window, or
|
|
84
|
+
* no forecast lands in it with a non-zero actual to compare.
|
|
85
|
+
*/
|
|
86
|
+
function backtestScore(actuals, origins, months) {
|
|
87
|
+
const actualByMonth = new Map();
|
|
88
|
+
for (const a of actuals) {
|
|
89
|
+
const i = monthIndex(a.date);
|
|
90
|
+
if (Number.isFinite(i) && Number.isFinite(a.value)) {
|
|
91
|
+
actualByMonth.set(i, a.value);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
if (months <= 0 || actualByMonth.size === 0)
|
|
95
|
+
return null;
|
|
96
|
+
const last = Math.max(...actualByMonth.keys());
|
|
97
|
+
const first = Math.min(...actualByMonth.keys());
|
|
98
|
+
if (last - first + 1 < months)
|
|
99
|
+
return null;
|
|
100
|
+
const from = last - months + 1;
|
|
101
|
+
let forecastSum = 0;
|
|
102
|
+
let baselineSum = 0;
|
|
103
|
+
let count = 0;
|
|
104
|
+
for (const o of origins) {
|
|
105
|
+
const landing = o.forecast[o.forecast.length - 1];
|
|
106
|
+
if (!landing)
|
|
107
|
+
continue;
|
|
108
|
+
const i = monthIndex(landing.date);
|
|
109
|
+
if (!(i >= from && i <= last))
|
|
110
|
+
continue;
|
|
111
|
+
const actual = actualByMonth.get(i);
|
|
112
|
+
if (actual === undefined || actual === 0 || !Number.isFinite(actual)) {
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
if (!Number.isFinite(landing.value) || !Number.isFinite(o.value))
|
|
116
|
+
continue;
|
|
117
|
+
forecastSum += Math.abs((landing.value - actual) / actual);
|
|
118
|
+
baselineSum += Math.abs((o.value - actual) / actual);
|
|
119
|
+
count += 1;
|
|
120
|
+
}
|
|
121
|
+
if (count === 0)
|
|
122
|
+
return null;
|
|
123
|
+
const forecastError = (forecastSum / count) * 100;
|
|
124
|
+
const baselineError = (baselineSum / count) * 100;
|
|
125
|
+
return {
|
|
126
|
+
months,
|
|
127
|
+
count,
|
|
128
|
+
forecastError,
|
|
129
|
+
baselineError,
|
|
130
|
+
errorRemoved: baselineError > 0 ? (1 - forecastError / baselineError) * 100 : null,
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export { backtestBaselineId, backtestBaselineKey, backtestForecastId, backtestForecastKey, backtestScore, buildBacktestRows };
|
package/dist/esm/src/index.js
CHANGED
|
@@ -24,7 +24,7 @@ export { ChartLegend, ChartTooltip } from './components/ui/Chart/Chart.js';
|
|
|
24
24
|
export { THEMES } from './components/ui/Chart/Chart.types.js';
|
|
25
25
|
export { ChartAreaInteractive, chartConfig } from './components/ui/ChartAreaInteractive/ChartAreaInteractive.js';
|
|
26
26
|
export { DRAG_TIME_RANGE_PREFIX, encodeDragTimeRange, filterDataForTimeRange, findPinPositionForDate, isAnalysisDone, isAnalysisFailed, isAnalysisNotFailed, isTimeRangePreset, longDateFormatter, parseDragTimeRange, shortDateFormatter } from './components/ui/ChartAreaInteractive/ChartAreaInteractive.helpers.js';
|
|
27
|
-
export { ChartLines, FORECAST_COLORS_MAP, FORECAST_LINE_COLORS, getForecastColor, getForecastQuantileBandColor, getHistoryColor, resolveHistoryLines, resolveQuantileBandFillForForecastLine } from './components/ui/ChartAreaInteractive/ChartLines.js';
|
|
27
|
+
export { ChartLines, FORECAST_COLORS_MAP, FORECAST_LINE_COLORS, getForecastColor, getForecastQuantileBandColor, getHistoryColor, lineStyleDasharray, resolveHistoryLines, resolveQuantileBandFillForForecastLine } from './components/ui/ChartAreaInteractive/ChartLines.js';
|
|
28
28
|
export { HISTORY_SERIES_KEY, forecastHistoryKey, historySeriesKey, historySeriesKeys, isHistorySeriesKey } from './components/ui/ChartAreaInteractive/chartHistories.js';
|
|
29
29
|
export { DonutChart } from './components/ui/DonutChart/DonutChart.js';
|
|
30
30
|
export { BarChart } from './components/ui/BarChart/BarChart.js';
|
|
@@ -141,6 +141,8 @@ export { PerformanceChart } from './components/widgets/PerformanceChart/Performa
|
|
|
141
141
|
export { PerformanceTable } from './components/widgets/PerformanceChart/PerformanceTable.js';
|
|
142
142
|
export { SPAGHETTI_DRIFT_PER_HORIZON_ID_BASE, SPAGHETTI_MODEL_PER_HORIZON_ID_BASE, averageForecastErrorsVsHistoricalForMatrixColumn, buildDriftSpaghettiMatrixForCustomDialog, buildPerHorizonSpaghettiEntries, buildSpaghettiMergedChartData, calculateYRangeFromChartData, extendCustomPerformanceDriftSeedToHistoricalEnd, extendCustomPerformanceMatrixWithDriftSeed, getForecastModelDisplayName, latestHistoricalMonthKey, spaghettiGridFromHistoricalPreviousMonth } from './components/widgets/PerformanceChart/performanceChart.helpers.js';
|
|
143
143
|
export { SPAGHETTI_LOCAL_LS_USER_SERIES_ROW_ID, SPAGHETTI_TIME_SERIES_MATRIX_V, tryParseSpaghettiPerformanceMatrix } from './components/widgets/PerformanceChart/performanceChartUserSeries.js';
|
|
144
|
+
export { BacktestChart } from './components/widgets/BacktestChart/BacktestChart.js';
|
|
145
|
+
export { backtestScore, buildBacktestRows } from './components/widgets/BacktestChart/backtestChart.helpers.js';
|
|
144
146
|
export { SybilionAuthLayout } from './components/widgets/SybilionAuthLayout/SybilionAuthLayout.js';
|
|
145
147
|
export { SybilionAuthHeadline } from './components/widgets/SybilionAuthLayout/SybilionAuthHeadline.js';
|
|
146
148
|
export { ChartTooltipItem } from './components/ui/Chart/components/ChartTooltipItem.js';
|