/
base.py
1661 lines (1419 loc) · 57 KB
/
base.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
"""
Core classes for ARCH models
"""
from __future__ import absolute_import, division
from arch.compat.python import add_metaclass, range
from copy import deepcopy
import datetime as dt
import warnings
import numpy as np
import scipy.stats as stats
import pandas as pd
from statsmodels.tools.decorators import cache_readonly, resettable_cache
from statsmodels.iolib.summary import Summary, fmt_2cols, fmt_params
from statsmodels.iolib.table import SimpleTable
from statsmodels.tools.numdiff import approx_fprime, approx_hess
from arch.univariate.distribution import Distribution, Normal
from arch.univariate.volatility import VolatilityProcess, ConstantVariance
from arch.utility.array import ensure1d, DocStringInheritor
from arch.utility.exceptions import ConvergenceWarning, StartingValueWarning, \
convergence_warning, starting_value_warning
__all__ = ['implicit_constant', 'ARCHModelResult', 'ARCHModel']
# Callback variables
_callback_iter, _callback_llf = 0, 0.0,
_callback_func_count, _callback_iter_display = 0, 1
def _callback(*args):
"""
Callback for use in optimization
Parameters
----------
parameters : : ndarray
Parameter value (not used by function)
Notes
-----
Uses global values to track iteration, iteration display frequency,
log likelihood and function count
"""
global _callback_iter
_callback_iter += 1
disp = 'Iteration: {0:>6}, Func. Count: {1:>6.3g}, Neg. LLF: {2}'
if _callback_iter % _callback_iter_display == 0:
print(disp.format(_callback_iter, _callback_func_count, _callback_llf))
return None
def constraint(a, b):
"""
Generate constraints from arrays
Parameters
----------
a : ndarray
Parameter loadings
b : ndarray
Constraint bounds
Returns
-------
constraints : dict
Dictionary of inequality constraints, one for each row of a
Notes
-----
Parameter constraints satisfy a.dot(parameters) - b >= 0
"""
def factory(coeff, val):
def f(params, *args):
return np.dot(coeff, params) - val
return f
constraints = []
for i in range(a.shape[0]):
con = {'type': 'ineq', 'fun': factory(a[i], b[i])}
constraints.append(con)
return constraints
def format_float_fixed(x, max_digits=10, decimal=4):
"""Formats a floating point number so that if it can be well expressed
in using a string with digits len, then it is converted simply, otherwise
it is expressed in scientific notation"""
# basic_format = '{:0.' + str(digits) + 'g}'
if x == 0:
return ('{:0.' + str(decimal) + 'f}').format(0.0)
scale = np.log10(np.abs(x))
scale = np.sign(scale) * np.ceil(np.abs(scale))
if scale > (max_digits - 2 - decimal) or scale < -(decimal - 2):
formatted = (
'{0:' + str(max_digits) + '.' + str(decimal) + 'e}').format(x)
else:
formatted = (
'{0:' + str(max_digits) + '.' + str(decimal) + 'f}').format(x)
return formatted
def implicit_constant(x):
"""
Test a matrix for an implicit constant
Parameters
----------
x : ndarray
Array to be tested
Returns
-------
constant : bool
Flag indicating whether the array has an implicit constant - whether
the array has a set of columns that adds to a constant value
"""
nobs = x.shape[0]
rank = np.linalg.matrix_rank(np.hstack((np.ones((nobs, 1)), x)))
return rank == x.shape[1]
@add_metaclass(DocStringInheritor)
class ARCHModel(object):
"""
Abstract base class for mean models in ARCH processes. Specifies the
conditional mean process.
All public methods that raise NotImplementedError should be overridden by
any subclass. Private methods that raise NotImplementedError are optional
to override but recommended where applicable.
"""
def __init__(self, y=None, volatility=None, distribution=None,
hold_back=None):
# Set on model fit
self._fit_indices = None
self._fit_y = None
self._is_pandas = isinstance(y, (pd.DataFrame, pd.Series))
if y is not None:
self._y_series = ensure1d(y, 'y', series=True)
else:
self._y_series = ensure1d(np.empty((0,)), 'y', series=True)
self._y = np.asarray(self._y_series)
self._y_original = y
self.hold_back = hold_back
self._hold_back = 0 if hold_back is None else hold_back
self._volatility = None
self._distribution = None
self._backcast = None
self._var_bounds = None
if volatility is not None:
self.volatility = volatility
else:
self.volatility = ConstantVariance()
if distribution is not None:
self.distribution = distribution
else:
self.distribution = Normal()
def constraints(self):
"""
Construct linear constraint arrays for use in non-linear optimization
Returns
-------
a : ndarray
Number of constraints by number of parameters loading array
b : ndarray
Number of constraints array of lower bounds
Notes
-----
Parameters satisfy a.dot(parameters) - b >= 0
"""
return np.empty((0, self.num_params)), np.empty(0)
def bounds(self):
"""
Construct bounds for parameters to use in non-linear optimization
Returns
-------
bounds : list (2-tuple of float)
Bounds for parameters to use in estimation.
"""
num_params = self.num_params
return [(-np.inf, np.inf)] * num_params
@property
def y(self):
"""Returns the dependent variable"""
return self._y_original
@property
def volatility(self):
"""Set or gets the volatility process
Volatility processes must be a subclass of VolatilityProcess
"""
return self._volatility
@volatility.setter
def volatility(self, value):
if not isinstance(value, VolatilityProcess):
raise ValueError("Must subclass VolatilityProcess")
self._volatility = value
@property
def distribution(self):
"""Set or gets the error distribution
Distributions must be a subclass of Distribution
"""
return self._distribution
@distribution.setter
def distribution(self, value):
if not isinstance(value, Distribution):
raise ValueError("Must subclass Distribution")
self._distribution = value
def _r2(self, params):
"""
Computes the model r-square. Optional to over-ride. Must match
signature.
"""
raise NotImplementedError("Subclasses optionally may provide.")
def _fit_no_arch_normal_errors(self, cov_type='robust'):
"""
Must be overridden with closed form estimator
"""
raise NotImplementedError("Subclasses must implement")
def _loglikelihood(self, parameters, sigma2, backcast, var_bounds,
individual=False):
"""
Computes the log-likelihood using the entire model
Parameters
----------
parameters
sigma2
backcast
individual : bool, optional
Returns
-------
neg_llf : float
Negative of model loglikelihood
"""
# Parse parameters
global _callback_func_count, _callback_llf
_callback_func_count += 1
# 1. Resids
mp, vp, dp = self._parse_parameters(parameters)
resids = self.resids(mp)
# 2. Compute sigma2 using VolatilityModel
sigma2 = self.volatility.compute_variance(vp, resids, sigma2, backcast,
var_bounds)
# 3. Compute log likelihood using Distribution
llf = self.distribution.loglikelihood(dp, resids, sigma2, individual)
_callback_llf = -1.0 * llf
return -1.0 * llf
def _all_parameter_names(self):
"""Returns a list containing all parameter names from the mean model,
volatility model and distribution"""
names = self.parameter_names()
names.extend(self.volatility.parameter_names())
names.extend(self.distribution.parameter_names())
return names
def _parse_parameters(self, x):
"""Return the parameters of each model in a tuple"""
km, kv = int(self.num_params), int(self.volatility.num_params)
return x[:km], x[km:km + kv], x[km + kv:]
def fix(self, params, first_obs=None, last_obs=None):
"""
Allows an ARCHModelFixedResult to be constructed from fixed parameters.
Parameters
----------
params: ndarray-like
User specified parameters to use when generating the result. Must
have the correct number of parameters for a given choice of mean
model, volatility model and distribution.
first_obs : {int, str, datetime, Timestamp}
First observation to use when fixing model
last_obs : {int, str, datetime, Timestamp}
Last observation to use when fixing model
Returns
-------
results : ARCHModelFixedResult
Object containing model results
Notes
-----
Parameters are not checked against model-specific constraints.
"""
v = self.volatility
self._adjust_sample(first_obs, last_obs)
resids = self.resids(self.starting_values())
sigma2 = np.zeros_like(resids)
backcast = v.backcast(resids)
self._backcast = backcast
var_bounds = v.variance_bounds(resids)
params = np.asarray(params)
loglikelihood = -1.0 * self._loglikelihood(params, sigma2, backcast,
var_bounds)
mp, vp, dp = self._parse_parameters(params)
resids = self.resids(mp)
vol = np.zeros_like(resids)
self.volatility.compute_variance(vp, resids, vol, backcast, var_bounds)
vol = np.sqrt(vol)
names = self._all_parameter_names()
# Reshape resids and vol
first_obs, last_obs = self._fit_indices
resids_final = np.empty_like(self._y, dtype=np.float64)
resids_final.fill(np.nan)
resids_final[first_obs:last_obs] = resids
vol_final = np.empty_like(self._y, dtype=np.float64)
vol_final.fill(np.nan)
vol_final[first_obs:last_obs] = vol
model_copy = deepcopy(self)
return ARCHModelFixedResult(params, resids, vol, self._y_series, names,
loglikelihood, self._is_pandas, model_copy)
def _adjust_sample(self, first_obs, last_obs):
"""
Performs sample adjustment for estimation
Parameters
----------
first_obs : {int, str, datetime, datetime64, Timestamp}
First observation to use when estimating model
last_obs : {int, str, datetime, datetime64, Timestamp}
Last observation to use when estimating model
Notes
-----
Adjusted sample must follow Python semantics of first_obs:last_obs
"""
raise NotImplementedError("Subclasses must implement")
def fit(self, update_freq=1, disp='final', starting_values=None,
cov_type='robust', show_warning=True, first_obs=None,
last_obs=None, tol=None, options=None):
"""
Fits the model given a nobs by 1 vector of sigma2 values
Parameters
----------
update_freq : int, optional
Frequency of iteration updates. Output is generated every
`update_freq` iterations. Set to 0 to disable iterative output.
disp : str
Either 'final' to print optimization result or 'off' to display
nothing
starting_values : ndarray, optional
Array of starting values to use. If not provided, starting values
are constructed by the model components.
cov_type : str, optional
Estimation method of parameter covariance. Supported options are
'robust', which does not assume the Information Matrix Equality
holds and 'classic' which does. In the ARCH literature, 'robust'
corresponds to Bollerslev-Wooldridge covariance estimator.
show_warning : bool, optional
Flag indicating whether convergence warnings should be shown.
first_obs : {int, str, datetime, Timestamp}
First observation to use when estimating model
last_obs : {int, str, datetime, Timestamp}
Last observation to use when estimating model
tol : float, optional
Tolerance for termination.
options : dict, optional
Options to pass to `scipy.optimize.minimize`. Valid entries
include 'ftol', 'eps', 'disp', and 'maxiter'.
Returns
-------
results : ARCHModelResult
Object containing model results
Notes
-----
A ConvergenceWarning is raised if SciPy's optimizer indicates
difficulty finding the optimum.
Parameters are optimized using SLSQP.
"""
if self._y_original is None:
raise RuntimeError('Cannot estimate model without data.')
# 1. Check in ARCH or Non-normal dist. If no ARCH and normal,
# use closed form
v, d = self.volatility, self.distribution
offsets = np.array((self.num_params, v.num_params, d.num_params))
total_params = sum(offsets)
has_closed_form = (v.closed_form and d.num_params == 0) or total_params == 0
self._adjust_sample(first_obs, last_obs)
if has_closed_form:
try:
return self._fit_no_arch_normal_errors(cov_type=cov_type)
except NotImplementedError:
pass
resids = self.resids(self.starting_values())
sigma2 = np.zeros_like(resids)
backcast = v.backcast(resids)
self._backcast = backcast
sv_volatility = v.starting_values(resids)
self._var_bounds = var_bounds = v.variance_bounds(resids)
v.compute_variance(sv_volatility, resids, sigma2, backcast, var_bounds)
std_resids = resids / np.sqrt(sigma2)
# 2. Construct constraint matrices from all models and distribution
constraints = (self.constraints(),
self.volatility.constraints(),
self.distribution.constraints())
num_constraints = [c[0].shape[0] for c in constraints]
num_constraints = np.array(num_constraints)
num_params = offsets.sum()
a = np.zeros((num_constraints.sum(), num_params))
b = np.zeros(num_constraints.sum())
for i, c in enumerate(constraints):
r_en = num_constraints[:i + 1].sum()
c_en = offsets[:i + 1].sum()
r_st = r_en - num_constraints[i]
c_st = c_en - offsets[i]
if r_en - r_st > 0:
a[r_st:r_en, c_st:c_en] = c[0]
b[r_st:r_en] = c[1]
bounds = self.bounds()
bounds.extend(v.bounds(resids))
bounds.extend(d.bounds(std_resids))
# 3. Construct starting values from all models
sv = starting_values
if starting_values is not None:
sv = ensure1d(sv, 'starting_values')
valid = (sv.shape[0] == num_params)
if a.shape[0] > 0:
satisfies_constraints = a.dot(sv) - b > 0
valid = valid and satisfies_constraints.all()
for i, bound in enumerate(bounds):
valid = valid and bound[0] <= sv[i] <= bound[1]
if not valid:
warnings.warn(starting_value_warning, StartingValueWarning)
starting_values = None
if starting_values is None:
sv = (self.starting_values(),
sv_volatility,
d.starting_values(std_resids))
sv = np.hstack(sv)
# 4. Estimate models using constrained optimization
global _callback_func_count, _callback_iter, _callback_iter_display
_callback_func_count, _callback_iter = 0, 0
if update_freq <= 0 or disp == 'off':
_callback_iter_display = 2 ** 31
else:
_callback_iter_display = update_freq
disp = True if disp == 'final' else False
func = self._loglikelihood
args = (sigma2, backcast, var_bounds)
ineq_constraints = constraint(a, b)
from scipy.optimize import minimize
options = {} if options is None else options
options.setdefault('disp', disp)
opt = minimize(func, sv, args=args, method='SLSQP', bounds=bounds,
constraints=ineq_constraints, tol=tol, callback=_callback,
options=options)
if show_warning:
warnings.filterwarnings('always', '', ConvergenceWarning)
else:
warnings.filterwarnings('ignore', '', ConvergenceWarning)
if opt.status != 0 and show_warning:
warnings.warn(convergence_warning.format(code=opt.status,
string_message=opt.message),
ConvergenceWarning)
# 5. Return results
params = opt.x
loglikelihood = -1.0 * opt.fun
mp, vp, dp = self._parse_parameters(params)
resids = self.resids(mp)
vol = np.zeros_like(resids)
self.volatility.compute_variance(vp, resids, vol, backcast, var_bounds)
vol = np.sqrt(vol)
try:
r2 = self._r2(mp)
except NotImplementedError:
r2 = np.nan
names = self._all_parameter_names()
# Reshape resids and vol
first_obs, last_obs = self._fit_indices
resids_final = np.empty_like(self._y, dtype=np.float64)
resids_final.fill(np.nan)
resids_final[first_obs:last_obs] = resids
vol_final = np.empty_like(self._y, dtype=np.float64)
vol_final.fill(np.nan)
vol_final[first_obs:last_obs] = vol
fit_start, fit_stop = self._fit_indices
model_copy = deepcopy(self)
return ARCHModelResult(params, None, r2, resids_final, vol_final,
cov_type, self._y_series, names, loglikelihood,
self._is_pandas, opt, fit_start, fit_stop, model_copy)
def parameter_names(self):
"""List of parameters names
Returns
-------
names : list (str)
List of variable names for the mean model
"""
raise NotImplementedError('Subclasses must implement')
def starting_values(self):
"""
Returns starting values for the mean model, often the same as the
values returned from fit
Returns
-------
sv : ndarray
Starting values
"""
params = np.asarray(self._fit_no_arch_normal_errors().params)
# Remove sigma2
if params.shape[0] == 1:
return np.empty(0)
elif params.shape[0] > 1:
return params[:-1]
@cache_readonly
def num_params(self):
"""
Returns the number of parameters
"""
raise NotImplementedError('Subclasses must implement')
def simulate(self, params, nobs, burn=500, initial_value=None, x=None,
initial_value_vol=None):
raise NotImplementedError('Subclasses must implement')
def resids(self, params, y=None, regressors=None):
"""
Compute model residuals
Parameters
----------
params : ndarray
Model parameters
y : ndarray, optional
Alternative values to use when computing model residuals
regressors : ndarray, optional
Alternative regressor values to use when computing model residuals
Returns
-------
resids : ndarray
Model residuals
"""
raise NotImplementedError('Subclasses must implement')
def compute_param_cov(self, params, backcast=None, robust=True):
"""
Computes parameter covariances using numerical derivatives.
Parameters
----------
params : ndarray
Model parameters
backcast : float
Value to use for pre-sample observations
robust : bool, optional
Flag indicating whether to use robust standard errors (True) or
classic MLE (False)
"""
resids = self.resids(self.starting_values())
var_bounds = self.volatility.variance_bounds(resids)
nobs = resids.shape[0]
if backcast is None and self._backcast is None:
backcast = self.volatility.backcast(resids)
self._backcast = backcast
elif backcast is None:
backcast = self._backcast
kwargs = {'sigma2': np.zeros_like(resids),
'backcast': backcast,
'var_bounds': var_bounds,
'individual': False}
hess = approx_hess(params, self._loglikelihood, kwargs=kwargs)
hess /= nobs
inv_hess = np.linalg.inv(hess)
if robust:
kwargs['individual'] = True
scores = approx_fprime(params, self._loglikelihood, kwargs=kwargs)
score_cov = np.cov(scores.T)
return inv_hess.dot(score_cov).dot(inv_hess) / nobs
else:
return inv_hess / nobs
def forecast(self, params, horizon=1, start=None, align='origin', method='analytic',
simulations=1000, rng=None):
"""
Construct forecasts from estimated model
Parameters
----------
params : ndarray, optional
Alternative parameters to use. If not provided, the parameters
estimated when fitting the model are used. Must be identical in
shape to the parameters computed by fitting the model.
horizon : int, optional
Number of steps to forecast
start : {int, datetime, Timestamp, str}, optional
An integer, datetime or str indicating the first observation to
produce the forecast for. Datetimes can only be used with pandas
inputs that have a datetime index. Strings must be convertible
to a date time, such as in '1945-01-01'.
align : str, optional
Either 'origin' or 'target'. When set of 'origin', the t-th row
of forecasts contains the forecasts for t+1, t+2, ..., t+h. When
set to 'target', the t-th row contains the 1-step ahead forecast
from time t-1, the 2 step from time t-2, ..., and the h-step from
time t-h. 'target' simplified computing forecast errors since the
realization and h-step forecast are aligned.
method : {'analytic', 'simulation', 'bootstrap'}
Method to use when producing the forecast. The default is analytic.
The method only affects the variance forecast generation. Not all
volatility models support all methods. In particular, volatility
models that do not evolve in squares such as EGARCH or TARCH do not
support the 'analytic' method for horizons > 1.
simulations : int
Number of simulations to run when computing the forecast using
either simulation or bootstrap.
rng : callable, optional
Custom random number generator to use in simulation-based forecasts.
Must produce random samples using the syntax `rng(size)` where size
is a tuple containing the dimension of the random values.
Returns
-------
forecasts : DataFrame
t by h data frame containing the forecasts. The alignment of the
forecasts is controlled by `align`.
Examples
--------
>>> import pandas as pd
>>> from arch import arch_model
>>> am = arch_model(None,mean='HAR',lags=[1,5,22],vol='Constant')
>>> sim_data = am.simulate([0.1,0.4,0.3,0.2,1.0], 250)
>>> sim_data.index = pd.date_range('2000-01-01',periods=250)
>>> am = arch_model(sim_data['data'],mean='HAR',lags=[1,5,22], vol='Constant')
>>> res = am.fit()
>>> fig = res.hedgehog_plot()
Notes
-----
The most basic 1-step ahead forecast will return a vector with the same
length as the original data, where the t-th value will be the time-t
forecast for time t + 1. When the horizon is > 1, and when using the
default value for `align`, the forecast value in position [t, h] is the
time-t, h+1 step ahead forecast.
If model contains exogenous variables (model.x is not None), then
only 1-step ahead forecasts are available. Using horizon > 1 will
produce a warning and all columns, except the first, will be
nan-filled.
If `align` is 'origin', forecast[t,h] contains the forecast made using
y[:t] (that is, up to but not including t) for horizon h + 1. For
example, y[100,2] contains the 3-step ahead forecast using the first
100 data points, which will correspond to the realization y[100 + 2].
If `align` is 'target', then the same forecast is in location
[102, 2], so that it is aligned with the observation to use when
evaluating, but still in the same column.
"""
raise NotImplementedError('Subclasses must implement')
class _SummaryRepr(object):
"""Base class for returning summary as repr and str"""
def summary(self):
return Summary()
def __repr__(self):
out = self.__str__() + '\n'
out += self.__class__.__name__
out += ', id: {0}'.format(hex(id(self)))
return out
def __str__(self):
return self.summary().as_text()
class ARCHModelFixedResult(_SummaryRepr):
"""
Results for fixed parameters for an ARCHModel model
Parameters
----------
params : ndarray
Estimated parameters
resid : ndarray
Residuals from model. Residuals have same shape as original data and
contain nan-values in locations not used in estimation
volatility : ndarray
Conditional volatility from model
dep_var: Series
Dependent variable
names: list (str)
Model parameter names
loglikelihood : float
Loglikelihood at specified parameters
is_pandas : bool
Whether the original input was pandas
model : ARCHModel
The model object used to estimate the parameters
Methods
-------
summary
Produce a summary of the results
plot
Produce a plot of the volatility and standardized residuals
forecast
Construct forecasts from a model
Attributes
----------
loglikelihood : float
Value of the log-likelihood
aic : float
Akaike information criteria
bic : float
Schwarz/Bayes information criteria
conditional_volatility : {ndarray, Series}
nobs element array containing the conditional volatility (square root
of conditional variance). The values are aligned with the input data
so that the value in the t-th position is the variance of t-th error,
which is computed using time-(t-1) information.
params : Series
Estimated parameters
nobs : int
Number of observations used in the estimation
num_params : int
Number of parameters in the model
resid : {ndarray, Series}
nobs element array containing model residuals
model : ARCHModel
Model instance used to produce the fit
"""
def __init__(self, params, resid, volatility, dep_var, names,
loglikelihood, is_pandas, model):
self._params = params
self._resid = resid
self._is_pandas = is_pandas
self.model = model
self._datetime = dt.datetime.now()
self._cache = resettable_cache()
self._dep_var = dep_var
self._dep_name = dep_var.name
self._names = names
self._loglikelihood = loglikelihood
self._nobs = self.model._fit_y.shape[0]
self._index = dep_var.index
self._volatility = volatility
def summary(self):
"""
Constructs a summary of the results from a fit model.
Returns
-------
summary : Summary instance
Object that contains tables and facilitated export to text, html or
latex
"""
# Summary layout
# 1. Overall information
# 2. Mean parameters
# 3. Volatility parameters
# 4. Distribution parameters
# 5. Notes
model = self.model
model_name = model.name + ' - ' + model.volatility.name
# Summary Header
top_left = [('Dep. Variable:', self._dep_name),
('Mean Model:', model.name),
('Vol Model:', model.volatility.name),
('Distribution:', model.distribution.name),
('Method:', 'User-specified Parameters'),
('', ''),
('Date:', self._datetime.strftime('%a, %b %d %Y')),
('Time:', self._datetime.strftime('%H:%M:%S'))]
top_right = [('R-squared:', '--'),
('Adj. R-squared:', '--'),
('Log-Likelihood:', '%#10.6g' % self.loglikelihood),
('AIC:', '%#10.6g' % self.aic),
('BIC:', '%#10.6g' % self.bic),
('No. Observations:', self._nobs),
('', ''),
('', ''), ]
title = model_name + ' Model Results'
stubs = []
vals = []
for stub, val in top_left:
stubs.append(stub)
vals.append([val])
table = SimpleTable(vals, txt_fmt=fmt_2cols, title=title, stubs=stubs)
# create summary table instance
smry = Summary()
# Top Table
# Parameter table
fmt = fmt_2cols
fmt['data_fmts'][1] = '%18s'
top_right = [('%-21s' % (' ' + k), v) for k, v in top_right]
stubs = []
vals = []
for stub, val in top_right:
stubs.append(stub)
vals.append([val])
table.extend_right(SimpleTable(vals, stubs=stubs))
smry.tables.append(table)
stubs = self._names
header = ['coef']
vals = (self.params,)
formats = [(10, 4)]
pos = 0
param_table_data = []
for _ in range(len(vals[0])):
row = []
for i, val in enumerate(vals):
if isinstance(val[pos], np.float64):
converted = format_float_fixed(val[pos], *formats[i])
else:
converted = val[pos]
row.append(converted)
pos += 1
param_table_data.append(row)
mc = self.model.num_params
vc = self.model.volatility.num_params
dc = self.model.distribution.num_params
counts = (mc, vc, dc)
titles = ('Mean Model', 'Volatility Model', 'Distribution')
total = 0
for title, count in zip(titles, counts):
if count == 0:
continue
table_data = param_table_data[total:total + count]
table_stubs = stubs[total:total + count]
total += count
table = SimpleTable(table_data,
stubs=table_stubs,
txt_fmt=fmt_params,
headers=header, title=title)
smry.tables.append(table)
extra_text = ('Results generated with user-specified parameters.',
'Since the model was not estimated, there are no std. '
'errors.')
smry.add_extra_txt(extra_text)
return smry
@cache_readonly
def loglikelihood(self):
"""Model loglikelihood"""
return self._loglikelihood
@cache_readonly
def aic(self):
"""Akaike Information Criteria
-2 * loglikelihood + 2 * num_params"""
return -2 * self.loglikelihood + 2 * self.num_params
@cache_readonly
def num_params(self):
"""Number of parameters in model"""
return len(self.params)
@cache_readonly
def bic(self):
"""
Schwarz/Bayesian Information Criteria
-2 * loglikelihood + log(nobs) * num_params
"""
return -2 * self.loglikelihood + np.log(self.nobs) * self.num_params
@cache_readonly
def params(self):
"""Model Parameters"""
return pd.Series(self._params, index=self._names, name='params')
@cache_readonly
def conditional_volatility(self):
"""
Estimated conditional volatility
"""
if self._is_pandas:
return pd.Series(self._volatility,
name='cond_vol',
index=self._index)
else:
return self._volatility
@cache_readonly
def nobs(self):
"""
Number of data points used ot estimate model
"""
return self._nobs
@cache_readonly
def resid(self):
"""
Model residuals
"""
if self._is_pandas:
return pd.Series(self._resid, name='resid', index=self._index)
else:
return self._resid
def plot(self, annualize=None, scale=None):
"""
Plot standardized residuals and conditional volatility
Parameters
----------
annualize : str, optional
String containing frequency of data that indicates plot should
contain annualized volatility. Supported values are 'D' (daily),
'W' (weekly) and 'M' (monthly), which scale variance by 252, 52,
and 12, respectively.
scale : float, optional