Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(correlation): regime timeline endpoint and UI (edge density + hysteresis)

ebujinovch555dcec5602d
diff --git a/agent/backtest/correlation.py b/agent/backtest/correlation.py
index fce037177..50c88ed44 100644
--- a/agent/backtest/correlation.py
+++ b/agent/backtest/correlation.py
@@ -84,6 +84,31 @@ def _normalize_symbol(code: str, market: str) -> str:
return cleaned
+def _close_series(code: str, df: pd.DataFrame) -> pd.Series:
+ """Extract the close-price series from a loader frame, date-indexed and sorted.
+
+ Supports ``trade_date`` as the index name, as a column, or a plain
+ DatetimeIndex — the shapes real loaders return.
+ """
+ if df.empty:
+ raise ValueError(f"Price series for '{code}' is empty")
+ if "close" not in df.columns and "close" not in df.index.names:
+ raise ValueError(f"No 'close' column in price series for '{code}'")
+ # Support trade_date as index name, column, or a plain DatetimeIndex.
+ if "trade_date" in df.columns:
+ ts = df.set_index("trade_date")["close"]
+ elif "close" in df.columns and (
+ "trade_date" in df.index.names
+ or isinstance(df.index, pd.DatetimeIndex)
+ ):
+ ts = df["close"]
+ else:
+ raise ValueError(
+ f"No trade_date index/column for price series '{code}'"
+ )
+ return ts.sort_index()
+
+
def _rolling_correlation_matrix(
price_series: Dict[str, pd.DataFrame],
window: int,
@@ -109,23 +134,7 @@ def _rolling_correlation_matrix(
returns_frames = []
closes = {}
for code, df in price_series.items():
- if df.empty:
- raise ValueError(f"Price series for '{code}' is empty")
- if "close" not in df.columns and "close" not in df.index.names:
- raise ValueError(f"No 'close' column in price series for '{code}'")
- # Support trade_date as index name, column, or a plain DatetimeIndex.
- if "trade_date" in df.columns:
- ts = df.set_index("trade_date")["close"]
- elif "close" in df.columns and (
- "trade_date" in df.index.names
- or isinstance(df.index, pd.DatetimeIndex)
- ):
- ts = df["close"]
- else:
- raise ValueError(
- f"No trade_date index/column for price series '{code}'"
- )
- closes[code] = ts.sort_index()
+ closes[code] = _close_series(code, df)
for code in codes:
ts = closes[code]
@@ -178,26 +187,22 @@ def _rolling_correlation_matrix(
return labels, matrix
-def compute_correlation_matrix(
+def _fetch_price_series(
codes: list[str],
- days: int = 90,
- method: Literal["pearson", "spearman"] = "pearson",
-) -> Dict[str, object]:
- """Fetch price data and compute correlation matrix for a list of assets.
+ start_date: str,
+ end_date: str,
+) -> Dict[str, pd.DataFrame]:
+ """Fetch daily price frames for each code via the loader fallback chains.
Args:
- codes: List of asset codes (e.g. ["BTC-USDT", "ETH-USDT", "SPY"]).
- days: Lookback window in days (default 90).
- method: Correlation method.
+ codes: Asset codes as supplied by the caller (used as result keys).
+ start_date: Fetch range start, ``YYYY-MM-DD``.
+ end_date: Fetch range end, ``YYYY-MM-DD``.
Returns:
- Dict with keys: labels, matrix, window, method.
+ Mapping of original code -> OHLCV DataFrame; codes no loader could
+ serve are omitted (with a warning logged).
"""
- from datetime import datetime, timedelta
-
- end_date = datetime.now().strftime("%Y-%m-%d")
- start_date = (datetime.now() - timedelta(days=days + 60)).strftime("%Y-%m-%d")
-
# Import here to avoid circular
from backtest.loaders import registry
@@ -248,6 +253,31 @@ def compute_correlation_matrix(
"(normalized from %r)", market, symbol, code,
)
+ return price_series
+
+
+def compute_correlation_matrix(
+ codes: list[str],
+ days: int = 90,
+ method: Literal["pearson", "spearman"] = "pearson",
+) -> Dict[str, object]:
+ """Fetch price data and compute correlation matrix for a list of assets.
+
+ Args:
+ codes: List of asset codes (e.g. ["BTC-USDT", "ETH-USDT", "SPY"]).
+ days: Lookback window in days (default 90).
+ method: Correlation method.
+
+ Returns:
+ Dict with keys: labels, matrix, window, method.
+ """
+ from datetime import datetime, timedelta
+
+ end_date = datetime.now().strftime("%Y-%m-%d")
+ start_date = (datetime.now() - timedelta(days=days + 60)).strftime("%Y-%m-%d")
+
+ price_series = _fetch_price_series(codes, start_date, end_date)
+
if len(price_series) < 2:
raise ValueError(
f"Could not fetch price data for at least 2 assets. "
@@ -260,4 +290,4 @@ def compute_correlation_matrix(
"matrix": matrix,
"window": days,
"method": method,
- }
\ No newline at end of file
+ }
diff --git a/agent/backtest/regime.py b/agent/backtest/regime.py
new file mode 100644
index 000000000..2d4a5a4e4
--- /dev/null
+++ b/agent/backtest/regime.py
@@ -0,0 +1,233 @@
+"""Correlation-regime timeline: edge density + hysteresis over time.
+
+Implements Mode 1 of the ``correlation-regime`` skill on top of the same
+price data the /correlation endpoint uses: rolling pairwise correlations are
+reduced to an edge-density scalar per bar, the density series is smoothed
+with a trailing (causal) window, and a two-threshold hysteresis state
+machine labels each bar FUSED or not. Used by the /correlation/regime API
+endpoint. Descriptive risk context — not a trading signal.
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Dict, Optional
+
+import numpy as np
+import pandas as pd
+
+from backtest.correlation import _close_series, _fetch_price_series
+
+logger = logging.getLogger(__name__)
+
+
+def compute_edge_density(
+ returns: pd.DataFrame,
+ corr_window: int = 60,
+ edge_threshold: float = 0.5,
+) -> pd.Series:
+ """Reduce rolling correlation matrices to an edge-density series.
+
+ Edge density is the fraction of distinct asset pairs whose rolling
+ |correlation| clears ``edge_threshold`` — a scalar "how fused is the
+ market" gauge in [0, 1].
+
+ Args:
+ returns: Multi-asset return matrix, columns are symbols
+ corr_window: Rolling window length (bars) for pairwise correlation
+ edge_threshold: |ρ| level at which a pair counts as an "edge"
+
+ Returns:
+ Edge-density series aligned to ``returns.index`` (NaN during warmup)
+ """
+ n_assets = returns.shape[1]
+ n_pairs = n_assets * (n_assets - 1) // 2
+ upper_mask = np.triu(np.ones((n_assets, n_assets), dtype=bool), k=1)
+
+ density = pd.Series(np.nan, index=returns.index)
+ for i in range(corr_window, len(returns) + 1):
+ corr = returns.iloc[i - corr_window:i].corr().abs().to_numpy()
+ density.iloc[i - 1] = float((corr[upper_mask] >= edge_threshold).sum()) / n_pairs
+ return density
+
+
+def detect_regimes(
+ density: pd.Series,
+ smooth_window: int = 5,
+ enter_threshold: float = 0.65,
+ exit_threshold: float = 0.45,
+) -> pd.DataFrame:
+ """Hysteresis (Schmitt-trigger) regime state machine on smoothed density.
+
+ The market is FUSED once smoothed density reaches ``enter_threshold`` and
+ stays FUSED until it falls back to ``exit_threshold``. The dead band
+ between the two thresholds is what suppresses chatter.
+
+ Args:
+ density: Edge-density series from :func:`compute_edge_density`
+ smooth_window: Trailing smoothing window (causal; never centered)
+ enter_threshold: Density level that opens a FUSED regime
+ exit_threshold: Density level that closes it (must be < enter_threshold)
+
+ Returns:
+ DataFrame with columns ``density``, ``smoothed``, ``fused`` (0/1)
+ """
+ if exit_threshold >= enter_threshold:
+ raise ValueError("exit_threshold must be below enter_threshold")
+
+ # Trailing mean = causal. A centered window here silently reads the future.
+ smoothed = density.rolling(smooth_window, min_periods=1).mean()
+
+ fused = False
+ states = np.zeros(len(smoothed), dtype=int)
+ for i, value in enumerate(smoothed.to_numpy()):
+ if np.isnan(value):
+ states[i] = int(fused)
+ continue
+ if not fused and value >= enter_threshold:
+ fused = True
+ elif fused and value <= exit_threshold:
+ fused = False
+ states[i] = int(fused)
+
+ return pd.DataFrame(
+ {"density": density, "smoothed": smoothed, "fused": states},
+ index=density.index,
+ )
+
+
+def _aligned_returns(price_series: Dict[str, pd.DataFrame]) -> pd.DataFrame:
+ """Build a date-aligned daily-returns frame (one column per code).
+
+ Mirrors the alignment in ``_rolling_correlation_matrix``: indexes are
+ normalized to midnight so cross-market assets (e.g. crypto at UTC
+ midnight vs US equity at EDT midnight) share dates, then inner-joined.
+ ``fill_method=None`` is explicit because under the project's
+ pandas>=2,<3 pin the ``pct_change`` default forward-fills missing
+ prices, silently manufacturing 0% returns.
+ """
+ returns_frames = []
+ for code in sorted(price_series):
+ ts = _close_series(code, price_series[code])
+ ts.index = ts.index.normalize()
+ rets = ts.pct_change(fill_method=None).dropna()
+ rets.name = code
+ returns_frames.append(rets)
+
+ aligned = pd.concat(returns_frames, axis=1).dropna()
+ if aligned.empty:
+ raise ValueError("No overlapping return data between assets")
+ return aligned
+
+
+def _fused_episodes(dates: list[str], fused: list[int]) -> list[Dict[str, Optional[str]]]:
+ """Contiguous FUSED intervals within the returned window.
+
+ ``end`` is the last date observed FUSED, or None while the final bar is
+ still FUSED (episode ongoing).
+ """
+ episodes: list[Dict[str, Optional[str]]] = []
+ start: Optional[str] = None
+ last_fused: Optional[str] = None
+ for date, state in zip(dates, fused):
+ if state:
+ if start is None:
+ start = date
+ last_fused = date
+ elif start is not None:
+ episodes.append({"start": start, "end": last_fused})
+ start = None
+ if start is not None:
+ episodes.append({"start": start, "end": None})
+ return episodes
+
+
+def compute_regime_timeline(
+ codes: list[str],
+ days: int = 90,
+ corr_window: int = 60,
+ edge_threshold: float = 0.5,
+ smooth_window: int = 5,
+ enter_threshold: float = 0.65,
+ exit_threshold: float = 0.45,
+) -> Dict[str, object]:
+ """Fetch price data and compute the correlation-regime timeline.
+
+ Args:
+ codes: List of asset codes, as for :func:`compute_correlation_matrix`.
+ days: Number of trailing timeline bars to return.
+ corr_window: Rolling window (bars) for pairwise correlation.
+ edge_threshold: |ρ| level at which a pair counts as an "edge".
+ smooth_window: Trailing smoothing window (bars) for the density series.
+ enter_threshold: Smoothed density that opens a FUSED regime.
+ exit_threshold: Smoothed density that closes it (must be below
+ ``enter_threshold``).
+
+ Returns:
+ Dict with keys: labels, dates, density, smoothed, fused, episodes,
+ params. ``density``/``smoothed`` use None for warmup bars; ``fused``
+ is 0/1 per bar; ``episodes`` lists FUSED intervals with ``end=None``
+ while the final bar is still FUSED.
+ """
+ from datetime import datetime, timedelta
+
+ if exit_threshold >= enter_threshold:
+ raise ValueError("exit_threshold must be below enter_threshold")
+
+ # Each returned bar needs a full corr_window of history behind it, so the
+ # warmup falls outside the returned window: extend /correlation's +60
+ # calendar-day fetch buffer by the correlation window (and a margin for
+ # non-trading days).
+ end_date = datetime.now().strftime("%Y-%m-%d")
+ start_date = (
+ datetime.now() - timedelta(days=days + corr_window + 90)
+ ).strftime("%Y-%m-%d")
+
+ price_series = _fetch_price_series(codes, start_date, end_date)
+
+ if len(price_series) < 2:
+ raise ValueError(
+ f"Could not fetch price data for at least 2 assets. "
+ f"Fetched: {list(price_series.keys())}"
+ )
+
+ returns = _aligned_returns(price_series)
+ density = compute_edge_density(
+ returns, corr_window=corr_window, edge_threshold=edge_threshold
+ )
+ regimes = detect_regimes(
+ density,
+ smooth_window=smooth_window,
+ enter_threshold=enter_threshold,
+ exit_threshold=exit_threshold,
+ )
+ # Trim to the requested window only after the state machine has run, so
+ # the regime state at the window's first bar reflects the full history.
+ if len(regimes) > days:
+ regimes = regimes.iloc[-days:]
+
+ dates = [d.strftime("%Y-%m-%d") for d in regimes.index]
+ density_out = [
+ None if np.isnan(v) else round(float(v), 4) for v in regimes["density"]
+ ]
+ smoothed_out = [
+ None if np.isnan(v) else round(float(v), 4) for v in regimes["smoothed"]
+ ]
+ fused_out = [int(v) for v in regimes["fused"]]
+
+ return {
+ "labels": list(returns.columns),
+ "dates": dates,
+ "density": density_out,
+ "smoothed": smoothed_out,
+ "fused": fused_out,
+ "episodes": _fused_episodes(dates, fused_out),
+ "params": {
+ "days": days,
+ "corr_window": corr_window,
+ "edge_threshold": edge_threshold,
+ "smooth_window": smooth_window,
+ "enter_threshold": enter_threshold,
+ "exit_threshold": exit_threshold,
+ },
+ }
diff --git a/agent/src/api/system_routes.py b/agent/src/api/system_routes.py
index 5c0c0dbfc..8f02ece0b 100644
--- a/agent/src/api/system_routes.py
+++ b/agent/src/api/system_routes.py
@@ -274,6 +274,57 @@ def register_system_routes(
logger.exception("Correlation computation failed for codes=%s", code_list)
raise HTTPException(status_code=500, detail="Correlation computation failed")
+ @app.get("/correlation/regime", dependencies=[Depends(require_auth)])
+ async def get_correlation_regime(
+ request: Request,
+ codes: str = Query(..., description="Comma-separated asset codes, e.g. BTC-USDT,ETH-USDT,SPY"),
+ days: int = Query(90, description="Timeline length in daily bars", ge=30, le=365),
+ corr_window: int = Query(60, description="Rolling correlation window in bars", ge=5, le=250),
+ edge_threshold: float = Query(0.5, description="|corr| level at which a pair counts as an edge", gt=0.0, lt=1.0),
+ smooth_window: int = Query(5, description="Trailing smoothing window in bars", ge=1, le=60),
+ enter_threshold: float = Query(0.65, description="Smoothed density that opens a FUSED regime", gt=0.0, lt=1.0),
+ exit_threshold: float = Query(0.45, description="Smoothed density that closes a FUSED regime (must be below enter_threshold)", gt=0.0, lt=1.0),
+ ):
+ """Correlation-regime timeline: edge density + hysteresis over time.
+
+ Applies Mode 1 of the correlation-regime skill to the same price data
+ /correlation uses: rolling pairwise correlations are reduced to an
+ edge-density series, causally smoothed, and run through a two-threshold
+ hysteresis state machine. Descriptive risk context, not a trading
+ signal. Shares /correlation's rate-limit budget.
+ """
+ from backtest.regime import compute_regime_timeline
+
+ if not _correlation_rate_limiter.allow(_client_key(request)):
+ raise HTTPException(
+ status_code=status.HTTP_429_TOO_MANY_REQUESTS,
+ detail="Rate limit exceeded, try again later",
+ )
+
+ code_list = [c.strip() for c in codes.split(",") if c.strip()]
+ if len(code_list) < 2:
+ raise HTTPException(status_code=400, detail="At least 2 asset codes required")
+ if len(code_list) > 20:
+ raise HTTPException(status_code=400, detail="Maximum 20 assets per request")
+ if exit_threshold >= enter_threshold:
+ raise HTTPException(status_code=400, detail="exit_threshold must be below enter_threshold")
+
+ try:
+ return compute_regime_timeline(
+ codes=code_list,
+ days=days,
+ corr_window=corr_window,
+ edge_threshold=edge_threshold,
+ smooth_window=smooth_window,
+ enter_threshold=enter_threshold,
+ exit_threshold=exit_threshold,
+ )
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc))
+ except Exception:
+ logger.exception("Regime timeline computation failed for codes=%s", code_list)
+ raise HTTPException(status_code=500, detail="Regime timeline computation failed")
+
@app.post("/system/shutdown")
async def shutdown_local_api(
background_tasks: BackgroundTasks,
diff --git a/agent/tests/test_regime.py b/agent/tests/test_regime.py
new file mode 100644
index 000000000..052f13387
--- /dev/null
+++ b/agent/tests/test_regime.py
@@ -0,0 +1,347 @@
+"""Tests for backtest/regime.py and the /correlation/regime route.
+
+The math tests pin the Mode 1 semantics of the correlation-regime skill:
+edge density in [0, 1] with NaN warmup, hysteresis that suppresses dead-band
+chatter, and strict causality (future bars never change past states). The
+route tests mirror test_system_routes.py: auth, validation, shared rate
+limiter, and error masking.
+"""
+
+from __future__ import annotations
+
+import numpy as np
+import pandas as pd
+import pytest
+
+from backtest.regime import (
+ _aligned_returns,
+ _fused_episodes,
+ compute_edge_density,
+ compute_regime_timeline,
+ detect_regimes,
+)
+
+
+def _returns_panel(blocks: list[np.ndarray]) -> pd.DataFrame:
+ """Stack return blocks into a date-indexed multi-asset returns frame."""
+ data = np.vstack(blocks)
+ dates = pd.date_range("2024-01-01", periods=len(data), freq="D")
+ cols = [f"A{k}" for k in range(data.shape[1])]
+ return pd.DataFrame(data, index=dates, columns=cols)
+
+
+def _calm_block(rng: np.random.Generator, n: int, n_assets: int) -> np.ndarray:
+ """Independent idiosyncratic returns — pairwise correlations near zero."""
+ return rng.standard_normal((n, n_assets)) * 0.01
+
+
+def _fused_block(rng: np.random.Generator, n: int, n_assets: int) -> np.ndarray:
+ """One common factor dominating — pairwise correlations near one."""
+ factor = rng.standard_normal((n, 1)) * 0.02
+ return factor + rng.standard_normal((n, n_assets)) * 0.002
+
+
+class TestComputeEdgeDensity:
+ def test_warmup_is_nan_then_values_start(self):
+ rng = np.random.default_rng(3)
+ returns = _returns_panel([_calm_block(rng, 60, 4)])
+ density = compute_edge_density(returns, corr_window=20)
+ assert density.iloc[: 20 - 1].isna().all()
+ assert density.iloc[20 - 1 :].notna().all()
+
+ def test_fused_panel_has_density_one(self):
+ rng = np.random.default_rng(5)
+ returns = _returns_panel([_fused_block(rng, 80, 4)])
+ density = compute_edge_density(returns, corr_window=20)
+ assert density.iloc[-1] == pytest.approx(1.0)
+
+ def test_independent_panel_has_low_density(self):
+ rng = np.random.default_rng(7)
+ returns = _returns_panel([_calm_block(rng, 120, 4)])
+ density = compute_edge_density(returns, corr_window=60)
+ assert density.iloc[-1] <= 0.2
+
+ def test_values_stay_in_unit_interval(self):
+ rng = np.random.default_rng(11)
+ returns = _returns_panel([_calm_block(rng, 50, 3), _fused_block(rng, 50, 3)])
+ density = compute_edge_density(returns, corr_window=15)
+ observed = density.dropna()
+ assert ((observed >= 0.0) & (observed <= 1.0)).all()
+
+
+class TestDetectRegimes:
+ def _series(self, values: list[float]) -> pd.Series:
+ dates = pd.date_range("2024-01-01", periods=len(values), freq="D")
+ return pd.Series(values, index=dates)
+
+ def test_exit_at_or_above_enter_raises(self):
+ with pytest.raises(ValueError, match="exit_threshold"):
+ detect_regimes(self._series([0.1]), enter_threshold=0.5, exit_threshold=0.5)
+
+ def test_enters_and_exits_across_thresholds(self):
+ density = self._series([0.1] * 10 + [0.9] * 10 + [0.1] * 10)
+ result = detect_regimes(density, smooth_window=1)
+ assert result["fused"].iloc[5] == 0
+ assert result["fused"].iloc[15] == 1
+ assert result["fused"].iloc[-1] == 0
+
+ def test_dead_band_chatter_stays_fused(self):
+ # After entry, density oscillating between the two thresholds
+ # (0.45 < value < 0.65) must never close the regime.
+ density = self._series([0.9] * 5 + [0.5, 0.6] * 10)
+ result = detect_regimes(density, smooth_window=1)
+ assert (result["fused"] == 1).all()
+
+ def test_causality_tail_corruption_never_changes_past(self):
+ rng = np.random.default_rng(13)
+ returns = _returns_panel([_calm_block(rng, 60, 4), _fused_block(rng, 60, 4)])
+ corrupted = returns.copy()
+ corrupted.iloc[-10:] = 0.5 # absurd future bars
+
+ def states(frame: pd.DataFrame) -> np.ndarray:
+ density = compute_edge_density(frame, corr_window=20)
+ return detect_regimes(density, smooth_window=3)["fused"].to_numpy()
+
+ np.testing.assert_array_equal(states(returns)[:-10], states(corrupted)[:-10])
+
+
+class TestFusedEpisodes:
+ DATES = [f"2024-01-{d:02d}" for d in range(1, 7)]
+
+ def test_closed_and_ongoing_episodes(self):
+ episodes = _fused_episodes(self.DATES, [0, 1, 1, 0, 0, 1])
+ assert episodes == [
+ {"start": "2024-01-02", "end": "2024-01-03"},
+ {"start": "2024-01-06", "end": None},
+ ]
+
+ def test_never_fused_is_empty(self):
+ assert _fused_episodes(self.DATES, [0] * 6) == []
+
+ def test_always_fused_is_one_open_episode(self):
+ assert _fused_episodes(self.DATES, [1] * 6) == [
+ {"start": "2024-01-01", "end": None}
+ ]
+
+
+class TestAlignedReturns:
+ def test_does_not_forward_fill_missing_prices(self):
+ # Under pandas>=2,<3 a bare pct_change() forward-fills NaN closes,
+ # manufacturing 0% returns; fill_method=None must keep them NaN so
+ # the inner join drops those dates instead.
+ dates = pd.date_range("2024-01-01", periods=6, freq="D")
+ with_gap = pd.DataFrame(
+ {"close": [100.0, np.nan, 102.0, 103.0, 104.0, 105.0]},
+ index=pd.Index(dates, name="trade_date"),
+ )
+ complete = pd.DataFrame(
+ {"close": [50.0, 51.0, 52.0, 53.0, 54.0, 55.0]},
+ index=pd.Index(dates, name="trade_date"),
+ )
+ aligned = _aligned_returns({"GAP": with_gap, "FULL": complete})
+ # The gap day and the day after it (whose return needs the gap day's
+ # close) must both be gone; no zero return may be fabricated.
+ assert len(aligned) == 3
+ assert not (aligned["GAP"] == 0.0).any()
+
+
+class _ServesPanelLoader:
+ """Fake loader serving a prebuilt panel, keyed by normalized symbol."""
+
+ frames: dict[str, pd.DataFrame] = {}
+ name = "fake_panel"
+ markets = {"us_equity"}
+
+ def is_available(self):
+ return True
+
+ def fetch(self, codes, start_date, end_date, *, interval="1D", fields=None):
+ return {c: self.frames[c].copy() for c in codes if c in self.frames}
+
+
+def _install_panel(monkeypatch: pytest.MonkeyPatch, closes: dict[str, np.ndarray]) -> None:
+ from backtest.loaders import registry
+
+ dates = pd.date_range("2024-01-01", periods=len(next(iter(closes.values()))), freq="D")
+ _ServesPanelLoader.frames = {
+ f"{code}.US": pd.DataFrame(
+ {"close": values}, index=pd.Index(dates, name="trade_date")
+ )
+ for code, values in closes.items()
+ }
+ monkeypatch.setattr(registry, "_registered", True)
+ monkeypatch.setattr(registry, "LOADER_REGISTRY", {"fake_panel": _ServesPanelLoader})
+ monkeypatch.setattr(registry, "FALLBACK_CHAINS", {"us_equity": ["fake_panel"]})
+
+
+class TestComputeRegimeTimeline:
+ def test_two_phase_panel_ends_fused_with_open_episode(self, monkeypatch):
+ rng = np.random.default_rng(17)
+ rets = np.vstack(
+ [_calm_block(rng, 140, 4), _fused_block(rng, 80, 4)]
+ )
+ prices = 100.0 * np.cumprod(1.0 + rets, axis=0)
+ codes = ["AAA", "BBB", "CCC", "DDD"]
+ _install_panel(
+ monkeypatch, {c: prices[:, k] for k, c in enumerate(codes)}
+ )
+
+ result = compute_regime_timeline(
+ codes=codes, days=150, corr_window=20, smooth_window=3
+ )
+
+ assert result["labels"] == codes
+ n = len(result["dates"])
+ assert n <= 150
+ assert len(result["density"]) == n
+ assert len(result["smoothed"]) == n
+ assert len(result["fused"]) == n
+ # The fetch buffer keeps warmup NaNs out of the returned window.
+ assert all(v is not None for v in result["density"])
+ assert all(0.0 <= v <= 1.0 for v in result["density"])
+ # The common-factor phase must end the timeline FUSED, as one
+ # still-open episode.
+ assert result["fused"][-1] == 1
+ assert result["episodes"]
+ assert result["episodes"][-1]["end"] is None
+ assert result["params"]["corr_window"] == 20
+
+ def test_invalid_thresholds_fail_before_any_fetch(self):
+ with pytest.raises(ValueError, match="exit_threshold"):
+ compute_regime_timeline(
+ codes=["AAA", "BBB"], enter_threshold=0.5, exit_threshold=0.6
+ )
+
+ def test_fewer_than_two_fetched_assets_raises(self, monkeypatch):
+ from backtest.loaders import registry
+
+ monkeypatch.setattr(registry, "_registered", True)
+ monkeypatch.setattr(registry, "LOADER_REGISTRY", {})
+ monkeypatch.setattr(registry, "FALLBACK_CHAINS", {})
+ with pytest.raises(ValueError, match="at least 2 assets"):
+ compute_regime_timeline(codes=["AAA", "BBB"])
+
+
+# ---------------------------------------------------------------------------
+# /correlation/regime route (mirrors test_system_routes.py)
+# ---------------------------------------------------------------------------
+
+
+def local_client(monkeypatch: pytest.MonkeyPatch):
+ """Loopback client with no API key configured (dev-mode: auth passes)."""
+ import api_server
+ from fastapi.testclient import TestClient
+
+ monkeypatch.delenv("API_AUTH_KEY", raising=False)
+ monkeypatch.setattr(api_server, "_API_KEY", "")
+ return TestClient(api_server.app, client=("127.0.0.1", 50000))
+
+
[email protected](autouse=True)
+def _reset_correlation_limiter():
+ """Clear the module-level rate limiter so tests never leak hits into each other."""
+ from src.api import system_routes
+
+ system_routes._correlation_rate_limiter.reset()
+
+
+_STUB_RESULT = {
+ "labels": ["AAPL", "SPY"],
+ "dates": ["2024-01-01"],
+ "density": [0.5],
+ "smoothed": [0.5],
+ "fused": [0],
+ "episodes": [],
+ "params": {},
+}
+
+
+def test_regime_route_returns_computation_result(local_client, monkeypatch):
+ import backtest.regime as regime
+
+ monkeypatch.setattr(regime, "compute_regime_timeline", lambda **_kwargs: _STUB_RESULT)
+ resp = local_client.get("/correlation/regime", params={"codes": "AAPL,SPY"})
+ assert resp.status_code == 200
+ assert resp.json() == _STUB_RESULT
+
+
+def test_regime_route_requires_auth_for_remote_client(monkeypatch):
+ import api_server
+ from fastapi.testclient import TestClient
+
+ monkeypatch.setattr(api_server, "_API_KEY", "server-secret")
+ remote = TestClient(api_server.app, client=("203.0.113.9", 51000))
+ resp = remote.get("/correlation/regime", params={"codes": "AAPL,SPY"})
+ assert resp.status_code == 401
+
+
+def test_regime_route_validates_code_count(local_client):
+ too_few = local_client.get("/correlation/regime", params={"codes": "AAPL"})
+ assert too_few.status_code == 400
+ too_many = local_client.get(
+ "/correlation/regime", params={"codes": ",".join(f"S{i}" for i in range(21))}
+ )
+ assert too_many.status_code == 400
+
+
+def test_regime_route_rejects_inverted_thresholds(local_client):
+ resp = local_client.get(
+ "/correlation/regime",
+ params={"codes": "AAPL,SPY", "enter_threshold": 0.5, "exit_threshold": 0.6},
+ )
+ assert resp.status_code == 400
+ assert resp.json()["detail"] == "exit_threshold must be below enter_threshold"
+
+
+def test_regime_route_rejects_days_below_floor(local_client):
+ # days < 30 with a 60-bar correlation window yields an empty timeline, so
+ # the route floors days at 30 (FastAPI validation → 422).
+ resp = local_client.get(
+ "/correlation/regime", params={"codes": "AAPL,SPY", "days": 20}
+ )
+ assert resp.status_code == 422
+
+
+def test_regime_route_value_error_surfaces_and_generic_is_masked(
+ local_client, monkeypatch
+):
+ import backtest.regime as regime
+
+ def _bad(**_kwargs):
+ raise ValueError("Not enough overlapping history")
+
+ monkeypatch.setattr(regime, "compute_regime_timeline", _bad)
+ resp = local_client.get("/correlation/regime", params={"codes": "AAPL,SPY"})
+ assert resp.status_code == 400
+ assert resp.json()["detail"] == "Not enough overlapping history"
+
+ def _boom(**_kwargs):
+ raise RuntimeError("sensitive internal detail: db=prod host=10.0.0.5")
+
+ monkeypatch.setattr(regime, "compute_regime_timeline", _boom)
+ resp = local_client.get("/correlation/regime", params={"codes": "AAPL,SPY"})
+ assert resp.status_code == 500
+ assert resp.json()["detail"] == "Regime timeline computation failed"
+
+
+def test_regime_route_shares_correlation_rate_limit_budget(local_client, monkeypatch):
+ """One budget across /correlation and /correlation/regime, per maintainer ask."""
+ import backtest.correlation as corr
+ from src.api import system_routes
+
+ monkeypatch.setattr(
+ corr,
+ "compute_correlation_matrix",
+ lambda **_kwargs: {"labels": ["AAPL", "SPY"], "matrix": [[1.0, 0.5], [0.5, 1.0]]},
+ )
+ monkeypatch.setattr(
+ system_routes,
+ "_correlation_rate_limiter",
+ system_routes._SlidingWindowRateLimiter(max_requests=1, window_seconds=60.0),
+ )
+
+ ok = local_client.get("/correlation", params={"codes": "AAPL,SPY"})
+ blocked = local_client.get("/correlation/regime", params={"codes": "AAPL,SPY"})
+ assert ok.status_code == 200
+ assert blocked.status_code == 429
diff --git a/frontend/src/components/charts/RegimeTimeline.tsx b/frontend/src/components/charts/RegimeTimeline.tsx
new file mode 100644
index 000000000..80150e475
--- /dev/null
+++ b/frontend/src/components/charts/RegimeTimeline.tsx
@@ -0,0 +1,133 @@
+import { useEffect, useRef } from "react";
+import i18n from "@/i18n";
+import type { CorrelationRegimeResponse } from "@/lib/api";
+import { getChartTheme } from "@/lib/chart-theme";
+import { echarts } from "@/lib/echarts";
+import { useDarkMode } from "@/hooks/useDarkMode";
+
+interface Props {
+ data: CorrelationRegimeResponse;
+ height?: number;
+}
+
+export function RegimeTimeline({ data, height = 260 }: Props) {
+ const ref = useRef<HTMLDivElement>(null);
+ const { dark } = useDarkMode();
+
+ useEffect(() => {
+ if (!ref.current || data.dates.length === 0) return;
+ const t = getChartTheme();
+ const chart = echarts.init(ref.current);
+
+ const { dates, density, smoothed, episodes, params } = data;
+ const densityName = i18n.t("correlation.regimeDensity");
+ const smoothedName = i18n.t("correlation.regimeSmoothed");
+ const fusedLabel = i18n.t("correlation.regimeFused");
+ const lastDate = dates[dates.length - 1];
+ const markAreas = episodes.map((e) => [
+ {
+ name: fusedLabel,
+ xAxis: e.start,
+ label: { color: t.downColor, fontSize: 10, position: "insideTop" },
+ },
+ { xAxis: e.end ?? lastDate },
+ ]);
+
+ chart.setOption({
+ backgroundColor: "transparent",
+ tooltip: {
+ trigger: "axis",
+ backgroundColor: t.tooltipBg,
+ borderColor: t.tooltipBorder,
+ textStyle: { color: t.tooltipText, fontSize: 11 },
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ formatter: (params_: any) => {
+ if (!Array.isArray(params_) || !params_.length) return "";
+ let html = `<b>${params_[0].axisValue}</b>`;
+ for (const p of params_) {
+ const val = p.value === null || p.value === undefined ? "—" : Number(p.value).toFixed(4);
+ html += `<br/>${p.marker} ${p.seriesName}: <b>${val}</b>`;
+ }
+ return html;
+ },
+ },
+ legend: {
+ data: [densityName, smoothedName],
+ textStyle: { color: t.textColor, fontSize: 11 },
+ right: 8,
+ top: 4,
+ },
+ grid: { left: 8, right: 8, top: 32, bottom: 8, containLabel: true },
+ xAxis: {
+ type: "category",
+ data: dates,
+ axisLine: { lineStyle: { color: t.axisColor } },
+ axisLabel: { color: t.textColor, fontSize: 10 },
+ },
+ yAxis: {
+ type: "value",
+ min: 0,
+ max: 1,
+ splitLine: { lineStyle: { color: t.gridColor } },
+ axisLabel: { color: t.textColor, fontSize: 10 },
+ },
+ series: [
+ {
+ name: densityName,
+ type: "line",
+ data: density,
+ color: t.axisColor,
+ smooth: false,
+ symbol: "none",
+ lineStyle: { color: t.axisColor, width: 1, opacity: 0.7 },
+ },
+ {
+ name: smoothedName,
+ type: "line",
+ data: smoothed,
+ color: t.infoColor,
+ smooth: false,
+ symbol: "none",
+ lineStyle: { color: t.infoColor, width: 2 },
+ markArea: {
+ silent: true,
+ itemStyle: { color: t.downColor + "22" },
+ data: markAreas,
+ },
+ markLine: {
+ silent: true,
+ symbol: "none",
+ lineStyle: { color: t.textColor, type: "dashed", width: 1 },
+ data: [
+ {
+ yAxis: params.enter_threshold,
+ label: {
+ formatter: `${i18n.t("correlation.regimeEnterThreshold")}: ${params.enter_threshold}`,
+ position: "insideEndTop",
+ fontSize: 10,
+ color: t.textColor,
+ },
+ },
+ {
+ yAxis: params.exit_threshold,
+ label: {
+ formatter: `${i18n.t("correlation.regimeExitThreshold")}: ${params.exit_threshold}`,
+ position: "insideEndBottom",
+ fontSize: 10,
+ color: t.textColor,
+ },
+ },
+ ],
+ },
+ },
+ ],
+ });
+
+ const ro = new ResizeObserver(() => chart.resize());
+ ro.observe(ref.current!);
+ return () => { ro.disconnect(); chart.dispose(); };
+ }, [data, dark]);
+
+ if (data.dates.length === 0) return null;
+ return <div ref={ref} style={{ height }} />;
+}
diff --git a/frontend/src/i18n/locales/ar.json b/frontend/src/i18n/locales/ar.json
index d221c64d0..a15c5866a 100644
--- a/frontend/src/i18n/locales/ar.json
+++ b/frontend/src/i18n/locales/ar.json
@@ -527,7 +527,14 @@
"loading": "جارٍ التحميل...",
"method_pearson": "بيرسون",
"method_spearman": "سبيرمان",
- "failedToCompute": "فشل احتساب الارتباط"
+ "failedToCompute": "فشل احتساب الارتباط",
+ "regimeTimeline": "الخط الزمني لنظام الارتباط",
+ "regimeTimelineHint": "كثافة الحواف مع التباطؤ عبر الزمن — سياق وصفي للمخاطر وليس إشارة تداول",
+ "regimeDensity": "كثافة الحواف",
+ "regimeSmoothed": "الكثافة الممهدة",
+ "regimeFused": "مندمج (FUSED)",
+ "regimeEnterThreshold": "عتبة الدخول",
+ "regimeExitThreshold": "عتبة الخروج"
},
"alphaZoo": {
"title": "Alpha Zoo",
diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.json
index 9fab60532..3caeb1a9a 100644
--- a/frontend/src/i18n/locales/en.json
+++ b/frontend/src/i18n/locales/en.json
@@ -532,7 +532,14 @@
"method_spearman": "Spearman",
"compute": "Compute",
"loading": "Computing...",
- "failedToCompute": "Failed to compute correlation"
+ "failedToCompute": "Failed to compute correlation",
+ "regimeTimeline": "Regime timeline",
+ "regimeTimelineHint": "Edge density + hysteresis over time — descriptive risk context, not a trading signal",
+ "regimeDensity": "Edge density",
+ "regimeSmoothed": "Smoothed",
+ "regimeFused": "FUSED",
+ "regimeEnterThreshold": "enter",
+ "regimeExitThreshold": "exit"
},
"alphaZoo": {
"title": "Alpha Zoo",
diff --git a/frontend/src/i18n/locales/ja.json b/frontend/src/i18n/locales/ja.json
index 631104976..ac85efe93 100644
--- a/frontend/src/i18n/locales/ja.json
+++ b/frontend/src/i18n/locales/ja.json
@@ -527,7 +527,14 @@
"loading": "読み込み中...",
"method_pearson": "ピアソン",
"method_spearman": "スピアマン",
- "failedToCompute": "相関の計算に失敗しました"
+ "failedToCompute": "相関の計算に失敗しました",
+ "regimeTimeline": "相関レジーム・タイムライン",
+ "regimeTimelineHint": "エッジ密度とヒステリシスの時系列 — 記述的なリスク文脈であり、売買シグナルではありません",
+ "regimeDensity": "エッジ密度",
+ "regimeSmoothed": "平滑化密度",
+ "regimeFused": "融合期 (FUSED)",
+ "regimeEnterThreshold": "開始しきい値",
+ "regimeExitThreshold": "終了しきい値"
},
"alphaZoo": {
"title": "Alpha Zoo",
diff --git a/frontend/src/i18n/locales/ko.json b/frontend/src/i18n/locales/ko.json
index 9ff95ebac..c1a7b82e4 100644
--- a/frontend/src/i18n/locales/ko.json
+++ b/frontend/src/i18n/locales/ko.json
@@ -527,7 +527,14 @@
"loading": "불러오는 중...",
"method_pearson": "피어슨",
"method_spearman": "스피어만",
- "failedToCompute": "상관 계산에 실패했습니다"
+ "failedToCompute": "상관 계산에 실패했습니다",
+ "regimeTimeline": "상관관계 국면 타임라인",
+ "regimeTimelineHint": "엣지 밀도 + 히스테리시스 시계열 — 설명용 리스크 컨텍스트이며 매매 신호가 아닙니다",
+ "regimeDensity": "엣지 밀도",
+ "regimeSmoothed": "평활 밀도",
+ "regimeFused": "융합 구간 (FUSED)",
+ "regimeEnterThreshold": "진입 임계값",
+ "regimeExitThreshold": "이탈 임계값"
},
"alphaZoo": {
"title": "Alpha Zoo",
diff --git a/frontend/src/i18n/locales/zh-CN.json b/frontend/src/i18n/locales/zh-CN.json
index 52a77b2a0..0949066dc 100644
--- a/frontend/src/i18n/locales/zh-CN.json
+++ b/frontend/src/i18n/locales/zh-CN.json
@@ -527,7 +527,14 @@
"loading": "加载中...",
"method_pearson": "皮尔逊相关",
"method_spearman": "斯皮尔曼秩相关",
- "failedToCompute": "计算相关性失败"
+ "failedToCompute": "计算相关性失败",
+ "regimeTimeline": "相关性状态时间线",
+ "regimeTimelineHint": "边密度 + 滞回状态机的时间序列 — 描述性风险背景,并非交易信号",
+ "regimeDensity": "边密度",
+ "regimeSmoothed": "平滑密度",
+ "regimeFused": "融合期 (FUSED)",
+ "regimeEnterThreshold": "进入阈值",
+ "regimeExitThreshold": "退出阈值"
},
"alphaZoo": {
"title": "Alpha 因子库",
diff --git a/frontend/src/lib/__tests__/api.test.ts b/frontend/src/lib/__tests__/api.test.ts
index eb0211ca6..f87315ecf 100644
--- a/frontend/src/lib/__tests__/api.test.ts
+++ b/frontend/src/lib/__tests__/api.test.ts
@@ -93,4 +93,38 @@ describe("api request helper", () => {
}),
);
});
+
+ it("sends the stored API key when fetching a correlation regime timeline", async () => {
+ vi.stubGlobal("localStorage", {
+ getItem: vi.fn(() => "remote-test-key"),
+ setItem: vi.fn(),
+ removeItem: vi.fn(),
+ });
+ const regime = {
+ labels: ["A", "B"],
+ dates: ["2024-01-01"],
+ density: [0.5],
+ smoothed: [0.5],
+ fused: [0],
+ episodes: [],
+ params: {},
+ };
+ const fetchMock = vi.fn().mockResolvedValue(
+ new Response(JSON.stringify(regime), {
+ status: 200,
+ headers: { "content-type": "application/json" },
+ }),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+
+ const { api } = await loadApiModule();
+
+ await expect(api.getCorrelationRegime("A,B", 90)).resolves.toEqual(regime);
+ expect(fetchMock).toHaveBeenCalledWith(
+ "/correlation/regime?codes=A%2CB&days=90",
+ expect.objectContaining({
+ headers: expect.objectContaining({ Authorization: "Bearer remote-test-key" }),
+ }),
+ );
+ });
});
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 09191600f..1e4ba189a 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -24,6 +24,28 @@ export interface CorrelationResponse {
matrix: number[][];
}
+export interface RegimeEpisode {
+ start: string;
+ end: string | null;
+}
+
+export interface CorrelationRegimeResponse {
+ labels: string[];
+ dates: string[];
+ density: (number | null)[];
+ smoothed: (number | null)[];
+ fused: number[];
+ episodes: RegimeEpisode[];
+ params: {
+ days: number;
+ corr_window: number;
+ edge_threshold: number;
+ smooth_window: number;
+ enter_threshold: number;
+ exit_threshold: number;
+ };
+}
+
async function errorFromResponse(res: Response): Promise<ApiError> {
let detail = `HTTP ${res.status}`;
try {
@@ -93,6 +115,10 @@ export const api = {
request<CorrelationResponse>(
`/correlation?codes=${encodeURIComponent(codes)}&days=${encodeURIComponent(String(days))}&method=${encodeURIComponent(method)}`,
),
+ getCorrelationRegime: (codes: string, days: number) =>
+ request<CorrelationRegimeResponse>(
+ `/correlation/regime?codes=${encodeURIComponent(codes)}&days=${encodeURIComponent(String(days))}`,
+ ),
listRuns: (limit?: number) => request<RunListItem[]>(`/runs${limit ? `?limit=${encodeURIComponent(String(limit))}` : ""}`),
getRun: (id: string, params: RunDetailParams = {}) => {
const q = new URLSearchParams();
diff --git a/frontend/src/pages/Correlation.tsx b/frontend/src/pages/Correlation.tsx
index d3012446a..4e966cbe9 100644
--- a/frontend/src/pages/Correlation.tsx
+++ b/frontend/src/pages/Correlation.tsx
@@ -2,7 +2,8 @@ import i18n from '@/i18n';
import { useRef, useState } from "react";
import { BarChart3 } from "lucide-react";
import { CorrelationMatrix } from "@/components/charts/CorrelationMatrix";
-import { api } from "@/lib/api";
+import { RegimeTimeline } from "@/components/charts/RegimeTimeline";
+import { api, type CorrelationRegimeResponse } from "@/lib/api";
const WINDOWS = [30, 60, 90, 180, 365] as const;
@@ -10,17 +11,20 @@ export function Correlation() {
const [codes, setCodes] = useState("000001.SZ,600519.SH,000858.SZ,601318.SH");
const [days, setDays] = useState<number>(90);
const [method, setMethod] = useState<"pearson" | "spearman">("pearson");
+ const [showRegime, setShowRegime] = useState(false);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [labels, setLabels] = useState<string[]>([]);
const [matrix, setMatrix] = useState<number[][]>([]);
+ const [regime, setRegime] = useState<CorrelationRegimeResponse | null>(null);
const requestGeneration = useRef(0);
const invalidateResult = () => {
requestGeneration.current += 1;
setLabels([]);
setMatrix([]);
+ setRegime(null);
setError(null);
setLoading(false);
};
@@ -30,12 +34,17 @@ export function Correlation() {
setError(null);
setLabels([]);
setMatrix([]);
+ setRegime(null);
setLoading(true);
try {
- const result = await api.getCorrelation(codes, days, method);
+ const [result, regimeResult] = await Promise.all([
+ api.getCorrelation(codes, days, method),
+ showRegime ? api.getCorrelationRegime(codes, days) : Promise.resolve(null),
+ ]);
if (requestGeneration.current === generation) {
setLabels(result.labels);
setMatrix(result.matrix);
+ setRegime(regimeResult);
}
} catch (e) {
if (requestGeneration.current === generation) {
@@ -119,6 +128,26 @@ export function Correlation() {
</div>
</div>
+ <div className="flex flex-col gap-1.5">
+ <label className="flex items-center gap-2 text-sm font-medium cursor-pointer">
+ <input
+ type="checkbox"
+ checked={showRegime}
+ onChange={(e) => {
+ invalidateResult();
+ setShowRegime(e.target.checked);
+ }}
+ className="h-4 w-4"
+ />
+ {i18n.t("correlation.regimeTimeline")}
+ </label>
+ {showRegime && (
+ <p className="text-xs text-muted-foreground">
+ {i18n.t("correlation.regimeTimelineHint")}
+ </p>
+ )}
+ </div>
+
<button
onClick={compute}
disabled={loading}
@@ -135,6 +164,9 @@ export function Correlation() {
</div>
)}
+ {/* Regime timeline (above the matrix when enabled) */}
+ {regime && <RegimeTimeline data={regime} height={260} />}
+
{/* Chart */}
{labels.length > 0 && <CorrelationMatrix labels={labels} matrix={matrix} height={520} />}
</div>