@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
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
import cn from 'classnames';
|
|
2
|
+
import { type ReactNode, useCallback, useMemo, useState } from 'react';
|
|
3
|
+
|
|
4
|
+
import { BaseChartWrapper } from '#uilib/components/ui/Chart/components/BaseChartWrapper';
|
|
5
|
+
import {
|
|
6
|
+
SeriesLegend,
|
|
7
|
+
type SeriesLegendItem,
|
|
8
|
+
} from '#uilib/components/ui/Chart/components/SeriesLegend';
|
|
9
|
+
import type { ForecastItemData } from '#uilib/components/ui/ChartAreaInteractive/ChartLines';
|
|
10
|
+
import { HISTORY_SERIES_KEY } from '#uilib/components/ui/ChartAreaInteractive/chartHistories';
|
|
11
|
+
|
|
12
|
+
import S from './BacktestChart.styl';
|
|
13
|
+
import {
|
|
14
|
+
type BacktestOrigin,
|
|
15
|
+
type BacktestPoint,
|
|
16
|
+
type BacktestScore,
|
|
17
|
+
backtestBaselineId,
|
|
18
|
+
backtestBaselineKey,
|
|
19
|
+
backtestForecastId,
|
|
20
|
+
backtestForecastKey,
|
|
21
|
+
backtestScore,
|
|
22
|
+
buildBacktestRows,
|
|
23
|
+
} from './backtestChart.helpers';
|
|
24
|
+
|
|
25
|
+
/** The legend's three groups; each hides or shows all of its lines. */
|
|
26
|
+
type Group = 'actual' | 'forecast' | 'baseline';
|
|
27
|
+
|
|
28
|
+
const DEFAULT_WINDOWS = [24, 12];
|
|
29
|
+
|
|
30
|
+
const PERCENT = new Intl.NumberFormat('en-GB', { maximumFractionDigits: 1 });
|
|
31
|
+
const defaultFormatPercent = (v: number) => `${PERCENT.format(v)}%`;
|
|
32
|
+
|
|
33
|
+
export type BacktestChartProps = {
|
|
34
|
+
/** The actual values, one per month. */
|
|
35
|
+
actuals: BacktestPoint[];
|
|
36
|
+
/** The past months forecasts were made from, each cut to one horizon. */
|
|
37
|
+
origins: BacktestOrigin[];
|
|
38
|
+
/**
|
|
39
|
+
* The score windows under the chart: the last N calendar months up to the
|
|
40
|
+
* latest actual (default: 24 and 12).
|
|
41
|
+
*/
|
|
42
|
+
windows?: number[];
|
|
43
|
+
actualLabel?: string;
|
|
44
|
+
forecastLabel?: string;
|
|
45
|
+
baselineLabel?: string;
|
|
46
|
+
actualColor?: string;
|
|
47
|
+
forecastColor?: string;
|
|
48
|
+
baselineColor?: string;
|
|
49
|
+
/** One score line; the default says "removes X% of the error". */
|
|
50
|
+
renderScore?: (score: BacktestScore) => ReactNode;
|
|
51
|
+
formatPercent?: (value: number) => string;
|
|
52
|
+
formatNumber?: (value: number) => string;
|
|
53
|
+
formatDate?: (value: string, detailed?: boolean) => string;
|
|
54
|
+
height?: number;
|
|
55
|
+
/** Draw the lines at once, with no animation. */
|
|
56
|
+
disableAnimation?: boolean;
|
|
57
|
+
isDarkTheme?: boolean;
|
|
58
|
+
renderId?: string;
|
|
59
|
+
className?: string;
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* A backtest: the actual values (solid), and from each origin the forecast
|
|
64
|
+
* out to its horizon (dashed, with a dot where it lands) and the last value
|
|
65
|
+
* held flat over the same months (dotted, the baseline). Under it, for each
|
|
66
|
+
* window, how much of the baseline's error the forecast removes.
|
|
67
|
+
*/
|
|
68
|
+
export function BacktestChart({
|
|
69
|
+
actuals,
|
|
70
|
+
origins,
|
|
71
|
+
windows = DEFAULT_WINDOWS,
|
|
72
|
+
actualLabel = 'Actual',
|
|
73
|
+
forecastLabel = 'Forecast',
|
|
74
|
+
baselineLabel = 'Last price held flat',
|
|
75
|
+
actualColor,
|
|
76
|
+
forecastColor = 'var(--sb-cyan-400)',
|
|
77
|
+
baselineColor = 'var(--sb-gray-400)',
|
|
78
|
+
renderScore,
|
|
79
|
+
formatPercent = defaultFormatPercent,
|
|
80
|
+
formatNumber,
|
|
81
|
+
formatDate,
|
|
82
|
+
height = 300,
|
|
83
|
+
disableAnimation = false,
|
|
84
|
+
isDarkTheme = false,
|
|
85
|
+
renderId = 'backtest',
|
|
86
|
+
className,
|
|
87
|
+
}: BacktestChartProps) {
|
|
88
|
+
const [hiddenGroups, setHiddenGroups] = useState<ReadonlySet<Group>>(
|
|
89
|
+
() => new Set(),
|
|
90
|
+
);
|
|
91
|
+
const toggle = useCallback((group: string) => {
|
|
92
|
+
setHiddenGroups(prev => {
|
|
93
|
+
const next = new Set(prev);
|
|
94
|
+
if (next.has(group as Group)) next.delete(group as Group);
|
|
95
|
+
else next.add(group as Group);
|
|
96
|
+
return next;
|
|
97
|
+
});
|
|
98
|
+
}, []);
|
|
99
|
+
|
|
100
|
+
const chartData = useMemo(
|
|
101
|
+
() => buildBacktestRows(actuals, origins),
|
|
102
|
+
[actuals, origins],
|
|
103
|
+
);
|
|
104
|
+
const historyColor = actualColor ?? (isDarkTheme ? '#ffffff' : '#000000');
|
|
105
|
+
|
|
106
|
+
const forecastData = useMemo<ForecastItemData[]>(
|
|
107
|
+
() =>
|
|
108
|
+
origins.flatMap((_, i) => [
|
|
109
|
+
// The baseline first, so each forecast is drawn over it.
|
|
110
|
+
{
|
|
111
|
+
id: backtestBaselineId(i),
|
|
112
|
+
name: baselineLabel,
|
|
113
|
+
color: baselineColor,
|
|
114
|
+
lineStyle: 'dotted' as const,
|
|
115
|
+
endDot: false,
|
|
116
|
+
},
|
|
117
|
+
{
|
|
118
|
+
id: backtestForecastId(i),
|
|
119
|
+
name: forecastLabel,
|
|
120
|
+
color: forecastColor,
|
|
121
|
+
lineStyle: 'dashed' as const,
|
|
122
|
+
endDot: true,
|
|
123
|
+
},
|
|
124
|
+
]),
|
|
125
|
+
[origins, baselineLabel, baselineColor, forecastLabel, forecastColor],
|
|
126
|
+
);
|
|
127
|
+
|
|
128
|
+
// The chart hides lines by data key; the legend hides whole groups.
|
|
129
|
+
const hiddenSeries = useMemo(() => {
|
|
130
|
+
const keys = new Set<string>();
|
|
131
|
+
if (hiddenGroups.has('actual')) keys.add(HISTORY_SERIES_KEY);
|
|
132
|
+
origins.forEach((_, i) => {
|
|
133
|
+
if (hiddenGroups.has('forecast')) keys.add(backtestForecastKey(i));
|
|
134
|
+
if (hiddenGroups.has('baseline')) keys.add(backtestBaselineKey(i));
|
|
135
|
+
});
|
|
136
|
+
return keys;
|
|
137
|
+
}, [hiddenGroups, origins]);
|
|
138
|
+
|
|
139
|
+
const legend = useMemo<SeriesLegendItem[]>(
|
|
140
|
+
() => [
|
|
141
|
+
{ dataKey: 'actual', label: actualLabel, color: historyColor },
|
|
142
|
+
{
|
|
143
|
+
dataKey: 'forecast',
|
|
144
|
+
label: forecastLabel,
|
|
145
|
+
color: forecastColor,
|
|
146
|
+
dashed: true,
|
|
147
|
+
},
|
|
148
|
+
{
|
|
149
|
+
dataKey: 'baseline',
|
|
150
|
+
label: baselineLabel,
|
|
151
|
+
color: baselineColor,
|
|
152
|
+
dotted: true,
|
|
153
|
+
},
|
|
154
|
+
],
|
|
155
|
+
[
|
|
156
|
+
actualLabel,
|
|
157
|
+
historyColor,
|
|
158
|
+
forecastLabel,
|
|
159
|
+
forecastColor,
|
|
160
|
+
baselineLabel,
|
|
161
|
+
baselineColor,
|
|
162
|
+
],
|
|
163
|
+
);
|
|
164
|
+
|
|
165
|
+
const scores = useMemo(
|
|
166
|
+
() =>
|
|
167
|
+
[...new Set(windows)]
|
|
168
|
+
.map(months => backtestScore(actuals, origins, months))
|
|
169
|
+
.filter((s): s is BacktestScore => s !== null),
|
|
170
|
+
[windows, actuals, origins],
|
|
171
|
+
);
|
|
172
|
+
|
|
173
|
+
const scoreLine =
|
|
174
|
+
renderScore ??
|
|
175
|
+
((s: BacktestScore) => defaultScoreLine(s, formatPercent, baselineLabel));
|
|
176
|
+
|
|
177
|
+
return (
|
|
178
|
+
<div className={cn(S.root, className)}>
|
|
179
|
+
<BaseChartWrapper
|
|
180
|
+
className={S.chart}
|
|
181
|
+
chartData={chartData}
|
|
182
|
+
historicalLineColor={historyColor}
|
|
183
|
+
forecastData={forecastData}
|
|
184
|
+
hiddenSeries={hiddenSeries}
|
|
185
|
+
// Each origin's lines share a month with its neighbours': a tooltip
|
|
186
|
+
// would list them all.
|
|
187
|
+
showTooltip={false}
|
|
188
|
+
showLegend={false}
|
|
189
|
+
showEndDots={false}
|
|
190
|
+
connectHistoryNulls
|
|
191
|
+
connectForecastNulls
|
|
192
|
+
renderId={renderId}
|
|
193
|
+
hasCombinedData={chartData.length > 0}
|
|
194
|
+
loading={false}
|
|
195
|
+
isDarkTheme={isDarkTheme}
|
|
196
|
+
height={height}
|
|
197
|
+
disableAnimation={disableAnimation}
|
|
198
|
+
formatNumber={formatNumber}
|
|
199
|
+
formatDate={formatDate}
|
|
200
|
+
/>
|
|
201
|
+
{chartData.length > 0 ? (
|
|
202
|
+
<SeriesLegend
|
|
203
|
+
items={legend}
|
|
204
|
+
hiddenSeries={hiddenGroups as ReadonlySet<string>}
|
|
205
|
+
onToggle={toggle}
|
|
206
|
+
/>
|
|
207
|
+
) : null}
|
|
208
|
+
{scores.length > 0 ? (
|
|
209
|
+
<ul className={S.scores}>
|
|
210
|
+
{scores.map(s => (
|
|
211
|
+
<li key={s.months}>{scoreLine(s)}</li>
|
|
212
|
+
))}
|
|
213
|
+
</ul>
|
|
214
|
+
) : null}
|
|
215
|
+
</div>
|
|
216
|
+
);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function defaultScoreLine(
|
|
220
|
+
s: BacktestScore,
|
|
221
|
+
formatPercent: (value: number) => string,
|
|
222
|
+
baselineLabel: string,
|
|
223
|
+
): ReactNode {
|
|
224
|
+
// Mid-sentence: the first letter drops its capital, unless the label
|
|
225
|
+
// starts with an acronym ("EUR spot held flat").
|
|
226
|
+
const baseline = /^.[A-Z]/.test(baselineLabel)
|
|
227
|
+
? baselineLabel
|
|
228
|
+
: baselineLabel.charAt(0).toLowerCase() + baselineLabel.slice(1);
|
|
229
|
+
const head =
|
|
230
|
+
s.errorRemoved === null
|
|
231
|
+
? s.forecastError > 0
|
|
232
|
+
? `more error than the ${baseline}`
|
|
233
|
+
: null
|
|
234
|
+
: formatPercent(Math.abs(s.errorRemoved)) === formatPercent(0)
|
|
235
|
+
? `about the same error as the ${baseline}`
|
|
236
|
+
: s.errorRemoved > 0
|
|
237
|
+
? `removes ${formatPercent(s.errorRemoved)} of the error`
|
|
238
|
+
: `${formatPercent(-s.errorRemoved)} more error than the ${baseline}`;
|
|
239
|
+
return (
|
|
240
|
+
<>
|
|
241
|
+
<strong>Last {s.months} months:</strong> {head ? `${head} · ` : null}
|
|
242
|
+
MAPE {formatPercent(s.forecastError)} forecast,{' '}
|
|
243
|
+
{formatPercent(s.baselineError)} {baseline} ({s.count}{' '}
|
|
244
|
+
{s.count === 1 ? 'forecast' : 'forecasts'})
|
|
245
|
+
</>
|
|
246
|
+
);
|
|
247
|
+
}
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import type { ChartDataPoint } from '#uilib/components/ui/ChartAreaInteractive/ChartAreaInteractive.types';
|
|
2
|
+
import { HISTORY_SERIES_KEY } from '#uilib/components/ui/ChartAreaInteractive/chartHistories';
|
|
3
|
+
|
|
4
|
+
/** One month's value: `date` is a sortable ISO date (`2024-03-01`). */
|
|
5
|
+
export type BacktestPoint = { date: string; value: number };
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* One backtest origin: a past month a forecast was made from.
|
|
9
|
+
* The baseline holds `value`, the last price known then, flat over the
|
|
10
|
+
* forecast's months.
|
|
11
|
+
*/
|
|
12
|
+
export type BacktestOrigin = {
|
|
13
|
+
/** The month the forecast was made in: the last month with a known value. */
|
|
14
|
+
date: string;
|
|
15
|
+
/** The value known at `date`, held flat as the baseline. */
|
|
16
|
+
value: number;
|
|
17
|
+
/**
|
|
18
|
+
* The forecast for the months after `date`, in date order. Its last point
|
|
19
|
+
* is where it lands: the month the scores compare with the actual value.
|
|
20
|
+
*/
|
|
21
|
+
forecast: BacktestPoint[];
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
/** One window's scores: mean absolute percentage error at the landing month. */
|
|
25
|
+
export type BacktestScore = {
|
|
26
|
+
/** The window: the last `months` calendar months up to the latest actual. */
|
|
27
|
+
months: number;
|
|
28
|
+
/** How many forecasts landed in the window with an actual to compare. */
|
|
29
|
+
count: number;
|
|
30
|
+
/** The forecast's MAPE, in percent. */
|
|
31
|
+
forecastError: number;
|
|
32
|
+
/** The held-flat baseline's MAPE, in percent. */
|
|
33
|
+
baselineError: number;
|
|
34
|
+
/**
|
|
35
|
+
* How much of the baseline's error the forecast removes, in percent
|
|
36
|
+
* (negative: the forecast has more error). Null when the baseline has none.
|
|
37
|
+
*/
|
|
38
|
+
errorRemoved: number | null;
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
/** The data key of origin `index`'s forecast line. */
|
|
42
|
+
export const backtestForecastKey = (index: number) =>
|
|
43
|
+
`forecast_${backtestForecastId(index)}`;
|
|
44
|
+
/** The data key of origin `index`'s held-flat line. */
|
|
45
|
+
export const backtestBaselineKey = (index: number) =>
|
|
46
|
+
`forecast_${backtestBaselineId(index)}`;
|
|
47
|
+
export const backtestForecastId = (index: number) => index * 2;
|
|
48
|
+
export const backtestBaselineId = (index: number) => index * 2 + 1;
|
|
49
|
+
|
|
50
|
+
/** A date's calendar month as a number (year × 12 + month), or NaN. */
|
|
51
|
+
function monthIndex(date: string): number {
|
|
52
|
+
const m = /^(\d{4})-(\d{2})/.exec(date);
|
|
53
|
+
const month = m ? Number(m[2]) : 0;
|
|
54
|
+
return m && month >= 1 && month <= 12
|
|
55
|
+
? Number(m[1]) * 12 + month - 1
|
|
56
|
+
: Number.NaN;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** The first day of month `index` (monthIndex's inverse). */
|
|
60
|
+
function monthStart(index: number): string {
|
|
61
|
+
const y = Math.floor(index / 12);
|
|
62
|
+
const m = (index % 12) + 1;
|
|
63
|
+
return `${String(y).padStart(4, '0')}-${String(m).padStart(2, '0')}-01`;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* The chart's rows, one per calendar month from the first to the last, keyed
|
|
68
|
+
* `YYYY-MM-01` (a month with no value has a row of its own, so the x axis
|
|
69
|
+
* spaces months evenly): the actuals under `historical`, and for each origin
|
|
70
|
+
* its forecast (from the origin's value through every forecast month) and its
|
|
71
|
+
* baseline (the origin's value on the same months), each under its own key.
|
|
72
|
+
* A date that is not `YYYY-MM…` is left out.
|
|
73
|
+
*/
|
|
74
|
+
export function buildBacktestRows(
|
|
75
|
+
actuals: BacktestPoint[],
|
|
76
|
+
origins: BacktestOrigin[],
|
|
77
|
+
): ChartDataPoint[] {
|
|
78
|
+
const byMonth = new Map<number, ChartDataPoint>();
|
|
79
|
+
const row = (date: string) => {
|
|
80
|
+
const i = monthIndex(date);
|
|
81
|
+
if (!Number.isFinite(i)) return undefined;
|
|
82
|
+
let r = byMonth.get(i);
|
|
83
|
+
if (!r) {
|
|
84
|
+
r = { date: monthStart(i) };
|
|
85
|
+
byMonth.set(i, r);
|
|
86
|
+
}
|
|
87
|
+
return r;
|
|
88
|
+
};
|
|
89
|
+
for (const a of actuals) {
|
|
90
|
+
if (!Number.isFinite(a.value)) continue;
|
|
91
|
+
const r = row(a.date);
|
|
92
|
+
if (r) r[HISTORY_SERIES_KEY] = a.value;
|
|
93
|
+
}
|
|
94
|
+
origins.forEach((o, i) => {
|
|
95
|
+
if (o.forecast.length === 0) return;
|
|
96
|
+
const fKey = backtestForecastKey(i);
|
|
97
|
+
const bKey = backtestBaselineKey(i);
|
|
98
|
+
const start = row(o.date);
|
|
99
|
+
if (start) {
|
|
100
|
+
start[fKey] = o.value;
|
|
101
|
+
start[bKey] = o.value;
|
|
102
|
+
}
|
|
103
|
+
for (const p of o.forecast) {
|
|
104
|
+
const r = row(p.date);
|
|
105
|
+
if (!r) continue;
|
|
106
|
+
r[fKey] = p.value;
|
|
107
|
+
r[bKey] = o.value;
|
|
108
|
+
}
|
|
109
|
+
});
|
|
110
|
+
if (byMonth.size === 0) return [];
|
|
111
|
+
const first = Math.min(...byMonth.keys());
|
|
112
|
+
const last = Math.max(...byMonth.keys());
|
|
113
|
+
const rows: ChartDataPoint[] = [];
|
|
114
|
+
for (let i = first; i <= last; i++) {
|
|
115
|
+
rows.push(byMonth.get(i) ?? { date: monthStart(i) });
|
|
116
|
+
}
|
|
117
|
+
return rows;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* The scores for the last `months` calendar months up to the latest actual:
|
|
122
|
+
* every origin whose forecast lands in one of them, against that month's
|
|
123
|
+
* actual. Dates match by calendar month (`2024-03-01` and `2024-03-31` are
|
|
124
|
+
* one month). Null when the actuals span fewer months than the window, or
|
|
125
|
+
* no forecast lands in it with a non-zero actual to compare.
|
|
126
|
+
*/
|
|
127
|
+
export function backtestScore(
|
|
128
|
+
actuals: BacktestPoint[],
|
|
129
|
+
origins: BacktestOrigin[],
|
|
130
|
+
months: number,
|
|
131
|
+
): BacktestScore | null {
|
|
132
|
+
const actualByMonth = new Map<number, number>();
|
|
133
|
+
for (const a of actuals) {
|
|
134
|
+
const i = monthIndex(a.date);
|
|
135
|
+
if (Number.isFinite(i) && Number.isFinite(a.value)) {
|
|
136
|
+
actualByMonth.set(i, a.value);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
if (months <= 0 || actualByMonth.size === 0) return null;
|
|
140
|
+
const last = Math.max(...actualByMonth.keys());
|
|
141
|
+
const first = Math.min(...actualByMonth.keys());
|
|
142
|
+
if (last - first + 1 < months) return null;
|
|
143
|
+
const from = last - months + 1;
|
|
144
|
+
let forecastSum = 0;
|
|
145
|
+
let baselineSum = 0;
|
|
146
|
+
let count = 0;
|
|
147
|
+
for (const o of origins) {
|
|
148
|
+
const landing = o.forecast[o.forecast.length - 1];
|
|
149
|
+
if (!landing) continue;
|
|
150
|
+
const i = monthIndex(landing.date);
|
|
151
|
+
if (!(i >= from && i <= last)) continue;
|
|
152
|
+
const actual = actualByMonth.get(i);
|
|
153
|
+
if (actual === undefined || actual === 0 || !Number.isFinite(actual)) {
|
|
154
|
+
continue;
|
|
155
|
+
}
|
|
156
|
+
if (!Number.isFinite(landing.value) || !Number.isFinite(o.value)) continue;
|
|
157
|
+
forecastSum += Math.abs((landing.value - actual) / actual);
|
|
158
|
+
baselineSum += Math.abs((o.value - actual) / actual);
|
|
159
|
+
count += 1;
|
|
160
|
+
}
|
|
161
|
+
if (count === 0) return null;
|
|
162
|
+
const forecastError = (forecastSum / count) * 100;
|
|
163
|
+
const baselineError = (baselineSum / count) * 100;
|
|
164
|
+
return {
|
|
165
|
+
months,
|
|
166
|
+
count,
|
|
167
|
+
forecastError,
|
|
168
|
+
baselineError,
|
|
169
|
+
errorRemoved:
|
|
170
|
+
baselineError > 0 ? (1 - forecastError / baselineError) * 100 : null,
|
|
171
|
+
};
|
|
172
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { useMemo, useState } from 'react';
|
|
2
|
+
|
|
3
|
+
import { PageContentSection } from '#uilib/components/ui/Page';
|
|
4
|
+
import { Tabs, TabsList, TabsTrigger } from '#uilib/components/ui/Tabs';
|
|
5
|
+
import {
|
|
6
|
+
BacktestChart,
|
|
7
|
+
type BacktestOrigin,
|
|
8
|
+
type BacktestPoint,
|
|
9
|
+
} from '#uilib/components/widgets/BacktestChart';
|
|
10
|
+
import BacktestChartGuidance from '#uilib/components/widgets/BacktestChart/AGENT.md';
|
|
11
|
+
import { useTheme } from '#uilib/contexts/theme-context';
|
|
12
|
+
|
|
13
|
+
import { AppPageHeader } from '../components/AppPageHeader/AppPageHeader';
|
|
14
|
+
import { DocsGuidance } from '../components/DocsGuidance/DocsGuidance';
|
|
15
|
+
import { DocsHeaderActions } from '../docsHeaderActions';
|
|
16
|
+
|
|
17
|
+
const HORIZONS = [1, 3, 6] as const;
|
|
18
|
+
|
|
19
|
+
function monthKey(i: number): string {
|
|
20
|
+
const y = 2021 + Math.floor(i / 12);
|
|
21
|
+
return `${y}-${String((i % 12) + 1).padStart(2, '0')}-01`;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** An invented monthly price. */
|
|
25
|
+
const ACTUALS: BacktestPoint[] = Array.from({ length: 48 }, (_, i) => ({
|
|
26
|
+
date: monthKey(i),
|
|
27
|
+
value: 100 + i * 0.8 + Math.sin(i * 0.45) * 9,
|
|
28
|
+
}));
|
|
29
|
+
|
|
30
|
+
/** A forecast that sees the trend and part of the swing, made each month. */
|
|
31
|
+
function buildOrigins(horizon: number): BacktestOrigin[] {
|
|
32
|
+
const origins: BacktestOrigin[] = [];
|
|
33
|
+
for (let o = 12; o + horizon < ACTUALS.length; o++) {
|
|
34
|
+
origins.push({
|
|
35
|
+
date: ACTUALS[o].date,
|
|
36
|
+
value: ACTUALS[o].value,
|
|
37
|
+
forecast: Array.from({ length: horizon }, (_, k) => {
|
|
38
|
+
const i = o + k + 1;
|
|
39
|
+
return {
|
|
40
|
+
date: ACTUALS[i].date,
|
|
41
|
+
value: 100 + i * 0.8 + Math.sin(i * 0.45 - 0.3) * 7,
|
|
42
|
+
};
|
|
43
|
+
}),
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
return origins;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export default function BacktestChartPage() {
|
|
50
|
+
const { isDarkMode } = useTheme();
|
|
51
|
+
const [horizon, setHorizon] = useState<number>(3);
|
|
52
|
+
const origins = useMemo(() => buildOrigins(horizon), [horizon]);
|
|
53
|
+
return (
|
|
54
|
+
<>
|
|
55
|
+
<AppPageHeader
|
|
56
|
+
breadcrumbs={[{ label: 'Backtest chart' }]}
|
|
57
|
+
title="BacktestChart"
|
|
58
|
+
subheader="Past forecasts for one horizon against the last value held flat, with how much of its error they remove."
|
|
59
|
+
actions={<DocsHeaderActions />}
|
|
60
|
+
/>
|
|
61
|
+
<DocsGuidance source={BacktestChartGuidance} />
|
|
62
|
+
<PageContentSection>
|
|
63
|
+
<div
|
|
64
|
+
style={{
|
|
65
|
+
display: 'flex',
|
|
66
|
+
flexDirection: 'column',
|
|
67
|
+
gap: 16,
|
|
68
|
+
width: '100%',
|
|
69
|
+
}}
|
|
70
|
+
>
|
|
71
|
+
<Tabs
|
|
72
|
+
value={String(horizon)}
|
|
73
|
+
onValueChange={v => setHorizon(Number(v))}
|
|
74
|
+
>
|
|
75
|
+
<TabsList>
|
|
76
|
+
{HORIZONS.map(h => (
|
|
77
|
+
<TabsTrigger key={h} value={String(h)}>
|
|
78
|
+
{h}m
|
|
79
|
+
</TabsTrigger>
|
|
80
|
+
))}
|
|
81
|
+
</TabsList>
|
|
82
|
+
</Tabs>
|
|
83
|
+
<BacktestChart
|
|
84
|
+
key={horizon}
|
|
85
|
+
actuals={ACTUALS}
|
|
86
|
+
origins={origins}
|
|
87
|
+
isDarkTheme={isDarkMode}
|
|
88
|
+
formatNumber={v => v.toFixed(0)}
|
|
89
|
+
/>
|
|
90
|
+
</div>
|
|
91
|
+
</PageContentSection>
|
|
92
|
+
</>
|
|
93
|
+
);
|
|
94
|
+
}
|
|
@@ -48,6 +48,20 @@ const PAID: StackedAreaChartOverlay[] = [
|
|
|
48
48
|
{ key: 'paid', label: 'Prices paid', compare: true },
|
|
49
49
|
];
|
|
50
50
|
|
|
51
|
+
// One price paid in the window, next to a market line.
|
|
52
|
+
const ONE_PAID_ROWS: StackedAreaChartDatum[] = COST_ROWS.slice(24).map(
|
|
53
|
+
(row, i) => ({
|
|
54
|
+
...row,
|
|
55
|
+
paid: i === 7 ? 3.4 : null,
|
|
56
|
+
market: Number((3.1 + 0.2 * Math.sin(i / 2)).toFixed(2)),
|
|
57
|
+
}),
|
|
58
|
+
);
|
|
59
|
+
|
|
60
|
+
const ONE_PAID_OVERLAYS: StackedAreaChartOverlay[] = [
|
|
61
|
+
{ key: 'market', label: 'Market', color: 'var(--muted-foreground)' },
|
|
62
|
+
{ key: 'paid', label: 'Prices paid', dotLonePoints: true },
|
|
63
|
+
];
|
|
64
|
+
|
|
51
65
|
const QUARTER_ROWS: StackedAreaChartDatum[] = [
|
|
52
66
|
{
|
|
53
67
|
quarter: 'Q1',
|
|
@@ -121,6 +135,22 @@ export default function StackedAreaChartPage() {
|
|
|
121
135
|
height={320}
|
|
122
136
|
/>
|
|
123
137
|
</PageContentSection>
|
|
138
|
+
<PageContentSection>
|
|
139
|
+
<SectionHeader
|
|
140
|
+
title="A lone price"
|
|
141
|
+
description="A market line, and a single price paid shown as a dot with dotLonePoints (a line with one value draws nothing)."
|
|
142
|
+
withMargin
|
|
143
|
+
/>
|
|
144
|
+
<StackedAreaChart
|
|
145
|
+
data={ONE_PAID_ROWS}
|
|
146
|
+
xKey="date"
|
|
147
|
+
layers={COST_LAYERS}
|
|
148
|
+
overlays={ONE_PAID_OVERLAYS}
|
|
149
|
+
valueFormatter={formatPrice}
|
|
150
|
+
tooltipLabelFormatter={formatMonth}
|
|
151
|
+
height={260}
|
|
152
|
+
/>
|
|
153
|
+
</PageContentSection>
|
|
124
154
|
<PageContentSection>
|
|
125
155
|
<SectionHeader
|
|
126
156
|
title="Few points"
|
package/src/docs/registry.ts
CHANGED
|
@@ -308,6 +308,12 @@ export const DOC_REGISTRY: DocEntry[] = [
|
|
|
308
308
|
section: 'Widgets',
|
|
309
309
|
load: () => import('./pages/DriverMapPage'),
|
|
310
310
|
},
|
|
311
|
+
{
|
|
312
|
+
slug: 'backtest-chart',
|
|
313
|
+
title: 'BacktestChart',
|
|
314
|
+
section: 'Widgets',
|
|
315
|
+
load: () => import('./pages/BacktestChartPage'),
|
|
316
|
+
},
|
|
311
317
|
{
|
|
312
318
|
slug: 'drivers-comparison-chart',
|
|
313
319
|
title: 'DriversComparisonChart',
|
package/src/index.ts
CHANGED
|
@@ -86,5 +86,6 @@ export * from './components/widgets/DriverCard';
|
|
|
86
86
|
export * from './components/widgets/DriverMap';
|
|
87
87
|
export * from './components/widgets/DriversComparisonChart';
|
|
88
88
|
export * from './components/widgets/PerformanceChart';
|
|
89
|
+
export * from './components/widgets/BacktestChart';
|
|
89
90
|
export * from './components/widgets/SybilionAuthLayout';
|
|
90
91
|
// SPA/router widgets (react-router-dom): `@sybilion/uilib/signin`
|