Detecting a market regime with price alone
TL;DR — A market can be classified into four regimes (bull, bear, range, volatile) using price alone: the slope of a moving average for trend, two moving averages for relative position, and the average of absolute returns for volatility. The goal is not absolute precision but reproducibility: a transparent classification, without look-ahead, that reveals "where your edge comes from". A strategy that only wins in one regime is fragile. This is exactly what the
computeRegimesfunction in the Playground does, bar by bar, for free. Strategy Arena is an educational simulation platform (paper-trading): nothing here is financial advice.
Why a strategy "that works" does not always work
The most poorly framed question in trading is "does this strategy work?". A strategy never works in the absolute: it works under certain market conditions and fails under others. Trend-following thrives when price moves in a straight line; it gets chopped to pieces when the market oscillates sideways. Conversely, mean-reversion — buying dips, selling tops — lives in trendless markets and gets crushed in a violent directional move.
A market regime is a phase during which the statistical behavior of price remains roughly stable: comparable direction, strength and agitation. As long as the regime holds, a family of strategies has a structural advantage. When the regime changes, the advantage can reverse. This is why a backtest showing a fine overall return can be misleading: if all the gain was captured during a single bullish phase of a few months, you do not have a robust edge — you may simply have benefited from the time slicing.
Detecting the regime is therefore two things at once: a diagnostic tool (which world am I in right now?) and an attribution tool (does my gain come from a single regime, or from several?).
Three ingredients, price and nothing else
The central idea of this article is deliberately austere: no on-chain data, no order book, no exotic indicator, no sentiment. Just the series of closing prices. With it, three measures are built.
1. Trend: the slope of a moving average
A moving average smooths noise. Its slope says in which direction it is moving. It is measured as a relative change over a short window:
slope = (SMA20[i] − SMA20[i−10]) / SMA20[i−10]
A clearly positive slope signals an advance; clearly negative, a decline; close to zero, stagnation. The relative ratio (not absolute) makes the measure comparable from one asset to another, whether it trades at 50 or 50,000.
2. Relative position: fast average against slow average
The sign of the slope is not enough — a fleeting bounce in a downtrend can produce a positive slope over ten bars. Confirmation by structure is therefore required: where does the short average sit relative to the long average?
SMA20 ≥ SMA50 → bullish bias
SMA20 < SMA50 → bearish bias
This is the good old moving average crossover, used here not to generate a buy signal, but as a consistency filter: "bull" is declared only if the slope AND the relative position point in the same direction.
3. Volatility: the average of absolute returns
What remains is agitation. It is measured simply by the average amplitude of bar-to-bar changes:
volatility = average over 20 bars of |price[k] / price[k−1] − 1|
This is the "nervousness" of price. When it exceeds a threshold, direction becomes secondary: whether it goes up or down hardly matters, it shakes, and most strategies suffer. Volatility is therefore treated as a state in its own right, taking priority over the others.
The exact algorithm (the one on the site)
Here is the logic actually executed by the computeRegimes function in the Playground, bar by bar. The order of priority matters: the first true rule wins.
For each bar i:
SMA20 = average of the last 20 prices
SMA50 = average of the last 50 prices
slope = (SMA20[i] − SMA20[i−10]) / SMA20[i−10]
vol = average over 20 bars of |price[k]/price[k−1] − 1|
1) if vol > 1.2% → VOLATILE
2) else if slope > +0.6% AND SMA20 ≥ SMA50 → BULL
3) else if slope < −0.6% AND SMA20 < SMA50 → BEAR
4) else → RANGE
Recapped in a table:
| Regime | Condition | Favored strategy family |
|---|---|---|
| ⚡ Volatile | volatility > 1.2% | None — reduce exposure |
| 🐂 Bull | slope > +0.6% and SMA20 ≥ SMA50 | Trend-following, momentum |
| 🐻 Bear | slope < −0.6% and SMA20 < SMA50 | Trend-following (short), cash |
| ➡ Range | everything else | Mean-reversion, grid |
Four states, two thresholds (0.6% and 1.2%), three windows (20, 50, 10). That is all. Nothing to adjust in secret, nothing irreproducible.
P&L attribution: "where your edge comes from"
This is where regime detection becomes a real research instrument, and not a visual gadget.
Once each bar is labeled, the site runs your strategy on the same series and splits the change in capital bar by bar into the corresponding regime. Concretely, for each time step, the gain or loss equity[i] − equity[i−1] is added to the counter of the regime active at that instant. The result — called regAgg in the code — is a breakdown by regime: how much your strategy earned (or lost) in a bull market, in a bear market, in range, in volatile.
This breakdown answers a question that overall return always hides:
Your strategy shows a positive return over the whole period? Very well. But if almost all of that gain comes from bullish phases, and range and volatile are neutral or negative, then you do not have an all-weather strategy: you have a disguised directional bet. The day the market spends months in range, your edge can disappear.
A sound edge is spread across several regimes, or at minimum positive (or neutral) everywhere except in the regime it explicitly targets. An edge concentrated in a single regime is fragile by construction. Seeing this breakdown in black and white teaches more than a fine final number.
Pitfall #1: look-ahead
The danger that silently invalidates most homemade regime detections is called look-ahead bias: using, to classify bar i, information that did not yet exist at instant i.
The classic error: centering a moving average (taking bars before and after point i), or normalizing volatility over the full range of the data. In both cases, you let the future leak into the present. The classification becomes magnificent… and unusable in real time.
The golden rule, respected by the site's implementation: everything, at bar i, is computed only on bars ≤ i. The SMA looks backward. The slope compares the present to ten past bars. Volatility aggregates the last twenty returns. No measure touches i+1. This is precisely what makes the classification verifiable: what the chart displays at a given instant is exactly what you would have known, live, at that instant.
Threshold sensitivity to timeframe
Let us be clear about what the numbers 0.6% and 1.2% are worth: they are thresholds calibrated for the time step of the displayed data, not universal constants.
Volatility and slope accumulate with time. On hourly bars, a 0.6% move is notable. On daily bars, the same threshold is crossed almost every day — everything would become "bull" or "bear", and the "range" regime would disappear. Conversely, on five-minute bars, these thresholds are too high and everything would fall back into "range".
Two practical consequences:
- Changing timeframe requires recalibration. As a first approximation, the volatility of an asset evolves roughly as the square root of time: moving from hourly to daily bars (≈ 24×) multiplies the typical amplitude by about 5. The thresholds must follow.
- There is no single "correct" setting. Hence the value of the sliders: you observe how the colored bands move when a threshold is moved, and you choose with full knowledge.
What it gives, regime by regime
Bringing diagnosis and attribution together, a stable pattern emerges — not as a promise of gains, but as a well-documented structural regularity:
- Marked bull / bear: trend-following has the wind at its back. Price advances in one direction, tight stop-losses hurt but gains run. This is the natural terrain of momentum.
- Range (no trend): mean-reversion gains the advantage. Buy the bottom of the channel, sell the top. Trend-following, for its part, multiplies false starts and wears itself out in commissions.
- Volatile: almost everything suffers. Violent wicks trigger stops in both directions, signals contradict each other. The best "strategy" there is often to reduce position size, or even stay out. The volatile regime serves mainly as a warning.
Understanding this transforms the reading of a backtest: instead of asking "how much does it earn?", one asks "in which regimes does it earn, and will those regimes recur?".
Do it yourself
All the theory above can be run live, for free, in the Playground:
- The regime color bands are overlaid on the price chart (green = bull, red = bear, gray = range, orange = volatile). You instantly see the temporal structure of the market.
- The P&L breakdown by regime shows, bar by bar, where your strategy gained and lost — your personal
regAgg, your "where your edge comes from". - The sliders let you move the parameters and observe in real time how the classification and attribution move. Move the volatility threshold and watch the orange bands expand or disappear.
- Everything is computed in the browser, on real arena data, without look-ahead.
- You can export your results to CSV, PDF, or even a Pine script for TradingView.
To compare how different families of strategies behave by regime, browse the catalog in /strategies. And before concluding that a per-regime edge is real, validate it against chance with the sibling article on Monte Carlo simulation: separating edge from luck.
Frequently asked questions
Why only four regimes? Is the market not more subtle?
It is, infinitely. Four states with fixed thresholds is a transparent heuristic, not a truth of nature. Its value is not finesse but reproducibility: anyone can recompute the same classification from price alone, without a black box. It is a solid pedagogical starting point, not the last word.
Why not use a machine learning model for the regime?
One can, and the site also offers an ML version elsewhere. But a learned model is harder to audit and reproduce by hand. This article deliberately teaches the "price alone" version that you can reimplement yourself in a few lines and verify line by line. Transparency takes precedence over sophistication for learning.
My thresholds give a strange classification, what should I do?
First check your timeframe: 0.6% and 1.2% are calibrated for the time step of the Playground data. On longer bars, raise the thresholds; on shorter bars, lower them. Use the sliders to find a setting where the four regimes appear in a balanced way.
Is an edge concentrated in a single regime necessarily bad?
Not bad — fragile. A strategy that explicitly targets bull markets can very well win only in bull markets, provided you know it and only deploy it there. The danger is believing you have a universal edge when attribution reveals a dependence on a single regime that might not recur.
Methodology & limits
Data. Detection relies solely on the series of closing prices displayed in the Playground (real arena data). No external data, no indicator derived from an order book or on-chain flow.
Calculation. SMA over 20 and 50 bars; slope as relative change over 10 bars; volatility = average of the absolute values of returns over 20 bars. Classification by priority: volatile → bull → bear → range. Thresholds 0.6% (slope) and 1.2% (volatility). Everything is computed on past bars only (no look-ahead). P&L is attributed bar by bar to the active regime.
Assumptions. The thresholds are fixed and depend on the timeframe. The boundary between regimes is sharp by construction, whereas in reality transitions are gradual — a bar labeled "range" near a threshold may be almost "bull". The 50-bar window imposes a "warm-up": the very first bars have less history to stabilize the averages.
What this test does NOT prove. It does not predict tomorrow's regime: it classifies the past and the present. It guarantees no future performance — a regime can flip at any moment and a past edge may never recur. It does not say that a strategy is "good"; it only says where, historically, its gain was concentrated. To verify that a per-regime edge is not a mere artifact of chance, complete this diagnosis with a Monte Carlo simulation.
Strategy Arena is an educational simulation platform (paper-trading) and a research laboratory. Nothing here is financial advice or a promise of gains. The strategies presented are designed for pedagogical purposes. Do your own research before any decision on real markets. For details of the assumptions and limits of all our tests, see the methodology page.
Test your own Pine strategy on a sealed period: free online judge.
⚠️ Disclaimer — This article is for informational and educational purposes only. It does not constitute investment advice or a buy/sell recommendation. Past performance does not guarantee future results. Strategy Arena is an educational simulator with virtual capital. Always do your own research before making investment decisions.