garch 1.0.2 → 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 +416 -121
- package/build/index.cjs +1329 -35
- package/build/index.mjs +1311 -36
- package/package.json +2 -1
- package/types.d.ts +346 -3
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
|
|
@@ -13,193 +14,487 @@
|
|
|
13
14
|
npm install garch
|
|
14
15
|
```
|
|
15
16
|
|
|
16
|
-
##
|
|
17
|
+
## API
|
|
17
18
|
|
|
18
|
-
###
|
|
19
|
+
### `predict(candles, interval, currentPrice?)`
|
|
20
|
+
|
|
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.
|
|
19
22
|
|
|
20
23
|
```typescript
|
|
21
|
-
import {
|
|
24
|
+
import { predict } from 'garch';
|
|
25
|
+
import type { Candle } from 'garch';
|
|
22
26
|
|
|
23
|
-
|
|
24
|
-
const prices = [100, 101, 99, 102, 98, ...];
|
|
25
|
-
const result = calibrateGarch(prices, { periodsPerYear: 252 });
|
|
27
|
+
const candles: Candle[] = await fetchCandles('BTCUSDT', '4h', 200);
|
|
26
28
|
|
|
27
|
-
|
|
29
|
+
const result = predict(candles, '4h');
|
|
28
30
|
// {
|
|
29
|
-
//
|
|
30
|
-
//
|
|
31
|
-
//
|
|
32
|
-
//
|
|
33
|
-
//
|
|
34
|
-
//
|
|
31
|
+
// currentPrice: 97500,
|
|
32
|
+
// sigma: 0.012, // 1.2% expected move
|
|
33
|
+
// move: 1170, // +/-$1170 price range
|
|
34
|
+
// upperPrice: 98670, // ceiling for next candle
|
|
35
|
+
// lowerPrice: 96330, // floor for next candle
|
|
36
|
+
// modelType: 'egarch',
|
|
37
|
+
// reliable: true
|
|
35
38
|
// }
|
|
36
39
|
|
|
37
|
-
//
|
|
38
|
-
const
|
|
39
|
-
const fit = model.fit();
|
|
40
|
-
|
|
41
|
-
// Get variance series
|
|
42
|
-
const variance = model.getVarianceSeries(fit.params);
|
|
43
|
-
|
|
44
|
-
// Forecast 10 periods ahead
|
|
45
|
-
const forecast = model.forecast(fit.params, 10);
|
|
46
|
-
console.log(forecast.annualized); // [32.1, 31.9, 31.8, ...]
|
|
40
|
+
// Pass VWAP or any reference price as 3rd argument
|
|
41
|
+
const result = predict(candles, '4h', vwap);
|
|
47
42
|
```
|
|
48
43
|
|
|
49
|
-
|
|
44
|
+
**Parameters:**
|
|
45
|
+
|
|
46
|
+
| Parameter | Type | Default | Description |
|
|
47
|
+
|-----------|------|---------|-------------|
|
|
48
|
+
| `candles` | `Candle[]` | required | OHLCV candle data |
|
|
49
|
+
| `interval` | `CandleInterval` | required | Candle timeframe |
|
|
50
|
+
| `currentPrice` | `number` | last close | Reference price to center the corridor |
|
|
50
51
|
|
|
51
|
-
|
|
52
|
+
**Returns:** `PredictionResult`
|
|
52
53
|
|
|
53
54
|
```typescript
|
|
54
|
-
|
|
55
|
+
interface PredictionResult {
|
|
56
|
+
currentPrice: number; // Reference price
|
|
57
|
+
sigma: number; // One-period volatility (decimal, e.g. 0.012 = 1.2%)
|
|
58
|
+
move: number; // +/- price move = currentPrice * sigma
|
|
59
|
+
upperPrice: number; // currentPrice + move
|
|
60
|
+
lowerPrice: number; // currentPrice - move
|
|
61
|
+
modelType: 'garch' | 'egarch' | 'gjr-garch' | 'har-rv' | 'novas'; // Auto-selected model
|
|
62
|
+
reliable: boolean; // Quality flag (convergence + persistence + Ljung-Box)
|
|
63
|
+
}
|
|
64
|
+
```
|
|
55
65
|
|
|
56
|
-
|
|
57
|
-
const returns = calculateReturnsFromPrices(prices);
|
|
58
|
-
const leverage = checkLeverageEffect(returns);
|
|
59
|
-
console.log(leverage);
|
|
60
|
-
// { negativeVol: 0.021, positiveVol: 0.015, ratio: 1.4, recommendation: 'egarch' }
|
|
66
|
+
---
|
|
61
67
|
|
|
62
|
-
|
|
63
|
-
const result = calibrateEgarch(prices, { periodsPerYear: 365 }); // crypto = 365
|
|
68
|
+
### `predictRange(candles, interval, steps, currentPrice?)`
|
|
64
69
|
|
|
65
|
-
|
|
70
|
+
Forecast cumulative expected price range over multiple candles. Cumulative sigma = sqrt(sigma_1^2 + sigma_2^2 + ... + sigma_n^2). Use for swing trades where you hold across multiple periods.
|
|
71
|
+
|
|
72
|
+
```typescript
|
|
73
|
+
import { predictRange } from 'garch';
|
|
74
|
+
|
|
75
|
+
const range = predictRange(candles, '4h', 5);
|
|
66
76
|
// {
|
|
67
|
-
//
|
|
68
|
-
//
|
|
69
|
-
//
|
|
70
|
-
//
|
|
71
|
-
//
|
|
72
|
-
//
|
|
73
|
-
//
|
|
77
|
+
// currentPrice: 97500,
|
|
78
|
+
// sigma: 0.027, // cumulative ~2.7% over 5 candles
|
|
79
|
+
// move: 2632, // +/-$2632 total range
|
|
80
|
+
// upperPrice: 100132,
|
|
81
|
+
// lowerPrice: 94868,
|
|
82
|
+
// modelType: 'egarch',
|
|
83
|
+
// reliable: true
|
|
74
84
|
// }
|
|
75
85
|
```
|
|
76
86
|
|
|
77
|
-
|
|
87
|
+
**Parameters:**
|
|
88
|
+
|
|
89
|
+
| Parameter | Type | Default | Description |
|
|
90
|
+
|-----------|------|---------|-------------|
|
|
91
|
+
| `candles` | `Candle[]` | required | OHLCV candle data |
|
|
92
|
+
| `interval` | `CandleInterval` | required | Candle timeframe |
|
|
93
|
+
| `steps` | `number` | required | Number of candles to forecast over |
|
|
94
|
+
| `currentPrice` | `number` | last close | Reference price |
|
|
95
|
+
|
|
96
|
+
**Returns:** `PredictionResult` (same structure as `predict`)
|
|
97
|
+
|
|
98
|
+
---
|
|
99
|
+
|
|
100
|
+
### `backtest(candles, interval, requiredPercent?)`
|
|
101
|
+
|
|
102
|
+
Walk-forward validation of `predict`. Uses 75% of candles for fitting, 25% for testing. Checks if the model's +-1 sigma corridor captures actual price moves at the required hit rate.
|
|
78
103
|
|
|
79
104
|
```typescript
|
|
80
|
-
import {
|
|
105
|
+
import { backtest } from 'garch';
|
|
106
|
+
|
|
107
|
+
backtest(candles, '4h'); // true -- hit rate >= 68% (default)
|
|
108
|
+
backtest(candles, '4h', 50); // true -- hit rate >= 50% (custom)
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
**Parameters:**
|
|
112
|
+
|
|
113
|
+
| Parameter | Type | Default | Description |
|
|
114
|
+
|-----------|------|---------|-------------|
|
|
115
|
+
| `candles` | `Candle[]` | required | OHLCV candle data |
|
|
116
|
+
| `interval` | `CandleInterval` | required | Candle timeframe |
|
|
117
|
+
| `requiredPercent` | `number` | `68` | Minimum hit rate (+-1 sigma ~ 68% theoretically) |
|
|
118
|
+
|
|
119
|
+
**Returns:** `boolean`
|
|
120
|
+
|
|
121
|
+
---
|
|
122
|
+
|
|
123
|
+
## Supported Intervals
|
|
124
|
+
|
|
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.
|
|
139
|
+
|
|
140
|
+
## Timeframes
|
|
141
|
+
|
|
142
|
+
The `periodsPerYear` value controls annualization of volatility. When using `predict`/`predictRange`/`backtest`, this is handled automatically via the `interval` parameter. When using `Garch`/`Egarch` classes directly, pass `periodsPerYear` manually.
|
|
143
|
+
|
|
144
|
+
| Timeframe | `periodsPerYear` | Notes |
|
|
145
|
+
|-----------|-----------------|-------|
|
|
146
|
+
| **1m** | `525,600` | 1440/day x 365 |
|
|
147
|
+
| **3m** | `175,200` | 480/day x 365 |
|
|
148
|
+
| **5m** | `105,120` | 288/day x 365 |
|
|
149
|
+
| **15m** | `35,040` | 96/day x 365 |
|
|
150
|
+
| **30m** | `17,520` | 48/day x 365 |
|
|
151
|
+
| **1h** | `8,760` | 24/day x 365 |
|
|
152
|
+
| **2h** | `4,380` | 12/day x 365 |
|
|
153
|
+
| **4h** | `2,190` | 6/day x 365 |
|
|
154
|
+
| **6h** | `1,460` | 4/day x 365 |
|
|
155
|
+
| **8h** | `1,095` | 3/day x 365 |
|
|
156
|
+
|
|
157
|
+
Lower timeframes contain more microstructure noise — use larger datasets to compensate.
|
|
158
|
+
|
|
159
|
+
## Math
|
|
160
|
+
|
|
161
|
+
### GARCH(1,1)
|
|
162
|
+
|
|
163
|
+
Conditional variance model (Bollerslev, 1986). Input type determines the innovation term automatically:
|
|
81
164
|
|
|
82
|
-
|
|
83
|
-
{ open: 100, high: 102, low: 99, close: 101, volume: 1000 },
|
|
84
|
-
{ open: 101, high: 103, low: 100, close: 99, volume: 1200 },
|
|
85
|
-
// ...
|
|
86
|
-
];
|
|
165
|
+
**Candle[] input** — Realized GARCH (Hansen & Huang, 2016). Uses Parkinson (1980) per-candle realized variance proxy (~5× more efficient than squared returns):
|
|
87
166
|
|
|
88
|
-
|
|
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)
|
|
89
170
|
```
|
|
90
171
|
|
|
91
|
-
|
|
172
|
+
**number[] input** — Classical GARCH. Uses squared returns:
|
|
92
173
|
|
|
93
|
-
```
|
|
94
|
-
|
|
174
|
+
```
|
|
175
|
+
sigma_t^2 = omega + alpha * epsilon_{t-1}^2 + beta * sigma_{t-1}^2
|
|
176
|
+
```
|
|
95
177
|
|
|
96
|
-
|
|
97
|
-
|
|
178
|
+
- **omega** > 0 — long-run variance anchor
|
|
179
|
+
- **alpha** >= 0 — shock reaction (how much yesterday's surprise matters)
|
|
180
|
+
- **beta** >= 0 — persistence (memory of past variance)
|
|
181
|
+
- Stationarity constraint: **alpha + beta < 1**
|
|
182
|
+
- Unconditional variance: **E[sigma^2] = omega / (1 - alpha - beta)**
|
|
98
183
|
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
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:
|
|
185
|
+
|
|
186
|
+
```
|
|
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)) ]
|
|
103
189
|
```
|
|
104
190
|
|
|
105
|
-
|
|
191
|
+
- **df** > 2 — degrees of freedom (estimated jointly with omega, alpha, beta via multi-start Nelder-Mead)
|
|
106
192
|
|
|
107
|
-
|
|
193
|
+
Multi-step forecast converges to unconditional variance (E[RV] = sigma^2, so recursion is identical):
|
|
108
194
|
|
|
109
|
-
|
|
195
|
+
```
|
|
196
|
+
sigma_{t+h}^2 = omega + (alpha + beta) * sigma_{t+h-1}^2
|
|
197
|
+
```
|
|
110
198
|
|
|
111
|
-
|
|
112
|
-
- `data`: `Candle[]` or `number[]` (prices)
|
|
113
|
-
- `options.periodsPerYear`: Annualization factor (default: 252)
|
|
114
|
-
- `options.maxIter`: Maximum optimizer iterations (default: 1000)
|
|
115
|
-
- `options.tol`: Convergence tolerance (default: 1e-8)
|
|
199
|
+
### EGARCH(1,1)
|
|
116
200
|
|
|
117
|
-
|
|
201
|
+
Exponential GARCH (Nelson, 1991). Models log-variance, capturing asymmetric volatility. Input type determines the magnitude term automatically:
|
|
118
202
|
|
|
119
|
-
|
|
203
|
+
**Candle[] input** — Realized EGARCH. Magnitude uses Parkinson RV, leverage keeps directional return:
|
|
120
204
|
|
|
121
|
-
|
|
205
|
+
```
|
|
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)
|
|
207
|
+
```
|
|
122
208
|
|
|
123
|
-
**
|
|
209
|
+
**number[] input** — Classical EGARCH. Magnitude uses |z|:
|
|
124
210
|
|
|
125
|
-
|
|
211
|
+
```
|
|
212
|
+
ln(sigma_t^2) = omega + alpha * (|z_{t-1}| - E[|Z|]) + gamma * z_{t-1} + beta * ln(sigma_{t-1}^2)
|
|
213
|
+
```
|
|
126
214
|
|
|
127
|
-
|
|
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:
|
|
128
216
|
|
|
129
|
-
|
|
217
|
+
```
|
|
218
|
+
E[|Z|] = sqrt((df-2)/pi) · Γ((df-1)/2) / Γ(df/2)
|
|
219
|
+
```
|
|
130
220
|
|
|
131
|
-
**
|
|
221
|
+
- **sqrt(RV/sigma^2)** is a more efficient estimate of |z| from OHLC data
|
|
222
|
+
- **gamma** < 0 — leverage effect (negative returns increase vol more than positive)
|
|
223
|
+
- No positivity constraints needed (log-variance is always real)
|
|
224
|
+
- Stationarity: **|beta| < 1**
|
|
225
|
+
- Unconditional variance: **E[sigma^2] ~ exp(omega / (1 - beta))**
|
|
226
|
+
- **df** > 2 — degrees of freedom (estimated jointly via multi-start Nelder-Mead)
|
|
132
227
|
|
|
133
|
-
###
|
|
228
|
+
### GJR-GARCH(1,1)
|
|
134
229
|
|
|
135
|
-
|
|
136
|
-
- `.fit(options?)` - Calibrate parameters
|
|
137
|
-
- `.getVarianceSeries(params)` - Compute conditional variance
|
|
138
|
-
- `.forecast(params, steps)` - Multi-step variance forecast
|
|
139
|
-
- `.getReturns()` - Get computed returns
|
|
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:
|
|
140
231
|
|
|
141
|
-
|
|
232
|
+
**Candle[] input** — Realized GJR-GARCH. Uses Parkinson RV as innovation, return sign as leverage indicator:
|
|
142
233
|
|
|
143
|
-
|
|
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
|
+
```
|
|
144
237
|
|
|
145
|
-
|
|
146
|
-
|-----------|-----------------|-------|
|
|
147
|
-
| **1d** | `252` (default) | Trading days per year |
|
|
148
|
-
| **4h** | `1512` | 252 × 6 |
|
|
149
|
-
| **1h** | `6048` (crypto) / `1638` (stocks) | Crypto trades 24/7, stocks ~6.5h/day |
|
|
150
|
-
| **15m** | `24192` (crypto) / `6552` (stocks) | 96 or 26 bars per day × 252 |
|
|
151
|
-
| **1m** | `362880` (crypto) / `393120` (stocks) | 1440 or 390 bars per day × 252 |
|
|
238
|
+
**number[] input** — Classical GJR-GARCH. Uses squared returns:
|
|
152
239
|
|
|
153
|
-
```
|
|
154
|
-
|
|
155
|
-
|
|
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)
|
|
156
251
|
|
|
157
|
-
|
|
158
|
-
calibrateGarch(prices, { periodsPerYear: 1512 });
|
|
252
|
+
Multi-step forecast uses effective persistence = alpha + gamma/2 + beta:
|
|
159
253
|
|
|
160
|
-
|
|
161
|
-
|
|
254
|
+
```
|
|
255
|
+
sigma_{t+h}^2 = omega + (alpha + gamma/2 + beta) * sigma_{t+h-1}^2
|
|
162
256
|
```
|
|
163
257
|
|
|
164
|
-
|
|
258
|
+
### HAR-RV
|
|
165
259
|
|
|
166
|
-
|
|
260
|
+
Heterogeneous Autoregressive model of Realized Variance (Corsi, 2009). Captures multi-scale volatility clustering via three overlapping horizons:
|
|
167
261
|
|
|
168
|
-
|
|
262
|
+
```
|
|
263
|
+
RV_{t+1} = beta_0 + beta_1 * RV_short + beta_2 * RV_medium + beta_3 * RV_long + epsilon
|
|
264
|
+
```
|
|
169
265
|
|
|
170
|
-
|
|
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):
|
|
171
278
|
|
|
172
279
|
```
|
|
173
|
-
|
|
280
|
+
beta = (X'X)^{-1} X'y
|
|
174
281
|
```
|
|
175
282
|
|
|
176
|
-
|
|
177
|
-
- `α` (alpha) ≥ 0: reaction to shocks
|
|
178
|
-
- `β` (beta) ≥ 0: persistence
|
|
179
|
-
- Stationarity: α + β < 1
|
|
283
|
+
After OLS, **df** (degrees of freedom) is profiled via grid search over the Student-t log-likelihood with the OLS-fitted variance series.
|
|
180
284
|
|
|
181
|
-
|
|
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):
|
|
182
296
|
|
|
183
297
|
```
|
|
184
|
-
|
|
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
|
|
185
301
|
```
|
|
186
302
|
|
|
187
|
-
|
|
188
|
-
- No positivity constraints needed (models log-variance)
|
|
189
|
-
- `|β|` < 1 for stationarity
|
|
303
|
+
**number[] input** — Classical NoVaS. Uses squared returns:
|
|
190
304
|
|
|
191
|
-
|
|
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
|
+
```
|
|
192
309
|
|
|
193
|
-
|
|
194
|
-
import { calibrateGarch, calibrateEgarch } from 'garch';
|
|
310
|
+
Parameters **a_0, ..., a_p** are chosen to minimize the non-normality of the transformed series {W_t}:
|
|
195
311
|
|
|
196
|
-
|
|
197
|
-
|
|
312
|
+
```
|
|
313
|
+
D^2 = S^2 + (K - 3)^2
|
|
314
|
+
```
|
|
198
315
|
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
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
|
+
```
|
|
346
|
+
|
|
347
|
+
### Model Auto-Selection
|
|
348
|
+
|
|
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.
|
|
382
|
+
|
|
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.
|
|
386
|
+
|
|
387
|
+
### Variance Estimators
|
|
388
|
+
|
|
389
|
+
**Yang-Zhang** (used as initial variance for model fitting):
|
|
390
|
+
|
|
391
|
+
```
|
|
392
|
+
sigma^2_YZ = sigma^2_overnight + k * sigma^2_close + (1-k) * sigma^2_RS
|
|
393
|
+
```
|
|
394
|
+
|
|
395
|
+
Combines overnight gaps, open-to-close moves, and Rogers-Satchell intraday range. More robust than close-to-close for OHLC data.
|
|
396
|
+
|
|
397
|
+
**Garman-Klass** (fallback):
|
|
398
|
+
|
|
399
|
+
```
|
|
400
|
+
sigma^2_GK = (1/n) * sum[ 0.5 * ln(H/L)^2 - (2*ln2 - 1) * ln(C/O)^2 ]
|
|
401
|
+
```
|
|
402
|
+
|
|
403
|
+
~5x more efficient than close-to-close variance.
|
|
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
|
+
|
|
423
|
+
### Reliability Check
|
|
424
|
+
|
|
425
|
+
The `reliable` flag in `PredictionResult` is `true` when all three conditions hold:
|
|
426
|
+
|
|
427
|
+
1. Optimizer converged
|
|
428
|
+
2. Persistence < 0.999 (not near unit root)
|
|
429
|
+
3. Ljung-Box test on squared standardized residuals: p-value >= 0.05 (no residual autocorrelation)
|
|
430
|
+
|
|
431
|
+
### Optimization
|
|
432
|
+
|
|
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).
|
|
452
|
+
|
|
453
|
+
## Tests
|
|
454
|
+
|
|
455
|
+
**923 tests** across **22 test files**. All passing.
|
|
456
|
+
|
|
457
|
+
| Category | Files | Tests | What's covered |
|
|
458
|
+
|----------|-------|-------|----------------|
|
|
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 |
|
|
461
|
+
| Full pipeline coverage | `plan-coverage.test.ts` | 73 | End-to-end: fit, forecast, predict, predictRange, backtest, model selection |
|
|
462
|
+
| GARCH unit | `garch.test.ts` | 10 | Parameter estimation, variance series, forecast convergence, candle vs price input |
|
|
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 |
|
|
471
|
+
| Robustness | `robustness.test.ts` | 53 | Extreme moves, stress scenarios |
|
|
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) |
|
|
495
|
+
|
|
496
|
+
```bash
|
|
497
|
+
npm test # run all tests
|
|
203
498
|
```
|
|
204
499
|
|
|
205
500
|
## License
|