AGENT SKILL

trend-analysis

Detect long-term trends in time series data using parametric and non-parametric methods. Use when determining if a variable shows statistically significant increase or decrease over time.

License 许可
MIT
最近更新
2026-11-14
Stars
★ 12
Forks
5

01 前言 Front Matter

name
trend-analysis
license
MIT
description
Detect long-term trends in time series data using parametric and non-parametric methods. Use when determining if a variable shows statistically significant increase or decrease over time.

03 SKILL.md 正文

Trend Analysis Guide

Overview

Trend analysis determines whether a time series shows a statistically significant long-term increase or decrease. This guide covers both parametric (linear regression) and non-parametric (Sen's slope) methods.

Parametric Method: Linear Regression

Linear regression fits a straight line to the data and tests if the slope is significantly different from zero.

from scipy import stats

slope, intercept, r_value, p_value, std_err = stats.linregress(years, values)

print(f"Slope: {slope:.2f} units/year")
print(f"p-value: {p_value:.3g}")

Assumptions

  • Linear relationship between time and variable
  • Residuals are normally distributed
  • Homoscedasticity (constant variance)

Non-Parametric Method: Sen's Slope with Mann-Kendall Test

Sen's slope is robust to outliers and does not assume normality. Recommended for environmental data.

import pymannkendall as mk

result = mk.original_test(values)

print(result.slope)  # Sen's slope (rate of change per time unit)
print(result.p)      # p-value for significance
print(result.trend)  # 'increasing', 'decreasing', or 'no trend'

Serial Autocorrelation

original_test assumes independent observations. Positive serial autocorrelation, common in annual climate, hydrology, and lake records, makes it report significant trends too often. Check the lag-1 autocorrelation and use a modified test when it is non-negligible:

import numpy as np
import pymannkendall as mk

x = np.asarray(values, dtype=np.float64)
d = x - x.mean()
r1 = np.sum(d[:-1] * d[1:]) / np.sum(d ** 2)   # lag-1 autocorrelation

mk.hamed_rao_modification_test(x)                 # variance correction (Hamed & Rao 1998)
mk.yue_wang_modification_test(x)                  # variance correction (Yue & Wang 2004)
mk.pre_whitening_modification_test(x)             # removes lag-1 AR before testing
mk.trend_free_pre_whitening_modification_test(x)  # TFPW: detrends before pre-whitening
mk.seasonal_test(x, period=12)                    # monthly data with seasonality
mk.correlated_seasonal_test(x, period=12)         # seasonality plus serial correlation

All return the same result fields (trend, p, slope). Report which test you used.

Comparison

Method Pros Cons
Linear Regression Easy to interpret, gives R² Sensitive to outliers
Sen's Slope Robust to outliers, no normality assumption Slightly less statistical power

Significance Levels

p-value Interpretation
p < 0.01 Highly significant trend
p < 0.05 Significant trend
p < 0.10 Marginally significant
p >= 0.10 No significant trend

Example: Annual Precipitation Trend

import pandas as pd
import pymannkendall as mk

# Load annual precipitation data
df = pd.read_csv('precipitation.csv')
precip = df['Precipitation'].values

# Run Mann-Kendall test
result = mk.original_test(precip)
print(f"Sen's slope: {result.slope:.2f} mm/year")
print(f"p-value: {result.p:.3g}")
print(f"Trend: {result.trend}")

Common Issues

Issue Cause Solution
p-value = NaN NaN in the input (linregress propagates it; pymannkendall drops missing values) Drop NaNs with an np.isfinite mask before linregress
Never significant Very short series: Mann-Kendall cannot reach p < 0.05 (two-sided) with n <= 4, and its normal approximation is rough below n ~ 10 Collect more data or report the test as underpowered
Conflicting results Linear regression assumes normal, independent residuals; Mann-Kendall is rank-based Check outliers and autocorrelation, and report both. Sen's slope estimates the magnitude; the Mann-Kendall p-value tests significance
Slope near zero but significant Large sample size Check practical significance

Best Practices

  • Use at least 10 data points for reliable results
  • Prefer Sen's slope for environmental time series
  • Report both slope magnitude and p-value
  • State which test variant was used (original or autocorrelation-corrected)

04 同仓库更多 Skills

stanfish06
stanfish06/skillquarium

zarr-python

Stores and queries chunked N-D scientific arrays with Zarr-Python 3, including codecs, sharding, S3/GCS storage, and NumPy/Dask/Xarray integration. Use for array layout, bounded I/O, format migration, or scientific metadata preservation.

★ 12
stanfish06
stanfish06/skillquarium

yeet

Publish local changes to GitHub by confirming scope, committing intentionally, pushing the branch, and opening a draft PR through the GitHub app from this plugin, with `gh` used only as a fallback where connector coverage is insufficient.

★ 12
stanfish06
stanfish06/skillquarium

xarray

N-dimensional labeled arrays and datasets in Python. Built on top of NumPy and Dask. It introduces labels in the form of dimensions, coordinates, and attributes on top of raw NumPy-like arrays, making data analysis in physical sciences more intuitive and less error-prone. Use for working with multi-dimensional scientific data, NetCDF/GRIB/Zarr files, climate/weather/oceanographic datasets, remote sensing, geospatial imaging, large out-of-memory datasets with Dask, and labeled array operations.

★ 12
stanfish06
stanfish06/skillquarium

writing-mstest-tests

Use when asked to fix, rewrite, update, improve, modernize, show corrected code for, or explain existing MSTest tests or MSTest-specific configuration. Use for "review" when corrected code or edits are wanted, even for one pasted assertion or passing tests with bad failure output. Covers expected/actual labels; generic Boolean, collection, string, numeric, null, identity, exception, hard-cast, and object[] checks; TestContext/lifecycle; timeout/cancellation; OS/CI conditions, retry, cleanup, parallelization, MSTest.Sdk project setup, and MSTESTxxxx. Honor the installed MSTest version. DO NOT USE to design new test cases (code-testing), perform report-only audits, create project files rather than explain MSTest setup, run tests, migrate frameworks, or handle non-MSTest/non-.NET code.

★ 12
stanfish06
stanfish06/skillquarium

wgs-prs

End-to-end WGS to polygenic risk score pipeline. Takes paired-end FASTQ files (or a pre-existing VCF) through nf-core/sarek for variant calling, applies VCF QC (normalisation, hard filtering, Ti/Tv and Het/Hom checks), then computes polygenic risk scores via the PGS Catalog. Fills the FASTQ to VCF gap upstream of the gwas-prs skill.

★ 12
stanfish06
stanfish06/skillquarium

webapp-testing

Toolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing browser screenshots, and viewing browser logs.

★ 12