OPEN-SOURCE SCRIPT

Gold Dual-Model Fair Value [Regime Adaptive]

153
OVERVIEW

Gold Dual-Model Fair Value [Regime Adaptive] is a chart overlay that plots two competing fair value estimates for gold, one regressed on the 10 year real yield and one regressed on a global M2 money supply composite, then combines them into a single fair value line by continuously measuring which model currently fits better. The thesis: gold's dominant macro driver is not constant, so a useful fair value model must detect the driver in force rather than assume it.


HISTORY / BACKGROUND

The inverse relationship between gold and real interest rates is one of the most widely documented regularities in the asset's modern history and is treated in academic work such as Erb and Harvey's "The Golden Dilemma" (2013). That relationship visibly weakened after 2022, when gold rose while real yields climbed to multi year highs, a divergence commonly attributed to price insensitive official sector buying. Macro strategists, notably Jurrien Timmer, have illustrated this as a regime change in which a real yield model stops explaining gold and a global liquidity model takes over.

The weakness of that illustration is that the regime break is declared after the fact, by inspection. This script's contribution is to make the regime decision endogenous: both models are estimated continuously, and the model in force is chosen by trailing out of sample fit, with no hardcoded break date. The regime change around 2022, if present in the data, emerges from the computation rather than being asserted.


HOW IT WORKS

All computation runs on the chart timeframe. The script requests the following series with request.security at the chart resolution, with no lookahead: FRED:DFII10 (10 year TIPS real yield), five M2 series (ECONOMICS:USM2, CNM2, EUM2, JPM2, GBM2) and four conversion rates (FX_IDC:CNYUSD, EURUSD, JPYUSD, GBPUSD).

Step 1. Global M2 composite. Each enabled non US component is converted to US dollars and the enabled components are summed. Two aggregation modes exist. Spot FX converts at the current exchange rate, replicating the standard global liquidity composite. Constant FX converts every bar at the rate captured on the first bar at or after a user defined anchor date, which freezes the currency translation effect and isolates changes in underlying money stocks. The composite is na until every enabled component has data, so its membership never changes mid history and no artificial level jumps are introduced.

Step 2. Two rolling regressions. Over a rolling fit window the script estimates ordinary least squares coefficients from running moments (beta equals covariance over variance, alpha equals mean of y minus beta times mean of x):

• Model A regresses the natural log of the chart close on the level of the 10 year real yield.
• Model B regresses the natural log of the chart close on the natural log of the M2 composite.

Each model produces a log fair value each bar from its current alpha, beta and regressor value.

Step 3. Fit measurement. Each model's residual (log price minus log fair value) is squared and averaged over a shorter trailing evaluation window; the square root is that model's rolling RMSE.

Step 4. Regime and combination. Two output modes:

• Blend (default): the combined log fair value is a weighted average of the two model fair values with weights proportional to inverse RMSE, so the better fitting model dominates smoothly.
• Hard switch: the combined fair value is the fair value of the incumbent model, and the incumbent only changes when the challenger's RMSE beats it by a user set hysteresis margin, which prevents rapid flip flopping when the models fit similarly.

Independently of the mode, the hard switch state machine always runs and its current state is reported in the table and as the background tint, so blend users can still see the discrete regime call.

Step 5. Deviation statistics. The deviation is log price minus combined log fair value. Its rolling standard deviation over the evaluation window defines a z score, and bands are drawn at the fair value times e to the plus and minus (band multiple times sigma). The z score's percent rank over a user defined lookback gives a deviation percentile.

If one model's inputs are unavailable (for example the M2 composite before all enabled components exist), the combined fair value falls back to the available model alone.


HOW TO USE

Apply the indicator to a gold chart (spot, futures or a fund proxy) on the weekly timeframe. Weekly is the design resolution for a structural reason: the M2 inputs are monthly series, so on lower resolutions the liquidity regressor is a long staircase while the real yield updates daily, which biases the fit comparison toward the real yield model for reasons unrelated to explanatory power. The default windows (156 and 52 bars) are calibrated as roughly three years and one year of weekly bars. An on chart warning label appears on intraday charts.

Visual elements:

• Orange line: the combined fair value, the primary output.
• Blue thin line: Model A fair value (real yields). Red thin line: Model B fair value (global liquidity). Comparing their paths shows where each model succeeded or failed.
• Gray bands and fill: the plus and minus sigma envelope around the combined fair value. Price above the upper band is statistically rich against the currently fitting model mix, below the lower band statistically cheap, between the bands unremarkable.
• Background tint: blue when the hard switch regime is the real yield model, red when it is the liquidity model.
• Status table: hard switch regime, active mode, each model's RMSE, the real yield model's blend weight, the deviation z score (colored when beyond the band multiple), its percentile, and the M2 aggregation mode.

