garch 1.0.3 → 1.1.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/README.md +278 -37
- package/build/index.cjs +1084 -43
- package/build/index.mjs +1072 -44
- package/package.json +1 -1
- package/types.d.ts +283 -4
package/README.md
CHANGED
|
@@ -3,8 +3,9 @@
|
|
|
3
3
|
</p>
|
|
4
4
|
|
|
5
5
|
<p align="center">
|
|
6
|
-
<strong>Missing
|
|
7
|
-
GARCH
|
|
6
|
+
<strong>Missing volatility forecast for NodeJS</strong><br>
|
|
7
|
+
Realized GARCH, Realized EGARCH, Realized GJR-GARCH, HAR-RV and NoVaS<br>
|
|
8
|
+
models for TypeScript. Zero dependencies.
|
|
8
9
|
</p>
|
|
9
10
|
|
|
10
11
|
## Installation
|
|
@@ -17,7 +18,7 @@ npm install garch
|
|
|
17
18
|
|
|
18
19
|
### `predict(candles, interval, currentPrice?)`
|
|
19
20
|
|
|
20
|
-
Forecast expected price range for the next candle (t+1). Auto-selects GARCH or
|
|
21
|
+
Forecast expected price range for the next candle (t+1). Auto-selects the best model (GARCH, EGARCH, GJR-GARCH, HAR-RV or NoVaS) by QLIKE forecast-error comparison. Returns a +-1 sigma price corridor.
|
|
21
22
|
|
|
22
23
|
```typescript
|
|
23
24
|
import { predict } from 'garch';
|
|
@@ -57,7 +58,7 @@ interface PredictionResult {
|
|
|
57
58
|
move: number; // +/- price move = currentPrice * sigma
|
|
58
59
|
upperPrice: number; // currentPrice + move
|
|
59
60
|
lowerPrice: number; // currentPrice - move
|
|
60
|
-
modelType: 'garch' | 'egarch'; // Auto-selected model
|
|
61
|
+
modelType: 'garch' | 'egarch' | 'gjr-garch' | 'har-rv' | 'novas'; // Auto-selected model
|
|
61
62
|
reliable: boolean; // Quality flag (convergence + persistence + Ljung-Box)
|
|
62
63
|
}
|
|
63
64
|
```
|
|
@@ -121,18 +122,20 @@ backtest(candles, '4h', 50); // true -- hit rate >= 50% (custom)
|
|
|
121
122
|
|
|
122
123
|
## Supported Intervals
|
|
123
124
|
|
|
124
|
-
| Interval | Min Candles | Periods/Year | Coverage |
|
|
125
|
-
|
|
126
|
-
| `1m` | 500 | 525,600 | ~8-16 hours |
|
|
127
|
-
| `3m` | 500 | 175,200 | ~25 hours |
|
|
128
|
-
| `5m` | 500 | 105,120 | ~1.7 days |
|
|
129
|
-
| `15m` | 300 | 35,040 | ~3 days |
|
|
130
|
-
| `30m` | 200 | 17,520 | ~4 days |
|
|
131
|
-
| `1h` | 200 | 8,760 | ~8 days |
|
|
132
|
-
| `2h` | 200 | 4,380 | ~17 days |
|
|
133
|
-
| `4h` | 200 | 2,190 | ~33 days |
|
|
134
|
-
| `6h` | 150 | 1,460 | ~37 days |
|
|
135
|
-
| `8h` | 150 | 1,095 | ~50 days |
|
|
125
|
+
| Interval | Min Candles | Recommended | Periods/Year | Coverage |
|
|
126
|
+
|----------|-------------|-------------|--------------|----------|
|
|
127
|
+
| `1m` | 500 | 1,500 | 525,600 | ~8-16 hours |
|
|
128
|
+
| `3m` | 500 | 1,500 | 175,200 | ~25 hours |
|
|
129
|
+
| `5m` | 500 | 1,500 | 105,120 | ~1.7 days |
|
|
130
|
+
| `15m` | 300 | 1,000 | 35,040 | ~3 days |
|
|
131
|
+
| `30m` | 200 | 1,000 | 17,520 | ~4 days |
|
|
132
|
+
| `1h` | 200 | 500 | 8,760 | ~8 days |
|
|
133
|
+
| `2h` | 200 | 500 | 4,380 | ~17 days |
|
|
134
|
+
| `4h` | 200 | 500 | 2,190 | ~33 days |
|
|
135
|
+
| `6h` | 150 | 300 | 1,460 | ~37 days |
|
|
136
|
+
| `8h` | 150 | 300 | 1,095 | ~50 days |
|
|
137
|
+
|
|
138
|
+
For intervals below 1h, per-candle Parkinson RV is noisier — more data helps OLS and QLIKE model selection. A `console.warn` is emitted when candle count is below the recommended value. Always check `reliable: true` in the output.
|
|
136
139
|
|
|
137
140
|
## Timeframes
|
|
138
141
|
|
|
@@ -157,7 +160,16 @@ Lower timeframes contain more microstructure noise — use larger datasets to co
|
|
|
157
160
|
|
|
158
161
|
### GARCH(1,1)
|
|
159
162
|
|
|
160
|
-
Conditional variance model (Bollerslev, 1986):
|
|
163
|
+
Conditional variance model (Bollerslev, 1986). Input type determines the innovation term automatically:
|
|
164
|
+
|
|
165
|
+
**Candle[] input** — Realized GARCH (Hansen & Huang, 2016). Uses Parkinson (1980) per-candle realized variance proxy (~5× more efficient than squared returns):
|
|
166
|
+
|
|
167
|
+
```
|
|
168
|
+
sigma_t^2 = omega + alpha * RV_{t-1} + beta * sigma_{t-1}^2
|
|
169
|
+
RV_t = (1 / (4·ln2)) · ln(H/L)^2 (Parkinson estimator)
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
**number[] input** — Classical GARCH. Uses squared returns:
|
|
161
173
|
|
|
162
174
|
```
|
|
163
175
|
sigma_t^2 = omega + alpha * epsilon_{t-1}^2 + beta * sigma_{t-1}^2
|
|
@@ -169,13 +181,16 @@ sigma_t^2 = omega + alpha * epsilon_{t-1}^2 + beta * sigma_{t-1}^2
|
|
|
169
181
|
- Stationarity constraint: **alpha + beta < 1**
|
|
170
182
|
- Unconditional variance: **E[sigma^2] = omega / (1 - alpha - beta)**
|
|
171
183
|
|
|
172
|
-
Parameter estimation via **
|
|
184
|
+
Parameter estimation via **Student-t MLE** (maximum likelihood) with multi-start Nelder-Mead optimization. The Student-t distribution captures fat tails observed in financial returns:
|
|
173
185
|
|
|
174
186
|
```
|
|
175
|
-
LL =
|
|
187
|
+
LL = n·[lnΓ((df+1)/2) - lnΓ(df/2) - 0.5·ln(π·(df-2))]
|
|
188
|
+
- 0.5 · sum[ ln(sigma_t^2) + (df+1)·ln(1 + r_t^2 / ((df-2)·sigma_t^2)) ]
|
|
176
189
|
```
|
|
177
190
|
|
|
178
|
-
|
|
191
|
+
- **df** > 2 — degrees of freedom (estimated jointly with omega, alpha, beta via multi-start Nelder-Mead)
|
|
192
|
+
|
|
193
|
+
Multi-step forecast converges to unconditional variance (E[RV] = sigma^2, so recursion is identical):
|
|
179
194
|
|
|
180
195
|
```
|
|
181
196
|
sigma_{t+h}^2 = omega + (alpha + beta) * sigma_{t+h-1}^2
|
|
@@ -183,26 +198,191 @@ sigma_{t+h}^2 = omega + (alpha + beta) * sigma_{t+h-1}^2
|
|
|
183
198
|
|
|
184
199
|
### EGARCH(1,1)
|
|
185
200
|
|
|
186
|
-
Exponential GARCH (Nelson, 1991). Models log-variance, capturing asymmetric volatility:
|
|
201
|
+
Exponential GARCH (Nelson, 1991). Models log-variance, capturing asymmetric volatility. Input type determines the magnitude term automatically:
|
|
202
|
+
|
|
203
|
+
**Candle[] input** — Realized EGARCH. Magnitude uses Parkinson RV, leverage keeps directional return:
|
|
187
204
|
|
|
188
205
|
```
|
|
189
|
-
ln(sigma_t^2) = omega + alpha * (
|
|
206
|
+
ln(sigma_t^2) = omega + alpha * (sqrt(RV_{t-1} / sigma_{t-1}^2) - E[|Z|]) + gamma * z_{t-1} + beta * ln(sigma_{t-1}^2)
|
|
190
207
|
```
|
|
191
208
|
|
|
192
|
-
|
|
209
|
+
**number[] input** — Classical EGARCH. Magnitude uses |z|:
|
|
210
|
+
|
|
211
|
+
```
|
|
212
|
+
ln(sigma_t^2) = omega + alpha * (|z_{t-1}| - E[|Z|]) + gamma * z_{t-1} + beta * ln(sigma_{t-1}^2)
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
Where **z_t = epsilon_t / sigma_t** is the standardized residual and **E[|Z|]** is the expected absolute value of a standardized Student-t(df) variable:
|
|
216
|
+
|
|
217
|
+
```
|
|
218
|
+
E[|Z|] = sqrt((df-2)/pi) · Γ((df-1)/2) / Γ(df/2)
|
|
219
|
+
```
|
|
193
220
|
|
|
221
|
+
- **sqrt(RV/sigma^2)** is a more efficient estimate of |z| from OHLC data
|
|
194
222
|
- **gamma** < 0 — leverage effect (negative returns increase vol more than positive)
|
|
195
223
|
- No positivity constraints needed (log-variance is always real)
|
|
196
224
|
- Stationarity: **|beta| < 1**
|
|
197
225
|
- Unconditional variance: **E[sigma^2] ~ exp(omega / (1 - beta))**
|
|
226
|
+
- **df** > 2 — degrees of freedom (estimated jointly via multi-start Nelder-Mead)
|
|
227
|
+
|
|
228
|
+
### GJR-GARCH(1,1)
|
|
229
|
+
|
|
230
|
+
Threshold GARCH (Glosten, Jagannathan & Runkle, 1993). Captures leverage effect in variance space (unlike EGARCH which uses log-variance). Input type determines the innovation term automatically:
|
|
231
|
+
|
|
232
|
+
**Candle[] input** — Realized GJR-GARCH. Uses Parkinson RV as innovation, return sign as leverage indicator:
|
|
233
|
+
|
|
234
|
+
```
|
|
235
|
+
sigma_t^2 = omega + alpha * RV_{t-1} + gamma * RV_{t-1} * I(r_{t-1}<0) + beta * sigma_{t-1}^2
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
**number[] input** — Classical GJR-GARCH. Uses squared returns:
|
|
239
|
+
|
|
240
|
+
```
|
|
241
|
+
sigma_t^2 = omega + alpha * epsilon_{t-1}^2 + gamma * epsilon_{t-1}^2 * I(r_{t-1}<0) + beta * sigma_{t-1}^2
|
|
242
|
+
```
|
|
243
|
+
|
|
244
|
+
Where **I(r<0) = 1** when return is negative, **0** otherwise.
|
|
245
|
+
|
|
246
|
+
- **gamma** >= 0 — leverage coefficient (bad news amplifies variance by extra gamma)
|
|
247
|
+
- **omega** > 0, **alpha** >= 0, **beta** >= 0
|
|
248
|
+
- Stationarity: **alpha + gamma/2 + beta < 1** (half of innovations are negative on average)
|
|
249
|
+
- Unconditional variance: **E[sigma^2] = omega / (1 - alpha - gamma/2 - beta)**
|
|
250
|
+
- **df** > 2 — degrees of freedom (estimated jointly via multi-start Nelder-Mead)
|
|
251
|
+
|
|
252
|
+
Multi-step forecast uses effective persistence = alpha + gamma/2 + beta:
|
|
253
|
+
|
|
254
|
+
```
|
|
255
|
+
sigma_{t+h}^2 = omega + (alpha + gamma/2 + beta) * sigma_{t+h-1}^2
|
|
256
|
+
```
|
|
257
|
+
|
|
258
|
+
### HAR-RV
|
|
259
|
+
|
|
260
|
+
Heterogeneous Autoregressive model of Realized Variance (Corsi, 2009). Captures multi-scale volatility clustering via three overlapping horizons:
|
|
261
|
+
|
|
262
|
+
```
|
|
263
|
+
RV_{t+1} = beta_0 + beta_1 * RV_short + beta_2 * RV_medium + beta_3 * RV_long + epsilon
|
|
264
|
+
```
|
|
265
|
+
|
|
266
|
+
Where **RV_t** is the per-candle realized variance proxy:
|
|
267
|
+
|
|
268
|
+
- **OHLC input** — Parkinson (1980): **RV_t = (1 / (4·ln2)) · ln(H/L)^2** (~5× more efficient than close-to-close)
|
|
269
|
+
- **Prices-only input** — squared return: **RV_t = r_t^2** (fallback when no OHLC available)
|
|
270
|
+
|
|
271
|
+
Classic HAR-RV uses sum of intraday squared returns, but that requires tick/minute data. Parkinson uses the high-low range of each candle as a variance proxy — no intraday data needed.
|
|
272
|
+
|
|
273
|
+
- **RV_short** = mean(RV_t) — last 1 period (default)
|
|
274
|
+
- **RV_medium** = mean(RV_{t-4} ... RV_t) — last 5 periods
|
|
275
|
+
- **RV_long** = mean(RV_{t-21} ... RV_t) — last 22 periods
|
|
276
|
+
|
|
277
|
+
Parameter estimation via **OLS** (closed-form, always converges):
|
|
278
|
+
|
|
279
|
+
```
|
|
280
|
+
beta = (X'X)^{-1} X'y
|
|
281
|
+
```
|
|
282
|
+
|
|
283
|
+
After OLS, **df** (degrees of freedom) is profiled via grid search over the Student-t log-likelihood with the OLS-fitted variance series.
|
|
284
|
+
|
|
285
|
+
- Persistence: **beta_1 + beta_2 + beta_3 < 1** for stationarity
|
|
286
|
+
- Unconditional variance: **E[RV] = beta_0 / (1 - beta_1 - beta_2 - beta_3)**
|
|
287
|
+
- **R^2** measures explained variance in the regression
|
|
288
|
+
|
|
289
|
+
Multi-step forecast via iterative substitution: each predicted RV feeds back into the rolling components for subsequent steps.
|
|
290
|
+
|
|
291
|
+
### NoVaS
|
|
292
|
+
|
|
293
|
+
Normalizing and Variance-Stabilizing transformation (Politis, 2003). Model-free approach using the ARCH frame. Input type determines the innovation term automatically:
|
|
294
|
+
|
|
295
|
+
**Candle[] input** — Realized NoVaS. Uses Parkinson (1980) per-candle RV as innovation (~5× more efficient than squared returns):
|
|
296
|
+
|
|
297
|
+
```
|
|
298
|
+
sigma_t^2 = a_0 + a_1 * RV_{t-1} + a_2 * RV_{t-2} + ... + a_p * RV_{t-p}
|
|
299
|
+
RV_t = (1 / (4·ln2)) · ln(H/L)^2 (Parkinson estimator)
|
|
300
|
+
W_t = X_t / sigma_t
|
|
301
|
+
```
|
|
302
|
+
|
|
303
|
+
**number[] input** — Classical NoVaS. Uses squared returns:
|
|
304
|
+
|
|
305
|
+
```
|
|
306
|
+
sigma_t^2 = a_0 + a_1 * X_{t-1}^2 + a_2 * X_{t-2}^2 + ... + a_p * X_{t-p}^2
|
|
307
|
+
W_t = X_t / sigma_t
|
|
308
|
+
```
|
|
309
|
+
|
|
310
|
+
Parameters **a_0, ..., a_p** are chosen to minimize the non-normality of the transformed series {W_t}:
|
|
311
|
+
|
|
312
|
+
```
|
|
313
|
+
D^2 = S^2 + (K - 3)^2
|
|
314
|
+
```
|
|
315
|
+
|
|
316
|
+
where **S** = skewness and **K** = kurtosis of {W_t}. For perfect normality D^2 = 0.
|
|
317
|
+
|
|
318
|
+
- **a_0** > 0 — baseline variance
|
|
319
|
+
- **a_j** >= 0 — weight on j-th lagged innovation (RV or squared return)
|
|
320
|
+
- Stationarity: **sum(a_1 ... a_p) < 1**
|
|
321
|
+
- Unconditional variance: **E[sigma^2] = a_0 / (1 - sum(a_1 ... a_p))**
|
|
322
|
+
- Default lags: **p = 10** (configurable)
|
|
323
|
+
- Parkinson RV is less noisy than r², so Candle[] typically achieves lower D^2
|
|
324
|
+
|
|
325
|
+
Key difference from GARCH: parameters are found via **normality criterion** (D^2 minimization), not MLE. No distributional assumptions on the return series — truly model-free. Uses multi-start Nelder-Mead for optimization (6 restarts to escape local minima in the 11-dimensional D^2 landscape). After fitting, **df** is profiled via grid search over the Student-t log-likelihood (same as HAR-RV).
|
|
326
|
+
|
|
327
|
+
After D^2 optimization, weights are **rescaled via OLS** on the realized variance series to minimize forecast error. This keeps NoVaS model-free (D^2 selects lag structure) while making it QLIKE-competitive with HAR-RV.
|
|
328
|
+
|
|
329
|
+
**Two-stage calibration:**
|
|
330
|
+
|
|
331
|
+
- **Stage 1** — D^2 minimization: discovers lag structure via normality criterion (model-free). Produces `weights` (a_0, ..., a_p).
|
|
332
|
+
- **Stage 2** — OLS rescaling: regresses RV_{t+1} on sigma_t^2(D^2) to produce forecast-optimal weights. Produces `forecastWeights` = [beta_0, beta_1].
|
|
333
|
+
|
|
334
|
+
```
|
|
335
|
+
forecast_sigma_t^2 = beta_0 + beta_1 * sigma_t^2(D^2)
|
|
336
|
+
```
|
|
337
|
+
|
|
338
|
+
D^2 acts as a data-driven smoother over RV lags — more flexible than HAR-RV's fixed rolling means (1, 5, 22). OLS rescaling adjusts for bias with only 2 parameters, keeping the model robust on small samples with noisy per-candle RV.
|
|
339
|
+
|
|
340
|
+
Multi-step forecast: replace future innovations with sigma^2 (since E[RV] = E[X^2] = sigma^2), then rescale:
|
|
341
|
+
|
|
342
|
+
```
|
|
343
|
+
d2_{t+h} = a_0 + sum_j a_j * E[innovation_{t+h-j}]
|
|
344
|
+
sigma_{t+h}^2 = beta_0 + beta_1 * d2_{t+h}
|
|
345
|
+
```
|
|
198
346
|
|
|
199
347
|
### Model Auto-Selection
|
|
200
348
|
|
|
201
|
-
`predict` and `predictRange`
|
|
349
|
+
`predict` and `predictRange` fit all five models and pick the winner by **QLIKE** (Patton, 2011) — a neutral forecast-error metric that judges how well each model's variance series predicts realized variance:
|
|
350
|
+
|
|
351
|
+
```
|
|
352
|
+
QLIKE = (1/n) · sum[ RV_t / sigma_t^2 - ln(RV_t / sigma_t^2) - 1 ]
|
|
353
|
+
```
|
|
354
|
+
|
|
355
|
+
Lower QLIKE = better forecast. Unlike AIC (which favors MLE-calibrated models), QLIKE is neutral to calibration method — OLS, D^2-minimization, and MLE all compete on equal footing.
|
|
356
|
+
|
|
357
|
+
1. **GARCH-family pipeline**: fit GARCH, EGARCH, GJR-GARCH — pick best by AIC (fair since all three optimize Student-t LL)
|
|
358
|
+
2. **HAR-RV pipeline**: fit HAR-RV via OLS. Skip if persistence >= 1 or R^2 < 0
|
|
359
|
+
3. **NoVaS pipeline**: fit NoVaS via D^2 minimization + OLS rescaling. Skip if persistence >= 1
|
|
360
|
+
4. Compute Parkinson RV from candles. Score each pipeline's variance series by QLIKE. Lowest QLIKE wins
|
|
361
|
+
|
|
362
|
+
```
|
|
363
|
+
fitModel(candles)
|
|
364
|
+
|-- fitGarchFamily() --> min_AIC(GARCH, EGARCH, GJR-GARCH) --> QLIKE_1
|
|
365
|
+
|-- fitHarRv() --> HAR-RV (OLS) --> QLIKE_2
|
|
366
|
+
|-- fitNoVaS() --> NoVaS (D²) --> QLIKE_3
|
|
367
|
+
|-- rv = perCandleParkinson(candles)
|
|
368
|
+
\-- return min(QLIKE_1, QLIKE_2, QLIKE_3)
|
|
369
|
+
```
|
|
370
|
+
|
|
371
|
+
When given `Candle[]`, all five OHLC-aware models (GARCH, EGARCH, GJR-GARCH, HAR-RV, NoVaS) use Parkinson per-candle RV instead of squared returns, extracting ~5× more information from the same data.
|
|
372
|
+
|
|
373
|
+
### When Each Model Wins
|
|
374
|
+
|
|
375
|
+
The library fits all five models on every call and picks the best by QLIKE. Each model uses its own calibration method (MLE, OLS, or D^2) but they all compete on the same forecast-error metric. Here's what patterns in data favor each:
|
|
376
|
+
|
|
377
|
+
- **GARCH** — Volatility spikes after any big move (up or down equally), then gradually fades back to normal. No difference between bullish and bearish shocks. Classic symmetric mean-reverting vol clustering.
|
|
378
|
+
|
|
379
|
+
- **EGARCH** — Drops hit harder than pumps. A -5% candle causes way more volatility than a +5% candle. Strong "fear > greed" asymmetry. Works through a log-variance model so the asymmetry coefficient `gamma * z` directly amplifies negative shocks. Typical for stocks and BTC during risk-off periods.
|
|
380
|
+
|
|
381
|
+
- **GJR-GARCH** — Same idea as EGARCH (red candles increase vol more than green ones) but the effect is milder and simpler: when the return is negative, a bonus term `gamma * epsilon^2` is added to variance. When positive — nothing extra. A binary switch rather than a continuous asymmetry. Common in altcoins and less panic-prone markets.
|
|
202
382
|
|
|
203
|
-
1.
|
|
204
|
-
|
|
205
|
-
3.
|
|
383
|
+
- **HAR-RV** — Volatility has memory at multiple horizons. The model takes a single timeframe of candles and internally builds three scales: last candle's RV (short, lag 1), rolling average over 5 candles (medium), and rolling average over 22 candles (long). These three components are combined via OLS regression. Works well when different types of participants (scalpers, swing traders, institutions) all influence the same market at different speeds. If your asset has visible "rhythm" across day/week/month — HAR-RV will likely beat GARCH family (sideways, daily patterns).
|
|
384
|
+
|
|
385
|
+
- **NoVaS** — Volatility drifts or cycles without clear shock-and-decay patterns. Slow trend changes, regime shifts, compression/expansion phases, or "breathing" patterns that don't fit any parametric formula. Model-free: finds weights `a_0...a_p` that make the normalized series as close to Gaussian as possible (minimizes D^2 = skewness^2 + (kurtosis - 3)^2). No assumptions about the distribution shape.
|
|
206
386
|
|
|
207
387
|
### Variance Estimators
|
|
208
388
|
|
|
@@ -222,6 +402,24 @@ sigma^2_GK = (1/n) * sum[ 0.5 * ln(H/L)^2 - (2*ln2 - 1) * ln(C/O)^2 ]
|
|
|
222
402
|
|
|
223
403
|
~5x more efficient than close-to-close variance.
|
|
224
404
|
|
|
405
|
+
### Student-t Log-Likelihood
|
|
406
|
+
|
|
407
|
+
All five models use a **Student-t** distribution for log-likelihood computation. Financial return series exhibit fat tails (excess kurtosis), and the Student-t captures this with an additional **degrees of freedom (df)** parameter:
|
|
408
|
+
|
|
409
|
+
- **df ~ 3–10**: Heavy tails (common in crypto/equity returns)
|
|
410
|
+
- **df ~ 20–50**: Mild excess kurtosis
|
|
411
|
+
- **df → ∞**: Thin tails
|
|
412
|
+
|
|
413
|
+
For GARCH, EGARCH, and GJR-GARCH, **df** is optimized jointly with the other parameters via Nelder-Mead. For HAR-RV and NoVaS, **df** is profiled via a two-pass grid search (coarse 2.5–50, then fine ±1 around the best) after the main optimization.
|
|
414
|
+
|
|
415
|
+
Helper functions exported from the library:
|
|
416
|
+
|
|
417
|
+
- `logGamma(x)` — Lanczos approximation (g=7, n=9), ~15-digit accuracy
|
|
418
|
+
- `studentTNegLL(returns, varianceSeries, df)` — Full negative log-likelihood
|
|
419
|
+
- `expectedAbsStudentT(df)` — E[|Z|] for standardized t(df), used in EGARCH centering
|
|
420
|
+
- `profileStudentTDf(returns, varianceSeries)` — Grid search for optimal df
|
|
421
|
+
- `qlike(varianceSeries, rv)` — QLIKE loss (Patton, 2011) for volatility forecast evaluation
|
|
422
|
+
|
|
225
423
|
### Reliability Check
|
|
226
424
|
|
|
227
425
|
The `reliable` flag in `PredictionResult` is `true` when all three conditions hold:
|
|
@@ -232,25 +430,68 @@ The `reliable` flag in `PredictionResult` is `true` when all three conditions ho
|
|
|
232
430
|
|
|
233
431
|
### Optimization
|
|
234
432
|
|
|
235
|
-
|
|
433
|
+
GARCH/EGARCH/GJR-GARCH parameters (including df) are estimated via **multi-start Nelder-Mead** simplex method (derivative-free). Each model runs Nelder-Mead from multiple deterministic starting points (golden-ratio quasi-random perturbation) and keeps the best result — this escapes local minima that single-start NM would get stuck in, especially important for higher-dimensional problems like NoVaS (11 parameters).
|
|
434
|
+
|
|
435
|
+
| Model | Parameters | Restarts | Total NM runs |
|
|
436
|
+
|-------|-----------|----------|---------------|
|
|
437
|
+
| GARCH | 4 (omega, alpha, beta, df) | 3 | 4 |
|
|
438
|
+
| EGARCH | 5 (omega, alpha, gamma, beta, df) | 4 | 5 |
|
|
439
|
+
| GJR-GARCH | 5 (omega, alpha, gamma, beta, df) | 4 | 5 |
|
|
440
|
+
| NoVaS | p+1 (a_0...a_p, default p=10) | 6 | 7 |
|
|
441
|
+
| HAR-RV | 4 (beta_0...beta_3) | — | OLS (closed-form) |
|
|
442
|
+
|
|
443
|
+
Default per run: 1000 iterations (2000 for NoVaS D^2), tolerance 1e-8. Initial simplex uses 20% perturbation from x0 for broader exploration. HAR-RV uses **OLS** (exact solution in one step) + df profiling.
|
|
444
|
+
|
|
445
|
+
Within the GARCH family, model comparison uses **AIC** (2k - 2LL) — fair since all three optimize the same Student-t LL objective. Across model families (GARCH vs HAR-RV vs NoVaS), comparison uses **QLIKE** (Patton, 2011):
|
|
446
|
+
|
|
447
|
+
```
|
|
448
|
+
QLIKE = (1/n) · sum[ RV_t / sigma_t^2 - ln(RV_t / sigma_t^2) - 1 ]
|
|
449
|
+
```
|
|
450
|
+
|
|
451
|
+
where RV_t is Parkinson per-candle realized variance and sigma_t^2 is the model's fitted conditional variance. QLIKE is the standard loss function for volatility forecast evaluation — it is neutral to calibration method (MLE, OLS, D^2 all compete fairly).
|
|
236
452
|
|
|
237
453
|
## Tests
|
|
238
454
|
|
|
239
|
-
**
|
|
455
|
+
**923 tests** across **22 test files**. All passing.
|
|
240
456
|
|
|
241
457
|
| Category | Files | Tests | What's covered |
|
|
242
458
|
|----------|-------|-------|----------------|
|
|
243
|
-
| Mathematical formulas | `math.test.ts` | 45 | GARCH/EGARCH variance recursion, log-likelihood, forecast formulas, AIC/BIC, Yang-Zhang, Garman-Klass, Ljung-Box, chi-squared |
|
|
459
|
+
| Mathematical formulas | `math.test.ts` | 45 | GARCH/EGARCH variance recursion, log-likelihood, forecast formulas, AIC/BIC, QLIKE, Yang-Zhang, Garman-Klass, Ljung-Box, chi-squared |
|
|
460
|
+
| Math coverage | `math-coverage.test.ts` | 79 | Parkinson formula verification, rv↔returns alignment, H=L fallback, Parkinson-based forecast, candle validation, reliable flag cascade, backtest validity, numerical precision, cross-model consistency, Realized GARCH/EGARCH/GJR-GARCH Candle[] vs number[], perCandleParkinson shared function |
|
|
244
461
|
| Full pipeline coverage | `plan-coverage.test.ts` | 73 | End-to-end: fit, forecast, predict, predictRange, backtest, model selection |
|
|
245
462
|
| GARCH unit | `garch.test.ts` | 10 | Parameter estimation, variance series, forecast convergence, candle vs price input |
|
|
246
|
-
| EGARCH unit | `egarch.test.ts` | 11 | Leverage detection, asymmetric volatility, model comparison
|
|
247
|
-
|
|
|
248
|
-
|
|
|
249
|
-
|
|
|
250
|
-
|
|
|
463
|
+
| EGARCH unit | `egarch.test.ts` | 11 | Leverage detection, asymmetric volatility, model comparison |
|
|
464
|
+
| GJR-GARCH unit | `gjr-garch.test.ts` | 86 | Variance recursion (r² and Parkinson), indicator function I(r<0), forecast formula (one-step + multi-step), constraint barriers, computed fields, AIC/BIC numParams=5, estimation properties (perturbation, determinism), numerical stability, degenerate params, Realized path (Candle[] vs number[], flat candles, bad OHLC), options forwarding, immutability, instance isolation, cross-model consistency, scale invariance, property-based fuzz, predict/predictRange/backtest integration |
|
|
465
|
+
| HAR-RV unit | `har.test.ts` | 138 | OLS regression, R^2, Parkinson RV proxy, forecast convergence, multi-step iterative substitution, rolling RV components, edge cases, fuzz, integration with predict, OLS orthogonality, TSS=RSS+ESS, normal equations, regression snapshots, mutation safety |
|
|
466
|
+
| NoVaS unit | `novas.test.ts` | 109 | D^2 minimization, normality improvement, variance series, forecast convergence, edge cases, fuzz, integration with predict, determinism, scale invariance |
|
|
467
|
+
| Optimizer | `optimizer.test.ts`, `optimizer-shrink.test.ts` | 20 | Nelder-Mead on Rosenbrock/quadratic/parabolic, convergence, shrinking, multi-start (Rastrigin escape, high-dimensional, equivalence) |
|
|
468
|
+
| Statistical properties | `properties.test.ts` | 15 | Parameter recovery from synthetic data, local LL maximum, unconditional variance, GJR-GARCH forecast convergence and model selection |
|
|
469
|
+
| Regression | `regression.test.ts` | 11 | Parameter recovery, deterministic outputs, cross-model consistency for GARCH/EGARCH/GJR-GARCH |
|
|
470
|
+
| Stability | `stability.test.ts` | 12 | Long-term forecast behavior, variance convergence, GJR-GARCH near-constant and outlier handling |
|
|
251
471
|
| Robustness | `robustness.test.ts` | 53 | Extreme moves, stress scenarios |
|
|
252
|
-
|
|
|
253
|
-
|
|
|
472
|
+
| Realized models | `realized-garch.test.ts` | 83 | Candle[] vs number[] for GARCH/EGARCH/GJR-GARCH/NoVaS, Parkinson RV edge cases, flat candles, extreme H/L, scale invariance, all-identical OHLC, minimum-length boundary, D² comparison, predict fallback, **ground-truth volatility recovery** (see below) |
|
|
473
|
+
| Edge cases | `edge-cases.test.ts`, `coverage-gaps*.test.ts` | 165 | Insufficient data, near-unit-root, zero returns, constant prices, negative prices, overflow/underflow, trending data, 10K+ data points, GJR-GARCH immutability and instance isolation, EGARCH df≤2 fallback, logGamma/expectedAbsStudentT/qlike edge cases |
|
|
474
|
+
| Miscellaneous | `misc.test.ts` | 13 | Integration scenarios, different intervals, immutability |
|
|
475
|
+
|
|
476
|
+
### Ground-Truth Volatility Test
|
|
477
|
+
|
|
478
|
+
The test suite includes an end-to-end integration test that verifies `predict` recovers known volatility from synthetic data. This is the strongest correctness guarantee — it proves the entire pipeline (data generation, model fitting, auto-selection, forecasting) produces numerically accurate results.
|
|
479
|
+
|
|
480
|
+
**How it works:**
|
|
481
|
+
|
|
482
|
+
1. Generate 500 OHLC candles with **known constant per-period volatility** sigma_true (returns are iid N(0, sigma_true^2), high/low simulated via Brownian bridge noise)
|
|
483
|
+
2. Run `predict()` on these candles — auto-selects the best model, fits parameters, produces a 1-step forecast
|
|
484
|
+
3. Verify predicted sigma matches sigma_true
|
|
485
|
+
|
|
486
|
+
**What is verified:**
|
|
487
|
+
|
|
488
|
+
| Test | Assertion |
|
|
489
|
+
|------|-----------|
|
|
490
|
+
| sigma_true = 0.2%, 1%, 3% | Relative error < 50% for each |
|
|
491
|
+
| Monotonicity | sigma_true_1 < sigma_true_2 < sigma_true_3 implies predicted_1 < predicted_2 < predicted_3 |
|
|
492
|
+
| Median accuracy (20 seeds) | Median relative error < 30% across 20 independent runs (sigma_true = 1%) |
|
|
493
|
+
| +-1 sigma hit rate (Monte Carlo) | Out-of-sample +-1 sigma corridor captures 45–90% of actual next moves across 30 trials (theoretical: 68.27%) |
|
|
494
|
+
| Proportionality | 2x sigma_true produces ~2x predicted sigma (ratio between 1.2x and 3.5x) |
|
|
254
495
|
|
|
255
496
|
```bash
|
|
256
497
|
npm test # run all tests
|