Anomaly Detector

The Anomaly Detection service detects anomalies automatically in time series data. It supports several functionalities, one is for detecting the whole series with model trained by the time series, another is detecting the last point with model trained by points before. With this service, business customers can discover incidents and establish a logic flow for root cause analysis. We also provide change point detection, which is another common scenario on time series analysis and service monitoring. Change point detection targets to discover tend changes in the time series. To ensure online service quality is one of the main reasons we developed this service. Our team is dedicated to continuing to improve the anomaly detection service to provide precise results.

Detect anomaly status of the latest point in time series.

This operation generates a model using points before the latest one. With this method, only historical points are used to determine whether the target point is an anomaly. The latest point detecting matches the scenario of real-time monitoring of business metrics.

Select the testing console in the region where you created your resource:

Open API testing console

Request URL

Request headers

string
Media type of the body sent to the API.
string
Subscription key which provides access to this API. Found in your Cognitive Services accounts.

Request body

Time series points and period if needed. Advanced model parameters can also be set in the request.

{
  "series": [
    {
      "timestamp": "1972-01-01T00:00:00Z",
      "value": 826
    },
    {
      "timestamp": "1972-02-01T00:00:00Z",
      "value": 799
    },
    {
      "timestamp": "1972-03-01T00:00:00Z",
      "value": 890
    },
    {
      "timestamp": "1972-04-01T00:00:00Z",
      "value": 900
    },
    {
      "timestamp": "1972-05-01T00:00:00Z",
      "value": 961
    },
    {
      "timestamp": "1972-06-01T00:00:00Z",
      "value": 935
    },
    {
      "timestamp": "1972-07-01T00:00:00Z",
      "value": 894
    },
    {
      "timestamp": "1972-08-01T00:00:00Z",
      "value": 855
    },
    {
      "timestamp": "1972-09-01T00:00:00Z",
      "value": 809
    },
    {
      "timestamp": "1972-10-01T00:00:00Z",
      "value": 810
    },
    {
      "timestamp": "1972-11-01T00:00:00Z",
      "value": 766
    },
    {
      "timestamp": "1972-12-01T00:00:00Z",
      "value": 805
    },
    {
      "timestamp": "1973-01-01T00:00:00Z",
      "value": 821
    },
    {
      "timestamp": "1973-02-01T00:00:00Z",
      "value": 773
    },
    {
      "timestamp": "1973-03-01T00:00:00Z",
      "value": 883
    },
    {
      "timestamp": "1973-04-01T00:00:00Z",
      "value": 898
    },
    {
      "timestamp": "1973-05-01T00:00:00Z",
      "value": 957
    },
    {
      "timestamp": "1973-06-01T00:00:00Z",
      "value": 924
    },
    {
      "timestamp": "1973-07-01T00:00:00Z",
      "value": 881
    },
    {
      "timestamp": "1973-08-01T00:00:00Z",
      "value": 837
    },
    {
      "timestamp": "1973-09-01T00:00:00Z",
      "value": 784
    },
    {
      "timestamp": "1973-10-01T00:00:00Z",
      "value": 791
    },
    {
      "timestamp": "1973-11-01T00:00:00Z",
      "value": 760
    },
    {
      "timestamp": "1973-12-01T00:00:00Z",
      "value": 802
    },
    {
      "timestamp": "1974-01-01T00:00:00Z",
      "value": 828
    },
    {
      "timestamp": "1974-02-01T00:00:00Z",
      "value": 1030
    },
    {
      "timestamp": "1974-03-01T00:00:00Z",
      "value": 889
    },
    {
      "timestamp": "1974-04-01T00:00:00Z",
      "value": 902
    },
    {
      "timestamp": "1974-05-01T00:00:00Z",
      "value": 969
    },
    {
      "timestamp": "1974-06-01T00:00:00Z",
      "value": 947
    },
    {
      "timestamp": "1974-07-01T00:00:00Z",
      "value": 908
    },
    {
      "timestamp": "1974-08-01T00:00:00Z",
      "value": 867
    },
    {
      "timestamp": "1974-09-01T00:00:00Z",
      "value": 815
    },
    {
      "timestamp": "1974-10-01T00:00:00Z",
      "value": 812
    },
    {
      "timestamp": "1974-11-01T00:00:00Z",
      "value": 773
    },
    {
      "timestamp": "1974-12-01T00:00:00Z",
      "value": 813
    },
    {
      "timestamp": "1975-01-01T00:00:00Z",
      "value": 834
    },
    {
      "timestamp": "1975-02-01T00:00:00Z",
      "value": 782
    },
    {
      "timestamp": "1975-03-01T00:00:00Z",
      "value": 892
    },
    {
      "timestamp": "1975-04-01T00:00:00Z",
      "value": 903
    },
    {
      "timestamp": "1975-05-01T00:00:00Z",
      "value": 966
    },
    {
      "timestamp": "1975-06-01T00:00:00Z",
      "value": 937
    },
    {
      "timestamp": "1975-07-01T00:00:00Z",
      "value": 896
    },
    {
      "timestamp": "1975-08-01T00:00:00Z",
      "value": 858
    },
    {
      "timestamp": "1975-09-01T00:00:00Z",
      "value": 817
    },
    {
      "timestamp": "1975-10-01T00:00:00Z",
      "value": 827
    },
    {
      "timestamp": "1975-11-01T00:00:00Z",
      "value": 797
    },
    {
      "timestamp": "1975-12-01T00:00:00Z",
      "value": 843
    }
  ],
  "maxAnomalyRatio": 0.25,
  "sensitivity": 95,
  "granularity": "monthly"
}
{
  "type": "object",
  "required": [
    "granularity",
    "series"
  ],
  "properties": {
    "series": {
      "type": "array",
      "description": "Time series data points. Points should be sorted by timestamp in ascending order to match the anomaly detection result. If the data is not sorted correctly or there is duplicated timestamp, the API will not work. In such case, an error message will be returned.",
      "items": {
        "type": "object",
        "required": [
          "timestamp",
          "value"
        ],
        "properties": {
          "timestamp": {
            "type": "string",
            "format": "date-time",
            "example": "1972-01-01T00:00:00Z",
            "description": "Timestamp of a data point (ISO8601 format)."
          },
          "value": {
            "type": "number",
            "format": "float",
            "example": 826.0,
            "description": "The measurement of that point, should be float."
          }
        }
      }
    },
    "granularity": {
      "type": "string",
      "example": "daily",
      "description": "Can only be one of yearly, monthly, weekly, daily, hourly, minutely or secondly. Granularity is used for verify whether input series is valid."
    },
    "customInterval": {
      "type": "integer",
      "example": 5,
      "description": "Custom Interval is used to set non-standard time interval, for example, if the series is 5 minutes, request can be set as {\"granularity\":\"minutely\", \"customInterval\":5}."
    },
    "period": {
      "type": "integer",
      "format": "int32",
      "example": 7,
      "description": "Optional argument, periodic value of a time series. If the value is null or does not present, the API will determine the period automatically."
    },
    "maxAnomalyRatio": {
      "type": "number",
      "format": "float",
      "example": 0.25,
      "description": "Optional argument, advanced model parameter, max anomaly ratio in a time series."
    },
    "sensitivity": {
      "type": "number",
      "format": "integer",
      "example": 95,
      "description": "Optional argument, advanced model parameter, between 0-99, the lower the value is, the larger the margin value will be which means less anomalies will be accepted"
    }
  },
  "example": {
    "series": [
      {
        "timestamp": "1972-01-01T00:00:00Z",
        "value": 826
      },
      {
        "timestamp": "1972-02-01T00:00:00Z",
        "value": 799
      },
      {
        "timestamp": "1972-03-01T00:00:00Z",
        "value": 890
      },
      {
        "timestamp": "1972-04-01T00:00:00Z",
        "value": 900
      },
      {
        "timestamp": "1972-05-01T00:00:00Z",
        "value": 961
      },
      {
        "timestamp": "1972-06-01T00:00:00Z",
        "value": 935
      },
      {
        "timestamp": "1972-07-01T00:00:00Z",
        "value": 894
      },
      {
        "timestamp": "1972-08-01T00:00:00Z",
        "value": 855
      },
      {
        "timestamp": "1972-09-01T00:00:00Z",
        "value": 809
      },
      {
        "timestamp": "1972-10-01T00:00:00Z",
        "value": 810
      },
      {
        "timestamp": "1972-11-01T00:00:00Z",
        "value": 766
      },
      {
        "timestamp": "1972-12-01T00:00:00Z",
        "value": 805
      },
      {
        "timestamp": "1973-01-01T00:00:00Z",
        "value": 821
      },
      {
        "timestamp": "1973-02-01T00:00:00Z",
        "value": 773
      },
      {
        "timestamp": "1973-03-01T00:00:00Z",
        "value": 883
      },
      {
        "timestamp": "1973-04-01T00:00:00Z",
        "value": 898
      },
      {
        "timestamp": "1973-05-01T00:00:00Z",
        "value": 957
      },
      {
        "timestamp": "1973-06-01T00:00:00Z",
        "value": 924
      },
      {
        "timestamp": "1973-07-01T00:00:00Z",
        "value": 881
      },
      {
        "timestamp": "1973-08-01T00:00:00Z",
        "value": 837
      },
      {
        "timestamp": "1973-09-01T00:00:00Z",
        "value": 784
      },
      {
        "timestamp": "1973-10-01T00:00:00Z",
        "value": 791
      },
      {
        "timestamp": "1973-11-01T00:00:00Z",
        "value": 760
      },
      {
        "timestamp": "1973-12-01T00:00:00Z",
        "value": 802
      },
      {
        "timestamp": "1974-01-01T00:00:00Z",
        "value": 828
      },
      {
        "timestamp": "1974-02-01T00:00:00Z",
        "value": 1030
      },
      {
        "timestamp": "1974-03-01T00:00:00Z",
        "value": 889
      },
      {
        "timestamp": "1974-04-01T00:00:00Z",
        "value": 902
      },
      {
        "timestamp": "1974-05-01T00:00:00Z",
        "value": 969
      },
      {
        "timestamp": "1974-06-01T00:00:00Z",
        "value": 947
      },
      {
        "timestamp": "1974-07-01T00:00:00Z",
        "value": 908
      },
      {
        "timestamp": "1974-08-01T00:00:00Z",
        "value": 867
      },
      {
        "timestamp": "1974-09-01T00:00:00Z",
        "value": 815
      },
      {
        "timestamp": "1974-10-01T00:00:00Z",
        "value": 812
      },
      {
        "timestamp": "1974-11-01T00:00:00Z",
        "value": 773
      },
      {
        "timestamp": "1974-12-01T00:00:00Z",
        "value": 813
      },
      {
        "timestamp": "1975-01-01T00:00:00Z",
        "value": 834
      },
      {
        "timestamp": "1975-02-01T00:00:00Z",
        "value": 782
      },
      {
        "timestamp": "1975-03-01T00:00:00Z",
        "value": 892
      },
      {
        "timestamp": "1975-04-01T00:00:00Z",
        "value": 903
      },
      {
        "timestamp": "1975-05-01T00:00:00Z",
        "value": 966
      },
      {
        "timestamp": "1975-06-01T00:00:00Z",
        "value": 937
      },
      {
        "timestamp": "1975-07-01T00:00:00Z",
        "value": 896
      },
      {
        "timestamp": "1975-08-01T00:00:00Z",
        "value": 858
      },
      {
        "timestamp": "1975-09-01T00:00:00Z",
        "value": 817
      },
      {
        "timestamp": "1975-10-01T00:00:00Z",
        "value": 827
      },
      {
        "timestamp": "1975-11-01T00:00:00Z",
        "value": 797
      },
      {
        "timestamp": "1975-12-01T00:00:00Z",
        "value": 843
      }
    ],
    "maxAnomalyRatio": 0.25,
    "sensitivity": 95,
    "granularity": "monthly"
  }
}

Response 200

Successful operation.

{
  "isAnomaly": false,
  "isPositiveAnomaly": false,
  "isNegativeAnomaly": false,
  "period": 12,
  "expectedValue": 809.2328084659704,
  "upperMargin": 40.46164042329852,
  "lowerMargin": 40.46164042329852,
  "suggestedWindow": 49
}
{
  "type": "object",
  "properties": {
    "period": {
      "type": "integer",
      "format": "int32",
      "example": 12,
      "description": "Frequency extracted from the series, zero means no recurrent pattern has been found."
    },
    "suggestedWindow": {
      "type": "integer",
      "format": "int32",
      "example": 49,
      "description": "Suggested input series points needed for detecting the latest point."
    },
    "expectedValue": {
      "type": "number",
      "format": "float",
      "example": 809.2328,
      "description": "Expected value of the latest point."
    },
    "upperMargin": {
      "type": "number",
      "format": "float",
      "example": 40.46164,
      "description": "Upper margin of the latest point. UpperMargin is used to calculate upperBoundary, which equals to expectedValue + (100 - marginScale)*upperMargin. If the value of latest point is between upperBoundary and lowerBoundary, it should be treated as normal value. By adjusting marginScale value, anomaly status of latest point can be changed."
    },
    "lowerMargin": {
      "type": "number",
      "format": "float",
      "example": 40.46164,
      "description": "Lower margin of the latest point. LowerMargin is used to calculate lowerBoundary, which equals to expectedValue - (100 - marginScale)*lowerMargin. "
    },
    "isAnomaly": {
      "type": "boolean",
      "example": false,
      "description": "Anomaly status of the latest point, true means the latest point is an anomaly either in negative direction or positive direction."
    },
    "isNegativeAnomaly": {
      "type": "boolean",
      "example": false,
      "description": "Anomaly status in negative direction of the latest point. True means the latest point is an anomaly and its real value is smaller than the expected one."
    },
    "isPositiveAnomaly": {
      "type": "boolean",
      "example": false,
      "description": "Anomaly status in positive direction of the latest point. True means the latest point is an anomaly and its real value is larger than the expected one."
    }
  },
  "example": {
    "suggestedWindow": 49,
    "isNegativeAnomaly": false,
    "lowerMargin": 40.46164,
    "isPositiveAnomaly": false,
    "period": 12,
    "expectedValue": 809.2328,
    "isAnomaly": false,
    "upperMargin": 40.46164
  }
}

Response 400

Possible Errors:

  • BadArgument
    Invalid json format, input data is Empty.
    The 'series' field is required in request.
    The 'granularity' field is required in request.
    The 'series' field cannot be empty.
    The 'series' field must be array/list type.
    'timestamp' or 'value' is malformed in 'series' Field.
    The 'series' field cannot have none values.
  • InvalidCustomInterval
    The 'customInterval' field must be an integer > 0.
  • InvalidGranularity
    The 'granularity' field can only be one of the following: ['daily', 'minutely', 'hourly', 'weekly', 'monthly', 'yearly', 'secondly'].
  • InvalidPeriod
    The 'period' field must be an integer >= 0.
  • InvalidModelArgument
    The 'maxAnomalyRatio' field must be less than 50% of the series points (0 < maxAnomalyRatio < 0.5).
    The 'sensitivity' field must be an integer between 0 and 99.
    The 'series' field must have more than 2 periods points.
  • InvalidSeries
    The 'series' field must be sorted by timestamp in ascending order.
    The 'series' field cannot have duplicated timestamp.
    Time points should be uniformly spaced in time in minutely granularity with 1 gran as interval, ratio of missing points should be less than 10%.
    The 'series' field must have at least 12 points.
    The 'series' field cannot have more than 8640 points.

{
  "code" : "InvalidSeries",
  "message" : "The 'series' field cannot have duplicated timestamp."
}

Response 403

The certificate you provided is not accepted by server.

Response 405

Method Not Allowed.

Response 500

Internal Server Error.

Code samples

@ECHO OFF

curl -v -X POST "https://*.cognitiveservices.azure.us/anomalydetector/v1.0/timeseries/last/detect"
-H "Content-Type: application/json"
-H "Ocp-Apim-Subscription-Key: {subscription key}"

--data-ascii "{body}" 
using System;
using System.Net.Http.Headers;
using System.Text;
using System.Net.Http;
using System.Web;

namespace CSHttpClientSample
{
    static class Program
    {
        static void Main()
        {
            MakeRequest();
            Console.WriteLine("Hit ENTER to exit...");
            Console.ReadLine();
        }
        
        static async void MakeRequest()
        {
            var client = new HttpClient();
            var queryString = HttpUtility.ParseQueryString(string.Empty);

            // Request headers
            client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "{subscription key}");

            var uri = "https://*.cognitiveservices.azure.us/anomalydetector/v1.0/timeseries/last/detect?" + queryString;

            HttpResponseMessage response;

            // Request body
            byte[] byteData = Encoding.UTF8.GetBytes("{body}");

            using (var content = new ByteArrayContent(byteData))
            {
               content.Headers.ContentType = new MediaTypeHeaderValue("< your content type, i.e. application/json >");
               response = await client.PostAsync(uri, content);
            }

        }
    }
}	
// // This sample uses the Apache HTTP client from HTTP Components (http://hc.apache.org/httpcomponents-client-ga/)
import java.net.URI;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class JavaSample 
{
    public static void main(String[] args) 
    {
        HttpClient httpclient = HttpClients.createDefault();

        try
        {
            URIBuilder builder = new URIBuilder("https://*.cognitiveservices.azure.us/anomalydetector/v1.0/timeseries/last/detect");


            URI uri = builder.build();
            HttpPost request = new HttpPost(uri);
            request.setHeader("Content-Type", "application/json");
            request.setHeader("Ocp-Apim-Subscription-Key", "{subscription key}");


            // Request body
            StringEntity reqEntity = new StringEntity("{body}");
            request.setEntity(reqEntity);

            HttpResponse response = httpclient.execute(request);
            HttpEntity entity = response.getEntity();

            if (entity != null) 
            {
                System.out.println(EntityUtils.toString(entity));
            }
        }
        catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
    }
}

<!DOCTYPE html>
<html>
<head>
    <title>JSSample</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>

<script type="text/javascript">
    $(function() {
        var params = {
            // Request parameters
        };
      
        $.ajax({
            url: "https://*.cognitiveservices.azure.us/anomalydetector/v1.0/timeseries/last/detect?" + $.param(params),
            beforeSend: function(xhrObj){
                // Request headers
                xhrObj.setRequestHeader("Content-Type","application/json");
                xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","{subscription key}");
            },
            type: "POST",
            // Request body
            data: "{body}",
        })
        .done(function(data) {
            alert("success");
        })
        .fail(function() {
            alert("error");
        });
    });
