Advertisement
Guest User

Untitled

a guest
Aug 18th, 2019
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. #Set initial values and some bounds
  2. ps = range(0, 5)
  3. d = 1
  4. qs = range(0, 5)
  5. Ps = range(0, 5)
  6. D = 1
  7. Qs = range(0, 5)
  8. s = 5
  9.  
  10. #Create a list with all possible combinations of parameters
  11. parameters = product(ps, qs, Ps, Qs)
  12. parameters_list = list(parameters)
  13. len(parameters_list)
  14.  
  15. # Train many SARIMA models to find the best set of parameters
  16. def optimize_SARIMA(parameters_list, d, D, s):
  17. """
  18. Return dataframe with parameters and corresponding AIC
  19.  
  20. parameters_list - list with (p, q, P, Q) tuples
  21. d - integration order
  22. D - seasonal integration order
  23. s - length of season
  24. """
  25.  
  26. results = []
  27. best_aic = float('inf')
  28.  
  29. for param in tqdm_notebook(parameters_list):
  30. try: model = sm.tsa.statespace.SARIMAX(data.CLOSE, order=(param[0], d, param[1]),
  31. seasonal_order=(param[2], D, param[3], s)).fit(disp=-1)
  32. except:
  33. continue
  34.  
  35. aic = model.aic
  36.  
  37. #Save best model, AIC and parameters
  38. if aic < best_aic:
  39. best_model = model
  40. best_aic = aic
  41. best_param = param
  42. results.append([param, model.aic])
  43.  
  44. result_table = pd.DataFrame(results)
  45. result_table.columns = ['parameters', 'aic']
  46. #Sort in ascending order, lower AIC is better
  47. result_table = result_table.sort_values(by='aic', ascending=True).reset_index(drop=True)
  48.  
  49. return result_table
  50.  
  51. result_table = optimize_SARIMA(parameters_list, d, D, s)
  52.  
  53. #Set parameters that give the lowest AIC (Akaike Information Criteria)
  54. p, q, P, Q = result_table.parameters[0]
  55.  
  56. best_model = sm.tsa.statespace.SARIMAX(data.CLOSE, order=(p, d, q),
  57. seasonal_order=(P, D, Q, s)).fit(disp=-1)
  58.  
  59. print(best_model.summary())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement