PulseHub
OPEN-SOURCE SCRIPT

Correlation Matrix [AFD]

314
Correlation Matrix [AFD] turns the active chart into a one-to-many cross-asset relationship monitor. It compares the chart symbol with up to eight instruments and brings slower and faster return correlation, fitted return sensitivity, matched spread distance, pair-specific correlation history, and data availability into one dashboard.

It is designed to answer practical research questions: Which selected markets have been moving with or against the chart symbol? Has recent co-movement departed from the slower relationship? How sensitive has the chart symbol been to each comparison? Is the matched spread unusually displaced for that pair? Is the reading supported by enough shared observations to interpret responsibly?

Built-in Symbol sets and Measurement presets provide repeatable samples. A Measurement preset selects a requested timeframe and Long/Short windows; it never changes the chart candles or requires a matching chart timeframe. Custom can follow the chart or request a fixed measurement timeframe. Optional rebased lines use a separate visual baseline. All outputs are descriptive measurements, not automated decisions.

What It Is Useful For

*Cross-asset mapping: Place an index, sector, currency, commodity, rate-sensitive instrument, volatility index, or digital asset on the chart and compare it with a preset universe or a Custom basket. This helps organize intermarket context around one common reference symbol.

*Relationship-change monitoring: Treat Long Correlation as the slower context sample and Short Correlation as the faster sample. Correlation Difference shows how far the faster coefficient sits above or below the slower one, while the two coefficients preserve their direction and sign. It is a comparison of two estimates, not a formal regime or significance test.

*Benchmark and proxy research: Compare correlation with Beta to separate consistency of co-movement from fitted magnitude of response. This can help screen which selected benchmark, sector, or macro proxy has historically had the closest relationship to the chart symbol. It is not factor attribution.

*Candidate-hedge research: Screen for relationships that have been negative across the selected windows, then use Beta and Data Coverage as sensitivity and sample context. The output can narrow further research; it does not select a hedge, calculate contract quantities, or account for liquidity, basis, carry, costs, or portfolio constraints.

*Relative-value triage: Use Spread to identify a matched relationship that is unusually displaced from its own Long-window average, then use correlation, History, and usable-sample counts to judge whether the observation deserves investigation. Spread is not a cointegration test, regression residual, stationarity test, or mean-reversion forecast.

*Exposure-overlap review: Chart one holding at a time against a Custom basket to identify potentially redundant co-movement or sensitivity. This is useful for screening concentration questions, but it is not a portfolio covariance engine or risk model.

*Sample-integrity review: Read Data Coverage and the usable Long/Short return counts before interpreting a coefficient, especially across different sessions, holidays, young listings, or sparse feeds. These are availability disclosures, not confidence or quality scores.

*Event and baseline comparison: Rebase percentage paths from Session Open, Rolling N Bars, Year Open, or a Fixed Date to inspect divergence after a session boundary, calendar reset, or chosen event. These chart lines are visual comparisons and never feed the statistics.

Capabilities

snapshot

*Eight configurable comparison slots. In Custom mode, each slot has a symbol, optional display name, color, Enabled switch, and Show comparison line switch. Blank slots remain hidden; an invalid or unavailable symbol displays No data without stopping valid rows.

*Five built-in Symbol sets: United States Indices, Risk On / Off, Major Foreign Exchange Pairs, Energy & Metals, and Crypto. Custom values are retained while a set temporarily supplies eight symbols and ticker-derived names. Risk On / Off supplies comparison instruments; it does not classify the market.

*Three Measurement presets plus Custom: Scalper requests 1 minute with Long 60 / Short 15; default Intraday requests 5 minutes with Long 78 / Short 20; Swing requests 1 day with Long 120 / Short 20. Swing on a 30-minute chart is an intended configuration, not an error: chart candles remain 30 minutes while completed 1-day observations drive measurements. Custom exposes the timeframe and both windows.

*Long Correlation, Short Correlation, Main Correlation, Correlation Difference, Long-window Beta, signed Spread z-score, optional History percentile, and Data Coverage. Tooltips disclose usable Long/Short returns and fresh-versus-eligible coverage counts.

*Contextual hover help on every dashboard heading and cell. It explains metric definitions, sample requirements, and unavailable states, with additional detail for Beta direction and fitted sensitivity, active Spread form and position, History's prior range and average, and Data Coverage endpoint counts.

*Context, Compact, Full, Minimal, and Custom dashboard views; an independent Correlation Difference switch; custom column overrides; nine table positions; slot, absolute Long Correlation, or absolute Spread sorting; and Heat or Mono cells.

*Optional rebased comparison lines with Auto from measurement preset, Session Open, Rolling N Bars, Year Open, and Fixed Date baselines. Seven appearances, a shared baseline marker, configurable line-end labels, and one-slot gap shading are included.

*Separate dashboard and comparison-line visibility switches. Measurements continue while either visual layer is hidden. Status text identifies chart and effective measurement timeframes; its tooltip also identifies the requested timeframe, completed higher-timeframe sampling, lower-timeframe fallback, active windows, adjusted Short window, and visual line baseline.

*Dashboard text, colors, backgrounds, transparency, alternating rows, borders, frame, line width/transparency, marker styling, label styling, gap colors, and a global master-opacity control can be adjusted without changing measurements.

How the Statistics Work
Correlation is computed on log returns, never on raw price levels. Correlating two trending price series directly can produce a spuriously high reading that reflects their shared trend rather than how their returns move together.

snapshot

Pearson correlation has no universal market timeframe or lookback. The effective measurement timeframe and window define the observations. A 120-bar window with 1-minute measurements and the same window with 5-minute measurements are different samples and can produce different coefficients.

Correlation runs from +100% through 0% to -100%. It standardizes direction and consistency of linear co-movement; it does not imply equal-sized returns. Correlation Difference is computed as Short minus Long and displayed as a rounded signed number in percentage points.

Beta uses Long-window matched returns and direct covariance/comparison-return variance. From the chart symbol's perspective, Beta +1.20 describes a fitted 1.20-unit chart-symbol log-return response per 1.00 unit of comparison-symbol return in that sample. It is directional and asymmetric, and is benchmark beta only when the comparison is the intended benchmark.
Spread is a signed population z-score of an equal-weight matched log spread. Non-negative Long Correlation selects log(chart) minus log(comparison); negative Long Correlation selects log(chart) plus log(comparison). Separate histories are maintained for the ratio and product forms. The tooltip identifies the active form and whether the latest spread is above or below its matched Long-window average.

When the chart symbol is selected as its own comparison under the same request context, the ratio log-spread has zero variation. Its z-score is therefore unavailable rather than 0.0; after warm-up, identical requested data with measurable return variation produce +100% correlation, zero Difference, and Beta 1.

snapshot

History ranks the current Main Correlation against only that pair's prior valid Main Correlation readings in the Historical window. A tie-aware midrank makes an all-tie sample read 50/100. It describes relative position inside the pair's own history, not statistical confidence or a forecast.
Data Coverage is fresh comparison endpoints divided by eligible Long-window measurement positions after the comparison first appears in loaded data. A carried timestamp is not counted twice. Coverage is distinct from the usable matched returns reported in the tooltips and does not alter any statistic.

Shared-Endpoint Alignment and Confirmation
At each chart-base measurement observation, the script selects the latest completed comparison endpoint known by that base close and maps it to the nearer current or preceding base close; a tie remains on the current close. A return pair is created only between consecutive accepted endpoint pairs when both base and comparison timestamps strictly advance.

Missing bars, holidays, and session gaps accumulate both instruments from the same prior shared endpoint instead of pairing different elapsed intervals. The accumulated interval remains one observation; it is not duration-normalized or split into synthetic bars. An unmatched observation writes one unavailable window position. A star marks a latest fresh comparison endpoint mapped to the preceding base close.

