def acovf_explicit(ar, ma, nobs): '''add correlation of MA representation explicitely ''' ir = arma_impulse_response(ar, ma) acovfexpl = [np.dot(ir[:nobs-t], ir[t:nobs]) for t in range(10)] return acovfexpl
def detectAO(model, alpha=0.05, robust=True): """ Adapted from R's TSA library detectAO. This function serves to detect whether there is any AO. It implements the test statistic lambda_{1,t} proposed by Chang, Chen and Tiao (1988). """ d = np.maximum(model.loglikelihood_burn, model.nobs_diffuse) resid = model.filter_results.standardized_forecasts_error[0] n_resid = len(resid) pi_weights = arma_impulse_response(ar=-model.polynomial_ma, ma=-model.polynomial_ar, leads=n_resid) rho2 = 1 / np.cumsum(pi_weights**2) k = np.zeros(2 * len(resid) - 1) k[-len(resid):] = resid[::-1] omega = lfilter(b=pi_weights, a=np.ones(1), x=k)[n_resid - 1:] * rho2 if robust: sigma = np.sqrt(np.pi / 2) * np.nanmean(np.abs(resid)) else: sigma = np.sqrt(model.params['sigma2']) lambda2T = (omega / (sigma * np.sqrt(rho2)))[::-1] cutoff = norm.ppf(1 - alpha / (2 * len(lambda2T))) out = (np.abs(lambda2T) > cutoff) ind = np.array(np.where(out)).squeeze() lambda2 = lambda2T[out].squeeze() return lambda2, ind
def acovf_explicit(ar, ma, nobs): '''add correlation of MA representation explicitely ''' ir = arma_impulse_response(ar, ma) acovfexpl = [np.dot(ir[:nobs - t], ir[t:nobs]) for t in range(10)] return acovfexpl
def arma_acovf_historical(ar, ma, nobs=10): if np.abs(np.sum(ar) - 1) > 0.9: nobs_ir = max(1000, 2 * nobs) else: nobs_ir = max(100, 2 * nobs) ir = arma_impulse_response(ar, ma, leads=nobs_ir) while ir[-1] > 5 * 1e-5: nobs_ir *= 10 ir = arma_impulse_response(ar, ma, leads=nobs_ir) if nobs_ir > 50000 and nobs < 1001: end = len(ir) acovf = np.array([np.dot(ir[:end-nobs-t], ir[t:end-nobs]) for t in range(nobs)]) else: acovf = np.correlate(ir, ir, 'full')[len(ir) - 1:] return acovf[:nobs]
def test_arma_impulse_response(): arrep = arma_impulse_response(armarep.ma, armarep.ar, leads=21)[1:] marep = arma_impulse_response(armarep.ar, armarep.ma, leads=21)[1:] assert_array_almost_equal(armarep.marep.ravel(), marep, 14) # difference in sign convention to matlab for AR term assert_array_almost_equal(-armarep.arrep.ravel(), arrep, 14)
def test_fi(): # test identity of ma and ar representation of fi lag polynomial n = 100 mafromar = arma_impulse_response(lpol_fiar(0.4, n=n), [1], n) assert_array_almost_equal(mafromar, lpol_fima(0.4, n=n), 13)
from statsmodels.tsa.arima_process import arma_generate_sample, arma_impulse_response from statsmodels.tsa.arima_process import arma_acovf, arma_acf, ARIMA #from movstat import acf, acovf #from statsmodels.sandbox.tsa import acf, acovf, pacf from statsmodels.tsa.stattools import acf, acovf, pacf ar = [1., -0.6] #ar = [1., 0.] ma = [1., 0.4] #ma = [1., 0.4, 0.6] #ma = [1., 0.] mod = ''#'ma2' x = arma_generate_sample(ar, ma, 5000) x_acf = acf(x)[:10] x_ir = arma_impulse_response(ar, ma) #print x_acf[:10] #print x_ir[:10] #irc2 = np.correlate(x_ir,x_ir,'full')[len(x_ir)-1:] #print irc2[:10] #print irc2[:10]/irc2[0] #print irc2[:10-1] / irc2[1:10] #print x_acf[:10-1] / x_acf[1:10] # detrend helper from matplotlib.mlab def detrend(x, key=None): if key is None or key=='constant': return detrend_mean(x) elif key=='linear': return detrend_linear(x)
-0.00231864]) >>> # verified for points [[5,10,20,25]] at 4 decimals with Bhardwaj, Swanson, Journal of Eonometrics 2006 ''' print(lpol_fiar(0.4, n=20)) print(lpol_fima(-0.4, n=20)) print(np.sum((lpol_fima(-0.4, n=n)[1:] + riinv[1:])**2)) #different signs print(np.sum((lpol_fiar(0.4, n=n)[1:] - riinv[1:])**2)) #corrected signs #test is now in statsmodels.tsa.tests.test_arima_process from statsmodels.tsa.tests.test_arima_process import test_fi test_fi() ar_true = [1, -0.4] ma_true = [1, 0.5] ar_desired = arma_impulse_response(ma_true, ar_true) ar_app, ma_app, res = ar2arma(ar_desired, 2, 1, n=100, mse='ar', start=[0.1]) print(ar_app, ma_app) ar_app, ma_app, res = ar2arma(ar_desired, 2, 2, n=100, mse='ar', start=[-0.1, 0.1]) print(ar_app, ma_app) ar_app, ma_app, res = ar2arma(ar_desired, 2, 3, n=100,
from statsmodels.tsa.arima_process import arma_generate_sample, arma_impulse_response from statsmodels.tsa.arima_process import arma_acovf, arma_acf, ARIMA #from movstat import acf, acovf #from statsmodels.sandbox.tsa import acf, acovf, pacf from statsmodels.tsa.stattools import acf, acovf, pacf ar = [1., -0.6] #ar = [1., 0.] ma = [1., 0.4] #ma = [1., 0.4, 0.6] #ma = [1., 0.] mod = '' #'ma2' x = arma_generate_sample(ar, ma, 5000) x_acf = acf(x)[:10] x_ir = arma_impulse_response(ar, ma) #print x_acf[:10] #print x_ir[:10] #irc2 = np.correlate(x_ir,x_ir,'full')[len(x_ir)-1:] #print irc2[:10] #print irc2[:10]/irc2[0] #print irc2[:10-1] / irc2[1:10] #print x_acf[:10-1] / x_acf[1:10] # detrend helper from matplotlib.mlab def detrend(x, key=None): if key is None or key == 'constant': return detrend_mean(x) elif key == 'linear':
plot_pacf(xt, lags=50, ax=ax_pacf) plt.tight_layout() return None # Number of samples n = 600 # Generate AR(1) dataset ar = np.r_[1, 0.6] ma = np.r_[1, 0.3] ar1ma1_data = smtsa.arma_generate_sample(ar=ar, ma=ma, nsample=n) plotds(ar1ma1_data) # Impluse response curve plt.plot(arima_process.arma_impulse_response(ar, ma, nobs=20)) plt.ylabel("Impact") plt.xlabel("Lag") # Build AR(1) model ar1ma1 = smtsa.ARMA(ar1ma1_data.tolist(), order=(1, 1)).fit(maxlag=30, method="mle", trend="nc") ar1ma1.summary() # Optimize ARMA parameters aicVal = [] for ari in range(1, 3): for maj in range(1, 3): arma_obj = smtsa.ARMA(ar1ma1_data.tolist(), order=(ari, maj)).fit(maxlag=30,
plot_pacf(xt, lags=50, ax=ax_pacf) plt.tight_layout() return None # Number of samples n = 600 # Generate AR(1) dataset ar = np.r_[1, 0.6] ma = np.r_[1, 0.3] ar1ma1_data = smtsa.arma_generate_sample(ar=ar, ma=ma, nsample=n) plotds(ar1ma1_data ) # Impluse response curve plt.plot(arima_process.arma_impulse_response(ar, ma, nobs=20)) plt.ylabel("Impact") plt.xlabel("Lag") # Build AR(1) model ar1ma1 = smtsa.ARMA(ar1ma1_data.tolist(), order=(1, 1)).fit( maxlag=30, method='mle', trend='nc') ar1ma1.summary() # Optimize ARMA parameters aicVal=[] for ari in range(1, 3): for maj in range(1,3): arma_obj = smtsa.ARMA(ar1ma1_data.tolist(), order=(ari, maj)).fit(maxlag=30, method='mle', trend='nc')
>>> # verified for points [[5,10,20,25]] at 4 decimals with Bhardwaj, Swanson, Journal of Eonometrics 2006 ''' print(lpol_fiar(0.4, n=20)) print(lpol_fima(-0.4, n=20)) print(np.sum((lpol_fima(-0.4, n=n)[1:] + riinv[1:])**2)) #different signs print(np.sum((lpol_fiar(0.4, n=n)[1:] - riinv[1:])**2)) #corrected signs #test is now in statsmodels.tsa.tests.test_arima_process from statsmodels.tsa.tests.test_arima_process import test_fi test_fi() ar_true = [1, -0.4] ma_true = [1, 0.5] ar_desired = arma_impulse_response(ma_true, ar_true) ar_app, ma_app, res = ar2arma(ar_desired, 2,1, n=100, mse='ar', start=[0.1]) print(ar_app, ma_app) ar_app, ma_app, res = ar2arma(ar_desired, 2,2, n=100, mse='ar', start=[-0.1, 0.1]) print(ar_app, ma_app) ar_app, ma_app, res = ar2arma(ar_desired, 2,3, n=100, mse='ar')#, start = [-0.1, 0.1]) print(ar_app, ma_app) slow = 1 if slow: ar_desired = lpol_fiar(0.4, n=100) ar_app, ma_app, res = ar2arma(ar_desired, 3, 1, n=100, mse='ar')#, start = [-0.1, 0.1]) print(ar_app, ma_app) ar_app, ma_app, res = ar2arma(ar_desired, 10, 10, n=100, mse='ar')#, start = [-0.1, 0.1]) print(ar_app, ma_app)
import statsmodels.tsa.arima_process as sm import numpy as np import matplotlib.pyplot as plt AR = np.array([1, -0.9]) MA = np.array([1, 1.2]) arma_process = sm.arma_impulse_response(AR, MA, leads=20) x = [1 * i for i in range(len(arma_process))] print(x) print(arma_process) plt.scatter(x, arma_process) plt.plot(x, arma_process) plt.xlabel("Future Periods (h)") plt.ylabel("Implus Responses") plt.show()