def get_har_forecast(dependent, lags, dist): import sys har_test = HARX(y=dependent, lags=lags, distribution=dist, rescale=True) index = dependent.index end_loc = np.where(index >= '2017-01-03')[0].min( ) #returns where index is greater than a date. forecasts = {} for i in range( 890): #878 values between the start and end of the OS dataset. sys.stdout.write('.') sys.stdout.flush() res = har_test.fit(first_obs=i, last_obs=i + end_loc, disp='off', options={ 'maxiter': 10000000, 'eps': 0.01, 'ftol': 0.0001 }) #https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.fmin_slsqp.html temp = res.forecast(horizon=1).mean fcast = temp.iloc[i + end_loc - 1] forecasts[fcast.name] = fcast har_forecast = (pd.DataFrame(forecasts).T) return (har_forecast)
def test_forecast_exogenous_regressors(self): y = 10 * self.rng.randn(1000, 1) x = self.rng.randn(1000, 2) am = HARX(y=y, x=x, lags=[1, 2]) res = am.fit() fcasts = res.forecast(horizon=1, start=1) const, har01, har02, ex0, ex1, _ = res.params y_01 = y[1:-1] y_02 = (y[1:-1] + y[0:-2]) / 2 x0 = x[2:, :1] x1 = x[2:, 1:2] direct = const + har01 * y_01 + har02 * y_02 + ex0 * x0 + ex1 * x1 direct = np.vstack(([[np.nan]], direct, [[np.nan]])) direct = pd.DataFrame(direct, columns=["h.1"]) assert_allclose(np.asarray(direct), fcasts.mean) fcasts2 = res.forecast(horizon=2, start=1) assert fcasts2.mean.shape == (1000, 2) assert fcasts2.mean.isnull().all()["h.2"] assert_frame_equal(fcasts.mean, fcasts2.mean[["h.1"]])
def test_forecast_exogenous_regressors(self): y = self.rng.randn(1000, 1) x = self.rng.randn(1000, 2) am = HARX(y=y, x=x, lags=[1, 2]) res = am.fit() fcasts = res.forecast(horizon=1, start=1) const, har01, har02, ex0, ex1, _ = res.params y_01 = y[1:-1] y_02 = (y[1:-1] + y[0:-2]) / 2 x0 = x[2:, :1] x1 = x[2:, 1:2] direct = const + har01 * y_01 + har02 * y_02 + ex0 * x0 + ex1 * x1 direct = np.vstack(([[np.nan]], direct, [[np.nan]])) direct = pd.DataFrame(direct, columns=['h.1']) assert_allclose(direct.values, fcasts.mean) fcasts2 = res.forecast(horizon=2, start=1) assert fcasts2.mean.shape == (1000, 2) assert fcasts2.mean.isnull().all()['h.2'] assert_frame_equal(fcasts.mean, fcasts2.mean[['h.1']])
HARCH, HARX, ConstantMean, ConstantVariance, EWMAVariance, MIDASHyperbolic, RiskMetrics2006, ZeroMean, arch_model, ) from arch.univariate.mean import _ar_forecast, _ar_to_impulse SP500 = 100 * sp500.load()["Adj Close"].pct_change().dropna() MEAN_MODELS = [ HARX(SP500, lags=[1, 5]), ARX(SP500, lags=2), ConstantMean(SP500), ZeroMean(SP500), ] VOLATILITIES = [ ConstantVariance(), GARCH(), FIGARCH(), EWMAVariance(lam=0.94), MIDASHyperbolic(), HARCH(lags=[1, 5, 22]), RiskMetrics2006(), APARCH(), EGARCH(),
def model(self): return HARX(**self.__params, lags=self.__lags)
def __bic_with(self, lag_list): model = HARX(**self.__params, lags=lag_list) result = model.fit(update_freq=0, disp='off') return round(result.bic, 4)