Skip to content

Instantly share code, notes, and snippets.

@himangSharatun
Created February 19, 2018 04:07
Show Gist options
  • Save himangSharatun/f7f468bfaf80f6f889e7b6e68f289d50 to your computer and use it in GitHub Desktop.
Save himangSharatun/f7f468bfaf80f6f889e7b6e68f289d50 to your computer and use it in GitHub Desktop.
from pandas import read_csv
from pandas import datetime
from matplotlib import pyplot
from statsmodels.tsa.arima_model import ARIMA
from sklearn.metrics import mean_squared_error
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf
file_path = "minyak-goreng-prices.csv"
# Parse the date into pandas.datetime
def parser(x):
splited = x.split('-')
return datetime.strptime(splited[0] + "-" + splited[1] + "-20" +splited[2], '%d-%b-%Y')
# Read and parse the csv file
series = read_csv(file_path, header=0, parse_dates=[0], index_col=0, squeeze=True, date_parser=parser)
X = series.values
# Split data for trainin and test 971 is number of data from previous year before 2015
size = int(971)
train, test = X[0:size], X[size:len(X)]
history = [x for x in train]
# Predictions loop for each data in 2015
predictions = list()
for t in range(len(test)):
# ARIMA hyperparameter configurations
model = ARIMA(history, order=(0,1,1))
# Train the model
model_fit = model.fit(disp=0)
# Forecast
output = model_fit.forecast()
yhat = output[0]
predictions.append(yhat)
obs = test[t]
history.append(obs)
print('predicted=%f, expected=%f' % (yhat, obs))
# Error calculation by using MSE
error = mean_squared_error(test, predictions)
print('Test MSE: %.3f' % error)
# Plot the result
pyplot.plot(test)
pyplot.plot(predictions, color='red')
pyplot.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment