Agent skill

Regime Detection

by agiprolabs in agiprolabs/claude-trading-skills

Market regime identification using volatility clustering, trend detection, and statistical methods for adaptive trading

MITAuto-check passedBusiness, Finance & HR

Install Regime Detection

skills CLI
$ npx skills add agiprolabs/claude-trading-skills --skill regime-detection -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install agiprolabs/claude-trading-skills regime-detection --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/agiprolabs/claude-trading-skills.git skills-src && mkdir -p .claude/skills && cp -r skills-src/skills/regime-detection .claude/skills/regime-detection && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
regime-detection
GitHub stars
410
Token cost
~2.6k tokens
SKILL.md length
652 words
Files
5 (incl. scripts, references)
Skills in repo
68
Repo updated
First seen
Licence
MIT

At a glance

Market regime identification using volatility clustering, trend detection, and statistical methods for adaptive trading

  • Works in 4 steps: ATR Volatility Percentile → ADX Trend Strength → EMA Slope + Price Position → …
  • Tasks that involve Trading and backtesting
  • SKILL.md covers Why Regime Detection Matters, Core Regime Dimensions, Simple Approaches (No ML… and Statistical Approaches, plus 5 more sections
  • Runs Python scripts from its folder

What it does

Regime Detection is an agent skill from agiprolabs/claude-trading-skills. Market regime identification using volatility clustering, trend detection, and statistical methods for adaptive trading

Its SKILL.md is about 2.6k tokens, which your agent loads only when the skill is triggered. The skill folder holds 6 other files, including scripts and reference files (for example `references/methodology.md`, `references/strategy_adaptation.md` and `scripts/detect_regime.py`).

It sits in Business, Finance & HR, covering Trading and backtesting. The repository describes itself as: 68 trading, DeFi, and quantitative finance Agent Skills. Works with Claude Code, Cursor, Codex, Gemini CLI, and 30+ other tools. The licence is MIT.

When your agent uses it

  • Tasks that involve Trading and backtesting

Example prompts

  • “/regime-detection”

Requirements

  • Python 3

Workflow steps

4 steps, taken from the step headings in SKILL.md.

  1. ATR Volatility Percentile
  2. ADX Trend Strength
  3. EMA Slope + Price Position
  4. Bollinger Band Width Percentile

What it can do on your machine

Read from SKILL.md and the folder at commit 981e1d7. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    Ships 2 files in scripts/ (Python), which the agent can run.

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Regime Detection loads about 2.6k tokens when it runs, and up to ~6.2k if it reads all its reference files. Until then it costs about 34 tokens; SKILL.md has 652 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~34
When it runs · the whole SKILL.md, loaded when a task matches
~2.6k
With references · SKILL.md plus every file in references/, read only if the agent opens them
~6.2k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); the scripts in this folder are not scanned.

SKILL.md

The full file from agiprolabs/claude-trading-skills at commit 981e1d7, republished under its MIT licence (© agiprolabs). 652 words, ~2,645 tokens.

