Search code examples
pythontime-seriestrend

Detect a given pattern in time series


How an I detect this type of change in a time series in python?click here to see image

Thanks for your help


Solution

  • There are many ways to do this. I will show one of the fastest and simplest way. It is based on using correlation.

    First of all we need a data(time series) and template(in our case the template is like a signum function):

    data = np.concatenate([np.random.rand(70),np.random.rand(30)+2])
    template = np.concatenate([[-1]*5,[1]*5])
    

    Before detection I strongly recommend normalize the data(for example like that):

    data = (data - data.mean())/data.std()
    

    And now all we need is use of correlation function:

    corr_res = np.correlate(data, template,mode='same')
    

    You need to choose the threshold for results(you should define that value based on your template):

    th = 9
    

    You can see the results:

    plt.figure(figsize=(10,5))
    plt.subplot(211)
    plt.plot(data)
    plt.subplot(212)
    plt.plot(corr_res)
    plt.plot(np.arange(len(corr_res))[corr_res > th],corr_res[corr_res > th],'ro')
    plt.show()
    

    result