Esempio n. 1
0
def test_param_cov():
    mod = ConstantMean(SP500)
    res = mod.fit(disp="off")
    mod._backcast = None
    cov = mod.compute_param_cov(res.params)
    k = res.params.shape[0]
    assert cov.shape == (k, k)
Esempio n. 2
0
def test_plot_bad_index():
    import matplotlib.pyplot as plt

    idx = sorted(
        [f"{a}{b}{c}" for a, b, c, in product(*([ascii_lowercase] * 3))])
    sp500_copy = SP500.copy()
    sp500_copy.index = idx[:sp500_copy.shape[0]]
    res = ConstantMean(sp500_copy).fit(disp=False)
    fig = res.plot()
    assert isinstance(fig, plt.Figure)
Esempio n. 3
0
    def test_date_first_last_obs(self):
        y = self.y_series

        cm = ConstantMean(y)
        res = cm.fit(last_obs=y.index[900], disp=DISPLAY)

        cm = ConstantMean(y)
        res2 = cm.fit(last_obs=900, disp=DISPLAY)

        assert_equal(res.resid.values, res2.resid.values)
Esempio n. 4
0
    def test_constant_mean(self):
        cm = ConstantMean(self.y)
        parameters = np.array([5.0, 1.0])
        cm.simulate(parameters, self.T)
        assert_equal(cm.num_params, 1)
        with pytest.raises(ValueError):
            cm.simulate(parameters, self.T, x=np.array(10))
        bounds = cm.bounds()
        assert_equal(bounds, [(-np.inf, np.inf)])
        assert_equal(cm.constant, True)
        a, b = cm.constraints()
        assert_equal(a, np.empty((0, 1)))
        assert_equal(b, np.empty((0,)))
        assert isinstance(cm.volatility, ConstantVariance)
        assert isinstance(cm.distribution, Normal)
        assert_equal(cm.lags, None)
        res = cm.fit(disp='off')
        expected = np.array([self.y.mean(), self.y.var()])
        assert_almost_equal(res.params, expected)

        forecasts = res.forecast(horizon=20, start=20)
        direct = pd.DataFrame(index=np.arange(self.y.shape[0]),
                              columns=['h.{0:>02d}'.format(i + 1) for i in
                                       range(20)],
                              dtype=np.float64)
        direct.iloc[20:, :] = res.params.iloc[0]
        # TODO
        # assert_frame_equal(direct, forecasts)
        assert isinstance(forecasts, ARCHModelForecast)
Esempio n. 5
0
    def test_constant_mean_fixed_variance(self):
        rng = RandomState(1234)
        variance = 2 + rng.standard_normal(self.y.shape[0])**2.0
        std = np.sqrt(variance)
        y = pd.Series(std * rng.standard_normal(self.y_series.shape[0]),
                      index=self.y_series.index)

        mod = ConstantMean(y, volatility=FixedVariance(variance))
        res = mod.fit(disp=DISPLAY)
        res.summary()
        assert len(res.params) == 2
        assert "scale" in res.params.index

        mod = ARX(self.y_series,
                  lags=[1, 2, 3],
                  volatility=FixedVariance(variance))
        res = mod.fit(disp=DISPLAY)
        assert len(res.params) == 5
        assert "scale" in res.params.index

        mod = ARX(
            self.y_series,
            lags=[1, 2, 3],
            volatility=FixedVariance(variance, unit_scale=True),
        )
        res = mod.fit(disp=DISPLAY)
        assert len(res.params) == 4
        assert "scale" not in res.params.index
