Skip to content

Instantly share code, notes, and snippets.

@h3ik0th
Created September 16, 2021 16:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save h3ik0th/19ba47965c50e5d4b84e14ba96137c93 to your computer and use it in GitHub Desktop.
Save h3ik0th/19ba47965c50e5d4b84e14ba96137c93 to your computer and use it in GitHub Desktop.
MAXLAG = 52
VARmodel1 = VAR(df_TC) # use the time series BEFORE differencing
lags = range(0, MAXLAG)
ic_dict = dict(enumerate(lags))
# fill a dictionary with the information criteria which the VAR model computes at each lag
for L in lags:
res = VARmodel1.fit(L)
ic_dict[L] = [res.aic, res.bic, res.hqic]
# find lag at which the respective information criterion has its minimum:
lag_min_aic = min(ic_dict, key=lambda k: ic_dict[k])
lag_min_bic = min(ic_dict, key=lambda k: ic_dict[k])
lag_min_hqic = min(ic_dict, key=lambda k: ic_dict[k])
# lags at which each of the information critera has its minimum
lag_min = {"aic": lag_min_aic, "bic": lag_min_bic, "hqic": lag_min_hqic}
print(lag_min)
# if the 3 information criteria return different lags, the model will choose the AIC-based lag as the
# relevant result: lag_min_aic
# plot the information criteria
df_ic = pd.DataFrame.from_dict(ic_dict).T
df_ic = df_ic.rename(columns={0:"aic", 1:"bic", 2:"hqic"})
ax = df_ic["aic"].plot(color="blue", label="AIC", legend=True, title="information criteria at VAR model lags", figsize=(20,6))
df_ic["bic"].plot(color="red", label="BIC", style="-", legend=True, ax=ax)
df_ic["hqic"].plot(color="black", label="HQIC", style="-", legend=True, ax=ax)
ax.autoscale(axis="x",tight=True)
ax.set(xlabel="lag", ylabel="")
plt.xticks([x for x in range(1, MAXLAG+1, 1)])
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment