from statsmodels.tsa.statespace.sarimax import SARIMAX
import pandas as pd
import itertools
import warnings
import numpy as np
import statsmodels.api as sm
try:
print(“Starting script…”)
# Load your dataset
print("Loading dataset...")
df = pd.read_csv('C:/Users/iameh/Downloads/archive/powerconsumption.csv')
# Convert 'Datetime' to datetime and set it as the index
print("Preprocessing data...")
df['Datetime'] = pd.to_datetime(df['Datetime'])
df.set_index('Datetime', inplace=True)
# Define the p, d, q parameters to take any value between 0 and 1
p = d = q = range(0, 2)
# Generate all different combinations of p, q and q triplets
pdq = list(itertools.product(p, d, q))
# Generate all different combinations of seasonal p, q and q triplets
seasonal_pdq = [(x[0], x[1], x[2], 12) for x in list(itertools.product(p, d, q))]
# Specify to ignore warning messages
warnings.filterwarnings("ignore")
# List of parameters to forecast
parameters = ['Temperature', 'Humidity', 'WindSpeed', 'GeneralDiffuseFlows', 'DiffuseFlows', 'PowerConsumption_Zone1', 'PowerConsumption_Zone2', 'PowerConsumption_Zone3']
print("Starting forecasting for each parameter...")
for parameter in parameters:
print(f"Forecasting for {parameter}...")
# Select the relevant column for forecasting
endog = df[parameter]
# Find the best parameters for the model
best_aic = np.inf
best_pdq = None
best_seasonal_pdq = None
temp_model = None
print("Finding best model parameters...")
for param in pdq:
for param_seasonal in seasonal_pdq:
try:
temp_model = SARIMAX(endog,
order = param,
seasonal_order = param_seasonal,
enforce_stationarity=False,
enforce_invertibility=False)
results = temp_model.fit()
# print("SARIMAX{}x{}12 - AIC:{}".format(param, param_seasonal, results.aic))
if results.aic < best_aic:
best_aic = results.aic
best_pdq = param
best_seasonal_pdq = param_seasonal
except:
continue
print("Best SARIMAX{}x{}12 model for {} - AIC:{}".format(best_pdq, best_seasonal_pdq, parameter, best_aic))
# Fit the best model
print("Fitting the best model...")
model = SARIMAX(endog,
order=best_pdq,
seasonal_order=best_seasonal_pdq,
enforce_stationarity=False,
enforce_invertibility=False)
results = model.fit()
# Get forecast steps ahead in future
print("Making forecasts...")
pred_uc = results.get_forecast(steps=52416)
# Write the DataFrame to a CSV file
print("Saving forecasts to CSV file...")
pred_uc.predicted_mean.to_csv(f'C:/Users/iameh/Downloads/archive/{parameter}_forecast.csv')
print(f"Forecasting for {parameter} completed!")
print("Script completed!")
except Exception as e:
print(“An error occurred during the execution of the script:”)
print(e)
I am using this code to generate the next years prediction. But it is crashing/shell is restarting