Esempio n. 6
0
    def test_constant_mean(self):
        cm = ConstantMean(self.y)
        parameters = np.array([5.0, 1.0])
        cm.simulate(parameters, self.T)
        assert_equal(cm.num_params, 1)
        bounds = cm.bounds()
        assert_equal(bounds, [(-np.inf, np.inf)])
        assert_equal(cm.constant, True)
        a, b = cm.constraints()
        assert_equal(a, np.empty((0, 1)))
        assert_equal(b, np.empty((0, )))
        assert_true(isinstance(cm.volatility, ConstantVariance))
        assert_true(isinstance(cm.distribution, Normal))
        assert_equal(cm.first_obs, 0)
        assert_equal(cm.last_obs, 1000)
        assert_equal(cm.lags, None)
        res = cm.fit()
        assert_almost_equal(res.params, np.array([self.y.mean(),
                                                  self.y.var()]))

        forecasts = res.forecast(horizon=20, start=20)
        direct = pd.DataFrame(
            index=np.arange(self.y.shape[0]),
            columns=['h.{0:>02d}'.format(i + 1) for i in range(20)],
            dtype=np.float64)
        direct.iloc[20:, :] = res.params.iloc[0]
        assert_frame_equal(direct, forecasts)
Esempio n. 7
0
 def test_egarch(self):
     cm = ConstantMean(self.y)
     cm.volatility = EGARCH()
     res = cm.fit(update_freq=0, disp=DISPLAY)
     summ = res.summary()
     assert "Df Model:                            1" in str(summ)
     cm.distribution = StudentsT()
     cm.fit(update_freq=0, disp=DISPLAY)
Esempio n. 8
0
    def test_no_param_volatility(self):
        cm = ConstantMean(self.y)
        cm.volatility = EWMAVariance()
        cm.fit(update_freq=0)
        cm.volatility = RiskMetrics2006()
        cm.fit(update_freq=0)

        ar = ARX(self.y, lags=5)
        ar.volatility = EWMAVariance()
        ar.fit(update_freq=0)
        ar.volatility = RiskMetrics2006()
        ar.fit(update_freq=0)
Esempio n. 9
0
    def test_constant_mean(self):
        cm = ConstantMean(self.y)
        parameters = np.array([5.0, 1.0])
        cm.simulate(parameters, self.T)
        assert_equal(cm.num_params, 1)
        bounds = cm.bounds()
        assert_equal(bounds, [(-np.inf, np.inf)])
        assert_equal(cm.constant, True)
        a, b = cm.constraints()
        assert_equal(a, np.empty((0, 1)))
        assert_equal(b, np.empty((0,)))
        assert isinstance(cm.volatility, ConstantVariance)
        assert isinstance(cm.distribution, Normal)
        assert_equal(cm.lags, None)
        res = cm.fit(disp='off')
        expected = np.array([self.y.mean(), self.y.var()])
        assert_almost_equal(res.params, expected)

        forecasts = res.forecast(horizon=20, start=20)
        direct = pd.DataFrame(index=np.arange(self.y.shape[0]),
                              columns=['h.{0:>02d}'.format(i + 1) for i in
                                       range(20)],
                              dtype=np.float64)
        direct.iloc[20:, :] = res.params.iloc[0]
        # TODO
        # assert_frame_equal(direct, forecasts)
        assert isinstance(forecasts, ARCHModelForecast)
Esempio n. 10
0
    def test_no_param_volatility(self):
        cm = ConstantMean(self.y)
        cm.volatility = EWMAVariance()
        cm.fit(update_freq=0, disp=DISPLAY)
        cm.volatility = RiskMetrics2006()
        cm.fit(update_freq=0, disp=DISPLAY)

        ar = ARX(self.y, lags=5)
        ar.volatility = EWMAVariance()
        ar.fit(update_freq=0, disp=DISPLAY)
        ar.volatility = RiskMetrics2006()
        ar.fit(update_freq=0, disp=DISPLAY)
        assert 'tau0' in str(ar.volatility)
        assert 'tau1' in str(ar.volatility)
        assert 'kmax' in str(ar.volatility)
Esempio n. 11
0
    def test_no_param_volatility(self):
        cm = ConstantMean(self.y)
        cm.volatility = EWMAVariance()
        cm.fit(update_freq=0)
        cm.volatility = RiskMetrics2006()
        cm.fit(update_freq=0)

        ar = ARX(self.y, lags=5)
        ar.volatility = EWMAVariance()
        ar.fit(update_freq=0)
        ar.volatility = RiskMetrics2006()
        ar.fit(update_freq=0)
Esempio n. 12
0
    def test_date_first_last_obs(self):
        y = self.y_series

        cm = ConstantMean(y)
        res = cm.fit(last_obs=y.index[900], disp=DISPLAY)

        cm = ConstantMean(y)
        res2 = cm.fit(last_obs=900, disp=DISPLAY)

        assert_equal(res.resid.values, res2.resid.values)
Esempio n. 13
0
    def test_no_param_volatility(self):
        cm = ConstantMean(self.y)
        cm.volatility = EWMAVariance()
        cm.fit(update_freq=0, disp=DISPLAY)
        cm.volatility = RiskMetrics2006()
        cm.fit(update_freq=0, disp=DISPLAY)

        ar = ARX(self.y, lags=5)
        ar.volatility = EWMAVariance()
        ar.fit(update_freq=0, disp=DISPLAY)
        ar.volatility = RiskMetrics2006()
        ar.fit(update_freq=0, disp=DISPLAY)
        assert 'tau0' in str(ar.volatility)
        assert 'tau1' in str(ar.volatility)
        assert 'kmax' in str(ar.volatility)
Esempio n. 14
0
    def test_constant_mean_fixed_variance(self):
        variance = 2 + self.rng.standard_normal(self.y.shape[0]) ** 2.0
        mod = ConstantMean(self.y_series, volatility=FixedVariance(variance))
        res = mod.fit()
        print(res.summary())
        assert len(res.params) == 2
        assert 'scale' in res.params.index

        mod = ARX(self.y_series, lags=[1, 2, 3], volatility=FixedVariance(variance))
        res = mod.fit()
        assert len(res.params) == 5
        assert 'scale' in res.params.index

        mod = ARX(self.y_series, lags=[1, 2, 3],
                  volatility=FixedVariance(variance, unit_scale=True))
        res = mod.fit()
        assert len(res.params) == 4
        assert 'scale' not in res.params.index
Esempio n. 15
0
    def test_constant_mean_fixed_variance(self):
        variance = 2 + np.random.standard_normal(self.y.shape[0]) ** 2.0
        mod = ConstantMean(self.y_series, volatility=FixedVariance(variance))
        res = mod.fit()
        print(res.summary())
        assert len(res.params) == 2
        assert 'scale' in res.params.index

        mod = ARX(self.y_series, lags=[1, 2, 3], volatility=FixedVariance(variance))
        res = mod.fit()
        assert len(res.params) == 5
        assert 'scale' in res.params.index

        mod = ARX(self.y_series, lags=[1, 2, 3],
                  volatility=FixedVariance(variance, unit_scale=True))
        res = mod.fit()
        assert len(res.params) == 4
        assert 'scale' not in res.params.index
Esempio n. 16
0
 def test_egarch(self):
     cm = ConstantMean(self.y)
     cm.volatility = EGARCH()
     cm.fit(update_freq=0, disp=DISPLAY)
     cm.distribution = StudentsT()
     cm.fit(update_freq=0, disp=DISPLAY)
Esempio n. 17
0
def test_invalid_vol_dist():
    with pytest.raises(TypeError, match="volatility must inherit"):
        ConstantMean(SP500, volatility="GARCH")
    with pytest.raises(TypeError, match="distribution must inherit"):
        ConstantMean(SP500, distribution="Skew-t")
