<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
	<id>http://www.simulace.info/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Hazn00</id>
	<title>Simulace.info - User contributions [en]</title>
	<link rel="self" type="application/atom+xml" href="http://www.simulace.info/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Hazn00"/>
	<link rel="alternate" type="text/html" href="http://www.simulace.info/index.php/Special:Contributions/Hazn00"/>
	<updated>2026-07-27T16:37:37Z</updated>
	<subtitle>User contributions</subtitle>
	<generator>MediaWiki 1.31.1</generator>
	<entry>
		<id>http://www.simulace.info/index.php?title=WS_2019/2020&amp;diff=19240</id>
		<title>WS 2019/2020</title>
		<link rel="alternate" type="text/html" href="http://www.simulace.info/index.php?title=WS_2019/2020&amp;diff=19240"/>
		<updated>2020-01-21T18:34:40Z</updated>

		<summary type="html">&lt;p&gt;Hazn00: /* Simulation */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Semestral papers from winter term 2019/2020. Please, put here links to the pages with your paper. First you need to have your [[Assignments WS 2019/2020|assignment approved]]&lt;br /&gt;
&lt;br /&gt;
== Simulation ==&lt;br /&gt;
[http://www.simulace.info/index.php/Cotton_Processing_Quality:_Cotton,_Seed,_Lint,_Trash Cotton Processing Quality: Cotton, Seed, Lint, Trash] , Ibrahim Aghazada (in progress)&lt;br /&gt;
&lt;br /&gt;
[http://www.simulace.info/index.php/Time_Series_Model_Building_Process Time Series Model Building Process] , [[User:Hazn00|Hazn0000]] ([[User talk:Hazn00|talk]]) 16:15, 20 January 2020 (CET) (done)&lt;br /&gt;
&lt;br /&gt;
[http://www.simulace.info/index.php/Indian_Elephant_Population_in_Thailand Indian Elephant Population in Thailand] , [[User:Xkavj12|Xkavj12]] ([[User talk:Xkavj12|talk]]) 18:42, 20 January 2020 (CET) &lt;br /&gt;
&lt;br /&gt;
[http://www.simulace.info/index.php/Atlantic_Bluefin_Tuna_Population Atlantic Bluefin Tuna Population], [[User:Vokp00|Vokp00]] ([[User talk:Vokp00|talk]]) 20:32, 20 January 2020 (CET)&lt;br /&gt;
&lt;br /&gt;
[http://www.simulace.info/index.php/Shopping_Centre_Simulation Shopping Centre Management Simulation], [[User:Tkad01|Tkad01]] ([[User talk:Tkad01|talk]]) 21:57, 20 January 2020 (CET)&lt;br /&gt;
&lt;br /&gt;
== Textbook Chapters ==&lt;br /&gt;
[http://www.simulace.info/index.php/Limits_to_Growth Limits to Growth] , Ibrahim Aghazada (in progress)&lt;/div&gt;</summary>
		<author><name>Hazn00</name></author>
		
	</entry>
	<entry>
		<id>http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19187</id>
		<title>Time Series Model Building Process</title>
		<link rel="alternate" type="text/html" href="http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19187"/>
		<updated>2020-01-20T18:14:48Z</updated>

		<summary type="html">&lt;p&gt;Hazn00: /* Conclusion */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Linear time series models, e.g., ARIMA models for univariate time series, is a popular tool for modeling dynamics of time series and predicting the time series. The methodology is not popular only in statistics, econometrics and science, but also in machine learning business applications. The key question is how to build the model. We have to choose the form of the model, in particular number of lags for so-called autoregressive part (usually denoted as p) and moving average part of the model (usually denoted as d). The common guides usually provide a ‘cook book’ for model selection, see for example [https://www.machinelearningplus.com/time-series/arima-model-time-series-forecasting-python/, ARIMA Model – Complete Guide to Time Series Forecasting in Python] . This goal of this simulation is to compare four basic methods for selection of lags (p) for the autoregressive part.&lt;br /&gt;
&lt;br /&gt;
== Problem Definition ==&lt;br /&gt;
&lt;br /&gt;
The autoregressive process has form&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\phi}_2x_{t-2}+...+{\phi}_px_{t-p} + {\epsilon}_t&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;{\epsilon}_t \sim N(0,{\sigma}^2) &amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
However, we observe only the realized value and we do not know the hyperparameter p. Therefore, we must estimate it. The considered methods are following.&lt;br /&gt;
&lt;br /&gt;
=== GETS (General-to-Specific) ===&lt;br /&gt;
&lt;br /&gt;
We first start with high enough p (pmax in the code), and perform statistical test whether the last lag has statistically significant impact, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p = 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p \neq 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the impact is insignificant, we reduce p by one and continue until the parameter for the last lag is significant, i.e. last lag has significant effect.&lt;br /&gt;
&lt;br /&gt;
=== Specific-to-General ===&lt;br /&gt;
&lt;br /&gt;
The second approach works similarly as GETS, the only difference is that we first start with model without any lag, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and we are adding lags until they are significant.&lt;br /&gt;
&lt;br /&gt;
=== BIC (Bayesian Information Criteria) ===&lt;br /&gt;
&lt;br /&gt;
Bayesian information criteria is based on a likelihood of the model and number of parameters. The criteria punish the model for high number of parameters for a potential over-fitting, and rewards the model for good fit of the data. The lower the BIC value is, the better the model (a little bit counterintuitive definition). We are supposed to select a model with the lowest value of BIC.&lt;br /&gt;
&lt;br /&gt;
=== AIC (Akaike Information Criteria)  ===&lt;br /&gt;
&lt;br /&gt;
Works exactly the same as BIC, but the formula is slightly different.&lt;br /&gt;
&lt;br /&gt;
== Method and Simulation Method ==&lt;br /&gt;
&lt;br /&gt;
The solution consists of three key elements, data generating process, AR(p) model, and simulation.&lt;br /&gt;
&lt;br /&gt;
=== Data Generating Process ===&lt;br /&gt;
&lt;br /&gt;
To answer the question, which model selection method is the best, we are generating an artificial data. We assume that data are created by AR(1) process&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
or AR(2)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\mu} + {\phi}_2x_{t-2} + {\epsilon}_{t}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
with random error &amp;lt;math&amp;gt;&amp;lt;/math&amp;gt; . Therefore, we must generate random numbers for random errors, and iterate over the equations described above. The initial values of the processes, e.g., &amp;lt;math&amp;gt;x_0&amp;lt;/math&amp;gt;, are set to the theoretical mean value of the process.&lt;br /&gt;
&lt;br /&gt;
=== AR(p) model ===&lt;br /&gt;
&lt;br /&gt;
For a given series &amp;lt;math&amp;gt;{x_1,x_2,...x_T}&amp;lt;/math&amp;gt; with a length ''T'' estimates a model for a given p.&lt;br /&gt;
&lt;br /&gt;
=== Simulation ===&lt;br /&gt;
&lt;br /&gt;
Perform n Monte Carlo simulations, where in each simulation the data generating process is used to create a time series. Then the AR(p) model is estimated for ''p=0,1,…,pmax'', and the best models are selected according to the selection criteria described above. Therefore, we will obtain four estimates of p that corresponds to the described methods for each of the n simulation. The final step is to compute % success of correctly estimated p for each of four methods.&lt;br /&gt;
&lt;br /&gt;
== Controls ==&lt;br /&gt;
The solution allow to set number of simulation n. We need high enough n to make sure that the results will converge close enough to actual results. Therefore, we have set &amp;lt;math&amp;gt;n=5000&amp;lt;/math&amp;gt;. Higher n will not significantly increase the precision of the results.&lt;br /&gt;
&lt;br /&gt;
The more important controls is selection of AR(1) or AR(2) process, and selection of parameters &amp;lt;math&amp;gt;{\mu},{\sigma},{\phi}_1&amp;lt;/math&amp;gt;  and  &amp;lt;math&amp;gt;{\phi}_2&amp;lt;/math&amp;gt; for the process. Additionally, we can set length of the generated series and even compare performance for series with two distinct lengths &amp;lt;math&amp;gt;T_1&amp;lt;/math&amp;gt; and &amp;lt;math&amp;gt;T_2&amp;lt;/math&amp;gt;. In other words, one method may perform better for low number of observations than other, and this control allow to compare the performance.&lt;br /&gt;
&lt;br /&gt;
== Results ==&lt;br /&gt;
&amp;lt;gallery&amp;gt;&lt;br /&gt;
File:Phi01.png|&amp;lt;math&amp;gt;{\Phi} = 0.1&amp;lt;/math&amp;gt;&lt;br /&gt;
File:Phi09.png|&amp;lt;math&amp;gt;{\Phi} = 0.9&amp;lt;/math&amp;gt;&lt;br /&gt;
File:Phi04Phi04.png|&amp;lt;math&amp;gt;{\Phi}_1= 0.4, {\Phi}_2 = 0.4&amp;lt;/math&amp;gt;&lt;br /&gt;
File:Phi00Phi09.png|&amp;lt;math&amp;gt;{\Phi}_1= 0.0, {\Phi}_2 = 0.9&amp;lt;/math&amp;gt;&lt;br /&gt;
&amp;lt;/gallery&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
===&amp;lt;math&amp;gt;{\phi} = 0.1&amp;lt;/math&amp;gt;===&lt;br /&gt;
Previous periods don't have big impact. &lt;br /&gt;
AIC method works well with smaller  samples. In case of bigger samples, BIC method works better than AIC.&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;math&amp;gt;{\phi} = 0.9&amp;lt;/math&amp;gt;===&lt;br /&gt;
BIC is the best method for small and big samples. Even though the GETS method doesn't work quite well, it is commonly used. The bigger tha max value of p is used, the bigger is the probability of getting the wrong guess from the simulation.&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;math&amp;gt;{\phi}_1 = 0.0&amp;lt;/math&amp;gt;  and &amp;lt;math&amp;gt;{\phi}_2 = 0.9&amp;lt;/math&amp;gt;===&lt;br /&gt;
BIC is the best method for small and big samples again. &lt;br /&gt;
As we can see, Spec-to-gen method gives us very wrong result in approximately 1/4 cases, because the null value gives no sense in this case.&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;math&amp;gt;{\phi}_1 = 0.4&amp;lt;/math&amp;gt; and &amp;lt;math&amp;gt;{\phi}_2 = 0.4&amp;lt;/math&amp;gt;===&lt;br /&gt;
This process is set to not be influenced by previous periods.&lt;br /&gt;
The BIC method works the best again.&lt;br /&gt;
&lt;br /&gt;
== Code ==&lt;br /&gt;
=== Models.py ===&lt;br /&gt;
The part of the code ''''class ARp(object)'''' was created with great help from another student and it is not originally created for this course.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import numpy as np from numpy.linalg &lt;br /&gt;
import inv from scipy.stats &lt;br /&gt;
import norm&lt;br /&gt;
&lt;br /&gt;
def sim1(mu, phi1, sigmaSq, T):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates single trajectory.&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    x = np.zeros(T+1)&lt;br /&gt;
    epsilon = np.random.normal(0,sigmaSq, T+1)&lt;br /&gt;
&lt;br /&gt;
    x[0] = mu / (1.0 - phi1)&lt;br /&gt;
&lt;br /&gt;
    for t in np.arange(T):&lt;br /&gt;
        x[t+1] = mu + phi1 * x[t] + epsilon[t]&lt;br /&gt;
&lt;br /&gt;
    return x[1:]&lt;br /&gt;
&lt;br /&gt;
def trajectories1(mu, phi1, sigmaSq, T, n):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates n-trajectories of AR(1) process&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :param n:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    X = np.zeros([n,T])&lt;br /&gt;
    for s in np.arange(n):&lt;br /&gt;
        X[s,:] = sim1(mu, phi1, sigmaSq, T)&lt;br /&gt;
    return X&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
def sim2(mu, phi1, phi2, sigmaSq, T):&lt;br /&gt;
    x = np.zeros(T+2)&lt;br /&gt;
    epsilon = np.random.normal(0,sigmaSq, T+2)&lt;br /&gt;
&lt;br /&gt;
    x[0] = mu / (1.0 - phi1-phi2)&lt;br /&gt;
    x[1] = mu / (1.0 - phi1-phi2)&lt;br /&gt;
&lt;br /&gt;
    for t in np.arange(T)+1:&lt;br /&gt;
        x[t+1] = mu + phi1 * x[t] + phi2 * x[t-1] + epsilon[t]&lt;br /&gt;
&lt;br /&gt;
    return x[2:]&lt;br /&gt;
&lt;br /&gt;
def trajectories2(mu, phi1, phi2, sigmaSq, T, n):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates n-trajectories of AR(2) process&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param phi2:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :param n:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    X = np.zeros([n,T])&lt;br /&gt;
    for s in np.arange(n):&lt;br /&gt;
        X[s,:] = sim2(mu, phi1, phi2, sigmaSq, T)&lt;br /&gt;
    return X&lt;br /&gt;
&lt;br /&gt;
class ARp(object):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;AR(p) class allowing to estimate the model &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
    def __init__(self, x, p, pmax):&lt;br /&gt;
        self.p = p&lt;br /&gt;
        self.x = x&lt;br /&gt;
        self.T = float(x.size)&lt;br /&gt;
        self.par = np.zeros(p+2) #np.array: c, phi_1, phi_2, ... phi_p, sigma^2&lt;br /&gt;
&lt;br /&gt;
        #Init. matrices for OLS&lt;br /&gt;
        Y = self.x[pmax:]&lt;br /&gt;
        Xtemp = []&lt;br /&gt;
&lt;br /&gt;
        for i in np.arange(Y.size):&lt;br /&gt;
            Xtemp.append(np.flip(x[i:(pmax+i)],0))&lt;br /&gt;
        X = np.ones((Y.size, p+1))&lt;br /&gt;
        X[:,1:] = np.array(Xtemp)[:,:p]&lt;br /&gt;
&lt;br /&gt;
        #OLS Estimate&lt;br /&gt;
        Phi = np.dot(np.dot(inv(np.dot(X.T,X)),X.T),Y)&lt;br /&gt;
        SigmaS = np.sum((Y - np.dot(X, Phi))**2.0)/(self.T-pmax)&lt;br /&gt;
        self.par[:-1] = Phi[:]&lt;br /&gt;
        self.par[-1] = SigmaS&lt;br /&gt;
&lt;br /&gt;
        #t-ratios&lt;br /&gt;
        self.VCOV = inv(np.dot(X.T,X))*SigmaS&lt;br /&gt;
        self.SE = np.diag(self.VCOV)**0.5&lt;br /&gt;
        self.t = self.par[:-1]/self.SE&lt;br /&gt;
&lt;br /&gt;
        #likelihood and IC&lt;br /&gt;
        self.logL = (-(self.T-pmax)/2.0)*np.log(2.0*np.pi) + (-(self.T-pmax)/2.0)*np.log(SigmaS) + (-(self.T-pmax)/2.0)&lt;br /&gt;
        self.AIC = 2.0*((self.par.size)-self.logL)&lt;br /&gt;
        self.BIC = np.log(Y.size)*self.par.size-2.0*self.logL&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Simulation.py ===&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import numpy as np&lt;br /&gt;
import models as mod&lt;br /&gt;
import matplotlib.pyplot as plt&lt;br /&gt;
from scipy.stats import norm&lt;br /&gt;
##########################&lt;br /&gt;
#Simulation and settings&lt;br /&gt;
#########################&lt;br /&gt;
#general&lt;br /&gt;
pmax = 10 # Maximum number of lags&lt;br /&gt;
n = 5000 # Number of simulations&lt;br /&gt;
T1 = 200 # Length of the first time series&lt;br /&gt;
T2 = 2000 # Length of the second time series&lt;br /&gt;
&lt;br /&gt;
#1. AR(1) process&lt;br /&gt;
#phi = 0.9&lt;br /&gt;
#mu = 5.0&lt;br /&gt;
#sigmaSq = 1.0&lt;br /&gt;
#X1 = mod.trajectories1(mu, phi, sigmaSq, T1, n)&lt;br /&gt;
#X2 = mod.trajectories1(mu, phi, sigmaSq, T2, n)&lt;br /&gt;
&lt;br /&gt;
#2. AR(2) process&lt;br /&gt;
phi1 = 0.4&lt;br /&gt;
phi2 = 0.4&lt;br /&gt;
mu = 5.0&lt;br /&gt;
sigmaSq = 1.0&lt;br /&gt;
X1 = mod.trajectories2(mu, phi1, phi2, sigmaSq, T1, n) # Rows = individual series; columns = time periods&lt;br /&gt;
X2 = mod.trajectories2(mu, phi1, phi2, sigmaSq, T2, n)&lt;br /&gt;
&lt;br /&gt;
#####&lt;br /&gt;
#GETS General to specific method&lt;br /&gt;
#####&lt;br /&gt;
tquantile = norm.ppf(0.95) #95% quantile&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop1 = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    p = pmax&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:],p,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;lt; tquantile and p&amp;gt;0:&lt;br /&gt;
            p-=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop1.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T1 finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop2 = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    p = pmax&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:],p,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;lt; tquantile and p&amp;gt;0:&lt;br /&gt;
            p-=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop2.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T2 finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
####################&lt;br /&gt;
#Specific-to-General&lt;br /&gt;
####################&lt;br /&gt;
tquantile = norm.ppf(0.95) #95% quantile&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop1SOG = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    p = 0&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:],p+1,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;gt; tquantile and p&amp;lt;=pmax:&lt;br /&gt;
            p+=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop1SOG.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T1 finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop2SOG = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    p = 0&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:],p+1,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;gt; tquantile and p&amp;lt;=pmax:&lt;br /&gt;
            p+=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop2SOG.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T2 finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
####################&lt;br /&gt;
#AIC and BIC&lt;br /&gt;
####################&lt;br /&gt;
#T1 simulation&lt;br /&gt;
AICp1 = []&lt;br /&gt;
BICp1 = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    AICtemp = np.zeros(11)&lt;br /&gt;
    BICtemp = np.zeros(11)&lt;br /&gt;
    for p in np.arange(pmax+1):&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:], p, pmax)&lt;br /&gt;
        AICtemp[p] = ARtemp.AIC&lt;br /&gt;
        BICtemp[p] = ARtemp.BIC&lt;br /&gt;
    AICp1.append(np.argmin(AICtemp))&lt;br /&gt;
    BICp1.append(np.argmin(BICtemp))&lt;br /&gt;
&lt;br /&gt;
print &amp;quot;T1 AIC+BIC finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
AICp2 = []&lt;br /&gt;
BICp2 = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    AICtemp = np.zeros(11)&lt;br /&gt;
    BICtemp = np.zeros(11)&lt;br /&gt;
    for p in np.arange(pmax+1):&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:], p, pmax)&lt;br /&gt;
        AICtemp[p] = ARtemp.AIC&lt;br /&gt;
        BICtemp[p] = ARtemp.BIC&lt;br /&gt;
    AICp2.append(np.argmin(AICtemp))&lt;br /&gt;
    BICp2.append(np.argmin(BICtemp))&lt;br /&gt;
print &amp;quot;T2 AIC+BIC finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
####################&lt;br /&gt;
#Plot&lt;br /&gt;
####################&lt;br /&gt;
&lt;br /&gt;
fig, axes = plt.subplots(nrows=4, ncols=2)&lt;br /&gt;
ax0, ax1, ax2, ax3, ax4, ax5, ax6, ax7 = axes.flatten()&lt;br /&gt;
&lt;br /&gt;
ax0.hist(tratiop1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax0.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax0.set_title('GETS, T=200')&lt;br /&gt;
&lt;br /&gt;
ax1.hist(tratiop2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax1.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax1.set_title('GETS, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax2.hist(tratiop1SOG, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax2.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax2.set_title('Spec-to-Gen, T=200')&lt;br /&gt;
&lt;br /&gt;
ax3.hist(tratiop2SOG, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax3.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax3.set_title('Spec-to-Gen, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax4.hist(AICp1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax4.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax4.set_title('AIC, T=200')&lt;br /&gt;
&lt;br /&gt;
ax5.hist(AICp2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax5.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax5.set_title('AIC, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax6.hist(BICp1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax6.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax6.set_title('BIC, T=200')&lt;br /&gt;
&lt;br /&gt;
ax7.hist(BICp2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax7.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax7.set_title('BIC, T=2000')&lt;br /&gt;
&lt;br /&gt;
fig.subplots_adjust(hspace=0.5)&lt;br /&gt;
plt.show()&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;/div&gt;</summary>
		<author><name>Hazn00</name></author>
		
	</entry>
	<entry>
		<id>http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19186</id>
		<title>Time Series Model Building Process</title>
		<link rel="alternate" type="text/html" href="http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19186"/>
		<updated>2020-01-20T18:14:06Z</updated>

		<summary type="html">&lt;p&gt;Hazn00: /* {\phi}_1 = 0.0  and {\phi}_2 = 0.9 */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Linear time series models, e.g., ARIMA models for univariate time series, is a popular tool for modeling dynamics of time series and predicting the time series. The methodology is not popular only in statistics, econometrics and science, but also in machine learning business applications. The key question is how to build the model. We have to choose the form of the model, in particular number of lags for so-called autoregressive part (usually denoted as p) and moving average part of the model (usually denoted as d). The common guides usually provide a ‘cook book’ for model selection, see for example [https://www.machinelearningplus.com/time-series/arima-model-time-series-forecasting-python/, ARIMA Model – Complete Guide to Time Series Forecasting in Python] . This goal of this simulation is to compare four basic methods for selection of lags (p) for the autoregressive part.&lt;br /&gt;
&lt;br /&gt;
== Problem Definition ==&lt;br /&gt;
&lt;br /&gt;
The autoregressive process has form&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\phi}_2x_{t-2}+...+{\phi}_px_{t-p} + {\epsilon}_t&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;{\epsilon}_t \sim N(0,{\sigma}^2) &amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
However, we observe only the realized value and we do not know the hyperparameter p. Therefore, we must estimate it. The considered methods are following.&lt;br /&gt;
&lt;br /&gt;
=== GETS (General-to-Specific) ===&lt;br /&gt;
&lt;br /&gt;
We first start with high enough p (pmax in the code), and perform statistical test whether the last lag has statistically significant impact, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p = 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p \neq 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the impact is insignificant, we reduce p by one and continue until the parameter for the last lag is significant, i.e. last lag has significant effect.&lt;br /&gt;
&lt;br /&gt;
=== Specific-to-General ===&lt;br /&gt;
&lt;br /&gt;
The second approach works similarly as GETS, the only difference is that we first start with model without any lag, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and we are adding lags until they are significant.&lt;br /&gt;
&lt;br /&gt;
=== BIC (Bayesian Information Criteria) ===&lt;br /&gt;
&lt;br /&gt;
Bayesian information criteria is based on a likelihood of the model and number of parameters. The criteria punish the model for high number of parameters for a potential over-fitting, and rewards the model for good fit of the data. The lower the BIC value is, the better the model (a little bit counterintuitive definition). We are supposed to select a model with the lowest value of BIC.&lt;br /&gt;
&lt;br /&gt;
=== AIC (Akaike Information Criteria)  ===&lt;br /&gt;
&lt;br /&gt;
Works exactly the same as BIC, but the formula is slightly different.&lt;br /&gt;
&lt;br /&gt;
== Method and Simulation Method ==&lt;br /&gt;
&lt;br /&gt;
The solution consists of three key elements, data generating process, AR(p) model, and simulation.&lt;br /&gt;
&lt;br /&gt;
=== Data Generating Process ===&lt;br /&gt;
&lt;br /&gt;
To answer the question, which model selection method is the best, we are generating an artificial data. We assume that data are created by AR(1) process&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
or AR(2)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\mu} + {\phi}_2x_{t-2} + {\epsilon}_{t}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
with random error &amp;lt;math&amp;gt;&amp;lt;/math&amp;gt; . Therefore, we must generate random numbers for random errors, and iterate over the equations described above. The initial values of the processes, e.g., &amp;lt;math&amp;gt;x_0&amp;lt;/math&amp;gt;, are set to the theoretical mean value of the process.&lt;br /&gt;
&lt;br /&gt;
=== AR(p) model ===&lt;br /&gt;
&lt;br /&gt;
For a given series &amp;lt;math&amp;gt;{x_1,x_2,...x_T}&amp;lt;/math&amp;gt; with a length ''T'' estimates a model for a given p.&lt;br /&gt;
&lt;br /&gt;
=== Simulation ===&lt;br /&gt;
&lt;br /&gt;
Perform n Monte Carlo simulations, where in each simulation the data generating process is used to create a time series. Then the AR(p) model is estimated for ''p=0,1,…,pmax'', and the best models are selected according to the selection criteria described above. Therefore, we will obtain four estimates of p that corresponds to the described methods for each of the n simulation. The final step is to compute % success of correctly estimated p for each of four methods.&lt;br /&gt;
&lt;br /&gt;
== Controls ==&lt;br /&gt;
The solution allow to set number of simulation n. We need high enough n to make sure that the results will converge close enough to actual results. Therefore, we have set &amp;lt;math&amp;gt;n=5000&amp;lt;/math&amp;gt;. Higher n will not significantly increase the precision of the results.&lt;br /&gt;
&lt;br /&gt;
The more important controls is selection of AR(1) or AR(2) process, and selection of parameters &amp;lt;math&amp;gt;{\mu},{\sigma},{\phi}_1&amp;lt;/math&amp;gt;  and  &amp;lt;math&amp;gt;{\phi}_2&amp;lt;/math&amp;gt; for the process. Additionally, we can set length of the generated series and even compare performance for series with two distinct lengths &amp;lt;math&amp;gt;T_1&amp;lt;/math&amp;gt; and &amp;lt;math&amp;gt;T_2&amp;lt;/math&amp;gt;. In other words, one method may perform better for low number of observations than other, and this control allow to compare the performance.&lt;br /&gt;
&lt;br /&gt;
== Results ==&lt;br /&gt;
&amp;lt;gallery&amp;gt;&lt;br /&gt;
File:Phi01.png|&amp;lt;math&amp;gt;{\Phi} = 0.1&amp;lt;/math&amp;gt;&lt;br /&gt;
File:Phi09.png|&amp;lt;math&amp;gt;{\Phi} = 0.9&amp;lt;/math&amp;gt;&lt;br /&gt;
File:Phi04Phi04.png|&amp;lt;math&amp;gt;{\Phi}_1= 0.4, {\Phi}_2 = 0.4&amp;lt;/math&amp;gt;&lt;br /&gt;
File:Phi00Phi09.png|&amp;lt;math&amp;gt;{\Phi}_1= 0.0, {\Phi}_2 = 0.9&amp;lt;/math&amp;gt;&lt;br /&gt;
&amp;lt;/gallery&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
===&amp;lt;math&amp;gt;{\phi} = 0.1&amp;lt;/math&amp;gt;===&lt;br /&gt;
Previous periods don't have big impact. &lt;br /&gt;
AIC method works well with smaller  samples. In case of bigger samples, BIC method works better than AIC.&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;math&amp;gt;{\phi} = 0.9&amp;lt;/math&amp;gt;===&lt;br /&gt;
BIC is the best method for small and big samples. Even though the GETS method doesn't work quite well, it is commonly used. The bigger tha max value of p is used, the bigger is the probability of getting the wrong guess from the simulation.&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;math&amp;gt;{\phi}_1 = 0.0&amp;lt;/math&amp;gt;  and &amp;lt;math&amp;gt;{\phi}_2 = 0.9&amp;lt;/math&amp;gt;===&lt;br /&gt;
BIC is the best method for small and big samples again. &lt;br /&gt;
As we can see, Spec-to-gen method gives us very wrong in approximately 1/4 cases, because the null value gives no sense in this case.&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;math&amp;gt;{\phi}_1 = 0.4&amp;lt;/math&amp;gt; and &amp;lt;math&amp;gt;{\phi}_2 = 0.4&amp;lt;/math&amp;gt;===&lt;br /&gt;
This process is set to not be influenced by previous periods.&lt;br /&gt;
The BIC method works the best again.&lt;br /&gt;
&lt;br /&gt;
== Code ==&lt;br /&gt;
=== Models.py ===&lt;br /&gt;
The part of the code ''''class ARp(object)'''' was created with great help from another student and it is not originally created for this course.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import numpy as np from numpy.linalg &lt;br /&gt;
import inv from scipy.stats &lt;br /&gt;
import norm&lt;br /&gt;
&lt;br /&gt;
def sim1(mu, phi1, sigmaSq, T):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates single trajectory.&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    x = np.zeros(T+1)&lt;br /&gt;
    epsilon = np.random.normal(0,sigmaSq, T+1)&lt;br /&gt;
&lt;br /&gt;
    x[0] = mu / (1.0 - phi1)&lt;br /&gt;
&lt;br /&gt;
    for t in np.arange(T):&lt;br /&gt;
        x[t+1] = mu + phi1 * x[t] + epsilon[t]&lt;br /&gt;
&lt;br /&gt;
    return x[1:]&lt;br /&gt;
&lt;br /&gt;
def trajectories1(mu, phi1, sigmaSq, T, n):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates n-trajectories of AR(1) process&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :param n:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    X = np.zeros([n,T])&lt;br /&gt;
    for s in np.arange(n):&lt;br /&gt;
        X[s,:] = sim1(mu, phi1, sigmaSq, T)&lt;br /&gt;
    return X&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
def sim2(mu, phi1, phi2, sigmaSq, T):&lt;br /&gt;
    x = np.zeros(T+2)&lt;br /&gt;
    epsilon = np.random.normal(0,sigmaSq, T+2)&lt;br /&gt;
&lt;br /&gt;
    x[0] = mu / (1.0 - phi1-phi2)&lt;br /&gt;
    x[1] = mu / (1.0 - phi1-phi2)&lt;br /&gt;
&lt;br /&gt;
    for t in np.arange(T)+1:&lt;br /&gt;
        x[t+1] = mu + phi1 * x[t] + phi2 * x[t-1] + epsilon[t]&lt;br /&gt;
&lt;br /&gt;
    return x[2:]&lt;br /&gt;
&lt;br /&gt;
def trajectories2(mu, phi1, phi2, sigmaSq, T, n):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates n-trajectories of AR(2) process&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param phi2:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :param n:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    X = np.zeros([n,T])&lt;br /&gt;
    for s in np.arange(n):&lt;br /&gt;
        X[s,:] = sim2(mu, phi1, phi2, sigmaSq, T)&lt;br /&gt;
    return X&lt;br /&gt;
&lt;br /&gt;
class ARp(object):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;AR(p) class allowing to estimate the model &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
    def __init__(self, x, p, pmax):&lt;br /&gt;
        self.p = p&lt;br /&gt;
        self.x = x&lt;br /&gt;
        self.T = float(x.size)&lt;br /&gt;
        self.par = np.zeros(p+2) #np.array: c, phi_1, phi_2, ... phi_p, sigma^2&lt;br /&gt;
&lt;br /&gt;
        #Init. matrices for OLS&lt;br /&gt;
        Y = self.x[pmax:]&lt;br /&gt;
        Xtemp = []&lt;br /&gt;
&lt;br /&gt;
        for i in np.arange(Y.size):&lt;br /&gt;
            Xtemp.append(np.flip(x[i:(pmax+i)],0))&lt;br /&gt;
        X = np.ones((Y.size, p+1))&lt;br /&gt;
        X[:,1:] = np.array(Xtemp)[:,:p]&lt;br /&gt;
&lt;br /&gt;
        #OLS Estimate&lt;br /&gt;
        Phi = np.dot(np.dot(inv(np.dot(X.T,X)),X.T),Y)&lt;br /&gt;
        SigmaS = np.sum((Y - np.dot(X, Phi))**2.0)/(self.T-pmax)&lt;br /&gt;
        self.par[:-1] = Phi[:]&lt;br /&gt;
        self.par[-1] = SigmaS&lt;br /&gt;
&lt;br /&gt;
        #t-ratios&lt;br /&gt;
        self.VCOV = inv(np.dot(X.T,X))*SigmaS&lt;br /&gt;
        self.SE = np.diag(self.VCOV)**0.5&lt;br /&gt;
        self.t = self.par[:-1]/self.SE&lt;br /&gt;
&lt;br /&gt;
        #likelihood and IC&lt;br /&gt;
        self.logL = (-(self.T-pmax)/2.0)*np.log(2.0*np.pi) + (-(self.T-pmax)/2.0)*np.log(SigmaS) + (-(self.T-pmax)/2.0)&lt;br /&gt;
        self.AIC = 2.0*((self.par.size)-self.logL)&lt;br /&gt;
        self.BIC = np.log(Y.size)*self.par.size-2.0*self.logL&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Simulation.py ===&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import numpy as np&lt;br /&gt;
import models as mod&lt;br /&gt;
import matplotlib.pyplot as plt&lt;br /&gt;
from scipy.stats import norm&lt;br /&gt;
##########################&lt;br /&gt;
#Simulation and settings&lt;br /&gt;
#########################&lt;br /&gt;
#general&lt;br /&gt;
pmax = 10 # Maximum number of lags&lt;br /&gt;
n = 5000 # Number of simulations&lt;br /&gt;
T1 = 200 # Length of the first time series&lt;br /&gt;
T2 = 2000 # Length of the second time series&lt;br /&gt;
&lt;br /&gt;
#1. AR(1) process&lt;br /&gt;
#phi = 0.9&lt;br /&gt;
#mu = 5.0&lt;br /&gt;
#sigmaSq = 1.0&lt;br /&gt;
#X1 = mod.trajectories1(mu, phi, sigmaSq, T1, n)&lt;br /&gt;
#X2 = mod.trajectories1(mu, phi, sigmaSq, T2, n)&lt;br /&gt;
&lt;br /&gt;
#2. AR(2) process&lt;br /&gt;
phi1 = 0.4&lt;br /&gt;
phi2 = 0.4&lt;br /&gt;
mu = 5.0&lt;br /&gt;
sigmaSq = 1.0&lt;br /&gt;
X1 = mod.trajectories2(mu, phi1, phi2, sigmaSq, T1, n) # Rows = individual series; columns = time periods&lt;br /&gt;
X2 = mod.trajectories2(mu, phi1, phi2, sigmaSq, T2, n)&lt;br /&gt;
&lt;br /&gt;
#####&lt;br /&gt;
#GETS General to specific method&lt;br /&gt;
#####&lt;br /&gt;
tquantile = norm.ppf(0.95) #95% quantile&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop1 = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    p = pmax&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:],p,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;lt; tquantile and p&amp;gt;0:&lt;br /&gt;
            p-=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop1.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T1 finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop2 = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    p = pmax&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:],p,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;lt; tquantile and p&amp;gt;0:&lt;br /&gt;
            p-=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop2.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T2 finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
####################&lt;br /&gt;
#Specific-to-General&lt;br /&gt;
####################&lt;br /&gt;
tquantile = norm.ppf(0.95) #95% quantile&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop1SOG = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    p = 0&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:],p+1,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;gt; tquantile and p&amp;lt;=pmax:&lt;br /&gt;
            p+=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop1SOG.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T1 finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop2SOG = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    p = 0&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:],p+1,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;gt; tquantile and p&amp;lt;=pmax:&lt;br /&gt;
            p+=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop2SOG.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T2 finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
####################&lt;br /&gt;
#AIC and BIC&lt;br /&gt;
####################&lt;br /&gt;
#T1 simulation&lt;br /&gt;
AICp1 = []&lt;br /&gt;
BICp1 = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    AICtemp = np.zeros(11)&lt;br /&gt;
    BICtemp = np.zeros(11)&lt;br /&gt;
    for p in np.arange(pmax+1):&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:], p, pmax)&lt;br /&gt;
        AICtemp[p] = ARtemp.AIC&lt;br /&gt;
        BICtemp[p] = ARtemp.BIC&lt;br /&gt;
    AICp1.append(np.argmin(AICtemp))&lt;br /&gt;
    BICp1.append(np.argmin(BICtemp))&lt;br /&gt;
&lt;br /&gt;
print &amp;quot;T1 AIC+BIC finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
AICp2 = []&lt;br /&gt;
BICp2 = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    AICtemp = np.zeros(11)&lt;br /&gt;
    BICtemp = np.zeros(11)&lt;br /&gt;
    for p in np.arange(pmax+1):&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:], p, pmax)&lt;br /&gt;
        AICtemp[p] = ARtemp.AIC&lt;br /&gt;
        BICtemp[p] = ARtemp.BIC&lt;br /&gt;
    AICp2.append(np.argmin(AICtemp))&lt;br /&gt;
    BICp2.append(np.argmin(BICtemp))&lt;br /&gt;
print &amp;quot;T2 AIC+BIC finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
####################&lt;br /&gt;
#Plot&lt;br /&gt;
####################&lt;br /&gt;
&lt;br /&gt;
fig, axes = plt.subplots(nrows=4, ncols=2)&lt;br /&gt;
ax0, ax1, ax2, ax3, ax4, ax5, ax6, ax7 = axes.flatten()&lt;br /&gt;
&lt;br /&gt;
ax0.hist(tratiop1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax0.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax0.set_title('GETS, T=200')&lt;br /&gt;
&lt;br /&gt;
ax1.hist(tratiop2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax1.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax1.set_title('GETS, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax2.hist(tratiop1SOG, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax2.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax2.set_title('Spec-to-Gen, T=200')&lt;br /&gt;
&lt;br /&gt;
ax3.hist(tratiop2SOG, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax3.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax3.set_title('Spec-to-Gen, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax4.hist(AICp1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax4.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax4.set_title('AIC, T=200')&lt;br /&gt;
&lt;br /&gt;
ax5.hist(AICp2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax5.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax5.set_title('AIC, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax6.hist(BICp1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax6.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax6.set_title('BIC, T=200')&lt;br /&gt;
&lt;br /&gt;
ax7.hist(BICp2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax7.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax7.set_title('BIC, T=2000')&lt;br /&gt;
&lt;br /&gt;
fig.subplots_adjust(hspace=0.5)&lt;br /&gt;
plt.show()&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;/div&gt;</summary>
		<author><name>Hazn00</name></author>
		
	</entry>
	<entry>
		<id>http://www.simulace.info/index.php?title=WS_2019/2020&amp;diff=19185</id>
		<title>WS 2019/2020</title>
		<link rel="alternate" type="text/html" href="http://www.simulace.info/index.php?title=WS_2019/2020&amp;diff=19185"/>
		<updated>2020-01-20T18:08:07Z</updated>

		<summary type="html">&lt;p&gt;Hazn00: /* Simulation */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Semestral papers from winter term 2019/2020. Please, put here links to the pages with your paper. First you need to have your [[Assignments WS 2019/2020|assignment approved]]&lt;br /&gt;
&lt;br /&gt;
== Simulation ==&lt;br /&gt;
[http://www.simulace.info/index.php/Cotton_Processing_Quality:_Cotton,_Seed,_Lint,_Trash Cotton Processing Quality: Cotton, Seed, Lint, Trash] , Ibrahim Aghazada (in progress)&lt;br /&gt;
&lt;br /&gt;
[http://www.simulace.info/index.php/Time_Series_Model_Building_Process Time Series Model Building Process] , Nikola Hažmuková&lt;br /&gt;
&lt;br /&gt;
[http://www.simulace.info/index.php/Indian_Elephant_Population_in_Thailand Indian Elephant Population in Thailand] , [[User:Xkavj12|Xkavj12]] ([[User talk:Xkavj12|talk]]) 18:42, 20 January 2020 (CET) (in progress)&lt;br /&gt;
&lt;br /&gt;
== Textbook Chapters ==&lt;br /&gt;
[http://www.simulace.info/index.php/Limits_to_Growth Limits to Growth] , Ibrahim Aghazada (in progress)&lt;/div&gt;</summary>
		<author><name>Hazn00</name></author>
		
	</entry>
	<entry>
		<id>http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19156</id>
		<title>Time Series Model Building Process</title>
		<link rel="alternate" type="text/html" href="http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19156"/>
		<updated>2020-01-19T14:38:39Z</updated>

		<summary type="html">&lt;p&gt;Hazn00: /* Conclusion */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Linear time series models, e.g., ARIMA models for univariate time series, is a popular tool for modeling dynamics of time series and predicting the time series. The methodology is not popular only in statistics, econometrics and science, but also in machine learning business applications. The key question is how to build the model. We have to choose the form of the model, in particular number of lags for so-called autoregressive part (usually denoted as p) and moving average part of the model (usually denoted as d). The common guides usually provide a ‘cook book’ for model selection, see for example [https://www.machinelearningplus.com/time-series/arima-model-time-series-forecasting-python/, ARIMA Model – Complete Guide to Time Series Forecasting in Python] . This goal of this simulation is to compare four basic methods for selection of lags (p) for the autoregressive part.&lt;br /&gt;
&lt;br /&gt;
== Problem Definition ==&lt;br /&gt;
&lt;br /&gt;
The autoregressive process has form&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\phi}_2x_{t-2}+...+{\phi}_px_{t-p} + {\epsilon}_t&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;{\epsilon}_t \sim N(0,{\sigma}^2) &amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
However, we observe only the realized value and we do not know the hyperparameter p. Therefore, we must estimate it. The considered methods are following.&lt;br /&gt;
&lt;br /&gt;
=== GETS (General-to-Specific) ===&lt;br /&gt;
&lt;br /&gt;
We first start with high enough p (pmax in the code), and perform statistical test whether the last lag has statistically significant impact, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p = 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p \neq 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the impact is insignificant, we reduce p by one and continue until the parameter for the last lag is significant, i.e. last lag has significant effect.&lt;br /&gt;
&lt;br /&gt;
=== Specific-to-General ===&lt;br /&gt;
&lt;br /&gt;
The second approach works similarly as GETS, the only difference is that we first start with model without any lag, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and we are adding lags until they are significant.&lt;br /&gt;
&lt;br /&gt;
=== BIC (Bayesian Information Criteria) ===&lt;br /&gt;
&lt;br /&gt;
Bayesian information criteria is based on a likelihood of the model and number of parameters. The criteria punish the model for high number of parameters for a potential over-fitting, and rewards the model for good fit of the data. The lower the BIC value is, the better the model (a little bit counterintuitive definition). We are supposed to select a model with the lowest value of BIC.&lt;br /&gt;
&lt;br /&gt;
=== AIC (Akaike Information Criteria)  ===&lt;br /&gt;
&lt;br /&gt;
Works exactly the same as BIC, but the formula is slightly different.&lt;br /&gt;
&lt;br /&gt;
== Method and Simulation Method ==&lt;br /&gt;
&lt;br /&gt;
The solution consists of three key elements, data generating process, AR(p) model, and simulation.&lt;br /&gt;
&lt;br /&gt;
=== Data Generating Process ===&lt;br /&gt;
&lt;br /&gt;
To answer the question, which model selection method is the best, we are generating an artificial data. We assume that data are created by AR(1) process&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
or AR(2)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\mu} + {\phi}_2x_{t-2} + {\epsilon}_{t}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
with random error &amp;lt;math&amp;gt;&amp;lt;/math&amp;gt; . Therefore, we must generate random numbers for random errors, and iterate over the equations described above. The initial values of the processes, e.g., &amp;lt;math&amp;gt;x_0&amp;lt;/math&amp;gt;, are set to the theoretical mean value of the process.&lt;br /&gt;
&lt;br /&gt;
=== AR(p) model ===&lt;br /&gt;
&lt;br /&gt;
For a given series &amp;lt;math&amp;gt;{x_1,x_2,...x_T}&amp;lt;/math&amp;gt; with a length ''T'' estimates a model for a given p.&lt;br /&gt;
&lt;br /&gt;
=== Simulation ===&lt;br /&gt;
&lt;br /&gt;
Perform n Monte Carlo simulations, where in each simulation the data generating process is used to create a time series. Then the AR(p) model is estimated for ''p=0,1,…,pmax'', and the best models are selected according to the selection criteria described above. Therefore, we will obtain four estimates of p that corresponds to the described methods for each of the n simulation. The final step is to compute % success of correctly estimated p for each of four methods.&lt;br /&gt;
&lt;br /&gt;
== Controls ==&lt;br /&gt;
The solution allow to set number of simulation n. We need high enough n to make sure that the results will converge close enough to actual results. Therefore, we have set &amp;lt;math&amp;gt;n=5000&amp;lt;/math&amp;gt;. Higher n will not significantly increase the precision of the results.&lt;br /&gt;
&lt;br /&gt;
The more important controls is selection of AR(1) or AR(2) process, and selection of parameters &amp;lt;math&amp;gt;{\mu},{\sigma},{\phi}_1&amp;lt;/math&amp;gt;  and  &amp;lt;math&amp;gt;{\phi}_2&amp;lt;/math&amp;gt; for the process. Additionally, we can set length of the generated series and even compare performance for series with two distinct lengths &amp;lt;math&amp;gt;T_1&amp;lt;/math&amp;gt; and &amp;lt;math&amp;gt;T_2&amp;lt;/math&amp;gt;. In other words, one method may perform better for low number of observations than other, and this control allow to compare the performance.&lt;br /&gt;
&lt;br /&gt;
== Results ==&lt;br /&gt;
&amp;lt;gallery&amp;gt;&lt;br /&gt;
File:Phi01.png|&amp;lt;math&amp;gt;{\Phi} = 0.1&amp;lt;/math&amp;gt;&lt;br /&gt;
File:Phi09.png|&amp;lt;math&amp;gt;{\Phi} = 0.9&amp;lt;/math&amp;gt;&lt;br /&gt;
File:Phi04Phi04.png|&amp;lt;math&amp;gt;{\Phi}_1= 0.4, {\Phi}_2 = 0.4&amp;lt;/math&amp;gt;&lt;br /&gt;
File:Phi00Phi09.png|&amp;lt;math&amp;gt;{\Phi}_1= 0.0, {\Phi}_2 = 0.9&amp;lt;/math&amp;gt;&lt;br /&gt;
&amp;lt;/gallery&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
===&amp;lt;math&amp;gt;{\phi} = 0.1&amp;lt;/math&amp;gt;===&lt;br /&gt;
Previous periods don't have big impact. &lt;br /&gt;
AIC method works well with smaller  samples. In case of bigger samples, BIC method works better than AIC.&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;math&amp;gt;{\phi} = 0.9&amp;lt;/math&amp;gt;===&lt;br /&gt;
BIC is the best method for small and big samples. Even though the GETS method doesn't work quite well, it is commonly used. The bigger tha max value of p is used, the bigger is the probability of getting the wrong guess from the simulation.&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;math&amp;gt;{\phi}_1 = 0.0&amp;lt;/math&amp;gt;  and &amp;lt;math&amp;gt;{\phi}_2 = 0.9&amp;lt;/math&amp;gt;===&lt;br /&gt;
BIC is the best method for small and big samples again. &lt;br /&gt;
We never want to use the Spec-to-gen method, because&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;math&amp;gt;{\phi}_1 = 0.4&amp;lt;/math&amp;gt; and &amp;lt;math&amp;gt;{\phi}_2 = 0.4&amp;lt;/math&amp;gt;===&lt;br /&gt;
This process is set to not be influenced by previous periods.&lt;br /&gt;
The BIC method works the best again.&lt;br /&gt;
&lt;br /&gt;
== Code ==&lt;br /&gt;
=== Models.py ===&lt;br /&gt;
The part of the code ''''class ARp(object)'''' was created with great help from another student and it is not originally created for this course.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import numpy as np from numpy.linalg &lt;br /&gt;
import inv from scipy.stats &lt;br /&gt;
import norm&lt;br /&gt;
&lt;br /&gt;
def sim1(mu, phi1, sigmaSq, T):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates single trajectory.&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    x = np.zeros(T+1)&lt;br /&gt;
    epsilon = np.random.normal(0,sigmaSq, T+1)&lt;br /&gt;
&lt;br /&gt;
    x[0] = mu / (1.0 - phi1)&lt;br /&gt;
&lt;br /&gt;
    for t in np.arange(T):&lt;br /&gt;
        x[t+1] = mu + phi1 * x[t] + epsilon[t]&lt;br /&gt;
&lt;br /&gt;
    return x[1:]&lt;br /&gt;
&lt;br /&gt;
def trajectories1(mu, phi1, sigmaSq, T, n):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates n-trajectories of AR(1) process&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :param n:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    X = np.zeros([n,T])&lt;br /&gt;
    for s in np.arange(n):&lt;br /&gt;
        X[s,:] = sim1(mu, phi1, sigmaSq, T)&lt;br /&gt;
    return X&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
def sim2(mu, phi1, phi2, sigmaSq, T):&lt;br /&gt;
    x = np.zeros(T+2)&lt;br /&gt;
    epsilon = np.random.normal(0,sigmaSq, T+2)&lt;br /&gt;
&lt;br /&gt;
    x[0] = mu / (1.0 - phi1-phi2)&lt;br /&gt;
    x[1] = mu / (1.0 - phi1-phi2)&lt;br /&gt;
&lt;br /&gt;
    for t in np.arange(T)+1:&lt;br /&gt;
        x[t+1] = mu + phi1 * x[t] + phi2 * x[t-1] + epsilon[t]&lt;br /&gt;
&lt;br /&gt;
    return x[2:]&lt;br /&gt;
&lt;br /&gt;
def trajectories2(mu, phi1, phi2, sigmaSq, T, n):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates n-trajectories of AR(2) process&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param phi2:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :param n:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    X = np.zeros([n,T])&lt;br /&gt;
    for s in np.arange(n):&lt;br /&gt;
        X[s,:] = sim2(mu, phi1, phi2, sigmaSq, T)&lt;br /&gt;
    return X&lt;br /&gt;
&lt;br /&gt;
class ARp(object):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;AR(p) class allowing to estimate the model &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
    def __init__(self, x, p, pmax):&lt;br /&gt;
        self.p = p&lt;br /&gt;
        self.x = x&lt;br /&gt;
        self.T = float(x.size)&lt;br /&gt;
        self.par = np.zeros(p+2) #np.array: c, phi_1, phi_2, ... phi_p, sigma^2&lt;br /&gt;
&lt;br /&gt;
        #Init. matrices for OLS&lt;br /&gt;
        Y = self.x[pmax:]&lt;br /&gt;
        Xtemp = []&lt;br /&gt;
&lt;br /&gt;
        for i in np.arange(Y.size):&lt;br /&gt;
            Xtemp.append(np.flip(x[i:(pmax+i)],0))&lt;br /&gt;
        X = np.ones((Y.size, p+1))&lt;br /&gt;
        X[:,1:] = np.array(Xtemp)[:,:p]&lt;br /&gt;
&lt;br /&gt;
        #OLS Estimate&lt;br /&gt;
        Phi = np.dot(np.dot(inv(np.dot(X.T,X)),X.T),Y)&lt;br /&gt;
        SigmaS = np.sum((Y - np.dot(X, Phi))**2.0)/(self.T-pmax)&lt;br /&gt;
        self.par[:-1] = Phi[:]&lt;br /&gt;
        self.par[-1] = SigmaS&lt;br /&gt;
&lt;br /&gt;
        #t-ratios&lt;br /&gt;
        self.VCOV = inv(np.dot(X.T,X))*SigmaS&lt;br /&gt;
        self.SE = np.diag(self.VCOV)**0.5&lt;br /&gt;
        self.t = self.par[:-1]/self.SE&lt;br /&gt;
&lt;br /&gt;
        #likelihood and IC&lt;br /&gt;
        self.logL = (-(self.T-pmax)/2.0)*np.log(2.0*np.pi) + (-(self.T-pmax)/2.0)*np.log(SigmaS) + (-(self.T-pmax)/2.0)&lt;br /&gt;
        self.AIC = 2.0*((self.par.size)-self.logL)&lt;br /&gt;
        self.BIC = np.log(Y.size)*self.par.size-2.0*self.logL&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Simulation.py ===&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import numpy as np&lt;br /&gt;
import models as mod&lt;br /&gt;
import matplotlib.pyplot as plt&lt;br /&gt;
from scipy.stats import norm&lt;br /&gt;
##########################&lt;br /&gt;
#Simulation and settings&lt;br /&gt;
#########################&lt;br /&gt;
#general&lt;br /&gt;
pmax = 10 # Maximum number of lags&lt;br /&gt;
n = 5000 # Number of simulations&lt;br /&gt;
T1 = 200 # Length of the first time series&lt;br /&gt;
T2 = 2000 # Length of the second time series&lt;br /&gt;
&lt;br /&gt;
#1. AR(1) process&lt;br /&gt;
#phi = 0.9&lt;br /&gt;
#mu = 5.0&lt;br /&gt;
#sigmaSq = 1.0&lt;br /&gt;
#X1 = mod.trajectories1(mu, phi, sigmaSq, T1, n)&lt;br /&gt;
#X2 = mod.trajectories1(mu, phi, sigmaSq, T2, n)&lt;br /&gt;
&lt;br /&gt;
#2. AR(2) process&lt;br /&gt;
phi1 = 0.4&lt;br /&gt;
phi2 = 0.4&lt;br /&gt;
mu = 5.0&lt;br /&gt;
sigmaSq = 1.0&lt;br /&gt;
X1 = mod.trajectories2(mu, phi1, phi2, sigmaSq, T1, n) # Rows = individual series; columns = time periods&lt;br /&gt;
X2 = mod.trajectories2(mu, phi1, phi2, sigmaSq, T2, n)&lt;br /&gt;
&lt;br /&gt;
#####&lt;br /&gt;
#GETS General to specific method&lt;br /&gt;
#####&lt;br /&gt;
tquantile = norm.ppf(0.95) #95% quantile&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop1 = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    p = pmax&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:],p,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;lt; tquantile and p&amp;gt;0:&lt;br /&gt;
            p-=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop1.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T1 finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop2 = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    p = pmax&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:],p,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;lt; tquantile and p&amp;gt;0:&lt;br /&gt;
            p-=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop2.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T2 finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
####################&lt;br /&gt;
#Specific-to-General&lt;br /&gt;
####################&lt;br /&gt;
tquantile = norm.ppf(0.95) #95% quantile&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop1SOG = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    p = 0&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:],p+1,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;gt; tquantile and p&amp;lt;=pmax:&lt;br /&gt;
            p+=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop1SOG.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T1 finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop2SOG = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    p = 0&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:],p+1,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;gt; tquantile and p&amp;lt;=pmax:&lt;br /&gt;
            p+=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop2SOG.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T2 finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
####################&lt;br /&gt;
#AIC and BIC&lt;br /&gt;
####################&lt;br /&gt;
#T1 simulation&lt;br /&gt;
AICp1 = []&lt;br /&gt;
BICp1 = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    AICtemp = np.zeros(11)&lt;br /&gt;
    BICtemp = np.zeros(11)&lt;br /&gt;
    for p in np.arange(pmax+1):&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:], p, pmax)&lt;br /&gt;
        AICtemp[p] = ARtemp.AIC&lt;br /&gt;
        BICtemp[p] = ARtemp.BIC&lt;br /&gt;
    AICp1.append(np.argmin(AICtemp))&lt;br /&gt;
    BICp1.append(np.argmin(BICtemp))&lt;br /&gt;
&lt;br /&gt;
print &amp;quot;T1 AIC+BIC finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
AICp2 = []&lt;br /&gt;
BICp2 = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    AICtemp = np.zeros(11)&lt;br /&gt;
    BICtemp = np.zeros(11)&lt;br /&gt;
    for p in np.arange(pmax+1):&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:], p, pmax)&lt;br /&gt;
        AICtemp[p] = ARtemp.AIC&lt;br /&gt;
        BICtemp[p] = ARtemp.BIC&lt;br /&gt;
    AICp2.append(np.argmin(AICtemp))&lt;br /&gt;
    BICp2.append(np.argmin(BICtemp))&lt;br /&gt;
print &amp;quot;T2 AIC+BIC finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
####################&lt;br /&gt;
#Plot&lt;br /&gt;
####################&lt;br /&gt;
&lt;br /&gt;
fig, axes = plt.subplots(nrows=4, ncols=2)&lt;br /&gt;
ax0, ax1, ax2, ax3, ax4, ax5, ax6, ax7 = axes.flatten()&lt;br /&gt;
&lt;br /&gt;
ax0.hist(tratiop1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax0.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax0.set_title('GETS, T=200')&lt;br /&gt;
&lt;br /&gt;
ax1.hist(tratiop2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax1.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax1.set_title('GETS, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax2.hist(tratiop1SOG, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax2.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax2.set_title('Spec-to-Gen, T=200')&lt;br /&gt;
&lt;br /&gt;
ax3.hist(tratiop2SOG, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax3.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax3.set_title('Spec-to-Gen, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax4.hist(AICp1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax4.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax4.set_title('AIC, T=200')&lt;br /&gt;
&lt;br /&gt;
ax5.hist(AICp2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax5.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax5.set_title('AIC, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax6.hist(BICp1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax6.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax6.set_title('BIC, T=200')&lt;br /&gt;
&lt;br /&gt;
ax7.hist(BICp2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax7.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax7.set_title('BIC, T=2000')&lt;br /&gt;
&lt;br /&gt;
fig.subplots_adjust(hspace=0.5)&lt;br /&gt;
plt.show()&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;/div&gt;</summary>
		<author><name>Hazn00</name></author>
		
	</entry>
	<entry>
		<id>http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19155</id>
		<title>Time Series Model Building Process</title>
		<link rel="alternate" type="text/html" href="http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19155"/>
		<updated>2020-01-19T14:38:24Z</updated>

		<summary type="html">&lt;p&gt;Hazn00: /* Conclusion */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Linear time series models, e.g., ARIMA models for univariate time series, is a popular tool for modeling dynamics of time series and predicting the time series. The methodology is not popular only in statistics, econometrics and science, but also in machine learning business applications. The key question is how to build the model. We have to choose the form of the model, in particular number of lags for so-called autoregressive part (usually denoted as p) and moving average part of the model (usually denoted as d). The common guides usually provide a ‘cook book’ for model selection, see for example [https://www.machinelearningplus.com/time-series/arima-model-time-series-forecasting-python/, ARIMA Model – Complete Guide to Time Series Forecasting in Python] . This goal of this simulation is to compare four basic methods for selection of lags (p) for the autoregressive part.&lt;br /&gt;
&lt;br /&gt;
== Problem Definition ==&lt;br /&gt;
&lt;br /&gt;
The autoregressive process has form&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\phi}_2x_{t-2}+...+{\phi}_px_{t-p} + {\epsilon}_t&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;{\epsilon}_t \sim N(0,{\sigma}^2) &amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
However, we observe only the realized value and we do not know the hyperparameter p. Therefore, we must estimate it. The considered methods are following.&lt;br /&gt;
&lt;br /&gt;
=== GETS (General-to-Specific) ===&lt;br /&gt;
&lt;br /&gt;
We first start with high enough p (pmax in the code), and perform statistical test whether the last lag has statistically significant impact, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p = 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p \neq 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the impact is insignificant, we reduce p by one and continue until the parameter for the last lag is significant, i.e. last lag has significant effect.&lt;br /&gt;
&lt;br /&gt;
=== Specific-to-General ===&lt;br /&gt;
&lt;br /&gt;
The second approach works similarly as GETS, the only difference is that we first start with model without any lag, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and we are adding lags until they are significant.&lt;br /&gt;
&lt;br /&gt;
=== BIC (Bayesian Information Criteria) ===&lt;br /&gt;
&lt;br /&gt;
Bayesian information criteria is based on a likelihood of the model and number of parameters. The criteria punish the model for high number of parameters for a potential over-fitting, and rewards the model for good fit of the data. The lower the BIC value is, the better the model (a little bit counterintuitive definition). We are supposed to select a model with the lowest value of BIC.&lt;br /&gt;
&lt;br /&gt;
=== AIC (Akaike Information Criteria)  ===&lt;br /&gt;
&lt;br /&gt;
Works exactly the same as BIC, but the formula is slightly different.&lt;br /&gt;
&lt;br /&gt;
== Method and Simulation Method ==&lt;br /&gt;
&lt;br /&gt;
The solution consists of three key elements, data generating process, AR(p) model, and simulation.&lt;br /&gt;
&lt;br /&gt;
=== Data Generating Process ===&lt;br /&gt;
&lt;br /&gt;
To answer the question, which model selection method is the best, we are generating an artificial data. We assume that data are created by AR(1) process&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
or AR(2)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\mu} + {\phi}_2x_{t-2} + {\epsilon}_{t}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
with random error &amp;lt;math&amp;gt;&amp;lt;/math&amp;gt; . Therefore, we must generate random numbers for random errors, and iterate over the equations described above. The initial values of the processes, e.g., &amp;lt;math&amp;gt;x_0&amp;lt;/math&amp;gt;, are set to the theoretical mean value of the process.&lt;br /&gt;
&lt;br /&gt;
=== AR(p) model ===&lt;br /&gt;
&lt;br /&gt;
For a given series &amp;lt;math&amp;gt;{x_1,x_2,...x_T}&amp;lt;/math&amp;gt; with a length ''T'' estimates a model for a given p.&lt;br /&gt;
&lt;br /&gt;
=== Simulation ===&lt;br /&gt;
&lt;br /&gt;
Perform n Monte Carlo simulations, where in each simulation the data generating process is used to create a time series. Then the AR(p) model is estimated for ''p=0,1,…,pmax'', and the best models are selected according to the selection criteria described above. Therefore, we will obtain four estimates of p that corresponds to the described methods for each of the n simulation. The final step is to compute % success of correctly estimated p for each of four methods.&lt;br /&gt;
&lt;br /&gt;
== Controls ==&lt;br /&gt;
The solution allow to set number of simulation n. We need high enough n to make sure that the results will converge close enough to actual results. Therefore, we have set &amp;lt;math&amp;gt;n=5000&amp;lt;/math&amp;gt;. Higher n will not significantly increase the precision of the results.&lt;br /&gt;
&lt;br /&gt;
The more important controls is selection of AR(1) or AR(2) process, and selection of parameters &amp;lt;math&amp;gt;{\mu},{\sigma},{\phi}_1&amp;lt;/math&amp;gt;  and  &amp;lt;math&amp;gt;{\phi}_2&amp;lt;/math&amp;gt; for the process. Additionally, we can set length of the generated series and even compare performance for series with two distinct lengths &amp;lt;math&amp;gt;T_1&amp;lt;/math&amp;gt; and &amp;lt;math&amp;gt;T_2&amp;lt;/math&amp;gt;. In other words, one method may perform better for low number of observations than other, and this control allow to compare the performance.&lt;br /&gt;
&lt;br /&gt;
== Results ==&lt;br /&gt;
&amp;lt;gallery&amp;gt;&lt;br /&gt;
File:Phi01.png|&amp;lt;math&amp;gt;{\Phi} = 0.1&amp;lt;/math&amp;gt;&lt;br /&gt;
File:Phi09.png|&amp;lt;math&amp;gt;{\Phi} = 0.9&amp;lt;/math&amp;gt;&lt;br /&gt;
File:Phi04Phi04.png|&amp;lt;math&amp;gt;{\Phi}_1= 0.4, {\Phi}_2 = 0.4&amp;lt;/math&amp;gt;&lt;br /&gt;
File:Phi00Phi09.png|&amp;lt;math&amp;gt;{\Phi}_1= 0.0, {\Phi}_2 = 0.9&amp;lt;/math&amp;gt;&lt;br /&gt;
&amp;lt;/gallery&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
===&amp;lt;math&amp;gt;{\phi} = 0.1&amp;lt;/math&amp;gt;===&lt;br /&gt;
Previous periods don't have big impact. &lt;br /&gt;
AIC method works well with smaller  samples. In case of bigger samples, BIC method works better than AIC.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;math&amp;gt;{\phi} = 0.9&amp;lt;/math&amp;gt;===&lt;br /&gt;
BIC is the best method for small and big samples. Even though the GETS method doesn't work quite well, it is commonly used. The bigger tha max value of p is used, the bigger is the probability of getting the wrong guess from the simulation.&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;math&amp;gt;{\phi}_1 = 0.0&amp;lt;/math&amp;gt;  and &amp;lt;math&amp;gt;{\phi}_2 = 0.9&amp;lt;/math&amp;gt;===&lt;br /&gt;
BIC is the best method for small and big samples again. &lt;br /&gt;
We never want to use the Spec-to-gen method, because&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;math&amp;gt;{\phi}_1 = 0.4&amp;lt;/math&amp;gt; and &amp;lt;math&amp;gt;{\phi}_2 = 0.4&amp;lt;/math&amp;gt;===&lt;br /&gt;
This process is set to not be influenced by previous periods.&lt;br /&gt;
The BIC method works the best again.&lt;br /&gt;
&lt;br /&gt;
== Code ==&lt;br /&gt;
=== Models.py ===&lt;br /&gt;
The part of the code ''''class ARp(object)'''' was created with great help from another student and it is not originally created for this course.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import numpy as np from numpy.linalg &lt;br /&gt;
import inv from scipy.stats &lt;br /&gt;
import norm&lt;br /&gt;
&lt;br /&gt;
def sim1(mu, phi1, sigmaSq, T):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates single trajectory.&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    x = np.zeros(T+1)&lt;br /&gt;
    epsilon = np.random.normal(0,sigmaSq, T+1)&lt;br /&gt;
&lt;br /&gt;
    x[0] = mu / (1.0 - phi1)&lt;br /&gt;
&lt;br /&gt;
    for t in np.arange(T):&lt;br /&gt;
        x[t+1] = mu + phi1 * x[t] + epsilon[t]&lt;br /&gt;
&lt;br /&gt;
    return x[1:]&lt;br /&gt;
&lt;br /&gt;
def trajectories1(mu, phi1, sigmaSq, T, n):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates n-trajectories of AR(1) process&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :param n:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    X = np.zeros([n,T])&lt;br /&gt;
    for s in np.arange(n):&lt;br /&gt;
        X[s,:] = sim1(mu, phi1, sigmaSq, T)&lt;br /&gt;
    return X&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
def sim2(mu, phi1, phi2, sigmaSq, T):&lt;br /&gt;
    x = np.zeros(T+2)&lt;br /&gt;
    epsilon = np.random.normal(0,sigmaSq, T+2)&lt;br /&gt;
&lt;br /&gt;
    x[0] = mu / (1.0 - phi1-phi2)&lt;br /&gt;
    x[1] = mu / (1.0 - phi1-phi2)&lt;br /&gt;
&lt;br /&gt;
    for t in np.arange(T)+1:&lt;br /&gt;
        x[t+1] = mu + phi1 * x[t] + phi2 * x[t-1] + epsilon[t]&lt;br /&gt;
&lt;br /&gt;
    return x[2:]&lt;br /&gt;
&lt;br /&gt;
def trajectories2(mu, phi1, phi2, sigmaSq, T, n):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates n-trajectories of AR(2) process&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param phi2:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :param n:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    X = np.zeros([n,T])&lt;br /&gt;
    for s in np.arange(n):&lt;br /&gt;
        X[s,:] = sim2(mu, phi1, phi2, sigmaSq, T)&lt;br /&gt;
    return X&lt;br /&gt;
&lt;br /&gt;
class ARp(object):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;AR(p) class allowing to estimate the model &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
    def __init__(self, x, p, pmax):&lt;br /&gt;
        self.p = p&lt;br /&gt;
        self.x = x&lt;br /&gt;
        self.T = float(x.size)&lt;br /&gt;
        self.par = np.zeros(p+2) #np.array: c, phi_1, phi_2, ... phi_p, sigma^2&lt;br /&gt;
&lt;br /&gt;
        #Init. matrices for OLS&lt;br /&gt;
        Y = self.x[pmax:]&lt;br /&gt;
        Xtemp = []&lt;br /&gt;
&lt;br /&gt;
        for i in np.arange(Y.size):&lt;br /&gt;
            Xtemp.append(np.flip(x[i:(pmax+i)],0))&lt;br /&gt;
        X = np.ones((Y.size, p+1))&lt;br /&gt;
        X[:,1:] = np.array(Xtemp)[:,:p]&lt;br /&gt;
&lt;br /&gt;
        #OLS Estimate&lt;br /&gt;
        Phi = np.dot(np.dot(inv(np.dot(X.T,X)),X.T),Y)&lt;br /&gt;
        SigmaS = np.sum((Y - np.dot(X, Phi))**2.0)/(self.T-pmax)&lt;br /&gt;
        self.par[:-1] = Phi[:]&lt;br /&gt;
        self.par[-1] = SigmaS&lt;br /&gt;
&lt;br /&gt;
        #t-ratios&lt;br /&gt;
        self.VCOV = inv(np.dot(X.T,X))*SigmaS&lt;br /&gt;
        self.SE = np.diag(self.VCOV)**0.5&lt;br /&gt;
        self.t = self.par[:-1]/self.SE&lt;br /&gt;
&lt;br /&gt;
        #likelihood and IC&lt;br /&gt;
        self.logL = (-(self.T-pmax)/2.0)*np.log(2.0*np.pi) + (-(self.T-pmax)/2.0)*np.log(SigmaS) + (-(self.T-pmax)/2.0)&lt;br /&gt;
        self.AIC = 2.0*((self.par.size)-self.logL)&lt;br /&gt;
        self.BIC = np.log(Y.size)*self.par.size-2.0*self.logL&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Simulation.py ===&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import numpy as np&lt;br /&gt;
import models as mod&lt;br /&gt;
import matplotlib.pyplot as plt&lt;br /&gt;
from scipy.stats import norm&lt;br /&gt;
##########################&lt;br /&gt;
#Simulation and settings&lt;br /&gt;
#########################&lt;br /&gt;
#general&lt;br /&gt;
pmax = 10 # Maximum number of lags&lt;br /&gt;
n = 5000 # Number of simulations&lt;br /&gt;
T1 = 200 # Length of the first time series&lt;br /&gt;
T2 = 2000 # Length of the second time series&lt;br /&gt;
&lt;br /&gt;
#1. AR(1) process&lt;br /&gt;
#phi = 0.9&lt;br /&gt;
#mu = 5.0&lt;br /&gt;
#sigmaSq = 1.0&lt;br /&gt;
#X1 = mod.trajectories1(mu, phi, sigmaSq, T1, n)&lt;br /&gt;
#X2 = mod.trajectories1(mu, phi, sigmaSq, T2, n)&lt;br /&gt;
&lt;br /&gt;
#2. AR(2) process&lt;br /&gt;
phi1 = 0.4&lt;br /&gt;
phi2 = 0.4&lt;br /&gt;
mu = 5.0&lt;br /&gt;
sigmaSq = 1.0&lt;br /&gt;
X1 = mod.trajectories2(mu, phi1, phi2, sigmaSq, T1, n) # Rows = individual series; columns = time periods&lt;br /&gt;
X2 = mod.trajectories2(mu, phi1, phi2, sigmaSq, T2, n)&lt;br /&gt;
&lt;br /&gt;
#####&lt;br /&gt;
#GETS General to specific method&lt;br /&gt;
#####&lt;br /&gt;
tquantile = norm.ppf(0.95) #95% quantile&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop1 = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    p = pmax&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:],p,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;lt; tquantile and p&amp;gt;0:&lt;br /&gt;
            p-=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop1.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T1 finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop2 = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    p = pmax&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:],p,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;lt; tquantile and p&amp;gt;0:&lt;br /&gt;
            p-=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop2.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T2 finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
####################&lt;br /&gt;
#Specific-to-General&lt;br /&gt;
####################&lt;br /&gt;
tquantile = norm.ppf(0.95) #95% quantile&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop1SOG = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    p = 0&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:],p+1,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;gt; tquantile and p&amp;lt;=pmax:&lt;br /&gt;
            p+=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop1SOG.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T1 finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop2SOG = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    p = 0&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:],p+1,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;gt; tquantile and p&amp;lt;=pmax:&lt;br /&gt;
            p+=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop2SOG.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T2 finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
####################&lt;br /&gt;
#AIC and BIC&lt;br /&gt;
####################&lt;br /&gt;
#T1 simulation&lt;br /&gt;
AICp1 = []&lt;br /&gt;
BICp1 = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    AICtemp = np.zeros(11)&lt;br /&gt;
    BICtemp = np.zeros(11)&lt;br /&gt;
    for p in np.arange(pmax+1):&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:], p, pmax)&lt;br /&gt;
        AICtemp[p] = ARtemp.AIC&lt;br /&gt;
        BICtemp[p] = ARtemp.BIC&lt;br /&gt;
    AICp1.append(np.argmin(AICtemp))&lt;br /&gt;
    BICp1.append(np.argmin(BICtemp))&lt;br /&gt;
&lt;br /&gt;
print &amp;quot;T1 AIC+BIC finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
AICp2 = []&lt;br /&gt;
BICp2 = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    AICtemp = np.zeros(11)&lt;br /&gt;
    BICtemp = np.zeros(11)&lt;br /&gt;
    for p in np.arange(pmax+1):&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:], p, pmax)&lt;br /&gt;
        AICtemp[p] = ARtemp.AIC&lt;br /&gt;
        BICtemp[p] = ARtemp.BIC&lt;br /&gt;
    AICp2.append(np.argmin(AICtemp))&lt;br /&gt;
    BICp2.append(np.argmin(BICtemp))&lt;br /&gt;
print &amp;quot;T2 AIC+BIC finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
####################&lt;br /&gt;
#Plot&lt;br /&gt;
####################&lt;br /&gt;
&lt;br /&gt;
fig, axes = plt.subplots(nrows=4, ncols=2)&lt;br /&gt;
ax0, ax1, ax2, ax3, ax4, ax5, ax6, ax7 = axes.flatten()&lt;br /&gt;
&lt;br /&gt;
ax0.hist(tratiop1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax0.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax0.set_title('GETS, T=200')&lt;br /&gt;
&lt;br /&gt;
ax1.hist(tratiop2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax1.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax1.set_title('GETS, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax2.hist(tratiop1SOG, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax2.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax2.set_title('Spec-to-Gen, T=200')&lt;br /&gt;
&lt;br /&gt;
ax3.hist(tratiop2SOG, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax3.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax3.set_title('Spec-to-Gen, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax4.hist(AICp1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax4.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax4.set_title('AIC, T=200')&lt;br /&gt;
&lt;br /&gt;
ax5.hist(AICp2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax5.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax5.set_title('AIC, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax6.hist(BICp1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax6.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax6.set_title('BIC, T=200')&lt;br /&gt;
&lt;br /&gt;
ax7.hist(BICp2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax7.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax7.set_title('BIC, T=2000')&lt;br /&gt;
&lt;br /&gt;
fig.subplots_adjust(hspace=0.5)&lt;br /&gt;
plt.show()&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;/div&gt;</summary>
		<author><name>Hazn00</name></author>
		
	</entry>
	<entry>
		<id>http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19154</id>
		<title>Time Series Model Building Process</title>
		<link rel="alternate" type="text/html" href="http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19154"/>
		<updated>2020-01-19T14:15:44Z</updated>

		<summary type="html">&lt;p&gt;Hazn00: /* Simulation */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Linear time series models, e.g., ARIMA models for univariate time series, is a popular tool for modeling dynamics of time series and predicting the time series. The methodology is not popular only in statistics, econometrics and science, but also in machine learning business applications. The key question is how to build the model. We have to choose the form of the model, in particular number of lags for so-called autoregressive part (usually denoted as p) and moving average part of the model (usually denoted as d). The common guides usually provide a ‘cook book’ for model selection, see for example [https://www.machinelearningplus.com/time-series/arima-model-time-series-forecasting-python/, ARIMA Model – Complete Guide to Time Series Forecasting in Python] . This goal of this simulation is to compare four basic methods for selection of lags (p) for the autoregressive part.&lt;br /&gt;
&lt;br /&gt;
== Problem Definition ==&lt;br /&gt;
&lt;br /&gt;
The autoregressive process has form&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\phi}_2x_{t-2}+...+{\phi}_px_{t-p} + {\epsilon}_t&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;{\epsilon}_t \sim N(0,{\sigma}^2) &amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
However, we observe only the realized value and we do not know the hyperparameter p. Therefore, we must estimate it. The considered methods are following.&lt;br /&gt;
&lt;br /&gt;
=== GETS (General-to-Specific) ===&lt;br /&gt;
&lt;br /&gt;
We first start with high enough p (pmax in the code), and perform statistical test whether the last lag has statistically significant impact, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p = 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p \neq 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the impact is insignificant, we reduce p by one and continue until the parameter for the last lag is significant, i.e. last lag has significant effect.&lt;br /&gt;
&lt;br /&gt;
=== Specific-to-General ===&lt;br /&gt;
&lt;br /&gt;
The second approach works similarly as GETS, the only difference is that we first start with model without any lag, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and we are adding lags until they are significant.&lt;br /&gt;
&lt;br /&gt;
=== BIC (Bayesian Information Criteria) ===&lt;br /&gt;
&lt;br /&gt;
Bayesian information criteria is based on a likelihood of the model and number of parameters. The criteria punish the model for high number of parameters for a potential over-fitting, and rewards the model for good fit of the data. The lower the BIC value is, the better the model (a little bit counterintuitive definition). We are supposed to select a model with the lowest value of BIC.&lt;br /&gt;
&lt;br /&gt;
=== AIC (Akaike Information Criteria)  ===&lt;br /&gt;
&lt;br /&gt;
Works exactly the same as BIC, but the formula is slightly different.&lt;br /&gt;
&lt;br /&gt;
== Method and Simulation Method ==&lt;br /&gt;
&lt;br /&gt;
The solution consists of three key elements, data generating process, AR(p) model, and simulation.&lt;br /&gt;
&lt;br /&gt;
=== Data Generating Process ===&lt;br /&gt;
&lt;br /&gt;
To answer the question, which model selection method is the best, we are generating an artificial data. We assume that data are created by AR(1) process&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
or AR(2)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\mu} + {\phi}_2x_{t-2} + {\epsilon}_{t}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
with random error &amp;lt;math&amp;gt;&amp;lt;/math&amp;gt; . Therefore, we must generate random numbers for random errors, and iterate over the equations described above. The initial values of the processes, e.g., &amp;lt;math&amp;gt;x_0&amp;lt;/math&amp;gt;, are set to the theoretical mean value of the process.&lt;br /&gt;
&lt;br /&gt;
=== AR(p) model ===&lt;br /&gt;
&lt;br /&gt;
For a given series &amp;lt;math&amp;gt;{x_1,x_2,...x_T}&amp;lt;/math&amp;gt; with a length ''T'' estimates a model for a given p.&lt;br /&gt;
&lt;br /&gt;
=== Simulation ===&lt;br /&gt;
&lt;br /&gt;
Perform n Monte Carlo simulations, where in each simulation the data generating process is used to create a time series. Then the AR(p) model is estimated for ''p=0,1,…,pmax'', and the best models are selected according to the selection criteria described above. Therefore, we will obtain four estimates of p that corresponds to the described methods for each of the n simulation. The final step is to compute % success of correctly estimated p for each of four methods.&lt;br /&gt;
&lt;br /&gt;
== Controls ==&lt;br /&gt;
The solution allow to set number of simulation n. We need high enough n to make sure that the results will converge close enough to actual results. Therefore, we have set &amp;lt;math&amp;gt;n=5000&amp;lt;/math&amp;gt;. Higher n will not significantly increase the precision of the results.&lt;br /&gt;
&lt;br /&gt;
The more important controls is selection of AR(1) or AR(2) process, and selection of parameters &amp;lt;math&amp;gt;{\mu},{\sigma},{\phi}_1&amp;lt;/math&amp;gt;  and  &amp;lt;math&amp;gt;{\phi}_2&amp;lt;/math&amp;gt; for the process. Additionally, we can set length of the generated series and even compare performance for series with two distinct lengths &amp;lt;math&amp;gt;T_1&amp;lt;/math&amp;gt; and &amp;lt;math&amp;gt;T_2&amp;lt;/math&amp;gt;. In other words, one method may perform better for low number of observations than other, and this control allow to compare the performance.&lt;br /&gt;
&lt;br /&gt;
== Results ==&lt;br /&gt;
&amp;lt;gallery&amp;gt;&lt;br /&gt;
File:Phi01.png|&amp;lt;math&amp;gt;{\Phi} = 0.1&amp;lt;/math&amp;gt;&lt;br /&gt;
File:Phi09.png|&amp;lt;math&amp;gt;{\Phi} = 0.9&amp;lt;/math&amp;gt;&lt;br /&gt;
File:Phi04Phi04.png|&amp;lt;math&amp;gt;{\Phi}_1= 0.4, {\Phi}_2 = 0.4&amp;lt;/math&amp;gt;&lt;br /&gt;
File:Phi00Phi09.png|&amp;lt;math&amp;gt;{\Phi}_1= 0.0, {\Phi}_2 = 0.9&amp;lt;/math&amp;gt;&lt;br /&gt;
&amp;lt;/gallery&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
&lt;br /&gt;
== Code ==&lt;br /&gt;
=== Models.py ===&lt;br /&gt;
The part of the code ''''class ARp(object)'''' was created with great help from another student and it is not originally created for this course.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import numpy as np from numpy.linalg &lt;br /&gt;
import inv from scipy.stats &lt;br /&gt;
import norm&lt;br /&gt;
&lt;br /&gt;
def sim1(mu, phi1, sigmaSq, T):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates single trajectory.&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    x = np.zeros(T+1)&lt;br /&gt;
    epsilon = np.random.normal(0,sigmaSq, T+1)&lt;br /&gt;
&lt;br /&gt;
    x[0] = mu / (1.0 - phi1)&lt;br /&gt;
&lt;br /&gt;
    for t in np.arange(T):&lt;br /&gt;
        x[t+1] = mu + phi1 * x[t] + epsilon[t]&lt;br /&gt;
&lt;br /&gt;
    return x[1:]&lt;br /&gt;
&lt;br /&gt;
def trajectories1(mu, phi1, sigmaSq, T, n):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates n-trajectories of AR(1) process&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :param n:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    X = np.zeros([n,T])&lt;br /&gt;
    for s in np.arange(n):&lt;br /&gt;
        X[s,:] = sim1(mu, phi1, sigmaSq, T)&lt;br /&gt;
    return X&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
def sim2(mu, phi1, phi2, sigmaSq, T):&lt;br /&gt;
    x = np.zeros(T+2)&lt;br /&gt;
    epsilon = np.random.normal(0,sigmaSq, T+2)&lt;br /&gt;
&lt;br /&gt;
    x[0] = mu / (1.0 - phi1-phi2)&lt;br /&gt;
    x[1] = mu / (1.0 - phi1-phi2)&lt;br /&gt;
&lt;br /&gt;
    for t in np.arange(T)+1:&lt;br /&gt;
        x[t+1] = mu + phi1 * x[t] + phi2 * x[t-1] + epsilon[t]&lt;br /&gt;
&lt;br /&gt;
    return x[2:]&lt;br /&gt;
&lt;br /&gt;
def trajectories2(mu, phi1, phi2, sigmaSq, T, n):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates n-trajectories of AR(2) process&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param phi2:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :param n:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    X = np.zeros([n,T])&lt;br /&gt;
    for s in np.arange(n):&lt;br /&gt;
        X[s,:] = sim2(mu, phi1, phi2, sigmaSq, T)&lt;br /&gt;
    return X&lt;br /&gt;
&lt;br /&gt;
class ARp(object):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;AR(p) class allowing to estimate the model &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
    def __init__(self, x, p, pmax):&lt;br /&gt;
        self.p = p&lt;br /&gt;
        self.x = x&lt;br /&gt;
        self.T = float(x.size)&lt;br /&gt;
        self.par = np.zeros(p+2) #np.array: c, phi_1, phi_2, ... phi_p, sigma^2&lt;br /&gt;
&lt;br /&gt;
        #Init. matrices for OLS&lt;br /&gt;
        Y = self.x[pmax:]&lt;br /&gt;
        Xtemp = []&lt;br /&gt;
&lt;br /&gt;
        for i in np.arange(Y.size):&lt;br /&gt;
            Xtemp.append(np.flip(x[i:(pmax+i)],0))&lt;br /&gt;
        X = np.ones((Y.size, p+1))&lt;br /&gt;
        X[:,1:] = np.array(Xtemp)[:,:p]&lt;br /&gt;
&lt;br /&gt;
        #OLS Estimate&lt;br /&gt;
        Phi = np.dot(np.dot(inv(np.dot(X.T,X)),X.T),Y)&lt;br /&gt;
        SigmaS = np.sum((Y - np.dot(X, Phi))**2.0)/(self.T-pmax)&lt;br /&gt;
        self.par[:-1] = Phi[:]&lt;br /&gt;
        self.par[-1] = SigmaS&lt;br /&gt;
&lt;br /&gt;
        #t-ratios&lt;br /&gt;
        self.VCOV = inv(np.dot(X.T,X))*SigmaS&lt;br /&gt;
        self.SE = np.diag(self.VCOV)**0.5&lt;br /&gt;
        self.t = self.par[:-1]/self.SE&lt;br /&gt;
&lt;br /&gt;
        #likelihood and IC&lt;br /&gt;
        self.logL = (-(self.T-pmax)/2.0)*np.log(2.0*np.pi) + (-(self.T-pmax)/2.0)*np.log(SigmaS) + (-(self.T-pmax)/2.0)&lt;br /&gt;
        self.AIC = 2.0*((self.par.size)-self.logL)&lt;br /&gt;
        self.BIC = np.log(Y.size)*self.par.size-2.0*self.logL&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Simulation.py ===&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import numpy as np&lt;br /&gt;
import models as mod&lt;br /&gt;
import matplotlib.pyplot as plt&lt;br /&gt;
from scipy.stats import norm&lt;br /&gt;
##########################&lt;br /&gt;
#Simulation and settings&lt;br /&gt;
#########################&lt;br /&gt;
#general&lt;br /&gt;
pmax = 10 # Maximum number of lags&lt;br /&gt;
n = 5000 # Number of simulations&lt;br /&gt;
T1 = 200 # Length of the first time series&lt;br /&gt;
T2 = 2000 # Length of the second time series&lt;br /&gt;
&lt;br /&gt;
#1. AR(1) process&lt;br /&gt;
#phi = 0.9&lt;br /&gt;
#mu = 5.0&lt;br /&gt;
#sigmaSq = 1.0&lt;br /&gt;
#X1 = mod.trajectories1(mu, phi, sigmaSq, T1, n)&lt;br /&gt;
#X2 = mod.trajectories1(mu, phi, sigmaSq, T2, n)&lt;br /&gt;
&lt;br /&gt;
#2. AR(2) process&lt;br /&gt;
phi1 = 0.4&lt;br /&gt;
phi2 = 0.4&lt;br /&gt;
mu = 5.0&lt;br /&gt;
sigmaSq = 1.0&lt;br /&gt;
X1 = mod.trajectories2(mu, phi1, phi2, sigmaSq, T1, n) # Rows = individual series; columns = time periods&lt;br /&gt;
X2 = mod.trajectories2(mu, phi1, phi2, sigmaSq, T2, n)&lt;br /&gt;
&lt;br /&gt;
#####&lt;br /&gt;
#GETS General to specific method&lt;br /&gt;
#####&lt;br /&gt;
tquantile = norm.ppf(0.95) #95% quantile&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop1 = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    p = pmax&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:],p,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;lt; tquantile and p&amp;gt;0:&lt;br /&gt;
            p-=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop1.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T1 finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop2 = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    p = pmax&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:],p,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;lt; tquantile and p&amp;gt;0:&lt;br /&gt;
            p-=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop2.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T2 finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
####################&lt;br /&gt;
#Specific-to-General&lt;br /&gt;
####################&lt;br /&gt;
tquantile = norm.ppf(0.95) #95% quantile&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop1SOG = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    p = 0&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:],p+1,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;gt; tquantile and p&amp;lt;=pmax:&lt;br /&gt;
            p+=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop1SOG.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T1 finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop2SOG = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    p = 0&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:],p+1,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;gt; tquantile and p&amp;lt;=pmax:&lt;br /&gt;
            p+=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop2SOG.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T2 finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
####################&lt;br /&gt;
#AIC and BIC&lt;br /&gt;
####################&lt;br /&gt;
#T1 simulation&lt;br /&gt;
AICp1 = []&lt;br /&gt;
BICp1 = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    AICtemp = np.zeros(11)&lt;br /&gt;
    BICtemp = np.zeros(11)&lt;br /&gt;
    for p in np.arange(pmax+1):&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:], p, pmax)&lt;br /&gt;
        AICtemp[p] = ARtemp.AIC&lt;br /&gt;
        BICtemp[p] = ARtemp.BIC&lt;br /&gt;
    AICp1.append(np.argmin(AICtemp))&lt;br /&gt;
    BICp1.append(np.argmin(BICtemp))&lt;br /&gt;
&lt;br /&gt;
print &amp;quot;T1 AIC+BIC finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
AICp2 = []&lt;br /&gt;
BICp2 = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    AICtemp = np.zeros(11)&lt;br /&gt;
    BICtemp = np.zeros(11)&lt;br /&gt;
    for p in np.arange(pmax+1):&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:], p, pmax)&lt;br /&gt;
        AICtemp[p] = ARtemp.AIC&lt;br /&gt;
        BICtemp[p] = ARtemp.BIC&lt;br /&gt;
    AICp2.append(np.argmin(AICtemp))&lt;br /&gt;
    BICp2.append(np.argmin(BICtemp))&lt;br /&gt;
print &amp;quot;T2 AIC+BIC finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
####################&lt;br /&gt;
#Plot&lt;br /&gt;
####################&lt;br /&gt;
&lt;br /&gt;
fig, axes = plt.subplots(nrows=4, ncols=2)&lt;br /&gt;
ax0, ax1, ax2, ax3, ax4, ax5, ax6, ax7 = axes.flatten()&lt;br /&gt;
&lt;br /&gt;
ax0.hist(tratiop1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax0.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax0.set_title('GETS, T=200')&lt;br /&gt;
&lt;br /&gt;
ax1.hist(tratiop2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax1.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax1.set_title('GETS, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax2.hist(tratiop1SOG, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax2.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax2.set_title('Spec-to-Gen, T=200')&lt;br /&gt;
&lt;br /&gt;
ax3.hist(tratiop2SOG, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax3.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax3.set_title('Spec-to-Gen, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax4.hist(AICp1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax4.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax4.set_title('AIC, T=200')&lt;br /&gt;
&lt;br /&gt;
ax5.hist(AICp2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax5.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax5.set_title('AIC, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax6.hist(BICp1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax6.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax6.set_title('BIC, T=200')&lt;br /&gt;
&lt;br /&gt;
ax7.hist(BICp2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax7.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax7.set_title('BIC, T=2000')&lt;br /&gt;
&lt;br /&gt;
fig.subplots_adjust(hspace=0.5)&lt;br /&gt;
plt.show()&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;/div&gt;</summary>
		<author><name>Hazn00</name></author>
		
	</entry>
	<entry>
		<id>http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19153</id>
		<title>Time Series Model Building Process</title>
		<link rel="alternate" type="text/html" href="http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19153"/>
		<updated>2020-01-19T14:14:57Z</updated>

		<summary type="html">&lt;p&gt;Hazn00: /* Models.py */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Linear time series models, e.g., ARIMA models for univariate time series, is a popular tool for modeling dynamics of time series and predicting the time series. The methodology is not popular only in statistics, econometrics and science, but also in machine learning business applications. The key question is how to build the model. We have to choose the form of the model, in particular number of lags for so-called autoregressive part (usually denoted as p) and moving average part of the model (usually denoted as d). The common guides usually provide a ‘cook book’ for model selection, see for example [https://www.machinelearningplus.com/time-series/arima-model-time-series-forecasting-python/, ARIMA Model – Complete Guide to Time Series Forecasting in Python] . This goal of this simulation is to compare four basic methods for selection of lags (p) for the autoregressive part.&lt;br /&gt;
&lt;br /&gt;
== Problem Definition ==&lt;br /&gt;
&lt;br /&gt;
The autoregressive process has form&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\phi}_2x_{t-2}+...+{\phi}_px_{t-p} + {\epsilon}_t&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;{\epsilon}_t \sim N(0,{\sigma}^2) &amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
However, we observe only the realized value and we do not know the hyperparameter p. Therefore, we must estimate it. The considered methods are following.&lt;br /&gt;
&lt;br /&gt;
=== GETS (General-to-Specific) ===&lt;br /&gt;
&lt;br /&gt;
We first start with high enough p (pmax in the code), and perform statistical test whether the last lag has statistically significant impact, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p = 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p \neq 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the impact is insignificant, we reduce p by one and continue until the parameter for the last lag is significant, i.e. last lag has significant effect.&lt;br /&gt;
&lt;br /&gt;
=== Specific-to-General ===&lt;br /&gt;
&lt;br /&gt;
The second approach works similarly as GETS, the only difference is that we first start with model without any lag, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and we are adding lags until they are significant.&lt;br /&gt;
&lt;br /&gt;
=== BIC (Bayesian Information Criteria) ===&lt;br /&gt;
&lt;br /&gt;
Bayesian information criteria is based on a likelihood of the model and number of parameters. The criteria punish the model for high number of parameters for a potential over-fitting, and rewards the model for good fit of the data. The lower the BIC value is, the better the model (a little bit counterintuitive definition). We are supposed to select a model with the lowest value of BIC.&lt;br /&gt;
&lt;br /&gt;
=== AIC (Akaike Information Criteria)  ===&lt;br /&gt;
&lt;br /&gt;
Works exactly the same as BIC, but the formula is slightly different.&lt;br /&gt;
&lt;br /&gt;
== Method and Simulation Method ==&lt;br /&gt;
&lt;br /&gt;
The solution consists of three key elements, data generating process, AR(p) model, and simulation.&lt;br /&gt;
&lt;br /&gt;
=== Data Generating Process ===&lt;br /&gt;
&lt;br /&gt;
To answer the question, which model selection method is the best, we are generating an artificial data. We assume that data are created by AR(1) process&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
or AR(2)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\mu} + {\phi}_2x_{t-2} + {\epsilon}_{t}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
with random error &amp;lt;math&amp;gt;&amp;lt;/math&amp;gt; . Therefore, we must generate random numbers for random errors, and iterate over the equations described above. The initial values of the processes, e.g., &amp;lt;math&amp;gt;x_0&amp;lt;/math&amp;gt;, are set to the theoretical mean value of the process.&lt;br /&gt;
&lt;br /&gt;
=== AR(p) model ===&lt;br /&gt;
&lt;br /&gt;
For a given series &amp;lt;math&amp;gt;{x_1,x_2,...x_T}&amp;lt;/math&amp;gt; with a length ''T'' estimates a model for a given p.&lt;br /&gt;
&lt;br /&gt;
=== Simulation ===&lt;br /&gt;
&lt;br /&gt;
Perform n Monte Carlo simulations, where in each simulation a the data generating process is used to create a time series. Then the AR(p) model is estimated for ''p=0,1,…,pmax'', and the best models are selected according to the selection criteria described above. Therefore, we will obtain four estimates of p that corresponds to the described methods for each of the n simulation. The final step is to compute % success of correctly estimated p for each of four methods.&lt;br /&gt;
&lt;br /&gt;
== Controls ==&lt;br /&gt;
The solution allow to set number of simulation n. We need high enough n to make sure that the results will converge close enough to actual results. Therefore, we have set &amp;lt;math&amp;gt;n=5000&amp;lt;/math&amp;gt;. Higher n will not significantly increase the precision of the results.&lt;br /&gt;
&lt;br /&gt;
The more important controls is selection of AR(1) or AR(2) process, and selection of parameters &amp;lt;math&amp;gt;{\mu},{\sigma},{\phi}_1&amp;lt;/math&amp;gt;  and  &amp;lt;math&amp;gt;{\phi}_2&amp;lt;/math&amp;gt; for the process. Additionally, we can set length of the generated series and even compare performance for series with two distinct lengths &amp;lt;math&amp;gt;T_1&amp;lt;/math&amp;gt; and &amp;lt;math&amp;gt;T_2&amp;lt;/math&amp;gt;. In other words, one method may perform better for low number of observations than other, and this control allow to compare the performance.&lt;br /&gt;
&lt;br /&gt;
== Results ==&lt;br /&gt;
&amp;lt;gallery&amp;gt;&lt;br /&gt;
File:Phi01.png|&amp;lt;math&amp;gt;{\Phi} = 0.1&amp;lt;/math&amp;gt;&lt;br /&gt;
File:Phi09.png|&amp;lt;math&amp;gt;{\Phi} = 0.9&amp;lt;/math&amp;gt;&lt;br /&gt;
File:Phi04Phi04.png|&amp;lt;math&amp;gt;{\Phi}_1= 0.4, {\Phi}_2 = 0.4&amp;lt;/math&amp;gt;&lt;br /&gt;
File:Phi00Phi09.png|&amp;lt;math&amp;gt;{\Phi}_1= 0.0, {\Phi}_2 = 0.9&amp;lt;/math&amp;gt;&lt;br /&gt;
&amp;lt;/gallery&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
&lt;br /&gt;
== Code ==&lt;br /&gt;
=== Models.py ===&lt;br /&gt;
The part of the code ''''class ARp(object)'''' was created with great help from another student and it is not originally created for this course.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import numpy as np from numpy.linalg &lt;br /&gt;
import inv from scipy.stats &lt;br /&gt;
import norm&lt;br /&gt;
&lt;br /&gt;
def sim1(mu, phi1, sigmaSq, T):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates single trajectory.&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    x = np.zeros(T+1)&lt;br /&gt;
    epsilon = np.random.normal(0,sigmaSq, T+1)&lt;br /&gt;
&lt;br /&gt;
    x[0] = mu / (1.0 - phi1)&lt;br /&gt;
&lt;br /&gt;
    for t in np.arange(T):&lt;br /&gt;
        x[t+1] = mu + phi1 * x[t] + epsilon[t]&lt;br /&gt;
&lt;br /&gt;
    return x[1:]&lt;br /&gt;
&lt;br /&gt;
def trajectories1(mu, phi1, sigmaSq, T, n):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates n-trajectories of AR(1) process&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :param n:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    X = np.zeros([n,T])&lt;br /&gt;
    for s in np.arange(n):&lt;br /&gt;
        X[s,:] = sim1(mu, phi1, sigmaSq, T)&lt;br /&gt;
    return X&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
def sim2(mu, phi1, phi2, sigmaSq, T):&lt;br /&gt;
    x = np.zeros(T+2)&lt;br /&gt;
    epsilon = np.random.normal(0,sigmaSq, T+2)&lt;br /&gt;
&lt;br /&gt;
    x[0] = mu / (1.0 - phi1-phi2)&lt;br /&gt;
    x[1] = mu / (1.0 - phi1-phi2)&lt;br /&gt;
&lt;br /&gt;
    for t in np.arange(T)+1:&lt;br /&gt;
        x[t+1] = mu + phi1 * x[t] + phi2 * x[t-1] + epsilon[t]&lt;br /&gt;
&lt;br /&gt;
    return x[2:]&lt;br /&gt;
&lt;br /&gt;
def trajectories2(mu, phi1, phi2, sigmaSq, T, n):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates n-trajectories of AR(2) process&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param phi2:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :param n:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    X = np.zeros([n,T])&lt;br /&gt;
    for s in np.arange(n):&lt;br /&gt;
        X[s,:] = sim2(mu, phi1, phi2, sigmaSq, T)&lt;br /&gt;
    return X&lt;br /&gt;
&lt;br /&gt;
class ARp(object):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;AR(p) class allowing to estimate the model &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
    def __init__(self, x, p, pmax):&lt;br /&gt;
        self.p = p&lt;br /&gt;
        self.x = x&lt;br /&gt;
        self.T = float(x.size)&lt;br /&gt;
        self.par = np.zeros(p+2) #np.array: c, phi_1, phi_2, ... phi_p, sigma^2&lt;br /&gt;
&lt;br /&gt;
        #Init. matrices for OLS&lt;br /&gt;
        Y = self.x[pmax:]&lt;br /&gt;
        Xtemp = []&lt;br /&gt;
&lt;br /&gt;
        for i in np.arange(Y.size):&lt;br /&gt;
            Xtemp.append(np.flip(x[i:(pmax+i)],0))&lt;br /&gt;
        X = np.ones((Y.size, p+1))&lt;br /&gt;
        X[:,1:] = np.array(Xtemp)[:,:p]&lt;br /&gt;
&lt;br /&gt;
        #OLS Estimate&lt;br /&gt;
        Phi = np.dot(np.dot(inv(np.dot(X.T,X)),X.T),Y)&lt;br /&gt;
        SigmaS = np.sum((Y - np.dot(X, Phi))**2.0)/(self.T-pmax)&lt;br /&gt;
        self.par[:-1] = Phi[:]&lt;br /&gt;
        self.par[-1] = SigmaS&lt;br /&gt;
&lt;br /&gt;
        #t-ratios&lt;br /&gt;
        self.VCOV = inv(np.dot(X.T,X))*SigmaS&lt;br /&gt;
        self.SE = np.diag(self.VCOV)**0.5&lt;br /&gt;
        self.t = self.par[:-1]/self.SE&lt;br /&gt;
&lt;br /&gt;
        #likelihood and IC&lt;br /&gt;
        self.logL = (-(self.T-pmax)/2.0)*np.log(2.0*np.pi) + (-(self.T-pmax)/2.0)*np.log(SigmaS) + (-(self.T-pmax)/2.0)&lt;br /&gt;
        self.AIC = 2.0*((self.par.size)-self.logL)&lt;br /&gt;
        self.BIC = np.log(Y.size)*self.par.size-2.0*self.logL&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Simulation.py ===&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import numpy as np&lt;br /&gt;
import models as mod&lt;br /&gt;
import matplotlib.pyplot as plt&lt;br /&gt;
from scipy.stats import norm&lt;br /&gt;
##########################&lt;br /&gt;
#Simulation and settings&lt;br /&gt;
#########################&lt;br /&gt;
#general&lt;br /&gt;
pmax = 10 # Maximum number of lags&lt;br /&gt;
n = 5000 # Number of simulations&lt;br /&gt;
T1 = 200 # Length of the first time series&lt;br /&gt;
T2 = 2000 # Length of the second time series&lt;br /&gt;
&lt;br /&gt;
#1. AR(1) process&lt;br /&gt;
#phi = 0.9&lt;br /&gt;
#mu = 5.0&lt;br /&gt;
#sigmaSq = 1.0&lt;br /&gt;
#X1 = mod.trajectories1(mu, phi, sigmaSq, T1, n)&lt;br /&gt;
#X2 = mod.trajectories1(mu, phi, sigmaSq, T2, n)&lt;br /&gt;
&lt;br /&gt;
#2. AR(2) process&lt;br /&gt;
phi1 = 0.4&lt;br /&gt;
phi2 = 0.4&lt;br /&gt;
mu = 5.0&lt;br /&gt;
sigmaSq = 1.0&lt;br /&gt;
X1 = mod.trajectories2(mu, phi1, phi2, sigmaSq, T1, n) # Rows = individual series; columns = time periods&lt;br /&gt;
X2 = mod.trajectories2(mu, phi1, phi2, sigmaSq, T2, n)&lt;br /&gt;
&lt;br /&gt;
#####&lt;br /&gt;
#GETS General to specific method&lt;br /&gt;
#####&lt;br /&gt;
tquantile = norm.ppf(0.95) #95% quantile&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop1 = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    p = pmax&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:],p,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;lt; tquantile and p&amp;gt;0:&lt;br /&gt;
            p-=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop1.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T1 finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop2 = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    p = pmax&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:],p,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;lt; tquantile and p&amp;gt;0:&lt;br /&gt;
            p-=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop2.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T2 finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
####################&lt;br /&gt;
#Specific-to-General&lt;br /&gt;
####################&lt;br /&gt;
tquantile = norm.ppf(0.95) #95% quantile&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop1SOG = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    p = 0&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:],p+1,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;gt; tquantile and p&amp;lt;=pmax:&lt;br /&gt;
            p+=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop1SOG.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T1 finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop2SOG = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    p = 0&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:],p+1,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;gt; tquantile and p&amp;lt;=pmax:&lt;br /&gt;
            p+=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop2SOG.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T2 finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
####################&lt;br /&gt;
#AIC and BIC&lt;br /&gt;
####################&lt;br /&gt;
#T1 simulation&lt;br /&gt;
AICp1 = []&lt;br /&gt;
BICp1 = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    AICtemp = np.zeros(11)&lt;br /&gt;
    BICtemp = np.zeros(11)&lt;br /&gt;
    for p in np.arange(pmax+1):&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:], p, pmax)&lt;br /&gt;
        AICtemp[p] = ARtemp.AIC&lt;br /&gt;
        BICtemp[p] = ARtemp.BIC&lt;br /&gt;
    AICp1.append(np.argmin(AICtemp))&lt;br /&gt;
    BICp1.append(np.argmin(BICtemp))&lt;br /&gt;
&lt;br /&gt;
print &amp;quot;T1 AIC+BIC finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
AICp2 = []&lt;br /&gt;
BICp2 = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    AICtemp = np.zeros(11)&lt;br /&gt;
    BICtemp = np.zeros(11)&lt;br /&gt;
    for p in np.arange(pmax+1):&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:], p, pmax)&lt;br /&gt;
        AICtemp[p] = ARtemp.AIC&lt;br /&gt;
        BICtemp[p] = ARtemp.BIC&lt;br /&gt;
    AICp2.append(np.argmin(AICtemp))&lt;br /&gt;
    BICp2.append(np.argmin(BICtemp))&lt;br /&gt;
print &amp;quot;T2 AIC+BIC finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
####################&lt;br /&gt;
#Plot&lt;br /&gt;
####################&lt;br /&gt;
&lt;br /&gt;
fig, axes = plt.subplots(nrows=4, ncols=2)&lt;br /&gt;
ax0, ax1, ax2, ax3, ax4, ax5, ax6, ax7 = axes.flatten()&lt;br /&gt;
&lt;br /&gt;
ax0.hist(tratiop1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax0.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax0.set_title('GETS, T=200')&lt;br /&gt;
&lt;br /&gt;
ax1.hist(tratiop2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax1.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax1.set_title('GETS, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax2.hist(tratiop1SOG, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax2.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax2.set_title('Spec-to-Gen, T=200')&lt;br /&gt;
&lt;br /&gt;
ax3.hist(tratiop2SOG, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax3.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax3.set_title('Spec-to-Gen, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax4.hist(AICp1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax4.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax4.set_title('AIC, T=200')&lt;br /&gt;
&lt;br /&gt;
ax5.hist(AICp2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax5.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax5.set_title('AIC, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax6.hist(BICp1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax6.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax6.set_title('BIC, T=200')&lt;br /&gt;
&lt;br /&gt;
ax7.hist(BICp2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax7.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax7.set_title('BIC, T=2000')&lt;br /&gt;
&lt;br /&gt;
fig.subplots_adjust(hspace=0.5)&lt;br /&gt;
plt.show()&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;/div&gt;</summary>
		<author><name>Hazn00</name></author>
		
	</entry>
	<entry>
		<id>http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19152</id>
		<title>Time Series Model Building Process</title>
		<link rel="alternate" type="text/html" href="http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19152"/>
		<updated>2020-01-19T14:10:04Z</updated>

		<summary type="html">&lt;p&gt;Hazn00: /* Data Generating Process */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Linear time series models, e.g., ARIMA models for univariate time series, is a popular tool for modeling dynamics of time series and predicting the time series. The methodology is not popular only in statistics, econometrics and science, but also in machine learning business applications. The key question is how to build the model. We have to choose the form of the model, in particular number of lags for so-called autoregressive part (usually denoted as p) and moving average part of the model (usually denoted as d). The common guides usually provide a ‘cook book’ for model selection, see for example [https://www.machinelearningplus.com/time-series/arima-model-time-series-forecasting-python/, ARIMA Model – Complete Guide to Time Series Forecasting in Python] . This goal of this simulation is to compare four basic methods for selection of lags (p) for the autoregressive part.&lt;br /&gt;
&lt;br /&gt;
== Problem Definition ==&lt;br /&gt;
&lt;br /&gt;
The autoregressive process has form&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\phi}_2x_{t-2}+...+{\phi}_px_{t-p} + {\epsilon}_t&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;{\epsilon}_t \sim N(0,{\sigma}^2) &amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
However, we observe only the realized value and we do not know the hyperparameter p. Therefore, we must estimate it. The considered methods are following.&lt;br /&gt;
&lt;br /&gt;
=== GETS (General-to-Specific) ===&lt;br /&gt;
&lt;br /&gt;
We first start with high enough p (pmax in the code), and perform statistical test whether the last lag has statistically significant impact, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p = 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p \neq 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the impact is insignificant, we reduce p by one and continue until the parameter for the last lag is significant, i.e. last lag has significant effect.&lt;br /&gt;
&lt;br /&gt;
=== Specific-to-General ===&lt;br /&gt;
&lt;br /&gt;
The second approach works similarly as GETS, the only difference is that we first start with model without any lag, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and we are adding lags until they are significant.&lt;br /&gt;
&lt;br /&gt;
=== BIC (Bayesian Information Criteria) ===&lt;br /&gt;
&lt;br /&gt;
Bayesian information criteria is based on a likelihood of the model and number of parameters. The criteria punish the model for high number of parameters for a potential over-fitting, and rewards the model for good fit of the data. The lower the BIC value is, the better the model (a little bit counterintuitive definition). We are supposed to select a model with the lowest value of BIC.&lt;br /&gt;
&lt;br /&gt;
=== AIC (Akaike Information Criteria)  ===&lt;br /&gt;
&lt;br /&gt;
Works exactly the same as BIC, but the formula is slightly different.&lt;br /&gt;
&lt;br /&gt;
== Method and Simulation Method ==&lt;br /&gt;
&lt;br /&gt;
The solution consists of three key elements, data generating process, AR(p) model, and simulation.&lt;br /&gt;
&lt;br /&gt;
=== Data Generating Process ===&lt;br /&gt;
&lt;br /&gt;
To answer the question, which model selection method is the best, we are generating an artificial data. We assume that data are created by AR(1) process&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
or AR(2)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\mu} + {\phi}_2x_{t-2} + {\epsilon}_{t}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
with random error &amp;lt;math&amp;gt;&amp;lt;/math&amp;gt; . Therefore, we must generate random numbers for random errors, and iterate over the equations described above. The initial values of the processes, e.g., &amp;lt;math&amp;gt;x_0&amp;lt;/math&amp;gt;, are set to the theoretical mean value of the process.&lt;br /&gt;
&lt;br /&gt;
=== AR(p) model ===&lt;br /&gt;
&lt;br /&gt;
For a given series &amp;lt;math&amp;gt;{x_1,x_2,...x_T}&amp;lt;/math&amp;gt; with a length ''T'' estimates a model for a given p.&lt;br /&gt;
&lt;br /&gt;
=== Simulation ===&lt;br /&gt;
&lt;br /&gt;
Perform n Monte Carlo simulations, where in each simulation a the data generating process is used to create a time series. Then the AR(p) model is estimated for ''p=0,1,…,pmax'', and the best models are selected according to the selection criteria described above. Therefore, we will obtain four estimates of p that corresponds to the described methods for each of the n simulation. The final step is to compute % success of correctly estimated p for each of four methods.&lt;br /&gt;
&lt;br /&gt;
== Controls ==&lt;br /&gt;
The solution allow to set number of simulation n. We need high enough n to make sure that the results will converge close enough to actual results. Therefore, we have set &amp;lt;math&amp;gt;n=5000&amp;lt;/math&amp;gt;. Higher n will not significantly increase the precision of the results.&lt;br /&gt;
&lt;br /&gt;
The more important controls is selection of AR(1) or AR(2) process, and selection of parameters &amp;lt;math&amp;gt;{\mu},{\sigma},{\phi}_1&amp;lt;/math&amp;gt;  and  &amp;lt;math&amp;gt;{\phi}_2&amp;lt;/math&amp;gt; for the process. Additionally, we can set length of the generated series and even compare performance for series with two distinct lengths &amp;lt;math&amp;gt;T_1&amp;lt;/math&amp;gt; and &amp;lt;math&amp;gt;T_2&amp;lt;/math&amp;gt;. In other words, one method may perform better for low number of observations than other, and this control allow to compare the performance.&lt;br /&gt;
&lt;br /&gt;
== Results ==&lt;br /&gt;
&amp;lt;gallery&amp;gt;&lt;br /&gt;
File:Phi01.png|&amp;lt;math&amp;gt;{\Phi} = 0.1&amp;lt;/math&amp;gt;&lt;br /&gt;
File:Phi09.png|&amp;lt;math&amp;gt;{\Phi} = 0.9&amp;lt;/math&amp;gt;&lt;br /&gt;
File:Phi04Phi04.png|&amp;lt;math&amp;gt;{\Phi}_1= 0.4, {\Phi}_2 = 0.4&amp;lt;/math&amp;gt;&lt;br /&gt;
File:Phi00Phi09.png|&amp;lt;math&amp;gt;{\Phi}_1= 0.0, {\Phi}_2 = 0.9&amp;lt;/math&amp;gt;&lt;br /&gt;
&amp;lt;/gallery&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
&lt;br /&gt;
== Code ==&lt;br /&gt;
=== Models.py ===&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import numpy as np from numpy.linalg &lt;br /&gt;
import inv from scipy.stats &lt;br /&gt;
import norm&lt;br /&gt;
&lt;br /&gt;
def sim1(mu, phi1, sigmaSq, T):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates single trajectory.&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    x = np.zeros(T+1)&lt;br /&gt;
    epsilon = np.random.normal(0,sigmaSq, T+1)&lt;br /&gt;
&lt;br /&gt;
    x[0] = mu / (1.0 - phi1)&lt;br /&gt;
&lt;br /&gt;
    for t in np.arange(T):&lt;br /&gt;
        x[t+1] = mu + phi1 * x[t] + epsilon[t]&lt;br /&gt;
&lt;br /&gt;
    return x[1:]&lt;br /&gt;
&lt;br /&gt;
def trajectories1(mu, phi1, sigmaSq, T, n):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates n-trajectories of AR(1) process&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :param n:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    X = np.zeros([n,T])&lt;br /&gt;
    for s in np.arange(n):&lt;br /&gt;
        X[s,:] = sim1(mu, phi1, sigmaSq, T)&lt;br /&gt;
    return X&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
def sim2(mu, phi1, phi2, sigmaSq, T):&lt;br /&gt;
    x = np.zeros(T+2)&lt;br /&gt;
    epsilon = np.random.normal(0,sigmaSq, T+2)&lt;br /&gt;
&lt;br /&gt;
    x[0] = mu / (1.0 - phi1-phi2)&lt;br /&gt;
    x[1] = mu / (1.0 - phi1-phi2)&lt;br /&gt;
&lt;br /&gt;
    for t in np.arange(T)+1:&lt;br /&gt;
        x[t+1] = mu + phi1 * x[t] + phi2 * x[t-1] + epsilon[t]&lt;br /&gt;
&lt;br /&gt;
    return x[2:]&lt;br /&gt;
&lt;br /&gt;
def trajectories2(mu, phi1, phi2, sigmaSq, T, n):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates n-trajectories of AR(2) process&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param phi2:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :param n:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    X = np.zeros([n,T])&lt;br /&gt;
    for s in np.arange(n):&lt;br /&gt;
        X[s,:] = sim2(mu, phi1, phi2, sigmaSq, T)&lt;br /&gt;
    return X&lt;br /&gt;
&lt;br /&gt;
class ARp(object):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;AR(p) class allowing to estimate the model &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
    def __init__(self, x, p, pmax):&lt;br /&gt;
        self.p = p&lt;br /&gt;
        self.x = x&lt;br /&gt;
        self.T = float(x.size)&lt;br /&gt;
        self.par = np.zeros(p+2) #np.array: c, phi_1, phi_2, ... phi_p, sigma^2&lt;br /&gt;
&lt;br /&gt;
        #Init. matrices for OLS&lt;br /&gt;
        Y = self.x[pmax:]&lt;br /&gt;
        Xtemp = []&lt;br /&gt;
&lt;br /&gt;
        for i in np.arange(Y.size):&lt;br /&gt;
            Xtemp.append(np.flip(x[i:(pmax+i)],0))&lt;br /&gt;
        X = np.ones((Y.size, p+1))&lt;br /&gt;
        X[:,1:] = np.array(Xtemp)[:,:p]&lt;br /&gt;
&lt;br /&gt;
        #OLS Estimate&lt;br /&gt;
        Phi = np.dot(np.dot(inv(np.dot(X.T,X)),X.T),Y)&lt;br /&gt;
        SigmaS = np.sum((Y - np.dot(X, Phi))**2.0)/(self.T-pmax)&lt;br /&gt;
        self.par[:-1] = Phi[:]&lt;br /&gt;
        self.par[-1] = SigmaS&lt;br /&gt;
&lt;br /&gt;
        #t-ratios&lt;br /&gt;
        self.VCOV = inv(np.dot(X.T,X))*SigmaS&lt;br /&gt;
        self.SE = np.diag(self.VCOV)**0.5&lt;br /&gt;
        self.t = self.par[:-1]/self.SE&lt;br /&gt;
&lt;br /&gt;
        #likelihood and IC&lt;br /&gt;
        self.logL = (-(self.T-pmax)/2.0)*np.log(2.0*np.pi) + (-(self.T-pmax)/2.0)*np.log(SigmaS) + (-(self.T-pmax)/2.0)&lt;br /&gt;
        self.AIC = 2.0*((self.par.size)-self.logL)&lt;br /&gt;
        self.BIC = np.log(Y.size)*self.par.size-2.0*self.logL&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Simulation.py ===&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import numpy as np&lt;br /&gt;
import models as mod&lt;br /&gt;
import matplotlib.pyplot as plt&lt;br /&gt;
from scipy.stats import norm&lt;br /&gt;
##########################&lt;br /&gt;
#Simulation and settings&lt;br /&gt;
#########################&lt;br /&gt;
#general&lt;br /&gt;
pmax = 10 # Maximum number of lags&lt;br /&gt;
n = 5000 # Number of simulations&lt;br /&gt;
T1 = 200 # Length of the first time series&lt;br /&gt;
T2 = 2000 # Length of the second time series&lt;br /&gt;
&lt;br /&gt;
#1. AR(1) process&lt;br /&gt;
#phi = 0.9&lt;br /&gt;
#mu = 5.0&lt;br /&gt;
#sigmaSq = 1.0&lt;br /&gt;
#X1 = mod.trajectories1(mu, phi, sigmaSq, T1, n)&lt;br /&gt;
#X2 = mod.trajectories1(mu, phi, sigmaSq, T2, n)&lt;br /&gt;
&lt;br /&gt;
#2. AR(2) process&lt;br /&gt;
phi1 = 0.4&lt;br /&gt;
phi2 = 0.4&lt;br /&gt;
mu = 5.0&lt;br /&gt;
sigmaSq = 1.0&lt;br /&gt;
X1 = mod.trajectories2(mu, phi1, phi2, sigmaSq, T1, n) # Rows = individual series; columns = time periods&lt;br /&gt;
X2 = mod.trajectories2(mu, phi1, phi2, sigmaSq, T2, n)&lt;br /&gt;
&lt;br /&gt;
#####&lt;br /&gt;
#GETS General to specific method&lt;br /&gt;
#####&lt;br /&gt;
tquantile = norm.ppf(0.95) #95% quantile&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop1 = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    p = pmax&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:],p,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;lt; tquantile and p&amp;gt;0:&lt;br /&gt;
            p-=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop1.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T1 finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop2 = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    p = pmax&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:],p,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;lt; tquantile and p&amp;gt;0:&lt;br /&gt;
            p-=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop2.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T2 finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
####################&lt;br /&gt;
#Specific-to-General&lt;br /&gt;
####################&lt;br /&gt;
tquantile = norm.ppf(0.95) #95% quantile&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop1SOG = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    p = 0&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:],p+1,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;gt; tquantile and p&amp;lt;=pmax:&lt;br /&gt;
            p+=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop1SOG.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T1 finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop2SOG = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    p = 0&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:],p+1,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;gt; tquantile and p&amp;lt;=pmax:&lt;br /&gt;
            p+=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop2SOG.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T2 finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
####################&lt;br /&gt;
#AIC and BIC&lt;br /&gt;
####################&lt;br /&gt;
#T1 simulation&lt;br /&gt;
AICp1 = []&lt;br /&gt;
BICp1 = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    AICtemp = np.zeros(11)&lt;br /&gt;
    BICtemp = np.zeros(11)&lt;br /&gt;
    for p in np.arange(pmax+1):&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:], p, pmax)&lt;br /&gt;
        AICtemp[p] = ARtemp.AIC&lt;br /&gt;
        BICtemp[p] = ARtemp.BIC&lt;br /&gt;
    AICp1.append(np.argmin(AICtemp))&lt;br /&gt;
    BICp1.append(np.argmin(BICtemp))&lt;br /&gt;
&lt;br /&gt;
print &amp;quot;T1 AIC+BIC finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
AICp2 = []&lt;br /&gt;
BICp2 = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    AICtemp = np.zeros(11)&lt;br /&gt;
    BICtemp = np.zeros(11)&lt;br /&gt;
    for p in np.arange(pmax+1):&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:], p, pmax)&lt;br /&gt;
        AICtemp[p] = ARtemp.AIC&lt;br /&gt;
        BICtemp[p] = ARtemp.BIC&lt;br /&gt;
    AICp2.append(np.argmin(AICtemp))&lt;br /&gt;
    BICp2.append(np.argmin(BICtemp))&lt;br /&gt;
print &amp;quot;T2 AIC+BIC finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
####################&lt;br /&gt;
#Plot&lt;br /&gt;
####################&lt;br /&gt;
&lt;br /&gt;
fig, axes = plt.subplots(nrows=4, ncols=2)&lt;br /&gt;
ax0, ax1, ax2, ax3, ax4, ax5, ax6, ax7 = axes.flatten()&lt;br /&gt;
&lt;br /&gt;
ax0.hist(tratiop1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax0.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax0.set_title('GETS, T=200')&lt;br /&gt;
&lt;br /&gt;
ax1.hist(tratiop2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax1.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax1.set_title('GETS, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax2.hist(tratiop1SOG, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax2.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax2.set_title('Spec-to-Gen, T=200')&lt;br /&gt;
&lt;br /&gt;
ax3.hist(tratiop2SOG, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax3.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax3.set_title('Spec-to-Gen, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax4.hist(AICp1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax4.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax4.set_title('AIC, T=200')&lt;br /&gt;
&lt;br /&gt;
ax5.hist(AICp2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax5.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax5.set_title('AIC, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax6.hist(BICp1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax6.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax6.set_title('BIC, T=200')&lt;br /&gt;
&lt;br /&gt;
ax7.hist(BICp2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax7.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax7.set_title('BIC, T=2000')&lt;br /&gt;
&lt;br /&gt;
fig.subplots_adjust(hspace=0.5)&lt;br /&gt;
plt.show()&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;/div&gt;</summary>
		<author><name>Hazn00</name></author>
		
	</entry>
	<entry>
		<id>http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19151</id>
		<title>Time Series Model Building Process</title>
		<link rel="alternate" type="text/html" href="http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19151"/>
		<updated>2020-01-19T14:08:29Z</updated>

		<summary type="html">&lt;p&gt;Hazn00: /* Results */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Linear time series models, e.g., ARIMA models for univariate time series, is a popular tool for modeling dynamics of time series and predicting the time series. The methodology is not popular only in statistics, econometrics and science, but also in machine learning business applications. The key question is how to build the model. We have to choose the form of the model, in particular number of lags for so-called autoregressive part (usually denoted as p) and moving average part of the model (usually denoted as d). The common guides usually provide a ‘cook book’ for model selection, see for example [https://www.machinelearningplus.com/time-series/arima-model-time-series-forecasting-python/, ARIMA Model – Complete Guide to Time Series Forecasting in Python] . This goal of this simulation is to compare four basic methods for selection of lags (p) for the autoregressive part.&lt;br /&gt;
&lt;br /&gt;
== Problem Definition ==&lt;br /&gt;
&lt;br /&gt;
The autoregressive process has form&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\phi}_2x_{t-2}+...+{\phi}_px_{t-p} + {\epsilon}_t&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;{\epsilon}_t \sim N(0,{\sigma}^2) &amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
However, we observe only the realized value and we do not know the hyperparameter p. Therefore, we must estimate it. The considered methods are following.&lt;br /&gt;
&lt;br /&gt;
=== GETS (General-to-Specific) ===&lt;br /&gt;
&lt;br /&gt;
We first start with high enough p (pmax in the code), and perform statistical test whether the last lag has statistically significant impact, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p = 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p \neq 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the impact is insignificant, we reduce p by one and continue until the parameter for the last lag is significant, i.e. last lag has significant effect.&lt;br /&gt;
&lt;br /&gt;
=== Specific-to-General ===&lt;br /&gt;
&lt;br /&gt;
The second approach works similarly as GETS, the only difference is that we first start with model without any lag, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and we are adding lags until they are significant.&lt;br /&gt;
&lt;br /&gt;
=== BIC (Bayesian Information Criteria) ===&lt;br /&gt;
&lt;br /&gt;
Bayesian information criteria is based on a likelihood of the model and number of parameters. The criteria punish the model for high number of parameters for a potential over-fitting, and rewards the model for good fit of the data. The lower the BIC value is, the better the model (a little bit counterintuitive definition). We are supposed to select a model with the lowest value of BIC.&lt;br /&gt;
&lt;br /&gt;
=== AIC (Akaike Information Criteria)  ===&lt;br /&gt;
&lt;br /&gt;
Works exactly the same as BIC, but the formula is slightly different.&lt;br /&gt;
&lt;br /&gt;
== Method and Simulation Method ==&lt;br /&gt;
&lt;br /&gt;
The solution consists of three key elements, data generating process, AR(p) model, and simulation.&lt;br /&gt;
&lt;br /&gt;
=== Data Generating Process ===&lt;br /&gt;
&lt;br /&gt;
To answer the question, which model selection method is the best, we are creating an artificial data. We assume that data are created by AR(1) process&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
or AR(2)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\mu} + {\phi}_2x_{t-2} + {\epsilon}_{t}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
with random error &amp;lt;math&amp;gt;&amp;lt;/math&amp;gt; . Therefore, we must generate random numbers for random errors, and iterate over the equations described above. The initial values of the processes, e.g., &amp;lt;math&amp;gt;x_0&amp;lt;/math&amp;gt;, are set to the theoretical mean value of the process.&lt;br /&gt;
&lt;br /&gt;
=== AR(p) model ===&lt;br /&gt;
&lt;br /&gt;
For a given series &amp;lt;math&amp;gt;{x_1,x_2,...x_T}&amp;lt;/math&amp;gt; with a length ''T'' estimates a model for a given p.&lt;br /&gt;
&lt;br /&gt;
=== Simulation ===&lt;br /&gt;
&lt;br /&gt;
Perform n Monte Carlo simulations, where in each simulation a the data generating process is used to create a time series. Then the AR(p) model is estimated for ''p=0,1,…,pmax'', and the best models are selected according to the selection criteria described above. Therefore, we will obtain four estimates of p that corresponds to the described methods for each of the n simulation. The final step is to compute % success of correctly estimated p for each of four methods.&lt;br /&gt;
&lt;br /&gt;
== Controls ==&lt;br /&gt;
The solution allow to set number of simulation n. We need high enough n to make sure that the results will converge close enough to actual results. Therefore, we have set &amp;lt;math&amp;gt;n=5000&amp;lt;/math&amp;gt;. Higher n will not significantly increase the precision of the results.&lt;br /&gt;
&lt;br /&gt;
The more important controls is selection of AR(1) or AR(2) process, and selection of parameters &amp;lt;math&amp;gt;{\mu},{\sigma},{\phi}_1&amp;lt;/math&amp;gt;  and  &amp;lt;math&amp;gt;{\phi}_2&amp;lt;/math&amp;gt; for the process. Additionally, we can set length of the generated series and even compare performance for series with two distinct lengths &amp;lt;math&amp;gt;T_1&amp;lt;/math&amp;gt; and &amp;lt;math&amp;gt;T_2&amp;lt;/math&amp;gt;. In other words, one method may perform better for low number of observations than other, and this control allow to compare the performance.&lt;br /&gt;
&lt;br /&gt;
== Results ==&lt;br /&gt;
&amp;lt;gallery&amp;gt;&lt;br /&gt;
File:Phi01.png|&amp;lt;math&amp;gt;{\Phi} = 0.1&amp;lt;/math&amp;gt;&lt;br /&gt;
File:Phi09.png|&amp;lt;math&amp;gt;{\Phi} = 0.9&amp;lt;/math&amp;gt;&lt;br /&gt;
File:Phi04Phi04.png|&amp;lt;math&amp;gt;{\Phi}_1= 0.4, {\Phi}_2 = 0.4&amp;lt;/math&amp;gt;&lt;br /&gt;
File:Phi00Phi09.png|&amp;lt;math&amp;gt;{\Phi}_1= 0.0, {\Phi}_2 = 0.9&amp;lt;/math&amp;gt;&lt;br /&gt;
&amp;lt;/gallery&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
&lt;br /&gt;
== Code ==&lt;br /&gt;
=== Models.py ===&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import numpy as np from numpy.linalg &lt;br /&gt;
import inv from scipy.stats &lt;br /&gt;
import norm&lt;br /&gt;
&lt;br /&gt;
def sim1(mu, phi1, sigmaSq, T):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates single trajectory.&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    x = np.zeros(T+1)&lt;br /&gt;
    epsilon = np.random.normal(0,sigmaSq, T+1)&lt;br /&gt;
&lt;br /&gt;
    x[0] = mu / (1.0 - phi1)&lt;br /&gt;
&lt;br /&gt;
    for t in np.arange(T):&lt;br /&gt;
        x[t+1] = mu + phi1 * x[t] + epsilon[t]&lt;br /&gt;
&lt;br /&gt;
    return x[1:]&lt;br /&gt;
&lt;br /&gt;
def trajectories1(mu, phi1, sigmaSq, T, n):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates n-trajectories of AR(1) process&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :param n:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    X = np.zeros([n,T])&lt;br /&gt;
    for s in np.arange(n):&lt;br /&gt;
        X[s,:] = sim1(mu, phi1, sigmaSq, T)&lt;br /&gt;
    return X&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
def sim2(mu, phi1, phi2, sigmaSq, T):&lt;br /&gt;
    x = np.zeros(T+2)&lt;br /&gt;
    epsilon = np.random.normal(0,sigmaSq, T+2)&lt;br /&gt;
&lt;br /&gt;
    x[0] = mu / (1.0 - phi1-phi2)&lt;br /&gt;
    x[1] = mu / (1.0 - phi1-phi2)&lt;br /&gt;
&lt;br /&gt;
    for t in np.arange(T)+1:&lt;br /&gt;
        x[t+1] = mu + phi1 * x[t] + phi2 * x[t-1] + epsilon[t]&lt;br /&gt;
&lt;br /&gt;
    return x[2:]&lt;br /&gt;
&lt;br /&gt;
def trajectories2(mu, phi1, phi2, sigmaSq, T, n):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates n-trajectories of AR(2) process&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param phi2:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :param n:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    X = np.zeros([n,T])&lt;br /&gt;
    for s in np.arange(n):&lt;br /&gt;
        X[s,:] = sim2(mu, phi1, phi2, sigmaSq, T)&lt;br /&gt;
    return X&lt;br /&gt;
&lt;br /&gt;
class ARp(object):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;AR(p) class allowing to estimate the model &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
    def __init__(self, x, p, pmax):&lt;br /&gt;
        self.p = p&lt;br /&gt;
        self.x = x&lt;br /&gt;
        self.T = float(x.size)&lt;br /&gt;
        self.par = np.zeros(p+2) #np.array: c, phi_1, phi_2, ... phi_p, sigma^2&lt;br /&gt;
&lt;br /&gt;
        #Init. matrices for OLS&lt;br /&gt;
        Y = self.x[pmax:]&lt;br /&gt;
        Xtemp = []&lt;br /&gt;
&lt;br /&gt;
        for i in np.arange(Y.size):&lt;br /&gt;
            Xtemp.append(np.flip(x[i:(pmax+i)],0))&lt;br /&gt;
        X = np.ones((Y.size, p+1))&lt;br /&gt;
        X[:,1:] = np.array(Xtemp)[:,:p]&lt;br /&gt;
&lt;br /&gt;
        #OLS Estimate&lt;br /&gt;
        Phi = np.dot(np.dot(inv(np.dot(X.T,X)),X.T),Y)&lt;br /&gt;
        SigmaS = np.sum((Y - np.dot(X, Phi))**2.0)/(self.T-pmax)&lt;br /&gt;
        self.par[:-1] = Phi[:]&lt;br /&gt;
        self.par[-1] = SigmaS&lt;br /&gt;
&lt;br /&gt;
        #t-ratios&lt;br /&gt;
        self.VCOV = inv(np.dot(X.T,X))*SigmaS&lt;br /&gt;
        self.SE = np.diag(self.VCOV)**0.5&lt;br /&gt;
        self.t = self.par[:-1]/self.SE&lt;br /&gt;
&lt;br /&gt;
        #likelihood and IC&lt;br /&gt;
        self.logL = (-(self.T-pmax)/2.0)*np.log(2.0*np.pi) + (-(self.T-pmax)/2.0)*np.log(SigmaS) + (-(self.T-pmax)/2.0)&lt;br /&gt;
        self.AIC = 2.0*((self.par.size)-self.logL)&lt;br /&gt;
        self.BIC = np.log(Y.size)*self.par.size-2.0*self.logL&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Simulation.py ===&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import numpy as np&lt;br /&gt;
import models as mod&lt;br /&gt;
import matplotlib.pyplot as plt&lt;br /&gt;
from scipy.stats import norm&lt;br /&gt;
##########################&lt;br /&gt;
#Simulation and settings&lt;br /&gt;
#########################&lt;br /&gt;
#general&lt;br /&gt;
pmax = 10 # Maximum number of lags&lt;br /&gt;
n = 5000 # Number of simulations&lt;br /&gt;
T1 = 200 # Length of the first time series&lt;br /&gt;
T2 = 2000 # Length of the second time series&lt;br /&gt;
&lt;br /&gt;
#1. AR(1) process&lt;br /&gt;
#phi = 0.9&lt;br /&gt;
#mu = 5.0&lt;br /&gt;
#sigmaSq = 1.0&lt;br /&gt;
#X1 = mod.trajectories1(mu, phi, sigmaSq, T1, n)&lt;br /&gt;
#X2 = mod.trajectories1(mu, phi, sigmaSq, T2, n)&lt;br /&gt;
&lt;br /&gt;
#2. AR(2) process&lt;br /&gt;
phi1 = 0.4&lt;br /&gt;
phi2 = 0.4&lt;br /&gt;
mu = 5.0&lt;br /&gt;
sigmaSq = 1.0&lt;br /&gt;
X1 = mod.trajectories2(mu, phi1, phi2, sigmaSq, T1, n) # Rows = individual series; columns = time periods&lt;br /&gt;
X2 = mod.trajectories2(mu, phi1, phi2, sigmaSq, T2, n)&lt;br /&gt;
&lt;br /&gt;
#####&lt;br /&gt;
#GETS General to specific method&lt;br /&gt;
#####&lt;br /&gt;
tquantile = norm.ppf(0.95) #95% quantile&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop1 = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    p = pmax&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:],p,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;lt; tquantile and p&amp;gt;0:&lt;br /&gt;
            p-=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop1.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T1 finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop2 = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    p = pmax&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:],p,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;lt; tquantile and p&amp;gt;0:&lt;br /&gt;
            p-=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop2.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T2 finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
####################&lt;br /&gt;
#Specific-to-General&lt;br /&gt;
####################&lt;br /&gt;
tquantile = norm.ppf(0.95) #95% quantile&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop1SOG = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    p = 0&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:],p+1,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;gt; tquantile and p&amp;lt;=pmax:&lt;br /&gt;
            p+=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop1SOG.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T1 finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop2SOG = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    p = 0&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:],p+1,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;gt; tquantile and p&amp;lt;=pmax:&lt;br /&gt;
            p+=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop2SOG.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T2 finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
####################&lt;br /&gt;
#AIC and BIC&lt;br /&gt;
####################&lt;br /&gt;
#T1 simulation&lt;br /&gt;
AICp1 = []&lt;br /&gt;
BICp1 = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    AICtemp = np.zeros(11)&lt;br /&gt;
    BICtemp = np.zeros(11)&lt;br /&gt;
    for p in np.arange(pmax+1):&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:], p, pmax)&lt;br /&gt;
        AICtemp[p] = ARtemp.AIC&lt;br /&gt;
        BICtemp[p] = ARtemp.BIC&lt;br /&gt;
    AICp1.append(np.argmin(AICtemp))&lt;br /&gt;
    BICp1.append(np.argmin(BICtemp))&lt;br /&gt;
&lt;br /&gt;
print &amp;quot;T1 AIC+BIC finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
AICp2 = []&lt;br /&gt;
BICp2 = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    AICtemp = np.zeros(11)&lt;br /&gt;
    BICtemp = np.zeros(11)&lt;br /&gt;
    for p in np.arange(pmax+1):&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:], p, pmax)&lt;br /&gt;
        AICtemp[p] = ARtemp.AIC&lt;br /&gt;
        BICtemp[p] = ARtemp.BIC&lt;br /&gt;
    AICp2.append(np.argmin(AICtemp))&lt;br /&gt;
    BICp2.append(np.argmin(BICtemp))&lt;br /&gt;
print &amp;quot;T2 AIC+BIC finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
####################&lt;br /&gt;
#Plot&lt;br /&gt;
####################&lt;br /&gt;
&lt;br /&gt;
fig, axes = plt.subplots(nrows=4, ncols=2)&lt;br /&gt;
ax0, ax1, ax2, ax3, ax4, ax5, ax6, ax7 = axes.flatten()&lt;br /&gt;
&lt;br /&gt;
ax0.hist(tratiop1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax0.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax0.set_title('GETS, T=200')&lt;br /&gt;
&lt;br /&gt;
ax1.hist(tratiop2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax1.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax1.set_title('GETS, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax2.hist(tratiop1SOG, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax2.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax2.set_title('Spec-to-Gen, T=200')&lt;br /&gt;
&lt;br /&gt;
ax3.hist(tratiop2SOG, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax3.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax3.set_title('Spec-to-Gen, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax4.hist(AICp1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax4.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax4.set_title('AIC, T=200')&lt;br /&gt;
&lt;br /&gt;
ax5.hist(AICp2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax5.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax5.set_title('AIC, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax6.hist(BICp1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax6.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax6.set_title('BIC, T=200')&lt;br /&gt;
&lt;br /&gt;
ax7.hist(BICp2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax7.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax7.set_title('BIC, T=2000')&lt;br /&gt;
&lt;br /&gt;
fig.subplots_adjust(hspace=0.5)&lt;br /&gt;
plt.show()&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;/div&gt;</summary>
		<author><name>Hazn00</name></author>
		
	</entry>
	<entry>
		<id>http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19150</id>
		<title>Time Series Model Building Process</title>
		<link rel="alternate" type="text/html" href="http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19150"/>
		<updated>2020-01-19T13:58:05Z</updated>

		<summary type="html">&lt;p&gt;Hazn00: /* Results */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Linear time series models, e.g., ARIMA models for univariate time series, is a popular tool for modeling dynamics of time series and predicting the time series. The methodology is not popular only in statistics, econometrics and science, but also in machine learning business applications. The key question is how to build the model. We have to choose the form of the model, in particular number of lags for so-called autoregressive part (usually denoted as p) and moving average part of the model (usually denoted as d). The common guides usually provide a ‘cook book’ for model selection, see for example [https://www.machinelearningplus.com/time-series/arima-model-time-series-forecasting-python/, ARIMA Model – Complete Guide to Time Series Forecasting in Python] . This goal of this simulation is to compare four basic methods for selection of lags (p) for the autoregressive part.&lt;br /&gt;
&lt;br /&gt;
== Problem Definition ==&lt;br /&gt;
&lt;br /&gt;
The autoregressive process has form&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\phi}_2x_{t-2}+...+{\phi}_px_{t-p} + {\epsilon}_t&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;{\epsilon}_t \sim N(0,{\sigma}^2) &amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
However, we observe only the realized value and we do not know the hyperparameter p. Therefore, we must estimate it. The considered methods are following.&lt;br /&gt;
&lt;br /&gt;
=== GETS (General-to-Specific) ===&lt;br /&gt;
&lt;br /&gt;
We first start with high enough p (pmax in the code), and perform statistical test whether the last lag has statistically significant impact, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p = 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p \neq 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the impact is insignificant, we reduce p by one and continue until the parameter for the last lag is significant, i.e. last lag has significant effect.&lt;br /&gt;
&lt;br /&gt;
=== Specific-to-General ===&lt;br /&gt;
&lt;br /&gt;
The second approach works similarly as GETS, the only difference is that we first start with model without any lag, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and we are adding lags until they are significant.&lt;br /&gt;
&lt;br /&gt;
=== BIC (Bayesian Information Criteria) ===&lt;br /&gt;
&lt;br /&gt;
Bayesian information criteria is based on a likelihood of the model and number of parameters. The criteria punish the model for high number of parameters for a potential over-fitting, and rewards the model for good fit of the data. The lower the BIC value is, the better the model (a little bit counterintuitive definition). We are supposed to select a model with the lowest value of BIC.&lt;br /&gt;
&lt;br /&gt;
=== AIC (Akaike Information Criteria)  ===&lt;br /&gt;
&lt;br /&gt;
Works exactly the same as BIC, but the formula is slightly different.&lt;br /&gt;
&lt;br /&gt;
== Method and Simulation Method ==&lt;br /&gt;
&lt;br /&gt;
The solution consists of three key elements, data generating process, AR(p) model, and simulation.&lt;br /&gt;
&lt;br /&gt;
=== Data Generating Process ===&lt;br /&gt;
&lt;br /&gt;
To answer the question, which model selection method is the best, we are creating an artificial data. We assume that data are created by AR(1) process&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
or AR(2)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\mu} + {\phi}_2x_{t-2} + {\epsilon}_{t}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
with random error &amp;lt;math&amp;gt;&amp;lt;/math&amp;gt; . Therefore, we must generate random numbers for random errors, and iterate over the equations described above. The initial values of the processes, e.g., &amp;lt;math&amp;gt;x_0&amp;lt;/math&amp;gt;, are set to the theoretical mean value of the process.&lt;br /&gt;
&lt;br /&gt;
=== AR(p) model ===&lt;br /&gt;
&lt;br /&gt;
For a given series &amp;lt;math&amp;gt;{x_1,x_2,...x_T}&amp;lt;/math&amp;gt; with a length ''T'' estimates a model for a given p.&lt;br /&gt;
&lt;br /&gt;
=== Simulation ===&lt;br /&gt;
&lt;br /&gt;
Perform n Monte Carlo simulations, where in each simulation a the data generating process is used to create a time series. Then the AR(p) model is estimated for ''p=0,1,…,pmax'', and the best models are selected according to the selection criteria described above. Therefore, we will obtain four estimates of p that corresponds to the described methods for each of the n simulation. The final step is to compute % success of correctly estimated p for each of four methods.&lt;br /&gt;
&lt;br /&gt;
== Controls ==&lt;br /&gt;
The solution allow to set number of simulation n. We need high enough n to make sure that the results will converge close enough to actual results. Therefore, we have set &amp;lt;math&amp;gt;n=5000&amp;lt;/math&amp;gt;. Higher n will not significantly increase the precision of the results.&lt;br /&gt;
&lt;br /&gt;
The more important controls is selection of AR(1) or AR(2) process, and selection of parameters &amp;lt;math&amp;gt;{\mu},{\sigma},{\phi}_1&amp;lt;/math&amp;gt;  and  &amp;lt;math&amp;gt;{\phi}_2&amp;lt;/math&amp;gt; for the process. Additionally, we can set length of the generated series and even compare performance for series with two distinct lengths &amp;lt;math&amp;gt;T_1&amp;lt;/math&amp;gt; and &amp;lt;math&amp;gt;T_2&amp;lt;/math&amp;gt;. In other words, one method may perform better for low number of observations than other, and this control allow to compare the performance.&lt;br /&gt;
&lt;br /&gt;
== Results ==&lt;br /&gt;
&amp;lt;gallery&amp;gt;&lt;br /&gt;
File:Phi01.png|&amp;lt;math&amp;gt;{\Phi} = 0.1&amp;lt;/math&amp;gt;&lt;br /&gt;
File:Phi09.png|&amp;lt;math&amp;gt;{\Phi} = 0.9&amp;lt;/math&amp;gt;&lt;br /&gt;
File:Phi04Phi04.png|&amp;lt;math&amp;gt;{\Phi}_1= 0.4, {\Phi}_2 = 0.4&amp;lt;/math&amp;gt;&lt;br /&gt;
File:Phi04Phi04.png|&amp;lt;math&amp;gt;{\Phi}_1= 0.0, {\Phi}_2 = 0.9&amp;lt;/math&amp;gt;&lt;br /&gt;
&amp;lt;/gallery&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
&lt;br /&gt;
== Code ==&lt;br /&gt;
=== Models.py ===&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import numpy as np from numpy.linalg &lt;br /&gt;
import inv from scipy.stats &lt;br /&gt;
import norm&lt;br /&gt;
&lt;br /&gt;
def sim1(mu, phi1, sigmaSq, T):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates single trajectory.&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    x = np.zeros(T+1)&lt;br /&gt;
    epsilon = np.random.normal(0,sigmaSq, T+1)&lt;br /&gt;
&lt;br /&gt;
    x[0] = mu / (1.0 - phi1)&lt;br /&gt;
&lt;br /&gt;
    for t in np.arange(T):&lt;br /&gt;
        x[t+1] = mu + phi1 * x[t] + epsilon[t]&lt;br /&gt;
&lt;br /&gt;
    return x[1:]&lt;br /&gt;
&lt;br /&gt;
def trajectories1(mu, phi1, sigmaSq, T, n):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates n-trajectories of AR(1) process&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :param n:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    X = np.zeros([n,T])&lt;br /&gt;
    for s in np.arange(n):&lt;br /&gt;
        X[s,:] = sim1(mu, phi1, sigmaSq, T)&lt;br /&gt;
    return X&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
def sim2(mu, phi1, phi2, sigmaSq, T):&lt;br /&gt;
    x = np.zeros(T+2)&lt;br /&gt;
    epsilon = np.random.normal(0,sigmaSq, T+2)&lt;br /&gt;
&lt;br /&gt;
    x[0] = mu / (1.0 - phi1-phi2)&lt;br /&gt;
    x[1] = mu / (1.0 - phi1-phi2)&lt;br /&gt;
&lt;br /&gt;
    for t in np.arange(T)+1:&lt;br /&gt;
        x[t+1] = mu + phi1 * x[t] + phi2 * x[t-1] + epsilon[t]&lt;br /&gt;
&lt;br /&gt;
    return x[2:]&lt;br /&gt;
&lt;br /&gt;
def trajectories2(mu, phi1, phi2, sigmaSq, T, n):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates n-trajectories of AR(2) process&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param phi2:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :param n:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    X = np.zeros([n,T])&lt;br /&gt;
    for s in np.arange(n):&lt;br /&gt;
        X[s,:] = sim2(mu, phi1, phi2, sigmaSq, T)&lt;br /&gt;
    return X&lt;br /&gt;
&lt;br /&gt;
class ARp(object):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;AR(p) class allowing to estimate the model &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
    def __init__(self, x, p, pmax):&lt;br /&gt;
        self.p = p&lt;br /&gt;
        self.x = x&lt;br /&gt;
        self.T = float(x.size)&lt;br /&gt;
        self.par = np.zeros(p+2) #np.array: c, phi_1, phi_2, ... phi_p, sigma^2&lt;br /&gt;
&lt;br /&gt;
        #Init. matrices for OLS&lt;br /&gt;
        Y = self.x[pmax:]&lt;br /&gt;
        Xtemp = []&lt;br /&gt;
&lt;br /&gt;
        for i in np.arange(Y.size):&lt;br /&gt;
            Xtemp.append(np.flip(x[i:(pmax+i)],0))&lt;br /&gt;
        X = np.ones((Y.size, p+1))&lt;br /&gt;
        X[:,1:] = np.array(Xtemp)[:,:p]&lt;br /&gt;
&lt;br /&gt;
        #OLS Estimate&lt;br /&gt;
        Phi = np.dot(np.dot(inv(np.dot(X.T,X)),X.T),Y)&lt;br /&gt;
        SigmaS = np.sum((Y - np.dot(X, Phi))**2.0)/(self.T-pmax)&lt;br /&gt;
        self.par[:-1] = Phi[:]&lt;br /&gt;
        self.par[-1] = SigmaS&lt;br /&gt;
&lt;br /&gt;
        #t-ratios&lt;br /&gt;
        self.VCOV = inv(np.dot(X.T,X))*SigmaS&lt;br /&gt;
        self.SE = np.diag(self.VCOV)**0.5&lt;br /&gt;
        self.t = self.par[:-1]/self.SE&lt;br /&gt;
&lt;br /&gt;
        #likelihood and IC&lt;br /&gt;
        self.logL = (-(self.T-pmax)/2.0)*np.log(2.0*np.pi) + (-(self.T-pmax)/2.0)*np.log(SigmaS) + (-(self.T-pmax)/2.0)&lt;br /&gt;
        self.AIC = 2.0*((self.par.size)-self.logL)&lt;br /&gt;
        self.BIC = np.log(Y.size)*self.par.size-2.0*self.logL&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Simulation.py ===&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import numpy as np&lt;br /&gt;
import models as mod&lt;br /&gt;
import matplotlib.pyplot as plt&lt;br /&gt;
from scipy.stats import norm&lt;br /&gt;
##########################&lt;br /&gt;
#Simulation and settings&lt;br /&gt;
#########################&lt;br /&gt;
#general&lt;br /&gt;
pmax = 10 # Maximum number of lags&lt;br /&gt;
n = 5000 # Number of simulations&lt;br /&gt;
T1 = 200 # Length of the first time series&lt;br /&gt;
T2 = 2000 # Length of the second time series&lt;br /&gt;
&lt;br /&gt;
#1. AR(1) process&lt;br /&gt;
#phi = 0.9&lt;br /&gt;
#mu = 5.0&lt;br /&gt;
#sigmaSq = 1.0&lt;br /&gt;
#X1 = mod.trajectories1(mu, phi, sigmaSq, T1, n)&lt;br /&gt;
#X2 = mod.trajectories1(mu, phi, sigmaSq, T2, n)&lt;br /&gt;
&lt;br /&gt;
#2. AR(2) process&lt;br /&gt;
phi1 = 0.4&lt;br /&gt;
phi2 = 0.4&lt;br /&gt;
mu = 5.0&lt;br /&gt;
sigmaSq = 1.0&lt;br /&gt;
X1 = mod.trajectories2(mu, phi1, phi2, sigmaSq, T1, n) # Rows = individual series; columns = time periods&lt;br /&gt;
X2 = mod.trajectories2(mu, phi1, phi2, sigmaSq, T2, n)&lt;br /&gt;
&lt;br /&gt;
#####&lt;br /&gt;
#GETS General to specific method&lt;br /&gt;
#####&lt;br /&gt;
tquantile = norm.ppf(0.95) #95% quantile&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop1 = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    p = pmax&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:],p,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;lt; tquantile and p&amp;gt;0:&lt;br /&gt;
            p-=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop1.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T1 finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop2 = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    p = pmax&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:],p,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;lt; tquantile and p&amp;gt;0:&lt;br /&gt;
            p-=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop2.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T2 finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
####################&lt;br /&gt;
#Specific-to-General&lt;br /&gt;
####################&lt;br /&gt;
tquantile = norm.ppf(0.95) #95% quantile&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop1SOG = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    p = 0&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:],p+1,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;gt; tquantile and p&amp;lt;=pmax:&lt;br /&gt;
            p+=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop1SOG.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T1 finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop2SOG = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    p = 0&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:],p+1,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;gt; tquantile and p&amp;lt;=pmax:&lt;br /&gt;
            p+=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop2SOG.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T2 finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
####################&lt;br /&gt;
#AIC and BIC&lt;br /&gt;
####################&lt;br /&gt;
#T1 simulation&lt;br /&gt;
AICp1 = []&lt;br /&gt;
BICp1 = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    AICtemp = np.zeros(11)&lt;br /&gt;
    BICtemp = np.zeros(11)&lt;br /&gt;
    for p in np.arange(pmax+1):&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:], p, pmax)&lt;br /&gt;
        AICtemp[p] = ARtemp.AIC&lt;br /&gt;
        BICtemp[p] = ARtemp.BIC&lt;br /&gt;
    AICp1.append(np.argmin(AICtemp))&lt;br /&gt;
    BICp1.append(np.argmin(BICtemp))&lt;br /&gt;
&lt;br /&gt;
print &amp;quot;T1 AIC+BIC finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
AICp2 = []&lt;br /&gt;
BICp2 = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    AICtemp = np.zeros(11)&lt;br /&gt;
    BICtemp = np.zeros(11)&lt;br /&gt;
    for p in np.arange(pmax+1):&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:], p, pmax)&lt;br /&gt;
        AICtemp[p] = ARtemp.AIC&lt;br /&gt;
        BICtemp[p] = ARtemp.BIC&lt;br /&gt;
    AICp2.append(np.argmin(AICtemp))&lt;br /&gt;
    BICp2.append(np.argmin(BICtemp))&lt;br /&gt;
print &amp;quot;T2 AIC+BIC finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
####################&lt;br /&gt;
#Plot&lt;br /&gt;
####################&lt;br /&gt;
&lt;br /&gt;
fig, axes = plt.subplots(nrows=4, ncols=2)&lt;br /&gt;
ax0, ax1, ax2, ax3, ax4, ax5, ax6, ax7 = axes.flatten()&lt;br /&gt;
&lt;br /&gt;
ax0.hist(tratiop1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax0.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax0.set_title('GETS, T=200')&lt;br /&gt;
&lt;br /&gt;
ax1.hist(tratiop2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax1.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax1.set_title('GETS, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax2.hist(tratiop1SOG, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax2.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax2.set_title('Spec-to-Gen, T=200')&lt;br /&gt;
&lt;br /&gt;
ax3.hist(tratiop2SOG, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax3.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax3.set_title('Spec-to-Gen, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax4.hist(AICp1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax4.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax4.set_title('AIC, T=200')&lt;br /&gt;
&lt;br /&gt;
ax5.hist(AICp2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax5.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax5.set_title('AIC, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax6.hist(BICp1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax6.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax6.set_title('BIC, T=200')&lt;br /&gt;
&lt;br /&gt;
ax7.hist(BICp2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax7.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax7.set_title('BIC, T=2000')&lt;br /&gt;
&lt;br /&gt;
fig.subplots_adjust(hspace=0.5)&lt;br /&gt;
plt.show()&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;/div&gt;</summary>
		<author><name>Hazn00</name></author>
		
	</entry>
	<entry>
		<id>http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19149</id>
		<title>Time Series Model Building Process</title>
		<link rel="alternate" type="text/html" href="http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19149"/>
		<updated>2020-01-19T13:55:38Z</updated>

		<summary type="html">&lt;p&gt;Hazn00: /* Results */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Linear time series models, e.g., ARIMA models for univariate time series, is a popular tool for modeling dynamics of time series and predicting the time series. The methodology is not popular only in statistics, econometrics and science, but also in machine learning business applications. The key question is how to build the model. We have to choose the form of the model, in particular number of lags for so-called autoregressive part (usually denoted as p) and moving average part of the model (usually denoted as d). The common guides usually provide a ‘cook book’ for model selection, see for example [https://www.machinelearningplus.com/time-series/arima-model-time-series-forecasting-python/, ARIMA Model – Complete Guide to Time Series Forecasting in Python] . This goal of this simulation is to compare four basic methods for selection of lags (p) for the autoregressive part.&lt;br /&gt;
&lt;br /&gt;
== Problem Definition ==&lt;br /&gt;
&lt;br /&gt;
The autoregressive process has form&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\phi}_2x_{t-2}+...+{\phi}_px_{t-p} + {\epsilon}_t&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;{\epsilon}_t \sim N(0,{\sigma}^2) &amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
However, we observe only the realized value and we do not know the hyperparameter p. Therefore, we must estimate it. The considered methods are following.&lt;br /&gt;
&lt;br /&gt;
=== GETS (General-to-Specific) ===&lt;br /&gt;
&lt;br /&gt;
We first start with high enough p (pmax in the code), and perform statistical test whether the last lag has statistically significant impact, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p = 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p \neq 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the impact is insignificant, we reduce p by one and continue until the parameter for the last lag is significant, i.e. last lag has significant effect.&lt;br /&gt;
&lt;br /&gt;
=== Specific-to-General ===&lt;br /&gt;
&lt;br /&gt;
The second approach works similarly as GETS, the only difference is that we first start with model without any lag, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and we are adding lags until they are significant.&lt;br /&gt;
&lt;br /&gt;
=== BIC (Bayesian Information Criteria) ===&lt;br /&gt;
&lt;br /&gt;
Bayesian information criteria is based on a likelihood of the model and number of parameters. The criteria punish the model for high number of parameters for a potential over-fitting, and rewards the model for good fit of the data. The lower the BIC value is, the better the model (a little bit counterintuitive definition). We are supposed to select a model with the lowest value of BIC.&lt;br /&gt;
&lt;br /&gt;
=== AIC (Akaike Information Criteria)  ===&lt;br /&gt;
&lt;br /&gt;
Works exactly the same as BIC, but the formula is slightly different.&lt;br /&gt;
&lt;br /&gt;
== Method and Simulation Method ==&lt;br /&gt;
&lt;br /&gt;
The solution consists of three key elements, data generating process, AR(p) model, and simulation.&lt;br /&gt;
&lt;br /&gt;
=== Data Generating Process ===&lt;br /&gt;
&lt;br /&gt;
To answer the question, which model selection method is the best, we are creating an artificial data. We assume that data are created by AR(1) process&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
or AR(2)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\mu} + {\phi}_2x_{t-2} + {\epsilon}_{t}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
with random error &amp;lt;math&amp;gt;&amp;lt;/math&amp;gt; . Therefore, we must generate random numbers for random errors, and iterate over the equations described above. The initial values of the processes, e.g., &amp;lt;math&amp;gt;x_0&amp;lt;/math&amp;gt;, are set to the theoretical mean value of the process.&lt;br /&gt;
&lt;br /&gt;
=== AR(p) model ===&lt;br /&gt;
&lt;br /&gt;
For a given series &amp;lt;math&amp;gt;{x_1,x_2,...x_T}&amp;lt;/math&amp;gt; with a length ''T'' estimates a model for a given p.&lt;br /&gt;
&lt;br /&gt;
=== Simulation ===&lt;br /&gt;
&lt;br /&gt;
Perform n Monte Carlo simulations, where in each simulation a the data generating process is used to create a time series. Then the AR(p) model is estimated for ''p=0,1,…,pmax'', and the best models are selected according to the selection criteria described above. Therefore, we will obtain four estimates of p that corresponds to the described methods for each of the n simulation. The final step is to compute % success of correctly estimated p for each of four methods.&lt;br /&gt;
&lt;br /&gt;
== Controls ==&lt;br /&gt;
The solution allow to set number of simulation n. We need high enough n to make sure that the results will converge close enough to actual results. Therefore, we have set &amp;lt;math&amp;gt;n=5000&amp;lt;/math&amp;gt;. Higher n will not significantly increase the precision of the results.&lt;br /&gt;
&lt;br /&gt;
The more important controls is selection of AR(1) or AR(2) process, and selection of parameters &amp;lt;math&amp;gt;{\mu},{\sigma},{\phi}_1&amp;lt;/math&amp;gt;  and  &amp;lt;math&amp;gt;{\phi}_2&amp;lt;/math&amp;gt; for the process. Additionally, we can set length of the generated series and even compare performance for series with two distinct lengths &amp;lt;math&amp;gt;T_1&amp;lt;/math&amp;gt; and &amp;lt;math&amp;gt;T_2&amp;lt;/math&amp;gt;. In other words, one method may perform better for low number of observations than other, and this control allow to compare the performance.&lt;br /&gt;
&lt;br /&gt;
== Results ==&lt;br /&gt;
&amp;lt;gallery&amp;gt;&lt;br /&gt;
File:Phi01.png|Phi = 0.1&lt;br /&gt;
File:Phi09.png|Phi = 0.9&lt;br /&gt;
File:Phi04Phi04.png|Phi1 = 0.4, Phi2 = 0.4&lt;br /&gt;
File:Phi04Phi04.png|Phi1 = 0.0, Phi2 = 0.9&lt;br /&gt;
&amp;lt;/gallery&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
&lt;br /&gt;
== Code ==&lt;br /&gt;
=== Models.py ===&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import numpy as np from numpy.linalg &lt;br /&gt;
import inv from scipy.stats &lt;br /&gt;
import norm&lt;br /&gt;
&lt;br /&gt;
def sim1(mu, phi1, sigmaSq, T):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates single trajectory.&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    x = np.zeros(T+1)&lt;br /&gt;
    epsilon = np.random.normal(0,sigmaSq, T+1)&lt;br /&gt;
&lt;br /&gt;
    x[0] = mu / (1.0 - phi1)&lt;br /&gt;
&lt;br /&gt;
    for t in np.arange(T):&lt;br /&gt;
        x[t+1] = mu + phi1 * x[t] + epsilon[t]&lt;br /&gt;
&lt;br /&gt;
    return x[1:]&lt;br /&gt;
&lt;br /&gt;
def trajectories1(mu, phi1, sigmaSq, T, n):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates n-trajectories of AR(1) process&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :param n:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    X = np.zeros([n,T])&lt;br /&gt;
    for s in np.arange(n):&lt;br /&gt;
        X[s,:] = sim1(mu, phi1, sigmaSq, T)&lt;br /&gt;
    return X&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
def sim2(mu, phi1, phi2, sigmaSq, T):&lt;br /&gt;
    x = np.zeros(T+2)&lt;br /&gt;
    epsilon = np.random.normal(0,sigmaSq, T+2)&lt;br /&gt;
&lt;br /&gt;
    x[0] = mu / (1.0 - phi1-phi2)&lt;br /&gt;
    x[1] = mu / (1.0 - phi1-phi2)&lt;br /&gt;
&lt;br /&gt;
    for t in np.arange(T)+1:&lt;br /&gt;
        x[t+1] = mu + phi1 * x[t] + phi2 * x[t-1] + epsilon[t]&lt;br /&gt;
&lt;br /&gt;
    return x[2:]&lt;br /&gt;
&lt;br /&gt;
def trajectories2(mu, phi1, phi2, sigmaSq, T, n):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates n-trajectories of AR(2) process&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param phi2:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :param n:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    X = np.zeros([n,T])&lt;br /&gt;
    for s in np.arange(n):&lt;br /&gt;
        X[s,:] = sim2(mu, phi1, phi2, sigmaSq, T)&lt;br /&gt;
    return X&lt;br /&gt;
&lt;br /&gt;
class ARp(object):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;AR(p) class allowing to estimate the model &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
    def __init__(self, x, p, pmax):&lt;br /&gt;
        self.p = p&lt;br /&gt;
        self.x = x&lt;br /&gt;
        self.T = float(x.size)&lt;br /&gt;
        self.par = np.zeros(p+2) #np.array: c, phi_1, phi_2, ... phi_p, sigma^2&lt;br /&gt;
&lt;br /&gt;
        #Init. matrices for OLS&lt;br /&gt;
        Y = self.x[pmax:]&lt;br /&gt;
        Xtemp = []&lt;br /&gt;
&lt;br /&gt;
        for i in np.arange(Y.size):&lt;br /&gt;
            Xtemp.append(np.flip(x[i:(pmax+i)],0))&lt;br /&gt;
        X = np.ones((Y.size, p+1))&lt;br /&gt;
        X[:,1:] = np.array(Xtemp)[:,:p]&lt;br /&gt;
&lt;br /&gt;
        #OLS Estimate&lt;br /&gt;
        Phi = np.dot(np.dot(inv(np.dot(X.T,X)),X.T),Y)&lt;br /&gt;
        SigmaS = np.sum((Y - np.dot(X, Phi))**2.0)/(self.T-pmax)&lt;br /&gt;
        self.par[:-1] = Phi[:]&lt;br /&gt;
        self.par[-1] = SigmaS&lt;br /&gt;
&lt;br /&gt;
        #t-ratios&lt;br /&gt;
        self.VCOV = inv(np.dot(X.T,X))*SigmaS&lt;br /&gt;
        self.SE = np.diag(self.VCOV)**0.5&lt;br /&gt;
        self.t = self.par[:-1]/self.SE&lt;br /&gt;
&lt;br /&gt;
        #likelihood and IC&lt;br /&gt;
        self.logL = (-(self.T-pmax)/2.0)*np.log(2.0*np.pi) + (-(self.T-pmax)/2.0)*np.log(SigmaS) + (-(self.T-pmax)/2.0)&lt;br /&gt;
        self.AIC = 2.0*((self.par.size)-self.logL)&lt;br /&gt;
        self.BIC = np.log(Y.size)*self.par.size-2.0*self.logL&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Simulation.py ===&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import numpy as np&lt;br /&gt;
import models as mod&lt;br /&gt;
import matplotlib.pyplot as plt&lt;br /&gt;
from scipy.stats import norm&lt;br /&gt;
##########################&lt;br /&gt;
#Simulation and settings&lt;br /&gt;
#########################&lt;br /&gt;
#general&lt;br /&gt;
pmax = 10 # Maximum number of lags&lt;br /&gt;
n = 5000 # Number of simulations&lt;br /&gt;
T1 = 200 # Length of the first time series&lt;br /&gt;
T2 = 2000 # Length of the second time series&lt;br /&gt;
&lt;br /&gt;
#1. AR(1) process&lt;br /&gt;
#phi = 0.9&lt;br /&gt;
#mu = 5.0&lt;br /&gt;
#sigmaSq = 1.0&lt;br /&gt;
#X1 = mod.trajectories1(mu, phi, sigmaSq, T1, n)&lt;br /&gt;
#X2 = mod.trajectories1(mu, phi, sigmaSq, T2, n)&lt;br /&gt;
&lt;br /&gt;
#2. AR(2) process&lt;br /&gt;
phi1 = 0.4&lt;br /&gt;
phi2 = 0.4&lt;br /&gt;
mu = 5.0&lt;br /&gt;
sigmaSq = 1.0&lt;br /&gt;
X1 = mod.trajectories2(mu, phi1, phi2, sigmaSq, T1, n) # Rows = individual series; columns = time periods&lt;br /&gt;
X2 = mod.trajectories2(mu, phi1, phi2, sigmaSq, T2, n)&lt;br /&gt;
&lt;br /&gt;
#####&lt;br /&gt;
#GETS General to specific method&lt;br /&gt;
#####&lt;br /&gt;
tquantile = norm.ppf(0.95) #95% quantile&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop1 = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    p = pmax&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:],p,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;lt; tquantile and p&amp;gt;0:&lt;br /&gt;
            p-=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop1.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T1 finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop2 = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    p = pmax&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:],p,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;lt; tquantile and p&amp;gt;0:&lt;br /&gt;
            p-=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop2.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T2 finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
####################&lt;br /&gt;
#Specific-to-General&lt;br /&gt;
####################&lt;br /&gt;
tquantile = norm.ppf(0.95) #95% quantile&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop1SOG = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    p = 0&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:],p+1,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;gt; tquantile and p&amp;lt;=pmax:&lt;br /&gt;
            p+=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop1SOG.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T1 finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop2SOG = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    p = 0&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:],p+1,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;gt; tquantile and p&amp;lt;=pmax:&lt;br /&gt;
            p+=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop2SOG.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T2 finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
####################&lt;br /&gt;
#AIC and BIC&lt;br /&gt;
####################&lt;br /&gt;
#T1 simulation&lt;br /&gt;
AICp1 = []&lt;br /&gt;
BICp1 = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    AICtemp = np.zeros(11)&lt;br /&gt;
    BICtemp = np.zeros(11)&lt;br /&gt;
    for p in np.arange(pmax+1):&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:], p, pmax)&lt;br /&gt;
        AICtemp[p] = ARtemp.AIC&lt;br /&gt;
        BICtemp[p] = ARtemp.BIC&lt;br /&gt;
    AICp1.append(np.argmin(AICtemp))&lt;br /&gt;
    BICp1.append(np.argmin(BICtemp))&lt;br /&gt;
&lt;br /&gt;
print &amp;quot;T1 AIC+BIC finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
AICp2 = []&lt;br /&gt;
BICp2 = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    AICtemp = np.zeros(11)&lt;br /&gt;
    BICtemp = np.zeros(11)&lt;br /&gt;
    for p in np.arange(pmax+1):&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:], p, pmax)&lt;br /&gt;
        AICtemp[p] = ARtemp.AIC&lt;br /&gt;
        BICtemp[p] = ARtemp.BIC&lt;br /&gt;
    AICp2.append(np.argmin(AICtemp))&lt;br /&gt;
    BICp2.append(np.argmin(BICtemp))&lt;br /&gt;
print &amp;quot;T2 AIC+BIC finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
####################&lt;br /&gt;
#Plot&lt;br /&gt;
####################&lt;br /&gt;
&lt;br /&gt;
fig, axes = plt.subplots(nrows=4, ncols=2)&lt;br /&gt;
ax0, ax1, ax2, ax3, ax4, ax5, ax6, ax7 = axes.flatten()&lt;br /&gt;
&lt;br /&gt;
ax0.hist(tratiop1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax0.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax0.set_title('GETS, T=200')&lt;br /&gt;
&lt;br /&gt;
ax1.hist(tratiop2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax1.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax1.set_title('GETS, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax2.hist(tratiop1SOG, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax2.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax2.set_title('Spec-to-Gen, T=200')&lt;br /&gt;
&lt;br /&gt;
ax3.hist(tratiop2SOG, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax3.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax3.set_title('Spec-to-Gen, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax4.hist(AICp1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax4.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax4.set_title('AIC, T=200')&lt;br /&gt;
&lt;br /&gt;
ax5.hist(AICp2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax5.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax5.set_title('AIC, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax6.hist(BICp1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax6.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax6.set_title('BIC, T=200')&lt;br /&gt;
&lt;br /&gt;
ax7.hist(BICp2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax7.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax7.set_title('BIC, T=2000')&lt;br /&gt;
&lt;br /&gt;
fig.subplots_adjust(hspace=0.5)&lt;br /&gt;
plt.show()&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;/div&gt;</summary>
		<author><name>Hazn00</name></author>
		
	</entry>
	<entry>
		<id>http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19148</id>
		<title>Time Series Model Building Process</title>
		<link rel="alternate" type="text/html" href="http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19148"/>
		<updated>2020-01-19T13:54:43Z</updated>

		<summary type="html">&lt;p&gt;Hazn00: /* Results */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Linear time series models, e.g., ARIMA models for univariate time series, is a popular tool for modeling dynamics of time series and predicting the time series. The methodology is not popular only in statistics, econometrics and science, but also in machine learning business applications. The key question is how to build the model. We have to choose the form of the model, in particular number of lags for so-called autoregressive part (usually denoted as p) and moving average part of the model (usually denoted as d). The common guides usually provide a ‘cook book’ for model selection, see for example [https://www.machinelearningplus.com/time-series/arima-model-time-series-forecasting-python/, ARIMA Model – Complete Guide to Time Series Forecasting in Python] . This goal of this simulation is to compare four basic methods for selection of lags (p) for the autoregressive part.&lt;br /&gt;
&lt;br /&gt;
== Problem Definition ==&lt;br /&gt;
&lt;br /&gt;
The autoregressive process has form&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\phi}_2x_{t-2}+...+{\phi}_px_{t-p} + {\epsilon}_t&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;{\epsilon}_t \sim N(0,{\sigma}^2) &amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
However, we observe only the realized value and we do not know the hyperparameter p. Therefore, we must estimate it. The considered methods are following.&lt;br /&gt;
&lt;br /&gt;
=== GETS (General-to-Specific) ===&lt;br /&gt;
&lt;br /&gt;
We first start with high enough p (pmax in the code), and perform statistical test whether the last lag has statistically significant impact, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p = 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p \neq 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the impact is insignificant, we reduce p by one and continue until the parameter for the last lag is significant, i.e. last lag has significant effect.&lt;br /&gt;
&lt;br /&gt;
=== Specific-to-General ===&lt;br /&gt;
&lt;br /&gt;
The second approach works similarly as GETS, the only difference is that we first start with model without any lag, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and we are adding lags until they are significant.&lt;br /&gt;
&lt;br /&gt;
=== BIC (Bayesian Information Criteria) ===&lt;br /&gt;
&lt;br /&gt;
Bayesian information criteria is based on a likelihood of the model and number of parameters. The criteria punish the model for high number of parameters for a potential over-fitting, and rewards the model for good fit of the data. The lower the BIC value is, the better the model (a little bit counterintuitive definition). We are supposed to select a model with the lowest value of BIC.&lt;br /&gt;
&lt;br /&gt;
=== AIC (Akaike Information Criteria)  ===&lt;br /&gt;
&lt;br /&gt;
Works exactly the same as BIC, but the formula is slightly different.&lt;br /&gt;
&lt;br /&gt;
== Method and Simulation Method ==&lt;br /&gt;
&lt;br /&gt;
The solution consists of three key elements, data generating process, AR(p) model, and simulation.&lt;br /&gt;
&lt;br /&gt;
=== Data Generating Process ===&lt;br /&gt;
&lt;br /&gt;
To answer the question, which model selection method is the best, we are creating an artificial data. We assume that data are created by AR(1) process&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
or AR(2)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\mu} + {\phi}_2x_{t-2} + {\epsilon}_{t}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
with random error &amp;lt;math&amp;gt;&amp;lt;/math&amp;gt; . Therefore, we must generate random numbers for random errors, and iterate over the equations described above. The initial values of the processes, e.g., &amp;lt;math&amp;gt;x_0&amp;lt;/math&amp;gt;, are set to the theoretical mean value of the process.&lt;br /&gt;
&lt;br /&gt;
=== AR(p) model ===&lt;br /&gt;
&lt;br /&gt;
For a given series &amp;lt;math&amp;gt;{x_1,x_2,...x_T}&amp;lt;/math&amp;gt; with a length ''T'' estimates a model for a given p.&lt;br /&gt;
&lt;br /&gt;
=== Simulation ===&lt;br /&gt;
&lt;br /&gt;
Perform n Monte Carlo simulations, where in each simulation a the data generating process is used to create a time series. Then the AR(p) model is estimated for ''p=0,1,…,pmax'', and the best models are selected according to the selection criteria described above. Therefore, we will obtain four estimates of p that corresponds to the described methods for each of the n simulation. The final step is to compute % success of correctly estimated p for each of four methods.&lt;br /&gt;
&lt;br /&gt;
== Controls ==&lt;br /&gt;
The solution allow to set number of simulation n. We need high enough n to make sure that the results will converge close enough to actual results. Therefore, we have set &amp;lt;math&amp;gt;n=5000&amp;lt;/math&amp;gt;. Higher n will not significantly increase the precision of the results.&lt;br /&gt;
&lt;br /&gt;
The more important controls is selection of AR(1) or AR(2) process, and selection of parameters &amp;lt;math&amp;gt;{\mu},{\sigma},{\phi}_1&amp;lt;/math&amp;gt;  and  &amp;lt;math&amp;gt;{\phi}_2&amp;lt;/math&amp;gt; for the process. Additionally, we can set length of the generated series and even compare performance for series with two distinct lengths &amp;lt;math&amp;gt;T_1&amp;lt;/math&amp;gt; and &amp;lt;math&amp;gt;T_2&amp;lt;/math&amp;gt;. In other words, one method may perform better for low number of observations than other, and this control allow to compare the performance.&lt;br /&gt;
&lt;br /&gt;
== Results ==&lt;br /&gt;
&amp;lt;gallery&amp;gt;&lt;br /&gt;
File:Phi01.png|Phi = 0.1&lt;br /&gt;
File:Phi09.png|Phi = 0.9&lt;br /&gt;
File:Phi04Phi04.png|Phi1 = 0.1&lt;br /&gt;
File:Phi04Phi04.png|Phi1 = 0.0, Phi2 = 0.9&lt;br /&gt;
&amp;lt;/gallery&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
&lt;br /&gt;
== Code ==&lt;br /&gt;
=== Models.py ===&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import numpy as np from numpy.linalg &lt;br /&gt;
import inv from scipy.stats &lt;br /&gt;
import norm&lt;br /&gt;
&lt;br /&gt;
def sim1(mu, phi1, sigmaSq, T):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates single trajectory.&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    x = np.zeros(T+1)&lt;br /&gt;
    epsilon = np.random.normal(0,sigmaSq, T+1)&lt;br /&gt;
&lt;br /&gt;
    x[0] = mu / (1.0 - phi1)&lt;br /&gt;
&lt;br /&gt;
    for t in np.arange(T):&lt;br /&gt;
        x[t+1] = mu + phi1 * x[t] + epsilon[t]&lt;br /&gt;
&lt;br /&gt;
    return x[1:]&lt;br /&gt;
&lt;br /&gt;
def trajectories1(mu, phi1, sigmaSq, T, n):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates n-trajectories of AR(1) process&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :param n:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    X = np.zeros([n,T])&lt;br /&gt;
    for s in np.arange(n):&lt;br /&gt;
        X[s,:] = sim1(mu, phi1, sigmaSq, T)&lt;br /&gt;
    return X&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
def sim2(mu, phi1, phi2, sigmaSq, T):&lt;br /&gt;
    x = np.zeros(T+2)&lt;br /&gt;
    epsilon = np.random.normal(0,sigmaSq, T+2)&lt;br /&gt;
&lt;br /&gt;
    x[0] = mu / (1.0 - phi1-phi2)&lt;br /&gt;
    x[1] = mu / (1.0 - phi1-phi2)&lt;br /&gt;
&lt;br /&gt;
    for t in np.arange(T)+1:&lt;br /&gt;
        x[t+1] = mu + phi1 * x[t] + phi2 * x[t-1] + epsilon[t]&lt;br /&gt;
&lt;br /&gt;
    return x[2:]&lt;br /&gt;
&lt;br /&gt;
def trajectories2(mu, phi1, phi2, sigmaSq, T, n):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates n-trajectories of AR(2) process&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param phi2:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :param n:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    X = np.zeros([n,T])&lt;br /&gt;
    for s in np.arange(n):&lt;br /&gt;
        X[s,:] = sim2(mu, phi1, phi2, sigmaSq, T)&lt;br /&gt;
    return X&lt;br /&gt;
&lt;br /&gt;
class ARp(object):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;AR(p) class allowing to estimate the model &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
    def __init__(self, x, p, pmax):&lt;br /&gt;
        self.p = p&lt;br /&gt;
        self.x = x&lt;br /&gt;
        self.T = float(x.size)&lt;br /&gt;
        self.par = np.zeros(p+2) #np.array: c, phi_1, phi_2, ... phi_p, sigma^2&lt;br /&gt;
&lt;br /&gt;
        #Init. matrices for OLS&lt;br /&gt;
        Y = self.x[pmax:]&lt;br /&gt;
        Xtemp = []&lt;br /&gt;
&lt;br /&gt;
        for i in np.arange(Y.size):&lt;br /&gt;
            Xtemp.append(np.flip(x[i:(pmax+i)],0))&lt;br /&gt;
        X = np.ones((Y.size, p+1))&lt;br /&gt;
        X[:,1:] = np.array(Xtemp)[:,:p]&lt;br /&gt;
&lt;br /&gt;
        #OLS Estimate&lt;br /&gt;
        Phi = np.dot(np.dot(inv(np.dot(X.T,X)),X.T),Y)&lt;br /&gt;
        SigmaS = np.sum((Y - np.dot(X, Phi))**2.0)/(self.T-pmax)&lt;br /&gt;
        self.par[:-1] = Phi[:]&lt;br /&gt;
        self.par[-1] = SigmaS&lt;br /&gt;
&lt;br /&gt;
        #t-ratios&lt;br /&gt;
        self.VCOV = inv(np.dot(X.T,X))*SigmaS&lt;br /&gt;
        self.SE = np.diag(self.VCOV)**0.5&lt;br /&gt;
        self.t = self.par[:-1]/self.SE&lt;br /&gt;
&lt;br /&gt;
        #likelihood and IC&lt;br /&gt;
        self.logL = (-(self.T-pmax)/2.0)*np.log(2.0*np.pi) + (-(self.T-pmax)/2.0)*np.log(SigmaS) + (-(self.T-pmax)/2.0)&lt;br /&gt;
        self.AIC = 2.0*((self.par.size)-self.logL)&lt;br /&gt;
        self.BIC = np.log(Y.size)*self.par.size-2.0*self.logL&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Simulation.py ===&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import numpy as np&lt;br /&gt;
import models as mod&lt;br /&gt;
import matplotlib.pyplot as plt&lt;br /&gt;
from scipy.stats import norm&lt;br /&gt;
##########################&lt;br /&gt;
#Simulation and settings&lt;br /&gt;
#########################&lt;br /&gt;
#general&lt;br /&gt;
pmax = 10 # Maximum number of lags&lt;br /&gt;
n = 5000 # Number of simulations&lt;br /&gt;
T1 = 200 # Length of the first time series&lt;br /&gt;
T2 = 2000 # Length of the second time series&lt;br /&gt;
&lt;br /&gt;
#1. AR(1) process&lt;br /&gt;
#phi = 0.9&lt;br /&gt;
#mu = 5.0&lt;br /&gt;
#sigmaSq = 1.0&lt;br /&gt;
#X1 = mod.trajectories1(mu, phi, sigmaSq, T1, n)&lt;br /&gt;
#X2 = mod.trajectories1(mu, phi, sigmaSq, T2, n)&lt;br /&gt;
&lt;br /&gt;
#2. AR(2) process&lt;br /&gt;
phi1 = 0.4&lt;br /&gt;
phi2 = 0.4&lt;br /&gt;
mu = 5.0&lt;br /&gt;
sigmaSq = 1.0&lt;br /&gt;
X1 = mod.trajectories2(mu, phi1, phi2, sigmaSq, T1, n) # Rows = individual series; columns = time periods&lt;br /&gt;
X2 = mod.trajectories2(mu, phi1, phi2, sigmaSq, T2, n)&lt;br /&gt;
&lt;br /&gt;
#####&lt;br /&gt;
#GETS General to specific method&lt;br /&gt;
#####&lt;br /&gt;
tquantile = norm.ppf(0.95) #95% quantile&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop1 = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    p = pmax&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:],p,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;lt; tquantile and p&amp;gt;0:&lt;br /&gt;
            p-=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop1.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T1 finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop2 = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    p = pmax&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:],p,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;lt; tquantile and p&amp;gt;0:&lt;br /&gt;
            p-=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop2.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T2 finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
####################&lt;br /&gt;
#Specific-to-General&lt;br /&gt;
####################&lt;br /&gt;
tquantile = norm.ppf(0.95) #95% quantile&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop1SOG = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    p = 0&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:],p+1,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;gt; tquantile and p&amp;lt;=pmax:&lt;br /&gt;
            p+=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop1SOG.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T1 finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop2SOG = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    p = 0&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:],p+1,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;gt; tquantile and p&amp;lt;=pmax:&lt;br /&gt;
            p+=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop2SOG.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T2 finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
####################&lt;br /&gt;
#AIC and BIC&lt;br /&gt;
####################&lt;br /&gt;
#T1 simulation&lt;br /&gt;
AICp1 = []&lt;br /&gt;
BICp1 = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    AICtemp = np.zeros(11)&lt;br /&gt;
    BICtemp = np.zeros(11)&lt;br /&gt;
    for p in np.arange(pmax+1):&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:], p, pmax)&lt;br /&gt;
        AICtemp[p] = ARtemp.AIC&lt;br /&gt;
        BICtemp[p] = ARtemp.BIC&lt;br /&gt;
    AICp1.append(np.argmin(AICtemp))&lt;br /&gt;
    BICp1.append(np.argmin(BICtemp))&lt;br /&gt;
&lt;br /&gt;
print &amp;quot;T1 AIC+BIC finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
AICp2 = []&lt;br /&gt;
BICp2 = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    AICtemp = np.zeros(11)&lt;br /&gt;
    BICtemp = np.zeros(11)&lt;br /&gt;
    for p in np.arange(pmax+1):&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:], p, pmax)&lt;br /&gt;
        AICtemp[p] = ARtemp.AIC&lt;br /&gt;
        BICtemp[p] = ARtemp.BIC&lt;br /&gt;
    AICp2.append(np.argmin(AICtemp))&lt;br /&gt;
    BICp2.append(np.argmin(BICtemp))&lt;br /&gt;
print &amp;quot;T2 AIC+BIC finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
####################&lt;br /&gt;
#Plot&lt;br /&gt;
####################&lt;br /&gt;
&lt;br /&gt;
fig, axes = plt.subplots(nrows=4, ncols=2)&lt;br /&gt;
ax0, ax1, ax2, ax3, ax4, ax5, ax6, ax7 = axes.flatten()&lt;br /&gt;
&lt;br /&gt;
ax0.hist(tratiop1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax0.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax0.set_title('GETS, T=200')&lt;br /&gt;
&lt;br /&gt;
ax1.hist(tratiop2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax1.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax1.set_title('GETS, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax2.hist(tratiop1SOG, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax2.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax2.set_title('Spec-to-Gen, T=200')&lt;br /&gt;
&lt;br /&gt;
ax3.hist(tratiop2SOG, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax3.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax3.set_title('Spec-to-Gen, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax4.hist(AICp1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax4.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax4.set_title('AIC, T=200')&lt;br /&gt;
&lt;br /&gt;
ax5.hist(AICp2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax5.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax5.set_title('AIC, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax6.hist(BICp1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax6.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax6.set_title('BIC, T=200')&lt;br /&gt;
&lt;br /&gt;
ax7.hist(BICp2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax7.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax7.set_title('BIC, T=2000')&lt;br /&gt;
&lt;br /&gt;
fig.subplots_adjust(hspace=0.5)&lt;br /&gt;
plt.show()&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;/div&gt;</summary>
		<author><name>Hazn00</name></author>
		
	</entry>
	<entry>
		<id>http://www.simulace.info/index.php?title=File:Phi00Phi09.png&amp;diff=19147</id>
		<title>File:Phi00Phi09.png</title>
		<link rel="alternate" type="text/html" href="http://www.simulace.info/index.php?title=File:Phi00Phi09.png&amp;diff=19147"/>
		<updated>2020-01-19T13:49:32Z</updated>

		<summary type="html">&lt;p&gt;Hazn00: Phi1 = 0.0
Phi2 = 0.9&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Summary ==&lt;br /&gt;
Phi1 = 0.0&lt;br /&gt;
Phi2 = 0.9&lt;/div&gt;</summary>
		<author><name>Hazn00</name></author>
		
	</entry>
	<entry>
		<id>http://www.simulace.info/index.php?title=File:Phi04Phi04.png&amp;diff=19146</id>
		<title>File:Phi04Phi04.png</title>
		<link rel="alternate" type="text/html" href="http://www.simulace.info/index.php?title=File:Phi04Phi04.png&amp;diff=19146"/>
		<updated>2020-01-19T13:48:00Z</updated>

		<summary type="html">&lt;p&gt;Hazn00: Phi1 = 0.4
Phi2 = 0.4&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Summary ==&lt;br /&gt;
Phi1 = 0.4&lt;br /&gt;
Phi2 = 0.4&lt;/div&gt;</summary>
		<author><name>Hazn00</name></author>
		
	</entry>
	<entry>
		<id>http://www.simulace.info/index.php?title=File:Phi09.png&amp;diff=19145</id>
		<title>File:Phi09.png</title>
		<link rel="alternate" type="text/html" href="http://www.simulace.info/index.php?title=File:Phi09.png&amp;diff=19145"/>
		<updated>2020-01-19T13:46:15Z</updated>

		<summary type="html">&lt;p&gt;Hazn00: Phi = 0.9&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Summary ==&lt;br /&gt;
Phi = 0.9&lt;/div&gt;</summary>
		<author><name>Hazn00</name></author>
		
	</entry>
	<entry>
		<id>http://www.simulace.info/index.php?title=File:Phi01.png&amp;diff=19144</id>
		<title>File:Phi01.png</title>
		<link rel="alternate" type="text/html" href="http://www.simulace.info/index.php?title=File:Phi01.png&amp;diff=19144"/>
		<updated>2020-01-19T13:43:27Z</updated>

		<summary type="html">&lt;p&gt;Hazn00: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Hazn00</name></author>
		
	</entry>
	<entry>
		<id>http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19143</id>
		<title>Time Series Model Building Process</title>
		<link rel="alternate" type="text/html" href="http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19143"/>
		<updated>2020-01-19T13:40:36Z</updated>

		<summary type="html">&lt;p&gt;Hazn00: /* Simulation */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Linear time series models, e.g., ARIMA models for univariate time series, is a popular tool for modeling dynamics of time series and predicting the time series. The methodology is not popular only in statistics, econometrics and science, but also in machine learning business applications. The key question is how to build the model. We have to choose the form of the model, in particular number of lags for so-called autoregressive part (usually denoted as p) and moving average part of the model (usually denoted as d). The common guides usually provide a ‘cook book’ for model selection, see for example [https://www.machinelearningplus.com/time-series/arima-model-time-series-forecasting-python/, ARIMA Model – Complete Guide to Time Series Forecasting in Python] . This goal of this simulation is to compare four basic methods for selection of lags (p) for the autoregressive part.&lt;br /&gt;
&lt;br /&gt;
== Problem Definition ==&lt;br /&gt;
&lt;br /&gt;
The autoregressive process has form&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\phi}_2x_{t-2}+...+{\phi}_px_{t-p} + {\epsilon}_t&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;{\epsilon}_t \sim N(0,{\sigma}^2) &amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
However, we observe only the realized value and we do not know the hyperparameter p. Therefore, we must estimate it. The considered methods are following.&lt;br /&gt;
&lt;br /&gt;
=== GETS (General-to-Specific) ===&lt;br /&gt;
&lt;br /&gt;
We first start with high enough p (pmax in the code), and perform statistical test whether the last lag has statistically significant impact, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p = 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p \neq 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the impact is insignificant, we reduce p by one and continue until the parameter for the last lag is significant, i.e. last lag has significant effect.&lt;br /&gt;
&lt;br /&gt;
=== Specific-to-General ===&lt;br /&gt;
&lt;br /&gt;
The second approach works similarly as GETS, the only difference is that we first start with model without any lag, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and we are adding lags until they are significant.&lt;br /&gt;
&lt;br /&gt;
=== BIC (Bayesian Information Criteria) ===&lt;br /&gt;
&lt;br /&gt;
Bayesian information criteria is based on a likelihood of the model and number of parameters. The criteria punish the model for high number of parameters for a potential over-fitting, and rewards the model for good fit of the data. The lower the BIC value is, the better the model (a little bit counterintuitive definition). We are supposed to select a model with the lowest value of BIC.&lt;br /&gt;
&lt;br /&gt;
=== AIC (Akaike Information Criteria)  ===&lt;br /&gt;
&lt;br /&gt;
Works exactly the same as BIC, but the formula is slightly different.&lt;br /&gt;
&lt;br /&gt;
== Method and Simulation Method ==&lt;br /&gt;
&lt;br /&gt;
The solution consists of three key elements, data generating process, AR(p) model, and simulation.&lt;br /&gt;
&lt;br /&gt;
=== Data Generating Process ===&lt;br /&gt;
&lt;br /&gt;
To answer the question, which model selection method is the best, we are creating an artificial data. We assume that data are created by AR(1) process&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
or AR(2)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\mu} + {\phi}_2x_{t-2} + {\epsilon}_{t}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
with random error &amp;lt;math&amp;gt;&amp;lt;/math&amp;gt; . Therefore, we must generate random numbers for random errors, and iterate over the equations described above. The initial values of the processes, e.g., &amp;lt;math&amp;gt;x_0&amp;lt;/math&amp;gt;, are set to the theoretical mean value of the process.&lt;br /&gt;
&lt;br /&gt;
=== AR(p) model ===&lt;br /&gt;
&lt;br /&gt;
For a given series &amp;lt;math&amp;gt;{x_1,x_2,...x_T}&amp;lt;/math&amp;gt; with a length ''T'' estimates a model for a given p.&lt;br /&gt;
&lt;br /&gt;
=== Simulation ===&lt;br /&gt;
&lt;br /&gt;
Perform n Monte Carlo simulations, where in each simulation a the data generating process is used to create a time series. Then the AR(p) model is estimated for ''p=0,1,…,pmax'', and the best models are selected according to the selection criteria described above. Therefore, we will obtain four estimates of p that corresponds to the described methods for each of the n simulation. The final step is to compute % success of correctly estimated p for each of four methods.&lt;br /&gt;
&lt;br /&gt;
== Controls ==&lt;br /&gt;
The solution allow to set number of simulation n. We need high enough n to make sure that the results will converge close enough to actual results. Therefore, we have set &amp;lt;math&amp;gt;n=5000&amp;lt;/math&amp;gt;. Higher n will not significantly increase the precision of the results.&lt;br /&gt;
&lt;br /&gt;
The more important controls is selection of AR(1) or AR(2) process, and selection of parameters &amp;lt;math&amp;gt;{\mu},{\sigma},{\phi}_1&amp;lt;/math&amp;gt;  and  &amp;lt;math&amp;gt;{\phi}_2&amp;lt;/math&amp;gt; for the process. Additionally, we can set length of the generated series and even compare performance for series with two distinct lengths &amp;lt;math&amp;gt;T_1&amp;lt;/math&amp;gt; and &amp;lt;math&amp;gt;T_2&amp;lt;/math&amp;gt;. In other words, one method may perform better for low number of observations than other, and this control allow to compare the performance.&lt;br /&gt;
&lt;br /&gt;
== Results ==&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
&lt;br /&gt;
== Code ==&lt;br /&gt;
=== Models.py ===&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import numpy as np from numpy.linalg &lt;br /&gt;
import inv from scipy.stats &lt;br /&gt;
import norm&lt;br /&gt;
&lt;br /&gt;
def sim1(mu, phi1, sigmaSq, T):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates single trajectory.&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    x = np.zeros(T+1)&lt;br /&gt;
    epsilon = np.random.normal(0,sigmaSq, T+1)&lt;br /&gt;
&lt;br /&gt;
    x[0] = mu / (1.0 - phi1)&lt;br /&gt;
&lt;br /&gt;
    for t in np.arange(T):&lt;br /&gt;
        x[t+1] = mu + phi1 * x[t] + epsilon[t]&lt;br /&gt;
&lt;br /&gt;
    return x[1:]&lt;br /&gt;
&lt;br /&gt;
def trajectories1(mu, phi1, sigmaSq, T, n):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates n-trajectories of AR(1) process&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :param n:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    X = np.zeros([n,T])&lt;br /&gt;
    for s in np.arange(n):&lt;br /&gt;
        X[s,:] = sim1(mu, phi1, sigmaSq, T)&lt;br /&gt;
    return X&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
def sim2(mu, phi1, phi2, sigmaSq, T):&lt;br /&gt;
    x = np.zeros(T+2)&lt;br /&gt;
    epsilon = np.random.normal(0,sigmaSq, T+2)&lt;br /&gt;
&lt;br /&gt;
    x[0] = mu / (1.0 - phi1-phi2)&lt;br /&gt;
    x[1] = mu / (1.0 - phi1-phi2)&lt;br /&gt;
&lt;br /&gt;
    for t in np.arange(T)+1:&lt;br /&gt;
        x[t+1] = mu + phi1 * x[t] + phi2 * x[t-1] + epsilon[t]&lt;br /&gt;
&lt;br /&gt;
    return x[2:]&lt;br /&gt;
&lt;br /&gt;
def trajectories2(mu, phi1, phi2, sigmaSq, T, n):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates n-trajectories of AR(2) process&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param phi2:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :param n:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    X = np.zeros([n,T])&lt;br /&gt;
    for s in np.arange(n):&lt;br /&gt;
        X[s,:] = sim2(mu, phi1, phi2, sigmaSq, T)&lt;br /&gt;
    return X&lt;br /&gt;
&lt;br /&gt;
class ARp(object):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;AR(p) class allowing to estimate the model &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
    def __init__(self, x, p, pmax):&lt;br /&gt;
        self.p = p&lt;br /&gt;
        self.x = x&lt;br /&gt;
        self.T = float(x.size)&lt;br /&gt;
        self.par = np.zeros(p+2) #np.array: c, phi_1, phi_2, ... phi_p, sigma^2&lt;br /&gt;
&lt;br /&gt;
        #Init. matrices for OLS&lt;br /&gt;
        Y = self.x[pmax:]&lt;br /&gt;
        Xtemp = []&lt;br /&gt;
&lt;br /&gt;
        for i in np.arange(Y.size):&lt;br /&gt;
            Xtemp.append(np.flip(x[i:(pmax+i)],0))&lt;br /&gt;
        X = np.ones((Y.size, p+1))&lt;br /&gt;
        X[:,1:] = np.array(Xtemp)[:,:p]&lt;br /&gt;
&lt;br /&gt;
        #OLS Estimate&lt;br /&gt;
        Phi = np.dot(np.dot(inv(np.dot(X.T,X)),X.T),Y)&lt;br /&gt;
        SigmaS = np.sum((Y - np.dot(X, Phi))**2.0)/(self.T-pmax)&lt;br /&gt;
        self.par[:-1] = Phi[:]&lt;br /&gt;
        self.par[-1] = SigmaS&lt;br /&gt;
&lt;br /&gt;
        #t-ratios&lt;br /&gt;
        self.VCOV = inv(np.dot(X.T,X))*SigmaS&lt;br /&gt;
        self.SE = np.diag(self.VCOV)**0.5&lt;br /&gt;
        self.t = self.par[:-1]/self.SE&lt;br /&gt;
&lt;br /&gt;
        #likelihood and IC&lt;br /&gt;
        self.logL = (-(self.T-pmax)/2.0)*np.log(2.0*np.pi) + (-(self.T-pmax)/2.0)*np.log(SigmaS) + (-(self.T-pmax)/2.0)&lt;br /&gt;
        self.AIC = 2.0*((self.par.size)-self.logL)&lt;br /&gt;
        self.BIC = np.log(Y.size)*self.par.size-2.0*self.logL&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Simulation.py ===&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import numpy as np&lt;br /&gt;
import models as mod&lt;br /&gt;
import matplotlib.pyplot as plt&lt;br /&gt;
from scipy.stats import norm&lt;br /&gt;
##########################&lt;br /&gt;
#Simulation and settings&lt;br /&gt;
#########################&lt;br /&gt;
#general&lt;br /&gt;
pmax = 10 # Maximum number of lags&lt;br /&gt;
n = 5000 # Number of simulations&lt;br /&gt;
T1 = 200 # Length of the first time series&lt;br /&gt;
T2 = 2000 # Length of the second time series&lt;br /&gt;
&lt;br /&gt;
#1. AR(1) process&lt;br /&gt;
#phi = 0.9&lt;br /&gt;
#mu = 5.0&lt;br /&gt;
#sigmaSq = 1.0&lt;br /&gt;
#X1 = mod.trajectories1(mu, phi, sigmaSq, T1, n)&lt;br /&gt;
#X2 = mod.trajectories1(mu, phi, sigmaSq, T2, n)&lt;br /&gt;
&lt;br /&gt;
#2. AR(2) process&lt;br /&gt;
phi1 = 0.4&lt;br /&gt;
phi2 = 0.4&lt;br /&gt;
mu = 5.0&lt;br /&gt;
sigmaSq = 1.0&lt;br /&gt;
X1 = mod.trajectories2(mu, phi1, phi2, sigmaSq, T1, n) # Rows = individual series; columns = time periods&lt;br /&gt;
X2 = mod.trajectories2(mu, phi1, phi2, sigmaSq, T2, n)&lt;br /&gt;
&lt;br /&gt;
#####&lt;br /&gt;
#GETS General to specific method&lt;br /&gt;
#####&lt;br /&gt;
tquantile = norm.ppf(0.95) #95% quantile&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop1 = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    p = pmax&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:],p,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;lt; tquantile and p&amp;gt;0:&lt;br /&gt;
            p-=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop1.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T1 finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop2 = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    p = pmax&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:],p,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;lt; tquantile and p&amp;gt;0:&lt;br /&gt;
            p-=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop2.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T2 finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
####################&lt;br /&gt;
#Specific-to-General&lt;br /&gt;
####################&lt;br /&gt;
tquantile = norm.ppf(0.95) #95% quantile&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop1SOG = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    p = 0&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:],p+1,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;gt; tquantile and p&amp;lt;=pmax:&lt;br /&gt;
            p+=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop1SOG.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T1 finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop2SOG = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    p = 0&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:],p+1,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;gt; tquantile and p&amp;lt;=pmax:&lt;br /&gt;
            p+=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop2SOG.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T2 finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
####################&lt;br /&gt;
#AIC and BIC&lt;br /&gt;
####################&lt;br /&gt;
#T1 simulation&lt;br /&gt;
AICp1 = []&lt;br /&gt;
BICp1 = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    AICtemp = np.zeros(11)&lt;br /&gt;
    BICtemp = np.zeros(11)&lt;br /&gt;
    for p in np.arange(pmax+1):&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:], p, pmax)&lt;br /&gt;
        AICtemp[p] = ARtemp.AIC&lt;br /&gt;
        BICtemp[p] = ARtemp.BIC&lt;br /&gt;
    AICp1.append(np.argmin(AICtemp))&lt;br /&gt;
    BICp1.append(np.argmin(BICtemp))&lt;br /&gt;
&lt;br /&gt;
print &amp;quot;T1 AIC+BIC finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
AICp2 = []&lt;br /&gt;
BICp2 = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    AICtemp = np.zeros(11)&lt;br /&gt;
    BICtemp = np.zeros(11)&lt;br /&gt;
    for p in np.arange(pmax+1):&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:], p, pmax)&lt;br /&gt;
        AICtemp[p] = ARtemp.AIC&lt;br /&gt;
        BICtemp[p] = ARtemp.BIC&lt;br /&gt;
    AICp2.append(np.argmin(AICtemp))&lt;br /&gt;
    BICp2.append(np.argmin(BICtemp))&lt;br /&gt;
print &amp;quot;T2 AIC+BIC finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
####################&lt;br /&gt;
#Plot&lt;br /&gt;
####################&lt;br /&gt;
&lt;br /&gt;
fig, axes = plt.subplots(nrows=4, ncols=2)&lt;br /&gt;
ax0, ax1, ax2, ax3, ax4, ax5, ax6, ax7 = axes.flatten()&lt;br /&gt;
&lt;br /&gt;
ax0.hist(tratiop1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax0.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax0.set_title('GETS, T=200')&lt;br /&gt;
&lt;br /&gt;
ax1.hist(tratiop2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax1.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax1.set_title('GETS, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax2.hist(tratiop1SOG, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax2.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax2.set_title('Spec-to-Gen, T=200')&lt;br /&gt;
&lt;br /&gt;
ax3.hist(tratiop2SOG, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax3.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax3.set_title('Spec-to-Gen, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax4.hist(AICp1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax4.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax4.set_title('AIC, T=200')&lt;br /&gt;
&lt;br /&gt;
ax5.hist(AICp2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax5.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax5.set_title('AIC, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax6.hist(BICp1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax6.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax6.set_title('BIC, T=200')&lt;br /&gt;
&lt;br /&gt;
ax7.hist(BICp2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax7.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax7.set_title('BIC, T=2000')&lt;br /&gt;
&lt;br /&gt;
fig.subplots_adjust(hspace=0.5)&lt;br /&gt;
plt.show()&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;/div&gt;</summary>
		<author><name>Hazn00</name></author>
		
	</entry>
	<entry>
		<id>http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19142</id>
		<title>Time Series Model Building Process</title>
		<link rel="alternate" type="text/html" href="http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19142"/>
		<updated>2020-01-19T13:39:28Z</updated>

		<summary type="html">&lt;p&gt;Hazn00: /* Models.py */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Linear time series models, e.g., ARIMA models for univariate time series, is a popular tool for modeling dynamics of time series and predicting the time series. The methodology is not popular only in statistics, econometrics and science, but also in machine learning business applications. The key question is how to build the model. We have to choose the form of the model, in particular number of lags for so-called autoregressive part (usually denoted as p) and moving average part of the model (usually denoted as d). The common guides usually provide a ‘cook book’ for model selection, see for example [https://www.machinelearningplus.com/time-series/arima-model-time-series-forecasting-python/, ARIMA Model – Complete Guide to Time Series Forecasting in Python] . This goal of this simulation is to compare four basic methods for selection of lags (p) for the autoregressive part.&lt;br /&gt;
&lt;br /&gt;
== Problem Definition ==&lt;br /&gt;
&lt;br /&gt;
The autoregressive process has form&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\phi}_2x_{t-2}+...+{\phi}_px_{t-p} + {\epsilon}_t&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;{\epsilon}_t \sim N(0,{\sigma}^2) &amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
However, we observe only the realized value and we do not know the hyperparameter p. Therefore, we must estimate it. The considered methods are following.&lt;br /&gt;
&lt;br /&gt;
=== GETS (General-to-Specific) ===&lt;br /&gt;
&lt;br /&gt;
We first start with high enough p (pmax in the code), and perform statistical test whether the last lag has statistically significant impact, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p = 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p \neq 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the impact is insignificant, we reduce p by one and continue until the parameter for the last lag is significant, i.e. last lag has significant effect.&lt;br /&gt;
&lt;br /&gt;
=== Specific-to-General ===&lt;br /&gt;
&lt;br /&gt;
The second approach works similarly as GETS, the only difference is that we first start with model without any lag, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and we are adding lags until they are significant.&lt;br /&gt;
&lt;br /&gt;
=== BIC (Bayesian Information Criteria) ===&lt;br /&gt;
&lt;br /&gt;
Bayesian information criteria is based on a likelihood of the model and number of parameters. The criteria punish the model for high number of parameters for a potential over-fitting, and rewards the model for good fit of the data. The lower the BIC value is, the better the model (a little bit counterintuitive definition). We are supposed to select a model with the lowest value of BIC.&lt;br /&gt;
&lt;br /&gt;
=== AIC (Akaike Information Criteria)  ===&lt;br /&gt;
&lt;br /&gt;
Works exactly the same as BIC, but the formula is slightly different.&lt;br /&gt;
&lt;br /&gt;
== Method and Simulation Method ==&lt;br /&gt;
&lt;br /&gt;
The solution consists of three key elements, data generating process, AR(p) model, and simulation.&lt;br /&gt;
&lt;br /&gt;
=== Data Generating Process ===&lt;br /&gt;
&lt;br /&gt;
To answer the question, which model selection method is the best, we are creating an artificial data. We assume that data are created by AR(1) process&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
or AR(2)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\mu} + {\phi}_2x_{t-2} + {\epsilon}_{t}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
with random error &amp;lt;math&amp;gt;&amp;lt;/math&amp;gt; . Therefore, we must generate random numbers for random errors, and iterate over the equations described above. The initial values of the processes, e.g., &amp;lt;math&amp;gt;x_0&amp;lt;/math&amp;gt;, are set to the theoretical mean value of the process.&lt;br /&gt;
&lt;br /&gt;
=== AR(p) model ===&lt;br /&gt;
&lt;br /&gt;
For a given series &amp;lt;math&amp;gt;{x_1,x_2,...x_T}&amp;lt;/math&amp;gt; with a length ''T'' estimates a model for a given p.&lt;br /&gt;
&lt;br /&gt;
=== Simulation ===&lt;br /&gt;
&lt;br /&gt;
Perform n Monte Carlo simulations, where in each simulation a the data generating process is used to create a time series. Then the AR(p) model is estimated for ''p=0,1,…,pmax'', and the best models are selected according to the selection criteria described above. Therefore, we will obtain four estimates of p that corresponds to the described methods for each of the n simulation. The final step is to compute % success of correctly estimated p for each of four methods.&lt;br /&gt;
&lt;br /&gt;
== Controls ==&lt;br /&gt;
The solution allow to set number of simulation n. We need high enough n to make sure that the results will converge close enough to actual results. Therefore, we have set &amp;lt;math&amp;gt;n=5000&amp;lt;/math&amp;gt;. Higher n will not significantly increase the precision of the results.&lt;br /&gt;
&lt;br /&gt;
The more important controls is selection of AR(1) or AR(2) process, and selection of parameters &amp;lt;math&amp;gt;{\mu},{\sigma},{\phi}_1&amp;lt;/math&amp;gt;  and  &amp;lt;math&amp;gt;{\phi}_2&amp;lt;/math&amp;gt; for the process. Additionally, we can set length of the generated series and even compare performance for series with two distinct lengths &amp;lt;math&amp;gt;T_1&amp;lt;/math&amp;gt; and &amp;lt;math&amp;gt;T_2&amp;lt;/math&amp;gt;. In other words, one method may perform better for low number of observations than other, and this control allow to compare the performance.&lt;br /&gt;
&lt;br /&gt;
== Results ==&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
&lt;br /&gt;
== Code ==&lt;br /&gt;
=== Models.py ===&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import numpy as np from numpy.linalg &lt;br /&gt;
import inv from scipy.stats &lt;br /&gt;
import norm&lt;br /&gt;
&lt;br /&gt;
def sim1(mu, phi1, sigmaSq, T):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates single trajectory.&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    x = np.zeros(T+1)&lt;br /&gt;
    epsilon = np.random.normal(0,sigmaSq, T+1)&lt;br /&gt;
&lt;br /&gt;
    x[0] = mu / (1.0 - phi1)&lt;br /&gt;
&lt;br /&gt;
    for t in np.arange(T):&lt;br /&gt;
        x[t+1] = mu + phi1 * x[t] + epsilon[t]&lt;br /&gt;
&lt;br /&gt;
    return x[1:]&lt;br /&gt;
&lt;br /&gt;
def trajectories1(mu, phi1, sigmaSq, T, n):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates n-trajectories of AR(1) process&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :param n:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    X = np.zeros([n,T])&lt;br /&gt;
    for s in np.arange(n):&lt;br /&gt;
        X[s,:] = sim1(mu, phi1, sigmaSq, T)&lt;br /&gt;
    return X&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
def sim2(mu, phi1, phi2, sigmaSq, T):&lt;br /&gt;
    x = np.zeros(T+2)&lt;br /&gt;
    epsilon = np.random.normal(0,sigmaSq, T+2)&lt;br /&gt;
&lt;br /&gt;
    x[0] = mu / (1.0 - phi1-phi2)&lt;br /&gt;
    x[1] = mu / (1.0 - phi1-phi2)&lt;br /&gt;
&lt;br /&gt;
    for t in np.arange(T)+1:&lt;br /&gt;
        x[t+1] = mu + phi1 * x[t] + phi2 * x[t-1] + epsilon[t]&lt;br /&gt;
&lt;br /&gt;
    return x[2:]&lt;br /&gt;
&lt;br /&gt;
def trajectories2(mu, phi1, phi2, sigmaSq, T, n):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates n-trajectories of AR(2) process&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param phi2:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :param n:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    X = np.zeros([n,T])&lt;br /&gt;
    for s in np.arange(n):&lt;br /&gt;
        X[s,:] = sim2(mu, phi1, phi2, sigmaSq, T)&lt;br /&gt;
    return X&lt;br /&gt;
&lt;br /&gt;
class ARp(object):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;AR(p) class allowing to estimate the model &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
    def __init__(self, x, p, pmax):&lt;br /&gt;
        self.p = p&lt;br /&gt;
        self.x = x&lt;br /&gt;
        self.T = float(x.size)&lt;br /&gt;
        self.par = np.zeros(p+2) #np.array: c, phi_1, phi_2, ... phi_p, sigma^2&lt;br /&gt;
&lt;br /&gt;
        #Init. matrices for OLS&lt;br /&gt;
        Y = self.x[pmax:]&lt;br /&gt;
        Xtemp = []&lt;br /&gt;
&lt;br /&gt;
        for i in np.arange(Y.size):&lt;br /&gt;
            Xtemp.append(np.flip(x[i:(pmax+i)],0))&lt;br /&gt;
        X = np.ones((Y.size, p+1))&lt;br /&gt;
        X[:,1:] = np.array(Xtemp)[:,:p]&lt;br /&gt;
&lt;br /&gt;
        #OLS Estimate&lt;br /&gt;
        Phi = np.dot(np.dot(inv(np.dot(X.T,X)),X.T),Y)&lt;br /&gt;
        SigmaS = np.sum((Y - np.dot(X, Phi))**2.0)/(self.T-pmax)&lt;br /&gt;
        self.par[:-1] = Phi[:]&lt;br /&gt;
        self.par[-1] = SigmaS&lt;br /&gt;
&lt;br /&gt;
        #t-ratios&lt;br /&gt;
        self.VCOV = inv(np.dot(X.T,X))*SigmaS&lt;br /&gt;
        self.SE = np.diag(self.VCOV)**0.5&lt;br /&gt;
        self.t = self.par[:-1]/self.SE&lt;br /&gt;
&lt;br /&gt;
        #likelihood and IC&lt;br /&gt;
        self.logL = (-(self.T-pmax)/2.0)*np.log(2.0*np.pi) + (-(self.T-pmax)/2.0)*np.log(SigmaS) + (-(self.T-pmax)/2.0)&lt;br /&gt;
        self.AIC = 2.0*((self.par.size)-self.logL)&lt;br /&gt;
        self.BIC = np.log(Y.size)*self.par.size-2.0*self.logL&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Simulation ===&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import numpy as np&lt;br /&gt;
import models as mod&lt;br /&gt;
import matplotlib.pyplot as plt&lt;br /&gt;
from scipy.stats import norm&lt;br /&gt;
pmax = 10&lt;br /&gt;
n = 5000&lt;br /&gt;
T1 = 200 &lt;br /&gt;
T2 = 2000 &lt;br /&gt;
#1. AR(1) process&lt;br /&gt;
#phi = 0.9&lt;br /&gt;
#mu = 5.0&lt;br /&gt;
#sigmaSq = 1.0&lt;br /&gt;
#X1 = mod.trajectories1(mu, phi, sigmaSq, T1, n)&lt;br /&gt;
#X2 = mod.trajectories1(mu, phi, sigmaSq, T2, n)&lt;br /&gt;
#2. AR(2) process&lt;br /&gt;
phi1 = 0.4&lt;br /&gt;
phi2 = 0.4&lt;br /&gt;
mu = 5.0&lt;br /&gt;
sigmaSq = 1.0&lt;br /&gt;
X1 = mod.trajectories2(mu, phi1, phi2, sigmaSq, T1, n) # Rows = individual series; columns = time periods&lt;br /&gt;
X2 = mod.trajectories2(mu, phi1, phi2, sigmaSq, T2, n)&lt;br /&gt;
&lt;br /&gt;
#####&lt;br /&gt;
#GETS General to specific method&lt;br /&gt;
#####&lt;br /&gt;
tquantile = norm.ppf(0.95) #95% quantile&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop1 = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    p = pmax&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:],p,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;lt; tquantile and p&amp;gt;0:&lt;br /&gt;
            p-=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop1.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T1 finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop2 = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    p = pmax&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:],p,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;lt; tquantile and p&amp;gt;0:&lt;br /&gt;
            p-=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop2.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T2 finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#Specific-to-General&lt;br /&gt;
&lt;br /&gt;
tquantile = norm.ppf(0.95) #95% quantile&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop1SOG = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    p = 0&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:],p+1,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;gt; tquantile and p&amp;lt;=pmax:&lt;br /&gt;
            p+=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop1SOG.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T1 finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop2SOG = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    p = 0&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:],p+1,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;gt; tquantile and p&amp;lt;=pmax:&lt;br /&gt;
            p+=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop2SOG.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T2 finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#AIC and BIC&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
AICp1 = []&lt;br /&gt;
BICp1 = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    AICtemp = np.zeros(11)&lt;br /&gt;
    BICtemp = np.zeros(11)&lt;br /&gt;
    for p in np.arange(pmax+1):&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:], p, pmax)&lt;br /&gt;
        AICtemp[p] = ARtemp.AIC&lt;br /&gt;
        BICtemp[p] = ARtemp.BIC&lt;br /&gt;
    AICp1.append(np.argmin(AICtemp))&lt;br /&gt;
    BICp1.append(np.argmin(BICtemp))&lt;br /&gt;
&lt;br /&gt;
print &amp;quot;T1 AIC+BIC finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
AICp2 = []&lt;br /&gt;
BICp2 = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    AICtemp = np.zeros(11)&lt;br /&gt;
    BICtemp = np.zeros(11)&lt;br /&gt;
    for p in np.arange(pmax+1):&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:], p, pmax)&lt;br /&gt;
        AICtemp[p] = ARtemp.AIC&lt;br /&gt;
        BICtemp[p] = ARtemp.BIC&lt;br /&gt;
    AICp2.append(np.argmin(AICtemp))&lt;br /&gt;
    BICp2.append(np.argmin(BICtemp))&lt;br /&gt;
print &amp;quot;T2 AIC+BIC finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#Plot&lt;br /&gt;
&lt;br /&gt;
fig, axes = plt.subplots(nrows=4, ncols=2)&lt;br /&gt;
ax0, ax1, ax2, ax3, ax4, ax5, ax6, ax7 = axes.flatten()&lt;br /&gt;
&lt;br /&gt;
ax0.hist(tratiop1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax0.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax0.set_title('GETS, T=200')&lt;br /&gt;
&lt;br /&gt;
ax1.hist(tratiop2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax1.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax1.set_title('GETS, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax2.hist(tratiop1SOG, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax2.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax2.set_title('Spec-to-Gen, T=200')&lt;br /&gt;
&lt;br /&gt;
ax3.hist(tratiop2SOG, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax3.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax3.set_title('Spec-to-Gen, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax4.hist(AICp1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax4.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax4.set_title('AIC, T=200')&lt;br /&gt;
&lt;br /&gt;
ax5.hist(AICp2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax5.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax5.set_title('AIC, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax6.hist(BICp1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax6.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax6.set_title('BIC, T=200')&lt;br /&gt;
&lt;br /&gt;
ax7.hist(BICp2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax7.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax7.set_title('BIC, T=2000')&lt;br /&gt;
&lt;br /&gt;
fig.subplots_adjust(hspace=0.5)&lt;br /&gt;
plt.show()&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;/div&gt;</summary>
		<author><name>Hazn00</name></author>
		
	</entry>
	<entry>
		<id>http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19141</id>
		<title>Time Series Model Building Process</title>
		<link rel="alternate" type="text/html" href="http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19141"/>
		<updated>2020-01-19T13:38:56Z</updated>

		<summary type="html">&lt;p&gt;Hazn00: /* Model */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Linear time series models, e.g., ARIMA models for univariate time series, is a popular tool for modeling dynamics of time series and predicting the time series. The methodology is not popular only in statistics, econometrics and science, but also in machine learning business applications. The key question is how to build the model. We have to choose the form of the model, in particular number of lags for so-called autoregressive part (usually denoted as p) and moving average part of the model (usually denoted as d). The common guides usually provide a ‘cook book’ for model selection, see for example [https://www.machinelearningplus.com/time-series/arima-model-time-series-forecasting-python/, ARIMA Model – Complete Guide to Time Series Forecasting in Python] . This goal of this simulation is to compare four basic methods for selection of lags (p) for the autoregressive part.&lt;br /&gt;
&lt;br /&gt;
== Problem Definition ==&lt;br /&gt;
&lt;br /&gt;
The autoregressive process has form&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\phi}_2x_{t-2}+...+{\phi}_px_{t-p} + {\epsilon}_t&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;{\epsilon}_t \sim N(0,{\sigma}^2) &amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
However, we observe only the realized value and we do not know the hyperparameter p. Therefore, we must estimate it. The considered methods are following.&lt;br /&gt;
&lt;br /&gt;
=== GETS (General-to-Specific) ===&lt;br /&gt;
&lt;br /&gt;
We first start with high enough p (pmax in the code), and perform statistical test whether the last lag has statistically significant impact, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p = 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p \neq 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the impact is insignificant, we reduce p by one and continue until the parameter for the last lag is significant, i.e. last lag has significant effect.&lt;br /&gt;
&lt;br /&gt;
=== Specific-to-General ===&lt;br /&gt;
&lt;br /&gt;
The second approach works similarly as GETS, the only difference is that we first start with model without any lag, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and we are adding lags until they are significant.&lt;br /&gt;
&lt;br /&gt;
=== BIC (Bayesian Information Criteria) ===&lt;br /&gt;
&lt;br /&gt;
Bayesian information criteria is based on a likelihood of the model and number of parameters. The criteria punish the model for high number of parameters for a potential over-fitting, and rewards the model for good fit of the data. The lower the BIC value is, the better the model (a little bit counterintuitive definition). We are supposed to select a model with the lowest value of BIC.&lt;br /&gt;
&lt;br /&gt;
=== AIC (Akaike Information Criteria)  ===&lt;br /&gt;
&lt;br /&gt;
Works exactly the same as BIC, but the formula is slightly different.&lt;br /&gt;
&lt;br /&gt;
== Method and Simulation Method ==&lt;br /&gt;
&lt;br /&gt;
The solution consists of three key elements, data generating process, AR(p) model, and simulation.&lt;br /&gt;
&lt;br /&gt;
=== Data Generating Process ===&lt;br /&gt;
&lt;br /&gt;
To answer the question, which model selection method is the best, we are creating an artificial data. We assume that data are created by AR(1) process&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
or AR(2)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\mu} + {\phi}_2x_{t-2} + {\epsilon}_{t}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
with random error &amp;lt;math&amp;gt;&amp;lt;/math&amp;gt; . Therefore, we must generate random numbers for random errors, and iterate over the equations described above. The initial values of the processes, e.g., &amp;lt;math&amp;gt;x_0&amp;lt;/math&amp;gt;, are set to the theoretical mean value of the process.&lt;br /&gt;
&lt;br /&gt;
=== AR(p) model ===&lt;br /&gt;
&lt;br /&gt;
For a given series &amp;lt;math&amp;gt;{x_1,x_2,...x_T}&amp;lt;/math&amp;gt; with a length ''T'' estimates a model for a given p.&lt;br /&gt;
&lt;br /&gt;
=== Simulation ===&lt;br /&gt;
&lt;br /&gt;
Perform n Monte Carlo simulations, where in each simulation a the data generating process is used to create a time series. Then the AR(p) model is estimated for ''p=0,1,…,pmax'', and the best models are selected according to the selection criteria described above. Therefore, we will obtain four estimates of p that corresponds to the described methods for each of the n simulation. The final step is to compute % success of correctly estimated p for each of four methods.&lt;br /&gt;
&lt;br /&gt;
== Controls ==&lt;br /&gt;
The solution allow to set number of simulation n. We need high enough n to make sure that the results will converge close enough to actual results. Therefore, we have set &amp;lt;math&amp;gt;n=5000&amp;lt;/math&amp;gt;. Higher n will not significantly increase the precision of the results.&lt;br /&gt;
&lt;br /&gt;
The more important controls is selection of AR(1) or AR(2) process, and selection of parameters &amp;lt;math&amp;gt;{\mu},{\sigma},{\phi}_1&amp;lt;/math&amp;gt;  and  &amp;lt;math&amp;gt;{\phi}_2&amp;lt;/math&amp;gt; for the process. Additionally, we can set length of the generated series and even compare performance for series with two distinct lengths &amp;lt;math&amp;gt;T_1&amp;lt;/math&amp;gt; and &amp;lt;math&amp;gt;T_2&amp;lt;/math&amp;gt;. In other words, one method may perform better for low number of observations than other, and this control allow to compare the performance.&lt;br /&gt;
&lt;br /&gt;
== Results ==&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
&lt;br /&gt;
== Code ==&lt;br /&gt;
=== Models.py ===&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import numpy as np&lt;br /&gt;
from numpy.linalg import inv&lt;br /&gt;
from scipy.stats import norm&lt;br /&gt;
&lt;br /&gt;
def sim1(mu, phi1, sigmaSq, T):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates single trajectory.&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    x = np.zeros(T+1)&lt;br /&gt;
    epsilon = np.random.normal(0,sigmaSq, T+1)&lt;br /&gt;
&lt;br /&gt;
    x[0] = mu / (1.0 - phi1)&lt;br /&gt;
&lt;br /&gt;
    for t in np.arange(T):&lt;br /&gt;
        x[t+1] = mu + phi1 * x[t] + epsilon[t]&lt;br /&gt;
&lt;br /&gt;
    return x[1:]&lt;br /&gt;
&lt;br /&gt;
def trajectories1(mu, phi1, sigmaSq, T, n):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates n-trajectories of AR(1) process&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :param n:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    X = np.zeros([n,T])&lt;br /&gt;
    for s in np.arange(n):&lt;br /&gt;
        X[s,:] = sim1(mu, phi1, sigmaSq, T)&lt;br /&gt;
    return X&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
def sim2(mu, phi1, phi2, sigmaSq, T):&lt;br /&gt;
    x = np.zeros(T+2)&lt;br /&gt;
    epsilon = np.random.normal(0,sigmaSq, T+2)&lt;br /&gt;
&lt;br /&gt;
    x[0] = mu / (1.0 - phi1-phi2)&lt;br /&gt;
    x[1] = mu / (1.0 - phi1-phi2)&lt;br /&gt;
&lt;br /&gt;
    for t in np.arange(T)+1:&lt;br /&gt;
        x[t+1] = mu + phi1 * x[t] + phi2 * x[t-1] + epsilon[t]&lt;br /&gt;
&lt;br /&gt;
    return x[2:]&lt;br /&gt;
&lt;br /&gt;
def trajectories2(mu, phi1, phi2, sigmaSq, T, n):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates n-trajectories of AR(2) process&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param phi2:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :param n:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    X = np.zeros([n,T])&lt;br /&gt;
    for s in np.arange(n):&lt;br /&gt;
        X[s,:] = sim2(mu, phi1, phi2, sigmaSq, T)&lt;br /&gt;
    return X&lt;br /&gt;
&lt;br /&gt;
class ARp(object):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;AR(p) class allowing to estimate the model &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
    def __init__(self, x, p, pmax):&lt;br /&gt;
        self.p = p&lt;br /&gt;
        self.x = x&lt;br /&gt;
        self.T = float(x.size)&lt;br /&gt;
        self.par = np.zeros(p+2) #np.array: c, phi_1, phi_2, ... phi_p, sigma^2&lt;br /&gt;
&lt;br /&gt;
        #Init. matrices for OLS&lt;br /&gt;
        Y = self.x[pmax:]&lt;br /&gt;
        Xtemp = []&lt;br /&gt;
&lt;br /&gt;
        for i in np.arange(Y.size):&lt;br /&gt;
            Xtemp.append(np.flip(x[i:(pmax+i)],0))&lt;br /&gt;
        X = np.ones((Y.size, p+1))&lt;br /&gt;
        X[:,1:] = np.array(Xtemp)[:,:p]&lt;br /&gt;
&lt;br /&gt;
        #OLS Estimate&lt;br /&gt;
        Phi = np.dot(np.dot(inv(np.dot(X.T,X)),X.T),Y)&lt;br /&gt;
        SigmaS = np.sum((Y - np.dot(X, Phi))**2.0)/(self.T-pmax)&lt;br /&gt;
        self.par[:-1] = Phi[:]&lt;br /&gt;
        self.par[-1] = SigmaS&lt;br /&gt;
&lt;br /&gt;
        #t-ratios&lt;br /&gt;
        self.VCOV = inv(np.dot(X.T,X))*SigmaS&lt;br /&gt;
        self.SE = np.diag(self.VCOV)**0.5&lt;br /&gt;
        self.t = self.par[:-1]/self.SE&lt;br /&gt;
&lt;br /&gt;
        #likelihood and IC&lt;br /&gt;
        self.logL = (-(self.T-pmax)/2.0)*np.log(2.0*np.pi) + (-(self.T-pmax)/2.0)*np.log(SigmaS) + (-(self.T-pmax)/2.0)&lt;br /&gt;
        self.AIC = 2.0*((self.par.size)-self.logL)&lt;br /&gt;
        self.BIC = np.log(Y.size)*self.par.size-2.0*self.logL&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Simulation ===&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import numpy as np&lt;br /&gt;
import models as mod&lt;br /&gt;
import matplotlib.pyplot as plt&lt;br /&gt;
from scipy.stats import norm&lt;br /&gt;
pmax = 10&lt;br /&gt;
n = 5000&lt;br /&gt;
T1 = 200 &lt;br /&gt;
T2 = 2000 &lt;br /&gt;
#1. AR(1) process&lt;br /&gt;
#phi = 0.9&lt;br /&gt;
#mu = 5.0&lt;br /&gt;
#sigmaSq = 1.0&lt;br /&gt;
#X1 = mod.trajectories1(mu, phi, sigmaSq, T1, n)&lt;br /&gt;
#X2 = mod.trajectories1(mu, phi, sigmaSq, T2, n)&lt;br /&gt;
#2. AR(2) process&lt;br /&gt;
phi1 = 0.4&lt;br /&gt;
phi2 = 0.4&lt;br /&gt;
mu = 5.0&lt;br /&gt;
sigmaSq = 1.0&lt;br /&gt;
X1 = mod.trajectories2(mu, phi1, phi2, sigmaSq, T1, n) # Rows = individual series; columns = time periods&lt;br /&gt;
X2 = mod.trajectories2(mu, phi1, phi2, sigmaSq, T2, n)&lt;br /&gt;
&lt;br /&gt;
#####&lt;br /&gt;
#GETS General to specific method&lt;br /&gt;
#####&lt;br /&gt;
tquantile = norm.ppf(0.95) #95% quantile&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop1 = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    p = pmax&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:],p,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;lt; tquantile and p&amp;gt;0:&lt;br /&gt;
            p-=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop1.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T1 finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop2 = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    p = pmax&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:],p,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;lt; tquantile and p&amp;gt;0:&lt;br /&gt;
            p-=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop2.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T2 finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#Specific-to-General&lt;br /&gt;
&lt;br /&gt;
tquantile = norm.ppf(0.95) #95% quantile&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop1SOG = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    p = 0&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:],p+1,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;gt; tquantile and p&amp;lt;=pmax:&lt;br /&gt;
            p+=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop1SOG.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T1 finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop2SOG = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    p = 0&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:],p+1,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;gt; tquantile and p&amp;lt;=pmax:&lt;br /&gt;
            p+=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop2SOG.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T2 finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#AIC and BIC&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
AICp1 = []&lt;br /&gt;
BICp1 = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    AICtemp = np.zeros(11)&lt;br /&gt;
    BICtemp = np.zeros(11)&lt;br /&gt;
    for p in np.arange(pmax+1):&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:], p, pmax)&lt;br /&gt;
        AICtemp[p] = ARtemp.AIC&lt;br /&gt;
        BICtemp[p] = ARtemp.BIC&lt;br /&gt;
    AICp1.append(np.argmin(AICtemp))&lt;br /&gt;
    BICp1.append(np.argmin(BICtemp))&lt;br /&gt;
&lt;br /&gt;
print &amp;quot;T1 AIC+BIC finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
AICp2 = []&lt;br /&gt;
BICp2 = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    AICtemp = np.zeros(11)&lt;br /&gt;
    BICtemp = np.zeros(11)&lt;br /&gt;
    for p in np.arange(pmax+1):&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:], p, pmax)&lt;br /&gt;
        AICtemp[p] = ARtemp.AIC&lt;br /&gt;
        BICtemp[p] = ARtemp.BIC&lt;br /&gt;
    AICp2.append(np.argmin(AICtemp))&lt;br /&gt;
    BICp2.append(np.argmin(BICtemp))&lt;br /&gt;
print &amp;quot;T2 AIC+BIC finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#Plot&lt;br /&gt;
&lt;br /&gt;
fig, axes = plt.subplots(nrows=4, ncols=2)&lt;br /&gt;
ax0, ax1, ax2, ax3, ax4, ax5, ax6, ax7 = axes.flatten()&lt;br /&gt;
&lt;br /&gt;
ax0.hist(tratiop1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax0.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax0.set_title('GETS, T=200')&lt;br /&gt;
&lt;br /&gt;
ax1.hist(tratiop2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax1.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax1.set_title('GETS, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax2.hist(tratiop1SOG, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax2.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax2.set_title('Spec-to-Gen, T=200')&lt;br /&gt;
&lt;br /&gt;
ax3.hist(tratiop2SOG, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax3.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax3.set_title('Spec-to-Gen, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax4.hist(AICp1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax4.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax4.set_title('AIC, T=200')&lt;br /&gt;
&lt;br /&gt;
ax5.hist(AICp2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax5.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax5.set_title('AIC, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax6.hist(BICp1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax6.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax6.set_title('BIC, T=200')&lt;br /&gt;
&lt;br /&gt;
ax7.hist(BICp2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax7.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax7.set_title('BIC, T=2000')&lt;br /&gt;
&lt;br /&gt;
fig.subplots_adjust(hspace=0.5)&lt;br /&gt;
plt.show()&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;/div&gt;</summary>
		<author><name>Hazn00</name></author>
		
	</entry>
	<entry>
		<id>http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19140</id>
		<title>Time Series Model Building Process</title>
		<link rel="alternate" type="text/html" href="http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19140"/>
		<updated>2020-01-19T13:38:07Z</updated>

		<summary type="html">&lt;p&gt;Hazn00: /* Simulation */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Linear time series models, e.g., ARIMA models for univariate time series, is a popular tool for modeling dynamics of time series and predicting the time series. The methodology is not popular only in statistics, econometrics and science, but also in machine learning business applications. The key question is how to build the model. We have to choose the form of the model, in particular number of lags for so-called autoregressive part (usually denoted as p) and moving average part of the model (usually denoted as d). The common guides usually provide a ‘cook book’ for model selection, see for example [https://www.machinelearningplus.com/time-series/arima-model-time-series-forecasting-python/, ARIMA Model – Complete Guide to Time Series Forecasting in Python] . This goal of this simulation is to compare four basic methods for selection of lags (p) for the autoregressive part.&lt;br /&gt;
&lt;br /&gt;
== Problem Definition ==&lt;br /&gt;
&lt;br /&gt;
The autoregressive process has form&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\phi}_2x_{t-2}+...+{\phi}_px_{t-p} + {\epsilon}_t&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;{\epsilon}_t \sim N(0,{\sigma}^2) &amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
However, we observe only the realized value and we do not know the hyperparameter p. Therefore, we must estimate it. The considered methods are following.&lt;br /&gt;
&lt;br /&gt;
=== GETS (General-to-Specific) ===&lt;br /&gt;
&lt;br /&gt;
We first start with high enough p (pmax in the code), and perform statistical test whether the last lag has statistically significant impact, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p = 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p \neq 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the impact is insignificant, we reduce p by one and continue until the parameter for the last lag is significant, i.e. last lag has significant effect.&lt;br /&gt;
&lt;br /&gt;
=== Specific-to-General ===&lt;br /&gt;
&lt;br /&gt;
The second approach works similarly as GETS, the only difference is that we first start with model without any lag, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and we are adding lags until they are significant.&lt;br /&gt;
&lt;br /&gt;
=== BIC (Bayesian Information Criteria) ===&lt;br /&gt;
&lt;br /&gt;
Bayesian information criteria is based on a likelihood of the model and number of parameters. The criteria punish the model for high number of parameters for a potential over-fitting, and rewards the model for good fit of the data. The lower the BIC value is, the better the model (a little bit counterintuitive definition). We are supposed to select a model with the lowest value of BIC.&lt;br /&gt;
&lt;br /&gt;
=== AIC (Akaike Information Criteria)  ===&lt;br /&gt;
&lt;br /&gt;
Works exactly the same as BIC, but the formula is slightly different.&lt;br /&gt;
&lt;br /&gt;
== Method and Simulation Method ==&lt;br /&gt;
&lt;br /&gt;
The solution consists of three key elements, data generating process, AR(p) model, and simulation.&lt;br /&gt;
&lt;br /&gt;
=== Data Generating Process ===&lt;br /&gt;
&lt;br /&gt;
To answer the question, which model selection method is the best, we are creating an artificial data. We assume that data are created by AR(1) process&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
or AR(2)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\mu} + {\phi}_2x_{t-2} + {\epsilon}_{t}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
with random error &amp;lt;math&amp;gt;&amp;lt;/math&amp;gt; . Therefore, we must generate random numbers for random errors, and iterate over the equations described above. The initial values of the processes, e.g., &amp;lt;math&amp;gt;x_0&amp;lt;/math&amp;gt;, are set to the theoretical mean value of the process.&lt;br /&gt;
&lt;br /&gt;
=== AR(p) model ===&lt;br /&gt;
&lt;br /&gt;
For a given series &amp;lt;math&amp;gt;{x_1,x_2,...x_T}&amp;lt;/math&amp;gt; with a length ''T'' estimates a model for a given p.&lt;br /&gt;
&lt;br /&gt;
=== Simulation ===&lt;br /&gt;
&lt;br /&gt;
Perform n Monte Carlo simulations, where in each simulation a the data generating process is used to create a time series. Then the AR(p) model is estimated for ''p=0,1,…,pmax'', and the best models are selected according to the selection criteria described above. Therefore, we will obtain four estimates of p that corresponds to the described methods for each of the n simulation. The final step is to compute % success of correctly estimated p for each of four methods.&lt;br /&gt;
&lt;br /&gt;
== Controls ==&lt;br /&gt;
The solution allow to set number of simulation n. We need high enough n to make sure that the results will converge close enough to actual results. Therefore, we have set &amp;lt;math&amp;gt;n=5000&amp;lt;/math&amp;gt;. Higher n will not significantly increase the precision of the results.&lt;br /&gt;
&lt;br /&gt;
The more important controls is selection of AR(1) or AR(2) process, and selection of parameters &amp;lt;math&amp;gt;{\mu},{\sigma},{\phi}_1&amp;lt;/math&amp;gt;  and  &amp;lt;math&amp;gt;{\phi}_2&amp;lt;/math&amp;gt; for the process. Additionally, we can set length of the generated series and even compare performance for series with two distinct lengths &amp;lt;math&amp;gt;T_1&amp;lt;/math&amp;gt; and &amp;lt;math&amp;gt;T_2&amp;lt;/math&amp;gt;. In other words, one method may perform better for low number of observations than other, and this control allow to compare the performance.&lt;br /&gt;
&lt;br /&gt;
== Results ==&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
&lt;br /&gt;
== Code ==&lt;br /&gt;
=== Model ===&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
import numpy as np from numpy.linalg &lt;br /&gt;
import inv from scipy.stats &lt;br /&gt;
import norm&lt;br /&gt;
def sim1(mu, phi1, sigmaSq, T):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates single trajectory.&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    x = np.zeros(T+1)&lt;br /&gt;
    epsilon = np.random.normal(0,sigmaSq, T+1)&lt;br /&gt;
    x[0] = mu / (1.0 - phi1)&lt;br /&gt;
    for t in np.arange(T):&lt;br /&gt;
        x[t+1] = mu + phi1 * x[t] + epsilon[t]&lt;br /&gt;
    return x[1:]&lt;br /&gt;
&amp;lt;code&amp;gt;def trajectories1(mu, phi1, sigmaSq, T, n):&amp;lt;/code&amp;gt;&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates n-trajectories of AR(1) process&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :param n:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    X = np.zeros([n,T])&lt;br /&gt;
    for s in np.arange(n):&lt;br /&gt;
        X[s,:] = sim1(mu, phi1, sigmaSq, T)&lt;br /&gt;
    return X&lt;br /&gt;
&amp;lt;code&amp;gt; def sim2(mu, phi1, phi2, sigmaSq, T):&amp;lt;/code&amp;gt;&lt;br /&gt;
    x = np.zeros(T+2)&lt;br /&gt;
    epsilon = np.random.normal(0,sigmaSq, T+2)&lt;br /&gt;
    x[0] = mu / (1.0 - phi1-phi2)&lt;br /&gt;
    x[1] = mu / (1.0 - phi1-phi2)&lt;br /&gt;
    for t in np.arange(T)+1:&lt;br /&gt;
        x[t+1] = mu + phi1 * x[t] + phi2 * x[t-1] + epsilon[t]&lt;br /&gt;
    return x[2:]&lt;br /&gt;
&amp;lt;code&amp;gt;def trajectories2(mu, phi1, phi2, sigmaSq, T, n):&amp;lt;/code&amp;gt;&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates n-trajectories of AR(2) process&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param phi2:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :param n:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    X = np.zeros([n,T])&lt;br /&gt;
    for s in np.arange(n):&lt;br /&gt;
        X[s,:] = sim2(mu, phi1, phi2, sigmaSq, T)&lt;br /&gt;
    return X&lt;br /&gt;
&amp;lt;code&amp;gt;class ARp(object):&amp;lt;/code&amp;gt;&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;AR(p) class allowing to estimate the model &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    def __init__(self, x, p, pmax):&lt;br /&gt;
        self.p = p&lt;br /&gt;
        self.x = x&lt;br /&gt;
        self.T = float(x.size)&lt;br /&gt;
        self.par = np.zeros(p+2) #np.array: c, phi_1, phi_2, ... phi_p, sigma^2&lt;br /&gt;
        #Init. matrices for OLS&lt;br /&gt;
        Y = self.x[pmax:]&lt;br /&gt;
        Xtemp = []&lt;br /&gt;
        for i in np.arange(Y.size):&lt;br /&gt;
            Xtemp.append(np.flip(x[i:(pmax+i)],0))&lt;br /&gt;
        X = np.ones((Y.size, p+1))&lt;br /&gt;
        X[:,1:] = np.array(Xtemp)[:,:p]&lt;br /&gt;
        #OLS Estimate&lt;br /&gt;
        Phi = np.dot(np.dot(inv(np.dot(X.T,X)),X.T),Y)&lt;br /&gt;
        SigmaS = np.sum((Y - np.dot(X, Phi))**2.0)/(self.T-pmax)&lt;br /&gt;
        self.par[:-1] = Phi[:]&lt;br /&gt;
        self.par[-1] = SigmaS&lt;br /&gt;
        #t-ratios&lt;br /&gt;
        self.VCOV = inv(np.dot(X.T,X))*SigmaS&lt;br /&gt;
        self.SE = np.diag(self.VCOV)**0.5&lt;br /&gt;
        self.t = self.par[:-1]/self.SE&lt;br /&gt;
        #likelihood and IC&lt;br /&gt;
        self.logL = (-(self.T-pmax)/2.0)*np.log(2.0*np.pi) + (-(self.T-pmax)/2.0)*np.log(SigmaS) + (-(self.T-pmax)/2.0)&lt;br /&gt;
        self.AIC = 2.0*((self.par.size)-self.logL)&lt;br /&gt;
        self.BIC = np.log(Y.size)*self.par.size-2.0*self.logL&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Simulation ===&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import numpy as np&lt;br /&gt;
import models as mod&lt;br /&gt;
import matplotlib.pyplot as plt&lt;br /&gt;
from scipy.stats import norm&lt;br /&gt;
pmax = 10&lt;br /&gt;
n = 5000&lt;br /&gt;
T1 = 200 &lt;br /&gt;
T2 = 2000 &lt;br /&gt;
#1. AR(1) process&lt;br /&gt;
#phi = 0.9&lt;br /&gt;
#mu = 5.0&lt;br /&gt;
#sigmaSq = 1.0&lt;br /&gt;
#X1 = mod.trajectories1(mu, phi, sigmaSq, T1, n)&lt;br /&gt;
#X2 = mod.trajectories1(mu, phi, sigmaSq, T2, n)&lt;br /&gt;
#2. AR(2) process&lt;br /&gt;
phi1 = 0.4&lt;br /&gt;
phi2 = 0.4&lt;br /&gt;
mu = 5.0&lt;br /&gt;
sigmaSq = 1.0&lt;br /&gt;
X1 = mod.trajectories2(mu, phi1, phi2, sigmaSq, T1, n) # Rows = individual series; columns = time periods&lt;br /&gt;
X2 = mod.trajectories2(mu, phi1, phi2, sigmaSq, T2, n)&lt;br /&gt;
&lt;br /&gt;
#####&lt;br /&gt;
#GETS General to specific method&lt;br /&gt;
#####&lt;br /&gt;
tquantile = norm.ppf(0.95) #95% quantile&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop1 = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    p = pmax&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:],p,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;lt; tquantile and p&amp;gt;0:&lt;br /&gt;
            p-=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop1.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T1 finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop2 = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    p = pmax&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:],p,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;lt; tquantile and p&amp;gt;0:&lt;br /&gt;
            p-=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop2.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T2 finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#Specific-to-General&lt;br /&gt;
&lt;br /&gt;
tquantile = norm.ppf(0.95) #95% quantile&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop1SOG = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    p = 0&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:],p+1,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;gt; tquantile and p&amp;lt;=pmax:&lt;br /&gt;
            p+=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop1SOG.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T1 finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop2SOG = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    p = 0&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:],p+1,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;gt; tquantile and p&amp;lt;=pmax:&lt;br /&gt;
            p+=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop2SOG.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T2 finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#AIC and BIC&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
AICp1 = []&lt;br /&gt;
BICp1 = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    AICtemp = np.zeros(11)&lt;br /&gt;
    BICtemp = np.zeros(11)&lt;br /&gt;
    for p in np.arange(pmax+1):&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:], p, pmax)&lt;br /&gt;
        AICtemp[p] = ARtemp.AIC&lt;br /&gt;
        BICtemp[p] = ARtemp.BIC&lt;br /&gt;
    AICp1.append(np.argmin(AICtemp))&lt;br /&gt;
    BICp1.append(np.argmin(BICtemp))&lt;br /&gt;
&lt;br /&gt;
print &amp;quot;T1 AIC+BIC finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
AICp2 = []&lt;br /&gt;
BICp2 = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    AICtemp = np.zeros(11)&lt;br /&gt;
    BICtemp = np.zeros(11)&lt;br /&gt;
    for p in np.arange(pmax+1):&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:], p, pmax)&lt;br /&gt;
        AICtemp[p] = ARtemp.AIC&lt;br /&gt;
        BICtemp[p] = ARtemp.BIC&lt;br /&gt;
    AICp2.append(np.argmin(AICtemp))&lt;br /&gt;
    BICp2.append(np.argmin(BICtemp))&lt;br /&gt;
print &amp;quot;T2 AIC+BIC finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#Plot&lt;br /&gt;
&lt;br /&gt;
fig, axes = plt.subplots(nrows=4, ncols=2)&lt;br /&gt;
ax0, ax1, ax2, ax3, ax4, ax5, ax6, ax7 = axes.flatten()&lt;br /&gt;
&lt;br /&gt;
ax0.hist(tratiop1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax0.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax0.set_title('GETS, T=200')&lt;br /&gt;
&lt;br /&gt;
ax1.hist(tratiop2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax1.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax1.set_title('GETS, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax2.hist(tratiop1SOG, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax2.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax2.set_title('Spec-to-Gen, T=200')&lt;br /&gt;
&lt;br /&gt;
ax3.hist(tratiop2SOG, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax3.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax3.set_title('Spec-to-Gen, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax4.hist(AICp1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax4.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax4.set_title('AIC, T=200')&lt;br /&gt;
&lt;br /&gt;
ax5.hist(AICp2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax5.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax5.set_title('AIC, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax6.hist(BICp1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax6.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax6.set_title('BIC, T=200')&lt;br /&gt;
&lt;br /&gt;
ax7.hist(BICp2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax7.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax7.set_title('BIC, T=2000')&lt;br /&gt;
&lt;br /&gt;
fig.subplots_adjust(hspace=0.5)&lt;br /&gt;
plt.show()&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;/div&gt;</summary>
		<author><name>Hazn00</name></author>
		
	</entry>
	<entry>
		<id>http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19139</id>
		<title>Time Series Model Building Process</title>
		<link rel="alternate" type="text/html" href="http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19139"/>
		<updated>2020-01-19T13:33:27Z</updated>

		<summary type="html">&lt;p&gt;Hazn00: /* Model */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Linear time series models, e.g., ARIMA models for univariate time series, is a popular tool for modeling dynamics of time series and predicting the time series. The methodology is not popular only in statistics, econometrics and science, but also in machine learning business applications. The key question is how to build the model. We have to choose the form of the model, in particular number of lags for so-called autoregressive part (usually denoted as p) and moving average part of the model (usually denoted as d). The common guides usually provide a ‘cook book’ for model selection, see for example [https://www.machinelearningplus.com/time-series/arima-model-time-series-forecasting-python/, ARIMA Model – Complete Guide to Time Series Forecasting in Python] . This goal of this simulation is to compare four basic methods for selection of lags (p) for the autoregressive part.&lt;br /&gt;
&lt;br /&gt;
== Problem Definition ==&lt;br /&gt;
&lt;br /&gt;
The autoregressive process has form&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\phi}_2x_{t-2}+...+{\phi}_px_{t-p} + {\epsilon}_t&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;{\epsilon}_t \sim N(0,{\sigma}^2) &amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
However, we observe only the realized value and we do not know the hyperparameter p. Therefore, we must estimate it. The considered methods are following.&lt;br /&gt;
&lt;br /&gt;
=== GETS (General-to-Specific) ===&lt;br /&gt;
&lt;br /&gt;
We first start with high enough p (pmax in the code), and perform statistical test whether the last lag has statistically significant impact, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p = 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p \neq 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the impact is insignificant, we reduce p by one and continue until the parameter for the last lag is significant, i.e. last lag has significant effect.&lt;br /&gt;
&lt;br /&gt;
=== Specific-to-General ===&lt;br /&gt;
&lt;br /&gt;
The second approach works similarly as GETS, the only difference is that we first start with model without any lag, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and we are adding lags until they are significant.&lt;br /&gt;
&lt;br /&gt;
=== BIC (Bayesian Information Criteria) ===&lt;br /&gt;
&lt;br /&gt;
Bayesian information criteria is based on a likelihood of the model and number of parameters. The criteria punish the model for high number of parameters for a potential over-fitting, and rewards the model for good fit of the data. The lower the BIC value is, the better the model (a little bit counterintuitive definition). We are supposed to select a model with the lowest value of BIC.&lt;br /&gt;
&lt;br /&gt;
=== AIC (Akaike Information Criteria)  ===&lt;br /&gt;
&lt;br /&gt;
Works exactly the same as BIC, but the formula is slightly different.&lt;br /&gt;
&lt;br /&gt;
== Method and Simulation Method ==&lt;br /&gt;
&lt;br /&gt;
The solution consists of three key elements, data generating process, AR(p) model, and simulation.&lt;br /&gt;
&lt;br /&gt;
=== Data Generating Process ===&lt;br /&gt;
&lt;br /&gt;
To answer the question, which model selection method is the best, we are creating an artificial data. We assume that data are created by AR(1) process&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
or AR(2)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\mu} + {\phi}_2x_{t-2} + {\epsilon}_{t}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
with random error &amp;lt;math&amp;gt;&amp;lt;/math&amp;gt; . Therefore, we must generate random numbers for random errors, and iterate over the equations described above. The initial values of the processes, e.g., &amp;lt;math&amp;gt;x_0&amp;lt;/math&amp;gt;, are set to the theoretical mean value of the process.&lt;br /&gt;
&lt;br /&gt;
=== AR(p) model ===&lt;br /&gt;
&lt;br /&gt;
For a given series &amp;lt;math&amp;gt;{x_1,x_2,...x_T}&amp;lt;/math&amp;gt; with a length ''T'' estimates a model for a given p.&lt;br /&gt;
&lt;br /&gt;
=== Simulation ===&lt;br /&gt;
&lt;br /&gt;
Perform n Monte Carlo simulations, where in each simulation a the data generating process is used to create a time series. Then the AR(p) model is estimated for ''p=0,1,…,pmax'', and the best models are selected according to the selection criteria described above. Therefore, we will obtain four estimates of p that corresponds to the described methods for each of the n simulation. The final step is to compute % success of correctly estimated p for each of four methods.&lt;br /&gt;
&lt;br /&gt;
== Controls ==&lt;br /&gt;
The solution allow to set number of simulation n. We need high enough n to make sure that the results will converge close enough to actual results. Therefore, we have set &amp;lt;math&amp;gt;n=5000&amp;lt;/math&amp;gt;. Higher n will not significantly increase the precision of the results.&lt;br /&gt;
&lt;br /&gt;
The more important controls is selection of AR(1) or AR(2) process, and selection of parameters &amp;lt;math&amp;gt;{\mu},{\sigma},{\phi}_1&amp;lt;/math&amp;gt;  and  &amp;lt;math&amp;gt;{\phi}_2&amp;lt;/math&amp;gt; for the process. Additionally, we can set length of the generated series and even compare performance for series with two distinct lengths &amp;lt;math&amp;gt;T_1&amp;lt;/math&amp;gt; and &amp;lt;math&amp;gt;T_2&amp;lt;/math&amp;gt;. In other words, one method may perform better for low number of observations than other, and this control allow to compare the performance.&lt;br /&gt;
&lt;br /&gt;
== Results ==&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
&lt;br /&gt;
== Code ==&lt;br /&gt;
=== Model ===&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
import numpy as np from numpy.linalg &lt;br /&gt;
import inv from scipy.stats &lt;br /&gt;
import norm&lt;br /&gt;
def sim1(mu, phi1, sigmaSq, T):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates single trajectory.&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    x = np.zeros(T+1)&lt;br /&gt;
    epsilon = np.random.normal(0,sigmaSq, T+1)&lt;br /&gt;
    x[0] = mu / (1.0 - phi1)&lt;br /&gt;
    for t in np.arange(T):&lt;br /&gt;
        x[t+1] = mu + phi1 * x[t] + epsilon[t]&lt;br /&gt;
    return x[1:]&lt;br /&gt;
&amp;lt;code&amp;gt;def trajectories1(mu, phi1, sigmaSq, T, n):&amp;lt;/code&amp;gt;&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates n-trajectories of AR(1) process&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :param n:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    X = np.zeros([n,T])&lt;br /&gt;
    for s in np.arange(n):&lt;br /&gt;
        X[s,:] = sim1(mu, phi1, sigmaSq, T)&lt;br /&gt;
    return X&lt;br /&gt;
&amp;lt;code&amp;gt; def sim2(mu, phi1, phi2, sigmaSq, T):&amp;lt;/code&amp;gt;&lt;br /&gt;
    x = np.zeros(T+2)&lt;br /&gt;
    epsilon = np.random.normal(0,sigmaSq, T+2)&lt;br /&gt;
    x[0] = mu / (1.0 - phi1-phi2)&lt;br /&gt;
    x[1] = mu / (1.0 - phi1-phi2)&lt;br /&gt;
    for t in np.arange(T)+1:&lt;br /&gt;
        x[t+1] = mu + phi1 * x[t] + phi2 * x[t-1] + epsilon[t]&lt;br /&gt;
    return x[2:]&lt;br /&gt;
&amp;lt;code&amp;gt;def trajectories2(mu, phi1, phi2, sigmaSq, T, n):&amp;lt;/code&amp;gt;&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates n-trajectories of AR(2) process&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param phi2:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :param n:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    X = np.zeros([n,T])&lt;br /&gt;
    for s in np.arange(n):&lt;br /&gt;
        X[s,:] = sim2(mu, phi1, phi2, sigmaSq, T)&lt;br /&gt;
    return X&lt;br /&gt;
&amp;lt;code&amp;gt;class ARp(object):&amp;lt;/code&amp;gt;&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;AR(p) class allowing to estimate the model &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    def __init__(self, x, p, pmax):&lt;br /&gt;
        self.p = p&lt;br /&gt;
        self.x = x&lt;br /&gt;
        self.T = float(x.size)&lt;br /&gt;
        self.par = np.zeros(p+2) #np.array: c, phi_1, phi_2, ... phi_p, sigma^2&lt;br /&gt;
        #Init. matrices for OLS&lt;br /&gt;
        Y = self.x[pmax:]&lt;br /&gt;
        Xtemp = []&lt;br /&gt;
        for i in np.arange(Y.size):&lt;br /&gt;
            Xtemp.append(np.flip(x[i:(pmax+i)],0))&lt;br /&gt;
        X = np.ones((Y.size, p+1))&lt;br /&gt;
        X[:,1:] = np.array(Xtemp)[:,:p]&lt;br /&gt;
        #OLS Estimate&lt;br /&gt;
        Phi = np.dot(np.dot(inv(np.dot(X.T,X)),X.T),Y)&lt;br /&gt;
        SigmaS = np.sum((Y - np.dot(X, Phi))**2.0)/(self.T-pmax)&lt;br /&gt;
        self.par[:-1] = Phi[:]&lt;br /&gt;
        self.par[-1] = SigmaS&lt;br /&gt;
        #t-ratios&lt;br /&gt;
        self.VCOV = inv(np.dot(X.T,X))*SigmaS&lt;br /&gt;
        self.SE = np.diag(self.VCOV)**0.5&lt;br /&gt;
        self.t = self.par[:-1]/self.SE&lt;br /&gt;
        #likelihood and IC&lt;br /&gt;
        self.logL = (-(self.T-pmax)/2.0)*np.log(2.0*np.pi) + (-(self.T-pmax)/2.0)*np.log(SigmaS) + (-(self.T-pmax)/2.0)&lt;br /&gt;
        self.AIC = 2.0*((self.par.size)-self.logL)&lt;br /&gt;
        self.BIC = np.log(Y.size)*self.par.size-2.0*self.logL&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Simulation ===&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
import numpy as np&lt;br /&gt;
import models as mod&lt;br /&gt;
import matplotlib.pyplot as plt&lt;br /&gt;
from scipy.stats import norm&lt;br /&gt;
&lt;br /&gt;
pmax = 10&lt;br /&gt;
n = 5000&lt;br /&gt;
T1 = 200 &lt;br /&gt;
T2 = 2000 &lt;br /&gt;
&lt;br /&gt;
#1. AR(1) process&lt;br /&gt;
#phi = 0.9&lt;br /&gt;
#mu = 5.0&lt;br /&gt;
#sigmaSq = 1.0&lt;br /&gt;
#X1 = mod.trajectories1(mu, phi, sigmaSq, T1, n)&lt;br /&gt;
#X2 = mod.trajectories1(mu, phi, sigmaSq, T2, n)&lt;br /&gt;
&lt;br /&gt;
#2. AR(2) process&lt;br /&gt;
phi1 = 0.4&lt;br /&gt;
phi2 = 0.4&lt;br /&gt;
mu = 5.0&lt;br /&gt;
sigmaSq = 1.0&lt;br /&gt;
X1 = mod.trajectories2(mu, phi1, phi2, sigmaSq, T1, n) # Rows = individual series; columns = time periods&lt;br /&gt;
X2 = mod.trajectories2(mu, phi1, phi2, sigmaSq, T2, n)&lt;br /&gt;
&lt;br /&gt;
#####&lt;br /&gt;
#GETS General to specific method&lt;br /&gt;
#####&lt;br /&gt;
tquantile = norm.ppf(0.95) #95% quantile&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop1 = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    p = pmax&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:],p,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;lt; tquantile and p&amp;gt;0:&lt;br /&gt;
            p-=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop1.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T1 finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop2 = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    p = pmax&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:],p,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;lt; tquantile and p&amp;gt;0:&lt;br /&gt;
            p-=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop2.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T2 finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#Specific-to-General&lt;br /&gt;
&lt;br /&gt;
tquantile = norm.ppf(0.95) #95% quantile&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop1SOG = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    p = 0&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:],p+1,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;gt; tquantile and p&amp;lt;=pmax:&lt;br /&gt;
            p+=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop1SOG.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T1 finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop2SOG = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    p = 0&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:],p+1,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;gt; tquantile and p&amp;lt;=pmax:&lt;br /&gt;
            p+=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop2SOG.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T2 finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#AIC and BIC&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
AICp1 = []&lt;br /&gt;
BICp1 = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    AICtemp = np.zeros(11)&lt;br /&gt;
    BICtemp = np.zeros(11)&lt;br /&gt;
    for p in np.arange(pmax+1):&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:], p, pmax)&lt;br /&gt;
        AICtemp[p] = ARtemp.AIC&lt;br /&gt;
        BICtemp[p] = ARtemp.BIC&lt;br /&gt;
    AICp1.append(np.argmin(AICtemp))&lt;br /&gt;
    BICp1.append(np.argmin(BICtemp))&lt;br /&gt;
&lt;br /&gt;
print &amp;quot;T1 AIC+BIC finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
AICp2 = []&lt;br /&gt;
BICp2 = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    AICtemp = np.zeros(11)&lt;br /&gt;
    BICtemp = np.zeros(11)&lt;br /&gt;
    for p in np.arange(pmax+1):&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:], p, pmax)&lt;br /&gt;
        AICtemp[p] = ARtemp.AIC&lt;br /&gt;
        BICtemp[p] = ARtemp.BIC&lt;br /&gt;
    AICp2.append(np.argmin(AICtemp))&lt;br /&gt;
    BICp2.append(np.argmin(BICtemp))&lt;br /&gt;
print &amp;quot;T2 AIC+BIC finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#Plot&lt;br /&gt;
&lt;br /&gt;
fig, axes = plt.subplots(nrows=4, ncols=2)&lt;br /&gt;
ax0, ax1, ax2, ax3, ax4, ax5, ax6, ax7 = axes.flatten()&lt;br /&gt;
&lt;br /&gt;
ax0.hist(tratiop1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax0.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax0.set_title('GETS, T=200')&lt;br /&gt;
&lt;br /&gt;
ax1.hist(tratiop2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax1.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax1.set_title('GETS, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax2.hist(tratiop1SOG, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax2.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax2.set_title('Spec-to-Gen, T=200')&lt;br /&gt;
&lt;br /&gt;
ax3.hist(tratiop2SOG, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax3.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax3.set_title('Spec-to-Gen, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax4.hist(AICp1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax4.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax4.set_title('AIC, T=200')&lt;br /&gt;
&lt;br /&gt;
ax5.hist(AICp2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax5.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax5.set_title('AIC, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax6.hist(BICp1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax6.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax6.set_title('BIC, T=200')&lt;br /&gt;
&lt;br /&gt;
ax7.hist(BICp2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax7.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax7.set_title('BIC, T=2000')&lt;br /&gt;
&lt;br /&gt;
fig.subplots_adjust(hspace=0.5)&lt;br /&gt;
plt.show()&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;/div&gt;</summary>
		<author><name>Hazn00</name></author>
		
	</entry>
	<entry>
		<id>http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19138</id>
		<title>Time Series Model Building Process</title>
		<link rel="alternate" type="text/html" href="http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19138"/>
		<updated>2020-01-19T13:32:57Z</updated>

		<summary type="html">&lt;p&gt;Hazn00: /* Model */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Linear time series models, e.g., ARIMA models for univariate time series, is a popular tool for modeling dynamics of time series and predicting the time series. The methodology is not popular only in statistics, econometrics and science, but also in machine learning business applications. The key question is how to build the model. We have to choose the form of the model, in particular number of lags for so-called autoregressive part (usually denoted as p) and moving average part of the model (usually denoted as d). The common guides usually provide a ‘cook book’ for model selection, see for example [https://www.machinelearningplus.com/time-series/arima-model-time-series-forecasting-python/, ARIMA Model – Complete Guide to Time Series Forecasting in Python] . This goal of this simulation is to compare four basic methods for selection of lags (p) for the autoregressive part.&lt;br /&gt;
&lt;br /&gt;
== Problem Definition ==&lt;br /&gt;
&lt;br /&gt;
The autoregressive process has form&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\phi}_2x_{t-2}+...+{\phi}_px_{t-p} + {\epsilon}_t&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;{\epsilon}_t \sim N(0,{\sigma}^2) &amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
However, we observe only the realized value and we do not know the hyperparameter p. Therefore, we must estimate it. The considered methods are following.&lt;br /&gt;
&lt;br /&gt;
=== GETS (General-to-Specific) ===&lt;br /&gt;
&lt;br /&gt;
We first start with high enough p (pmax in the code), and perform statistical test whether the last lag has statistically significant impact, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p = 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p \neq 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the impact is insignificant, we reduce p by one and continue until the parameter for the last lag is significant, i.e. last lag has significant effect.&lt;br /&gt;
&lt;br /&gt;
=== Specific-to-General ===&lt;br /&gt;
&lt;br /&gt;
The second approach works similarly as GETS, the only difference is that we first start with model without any lag, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and we are adding lags until they are significant.&lt;br /&gt;
&lt;br /&gt;
=== BIC (Bayesian Information Criteria) ===&lt;br /&gt;
&lt;br /&gt;
Bayesian information criteria is based on a likelihood of the model and number of parameters. The criteria punish the model for high number of parameters for a potential over-fitting, and rewards the model for good fit of the data. The lower the BIC value is, the better the model (a little bit counterintuitive definition). We are supposed to select a model with the lowest value of BIC.&lt;br /&gt;
&lt;br /&gt;
=== AIC (Akaike Information Criteria)  ===&lt;br /&gt;
&lt;br /&gt;
Works exactly the same as BIC, but the formula is slightly different.&lt;br /&gt;
&lt;br /&gt;
== Method and Simulation Method ==&lt;br /&gt;
&lt;br /&gt;
The solution consists of three key elements, data generating process, AR(p) model, and simulation.&lt;br /&gt;
&lt;br /&gt;
=== Data Generating Process ===&lt;br /&gt;
&lt;br /&gt;
To answer the question, which model selection method is the best, we are creating an artificial data. We assume that data are created by AR(1) process&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
or AR(2)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\mu} + {\phi}_2x_{t-2} + {\epsilon}_{t}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
with random error &amp;lt;math&amp;gt;&amp;lt;/math&amp;gt; . Therefore, we must generate random numbers for random errors, and iterate over the equations described above. The initial values of the processes, e.g., &amp;lt;math&amp;gt;x_0&amp;lt;/math&amp;gt;, are set to the theoretical mean value of the process.&lt;br /&gt;
&lt;br /&gt;
=== AR(p) model ===&lt;br /&gt;
&lt;br /&gt;
For a given series &amp;lt;math&amp;gt;{x_1,x_2,...x_T}&amp;lt;/math&amp;gt; with a length ''T'' estimates a model for a given p.&lt;br /&gt;
&lt;br /&gt;
=== Simulation ===&lt;br /&gt;
&lt;br /&gt;
Perform n Monte Carlo simulations, where in each simulation a the data generating process is used to create a time series. Then the AR(p) model is estimated for ''p=0,1,…,pmax'', and the best models are selected according to the selection criteria described above. Therefore, we will obtain four estimates of p that corresponds to the described methods for each of the n simulation. The final step is to compute % success of correctly estimated p for each of four methods.&lt;br /&gt;
&lt;br /&gt;
== Controls ==&lt;br /&gt;
The solution allow to set number of simulation n. We need high enough n to make sure that the results will converge close enough to actual results. Therefore, we have set &amp;lt;math&amp;gt;n=5000&amp;lt;/math&amp;gt;. Higher n will not significantly increase the precision of the results.&lt;br /&gt;
&lt;br /&gt;
The more important controls is selection of AR(1) or AR(2) process, and selection of parameters &amp;lt;math&amp;gt;{\mu},{\sigma},{\phi}_1&amp;lt;/math&amp;gt;  and  &amp;lt;math&amp;gt;{\phi}_2&amp;lt;/math&amp;gt; for the process. Additionally, we can set length of the generated series and even compare performance for series with two distinct lengths &amp;lt;math&amp;gt;T_1&amp;lt;/math&amp;gt; and &amp;lt;math&amp;gt;T_2&amp;lt;/math&amp;gt;. In other words, one method may perform better for low number of observations than other, and this control allow to compare the performance.&lt;br /&gt;
&lt;br /&gt;
== Results ==&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
&lt;br /&gt;
== Code ==&lt;br /&gt;
=== Model ===&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
import numpy as np from numpy.linalg &lt;br /&gt;
&lt;br /&gt;
import inv from scipy.stats &lt;br /&gt;
&lt;br /&gt;
import norm&lt;br /&gt;
&lt;br /&gt;
def sim1(mu, phi1, sigmaSq, T):&lt;br /&gt;
&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates single trajectory.&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    x = np.zeros(T+1)&lt;br /&gt;
    epsilon = np.random.normal(0,sigmaSq, T+1)&lt;br /&gt;
    x[0] = mu / (1.0 - phi1)&lt;br /&gt;
    for t in np.arange(T):&lt;br /&gt;
        x[t+1] = mu + phi1 * x[t] + epsilon[t]&lt;br /&gt;
    return x[1:]&lt;br /&gt;
&amp;lt;code&amp;gt;def trajectories1(mu, phi1, sigmaSq, T, n):&amp;lt;/code&amp;gt;&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates n-trajectories of AR(1) process&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :param n:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    X = np.zeros([n,T])&lt;br /&gt;
    for s in np.arange(n):&lt;br /&gt;
        X[s,:] = sim1(mu, phi1, sigmaSq, T)&lt;br /&gt;
    return X&lt;br /&gt;
&amp;lt;code&amp;gt; def sim2(mu, phi1, phi2, sigmaSq, T):&amp;lt;/code&amp;gt;&lt;br /&gt;
    x = np.zeros(T+2)&lt;br /&gt;
    epsilon = np.random.normal(0,sigmaSq, T+2)&lt;br /&gt;
    x[0] = mu / (1.0 - phi1-phi2)&lt;br /&gt;
    x[1] = mu / (1.0 - phi1-phi2)&lt;br /&gt;
    for t in np.arange(T)+1:&lt;br /&gt;
        x[t+1] = mu + phi1 * x[t] + phi2 * x[t-1] + epsilon[t]&lt;br /&gt;
    return x[2:]&lt;br /&gt;
&amp;lt;code&amp;gt;def trajectories2(mu, phi1, phi2, sigmaSq, T, n):&amp;lt;/code&amp;gt;&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates n-trajectories of AR(2) process&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param phi2:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :param n:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    X = np.zeros([n,T])&lt;br /&gt;
    for s in np.arange(n):&lt;br /&gt;
        X[s,:] = sim2(mu, phi1, phi2, sigmaSq, T)&lt;br /&gt;
    return X&lt;br /&gt;
&amp;lt;code&amp;gt;class ARp(object):&amp;lt;/code&amp;gt;&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;AR(p) class allowing to estimate the model &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    def __init__(self, x, p, pmax):&lt;br /&gt;
        self.p = p&lt;br /&gt;
        self.x = x&lt;br /&gt;
        self.T = float(x.size)&lt;br /&gt;
        self.par = np.zeros(p+2) #np.array: c, phi_1, phi_2, ... phi_p, sigma^2&lt;br /&gt;
        #Init. matrices for OLS&lt;br /&gt;
        Y = self.x[pmax:]&lt;br /&gt;
        Xtemp = []&lt;br /&gt;
&lt;br /&gt;
        for i in np.arange(Y.size):&lt;br /&gt;
            Xtemp.append(np.flip(x[i:(pmax+i)],0))&lt;br /&gt;
        X = np.ones((Y.size, p+1))&lt;br /&gt;
        X[:,1:] = np.array(Xtemp)[:,:p]&lt;br /&gt;
&lt;br /&gt;
        #OLS Estimate&lt;br /&gt;
        Phi = np.dot(np.dot(inv(np.dot(X.T,X)),X.T),Y)&lt;br /&gt;
        SigmaS = np.sum((Y - np.dot(X, Phi))**2.0)/(self.T-pmax)&lt;br /&gt;
        self.par[:-1] = Phi[:]&lt;br /&gt;
        self.par[-1] = SigmaS&lt;br /&gt;
&lt;br /&gt;
        #t-ratios&lt;br /&gt;
        self.VCOV = inv(np.dot(X.T,X))*SigmaS&lt;br /&gt;
        self.SE = np.diag(self.VCOV)**0.5&lt;br /&gt;
        self.t = self.par[:-1]/self.SE&lt;br /&gt;
&lt;br /&gt;
        #likelihood and IC&lt;br /&gt;
        self.logL = (-(self.T-pmax)/2.0)*np.log(2.0*np.pi) + (-(self.T-pmax)/2.0)*np.log(SigmaS) + (-(self.T-pmax)/2.0)&lt;br /&gt;
        self.AIC = 2.0*((self.par.size)-self.logL)&lt;br /&gt;
        self.BIC = np.log(Y.size)*self.par.size-2.0*self.logL&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Simulation ===&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
import numpy as np&lt;br /&gt;
import models as mod&lt;br /&gt;
import matplotlib.pyplot as plt&lt;br /&gt;
from scipy.stats import norm&lt;br /&gt;
&lt;br /&gt;
pmax = 10&lt;br /&gt;
n = 5000&lt;br /&gt;
T1 = 200 &lt;br /&gt;
T2 = 2000 &lt;br /&gt;
&lt;br /&gt;
#1. AR(1) process&lt;br /&gt;
#phi = 0.9&lt;br /&gt;
#mu = 5.0&lt;br /&gt;
#sigmaSq = 1.0&lt;br /&gt;
#X1 = mod.trajectories1(mu, phi, sigmaSq, T1, n)&lt;br /&gt;
#X2 = mod.trajectories1(mu, phi, sigmaSq, T2, n)&lt;br /&gt;
&lt;br /&gt;
#2. AR(2) process&lt;br /&gt;
phi1 = 0.4&lt;br /&gt;
phi2 = 0.4&lt;br /&gt;
mu = 5.0&lt;br /&gt;
sigmaSq = 1.0&lt;br /&gt;
X1 = mod.trajectories2(mu, phi1, phi2, sigmaSq, T1, n) # Rows = individual series; columns = time periods&lt;br /&gt;
X2 = mod.trajectories2(mu, phi1, phi2, sigmaSq, T2, n)&lt;br /&gt;
&lt;br /&gt;
#####&lt;br /&gt;
#GETS General to specific method&lt;br /&gt;
#####&lt;br /&gt;
tquantile = norm.ppf(0.95) #95% quantile&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop1 = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    p = pmax&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:],p,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;lt; tquantile and p&amp;gt;0:&lt;br /&gt;
            p-=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop1.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T1 finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop2 = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    p = pmax&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:],p,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;lt; tquantile and p&amp;gt;0:&lt;br /&gt;
            p-=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop2.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T2 finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#Specific-to-General&lt;br /&gt;
&lt;br /&gt;
tquantile = norm.ppf(0.95) #95% quantile&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop1SOG = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    p = 0&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:],p+1,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;gt; tquantile and p&amp;lt;=pmax:&lt;br /&gt;
            p+=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop1SOG.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T1 finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop2SOG = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    p = 0&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:],p+1,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;gt; tquantile and p&amp;lt;=pmax:&lt;br /&gt;
            p+=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop2SOG.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T2 finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#AIC and BIC&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
AICp1 = []&lt;br /&gt;
BICp1 = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    AICtemp = np.zeros(11)&lt;br /&gt;
    BICtemp = np.zeros(11)&lt;br /&gt;
    for p in np.arange(pmax+1):&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:], p, pmax)&lt;br /&gt;
        AICtemp[p] = ARtemp.AIC&lt;br /&gt;
        BICtemp[p] = ARtemp.BIC&lt;br /&gt;
    AICp1.append(np.argmin(AICtemp))&lt;br /&gt;
    BICp1.append(np.argmin(BICtemp))&lt;br /&gt;
&lt;br /&gt;
print &amp;quot;T1 AIC+BIC finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
AICp2 = []&lt;br /&gt;
BICp2 = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    AICtemp = np.zeros(11)&lt;br /&gt;
    BICtemp = np.zeros(11)&lt;br /&gt;
    for p in np.arange(pmax+1):&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:], p, pmax)&lt;br /&gt;
        AICtemp[p] = ARtemp.AIC&lt;br /&gt;
        BICtemp[p] = ARtemp.BIC&lt;br /&gt;
    AICp2.append(np.argmin(AICtemp))&lt;br /&gt;
    BICp2.append(np.argmin(BICtemp))&lt;br /&gt;
print &amp;quot;T2 AIC+BIC finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#Plot&lt;br /&gt;
&lt;br /&gt;
fig, axes = plt.subplots(nrows=4, ncols=2)&lt;br /&gt;
ax0, ax1, ax2, ax3, ax4, ax5, ax6, ax7 = axes.flatten()&lt;br /&gt;
&lt;br /&gt;
ax0.hist(tratiop1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax0.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax0.set_title('GETS, T=200')&lt;br /&gt;
&lt;br /&gt;
ax1.hist(tratiop2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax1.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax1.set_title('GETS, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax2.hist(tratiop1SOG, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax2.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax2.set_title('Spec-to-Gen, T=200')&lt;br /&gt;
&lt;br /&gt;
ax3.hist(tratiop2SOG, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax3.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax3.set_title('Spec-to-Gen, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax4.hist(AICp1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax4.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax4.set_title('AIC, T=200')&lt;br /&gt;
&lt;br /&gt;
ax5.hist(AICp2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax5.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax5.set_title('AIC, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax6.hist(BICp1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax6.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax6.set_title('BIC, T=200')&lt;br /&gt;
&lt;br /&gt;
ax7.hist(BICp2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax7.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax7.set_title('BIC, T=2000')&lt;br /&gt;
&lt;br /&gt;
fig.subplots_adjust(hspace=0.5)&lt;br /&gt;
plt.show()&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;/div&gt;</summary>
		<author><name>Hazn00</name></author>
		
	</entry>
	<entry>
		<id>http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19137</id>
		<title>Time Series Model Building Process</title>
		<link rel="alternate" type="text/html" href="http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19137"/>
		<updated>2020-01-19T13:32:33Z</updated>

		<summary type="html">&lt;p&gt;Hazn00: /* Model */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Linear time series models, e.g., ARIMA models for univariate time series, is a popular tool for modeling dynamics of time series and predicting the time series. The methodology is not popular only in statistics, econometrics and science, but also in machine learning business applications. The key question is how to build the model. We have to choose the form of the model, in particular number of lags for so-called autoregressive part (usually denoted as p) and moving average part of the model (usually denoted as d). The common guides usually provide a ‘cook book’ for model selection, see for example [https://www.machinelearningplus.com/time-series/arima-model-time-series-forecasting-python/, ARIMA Model – Complete Guide to Time Series Forecasting in Python] . This goal of this simulation is to compare four basic methods for selection of lags (p) for the autoregressive part.&lt;br /&gt;
&lt;br /&gt;
== Problem Definition ==&lt;br /&gt;
&lt;br /&gt;
The autoregressive process has form&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\phi}_2x_{t-2}+...+{\phi}_px_{t-p} + {\epsilon}_t&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;{\epsilon}_t \sim N(0,{\sigma}^2) &amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
However, we observe only the realized value and we do not know the hyperparameter p. Therefore, we must estimate it. The considered methods are following.&lt;br /&gt;
&lt;br /&gt;
=== GETS (General-to-Specific) ===&lt;br /&gt;
&lt;br /&gt;
We first start with high enough p (pmax in the code), and perform statistical test whether the last lag has statistically significant impact, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p = 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p \neq 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the impact is insignificant, we reduce p by one and continue until the parameter for the last lag is significant, i.e. last lag has significant effect.&lt;br /&gt;
&lt;br /&gt;
=== Specific-to-General ===&lt;br /&gt;
&lt;br /&gt;
The second approach works similarly as GETS, the only difference is that we first start with model without any lag, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and we are adding lags until they are significant.&lt;br /&gt;
&lt;br /&gt;
=== BIC (Bayesian Information Criteria) ===&lt;br /&gt;
&lt;br /&gt;
Bayesian information criteria is based on a likelihood of the model and number of parameters. The criteria punish the model for high number of parameters for a potential over-fitting, and rewards the model for good fit of the data. The lower the BIC value is, the better the model (a little bit counterintuitive definition). We are supposed to select a model with the lowest value of BIC.&lt;br /&gt;
&lt;br /&gt;
=== AIC (Akaike Information Criteria)  ===&lt;br /&gt;
&lt;br /&gt;
Works exactly the same as BIC, but the formula is slightly different.&lt;br /&gt;
&lt;br /&gt;
== Method and Simulation Method ==&lt;br /&gt;
&lt;br /&gt;
The solution consists of three key elements, data generating process, AR(p) model, and simulation.&lt;br /&gt;
&lt;br /&gt;
=== Data Generating Process ===&lt;br /&gt;
&lt;br /&gt;
To answer the question, which model selection method is the best, we are creating an artificial data. We assume that data are created by AR(1) process&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
or AR(2)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\mu} + {\phi}_2x_{t-2} + {\epsilon}_{t}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
with random error &amp;lt;math&amp;gt;&amp;lt;/math&amp;gt; . Therefore, we must generate random numbers for random errors, and iterate over the equations described above. The initial values of the processes, e.g., &amp;lt;math&amp;gt;x_0&amp;lt;/math&amp;gt;, are set to the theoretical mean value of the process.&lt;br /&gt;
&lt;br /&gt;
=== AR(p) model ===&lt;br /&gt;
&lt;br /&gt;
For a given series &amp;lt;math&amp;gt;{x_1,x_2,...x_T}&amp;lt;/math&amp;gt; with a length ''T'' estimates a model for a given p.&lt;br /&gt;
&lt;br /&gt;
=== Simulation ===&lt;br /&gt;
&lt;br /&gt;
Perform n Monte Carlo simulations, where in each simulation a the data generating process is used to create a time series. Then the AR(p) model is estimated for ''p=0,1,…,pmax'', and the best models are selected according to the selection criteria described above. Therefore, we will obtain four estimates of p that corresponds to the described methods for each of the n simulation. The final step is to compute % success of correctly estimated p for each of four methods.&lt;br /&gt;
&lt;br /&gt;
== Controls ==&lt;br /&gt;
The solution allow to set number of simulation n. We need high enough n to make sure that the results will converge close enough to actual results. Therefore, we have set &amp;lt;math&amp;gt;n=5000&amp;lt;/math&amp;gt;. Higher n will not significantly increase the precision of the results.&lt;br /&gt;
&lt;br /&gt;
The more important controls is selection of AR(1) or AR(2) process, and selection of parameters &amp;lt;math&amp;gt;{\mu},{\sigma},{\phi}_1&amp;lt;/math&amp;gt;  and  &amp;lt;math&amp;gt;{\phi}_2&amp;lt;/math&amp;gt; for the process. Additionally, we can set length of the generated series and even compare performance for series with two distinct lengths &amp;lt;math&amp;gt;T_1&amp;lt;/math&amp;gt; and &amp;lt;math&amp;gt;T_2&amp;lt;/math&amp;gt;. In other words, one method may perform better for low number of observations than other, and this control allow to compare the performance.&lt;br /&gt;
&lt;br /&gt;
== Results ==&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
&lt;br /&gt;
== Code ==&lt;br /&gt;
=== Model ===&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
import numpy as np from numpy.linalg &lt;br /&gt;
import inv from scipy.stats &lt;br /&gt;
import norm&lt;br /&gt;
def sim1(mu, phi1, sigmaSq, T):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates single trajectory.&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    x = np.zeros(T+1)&lt;br /&gt;
    epsilon = np.random.normal(0,sigmaSq, T+1)&lt;br /&gt;
    x[0] = mu / (1.0 - phi1)&lt;br /&gt;
    for t in np.arange(T):&lt;br /&gt;
        x[t+1] = mu + phi1 * x[t] + epsilon[t]&lt;br /&gt;
    return x[1:]&lt;br /&gt;
&amp;lt;code&amp;gt;def trajectories1(mu, phi1, sigmaSq, T, n):&amp;lt;/code&amp;gt;&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates n-trajectories of AR(1) process&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :param n:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    X = np.zeros([n,T])&lt;br /&gt;
    for s in np.arange(n):&lt;br /&gt;
        X[s,:] = sim1(mu, phi1, sigmaSq, T)&lt;br /&gt;
    return X&lt;br /&gt;
&amp;lt;code&amp;gt; def sim2(mu, phi1, phi2, sigmaSq, T):&amp;lt;/code&amp;gt;&lt;br /&gt;
    x = np.zeros(T+2)&lt;br /&gt;
    epsilon = np.random.normal(0,sigmaSq, T+2)&lt;br /&gt;
    x[0] = mu / (1.0 - phi1-phi2)&lt;br /&gt;
    x[1] = mu / (1.0 - phi1-phi2)&lt;br /&gt;
    for t in np.arange(T)+1:&lt;br /&gt;
        x[t+1] = mu + phi1 * x[t] + phi2 * x[t-1] + epsilon[t]&lt;br /&gt;
    return x[2:]&lt;br /&gt;
&amp;lt;code&amp;gt;def trajectories2(mu, phi1, phi2, sigmaSq, T, n):&amp;lt;/code&amp;gt;&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates n-trajectories of AR(2) process&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param phi2:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :param n:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    X = np.zeros([n,T])&lt;br /&gt;
    for s in np.arange(n):&lt;br /&gt;
        X[s,:] = sim2(mu, phi1, phi2, sigmaSq, T)&lt;br /&gt;
    return X&lt;br /&gt;
&amp;lt;code&amp;gt;class ARp(object):&amp;lt;/code&amp;gt;&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;AR(p) class allowing to estimate the model &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    def __init__(self, x, p, pmax):&lt;br /&gt;
        self.p = p&lt;br /&gt;
        self.x = x&lt;br /&gt;
        self.T = float(x.size)&lt;br /&gt;
        self.par = np.zeros(p+2) #np.array: c, phi_1, phi_2, ... phi_p, sigma^2&lt;br /&gt;
        #Init. matrices for OLS&lt;br /&gt;
        Y = self.x[pmax:]&lt;br /&gt;
        Xtemp = []&lt;br /&gt;
&lt;br /&gt;
        for i in np.arange(Y.size):&lt;br /&gt;
            Xtemp.append(np.flip(x[i:(pmax+i)],0))&lt;br /&gt;
        X = np.ones((Y.size, p+1))&lt;br /&gt;
        X[:,1:] = np.array(Xtemp)[:,:p]&lt;br /&gt;
&lt;br /&gt;
        #OLS Estimate&lt;br /&gt;
        Phi = np.dot(np.dot(inv(np.dot(X.T,X)),X.T),Y)&lt;br /&gt;
        SigmaS = np.sum((Y - np.dot(X, Phi))**2.0)/(self.T-pmax)&lt;br /&gt;
        self.par[:-1] = Phi[:]&lt;br /&gt;
        self.par[-1] = SigmaS&lt;br /&gt;
&lt;br /&gt;
        #t-ratios&lt;br /&gt;
        self.VCOV = inv(np.dot(X.T,X))*SigmaS&lt;br /&gt;
        self.SE = np.diag(self.VCOV)**0.5&lt;br /&gt;
        self.t = self.par[:-1]/self.SE&lt;br /&gt;
&lt;br /&gt;
        #likelihood and IC&lt;br /&gt;
        self.logL = (-(self.T-pmax)/2.0)*np.log(2.0*np.pi) + (-(self.T-pmax)/2.0)*np.log(SigmaS) + (-(self.T-pmax)/2.0)&lt;br /&gt;
        self.AIC = 2.0*((self.par.size)-self.logL)&lt;br /&gt;
        self.BIC = np.log(Y.size)*self.par.size-2.0*self.logL&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Simulation ===&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
import numpy as np&lt;br /&gt;
import models as mod&lt;br /&gt;
import matplotlib.pyplot as plt&lt;br /&gt;
from scipy.stats import norm&lt;br /&gt;
&lt;br /&gt;
pmax = 10&lt;br /&gt;
n = 5000&lt;br /&gt;
T1 = 200 &lt;br /&gt;
T2 = 2000 &lt;br /&gt;
&lt;br /&gt;
#1. AR(1) process&lt;br /&gt;
#phi = 0.9&lt;br /&gt;
#mu = 5.0&lt;br /&gt;
#sigmaSq = 1.0&lt;br /&gt;
#X1 = mod.trajectories1(mu, phi, sigmaSq, T1, n)&lt;br /&gt;
#X2 = mod.trajectories1(mu, phi, sigmaSq, T2, n)&lt;br /&gt;
&lt;br /&gt;
#2. AR(2) process&lt;br /&gt;
phi1 = 0.4&lt;br /&gt;
phi2 = 0.4&lt;br /&gt;
mu = 5.0&lt;br /&gt;
sigmaSq = 1.0&lt;br /&gt;
X1 = mod.trajectories2(mu, phi1, phi2, sigmaSq, T1, n) # Rows = individual series; columns = time periods&lt;br /&gt;
X2 = mod.trajectories2(mu, phi1, phi2, sigmaSq, T2, n)&lt;br /&gt;
&lt;br /&gt;
#####&lt;br /&gt;
#GETS General to specific method&lt;br /&gt;
#####&lt;br /&gt;
tquantile = norm.ppf(0.95) #95% quantile&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop1 = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    p = pmax&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:],p,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;lt; tquantile and p&amp;gt;0:&lt;br /&gt;
            p-=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop1.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T1 finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop2 = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    p = pmax&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:],p,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;lt; tquantile and p&amp;gt;0:&lt;br /&gt;
            p-=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop2.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T2 finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#Specific-to-General&lt;br /&gt;
&lt;br /&gt;
tquantile = norm.ppf(0.95) #95% quantile&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop1SOG = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    p = 0&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:],p+1,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;gt; tquantile and p&amp;lt;=pmax:&lt;br /&gt;
            p+=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop1SOG.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T1 finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop2SOG = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    p = 0&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:],p+1,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;gt; tquantile and p&amp;lt;=pmax:&lt;br /&gt;
            p+=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop2SOG.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T2 finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#AIC and BIC&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
AICp1 = []&lt;br /&gt;
BICp1 = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    AICtemp = np.zeros(11)&lt;br /&gt;
    BICtemp = np.zeros(11)&lt;br /&gt;
    for p in np.arange(pmax+1):&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:], p, pmax)&lt;br /&gt;
        AICtemp[p] = ARtemp.AIC&lt;br /&gt;
        BICtemp[p] = ARtemp.BIC&lt;br /&gt;
    AICp1.append(np.argmin(AICtemp))&lt;br /&gt;
    BICp1.append(np.argmin(BICtemp))&lt;br /&gt;
&lt;br /&gt;
print &amp;quot;T1 AIC+BIC finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
AICp2 = []&lt;br /&gt;
BICp2 = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    AICtemp = np.zeros(11)&lt;br /&gt;
    BICtemp = np.zeros(11)&lt;br /&gt;
    for p in np.arange(pmax+1):&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:], p, pmax)&lt;br /&gt;
        AICtemp[p] = ARtemp.AIC&lt;br /&gt;
        BICtemp[p] = ARtemp.BIC&lt;br /&gt;
    AICp2.append(np.argmin(AICtemp))&lt;br /&gt;
    BICp2.append(np.argmin(BICtemp))&lt;br /&gt;
print &amp;quot;T2 AIC+BIC finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#Plot&lt;br /&gt;
&lt;br /&gt;
fig, axes = plt.subplots(nrows=4, ncols=2)&lt;br /&gt;
ax0, ax1, ax2, ax3, ax4, ax5, ax6, ax7 = axes.flatten()&lt;br /&gt;
&lt;br /&gt;
ax0.hist(tratiop1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax0.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax0.set_title('GETS, T=200')&lt;br /&gt;
&lt;br /&gt;
ax1.hist(tratiop2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax1.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax1.set_title('GETS, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax2.hist(tratiop1SOG, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax2.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax2.set_title('Spec-to-Gen, T=200')&lt;br /&gt;
&lt;br /&gt;
ax3.hist(tratiop2SOG, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax3.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax3.set_title('Spec-to-Gen, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax4.hist(AICp1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax4.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax4.set_title('AIC, T=200')&lt;br /&gt;
&lt;br /&gt;
ax5.hist(AICp2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax5.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax5.set_title('AIC, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax6.hist(BICp1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax6.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax6.set_title('BIC, T=200')&lt;br /&gt;
&lt;br /&gt;
ax7.hist(BICp2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax7.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax7.set_title('BIC, T=2000')&lt;br /&gt;
&lt;br /&gt;
fig.subplots_adjust(hspace=0.5)&lt;br /&gt;
plt.show()&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;/div&gt;</summary>
		<author><name>Hazn00</name></author>
		
	</entry>
	<entry>
		<id>http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19136</id>
		<title>Time Series Model Building Process</title>
		<link rel="alternate" type="text/html" href="http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19136"/>
		<updated>2020-01-19T13:30:55Z</updated>

		<summary type="html">&lt;p&gt;Hazn00: /* Model */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Linear time series models, e.g., ARIMA models for univariate time series, is a popular tool for modeling dynamics of time series and predicting the time series. The methodology is not popular only in statistics, econometrics and science, but also in machine learning business applications. The key question is how to build the model. We have to choose the form of the model, in particular number of lags for so-called autoregressive part (usually denoted as p) and moving average part of the model (usually denoted as d). The common guides usually provide a ‘cook book’ for model selection, see for example [https://www.machinelearningplus.com/time-series/arima-model-time-series-forecasting-python/, ARIMA Model – Complete Guide to Time Series Forecasting in Python] . This goal of this simulation is to compare four basic methods for selection of lags (p) for the autoregressive part.&lt;br /&gt;
&lt;br /&gt;
== Problem Definition ==&lt;br /&gt;
&lt;br /&gt;
The autoregressive process has form&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\phi}_2x_{t-2}+...+{\phi}_px_{t-p} + {\epsilon}_t&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;{\epsilon}_t \sim N(0,{\sigma}^2) &amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
However, we observe only the realized value and we do not know the hyperparameter p. Therefore, we must estimate it. The considered methods are following.&lt;br /&gt;
&lt;br /&gt;
=== GETS (General-to-Specific) ===&lt;br /&gt;
&lt;br /&gt;
We first start with high enough p (pmax in the code), and perform statistical test whether the last lag has statistically significant impact, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p = 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p \neq 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the impact is insignificant, we reduce p by one and continue until the parameter for the last lag is significant, i.e. last lag has significant effect.&lt;br /&gt;
&lt;br /&gt;
=== Specific-to-General ===&lt;br /&gt;
&lt;br /&gt;
The second approach works similarly as GETS, the only difference is that we first start with model without any lag, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and we are adding lags until they are significant.&lt;br /&gt;
&lt;br /&gt;
=== BIC (Bayesian Information Criteria) ===&lt;br /&gt;
&lt;br /&gt;
Bayesian information criteria is based on a likelihood of the model and number of parameters. The criteria punish the model for high number of parameters for a potential over-fitting, and rewards the model for good fit of the data. The lower the BIC value is, the better the model (a little bit counterintuitive definition). We are supposed to select a model with the lowest value of BIC.&lt;br /&gt;
&lt;br /&gt;
=== AIC (Akaike Information Criteria)  ===&lt;br /&gt;
&lt;br /&gt;
Works exactly the same as BIC, but the formula is slightly different.&lt;br /&gt;
&lt;br /&gt;
== Method and Simulation Method ==&lt;br /&gt;
&lt;br /&gt;
The solution consists of three key elements, data generating process, AR(p) model, and simulation.&lt;br /&gt;
&lt;br /&gt;
=== Data Generating Process ===&lt;br /&gt;
&lt;br /&gt;
To answer the question, which model selection method is the best, we are creating an artificial data. We assume that data are created by AR(1) process&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
or AR(2)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\mu} + {\phi}_2x_{t-2} + {\epsilon}_{t}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
with random error &amp;lt;math&amp;gt;&amp;lt;/math&amp;gt; . Therefore, we must generate random numbers for random errors, and iterate over the equations described above. The initial values of the processes, e.g., &amp;lt;math&amp;gt;x_0&amp;lt;/math&amp;gt;, are set to the theoretical mean value of the process.&lt;br /&gt;
&lt;br /&gt;
=== AR(p) model ===&lt;br /&gt;
&lt;br /&gt;
For a given series &amp;lt;math&amp;gt;{x_1,x_2,...x_T}&amp;lt;/math&amp;gt; with a length ''T'' estimates a model for a given p.&lt;br /&gt;
&lt;br /&gt;
=== Simulation ===&lt;br /&gt;
&lt;br /&gt;
Perform n Monte Carlo simulations, where in each simulation a the data generating process is used to create a time series. Then the AR(p) model is estimated for ''p=0,1,…,pmax'', and the best models are selected according to the selection criteria described above. Therefore, we will obtain four estimates of p that corresponds to the described methods for each of the n simulation. The final step is to compute % success of correctly estimated p for each of four methods.&lt;br /&gt;
&lt;br /&gt;
== Controls ==&lt;br /&gt;
The solution allow to set number of simulation n. We need high enough n to make sure that the results will converge close enough to actual results. Therefore, we have set &amp;lt;math&amp;gt;n=5000&amp;lt;/math&amp;gt;. Higher n will not significantly increase the precision of the results.&lt;br /&gt;
&lt;br /&gt;
The more important controls is selection of AR(1) or AR(2) process, and selection of parameters &amp;lt;math&amp;gt;{\mu},{\sigma},{\phi}_1&amp;lt;/math&amp;gt;  and  &amp;lt;math&amp;gt;{\phi}_2&amp;lt;/math&amp;gt; for the process. Additionally, we can set length of the generated series and even compare performance for series with two distinct lengths &amp;lt;math&amp;gt;T_1&amp;lt;/math&amp;gt; and &amp;lt;math&amp;gt;T_2&amp;lt;/math&amp;gt;. In other words, one method may perform better for low number of observations than other, and this control allow to compare the performance.&lt;br /&gt;
&lt;br /&gt;
== Results ==&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
&lt;br /&gt;
== Code ==&lt;br /&gt;
=== Model ===&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
import numpy as np&lt;br /&gt;
from numpy.linalg import inv&lt;br /&gt;
from scipy.stats import norm&lt;br /&gt;
&lt;br /&gt;
def sim1(mu, phi1, sigmaSq, T):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates single trajectory.&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    x = np.zeros(T+1)&lt;br /&gt;
    epsilon = np.random.normal(0,sigmaSq, T+1)&lt;br /&gt;
&lt;br /&gt;
    x[0] = mu / (1.0 - phi1)&lt;br /&gt;
&lt;br /&gt;
    for t in np.arange(T):&lt;br /&gt;
        x[t+1] = mu + phi1 * x[t] + epsilon[t]&lt;br /&gt;
&lt;br /&gt;
    return x[1:]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;def trajectories1(mu, phi1, sigmaSq, T, n):&amp;lt;/code&amp;gt;&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates n-trajectories of AR(1) process&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :param n:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    X = np.zeros([n,T])&lt;br /&gt;
    for s in np.arange(n):&lt;br /&gt;
        X[s,:] = sim1(mu, phi1, sigmaSq, T)&lt;br /&gt;
    return X&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt; def sim2(mu, phi1, phi2, sigmaSq, T):&amp;lt;/code&amp;gt;&lt;br /&gt;
    x = np.zeros(T+2)&lt;br /&gt;
    epsilon = np.random.normal(0,sigmaSq, T+2)&lt;br /&gt;
&lt;br /&gt;
    x[0] = mu / (1.0 - phi1-phi2)&lt;br /&gt;
    x[1] = mu / (1.0 - phi1-phi2)&lt;br /&gt;
&lt;br /&gt;
    for t in np.arange(T)+1:&lt;br /&gt;
        x[t+1] = mu + phi1 * x[t] + phi2 * x[t-1] + epsilon[t]&lt;br /&gt;
&lt;br /&gt;
    return x[2:]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;def trajectories2(mu, phi1, phi2, sigmaSq, T, n):&amp;lt;/code&amp;gt;&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates n-trajectories of AR(2) process&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param phi2:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :param n:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    X = np.zeros([n,T])&lt;br /&gt;
    for s in np.arange(n):&lt;br /&gt;
        X[s,:] = sim2(mu, phi1, phi2, sigmaSq, T)&lt;br /&gt;
    return X&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;class ARp(object):&amp;lt;/code&amp;gt;&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;AR(p) class allowing to estimate the model &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
    def __init__(self, x, p, pmax):&lt;br /&gt;
        self.p = p&lt;br /&gt;
        self.x = x&lt;br /&gt;
        self.T = float(x.size)&lt;br /&gt;
        self.par = np.zeros(p+2) #np.array: c, phi_1, phi_2, ... phi_p, sigma^2&lt;br /&gt;
&lt;br /&gt;
        #Init. matrices for OLS&lt;br /&gt;
        Y = self.x[pmax:]&lt;br /&gt;
        Xtemp = []&lt;br /&gt;
&lt;br /&gt;
        for i in np.arange(Y.size):&lt;br /&gt;
            Xtemp.append(np.flip(x[i:(pmax+i)],0))&lt;br /&gt;
        X = np.ones((Y.size, p+1))&lt;br /&gt;
        X[:,1:] = np.array(Xtemp)[:,:p]&lt;br /&gt;
&lt;br /&gt;
        #OLS Estimate&lt;br /&gt;
        Phi = np.dot(np.dot(inv(np.dot(X.T,X)),X.T),Y)&lt;br /&gt;
        SigmaS = np.sum((Y - np.dot(X, Phi))**2.0)/(self.T-pmax)&lt;br /&gt;
        self.par[:-1] = Phi[:]&lt;br /&gt;
        self.par[-1] = SigmaS&lt;br /&gt;
&lt;br /&gt;
        #t-ratios&lt;br /&gt;
        self.VCOV = inv(np.dot(X.T,X))*SigmaS&lt;br /&gt;
        self.SE = np.diag(self.VCOV)**0.5&lt;br /&gt;
        self.t = self.par[:-1]/self.SE&lt;br /&gt;
&lt;br /&gt;
        #likelihood and IC&lt;br /&gt;
        self.logL = (-(self.T-pmax)/2.0)*np.log(2.0*np.pi) + (-(self.T-pmax)/2.0)*np.log(SigmaS) + (-(self.T-pmax)/2.0)&lt;br /&gt;
        self.AIC = 2.0*((self.par.size)-self.logL)&lt;br /&gt;
        self.BIC = np.log(Y.size)*self.par.size-2.0*self.logL&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Simulation ===&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
import numpy as np&lt;br /&gt;
import models as mod&lt;br /&gt;
import matplotlib.pyplot as plt&lt;br /&gt;
from scipy.stats import norm&lt;br /&gt;
&lt;br /&gt;
pmax = 10&lt;br /&gt;
n = 5000&lt;br /&gt;
T1 = 200 &lt;br /&gt;
T2 = 2000 &lt;br /&gt;
&lt;br /&gt;
#1. AR(1) process&lt;br /&gt;
#phi = 0.9&lt;br /&gt;
#mu = 5.0&lt;br /&gt;
#sigmaSq = 1.0&lt;br /&gt;
#X1 = mod.trajectories1(mu, phi, sigmaSq, T1, n)&lt;br /&gt;
#X2 = mod.trajectories1(mu, phi, sigmaSq, T2, n)&lt;br /&gt;
&lt;br /&gt;
#2. AR(2) process&lt;br /&gt;
phi1 = 0.4&lt;br /&gt;
phi2 = 0.4&lt;br /&gt;
mu = 5.0&lt;br /&gt;
sigmaSq = 1.0&lt;br /&gt;
X1 = mod.trajectories2(mu, phi1, phi2, sigmaSq, T1, n) # Rows = individual series; columns = time periods&lt;br /&gt;
X2 = mod.trajectories2(mu, phi1, phi2, sigmaSq, T2, n)&lt;br /&gt;
&lt;br /&gt;
#####&lt;br /&gt;
#GETS General to specific method&lt;br /&gt;
#####&lt;br /&gt;
tquantile = norm.ppf(0.95) #95% quantile&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop1 = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    p = pmax&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:],p,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;lt; tquantile and p&amp;gt;0:&lt;br /&gt;
            p-=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop1.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T1 finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop2 = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    p = pmax&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:],p,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;lt; tquantile and p&amp;gt;0:&lt;br /&gt;
            p-=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop2.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T2 finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#Specific-to-General&lt;br /&gt;
&lt;br /&gt;
tquantile = norm.ppf(0.95) #95% quantile&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop1SOG = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    p = 0&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:],p+1,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;gt; tquantile and p&amp;lt;=pmax:&lt;br /&gt;
            p+=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop1SOG.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T1 finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop2SOG = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    p = 0&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:],p+1,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;gt; tquantile and p&amp;lt;=pmax:&lt;br /&gt;
            p+=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop2SOG.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T2 finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#AIC and BIC&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
AICp1 = []&lt;br /&gt;
BICp1 = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    AICtemp = np.zeros(11)&lt;br /&gt;
    BICtemp = np.zeros(11)&lt;br /&gt;
    for p in np.arange(pmax+1):&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:], p, pmax)&lt;br /&gt;
        AICtemp[p] = ARtemp.AIC&lt;br /&gt;
        BICtemp[p] = ARtemp.BIC&lt;br /&gt;
    AICp1.append(np.argmin(AICtemp))&lt;br /&gt;
    BICp1.append(np.argmin(BICtemp))&lt;br /&gt;
&lt;br /&gt;
print &amp;quot;T1 AIC+BIC finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
AICp2 = []&lt;br /&gt;
BICp2 = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    AICtemp = np.zeros(11)&lt;br /&gt;
    BICtemp = np.zeros(11)&lt;br /&gt;
    for p in np.arange(pmax+1):&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:], p, pmax)&lt;br /&gt;
        AICtemp[p] = ARtemp.AIC&lt;br /&gt;
        BICtemp[p] = ARtemp.BIC&lt;br /&gt;
    AICp2.append(np.argmin(AICtemp))&lt;br /&gt;
    BICp2.append(np.argmin(BICtemp))&lt;br /&gt;
print &amp;quot;T2 AIC+BIC finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#Plot&lt;br /&gt;
&lt;br /&gt;
fig, axes = plt.subplots(nrows=4, ncols=2)&lt;br /&gt;
ax0, ax1, ax2, ax3, ax4, ax5, ax6, ax7 = axes.flatten()&lt;br /&gt;
&lt;br /&gt;
ax0.hist(tratiop1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax0.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax0.set_title('GETS, T=200')&lt;br /&gt;
&lt;br /&gt;
ax1.hist(tratiop2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax1.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax1.set_title('GETS, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax2.hist(tratiop1SOG, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax2.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax2.set_title('Spec-to-Gen, T=200')&lt;br /&gt;
&lt;br /&gt;
ax3.hist(tratiop2SOG, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax3.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax3.set_title('Spec-to-Gen, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax4.hist(AICp1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax4.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax4.set_title('AIC, T=200')&lt;br /&gt;
&lt;br /&gt;
ax5.hist(AICp2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax5.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax5.set_title('AIC, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax6.hist(BICp1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax6.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax6.set_title('BIC, T=200')&lt;br /&gt;
&lt;br /&gt;
ax7.hist(BICp2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax7.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax7.set_title('BIC, T=2000')&lt;br /&gt;
&lt;br /&gt;
fig.subplots_adjust(hspace=0.5)&lt;br /&gt;
plt.show()&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;/div&gt;</summary>
		<author><name>Hazn00</name></author>
		
	</entry>
	<entry>
		<id>http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19135</id>
		<title>Time Series Model Building Process</title>
		<link rel="alternate" type="text/html" href="http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19135"/>
		<updated>2020-01-19T13:26:23Z</updated>

		<summary type="html">&lt;p&gt;Hazn00: /* Simulation */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Linear time series models, e.g., ARIMA models for univariate time series, is a popular tool for modeling dynamics of time series and predicting the time series. The methodology is not popular only in statistics, econometrics and science, but also in machine learning business applications. The key question is how to build the model. We have to choose the form of the model, in particular number of lags for so-called autoregressive part (usually denoted as p) and moving average part of the model (usually denoted as d). The common guides usually provide a ‘cook book’ for model selection, see for example [https://www.machinelearningplus.com/time-series/arima-model-time-series-forecasting-python/, ARIMA Model – Complete Guide to Time Series Forecasting in Python] . This goal of this simulation is to compare four basic methods for selection of lags (p) for the autoregressive part.&lt;br /&gt;
&lt;br /&gt;
== Problem Definition ==&lt;br /&gt;
&lt;br /&gt;
The autoregressive process has form&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\phi}_2x_{t-2}+...+{\phi}_px_{t-p} + {\epsilon}_t&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;{\epsilon}_t \sim N(0,{\sigma}^2) &amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
However, we observe only the realized value and we do not know the hyperparameter p. Therefore, we must estimate it. The considered methods are following.&lt;br /&gt;
&lt;br /&gt;
=== GETS (General-to-Specific) ===&lt;br /&gt;
&lt;br /&gt;
We first start with high enough p (pmax in the code), and perform statistical test whether the last lag has statistically significant impact, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p = 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p \neq 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the impact is insignificant, we reduce p by one and continue until the parameter for the last lag is significant, i.e. last lag has significant effect.&lt;br /&gt;
&lt;br /&gt;
=== Specific-to-General ===&lt;br /&gt;
&lt;br /&gt;
The second approach works similarly as GETS, the only difference is that we first start with model without any lag, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and we are adding lags until they are significant.&lt;br /&gt;
&lt;br /&gt;
=== BIC (Bayesian Information Criteria) ===&lt;br /&gt;
&lt;br /&gt;
Bayesian information criteria is based on a likelihood of the model and number of parameters. The criteria punish the model for high number of parameters for a potential over-fitting, and rewards the model for good fit of the data. The lower the BIC value is, the better the model (a little bit counterintuitive definition). We are supposed to select a model with the lowest value of BIC.&lt;br /&gt;
&lt;br /&gt;
=== AIC (Akaike Information Criteria)  ===&lt;br /&gt;
&lt;br /&gt;
Works exactly the same as BIC, but the formula is slightly different.&lt;br /&gt;
&lt;br /&gt;
== Method and Simulation Method ==&lt;br /&gt;
&lt;br /&gt;
The solution consists of three key elements, data generating process, AR(p) model, and simulation.&lt;br /&gt;
&lt;br /&gt;
=== Data Generating Process ===&lt;br /&gt;
&lt;br /&gt;
To answer the question, which model selection method is the best, we are creating an artificial data. We assume that data are created by AR(1) process&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
or AR(2)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\mu} + {\phi}_2x_{t-2} + {\epsilon}_{t}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
with random error &amp;lt;math&amp;gt;&amp;lt;/math&amp;gt; . Therefore, we must generate random numbers for random errors, and iterate over the equations described above. The initial values of the processes, e.g., &amp;lt;math&amp;gt;x_0&amp;lt;/math&amp;gt;, are set to the theoretical mean value of the process.&lt;br /&gt;
&lt;br /&gt;
=== AR(p) model ===&lt;br /&gt;
&lt;br /&gt;
For a given series &amp;lt;math&amp;gt;{x_1,x_2,...x_T}&amp;lt;/math&amp;gt; with a length ''T'' estimates a model for a given p.&lt;br /&gt;
&lt;br /&gt;
=== Simulation ===&lt;br /&gt;
&lt;br /&gt;
Perform n Monte Carlo simulations, where in each simulation a the data generating process is used to create a time series. Then the AR(p) model is estimated for ''p=0,1,…,pmax'', and the best models are selected according to the selection criteria described above. Therefore, we will obtain four estimates of p that corresponds to the described methods for each of the n simulation. The final step is to compute % success of correctly estimated p for each of four methods.&lt;br /&gt;
&lt;br /&gt;
== Controls ==&lt;br /&gt;
The solution allow to set number of simulation n. We need high enough n to make sure that the results will converge close enough to actual results. Therefore, we have set &amp;lt;math&amp;gt;n=5000&amp;lt;/math&amp;gt;. Higher n will not significantly increase the precision of the results.&lt;br /&gt;
&lt;br /&gt;
The more important controls is selection of AR(1) or AR(2) process, and selection of parameters &amp;lt;math&amp;gt;{\mu},{\sigma},{\phi}_1&amp;lt;/math&amp;gt;  and  &amp;lt;math&amp;gt;{\phi}_2&amp;lt;/math&amp;gt; for the process. Additionally, we can set length of the generated series and even compare performance for series with two distinct lengths &amp;lt;math&amp;gt;T_1&amp;lt;/math&amp;gt; and &amp;lt;math&amp;gt;T_2&amp;lt;/math&amp;gt;. In other words, one method may perform better for low number of observations than other, and this control allow to compare the performance.&lt;br /&gt;
&lt;br /&gt;
== Results ==&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
&lt;br /&gt;
== Code ==&lt;br /&gt;
=== Model ===&lt;br /&gt;
&lt;br /&gt;
import numpy as np&lt;br /&gt;
from numpy.linalg import inv&lt;br /&gt;
from scipy.stats import norm&lt;br /&gt;
&lt;br /&gt;
def sim1(mu, phi1, sigmaSq, T):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates single trajectory.&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    x = np.zeros(T+1)&lt;br /&gt;
    epsilon = np.random.normal(0,sigmaSq, T+1)&lt;br /&gt;
&lt;br /&gt;
    x[0] = mu / (1.0 - phi1)&lt;br /&gt;
&lt;br /&gt;
    for t in np.arange(T):&lt;br /&gt;
        x[t+1] = mu + phi1 * x[t] + epsilon[t]&lt;br /&gt;
&lt;br /&gt;
    return x[1:]&lt;br /&gt;
&lt;br /&gt;
def trajectories1(mu, phi1, sigmaSq, T, n):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates n-trajectories of AR(1) process&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :param n:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    X = np.zeros([n,T])&lt;br /&gt;
    for s in np.arange(n):&lt;br /&gt;
        X[s,:] = sim1(mu, phi1, sigmaSq, T)&lt;br /&gt;
    return X&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
def sim2(mu, phi1, phi2, sigmaSq, T):&lt;br /&gt;
    x = np.zeros(T+2)&lt;br /&gt;
    epsilon = np.random.normal(0,sigmaSq, T+2)&lt;br /&gt;
&lt;br /&gt;
    x[0] = mu / (1.0 - phi1-phi2)&lt;br /&gt;
    x[1] = mu / (1.0 - phi1-phi2)&lt;br /&gt;
&lt;br /&gt;
    for t in np.arange(T)+1:&lt;br /&gt;
        x[t+1] = mu + phi1 * x[t] + phi2 * x[t-1] + epsilon[t]&lt;br /&gt;
&lt;br /&gt;
    return x[2:]&lt;br /&gt;
&lt;br /&gt;
def trajectories2(mu, phi1, phi2, sigmaSq, T, n):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates n-trajectories of AR(2) process&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param phi2:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :param n:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    X = np.zeros([n,T])&lt;br /&gt;
    for s in np.arange(n):&lt;br /&gt;
        X[s,:] = sim2(mu, phi1, phi2, sigmaSq, T)&lt;br /&gt;
    return X&lt;br /&gt;
&lt;br /&gt;
class ARp(object):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;AR(p) class allowing to estimate the model &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
    def __init__(self, x, p, pmax):&lt;br /&gt;
        self.p = p&lt;br /&gt;
        self.x = x&lt;br /&gt;
        self.T = float(x.size)&lt;br /&gt;
        self.par = np.zeros(p+2) #np.array: c, phi_1, phi_2, ... phi_p, sigma^2&lt;br /&gt;
&lt;br /&gt;
        #Init. matrices for OLS&lt;br /&gt;
        Y = self.x[pmax:]&lt;br /&gt;
        Xtemp = []&lt;br /&gt;
&lt;br /&gt;
        for i in np.arange(Y.size):&lt;br /&gt;
            Xtemp.append(np.flip(x[i:(pmax+i)],0))&lt;br /&gt;
        X = np.ones((Y.size, p+1))&lt;br /&gt;
        X[:,1:] = np.array(Xtemp)[:,:p]&lt;br /&gt;
&lt;br /&gt;
        #OLS Estimate&lt;br /&gt;
        Phi = np.dot(np.dot(inv(np.dot(X.T,X)),X.T),Y)&lt;br /&gt;
        SigmaS = np.sum((Y - np.dot(X, Phi))**2.0)/(self.T-pmax)&lt;br /&gt;
        self.par[:-1] = Phi[:]&lt;br /&gt;
        self.par[-1] = SigmaS&lt;br /&gt;
&lt;br /&gt;
        #t-ratios&lt;br /&gt;
        self.VCOV = inv(np.dot(X.T,X))*SigmaS&lt;br /&gt;
        self.SE = np.diag(self.VCOV)**0.5&lt;br /&gt;
        self.t = self.par[:-1]/self.SE&lt;br /&gt;
&lt;br /&gt;
        #likelihood and IC&lt;br /&gt;
        self.logL = (-(self.T-pmax)/2.0)*np.log(2.0*np.pi) + (-(self.T-pmax)/2.0)*np.log(SigmaS) + (-(self.T-pmax)/2.0)&lt;br /&gt;
        self.AIC = 2.0*((self.par.size)-self.logL)&lt;br /&gt;
        self.BIC = np.log(Y.size)*self.par.size-2.0*self.logL&lt;br /&gt;
&lt;br /&gt;
=== Simulation ===&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
import numpy as np&lt;br /&gt;
import models as mod&lt;br /&gt;
import matplotlib.pyplot as plt&lt;br /&gt;
from scipy.stats import norm&lt;br /&gt;
&lt;br /&gt;
pmax = 10&lt;br /&gt;
n = 5000&lt;br /&gt;
T1 = 200 &lt;br /&gt;
T2 = 2000 &lt;br /&gt;
&lt;br /&gt;
#1. AR(1) process&lt;br /&gt;
#phi = 0.9&lt;br /&gt;
#mu = 5.0&lt;br /&gt;
#sigmaSq = 1.0&lt;br /&gt;
#X1 = mod.trajectories1(mu, phi, sigmaSq, T1, n)&lt;br /&gt;
#X2 = mod.trajectories1(mu, phi, sigmaSq, T2, n)&lt;br /&gt;
&lt;br /&gt;
#2. AR(2) process&lt;br /&gt;
phi1 = 0.4&lt;br /&gt;
phi2 = 0.4&lt;br /&gt;
mu = 5.0&lt;br /&gt;
sigmaSq = 1.0&lt;br /&gt;
X1 = mod.trajectories2(mu, phi1, phi2, sigmaSq, T1, n) # Rows = individual series; columns = time periods&lt;br /&gt;
X2 = mod.trajectories2(mu, phi1, phi2, sigmaSq, T2, n)&lt;br /&gt;
&lt;br /&gt;
#####&lt;br /&gt;
#GETS General to specific method&lt;br /&gt;
#####&lt;br /&gt;
tquantile = norm.ppf(0.95) #95% quantile&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop1 = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    p = pmax&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:],p,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;lt; tquantile and p&amp;gt;0:&lt;br /&gt;
            p-=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop1.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T1 finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop2 = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    p = pmax&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:],p,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;lt; tquantile and p&amp;gt;0:&lt;br /&gt;
            p-=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop2.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T2 finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#Specific-to-General&lt;br /&gt;
&lt;br /&gt;
tquantile = norm.ppf(0.95) #95% quantile&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop1SOG = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    p = 0&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:],p+1,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;gt; tquantile and p&amp;lt;=pmax:&lt;br /&gt;
            p+=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop1SOG.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T1 finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop2SOG = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    p = 0&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:],p+1,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;gt; tquantile and p&amp;lt;=pmax:&lt;br /&gt;
            p+=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop2SOG.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T2 finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#AIC and BIC&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
AICp1 = []&lt;br /&gt;
BICp1 = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    AICtemp = np.zeros(11)&lt;br /&gt;
    BICtemp = np.zeros(11)&lt;br /&gt;
    for p in np.arange(pmax+1):&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:], p, pmax)&lt;br /&gt;
        AICtemp[p] = ARtemp.AIC&lt;br /&gt;
        BICtemp[p] = ARtemp.BIC&lt;br /&gt;
    AICp1.append(np.argmin(AICtemp))&lt;br /&gt;
    BICp1.append(np.argmin(BICtemp))&lt;br /&gt;
&lt;br /&gt;
print &amp;quot;T1 AIC+BIC finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
AICp2 = []&lt;br /&gt;
BICp2 = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    AICtemp = np.zeros(11)&lt;br /&gt;
    BICtemp = np.zeros(11)&lt;br /&gt;
    for p in np.arange(pmax+1):&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:], p, pmax)&lt;br /&gt;
        AICtemp[p] = ARtemp.AIC&lt;br /&gt;
        BICtemp[p] = ARtemp.BIC&lt;br /&gt;
    AICp2.append(np.argmin(AICtemp))&lt;br /&gt;
    BICp2.append(np.argmin(BICtemp))&lt;br /&gt;
print &amp;quot;T2 AIC+BIC finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#Plot&lt;br /&gt;
&lt;br /&gt;
fig, axes = plt.subplots(nrows=4, ncols=2)&lt;br /&gt;
ax0, ax1, ax2, ax3, ax4, ax5, ax6, ax7 = axes.flatten()&lt;br /&gt;
&lt;br /&gt;
ax0.hist(tratiop1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax0.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax0.set_title('GETS, T=200')&lt;br /&gt;
&lt;br /&gt;
ax1.hist(tratiop2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax1.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax1.set_title('GETS, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax2.hist(tratiop1SOG, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax2.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax2.set_title('Spec-to-Gen, T=200')&lt;br /&gt;
&lt;br /&gt;
ax3.hist(tratiop2SOG, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax3.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax3.set_title('Spec-to-Gen, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax4.hist(AICp1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax4.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax4.set_title('AIC, T=200')&lt;br /&gt;
&lt;br /&gt;
ax5.hist(AICp2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax5.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax5.set_title('AIC, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax6.hist(BICp1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax6.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax6.set_title('BIC, T=200')&lt;br /&gt;
&lt;br /&gt;
ax7.hist(BICp2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax7.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax7.set_title('BIC, T=2000')&lt;br /&gt;
&lt;br /&gt;
fig.subplots_adjust(hspace=0.5)&lt;br /&gt;
plt.show()&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;/div&gt;</summary>
		<author><name>Hazn00</name></author>
		
	</entry>
	<entry>
		<id>http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19134</id>
		<title>Time Series Model Building Process</title>
		<link rel="alternate" type="text/html" href="http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19134"/>
		<updated>2020-01-19T13:17:43Z</updated>

		<summary type="html">&lt;p&gt;Hazn00: /* Model */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Linear time series models, e.g., ARIMA models for univariate time series, is a popular tool for modeling dynamics of time series and predicting the time series. The methodology is not popular only in statistics, econometrics and science, but also in machine learning business applications. The key question is how to build the model. We have to choose the form of the model, in particular number of lags for so-called autoregressive part (usually denoted as p) and moving average part of the model (usually denoted as d). The common guides usually provide a ‘cook book’ for model selection, see for example [https://www.machinelearningplus.com/time-series/arima-model-time-series-forecasting-python/, ARIMA Model – Complete Guide to Time Series Forecasting in Python] . This goal of this simulation is to compare four basic methods for selection of lags (p) for the autoregressive part.&lt;br /&gt;
&lt;br /&gt;
== Problem Definition ==&lt;br /&gt;
&lt;br /&gt;
The autoregressive process has form&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\phi}_2x_{t-2}+...+{\phi}_px_{t-p} + {\epsilon}_t&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;{\epsilon}_t \sim N(0,{\sigma}^2) &amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
However, we observe only the realized value and we do not know the hyperparameter p. Therefore, we must estimate it. The considered methods are following.&lt;br /&gt;
&lt;br /&gt;
=== GETS (General-to-Specific) ===&lt;br /&gt;
&lt;br /&gt;
We first start with high enough p (pmax in the code), and perform statistical test whether the last lag has statistically significant impact, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p = 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p \neq 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the impact is insignificant, we reduce p by one and continue until the parameter for the last lag is significant, i.e. last lag has significant effect.&lt;br /&gt;
&lt;br /&gt;
=== Specific-to-General ===&lt;br /&gt;
&lt;br /&gt;
The second approach works similarly as GETS, the only difference is that we first start with model without any lag, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and we are adding lags until they are significant.&lt;br /&gt;
&lt;br /&gt;
=== BIC (Bayesian Information Criteria) ===&lt;br /&gt;
&lt;br /&gt;
Bayesian information criteria is based on a likelihood of the model and number of parameters. The criteria punish the model for high number of parameters for a potential over-fitting, and rewards the model for good fit of the data. The lower the BIC value is, the better the model (a little bit counterintuitive definition). We are supposed to select a model with the lowest value of BIC.&lt;br /&gt;
&lt;br /&gt;
=== AIC (Akaike Information Criteria)  ===&lt;br /&gt;
&lt;br /&gt;
Works exactly the same as BIC, but the formula is slightly different.&lt;br /&gt;
&lt;br /&gt;
== Method and Simulation Method ==&lt;br /&gt;
&lt;br /&gt;
The solution consists of three key elements, data generating process, AR(p) model, and simulation.&lt;br /&gt;
&lt;br /&gt;
=== Data Generating Process ===&lt;br /&gt;
&lt;br /&gt;
To answer the question, which model selection method is the best, we are creating an artificial data. We assume that data are created by AR(1) process&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
or AR(2)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\mu} + {\phi}_2x_{t-2} + {\epsilon}_{t}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
with random error &amp;lt;math&amp;gt;&amp;lt;/math&amp;gt; . Therefore, we must generate random numbers for random errors, and iterate over the equations described above. The initial values of the processes, e.g., &amp;lt;math&amp;gt;x_0&amp;lt;/math&amp;gt;, are set to the theoretical mean value of the process.&lt;br /&gt;
&lt;br /&gt;
=== AR(p) model ===&lt;br /&gt;
&lt;br /&gt;
For a given series &amp;lt;math&amp;gt;{x_1,x_2,...x_T}&amp;lt;/math&amp;gt; with a length ''T'' estimates a model for a given p.&lt;br /&gt;
&lt;br /&gt;
=== Simulation ===&lt;br /&gt;
&lt;br /&gt;
Perform n Monte Carlo simulations, where in each simulation a the data generating process is used to create a time series. Then the AR(p) model is estimated for ''p=0,1,…,pmax'', and the best models are selected according to the selection criteria described above. Therefore, we will obtain four estimates of p that corresponds to the described methods for each of the n simulation. The final step is to compute % success of correctly estimated p for each of four methods.&lt;br /&gt;
&lt;br /&gt;
== Controls ==&lt;br /&gt;
The solution allow to set number of simulation n. We need high enough n to make sure that the results will converge close enough to actual results. Therefore, we have set &amp;lt;math&amp;gt;n=5000&amp;lt;/math&amp;gt;. Higher n will not significantly increase the precision of the results.&lt;br /&gt;
&lt;br /&gt;
The more important controls is selection of AR(1) or AR(2) process, and selection of parameters &amp;lt;math&amp;gt;{\mu},{\sigma},{\phi}_1&amp;lt;/math&amp;gt;  and  &amp;lt;math&amp;gt;{\phi}_2&amp;lt;/math&amp;gt; for the process. Additionally, we can set length of the generated series and even compare performance for series with two distinct lengths &amp;lt;math&amp;gt;T_1&amp;lt;/math&amp;gt; and &amp;lt;math&amp;gt;T_2&amp;lt;/math&amp;gt;. In other words, one method may perform better for low number of observations than other, and this control allow to compare the performance.&lt;br /&gt;
&lt;br /&gt;
== Results ==&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
&lt;br /&gt;
== Code ==&lt;br /&gt;
=== Model ===&lt;br /&gt;
&lt;br /&gt;
import numpy as np&lt;br /&gt;
from numpy.linalg import inv&lt;br /&gt;
from scipy.stats import norm&lt;br /&gt;
&lt;br /&gt;
def sim1(mu, phi1, sigmaSq, T):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates single trajectory.&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    x = np.zeros(T+1)&lt;br /&gt;
    epsilon = np.random.normal(0,sigmaSq, T+1)&lt;br /&gt;
&lt;br /&gt;
    x[0] = mu / (1.0 - phi1)&lt;br /&gt;
&lt;br /&gt;
    for t in np.arange(T):&lt;br /&gt;
        x[t+1] = mu + phi1 * x[t] + epsilon[t]&lt;br /&gt;
&lt;br /&gt;
    return x[1:]&lt;br /&gt;
&lt;br /&gt;
def trajectories1(mu, phi1, sigmaSq, T, n):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates n-trajectories of AR(1) process&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :param n:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    X = np.zeros([n,T])&lt;br /&gt;
    for s in np.arange(n):&lt;br /&gt;
        X[s,:] = sim1(mu, phi1, sigmaSq, T)&lt;br /&gt;
    return X&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
def sim2(mu, phi1, phi2, sigmaSq, T):&lt;br /&gt;
    x = np.zeros(T+2)&lt;br /&gt;
    epsilon = np.random.normal(0,sigmaSq, T+2)&lt;br /&gt;
&lt;br /&gt;
    x[0] = mu / (1.0 - phi1-phi2)&lt;br /&gt;
    x[1] = mu / (1.0 - phi1-phi2)&lt;br /&gt;
&lt;br /&gt;
    for t in np.arange(T)+1:&lt;br /&gt;
        x[t+1] = mu + phi1 * x[t] + phi2 * x[t-1] + epsilon[t]&lt;br /&gt;
&lt;br /&gt;
    return x[2:]&lt;br /&gt;
&lt;br /&gt;
def trajectories2(mu, phi1, phi2, sigmaSq, T, n):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates n-trajectories of AR(2) process&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param phi2:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :param n:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    X = np.zeros([n,T])&lt;br /&gt;
    for s in np.arange(n):&lt;br /&gt;
        X[s,:] = sim2(mu, phi1, phi2, sigmaSq, T)&lt;br /&gt;
    return X&lt;br /&gt;
&lt;br /&gt;
class ARp(object):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;AR(p) class allowing to estimate the model &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
    def __init__(self, x, p, pmax):&lt;br /&gt;
        self.p = p&lt;br /&gt;
        self.x = x&lt;br /&gt;
        self.T = float(x.size)&lt;br /&gt;
        self.par = np.zeros(p+2) #np.array: c, phi_1, phi_2, ... phi_p, sigma^2&lt;br /&gt;
&lt;br /&gt;
        #Init. matrices for OLS&lt;br /&gt;
        Y = self.x[pmax:]&lt;br /&gt;
        Xtemp = []&lt;br /&gt;
&lt;br /&gt;
        for i in np.arange(Y.size):&lt;br /&gt;
            Xtemp.append(np.flip(x[i:(pmax+i)],0))&lt;br /&gt;
        X = np.ones((Y.size, p+1))&lt;br /&gt;
        X[:,1:] = np.array(Xtemp)[:,:p]&lt;br /&gt;
&lt;br /&gt;
        #OLS Estimate&lt;br /&gt;
        Phi = np.dot(np.dot(inv(np.dot(X.T,X)),X.T),Y)&lt;br /&gt;
        SigmaS = np.sum((Y - np.dot(X, Phi))**2.0)/(self.T-pmax)&lt;br /&gt;
        self.par[:-1] = Phi[:]&lt;br /&gt;
        self.par[-1] = SigmaS&lt;br /&gt;
&lt;br /&gt;
        #t-ratios&lt;br /&gt;
        self.VCOV = inv(np.dot(X.T,X))*SigmaS&lt;br /&gt;
        self.SE = np.diag(self.VCOV)**0.5&lt;br /&gt;
        self.t = self.par[:-1]/self.SE&lt;br /&gt;
&lt;br /&gt;
        #likelihood and IC&lt;br /&gt;
        self.logL = (-(self.T-pmax)/2.0)*np.log(2.0*np.pi) + (-(self.T-pmax)/2.0)*np.log(SigmaS) + (-(self.T-pmax)/2.0)&lt;br /&gt;
        self.AIC = 2.0*((self.par.size)-self.logL)&lt;br /&gt;
        self.BIC = np.log(Y.size)*self.par.size-2.0*self.logL&lt;br /&gt;
&lt;br /&gt;
=== Simulation ===&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
import numpy as np&lt;br /&gt;
import models as mod&lt;br /&gt;
import matplotlib.pyplot as plt&lt;br /&gt;
from scipy.stats import norm&lt;br /&gt;
##########################&lt;br /&gt;
#Simulation and settings&lt;br /&gt;
#########################&lt;br /&gt;
#general&lt;br /&gt;
pmax = 10 # Maximum number of lags&lt;br /&gt;
n = 5000 # Number of simulations&lt;br /&gt;
T1 = 200 # Length of the first time series&lt;br /&gt;
T2 = 2000 # Length of the second time series&lt;br /&gt;
&lt;br /&gt;
#1. AR(1) process&lt;br /&gt;
#phi = 0.9&lt;br /&gt;
#mu = 5.0&lt;br /&gt;
#sigmaSq = 1.0&lt;br /&gt;
#X1 = mod.trajectories1(mu, phi, sigmaSq, T1, n)&lt;br /&gt;
#X2 = mod.trajectories1(mu, phi, sigmaSq, T2, n)&lt;br /&gt;
&lt;br /&gt;
#2. AR(2) process&lt;br /&gt;
phi1 = 0.4&lt;br /&gt;
phi2 = 0.4&lt;br /&gt;
mu = 5.0&lt;br /&gt;
sigmaSq = 1.0&lt;br /&gt;
X1 = mod.trajectories2(mu, phi1, phi2, sigmaSq, T1, n) # Rows = individual series; columns = time periods&lt;br /&gt;
X2 = mod.trajectories2(mu, phi1, phi2, sigmaSq, T2, n)&lt;br /&gt;
&lt;br /&gt;
#####&lt;br /&gt;
#GETS General to specific method&lt;br /&gt;
#####&lt;br /&gt;
tquantile = norm.ppf(0.95) #95% quantile&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop1 = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    p = pmax&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:],p,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;lt; tquantile and p&amp;gt;0:&lt;br /&gt;
            p-=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop1.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T1 finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop2 = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    p = pmax&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:],p,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;lt; tquantile and p&amp;gt;0:&lt;br /&gt;
            p-=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop2.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T2 finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
####################&lt;br /&gt;
#Specific-to-General&lt;br /&gt;
####################&lt;br /&gt;
tquantile = norm.ppf(0.95) #95% quantile&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop1SOG = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    p = 0&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:],p+1,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;gt; tquantile and p&amp;lt;=pmax:&lt;br /&gt;
            p+=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop1SOG.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T1 finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop2SOG = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    p = 0&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:],p+1,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;gt; tquantile and p&amp;lt;=pmax:&lt;br /&gt;
            p+=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop2SOG.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T2 finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
####################&lt;br /&gt;
#AIC and BIC&lt;br /&gt;
####################&lt;br /&gt;
#T1 simulation&lt;br /&gt;
AICp1 = []&lt;br /&gt;
BICp1 = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    AICtemp = np.zeros(11)&lt;br /&gt;
    BICtemp = np.zeros(11)&lt;br /&gt;
    for p in np.arange(pmax+1):&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:], p, pmax)&lt;br /&gt;
        AICtemp[p] = ARtemp.AIC&lt;br /&gt;
        BICtemp[p] = ARtemp.BIC&lt;br /&gt;
    AICp1.append(np.argmin(AICtemp))&lt;br /&gt;
    BICp1.append(np.argmin(BICtemp))&lt;br /&gt;
&lt;br /&gt;
print &amp;quot;T1 AIC+BIC finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
AICp2 = []&lt;br /&gt;
BICp2 = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    AICtemp = np.zeros(11)&lt;br /&gt;
    BICtemp = np.zeros(11)&lt;br /&gt;
    for p in np.arange(pmax+1):&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:], p, pmax)&lt;br /&gt;
        AICtemp[p] = ARtemp.AIC&lt;br /&gt;
        BICtemp[p] = ARtemp.BIC&lt;br /&gt;
    AICp2.append(np.argmin(AICtemp))&lt;br /&gt;
    BICp2.append(np.argmin(BICtemp))&lt;br /&gt;
print &amp;quot;T2 AIC+BIC finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
####################&lt;br /&gt;
#Plot&lt;br /&gt;
####################&lt;br /&gt;
&lt;br /&gt;
fig, axes = plt.subplots(nrows=4, ncols=2)&lt;br /&gt;
ax0, ax1, ax2, ax3, ax4, ax5, ax6, ax7 = axes.flatten()&lt;br /&gt;
&lt;br /&gt;
ax0.hist(tratiop1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax0.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax0.set_title('GETS, T=200')&lt;br /&gt;
&lt;br /&gt;
ax1.hist(tratiop2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax1.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax1.set_title('GETS, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax2.hist(tratiop1SOG, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax2.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax2.set_title('Spec-to-Gen, T=200')&lt;br /&gt;
&lt;br /&gt;
ax3.hist(tratiop2SOG, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax3.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax3.set_title('Spec-to-Gen, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax4.hist(AICp1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax4.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax4.set_title('AIC, T=200')&lt;br /&gt;
&lt;br /&gt;
ax5.hist(AICp2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax5.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax5.set_title('AIC, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax6.hist(BICp1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax6.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax6.set_title('BIC, T=200')&lt;br /&gt;
&lt;br /&gt;
ax7.hist(BICp2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax7.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax7.set_title('BIC, T=2000')&lt;br /&gt;
&lt;br /&gt;
fig.subplots_adjust(hspace=0.5)&lt;br /&gt;
plt.show()&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;/div&gt;</summary>
		<author><name>Hazn00</name></author>
		
	</entry>
	<entry>
		<id>http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19133</id>
		<title>Time Series Model Building Process</title>
		<link rel="alternate" type="text/html" href="http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19133"/>
		<updated>2020-01-18T14:52:23Z</updated>

		<summary type="html">&lt;p&gt;Hazn00: /* Model */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Linear time series models, e.g., ARIMA models for univariate time series, is a popular tool for modeling dynamics of time series and predicting the time series. The methodology is not popular only in statistics, econometrics and science, but also in machine learning business applications. The key question is how to build the model. We have to choose the form of the model, in particular number of lags for so-called autoregressive part (usually denoted as p) and moving average part of the model (usually denoted as d). The common guides usually provide a ‘cook book’ for model selection, see for example [https://www.machinelearningplus.com/time-series/arima-model-time-series-forecasting-python/, ARIMA Model – Complete Guide to Time Series Forecasting in Python] . This goal of this simulation is to compare four basic methods for selection of lags (p) for the autoregressive part.&lt;br /&gt;
&lt;br /&gt;
== Problem Definition ==&lt;br /&gt;
&lt;br /&gt;
The autoregressive process has form&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\phi}_2x_{t-2}+...+{\phi}_px_{t-p} + {\epsilon}_t&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;{\epsilon}_t \sim N(0,{\sigma}^2) &amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
However, we observe only the realized value and we do not know the hyperparameter p. Therefore, we must estimate it. The considered methods are following.&lt;br /&gt;
&lt;br /&gt;
=== GETS (General-to-Specific) ===&lt;br /&gt;
&lt;br /&gt;
We first start with high enough p (pmax in the code), and perform statistical test whether the last lag has statistically significant impact, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p = 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p \neq 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the impact is insignificant, we reduce p by one and continue until the parameter for the last lag is significant, i.e. last lag has significant effect.&lt;br /&gt;
&lt;br /&gt;
=== Specific-to-General ===&lt;br /&gt;
&lt;br /&gt;
The second approach works similarly as GETS, the only difference is that we first start with model without any lag, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and we are adding lags until they are significant.&lt;br /&gt;
&lt;br /&gt;
=== BIC (Bayesian Information Criteria) ===&lt;br /&gt;
&lt;br /&gt;
Bayesian information criteria is based on a likelihood of the model and number of parameters. The criteria punish the model for high number of parameters for a potential over-fitting, and rewards the model for good fit of the data. The lower the BIC value is, the better the model (a little bit counterintuitive definition). We are supposed to select a model with the lowest value of BIC.&lt;br /&gt;
&lt;br /&gt;
=== AIC (Akaike Information Criteria)  ===&lt;br /&gt;
&lt;br /&gt;
Works exactly the same as BIC, but the formula is slightly different.&lt;br /&gt;
&lt;br /&gt;
== Method and Simulation Method ==&lt;br /&gt;
&lt;br /&gt;
The solution consists of three key elements, data generating process, AR(p) model, and simulation.&lt;br /&gt;
&lt;br /&gt;
=== Data Generating Process ===&lt;br /&gt;
&lt;br /&gt;
To answer the question, which model selection method is the best, we are creating an artificial data. We assume that data are created by AR(1) process&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
or AR(2)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\mu} + {\phi}_2x_{t-2} + {\epsilon}_{t}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
with random error &amp;lt;math&amp;gt;&amp;lt;/math&amp;gt; . Therefore, we must generate random numbers for random errors, and iterate over the equations described above. The initial values of the processes, e.g., &amp;lt;math&amp;gt;x_0&amp;lt;/math&amp;gt;, are set to the theoretical mean value of the process.&lt;br /&gt;
&lt;br /&gt;
=== AR(p) model ===&lt;br /&gt;
&lt;br /&gt;
For a given series &amp;lt;math&amp;gt;{x_1,x_2,...x_T}&amp;lt;/math&amp;gt; with a length ''T'' estimates a model for a given p.&lt;br /&gt;
&lt;br /&gt;
=== Simulation ===&lt;br /&gt;
&lt;br /&gt;
Perform n Monte Carlo simulations, where in each simulation a the data generating process is used to create a time series. Then the AR(p) model is estimated for ''p=0,1,…,pmax'', and the best models are selected according to the selection criteria described above. Therefore, we will obtain four estimates of p that corresponds to the described methods for each of the n simulation. The final step is to compute % success of correctly estimated p for each of four methods.&lt;br /&gt;
&lt;br /&gt;
== Controls ==&lt;br /&gt;
The solution allow to set number of simulation n. We need high enough n to make sure that the results will converge close enough to actual results. Therefore, we have set &amp;lt;math&amp;gt;n=5000&amp;lt;/math&amp;gt;. Higher n will not significantly increase the precision of the results.&lt;br /&gt;
&lt;br /&gt;
The more important controls is selection of AR(1) or AR(2) process, and selection of parameters &amp;lt;math&amp;gt;{\mu},{\sigma},{\phi}_1&amp;lt;/math&amp;gt;  and  &amp;lt;math&amp;gt;{\phi}_2&amp;lt;/math&amp;gt; for the process. Additionally, we can set length of the generated series and even compare performance for series with two distinct lengths &amp;lt;math&amp;gt;T_1&amp;lt;/math&amp;gt; and &amp;lt;math&amp;gt;T_2&amp;lt;/math&amp;gt;. In other words, one method may perform better for low number of observations than other, and this control allow to compare the performance.&lt;br /&gt;
&lt;br /&gt;
== Results ==&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
&lt;br /&gt;
== Code ==&lt;br /&gt;
=== Model ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
import numpy as np&lt;br /&gt;
from numpy.linalg import inv&lt;br /&gt;
from scipy.stats import norm&lt;br /&gt;
&lt;br /&gt;
def sim1(mu, phi1, sigmaSq, T):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates single trajectory.&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    x = np.zeros(T+1)&lt;br /&gt;
    epsilon = np.random.normal(0,sigmaSq, T+1)&lt;br /&gt;
&lt;br /&gt;
    x[0] = mu / (1.0 - phi1)&lt;br /&gt;
&lt;br /&gt;
    for t in np.arange(T):&lt;br /&gt;
        x[t+1] = mu + phi1 * x[t] + epsilon[t]&lt;br /&gt;
&lt;br /&gt;
    return x[1:]&lt;br /&gt;
&lt;br /&gt;
def trajectories1(mu, phi1, sigmaSq, T, n):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates n-trajectories of AR(1) process&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :param n:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    X = np.zeros([n,T])&lt;br /&gt;
    for s in np.arange(n):&lt;br /&gt;
        X[s,:] = sim1(mu, phi1, sigmaSq, T)&lt;br /&gt;
    return X&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
def sim2(mu, phi1, phi2, sigmaSq, T):&lt;br /&gt;
    x = np.zeros(T+2)&lt;br /&gt;
    epsilon = np.random.normal(0,sigmaSq, T+2)&lt;br /&gt;
&lt;br /&gt;
    x[0] = mu / (1.0 - phi1-phi2)&lt;br /&gt;
    x[1] = mu / (1.0 - phi1-phi2)&lt;br /&gt;
&lt;br /&gt;
    for t in np.arange(T)+1:&lt;br /&gt;
        x[t+1] = mu + phi1 * x[t] + phi2 * x[t-1] + epsilon[t]&lt;br /&gt;
&lt;br /&gt;
    return x[2:]&lt;br /&gt;
&lt;br /&gt;
def trajectories2(mu, phi1, phi2, sigmaSq, T, n):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates n-trajectories of AR(2) process&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param phi2:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :param n:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    X = np.zeros([n,T])&lt;br /&gt;
    for s in np.arange(n):&lt;br /&gt;
        X[s,:] = sim2(mu, phi1, phi2, sigmaSq, T)&lt;br /&gt;
    return X&lt;br /&gt;
&lt;br /&gt;
class ARp(object):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;AR(p) class allowing to estimate the model &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
    def __init__(self, x, p, pmax):&lt;br /&gt;
        self.p = p&lt;br /&gt;
        self.x = x&lt;br /&gt;
        self.T = float(x.size)&lt;br /&gt;
        self.par = np.zeros(p+2) #np.array: c, phi_1, phi_2, ... phi_p, sigma^2&lt;br /&gt;
&lt;br /&gt;
        #Init. matrices for OLS&lt;br /&gt;
        Y = self.x[pmax:]&lt;br /&gt;
        Xtemp = []&lt;br /&gt;
&lt;br /&gt;
        for i in np.arange(Y.size):&lt;br /&gt;
            Xtemp.append(np.flip(x[i:(pmax+i)],0))&lt;br /&gt;
        X = np.ones((Y.size, p+1))&lt;br /&gt;
        X[:,1:] = np.array(Xtemp)[:,:p]&lt;br /&gt;
&lt;br /&gt;
        #OLS Estimate&lt;br /&gt;
        Phi = np.dot(np.dot(inv(np.dot(X.T,X)),X.T),Y)&lt;br /&gt;
        SigmaS = np.sum((Y - np.dot(X, Phi))**2.0)/(self.T-pmax)&lt;br /&gt;
        self.par[:-1] = Phi[:]&lt;br /&gt;
        self.par[-1] = SigmaS&lt;br /&gt;
&lt;br /&gt;
        #t-ratios&lt;br /&gt;
        self.VCOV = inv(np.dot(X.T,X))*SigmaS&lt;br /&gt;
        self.SE = np.diag(self.VCOV)**0.5&lt;br /&gt;
        self.t = self.par[:-1]/self.SE&lt;br /&gt;
&lt;br /&gt;
        #likelihood and IC&lt;br /&gt;
        self.logL = (-(self.T-pmax)/2.0)*np.log(2.0*np.pi) + (-(self.T-pmax)/2.0)*np.log(SigmaS) + (-(self.T-pmax)/2.0)&lt;br /&gt;
        self.AIC = 2.0*((self.par.size)-self.logL)&lt;br /&gt;
        self.BIC = np.log(Y.size)*self.par.size-2.0*self.logL&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Simulation ===&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
import numpy as np&lt;br /&gt;
import models as mod&lt;br /&gt;
import matplotlib.pyplot as plt&lt;br /&gt;
from scipy.stats import norm&lt;br /&gt;
##########################&lt;br /&gt;
#Simulation and settings&lt;br /&gt;
#########################&lt;br /&gt;
#general&lt;br /&gt;
pmax = 10 # Maximum number of lags&lt;br /&gt;
n = 5000 # Number of simulations&lt;br /&gt;
T1 = 200 # Length of the first time series&lt;br /&gt;
T2 = 2000 # Length of the second time series&lt;br /&gt;
&lt;br /&gt;
#1. AR(1) process&lt;br /&gt;
#phi = 0.9&lt;br /&gt;
#mu = 5.0&lt;br /&gt;
#sigmaSq = 1.0&lt;br /&gt;
#X1 = mod.trajectories1(mu, phi, sigmaSq, T1, n)&lt;br /&gt;
#X2 = mod.trajectories1(mu, phi, sigmaSq, T2, n)&lt;br /&gt;
&lt;br /&gt;
#2. AR(2) process&lt;br /&gt;
phi1 = 0.4&lt;br /&gt;
phi2 = 0.4&lt;br /&gt;
mu = 5.0&lt;br /&gt;
sigmaSq = 1.0&lt;br /&gt;
X1 = mod.trajectories2(mu, phi1, phi2, sigmaSq, T1, n) # Rows = individual series; columns = time periods&lt;br /&gt;
X2 = mod.trajectories2(mu, phi1, phi2, sigmaSq, T2, n)&lt;br /&gt;
&lt;br /&gt;
#####&lt;br /&gt;
#GETS General to specific method&lt;br /&gt;
#####&lt;br /&gt;
tquantile = norm.ppf(0.95) #95% quantile&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop1 = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    p = pmax&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:],p,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;lt; tquantile and p&amp;gt;0:&lt;br /&gt;
            p-=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop1.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T1 finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop2 = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    p = pmax&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:],p,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;lt; tquantile and p&amp;gt;0:&lt;br /&gt;
            p-=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop2.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T2 finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
####################&lt;br /&gt;
#Specific-to-General&lt;br /&gt;
####################&lt;br /&gt;
tquantile = norm.ppf(0.95) #95% quantile&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop1SOG = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    p = 0&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:],p+1,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;gt; tquantile and p&amp;lt;=pmax:&lt;br /&gt;
            p+=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop1SOG.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T1 finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop2SOG = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    p = 0&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:],p+1,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;gt; tquantile and p&amp;lt;=pmax:&lt;br /&gt;
            p+=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop2SOG.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T2 finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
####################&lt;br /&gt;
#AIC and BIC&lt;br /&gt;
####################&lt;br /&gt;
#T1 simulation&lt;br /&gt;
AICp1 = []&lt;br /&gt;
BICp1 = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    AICtemp = np.zeros(11)&lt;br /&gt;
    BICtemp = np.zeros(11)&lt;br /&gt;
    for p in np.arange(pmax+1):&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:], p, pmax)&lt;br /&gt;
        AICtemp[p] = ARtemp.AIC&lt;br /&gt;
        BICtemp[p] = ARtemp.BIC&lt;br /&gt;
    AICp1.append(np.argmin(AICtemp))&lt;br /&gt;
    BICp1.append(np.argmin(BICtemp))&lt;br /&gt;
&lt;br /&gt;
print &amp;quot;T1 AIC+BIC finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
AICp2 = []&lt;br /&gt;
BICp2 = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    AICtemp = np.zeros(11)&lt;br /&gt;
    BICtemp = np.zeros(11)&lt;br /&gt;
    for p in np.arange(pmax+1):&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:], p, pmax)&lt;br /&gt;
        AICtemp[p] = ARtemp.AIC&lt;br /&gt;
        BICtemp[p] = ARtemp.BIC&lt;br /&gt;
    AICp2.append(np.argmin(AICtemp))&lt;br /&gt;
    BICp2.append(np.argmin(BICtemp))&lt;br /&gt;
print &amp;quot;T2 AIC+BIC finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
####################&lt;br /&gt;
#Plot&lt;br /&gt;
####################&lt;br /&gt;
&lt;br /&gt;
fig, axes = plt.subplots(nrows=4, ncols=2)&lt;br /&gt;
ax0, ax1, ax2, ax3, ax4, ax5, ax6, ax7 = axes.flatten()&lt;br /&gt;
&lt;br /&gt;
ax0.hist(tratiop1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax0.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax0.set_title('GETS, T=200')&lt;br /&gt;
&lt;br /&gt;
ax1.hist(tratiop2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax1.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax1.set_title('GETS, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax2.hist(tratiop1SOG, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax2.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax2.set_title('Spec-to-Gen, T=200')&lt;br /&gt;
&lt;br /&gt;
ax3.hist(tratiop2SOG, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax3.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax3.set_title('Spec-to-Gen, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax4.hist(AICp1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax4.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax4.set_title('AIC, T=200')&lt;br /&gt;
&lt;br /&gt;
ax5.hist(AICp2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax5.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax5.set_title('AIC, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax6.hist(BICp1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax6.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax6.set_title('BIC, T=200')&lt;br /&gt;
&lt;br /&gt;
ax7.hist(BICp2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax7.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax7.set_title('BIC, T=2000')&lt;br /&gt;
&lt;br /&gt;
fig.subplots_adjust(hspace=0.5)&lt;br /&gt;
plt.show()&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;/div&gt;</summary>
		<author><name>Hazn00</name></author>
		
	</entry>
	<entry>
		<id>http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19132</id>
		<title>Time Series Model Building Process</title>
		<link rel="alternate" type="text/html" href="http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19132"/>
		<updated>2020-01-18T14:51:32Z</updated>

		<summary type="html">&lt;p&gt;Hazn00: /* Simulation */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Linear time series models, e.g., ARIMA models for univariate time series, is a popular tool for modeling dynamics of time series and predicting the time series. The methodology is not popular only in statistics, econometrics and science, but also in machine learning business applications. The key question is how to build the model. We have to choose the form of the model, in particular number of lags for so-called autoregressive part (usually denoted as p) and moving average part of the model (usually denoted as d). The common guides usually provide a ‘cook book’ for model selection, see for example [https://www.machinelearningplus.com/time-series/arima-model-time-series-forecasting-python/, ARIMA Model – Complete Guide to Time Series Forecasting in Python] . This goal of this simulation is to compare four basic methods for selection of lags (p) for the autoregressive part.&lt;br /&gt;
&lt;br /&gt;
== Problem Definition ==&lt;br /&gt;
&lt;br /&gt;
The autoregressive process has form&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\phi}_2x_{t-2}+...+{\phi}_px_{t-p} + {\epsilon}_t&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;{\epsilon}_t \sim N(0,{\sigma}^2) &amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
However, we observe only the realized value and we do not know the hyperparameter p. Therefore, we must estimate it. The considered methods are following.&lt;br /&gt;
&lt;br /&gt;
=== GETS (General-to-Specific) ===&lt;br /&gt;
&lt;br /&gt;
We first start with high enough p (pmax in the code), and perform statistical test whether the last lag has statistically significant impact, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p = 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p \neq 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the impact is insignificant, we reduce p by one and continue until the parameter for the last lag is significant, i.e. last lag has significant effect.&lt;br /&gt;
&lt;br /&gt;
=== Specific-to-General ===&lt;br /&gt;
&lt;br /&gt;
The second approach works similarly as GETS, the only difference is that we first start with model without any lag, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and we are adding lags until they are significant.&lt;br /&gt;
&lt;br /&gt;
=== BIC (Bayesian Information Criteria) ===&lt;br /&gt;
&lt;br /&gt;
Bayesian information criteria is based on a likelihood of the model and number of parameters. The criteria punish the model for high number of parameters for a potential over-fitting, and rewards the model for good fit of the data. The lower the BIC value is, the better the model (a little bit counterintuitive definition). We are supposed to select a model with the lowest value of BIC.&lt;br /&gt;
&lt;br /&gt;
=== AIC (Akaike Information Criteria)  ===&lt;br /&gt;
&lt;br /&gt;
Works exactly the same as BIC, but the formula is slightly different.&lt;br /&gt;
&lt;br /&gt;
== Method and Simulation Method ==&lt;br /&gt;
&lt;br /&gt;
The solution consists of three key elements, data generating process, AR(p) model, and simulation.&lt;br /&gt;
&lt;br /&gt;
=== Data Generating Process ===&lt;br /&gt;
&lt;br /&gt;
To answer the question, which model selection method is the best, we are creating an artificial data. We assume that data are created by AR(1) process&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
or AR(2)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\mu} + {\phi}_2x_{t-2} + {\epsilon}_{t}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
with random error &amp;lt;math&amp;gt;&amp;lt;/math&amp;gt; . Therefore, we must generate random numbers for random errors, and iterate over the equations described above. The initial values of the processes, e.g., &amp;lt;math&amp;gt;x_0&amp;lt;/math&amp;gt;, are set to the theoretical mean value of the process.&lt;br /&gt;
&lt;br /&gt;
=== AR(p) model ===&lt;br /&gt;
&lt;br /&gt;
For a given series &amp;lt;math&amp;gt;{x_1,x_2,...x_T}&amp;lt;/math&amp;gt; with a length ''T'' estimates a model for a given p.&lt;br /&gt;
&lt;br /&gt;
=== Simulation ===&lt;br /&gt;
&lt;br /&gt;
Perform n Monte Carlo simulations, where in each simulation a the data generating process is used to create a time series. Then the AR(p) model is estimated for ''p=0,1,…,pmax'', and the best models are selected according to the selection criteria described above. Therefore, we will obtain four estimates of p that corresponds to the described methods for each of the n simulation. The final step is to compute % success of correctly estimated p for each of four methods.&lt;br /&gt;
&lt;br /&gt;
== Controls ==&lt;br /&gt;
The solution allow to set number of simulation n. We need high enough n to make sure that the results will converge close enough to actual results. Therefore, we have set &amp;lt;math&amp;gt;n=5000&amp;lt;/math&amp;gt;. Higher n will not significantly increase the precision of the results.&lt;br /&gt;
&lt;br /&gt;
The more important controls is selection of AR(1) or AR(2) process, and selection of parameters &amp;lt;math&amp;gt;{\mu},{\sigma},{\phi}_1&amp;lt;/math&amp;gt;  and  &amp;lt;math&amp;gt;{\phi}_2&amp;lt;/math&amp;gt; for the process. Additionally, we can set length of the generated series and even compare performance for series with two distinct lengths &amp;lt;math&amp;gt;T_1&amp;lt;/math&amp;gt; and &amp;lt;math&amp;gt;T_2&amp;lt;/math&amp;gt;. In other words, one method may perform better for low number of observations than other, and this control allow to compare the performance.&lt;br /&gt;
&lt;br /&gt;
== Results ==&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
&lt;br /&gt;
== Code ==&lt;br /&gt;
=== Model ===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
import numpy as np&lt;br /&gt;
from numpy.linalg import inv&lt;br /&gt;
from scipy.stats import norm&lt;br /&gt;
&lt;br /&gt;
def sim1(mu, phi1, sigmaSq, T):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates single trajectory.&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    x = np.zeros(T+1)&lt;br /&gt;
    epsilon = np.random.normal(0,sigmaSq, T+1)&lt;br /&gt;
&lt;br /&gt;
    x[0] = mu / (1.0 - phi1)&lt;br /&gt;
&lt;br /&gt;
    for t in np.arange(T):&lt;br /&gt;
        x[t+1] = mu + phi1 * x[t] + epsilon[t]&lt;br /&gt;
&lt;br /&gt;
    return x[1:]&lt;br /&gt;
&lt;br /&gt;
def trajectories1(mu, phi1, sigmaSq, T, n):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates n-trajectories of AR(1) process&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :param n:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    X = np.zeros([n,T])&lt;br /&gt;
    for s in np.arange(n):&lt;br /&gt;
        X[s,:] = sim1(mu, phi1, sigmaSq, T)&lt;br /&gt;
    return X&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
def sim2(mu, phi1, phi2, sigmaSq, T):&lt;br /&gt;
    x = np.zeros(T+2)&lt;br /&gt;
    epsilon = np.random.normal(0,sigmaSq, T+2)&lt;br /&gt;
&lt;br /&gt;
    x[0] = mu / (1.0 - phi1-phi2)&lt;br /&gt;
    x[1] = mu / (1.0 - phi1-phi2)&lt;br /&gt;
&lt;br /&gt;
    for t in np.arange(T)+1:&lt;br /&gt;
        x[t+1] = mu + phi1 * x[t] + phi2 * x[t-1] + epsilon[t]&lt;br /&gt;
&lt;br /&gt;
    return x[2:]&lt;br /&gt;
&lt;br /&gt;
def trajectories2(mu, phi1, phi2, sigmaSq, T, n):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates n-trajectories of AR(2) process&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param phi2:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :param n:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    X = np.zeros([n,T])&lt;br /&gt;
    for s in np.arange(n):&lt;br /&gt;
        X[s,:] = sim2(mu, phi1, phi2, sigmaSq, T)&lt;br /&gt;
    return X&lt;br /&gt;
&lt;br /&gt;
class ARp(object):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;AR(p) class allowing to estimate the model &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
    def __init__(self, x, p, pmax):&lt;br /&gt;
        self.p = p&lt;br /&gt;
        self.x = x&lt;br /&gt;
        self.T = float(x.size)&lt;br /&gt;
        self.par = np.zeros(p+2) #np.array: c, phi_1, phi_2, ... phi_p, sigma^2&lt;br /&gt;
&lt;br /&gt;
        #Init. matrices for OLS&lt;br /&gt;
        Y = self.x[pmax:]&lt;br /&gt;
        Xtemp = []&lt;br /&gt;
&lt;br /&gt;
        for i in np.arange(Y.size):&lt;br /&gt;
            Xtemp.append(np.flip(x[i:(pmax+i)],0))&lt;br /&gt;
        X = np.ones((Y.size, p+1))&lt;br /&gt;
        X[:,1:] = np.array(Xtemp)[:,:p]&lt;br /&gt;
&lt;br /&gt;
        #OLS Estimate&lt;br /&gt;
        Phi = np.dot(np.dot(inv(np.dot(X.T,X)),X.T),Y)&lt;br /&gt;
        SigmaS = np.sum((Y - np.dot(X, Phi))**2.0)/(self.T-pmax)&lt;br /&gt;
        self.par[:-1] = Phi[:]&lt;br /&gt;
        self.par[-1] = SigmaS&lt;br /&gt;
&lt;br /&gt;
        #t-ratios&lt;br /&gt;
        self.VCOV = inv(np.dot(X.T,X))*SigmaS&lt;br /&gt;
        self.SE = np.diag(self.VCOV)**0.5&lt;br /&gt;
        self.t = self.par[:-1]/self.SE&lt;br /&gt;
&lt;br /&gt;
        #likelihood and IC&lt;br /&gt;
        self.logL = (-(self.T-pmax)/2.0)*np.log(2.0*np.pi) + (-(self.T-pmax)/2.0)*np.log(SigmaS) + (-(self.T-pmax)/2.0)&lt;br /&gt;
        self.AIC = 2.0*((self.par.size)-self.logL)&lt;br /&gt;
        self.BIC = np.log(Y.size)*self.par.size-2.0*self.logL&lt;br /&gt;
&lt;br /&gt;
=== Simulation ===&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
import numpy as np&lt;br /&gt;
import models as mod&lt;br /&gt;
import matplotlib.pyplot as plt&lt;br /&gt;
from scipy.stats import norm&lt;br /&gt;
##########################&lt;br /&gt;
#Simulation and settings&lt;br /&gt;
#########################&lt;br /&gt;
#general&lt;br /&gt;
pmax = 10 # Maximum number of lags&lt;br /&gt;
n = 5000 # Number of simulations&lt;br /&gt;
T1 = 200 # Length of the first time series&lt;br /&gt;
T2 = 2000 # Length of the second time series&lt;br /&gt;
&lt;br /&gt;
#1. AR(1) process&lt;br /&gt;
#phi = 0.9&lt;br /&gt;
#mu = 5.0&lt;br /&gt;
#sigmaSq = 1.0&lt;br /&gt;
#X1 = mod.trajectories1(mu, phi, sigmaSq, T1, n)&lt;br /&gt;
#X2 = mod.trajectories1(mu, phi, sigmaSq, T2, n)&lt;br /&gt;
&lt;br /&gt;
#2. AR(2) process&lt;br /&gt;
phi1 = 0.4&lt;br /&gt;
phi2 = 0.4&lt;br /&gt;
mu = 5.0&lt;br /&gt;
sigmaSq = 1.0&lt;br /&gt;
X1 = mod.trajectories2(mu, phi1, phi2, sigmaSq, T1, n) # Rows = individual series; columns = time periods&lt;br /&gt;
X2 = mod.trajectories2(mu, phi1, phi2, sigmaSq, T2, n)&lt;br /&gt;
&lt;br /&gt;
#####&lt;br /&gt;
#GETS General to specific method&lt;br /&gt;
#####&lt;br /&gt;
tquantile = norm.ppf(0.95) #95% quantile&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop1 = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    p = pmax&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:],p,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;lt; tquantile and p&amp;gt;0:&lt;br /&gt;
            p-=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop1.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T1 finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop2 = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    p = pmax&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:],p,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;lt; tquantile and p&amp;gt;0:&lt;br /&gt;
            p-=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop2.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T2 finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
####################&lt;br /&gt;
#Specific-to-General&lt;br /&gt;
####################&lt;br /&gt;
tquantile = norm.ppf(0.95) #95% quantile&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop1SOG = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    p = 0&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:],p+1,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;gt; tquantile and p&amp;lt;=pmax:&lt;br /&gt;
            p+=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop1SOG.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T1 finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop2SOG = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    p = 0&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:],p+1,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;gt; tquantile and p&amp;lt;=pmax:&lt;br /&gt;
            p+=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop2SOG.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T2 finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
####################&lt;br /&gt;
#AIC and BIC&lt;br /&gt;
####################&lt;br /&gt;
#T1 simulation&lt;br /&gt;
AICp1 = []&lt;br /&gt;
BICp1 = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    AICtemp = np.zeros(11)&lt;br /&gt;
    BICtemp = np.zeros(11)&lt;br /&gt;
    for p in np.arange(pmax+1):&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:], p, pmax)&lt;br /&gt;
        AICtemp[p] = ARtemp.AIC&lt;br /&gt;
        BICtemp[p] = ARtemp.BIC&lt;br /&gt;
    AICp1.append(np.argmin(AICtemp))&lt;br /&gt;
    BICp1.append(np.argmin(BICtemp))&lt;br /&gt;
&lt;br /&gt;
print &amp;quot;T1 AIC+BIC finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
AICp2 = []&lt;br /&gt;
BICp2 = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    AICtemp = np.zeros(11)&lt;br /&gt;
    BICtemp = np.zeros(11)&lt;br /&gt;
    for p in np.arange(pmax+1):&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:], p, pmax)&lt;br /&gt;
        AICtemp[p] = ARtemp.AIC&lt;br /&gt;
        BICtemp[p] = ARtemp.BIC&lt;br /&gt;
    AICp2.append(np.argmin(AICtemp))&lt;br /&gt;
    BICp2.append(np.argmin(BICtemp))&lt;br /&gt;
print &amp;quot;T2 AIC+BIC finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
####################&lt;br /&gt;
#Plot&lt;br /&gt;
####################&lt;br /&gt;
&lt;br /&gt;
fig, axes = plt.subplots(nrows=4, ncols=2)&lt;br /&gt;
ax0, ax1, ax2, ax3, ax4, ax5, ax6, ax7 = axes.flatten()&lt;br /&gt;
&lt;br /&gt;
ax0.hist(tratiop1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax0.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax0.set_title('GETS, T=200')&lt;br /&gt;
&lt;br /&gt;
ax1.hist(tratiop2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax1.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax1.set_title('GETS, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax2.hist(tratiop1SOG, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax2.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax2.set_title('Spec-to-Gen, T=200')&lt;br /&gt;
&lt;br /&gt;
ax3.hist(tratiop2SOG, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax3.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax3.set_title('Spec-to-Gen, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax4.hist(AICp1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax4.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax4.set_title('AIC, T=200')&lt;br /&gt;
&lt;br /&gt;
ax5.hist(AICp2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax5.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax5.set_title('AIC, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax6.hist(BICp1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax6.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax6.set_title('BIC, T=200')&lt;br /&gt;
&lt;br /&gt;
ax7.hist(BICp2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax7.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax7.set_title('BIC, T=2000')&lt;br /&gt;
&lt;br /&gt;
fig.subplots_adjust(hspace=0.5)&lt;br /&gt;
plt.show()&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;/div&gt;</summary>
		<author><name>Hazn00</name></author>
		
	</entry>
	<entry>
		<id>http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19131</id>
		<title>Time Series Model Building Process</title>
		<link rel="alternate" type="text/html" href="http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19131"/>
		<updated>2020-01-18T14:50:31Z</updated>

		<summary type="html">&lt;p&gt;Hazn00: /* Simulation */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Linear time series models, e.g., ARIMA models for univariate time series, is a popular tool for modeling dynamics of time series and predicting the time series. The methodology is not popular only in statistics, econometrics and science, but also in machine learning business applications. The key question is how to build the model. We have to choose the form of the model, in particular number of lags for so-called autoregressive part (usually denoted as p) and moving average part of the model (usually denoted as d). The common guides usually provide a ‘cook book’ for model selection, see for example [https://www.machinelearningplus.com/time-series/arima-model-time-series-forecasting-python/, ARIMA Model – Complete Guide to Time Series Forecasting in Python] . This goal of this simulation is to compare four basic methods for selection of lags (p) for the autoregressive part.&lt;br /&gt;
&lt;br /&gt;
== Problem Definition ==&lt;br /&gt;
&lt;br /&gt;
The autoregressive process has form&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\phi}_2x_{t-2}+...+{\phi}_px_{t-p} + {\epsilon}_t&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;{\epsilon}_t \sim N(0,{\sigma}^2) &amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
However, we observe only the realized value and we do not know the hyperparameter p. Therefore, we must estimate it. The considered methods are following.&lt;br /&gt;
&lt;br /&gt;
=== GETS (General-to-Specific) ===&lt;br /&gt;
&lt;br /&gt;
We first start with high enough p (pmax in the code), and perform statistical test whether the last lag has statistically significant impact, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p = 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p \neq 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the impact is insignificant, we reduce p by one and continue until the parameter for the last lag is significant, i.e. last lag has significant effect.&lt;br /&gt;
&lt;br /&gt;
=== Specific-to-General ===&lt;br /&gt;
&lt;br /&gt;
The second approach works similarly as GETS, the only difference is that we first start with model without any lag, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and we are adding lags until they are significant.&lt;br /&gt;
&lt;br /&gt;
=== BIC (Bayesian Information Criteria) ===&lt;br /&gt;
&lt;br /&gt;
Bayesian information criteria is based on a likelihood of the model and number of parameters. The criteria punish the model for high number of parameters for a potential over-fitting, and rewards the model for good fit of the data. The lower the BIC value is, the better the model (a little bit counterintuitive definition). We are supposed to select a model with the lowest value of BIC.&lt;br /&gt;
&lt;br /&gt;
=== AIC (Akaike Information Criteria)  ===&lt;br /&gt;
&lt;br /&gt;
Works exactly the same as BIC, but the formula is slightly different.&lt;br /&gt;
&lt;br /&gt;
== Method and Simulation Method ==&lt;br /&gt;
&lt;br /&gt;
The solution consists of three key elements, data generating process, AR(p) model, and simulation.&lt;br /&gt;
&lt;br /&gt;
=== Data Generating Process ===&lt;br /&gt;
&lt;br /&gt;
To answer the question, which model selection method is the best, we are creating an artificial data. We assume that data are created by AR(1) process&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
or AR(2)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\mu} + {\phi}_2x_{t-2} + {\epsilon}_{t}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
with random error &amp;lt;math&amp;gt;&amp;lt;/math&amp;gt; . Therefore, we must generate random numbers for random errors, and iterate over the equations described above. The initial values of the processes, e.g., &amp;lt;math&amp;gt;x_0&amp;lt;/math&amp;gt;, are set to the theoretical mean value of the process.&lt;br /&gt;
&lt;br /&gt;
=== AR(p) model ===&lt;br /&gt;
&lt;br /&gt;
For a given series &amp;lt;math&amp;gt;{x_1,x_2,...x_T}&amp;lt;/math&amp;gt; with a length ''T'' estimates a model for a given p.&lt;br /&gt;
&lt;br /&gt;
=== Simulation ===&lt;br /&gt;
&lt;br /&gt;
Perform n Monte Carlo simulations, where in each simulation a the data generating process is used to create a time series. Then the AR(p) model is estimated for ''p=0,1,…,pmax'', and the best models are selected according to the selection criteria described above. Therefore, we will obtain four estimates of p that corresponds to the described methods for each of the n simulation. The final step is to compute % success of correctly estimated p for each of four methods.&lt;br /&gt;
&lt;br /&gt;
== Controls ==&lt;br /&gt;
The solution allow to set number of simulation n. We need high enough n to make sure that the results will converge close enough to actual results. Therefore, we have set &amp;lt;math&amp;gt;n=5000&amp;lt;/math&amp;gt;. Higher n will not significantly increase the precision of the results.&lt;br /&gt;
&lt;br /&gt;
The more important controls is selection of AR(1) or AR(2) process, and selection of parameters &amp;lt;math&amp;gt;{\mu},{\sigma},{\phi}_1&amp;lt;/math&amp;gt;  and  &amp;lt;math&amp;gt;{\phi}_2&amp;lt;/math&amp;gt; for the process. Additionally, we can set length of the generated series and even compare performance for series with two distinct lengths &amp;lt;math&amp;gt;T_1&amp;lt;/math&amp;gt; and &amp;lt;math&amp;gt;T_2&amp;lt;/math&amp;gt;. In other words, one method may perform better for low number of observations than other, and this control allow to compare the performance.&lt;br /&gt;
&lt;br /&gt;
== Results ==&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
&lt;br /&gt;
== Code ==&lt;br /&gt;
=== Model ===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
import numpy as np&lt;br /&gt;
from numpy.linalg import inv&lt;br /&gt;
from scipy.stats import norm&lt;br /&gt;
&lt;br /&gt;
def sim1(mu, phi1, sigmaSq, T):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates single trajectory.&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    x = np.zeros(T+1)&lt;br /&gt;
    epsilon = np.random.normal(0,sigmaSq, T+1)&lt;br /&gt;
&lt;br /&gt;
    x[0] = mu / (1.0 - phi1)&lt;br /&gt;
&lt;br /&gt;
    for t in np.arange(T):&lt;br /&gt;
        x[t+1] = mu + phi1 * x[t] + epsilon[t]&lt;br /&gt;
&lt;br /&gt;
    return x[1:]&lt;br /&gt;
&lt;br /&gt;
def trajectories1(mu, phi1, sigmaSq, T, n):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates n-trajectories of AR(1) process&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :param n:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    X = np.zeros([n,T])&lt;br /&gt;
    for s in np.arange(n):&lt;br /&gt;
        X[s,:] = sim1(mu, phi1, sigmaSq, T)&lt;br /&gt;
    return X&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
def sim2(mu, phi1, phi2, sigmaSq, T):&lt;br /&gt;
    x = np.zeros(T+2)&lt;br /&gt;
    epsilon = np.random.normal(0,sigmaSq, T+2)&lt;br /&gt;
&lt;br /&gt;
    x[0] = mu / (1.0 - phi1-phi2)&lt;br /&gt;
    x[1] = mu / (1.0 - phi1-phi2)&lt;br /&gt;
&lt;br /&gt;
    for t in np.arange(T)+1:&lt;br /&gt;
        x[t+1] = mu + phi1 * x[t] + phi2 * x[t-1] + epsilon[t]&lt;br /&gt;
&lt;br /&gt;
    return x[2:]&lt;br /&gt;
&lt;br /&gt;
def trajectories2(mu, phi1, phi2, sigmaSq, T, n):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates n-trajectories of AR(2) process&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param phi2:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :param n:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    X = np.zeros([n,T])&lt;br /&gt;
    for s in np.arange(n):&lt;br /&gt;
        X[s,:] = sim2(mu, phi1, phi2, sigmaSq, T)&lt;br /&gt;
    return X&lt;br /&gt;
&lt;br /&gt;
class ARp(object):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;AR(p) class allowing to estimate the model &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
    def __init__(self, x, p, pmax):&lt;br /&gt;
        self.p = p&lt;br /&gt;
        self.x = x&lt;br /&gt;
        self.T = float(x.size)&lt;br /&gt;
        self.par = np.zeros(p+2) #np.array: c, phi_1, phi_2, ... phi_p, sigma^2&lt;br /&gt;
&lt;br /&gt;
        #Init. matrices for OLS&lt;br /&gt;
        Y = self.x[pmax:]&lt;br /&gt;
        Xtemp = []&lt;br /&gt;
&lt;br /&gt;
        for i in np.arange(Y.size):&lt;br /&gt;
            Xtemp.append(np.flip(x[i:(pmax+i)],0))&lt;br /&gt;
        X = np.ones((Y.size, p+1))&lt;br /&gt;
        X[:,1:] = np.array(Xtemp)[:,:p]&lt;br /&gt;
&lt;br /&gt;
        #OLS Estimate&lt;br /&gt;
        Phi = np.dot(np.dot(inv(np.dot(X.T,X)),X.T),Y)&lt;br /&gt;
        SigmaS = np.sum((Y - np.dot(X, Phi))**2.0)/(self.T-pmax)&lt;br /&gt;
        self.par[:-1] = Phi[:]&lt;br /&gt;
        self.par[-1] = SigmaS&lt;br /&gt;
&lt;br /&gt;
        #t-ratios&lt;br /&gt;
        self.VCOV = inv(np.dot(X.T,X))*SigmaS&lt;br /&gt;
        self.SE = np.diag(self.VCOV)**0.5&lt;br /&gt;
        self.t = self.par[:-1]/self.SE&lt;br /&gt;
&lt;br /&gt;
        #likelihood and IC&lt;br /&gt;
        self.logL = (-(self.T-pmax)/2.0)*np.log(2.0*np.pi) + (-(self.T-pmax)/2.0)*np.log(SigmaS) + (-(self.T-pmax)/2.0)&lt;br /&gt;
        self.AIC = 2.0*((self.par.size)-self.logL)&lt;br /&gt;
        self.BIC = np.log(Y.size)*self.par.size-2.0*self.logL&lt;br /&gt;
&lt;br /&gt;
=== Simulation ===&lt;br /&gt;
import numpy as np&lt;br /&gt;
import models as mod&lt;br /&gt;
import matplotlib.pyplot as plt&lt;br /&gt;
from scipy.stats import norm&lt;br /&gt;
##########################&lt;br /&gt;
#Simulation and settings&lt;br /&gt;
#########################&lt;br /&gt;
#general&lt;br /&gt;
pmax = 10 # Maximum number of lags&lt;br /&gt;
n = 5000 # Number of simulations&lt;br /&gt;
T1 = 200 # Length of the first time series&lt;br /&gt;
T2 = 2000 # Length of the second time series&lt;br /&gt;
&lt;br /&gt;
#1. AR(1) process&lt;br /&gt;
#phi = 0.9&lt;br /&gt;
#mu = 5.0&lt;br /&gt;
#sigmaSq = 1.0&lt;br /&gt;
#X1 = mod.trajectories1(mu, phi, sigmaSq, T1, n)&lt;br /&gt;
#X2 = mod.trajectories1(mu, phi, sigmaSq, T2, n)&lt;br /&gt;
&lt;br /&gt;
#2. AR(2) process&lt;br /&gt;
phi1 = 0.4&lt;br /&gt;
phi2 = 0.4&lt;br /&gt;
mu = 5.0&lt;br /&gt;
sigmaSq = 1.0&lt;br /&gt;
X1 = mod.trajectories2(mu, phi1, phi2, sigmaSq, T1, n) # Rows = individual series; columns = time periods&lt;br /&gt;
X2 = mod.trajectories2(mu, phi1, phi2, sigmaSq, T2, n)&lt;br /&gt;
&lt;br /&gt;
#####&lt;br /&gt;
#GETS General to specific method&lt;br /&gt;
#####&lt;br /&gt;
tquantile = norm.ppf(0.95) #95% quantile&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop1 = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    p = pmax&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:],p,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;lt; tquantile and p&amp;gt;0:&lt;br /&gt;
            p-=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop1.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T1 finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop2 = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    p = pmax&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:],p,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;lt; tquantile and p&amp;gt;0:&lt;br /&gt;
            p-=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop2.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T2 finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
####################&lt;br /&gt;
#Specific-to-General&lt;br /&gt;
####################&lt;br /&gt;
tquantile = norm.ppf(0.95) #95% quantile&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#T1 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop1SOG = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    p = 0&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:],p+1,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;gt; tquantile and p&amp;lt;=pmax:&lt;br /&gt;
            p+=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop1SOG.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T1 finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
ARarray = []&lt;br /&gt;
tratiop2SOG = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    p = 0&lt;br /&gt;
    while True:&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:],p+1,pmax)&lt;br /&gt;
        if np.abs(ARtemp.t[-1]) &amp;gt; tquantile and p&amp;lt;=pmax:&lt;br /&gt;
            p+=1&lt;br /&gt;
        else:&lt;br /&gt;
            ARarray.append(ARtemp)&lt;br /&gt;
            tratiop2SOG.append(p)&lt;br /&gt;
            break&lt;br /&gt;
print &amp;quot;t-ratio T2 finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
####################&lt;br /&gt;
#AIC and BIC&lt;br /&gt;
####################&lt;br /&gt;
#T1 simulation&lt;br /&gt;
AICp1 = []&lt;br /&gt;
BICp1 = []&lt;br /&gt;
for i in np.arange(X1.shape[0]):&lt;br /&gt;
    AICtemp = np.zeros(11)&lt;br /&gt;
    BICtemp = np.zeros(11)&lt;br /&gt;
    for p in np.arange(pmax+1):&lt;br /&gt;
        ARtemp = mod.ARp(X1[i,:], p, pmax)&lt;br /&gt;
        AICtemp[p] = ARtemp.AIC&lt;br /&gt;
        BICtemp[p] = ARtemp.BIC&lt;br /&gt;
    AICp1.append(np.argmin(AICtemp))&lt;br /&gt;
    BICp1.append(np.argmin(BICtemp))&lt;br /&gt;
&lt;br /&gt;
print &amp;quot;T1 AIC+BIC finished&amp;quot;&lt;br /&gt;
#T2 simulation&lt;br /&gt;
AICp2 = []&lt;br /&gt;
BICp2 = []&lt;br /&gt;
for i in np.arange(X2.shape[0]):&lt;br /&gt;
    AICtemp = np.zeros(11)&lt;br /&gt;
    BICtemp = np.zeros(11)&lt;br /&gt;
    for p in np.arange(pmax+1):&lt;br /&gt;
        ARtemp = mod.ARp(X2[i,:], p, pmax)&lt;br /&gt;
        AICtemp[p] = ARtemp.AIC&lt;br /&gt;
        BICtemp[p] = ARtemp.BIC&lt;br /&gt;
    AICp2.append(np.argmin(AICtemp))&lt;br /&gt;
    BICp2.append(np.argmin(BICtemp))&lt;br /&gt;
print &amp;quot;T2 AIC+BIC finished&amp;quot;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
####################&lt;br /&gt;
#Plot&lt;br /&gt;
####################&lt;br /&gt;
&lt;br /&gt;
fig, axes = plt.subplots(nrows=4, ncols=2)&lt;br /&gt;
ax0, ax1, ax2, ax3, ax4, ax5, ax6, ax7 = axes.flatten()&lt;br /&gt;
&lt;br /&gt;
ax0.hist(tratiop1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax0.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax0.set_title('GETS, T=200')&lt;br /&gt;
&lt;br /&gt;
ax1.hist(tratiop2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax1.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax1.set_title('GETS, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax2.hist(tratiop1SOG, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax2.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax2.set_title('Spec-to-Gen, T=200')&lt;br /&gt;
&lt;br /&gt;
ax3.hist(tratiop2SOG, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax3.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax3.set_title('Spec-to-Gen, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax4.hist(AICp1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax4.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax4.set_title('AIC, T=200')&lt;br /&gt;
&lt;br /&gt;
ax5.hist(AICp2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax5.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax5.set_title('AIC, T=2000')&lt;br /&gt;
&lt;br /&gt;
ax6.hist(BICp1, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax6.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax6.set_title('BIC, T=200')&lt;br /&gt;
&lt;br /&gt;
ax7.hist(BICp2, bins=11, range=(-0.5, 10.5), weights=np.zeros(n) + 1. / n)&lt;br /&gt;
ax7.xaxis.set_ticks(np.arange(0, 11, 1.0))&lt;br /&gt;
ax7.set_title('BIC, T=2000')&lt;br /&gt;
&lt;br /&gt;
fig.subplots_adjust(hspace=0.5)&lt;br /&gt;
plt.show()&lt;/div&gt;</summary>
		<author><name>Hazn00</name></author>
		
	</entry>
	<entry>
		<id>http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19129</id>
		<title>Time Series Model Building Process</title>
		<link rel="alternate" type="text/html" href="http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19129"/>
		<updated>2020-01-18T09:59:10Z</updated>

		<summary type="html">&lt;p&gt;Hazn00: /* Code */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Linear time series models, e.g., ARIMA models for univariate time series, is a popular tool for modeling dynamics of time series and predicting the time series. The methodology is not popular only in statistics, econometrics and science, but also in machine learning business applications. The key question is how to build the model. We have to choose the form of the model, in particular number of lags for so-called autoregressive part (usually denoted as p) and moving average part of the model (usually denoted as d). The common guides usually provide a ‘cook book’ for model selection, see for example [https://www.machinelearningplus.com/time-series/arima-model-time-series-forecasting-python/, ARIMA Model – Complete Guide to Time Series Forecasting in Python] . This goal of this simulation is to compare four basic methods for selection of lags (p) for the autoregressive part.&lt;br /&gt;
&lt;br /&gt;
== Problem Definition ==&lt;br /&gt;
&lt;br /&gt;
The autoregressive process has form&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\phi}_2x_{t-2}+...+{\phi}_px_{t-p} + {\epsilon}_t&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;{\epsilon}_t \sim N(0,{\sigma}^2) &amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
However, we observe only the realized value and we do not know the hyperparameter p. Therefore, we must estimate it. The considered methods are following.&lt;br /&gt;
&lt;br /&gt;
=== GETS (General-to-Specific) ===&lt;br /&gt;
&lt;br /&gt;
We first start with high enough p (pmax in the code), and perform statistical test whether the last lag has statistically significant impact, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p = 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p \neq 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the impact is insignificant, we reduce p by one and continue until the parameter for the last lag is significant, i.e. last lag has significant effect.&lt;br /&gt;
&lt;br /&gt;
=== Specific-to-General ===&lt;br /&gt;
&lt;br /&gt;
The second approach works similarly as GETS, the only difference is that we first start with model without any lag, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and we are adding lags until they are significant.&lt;br /&gt;
&lt;br /&gt;
=== BIC (Bayesian Information Criteria) ===&lt;br /&gt;
&lt;br /&gt;
Bayesian information criteria is based on a likelihood of the model and number of parameters. The criteria punish the model for high number of parameters for a potential over-fitting, and rewards the model for good fit of the data. The lower the BIC value is, the better the model (a little bit counterintuitive definition). We are supposed to select a model with the lowest value of BIC.&lt;br /&gt;
&lt;br /&gt;
=== AIC (Akaike Information Criteria)  ===&lt;br /&gt;
&lt;br /&gt;
Works exactly the same as BIC, but the formula is slightly different.&lt;br /&gt;
&lt;br /&gt;
== Method and Simulation Method ==&lt;br /&gt;
&lt;br /&gt;
The solution consists of three key elements, data generating process, AR(p) model, and simulation.&lt;br /&gt;
&lt;br /&gt;
=== Data Generating Process ===&lt;br /&gt;
&lt;br /&gt;
To answer the question, which model selection method is the best, we are creating an artificial data. We assume that data are created by AR(1) process&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
or AR(2)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\mu} + {\phi}_2x_{t-2} + {\epsilon}_{t}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
with random error &amp;lt;math&amp;gt;&amp;lt;/math&amp;gt; . Therefore, we must generate random numbers for random errors, and iterate over the equations described above. The initial values of the processes, e.g., &amp;lt;math&amp;gt;x_0&amp;lt;/math&amp;gt;, are set to the theoretical mean value of the process.&lt;br /&gt;
&lt;br /&gt;
=== AR(p) model ===&lt;br /&gt;
&lt;br /&gt;
For a given series &amp;lt;math&amp;gt;{x_1,x_2,...x_T}&amp;lt;/math&amp;gt; with a length ''T'' estimates a model for a given p.&lt;br /&gt;
&lt;br /&gt;
=== Simulation ===&lt;br /&gt;
&lt;br /&gt;
Perform n Monte Carlo simulations, where in each simulation a the data generating process is used to create a time series. Then the AR(p) model is estimated for ''p=0,1,…,pmax'', and the best models are selected according to the selection criteria described above. Therefore, we will obtain four estimates of p that corresponds to the described methods for each of the n simulation. The final step is to compute % success of correctly estimated p for each of four methods.&lt;br /&gt;
&lt;br /&gt;
== Controls ==&lt;br /&gt;
The solution allow to set number of simulation n. We need high enough n to make sure that the results will converge close enough to actual results. Therefore, we have set &amp;lt;math&amp;gt;n=5000&amp;lt;/math&amp;gt;. Higher n will not significantly increase the precision of the results.&lt;br /&gt;
&lt;br /&gt;
The more important controls is selection of AR(1) or AR(2) process, and selection of parameters &amp;lt;math&amp;gt;{\mu},{\sigma},{\phi}_1&amp;lt;/math&amp;gt;  and  &amp;lt;math&amp;gt;{\phi}_2&amp;lt;/math&amp;gt; for the process. Additionally, we can set length of the generated series and even compare performance for series with two distinct lengths &amp;lt;math&amp;gt;T_1&amp;lt;/math&amp;gt; and &amp;lt;math&amp;gt;T_2&amp;lt;/math&amp;gt;. In other words, one method may perform better for low number of observations than other, and this control allow to compare the performance.&lt;br /&gt;
&lt;br /&gt;
== Results ==&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
&lt;br /&gt;
== Code ==&lt;br /&gt;
=== Model ===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
import numpy as np&lt;br /&gt;
from numpy.linalg import inv&lt;br /&gt;
from scipy.stats import norm&lt;br /&gt;
&lt;br /&gt;
def sim1(mu, phi1, sigmaSq, T):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates single trajectory.&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    x = np.zeros(T+1)&lt;br /&gt;
    epsilon = np.random.normal(0,sigmaSq, T+1)&lt;br /&gt;
&lt;br /&gt;
    x[0] = mu / (1.0 - phi1)&lt;br /&gt;
&lt;br /&gt;
    for t in np.arange(T):&lt;br /&gt;
        x[t+1] = mu + phi1 * x[t] + epsilon[t]&lt;br /&gt;
&lt;br /&gt;
    return x[1:]&lt;br /&gt;
&lt;br /&gt;
def trajectories1(mu, phi1, sigmaSq, T, n):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates n-trajectories of AR(1) process&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :param n:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    X = np.zeros([n,T])&lt;br /&gt;
    for s in np.arange(n):&lt;br /&gt;
        X[s,:] = sim1(mu, phi1, sigmaSq, T)&lt;br /&gt;
    return X&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
def sim2(mu, phi1, phi2, sigmaSq, T):&lt;br /&gt;
    x = np.zeros(T+2)&lt;br /&gt;
    epsilon = np.random.normal(0,sigmaSq, T+2)&lt;br /&gt;
&lt;br /&gt;
    x[0] = mu / (1.0 - phi1-phi2)&lt;br /&gt;
    x[1] = mu / (1.0 - phi1-phi2)&lt;br /&gt;
&lt;br /&gt;
    for t in np.arange(T)+1:&lt;br /&gt;
        x[t+1] = mu + phi1 * x[t] + phi2 * x[t-1] + epsilon[t]&lt;br /&gt;
&lt;br /&gt;
    return x[2:]&lt;br /&gt;
&lt;br /&gt;
def trajectories2(mu, phi1, phi2, sigmaSq, T, n):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    Simulates n-trajectories of AR(2) process&lt;br /&gt;
    :param mu:&lt;br /&gt;
    :param phi1:&lt;br /&gt;
    :param phi2:&lt;br /&gt;
    :param sigmaSq:&lt;br /&gt;
    :param T:&lt;br /&gt;
    :param n:&lt;br /&gt;
    :return:&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    X = np.zeros([n,T])&lt;br /&gt;
    for s in np.arange(n):&lt;br /&gt;
        X[s,:] = sim2(mu, phi1, phi2, sigmaSq, T)&lt;br /&gt;
    return X&lt;br /&gt;
&lt;br /&gt;
class ARp(object):&lt;br /&gt;
    &amp;quot;&amp;quot;&amp;quot;AR(p) class allowing to estimate the model &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
    def __init__(self, x, p, pmax):&lt;br /&gt;
        self.p = p&lt;br /&gt;
        self.x = x&lt;br /&gt;
        self.T = float(x.size)&lt;br /&gt;
        self.par = np.zeros(p+2) #np.array: c, phi_1, phi_2, ... phi_p, sigma^2&lt;br /&gt;
&lt;br /&gt;
        #Init. matrices for OLS&lt;br /&gt;
        Y = self.x[pmax:]&lt;br /&gt;
        Xtemp = []&lt;br /&gt;
&lt;br /&gt;
        for i in np.arange(Y.size):&lt;br /&gt;
            Xtemp.append(np.flip(x[i:(pmax+i)],0))&lt;br /&gt;
        X = np.ones((Y.size, p+1))&lt;br /&gt;
        X[:,1:] = np.array(Xtemp)[:,:p]&lt;br /&gt;
&lt;br /&gt;
        #OLS Estimate&lt;br /&gt;
        Phi = np.dot(np.dot(inv(np.dot(X.T,X)),X.T),Y)&lt;br /&gt;
        SigmaS = np.sum((Y - np.dot(X, Phi))**2.0)/(self.T-pmax)&lt;br /&gt;
        self.par[:-1] = Phi[:]&lt;br /&gt;
        self.par[-1] = SigmaS&lt;br /&gt;
&lt;br /&gt;
        #t-ratios&lt;br /&gt;
        self.VCOV = inv(np.dot(X.T,X))*SigmaS&lt;br /&gt;
        self.SE = np.diag(self.VCOV)**0.5&lt;br /&gt;
        self.t = self.par[:-1]/self.SE&lt;br /&gt;
&lt;br /&gt;
        #likelihood and IC&lt;br /&gt;
        self.logL = (-(self.T-pmax)/2.0)*np.log(2.0*np.pi) + (-(self.T-pmax)/2.0)*np.log(SigmaS) + (-(self.T-pmax)/2.0)&lt;br /&gt;
        self.AIC = 2.0*((self.par.size)-self.logL)&lt;br /&gt;
        self.BIC = np.log(Y.size)*self.par.size-2.0*self.logL&lt;br /&gt;
&lt;br /&gt;
=== Simulation ===&lt;/div&gt;</summary>
		<author><name>Hazn00</name></author>
		
	</entry>
	<entry>
		<id>http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19128</id>
		<title>Time Series Model Building Process</title>
		<link rel="alternate" type="text/html" href="http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19128"/>
		<updated>2020-01-18T09:40:57Z</updated>

		<summary type="html">&lt;p&gt;Hazn00: /* Controls */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Linear time series models, e.g., ARIMA models for univariate time series, is a popular tool for modeling dynamics of time series and predicting the time series. The methodology is not popular only in statistics, econometrics and science, but also in machine learning business applications. The key question is how to build the model. We have to choose the form of the model, in particular number of lags for so-called autoregressive part (usually denoted as p) and moving average part of the model (usually denoted as d). The common guides usually provide a ‘cook book’ for model selection, see for example [https://www.machinelearningplus.com/time-series/arima-model-time-series-forecasting-python/, ARIMA Model – Complete Guide to Time Series Forecasting in Python] . This goal of this simulation is to compare four basic methods for selection of lags (p) for the autoregressive part.&lt;br /&gt;
&lt;br /&gt;
== Problem Definition ==&lt;br /&gt;
&lt;br /&gt;
The autoregressive process has form&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\phi}_2x_{t-2}+...+{\phi}_px_{t-p} + {\epsilon}_t&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;{\epsilon}_t \sim N(0,{\sigma}^2) &amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
However, we observe only the realized value and we do not know the hyperparameter p. Therefore, we must estimate it. The considered methods are following.&lt;br /&gt;
&lt;br /&gt;
=== GETS (General-to-Specific) ===&lt;br /&gt;
&lt;br /&gt;
We first start with high enough p (pmax in the code), and perform statistical test whether the last lag has statistically significant impact, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p = 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p \neq 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the impact is insignificant, we reduce p by one and continue until the parameter for the last lag is significant, i.e. last lag has significant effect.&lt;br /&gt;
&lt;br /&gt;
=== Specific-to-General ===&lt;br /&gt;
&lt;br /&gt;
The second approach works similarly as GETS, the only difference is that we first start with model without any lag, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and we are adding lags until they are significant.&lt;br /&gt;
&lt;br /&gt;
=== BIC (Bayesian Information Criteria) ===&lt;br /&gt;
&lt;br /&gt;
Bayesian information criteria is based on a likelihood of the model and number of parameters. The criteria punish the model for high number of parameters for a potential over-fitting, and rewards the model for good fit of the data. The lower the BIC value is, the better the model (a little bit counterintuitive definition). We are supposed to select a model with the lowest value of BIC.&lt;br /&gt;
&lt;br /&gt;
=== AIC (Akaike Information Criteria)  ===&lt;br /&gt;
&lt;br /&gt;
Works exactly the same as BIC, but the formula is slightly different.&lt;br /&gt;
&lt;br /&gt;
== Method and Simulation Method ==&lt;br /&gt;
&lt;br /&gt;
The solution consists of three key elements, data generating process, AR(p) model, and simulation.&lt;br /&gt;
&lt;br /&gt;
=== Data Generating Process ===&lt;br /&gt;
&lt;br /&gt;
To answer the question, which model selection method is the best, we are creating an artificial data. We assume that data are created by AR(1) process&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
or AR(2)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\mu} + {\phi}_2x_{t-2} + {\epsilon}_{t}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
with random error &amp;lt;math&amp;gt;&amp;lt;/math&amp;gt; . Therefore, we must generate random numbers for random errors, and iterate over the equations described above. The initial values of the processes, e.g., &amp;lt;math&amp;gt;x_0&amp;lt;/math&amp;gt;, are set to the theoretical mean value of the process.&lt;br /&gt;
&lt;br /&gt;
=== AR(p) model ===&lt;br /&gt;
&lt;br /&gt;
For a given series &amp;lt;math&amp;gt;{x_1,x_2,...x_T}&amp;lt;/math&amp;gt; with a length ''T'' estimates a model for a given p.&lt;br /&gt;
&lt;br /&gt;
=== Simulation ===&lt;br /&gt;
&lt;br /&gt;
Perform n Monte Carlo simulations, where in each simulation a the data generating process is used to create a time series. Then the AR(p) model is estimated for ''p=0,1,…,pmax'', and the best models are selected according to the selection criteria described above. Therefore, we will obtain four estimates of p that corresponds to the described methods for each of the n simulation. The final step is to compute % success of correctly estimated p for each of four methods.&lt;br /&gt;
&lt;br /&gt;
== Controls ==&lt;br /&gt;
The solution allow to set number of simulation n. We need high enough n to make sure that the results will converge close enough to actual results. Therefore, we have set &amp;lt;math&amp;gt;n=5000&amp;lt;/math&amp;gt;. Higher n will not significantly increase the precision of the results.&lt;br /&gt;
&lt;br /&gt;
The more important controls is selection of AR(1) or AR(2) process, and selection of parameters &amp;lt;math&amp;gt;{\mu},{\sigma},{\phi}_1&amp;lt;/math&amp;gt;  and  &amp;lt;math&amp;gt;{\phi}_2&amp;lt;/math&amp;gt; for the process. Additionally, we can set length of the generated series and even compare performance for series with two distinct lengths &amp;lt;math&amp;gt;T_1&amp;lt;/math&amp;gt; and &amp;lt;math&amp;gt;T_2&amp;lt;/math&amp;gt;. In other words, one method may perform better for low number of observations than other, and this control allow to compare the performance.&lt;br /&gt;
&lt;br /&gt;
== Results ==&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
&lt;br /&gt;
== Code ==&lt;/div&gt;</summary>
		<author><name>Hazn00</name></author>
		
	</entry>
	<entry>
		<id>http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19127</id>
		<title>Time Series Model Building Process</title>
		<link rel="alternate" type="text/html" href="http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19127"/>
		<updated>2020-01-18T09:40:03Z</updated>

		<summary type="html">&lt;p&gt;Hazn00: /* Controls */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Linear time series models, e.g., ARIMA models for univariate time series, is a popular tool for modeling dynamics of time series and predicting the time series. The methodology is not popular only in statistics, econometrics and science, but also in machine learning business applications. The key question is how to build the model. We have to choose the form of the model, in particular number of lags for so-called autoregressive part (usually denoted as p) and moving average part of the model (usually denoted as d). The common guides usually provide a ‘cook book’ for model selection, see for example [https://www.machinelearningplus.com/time-series/arima-model-time-series-forecasting-python/, ARIMA Model – Complete Guide to Time Series Forecasting in Python] . This goal of this simulation is to compare four basic methods for selection of lags (p) for the autoregressive part.&lt;br /&gt;
&lt;br /&gt;
== Problem Definition ==&lt;br /&gt;
&lt;br /&gt;
The autoregressive process has form&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\phi}_2x_{t-2}+...+{\phi}_px_{t-p} + {\epsilon}_t&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;{\epsilon}_t \sim N(0,{\sigma}^2) &amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
However, we observe only the realized value and we do not know the hyperparameter p. Therefore, we must estimate it. The considered methods are following.&lt;br /&gt;
&lt;br /&gt;
=== GETS (General-to-Specific) ===&lt;br /&gt;
&lt;br /&gt;
We first start with high enough p (pmax in the code), and perform statistical test whether the last lag has statistically significant impact, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p = 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p \neq 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the impact is insignificant, we reduce p by one and continue until the parameter for the last lag is significant, i.e. last lag has significant effect.&lt;br /&gt;
&lt;br /&gt;
=== Specific-to-General ===&lt;br /&gt;
&lt;br /&gt;
The second approach works similarly as GETS, the only difference is that we first start with model without any lag, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and we are adding lags until they are significant.&lt;br /&gt;
&lt;br /&gt;
=== BIC (Bayesian Information Criteria) ===&lt;br /&gt;
&lt;br /&gt;
Bayesian information criteria is based on a likelihood of the model and number of parameters. The criteria punish the model for high number of parameters for a potential over-fitting, and rewards the model for good fit of the data. The lower the BIC value is, the better the model (a little bit counterintuitive definition). We are supposed to select a model with the lowest value of BIC.&lt;br /&gt;
&lt;br /&gt;
=== AIC (Akaike Information Criteria)  ===&lt;br /&gt;
&lt;br /&gt;
Works exactly the same as BIC, but the formula is slightly different.&lt;br /&gt;
&lt;br /&gt;
== Method and Simulation Method ==&lt;br /&gt;
&lt;br /&gt;
The solution consists of three key elements, data generating process, AR(p) model, and simulation.&lt;br /&gt;
&lt;br /&gt;
=== Data Generating Process ===&lt;br /&gt;
&lt;br /&gt;
To answer the question, which model selection method is the best, we are creating an artificial data. We assume that data are created by AR(1) process&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
or AR(2)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\mu} + {\phi}_2x_{t-2} + {\epsilon}_{t}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
with random error &amp;lt;math&amp;gt;&amp;lt;/math&amp;gt; . Therefore, we must generate random numbers for random errors, and iterate over the equations described above. The initial values of the processes, e.g., &amp;lt;math&amp;gt;x_0&amp;lt;/math&amp;gt;, are set to the theoretical mean value of the process.&lt;br /&gt;
&lt;br /&gt;
=== AR(p) model ===&lt;br /&gt;
&lt;br /&gt;
For a given series &amp;lt;math&amp;gt;{x_1,x_2,...x_T}&amp;lt;/math&amp;gt; with a length ''T'' estimates a model for a given p.&lt;br /&gt;
&lt;br /&gt;
=== Simulation ===&lt;br /&gt;
&lt;br /&gt;
Perform n Monte Carlo simulations, where in each simulation a the data generating process is used to create a time series. Then the AR(p) model is estimated for ''p=0,1,…,pmax'', and the best models are selected according to the selection criteria described above. Therefore, we will obtain four estimates of p that corresponds to the described methods for each of the n simulation. The final step is to compute % success of correctly estimated p for each of four methods.&lt;br /&gt;
&lt;br /&gt;
== Controls ==&lt;br /&gt;
The solution allow to set number of simulation n. We need high enough n to make sure that the results will converge close enough to actual results. Therefore, we have set &amp;lt;math&amp;gt;n=5000&amp;lt;/math&amp;gt;. Higher n will not significantly increase the precision of the results.&lt;br /&gt;
&lt;br /&gt;
The more important controls is selection of AR(1) or AR(2) process, and selection of parameters &amp;lt;math&amp;gt;{\mu},{\sigma},{\phi}_1 and {\phi}_2&amp;lt;/math&amp;gt; for the process. Additionally, we can set length of the generated series and even compare performance for series with two distinct lengths &amp;lt;math&amp;gt;T_1&amp;lt;/math&amp;gt; and &amp;lt;math&amp;gt;T_2&amp;lt;/math&amp;gt;. In other words, one method may perform better for low number of observations than other, and this control allow to compare the performance.&lt;br /&gt;
&lt;br /&gt;
== Results ==&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
&lt;br /&gt;
== Code ==&lt;/div&gt;</summary>
		<author><name>Hazn00</name></author>
		
	</entry>
	<entry>
		<id>http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19126</id>
		<title>Time Series Model Building Process</title>
		<link rel="alternate" type="text/html" href="http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19126"/>
		<updated>2020-01-18T09:39:25Z</updated>

		<summary type="html">&lt;p&gt;Hazn00: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Linear time series models, e.g., ARIMA models for univariate time series, is a popular tool for modeling dynamics of time series and predicting the time series. The methodology is not popular only in statistics, econometrics and science, but also in machine learning business applications. The key question is how to build the model. We have to choose the form of the model, in particular number of lags for so-called autoregressive part (usually denoted as p) and moving average part of the model (usually denoted as d). The common guides usually provide a ‘cook book’ for model selection, see for example [https://www.machinelearningplus.com/time-series/arima-model-time-series-forecasting-python/, ARIMA Model – Complete Guide to Time Series Forecasting in Python] . This goal of this simulation is to compare four basic methods for selection of lags (p) for the autoregressive part.&lt;br /&gt;
&lt;br /&gt;
== Problem Definition ==&lt;br /&gt;
&lt;br /&gt;
The autoregressive process has form&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\phi}_2x_{t-2}+...+{\phi}_px_{t-p} + {\epsilon}_t&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;{\epsilon}_t \sim N(0,{\sigma}^2) &amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
However, we observe only the realized value and we do not know the hyperparameter p. Therefore, we must estimate it. The considered methods are following.&lt;br /&gt;
&lt;br /&gt;
=== GETS (General-to-Specific) ===&lt;br /&gt;
&lt;br /&gt;
We first start with high enough p (pmax in the code), and perform statistical test whether the last lag has statistically significant impact, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p = 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p \neq 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the impact is insignificant, we reduce p by one and continue until the parameter for the last lag is significant, i.e. last lag has significant effect.&lt;br /&gt;
&lt;br /&gt;
=== Specific-to-General ===&lt;br /&gt;
&lt;br /&gt;
The second approach works similarly as GETS, the only difference is that we first start with model without any lag, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and we are adding lags until they are significant.&lt;br /&gt;
&lt;br /&gt;
=== BIC (Bayesian Information Criteria) ===&lt;br /&gt;
&lt;br /&gt;
Bayesian information criteria is based on a likelihood of the model and number of parameters. The criteria punish the model for high number of parameters for a potential over-fitting, and rewards the model for good fit of the data. The lower the BIC value is, the better the model (a little bit counterintuitive definition). We are supposed to select a model with the lowest value of BIC.&lt;br /&gt;
&lt;br /&gt;
=== AIC (Akaike Information Criteria)  ===&lt;br /&gt;
&lt;br /&gt;
Works exactly the same as BIC, but the formula is slightly different.&lt;br /&gt;
&lt;br /&gt;
== Method and Simulation Method ==&lt;br /&gt;
&lt;br /&gt;
The solution consists of three key elements, data generating process, AR(p) model, and simulation.&lt;br /&gt;
&lt;br /&gt;
=== Data Generating Process ===&lt;br /&gt;
&lt;br /&gt;
To answer the question, which model selection method is the best, we are creating an artificial data. We assume that data are created by AR(1) process&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
or AR(2)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\mu} + {\phi}_2x_{t-2} + {\epsilon}_{t}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
with random error &amp;lt;math&amp;gt;&amp;lt;/math&amp;gt; . Therefore, we must generate random numbers for random errors, and iterate over the equations described above. The initial values of the processes, e.g., &amp;lt;math&amp;gt;x_0&amp;lt;/math&amp;gt;, are set to the theoretical mean value of the process.&lt;br /&gt;
&lt;br /&gt;
=== AR(p) model ===&lt;br /&gt;
&lt;br /&gt;
For a given series &amp;lt;math&amp;gt;{x_1,x_2,...x_T}&amp;lt;/math&amp;gt; with a length ''T'' estimates a model for a given p.&lt;br /&gt;
&lt;br /&gt;
=== Simulation ===&lt;br /&gt;
&lt;br /&gt;
Perform n Monte Carlo simulations, where in each simulation a the data generating process is used to create a time series. Then the AR(p) model is estimated for ''p=0,1,…,pmax'', and the best models are selected according to the selection criteria described above. Therefore, we will obtain four estimates of p that corresponds to the described methods for each of the n simulation. The final step is to compute % success of correctly estimated p for each of four methods.&lt;br /&gt;
&lt;br /&gt;
== Controls ==&lt;br /&gt;
The solution allow to set number of simulation n. We need high enough n to make sure that the results will converge close enough to actual results. Therefore, we have set &amp;lt;math&amp;gt;n=5000&amp;lt;/math&amp;gt;. Higher n will not significantly increase the precision of the results.&lt;br /&gt;
&lt;br /&gt;
The more important controls is selection of AR(1) or AR(2) process, and selection of parameters &amp;lt;math&amp;gt;{\mu},{/sigma},{phi}_1 and {phi}_2 and&amp;lt;/math&amp;gt; for the process. Additionally, we can set length of the generated series and even compare performance for series with two distinct lengths &amp;lt;math&amp;gt;T_1&amp;lt;/math&amp;gt; and &amp;lt;math&amp;gt;T_2&amp;lt;/math&amp;gt;. In other words, one method may perform better for low number of observations than other, and this control allow to compare the performance. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Results ==&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
&lt;br /&gt;
== Code ==&lt;/div&gt;</summary>
		<author><name>Hazn00</name></author>
		
	</entry>
	<entry>
		<id>http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19125</id>
		<title>Time Series Model Building Process</title>
		<link rel="alternate" type="text/html" href="http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19125"/>
		<updated>2020-01-18T09:36:11Z</updated>

		<summary type="html">&lt;p&gt;Hazn00: /* Simulation */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Linear time series models, e.g., ARIMA models for univariate time series, is a popular tool for modeling dynamics of time series and predicting the time series. The methodology is not popular only in statistics, econometrics and science, but also in machine learning business applications. The key question is how to build the model. We have to choose the form of the model, in particular number of lags for so-called autoregressive part (usually denoted as p) and moving average part of the model (usually denoted as d). The common guides usually provide a ‘cook book’ for model selection, see for example [https://www.machinelearningplus.com/time-series/arima-model-time-series-forecasting-python/, ARIMA Model – Complete Guide to Time Series Forecasting in Python] . This goal of this simulation is to compare four basic methods for selection of lags (p) for the autoregressive part.&lt;br /&gt;
&lt;br /&gt;
== Problem Definition ==&lt;br /&gt;
&lt;br /&gt;
The autoregressive process has form&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\phi}_2x_{t-2}+...+{\phi}_px_{t-p} + {\epsilon}_t&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;{\epsilon}_t \sim N(0,{\sigma}^2) &amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
However, we observe only the realized value and we do not know the hyperparameter p. Therefore, we must estimate it. The considered methods are following.&lt;br /&gt;
&lt;br /&gt;
=== GETS (General-to-Specific) ===&lt;br /&gt;
&lt;br /&gt;
We first start with high enough p (pmax in the code), and perform statistical test whether the last lag has statistically significant impact, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p = 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p \neq 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the impact is insignificant, we reduce p by one and continue until the parameter for the last lag is significant, i.e. last lag has significant effect.&lt;br /&gt;
&lt;br /&gt;
=== Specific-to-General ===&lt;br /&gt;
&lt;br /&gt;
The second approach works similarly as GETS, the only difference is that we first start with model without any lag, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and we are adding lags until they are significant.&lt;br /&gt;
&lt;br /&gt;
=== BIC (Bayesian Information Criteria) ===&lt;br /&gt;
&lt;br /&gt;
Bayesian information criteria is based on a likelihood of the model and number of parameters. The criteria punish the model for high number of parameters for a potential over-fitting, and rewards the model for good fit of the data. The lower the BIC value is, the better the model (a little bit counterintuitive definition). We are supposed to select a model with the lowest value of BIC.&lt;br /&gt;
&lt;br /&gt;
=== AIC (Akaike Information Criteria)  ===&lt;br /&gt;
&lt;br /&gt;
Works exactly the same as BIC, but the formula is slightly different.&lt;br /&gt;
&lt;br /&gt;
== Method and Simulation Method ==&lt;br /&gt;
&lt;br /&gt;
The solution consists of three key elements, data generating process, AR(p) model, and simulation.&lt;br /&gt;
&lt;br /&gt;
=== Data Generating Process ===&lt;br /&gt;
&lt;br /&gt;
To answer the question, which model selection method is the best, we are creating an artificial data. We assume that data are created by AR(1) process&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
or AR(2)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\mu} + {\phi}_2x_{t-2} + {\epsilon}_{t}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
with random error &amp;lt;math&amp;gt;&amp;lt;/math&amp;gt; . Therefore, we must generate random numbers for random errors, and iterate over the equations described above. The initial values of the processes, e.g., &amp;lt;math&amp;gt;x_0&amp;lt;/math&amp;gt;, are set to the theoretical mean value of the process.&lt;br /&gt;
&lt;br /&gt;
=== AR(p) model ===&lt;br /&gt;
&lt;br /&gt;
For a given series &amp;lt;math&amp;gt;{x_1,x_2,...x_T}&amp;lt;/math&amp;gt; with a length ''T'' estimates a model for a given p.&lt;br /&gt;
&lt;br /&gt;
=== Simulation ===&lt;br /&gt;
&lt;br /&gt;
Perform n Monte Carlo simulations, where in each simulation a the data generating process is used to create a time series. Then the AR(p) model is estimated for ''p=0,1,…,pmax'', and the best models are selected according to the selection criteria described above. Therefore, we will obtain four estimates of p that corresponds to the described methods for each of the n simulation. The final step is to compute % success of correctly estimated p for each of four methods.&lt;br /&gt;
&lt;br /&gt;
== Results ==&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
&lt;br /&gt;
== Code ==&lt;/div&gt;</summary>
		<author><name>Hazn00</name></author>
		
	</entry>
	<entry>
		<id>http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19124</id>
		<title>Time Series Model Building Process</title>
		<link rel="alternate" type="text/html" href="http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19124"/>
		<updated>2020-01-18T09:35:47Z</updated>

		<summary type="html">&lt;p&gt;Hazn00: /* AR(p) model */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Linear time series models, e.g., ARIMA models for univariate time series, is a popular tool for modeling dynamics of time series and predicting the time series. The methodology is not popular only in statistics, econometrics and science, but also in machine learning business applications. The key question is how to build the model. We have to choose the form of the model, in particular number of lags for so-called autoregressive part (usually denoted as p) and moving average part of the model (usually denoted as d). The common guides usually provide a ‘cook book’ for model selection, see for example [https://www.machinelearningplus.com/time-series/arima-model-time-series-forecasting-python/, ARIMA Model – Complete Guide to Time Series Forecasting in Python] . This goal of this simulation is to compare four basic methods for selection of lags (p) for the autoregressive part.&lt;br /&gt;
&lt;br /&gt;
== Problem Definition ==&lt;br /&gt;
&lt;br /&gt;
The autoregressive process has form&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\phi}_2x_{t-2}+...+{\phi}_px_{t-p} + {\epsilon}_t&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;{\epsilon}_t \sim N(0,{\sigma}^2) &amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
However, we observe only the realized value and we do not know the hyperparameter p. Therefore, we must estimate it. The considered methods are following.&lt;br /&gt;
&lt;br /&gt;
=== GETS (General-to-Specific) ===&lt;br /&gt;
&lt;br /&gt;
We first start with high enough p (pmax in the code), and perform statistical test whether the last lag has statistically significant impact, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p = 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p \neq 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the impact is insignificant, we reduce p by one and continue until the parameter for the last lag is significant, i.e. last lag has significant effect.&lt;br /&gt;
&lt;br /&gt;
=== Specific-to-General ===&lt;br /&gt;
&lt;br /&gt;
The second approach works similarly as GETS, the only difference is that we first start with model without any lag, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and we are adding lags until they are significant.&lt;br /&gt;
&lt;br /&gt;
=== BIC (Bayesian Information Criteria) ===&lt;br /&gt;
&lt;br /&gt;
Bayesian information criteria is based on a likelihood of the model and number of parameters. The criteria punish the model for high number of parameters for a potential over-fitting, and rewards the model for good fit of the data. The lower the BIC value is, the better the model (a little bit counterintuitive definition). We are supposed to select a model with the lowest value of BIC.&lt;br /&gt;
&lt;br /&gt;
=== AIC (Akaike Information Criteria)  ===&lt;br /&gt;
&lt;br /&gt;
Works exactly the same as BIC, but the formula is slightly different.&lt;br /&gt;
&lt;br /&gt;
== Method and Simulation Method ==&lt;br /&gt;
&lt;br /&gt;
The solution consists of three key elements, data generating process, AR(p) model, and simulation.&lt;br /&gt;
&lt;br /&gt;
=== Data Generating Process ===&lt;br /&gt;
&lt;br /&gt;
To answer the question, which model selection method is the best, we are creating an artificial data. We assume that data are created by AR(1) process&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
or AR(2)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\mu} + {\phi}_2x_{t-2} + {\epsilon}_{t}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
with random error &amp;lt;math&amp;gt;&amp;lt;/math&amp;gt; . Therefore, we must generate random numbers for random errors, and iterate over the equations described above. The initial values of the processes, e.g., &amp;lt;math&amp;gt;x_0&amp;lt;/math&amp;gt;, are set to the theoretical mean value of the process.&lt;br /&gt;
&lt;br /&gt;
=== AR(p) model ===&lt;br /&gt;
&lt;br /&gt;
For a given series &amp;lt;math&amp;gt;{x_1,x_2,...x_T}&amp;lt;/math&amp;gt; with a length ''T'' estimates a model for a given p.&lt;br /&gt;
&lt;br /&gt;
=== Simulation ===&lt;br /&gt;
&lt;br /&gt;
Perform n Monte Carlo simulations, where in each simulation a the data generating process is used to create a time series. Then the AR(p) model is estimated for p=0,1,…,pmax, and the best models are selected according to the selection criteria described above. Therefore, we will obtain four estimates of p that corresponds to the described methods for each of the n simulation. The final step is to compute % success of correctly estimated p for each of four methods.&lt;br /&gt;
&lt;br /&gt;
== Results ==&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
&lt;br /&gt;
== Code ==&lt;/div&gt;</summary>
		<author><name>Hazn00</name></author>
		
	</entry>
	<entry>
		<id>http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19123</id>
		<title>Time Series Model Building Process</title>
		<link rel="alternate" type="text/html" href="http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19123"/>
		<updated>2020-01-18T09:35:34Z</updated>

		<summary type="html">&lt;p&gt;Hazn00: /* AR(p) model */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Linear time series models, e.g., ARIMA models for univariate time series, is a popular tool for modeling dynamics of time series and predicting the time series. The methodology is not popular only in statistics, econometrics and science, but also in machine learning business applications. The key question is how to build the model. We have to choose the form of the model, in particular number of lags for so-called autoregressive part (usually denoted as p) and moving average part of the model (usually denoted as d). The common guides usually provide a ‘cook book’ for model selection, see for example [https://www.machinelearningplus.com/time-series/arima-model-time-series-forecasting-python/, ARIMA Model – Complete Guide to Time Series Forecasting in Python] . This goal of this simulation is to compare four basic methods for selection of lags (p) for the autoregressive part.&lt;br /&gt;
&lt;br /&gt;
== Problem Definition ==&lt;br /&gt;
&lt;br /&gt;
The autoregressive process has form&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\phi}_2x_{t-2}+...+{\phi}_px_{t-p} + {\epsilon}_t&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;{\epsilon}_t \sim N(0,{\sigma}^2) &amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
However, we observe only the realized value and we do not know the hyperparameter p. Therefore, we must estimate it. The considered methods are following.&lt;br /&gt;
&lt;br /&gt;
=== GETS (General-to-Specific) ===&lt;br /&gt;
&lt;br /&gt;
We first start with high enough p (pmax in the code), and perform statistical test whether the last lag has statistically significant impact, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p = 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p \neq 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the impact is insignificant, we reduce p by one and continue until the parameter for the last lag is significant, i.e. last lag has significant effect.&lt;br /&gt;
&lt;br /&gt;
=== Specific-to-General ===&lt;br /&gt;
&lt;br /&gt;
The second approach works similarly as GETS, the only difference is that we first start with model without any lag, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and we are adding lags until they are significant.&lt;br /&gt;
&lt;br /&gt;
=== BIC (Bayesian Information Criteria) ===&lt;br /&gt;
&lt;br /&gt;
Bayesian information criteria is based on a likelihood of the model and number of parameters. The criteria punish the model for high number of parameters for a potential over-fitting, and rewards the model for good fit of the data. The lower the BIC value is, the better the model (a little bit counterintuitive definition). We are supposed to select a model with the lowest value of BIC.&lt;br /&gt;
&lt;br /&gt;
=== AIC (Akaike Information Criteria)  ===&lt;br /&gt;
&lt;br /&gt;
Works exactly the same as BIC, but the formula is slightly different.&lt;br /&gt;
&lt;br /&gt;
== Method and Simulation Method ==&lt;br /&gt;
&lt;br /&gt;
The solution consists of three key elements, data generating process, AR(p) model, and simulation.&lt;br /&gt;
&lt;br /&gt;
=== Data Generating Process ===&lt;br /&gt;
&lt;br /&gt;
To answer the question, which model selection method is the best, we are creating an artificial data. We assume that data are created by AR(1) process&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
or AR(2)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\mu} + {\phi}_2x_{t-2} + {\epsilon}_{t}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
with random error &amp;lt;math&amp;gt;&amp;lt;/math&amp;gt; . Therefore, we must generate random numbers for random errors, and iterate over the equations described above. The initial values of the processes, e.g., &amp;lt;math&amp;gt;x_0&amp;lt;/math&amp;gt;, are set to the theoretical mean value of the process.&lt;br /&gt;
&lt;br /&gt;
=== AR(p) model ===&lt;br /&gt;
&lt;br /&gt;
For a given series &amp;lt;math&amp;gt;{x_1,x_2,...x?T}&amp;lt;/math&amp;gt; with a length ''T'' estimates a model for a given p.&lt;br /&gt;
&lt;br /&gt;
=== Simulation ===&lt;br /&gt;
&lt;br /&gt;
Perform n Monte Carlo simulations, where in each simulation a the data generating process is used to create a time series. Then the AR(p) model is estimated for p=0,1,…,pmax, and the best models are selected according to the selection criteria described above. Therefore, we will obtain four estimates of p that corresponds to the described methods for each of the n simulation. The final step is to compute % success of correctly estimated p for each of four methods.&lt;br /&gt;
&lt;br /&gt;
== Results ==&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
&lt;br /&gt;
== Code ==&lt;/div&gt;</summary>
		<author><name>Hazn00</name></author>
		
	</entry>
	<entry>
		<id>http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19122</id>
		<title>Time Series Model Building Process</title>
		<link rel="alternate" type="text/html" href="http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19122"/>
		<updated>2020-01-18T09:34:51Z</updated>

		<summary type="html">&lt;p&gt;Hazn00: /* Data Generating Process */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Linear time series models, e.g., ARIMA models for univariate time series, is a popular tool for modeling dynamics of time series and predicting the time series. The methodology is not popular only in statistics, econometrics and science, but also in machine learning business applications. The key question is how to build the model. We have to choose the form of the model, in particular number of lags for so-called autoregressive part (usually denoted as p) and moving average part of the model (usually denoted as d). The common guides usually provide a ‘cook book’ for model selection, see for example [https://www.machinelearningplus.com/time-series/arima-model-time-series-forecasting-python/, ARIMA Model – Complete Guide to Time Series Forecasting in Python] . This goal of this simulation is to compare four basic methods for selection of lags (p) for the autoregressive part.&lt;br /&gt;
&lt;br /&gt;
== Problem Definition ==&lt;br /&gt;
&lt;br /&gt;
The autoregressive process has form&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\phi}_2x_{t-2}+...+{\phi}_px_{t-p} + {\epsilon}_t&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;{\epsilon}_t \sim N(0,{\sigma}^2) &amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
However, we observe only the realized value and we do not know the hyperparameter p. Therefore, we must estimate it. The considered methods are following.&lt;br /&gt;
&lt;br /&gt;
=== GETS (General-to-Specific) ===&lt;br /&gt;
&lt;br /&gt;
We first start with high enough p (pmax in the code), and perform statistical test whether the last lag has statistically significant impact, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p = 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p \neq 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the impact is insignificant, we reduce p by one and continue until the parameter for the last lag is significant, i.e. last lag has significant effect.&lt;br /&gt;
&lt;br /&gt;
=== Specific-to-General ===&lt;br /&gt;
&lt;br /&gt;
The second approach works similarly as GETS, the only difference is that we first start with model without any lag, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and we are adding lags until they are significant.&lt;br /&gt;
&lt;br /&gt;
=== BIC (Bayesian Information Criteria) ===&lt;br /&gt;
&lt;br /&gt;
Bayesian information criteria is based on a likelihood of the model and number of parameters. The criteria punish the model for high number of parameters for a potential over-fitting, and rewards the model for good fit of the data. The lower the BIC value is, the better the model (a little bit counterintuitive definition). We are supposed to select a model with the lowest value of BIC.&lt;br /&gt;
&lt;br /&gt;
=== AIC (Akaike Information Criteria)  ===&lt;br /&gt;
&lt;br /&gt;
Works exactly the same as BIC, but the formula is slightly different.&lt;br /&gt;
&lt;br /&gt;
== Method and Simulation Method ==&lt;br /&gt;
&lt;br /&gt;
The solution consists of three key elements, data generating process, AR(p) model, and simulation.&lt;br /&gt;
&lt;br /&gt;
=== Data Generating Process ===&lt;br /&gt;
&lt;br /&gt;
To answer the question, which model selection method is the best, we are creating an artificial data. We assume that data are created by AR(1) process&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
or AR(2)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\mu} + {\phi}_2x_{t-2} + {\epsilon}_{t}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
with random error &amp;lt;math&amp;gt;&amp;lt;/math&amp;gt; . Therefore, we must generate random numbers for random errors, and iterate over the equations described above. The initial values of the processes, e.g., &amp;lt;math&amp;gt;x_0&amp;lt;/math&amp;gt;, are set to the theoretical mean value of the process.&lt;br /&gt;
&lt;br /&gt;
=== AR(p) model ===&lt;br /&gt;
&lt;br /&gt;
For a given series &amp;lt;math&amp;gt;&amp;lt;/math&amp;gt; with a length ''T'' estimates a model for a given p.&lt;br /&gt;
&lt;br /&gt;
=== Simulation ===&lt;br /&gt;
&lt;br /&gt;
Perform n Monte Carlo simulations, where in each simulation a the data generating process is used to create a time series. Then the AR(p) model is estimated for p=0,1,…,pmax, and the best models are selected according to the selection criteria described above. Therefore, we will obtain four estimates of p that corresponds to the described methods for each of the n simulation. The final step is to compute % success of correctly estimated p for each of four methods.&lt;br /&gt;
&lt;br /&gt;
== Results ==&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
&lt;br /&gt;
== Code ==&lt;/div&gt;</summary>
		<author><name>Hazn00</name></author>
		
	</entry>
	<entry>
		<id>http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19121</id>
		<title>Time Series Model Building Process</title>
		<link rel="alternate" type="text/html" href="http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19121"/>
		<updated>2020-01-18T09:34:23Z</updated>

		<summary type="html">&lt;p&gt;Hazn00: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Linear time series models, e.g., ARIMA models for univariate time series, is a popular tool for modeling dynamics of time series and predicting the time series. The methodology is not popular only in statistics, econometrics and science, but also in machine learning business applications. The key question is how to build the model. We have to choose the form of the model, in particular number of lags for so-called autoregressive part (usually denoted as p) and moving average part of the model (usually denoted as d). The common guides usually provide a ‘cook book’ for model selection, see for example [https://www.machinelearningplus.com/time-series/arima-model-time-series-forecasting-python/, ARIMA Model – Complete Guide to Time Series Forecasting in Python] . This goal of this simulation is to compare four basic methods for selection of lags (p) for the autoregressive part.&lt;br /&gt;
&lt;br /&gt;
== Problem Definition ==&lt;br /&gt;
&lt;br /&gt;
The autoregressive process has form&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\phi}_2x_{t-2}+...+{\phi}_px_{t-p} + {\epsilon}_t&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;{\epsilon}_t \sim N(0,{\sigma}^2) &amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
However, we observe only the realized value and we do not know the hyperparameter p. Therefore, we must estimate it. The considered methods are following.&lt;br /&gt;
&lt;br /&gt;
=== GETS (General-to-Specific) ===&lt;br /&gt;
&lt;br /&gt;
We first start with high enough p (pmax in the code), and perform statistical test whether the last lag has statistically significant impact, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p = 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p \neq 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the impact is insignificant, we reduce p by one and continue until the parameter for the last lag is significant, i.e. last lag has significant effect.&lt;br /&gt;
&lt;br /&gt;
=== Specific-to-General ===&lt;br /&gt;
&lt;br /&gt;
The second approach works similarly as GETS, the only difference is that we first start with model without any lag, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and we are adding lags until they are significant.&lt;br /&gt;
&lt;br /&gt;
=== BIC (Bayesian Information Criteria) ===&lt;br /&gt;
&lt;br /&gt;
Bayesian information criteria is based on a likelihood of the model and number of parameters. The criteria punish the model for high number of parameters for a potential over-fitting, and rewards the model for good fit of the data. The lower the BIC value is, the better the model (a little bit counterintuitive definition). We are supposed to select a model with the lowest value of BIC.&lt;br /&gt;
&lt;br /&gt;
=== AIC (Akaike Information Criteria)  ===&lt;br /&gt;
&lt;br /&gt;
Works exactly the same as BIC, but the formula is slightly different.&lt;br /&gt;
&lt;br /&gt;
== Method and Simulation Method ==&lt;br /&gt;
&lt;br /&gt;
The solution consists of three key elements, data generating process, AR(p) model, and simulation.&lt;br /&gt;
&lt;br /&gt;
=== Data Generating Process ===&lt;br /&gt;
&lt;br /&gt;
To answer the question, which model selection method is the best, we are creating an artificial data. We assume that data are created by AR(1) process&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
or AR(2)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\mu} + {\phi}_2x_{t-2} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
with random error &amp;lt;math&amp;gt;&amp;lt;/math&amp;gt; . Therefore, we must generate random numbers for random errors, and iterate over the equations described above. The initial values of the processes, e.g., &amp;lt;math&amp;gt;x_0&amp;lt;/math&amp;gt;, are set to the theoretical mean value of the process.&lt;br /&gt;
&lt;br /&gt;
=== AR(p) model ===&lt;br /&gt;
&lt;br /&gt;
For a given series &amp;lt;math&amp;gt;&amp;lt;/math&amp;gt; with a length ''T'' estimates a model for a given p.&lt;br /&gt;
&lt;br /&gt;
=== Simulation ===&lt;br /&gt;
&lt;br /&gt;
Perform n Monte Carlo simulations, where in each simulation a the data generating process is used to create a time series. Then the AR(p) model is estimated for p=0,1,…,pmax, and the best models are selected according to the selection criteria described above. Therefore, we will obtain four estimates of p that corresponds to the described methods for each of the n simulation. The final step is to compute % success of correctly estimated p for each of four methods.&lt;br /&gt;
&lt;br /&gt;
== Results ==&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
&lt;br /&gt;
== Code ==&lt;/div&gt;</summary>
		<author><name>Hazn00</name></author>
		
	</entry>
	<entry>
		<id>http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19120</id>
		<title>Time Series Model Building Process</title>
		<link rel="alternate" type="text/html" href="http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19120"/>
		<updated>2020-01-18T09:30:59Z</updated>

		<summary type="html">&lt;p&gt;Hazn00: /* AR(p) model */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Linear time series models, e.g., ARIMA models for univariate time series, is a popular tool for modeling dynamics of time series and predicting the time series. The methodology is not popular only in statistics, econometrics and science, but also in machine learning business applications. The key question is how to build the model. We have to choose the form of the model, in particular number of lags for so-called autoregressive part (usually denoted as p) and moving average part of the model (usually denoted as d). The common guides usually provide a ‘cook book’ for model selection, see for example [https://www.machinelearningplus.com/time-series/arima-model-time-series-forecasting-python/, ARIMA Model – Complete Guide to Time Series Forecasting in Python] . This goal of this simulation is to compare four basic methods for selection of lags (p) for the autoregressive part.&lt;br /&gt;
&lt;br /&gt;
== Problem Definition ==&lt;br /&gt;
&lt;br /&gt;
The autoregressive process has form&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\phi}_2x_{t-2}+...+{\phi}_px_{t-p} + {\epsilon}_t&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;{\epsilon}_t \sim N(0,{\sigma}^2) &amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
However, we observe only the realized value and we do not know the hyperparameter p. Therefore, we must estimate it. The considered methods are following.&lt;br /&gt;
&lt;br /&gt;
=== GETS (General-to-Specific) ===&lt;br /&gt;
&lt;br /&gt;
We first start with high enough p (pmax in the code), and perform statistical test whether the last lag has statistically significant impact, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p = 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p \neq 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the impact is insignificant, we reduce p by one and continue until the parameter for the last lag is significant, i.e. last lag has significant effect.&lt;br /&gt;
&lt;br /&gt;
=== Specific-to-General ===&lt;br /&gt;
&lt;br /&gt;
The second approach works similarly as GETS, the only difference is that we first start with model without any lag, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and we are adding lags until they are significant.&lt;br /&gt;
&lt;br /&gt;
=== BIC (Bayesian Information Criteria) ===&lt;br /&gt;
&lt;br /&gt;
Bayesian information criteria is based on a likelihood of the model and number of parameters. The criteria punish the model for high number of parameters for a potential over-fitting, and rewards the model for good fit of the data. The lower the BIC value is, the better the model (a little bit counterintuitive definition). We are supposed to select a model with the lowest value of BIC.&lt;br /&gt;
&lt;br /&gt;
=== AIC (Akaike Information Criteria)  ===&lt;br /&gt;
&lt;br /&gt;
Works exactly the same as BIC, but the formula is slightly different.&lt;br /&gt;
&lt;br /&gt;
== Method and Simulation Method ==&lt;br /&gt;
&lt;br /&gt;
The solution consists of three key elements, data generating process, AR(p) model, and simulation.&lt;br /&gt;
&lt;br /&gt;
=== Data Generating Process ===&lt;br /&gt;
&lt;br /&gt;
To answer the question, which model selection method is the best, we are creating an artificial data. We assume that data are created by AR(1) process&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
or AR(2)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
with random error &amp;lt;math&amp;gt;&amp;lt;/math&amp;gt; . Therefore, we must generate random numbers for random errors, and iterate over the equations described above. The initial values of the processes, e.g., &amp;lt;math&amp;gt;x_0&amp;lt;/math&amp;gt;, are set to the theoretical mean value of the process.&lt;br /&gt;
&lt;br /&gt;
=== AR(p) model ===&lt;br /&gt;
&lt;br /&gt;
For a given series &amp;lt;math&amp;gt;&amp;lt;/math&amp;gt; with a length ''T'' estimates a model for a given p.&lt;br /&gt;
&lt;br /&gt;
=== Simulation ===&lt;br /&gt;
&lt;br /&gt;
Perform n Monte Carlo simulations, where in each simulation a the data generating process is used to create a time series. Then the AR(p) model is estimated for p=0,1,…,pmax, and the best models are selected according to the selection criteria described above. Therefore, we will obtain four estimates of p that corresponds to the described methods for each of the n simulation. The final step is to compute % success of correctly estimated p for each of four methods.&lt;br /&gt;
&lt;br /&gt;
== Results ==&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
&lt;br /&gt;
== Code ==&lt;/div&gt;</summary>
		<author><name>Hazn00</name></author>
		
	</entry>
	<entry>
		<id>http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19119</id>
		<title>Time Series Model Building Process</title>
		<link rel="alternate" type="text/html" href="http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19119"/>
		<updated>2020-01-18T09:30:30Z</updated>

		<summary type="html">&lt;p&gt;Hazn00: /* Data Generating Process */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Linear time series models, e.g., ARIMA models for univariate time series, is a popular tool for modeling dynamics of time series and predicting the time series. The methodology is not popular only in statistics, econometrics and science, but also in machine learning business applications. The key question is how to build the model. We have to choose the form of the model, in particular number of lags for so-called autoregressive part (usually denoted as p) and moving average part of the model (usually denoted as d). The common guides usually provide a ‘cook book’ for model selection, see for example [https://www.machinelearningplus.com/time-series/arima-model-time-series-forecasting-python/, ARIMA Model – Complete Guide to Time Series Forecasting in Python] . This goal of this simulation is to compare four basic methods for selection of lags (p) for the autoregressive part.&lt;br /&gt;
&lt;br /&gt;
== Problem Definition ==&lt;br /&gt;
&lt;br /&gt;
The autoregressive process has form&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\phi}_2x_{t-2}+...+{\phi}_px_{t-p} + {\epsilon}_t&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;{\epsilon}_t \sim N(0,{\sigma}^2) &amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
However, we observe only the realized value and we do not know the hyperparameter p. Therefore, we must estimate it. The considered methods are following.&lt;br /&gt;
&lt;br /&gt;
=== GETS (General-to-Specific) ===&lt;br /&gt;
&lt;br /&gt;
We first start with high enough p (pmax in the code), and perform statistical test whether the last lag has statistically significant impact, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p = 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p \neq 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the impact is insignificant, we reduce p by one and continue until the parameter for the last lag is significant, i.e. last lag has significant effect.&lt;br /&gt;
&lt;br /&gt;
=== Specific-to-General ===&lt;br /&gt;
&lt;br /&gt;
The second approach works similarly as GETS, the only difference is that we first start with model without any lag, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and we are adding lags until they are significant.&lt;br /&gt;
&lt;br /&gt;
=== BIC (Bayesian Information Criteria) ===&lt;br /&gt;
&lt;br /&gt;
Bayesian information criteria is based on a likelihood of the model and number of parameters. The criteria punish the model for high number of parameters for a potential over-fitting, and rewards the model for good fit of the data. The lower the BIC value is, the better the model (a little bit counterintuitive definition). We are supposed to select a model with the lowest value of BIC.&lt;br /&gt;
&lt;br /&gt;
=== AIC (Akaike Information Criteria)  ===&lt;br /&gt;
&lt;br /&gt;
Works exactly the same as BIC, but the formula is slightly different.&lt;br /&gt;
&lt;br /&gt;
== Method and Simulation Method ==&lt;br /&gt;
&lt;br /&gt;
The solution consists of three key elements, data generating process, AR(p) model, and simulation.&lt;br /&gt;
&lt;br /&gt;
=== Data Generating Process ===&lt;br /&gt;
&lt;br /&gt;
To answer the question, which model selection method is the best, we are creating an artificial data. We assume that data are created by AR(1) process&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
or AR(2)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
with random error &amp;lt;math&amp;gt;&amp;lt;/math&amp;gt; . Therefore, we must generate random numbers for random errors, and iterate over the equations described above. The initial values of the processes, e.g., &amp;lt;math&amp;gt;x_0&amp;lt;/math&amp;gt;, are set to the theoretical mean value of the process.&lt;br /&gt;
&lt;br /&gt;
=== AR(p) model ===&lt;br /&gt;
&lt;br /&gt;
For a given series {x_1,x_2,…,x_T} with a length T estimates a model for a given p. &lt;br /&gt;
&lt;br /&gt;
=== Simulation ===&lt;br /&gt;
&lt;br /&gt;
Perform n Monte Carlo simulations, where in each simulation a the data generating process is used to create a time series. Then the AR(p) model is estimated for p=0,1,…,pmax, and the best models are selected according to the selection criteria described above. Therefore, we will obtain four estimates of p that corresponds to the described methods for each of the n simulation. The final step is to compute % success of correctly estimated p for each of four methods.&lt;br /&gt;
&lt;br /&gt;
== Results ==&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
&lt;br /&gt;
== Code ==&lt;/div&gt;</summary>
		<author><name>Hazn00</name></author>
		
	</entry>
	<entry>
		<id>http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19118</id>
		<title>Time Series Model Building Process</title>
		<link rel="alternate" type="text/html" href="http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19118"/>
		<updated>2020-01-18T09:29:35Z</updated>

		<summary type="html">&lt;p&gt;Hazn00: /* Data Generating Process */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Linear time series models, e.g., ARIMA models for univariate time series, is a popular tool for modeling dynamics of time series and predicting the time series. The methodology is not popular only in statistics, econometrics and science, but also in machine learning business applications. The key question is how to build the model. We have to choose the form of the model, in particular number of lags for so-called autoregressive part (usually denoted as p) and moving average part of the model (usually denoted as d). The common guides usually provide a ‘cook book’ for model selection, see for example [https://www.machinelearningplus.com/time-series/arima-model-time-series-forecasting-python/, ARIMA Model – Complete Guide to Time Series Forecasting in Python] . This goal of this simulation is to compare four basic methods for selection of lags (p) for the autoregressive part.&lt;br /&gt;
&lt;br /&gt;
== Problem Definition ==&lt;br /&gt;
&lt;br /&gt;
The autoregressive process has form&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\phi}_2x_{t-2}+...+{\phi}_px_{t-p} + {\epsilon}_t&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;{\epsilon}_t \sim N(0,{\sigma}^2) &amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
However, we observe only the realized value and we do not know the hyperparameter p. Therefore, we must estimate it. The considered methods are following.&lt;br /&gt;
&lt;br /&gt;
=== GETS (General-to-Specific) ===&lt;br /&gt;
&lt;br /&gt;
We first start with high enough p (pmax in the code), and perform statistical test whether the last lag has statistically significant impact, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p = 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p \neq 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the impact is insignificant, we reduce p by one and continue until the parameter for the last lag is significant, i.e. last lag has significant effect.&lt;br /&gt;
&lt;br /&gt;
=== Specific-to-General ===&lt;br /&gt;
&lt;br /&gt;
The second approach works similarly as GETS, the only difference is that we first start with model without any lag, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and we are adding lags until they are significant.&lt;br /&gt;
&lt;br /&gt;
=== BIC (Bayesian Information Criteria) ===&lt;br /&gt;
&lt;br /&gt;
Bayesian information criteria is based on a likelihood of the model and number of parameters. The criteria punish the model for high number of parameters for a potential over-fitting, and rewards the model for good fit of the data. The lower the BIC value is, the better the model (a little bit counterintuitive definition). We are supposed to select a model with the lowest value of BIC.&lt;br /&gt;
&lt;br /&gt;
=== AIC (Akaike Information Criteria)  ===&lt;br /&gt;
&lt;br /&gt;
Works exactly the same as BIC, but the formula is slightly different.&lt;br /&gt;
&lt;br /&gt;
== Method and Simulation Method ==&lt;br /&gt;
&lt;br /&gt;
The solution consists of three key elements, data generating process, AR(p) model, and simulation.&lt;br /&gt;
&lt;br /&gt;
=== Data Generating Process ===&lt;br /&gt;
&lt;br /&gt;
To answer the question, which model selection method is the best, we are creating an artificial data. We assume that data are created by AR(1) process&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
or AR(2)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
with random error (formula). Therefore, we must generate random numbers for random errors, and iterate over the equations described above. The initial values of the processes, e.g., (formula), are set to the theoretical mean value of the process.&lt;br /&gt;
&lt;br /&gt;
=== AR(p) model ===&lt;br /&gt;
&lt;br /&gt;
For a given series {x_1,x_2,…,x_T} with a length T estimates a model for a given p. &lt;br /&gt;
&lt;br /&gt;
=== Simulation ===&lt;br /&gt;
&lt;br /&gt;
Perform n Monte Carlo simulations, where in each simulation a the data generating process is used to create a time series. Then the AR(p) model is estimated for p=0,1,…,pmax, and the best models are selected according to the selection criteria described above. Therefore, we will obtain four estimates of p that corresponds to the described methods for each of the n simulation. The final step is to compute % success of correctly estimated p for each of four methods.&lt;br /&gt;
&lt;br /&gt;
== Results ==&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
&lt;br /&gt;
== Code ==&lt;/div&gt;</summary>
		<author><name>Hazn00</name></author>
		
	</entry>
	<entry>
		<id>http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19117</id>
		<title>Time Series Model Building Process</title>
		<link rel="alternate" type="text/html" href="http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19117"/>
		<updated>2020-01-18T09:28:16Z</updated>

		<summary type="html">&lt;p&gt;Hazn00: /* Specific-to-General */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Linear time series models, e.g., ARIMA models for univariate time series, is a popular tool for modeling dynamics of time series and predicting the time series. The methodology is not popular only in statistics, econometrics and science, but also in machine learning business applications. The key question is how to build the model. We have to choose the form of the model, in particular number of lags for so-called autoregressive part (usually denoted as p) and moving average part of the model (usually denoted as d). The common guides usually provide a ‘cook book’ for model selection, see for example [https://www.machinelearningplus.com/time-series/arima-model-time-series-forecasting-python/, ARIMA Model – Complete Guide to Time Series Forecasting in Python] . This goal of this simulation is to compare four basic methods for selection of lags (p) for the autoregressive part.&lt;br /&gt;
&lt;br /&gt;
== Problem Definition ==&lt;br /&gt;
&lt;br /&gt;
The autoregressive process has form&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\phi}_2x_{t-2}+...+{\phi}_px_{t-p} + {\epsilon}_t&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;{\epsilon}_t \sim N(0,{\sigma}^2) &amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
However, we observe only the realized value and we do not know the hyperparameter p. Therefore, we must estimate it. The considered methods are following.&lt;br /&gt;
&lt;br /&gt;
=== GETS (General-to-Specific) ===&lt;br /&gt;
&lt;br /&gt;
We first start with high enough p (pmax in the code), and perform statistical test whether the last lag has statistically significant impact, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p = 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p \neq 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the impact is insignificant, we reduce p by one and continue until the parameter for the last lag is significant, i.e. last lag has significant effect.&lt;br /&gt;
&lt;br /&gt;
=== Specific-to-General ===&lt;br /&gt;
&lt;br /&gt;
The second approach works similarly as GETS, the only difference is that we first start with model without any lag, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and we are adding lags until they are significant.&lt;br /&gt;
&lt;br /&gt;
=== BIC (Bayesian Information Criteria) ===&lt;br /&gt;
&lt;br /&gt;
Bayesian information criteria is based on a likelihood of the model and number of parameters. The criteria punish the model for high number of parameters for a potential over-fitting, and rewards the model for good fit of the data. The lower the BIC value is, the better the model (a little bit counterintuitive definition). We are supposed to select a model with the lowest value of BIC.&lt;br /&gt;
&lt;br /&gt;
=== AIC (Akaike Information Criteria)  ===&lt;br /&gt;
&lt;br /&gt;
Works exactly the same as BIC, but the formula is slightly different.&lt;br /&gt;
&lt;br /&gt;
== Method and Simulation Method ==&lt;br /&gt;
&lt;br /&gt;
The solution consists of three key elements, data generating process, AR(p) model, and simulation.&lt;br /&gt;
&lt;br /&gt;
=== Data Generating Process ===&lt;br /&gt;
&lt;br /&gt;
To answer the question, which model selection method is the best, we are creating an artificial data. We assume that data are created by AR(1) process&lt;br /&gt;
&lt;br /&gt;
(Formula)&lt;br /&gt;
&lt;br /&gt;
with random error (formula). Therefore, we must generate random numbers for random errors, and iterate over the equations described above. The initial values of the processes, e.g., (formula), are set to the theoretical mean value of the process.&lt;br /&gt;
&lt;br /&gt;
=== AR(p) model ===&lt;br /&gt;
&lt;br /&gt;
For a given series {x_1,x_2,…,x_T} with a length T estimates a model for a given p. &lt;br /&gt;
&lt;br /&gt;
=== Simulation ===&lt;br /&gt;
&lt;br /&gt;
Perform n Monte Carlo simulations, where in each simulation a the data generating process is used to create a time series. Then the AR(p) model is estimated for p=0,1,…,pmax, and the best models are selected according to the selection criteria described above. Therefore, we will obtain four estimates of p that corresponds to the described methods for each of the n simulation. The final step is to compute % success of correctly estimated p for each of four methods.&lt;br /&gt;
&lt;br /&gt;
== Results ==&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
&lt;br /&gt;
== Code ==&lt;/div&gt;</summary>
		<author><name>Hazn00</name></author>
		
	</entry>
	<entry>
		<id>http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19116</id>
		<title>Time Series Model Building Process</title>
		<link rel="alternate" type="text/html" href="http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19116"/>
		<updated>2020-01-18T09:27:50Z</updated>

		<summary type="html">&lt;p&gt;Hazn00: /* Specific-to-General */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Linear time series models, e.g., ARIMA models for univariate time series, is a popular tool for modeling dynamics of time series and predicting the time series. The methodology is not popular only in statistics, econometrics and science, but also in machine learning business applications. The key question is how to build the model. We have to choose the form of the model, in particular number of lags for so-called autoregressive part (usually denoted as p) and moving average part of the model (usually denoted as d). The common guides usually provide a ‘cook book’ for model selection, see for example [https://www.machinelearningplus.com/time-series/arima-model-time-series-forecasting-python/, ARIMA Model – Complete Guide to Time Series Forecasting in Python] . This goal of this simulation is to compare four basic methods for selection of lags (p) for the autoregressive part.&lt;br /&gt;
&lt;br /&gt;
== Problem Definition ==&lt;br /&gt;
&lt;br /&gt;
The autoregressive process has form&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\phi}_2x_{t-2}+...+{\phi}_px_{t-p} + {\epsilon}_t&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;{\epsilon}_t \sim N(0,{\sigma}^2) &amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
However, we observe only the realized value and we do not know the hyperparameter p. Therefore, we must estimate it. The considered methods are following.&lt;br /&gt;
&lt;br /&gt;
=== GETS (General-to-Specific) ===&lt;br /&gt;
&lt;br /&gt;
We first start with high enough p (pmax in the code), and perform statistical test whether the last lag has statistically significant impact, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p = 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p \neq 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the impact is insignificant, we reduce p by one and continue until the parameter for the last lag is significant, i.e. last lag has significant effect.&lt;br /&gt;
&lt;br /&gt;
=== Specific-to-General ===&lt;br /&gt;
&lt;br /&gt;
The second approach works similarly as GETS, the only difference is that we first start with model without any lag, i.e.,&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\epsilon}_{t'}&amp;lt;/math&amp;gt;&lt;br /&gt;
and we are adding lags until they are significant.&lt;br /&gt;
&lt;br /&gt;
=== BIC (Bayesian Information Criteria) ===&lt;br /&gt;
&lt;br /&gt;
Bayesian information criteria is based on a likelihood of the model and number of parameters. The criteria punish the model for high number of parameters for a potential over-fitting, and rewards the model for good fit of the data. The lower the BIC value is, the better the model (a little bit counterintuitive definition). We are supposed to select a model with the lowest value of BIC.&lt;br /&gt;
&lt;br /&gt;
=== AIC (Akaike Information Criteria)  ===&lt;br /&gt;
&lt;br /&gt;
Works exactly the same as BIC, but the formula is slightly different.&lt;br /&gt;
&lt;br /&gt;
== Method and Simulation Method ==&lt;br /&gt;
&lt;br /&gt;
The solution consists of three key elements, data generating process, AR(p) model, and simulation.&lt;br /&gt;
&lt;br /&gt;
=== Data Generating Process ===&lt;br /&gt;
&lt;br /&gt;
To answer the question, which model selection method is the best, we are creating an artificial data. We assume that data are created by AR(1) process&lt;br /&gt;
&lt;br /&gt;
(Formula)&lt;br /&gt;
&lt;br /&gt;
with random error (formula). Therefore, we must generate random numbers for random errors, and iterate over the equations described above. The initial values of the processes, e.g., (formula), are set to the theoretical mean value of the process.&lt;br /&gt;
&lt;br /&gt;
=== AR(p) model ===&lt;br /&gt;
&lt;br /&gt;
For a given series {x_1,x_2,…,x_T} with a length T estimates a model for a given p. &lt;br /&gt;
&lt;br /&gt;
=== Simulation ===&lt;br /&gt;
&lt;br /&gt;
Perform n Monte Carlo simulations, where in each simulation a the data generating process is used to create a time series. Then the AR(p) model is estimated for p=0,1,…,pmax, and the best models are selected according to the selection criteria described above. Therefore, we will obtain four estimates of p that corresponds to the described methods for each of the n simulation. The final step is to compute % success of correctly estimated p for each of four methods.&lt;br /&gt;
&lt;br /&gt;
== Results ==&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
&lt;br /&gt;
== Code ==&lt;/div&gt;</summary>
		<author><name>Hazn00</name></author>
		
	</entry>
	<entry>
		<id>http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19115</id>
		<title>Time Series Model Building Process</title>
		<link rel="alternate" type="text/html" href="http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19115"/>
		<updated>2020-01-18T09:26:12Z</updated>

		<summary type="html">&lt;p&gt;Hazn00: /* GETS (General-to-Specific) */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Linear time series models, e.g., ARIMA models for univariate time series, is a popular tool for modeling dynamics of time series and predicting the time series. The methodology is not popular only in statistics, econometrics and science, but also in machine learning business applications. The key question is how to build the model. We have to choose the form of the model, in particular number of lags for so-called autoregressive part (usually denoted as p) and moving average part of the model (usually denoted as d). The common guides usually provide a ‘cook book’ for model selection, see for example [https://www.machinelearningplus.com/time-series/arima-model-time-series-forecasting-python/, ARIMA Model – Complete Guide to Time Series Forecasting in Python] . This goal of this simulation is to compare four basic methods for selection of lags (p) for the autoregressive part.&lt;br /&gt;
&lt;br /&gt;
== Problem Definition ==&lt;br /&gt;
&lt;br /&gt;
The autoregressive process has form&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\phi}_2x_{t-2}+...+{\phi}_px_{t-p} + {\epsilon}_t&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;{\epsilon}_t \sim N(0,{\sigma}^2) &amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
However, we observe only the realized value and we do not know the hyperparameter p. Therefore, we must estimate it. The considered methods are following.&lt;br /&gt;
&lt;br /&gt;
=== GETS (General-to-Specific) ===&lt;br /&gt;
&lt;br /&gt;
We first start with high enough p (pmax in the code), and perform statistical test whether the last lag has statistically significant impact, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p = 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p \neq 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the impact is insignificant, we reduce p by one and continue until the parameter for the last lag is significant, i.e. last lag has significant effect.&lt;br /&gt;
&lt;br /&gt;
=== Specific-to-General ===&lt;br /&gt;
&lt;br /&gt;
The second approach works similarly as GETS, the only difference is that we first start with model without any lag, i.e.,&lt;br /&gt;
&lt;br /&gt;
(formula)&lt;br /&gt;
&lt;br /&gt;
and we are adding lags until they are significant. &lt;br /&gt;
&lt;br /&gt;
=== BIC (Bayesian Information Criteria) ===&lt;br /&gt;
&lt;br /&gt;
Bayesian information criteria is based on a likelihood of the model and number of parameters. The criteria punish the model for high number of parameters for a potential over-fitting, and rewards the model for good fit of the data. The lower the BIC value is, the better the model (a little bit counterintuitive definition). We are supposed to select a model with the lowest value of BIC.&lt;br /&gt;
&lt;br /&gt;
=== AIC (Akaike Information Criteria)  ===&lt;br /&gt;
&lt;br /&gt;
Works exactly the same as BIC, but the formula is slightly different.&lt;br /&gt;
&lt;br /&gt;
== Method and Simulation Method ==&lt;br /&gt;
&lt;br /&gt;
The solution consists of three key elements, data generating process, AR(p) model, and simulation.&lt;br /&gt;
&lt;br /&gt;
=== Data Generating Process ===&lt;br /&gt;
&lt;br /&gt;
To answer the question, which model selection method is the best, we are creating an artificial data. We assume that data are created by AR(1) process&lt;br /&gt;
&lt;br /&gt;
(Formula)&lt;br /&gt;
&lt;br /&gt;
with random error (formula). Therefore, we must generate random numbers for random errors, and iterate over the equations described above. The initial values of the processes, e.g., (formula), are set to the theoretical mean value of the process.&lt;br /&gt;
&lt;br /&gt;
=== AR(p) model ===&lt;br /&gt;
&lt;br /&gt;
For a given series {x_1,x_2,…,x_T} with a length T estimates a model for a given p. &lt;br /&gt;
&lt;br /&gt;
=== Simulation ===&lt;br /&gt;
&lt;br /&gt;
Perform n Monte Carlo simulations, where in each simulation a the data generating process is used to create a time series. Then the AR(p) model is estimated for p=0,1,…,pmax, and the best models are selected according to the selection criteria described above. Therefore, we will obtain four estimates of p that corresponds to the described methods for each of the n simulation. The final step is to compute % success of correctly estimated p for each of four methods.&lt;br /&gt;
&lt;br /&gt;
== Results ==&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
&lt;br /&gt;
== Code ==&lt;/div&gt;</summary>
		<author><name>Hazn00</name></author>
		
	</entry>
	<entry>
		<id>http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19114</id>
		<title>Time Series Model Building Process</title>
		<link rel="alternate" type="text/html" href="http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19114"/>
		<updated>2020-01-18T09:25:48Z</updated>

		<summary type="html">&lt;p&gt;Hazn00: /* Problem Definition */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Linear time series models, e.g., ARIMA models for univariate time series, is a popular tool for modeling dynamics of time series and predicting the time series. The methodology is not popular only in statistics, econometrics and science, but also in machine learning business applications. The key question is how to build the model. We have to choose the form of the model, in particular number of lags for so-called autoregressive part (usually denoted as p) and moving average part of the model (usually denoted as d). The common guides usually provide a ‘cook book’ for model selection, see for example [https://www.machinelearningplus.com/time-series/arima-model-time-series-forecasting-python/, ARIMA Model – Complete Guide to Time Series Forecasting in Python] . This goal of this simulation is to compare four basic methods for selection of lags (p) for the autoregressive part.&lt;br /&gt;
&lt;br /&gt;
== Problem Definition ==&lt;br /&gt;
&lt;br /&gt;
The autoregressive process has form&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\phi}_2x_{t-2}+...+{\phi}_px_{t-p} + {\epsilon}_t&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;{\epsilon}_t \sim N(0,{\sigma}^2) &amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
However, we observe only the realized value and we do not know the hyperparameter p. Therefore, we must estimate it. The considered methods are following.&lt;br /&gt;
&lt;br /&gt;
=== GETS (General-to-Specific) ===&lt;br /&gt;
&lt;br /&gt;
We first start with high enough p (pmax in the code), and perform statistical test whether the last lag has statistically significant impact, i.e.,&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p = 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&amp;lt;math&amp;gt;H_0:{\phi}_p \neq 0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the impact is insignificant, we reduce p by one and continue until the parameter for the last lag is significant, i.e. last lag has significant effect.&lt;br /&gt;
&lt;br /&gt;
=== Specific-to-General ===&lt;br /&gt;
&lt;br /&gt;
The second approach works similarly as GETS, the only difference is that we first start with model without any lag, i.e.,&lt;br /&gt;
&lt;br /&gt;
(formula)&lt;br /&gt;
&lt;br /&gt;
and we are adding lags until they are significant. &lt;br /&gt;
&lt;br /&gt;
=== BIC (Bayesian Information Criteria) ===&lt;br /&gt;
&lt;br /&gt;
Bayesian information criteria is based on a likelihood of the model and number of parameters. The criteria punish the model for high number of parameters for a potential over-fitting, and rewards the model for good fit of the data. The lower the BIC value is, the better the model (a little bit counterintuitive definition). We are supposed to select a model with the lowest value of BIC.&lt;br /&gt;
&lt;br /&gt;
=== AIC (Akaike Information Criteria)  ===&lt;br /&gt;
&lt;br /&gt;
Works exactly the same as BIC, but the formula is slightly different.&lt;br /&gt;
&lt;br /&gt;
== Method and Simulation Method ==&lt;br /&gt;
&lt;br /&gt;
The solution consists of three key elements, data generating process, AR(p) model, and simulation.&lt;br /&gt;
&lt;br /&gt;
=== Data Generating Process ===&lt;br /&gt;
&lt;br /&gt;
To answer the question, which model selection method is the best, we are creating an artificial data. We assume that data are created by AR(1) process&lt;br /&gt;
&lt;br /&gt;
(Formula)&lt;br /&gt;
&lt;br /&gt;
with random error (formula). Therefore, we must generate random numbers for random errors, and iterate over the equations described above. The initial values of the processes, e.g., (formula), are set to the theoretical mean value of the process.&lt;br /&gt;
&lt;br /&gt;
=== AR(p) model ===&lt;br /&gt;
&lt;br /&gt;
For a given series {x_1,x_2,…,x_T} with a length T estimates a model for a given p. &lt;br /&gt;
&lt;br /&gt;
=== Simulation ===&lt;br /&gt;
&lt;br /&gt;
Perform n Monte Carlo simulations, where in each simulation a the data generating process is used to create a time series. Then the AR(p) model is estimated for p=0,1,…,pmax, and the best models are selected according to the selection criteria described above. Therefore, we will obtain four estimates of p that corresponds to the described methods for each of the n simulation. The final step is to compute % success of correctly estimated p for each of four methods.&lt;br /&gt;
&lt;br /&gt;
== Results ==&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
&lt;br /&gt;
== Code ==&lt;/div&gt;</summary>
		<author><name>Hazn00</name></author>
		
	</entry>
	<entry>
		<id>http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19113</id>
		<title>Time Series Model Building Process</title>
		<link rel="alternate" type="text/html" href="http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19113"/>
		<updated>2020-01-18T09:19:28Z</updated>

		<summary type="html">&lt;p&gt;Hazn00: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Linear time series models, e.g., ARIMA models for univariate time series, is a popular tool for modeling dynamics of time series and predicting the time series. The methodology is not popular only in statistics, econometrics and science, but also in machine learning business applications. The key question is how to build the model. We have to choose the form of the model, in particular number of lags for so-called autoregressive part (usually denoted as p) and moving average part of the model (usually denoted as d). The common guides usually provide a ‘cook book’ for model selection, see for example [https://www.machinelearningplus.com/time-series/arima-model-time-series-forecasting-python/, ARIMA Model – Complete Guide to Time Series Forecasting in Python] . This goal of this simulation is to compare four basic methods for selection of lags (p) for the autoregressive part.&lt;br /&gt;
&lt;br /&gt;
== Problem Definition ==&lt;br /&gt;
&lt;br /&gt;
The autoregressive process has form&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;x_t = {\mu} + {\phi}_1x_{t-1} + {\phi}_2x_{t-2}+...+{\phi}_px_{t-p} + {\epsilon}_t&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
However, we observe only the realized value and we do not know the hyperparameter p. Therefore, we must estimate it. The considered methods are following.&lt;br /&gt;
&lt;br /&gt;
=== GETS (General-to-Specific) ===&lt;br /&gt;
&lt;br /&gt;
We first start with high enough p (pmax in the code), and perform statistical test whether the last lag has statistically significant impact, i.e.,&lt;br /&gt;
&lt;br /&gt;
(formula)&lt;br /&gt;
&lt;br /&gt;
If the impact is insignificant, we reduce p by one and continue until the parameter for the last lag is significant, i.e. last lag has significant effect.&lt;br /&gt;
&lt;br /&gt;
=== Specific-to-General ===&lt;br /&gt;
&lt;br /&gt;
The second approach works similarly as GETS, the only difference is that we first start with model without any lag, i.e.,&lt;br /&gt;
&lt;br /&gt;
(formula)&lt;br /&gt;
&lt;br /&gt;
and we are adding lags until they are significant. &lt;br /&gt;
&lt;br /&gt;
=== BIC (Bayesian Information Criteria) ===&lt;br /&gt;
&lt;br /&gt;
Bayesian information criteria is based on a likelihood of the model and number of parameters. The criteria punish the model for high number of parameters for a potential over-fitting, and rewards the model for good fit of the data. The lower the BIC value is, the better the model (a little bit counterintuitive definition). We are supposed to select a model with the lowest value of BIC.&lt;br /&gt;
&lt;br /&gt;
=== AIC (Akaike Information Criteria)  ===&lt;br /&gt;
&lt;br /&gt;
Works exactly the same as BIC, but the formula is slightly different.&lt;br /&gt;
&lt;br /&gt;
== Method and Simulation Method ==&lt;br /&gt;
&lt;br /&gt;
The solution consists of three key elements, data generating process, AR(p) model, and simulation.&lt;br /&gt;
&lt;br /&gt;
=== Data Generating Process ===&lt;br /&gt;
&lt;br /&gt;
To answer the question, which model selection method is the best, we are creating an artificial data. We assume that data are created by AR(1) process&lt;br /&gt;
&lt;br /&gt;
(Formula)&lt;br /&gt;
&lt;br /&gt;
with random error (formula). Therefore, we must generate random numbers for random errors, and iterate over the equations described above. The initial values of the processes, e.g., (formula), are set to the theoretical mean value of the process.&lt;br /&gt;
&lt;br /&gt;
=== AR(p) model ===&lt;br /&gt;
&lt;br /&gt;
For a given series {x_1,x_2,…,x_T} with a length T estimates a model for a given p. &lt;br /&gt;
&lt;br /&gt;
=== Simulation ===&lt;br /&gt;
&lt;br /&gt;
Perform n Monte Carlo simulations, where in each simulation a the data generating process is used to create a time series. Then the AR(p) model is estimated for p=0,1,…,pmax, and the best models are selected according to the selection criteria described above. Therefore, we will obtain four estimates of p that corresponds to the described methods for each of the n simulation. The final step is to compute % success of correctly estimated p for each of four methods.&lt;br /&gt;
&lt;br /&gt;
== Results ==&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
&lt;br /&gt;
== Code ==&lt;/div&gt;</summary>
		<author><name>Hazn00</name></author>
		
	</entry>
	<entry>
		<id>http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19111</id>
		<title>Time Series Model Building Process</title>
		<link rel="alternate" type="text/html" href="http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19111"/>
		<updated>2020-01-16T16:56:55Z</updated>

		<summary type="html">&lt;p&gt;Hazn00: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Linear time series models, e.g., ARIMA models for univariate time series, is a popular tool for modeling dynamics of time series and predicting the time series. The methodology is not popular only in statistics, econometrics and science, but also in machine learning business applications. The key question is how to build the model. We have to choose the form of the model, in particular number of lags for so-called autoregressive part (usually denoted as p) and moving average part of the model (usually denoted as d). The common guides usually provide a ‘cook book’ for model selection, see for example [https://www.machinelearningplus.com/time-series/arima-model-time-series-forecasting-python/, ARIMA Model – Complete Guide to Time Series Forecasting in Python] . This goal of this simulation is to compare four basic methods for selection of lags (p) for the autoregressive part.&lt;br /&gt;
&lt;br /&gt;
== Problem Definition ==&lt;br /&gt;
&lt;br /&gt;
The autoregressive process has form&lt;br /&gt;
&lt;br /&gt;
(math formula that is pretty difficult to format in this editor -_-&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
However, we observe only the realized value and we do not know the hyperparameter p. Therefore, we must estimate it. The considered methods are following.&lt;br /&gt;
&lt;br /&gt;
=== GETS (General-to-Specific) ===&lt;br /&gt;
&lt;br /&gt;
We first start with high enough p (pmax in the code), and perform statistical test whether the last lag has statistically significant impact, i.e.,&lt;br /&gt;
&lt;br /&gt;
(formula)&lt;br /&gt;
&lt;br /&gt;
If the impact is insignificant, we reduce p by one and continue until the parameter for the last lag is significant, i.e. last lag has significant effect.&lt;br /&gt;
&lt;br /&gt;
=== Specific-to-General ===&lt;br /&gt;
&lt;br /&gt;
The second approach works similarly as GETS, the only difference is that we first start with model without any lag, i.e.,&lt;br /&gt;
&lt;br /&gt;
(formula)&lt;br /&gt;
&lt;br /&gt;
and we are adding lags until they are significant. &lt;br /&gt;
&lt;br /&gt;
=== BIC (Bayesian Information Criteria) ===&lt;br /&gt;
&lt;br /&gt;
Bayesian information criteria is based on a likelihood of the model and number of parameters. The criteria punish the model for high number of parameters for a potential over-fitting, and rewards the model for good fit of the data. The lower the BIC value is, the better the model (a little bit counterintuitive definition). We are supposed to select a model with the lowest value of BIC.&lt;br /&gt;
&lt;br /&gt;
=== AIC (Akaike Information Criteria)  ===&lt;br /&gt;
&lt;br /&gt;
Works exactly the same as BIC, but the formula is slightly different.&lt;br /&gt;
&lt;br /&gt;
== Method and Simulation Method ==&lt;br /&gt;
&lt;br /&gt;
The solution consists of three key elements, data generating process, AR(p) model, and simulation.&lt;br /&gt;
&lt;br /&gt;
=== Data Generating Process ===&lt;br /&gt;
&lt;br /&gt;
To answer the question, which model selection method is the best, we are creating an artificial data. We assume that data are created by AR(1) process&lt;br /&gt;
&lt;br /&gt;
(Formula)&lt;br /&gt;
&lt;br /&gt;
with random error (formula). Therefore, we must generate random numbers for random errors, and iterate over the equations described above. The initial values of the processes, e.g., (formula), are set to the theoretical mean value of the process.&lt;br /&gt;
&lt;br /&gt;
=== AR(p) model ===&lt;br /&gt;
&lt;br /&gt;
For a given series {x_1,x_2,…,x_T} with a length T estimates a model for a given p. &lt;br /&gt;
&lt;br /&gt;
=== Simulation ===&lt;br /&gt;
&lt;br /&gt;
Perform n Monte Carlo simulations, where in each simulation a the data generating process is used to create a time series. Then the AR(p) model is estimated for p=0,1,…,pmax, and the best models are selected according to the selection criteria described above. Therefore, we will obtain four estimates of p that corresponds to the described methods for each of the n simulation. The final step is to compute % success of correctly estimated p for each of four methods.&lt;br /&gt;
&lt;br /&gt;
== Results ==&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
&lt;br /&gt;
== Code ==&lt;/div&gt;</summary>
		<author><name>Hazn00</name></author>
		
	</entry>
	<entry>
		<id>http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19110</id>
		<title>Time Series Model Building Process</title>
		<link rel="alternate" type="text/html" href="http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19110"/>
		<updated>2020-01-16T16:49:21Z</updated>

		<summary type="html">&lt;p&gt;Hazn00: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Linear time series models, e.g., ARIMA models for univariate time series, is a popular tool for modeling dynamics of time series and predicting the time series. The methodology is not popular only in statistics, econometrics and science, but also in machine learning business applications. The key question is how to build the model. We have to choose the form of the model, in particular number of lags for so-called autoregressive part (usually denoted as p) and moving average part of the model (usually denoted as d). The common guides usually provide a ‘cook book’ for model selection, see for example [https://www.machinelearningplus.com/time-series/arima-model-time-series-forecasting-python/, ARIMA Model – Complete Guide to Time Series Forecasting in Python] . This goal of this simulation is to compare four basic methods for selection of lags (p) for the autoregressive part.&lt;br /&gt;
&lt;br /&gt;
== Problem Definition ==&lt;br /&gt;
&lt;br /&gt;
The autoregressive process has form&lt;br /&gt;
&lt;br /&gt;
(math formula that is difficult to format in this editor -_-&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
However, we observe only the realized value and we do not know the hyperparameter p. Therefore, we must estimate it. The considered methods are following.&lt;br /&gt;
&lt;br /&gt;
=== GETS (General-to-Specific) ===&lt;br /&gt;
&lt;br /&gt;
We first start with high enough p (pmax in the code), and perform statistical test whether the last lag has statistically significant impact, i.e.,&lt;br /&gt;
&lt;br /&gt;
(formula)&lt;br /&gt;
&lt;br /&gt;
If the impact is insignificant, we reduce p by one and continue until the parameter for the last lag is significant, i.e. last lag has significant effect.&lt;br /&gt;
&lt;br /&gt;
=== Specific-to-General ===&lt;br /&gt;
&lt;br /&gt;
The second approach works similarly as GETS, the only difference is that we first start with model without any lag, i.e.,&lt;br /&gt;
&lt;br /&gt;
(formula)&lt;br /&gt;
&lt;br /&gt;
and we are adding lags until they are significant. &lt;br /&gt;
&lt;br /&gt;
=== BIC (Bayesian Information Criteria) ===&lt;br /&gt;
&lt;br /&gt;
Bayesian information criteria is based on a likelihood of the model and number of parameters. The criteria punish the model for high number of parameters for a potential over-fitting, and rewards the model for good fit of the data. The lower the BIC value is, the better the model (a little bit counterintuitive definition). We are supposed to select a model with the lowest value of BIC.&lt;br /&gt;
&lt;br /&gt;
=== AIC  ===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Method ==&lt;br /&gt;
&lt;br /&gt;
== Model ==&lt;br /&gt;
&lt;br /&gt;
== Results ==&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
&lt;br /&gt;
== Code ==&lt;/div&gt;</summary>
		<author><name>Hazn00</name></author>
		
	</entry>
	<entry>
		<id>http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19109</id>
		<title>Time Series Model Building Process</title>
		<link rel="alternate" type="text/html" href="http://www.simulace.info/index.php?title=Time_Series_Model_Building_Process&amp;diff=19109"/>
		<updated>2020-01-16T16:48:47Z</updated>

		<summary type="html">&lt;p&gt;Hazn00: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== Introduction ==&lt;br /&gt;
&lt;br /&gt;
Linear time series models, e.g., ARIMA models for univariate time series, is a popular tool for modeling dynamics of time series and predicting the time series. The methodology is not popular only in statistics, econometrics and science, but also in machine learning business applications. The key question is how to build the model. We have to choose the form of the model, in particular number of lags for so-called autoregressive part (usually denoted as p) and moving average part of the model (usually denoted as d). The common guides usually provide a ‘cook book’ for model selection, see for example [https://www.machinelearningplus.com/time-series/arima-model-time-series-forecasting-python/, ARIMA Model – Complete Guide to Time Series Forecasting in Python] . This goal of this simulation is to compare four basic methods for selection of lags (p) for the autoregressive part.&lt;br /&gt;
&lt;br /&gt;
== Problem Definition ==&lt;br /&gt;
&lt;br /&gt;
The autoregressive process has form&lt;br /&gt;
&lt;br /&gt;
(math formula that is difficult to format in this editor -_-&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
However, we observe only the realized value and we do not know the hyperparameter p. Therefore, we must estimate it. The considered methods are following.&lt;br /&gt;
&lt;br /&gt;
=== GETS (General-to-Specific) ===&lt;br /&gt;
&lt;br /&gt;
We first start with high enough p (pmax in the code), and perform statistical test whether the last lag has statistically significant impact, i.e.,&lt;br /&gt;
(formula)&lt;br /&gt;
If the impact is insignificant, we reduce p by one and continue until the parameter for the last lag is significant, i.e. last lag has significant effect.&lt;br /&gt;
&lt;br /&gt;
=== Specific-to-General ===&lt;br /&gt;
&lt;br /&gt;
The second approach works similarly as GETS, the only difference is that we first start with model without any lag, i.e.,&lt;br /&gt;
(formula)&lt;br /&gt;
and we are adding lags until they are significant. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== BIC (Bayesian Information Criteria) ===&lt;br /&gt;
&lt;br /&gt;
Bayesian information criteria is based on a likelihood of the model and number of parameters. The criteria punish the model for high number of parameters for a potential over-fitting, and rewards the model for good fit of the data. The lower the BIC value is, the better the model (a little bit counterintuitive definition). We are supposed to select a model with the lowest value of BIC.&lt;br /&gt;
&lt;br /&gt;
=== AIC  ===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Method ==&lt;br /&gt;
&lt;br /&gt;
== Model ==&lt;br /&gt;
&lt;br /&gt;
== Results ==&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
&lt;br /&gt;
== Code ==&lt;/div&gt;</summary>
		<author><name>Hazn00</name></author>
		
	</entry>
</feed>