A complete configured measurement window, at least three usable returns, and measurable variation are required before Pearson is shown. Beta requires measurable comparison-return variance. Blank results are intentional when these conditions are not met.

Equal-timeframe requests use lookahead off and statistical snapshots commit on chart confirmation. Fixed higher measurement timeframes use completed bars: every requested price and timestamp field is offset by one measurement bar before lookahead is enabled. The chart timeframe does not need to match. A requested measurement timeframe below the chart falls back to the chart timeframe and produces an amber warning.

The chart-base request retains the active chart's complete ticker context. A slot set to the chart symbol reuses that exact context; other nonblank comparisons inherit applicable session, price-adjustment, currency, and futures modifiers. PulseWire ignores modifiers that do not apply to a comparison instrument. Changing an applicable modifier can change requested prices, timestamps, measurements, coverage, and rebased lines.

The comparison lines are a ratio, not a 1:1 price overlay
The optional chart lines do not plot the other symbol's raw price or its correlation. Each line is tied to the chart symbol's measurement-timeframe price, then moved forward by the percentage change of the compared symbol from that line baseline:

That is a ratio calculation, not a 1:1 mirror of price. Every drawn line uses the same baseline rule when measurement data is available, so its percentage path shares the chart's scale regardless of what either instrument costs.

Comparison line starting point is visual only. Auto from measurement preset uses Session Open for Scalper, Intraday, and Custom, and Year Open for Swing. Fixed Date sets the first base boundary on or after the date. Rolling N Bars moves the shared boundary. Each comparison waits for fresh eligible data, so a line can begin after the marker, remain blank, or jump as a rolling window changes. No line setting changes any dashboard measurement.

Settings
*Quick Setup: Measurement preset selects timeframe and Long/Short windows without changing or requiring a matching chart. Dashboard view and Show correlation difference control columns. Symbol set controls the universe. Show dashboard and Show comparison lines control visual layers. Comparison line starting point controls rebased visuals.

*Symbols and slots: Custom is the default Symbol set. On an SPY chart, the starting Custom symbols are QQQ, DIA, and IWM; the remaining slots are blank. These are examples, not recommendations. A blank display name derives the ticker automatically. Built-in sets override retained Custom symbols and names until Custom is selected again.

*Custom measurements: Blank Custom timeframe follows the chart; a fixed selection at or above the chart holds its requested sampling without changing candles. Long defaults to 120 (range 10-1000); Short to 20 (range 5-200). If Short is not below Long, effective Short becomes Long minus one and appears in amber. Long changes Long, Difference, Beta, Spread, and Coverage; Short changes Short and Difference.

*Main Correlation and History: Main correlation window defaults to Short and selects the existing Long or Short result used by Main Correlation, History, and line-end correlation text. Historical comparison defaults off. Its window defaults to 750 and accepts 100-5000 effective measurement positions; History remains blank until the full measurement window exists.

*Dashboard views and columns: Default Context shows Symbol, Long, Short, Spread, and Coverage; Compact shows Symbol, Short, and Spread; Full shows Symbol, Long, Short, Beta, Spread, Coverage, and enabled History; Minimal shows Symbol and Main; Custom uses individual metric switches. Custom columns can override any view. Difference is independently on by default.

*Dashboard layout: Nine positions default to Top Right. Sorting uses Slot order, strongest absolute Long, or widest absolute Spread. Cells use Heat or Mono. Text, colors, backgrounds, transparency, row shading, borders, and frame are adjustable.

*Comparison line style: Solid is the default; Dashed, Dotted, Step, Step with diamonds, Points, and Crosses are available. Width defaults to 2 and transparency to 50. Area, histogram, and column modes are intentionally excluded because they can obscure candles or distort the price scale.

*Starting-point details: Rolling N Bars defaults to 120 and accepts 10-1000 effective measurement bars. Each line waits for its first fresh valid endpoint at or after the shared rolling boundary. Fixed Date is editable and defaults to 1 January 2026. The optional shared marker has style, color, transparency, and width controls.

