惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
W
WeLiveSecurity
O
OpenAI News
N
News and Events Feed by Topic
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Webroot Blog
Webroot Blog
Google Online Security Blog
Google Online Security Blog
云风的 BLOG
云风的 BLOG
N
News | PayPal Newsroom
H
Hacker News: Front Page
博客园_首页
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
The Last Watchdog
The Last Watchdog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
H
Heimdal Security Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
S
Schneier on Security
宝玉的分享
宝玉的分享
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Y
Y Combinator Blog
Cyberwarzone
Cyberwarzone
Microsoft Security Blog
Microsoft Security Blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
GbyAI
GbyAI
Cloudbric
Cloudbric
TaoSecurity Blog
TaoSecurity Blog
人人都是产品经理
人人都是产品经理
P
Palo Alto Networks Blog
M
MIT News - Artificial intelligence
G
GRAHAM CLULEY
C
Check Point Blog
Apple Machine Learning Research
Apple Machine Learning Research
Last Week in AI
Last Week in AI
T
Troy Hunt's Blog
L
Lohrmann on Cybersecurity
www.infosecurity-magazine.com
www.infosecurity-magazine.com
P
Proofpoint News Feed
Blog — PlanetScale
Blog — PlanetScale
量子位
博客园 - 聂微东
S
Securelist
博客园 - 三生石上(FineUI控件)
F
Full Disclosure
G
Google Developers Blog
L
LINUX DO - 热门话题
P
Proofpoint News Feed
AI
AI
PCI Perspectives
PCI Perspectives

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
How to Backtest Crypto Strategies by Market Regime (With Real Data)
Gunnar Thord · 2026-05-02 · via DEV Community

How to Backtest Crypto Strategies by Market Regime (With Real Data)

Your backtest says Sharpe 2.0. You deploy. It immediately starts losing money.

Sound familiar?

The problem isn't your strategy. It's your backtest. Specifically: it averaged across multiple market regimes, hiding where your edge actually lives.

The Regime Selection Bias Problem

A strategy that returns 40% in bull markets and -20% in bear markets will show a healthy positive backtest if your sample is 60% bull. Deploy it into a bear market and it looks like the signal "decayed."

It didn't decay. You were never testing what you thought you were testing.

Here's what regime-split backtesting reveals:

Strategy Bull Sharpe Bear Sharpe Chop Sharpe Aggregate Sharpe
SMA 50/200 2.4 -0.3 0.1 1.1
Mean Reversion 0.4 1.8 1.2 1.0
Momentum 3.1 -1.2 -0.5 0.9

The aggregate Sharpe looks similar across strategies. The regime-split view tells a completely different story: SMA crossover only works in trends, mean reversion works everywhere except bull, momentum is great in bull and terrible otherwise.

This is the insight most traders miss.

Step 1: Classify Historical Regimes

Before you can split backtest results by regime, you need regime labels for every historical period.

You have three options:

Option A: Use Regime's Historical API (Recommended)

The /intelligence/regime-history endpoint returns timestamped regime classifications going back to the start of the dataset. Each classification includes regime (bull/bear/chop), subtype, and confidence.

import requests

API_KEY = "your_api_key"
headers = {"Authorization": f"Bearer {API_KEY}"}

# Get regime history
history = requests.get(
    "https://getregime.com/api/v1/intelligence/regime-history",
    headers=headers
).json()

# Each transition includes start time, end time, and average confidence
for transition in history["transitions"]:
    print(f"{transition['regime']} from {transition['started_at']} "
          f"to {transition['ended_at']} "
          f"(confidence: {transition['avg_confidence']:.0%})")

Enter fullscreen mode Exit fullscreen mode

For point-in-time queries (what was the regime at any specific timestamp):

# What regime was it on March 15, 2026?
regime_at = requests.get(
    "https://getregime.com/api/v1/intelligence/regime-at",
    params={"ts": "2026-03-15T00:00:00Z"},
    headers=headers
).json()

print(f"Regime: {regime_at['regime']} ({regime_at['confidence']:.0%})")

Enter fullscreen mode Exit fullscreen mode

Option B: Build Your Own Classifier

If you want to roll your own, the minimum viable regime detector uses 3-4 uncorrelated signals:

  1. Trend: BTC price vs 200-day SMA
  2. Volatility: ATR(20) / ATR(90) ratio
  3. Sentiment: Fear & Greed Index
  4. Macro: DXY direction (optional)

Classify as "bull" when 3+ signals agree bullish, "bear" when 3+ agree bearish, "chop" otherwise. This won't be as accurate as a 10-signal weighted classifier, but it avoids overfitting and is simple to implement.

Option C: Use an HMM

Hidden Markov Models with 2-3 states are popular in academic literature. They work well in-sample but watch out for:

  • Transition probability drift out-of-sample
  • Sensitivity to initialization
  • Overfitting on the training regime distribution

Regime's API includes an HMM endpoint trained on 8,000+ snapshots if you want to compare against your own implementation.

Step 2: Tag Every Trade

Once you have regime labels, tag every trade in your backtest with the regime that was active when the trade was opened.

import pandas as pd

# Your trades dataframe
trades = pd.DataFrame({
    'entry_time': [...],
    'exit_time': [...],
    'pnl_pct': [...],
    'symbol': [...],
})

# Regime transitions from API
transitions = pd.DataFrame(history['transitions'])
transitions['started_at'] = pd.to_datetime(transitions['started_at'], unit='ms')
transitions['ended_at'] = pd.to_datetime(transitions['ended_at'], unit='ms')

def get_regime_at(ts):
    for _, t in transitions.iterrows():
        if t['started_at'] <= ts <= t['ended_at']:
            return t['regime']
    return 'unknown'

trades['regime'] = trades['entry_time'].apply(get_regime_at)

Enter fullscreen mode Exit fullscreen mode

Step 3: Split Performance Metrics

Now calculate Sharpe, win rate, max drawdown, and average trade PnL per regime:

for regime in ['bull', 'bear', 'chop']:
    subset = trades[trades['regime'] == regime]
    if len(subset) == 0:
        continue

    sharpe = subset['pnl_pct'].mean() / subset['pnl_pct'].std() * (252**0.5)
    win_rate = (subset['pnl_pct'] > 0).mean()
    avg_pnl = subset['pnl_pct'].mean()
    max_dd = subset['pnl_pct'].cumsum().cummax() - subset['pnl_pct'].cumsum()

    print(f"\n{regime.upper()}")
    print(f"  Trades: {len(subset)}")
    print(f"  Sharpe: {sharpe:.2f}")
    print(f"  Win Rate: {win_rate:.1%}")
    print(f"  Avg PnL: {avg_pnl:.2%}")
    print(f"  Max DD: {max_dd.max():.2%}")

Enter fullscreen mode Exit fullscreen mode

Step 4: Build a Regime-Aware Strategy

Once you know which regimes your strategy works in, the fix is straightforward:

import requests

def should_trade():
    """Check regime before entering any position."""
    regime = requests.get(
        "https://getregime.com/api/v1/market/regime"
    ).json()

    current = regime['regime']
    confidence = regime['confidence']

    # Only trade in regimes where backtest shows positive Sharpe
    if current == 'chop' and confidence > 0.6:
        return False  # Our strategy loses in chop

    if current == 'bear' and confidence > 0.7:
        return 'short_only'  # Flip to short-only in bear

    return True  # Full trading in bull

# Position sizing by regime
REGIME_SIZE = {
    'bull': 1.0,    # Full size
    'bear': 0.6,    # Reduced
    'chop': 0.4,    # Minimal
}

Enter fullscreen mode Exit fullscreen mode

Real Results: Regime-Following vs Buy-and-Hold

Our track record page shows live, verifiable results from applying regime-based position sizing to BTC:

  • Regime-following: +7.59%
  • Buy-and-hold: -1.89%
  • Alpha: +9.48%

This is from 4,941 market snapshots over 29 days. Not a backtest — real data, real classifications, verifiable on-chain.

Key Takeaways

  1. Never report aggregate backtest Sharpe. Always split by regime. A "Sharpe 2.0" strategy might be a "Sharpe 3.5 in bull, -0.5 in everything else" strategy.

  2. Regime detection doesn't need to be fast — it needs to be right. A 2-day lag on detecting a regime change costs a few percent. A false regime flip costs much more.

  3. Use multiple uncorrelated signals. Single-indicator regime detectors (just RSI, just SMA) overfit. Require supermajority agreement across 4+ signals before reclassifying.

  4. Size by regime, not just signal. Even if you trade in all regimes, reduce position size in regimes where your strategy has low Sharpe.

  5. Track regime-adjusted Sharpe in production. If rolling 30-trade Sharpe drops below 0.5 for the current regime, that's a yellow flag.


Try It

Get regime-classified historical data for your own backtests:

# No auth needed for current regime
curl https://getregime.com/api/v1/market/regime

# Full history requires Pro ($49/mo) or Institutional ($149/mo)
curl -H "Authorization: Bearer YOUR_KEY" \
  https://getregime.com/api/v1/intelligence/regime-history

Enter fullscreen mode Exit fullscreen mode

Free tier: 500 calls/day, regime + market overview. Start here.


Try Regime Intelligence

Regime is a real-time crypto market regime detection API. One endpoint tells you if the market is bull, bear, or chop — so your bot only trades when conditions match your strategy.

Free API access → | See pricing → | API docs →