@numero-uno-jpn/rstats 1.19.0 → 1.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +38 -0
- package/README.ja.md +6 -6
- package/README.md +6 -6
- package/dist/causal.js +2 -2
- package/dist/chunks/chunk-33ODAPMR.js +2 -0
- package/dist/chunks/chunk-3ST6RZXG.js +2 -0
- package/dist/chunks/{chunk-FAKOND5W.js → chunk-4EQN74JN.js} +2 -2
- package/dist/chunks/chunk-5RRFO4NU.js +2 -0
- package/dist/chunks/{chunk-ILQ4VWSD.js → chunk-64DDDGJU.js} +2 -2
- package/dist/chunks/chunk-66TEOHPF.js +2 -0
- package/dist/chunks/chunk-6ISDROPG.js +2 -0
- package/dist/chunks/{chunk-OTETSONJ.js → chunk-6LAKI2QG.js} +2 -2
- package/dist/chunks/{chunk-SJJJ7Y4X.js → chunk-6QCH4LAL.js} +2 -2
- package/dist/chunks/{chunk-FCGTZ6BD.js → chunk-6RA73LXX.js} +2 -2
- package/dist/chunks/{chunk-MPBFXHXT.js → chunk-7C2ECGT6.js} +1 -1
- package/dist/chunks/{chunk-QH4GK3JN.js → chunk-7KPFNJBE.js} +2 -2
- package/dist/chunks/chunk-ARPXG2PG.js +2 -0
- package/dist/chunks/chunk-AWXW4WSX.js +2 -0
- package/dist/chunks/{chunk-WWRKCRTZ.js → chunk-B5GSH3AK.js} +1 -1
- package/dist/chunks/{chunk-XHHDBEHB.js → chunk-BLDLJHUG.js} +2 -2
- package/dist/chunks/{chunk-ANFN3X2M.js → chunk-BU4I544S.js} +2 -2
- package/dist/chunks/{chunk-LWFKGF43.js → chunk-CAUNJ7S6.js} +2 -2
- package/dist/chunks/chunk-DFGW4QWU.js +2 -0
- package/dist/chunks/{chunk-MOYWWJP4.js → chunk-DPCCSFCG.js} +1 -1
- package/dist/chunks/chunk-EXS5QD7V.js +2 -0
- package/dist/chunks/chunk-FOCHNNP3.js +2 -0
- package/dist/chunks/{chunk-VNLSP22M.js → chunk-HEPGGURG.js} +2 -2
- package/dist/chunks/chunk-INNFAVT3.js +2 -0
- package/dist/chunks/chunk-JEELIABM.js +2 -0
- package/dist/chunks/chunk-KNF2GPJV.js +2 -0
- package/dist/chunks/chunk-L4ZS7MAX.js +2 -0
- package/dist/chunks/{chunk-7D7FBLWD.js → chunk-LZAB4M7P.js} +2 -2
- package/dist/chunks/chunk-LZTDYQRS.js +3 -0
- package/dist/chunks/{chunk-AS2XTRHH.js → chunk-MTSU2QHB.js} +2 -2
- package/dist/chunks/{chunk-5NW4WT4F.js → chunk-MXRN2G7O.js} +2 -2
- package/dist/chunks/chunk-OFDD4GTZ.js +2 -0
- package/dist/chunks/chunk-OOHFFLMY.js +2 -0
- package/dist/chunks/chunk-OOO5AAM7.js +2 -0
- package/dist/chunks/chunk-PJJJR3H6.js +2 -0
- package/dist/chunks/chunk-PVRNAOO7.js +2 -0
- package/dist/chunks/chunk-Q2JLU5YD.js +2 -0
- package/dist/chunks/{chunk-SAFH76DR.js → chunk-QCQBK5AC.js} +2 -2
- package/dist/chunks/chunk-RXK4KSKH.js +2 -0
- package/dist/chunks/chunk-UC3YYJHM.js +4 -0
- package/dist/chunks/chunk-UPACHZ4F.js +2 -0
- package/dist/chunks/{chunk-DXSVV47D.js → chunk-VCXPGCA4.js} +2 -2
- package/dist/chunks/chunk-VFL4GGYT.js +2 -0
- package/dist/chunks/chunk-VL72MQOQ.js +2 -0
- package/dist/chunks/chunk-VSV5QGXX.js +2 -0
- package/dist/chunks/{chunk-U6RXYALO.js → chunk-WMEF5XWO.js} +2 -2
- package/dist/chunks/chunk-X6JS6ZZB.js +2 -0
- package/dist/chunks/chunk-YEDVOX5V.js +2 -0
- package/dist/chunks/chunk-ZCTB4N5J.js +3 -0
- package/dist/descriptive.js +2 -2
- package/dist/distributions.js +2 -2
- package/dist/entries/tests.d.ts +5 -0
- package/dist/entries/tests.js +5 -0
- package/dist/entries/timeseries.d.ts +11 -0
- package/dist/entries/timeseries.js +11 -0
- package/dist/linalg.js +2 -2
- package/dist/meta/metabin.d.ts +32 -0
- package/dist/meta/metabin.js +137 -0
- package/dist/meta/metaextra.d.ts +153 -0
- package/dist/meta/metaextra.js +290 -0
- package/dist/meta/metagen.d.ts +124 -0
- package/dist/meta/metagen.js +263 -0
- package/dist/meta/metaother.d.ts +87 -0
- package/dist/meta/metaother.js +342 -0
- package/dist/meta/netmeta.d.ts +256 -0
- package/dist/meta/netmeta.js +547 -0
- package/dist/mixed.js +3 -4
- package/dist/models/glmFamily.js +4 -1
- package/dist/models/metaAnalysis.d.ts +4 -0
- package/dist/models/metaAnalysis.js +100 -18
- package/dist/multivariate.js +2 -2
- package/dist/numerics.js +2 -2
- package/dist/regression.js +2 -2
- package/dist/rstats.js +20 -18
- package/dist/special.js +2 -2
- package/dist/tests.js +15 -15
- package/dist/timeseries/acf.js +5 -2
- package/dist/timeseries/arima.d.ts +154 -0
- package/dist/timeseries/arima.js +1007 -0
- package/dist/timeseries/autoArima.d.ts +70 -0
- package/dist/timeseries/autoArima.js +191 -0
- package/dist/timeseries/ets.d.ts +158 -0
- package/dist/timeseries/ets.js +883 -0
- package/dist/timeseries/forecastArima.d.ts +136 -0
- package/dist/timeseries/forecastArima.js +432 -0
- package/dist/timeseries/forecastDispatch.d.ts +83 -0
- package/dist/timeseries/forecastDispatch.js +130 -0
- package/dist/timeseries/forecastSimple.d.ts +177 -0
- package/dist/timeseries/forecastSimple.js +371 -0
- package/dist/timeseries/forecastUtils.d.ts +260 -0
- package/dist/timeseries/forecastUtils.js +619 -0
- package/dist/timeseries/holtWinters.d.ts +65 -0
- package/dist/timeseries/holtWinters.js +193 -0
- package/dist/timeseries/input.d.ts +8 -0
- package/dist/timeseries/input.js +27 -0
- package/dist/timeseries/ocsbCritical.d.ts +2 -0
- package/dist/timeseries/ocsbCritical.js +6 -0
- package/dist/timeseries/scale.d.ts +16 -0
- package/dist/timeseries/scale.js +48 -0
- package/dist/timeseries/statsTs.d.ts +128 -0
- package/dist/timeseries/statsTs.js +456 -0
- package/dist/timeseries/stl.d.ts +131 -0
- package/dist/timeseries/stl.js +489 -0
- package/dist/timeseries/tseries.d.ts +110 -0
- package/dist/timeseries/tseries.js +369 -0
- package/dist/timeseries.js +2 -2
- package/package.json +1 -1
- package/dist/chunks/chunk-2S45NNTL.js +0 -2
- package/dist/chunks/chunk-4JFGT4PN.js +0 -2
- package/dist/chunks/chunk-4JRJU5F5.js +0 -2
- package/dist/chunks/chunk-6ZGEYAFC.js +0 -2
- package/dist/chunks/chunk-BJ5WAL2C.js +0 -2
- package/dist/chunks/chunk-CEOSH3H2.js +0 -2
- package/dist/chunks/chunk-CMNKXRZF.js +0 -3
- package/dist/chunks/chunk-CNJLPH6W.js +0 -2
- package/dist/chunks/chunk-FELX2TZZ.js +0 -2
- package/dist/chunks/chunk-G4B2SQR6.js +0 -4
- package/dist/chunks/chunk-HPIZAWMT.js +0 -2
- package/dist/chunks/chunk-I5XUWUEV.js +0 -2
- package/dist/chunks/chunk-JLFRYDYO.js +0 -2
- package/dist/chunks/chunk-JXKHFSGK.js +0 -2
- package/dist/chunks/chunk-LBU73UMS.js +0 -2
- package/dist/chunks/chunk-LSZTDKIB.js +0 -2
- package/dist/chunks/chunk-M5J3DHXB.js +0 -2
- package/dist/chunks/chunk-NWNJEAKI.js +0 -2
- package/dist/chunks/chunk-QVE7V5UG.js +0 -2
- package/dist/chunks/chunk-RMGEIU4Z.js +0 -2
- package/dist/chunks/chunk-TVU4N6BA.js +0 -2
- package/dist/chunks/chunk-W4EITKLJ.js +0 -2
- package/dist/chunks/chunk-XJMBX6A2.js +0 -2
- package/dist/chunks/chunk-YZ6SBFFG.js +0 -2
|
@@ -0,0 +1,619 @@
|
|
|
1
|
+
// forecast's small functions: accuracy, ma, fourier, seasonaldummy, monthdays, easter, bizdays, dm.test, CV,
|
|
2
|
+
// checkresiduals, tsCV, arimaorder, findfrequency, na.interp, tsoutliers and tsclean. Written for rStats.js from the
|
|
3
|
+
// behaviour specification oracle/tsmeta-behaviour.md with the details found in experiments/tsmeta120-log.md (items
|
|
4
|
+
// 28-32, 52-60). No R or package source was read.
|
|
5
|
+
import { pt } from "../distributions/t.js";
|
|
6
|
+
import { lm } from "../models/lm.js";
|
|
7
|
+
import { ar } from "./statsTs.js";
|
|
8
|
+
import { boxTest } from "./statsTs.js";
|
|
9
|
+
import { mstl, seasadj, supsmu } from "./stl.js";
|
|
10
|
+
import { centred, powerOfTwoScale } from "./scale.js";
|
|
11
|
+
import { tsInput } from "./input.js";
|
|
12
|
+
// Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
|
|
13
|
+
import { checkOptions, nestedOptions } from "../internal/checkOptions.js";
|
|
14
|
+
const ACCURACY_KEYS_0 = ["y", "fitted"];
|
|
15
|
+
const ACCURACY_KEYS_1 = ["frequency", "test"];
|
|
16
|
+
const ACCURACY_TEST_KEYS = ["y", "forecast"];
|
|
17
|
+
const MA_KEYS = ["centre"];
|
|
18
|
+
const FOURIER_KEYS = ["frequency", "K", "n", "h"];
|
|
19
|
+
const SEASONALDUMMY_KEYS = ["frequency", "n", "start", "h"];
|
|
20
|
+
const MONTHDAYS_KEYS = ["startYear", "startPeriod", "n", "frequency"];
|
|
21
|
+
const EASTER_KEYS = ["startYear", "startPeriod", "n", "frequency", "easterMon"];
|
|
22
|
+
const BIZDAYS_KEYS = ["startYear", "startPeriod", "n", "frequency", "finCenter"];
|
|
23
|
+
const DM_TEST_KEYS = ["alternative", "h", "power"];
|
|
24
|
+
const CHECKRESIDUALS_KEYS = ["frequency", "df"];
|
|
25
|
+
const TS_CV_KEYS = ["h"];
|
|
26
|
+
const SPEC_AR_KEYS = ["nFreq"];
|
|
27
|
+
const NA_INTERP_KEYS = ["frequency"];
|
|
28
|
+
const TSOUTLIERS_KEYS = ["frequency", "iterate"];
|
|
29
|
+
const TSCLEAN_KEYS = ["frequency", "replaceMissing", "iterate"];
|
|
30
|
+
// Generated by `node scripts/option-keys.mjs --write` (end)
|
|
31
|
+
const meanOf = (v) => v.reduce((a, b) => a + b, 0) / v.length;
|
|
32
|
+
/**
|
|
33
|
+
* Accuracy measures (forecast's `accuracy()`): ME, RMSE, MAE, MPE, MAPE, MASE (scaled by the training data's mean
|
|
34
|
+
* |y_t - y_{t-m}|), ACF1 of the errors; for a test set also Theil's U.
|
|
35
|
+
* Equivalent to `forecast::accuracy()` in R.
|
|
36
|
+
*
|
|
37
|
+
* @category Time series
|
|
38
|
+
*/
|
|
39
|
+
export function accuracy(training, options = {}) {
|
|
40
|
+
checkOptions(training, ACCURACY_KEYS_0, "accuracy"); // generated: option-keys.mjs
|
|
41
|
+
checkOptions(options, ACCURACY_KEYS_1, "accuracy"); // generated: option-keys.mjs
|
|
42
|
+
checkOptions(nestedOptions(options, "test"), ACCURACY_TEST_KEYS, "accuracy", "test"); // generated: option-keys.mjs
|
|
43
|
+
const m = options.frequency ?? 1;
|
|
44
|
+
const y = training.y;
|
|
45
|
+
const scaleDiffs = [];
|
|
46
|
+
for (let t = m; t < y.length; t++)
|
|
47
|
+
if (Number.isFinite(y[t]) && Number.isFinite(y[t - m]))
|
|
48
|
+
scaleDiffs.push(Math.abs(y[t] - y[t - m]));
|
|
49
|
+
const scale = meanOf(scaleDiffs);
|
|
50
|
+
const row = (obs, pred, theil) => {
|
|
51
|
+
const e = [], pe = [], ys = [];
|
|
52
|
+
obs.forEach((v, i) => { const f = pred[i]; if (Number.isFinite(v) && Number.isFinite(f)) {
|
|
53
|
+
e.push(v - f);
|
|
54
|
+
pe.push((100 * (v - f)) / v);
|
|
55
|
+
ys.push(v);
|
|
56
|
+
} });
|
|
57
|
+
// the squares of the errors divided by a power of two (exact), so that RMSE and ACF1 stay right at 1e+-300 (log 110)
|
|
58
|
+
const c = powerOfTwoScale(e);
|
|
59
|
+
const es = e.map((v) => v / c);
|
|
60
|
+
const ME = meanOf(e), RMSE = c * Math.sqrt(meanOf(es.map((v) => v * v))), MAE = meanOf(e.map(Math.abs));
|
|
61
|
+
const MPE = meanOf(pe), MAPE = meanOf(pe.map(Math.abs)), MASE = MAE / scale;
|
|
62
|
+
const em = meanOf(es);
|
|
63
|
+
let c0 = 0, c1 = 0;
|
|
64
|
+
for (let t = 0; t < es.length; t++) {
|
|
65
|
+
c0 += (es[t] - em) ** 2;
|
|
66
|
+
if (t > 0)
|
|
67
|
+
c1 += (es[t] - em) * (es[t - 1] - em);
|
|
68
|
+
}
|
|
69
|
+
const out = { ME, RMSE, MAE, MPE, MAPE, MASE, ACF1: c1 / c0 };
|
|
70
|
+
if (theil) {
|
|
71
|
+
let num = 0, den = 0;
|
|
72
|
+
for (let t = 0; t + 1 < obs.length; t++) {
|
|
73
|
+
num += ((obs[t + 1] - pred[t + 1]) / obs[t]) ** 2;
|
|
74
|
+
den += ((obs[t + 1] - obs[t]) / obs[t]) ** 2;
|
|
75
|
+
}
|
|
76
|
+
out.TheilU = Math.sqrt(num / den);
|
|
77
|
+
}
|
|
78
|
+
return out;
|
|
79
|
+
};
|
|
80
|
+
const tr = row(y, training.fitted, false);
|
|
81
|
+
return options.test ? { training: tr, test: row(options.test.y, options.test.forecast, true) } : { training: tr };
|
|
82
|
+
}
|
|
83
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
84
|
+
// ma, fourier, seasonaldummy
|
|
85
|
+
/**
|
|
86
|
+
* Moving-average smoother (forecast's `ma()`): order k, centred (a 2 x k average) for even k when `centre`. Equivalent to `forecast::ma()` in R.
|
|
87
|
+
*
|
|
88
|
+
* @category Time series
|
|
89
|
+
*/
|
|
90
|
+
export function ma(x, order, options = {}) {
|
|
91
|
+
checkOptions(options, MA_KEYS, "ma"); // generated: option-keys.mjs
|
|
92
|
+
const centre = options.centre ?? true;
|
|
93
|
+
const n = x.length;
|
|
94
|
+
let w;
|
|
95
|
+
if (order % 2 === 1)
|
|
96
|
+
w = new Array(order).fill(1 / order);
|
|
97
|
+
else if (centre)
|
|
98
|
+
w = [0.5, ...new Array(order - 1).fill(1), 0.5].map((v) => v / order);
|
|
99
|
+
else
|
|
100
|
+
w = new Array(order).fill(1 / order);
|
|
101
|
+
const half = Math.floor(w.length / 2);
|
|
102
|
+
const off = order % 2 === 0 && !centre ? order / 2 - 1 : half;
|
|
103
|
+
return Array.from({ length: n }, (_, i) => {
|
|
104
|
+
let s = 0;
|
|
105
|
+
for (let j = 0; j < w.length; j++) {
|
|
106
|
+
const k = i - off + j;
|
|
107
|
+
if (k < 0 || k >= n)
|
|
108
|
+
return NaN;
|
|
109
|
+
s += w[j] * x[k];
|
|
110
|
+
}
|
|
111
|
+
return s;
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Fourier terms (forecast's `fourier()`): S_k = sin(2 pi k t / m), C_k = cos(2 pi k t / m) for k = 1..K, t = 1..n (or
|
|
116
|
+
* n + 1..n + h), the sine dropped at k = m / 2; columns named "S1-12", "C1-12", ...
|
|
117
|
+
* Equivalent to `forecast::fourier()` in R.
|
|
118
|
+
*
|
|
119
|
+
* @category Time series
|
|
120
|
+
*/
|
|
121
|
+
export function fourier(options) {
|
|
122
|
+
checkOptions(options, FOURIER_KEYS, "fourier"); // generated: option-keys.mjs
|
|
123
|
+
const m = options.frequency;
|
|
124
|
+
const t0 = options.h !== undefined ? options.n : 0;
|
|
125
|
+
const len = options.h ?? options.n;
|
|
126
|
+
const names = [], columns = [];
|
|
127
|
+
for (let k = 1; k <= options.K; k++) {
|
|
128
|
+
const t = Array.from({ length: len }, (_, i) => t0 + i + 1);
|
|
129
|
+
if (2 * k !== m) {
|
|
130
|
+
names.push(`S${k}-${m}`);
|
|
131
|
+
columns.push(t.map((v) => Math.sin((2 * Math.PI * k * v) / m)));
|
|
132
|
+
}
|
|
133
|
+
names.push(`C${k}-${m}`);
|
|
134
|
+
columns.push(t.map((v) => Math.cos((2 * Math.PI * k * v) / m)));
|
|
135
|
+
}
|
|
136
|
+
return { names, columns };
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Seasonal dummies (forecast's `seasonaldummy()`): m - 1 columns, the last period omitted; `start` the cycle position (1-based) of the first row. Equivalent to `forecast::seasonaldummy()` in R.
|
|
140
|
+
*
|
|
141
|
+
* @category Time series
|
|
142
|
+
*/
|
|
143
|
+
export function seasonaldummy(options) {
|
|
144
|
+
checkOptions(options, SEASONALDUMMY_KEYS, "seasonaldummy"); // generated: option-keys.mjs
|
|
145
|
+
const m = options.frequency;
|
|
146
|
+
const s0 = (options.start ?? 1) - 1 + (options.h !== undefined ? options.n : 0);
|
|
147
|
+
const len = options.h ?? options.n;
|
|
148
|
+
return Array.from({ length: m - 1 }, (_, k) => Array.from({ length: len }, (_, i) => ((s0 + i) % m === k ? 1 : 0)));
|
|
149
|
+
}
|
|
150
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
151
|
+
// calendars
|
|
152
|
+
const daysInMonth = (Y, mo) => new Date(Date.UTC(Y, mo, 0)).getUTCDate();
|
|
153
|
+
const periodsOf = (startYear, startPeriod, n, frequency) => Array.from({ length: n }, (_, i) => { const k = startPeriod - 1 + i; return { Y: startYear + Math.floor(k / frequency), p: (k % frequency) + 1 }; });
|
|
154
|
+
const monthsOf = (p, frequency) => (frequency === 12 ? [p] : [3 * p - 2, 3 * p - 1, 3 * p]);
|
|
155
|
+
/**
|
|
156
|
+
* Days in each month or quarter (forecast's `monthdays()`). Equivalent to `forecast::monthdays()` in R.
|
|
157
|
+
*
|
|
158
|
+
* @category Time series
|
|
159
|
+
*/
|
|
160
|
+
export function monthdays(options) {
|
|
161
|
+
checkOptions(options, MONTHDAYS_KEYS, "monthdays"); // generated: option-keys.mjs
|
|
162
|
+
const f = options.frequency ?? 12;
|
|
163
|
+
return periodsOf(options.startYear, options.startPeriod ?? 1, options.n, f).map(({ Y, p }) => monthsOf(p, f).reduce((a, mo) => a + daysInMonth(Y, mo), 0));
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Easter Sunday of year Y (anonymous Gregorian algorithm) as [month, day]. Not an R function.
|
|
167
|
+
*
|
|
168
|
+
* @category Time series
|
|
169
|
+
*/
|
|
170
|
+
export function easterSunday(Y) {
|
|
171
|
+
const a = Y % 19, b = Math.floor(Y / 100), c = Y % 100, d = Math.floor(b / 4), e = b % 4, f = Math.floor((b + 8) / 25), g = Math.floor((b - f + 1) / 3);
|
|
172
|
+
const h = (19 * a + b - d - g + 15) % 30, i = Math.floor(c / 4), k = c % 4, l = (32 + 2 * e + 2 * i - h - k) % 7;
|
|
173
|
+
const m = Math.floor((a + 11 * h + 22 * l) / 451);
|
|
174
|
+
const v = h + l - 7 * m + 114;
|
|
175
|
+
return [Math.floor(v / 31), (v % 31) + 1];
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* The Easter holidays in each month or quarter (forecast's `easter()`): the share of Good Friday .. Easter Sunday (..
|
|
179
|
+
* Monday with `easterMon`) falling in the period, rounded to two decimals (as R). Departs from R for quarterly data
|
|
180
|
+
* with `easterMon` when the holidays span two quarters: R's shares are shifted there (it warns about a replacement
|
|
181
|
+
* length; log 91), rStats.js gives each quarter its share.
|
|
182
|
+
* Equivalent to `forecast::easter()` in R.
|
|
183
|
+
*
|
|
184
|
+
* @category Time series
|
|
185
|
+
*/
|
|
186
|
+
export function easter(options) {
|
|
187
|
+
checkOptions(options, EASTER_KEYS, "easter"); // generated: option-keys.mjs
|
|
188
|
+
const f = options.frequency ?? 12;
|
|
189
|
+
return periodsOf(options.startYear, options.startPeriod ?? 1, options.n, f).map(({ Y, p }) => {
|
|
190
|
+
const [mo, d] = easterSunday(Y);
|
|
191
|
+
const sun = Date.UTC(Y, mo - 1, d);
|
|
192
|
+
const days = Array.from({ length: options.easterMon ? 4 : 3 }, (_, i) => new Date(sun + (i - 2) * 86400000));
|
|
193
|
+
const months = monthsOf(p, f);
|
|
194
|
+
const share = days.filter((dd) => dd.getUTCFullYear() === Y && months.includes(dd.getUTCMonth() + 1)).length / days.length;
|
|
195
|
+
return Math.round(share * 100) / 100;
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
const D = (Y, m, d) => Date.UTC(Y, m - 1, d) / 86400000;
|
|
199
|
+
const wday = (x) => { const w = new Date(x * 86400000).getUTCDay(); return w === 0 ? 7 : w; }; // 1 = Monday .. 7 = Sunday
|
|
200
|
+
const nthDow = (Y, m, dow, k) => { let x = D(Y, m, 1); while (wday(x) !== dow)
|
|
201
|
+
x++; return x + 7 * (k - 1); };
|
|
202
|
+
const lastDow = (Y, m, dow) => { let x = D(Y, m, daysInMonth(Y, m)); while (wday(x) !== dow)
|
|
203
|
+
x--; return x; };
|
|
204
|
+
const wkMon = (x) => (wday(x) === 6 ? x + 2 : wday(x) === 7 ? x + 1 : x);
|
|
205
|
+
const easterDay = (Y) => { const [m, d] = easterSunday(Y); return D(Y, m, d); };
|
|
206
|
+
function xmasPair(Y, toronto = false) {
|
|
207
|
+
const c25 = D(Y, 12, 25);
|
|
208
|
+
const w = wday(c25);
|
|
209
|
+
if (w === 5)
|
|
210
|
+
return [c25, c25 + 3];
|
|
211
|
+
if (w === 6)
|
|
212
|
+
return toronto ? [c25 + 2] : [c25 + 2, c25 + 3];
|
|
213
|
+
if (w === 7)
|
|
214
|
+
return [c25 + 1, c25 + 2];
|
|
215
|
+
return [c25, c25 + 1];
|
|
216
|
+
}
|
|
217
|
+
const HOLIDAYS = {
|
|
218
|
+
London: (Y) => {
|
|
219
|
+
const em = Y === 1995 || Y === 2020 ? D(Y, 5, 8) : nthDow(Y, 5, 1, 1);
|
|
220
|
+
const sp = Y === 2002 || Y === 2012 ? D(Y, 6, 4) : Y === 2022 ? D(Y, 6, 2) : lastDow(Y, 5, 1);
|
|
221
|
+
const ex = { 1999: [D(1999, 12, 31)], 2002: [D(2002, 6, 3)], 2011: [D(2011, 4, 29)], 2012: [D(2012, 6, 5)], 2022: [D(2022, 6, 3), D(2022, 9, 19)], 2023: [D(2023, 5, 8)] };
|
|
222
|
+
return [wkMon(D(Y, 1, 1)), easterDay(Y) - 2, easterDay(Y) + 1, em, sp, lastDow(Y, 8, 1), ...xmasPair(Y), ...(ex[Y] ?? [])];
|
|
223
|
+
},
|
|
224
|
+
Toronto: (Y) => {
|
|
225
|
+
let vic = D(Y, 5, 24);
|
|
226
|
+
while (wday(vic) !== 1)
|
|
227
|
+
vic--;
|
|
228
|
+
return [wkMon(D(Y, 1, 1)), ...(Y >= 2008 ? [nthDow(Y, 2, 1, 3)] : []), easterDay(Y) - 2, vic, wkMon(D(Y, 7, 1)), nthDow(Y, 8, 1, 1),
|
|
229
|
+
nthDow(Y, 9, 1, 1), nthDow(Y, 10, 1, 2), ...xmasPair(Y, true)];
|
|
230
|
+
},
|
|
231
|
+
Zurich: (Y) => [D(Y, 1, 1), D(Y, 1, 2), easterDay(Y) - 2, easterDay(Y) + 1, D(Y, 5, 1), easterDay(Y) + 39, easterDay(Y) + 50, D(Y, 8, 1),
|
|
232
|
+
D(Y, 12, 25), D(Y, 12, 26), nthDow(Y, 4, 1, 3), nthDow(Y, 9, 1, 2)],
|
|
233
|
+
"New York": (Y) => {
|
|
234
|
+
const obsSF = (x) => (wday(x) === 6 ? x - 1 : wday(x) === 7 ? x + 1 : x);
|
|
235
|
+
const h = [wday(D(Y, 1, 1)) === 7 ? D(Y, 1, 2) : D(Y, 1, 1), ...(Y >= 1998 ? [nthDow(Y, 1, 1, 3)] : []), nthDow(Y, 2, 1, 3), easterDay(Y) - 2,
|
|
236
|
+
lastDow(Y, 5, 1), obsSF(D(Y, 7, 4)), nthDow(Y, 9, 1, 1), nthDow(Y, 11, 4, 4), obsSF(D(Y, 12, 25))];
|
|
237
|
+
if (Y >= 2022)
|
|
238
|
+
h.push(obsSF(D(Y, 6, 19)));
|
|
239
|
+
// the NYSE's special closings (log 30, 32)
|
|
240
|
+
const sp = { 1994: [D(1994, 4, 27)], 2001: [0, 1, 2, 3].map((k) => D(2001, 9, 11) + k), 2004: [D(2004, 6, 11)], 2007: [D(2007, 1, 2)], 2012: [D(2012, 10, 29), D(2012, 10, 30)] };
|
|
241
|
+
return [...h, ...(sp[Y] ?? [])];
|
|
242
|
+
},
|
|
243
|
+
NERC: (Y) => {
|
|
244
|
+
const obs = (x) => (wday(x) === 7 ? x + 1 : x);
|
|
245
|
+
return [obs(D(Y, 1, 1)), lastDow(Y, 5, 1), obs(D(Y, 7, 4)), nthDow(Y, 9, 1, 1), nthDow(Y, 11, 4, 4), obs(D(Y, 12, 25))];
|
|
246
|
+
},
|
|
247
|
+
};
|
|
248
|
+
/**
|
|
249
|
+
* Trading days in each month or quarter (forecast's `bizdays()`): weekdays minus the holidays of the financial centre
|
|
250
|
+
* ("New York" (NYSE, default), "London", "NERC", "Toronto", "Zurich"; the rules of log 30-32).
|
|
251
|
+
* Equivalent to `forecast::bizdays()` in R.
|
|
252
|
+
*
|
|
253
|
+
* @category Time series
|
|
254
|
+
*/
|
|
255
|
+
export function bizdays(options) {
|
|
256
|
+
checkOptions(options, BIZDAYS_KEYS, "bizdays"); // generated: option-keys.mjs
|
|
257
|
+
const f = options.frequency ?? 12;
|
|
258
|
+
const hol = HOLIDAYS[options.finCenter ?? "New York"];
|
|
259
|
+
const cache = new Map();
|
|
260
|
+
const isHol = (x) => { const Y = new Date(x * 86400000).getUTCFullYear(); if (!cache.has(Y))
|
|
261
|
+
cache.set(Y, new Set(hol(Y))); return cache.get(Y).has(x); };
|
|
262
|
+
return periodsOf(options.startYear, options.startPeriod ?? 1, options.n, f).map(({ Y, p }) => {
|
|
263
|
+
let c = 0;
|
|
264
|
+
for (const mo of monthsOf(p, f))
|
|
265
|
+
for (let d = 1; d <= daysInMonth(Y, mo); d++) {
|
|
266
|
+
const x = D(Y, mo, d);
|
|
267
|
+
if (wday(x) <= 5 && !isHol(x))
|
|
268
|
+
c++;
|
|
269
|
+
}
|
|
270
|
+
return c;
|
|
271
|
+
});
|
|
272
|
+
}
|
|
273
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
274
|
+
// dm.test, CV, checkresiduals, tsCV, arimaorder
|
|
275
|
+
/**
|
|
276
|
+
* The Diebold-Mariano test with the Harvey-Leybourne-Newbold correction (forecast's `dm.test()`): d = |e1|^power -
|
|
277
|
+
* |e2|^power, its variance from the autocovariances up to h - 1 (over n), t(n - 1).
|
|
278
|
+
* Equivalent to `forecast::dm.test()` in R.
|
|
279
|
+
*
|
|
280
|
+
* @category Time series
|
|
281
|
+
*/
|
|
282
|
+
export function dmTest(e1, e2, options = {}) {
|
|
283
|
+
checkOptions(options, DM_TEST_KEYS, "dmTest"); // generated: option-keys.mjs
|
|
284
|
+
const h = options.h ?? 1;
|
|
285
|
+
const power = options.power ?? 2;
|
|
286
|
+
const alt = options.alternative ?? "two.sided";
|
|
287
|
+
if (e1.length !== e2.length)
|
|
288
|
+
throw new RangeError("dmTest: e1 and e2 must have the same length");
|
|
289
|
+
// both errors divided by one power of two (exact; the statistic does not depend on their common scale), so that
|
|
290
|
+
// |e|^power stays in range at 1e+-300 (log 110)
|
|
291
|
+
const c = powerOfTwoScale([...e1, ...e2]);
|
|
292
|
+
const d = e1.map((v, i) => Math.abs(v / c) ** power - Math.abs(e2[i] / c) ** power);
|
|
293
|
+
const n = d.length;
|
|
294
|
+
const dm = meanOf(d);
|
|
295
|
+
const gamma = (k) => { let s = 0; for (let t = k; t < n; t++)
|
|
296
|
+
s += (d[t] - dm) * (d[t - k] - dm); return s / n; };
|
|
297
|
+
let v = gamma(0);
|
|
298
|
+
for (let k = 1; k < h; k++)
|
|
299
|
+
v += 2 * gamma(k);
|
|
300
|
+
const stat0 = dm / Math.sqrt(v / n);
|
|
301
|
+
const k = Math.sqrt((n + 1 - 2 * h + (h * (h - 1)) / n) / n);
|
|
302
|
+
const statistic = stat0 * k;
|
|
303
|
+
const df = n - 1;
|
|
304
|
+
const pValue = alt === "two.sided" ? 2 * pt(-Math.abs(statistic), df) : alt === "less" ? pt(statistic, df) : pt(statistic, df, { lowerTail: false });
|
|
305
|
+
return { statistic, parameter: df, pValue };
|
|
306
|
+
}
|
|
307
|
+
/**
|
|
308
|
+
* Cross-validation and information criteria of a linear model (forecast's `CV()`): CV = mean((e / (1 - h_ii))^2), AIC =
|
|
309
|
+
* n log(SSE/n) + 2(k + 2), AICc, BIC, adjusted R^2 (k = the number of predictors).
|
|
310
|
+
* Equivalent to `forecast::CV()` in R.
|
|
311
|
+
*
|
|
312
|
+
* @category Time series
|
|
313
|
+
*/
|
|
314
|
+
export function cvLm(x, y0) {
|
|
315
|
+
// y less a large common value (the residuals do not depend on it) and divided by a power of two (exact): the sums of
|
|
316
|
+
// squares stay in range at 1e+-300 and keep their digits at y + 1e15 (log 110); CV and AIC mapped back
|
|
317
|
+
const yc = centred(y0);
|
|
318
|
+
const sy = powerOfTwoScale(yc);
|
|
319
|
+
const y = yc.map((v) => v / sy);
|
|
320
|
+
const f = lm(x, y, {});
|
|
321
|
+
const n = y.length;
|
|
322
|
+
const k = x[0].length;
|
|
323
|
+
const X = x.map((r) => [1, ...r]);
|
|
324
|
+
const p = k + 1;
|
|
325
|
+
const A = Array.from({ length: p }, (_, i) => Array.from({ length: p }, (_, j) => X.reduce((s, r) => s + r[i] * r[j], 0)));
|
|
326
|
+
const inv = invertSmall(A);
|
|
327
|
+
const hii = X.map((r) => r.reduce((s, v, i) => s + v * r.reduce((s2, w, j) => s2 + inv[i][j] * w, 0), 0));
|
|
328
|
+
const e = f.residuals;
|
|
329
|
+
const sse = e.reduce((a, v) => a + v * v, 0);
|
|
330
|
+
const CV = meanOf(e.map((v, i) => (v / (1 - hii[i])) ** 2)) * sy * sy;
|
|
331
|
+
const AIC = n * Math.log(sse / n) + 2 * n * Math.log(sy) + 2 * (k + 2);
|
|
332
|
+
const AICc = AIC + (2 * (k + 2) * (k + 3)) / (n - k - 3);
|
|
333
|
+
const BIC = AIC + (k + 2) * (Math.log(n) - 2);
|
|
334
|
+
const ym = meanOf(y);
|
|
335
|
+
const sst = y.reduce((a, v) => a + (v - ym) ** 2, 0);
|
|
336
|
+
const AdjR2 = 1 - ((sse / sst) * (n - 1)) / (n - k - 1);
|
|
337
|
+
return { CV, AIC, AICc, BIC, AdjR2 };
|
|
338
|
+
}
|
|
339
|
+
function invertSmall(A) {
|
|
340
|
+
const k = A.length;
|
|
341
|
+
const M = A.map((r, i) => [...r, ...Array.from({ length: k }, (_, j) => (i === j ? 1 : 0))]);
|
|
342
|
+
for (let i = 0; i < k; i++) {
|
|
343
|
+
let p = i;
|
|
344
|
+
for (let r = i + 1; r < k; r++)
|
|
345
|
+
if (Math.abs(M[r][i]) > Math.abs(M[p][i]))
|
|
346
|
+
p = r;
|
|
347
|
+
[M[i], M[p]] = [M[p], M[i]];
|
|
348
|
+
const d = M[i][i];
|
|
349
|
+
for (let c = 0; c < 2 * k; c++)
|
|
350
|
+
M[i][c] /= d;
|
|
351
|
+
for (let r = 0; r < k; r++)
|
|
352
|
+
if (r !== i) {
|
|
353
|
+
const fct = M[r][i];
|
|
354
|
+
for (let c = 0; c < 2 * k; c++)
|
|
355
|
+
M[r][c] -= fct * M[i][c];
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
return M.map((r) => r.slice(k));
|
|
359
|
+
}
|
|
360
|
+
/**
|
|
361
|
+
* The Ljung-Box test of a model's residuals (forecast's `checkresiduals()`, without the plots): lag = min(2m, n/5) for
|
|
362
|
+
* seasonal data or min(10, n/5), at least df + 3, df = the number of ARMA coefficients (0 for plain residuals).
|
|
363
|
+
* Equivalent to `forecast::checkresiduals()` in R.
|
|
364
|
+
*
|
|
365
|
+
* @category Time series
|
|
366
|
+
*/
|
|
367
|
+
export function checkresiduals(residuals, options = {}) {
|
|
368
|
+
checkOptions(options, CHECKRESIDUALS_KEYS, "checkresiduals"); // generated: option-keys.mjs
|
|
369
|
+
const res = residuals.filter(Number.isFinite);
|
|
370
|
+
const n = res.length;
|
|
371
|
+
const m = options.frequency ?? 1;
|
|
372
|
+
const df = options.df ?? 0;
|
|
373
|
+
let lag = m > 1 ? Math.min(2 * m, n / 5) : Math.min(10, n / 5);
|
|
374
|
+
lag = Math.max(df + 3, lag);
|
|
375
|
+
lag = Math.floor(lag);
|
|
376
|
+
const r = boxTest(res, { lag, type: "Ljung-Box", fitdf: df });
|
|
377
|
+
return { statistic: r.statistic, parameter: r.parameter, pValue: r.pValue, lag };
|
|
378
|
+
}
|
|
379
|
+
/** The number of ARMA coefficients of a fit (for checkresiduals' df). */
|
|
380
|
+
export function armaCoefficients(fit) { return fit.arma[0] + fit.arma[1] + fit.arma[2] + fit.arma[3]; }
|
|
381
|
+
/**
|
|
382
|
+
* Time series cross-validation (forecast's `tsCV()`): for each origin t the forecast errors of y_{t+1..t+h} from the fit
|
|
383
|
+
* to y_1..y_t, stored in row t (NaN where unavailable).
|
|
384
|
+
* Equivalent to `forecast::tsCV()` in R.
|
|
385
|
+
*
|
|
386
|
+
* @category Time series
|
|
387
|
+
*/
|
|
388
|
+
export function tsCV(y, forecastFun, options = {}) {
|
|
389
|
+
checkOptions(options, TS_CV_KEYS, "tsCV"); // generated: option-keys.mjs
|
|
390
|
+
const h = options.h ?? 1;
|
|
391
|
+
const n = y.length;
|
|
392
|
+
return Array.from({ length: n }, (_, t) => {
|
|
393
|
+
let fc = null;
|
|
394
|
+
try {
|
|
395
|
+
fc = forecastFun(y.slice(0, t + 1), h);
|
|
396
|
+
}
|
|
397
|
+
catch {
|
|
398
|
+
fc = null;
|
|
399
|
+
}
|
|
400
|
+
return Array.from({ length: h }, (_, k) => (fc && t + k + 1 < n ? y[t + k + 1] - fc[k] : NaN));
|
|
401
|
+
});
|
|
402
|
+
}
|
|
403
|
+
/**
|
|
404
|
+
* The (p, d, q) or (p, d, q, P, D, Q, frequency) of an ARIMA fit (forecast's `arimaorder()`). Equivalent to `forecast::arimaorder()` in R.
|
|
405
|
+
*
|
|
406
|
+
* @category Time series
|
|
407
|
+
*/
|
|
408
|
+
export function arimaorder(fit) {
|
|
409
|
+
const [p, q, P, Q, s, d, D] = fit.arma;
|
|
410
|
+
return P + D + Q > 0 && s > 1 ? { p, d, q, P, D, Q, Frequency: s } : { p, d, q };
|
|
411
|
+
}
|
|
412
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
413
|
+
// findfrequency (spec.ar)
|
|
414
|
+
/**
|
|
415
|
+
* The AR spectrum (stats' `spec.ar()` at n.freq frequencies 0..0.5) of x: var.pred / |1 - sum a_k e^{-2 pi i f k}|^2. Equivalent to R's `spec.ar()`.
|
|
416
|
+
*
|
|
417
|
+
* @category Time series
|
|
418
|
+
*/
|
|
419
|
+
export function specAr(x, options = {}) {
|
|
420
|
+
checkOptions(options, SPEC_AR_KEYS, "specAr"); // generated: option-keys.mjs
|
|
421
|
+
const fit = ar(x);
|
|
422
|
+
const nf = options.nFreq ?? 500;
|
|
423
|
+
const freq = Array.from({ length: nf }, (_, i) => (0.5 * i) / (nf - 1));
|
|
424
|
+
const spec = freq.map((f) => {
|
|
425
|
+
let re = 1, im = 0;
|
|
426
|
+
for (let k = 0; k < fit.order; k++) {
|
|
427
|
+
re -= fit.ar[k] * Math.cos(2 * Math.PI * f * (k + 1));
|
|
428
|
+
im += fit.ar[k] * Math.sin(2 * Math.PI * f * (k + 1));
|
|
429
|
+
}
|
|
430
|
+
return fit.varPred / (re * re + im * im);
|
|
431
|
+
});
|
|
432
|
+
return { freq, spec, order: fit.order };
|
|
433
|
+
}
|
|
434
|
+
/**
|
|
435
|
+
* The dominant period of a series (forecast's `findfrequency()`): 1 unless the maximum of the AR spectrum of the
|
|
436
|
+
* detrended series exceeds 10; then round(1 / f) at the maximum, or, when the maximum is at the lowest frequency, at
|
|
437
|
+
* the largest value after the spectrum first rises (1 if that is the last frequency).
|
|
438
|
+
* Equivalent to `forecast::findfrequency()` in R.
|
|
439
|
+
*
|
|
440
|
+
* @category Time series
|
|
441
|
+
*/
|
|
442
|
+
export function findfrequency(x) {
|
|
443
|
+
const xs = tsInput(x, "findfrequency", { missing: "allow", minLength: 2 }).filter(Number.isFinite);
|
|
444
|
+
const res = lm(xs.map((_, t) => [t + 1]), xs, {}).residuals;
|
|
445
|
+
const { freq, spec } = specAr(res);
|
|
446
|
+
if (Math.max(...spec) <= 10)
|
|
447
|
+
return 1;
|
|
448
|
+
let jm = 0;
|
|
449
|
+
for (let j = 1; j < spec.length; j++)
|
|
450
|
+
if (spec[j] > spec[jm])
|
|
451
|
+
jm = j;
|
|
452
|
+
if (jm > 0)
|
|
453
|
+
return Math.round(1 / freq[jm]);
|
|
454
|
+
let st = -1;
|
|
455
|
+
for (let j = 0; j + 1 < spec.length; j++)
|
|
456
|
+
if (spec[j + 1] - spec[j] > 0) {
|
|
457
|
+
st = j;
|
|
458
|
+
break;
|
|
459
|
+
}
|
|
460
|
+
if (st < 0)
|
|
461
|
+
return 1;
|
|
462
|
+
let j = st + 1;
|
|
463
|
+
for (let k = st + 1; k < spec.length; k++)
|
|
464
|
+
if (spec[k] > spec[j])
|
|
465
|
+
j = k;
|
|
466
|
+
return j < spec.length - 1 ? Math.round(1 / freq[j]) : 1;
|
|
467
|
+
}
|
|
468
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
469
|
+
// na.interp, tsoutliers, tsclean
|
|
470
|
+
/** Linear interpolation of the NaNs, constant beyond the ends (approx rule = 2). */
|
|
471
|
+
function approxRule2(x) {
|
|
472
|
+
const idx = x.map((v, i) => (Number.isNaN(v) ? -1 : i)).filter((i) => i >= 0);
|
|
473
|
+
if (idx.length === 0)
|
|
474
|
+
return x.slice();
|
|
475
|
+
return x.map((v, i) => {
|
|
476
|
+
if (!Number.isNaN(v))
|
|
477
|
+
return v;
|
|
478
|
+
if (i < idx[0])
|
|
479
|
+
return x[idx[0]];
|
|
480
|
+
if (i > idx[idx.length - 1])
|
|
481
|
+
return x[idx[idx.length - 1]];
|
|
482
|
+
let k = 0;
|
|
483
|
+
while (idx[k + 1] < i)
|
|
484
|
+
k++;
|
|
485
|
+
const a = idx[k], b = idx[k + 1];
|
|
486
|
+
return x[a] + ((x[b] - x[a]) * (i - a)) / (b - a);
|
|
487
|
+
});
|
|
488
|
+
}
|
|
489
|
+
/**
|
|
490
|
+
* Interpolation of missing values (forecast's `na.interp()`): linear for non-seasonal series (or at most two periods
|
|
491
|
+
* observed); for seasonal series the seasonal component of a robust mstl of a first filling (lm on Fourier terms K =
|
|
492
|
+
* min(5, floor(m/2)) and a polynomial of degree min(6, floor(n/10))), the seasonally adjusted series interpolated
|
|
493
|
+
* linearly.
|
|
494
|
+
* Equivalent to `forecast::na.interp()` in R.
|
|
495
|
+
*
|
|
496
|
+
* @category Time series
|
|
497
|
+
*/
|
|
498
|
+
export function naInterp(x, options = {}) {
|
|
499
|
+
checkOptions(options, NA_INTERP_KEYS, "naInterp"); // generated: option-keys.mjs
|
|
500
|
+
x = tsInput(x, "naInterp", { missing: "allow" });
|
|
501
|
+
const m = options.frequency ?? 1;
|
|
502
|
+
const n = x.length;
|
|
503
|
+
const obs = x.filter((v) => !Number.isNaN(v)).length;
|
|
504
|
+
if (!x.some((v) => Number.isNaN(v)))
|
|
505
|
+
return x.slice();
|
|
506
|
+
if (m <= 1 || obs <= 2 * m)
|
|
507
|
+
return approxRule2(x);
|
|
508
|
+
const K = Math.min(5, Math.floor(m / 2));
|
|
509
|
+
const deg = Math.min(6, Math.floor(n / 10));
|
|
510
|
+
const four = fourier({ frequency: m, K, n }).columns;
|
|
511
|
+
// the polynomial in t centred and scaled (the fit is invariant to the basis)
|
|
512
|
+
const tm = (n + 1) / 2, ts = n / 2;
|
|
513
|
+
const rowsAll = x.map((_, t) => [...four.map((c) => c[t]), ...Array.from({ length: deg }, (_, d) => ((t + 1 - tm) / ts) ** (d + 1))]);
|
|
514
|
+
const okIdx = x.map((v, i) => (Number.isNaN(v) ? -1 : i)).filter((i) => i >= 0);
|
|
515
|
+
const f = lm(okIdx.map((i) => rowsAll[i]), okIdx.map((i) => x[i]), {});
|
|
516
|
+
const pred = (r) => f.coefficients[0] + r.reduce((s, v, j) => s + v * f.coefficients[j + 1], 0);
|
|
517
|
+
const filled = x.map((v, i) => (Number.isNaN(v) ? pred(rowsAll[i]) : v));
|
|
518
|
+
const seas = mstl(filled, { frequency: m, robust: true }).seasonal ?? new Array(n).fill(0);
|
|
519
|
+
const adj = approxRule2(x.map((v, i) => v - seas[i]));
|
|
520
|
+
return adj.map((v, i) => v + seas[i]);
|
|
521
|
+
}
|
|
522
|
+
const quantile7 = (v, p) => {
|
|
523
|
+
const s = v.filter(Number.isFinite).sort((a, b) => a - b);
|
|
524
|
+
const h = (s.length - 1) * p;
|
|
525
|
+
const lo = Math.floor(h);
|
|
526
|
+
return s[lo] + (h - lo) * ((s[Math.min(lo + 1, s.length - 1)] ?? s[lo]) - s[lo]);
|
|
527
|
+
};
|
|
528
|
+
function outlierPass(x, m) {
|
|
529
|
+
const n = x.length;
|
|
530
|
+
const xi = naInterp(x, { frequency: m });
|
|
531
|
+
let resid;
|
|
532
|
+
if (m > 1 && n > 2 * m) {
|
|
533
|
+
const adj = seasadj(mstl(xi, { frequency: m, robust: true }));
|
|
534
|
+
const sm = supsmu(adj.map((_, t) => t + 1), adj).y;
|
|
535
|
+
resid = adj.map((v, i) => v - sm[i]);
|
|
536
|
+
}
|
|
537
|
+
else {
|
|
538
|
+
const sm = supsmu(xi.map((_, t) => t + 1), xi).y;
|
|
539
|
+
resid = xi.map((v, i) => v - sm[i]);
|
|
540
|
+
}
|
|
541
|
+
// residuals at the level of rounding (below 1e-12 of the largest |x|) are zero: an exact fit (a constant series)
|
|
542
|
+
// has no outliers, as R's, whose residuals are exact zeros there (log 107)
|
|
543
|
+
let big = 0;
|
|
544
|
+
for (const v of x)
|
|
545
|
+
if (Number.isFinite(v))
|
|
546
|
+
big = Math.max(big, Math.abs(v));
|
|
547
|
+
resid = resid.map((v, i) => (Number.isNaN(x[i]) ? NaN : Math.abs(v) <= 1e-12 * big ? 0 : v));
|
|
548
|
+
const q1 = quantile7(resid, 0.25), q3 = quantile7(resid, 0.75);
|
|
549
|
+
const iqr = q3 - q1;
|
|
550
|
+
return resid.map((v, i) => (Number.isFinite(v) && (v < q1 - 3 * iqr || v > q3 + 3 * iqr) ? i : -1)).filter((i) => i >= 0);
|
|
551
|
+
}
|
|
552
|
+
/**
|
|
553
|
+
* Outliers and their replacements (forecast's `tsoutliers()`): the remainder of seasadj(robust mstl) minus supsmu (or x
|
|
554
|
+
* minus supsmu), points outside [Q1 - 3 IQR, Q3 + 3 IQR], replaced by na.interp with them removed; `iterate` passes
|
|
555
|
+
* (default 2), the union of the flags.
|
|
556
|
+
* Equivalent to `forecast::tsoutliers()` in R.
|
|
557
|
+
*
|
|
558
|
+
* @category Time series
|
|
559
|
+
*/
|
|
560
|
+
export function tsoutliers(x, options = {}) {
|
|
561
|
+
checkOptions(options, TSOUTLIERS_KEYS, "tsoutliers"); // generated: option-keys.mjs
|
|
562
|
+
const m = options.frequency ?? 1;
|
|
563
|
+
const it = options.iterate ?? 2;
|
|
564
|
+
let flags = new Set();
|
|
565
|
+
let cur = tsInput(x, "tsoutliers", { missing: "allow" });
|
|
566
|
+
for (let k = 0; k < it; k++) {
|
|
567
|
+
const idx = outlierPass(cur, m);
|
|
568
|
+
if (idx.length === 0)
|
|
569
|
+
break;
|
|
570
|
+
idx.forEach((i) => flags.add(i));
|
|
571
|
+
const removed = x.map((v, i) => (flags.has(i) ? NaN : v));
|
|
572
|
+
cur = naInterp(removed, { frequency: m });
|
|
573
|
+
}
|
|
574
|
+
const index = [...flags].sort((a, b) => a - b);
|
|
575
|
+
if (index.length === 0)
|
|
576
|
+
return { index: [], replacements: [] };
|
|
577
|
+
const filled = naInterp(x.map((v, i) => (flags.has(i) ? NaN : v)), { frequency: m });
|
|
578
|
+
flags = new Set(index);
|
|
579
|
+
return { index, replacements: index.map((i) => filled[i]) };
|
|
580
|
+
}
|
|
581
|
+
/**
|
|
582
|
+
* The series with missing values interpolated and outliers replaced (forecast's `tsclean()`).
|
|
583
|
+
* Equivalent to `forecast::tsclean()` in R.
|
|
584
|
+
*
|
|
585
|
+
* @category Time series
|
|
586
|
+
*/
|
|
587
|
+
export function tsclean(x, options = {}) {
|
|
588
|
+
checkOptions(options, TSCLEAN_KEYS, "tsclean"); // generated: option-keys.mjs
|
|
589
|
+
const m = options.frequency ?? 1;
|
|
590
|
+
const o = tsoutliers(x, { frequency: m, ...(options.iterate !== undefined ? { iterate: options.iterate } : {}) });
|
|
591
|
+
// the outliers replaced first, then the missing values interpolated (as R, log 91)
|
|
592
|
+
const out = x.slice();
|
|
593
|
+
o.index.forEach((i, k) => { out[i] = o.replacements[k]; });
|
|
594
|
+
return options.replaceMissing ?? true ? naInterp(out, { frequency: m }) : out;
|
|
595
|
+
}
|
|
596
|
+
/**
|
|
597
|
+
* The seasonal component of an {@link mstl} decomposition (forecast's `seasonal()`; zeros without one). Equivalent to `forecast::seasonal()` in R.
|
|
598
|
+
*
|
|
599
|
+
* @category Time series
|
|
600
|
+
*/
|
|
601
|
+
export function seasonalComponent(dec) {
|
|
602
|
+
return dec.seasonal ?? dec.data.map(() => 0);
|
|
603
|
+
}
|
|
604
|
+
/**
|
|
605
|
+
* The trend-cycle component of an {@link mstl} decomposition (forecast's `trendcycle()`). Equivalent to `forecast::trendcycle()` in R.
|
|
606
|
+
*
|
|
607
|
+
* @category Time series
|
|
608
|
+
*/
|
|
609
|
+
export function trendcycle(dec) {
|
|
610
|
+
return dec.trend.slice();
|
|
611
|
+
}
|
|
612
|
+
/**
|
|
613
|
+
* The remainder component of an {@link mstl} decomposition (forecast's `remainder()`). Equivalent to `forecast::remainder()` in R.
|
|
614
|
+
*
|
|
615
|
+
* @category Time series
|
|
616
|
+
*/
|
|
617
|
+
export function remainder(dec) {
|
|
618
|
+
return dec.remainder.slice();
|
|
619
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Options of {@link holtWinters}.
|
|
3
|
+
*
|
|
4
|
+
* @category Time series
|
|
5
|
+
*/
|
|
6
|
+
export interface HoltWintersOptions {
|
|
7
|
+
frequency?: number;
|
|
8
|
+
/** Given, or estimated when undefined; `false` for beta / gamma leaves that component out. */
|
|
9
|
+
alpha?: number;
|
|
10
|
+
beta?: number | false;
|
|
11
|
+
gamma?: number | false;
|
|
12
|
+
seasonal?: "additive" | "multiplicative";
|
|
13
|
+
startPeriods?: number;
|
|
14
|
+
lStart?: number;
|
|
15
|
+
bStart?: number;
|
|
16
|
+
sStart?: readonly number[];
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Result of {@link holtWinters}.
|
|
20
|
+
*
|
|
21
|
+
* @category Time series
|
|
22
|
+
*/
|
|
23
|
+
export interface HoltWintersResult {
|
|
24
|
+
alpha: number;
|
|
25
|
+
beta: number | false;
|
|
26
|
+
gamma: number | false;
|
|
27
|
+
/** a, b, s1..sf (R's coefficients). */
|
|
28
|
+
coefficients: number[];
|
|
29
|
+
coefficientNames: string[];
|
|
30
|
+
SSE: number;
|
|
31
|
+
/** One-step fitted values from the first fitted time (R's fitted xhat). */
|
|
32
|
+
fitted: number[];
|
|
33
|
+
/** The time index (0-based) of the first fitted value. */
|
|
34
|
+
start: number;
|
|
35
|
+
seasonal: "additive" | "multiplicative";
|
|
36
|
+
frequency: number;
|
|
37
|
+
x: number[];
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Holt-Winters filtering (stats' `HoltWinters()`): exponential smoothing with optional trend and seasonal components,
|
|
41
|
+
* the start values from decompose() of the first start.periods periods, the parameters minimising the SSE.
|
|
42
|
+
* Equivalent to R's `HoltWinters()`.
|
|
43
|
+
*
|
|
44
|
+
* @category Time series
|
|
45
|
+
*/
|
|
46
|
+
export declare function holtWinters(x: readonly number[], options?: HoltWintersOptions): HoltWintersResult;
|
|
47
|
+
/**
|
|
48
|
+
* Predictions from a {@link holtWinters} fit with intervals (stats' `predict.HoltWinters()`): additive and
|
|
49
|
+
* non-seasonal models var(residuals) (1 + sum_{j<h} psi_j^2), psi_j = alpha (1 + j beta) + gamma (1 - alpha) [j mod f
|
|
50
|
+
* = 0]; multiplicative models var(residuals) sum_{j=0}^{h-1} (psi_j s_h / s_{h-j})^2 with cyclic seasonal indices
|
|
51
|
+
* (R reads the seasonal factors at fixed positions of its coefficient vector instead: R bug 19369; equal for h < f with
|
|
52
|
+
* a trend).
|
|
53
|
+
* Equivalent to R's `predict()`.
|
|
54
|
+
*
|
|
55
|
+
* @category Time series
|
|
56
|
+
*/
|
|
57
|
+
export declare function predictHoltWinters(fit: HoltWintersResult, options?: {
|
|
58
|
+
nAhead?: number;
|
|
59
|
+
predictionInterval?: boolean;
|
|
60
|
+
level?: number;
|
|
61
|
+
}): {
|
|
62
|
+
fit: number[];
|
|
63
|
+
upr?: number[];
|
|
64
|
+
lwr?: number[];
|
|
65
|
+
};
|