signaflo / java-timeseries

Time series analysis in Java
MIT License
195 stars 49 forks source link

Positive time series value predictions #10

Closed rathnaviraj closed 6 years ago

rathnaviraj commented 6 years ago

Hi Is there any way to restrict prediction values for positive values. Because the time series that I'm working can have only positive values. But the ARIMA model time series forecast gives me negative values some times.

signaflo commented 6 years ago

rathnaviraj,

I found this: https://stats.stackexchange.com/questions/80859/how-to-achieve-strictly-positive-forecasts

I think the most obvious option is to take the logarithm before modeling and forecasting.

As of now, this needs to be done somewhat manually. You can do this by creating a time series from your values and then calling the transform function with argument equal to 0.0. This does a Box-Cox transformation, and the Box-Cox transformation at 0.0 is identical to taking the logarithm.

The downside: You have to manually back transform the point estimates and prediction intervals. For example,

import com.github.signaflo.data.Range;

double[] x = Range.inclusiveRange(50, 1).asArray(); // Trending towards zero.
Distribution d = new Normal();

for (int i = 0; i < x.length; i++) x[i] += d.rand(); // Add a little noise.

TimeSeries ts = TimeSeries.from(x).transform(0);
ArimaOrder order = ArimaOrder.order(0, 2, 0);

Model model = Arima.model(ts, order);
Forecast forecast = model.forecast(10);

// Now the annoying part where we need to manually back transform.
TimeSeries point = forecast.pointEstimates().backTransform(0);
TimeSeries lower = forecast.lowerPredictionInterval().backTransform(0);
TimeSeries upper = forecast.upperPredictionInterval().backTransform(0);

// Note that the prediction intervals for this example may look very unrealistic 
// since we fed a very clear signal with only a little bit of noise.

A future enhancement that can come from this issue is the option to specify the transformation as an argument to the modeling method, just as is done in the R forecast package. This way the forecasts can be automatically back-transformed and all you will have to is remember to set the transform parameter to 0.

rathnaviraj commented 6 years ago

This is interesting.

Then I can manage this by manually applying the transformation for now. Hope there will be an enhancement for this library in future which we can specify the transformation through an argument pass.

Thanks.

signaflo commented 6 years ago

Thanks for bringing it up @rathnaviraj. This is something that we should add as a top priority to the main development line. It's an extremely common use case (people also do it to help stabilize the variance), and thankfully not too difficult to implement.

signaflo commented 6 years ago

@rathnaviraj, added issue #11