Example #1
0
 def run_auto_arima(self, y, **kwargs):
     print(kwargs)
     return auto_arima(
         y,
         seasonal=True,
         trace=True,
         error_action=
         'ignore',  # don't want to know if an order does not work
         suppress_warnings=True,  # don't want convergence warnings
         stepwise=True,  # set to stepwise
         **kwargs)
def train_arima(X: pd.DataFrame, y: pd.Series, config: Config):
    df = pd.Series(data=y.values, index=X["time_series_lag"]).sort_index()
    exog = X.sort_values(
        "time_series_lag")["is_working_datetime_0"].values.reshape(-1, 1)
    config["model_arima"] = pm.auto_arima(
        df,  # exogenous=exog,
        max_p=3,
        max_q=3,
        m=7,
        seasonal=True,
        error_action='ignore',
        suppress_warnings=True,
    )
Example #3
0
def autoarima_method(s, pre_len, season_period):
    stepwise_fit = pm.auto_arima(
        np.asarray(s),
        start_p=1,
        start_q=1,
        max_p=3,
        max_q=3,
        m=season_period,
        start_P=0,
        seasonal=True,
        d=1,
        D=1,
        trace=True,
        error_action='ignore',  # don't want to know if an order does not work
        suppress_warnings=True,  # don't want convergence warnings
        stepwise=True)

    return stepwise_fit.predict(pre_len)
def autoARIMA(inputDataSet, n):
    inputData = inputDataSet.astype(np.float64)
    stepwise_fit = pm.auto_arima(
        inputData,
        start_p=1,
        start_q=1,
        max_p=3,
        max_q=3,
        m=12,
        start_P=0,
        seasonal=True,
        d=1,
        D=1,
        trace=True,
        error_action='ignore',  # don't want to know if an order does not work
        suppress_warnings=True,  # don't want convergence warnings
        stepwise=True)  # set to stepwise
    return stepwise_fit.predict(n)
def ARIMA_pred(data, forc_data):

    listp = forc_data.values

    stepwise_model = auto_arima(data,
                                start_p=1,
                                start_q=1,
                                max_p=3,
                                max_q=3,
                                start_P=0,
                                start_Q=0,
                                max_P=3,
                                max_Q=3,
                                error_action='ignore',
                                suppress_warnings=True,
                                stepwise=True)
    stepwise_model.fit(data)
    pr = stepwise_model.predict(n_periods=100)

    plt.plot(listp, color='red', label='Real Stock Price')
    plt.plot(pr, color='blue', label='Predicted Stock Price')
    plt.title(' Stock Price Prediction using ARIMA')
    plt.xlabel('Time')
    plt.ylabel('Stock Price')
    plt.legend()
    plt.show()
    print("For ARIMA The mean squared error is:")
    print(mean_squared_error(listp, pr))
    print("For ARIMA The R squared error is:")
    print(r2_score(listp, pr))
    plt.style.use('fivethirtyeight')
    plt.scatter(data,
                data - stepwise_model.predict_in_sample(data),
                color="green",
                s=10,
                label='Train data')
    plt.scatter(listp, listp - pr, color="blue", s=10, label='Test data')
    plt.hlines(y=0, xmin=0, xmax=250, linewidth=2)
    plt.legend(loc='upper right')
    plt.title("Residual errors for ARIMA")
    plt.show()
Example #6
0
def a_arima(timeseries):
    
    stepwise_model = auto_arima(timeseries, start_p=1, start_q=1,
                               max_p=3, max_q=3, m=12,
                               start_P=0, seasonal=True,
                               d=1, D=1, trace=True,
                               error_action='ignore',  
                               suppress_warnings=True, 
                               stepwise=True)
    #print(stepwise_model.aic())

    #df['Year'] = pd.to_datetime(df['Year'])
    train = df.loc['2009-06-02 00:00:00':'2017-12-31 00:00:00']
    test = df.loc['2018-01-01 00:00:00':]
    
    # Train the Model
    stepwise_model.fit(train)

    future_forecast = stepwise_model.predict(n_periods=182)
    future_forecast = pd.DataFrame(future_forecast, index = test.index, column=['Prediction'])
    pd.concat([test,future_forecast],axis=1).iplot()
plt.xlabel('time')
plt.ylabel('passengers')
plt.plot()

train = df[:int(0.8 * (len(df)))]
test = df[int(0.8 * (len(df))):]
print(train.shape)
print(test.shape)

