Created
January 4, 2020 23:37
-
-
Save kperry2215/90c1b16fdcb370757f6283d1c60a58f1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def seasonal_arima_model(time_series, order, seasonal_order, trend): | |
""" | |
Generate a seasonal ARIMA model using a set of hyperparameters. Returns the model fit, and the | |
associated model AIC and BIC values. | |
""" | |
try: | |
model = sm_api.tsa.SARIMAX(time_series, | |
order=order, | |
seasonal_order=seasonal_order, | |
trend = trend, | |
enforce_stationarity=False, | |
enforce_invertibility=False) | |
model_fit = model.fit() | |
#Print the model results | |
print(model_fit.summary()) | |
return model_fit, model_fit.aic, model_fit.bic | |
except: | |
print("Could not fit with the designated model parameters") | |
return None, None, None | |
### EXECUTE IN MAIN FUNCTION ### | |
lowest_aic_val = 100000000000 | |
#Generate model for each of hyperparameter combination in a loop | |
for order_combo in order_combos: | |
for seasonal_order_combo in seasonal_order_combos: | |
#Convert the combination to list format | |
seasonal_order_combo = list(seasonal_order_combo) | |
#Generate the SARIMA model | |
model_fit, model_aic, model_bic = seasonal_arima_model(time_series = training_set, | |
order = order_combo, | |
seasonal_order = seasonal_order_combo[0:4], | |
trend = seasonal_order_combo[-1]) | |
#Test model performance, and keep running tab of best performing model | |
#Set with the newest value if the lowest_aic_value hasn't yet been calculated (on first run), | |
#or if the newly calculated model AIC is lower than the lowest calculated AIC value | |
if (model_aic < lowest_aic_val): | |
lowest_aic_val = model_aic | |
best_model = model_fit | |
best_order = order_combo | |
best_seasonal_order = seasonal_order_combo | |
#Print the best model parameters after the | |
print("Best model paramaters: order-- ", best_order, ", seasonal order-- ", best_seasonal_order) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment