OPEN-SOURCE SCRIPT

Bubble Risk Model

136
The question of whether markets can be objectively assessed for overextension has occupied financial researchers for decades. Charles Kindleberger, in his seminal work "Manias, Panics, and Crashes" (1978), documented that speculative bubbles follow remarkably consistent patterns across centuries and asset classes. Yet identifying these patterns in real time remains notoriously difficult. The Bubble Risk Model attempts to address this challenge not by predicting crashes, but by systematically measuring the statistical characteristics that historically precede fragile market conditions.

The theoretical foundation draws from two distinct research traditions. The first is the work on regime-switching models pioneered by James Hamilton (1989), who demonstrated that economic time series often exhibit discrete shifts between different behavioral states. The second is the literature on tail risk and market fragility, most notably articulated by Nassim Taleb in "The Black Swan" (2007), which emphasizes that extreme events carry disproportionate importance and that traditional risk measures systematically underestimate their probability.

Rather than attempting to build a probabilistic model requiring assumptions about underlying distributions, the Bubble Risk Model operates as a deterministic state-inference system. This distinction matters. Lawrence Rabiner's foundational tutorial on Hidden Markov Models (1989) established the mathematical framework for inferring hidden states from observable data through Bayesian updating. The present model borrows the conceptual architecture of states and transitions but replaces probabilistic inference with rule-based logic. States are not computed through forward-backward algorithms but inferred through deterministic thresholds. This trade-off sacrifices theoretical elegance for practical robustness and interpretability.

The measurement framework rests on four empirically grounded components. The first captures trailing twelve-month returns, reflecting the well-documented momentum effect identified by Jegadeesh and Titman (1993), who found that securities with strong past performance tend to continue outperforming over intermediate horizons. The second component measures trend persistence as the proportion of positive daily returns over a quarterly window, drawing on the research by Campbell and Shiller (1988) showing that price trends exhibit serial correlation that deviates from random walk assumptions. The third normalizes the distance between current prices and their long-term moving average by volatility, addressing the cross-sectional comparability problem noted by Fama and French (1992) when analyzing assets with different variance characteristics. The fourth component calculates return efficiency as the ratio of returns to realized volatility, a concept related to the Sharpe ratio but stripped of distributional assumptions that often fail in practice.

The aggregation methodology deliberately prioritizes worst-case scenarios. Rather than averaging component scores, the model uses quantile-based aggregation with an explicit tail penalty. This design choice reflects the asymmetric error costs in bubble detection: failing to identify fragility carries greater consequences than occasional false positives. The approach aligns with the precautionary principle advocated by Taleb and colleagues in their work on fragility and antifragility (2012), which argues that systems exposed to tail risks require conservative assessment frameworks.

Normalization presents a particular challenge. Raw metrics like year-over-year returns are not directly comparable across asset classes with different volatility profiles. The model addresses this through percentile ranking over multiple historical windows, typically two and five years. This dual-window approach provides regime stability, preventing the normalization from adapting too quickly during extended bull markets where elevated readings become statistically normal. The methodology draws on the concept of lookback bias documented by Lo and MacKinlay (1990), who demonstrated that single-window statistical measures can produce misleading results when market regimes shift.

The state machine introduces controlled inertia into the system. Once the model enters a particular state, transitions become progressively more difficult as the state matures. This transition resistance mechanism prevents rapid oscillation near threshold boundaries, a problem that plagues many indicator-based systems. The concept parallels the hysteresis effects described in economic literature by Dixit (1989), where systems exhibit path dependence and resist returning to previous states even when underlying conditions change.

Volatility regime detection adds contextual interpretation. Research by Engle (1982) on autoregressive conditional heteroskedasticity established that volatility clusters, with periods of high volatility tending to follow other high-volatility periods. The model scales its maturity thresholds inversely with volatility: in calm markets, states mature slowly and persist longer; in turbulent markets, information decays faster and states become more transient. This adaptive behavior reflects the empirical observation that low-volatility environments often precede significant market dislocations, as documented by Brunnermeier and Pedersen (2009) in their work on liquidity spirals.

The confidence metric addresses internal model consistency. When individual components diverge substantially, the overall score becomes less reliable regardless of its absolute level. This approach draws on ensemble methods in machine learning, where disagreement among predictors signals increased uncertainty. Dietterich (2000) provides theoretical justification for this principle, demonstrating that ensemble disagreement correlates with prediction error.

