This notebook shows you how to refine TimeGPT’s anomaly detection process. By tuning parameters, you can align anomaly detection with specific use cases and improve accuracy.

1

1. Install and Import Dependencies

In your environment, install and import the necessary libraries:

Import Dependencies
import pandas as pd
from nixtla import NixtlaClient
import matplotlib.pyplot as plt
2

2. Define a Plotting Utility Function

Use this helper function to visualize detected anomalies:

Plot Anomaly Function
def plot_anomaly(df, anomaly_df, time_col='ts', target_col='y'):
    merged_df = pd.merge(
        df.tail(300),
        anomaly_df[[time_col, 'anomaly', 'TimeGPT']],
        on=time_col,
        how='left'
    )
    plt.figure(figsize=(12, 2))
    plt.plot(merged_df[time_col], merged_df[target_col], label='y', color='navy', alpha=0.8)
    plt.plot(merged_df[time_col], merged_df['TimeGPT'], label='TimeGPT', color='orchid', alpha=0.7)
    plt.scatter(
        merged_df.loc[merged_df['anomaly'], time_col],
        merged_df.loc[merged_df['anomaly'], target_col],
        color='orchid',
        label='Anomalies Detected'
    )
    plt.legend()
    plt.tight_layout()
    plt.show()
3

3. Initialize the Nixtla Client

Create an instance of NixtlaClient with your API key:

Initialize Nixtla Client
nixtla_client = NixtlaClient(api_key='my_api_key_provided_by_nixtla')  # Replace with your Nixtla API key

If you are using an Azure AI endpoint, set the base_url parameter:

Azure AI Endpoint Setup
nixtla_client = NixtlaClient(
    base_url="your azure ai endpoint",
    api_key="your api_key"
)

Why Anomaly Detection?

TimeGPT leverages forecast errors to identify anomalies in your time-series data. By optimizing parameters, you can detect subtle deviations and customize results for specific use cases.

Key Parameters

detection_size determines data window size for threshold calculation.

level sets confidence intervals for anomaly thresholds.

freq aligns detection with data frequency (e.g., “D” for daily).

Conduct a Baseline Anomaly Detection

Load a portion of the Peyton Manning dataset to illustrate the default anomaly detection process:

Load Dataset
df = pd.read_csv(
    'https://datasets-nixtla.s3.amazonaws.com/peyton-manning.csv',
    parse_dates=['ds']
).tail(200)

df.head()

You have successfully refined anomaly detection using TimeGPT. Experiment with different fine-tuning strategies, horizons, and step sizes to tailor alerts for your unique data patterns.