Interpretation cautions. The fair value is a rolling fit, so a deviation can close either by price moving toward the line or by the line re estimating toward price; a band touch is a valuation observation, not a mechanical entry signal. The regime readout tells you which catalyst matters: in the liquidity regime, a cheap reading resolves with money supply reacceleration rather than falling yields. Comparing Spot FX and Constant FX modes shows how much of the liquidity signal is currency translation rather than money creation; if a stretched reading shrinks materially under Constant FX, part of it was the US dollar itself.


SETTINGS

Model group:

• Regression fit window (bars), default 156: the rolling OLS estimation window for both models.
• Fit evaluation window (bars), default 52: the trailing window for RMSE, regime detection and deviation sigma.
• Regime mode, default Blend (inverse RMSE weights): selects between the blended fair value and the hard switch fair value.
• Switch hysteresis (%), default 10: hard switch mode only, the margin by which the challenger RMSE must beat the incumbent before the regime flips.
• Deviation band (sigma), default 2.0: the band multiple and the z score threshold for table coloring.
• Deviation percentile lookback (bars), default 260: the window for the z score percent rank.

Global M2 composite group:

• FX aggregation, default Spot FX: Spot FX or Constant FX (anchor date), as described above.
• Constant FX anchor date, default 1 January 2018: the date whose exchange rates are frozen in Constant FX mode.
• US M2, China M2, Eurozone M2, Japan M2, UK M2, all enabled by default: component toggles. Disabling a short history component lets the composite, and therefore Model B, begin earlier.

Display group:

• Show individual model lines, default on.
• Show deviation bands, default on.
• Show status table, default on.
• Regime background tint, default on.
• Table position, default top right.


WHAT MAKES IT ORIGINAL

Published global M2 composites plot the liquidity series itself, usually with a fixed time offset against an asset, and published regime indicators classify price behavior such as trending versus ranging. This script occupies a different intersection and does three things no script in either group does:

• It converts both macro drivers into explicit fair value estimates via rolling least squares regression rather than displaying the raw series, so the drivers and the asset live on the same axis and disagreement between them is measurable in price terms.
• It selects or weights the two models by trailing out of sample RMSE, so the widely discussed post 2022 handoff from real yields to liquidity is detected by the data instead of hardcoded, and any future handoff back requires no code change.
• Its liquidity composite offers a Constant FX aggregation mode alongside the standard Spot FX mode. Spot converted composites embed the US dollar's own fluctuations, which are correlated with gold, into the liquidity measure. The Constant FX mode removes that translation effect, giving users a built in test of how much of the liquidity signal is monetary and how much is currency denomination. To this author's knowledge no published composite exposes this distinction.


NOTES / LIMITATIONS

• The M2 inputs are monthly economic series requested at the chart resolution. They hold their value between releases, so the liquidity fair value moves in steps between prints, and releases arrive with publication lag.
• Economic series are subject to vendor revisions. A revised M2 or real yield history changes the regression inputs, so the historical fair value shown today can differ from what the script displayed in real time. This is a property of the data, not lookahead: the script uses no lookahead and requests no timeframe above the chart's.
• Model B is na until every enabled M2 component and its conversion rate have history, and each regression additionally needs the full fit window plus evaluation window of bars before its output and RMSE are defined. On deep weekly gold history the real yield model also cannot begin before the real yield series itself starts in 2003. Expect a substantial warm up period at the left edge of the chart, during which the script falls back to whichever single model is available, or plots nothing.
• The logic is designed for the weekly timeframe. On daily and lower resolutions the mixed update frequencies of the regressors distort the fit comparison, the default windows lose their intended calendar meaning, and an on chart label warns on intraday charts.
• The script uses the chart symbol's close as the dependent variable. Its economic reasoning applies to gold denominated symbols; applied to unrelated symbols it will still compute, but the output has no stated meaning.
• The fair value lines are descriptive regression fits over past data. They quantify the historical relationship between gold and each driver and say nothing about future prices.

Отказ от ответственности

Информация и публикации не предназначены для предоставления и не являются финансовыми, инвестиционными, торговыми или другими видами советов или рекомендаций, предоставленных или одобренных TradingView. Подробнее читайте в Условиях использования.