Exemple #1
0
def simple_exponential_smoothing(alpha=0.2):
    df = pd.read_csv('airline_passengers.csv',
                     index_col='Month',
                     parse_dates=True)
    df['EWMA'] = df['Passengers'].ewm(alpha=alpha, adjust=False).mean()
    df.index.freq = 'MS'

    ses = SimpleExpSmoothing(df['Passengers'])
    res = ses.fit(smoothing_level=alpha, optimized=False)
    print(res.predict(start=df.index[0], end=df.index[-1]))

    df['SES'] = res.predict(start=df.index[0], end=df.index[-1])
    df.plot()
    plt.show()

    N_test = 12
    train = df.iloc[:-N_test]
    test = df.iloc[-N_test:]

    ses = SimpleExpSmoothing(train['Passengers'])
    res = ses.fit()

    # Boolean series to index df rows
    train_idx = df.index <= train.index[-1]
    test_idx = df.index > train.index[-1]

    df.loc[train_idx, 'SESfitted'] = res.fittedvalues
    df.loc[test_idx, 'SESfitted'] = res.forecast(N_test)
    df[['Passengers', 'SESfitted']].plot()
    plt.show()

    print(f"The Model parameters: {res.params}")
def model_exp_smooth(data3,train_X,train_y,col_name):
    # create class
    model = SimpleExpSmoothing(data3).fit(smoothing_level=0.3,optimized=False)
    # fit model
    for i in range(5):
        model_fit = model.forecast(1)
        model_fit.columns=[col_name]
        data3=pd.concat([data3,model_fit])
        data3.iloc[-1,0]=data3.iloc[-1,-1]
        data3.drop(data3.columns[-1],inplace=True,axis=1)
        data3.columns=[col_name]
        model = SimpleExpSmoothing(data3).fit(smoothing_level=0.2, optimized=True)
    return model,data3
Exemple #3
0
 def test_simple_exp_smoothing(self):
     fit1 = SimpleExpSmoothing(self.oildata_oil).fit(0.2, optimized=False)
     fit2 = SimpleExpSmoothing(self.oildata_oil).fit(0.6, optimized=False)
     fit3 = SimpleExpSmoothing(self.oildata_oil).fit()
     assert_almost_equal(fit1.forecast(1), [484.802468], 4)
     assert_almost_equal(fit1.level, [
         446.65652290, 448.21987962, 449.7084985, 444.49324656,
         446.84886283, 445.59670028, 441.54386424, 450.26498098,
         461.4216172, 474.49569042, 482.45033014, 484.80246797
     ], 4)
     assert_almost_equal(fit2.forecast(1), [501.837461], 4)
     assert_almost_equal(fit3.forecast(1), [496.493543], 4)
     assert_almost_equal(fit3.params['smoothing_level'], 0.891998, 4)
     # has to be 3 for old python2.7 scipy versions
     assert_almost_equal(fit3.params['initial_level'], 447.478440, 3)
def predict():
    """Compare stats models
    """
    df = pd.read_csv('crime_gr.csv')
    df = df['N_CRIMES']

    train, test = list(df[:-10]), list(df[-10:])

    model = AR(train)
    model_fit = model.fit()

    # make prediction
    prediction = model_fit.predict(len(train), len(train) + 9)
    metric = rmse(test, prediction)
    print('Autoregression', metric)

    model = ARMA(train, order=(0, 1))
    model_fit = model.fit(disp=False)

    # make prediction
    prediction = model_fit.predict(len(train), len(train) + 9)
    metric = rmse(test, prediction)
    print('Moving average', metric)

    model = SimpleExpSmoothing(train)
    model_fit = model.fit()

    # make prediction
    prediction = model_fit.predict(len(train), len(train) + 9)
    metric = rmse(test, prediction)
    print('Exp', metric)
Exemple #5
0
    def predict_throughput(self,
                           horizon,
                           throughput_values,
                           throughput_times=None,
                           method="harmonic"):
        """Take bandwidth history and return predicted future bandwidths."""
        if method == "expsmoothing":
            data = np.array(throughput_values)
            model = SimpleExpSmoothing(data)
            model_fit = model.fit(0.5)
            pred_start = len(throughput_values)
            pred_end = pred_start + horizon - 1
            prediction = model_fit.predict(pred_start, pred_end)
            return prediction

        elif method == "harmonic":
            prediction = []
            for i in range(horizon):
                history_size = len(throughput_values)

                sum_inverse = 0
                for throughput in throughput_values:
                    sum_inverse += 1 / throughput

                tp_prediction = history_size / sum_inverse
                prediction.append(tp_prediction)
                throughput_values.append(tp_prediction)
            return prediction
Exemple #6
0
    def test_holt_damp_fit(self):
        # Smoke test for parameter estimation
        fit1 = SimpleExpSmoothing(self.livestock2_livestock).fit()
        mod4 = Holt(self.livestock2_livestock, damped=True)
        fit4 = mod4.fit(damping_slope=0.98)
        mod5 = Holt(self.livestock2_livestock, exponential=True, damped=True)
        fit5 = mod5.fit()
        # We accept the below values as we getting a better SSE than text book
        assert_almost_equal(fit1.params['smoothing_level'], 1.00, 2)
        assert_almost_equal(fit1.params['smoothing_slope'], np.NaN, 2)
        assert_almost_equal(fit1.params['damping_slope'], np.NaN, 2)
        assert_almost_equal(fit1.params['initial_level'], 263.92, 2)
        assert_almost_equal(fit1.params['initial_slope'], np.NaN, 2)
        assert_almost_equal(fit1.sse, 6761.35, 2)  # 6080.26

        assert_almost_equal(fit4.params['smoothing_level'], 0.98, 2)
        assert_almost_equal(fit4.params['smoothing_slope'], 0.00, 2)
        assert_almost_equal(fit4.params['damping_slope'], 0.98, 2)
        assert_almost_equal(fit4.params['initial_level'], 257.36, 2)
        assert_almost_equal(fit4.params['initial_slope'], 6.64, 2)
        assert_almost_equal(fit4.sse, 6036.56, 2)  # 6080.26

        assert_almost_equal(fit5.params['smoothing_level'], 0.97, 2)
        assert_almost_equal(fit5.params['smoothing_slope'], 0.00, 2)
        assert_almost_equal(fit5.params['damping_slope'], 0.98, 2)
        assert_almost_equal(fit5.params['initial_level'], 258.95, 2)
        assert_almost_equal(fit5.params['initial_slope'], 1.04, 2)
        assert_almost_equal(fit5.sse, 6082.00, 2)  # 6100.11
Exemple #7
0
def test_direct_holt_add():
    mod = SimpleExpSmoothing(housing_data)
    res = mod.fit()
    x = np.squeeze(np.asarray(mod.endog))
    alpha = res.params['smoothing_level']
    l, b, f, err, xhat = _simple_dbl_exp_smoother(x, alpha, beta=0.0,
                                                  l0=res.params['initial_level'], b0=0.0,
                                                  nforecast=5)

    assert_allclose(l, res.level)
    assert_allclose(f, res.level.iloc[-1] * np.ones(5))
    assert_allclose(f, res.forecast(5))

    mod = ExponentialSmoothing(housing_data, trend='add')
    res = mod.fit()
    x = np.squeeze(np.asarray(mod.endog))
    alpha = res.params['smoothing_level']
    beta = res.params['smoothing_slope']
    l, b, f, err, xhat = _simple_dbl_exp_smoother(x, alpha, beta=beta,
                                                  l0=res.params['initial_level'],
                                                  b0=res.params['initial_slope'], nforecast=5)

    assert_allclose(xhat, res.fittedvalues)
    assert_allclose(l + b, res.level + res.slope)
    assert_allclose(l, res.level)
    assert_allclose(b, res.slope)
    assert_allclose(f, res.level.iloc[-1] + res.slope.iloc[-1] * np.array([1, 2, 3, 4, 5]))
    assert_allclose(f, res.forecast(5))
Exemple #8
0
    def holt_winters(self,
                     column,
                     trend=None,
                     damped=False,
                     seasonal=None,
                     seasonal_periods=None,
                     dates=None,
                     freq=None,
                     smoothing_level=None):
        """Holt Winters Model"""

        x = self.df[column].astype(float)
        if trend is None:
            model = SimpleExpSmoothing(x)
            c_name = f'hw_simple_{round(smoothing_level,2)}_{column}'
            fitted_model = model.fit(smoothing_level=smoothing_level,
                                     optimized=True)

        else:
            model = ExponentialSmoothing(x,
                                         trend=trend,
                                         damped=damped,
                                         seasonal=seasonal,
                                         seasonal_periods=seasonal_periods,
                                         dates=dates,
                                         freq=freq)
            c_name = f'hw_exp_{trend}'
            if seasonal is not None:
                c_name += f'_{seasonal}'
            if seasonal_periods is not None:
                c_name += f'_{seasonal_periods}'
            c_name += f'_{column}'
            fitted_model = model.fit(smoothing_level=smoothing_level)

        self.df[c_name] = fitted_model.fittedvalues
    def get_predictions_rmse_mape_final(self, min_algo):
        if min_algo == Constants.ARIMA:
            model = ARIMA(self.total, order=(7, 0, 1))
            model_fit = model.fit()
        elif min_algo == Constants.MOVING_AVERAGE:
            model = ARMA(self.total, order=[0, 1])
            model_fit = model.fit(disp=0)
        elif min_algo == Constants.AR:
            model = AR(self.total)
            model_fit = model.fit(disp=0)
        elif min_algo == Constants.ARMA:
            # model = ARMA(self.total, order=[1,0])
            model = ARMA(self.total, order=[2, 1])
            model_fit = model.fit(disp=0)
        elif min_algo == Constants.SARIMA:
            model = SARIMAX(self.total,
                            order=(1, 1, 1),
                            seasonal_order=(1, 1, 1, 12))
            model_fit = model.fit(disp=0)
        elif min_algo == Constants.SES:
            model = SimpleExpSmoothing(self.total)
            model_fit = model.fit()

        start_index = len(self.total)
        # end_index = start_index + 11
        end_index = start_index + Constants.NUMBER_OF_PREDICTIONS - 1
        forecast = model_fit.predict(start=start_index, end=end_index)
        for i in range(0, len(forecast)):
            forecast[i] = round(forecast[i])
            if forecast[i] < 0:
                forecast[i] = 0
        return forecast
Exemple #10
0
	def smoothing(self):
		alist = [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9]
		rmse_list = []
		for alpha in alist:
			savg = [self.df['x'][0]]
			savgm = SimpleExpSmoothing(self.df)
			savgfit = savgm.fit(alpha,optimized=False)
			savg = savgfit.fittedvalues
			#print(savg)
			mse = mean_squared_error(self.df['x'], savg)
			rmse = sqrt(mse)
			rmse_list.append(rmse)
		#print(rmse_list)
		best_a = alist[np.argmin(rmse_list)]  ##get index of the minimum mean to obtain best alpha value
		min_rmse = np.min(rmse_list)   ##get minimum of root mean square value
		print("Best Min RMSE,Alpha using fit:",min_rmse,best_a)


		##Ploting RMSE against K values
		plt.plot(alist,rmse_list)
		plt.title('RMSE vs alpha')
		plt.xlabel('a')
		plt.ylabel('RMSE')
		plt.savefig('./rmse_a')
		plt.clf()
		return best_a,min_rmse
def Croston_HW(crop_data, market, time_to_predict, date):
    marketData = marketChoice(crop_data, market)  # nan rows are made
    marketData = croston_prep(marketData, market)
    marketData["Modal"] = pd.to_numeric(marketData["Modal"])
    crostonData = Croston(marketData["Modal"], extra_periods=1, alpha=0.4)
    for ind in crostonData.index:
        if crostonData["Demand"][ind] == 0:
            crostonData["Demand"][ind] = crostonData["Forecast"][ind]
    crostonData = crostonData["Demand"]
    trial = marketChoice(crop_data, market)
    trial = trial[trial['Date'] == date]
    start_date = trial.index[0]
    train_data, test_data = split_test_train(crostonData, time_to_predict,
                                             start_date)
    #   print("train_data: ", train_data)
    #   print("\n")
    #   print("test_data: ", test_data)
    test_data = test_data[0:len(test_data) - 1]
    #   fit1 = ExponentialSmoothing(train_data,
    #                             seasonal_periods=rand,
    #                             trend='multiplicative',
    #                             seasonal='mul',
    #                             damped=True).fit(use_boxcox=True)
    fit1 = SimpleExpSmoothing(train_data).fit(use_boxcox=True)
    frame = fit1.forecast(int(time_to_predict))
    pred = pd.DataFrame
    pred = frame
    res = list(pred[0:int(time_to_predict)])
    return res, test_data
Exemple #12
0
def single_exponential_smoothing(alpha, y_test):
    # Accounts only for the level of the series

    # Simple Exponential Smoothing
    ses_model1 = SimpleExpSmoothing(y_test).fit(smoothing_level=alpha,
                                                optimized=True)
    y_pred_ses = ses_model1.predict(31924).rename(
        r'$\alpha=%s$' % ses_model1.model.params['smoothing_level'])

    fig = plt.figure(figsize=(60, 8))
    y_pred_ses[31925:].plot(color='grey', legend=True)
    ses_model1.fittedvalues.plot(color='grey')
    plt.title("Single Exponential Smoothing")
    plt.show()
    fig.savefig('results/SES/final_output.jpg', bbox_inches='tight')

    # print("Predicted values: ", y_pred, "\n")
    mse_ses = mean_squared_error(y_test[31923:-1], y_pred_ses)
    rmse_ses = mean_squared_error(y_pred_ses, y_test[31923:-1], squared=False)
    r2_ses = r2_score(y_test[31923:-1], y_pred_ses)

    # Storing the result in a file: 'load_forecasting_result.txt'
    predicted_test_result = y_pred_ses
    np.savetxt('results/SES/predicted_values.txt', predicted_test_result)
    actual_test_result = y_test
    np.savetxt('results/SES/test_values.txt', actual_test_result)

    return mse_ses, rmse_ses, r2_ses, y_pred_ses
Exemple #13
0
def get_forecast(df, month, country="ALL"): 

    df_ts = df.copy() if country=="ALL" else df[df['country']==country].copy()
    if len(df_ts) <= 180: 
        return None
    
    actual = df_ts[df_ts['inv_month'] == month.isoformat()]['value'].sum()

    df_ts = df_ts[['inv_month', 'inv_date', 'value']].groupby(['inv_month', 'inv_date']).sum().reset_index()
    
    df_train = df_ts[df_ts['inv_month'] < month.isoformat()]
    df_train['inv_date'] = pd.to_datetime(df_train['inv_date'])
    df_train.rename(columns={'inv_date':'ds', 'value':'y'}, inplace=True)

    m = Prophet(yearly_seasonality=20)
    m.fit(df_train)
    future = m.make_future_dataframe(periods=60, freq='D')
    df_forecast = m.predict(future)
    df_forecast['inv_month'] = df_forecast['ds'].apply(lambda v: date(v.year, v.month, 1).isoformat())
    forecast = df_forecast[df_forecast['inv_month'] == month.isoformat()]['yhat'].sum()

    exp_model = SimpleExpSmoothing(df_ts[['inv_month', 'inv_date', 'value']].set_index(['inv_month', 'inv_date'])).fit(smoothing_level=0.2, optimized=False)
    exp_forecast = forecast_df = sum(exp_model.forecast(30))
    
    return actual, forecast, exp_forecast
def Ses(data):
    inter_df = data[['Volume']]
    size = np.sum(data['Date'] <= '12/31/2018')
    train, test = inter_df.iloc[:size, 0], inter_df.iloc[size:, 0]
    model = SimpleExpSmoothing(train).fit()
    pred = model.predict(start=test.index[0], end=test.index[-1])
    return pred
Exemple #15
0
def calc_ses(
    train_set: pd.DataFrame,
    test_set: pd.DataFrame,
    dataframe: pd.DataFrame,
    series_name: str,
    pred_dict: dict,
    errors_dict: dict,
) -> dict:
    """Calculate using SES model based on given training and test sets, on given Pandas DataFrame
    and series name. Results are stored into provided dicts with predictions and errors."""
    yhat = list()
    for t in tqdm(range(len(test_set[series_name]))):
        temp_train = dataframe[:len(train_set) + t]
        model = SimpleExpSmoothing(temp_train[series_name])
        model_fit = model.fit()
        predictions = model_fit.predict(start=len(temp_train),
                                        end=len(temp_train))
        yhat = yhat + [predictions]

    hypothesis = pd.concat(yhat)
    pred_dict["SES"] = hypothesis
    actuals = test_set[series_name]
    errors_dict = EvaluationUtil.evaluate_error("SES", hypothesis, actuals,
                                                errors_dict)
    return errors_dict
Exemple #16
0
def ses(train, test, alpha=0.0):

    if (alpha > 0.0):
        model = SimpleExpSmoothing(train).fit(smoothing_level=alpha,
                                              optimized=False)
        _alpha = '{0:2.1f}'.format(alpha)
    else:
        model = SimpleExpSmoothing(train).fit()
        _alpha = model.model.params['smoothing_level']

    pred = model.predict(start=test.index[0], end=test.index[-1])

    plt.plot(train.index, train, label='Train')
    plt.plot(test.index, test, label='Test')
    plt.plot(pred.index, pred, label=r'SES, $\alpha={0}$'.format(_alpha))
    plt.legend(loc='best')
 def __prepare_collective_anomalies(self, smoothing_level=0.01) -> None:
     """Constructs model to generate collective anomalies
     :param smoothing_level: parameter for SimpleExpSmoothing
     """
     self.collective_anomalies_models = {}
     for column in self.data_columns:
         self.collective_anomalies_models[column] = SimpleExpSmoothing(self.dataframe[column]) \
             .fit(smoothing_level=smoothing_level, optimized=False)
Exemple #18
0
 def execute(self, dataset: Dataset) -> Dataset:
     model = SimpleExpSmoothing(dataset.train.passengers)
     model_fit = model.fit()
     y_predict = model_fit.forecast(len(dataset.predict))
     return dataset.update(
         predict=dataset.predict.assign(passengers=y_predict.values),
         label=self.name,
     )
def model_SimpleExpSmoothing(time_series, span):
    """
    reference: Hyndman, Rob J., and George Athanasopoulos. Forecasting: principles and practice. OTexts, 2014.
    """
    alpha = 2 / (span + 1)
    model = SimpleExpSmoothing(time_series).fit(smoothing_level=alpha,
                                                optimized=False)
    return model
Exemple #20
0
def simple_exponential_smoothing(column):
    length = len(column)
    model = SimpleExpSmoothing(column)
    try:
        forecast = list(model.fit().predict(length, length))[0]
    except:
        forecast = '-'
    return forecast
Exemple #21
0
 def update(self):
     begin = max(0,self.index-self.window)
     data = self.arrivals[begin:self.index]
     # fit model
     model = SimpleExpSmoothing(data)
     model_fit = model.fit()
     self.model = model_fit
     # make prediction
     self.prediction = model_fit.predict(len(data), len(data))[0]
Exemple #22
0
def predict_simple_exponential_smoothing(data,
                                         predict_start=None,
                                         intervals=15):
    model = SimpleExpSmoothing(data, initialization_method='estimated')
    model_fit = model.fit()

    if predict_start is None:
        predict_start = len(data) - 2

    return model_fit.predict(predict_start, predict_start + intervals)
 def update(self):
     begin = max(0, self.index - self.window)
     data = self.arrivals[begin:self.index]
     # fit model
     model = SimpleExpSmoothing(data)
     model_fit = model.fit()
     self.model = model_fit
     self.smoothedValues.append(self.model.params['smoothing_level'])
     # make prediction
     self.prediction = model_fit.predict(len(data), len(data))[0]
Exemple #24
0
def SES(df, category, time_range, column):
    from statsmodels.tsa.holtwinters import SimpleExpSmoothing
    new_df = pd.DataFrame()
    for u in df[category].unique():
        df2 = df[df[category] == u]
        df2 = df2.reset_index(drop=True)
        DoF = np.max(df[time_range])+1 - np.min(df[time_range])
        if df2.isna().sum()[column] == DoF:
            df2[column] = df[column].dropna().mean()
        while df2.isna().sum()[column] > 0: 
            data = df2[column].tolist()
            for n, nxt in zip (data, data[1:]):
                if np.isnan(n) == False and np.isnan(nxt) == True:
                    data_list = list()
                    for m in data[:data.index(nxt)]:
                        if np.isnan(m) == False:
                            data_list.append(m)
                    if len(data_list) < 2:
                        df2[column][data.index(nxt)] = n
                    else:
                        model = SimpleExpSmoothing(data_list)
                        model_fit = model.fit()
                        #obtain predicted value
                        yhat = model_fit.forecast()
                        df2[column][data.index(nxt)] = yhat
            data = df2[column].tolist()[::-1]
            for n, nxt in zip (data, data[1:] ):
                if np.isnan(n) == False and np.isnan(nxt) == True:
                    datalist = data[:data.index(nxt)]
                    data_list = list()
                    for m in datalist:
                        if np.isnan(m) == False:
                            data_list.append(m)
                    if len(data_list) < 2:
                        df2[column][len(data) - 1 - data.index(nxt)] = n
                    else:
                        model = SimpleExpSmoothing(data_list)
                        model_fit = model.fit()
                        #obtain predicted value
                        yhat = model_fit.forecast()
                        df2[column][len(data) - 1 - data.index(nxt)] = yhat
        new_df = new_df.append(df2)
    return new_df
 def exp_moving_average_forecast(self):
     parameters = [0.1, 0.2, 0.6]
     self.create_fig_with_data()
     for p in parameters:
         fit1 = SimpleExpSmoothing(self.data_of_shares.Average).fit(
             smoothing_level=p, optimized=False)
         y_hat = fit1.fittedvalues
         plt.plot(y_hat[0:self.amount_of_test_data],
                  label=f'Simple exp smoothing level={p}')
     plt.legend(loc='best')
     plt.savefig("static/results/exp_moving_forecast")
Exemple #26
0
 def fit_ts_univariate_model(self, x, model_type = 'SimpleExpSmoothing'):
     if model_type == 'ExponentialSmoothing':
         model = ExponentialSmoothing(x)
         model_fit = model.fit()
     elif model_type == 'ARIMA':
         model = ARIMA(x, order=(1, 1, 1))
         model_fit = model.fit(disp=False)
     else:
         model = SimpleExpSmoothing(x)
         model_fit = model.fit()
     self.models[model_type] = model_fit
Exemple #27
0
def CC_CLS_CL(Dataframe, HNAME_List, Raceday):

    """
    Horse's Competition Level
    Parameter
    ---------
    Matchday : Matchday Dataframe
    HNAME_List : String of List of Horse Names
    Raceday : Date of Race
    Return
    ------
    Dataframe [HNAME, CC_CLS_CL]
    """

    Feature_DF = Dataframe.loc[:,['HNAME','HJRAT']]

    Horse_Comp = []
    #For each horse, get data for last 5 races
    for Horse in Dataframe['HNAME'].tolist():
        Extraction = Extraction_Database("""
                                         Select HNAME, RARID, HJRAT, RESFP from RaceDb
                                         where RARID in (
                                         Select RARID from RaceDb
                                         where RADAT < {Raceday} and HNAME = {Horse}
                                         ORDER BY RARID DESC
                                         LIMIT 5)
                                         """.format(Raceday = Raceday, Horse = "'" + Horse + "'"))

        for RARID, race in Extraction.groupby('RARID'):
            Horse_Rat = race.loc[race.loc[:,'HNAME']==Horse,'HJRAT'].to_list()[0]
            Horse_FP = race.loc[race.loc[:,'HNAME']==Horse,'RESFP'].to_list()[0]
            Comp_Rat = race.nlargest(3, 'HJRAT').loc[:,'HJRAT'].mean()
            Comp_Level = (Comp_Rat - Horse_Rat) / Horse_FP
            Horse_Comp.append([Horse,Comp_Level])
    Horse_Comp = pd.DataFrame(Horse_Comp, columns=['HNAME', 'Comp_Level'])

    #Recency Weighting
    Comp = []
    for name, group in Horse_Comp.groupby('HNAME'):
        Comp_Figure = group.loc[:,'Comp_Level'].dropna().values
        try :
            model = SimpleExpSmoothing(Comp_Figure)
            model = model.fit()
            Comp.append([name, model.forecast()[0]])
        except :
            Comp.append([name,Comp_Figure[0]])
    Comp = pd.DataFrame(Comp, columns=['HNAME','CC_CLS_CL'])

    Feature_DF = Feature_DF.merge(Comp, how='left')
    Feature_DF.loc[:, 'CC_CLS_CL'].fillna(Feature_DF.loc[:, 'CC_CLS_CL'].min(), inplace = True)
    Feature_DF.loc[:, 'CC_CLS_CL'].fillna(0, inplace=True)
    Feature_DF = Feature_DF.loc[:, ['HNAME', 'CC_CLS_CL']]

    return Feature_DF
Exemple #28
0
def forecasting(*, metrics: List, timeframe: int) -> List:
    '''Estimate forecasting for Lambda container demand'''
    data = [float(val) for val in metrics.values()]

    model = SimpleExpSmoothing(endog=data)
    fitted_model = model.fit(**EXP_SMOOTH_PARAMS)

    forecasts = fitted_model.predict(
        start=len(data),
        end=len(data) + timeframe - 1,
    )

    return [math.ceil(val) for val in forecasts]
def forecast_plots(data):
    fig = plt.figure(figsize=(12.8, 9.6), dpi=250)
    ax = fig.add_subplot(1, 1, 1)

    offset = 500

    data.index = pd.to_datetime(data.index, utc=True)
    train = data.iloc[100 + offset:200 + offset]
    train.index = pd.to_datetime(train.index)
    test = data.iloc[200 + offset:210 + offset]
    test.index = pd.to_datetime(test.index)

    model = SimpleExpSmoothing(np.asarray(train['total load actual']))
    model._index = pd.to_datetime(train.index)

    colours = ["orange", "green"]

    # Fit and plot two SES models, with alpha = 0.2, 0.4
    for i in range(1, 3):
        fit = model.fit(smoothing_level=str(0.2 * i))
        pred = fit.forecast(9)
        ax.plot(train.index,
                fit.fittedvalues,
                label=u'\u03B1' + " = " + str(0.1 * i),
                color=colours[i - 1])
        ax.plot(test.index, pred, color=colours[i - 1])

    # Fit and plot the optimal SES model - statsmodels finds the optimal alpha
    optimised_fit = model.fit(optimized=True)
    optimised_pred = optimised_fit.forecast(9)
    ax.plot(train.index,
            optimised_fit.fittedvalues,
            label=u'\u03B1' + " = " +
            str(optimised_fit.params['smoothing_level'])[:3],
            color="darkkhaki")
    ax.plot(test.index, optimised_pred, color="darkkhaki")

    # Plot the training and test values
    ax.plot(train.index,
            train['total load actual'],
            label="Training Data",
            marker="o")
    ax.plot(test.index,
            test['total load actual'],
            color="grey",
            marker="o",
            label="Test Data")

    # Add legend and show plot
    ax.legend(loc="best")
    plt.show()
Exemple #30
0
def update_graph(selected_dropdown):
    df = values["Gold"]

    trace1 = []
    trace1.append(
        go.Scatter(x=values.date,
                   y=df,
                   mode='lines',
                   opacity=0.6,
                   name='Actual values',
                   textposition='bottom center'))

    if selected_dropdown != None:
        for alpha in selected_dropdown:
            model = SimpleExpSmoothing(np.asarray(df))
            fit = model.fit(smoothing_level=alpha)
            result = fit.fittedvalues

            name = 'Exponential Smoothing ' + '{0:.2f}'.format(alpha)
            trace1.append(
                go.Scatter(x=values.date,
                           y=result,
                           mode='lines',
                           opacity=0.6,
                           name=name,
                           textposition='bottom center'))

    title = ""
    traces = [trace1]
    data = [val for sublist in traces for val in sublist]
    figure = {
        'data':
        data,
        'layout':
        go.Layout(colorway=[
            "#5E0DAC", '#FF4F00', '#375CB1', '#FF7400', '#FFF400', '#FF0056'
        ],
                  height=600,
                  title=title,
                  xaxis={
                      "title": "Date",
                      'rangeslider': {
                          'visible': True
                      },
                  },
                  yaxis={"title": "Price (USD)"},
                  paper_bgcolor='rgba(0,0,0,0)',
                  plot_bgcolor='rgba(0,0,0,0)')
    }

    return figure