Skip to content

[ARMA] Prediction always begins at zero value #3269

Closed

Description

@k0pernicus

edit: This issue has two parts, one usage question, and one bug in name handling

  • usage: When working with a differenced series, then we have to be careful about the distinction between prediction of differences/growth and prediction in levels
  • bug: name handling is not robust if the data is not a pandas.Series with a simple string name

Using the code below, I canno't predict out-sample (for 45 days) because my prediction begins at zero every time...

For example, using this code:

arma_order = arma_order_select_ic(endog_products, ic=['aic', 'bic', 'hqic'], trend='c', fit_kw=dict(method='css-mle'))
# Select p and q
p = arma_order.aic_min_order[0]
q = arma_order.aic_min_order[1]

# Fit the model
arma_model = ARMA(endog_products, freq='D', order=(p, q))
arma_res = arma_model.fit(method="css-mle", trend='c', transparams=True) 

# Get the dates
learning_date = str(current_products.index[LEARNING_DAYS])[:10]
max_date = str(current_products.index[STUDIED_PERIOD - 1])[:10]

prediction_values = arma_res.predict(start=learning_date, end=max_date)

sum_current_products = current_products[:STUDIED_PERIOD].cumsum()
sum_prediction_products = prediction_values.cumsum()
            
sum_current_products.plot(figsize=(13, 8), label=('Real Sales %s' % product))
_ax = sum_prediction_products.plot(color='r', label='Dynamic Prediction')
_ax.axvline(x=learning_date, linewidth=1, color='k', linestyle='--')
_ax.legend()
plt.show()

I obtain this prediction (in red):

out_sample

Using prediction in sample with this code (I just changed LEARNING_DAYS to PRELEARNING_DAYS, which PRELEARNING_DAYS corresponds to the beginning of the learning phasis):

arma_order = arma_order_select_ic(endog_products, ic=['aic', 'bic', 'hqic'], trend='c', fit_kw=dict(method='css-mle'))
# Select p and q
p = arma_order.aic_min_order[0]
q = arma_order.aic_min_order[1]

# Fit the model
arma_model = ARMA(endog_products, freq='D', order=(p, q))
arma_res = arma_model.fit(method="css-mle", trend='c', transparams=True) 

# Get the dates -> Change LEARNING_DAYS to PRELEARNING_DAYS
learning_date = str(current_products.index[PRELEARNING_DAYS])[:10]
max_date = str(current_products.index[STUDIED_PERIOD - 1])[:10]

prediction_values = arma_res.predict(start=learning_date, end=max_date)

sum_current_products = current_products[:STUDIED_PERIOD].cumsum()
sum_prediction_products = prediction_values.cumsum()
            
sum_current_products.plot(figsize=(13, 8), label=('Real Sales %s' % product))
_ax = sum_prediction_products.plot(color='r', label='Dynamic Prediction')
_ax.axvline(x=learning_date, linewidth=1, color='k', linestyle='--')
_ax.legend()
plt.show()

I obtain this better result, but it still begins at 0 at the beginning of the prediction (in red too):

in_sample

or for example this:

in_sample_2

or (best example) this:

in_sample_3

Is there any mistake in my code?
Also, I don't understand why my prediction begins ALLWAYS at zero et became linear predicting out sample values...

Thanks a lot!

Activity

  1. changed the title [-][ARMA] Prediction always begins at zero[/-] [+][ARMA] Prediction always begins at zero value[/+] on Nov 14, 2016
  2. josef-pkt commented on Nov 14, 2016

    @josef-pkt
    Member

    to the first part: prediction starting at zero
    This might be (partially) your doing if you predict the growth/change and use cusum, i.e. the changes start at zero (if the first period is the last observed period, or something like that). Maybe you need to add the starting level to your prediction. Also, check the original prediction to see whether that looks ok.
    You could compare with ARIMA(p, 1, q) with predict(..., typ='level') which does the integration of the differenced series.

    to dynamic or longterm prediction:
    If you cusum a change with mean > 0, then the long run prediction will be just a linear trend. In forecasting with a short ARMA, the prediction converges relatively fast to the mean.
    Your last three plots all show a change in the trend that is not properly captured by the estimation of the constant/mean in the differenced series. Imagine a linear trend in the training sample and extrapolate. That is the main long term prediction. The dynamics will float around this. (The trend is stochastic, so there could be quite a large fluctuation around the trend, but it doesn't look so large in your cases. The main point is that the trend will start at the last observation, with some short run fluctuations initially from the short run dynamics)

  3. k0pernicus commented on Nov 14, 2016

    @k0pernicus
    Author

    Thanks again @josef-pkt for your answer.
    Indeed, there is a problem when I compare my code with ARIMA(p, 1, q).
    Using this code:

    arma_order = arma_order_select_ic(endog_products, ic=['aic', 'bic', 'hqic'], trend='c', fit_kw=dict(method='css-mle'))
    p = arma_order.aic_min_order[0]
    q = arma_order.aic_min_order[1]
    arma_model = ARIMA(endog_products, freq='D', order=(p, 1, q))
    

    I have this traceback error:

    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    <ipython-input-6-fb542402cc0e> in <module>()
         54         print(endog_products)
         55 
    ---> 56         arma_model = ARIMA(endog_products, freq='D', order=(p, 1, q))
         57         arma_res = arma_model.fit(method="css-mle", trend='c', transparams=True)
         58 
    
    /usr/local/lib/python3.5/dist-packages/statsmodels/tsa/arima_model.py in __new__(cls, endog, order, exog, dates, freq, missing)
        963         else:
        964             mod = super(ARIMA, cls).__new__(cls)
    --> 965             mod.__init__(endog, order, exog, dates, freq, missing)
        966             return mod
        967 
    
    /usr/local/lib/python3.5/dist-packages/statsmodels/tsa/arima_model.py in __init__(self, endog, order, exog, dates, freq, missing)
        982             self.exog = self.exog[d:]
        983         if d == 1:
    --> 984             self.data.ynames = 'D.' + self.endog_names
        985         else:
        986             self.data.ynames = 'D{0:d}.'.format(d) + self.endog_names
    
    TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('<U21') dtype('<U21') dtype('<U21')
    

    I checked values of endog_products and the type is dtype: float64...
    This error is raised when a type error has been found, no?

    Also, is the starting level is to set the parameter start_params in statsmodels.tsa.arima_model.ARMA.fit?

  4. josef-pkt commented on Nov 14, 2016

    @josef-pkt
    Member

    the TypeError is related to self.endog_names which should be string or unicode, so that plus is string concatenation. It looks like self.endog_names is some numpy object that doesn't do string concatenation.

    start_params are always the initial values for the parameters (lag coefficients and constant) for the nonlinear optimization. They are not related to initial observation for the conditional methods.

    I don't know if the string/unicode problem is still present or if it is a version incompatibility with the old statsmodels. In the former case we would have to make this more robust.

    BTW: which python version do you use?

  5. k0pernicus commented on Nov 14, 2016

    @k0pernicus
    Author

    Okay... But, my numpy object is just an array of float indexed with date, the same structure I give to fit the ARMA model... :-/
    Currently, I am using Python 3.5.2, with those versions:

    numpy==1.11.2
    pandas==0.19.1
    pytz==2016.7
    scipy==0.18.1
    statsmodels==0.6.1
    
  6. josef-pkt commented on Nov 14, 2016

    @josef-pkt
    Member

    AFAIK without checking, endog_names should be the variable name of endog, not the index or datetimes, i.e. the name of your endog_products pandas Series if defined or a made up generic name.

  7. k0pernicus commented on Nov 14, 2016

    @k0pernicus
    Author

    Okay - thanks a lot!

  8. added this to the 0.9 milestone on Oct 9, 2017
  9. self-assigned this
    on Jul 23, 2019
  10. bashtage commented on Jul 23, 2019

    @bashtage
    Member

    Closing as answered.

  11. modified the milestones: 0.9, 0.11 on Dec 18, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions