Recession Warning Model [BackQuant]Recession Warning Model
Overview
The Recession Warning Model (RWM) is a Pine Script® indicator designed to estimate the probability of an economic recession by integrating multiple macroeconomic, market sentiment, and labor market indicators. It combines over a dozen data series into a transparent, adaptive, and actionable tool for traders, portfolio managers, and researchers. The model provides customizable complexity levels, display modes, and data processing options to accommodate various analytical requirements while ensuring robustness through dynamic weighting and regime-aware adjustments.
Purpose
The RWM fulfills the need for a concise yet comprehensive tool to monitor recession risk. Unlike approaches relying on a single metric, such as yield-curve inversion, or extensive economic reports, it consolidates multiple data sources into a single probability output. The model identifies active indicators, their confidence levels, and the current economic regime, enabling users to anticipate downturns and adjust strategies accordingly.
Core Features
- Indicator Families : Incorporates 13 indicators across five categories: Yield, Labor, Sentiment, Production, and Financial Stress.
- Dynamic Weighting : Adjusts indicator weights based on recent predictive accuracy, constrained within user-defined boundaries.
- Leading and Coincident Split : Separates early-warning (leading) and confirmatory (coincident) signals, with adjustable weighting (default 60/40 mix).
- Economic Regime Sensitivity : Modulates output sensitivity based on market conditions (Expansion, Late-Cycle, Stress, Crisis), using a composite of VIX, yield-curve, financial conditions, and credit spreads.
- Display Options : Supports four modes—Probability (0-100%), Binary (four risk bins), Lead/Coincident, and Ensemble (blended probability).
- Confidence Intervals : Reflects model stability, widening during high volatility or conflicting signals.
- Alerts : Configurable thresholds (Watch, Caution, Warning, Alert) with persistence filters to minimize false signals.
- Data Export : Enables CSV output for probabilities, signals, and regimes, facilitating external analysis in Python or R.
Model Complexity Levels
Users can select from four tiers to balance simplicity and depth:
1. Essential : Focuses on three core indicators—yield-curve spread, jobless claims, and unemployment change—for minimalistic monitoring.
2. Standard : Expands to nine indicators, adding consumer confidence, PMI, VIX, S&P 500 trend, money supply vs. GDP, and the Sahm Rule.
3. Professional : Includes all 13 indicators, incorporating financial conditions, credit spreads, JOLTS vacancies, and wage growth.
4. Research : Unlocks all indicators plus experimental settings for advanced users.
Key Indicators
Below is a summary of the 13 indicators, their data sources, and economic significance:
- Yield-Curve Spread : Difference between 10-year and 3-month Treasury yields. Negative spreads signal banking sector stress.
- Jobless Claims : Four-week moving average of unemployment claims. Sustained increases indicate rising layoffs.
- Unemployment Change : Three-month change in unemployment rate. Sharp rises often precede recessions.
- Sahm Rule : Triggers when unemployment rises 0.5% above its 12-month low, a reliable recession indicator.
- Consumer Confidence : University of Michigan survey. Declines reflect household pessimism, impacting spending.
- PMI : Purchasing Managers’ Index. Values below 50 indicate manufacturing contraction.
- VIX : CBOE Volatility Index. Elevated levels suggest market anticipation of economic distress.
- S&P 500 Growth : Weekly moving average trend. Declines reduce wealth effects, curbing consumption.
- M2 + GDP Trend : Monitors money supply and real GDP. Simultaneous declines signal credit contraction.
- NFCI : Chicago Fed’s National Financial Conditions Index. Positive values indicate tighter conditions.
- Credit Spreads : Proxy for corporate bond spreads using 10-year vs. 2-year Treasury yields. Widening spreads reflect stress.
- JOLTS Vacancies : Job openings data. Significant drops precede hiring slowdowns.
- Wage Growth : Year-over-year change in average hourly earnings. Late-cycle spikes often signal economic overheating.
Data Processing
- Rate of Change (ROC) : Optionally applied to capture momentum in data series (default: 21-bar period).
- Z-Score Normalization : Standardizes indicators to a common scale (default: 252-bar lookback).
- Smoothing : Applies a short moving average to final signals (default: 5-bar period) to reduce noise.
- Binary Signals : Generated for each indicator (e.g., yield-curve inverted or PMI below 50) based on thresholds or Z-score deviations.
Probability Calculation
1. Each indicator’s binary signal is weighted according to user settings or dynamic performance.
2. Weights are normalized to sum to 100% across active indicators.
3. Leading and coincident signals are aggregated separately (if split mode is enabled) and combined using the specified mix.
4. The probability is adjusted by a regime multiplier, amplifying risk during Stress or Crisis regimes.
5. Optional smoothing ensures stable outputs.
Display and Visualization
- Probability Mode : Plots a continuous 0-100% recession probability with color gradients and confidence bands.
- Binary Mode : Categorizes risk into four levels (Minimal, Watch, Caution, Alert) for simplified dashboards.
- Lead/Coincident Mode : Displays leading and coincident probabilities separately to track signal divergence.
- Ensemble Mode : Averages traditional and split probabilities for a balanced view.
- Regime Background : Color-coded overlays (green for Expansion, orange for Late-Cycle, amber for Stress, red for Crisis).
- Analytics Table : Optional dashboard showing probability, confidence, regime, and top indicator statuses.
Practical Applications
- Asset Allocation : Adjust equity or bond exposures based on sustained probability increases.
- Risk Management : Hedge portfolios with VIX futures or options during regime shifts to Stress or Crisis.
- Sector Rotation : Shift toward defensive sectors when coincident signals rise above 50%.
- Trading Filters : Disable short-term strategies during high-risk regimes.
- Event Timing : Scale positions ahead of high-impact data releases when probability and VIX are elevated.
Configuration Guidelines
- Enable ROC and Z-score for consistent indicator comparison unless raw data is preferred.
- Use dynamic weighting with at least one economic cycle of data for optimal performance.
- Monitor stress composite scores above 80 alongside probabilities above 70 for critical risk signals.
- Adjust adaptation speed (default: 0.1) to 0.2 during Crisis regimes for faster indicator prioritization.
- Combine RWM with complementary tools (e.g., liquidity metrics) for intraday or short-term trading.
Limitations
- Macro indicators lag intraday market moves, making RWM better suited for strategic rather than tactical trading.
- Historical data availability may constrain dynamic weighting on shorter timeframes.
- Model accuracy depends on the quality and timeliness of economic data feeds.
Final Note
The Recession Warning Model provides a disciplined framework for monitoring economic downturn risks. By integrating diverse indicators with transparent weighting and regime-aware adjustments, it empowers users to make informed decisions in portfolio management, risk hedging, or macroeconomic research. Regular review of model outputs alongside market-specific tools ensures its effective application across varying market conditions.
Interestrates
FEDFUNDS Rate Divergence Oscillator [BackQuant]FEDFUNDS Rate Divergence Oscillator
1. Concept and Rationale
The United States Federal Funds Rate is the anchor around which global dollar liquidity and risk-free yield expectations revolve. When the Fed hikes, borrowing costs rise, liquidity tightens and most risk assets encounter head-winds. When it cuts, liquidity expands, speculative appetite often recovers. Bitcoin, a 24-hour permissionless asset sometimes described as “digital gold with venture-capital-like convexity,” is particularly sensitive to macro-liquidity swings.
The FED Divergence Oscillator quantifies the behavioural gap between short-term monetary policy (proxied by the effective Fed Funds Rate) and Bitcoin’s own percentage price change. By converting each series into identical rate-of-change units, subtracting them, then optionally smoothing the result, the script produces a single bounded-yet-dynamic line that tells you, at a glance, whether Bitcoin is outperforming or underperforming the policy backdrop—and by how much.
2. Data Pipeline
• Fed Funds Rate – Pulled directly from the FRED database via the ticker “FRED:FEDFUNDS,” sampled at daily frequency to synchronise with crypto closes.
• Bitcoin Price – By default the script forces a daily timeframe so that both series share time alignment, although you can disable that and plot the oscillator on intraday charts if you prefer.
• User Source Flexibility – The BTC series is not hard-wired; you can select any exchange-specific symbol or even swap BTC for another crypto or risk asset whose interaction with the Fed rate you wish to study.
3. Math under the Hood
(1) Rate of Change (ROC) – Both the Fed rate and BTC close are converted to percent return over a user-chosen lookback (default 30 bars). This means a cut from 5.25 percent to 5.00 percent feeds in as –4.76 percent, while a climb from 25 000 to 30 000 USD in BTC over the same window converts to +20 percent.
(2) Divergence Construction – The script subtracts the Fed ROC from the BTC ROC. Positive values show BTC appreciating faster than policy is tightening (or falling slower than the rate is cutting); negative values show the opposite.
(3) Optional Smoothing – Macro series are noisy. Toggle “Apply Smoothing” to calm the line with your preferred moving-average flavour: SMA, EMA, DEMA, TEMA, RMA, WMA or Hull. The default EMA-25 removes day-to-day whips while keeping turning points alive.
(4) Dynamic Colour Mapping – Rather than using a single hue, the oscillator line employs a gradient where deep greens represent strong bullish divergence and dark reds flag sharp bearish divergence. This heat-map approach lets you gauge intensity without squinting at numbers.
(5) Threshold Grid – Five horizontal guides create a structured regime map:
• Lower Extreme (–50 pct) and Upper Extreme (+50 pct) identify panic capitulations and euphoria blow-offs.
• Oversold (–20 pct) and Overbought (+20 pct) act as early warning alarms.
• Zero Line demarcates neutral alignment.
4. Chart Furniture and User Interface
• Oscillator fill with a secondary DEMA-30 “shader” offers depth perception: fat ribbons often precede high-volatility macro shifts.
• Optional bar-colouring paints candles green when the oscillator is above zero and red below, handy for visual correlation.
• Background tints when the line breaches extreme zones, making macro inflection weeks pop out in the replay bar.
• Everything—line width, thresholds, colours—can be customised so the indicator blends into any template.
5. Interpretation Guide
Macro Liquidity Pulse
• When the oscillator spends weeks above +20 while the Fed is still raising rates, Bitcoin is signalling liquidity tolerance or an anticipatory pivot view. That condition often marks the embryonic phase of major bull cycles (e.g., March 2020 rebound).
• Sustained prints below –20 while the Fed is already dovish indicate risk aversion or idiosyncratic crypto stress—think exchange scandals or broad flight to safety.
Regime Transition Signals
• Bullish cross through zero after a long sub-zero stint shows Bitcoin regaining upward escape velocity versus policy.
• Bearish cross under zero during a hiking cycle tells you monetary tightening has finally started to bite.
Momentum Exhaustion and Mean-Reversion
• Touches of +50 (or –50) come rarely; they are statistically stretched events. Fade strategies either taking profits or hedging have historically enjoyed positive expectancy.
• Inside-bar candlestick patterns or lower-timeframe bearish engulfings simultaneously with an extreme overbought print make high-probability short scalp setups, especially near weekly resistance. The same logic mirrors for oversold.
Pair Trading / Relative Value
• Combine the oscillator with spreads like BTC versus Nasdaq 100. When both the FED Divergence oscillator and the BTC–NDQ relative-strength line roll south together, the cross-asset confirmation amplifies conviction in a mean-reversion short.
• Swap BTC for miners, altcoins or high-beta equities to test who is the divergence leader.
Event-Driven Tactics
• FOMC days: plot the oscillator on an hourly chart (disable ‘Force Daily TF’). Watch for micro-structural spikes that resolve in the first hour after the statement; rapid flips across zero can front-run post-FOMC swings.
• CPI and NFP prints: extremes reached into the release often mean positioning is one-sided. A reversion toward neutral in the first 24 hours is common.
6. Alerts Suite
Pre-bundled conditions let you automate workflows:
• Bullish / Bearish zero crosses – queue spot or futures entries.
• Standard OB / OS – notify for first contact with actionable zones.
• Extreme OB / OS – prime time to review hedges, take profits or build contrarian swing positions.
7. Parameter Playground
• Shorten ROC Lookback to 14 for tactical traders; lengthen to 90 for macro investors.
• Raise extreme thresholds (for example ±80) when plotting on altcoins that exhibit higher volatility than BTC.
• Try HMA smoothing for responsive yet smooth curves on intraday charts.
• Colour-blind users can easily swap bull and bear palette selections for preferred contrasts.
8. Limitations and Best Practices
• The Fed Funds series is step-wise; it only changes on meeting days. Rapid BTC oscillations in between may dominate the calculation. Keep that perspective when interpreting very high-frequency signals.
• Divergence does not equal causation. Crypto-native catalysts (ETF approvals, hack headlines) can overwhelm macro links temporarily.
• Use in conjunction with classical confirmation tools—order-flow footprints, market-profile ledges, or simple price action to avoid “pure-indicator” traps.
9. Final Thoughts
The FEDFUNDS Rate Divergence Oscillator distills an entire macro narrative monetary policy versus risk sentiment into a single colourful heartbeat. It will not magically predict every pivot, yet it excels at framing market context, spotting stretches and timing regime changes. Treat it as a strategic compass rather than a tactical sniper scope, combine it with sound risk management and multi-factor confirmation, and you will possess a robust edge anchored in the world’s most influential interest-rate benchmark.
Trade consciously, stay adaptive, and let the policy-price tension guide your roadmap.
Interest Rate Trading (Manually Added Rate Decisions) [TANHEF]Interest Rate Trading: How Interest Rates Can Guide Your Next Move.
How were interest rate decisions added?
All interest rate decision dates were manually retrieved from the 'Record of Policy Actions' and 'Minutes of Actions' on the Federal Reserve's website due to inconsistent dates from other sources. These were manually added as Pine Script currently only identifies rate changes, not pauses.
█ Simple Explanation:
This script is designed for analyzing and backtesting trading strategies based on U.S. interest rate decisions which occur during Federal Open Market Committee (FOMC) meetings, to make trading decisions. No trading strategy is perfect, and it's important to understand that expectations won't always play out. The script leverages historical interest rate changes, including increases, decreases, and pauses, across multiple economic time periods from 1971 to the present. The tool integrates two key data sources for interest rates—USINTR and FEDFUNDS—to support decision-making around rate-based trades. The focus is on identifying opportunities and tracking trades driven by interest rate movements.
█ Interest Rate Decision Sources:
As noted above, each decision date has been manually added from the 'Record of Policy Actions' and 'Minutes of Actions' documents on the Federal Reserve's website. This includes +50 years of more than 600 rate decisions.
█ Interest Rate Data Sources:
USINTR: Reflects broader U.S. interest rate trends, including Treasury yields and various benchmarks. This is the preferred option as it corresponds well to the rate decision dates.
FEDFUNDS: Tracks the Federal Funds Rate, which is a more specific rate targeted by the Federal Reserve. This does not change on the exact same days as the rate decisions that occur at FOMC meetings.
█ Trade Criteria:
A variety of trading conditions are predefined to suit different trading strategies. These conditions include:
Increase/Decrease: Standard rate increases or decreases.
Double/Triple Increase/Decrease: A series of consecutive changes.
Aggressive Increase/Decrease: Rate changes that exceed recent movements.
Pause: Identification of no changes (pauses) between rate decisions, including double or triple pauses.
Complex Patterns: Combinations of pauses, increases, or decreases, such as "Pause after Increase" or "Pause or Increase."
█ Trade Execution and Exit:
The script allows automated trade execution based on selected criteria:
Auto-Entry: Option to enter trades automatically at the first valid period.
Max Trade Duration: Optional exit of trades after a specified number of bars (candles).
Pause Days: Minimum duration (in days) to validate rate pauses as entry conditions. This is especially useful for earlier periods (prior to the 2000s), where rate decisions often seemed random compared to the consistency we see today.
█ Visualization:
Several visual elements enhance the backtesting experience:
Time Period Highlighting: Economic time periods are visually segmented on the chart, each with a unique color. These periods include historical phases such as "Stagflation (1971-1982)" and "Post-Pandemic Recovery (2021-Present)".
Trade and Holding Results: Displays the profit and loss of trades and holding results directly on the chart.
Interest Rate Plot: Plots the interest rate movements on the chart, allowing for real-time tracking of rate changes.
Trade Status: Highlights active long or short positions on the chart.
█ Statistics and Criteria Display:
Stats Table: Summarizes trade results, including wins, losses, and draw percentages for both long and short trades.
Criteria Table: Lists the selected entry and exit criteria for both long and short positions.
█ Economic Time Periods:
The script organizes interest rate decisions into well-defined economic periods, allowing traders to backtest strategies specific to historical contexts like:
(1971-1982) Stagflation
(1983-1990) Reaganomics and Deregulation
(1991-1994) Early 1990s (Recession and Recovery)
(1995-2001) Dot-Com Bubble
(2001-2006) Housing Boom
(2007-2009) Global Financial Crisis
(2009-2015) Great Recession Recovery
(2015-2019) Normalization Period
(2019-2021) COVID-19 Pandemic
(2021-Present) Post-Pandemic Recovery
█ User-Configurable Inputs:
Rate Source Selection: Choose between USINTR or FEDFUNDS as the primary interest rate source.
Trade Criteria Customization: Users can select the criteria for long and short trades, specifying when to enter or exit based on changes in the interest rate.
Time Period: Select the time period that you want to isolate testing a strategy with.
Auto-Entry and Pause Settings: Options to automatically enter trades and specify the number of days to confirm a rate pause.
Max Trade Duration: Limits how long trades can remain open, defined by the number of bars.
█ Trade Logic:
The script manages entries and exits for both long and short trades. It calculates the profit or loss percentage based on the entry and exit prices. The script tracks ongoing trades, dynamically updating the profit or loss as price changes.
█ Examples:
One of the most popular opinions is that when rate starts begin you should sell, then buy back in when rate cuts stop dropping. However, this can be easily proven to be a difficult task. Predicting the end of a rate cut is very difficult to do with the the exception that assumes rates will not fall below 0.25%.
2001-2009
Trade Result: +29.85%
Holding Result: -27.74%
1971-2024
Trade Result: +533%
Holding Result: +5901%
█ Backtest and Real-Time Use:
This backtester is useful for historical analysis and real-time trading. By setting up various entry and exit rules tied to interest rate movements, traders can test and refine strategies based on real historical data and rate decision trends.
This powerful tool allows traders to customize strategies, backtest them through different economic periods, and get visual feedback on their trading performance, helping to make more informed decisions based on interest rate dynamics. The main goal of this indicator is to challenge the belief that future events must mirror the 2001 and 2007 rate cuts. If everyone expects something to happen, it usually doesn’t.
Historical Fed Interest rate This script is Historical Fed Interest rate
The data is between 1991 - 2023 , but for some reason data between 1991 - 10/2001 is not work
Green line for rate cut and Red line for rate hike and detail at the label
Forex Macro Metrics [MacroGlide]"Forex Macro Metrics " is a powerful tool for analyzing macroeconomic metrics, designed to help traders make more informed decisions in the forex market. This indicator displays key economic indicators such as interest rates, money supply (M1 and M2), unemployment rate, and government debt for various currencies and their pairs, allowing users to assess the macroeconomic differences between the base and quote currencies.
Key Features:
• Interest Rates Display: Includes interest rates for major world currencies with the ability to show the differential between the base and quote currencies.
• Money Supply Analysis (M1 and M2): Displays the money supply for both the base and quote currencies, including differential calculations.
• Unemployment Rate: Compares the unemployment rates between currencies, showing the differences on the chart.
• Government Debt: Shows government debt levels for the base and quote currencies with differential calculations.
• Customizable Options: Enable/disable specific metrics and adjust colors for better visual clarity.
How to Use:
• Select a Currency Pair: Apply the indicator to your chart and choose the desired currency pair. The indicator will automatically load the relevant data for the base and quote currencies.
• Adjust Display Settings: Use the indicator settings to enable or disable specific metrics and their differentials.
• Analyze the Data: Compare the economic conditions of the two currencies through the charts and identify potential trading opportunities based on macroeconomic differences.
Methodology:
The indicator uses economic data available through TradingView tickers to calculate the values of the base and quote currencies. Differentials are calculated by subtracting the values of the quote currency from the base currency, allowing for a visual assessment of their differences. The displayed data includes historical changes, helping to identify trends and potential reversal points.
Originality and Usefulness:
"Forex Macro Metrics " is a unique tool that combines several key macroeconomic indicators into one comprehensive indicator. This simplifies the analysis process for traders looking to understand the fundamental differences between currencies. Using this approach provides an advantage in assessing long-term trends and potential shifts in currency pairs driven by changes in macroeconomic conditions.
Charts:
The indicator displays data in the form of lines and areas on the chart, with interest rates shown as lines for the base and quote currencies, accompanied by an area representing the differential. For money supply (M1 and M2), lines are drawn for each currency, with areas highlighting the differences. Similarly, the unemployment rate and government debt are displayed with clear visual separation of the data and their differentials, making it easy to compare and analyze the macroeconomic conditions of the currencies involved.
Enjoy the game!
Yield Curve SpaghettiDisplays the difference in yield between multiple bond pairs for a given country.
Currently supports US, DE, and GB bonds
Interest Rate IndicatorThis script offers a overview of Year-over-Year (YoY) interest rates for key countries. The interest rate data utilized by default are sourced from TradingView Tickers, but they can be modified to any preferred source via the settings.
The script does not perform any calculations; its primary function is to present a comparative view of interest rates across different countries in a single indicator.
Key features include:
Interest rate data for the USA, European Union, Australia, Canada, Switzerland, Japan, United Kingdom, and New Zealand (Interest Rate Symbols are editable in the settings).
A table displaying country flags, names, and the latest interest rates, providing a clear and immediate comparison.
Country-representative colors for easy identification and visual distinction between different countries' data.
This indicator is designed for traders and analysts looking for a quick and efficient way to monitor and compare the interest rates of major economies directly within TradingView, facilitating better informed financial and investment decisions.
interest rate gap for forexThis indicator is useful for forex traders.
This script displays interest rate differentials and customizable durations for about 180 currencies.
In general, when interest rate differentials widen, traders tend to buy currencies with higher interest rates.
Interest Rates [WhaleCrew]This indicator allows you to display the interest rates of multiple central banks (US, EU, China, Russia, Japan, UK, ...) at once.
Built-in Interest Rates
US ECONOMICS:USINTR
EU ECONOMICS:EUINTR
China ECONOMICS:CNINTR
Russia ECONOMICS:RUINTR
Japan ECONOMICS:JPINTR
UK ECONOMICS:GBINTR
Custom Symbol (default: ECONOMICS:CHINTR )
All Central Bank Interest RatesWith another period of mass interest rates manipulation, I created this indicator to show them all. It reveals latest interest ratest (at a time of the last update) and a date when each central bank manipulated the rates.
If you would rather view a single pair data check: and
Interest Rates | USA / EU / UKThis script shows the Interest Rates of the USA, EU and UK.
USA = Red
EU = Blue
UK = White
Central Bank Interest RatesThis indicator will show central bank interest rates on any major currency pairs.
I included the last 10 values for the study and will update them with future changes.
Major currencies: USD, CAD, NZD, AUD, JPY, EUR, CHF, GBP
I might add CZK, TRY, ZAR, and Yuan in the future.
Table: Forex Central Bank Interest RatesThis tool shows CB Interest Rates for USD, JPY, CAD, CHF, EUR, GBP, NZD, AUD - basically all the majors.
Use override and input your own value if it is changed and I haven't updated the script yet.
Real Interest Rate DifferentialThe Real IRD is a simple indicator built for forex trades that need a long-term view and want to compare currencies in search of high yield. The indicated interest rate maturity is 2 years, since shorter maturities may not price central banks' monetary policy decisions.
Example:
- You need to do an analysis of the AUDUSD
- In the Interest Rate 1 field, we put the interest rate for the base currency, in this case the AUD
- In the Interest Rate 2 field, the interest rate of the other currency, in this case the USD
- In the CPI 1 field, inflation referring to base currency
- In the CPI 2 field, inflation for another currency
CPI Codes:
QUANDL:RATEINF/INFLATION_USA < USD
QUANDL:RATEINF/INFLATION_EUR < EUR
QUANDL:RATEINF/INFLATION_JPN < JPY
QUANDL:RATEINF/INFLATION_CHE < CHF
QUANDL:RATEINF/INFLATION_GBR < GBP
QUANDL:RATEINF/INFLATION_CAN < CAD
QUANDL:RATEINF/INFLATION_RUS < RUB
QUANDL:RATEINF/INFLATION_AUS < AUD
QUANDL:RATEINF/INFLATION_NZL < NZD