Esempio n. 18
0
 def test_multiple_lags(self):
     """Smoke test to ensure models estimate with multiple lags"""
     vp = {'garch': GARCH,
           'egarch': EGARCH,
           'harch': HARCH,
           'arch': ARCH}
     cm = ConstantMean(self.y)
     for name, process in iteritems(vp):
         cm.volatility = process()
         cm.fit(update_freq=0, disp='off')
         for p in [1, 2, 3]:
             for o in [1, 2, 3]:
                 for q in [1, 2, 3]:
                     if name in ('arch',):
                         cm.volatility = process(p=p + o + q)
                         cm.fit(update_freq=0, disp='off')
                     elif name in ('harch',):
                         cm.volatility = process(lags=[p, p + o, p + o + q])
                         cm.fit(update_freq=0, disp='off')
                     else:
                         cm.volatility = process(p=p, o=o, q=q)
                         cm.fit(update_freq=0, disp='off')
Esempio n. 19
0
 def test_egarch(self):
     cm = ConstantMean(self.y)
     cm.volatility = EGARCH()
     cm.fit(update_freq=0, disp=DISPLAY)
     cm.distribution = StudentsT()
     cm.fit(update_freq=0, disp=DISPLAY)
Esempio n. 20
0
def test_false_reindex():
    res = ConstantMean(SP500, volatility=GARCH()).fit(disp="off")
    fcast = res.forecast(start=0, reindex=True)
    assert fcast.mean.shape[0] == SP500.shape[0]
    assert_series_equal(pd.Series(fcast.mean.index), pd.Series(SP500.index))
Esempio n. 21
0
 def test_multiple_lags(self):
     """Smoke test to ensure models estimate with multiple lags"""
     vp = {"garch": GARCH, "egarch": EGARCH, "harch": HARCH, "arch": ARCH}
     cm = ConstantMean(self.y)
     for name, process in vp.items():
         cm.volatility = process()
         cm.fit(update_freq=0, disp=DISPLAY)
         for p in [1, 2, 3]:
             for o in [1, 2, 3]:
                 for q in [1, 2, 3]:
                     if name in ("arch",):
                         cm.volatility = process(p=p + o + q)
                         cm.fit(update_freq=0, disp=DISPLAY)
                     elif name in ("harch",):
                         cm.volatility = process(lags=[p, p + o, p + o + q])
                         cm.fit(update_freq=0, disp=DISPLAY)
                     else:
                         cm.volatility = process(p=p, o=o, q=q)
                         cm.fit(update_freq=0, disp=DISPLAY)
Esempio n. 22
0
    def test_date_first_last_obs(self):
        y = self.y_series
        cm = ConstantMean(y, hold_back=y.index[100])
        res = cm.fit()
        cm = ConstantMean(y, hold_back=100)
        res2 = cm.fit()
        assert_equal(res.resid.values, res2.resid.values)
        cm = ConstantMean(y, hold_back='2002-12-01')
        res2 = cm.fit()
        assert_equal(res.resid.values, res2.resid.values)
        # Test non-exact start
        cm = ConstantMean(y, hold_back='2002-12-02')
        res2 = cm.fit()
        assert_equal(res.resid.values, res2.resid.values)

        cm = ConstantMean(y, last_obs=y.index[900])
        res = cm.fit()
        cm = ConstantMean(y, last_obs=900)
        res2 = cm.fit()
        assert_equal(res.resid.values, res2.resid.values)

        cm = ConstantMean(y, hold_back='2002-12-02', last_obs=y.index[900])
        res = cm.fit()
        cm = ConstantMean(y, hold_back=100, last_obs=900)
        res2 = cm.fit()
        assert_equal(res.resid.values, res2.resid.values)
        # Mix and match
        cm = ConstantMean(y, hold_back=100, last_obs=y.index[900])
        res2 = cm.fit()
        assert_equal(res.resid.values, res2.resid.values)