Distribution drift detection monitors whether the model's calibration remains valid. By comparing recent score distributions to longer historical baselines, the model can identify when market structure has shifted sufficiently to potentially invalidate its historical percentile rankings. This self-diagnostic capability reflects the concern raised by Andrews (1993) about parameter instability in time series models, where structural breaks can render previously estimated relationships unreliable.

The cross-asset analysis extends the framework beyond individual securities. By calculating scores for multiple asset classes simultaneously and measuring their correlation, the model distinguishes between idiosyncratic overextension affecting a single asset and systemic conditions affecting markets broadly. This differentiation matters for portfolio construction, as documented by Longin and Solnik (2001), who found that correlations between international equity markets increase significantly during periods of market stress.

Several limitations deserve explicit acknowledgment. The model cannot identify timing. Overextended conditions can persist far longer than rational analysis might suggest, a phenomenon documented by Shiller (2000) in his analysis of speculative episodes. The model provides no mechanism for determining when fragile conditions will resolve. Additionally, the cross-asset analysis lacks lead-lag detection, meaning it cannot distinguish whether assets became overextended simultaneously or sequentially. Finally, the rule-based nature of state inference means the model cannot express graduated probability assessments; states are discrete rather than continuous.

The philosophical stance underlying the model is one of epistemic humility. It does not claim to identify bubbles definitively or predict their collapse. Instead, it provides a systematic framework for measuring characteristics that have historically been associated with fragile market conditions. The distinction between information and action remains the user's responsibility. States describe current conditions; how to respond to those conditions requires judgment that no quantitative model can provide.


Practical guide for traders

This section translates the model's outputs into actionable intelligence for both retail traders managing personal portfolios and professional traders operating within institutional frameworks. The interpretation differs not in kind but in scale and consequence.

Understanding the score

The primary output is a continuous score ranging from zero to one. Lower scores indicate elevated bubble risk; higher scores suggest more sustainable market conditions. This inverse relationship may seem counterintuitive but reflects the model's construction: it measures how extreme current conditions are relative to historical norms, with extremity mapping to fragility.

A score above 0.50 generally indicates normal market conditions where standard investment approaches remain appropriate. Scores between 0.30 and 0.50 represent an elevated zone where caution is warranted but not alarm. Scores below 0.30 enter the extreme territory where historical precedent suggests increased fragility. These thresholds are not magical boundaries but represent statistical rarity: a score below 0.30 indicates conditions that occur in roughly the bottom quintile of historical observations.

For retail traders, a score in the normal range means continuing with established strategies without modification. In the elevated range, this might mean pausing new position additions while maintaining existing holdings. In the extreme range, retail traders should consider whether their portfolio could withstand a significant drawdown and whether their time horizon permits waiting for recovery. For professional traders, the score integrates into broader risk frameworks: normal conditions permit full risk budgets, elevated conditions might trigger reduced position sizing or tighter stop losses, and extreme conditions could warrant defensive positioning or increased hedging activity.

Reading the states

The model classifies conditions into three discrete states: Normal, Elevated, and Extreme. These states differ from the continuous score by incorporating persistence and transition resistance. A market can have a score temporarily dipping below 0.30 without triggering an Extreme state if the condition proves transient.

The Normal state indicates business as usual. Market conditions fall within historical norms across all measured dimensions. For retail traders, this means standard portfolio management applies. For professional traders, full strategy deployment remains appropriate with normal risk parameters.

The Elevated state signals heightened attention. At least one dimension of market behavior has moved outside normal ranges, though not to extreme levels. Retail traders should review portfolio concentration and ensure diversification remains intact. Professional traders might reduce leverage slightly, tighten risk limits, or increase monitoring frequency.

The Extreme state represents statistically rare conditions. Multiple dimensions show readings that historically occur infrequently. Retail traders should seriously evaluate whether they can tolerate potential drawdowns and consider reducing exposure to volatile assets. Professional traders should implement defensive protocols, potentially reducing gross exposure, increasing cash allocations, or adding protective positions.

Interpreting transitions

State transitions carry more information than states themselves. The model tracks whether conditions are entering, persisting in, or exiting particular states.

An Entry into Extreme represents the most important signal. It indicates a regime shift from normal or elevated conditions into territory associated with historical fragility. For retail traders, this warrants immediate portfolio review. For professional traders, this typically triggers predefined defensive protocols.

Persistence in a state indicates stability. Whether Normal or Extreme, persistence suggests the current regime has become established. For retail traders, persistence in Extreme over extended periods actually reduces immediate concern; the dangerous moment was the entry, not the continuation. For professional traders, persistent Extreme states require maintained vigilance but do not necessarily demand additional action beyond what the initial entry triggered.

An Exit from Extreme suggests improving conditions. For retail traders, this might warrant cautious return to normal positioning over time. For professional traders, exits permit gradual normalization of risk budgets, though institutional memory typically counsels slower reentry than the mathematical signal might suggest.

Duration and its meaning

The model distinguishes between Tactical, Accelerating, and Structural durations in critical zones.

Tactical duration (10-39 bars in critical territory) represents short-term overextension. Many Tactical episodes resolve without significant market disruption. Retail traders should note the condition but need not take dramatic action. Professional traders might implement modest hedges or reduce marginal positions.

Accelerating indicates Tactical duration combined with actively deteriorating scores. This combination historically precedes more significant corrections. Retail traders should consider lightening positions in their most volatile holdings. Professional traders typically implement more substantial hedges.

Structural duration (40+ bars in critical territory) indicates persistent overextension that has become a market feature rather than a temporary condition. Paradoxically, Structural conditions are both more concerning and less immediately actionable than Accelerating conditions. The market has demonstrated ability to sustain extreme readings. Retail traders should maintain heightened awareness but recognize that timing remains impossible. Professional traders often find Structural conditions require strategy adaptation rather than simple defensive positioning.

Confidence and what it tells you

The Confidence reading indicates internal model consistency. High confidence means all four underlying components agree in their assessment. Low confidence means components diverge significantly.

High confidence combined with Extreme state represents the clearest signal. The model is both indicating fragility and agreeing with itself about that assessment. Retail and professional traders alike should treat this combination with maximum seriousness.

Low confidence in any state reduces signal reliability. For retail traders, low confidence suggests waiting for clearer conditions before making significant portfolio changes. For professional traders, low confidence warrants increased skepticism about the score and potentially reduced position sizing in either direction.

Alignment and model health

The Alignment indicator monitors whether the model's calibration remains valid relative to recent market behavior.

Good alignment means recent score distributions match longer-term historical patterns. The model's percentile rankings remain meaningful. Both retail and professional traders can interpret scores at face value.

Degraded alignment indicates that recent market behavior has shifted somewhat from historical norms. Scores remain interpretable but with reduced precision. Retail traders should apply wider uncertainty bands to their interpretation. Professional traders might reduce position sizing slightly or require additional confirmation before acting.

Poor alignment signals significant distribution shift. The model may be comparing current conditions to an increasingly irrelevant historical baseline. Retail traders should rely more heavily on other information sources during Poor alignment periods. Professional traders typically reduce model weight in their decision frameworks until alignment recovers.

Volatility regime context

The volatility regime provides essential context for score interpretation.

Low volatility combined with Extreme state creates maximum concern. Research consistently shows that low-volatility environments can precede significant market dislocations. The market's apparent calm masks underlying fragility. Retail traders should recognize that low volatility does not mean low risk; it often means compressed risk premiums that will eventually normalize, potentially violently. Professional traders typically maintain or increase defensive positioning despite the market's calm appearance.

High volatility combined with Extreme state is actually less immediately concerning than low volatility. The market has already acknowledged stress; risk premiums have expanded; potential sellers may have already sold. Retail traders should resist the urge to panic sell during high-volatility extremes, as much of the adjustment may have already occurred. Professional traders recognize that high-volatility extremes often represent better entry points than low-volatility extremes.

Normal volatility requires no regime adjustment to interpretation. Scores mean what they appear to mean.

Cross-asset analysis

When enabled, the model calculates scores for multiple asset classes simultaneously, enabling systemic versus idiosyncratic risk assessment.

Systemic risk (multiple assets in Extreme with high correlation) indicates market-wide fragility. Diversification benefits are reduced precisely when most needed. Retail traders should recognize that their portfolio's apparent diversification may not protect them during systemic events. Professional traders implement cross-asset hedges and consider tail-risk protection.

Broad risk (multiple assets in Extreme with low correlation) suggests widespread but potentially unrelated overextension. Diversification may still provide some protection. Retail traders can take modest comfort in genuine diversification. Professional traders analyze which assets might offer relative value.

Isolated risk (single asset in Extreme while others remain Normal) indicates asset-specific rather than market-wide conditions. Retail traders holding the affected asset should evaluate their position specifically. Professional traders may find relative value opportunities going long unaffected assets against the extended one.

Scattered risk represents a few assets showing elevation without clear pattern. This typically warrants monitoring rather than action for both retail and professional traders.

Parameter guidance

The Short Percentile parameter (default 504 bars, approximately two years) controls the shorter normalization window. Increasing this value makes the model more conservative, requiring more extreme readings to flag concern. Retail traders should generally leave this at default. Professional traders might increase it for assets with shorter reliable history.

