How can I detect if trend is increasing or decreasing in time series?

Kanika Singhal picture Kanika Singhal · Apr 12, 2019 · Viewed 13.2k times · Source

I have few weeks data with units sold given

xs[weeks] = [1,2,3,4]
ys['Units Sold'] = [1043,6582,5452,7571]

from the given series, we can see that although there is a drop from xs[2] to xs[3] but overall the trend is increasing. How to detect the trend in small time series dataset.

Is finding a slope for the line is the best way? And how to calculate slope angle of a line in python?

Answer

Majo_Jose picture Majo_Jose · Apr 12, 2019

I have gone through the same issue that you face today. In order to detect the trend, I couldn't find a specific function to handle the situation.

I found a really helpful function ie, numpy.polyfit():

numpy.polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False) 
                                                    

[Check this Official Documentation]

You can use the function like this

def trenddetector(list_of_index, array_of_data, order=1):
    result = np.polyfit(list_of_index, list(array_of_data), order)
    slope = result[-2]
    return float(slope)

This function returns a float value that indicates the trend of your data and also you can analyze it by something like this.

For example,

if the slope is a +ve value --> increasing trend

if the slope is a -ve value --> decreasing trend

if the slope is a zero value --> No trend

Play with this function and find out the correct threshold as per your problem and give it as a condition.

Example Code for your Solution

import numpy as np
def trendline(index,data, order=1):
    coeffs = np.polyfit(index, list(data), order)
    slope = coeffs[-2]
    return float(slope)

index=[1,2,3,4]
List=[1043,6582,5452,7571]
resultent=trendline(index,List)
print(resultent)  

RESULT

1845.3999999999999

As per this output, The result is much greater than zero so it shows your data is increasing steadily.