timeseries-detrending
Tools and techniques for detrending time series data in macroeconomic analysis. Use when working with economic time series that need to be decomposed into trend and cyclical components. Covers HP filter, log transformations for growth series, and correlation analysis of business cycles.
Install
mkdir -p .claude/skills/timeseries-detrending && curl -L -o skill.zip "https://mcp.directory/api/skills/download/5773" && unzip -o skill.zip -d .claude/skills/timeseries-detrending && rm skill.zipInstalls to .claude/skills/timeseries-detrending
About this skill
Time Series Detrending for Macroeconomic Analysis
This skill provides guidance on decomposing economic time series into trend and cyclical components, a fundamental technique in business cycle analysis.
Overview
Economic time series like GDP, consumption, and investment contain both long-term trends and short-term fluctuations (business cycles). Separating these components is essential for:
- Analyzing business cycle correlations
- Comparing volatility across variables
- Identifying leading/lagging indicators
The Hodrick-Prescott (HP) Filter
The HP filter is the most widely used method for detrending macroeconomic data. It decomposes a time series into a trend component and a cyclical component.
Mathematical Foundation
Given a time series $y_t$, the HP filter finds the trend $\tau_t$ that minimizes:
$$\sum_{t=1}^{T}(y_t - \tau_t)^2 + \lambda \sum_{t=2}^{T-1}[(\tau_{t+1} - \tau_t) - (\tau_t - \tau_{t-1})]^2$$
Where:
- First term: Minimizes deviation of data from trend
- Second term: Penalizes changes in the trend's growth rate
- $\lambda$: Smoothing parameter controlling the trade-off
Choosing Lambda (λ)
Critical: The choice of λ depends on data frequency:
| Data Frequency | Recommended λ | Rationale |
|---|---|---|
| Annual | 100 | Standard for yearly data |
| Quarterly | 1600 | Hodrick-Prescott (1997) recommendation |
| Monthly | 14400 | Ravn-Uhlig (2002) adjustment |
Common mistake: Using λ=1600 (quarterly default) for annual data produces an overly smooth trend that misses important cyclical dynamics.
Python Implementation
from statsmodels.tsa.filters.hp_filter import hpfilter
import numpy as np
# Apply HP filter
# Returns: (cyclical_component, trend_component)
cycle, trend = hpfilter(data, lamb=100) # For annual data
# For quarterly data
cycle_q, trend_q = hpfilter(quarterly_data, lamb=1600)
Important: The function parameter is lamb (not lambda, which is a Python keyword).
Log Transformation for Growth Series
Why Use Logs?
For most macroeconomic aggregates (GDP, consumption, investment), you should apply the natural logarithm before filtering:
- Multiplicative to Additive: Converts percentage changes to log differences
- Stabilizes Variance: Growth rates become comparable across time
- Economic Interpretation: Cyclical component represents percentage deviations from trend
- Standard Practice: Required for business cycle statistics that compare volatilities
import numpy as np
# Apply log transformation BEFORE HP filtering
log_series = np.log(real_series)
cycle, trend = hpfilter(log_series, lamb=100)
# The cycle now represents percentage deviations from trend
# e.g., cycle = 0.02 means 2% above trend
When NOT to Use Logs
- Series that can be negative (net exports, current account)
- Series already expressed as rates or percentages
- Series with zeros
Complete Workflow for Detrending
Step-by-Step Process
- Load and clean data: Handle missing values, ensure proper time ordering
- Convert to real terms: Deflate nominal values using appropriate price index
- Apply log transformation: For positive level variables
- Apply HP filter: Use appropriate λ for data frequency
- Analyze cyclical component: Compute correlations, volatilities, etc.
Example: Business Cycle Correlation
import pandas as pd
import numpy as np
from statsmodels.tsa.filters.hp_filter import hpfilter
# Load real (inflation-adjusted) data
real_consumption = pd.Series(...) # Real consumption expenditure
real_investment = pd.Series(...) # Real fixed investment
# Log transformation
ln_consumption = np.log(real_consumption)
ln_investment = np.log(real_investment)
# HP filter with λ=100 for annual data
cycle_c, trend_c = hpfilter(ln_consumption, lamb=100)
cycle_i, trend_i = hpfilter(ln_investment, lamb=100)
# Compute correlation of cyclical components
correlation = np.corrcoef(cycle_c, cycle_i)[0, 1]
print(f"Business cycle correlation: {correlation:.4f}")
Dependencies
Ensure these packages are installed:
pip install statsmodels pandas numpy
The HP filter is in statsmodels.tsa.filters.hp_filter.
More by benchflow-ai
View all skills by benchflow-ai →You might also like
flutter-development
aj-geddes
Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.
drawio-diagrams-enhanced
jgtolentino
Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.
ui-ux-pro-max
nextlevelbuilder
"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."
godot
bfollington
This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.
nano-banana-pro
garg-aayush
Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.
fastapi-templates
wshobson
Create production-ready FastAPI projects with async patterns, dependency injection, and comprehensive error handling. Use when building new FastAPI applications or setting up backend API projects.
Related MCP Servers
Browse all serversConnect to InfluxDB time series databases for querying, writing, and managing data using powerful tools and resources.
Integrate with Prometheus for real-time performance analysis, process monitoring, and advanced Prometheus 2.0 metric dis
Create modern React UI components instantly with Magic AI Agent. Integrates with top IDEs for fast, stunning design and
Empower AI with the Exa MCP Server—an AI research tool for real-time web search, academic data, and smarter, up-to-date
Access real-time web scraping with Bright Data. Scrape any website and extract structured data easily using advanced web
Empower your workflows with Perplexity Ask MCP Server—seamless integration of AI research tools for real-time, accurate
Stay ahead of the MCP ecosystem
Get weekly updates on new skills and servers.