Question

What's the best way to check if a sequence of numbers has an increasing or decreasing trend?

I know that I could pick the first and last value of the sequence, and check their difference, but I'd like a somewhat more robust check. This means that I want to be able to tolerate a minority of increasing values within a mostly decreasing sequence, and viceversa.

More specifically, the numbers are stored as

vector<int> mySequence;

A few more details about the number sequences that I am dealing with:

  • All the numbers within the sequence have the same order of magnitude. This means that no sequence like the following can appear: [45 38 320 22 12 6].
  • By descending trend I mean that most or all the numbers within the sequence are lesser than the previous one. (The opposite applies for ascending trend). As a consequence, the following sequence is to be considered as descending: [45 42 38 32 28 34 26 20 12 8 48]
Was it helpful?

Solution

I would accumulate the number of increases vs number of decreases, which should give you an idea of whether there's an overall trend to increase or decrease.

OTHER TIPS

You probably could look into trend estimation and some type of regression like linear regression.

It depends of course on the specific application of yours, but in general it sounds like a fitting problem.

I think you can simply calculate the median of your sequence and check if it is greater than the first value.
This is ONE way, not THE way.

Another way, always considering average medium, you can check the number of ascending and descending values in the sequence.

int trend = 0;
int avg = mySequence[0]; 
int size = mySequence.size();
for (int i=0; i < size - 1; ++i) {
  if(i > 0) { 
   avg = (avg + mySequence[i]) / 2; 
  }
  (mySequence[i+1] - avg) > 0 ? ++trend; --trend;    
}

One possibility would be to count the number of ascending and descending values in the sequence:

int trend = 0;
for (int i=0;i<mySequence.size()-1;++i)
{
    diff = mySequence[i+1] - mySequence[i];
    if (diff > 0)
    {
       trend++;
    }
    else if (diff < 0)
    {
       trend--;
    }
}

The sequence you give in example will end with trend equal to -6

I would most probably try to split the sequence into multiple segments, as you said the values do not differ dramatically - see piecewise regression and to interpret the segments as your business needs.

You will need a vector for storing the segments, each segment having start/end index, some sort of median value, etc - see also where to split a piecewise regression

I suggest using methods from mathematical analysis (e.g. integral and differential calculus) applied to discrete integer sequences.

One way is then to compute rolling averages and see if those averages increase or decrease. Natural and easy ;)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top