Adding date features is a powerful way to enrich your dataset when no exogenous variables are available. These features help guide the historical anomaly detection model in recognizing seasonal and temporal patterns.

1

Step 1: Install and Import

First, ensure the nixtla Python client is installed and then import the required libraries:

Import Libraries
import pandas as pd
from nixtla import NixtlaClient
2

Step 2: Initialize the Nixtla Client

Create an instance of NixtlaClient. By default, it uses your NIXTLA_API_KEY environment variable. You can also provide a key directly:

Nixtla Client Initialization
nixtla_client = NixtlaClient(
    # Defaults to os.environ.get("NIXTLA_API_KEY")
    api_key='my_api_key_provided_by_nixtla'
)

When using an Azure AI endpoint, specify the base_url argument:

Azure AI Client Initialization
nixtla_client = NixtlaClient(
    base_url="your azure ai endpoint",
    api_key="your api_key"
)
3

Step 3: Add Date Features for Anomaly Detection

Read your dataset, and add time-based features to guide the anomaly detection model. You can enable all possible features by setting date_features=True, or specify certain features to focus on:

Add Date Features Example
# Read the data
df = pd.read_csv('https://datasets-nixtla.s3.amazonaws.com/peyton-manning.csv')

# Add date features at the month and year levels
anomalies_df_x = nixtla_client.detect_anomalies(
    df,
    freq='D',
    date_features=['month', 'year'],
    date_features_to_one_hot=True,
    level=99.99,
)

# Plot anomalies
nixtla_client.plot(df, anomalies_df_x)

This approach extracts monthly and yearly patterns, then converts them to one-hot-encoded features, creating multiple exogenous variables for the anomaly detection model.

4

Step 4: Review Output Logs & Visualize

When you run the detection, logs inform you about which exogenous features were used:

Next, visualize the anomalies:

Anomaly plot showing flagged points based on date features.

And plot the weight contributions of the date features:

Weights Plot
nixtla_client.weights_x.plot.barh(
    x='features',
    y='weights'
)

Bar chart indicating which date features contribute most to anomaly detection.

Key Concept: Date Features

Date features help the model recognize seasonal patterns, holiday effects, or recurring fluctuations. Examples include day_of_week, month, year, and more.

Learn More

For a deeper dive into anomaly detection, refer to the comprehensive anomaly detection tutorial.