AutoTrend

Local Linear Trend Extraction for Time Series

A lightweight, iterative method for extracting local linear trends from time series data with computational efficiency and automatic trend boundary discovery.

pip install autotrend
Python 3.8+ MIT License PyPI version
AutoTrend Demo

Key Features

Computationally Efficient

Minimal model training compared to full sliding windows

Adaptive

Automatically discovers trend boundaries without predefined change points

Interpretable

Clear linear segments with explicit slopes and intercepts

Flexible

Adjustable error thresholds and iteration limits

Documentation

Installation

pip install autotrend

Or install from source:

git clone https://github.com/chotanansub/autotrend.git
cd autotrend
pip install -e .

Quick Start

import numpy as np
from autotrend import decompose_llt

# Generate or load your time series
sequence = np.sin(np.linspace(0, 50, 500)) + np.linspace(0, 5, 500)

# Run LLT decomposition
result = decompose_llt(
    seq=sequence,
    max_models=5,
    window_size=10,
    error_percentile=40
)

# Visualize results
result.plot_full_decomposition()

# Access results
print(f"Number of iterations: {result.get_num_iterations()}")
print(f"Trend segments: {result.get_trend_segments()}")

Core Concept

The Problem: Traditional sliding window regression methods fit a new model at every time point, leading to high computational costs.

The Solution: AutoTrend uses an iterative, focus-based approach:

  1. Single Model per Region: Train one linear regression model at the start of each focus region
  2. Trend Extension: Extend the trend line forward without retraining
  3. Error-Based Refinement: Identify high-error points and focus on them in the next iteration
  4. Adaptive Segmentation: Automatically discover trend boundaries based on prediction error

API Reference

Functional API

from autotrend import decompose_llt

result = decompose_llt(
    seq,                    # 1D input sequence
    max_models=10,          # Maximum number of iterations
    window_size=5,          # Length of training window
    error_percentile=40,    # Error threshold percentile
    percentile_step=0,      # Increment per iteration
    update_threshold=False, # Update threshold each iteration
    verbose=2,              # Verbosity level (0-2)
    store_sequence=True     # Store sequence for plotting
)

Object-based API

from autotrend import DecomposeLLT

# Create decomposer with custom parameters
decomposer = DecomposeLLT(
    max_models=10,
    window_size=20,
    error_percentile=40,
    update_threshold=True,
    percentile_step=2
)

# Fit to sequence
result = decomposer.fit(sequence)

# Or fit and plot in one call
result = decomposer.fit_plot(
    sequence,
    plot_types=['full_decomposition'],
    show=True
)

Result Object

# Access components
trends = result.trend_marks        # Iteration labels for each point
predictions = result.prediction_marks  # Predicted values
models = result.models             # LinearRegression models

# Get summary information
n_iterations = result.get_num_iterations()
segments = result.get_trend_segments()
indices, preds = result.get_predictions_by_iteration(iteration=1)

# Plotting methods
result.plot_error()
result.plot_slopes()
result.plot_full_decomposition()
result.plot_iteration_grid()
result.plot_statistics()
result.plot_all(output_dir="results/")

Visualization

AutoTrend provides comprehensive visualization tools:

  • Error Analysis: Shows the iterative process with error bars
  • Slope Comparison: Compares slopes across models with multiple views
  • Full Decomposition: 3-panel view with predictions, trends, and residuals
  • Iteration Grid: Individual subplots for each iteration
  • Model Statistics: Summary of segment lengths, slopes, and coverage
  • Animation: Animated view of the iterative refinement process
# Generate animation
from autotrend import animate_error_threshold

animate_error_threshold(
    result,
    output_path='animation.gif',
    sliding_mode=True,
    fps=5
)

Data Generators

Built-in synthetic data generators for testing:

from autotrend import (
    generate_simple_wave,
    generate_nonstationary_wave,
    generate_piecewise_linear
)

# Simple sine wave
wave = generate_simple_wave(
    length=500,
    frequency=5.0,
    add_noise=True
)

# Non-stationary wave with amplitude modulation
nonstat = generate_nonstationary_wave(
    add_noise=True,
    noise_strength=2
)

# Piecewise linear segments
piecewise = generate_piecewise_linear(
    trends=['increase', 'decrease', 'steady'],
    total_length=300,
    min_seg_len=50,
    max_seg_len=150
)

Parameters Guide

Parameter Description Default
window_size Size of training window. Smaller values capture finer trends. 5
max_models Maximum iterations. More iterations allow finer refinement. 10
error_percentile Threshold percentile (0-100). Lower values are more strict. 40
percentile_step Increment per iteration. Enables adaptive thresholding. 0
update_threshold Whether to update threshold each iteration. False
verbose Verbosity level: 0 (silent), 1 (progress), 2 (detailed). 2

Examples

See the examples directory for complete usage examples:

  • 01_quick_start.py - Minimal example
  • 02_basic_usage.py - API patterns and customization

Run demos:

python demo/run_all.py

Algorithm Details

For detailed algorithm description, see the full README.

Key Steps:

  1. Initialize focus targets covering all predictable points
  2. Train linear model on first window of focus region
  3. Extend trend and measure prediction errors
  4. Segment points by error threshold
  5. Iterate on high-error regions until convergence

Contributing

Contributions are welcome! Please see our GitHub issues page.

License

AutoTrend is released under the MIT License. See LICENSE for details.