<jupyter_start><jupyter_text>Clase 4 - [FBI NICS Firearm Background Check Data](https://github.com/BuzzFeedNews/nics-firearm-background-checks)- [Forecasting Book](https://otexts.com/fpp2/)  ARIMA<jupyter_code>import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
sns.set(rc={'figure.figsize': (12,8)})
df = pd.read_csv('data/firearms.csv', parse_dates=['month'])
df.head()
total = df[['totals', 'month']].groupby('month').sum();
total.head()
total = total.drop(total.iloc[[0]].index)
total['totals'].plot();
import statsmodels.api as sm
fig, (ax1, ax2) = plt.subplots(2)
sm.graphics.tsa.plot_acf(total['totals'], ax=ax1)
sm.graphics.tsa.plot_pacf(total['totals'], ax=ax2);
total['diferencias'] = total.pct_change()
diferencias = total[['diferencias']].dropna()
diferencias.plot();
fig, (ax1, ax2) = plt.subplots(2)
sm.graphics.tsa.plot_acf(diferencias, ax=ax1)
sm.graphics.tsa.plot_pacf(diferencias.dropna(), ax=ax2);
# Código adaptado de https://www.quantstart.com/articles/Basics-of-Statistical-Mean-Reversion-Testing
def hurst(ts):
    lags = range(2, 100)
    tau = [np.sqrt(np.std(np.subtract(ts[lag:], ts[:-lag]))) for lag in lags]
    poly = np.polyfit(np.log(lags), np.log(tau), 1)

    return poly[0] * 2.0
hurst(total['totals'].values)
hurst(diferencias.values)
stl_decomposition = sm.tsa.STL(total['totals'], period=12)
res = stl_decomposition.fit()
res.plot();
import pmdarima as pm
from sklearn.model_selection import train_test_split
train, test = train_test_split(total['totals'].values, train_size=0.9, shuffle=False)

model = pm.auto_arima(train, seasonal=True, m=12, suppress_warnings=True)
model.summary()
forecasts = model.predict(len(test))  # predict N steps into the future
x = np.arange(total['totals'].shape[0])
plt.plot(total['totals'].index, total['totals'], c='blue', label = 'Datos')
plt.plot(total['totals'].index[len(train):], forecasts, c='red', label = 'Predicción')
plt.legend();
import pyflux as pf
residuos = model.resid()
model_garch = pf.GARCH(residuos,1,1)
x = model_garch.fit()
x.summary()
model_garch.plot_predict(h=10)
model_garch.plot_predict_is(h=50,figsize=(15,5))<jupyter_output><empty_output><jupyter_text>Facebook Prophet<jupyter_code>from fbprophet import Prophet
train_df = total[:len(train)]
test_df = total[len(train):]
data = pd.DataFrame({'ds': train_df.index, 'y': train_df['totals']})

prophet_model = Prophet()
#prophet_model.add_seasonality(name='annual', period=12, fourier_order=5)
prophet_model.fit(data);
future = prophet_model.make_future_dataframe(freq='M', periods=len(test))
prophet_forecast = prophet_model.predict(future)
prophet_model.plot_components(prophet_forecast)
ax = sns.lineplot(x=total.index, y=total['totals'], label='Firearm checks')
sns.lineplot(y=prophet_forecast['yhat'], x=prophet_forecast['ds'], label='Prophet forecast', ax=ax)
ax.set_xlabel('Fecha')
ax.set_ylabel('Checks')
ax.set_title('Firearm checks');<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.17555705604321403, 'fraction_numerical': 0.01451721809588116, 'mean_word_length': 7.58840579710145, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 3, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '583931', 'license': 'MIT', 'n_tokens_mistral': 1181, 'n_tokens_neox': 1141, 'n_words': 187, 'path': 'clases/clase_4/clase_4_ARIMA.ipynb', 'repo_name': 'lambdaclass/data_etudes', 'size': '2962'}