Coverage for topology/market_topology.py: 100%
321 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
1"""3D market-topology modeling for Aether Quant V2: correlation-driven
2asset clustering and 3D coordinate generation for the runtime market
3structure layer consumed by the dashboard and the central market analyzer."""
5from __future__ import annotations
7import math
8from collections.abc import Callable
9from dataclasses import asdict, dataclass, field
10from typing import TYPE_CHECKING, Any
12import numpy as np
14if TYPE_CHECKING:
15 from numpy.typing import ArrayLike
18ANNUALIZATION_FACTOR = math.sqrt(252)
19ELEVATED_VOLATILITY_THRESHOLD = 0.45
22def resolve_elevated_volatility_thresholds(
23 raw_threshold: float | dict[str, Any] | None,
24 asset_class_by_symbol: dict[str, str | None],
25) -> tuple[float, dict[str, float]]:
26 """V5.5.0 (Problems.md #129) - normalize `phase_v2.topology.elevated_volatility_threshold`.
28 Accepts the legacy bare float (one cutoff for everyone - unchanged
29 behavior) or a dict like {"default": 0.45, "crypto": 1.2} keyed by
30 asset class. Returns (default_threshold, {symbol: threshold}) where the
31 per-symbol map only holds symbols whose class has its own entry.
32 Malformed/non-finite/non-positive entries are ignored, never raised on.
33 """
34 def _valid(value) -> float | None:
35 try:
36 number = float(value)
37 except (TypeError, ValueError):
38 return None
39 return number if math.isfinite(number) and number > 0.0 else None
41 if not isinstance(raw_threshold, dict):
42 scalar = _valid(raw_threshold)
43 return (scalar if scalar is not None else ELEVATED_VOLATILITY_THRESHOLD), {}
45 default_value = _valid(raw_threshold.get("default"))
46 default_threshold = default_value if default_value is not None else ELEVATED_VOLATILITY_THRESHOLD
47 by_class = {
48 str(asset_class): threshold
49 for asset_class, value in raw_threshold.items()
50 if asset_class != "default" and (threshold := _valid(value)) is not None
51 }
52 by_symbol = {
53 symbol: by_class[asset_class]
54 for symbol, asset_class in asset_class_by_symbol.items()
55 if asset_class is not None and asset_class in by_class
56 }
57 return default_threshold, by_symbol
58NEUTRAL_DIMENSIONS = {"width": 100, "height": 100, "depth": 1}
59EMBEDDING_CENTER = 50.0
60EMBEDDING_MAX_RADIUS = 42.0
61# V4-W3: how far the volatility-derived z seed spreads around
62# EMBEDDING_CENTER before SMACOF runs. Only used in 3D mode - a flat seed
63# plane would leave the z axis degenerate, since SMACOF can only move
64# points along directions its seed already separates them on.
65EMBEDDING_Z_SEED_SPREAD = 40.0
68def _dimensions_for(embedding_dimensions: int) -> dict[str, Any]:
69 """Scene bounds for the active embedding mode. depth stays 1 in 2D
70 mode - there z is the volatility encoding on a 0..1 scale, not a
71 spatial axis - and becomes 100 in 3D mode, matching width/height so
72 the webui's `dimensions`-relative normalization stays isotropic."""
73 return {"width": 100, "height": 100, "depth": 100 if embedding_dimensions == 3 else 1}
76@dataclass(frozen=True)
77class TopologyNode:
78 """One name's place in the topology: its cluster, 3D position, distance from the market and risk label."""
79 symbol: str
80 cluster_id: str
81 x: float
82 y: float
83 z: float
84 market_distance: float
85 correlation_strength: float
86 volatility_pressure: float
87 topology_risk: str
88 regime_label: str
89 # Ranked (descending correlation) top-N peer symbols across the WHOLE
90 # eligible universe (not just this node's own cluster - a
91 # correlation_threshold-defined cluster can be much smaller than
92 # top_peers_n) and each peer's own latest available return - a genuine
93 # new information channel for the prediction model (see
94 # train.py::build_peer_return_features_by_date()), distinct from
95 # correlation_strength above (a single mean scalar). Empty for an
96 # isolated node (no peers). No lookahead: each peer's latest return is
97 # already known as of this node's own current bar.
98 top_peers: list[str]
99 top_peer_returns: list[float]
101 def to_dict(self) -> dict[str, Any]:
102 return asdict(self)
105@dataclass(frozen=True)
106class TopologyLink:
107 """A correlation link between two names."""
108 source: str
109 target: str
110 correlation: float
111 distance: float
113 def to_dict(self) -> dict[str, Any]:
114 return asdict(self)
117@dataclass(frozen=True)
118class TopologyCluster:
119 """One cluster of correlated names, with its average correlation."""
120 cluster_id: str
121 members: list[str]
122 average_correlation: float
123 dominant_regime_label: str
125 def to_dict(self) -> dict[str, Any]:
126 return asdict(self)
129@dataclass(frozen=True)
130class MarketTopology:
131 """The market's correlation topology on one bar: nodes, links, clusters and the reasons for its state."""
132 state: str
133 nodes: list[TopologyNode]
134 links: list[TopologyLink]
135 clusters: list[TopologyCluster]
136 dimensions: dict
137 reasons: list[str]
138 # Sparse pairwise Pearson correlations this bar (symbol pair -> value),
139 # keyed the same way build_market_topology()'s internal `correlations`
140 # dict is - NOT part of to_dict()'s output (tuple keys aren't JSON-safe,
141 # and the webui has no use for raw correlations). Exists so a caller
142 # (main.py) can pass this bar's result back in as next bar's
143 # `previous_correlations` - see build_market_topology()'s
144 # correlation_stability_tolerance parameter, development/Problems.md#36.
145 correlations: dict[tuple[str, str], float]
146 # V4.9 Priority 1 (development/Problems.md#36's percentile-tolerance
147 # follow-up) - rolling window of recent per-bar max-pairwise-
148 # correlation-change values, updated every bar previous_correlations
149 # is available and comparable. NOT part of to_dict()'s output (same
150 # reason as `correlations` above - internal state carryover only).
151 # Exists so a caller (main.py) can pass this bar's result back in as
152 # next bar's `correlation_change_history` - see
153 # build_market_topology()'s correlation_stability_tolerance_percentile
154 # parameter. Defaults to an empty list so every existing caller/test
155 # constructing a MarketTopology directly (not via
156 # build_market_topology()) is unaffected.
157 correlation_change_history: list[float] = field(default_factory=list)
159 def to_dict(self) -> dict[str, Any]:
160 return {
161 "state": self.state,
162 "nodes": [node.to_dict() for node in self.nodes],
163 "links": [link.to_dict() for link in self.links],
164 "clusters": [cluster.to_dict() for cluster in self.clusters],
165 "dimensions": dict(self.dimensions),
166 "reasons": list(self.reasons),
167 }
170def _mean(values: list[float]) -> float:
171 return sum(values) / len(values)
174def _pearson_correlation(series_a: list[float], series_b: list[float]) -> float:
175 length = min(len(series_a), len(series_b))
176 if length < 2:
177 return 0.0
178 series_a = series_a[-length:]
179 series_b = series_b[-length:]
180 # a constant window has zero variance by definition; testing the VALUES keeps it independent of how sum() rounds
181 # (Python <= 3.11 sums naively, so mean([0.001] * 24) != 0.001 and the "zero" variance came out ~1e-35, which
182 # divided into noise)
183 if max(series_a) == min(series_a) or max(series_b) == min(series_b):
184 return 0.0
185 mean_a = _mean(series_a)
186 mean_b = _mean(series_b)
187 covariance = sum((a - mean_a) * (b - mean_b) for a, b in zip(series_a, series_b, strict=False))
188 variance_a = sum((a - mean_a) ** 2 for a in series_a)
189 variance_b = sum((b - mean_b) ** 2 for b in series_b)
190 denominator = math.sqrt(variance_a * variance_b)
191 if denominator == 0:
192 return 0.0
193 return max(-1.0, min(1.0, covariance / denominator))
196def _full_window_correlation_matrix(
197 returns_by_symbol: dict[str, list[float]], symbols: list[str]
198) -> tuple[dict[str, int], object] | None:
199 """Pearson matrix over the symbols whose return window has the maximum length (steady state: all of them),
200 as (symbol -> row, matrix); None when numpy is unavailable or fewer than two such symbols exist.
202 Same formula as _pearson_correlation() (centred cross-products over sqrt of the variance product, zero
203 variance -> 0.0, clamped to [-1, 1]) evaluated in one BLAS call instead of ~5k Python loops - the loops were
204 ~87% of build_market_topology()'s 332 ms/call. Results agree with the scalar path to ~1e-15.
205 """
206 try:
207 import numpy as np
208 except ImportError:
209 return None
210 if not symbols:
211 return None
212 longest = max(len(returns_by_symbol[symbol]) for symbol in symbols)
213 full = [symbol for symbol in symbols if len(returns_by_symbol[symbol]) == longest]
214 if longest < 2 or len(full) < 2:
215 return None
216 matrix = np.asarray([returns_by_symbol[symbol] for symbol in full], dtype=float)
217 constant = matrix.max(axis=1) == matrix.min(axis=1)
218 centered = matrix - matrix.mean(axis=1, keepdims=True)
219 covariance = centered @ centered.T
220 variance = np.diag(covariance)
221 denominator = np.sqrt(np.outer(variance, variance))
222 with np.errstate(divide="ignore", invalid="ignore"):
223 correlation = np.where(denominator == 0.0, 0.0, covariance / denominator)
224 correlation = np.clip(correlation, -1.0, 1.0)
225 if constant.any():
226 correlation[constant, :] = 0.0
227 correlation[:, constant] = 0.0
228 return {symbol: row for row, symbol in enumerate(full)}, correlation
231def _annualized_volatility(returns: list[float]) -> float:
232 if len(returns) < 2:
233 return 0.0
234 mean_value = _mean(returns)
235 variance = sum((value - mean_value) ** 2 for value in returns) / (len(returns) - 1)
236 return math.sqrt(max(variance, 0.0)) * ANNUALIZATION_FACTOR
239class _UnionFind:
240 def __init__(self, items: list[str]):
241 self._parent = {item: item for item in items}
243 def find(self, item: str) -> str:
244 root = item
245 while self._parent[root] != root:
246 root = self._parent[root]
247 while self._parent[item] != root:
248 self._parent[item], item = root, self._parent[item]
249 return root
251 def union(self, a: str, b: str) -> None:
252 root_a, root_b = self.find(a), self.find(b)
253 if root_a != root_b:
254 self._parent[max(root_a, root_b)] = min(root_a, root_b)
257def _distance(a: tuple[float, ...], b: tuple[float, ...]) -> float:
258 return math.sqrt(sum((component_a - component_b) ** 2 for component_a, component_b in zip(a, b, strict=False)))
261def _stress_majorize(
262 symbols: list[str],
263 distance_fn: Callable[[str, str], float],
264 initial_positions: dict[str, tuple[float, ...]],
265 iterations: int = 100,
266 convergence_tolerance: float | None = None,
267 target_distance_matrix=None,
268) -> dict[str, tuple[float, ...]]:
269 """Deterministic SMACOF (Scaling by MAjorizing a COmplicated Function):
270 iteratively moves each point toward the position implied by every other
271 point's target distance (the classical Guttman transform), so the final
272 layout's pairwise Euclidean distances approximate the real target
273 distances instead of an arbitrary index-based placement.
275 Seeded from initial_positions - the existing cosmetic circular layout,
276 or (Part D2) the previous bar's converged positions when warm-starting
277 is enabled - rather than randomly, so the result is fully deterministic
278 given the same inputs. Vectorized with numpy (this was previously pure
279 Python, an O(N^2 x iterations) nested loop and the dominant per-bar
280 cost in the topology layer) - same inputs/outputs/seeding as the
281 pure-Python version when `convergence_tolerance` is None; see
282 tests/test_market_topology.py's parity test.
284 Dimension-agnostic (V4-W3): the embedding dimensionality is inferred
285 from the length of the seed tuples rather than passed as a flag, so
286 2-tuple seeds reproduce the original 2D behavior exactly (the parity
287 test above is what holds that guarantee) and 3-tuple seeds produce a
288 genuine 3D embedding. Every step below is already axis-generic except
289 the coincident-point nudge, which is handled explicitly.
291 `convergence_tolerance`, when set, exits before `iterations` once every
292 point's per-iteration movement drops below it - this is what lets a
293 warm start (already close to this bar's stationary point) actually
294 finish faster, rather than always spending the full fixed iteration
295 budget regardless of how close the seed already is.
296 """
297 if len(symbols) < 2:
298 return dict(initial_positions)
300 n = len(symbols)
301 denominator = n - 1
302 positions = np.array([initial_positions[symbol] for symbol in symbols], dtype=np.float64)
303 dimensions = positions.shape[1]
304 if target_distance_matrix is not None:
305 target_distances = np.array(target_distance_matrix, dtype=np.float64, copy=True)
306 else:
307 target_distances = np.array(
308 [[distance_fn(symbol_a, symbol_b) for symbol_b in symbols] for symbol_a in symbols],
309 dtype=np.float64,
310 )
311 np.fill_diagonal(target_distances, 0.0)
313 for _ in range(iterations):
314 diff = positions[:, None, :] - positions[None, :, :]
315 current_distance = np.sqrt((diff**2).sum(axis=-1))
316 coincident = current_distance <= 1e-9
317 safe_distance = np.where(coincident, 1.0, current_distance)
318 scale = np.where(coincident, 0.0, target_distances / safe_distance)
319 direction = diff * scale[:, :, None]
320 # Coincident points (including the i==j diagonal, always coincident
321 # with itself): nudge apart along a fixed axis rather than dividing
322 # by zero. target_distances' diagonal is 0, so the i==j case
323 # naturally contributes an all-zero vector, matching the original
324 # loop's `if other == symbol: continue` skip. The nudge goes along
325 # axis 0 only, in every dimensionality - identical to the 2D
326 # original, which set axis 0 to target_distances and axis 1 to 0.
327 direction[..., 0] = np.where(coincident, target_distances, direction[..., 0])
328 for axis in range(1, dimensions):
329 direction[..., axis] = np.where(coincident, 0.0, direction[..., axis])
331 sum_positions = positions.sum(axis=0)
332 direction_sum = direction.sum(axis=1)
333 new_positions = (sum_positions[None, :] + direction_sum - positions) / denominator
335 if convergence_tolerance is not None:
336 max_shift = np.sqrt(((new_positions - positions) ** 2).sum(axis=1)).max()
337 positions = new_positions
338 if max_shift < convergence_tolerance:
339 break
340 else:
341 positions = new_positions
343 return {
344 symbol: tuple(float(component) for component in positions[index]) for index, symbol in enumerate(symbols)
345 }
348def _rescale_positions_to_bounds(
349 positions: dict[str, tuple[float, ...]],
350 center: float = EMBEDDING_CENTER,
351 max_radius: float = EMBEDDING_MAX_RADIUS,
352) -> dict[str, tuple[float, ...]]:
353 """Uniformly scale and re-center the embedding to fit within the
354 existing NEUTRAL_DIMENSIONS [0,100]^d bounds.
356 A single isometric scale factor (not independent per-axis min-max
357 normalization) -- stretching axes independently would distort the very
358 relative distances this embedding exists to preserve. Dimension-
359 agnostic (V4-W3): the same single factor now covers z too when the
360 embedding runs in 3D.
361 """
362 if not positions:
363 return {}
365 dimensions = len(next(iter(positions.values())))
366 centroid = tuple(_mean([point[axis] for point in positions.values()]) for axis in range(dimensions))
367 max_extent = max(
368 (_distance(point, centroid) for point in positions.values()),
369 default=0.0,
370 )
371 if max_extent <= 1e-9:
372 return dict.fromkeys(positions, (center,) * dimensions)
374 scale = max_radius / max_extent
375 return {
376 symbol: tuple(center + (point[axis] - centroid[axis]) * scale for axis in range(dimensions))
377 for symbol, point in positions.items()
378 }
381def _isolated_node(
382 symbol: str,
383 returns: list[float],
384 cluster_id: str,
385 regime_label: str,
386 embedding_dimensions: int = 2,
387) -> TopologyNode:
388 return TopologyNode(
389 symbol=symbol,
390 cluster_id=cluster_id,
391 x=50.0,
392 y=50.0,
393 # In 3D mode z is a spatial axis on the same 0..100 scale as x/y,
394 # so an isolated node sits at the centre like it already does on
395 # x/y. In 2D mode z keeps its volatility-encoding meaning.
396 z=(
397 EMBEDDING_CENTER
398 if embedding_dimensions == 3
399 else max(0.1, min(0.95, 0.25 + _annualized_volatility(returns)))
400 ),
401 market_distance=1.0,
402 correlation_strength=0.0,
403 volatility_pressure=_annualized_volatility(returns),
404 topology_risk="isolated",
405 regime_label=regime_label,
406 top_peers=[],
407 top_peer_returns=[],
408 )
411def _percentile(values: list[float], p: float) -> float:
412 """Nearest-rank percentile over `values` (need not be pre-sorted), p in
413 [0, 100]. V4.9 Priority 1 - local to this module rather than shared
414 with scripts/profile_inference.py's own percentile() helper: same
415 nearest-rank math, but a genuinely different domain (correlation-
416 change magnitudes vs. latency durations) with no real coupling to gain
417 from sharing. Returns 0.0 for an empty list rather than raising."""
418 if not values:
419 return 0.0
420 sorted_values = sorted(values)
421 index = min(int(round(p / 100.0 * (len(sorted_values) - 1))), len(sorted_values) - 1)
422 return sorted_values[index]
425def rank_correlated_peers(
426 symbol: str,
427 eligible_symbols: list[str],
428 correlation_fn: Callable[[str, str], float],
429 top_n: int,
430) -> list[str]:
431 """Ranks every OTHER eligible symbol by descending correlation to
432 `symbol` across the WHOLE eligible universe (not just `symbol`'s own
433 cluster - a correlation_threshold-defined cluster can be much smaller
434 than top_n), returning up to `top_n` symbols. Ties broken
435 alphabetically for determinism (matches this module's existing
436 tie-breaking convention, e.g. sorted_roots/nodes.sort() below)."""
437 others = [other for other in eligible_symbols if other != symbol]
438 ranked = sorted(others, key=lambda other: (-correlation_fn(symbol, other), other))
439 return ranked[:top_n]
442def rank_correlated_peers_from_row(
443 row_index: int, symbols: list[str], correlation_row: ArrayLike, top_n: int, alphabetical_positions: ArrayLike | None=None
444) -> list[str]:
445 """rank_correlated_peers() on one row of the full correlation matrix (V5.8.0): the same ordering - descending
446 correlation, ties by symbol name - via one stable lexsort instead of a Python sort with a lookup per pair.
447 `symbols` must be in the matrix's row order; `alphabetical_positions` (rank of each symbol's name) defaults to the
448 row order, which equals alphabetical order for build_market_topology()'s sorted eligible symbols."""
449 import numpy as np
451 values = -np.asarray(correlation_row, dtype=np.float64)
452 names = np.arange(len(symbols)) if alphabetical_positions is None else np.asarray(alphabetical_positions)
453 order = np.lexsort((names, values))
454 peers = [symbols[index] for index in order if index != row_index]
455 return peers[:top_n]
458def build_market_topology(
459 returns_by_symbol: dict[str, list[float]],
460 regime_labels_by_symbol: dict[str, str] | None = None,
461 correlation_threshold: float = 0.6,
462 link_threshold: float = 0.5,
463 min_observations: int = 5,
464 embedding_iterations: int = 100,
465 previous_positions: dict[str, tuple[float, ...]] | None = None,
466 convergence_tolerance: float | None = None,
467 top_peers_n: int = 3,
468 previous_correlations: dict[tuple[str, str], float] | None = None,
469 correlation_stability_tolerance: float | None = None,
470 embedding_dimensions: int = 2,
471 correlation_stability_tolerance_percentile: float | None = None,
472 correlation_change_history: list[float] | None = None,
473 correlation_change_history_max_len: int = 50,
474 elevated_volatility_threshold: float = ELEVATED_VOLATILITY_THRESHOLD,
475 elevated_volatility_threshold_by_symbol: dict[str, float] | None = None,
476) -> MarketTopology:
477 """`embedding_dimensions` (V4-W3, `phase_v2.topology.embedding_dimensions`,
478 default 2) selects how many axes SMACOF embeds. At 2 - the default -
479 every coordinate, reason string and dimension is byte-identical to the
480 pre-V4 behavior, and z stays the volatility encoding. At 3, z becomes
481 a real correlation-distance axis on the same 0..100 scale as x/y, and
482 volatility is carried by node radius in the webui instead.
484 `correlation_stability_tolerance_percentile` (V4.9 Priority 1, default
485 None) is a self-relative alternative to the fixed
486 `correlation_stability_tolerance` above - development/Problems.md#36
487 found the fixed default poorly calibrated (the skip "essentially never
488 fires" against synthetic data, and this environment can't run a real
489 backtest to calibrate a better fixed number). When set, the effective
490 tolerance each bar is the given percentile of
491 `correlation_change_history` (a rolling window of RECENT PRIOR bars'
492 own max-pairwise-correlation-change values, NOT including this bar's -
493 avoids the circularity of a bar judging itself), making the skip rate
494 a mathematically-guaranteed function of the chosen percentile
495 regardless of the real correlation-noise distribution. Takes priority
496 over `correlation_stability_tolerance` when set; None (the default)
497 reproduces the fixed-tolerance behavior byte-identically. The caller
498 (main.py) is expected to thread `correlation_change_history` through
499 bar-to-bar exactly like `previous_positions`/`previous_correlations` -
500 read this call's returned `MarketTopology.correlation_change_history`
501 and pass it back in as next bar's `correlation_change_history`.
503 `elevated_volatility_threshold` (V5.2.6, development/Problems.md,
504 default matches the module's own `ELEVATED_VOLATILITY_THRESHOLD`
505 constant exactly - a no-op unless a caller passes a different value)
506 is the volatility_pressure cutoff for a node's topology_risk becoming
507 "elevated" - which analyzer/market_analyzer.py::build_market_analysis_decision()'s
508 Priority 3 uses to unconditionally override any directional signal.
509 Threaded through (not just a bare module constant) so main.py can
510 raise it to a value derived from this backtest universe's own real
511 historical volatility_pressure distribution, narrowing the override
512 to genuinely extreme readings instead of a fixed, ungrounded 0.45.
514 `elevated_volatility_threshold_by_symbol` (V5.5.0, Problems.md #129,
515 default None = every symbol uses the single threshold above) lets a
516 symbol carry its own cutoff - see resolve_elevated_volatility_thresholds().
517 Crypto's annualized volatility sits structurally above 0.45, so under
518 one global cutoff every crypto node was permanently "elevated" and the
519 analyzer's Priority 3 cancelled every BTC/LTC directional signal (13 of
520 its 26 book selections in the 2026-08-27 backtest)."""
521 regime_labels_by_symbol = regime_labels_by_symbol or {}
522 reasons: list[str] = []
523 embed_3d = embedding_dimensions == 3
525 eligible_symbols = sorted(
526 symbol for symbol, returns in returns_by_symbol.items() if len(returns) >= min_observations
527 )
528 excluded_symbols = sorted(set(returns_by_symbol) - set(eligible_symbols))
529 if excluded_symbols:
530 reasons.append(f"excluded_insufficient_history={','.join(excluded_symbols)}")
532 if len(eligible_symbols) < 2:
533 reasons.append("insufficient_eligible_assets_for_correlation")
534 isolated_nodes = [
535 _isolated_node(
536 symbol,
537 returns_by_symbol.get(symbol, []),
538 f"cluster_{index}",
539 regime_labels_by_symbol.get(symbol, "unknown"),
540 embedding_dimensions,
541 )
542 for index, symbol in enumerate(sorted(returns_by_symbol))
543 ]
544 return MarketTopology(
545 state="insufficient_data",
546 nodes=isolated_nodes,
547 links=[],
548 clusters=[],
549 dimensions=_dimensions_for(embedding_dimensions),
550 reasons=reasons,
551 correlations={},
552 )
554 correlations: dict[tuple[str, str], float] = {}
555 full_matrix = _full_window_correlation_matrix(returns_by_symbol, eligible_symbols)
556 row_by_symbol, matrix = full_matrix if full_matrix is not None else ({}, None)
557 for index, symbol_a in enumerate(eligible_symbols):
558 for symbol_b in eligible_symbols[index + 1 :]:
559 if symbol_a in row_by_symbol and symbol_b in row_by_symbol:
560 correlations[(symbol_a, symbol_b)] = float(matrix[row_by_symbol[symbol_a], row_by_symbol[symbol_b]])
561 else: # a shorter (young) window: tail-aligned scalar path
562 correlations[(symbol_a, symbol_b)] = _pearson_correlation(
563 returns_by_symbol[symbol_a], returns_by_symbol[symbol_b]
564 )
566 # V5.8.0 - one dense symmetric matrix (nested lists for scalar reads, numpy for the embedding and peer ranking)
567 # holding exactly the floats in `correlations`; every lookup below used to probe the pair dict twice.
568 position_by_symbol = {symbol: index for index, symbol in enumerate(eligible_symbols)}
569 correlation_rows = [[0.0] * len(eligible_symbols) for _ in eligible_symbols]
570 for index in range(len(eligible_symbols)):
571 correlation_rows[index][index] = 1.0
572 for (symbol_a, symbol_b), value in correlations.items():
573 index_a, index_b = position_by_symbol[symbol_a], position_by_symbol[symbol_b]
574 correlation_rows[index_a][index_b] = value
575 correlation_rows[index_b][index_a] = value
577 def correlation_between(symbol_a: str, symbol_b: str) -> float: # the diagonal of the matrix is 1.0
578 return correlation_rows[position_by_symbol[symbol_a]][position_by_symbol[symbol_b]]
580 union_find = _UnionFind(eligible_symbols)
581 for (symbol_a, symbol_b), correlation in correlations.items():
582 if correlation >= correlation_threshold:
583 union_find.union(symbol_a, symbol_b)
585 members_by_root: dict[str, list[str]] = {}
586 for symbol in eligible_symbols:
587 members_by_root.setdefault(union_find.find(symbol), []).append(symbol)
589 sorted_roots = sorted(members_by_root, key=lambda root: members_by_root[root])
590 cluster_count = len(sorted_roots)
592 clusters: list[TopologyCluster] = []
593 nodes: list[TopologyNode] = []
595 # Pass 1: cluster structure + per-symbol metadata, and a cosmetic
596 # index-based seed layout (the module's previous, sole layout method) --
597 # kept only as SMACOF's deterministic starting point below, not as the
598 # final coordinates.
599 cluster_id_by_symbol: dict[str, str] = {}
600 correlation_strength_by_symbol: dict[str, float] = {}
601 market_distance_by_symbol: dict[str, float] = {}
602 member_count_by_symbol: dict[str, int] = {}
603 seed_positions: dict[str, tuple[float, ...]] = {}
604 # Hoisted out of Pass 3 (where it used to be computed) because the 3D
605 # seed below needs it too - computing it once keeps the two uses from
606 # drifting apart and saves a second pass over every return series.
607 volatility_by_symbol = {symbol: _annualized_volatility(returns_by_symbol[symbol]) for symbol in eligible_symbols}
609 for cluster_index, root in enumerate(sorted_roots):
610 members = sorted(members_by_root[root])
611 cluster_id = f"cluster_{cluster_index}"
612 angle = (2 * math.pi * cluster_index) / max(cluster_count, 1)
613 centroid_x = 50.0 + math.cos(angle) * 28.0
614 centroid_y = 50.0 + math.sin(angle) * 22.0
616 pairwise_in_cluster = [
617 correlation_between(a, b) for idx, a in enumerate(members) for b in members[idx + 1 :]
618 ]
619 cluster_average_correlation = _mean(pairwise_in_cluster) if pairwise_in_cluster else 0.0
621 regime_votes: dict[str, int] = {}
622 for member in members:
623 label = regime_labels_by_symbol.get(member, "unknown")
624 regime_votes[label] = regime_votes.get(label, 0) + 1
625 dominant_regime_label = max(sorted(regime_votes), key=lambda label: regime_votes[label])
627 clusters.append(
628 TopologyCluster(
629 cluster_id=cluster_id,
630 members=members,
631 average_correlation=cluster_average_correlation,
632 dominant_regime_label=dominant_regime_label,
633 )
634 )
636 for member_index, symbol in enumerate(members):
637 peer_correlations = [correlation_between(symbol, other) for other in members if other != symbol]
638 correlation_strength = _mean(peer_correlations) if peer_correlations else 0.0
639 market_distance = max(0.0, 1.0 - correlation_strength) if peer_correlations else 1.0
641 within_cluster_angle = (2 * math.pi * member_index) / max(len(members), 1)
642 offset_radius = 4.0 + market_distance * 10.0
643 seed_x = centroid_x + math.cos(within_cluster_angle) * offset_radius
644 seed_y = centroid_y + math.sin(within_cluster_angle) * offset_radius
646 cluster_id_by_symbol[symbol] = cluster_id
647 correlation_strength_by_symbol[symbol] = correlation_strength
648 market_distance_by_symbol[symbol] = market_distance
649 member_count_by_symbol[symbol] = len(members)
650 if embed_3d:
651 # Seed z from the same volatility value 2D mode encodes
652 # there directly, spread across a range comparable to the
653 # x/y seed. SMACOF only separates points along directions
654 # its seed already separates them on, so seeding z flat
655 # (or on the raw 0.1..0.95 volatility scale, which is
656 # ~1/100th of the x/y spread) would collapse the third
657 # axis - the layout would stay visually 2D.
658 volatility_z = max(0.1, min(0.95, 0.25 + volatility_by_symbol[symbol]))
659 seed_z = EMBEDDING_CENTER + (volatility_z - 0.5) * EMBEDDING_Z_SEED_SPREAD
660 seed_positions[symbol] = (seed_x, seed_y, seed_z)
661 else:
662 seed_positions[symbol] = (seed_x, seed_y)
664 # development/Problems.md#36: skip re-running the expensive Pass 2
665 # embedding entirely when correlation structure hasn't materially
666 # changed bar-to-bar - reuse the prior bar's already-converged,
667 # already-rescaled positions directly instead of paying SMACOF's
668 # ~500-600ms/bar cost again for a result that would barely move. Only
669 # valid when the eligible-symbol universe is unchanged (a new/dropped
670 # symbol always forces a full recompute - set(correlations.keys()) ==
671 # set(previous_correlations.keys()) is sufficient to guarantee this,
672 # since pair-keys uniquely determine the symbol set once >=2 symbols
673 # are eligible) and every pairwise correlation moved by no more than
674 # correlation_stability_tolerance. Off by default
675 # (correlation_stability_tolerance=None, from main.py's
676 # phase_v2.topology.cache_enabled=false) - previous_correlations/
677 # correlation_stability_tolerance both being None reproduces today's
678 # exact always-fresh-compute behavior, byte-identical, same contract
679 # the Part D2 warm-start feature below already guarantees.
680 # V4-W3: positions carried over from a run at a different
681 # embedding_dimensions (the flag flipped between bars, or a resumed
682 # run) have the wrong tuple width - reusing or seeding from them would
683 # either drop the z axis or blow up the numpy stack. Treat them as
684 # absent, exactly like a symbol the previous bar never saw.
685 if previous_positions is not None:
686 previous_positions = {
687 symbol: point for symbol, point in previous_positions.items() if len(point) == embedding_dimensions
688 }
689 if not previous_positions:
690 previous_positions = None
692 # V4.9 Priority 1: max_correlation_change is computed here, OUTSIDE the
693 # can_reuse_previous_embedding gate below, whenever it's comparable at
694 # all (previous_correlations present and covering the same symbol
695 # pairs) - correlation_change_history needs every bar's value to build
696 # a meaningful rolling window, not just the bars where reuse ends up
697 # being attempted for other reasons too.
698 max_correlation_change: float | None = None
699 if previous_correlations is not None and set(correlations.keys()) == set(previous_correlations.keys()):
700 max_correlation_change = max(
701 (abs(correlations[key] - previous_correlations[key]) for key in correlations),
702 default=0.0,
703 )
705 updated_correlation_change_history = list(correlation_change_history or [])
706 if max_correlation_change is not None:
707 updated_correlation_change_history.append(max_correlation_change)
708 if len(updated_correlation_change_history) > correlation_change_history_max_len:
709 updated_correlation_change_history = updated_correlation_change_history[-correlation_change_history_max_len:]
711 if correlation_stability_tolerance_percentile is not None:
712 # Percentile of RECENT PRIOR bars only (the input history, not the
713 # just-updated one above) - a bar must never be judged against a
714 # window that already includes its own value.
715 effective_tolerance = (
716 _percentile(correlation_change_history, correlation_stability_tolerance_percentile)
717 if correlation_change_history
718 else None
719 )
720 else:
721 effective_tolerance = correlation_stability_tolerance
723 can_reuse_previous_embedding = (
724 effective_tolerance is not None
725 and previous_correlations is not None
726 and previous_positions is not None
727 and set(correlations.keys()) == set(previous_correlations.keys())
728 and set(eligible_symbols).issubset(previous_positions.keys())
729 and max_correlation_change is not None
730 and max_correlation_change <= effective_tolerance
731 )
733 if can_reuse_previous_embedding:
734 final_positions = {symbol: previous_positions[symbol] for symbol in eligible_symbols}
735 reasons.append("topology_embedding_reused_stable_correlations")
736 else:
737 # Part D2 warm start: for any eligible symbol present in
738 # previous_positions (the prior bar's converged embedding), seed
739 # SMACOF from there instead of the cosmetic angle-based layout
740 # above - correlations evolve slowly bar to bar, so the prior
741 # bar's embedding is typically already close to this bar's
742 # stationary point. Symbols absent from previous_positions (new
743 # to the universe, or isolated last bar) fall back to the
744 # cosmetic seed untouched.
745 if previous_positions:
746 for symbol in eligible_symbols:
747 if symbol in previous_positions:
748 seed_positions[symbol] = previous_positions[symbol]
750 # Pass 2: real distance-preserving embedding -- pairwise distance
751 # across ALL eligible symbols (not just within-cluster pairs;
752 # cross-cluster distance matters for a meaningful layout too),
753 # seeded from the cosmetic layout (or the warm-start layout
754 # above) so the result is deterministic and converges fast. This
755 # is what makes spatial distance actually reflect correlation
756 # distance instead of arbitrary index-based placement.
757 import numpy as np
759 final_positions = _rescale_positions_to_bounds(
760 _stress_majorize(
761 eligible_symbols,
762 lambda symbol_a, symbol_b: max(0.0, 1.0 - correlation_between(symbol_a, symbol_b)),
763 seed_positions,
764 iterations=embedding_iterations,
765 convergence_tolerance=convergence_tolerance,
766 target_distance_matrix=np.maximum(0.0, 1.0 - np.asarray(correlation_rows, dtype=np.float64)),
767 )
768 )
770 # Pass 3: build nodes from the real embedding + per-symbol metadata.
771 default_position = (EMBEDDING_CENTER,) * embedding_dimensions
772 for symbol in eligible_symbols:
773 position = final_positions.get(symbol, default_position)
774 x, y = position[0], position[1]
775 volatility_pressure = volatility_by_symbol[symbol]
776 # 3D mode: z is the embedding's third axis. 2D mode: z keeps its
777 # original volatility encoding, untouched.
778 z = position[2] if embed_3d else max(0.1, min(0.95, 0.25 + volatility_pressure))
780 if member_count_by_symbol[symbol] == 1:
781 topology_risk = "isolated"
782 elif volatility_pressure >= (
783 elevated_volatility_threshold_by_symbol.get(symbol, elevated_volatility_threshold)
784 if elevated_volatility_threshold_by_symbol
785 else elevated_volatility_threshold
786 ):
787 topology_risk = "elevated"
788 else:
789 topology_risk = "normal"
791 top_peer_symbols = rank_correlated_peers_from_row(
792 position_by_symbol[symbol], eligible_symbols, correlation_rows[position_by_symbol[symbol]], top_peers_n
793 )
794 top_peer_returns = [returns_by_symbol[peer][-1] for peer in top_peer_symbols]
796 nodes.append(
797 TopologyNode(
798 symbol=symbol,
799 cluster_id=cluster_id_by_symbol[symbol],
800 x=x,
801 y=y,
802 z=z,
803 market_distance=market_distance_by_symbol[symbol],
804 correlation_strength=correlation_strength_by_symbol[symbol],
805 volatility_pressure=volatility_pressure,
806 topology_risk=topology_risk,
807 regime_label=regime_labels_by_symbol.get(symbol, "unknown"),
808 top_peers=top_peer_symbols,
809 top_peer_returns=top_peer_returns,
810 )
811 )
813 links: list[TopologyLink] = [
814 TopologyLink(
815 source=symbol_a,
816 target=symbol_b,
817 correlation=correlation,
818 distance=max(0.0, 1.0 - correlation),
819 )
820 for (symbol_a, symbol_b), correlation in correlations.items()
821 if correlation >= link_threshold
822 ]
824 for symbol in excluded_symbols:
825 nodes.append(
826 _isolated_node(
827 symbol,
828 returns_by_symbol.get(symbol, []),
829 "cluster_unassigned",
830 regime_labels_by_symbol.get(symbol, "unknown"),
831 embedding_dimensions,
832 )
833 )
835 nodes.sort(key=lambda node: node.symbol)
836 links.sort(key=lambda link: (link.source, link.target))
838 return MarketTopology(
839 state="ready",
840 nodes=nodes,
841 links=links,
842 clusters=clusters,
843 dimensions=_dimensions_for(embedding_dimensions),
844 reasons=reasons,
845 correlations=correlations,
846 correlation_change_history=updated_correlation_change_history,
847 )