Esempio n. 23
0
    def test_constant_mean(self):
        cm = ConstantMean(self.y)
        parameters = np.array([5.0, 1.0])
        cm.simulate(parameters, self.T)
        assert_equal(cm.num_params, 1)
        with pytest.raises(ValueError):
            cm.simulate(parameters, self.T, x=np.array(10))
        bounds = cm.bounds()
        assert_equal(bounds, [(-np.inf, np.inf)])
        assert_equal(cm.constant, True)
        a, b = cm.constraints()
        assert_equal(a, np.empty((0, 1)))
        assert_equal(b, np.empty((0,)))
        assert isinstance(cm.volatility, ConstantVariance)
        assert isinstance(cm.distribution, Normal)
        assert cm.lags is None
        res = cm.fit(disp=DISPLAY)
        expected = np.array([self.y.mean(), self.y.var()])
        assert_almost_equal(res.params, expected)

        forecasts = res.forecast(horizon=20, start=20)
        direct = pd.DataFrame(
            index=np.arange(self.y.shape[0]),
            columns=["h.{0:>02d}".format(i + 1) for i in range(20)],
            dtype="double",
        )
        direct.iloc[20:, :] = res.params.iloc[0]
        # TODO
        # assert_frame_equal(direct, forecasts)
        assert isinstance(forecasts, ARCHModelForecast)
        assert isinstance(cm.__repr__(), str)
        assert isinstance(cm.__str__(), str)
        assert "<strong>" in cm._repr_html_()
        with pytest.raises(ValueError, match="horizon must be an integer >= 1"):
            res.forecast(horizon=0, start=20)
Esempio n. 24
0
    def test_date_first_last_obs(self):
        y = self.y_series
        cm = ConstantMean(y, hold_back=y.index[100])
        res = cm.fit()
        cm = ConstantMean(y, hold_back=100)
        res2 = cm.fit()
        assert_equal(res.resid.values, res2.resid.values)
        cm = ConstantMean(y, hold_back='2002-12-01')
        res2 = cm.fit()
        assert_equal(res.resid.values, res2.resid.values)
        # Test non-exact start
        cm = ConstantMean(y, hold_back='2002-12-02')
        res2 = cm.fit()
        assert_equal(res.resid.values, res2.resid.values)

        cm = ConstantMean(y, last_obs=y.index[900])
        res = cm.fit()
        cm = ConstantMean(y, last_obs=900)
        res2 = cm.fit()
        assert_equal(res.resid.values, res2.resid.values)

        cm = ConstantMean(y, hold_back='2002-12-02', last_obs=y.index[900])
        res = cm.fit()
        cm = ConstantMean(y, hold_back=100, last_obs=900)
        res2 = cm.fit()
        assert_equal(res.resid.values, res2.resid.values)
        # Mix and match
        cm = ConstantMean(y, hold_back=100, last_obs=y.index[900])
        res2 = cm.fit()
        assert_equal(res.resid.values, res2.resid.values)
Esempio n. 25
0
def test_parameterless_fit(first_obs, last_obs, vol):
    base = ConstantMean(SP500, volatility=vol)
    base_res = base.fit(first_obs=first_obs, last_obs=last_obs, disp="off")
    mod = ZeroMean(SP500, volatility=vol)
    res = mod.fit(first_obs=first_obs, last_obs=last_obs, disp="off")
    assert res.conditional_volatility.shape == base_res.conditional_volatility.shape
Esempio n. 26
0
 def test_multiple_lags(self):
     """Smoke test to ensure models estimate with multiple lags"""
     vp = {'garch': GARCH,
           'egarch': EGARCH,
           'harch': HARCH,
           'arch': ARCH}
     cm = ConstantMean(self.y)
     for name, process in iteritems(vp):
         cm.volatility = process()
         cm.fit(update_freq=0, disp='off')
         for p in [1, 2, 3]:
             for o in [1, 2, 3]:
                 for q in [1, 2, 3]:
                     if name in ('arch',):
                         cm.volatility = process(p=p + o + q)
                         cm.fit(update_freq=0, disp='off')
                     elif name in ('harch',):
                         cm.volatility = process(lags=[p, p + o, p + o + q])
                         cm.fit(update_freq=0, disp='off')
                     else:
                         cm.volatility = process(p=p, o=o, q=q)
                         cm.fit(update_freq=0, disp='off')