-
Notifications
You must be signed in to change notification settings - Fork 248
/
volatility.py
3740 lines (3186 loc) · 119 KB
/
volatility.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Volatility processes for ARCH model estimation. All volatility processes must
inherit from :class:`VolatilityProcess` and provide the same methods with the
same inputs.
"""
from __future__ import annotations
from abc import ABCMeta, abstractmethod
from collections.abc import Sequence
import itertools
from typing import TYPE_CHECKING, cast
from warnings import warn
import numpy as np
from numpy.random import RandomState
from scipy.special import gammaln
from arch.typing import (
ArrayLike1D,
Float64Array,
ForecastingMethod,
Int32Array,
RNGType,
)
from arch.univariate.distribution import Normal
from arch.utility.array import AbstractDocStringInheritor, ensure1d
from arch.utility.exceptions import (
InitialValueWarning,
ValueWarning,
initial_value_warning,
)
if TYPE_CHECKING:
from arch.univariate import recursions_python as rec
else:
try:
from arch.univariate import recursions as rec
except ImportError:
from arch.univariate import recursions_python as rec
__all__ = [
"GARCH",
"ARCH",
"HARCH",
"ConstantVariance",
"EWMAVariance",
"RiskMetrics2006",
"EGARCH",
"FIGARCH",
"FixedVariance",
"BootstrapRng",
"MIDASHyperbolic",
"VolatilityProcess",
]
def _common_names(p: int, o: int, q: int) -> list[str]:
names = ["omega"]
names.extend(["alpha[" + str(i + 1) + "]" for i in range(p)])
names.extend(["gamma[" + str(i + 1) + "]" for i in range(o)])
names.extend(["beta[" + str(i + 1) + "]" for i in range(q)])
return names
class BootstrapRng:
"""
Simple fake RNG used to transform bootstrap-based forecasting into a standard
simulation forecasting problem
Parameters
----------
std_resid : ndarray
Array containing standardized residuals
start : int
Location of first forecast
random_state : RandomState, optional
NumPy RandomState instance
"""
def __init__(
self,
std_resid: Float64Array,
start: int,
random_state: RandomState | None = None,
) -> None:
if start <= 0 or start > std_resid.shape[0]:
raise ValueError("start must be > 0 and <= len(std_resid).")
self.std_resid: Float64Array = std_resid
self.start: int = start
self._index = start
if random_state is None:
self._random_state = RandomState()
elif isinstance(random_state, RandomState):
self._random_state = random_state
else:
raise TypeError("random_state must be a NumPy RandomState instance.")
@property
def random_state(self) -> RandomState:
return self._random_state
def rng(self) -> RNGType:
def _rng(size: int | tuple[int, ...]) -> Float64Array:
if self._index >= self.std_resid.shape[0]:
raise IndexError("not enough data points.")
index = self._random_state.random_sample(size)
int_index = np.floor((self._index + 1) * index)
int_index = int_index.astype(np.int64)
self._index += 1
return self.std_resid[int_index]
return _rng
def ewma_recursion(
lam: float, resids: Float64Array, sigma2: Float64Array, nobs: int, backcast: float
) -> Float64Array:
"""
Compute variance recursion for EWMA/RiskMetrics Variance
Parameters
----------
lam : float
Smoothing parameter
resids : ndarray
Residuals to use in the recursion
sigma2 : ndarray
Conditional variances with same shape as resids
nobs : int
Length of resids
backcast : float
Value to use when initializing the recursion
"""
# Throw away bounds
var_bounds = np.ones((nobs, 2)) * np.array([-1.0, 1.7e308])
rec.garch_recursion(
np.array([0.0, 1.0 - lam, lam]),
resids**2.0,
resids,
sigma2,
1,
0,
1,
nobs,
backcast,
var_bounds,
)
return sigma2
class VarianceForecast:
_forecasts = None
_forecast_paths = None
def __init__(
self,
forecasts: Float64Array,
forecast_paths: Float64Array | None = None,
shocks: Float64Array | None = None,
) -> None:
self._forecasts = forecasts
self._forecast_paths = forecast_paths
self._shocks = shocks
@property
def forecasts(self) -> Float64Array | None:
return self._forecasts
@property
def forecast_paths(self) -> Float64Array | None:
return self._forecast_paths
@property
def shocks(self) -> Float64Array | None:
return self._shocks
class VolatilityProcess(metaclass=ABCMeta):
"""
Abstract base class for ARCH models. Allows the conditional mean model to be
specified separately from the conditional variance, even though parameters
are estimated jointly.
"""
_updatable: bool = True
def __init__(self) -> None:
self._num_params = 0
self._name = ""
self.closed_form: bool = False
self._normal = Normal()
self._min_bootstrap_obs = 100
self._start = 0
self._stop = -1
self._volatility_updater: rec.VolatilityUpdater | None = None
def __str__(self) -> str:
return self.name
def __repr__(self) -> str:
return self.__str__() + ", id: " + hex(id(self))
@property
def name(self) -> str:
"""The name of the volatility process"""
return self._name
@property
def start(self) -> int:
"""Index to use to start variance subarray selection"""
return self._start
@start.setter
def start(self, value: int) -> None:
self._start = value
@property
def stop(self) -> int:
"""Index to use to stop variance subarray selection"""
return self._stop
@stop.setter
def stop(self, value: int) -> None:
self._stop = value
@property
def num_params(self) -> int:
"""The number of parameters in the model"""
return self._num_params
@property
def updateable(self) -> bool:
"""Flag indicating that the volatility process supports update"""
return self._updatable
@property
def volatility_updater(self) -> rec.VolatilityUpdater:
"""
Get the volatility updater associated with the volatility process
Returns
-------
VolatilityUpdater
The updater class
Raises
------
NotImplementedError
If the process is not updateable
"""
if not self._updatable or self._volatility_updater is None:
raise NotImplementedError("Subclasses may optionally implement")
assert self._volatility_updater is not None
return self._volatility_updater
def update(
self,
index: int,
parameters: Float64Array,
resids: Float64Array,
sigma2: Float64Array,
backcast: float | Float64Array,
var_bounds: Float64Array,
) -> float:
"""
Compute the variance for a single observation
Parameters
----------
index : int
The numerical index of the variance to compute
parameters : ndarray
The variance model parameters
resids :
The residual array. Only uses ``resids[:index]`` when computing
``sigma2[index]``
sigma2 : ndarray
The array containing the variances. Only uses ``sigma2[:index]``
when computing ``sigma2[index]``. The computed value is stored
in ``sigma2[index]``.
backcast : {float, ndarray}
Value to use when initializing the recursion
var_bounds : ndarray
Array containing columns of lower and upper bounds
Returns
-------
float
The variance computed for location ``index``
"""
raise NotImplementedError("Subclasses may optionally implement")
@abstractmethod
def _check_forecasting_method(
self, method: ForecastingMethod, horizon: int
) -> None:
"""
Verify the requested forecasting method as valid for the specification
Parameters
----------
method : str
Forecasting method
horizon : int
Forecast horizon
Raises
------
NotImplementedError
* If method is not known or not supported
"""
def _one_step_forecast(
self,
parameters: Float64Array,
resids: Float64Array,
backcast: float | Float64Array,
var_bounds: Float64Array,
horizon: int,
start_index: int,
) -> tuple[Float64Array, Float64Array]:
"""
One-step ahead forecast
Parameters
----------
parameters : ndarray
Parameters required to forecast the volatility model
resids : ndarray
Residuals to use in the recursion
backcast : float
Value to use when initializing the recursion
var_bounds : ndarray
Array containing columns of lower and upper bounds
horizon : int
Forecast horizon. Must be 1 or larger. Forecasts are produced
for horizons in [1, horizon].
Returns
-------
sigma2 : ndarray
t element array containing the one-step ahead forecasts
forecasts : ndarray
t by horizon array containing the one-step ahead forecasts in the first
location
"""
t = resids.shape[0]
_resids: Float64Array = np.concatenate((resids, np.array([0.0])))
_var_bounds: Float64Array = np.concatenate(
(var_bounds, np.array([[0, np.inf]]))
)
sigma2 = np.zeros(t + 1)
self.compute_variance(parameters, _resids, sigma2, backcast, _var_bounds)
forecasts = np.zeros((t - start_index, horizon))
forecasts[:, 0] = sigma2[start_index + 1 :]
sigma2 = sigma2[:-1]
return sigma2, forecasts
@abstractmethod
def _analytic_forecast(
self,
parameters: Float64Array,
resids: Float64Array,
backcast: float | Float64Array,
var_bounds: Float64Array,
start: int,
horizon: int,
) -> VarianceForecast:
"""
Analytic multi-step volatility forecasts from the model
Parameters
----------
parameters : ndarray
Parameters required to forecast the volatility model
resids : ndarray
Residuals to use in the recursion
backcast : float
Value to use when initializing the recursion
var_bounds : ndarray
Array containing columns of lower and upper bounds
start : int
Index of the first observation to use as the starting point for
the forecast. Default is 0.
horizon : int
Forecast horizon. Must be 1 or larger. Forecasts are produced
for horizons in [1, horizon].
Returns
-------
forecasts : VarianceForecast
Class containing the variance forecasts, and, if using simulation
or bootstrap, the simulated paths.
"""
@abstractmethod
def _simulation_forecast(
self,
parameters: Float64Array,
resids: Float64Array,
backcast: float | Float64Array,
var_bounds: Float64Array,
start: int,
horizon: int,
simulations: int,
rng: RNGType,
) -> VarianceForecast:
"""
Simulation-based volatility forecasts from the model
Parameters
----------
parameters : ndarray
Parameters required to forecast the volatility model
resids : ndarray
Residuals to use in the recursion
backcast : float
Value to use when initializing the recursion. The backcast is
assumed to be appropriately transformed so that it can be
used without modification, e.g., log of the variance backcast
in an EGARCH model.
var_bounds : ndarray
Array containing columns of lower and upper bounds
start : int
Index of the first observation to use as the starting point for
the forecast. Default is 0.
horizon : int
Forecast horizon. Must be 1 or larger. Forecasts are produced
for horizons in [1, horizon].
simulations : int
Number of simulations to run when computing the forecast using
either simulation or bootstrap.
rng : callable
Callable random number generator required if method is
'simulation'. Must take a single shape input and return random
samples numbers with that shape.
Returns
-------
forecasts : VarianceForecast
Class containing the variance forecasts, and, if using simulation
or bootstrap, the simulated paths.
"""
def _bootstrap_forecast(
self,
parameters: Float64Array,
resids: Float64Array,
backcast: float | Float64Array,
var_bounds: Float64Array,
start: int,
horizon: int,
simulations: int,
random_state: RandomState | None,
) -> VarianceForecast:
"""
Simulation-based volatility forecasts using model residuals
Parameters
----------
parameters : ndarray
Parameters required to forecast the volatility model
resids : ndarray
Residuals to use in the recursion
backcast : {float, ndarray}
Value to use when initializing the recursion
var_bounds : ndarray
Array containing columns of lower and upper bounds
start : int
Index of the first observation to use as the starting point for
the forecast. Default is 0.
horizon : int
Forecast horizon. Must be 1 or larger. Forecasts are produced
for horizons in [1, horizon].
simulations : int
Number of simulations to run when computing the forecast using
either simulation or bootstrap.
random_state : {RandomState, None}
NumPy RandomState instance to use in the BootstrapRng
Returns
-------
forecasts : VarianceForecast
Class containing the variance forecasts, and, if using simulation
or bootstrap, the simulated paths.
"""
sigma2 = np.empty_like(resids)
self.compute_variance(parameters, resids, sigma2, backcast, var_bounds)
std_resid = resids / np.sqrt(sigma2)
if start < self._min_bootstrap_obs:
raise ValueError(
"start must include more than {} "
"observations".format(self._min_bootstrap_obs)
)
rng = BootstrapRng(std_resid, start, random_state=random_state).rng()
return self._simulation_forecast(
parameters, resids, backcast, var_bounds, start, horizon, simulations, rng
)
def variance_bounds(self, resids: Float64Array, power: float = 2.0) -> Float64Array:
"""
Construct loose bounds for conditional variances.
These bounds are used in parameter estimation to ensure
that the log-likelihood does not produce NaN values.
Parameters
----------
resids : ndarray
Approximate residuals to use to compute the lower and upper bounds
on the conditional variance
power : float, optional
Power used in the model. 2.0, the default corresponds to standard
ARCH models that evolve in squares.
Returns
-------
var_bounds : ndarray
Array containing columns of lower and upper bounds with the same
number of elements as resids
"""
nobs = resids.shape[0]
tau = min(75, nobs)
w = 0.94 ** np.arange(tau)
w = w / sum(w)
var_bound = np.zeros(nobs)
initial_value = w.dot(resids[:tau] ** 2.0)
ewma_recursion(0.94, resids, var_bound, resids.shape[0], initial_value)
var_bounds = np.vstack((var_bound / 1e6, var_bound * 1e6)).T
var = resids.var()
min_upper_bound = 1 + (resids**2.0).max()
lower_bound, upper_bound = var / 1e8, 1e7 * (1 + (resids**2.0).max())
var_bounds[var_bounds[:, 0] < lower_bound, 0] = lower_bound
var_bounds[var_bounds[:, 1] < min_upper_bound, 1] = min_upper_bound
var_bounds[var_bounds[:, 1] > upper_bound, 1] = upper_bound
if power != 2.0:
var_bounds **= power / 2.0
return np.ascontiguousarray(var_bounds)
@abstractmethod
def starting_values(self, resids: Float64Array) -> Float64Array:
"""
Returns starting values for the ARCH model
Parameters
----------
resids : ndarray
Array of (approximate) residuals to use when computing starting
values
Returns
-------
sv : ndarray
Array of starting values
"""
def backcast(self, resids: Float64Array) -> float | Float64Array:
"""
Construct values for backcasting to start the recursion
Parameters
----------
resids : ndarray
Vector of (approximate) residuals
Returns
-------
backcast : float
Value to use in backcasting in the volatility recursion
"""
tau = min(75, resids.shape[0])
w = 0.94 ** np.arange(tau)
w = w / sum(w)
return float(np.sum((resids[:tau] ** 2.0) * w))
def backcast_transform(
self, backcast: float | Float64Array
) -> float | Float64Array:
"""
Transformation to apply to user-provided backcast values
Parameters
----------
backcast : {float, ndarray}
User-provided ``backcast`` that approximates sigma2[0].
Returns
-------
backcast : {float, ndarray}
Backcast transformed to the model-appropriate scale
"""
if np.any(backcast < 0):
raise ValueError("User backcast value must be strictly positive.")
return backcast
@abstractmethod
def bounds(self, resids: Float64Array) -> list[tuple[float, float]]:
"""
Returns bounds for parameters
Parameters
----------
resids : ndarray
Vector of (approximate) residuals
Returns
-------
bounds : list[tuple[float,float]]
List of bounds where each element is (lower, upper).
"""
@abstractmethod
def compute_variance(
self,
parameters: Float64Array,
resids: Float64Array,
sigma2: Float64Array,
backcast: float | Float64Array,
var_bounds: Float64Array,
) -> Float64Array:
"""
Compute the variance for the ARCH model
Parameters
----------
parameters : ndarray
Model parameters
resids : ndarray
Vector of mean zero residuals
sigma2 : ndarray
Array with same size as resids to store the conditional variance
backcast : {float, ndarray}
Value to use when initializing ARCH recursion. Can be an ndarray
when the model contains multiple components.
var_bounds : ndarray
Array containing columns of lower and upper bounds
"""
@abstractmethod
def constraints(self) -> tuple[Float64Array, Float64Array]:
"""
Construct parameter constraints arrays for parameter estimation
Returns
-------
A : ndarray
Parameters loadings in constraint. Shape is number of constraints
by number of parameters
b : ndarray
Constraint values, one for each constraint
Notes
-----
Values returned are used in constructing linear inequality
constraints of the form A.dot(parameters) - b >= 0
"""
def forecast(
self,
parameters: ArrayLike1D,
resids: Float64Array,
backcast: Float64Array | float,
var_bounds: Float64Array,
start: int | None = None,
horizon: int = 1,
method: ForecastingMethod = "analytic",
simulations: int = 1000,
rng: RNGType | None = None,
random_state: RandomState | None = None,
) -> VarianceForecast:
"""
Forecast volatility from the model
Parameters
----------
parameters : {ndarray, Series}
Parameters required to forecast the volatility model
resids : ndarray
Residuals to use in the recursion
backcast : float
Value to use when initializing the recursion
var_bounds : ndarray, 2-d
Array containing columns of lower and upper bounds
start : {None, int}
Index of the first observation to use as the starting point for
the forecast. Default is len(resids).
horizon : int
Forecast horizon. Must be 1 or larger. Forecasts are produced
for horizons in [1, horizon].
method : {'analytic', 'simulation', 'bootstrap'}
Method to use when producing the forecast. The default is analytic.
simulations : int
Number of simulations to run when computing the forecast using
either simulation or bootstrap.
rng : callable
Callable random number generator required if method is
'simulation'. Must take a single shape input and return random
samples numbers with that shape.
random_state : RandomState, optional
NumPy RandomState instance to use when method is 'bootstrap'
Returns
-------
forecasts : VarianceForecast
Class containing the variance forecasts, and, if using simulation
or bootstrap, the simulated paths.
Raises
------
NotImplementedError
* If method is not supported
ValueError
* If the method is not known
Notes
-----
The analytic ``method`` is not supported for all models. Attempting
to use this method when not available will raise a ValueError.
"""
parameters = np.asarray(parameters)
method_name = method.lower()
if method_name not in ("analytic", "simulation", "bootstrap"):
raise ValueError(f"{method} is not a known forecasting method")
if not isinstance(horizon, (int, np.integer)) or horizon < 1:
raise ValueError("horizon must be an integer >= 1.")
self._check_forecasting_method(cast(ForecastingMethod, method_name), horizon)
start = len(resids) - 1 if start is None else start
if method_name == "analytic":
return self._analytic_forecast(
parameters, resids, backcast, var_bounds, start, horizon
)
elif method == "simulation":
# TODO: This looks like a design flaw.It is optional above but then must
# be present. This happens because the caller of this function is
# expected to know when to provide the rng or not
assert rng is not None
return self._simulation_forecast(
parameters,
resids,
backcast,
var_bounds,
start,
horizon,
simulations,
rng,
)
else:
if start < 10 or (horizon / start) >= 0.2:
raise ValueError(
"Bootstrap forecasting requires at least 10 initial "
"observations, and the ratio of horizon-to-start < 20%."
)
return self._bootstrap_forecast(
parameters,
resids,
backcast,
var_bounds,
start,
horizon,
simulations,
random_state,
)
@abstractmethod
def simulate(
self,
parameters: Sequence[int | float] | ArrayLike1D,
nobs: int,
rng: RNGType,
burn: int = 500,
initial_value: None | float | Float64Array = None,
) -> tuple[Float64Array, Float64Array]:
"""
Simulate data from the model
Parameters
----------
parameters : {ndarray, Series}
Parameters required to simulate the volatility model
nobs : int
Number of data points to simulate
rng : callable
Callable function that takes a single integer input and returns
a vector of random numbers
burn : int, optional
Number of additional observations to generate when initializing
the simulation
initial_value : {float, ndarray}, optional
Scalar or array of initial values to use when initializing the
simulation
Returns
-------
resids : ndarray
The simulated residuals
variance : ndarray
The simulated variance
"""
def _gaussian_loglikelihood(
self,
parameters: Float64Array,
resids: Float64Array,
backcast: float | Float64Array,
var_bounds: Float64Array,
) -> float:
"""
Private implementation of a Gaussian log-likelihood for use in constructing
starting values or other quantities that do not depend on the distribution
used by the model.
"""
sigma2 = np.zeros_like(resids)
self.compute_variance(parameters, resids, sigma2, backcast, var_bounds)
return float(self._normal.loglikelihood([], resids, sigma2))
@abstractmethod
def parameter_names(self) -> list[str]:
"""
Names of model parameters
Returns
-------
names : list (str)
Variables names
"""
class ConstantVariance(VolatilityProcess, metaclass=AbstractDocStringInheritor):
r"""
Constant volatility process
Notes
-----
Model has the same variance in all periods
"""
def __init__(self) -> None:
super().__init__()
self._num_params = 1
self._name = "Constant Variance"
self.closed_form: bool = True
def compute_variance(
self,
parameters: Float64Array,
resids: Float64Array,
sigma2: Float64Array,
backcast: float | Float64Array,
var_bounds: Float64Array,
) -> Float64Array:
sigma2[:] = parameters[0]
return sigma2
def starting_values(self, resids: Float64Array) -> Float64Array:
return np.array([resids.var()])
def simulate(
self,
parameters: Sequence[int | float] | ArrayLike1D,
nobs: int,
rng: RNGType,
burn: int = 500,
initial_value: None | float | Float64Array = None,
) -> tuple[Float64Array, Float64Array]:
parameters = ensure1d(parameters, "parameters", False)
errors = rng(nobs + burn)
sigma2 = np.ones(nobs + burn) * parameters[0]
data = np.sqrt(sigma2) * errors
return data[burn:], sigma2[burn:]
def constraints(self) -> tuple[Float64Array, Float64Array]:
return np.ones((1, 1)), np.zeros(1)
def backcast_transform(
self, backcast: float | Float64Array
) -> float | Float64Array:
backcast = super().backcast_transform(backcast)
return backcast
def backcast(self, resids: Float64Array) -> float | Float64Array:
return float(resids.var())
def bounds(self, resids: Float64Array) -> list[tuple[float, float]]:
v = float(resids.var())
return [(v / 100000.0, 10.0 * (v + float(resids.mean()) ** 2.0))]
def parameter_names(self) -> list[str]:
return ["sigma2"]
def _check_forecasting_method(
self, method: ForecastingMethod, horizon: int
) -> None:
return
def _analytic_forecast(
self,
parameters: Float64Array,
resids: Float64Array,
backcast: float | Float64Array,
var_bounds: Float64Array,
start: int,
horizon: int,
) -> VarianceForecast:
t = resids.shape[0]
forecasts = np.full((t - start, horizon), np.nan)
forecasts[:, :] = parameters[0]
forecast_paths = None
return VarianceForecast(forecasts, forecast_paths)
def _simulation_forecast(
self,
parameters: Float64Array,
resids: Float64Array,
backcast: float | Float64Array,
var_bounds: Float64Array,
start: int,
horizon: int,
simulations: int,
rng: RNGType,
) -> VarianceForecast:
t = resids.shape[0]
forecasts = np.empty((t - start, horizon))
forecast_paths = np.empty((t - start, simulations, horizon))
shocks = np.empty((t - start, simulations, horizon))
for i in range(t - start):
shocks[i, :, :] = np.sqrt(parameters[0]) * rng((simulations, horizon))
forecasts[:, :] = parameters[0]
forecast_paths[:, :, :] = parameters[0]
return VarianceForecast(forecasts, forecast_paths, shocks)
class GARCH(VolatilityProcess, metaclass=AbstractDocStringInheritor):
r"""
GARCH and related model estimation
The following models can be specified using GARCH:
* ARCH(p)
* GARCH(p,q)
* GJR-GARCH(p,o,q)
* AVARCH(p)
* AVGARCH(p,q)
* TARCH(p,o,q)
* Models with arbitrary, pre-specified powers
Parameters
----------
p : int
Order of the symmetric innovation
o : int
Order of the asymmetric innovation
q : int
Order of the lagged (transformed) conditional variance
power : float, optional
Power to use with the innovations, abs(e) ** power. Default is 2.0, which
produces ARCH and related models. Using 1.0 produces AVARCH and related
models. Other powers can be specified, although these should be strictly
positive, and usually larger than 0.25.
Examples
--------
>>> from arch.univariate import GARCH
Standard GARCH(1,1)
>>> garch = GARCH(p=1, q=1)
Asymmetric GJR-GARCH process
>>> gjr = GARCH(p=1, o=1, q=1)
Asymmetric TARCH process
>>> tarch = GARCH(p=1, o=1, q=1, power=1.0)
Notes
-----
In this class of processes, the variance dynamics are
.. math::
\sigma_{t}^{\lambda}=\omega
+ \sum_{i=1}^{p}\alpha_{i}\left|\epsilon_{t-i}\right|^{\lambda}
+\sum_{j=1}^{o}\gamma_{j}\left|\epsilon_{t-j}\right|^{\lambda}
I\left[\epsilon_{t-j}<0\right]+\sum_{k=1}^{q}\beta_{k}\sigma_{t-k}^{\lambda}
where :math:`\lambda` is the ``power``.