The Long Percentile parameter (default 1260 bars, approximately five years) controls the longer normalization window. This provides regime stability. Again, default settings suit most applications.

The Critical Threshold (default 0.30) determines where the Extreme state boundary lies. Lowering this value makes the model less sensitive, flagging fewer Extreme conditions. Raising it increases sensitivity. Retail traders seeking fewer false alarms might lower this to 0.25. Professional traders seeking earlier warning might raise it to 0.35.

The Structural Duration parameter (default 40 bars) determines when Tactical conditions become Structural. Shorter values provide earlier Structural classification. Longer values require more persistence before reclassification.

The State Maturity and Transition Resistance parameters control how readily the model changes states. Higher values create more stable states with fewer transitions. Lower values create more responsive but potentially noisier state changes. Default settings balance responsiveness against stability.

The Adaptive Smoothing parameters control how the model filters noise. In extreme zones, longer smoothing periods reduce whipsaws but increase lag. In normal zones, shorter periods maintain responsiveness. Most traders should leave these at defaults.

What the model cannot do

The model cannot predict when overextended conditions will resolve. Markets can remain irrational longer than any trader can remain solvent, as the saying goes. Extended Extreme readings may persist for months or even years before any correction materializes.

The model cannot distinguish between healthy bull markets and dangerous bubbles in their early stages. Both initially appear as strong returns and positive momentum. The model begins flagging concern only when statistical extremity develops, which may occur well into an advance.

The model cannot account for fundamental changes in market structure. If a new paradigm genuinely justifies higher valuations (rare but not impossible), the model will continue flagging extremity against historical norms that may no longer apply. The Alignment indicator provides partial protection against this failure mode but cannot eliminate it.

The model cannot replace judgment. It provides systematic measurement of conditions that have historically preceded fragility. Whether and how to act on that measurement remains entirely the trader's responsibility. Retail traders must still evaluate their personal circumstances, time horizons, and risk tolerance. Professional traders must still integrate model output with fundamental analysis, portfolio constraints, and client mandates.


References

Andrews, D.W.K. (1993). Tests for Parameter Instability and Structural Change with Unknown Change Point. Econometrica, 61(4).

Brunnermeier, M.K., & Pedersen, L.H. (2009). Market Liquidity and Funding Liquidity. Review of Financial Studies, 22(6).

Campbell, J.Y., & Shiller, R.J. (1988). Stock Prices, Earnings, and Expected Dividends. Journal of Finance, 43(3).

Dietterich, T.G. (2000). Ensemble Methods in Machine Learning. Multiple Classifier Systems.

Dixit, A. (1989). Entry and Exit Decisions under Uncertainty. Journal of Political Economy, 97(3).

Engle, R.F. (1982). Autoregressive Conditional Heteroscedasticity with Estimates of the Variance of United Kingdom Inflation. Econometrica, 50(4).

Fama, E.F., & French, K.R. (1992). The Cross-Section of Expected Stock Returns. Journal of Finance, 47(2).

Hamilton, J.D. (1989). A New Approach to the Economic Analysis of Nonstationary Time Series and the Business Cycle. Econometrica, 57(2).

Jegadeesh, N., & Titman, S. (1993). Returns to Buying Winners and Selling Losers: Implications for Stock Market Efficiency. Journal of Finance, 48(1).

Kindleberger, C.P. (1978). Manias, Panics, and Crashes: A History of Financial Crises. Basic Books.

Lo, A.W., & MacKinlay, A.C. (1990). Data-Snooping Biases in Tests of Financial Asset Pricing Models. Review of Financial Studies, 3(3).

Longin, F., & Solnik, B. (2001). Extreme Correlation of International Equity Markets. Journal of Finance, 56(2).

Rabiner, L.R. (1989). A Tutorial on Hidden Markov Models and Selected Applications in Speech Recognition. Proceedings of the IEEE, 77(2).

Shiller, R.J. (2000). Irrational Exuberance. Princeton University Press.

Taleb, N.N. (2007). The Black Swan: The Impact of the Highly Improbable. Random House.

Taleb, N.N., & Douady, R. (2012). Mathematical Definition, Mapping, and Detection of (Anti)Fragility. Quantitative Finance, 13(11).

Declinazione di responsabilità

Le informazioni e le pubblicazioni non sono intese come, e non costituiscono, consulenza o raccomandazioni finanziarie, di investimento, di trading o di altro tipo fornite o approvate da TradingView. Per ulteriori informazioni, consultare i Termini di utilizzo.