*Gap shading and labels: Gap shading can fill between chart price and one selected rebased slot with separate chart-above/chart-below colors and transparency. Line-end labels can include display name, Main Correlation, and Spread, with size and slot/custom text-color controls.

*Global appearance: Master opacity adds fade to table cells/text, lines, marker, fill, and labels; table border and frame keep their own colors. Appearance, visibility, ordering, and baseline controls do not alter calculations.

What It Does Not Do / Limitations

*This is a one-to-many dashboard: every row compares one instrument with the active chart symbol. It is not a full pairwise matrix among all eight comparisons, a covariance matrix, portfolio optimizer, factor model, value-at-risk calculation, or position-sizing engine.

*Correlation measures a historical linear relationship in returns. It does not establish causation, forecast persistence, detect nonlinear dependence, or label a pair bullish or bearish.

*Correlation Difference is not a hypothesis test or statistical regime detector. The indicator does not calculate p-values, confidence intervals, statistical significance, or multiple-comparison adjustments.

*Beta is a backward-looking fitted sensitivity with the chart symbol as the dependent return series. It is not symmetric and is not a dollar-, volatility-, or contract-neutral hedge ratio.

*Spread is an equal-weight log ratio/product z-score selected by the sign of Long Correlation. It does not establish cointegration, stationarity, fair value, or an expectation of mean reversion.

*History percentile and its Low-to-High context bands are relative only to that pair's prior Main Correlation. They are not confidence levels, relationship grades, decision rules, or forecasts.

*Data Coverage measures fresh endpoint availability, not data accuracy, sample quality, or statistical reliability. Markets with different sessions can supply fewer usable returns, and an interval accumulated across a gap remains one observation.

*Results depend on PulseWire's feed, exchange and session coverage, loaded history, selected symbols, applicable chart modifiers, effective measurement timeframe, and window lengths. Changing session, price adjustment, currency conversion, supported futures settings, or other applicable data settings can change the values.

*The indicator requires standard, time-based candles. Non-standard chart types and tick charts halt with a runtime message because the measurement contract requires ordinary time-based OHLC bars rather than synthetic or tick-built observations.

*Blank Custom timeframe follows the chart. Built-in presets and fixed Custom timeframes do not require a chart match. A request below the chart falls back to the chart timeframe; a fixed higher timeframe excludes the developing measurement bar and can update up to one confirming chart bar later.

*Blank cells indicate insufficient measurement history, matched returns, or variation. A line can begin after its marker or remain blank when no fresh baseline observation exists. Rebased lines can stretch autoscale, and Rolling N Bars can jump as its denominator moves.

*The implementation keeps eight static comparison requests plus one chart-base request. Disabling a slot changes the display but does not remove its request or reduce the fixed request cost.

*This measurement-only build does not generate alerts, classify relationships, automate decisions, execute orders, or provide position- or risk-management instructions.

Design and Originality
Pearson correlation, covariance, Beta, and z-scores are standard statistics. This implementation integrates an eight-instrument universe, independent measurement and visual baselines, two return windows, causal shared-endpoint matching, sample disclosures, direct Beta, separate ratio/product spread histories, prior-only tie-aware History, sortable views, and fresh-boundary rebased lines.

The components share one confirmed measurement clock and interpretation surface. They combine slower/faster relationship context, fitted sensitivity, availability, spread displacement, pair history, and normalized paths without importing an external correlation series or creating a classification state.

Open-source License
This is an open-source publication. The source is licensed under the Mozilla Public License 2.0 (MPL 2.0) and includes AuctionFoundry attribution. Reuse in another PulseWire publication must first satisfy PulseWire's open-source reuse rules; once those rules are met, the MPL 2.0 terms apply.

Disclaimer
For educational and informational purposes only. Not financial advice.

Disclaimer

The information and publications are not meant to be, and do not constitute, financial, investment, trading, or other types of advice or recommendations supplied or endorsed by PulseWire. Read more in the Terms of Use.