Download SKILL.mdSave it as .claude/skills/regime-detection/SKILL.md (or your agent's skills folder). This skill also uses 4 other files; get the full folder from GitHub.
name
regime-detection
description
Market regime identification using volatility clustering, trend detection, and statistical methods for adaptive trading

Regime Detection

Identify the current market regime so you can pick the right strategy, size positions correctly, and avoid deploying trend-following logic in a ranging market (or vice versa).

Why Regime Detection Matters

Every strategy has a "home regime." A momentum strategy prints money in a clean uptrend but bleeds in a choppy range. A mean-reversion grid thrives in low-volatility consolidation but gets steamrolled by a trending breakout. Regime detection tells you which playbook to use right now.

Key benefits:

  • Strategy selection: Route signals to the right strategy for the current environment
  • Position sizing: Reduce exposure in hostile regimes, increase in favorable ones
  • Stop adaptation: Wider stops in high-vol regimes, tighter in low-vol trends
  • Drawdown control: Sit out "danger zone" regimes (high vol + no trend)

Core Regime Dimensions

Two orthogonal axes define the four-quadrant regime model:

Low VolatilityHigh Volatility
TrendingQ1: Clean trend — best for trend followingQ2: Volatile trend — momentum with caution
RangingQ3: Quiet range — mean-reversion paradiseQ4: Choppy chaos — reduce or sit out

A third dimension — mean-reversion tendency (Hurst exponent) — refines Q3 by telling you how reliably price reverts.

Simple Approaches (No ML Required)

1. ATR Volatility Percentile

Rank the current ATR against its own recent history to get a 0–100 percentile score.

python
import pandas as pd
import numpy as np

def atr_percentile(
    high: pd.Series, low: pd.Series, close: pd.Series,
    atr_period: int = 14, lookback: int = 100
) -> pd.Series:
    """ATR percentile rank over a rolling window."""
    tr = pd.concat([
        high - low,
        (high - close.shift(1)).abs(),
        (low - close.shift(1)).abs()
    ], axis=1).max(axis=1)
    atr = tr.rolling(atr_period).mean()
    return atr.rolling(lookback).apply(
        lambda x: pd.Series(x).rank(pct=True).iloc[-1], raw=False
    )
  • < 25th percentile → Low volatility regime
  • 25th–75th → Normal volatility
  • > 75th percentile → High volatility regime
2. ADX Trend Strength

ADX above 25 signals a trending market; below 20 signals a range.

python
def compute_adx(
    high: pd.Series, low: pd.Series, close: pd.Series,
    period: int = 14
) -> pd.Series:
    """Average Directional Index."""
    plus_dm = high.diff().clip(lower=0)
    minus_dm = (-low.diff()).clip(lower=0)
    # Zero out when the other is larger
    plus_dm[plus_dm < minus_dm] = 0
    minus_dm[minus_dm < plus_dm] = 0

    tr = pd.concat([
        high - low,
        (high - close.shift(1)).abs(),
        (low - close.shift(1)).abs()
    ], axis=1).max(axis=1)

    atr = tr.ewm(span=period, adjust=False).mean()
    plus_di = 100 * plus_dm.ewm(span=period, adjust=False).mean() / atr
    minus_di = 100 * minus_dm.ewm(span=period, adjust=False).mean() / atr
    dx = 100 * (plus_di - minus_di).abs() / (plus_di + minus_di)
    return dx.ewm(span=period, adjust=False).mean()
3. EMA Slope + Price Position
python
def trend_direction(close: pd.Series, period: int = 20) -> pd.Series:
    """Returns +1 (uptrend), -1 (downtrend), 0 (neutral)."""
    ema = close.ewm(span=period, adjust=False).mean()
    slope = ema.diff(5)  # 5-bar slope
    above = (close > ema).astype(int)
    direction = pd.Series(0, index=close.index)
    direction[(slope > 0) & (above == 1)] = 1
    direction[(slope < 0) & (above == 0)] = -1
    return direction
4. Bollinger Band Width Percentile

BB width (upper - lower) / middle as a volatility proxy. A "squeeze" (low percentile) often precedes a breakout.

python
def bb_width_percentile(
    close: pd.Series, period: int = 20,
    std_dev: float = 2.0, lookback: int = 100
) -> pd.Series:
    """Bollinger Band width percentile."""
    sma = close.rolling(period).mean()
    std = close.rolling(period).std()
    width = (2 * std_dev * std) / sma
    return width.rolling(lookback).apply(
        lambda x: pd.Series(x).rank(pct=True).iloc[-1], raw=False
    )

Statistical Approaches

Rolling Hurst Exponent

The Hurst exponent H classifies time series behavior:

  • H < 0.4 → Mean-reverting (anti-persistent)
  • 0.4 ≤ H ≤ 0.6 → Random walk (no exploitable structure)
  • H > 0.6 → Trending (persistent)

Computed via the Rescaled Range (R/S) method. See references/methodology.md for the full derivation.

python
def hurst_exponent(series: pd.Series, max_lag: int = 50) -> float:
    """Estimate Hurst exponent using R/S method."""
    lags = range(2, max_lag)
    rs_values = []
    for lag in lags:
        chunks = [series.iloc[i:i+lag] for i in range(0, len(series) - lag, lag)]
        rs_list = []
        for chunk in chunks:
            if len(chunk) < lag:
                continue
            mean_val = chunk.mean()
            devs = chunk - mean_val
            cumdev = devs.cumsum()
            r = cumdev.max() - cumdev.min()
            s = chunk.std(ddof=1)
            if s > 0:
                rs_list.append(r / s)
        if rs_list:
            rs_values.append(np.mean(rs_list))
        else:
            rs_values.append(np.nan)
    valid = [(l, r) for l, r in zip(lags, rs_values) if not np.isnan(r)]
    if len(valid) < 5:
        return 0.5
    log_lags = np.log([v[0] for v in valid])
    log_rs = np.log([v[1] for v in valid])
    coeffs = np.polyfit(log_lags, log_rs, 1)
    return coeffs[0]
Change-Point Detection (CUSUM)

Detects abrupt shifts in mean or variance of a return series.

python
def cusum_test(
    returns: pd.Series, threshold: float = 2.0
) -> list[int]:
    """CUSUM change-point detection on returns.

    Returns indices where regime changes are detected.
    """
    mean_r = returns.mean()
    std_r = returns.std()
    if std_r == 0:
        return []
    s_pos, s_neg = 0.0, 0.0
    changes = []
    for i, r in enumerate(returns):
        z = (r - mean_r) / std_r
        s_pos = max(0, s_pos + z - 0.5)
        s_neg = max(0, s_neg - z - 0.5)
        if s_pos > threshold or s_neg > threshold:
            changes.append(i)
            s_pos, s_neg = 0.0, 0.0
    return changes
Hidden Markov Models

For 2–3 state regime models using hmmlearn. This is optional — all core functionality works with numpy/pandas only.

python
# Optional: requires `uv pip install hmmlearn`
from hmmlearn import hmm

def fit_hmm_regimes(
    returns: np.ndarray, n_states: int = 2, n_iter: int = 100
) -> tuple[np.ndarray, object]:
    """Fit a Gaussian HMM to return series."""
    X = returns.reshape(-1, 1)
    model = hmm.GaussianHMM(
        n_components=n_states, covariance_type="full", n_iter=n_iter
    )
    model.fit(X)
    states = model.predict(X)
    return states, model

See references/methodology.md for details on feature selection and state interpretation.

Crypto-Specific Considerations

Regime Speed

Crypto regimes change much faster than equities:

ParameterEquitiesCrypto (large cap)Crypto (micro cap / PumpFun)
ATR lookback100–200 bars50–100 bars20–50 bars
ADX period14–2810–147–10
Regime persistenceWeeks–monthsDays–weeksHours–days
Hurst window200+ bars100 bars50 bars
Show full SKILL.md (257 more words)Show less
Volume as a Regime Signal

In crypto, volume confirms regime quality:

  • High volume + trend → Strong conviction, ride it
  • Low volume + trend → Drift, unreliable, reduce size
  • High volume + range → Distribution or accumulation, watch for breakout
  • Low volume + range → Dead market, skip
PumpFun Micro-Regimes

New token launches follow a stereotyped sequence:

  1. Launch pump (minutes): Vertical move, extreme vol, no mean-reversion
  2. First dump (minutes–hours): Profit-taking, high vol, trending down
  3. Consolidation (hours–days): Low vol range, potential mean-reversion
  4. Second wave or death: Either breaks out again (new trend) or fades to zero

Each micro-regime lasts minutes to hours. Use 1-minute bars with 20–50 bar windows.

Combined Regime Classification

python
def classify_regime(
    vol_percentile: float, adx: float, hurst: float,
    trend_dir: int
) -> dict[str, str]:
    """Classify into the 4-quadrant model."""
    vol_regime = (
        "low" if vol_percentile < 0.30
        else "high" if vol_percentile > 0.70
        else "normal"
    )
    trend_regime = (
        "trending" if adx > 25
        else "ranging" if adx < 20
        else "transitional"
    )
    direction = (
        "up" if trend_dir > 0
        else "down" if trend_dir < 0
        else "neutral"
    )
    mr_regime = (
        "mean_reverting" if hurst < 0.4
        else "trending" if hurst > 0.6
        else "random"
    )
    return {
        "volatility": vol_regime,
        "trend": trend_regime,
        "direction": direction,
        "mean_reversion": mr_regime,
        "quadrant": f"{vol_regime}_vol_{trend_regime}",
    }

Strategy Adaptation

See references/strategy_adaptation.md for the full regime-strategy matrix.

Quick reference:

Current RegimeAction
Low vol + trending upFull size trend-following, tight stops
High vol + trendingHalf size momentum, wide stops
Low vol + rangingMean-reversion / grid strategies
High vol + rangingReduce to 25% size or sit out
Regime transitionFlatten or reduce to minimum size

Integration with Other Skills

  • pandas-ta: Compute ATR, ADX, Bollinger Bands, EMAs
  • volatility-modeling: Advanced vol forecasting (GARCH, realized vol)
  • strategy-framework: Route signals through regime filter before execution
  • position-sizing: Scale position size by regime volatility
  • risk-management: Adjust portfolio risk limits per regime

Files

References
  • references/methodology.md — Detailed math for Hurst exponent, HMM, change-point detection, and volatility estimation methods
  • references/strategy_adaptation.md — Full regime-strategy matrix with position sizing, stop adaptation, and PumpFun micro-regime playbook
Scripts
  • scripts/detect_regime.py — Compute regime indicators on live or demo data, classify into 4-quadrant model
  • scripts/regime_backtest.py — Compare regime-adaptive vs static strategy on synthetic data with clear regime transitions

© agiprolabs, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

SKILL.md and 4 other files (scripts, references) in skills/regime-detection of agiprolabs/claude-trading-skills.

  • SKILL.md
  • references/methodology.md
  • references/strategy_adaptation.md
  • scripts/detect_regime.py
  • scripts/regime_backtest.py

Open the folder on GitHubat commit 981e1d7

Compare with similar skills

Regime Detection next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Regime Detection compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Regime Detection this skillagiprolabs/claude-trading-skills410—~2.6kAutomated safety check: PassMIT
Tushare Datazillionare/zillionare3212 repos~2.3kAutomated safety check: PassNone
Tradingview MCPatilaahmettaner/tradingview-mcp5k—~1.3kAutomated safety check: PassMIT
Digital Oraclekomako-workshop/digital-oracle875—~5.9kAutomated safety check: PassMIT
Polyclawchainstacklabs/polyclaw3591 repos~2kAutomated safety check: PassApache-2.0
Markdownfacioquo/stock-indicators-dotnet1.2k—~812Automated safety check: PassApache-2.0

Similar skills

  • Tushare Data

    zillionare/zillionare

    面向中文自然语言的 Tushare 数据研究技能。用于把“看看这只股票最近怎么样”“帮我查财报趋势”“最近哪个板块最强”“北向资金在买什么”“给我导出一份行情数据”这类请求,转成可执行的数据获取、清洗、对比、筛选、导出与简要分析流程。适用于 A 股、指数、ETF/基金、财务、估值、资金流、公告新闻、板块概念与宏观数据等研究场景。

    321 GitHub starsUsed in 2 repos~2.3k tokens
    Business, Finance & HRAuto-check passed
  • Tradingview MCP

    atilaahmettaner/tradingview-mcp

    AI Trading Intelligence — live prices, 30+ technical indicators, backtesting (6 strategies), walk-forward overfitting detection, trade logs, equity curves, licensed news sentiment (Marketaux), and…

    5k GitHub stars~1.3k tokensUpdated 2 days ago
    Business, Finance & HRAuto-check passed
  • Digital Oracle

    komako-workshop/digital-oracle

    Answer prediction questions using market trading data, not opinions.

    875 GitHub stars~5.9k tokensUpdated 2 mo ago
    Business, Finance & HRAuto-check passed
  • Polyclaw

    chainstacklabs/polyclaw

    Trade on Polymarket via split + CLOB execution. An agent skill from chainstacklabs/polyclaw.

    359 GitHub starsUsed in 1 repo~2k tokens
    Business, Finance & HRAuto-check passed
  • Markdown

    facioquo/stock-indicators-dotnet

    Format and lint Markdown in this repository against GitHub Flavored Markdown and its markdownlint-cli2 configuration — headers, lists, code fences, callouts (VitePress containers on docs-site pages…

    1.2k GitHub stars~812 tokensUpdated today
    Business, Finance & HRAuto-check passed
  • Openmobius Skill

    MobiusQuant/OpenMobius-skill

    Provides multi-school trading Q&A, chart/OHLCV analysis, annotation, and fresh-market workflows covering ICT/SMC, ChanLun, Wyckoff, Price Action, Order Flow, VSA, and Elliott Wave.

    695 GitHub stars~7.2k tokensUpdated 1 mo ago
    Business, Finance & HRAuto-check passed

More from agiprolabs/claude-trading-skills

All 68 skills in this repo
  • Backtrader

    agiprolabs/claude-trading-skills

    Event-driven backtesting with bar-by-bar execution, complex order types, multiple analyzers, and custom indicators

    410 GitHub stars~2.4k tokensUpdated 1 mo ago
    Auto-check passed
  • Birdeye API

    agiprolabs/claude-trading-skills

    Solana token market data via Birdeye — prices, OHLCV, trades, token metadata, security checks, and trader activity

    410 GitHub stars~1.8k tokensUpdated 1 mo ago
    Auto-check passed
  • Coingecko API

    agiprolabs/claude-trading-skills

    Broad crypto market data from CoinGecko covering 13,000+ tokens.

    410 GitHub stars~1.6k tokensUpdated 1 mo ago
    Auto-check passed
  • Cointegration Analysis

    agiprolabs/claude-trading-skills

    Cointegration testing for pairs trading using Engle-Granger, Johansen, and rolling stability analysis

    410 GitHub stars~2.1k tokensUpdated 1 mo ago
    Auto-check passed
  • Copy Trading

    agiprolabs/claude-trading-skills

    Wallet evaluation, monitoring, and copy-trade strategy design for Solana DEX trading

    410 GitHub stars~2.4k tokensUpdated 1 mo ago
    Auto-check passed
  • Correlation Analysis

    agiprolabs/claude-trading-skills

    Cross-asset correlation analysis including rolling correlation, hierarchical clustering, tail dependence, and regime-dependent correlation

    410 GitHub stars~2.4k tokensUpdated 1 mo ago
    Auto-check passed

Questions about Regime Detection

What does Regime Detection do?

Market regime identification using volatility clustering, trend detection, and statistical methods for adaptive trading. Regime Detection is an agent skill from agiprolabs/claude-trading-skills.

When should I use Regime Detection?

Regime Detection fits situations like: tasks that involve Trading and backtesting.

How do I install Regime Detection in Claude Code?

Run `npx skills add agiprolabs/claude-trading-skills --skill regime-detection -a claude-code`. Or copy the skill folder (skills/regime-detection in agiprolabs/claude-trading-skills) into .claude/skills/regime-detection in your project. Claude Code loads it when a task matches its description.

How do I install Regime Detection in Codex?

Run `npx skills add agiprolabs/claude-trading-skills --skill regime-detection -a codex`. Or copy the skill folder (skills/regime-detection in agiprolabs/claude-trading-skills) into .agents/skills/regime-detection in your project. Codex loads it when a task matches its description.

Can I use Regime Detection in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add agiprolabs/claude-trading-skills --skill regime-detection -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/regime-detection, .gemini/skills/regime-detection, .github/skills/regime-detection and .opencode/skills/regime-detection in your project.

What does Regime Detection need to run?

Going by SKILL.md and its folder, Regime Detection needs Python for the scripts in its folder. Our summary lists: Python 3.

Does Regime Detection access the network?

SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.

Is Regime Detection safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. The check reads SKILL.md only: the scripts in the folder are not scanned, so read them before running anything.

What licence does Regime Detection use?

Regime Detection is published under the MIT licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Regime Detection use?

About 2.6k tokens (SKILL.md is roughly 11k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full. Its references folder adds about 3.6k tokens, read only when the agent opens those files.

What are the alternatives to Regime Detection?

Skills that share tags, products or a category with Regime Detection: Tushare Data (zillionare/zillionare, 321 stars), Tradingview MCP (atilaahmettaner/tradingview-mcp, 5k stars), Digital Oracle (komako-workshop/digital-oracle, 875 stars) and Polyclaw (chainstacklabs/polyclaw, 359 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Regime Detection?

agiprolabs (a GitHub user) maintains it in agiprolabs/claude-trading-skills, which has 410 GitHub stars. The repository holds 68 skills in this directory. The repository was last updated on September 3, 2026.

Source: agiprolabs/claude-trading-skills on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.