model = auto_arima(train,
                   trace=True,
                   start_q=0,
                   start_p=0,
                   start_Q=0,
                   max_p=10,
                   max_q=10,
                   max_P=10,
                   max_Q=10,
                   seasonal=True,
                   stepwise=False,
                   suppress_warnings=True,
                   D=1,
                   max_D=10,
                   error_action='ignore',
                   approximation=False)
mode.fit(train)

y_pred = model.predict(n_periods=len(valid))
from sklearn.metrics import r2_score
acc = r2_score(valid.values, y_pred)
print(acc)
Example #8
0
result.plot()
plt.show()

# Lowess Filter also does not provide the expected results
# Using ARIMA Model to predict the time series analysis
# it is not always needed to have the HP and lowess filter analysis, but it was necessary in this case to use them
# WTI ARIMA
print(clear)

stepwise_model_wti = auto_arima(wti_train['WTI'],
                                start_p=1,
                                start_q=1,
                                max_p=3,
                                max_q=3,
                                m=12,
                                start_P=0,
                                seasonal=True,
                                d=1,
                                D=1,
                                trace=True,
                                error_action='ignore',
                                suppress_warnings=True,
                                stepwise=True)
print('WTI AIC')
print(stepwise_model_wti.aic())

print("Training the model on our datasets")
stepwise_model_wti.fit(wti_train['WTI'])

print("Forecasting WTI for next 13 periods")
future_forecast_wti = stepwise_model_wti.predict(n_periods=13)
dts = [
Example #9
0
# -*- coding: utf-8 -*-
# @Time    : 20/3/14 0:19
# @Author  : Jay Lam
# @File    : test.py
# @Software: PyCharm


import numpy as np
import pandas as pd
import warnings
warnings.simplefilter(action='ignore', category=(FutureWarning,UserWarning))
import pyramid as pm
from pyramid.datasets import load_wineind

# this is a dataset from R
wineind = pd.read_csv('pg43.csv').astype(np.float64)
#wineind =wineind = load_wineind().astype(np.float64)


# fit stepwise auto-ARIMA
stepwise_fit = pm.auto_arima(wineind, start_p=1, start_q=1,
                             max_p=3, max_q=3, m=12,
                             start_P=0, seasonal=True,
                             d=1, D=1, trace=True,
                             error_action='ignore',  # don't want to know if an order does not work
                             suppress_warnings=True,  # don't want convergence warnings
                             stepwise=True)  # set to stepwise


#print(stepwise_fit.summary())
print(type(stepwise_fit.predict(3)))
Example #10
0
   <br/>
"""
print(__doc__)

# Author: Taylor Smith <*****@*****.**>

import pyramid as pm
import numpy as np
from matplotlib import pyplot as plt

# #############################################################################
# Load the data and split it into separate pieces
data = pm.datasets.load_wineind()
train, test = data[:150], data[150:]

# Fit a simple auto_arima model
arima = pm.auto_arima(train,
                      error_action='ignore',
                      trace=1,
                      seasonal=True,
                      m=12)

# #############################################################################
# Plot actual test vs. forecasts:
x = np.arange(test.shape[0])
plt.scatter(x, test, marker='x')
plt.plot(x, arima.predict(n_periods=test.shape[0]))
plt.title('Actual test samples vs. forecasts')
plt.show()
#divide into train and validation set
#2344 - 2000-01-01
#2487 - 2011-12-01
#2488 - 2012-01-01
#2507 - 2013-08-01
#train = dataset.loc[2344:2487:][:int(1*(len(dataset.loc[2344:2487:])))]
#test = dataset.loc[2488:2507:][int(1*(len(dataset.loc[2488:2507:]))):]
train = dataset.loc[2344:2487, :]
test = dataset.loc[2488:, :]

#-----------------------------------------------------------------------------------------------------------------

#building the model
from pyramid import auto_arima
model = auto_arima(train['Avg_Temp'],
                   trace=True,
                   error_action='ignore',
                   suppress_warnings=True)

#-------------------------------------------------------------------------------------------------------

forecast = model.predict(n_periods=len(test['Avg_Temp']))
forecast = pd.DataFrame(forecast,
                        index=test['Avg_Temp'].index,
                        columns=['Prediction'])
forecast.head()

#---------------------------------------------------------------------------------------------------

#PREDICT FROM 2013-Sept to 2014-Aug
forecastTest = model.predict(n_periods=24)
forecastTest = pd.DataFrame(forecastTest, columns=['PredictionUntilThisMonth'])