</script>
</body>
</html>
#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    
    NSString* path = @"https://*.cognitiveservices.azure.us/anomalydetector/v1.0/timeseries/last/detect";
    NSArray* array = @[
                         // Request parameters
                         @"entities=true",
                      ];
    
    NSString* string = [array componentsJoinedByString:@"&"];
    path = [path stringByAppendingFormat:@"?%@", string];

    NSLog(@"%@", path);

    NSMutableURLRequest* _request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:path]];
    [_request setHTTPMethod:@"POST"];
    // Request headers
    [_request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [_request setValue:@"{subscription key}" forHTTPHeaderField:@"Ocp-Apim-Subscription-Key"];
    // Request body
    [_request setHTTPBody:[@"{body}" dataUsingEncoding:NSUTF8StringEncoding]];
    
    NSURLResponse *response = nil;
    NSError *error = nil;
    NSData* _connectionData = [NSURLConnection sendSynchronousRequest:_request returningResponse:&response error:&error];

    if (nil != error)
    {
        NSLog(@"Error: %@", error);
    }
    else
    {
        NSError* error = nil;
        NSMutableDictionary* json = nil;
        NSString* dataString = [[NSString alloc] initWithData:_connectionData encoding:NSUTF8StringEncoding];
        NSLog(@"%@", dataString);
        
        if (nil != _connectionData)
        {
            json = [NSJSONSerialization JSONObjectWithData:_connectionData options:NSJSONReadingMutableContainers error:&error];
        }
        
        if (error || !json)
        {
            NSLog(@"Could not parse loaded json with error:%@", error);
        }
        
        NSLog(@"%@", json);
        _connectionData = nil;
    }
    
    [pool drain];

    return 0;
}
<?php
// This sample uses the Apache HTTP client from HTTP Components (http://hc.apache.org/httpcomponents-client-ga/)
require_once 'HTTP/Request2.php';

$request = new Http_Request2('https://*.cognitiveservices.azure.us/anomalydetector/v1.0/timeseries/last/detect');
$url = $request->getUrl();

$headers = array(
    // Request headers
    'Content-Type' => 'application/json',
    'Ocp-Apim-Subscription-Key' => '{subscription key}',
);

$request->setHeader($headers);

$parameters = array(
    // Request parameters
);

$url->setQueryVariables($parameters);

$request->setMethod(HTTP_Request2::METHOD_POST);

// Request body
$request->setBody("{body}");

try
{
    $response = $request->send();
    echo $response->getBody();
}
catch (HttpException $ex)
{
    echo $ex;
}

?>
########### Python 2.7 #############
import httplib, urllib, base64

headers = {
    # Request headers
    'Content-Type': 'application/json',
    'Ocp-Apim-Subscription-Key': '{subscription key}',
}

params = urllib.urlencode({
})

try:
    conn = httplib.HTTPSConnection('*.cognitiveservices.azure.us')
    conn.request("POST", "/anomalydetector/v1.0/timeseries/last/detect?%s" % params, "{body}", headers)
    response = conn.getresponse()
    data = response.read()
    print(data)
    conn.close()
except Exception as e:
    print("[Errno {0}] {1}".format(e.errno, e.strerror))

####################################

########### Python 3.2 #############
import http.client, urllib.request, urllib.parse, urllib.error, base64

headers = {
    # Request headers
    'Content-Type': 'application/json',
    'Ocp-Apim-Subscription-Key': '{subscription key}',
}

params = urllib.parse.urlencode({
})

try:
    conn = http.client.HTTPSConnection('*.cognitiveservices.azure.us')
    conn.request("POST", "/anomalydetector/v1.0/timeseries/last/detect?%s" % params, "{body}", headers)
    response = conn.getresponse()
    data = response.read()
    print(data)
    conn.close()
except Exception as e:
    print("[Errno {0}] {1}".format(e.errno, e.strerror))

####################################
require 'net/http'

uri = URI('https://*.cognitiveservices.azure.us/anomalydetector/v1.0/timeseries/last/detect')
uri.query = URI.encode_www_form({
})

request = Net::HTTP::Post.new(uri.request_uri)
# Request headers
request['Content-Type'] = 'application/json'
# Request headers
request['Ocp-Apim-Subscription-Key'] = '{subscription key}'
# Request body
request.body = "{body}"

response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http|
    http.request(request)
end

puts response.body