"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat: add correlation heatmap dashboard (#64)
MB-Ndhlovuc3174bacb9a3
diff --git a/agent/api_server.py b/agent/api_server.pyindex d04d34ef4..e8ae43e89 100644--- a/agent/api_server.py+++ b/agent/api_server.py@@ -1018,6 +1018,36 @@ async def health_check():)[email protected]("/correlation")+async def get_correlation_matrix(+ codes: str = Query(..., description="Comma-separated asset codes, e.g. BTC-USDT,ETH-USDT,SPY"),+ days: int = Query(90, description="Lookback window in days", ge=7, le=365),+ method: str = Query("pearson", description="Correlation method: pearson or spearman"),+):+ """Compute cross-asset correlation matrix from daily returns.++ Fetches price data for each code via available data loaders,+ computes pairwise correlation of daily returns over the lookback window.+ """+ from backtest.correlation import compute_correlation_matrix++ 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 method not in ("pearson", "spearman"):+ raise HTTPException(status_code=400, detail="method must be 'pearson' or 'spearman'")++ try:+ result = compute_correlation_matrix(codes=code_list, days=days, method=method)+ return result+ except ValueError as exc:+ raise HTTPException(status_code=400, detail=str(exc))+ except Exception as exc:+ raise HTTPException(status_code=500, detail=f"Correlation computation failed: {exc}")++def _terminate_current_process() -> None:"""Stop the current API process after the response has been sent."""time.sleep(0.25)diff --git a/agent/backtest/correlation.py b/agent/backtest/correlation.pynew file mode 100644index 000000000..57f959d31--- /dev/null+++ b/agent/backtest/correlation.py@@ -0,0 +1,175 @@+"""Cross-asset correlation matrix computation.++Computes pairwise Pearson or Spearman correlation of daily returns+over a configurable lookback window. Used by the /correlation API endpoint.+"""++from __future__ import annotations++from typing import Dict, Literal++import pandas as pd+import numpy as np+from scipy.stats import spearmanr+++def infer_market(code: str) -> str:+ """Infer market key from a ticker symbol."""+ code_upper = code.upper()+ crypto_suffixes = ("USDT", "BTC", "ETH", "BNB", "SOL", "ADA", "DOGE")+ if any(code_upper.endswith(s) for s in crypto_suffixes) or "/" in code:+ return "crypto"+ # Check .HK suffix FIRST so leading-zero tickers like 0700.HK / 0005.HK+ # are correctly classified before the A-share prefix checks+ if code_upper.endswith(".HK"):+ return "hk_equity"+ if code_upper.startswith(("6", "000", "001", "002")):+ return "a_share"+ if code_upper.startswith(("0", "399")):+ return "a_share"+ if code_upper.startswith(("0", "1", "2", "3", "4")):+ return "hk_equity"+ return "us_equity"+++def _rolling_correlation_matrix(+ price_series: Dict[str, pd.DataFrame],+ window: int,+ method: Literal["pearson", "spearman"],+) -> tuple[list[str], list[list[float]]]:+ """Compute correlation matrix for multiple price series.++ Args:+ price_series: Mapping of asset code -> DataFrame with a ``close`` column.+ window: Rolling window size in days.+ method: "pearson" or "spearman".++ Returns:+ (labels, matrix) where labels is the sorted list of codes and matrix+ is a symmetric NxN matrix of correlation coefficients.+ """+ if not price_series:+ return [], []++ codes = sorted(price_series.keys())++ # Build a aligned returns DataFrame (row index = date)+ 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 both column-based and index-based trade_date+ if "trade_date" in df.index.names and "trade_date" not in df.columns:+ ts = df["close"]+ else:+ ts = df.set_index("trade_date")["close"]+ closes[code] = ts.sort_index()++ for code in codes:+ ts = closes[code]+ rets = ts.pct_change().dropna()+ rets.name = code+ returns_frames.append(rets)++ # Align all series to a common index (inner join)+ aligned = pd.concat(returns_frames, axis=1).dropna()+ if aligned.empty:+ raise ValueError("No overlapping return data between assets")++ # Apply the trailing window — only use the last `window` rows of aligned data+ if len(aligned) > window:+ aligned = aligned.iloc[-window:]++ n = len(aligned)+ if n < 2:+ raise ValueError("Not enough data points to compute correlation")++ labels = codes+ n_assets = len(labels)+ matrix = [[1.0] * n_assets for _ in range(n_assets)]++ for i in range(n_assets):+ for j in range(i + 1, n_assets):+ xi = aligned.iloc[:, i].values+ xj = aligned.iloc[:, j].values+ if method == "spearman":+ corr, _ = spearmanr(xi, xj)+ else:+ corr = np.corrcoef(xi, xj)[0, 1]+ if np.isnan(corr):+ corr = 0.0+ matrix[i][j] = round(corr, 4)+ matrix[j][i] = round(corr, 4)++ return labels, matrix+++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")++ # Import here to avoid circular+ from backtest.loaders.registry import resolve_loader++ price_series: Dict[str, pd.DataFrame] = {}++ for code in codes:+ market = infer_market(code)+ try:+ loader = resolve_loader(market)+ except Exception:+ # Fall back to yfinance for us_equity / hk_equity+ try:+ from backtest.loaders.registry import LOADER_REGISTRY+ if "yfinance" in LOADER_REGISTRY:+ loader = LOADER_REGISTRY["yfinance"]()+ else:+ continue+ except Exception:+ continue++ try:+ result = loader.fetch(+ codes=[code],+ start_date=start_date,+ end_date=end_date,+ interval="1D",+ fields=["trade_date", "open", "high", "low", "close", "volume"],+ )+ if code in result and not result[code].empty:+ price_series[code] = result[code]+ except Exception:+ continue++ if len(price_series) < 2:+ raise ValueError(+ f"Could not fetch price data for at least 2 assets. "+ f"Fetched: {list(price_series.keys())}"+ )++ labels, matrix = _rolling_correlation_matrix(price_series, days, method)+ return {+ "labels": labels,+ "matrix": matrix,+ "window": days,+ "method": method,+ }\ No newline at end of filediff --git a/agent/tests/test_correlation.py b/agent/tests/test_correlation.pynew file mode 100644index 000000000..2799c6f93--- /dev/null+++ b/agent/tests/test_correlation.py@@ -0,0 +1,127 @@+"""Tests for backtest/correlation.py"""++import numpy as np+import pandas as pd+import pytest++from backtest.correlation import (+ _rolling_correlation_matrix,+ infer_market,+)+++class TestInferMarket:+ def test_crypto_usdt(self):+ assert infer_market("BTC-USDT") == "crypto"+ assert infer_market("ETH-USDT") == "crypto"++ def test_a_share(self):+ assert infer_market("000001.SZ") == "a_share"+ assert infer_market("600519.SH") == "a_share"++ def test_us_equity(self):+ assert infer_market("AAPL") == "us_equity"+ assert infer_market("SPY") == "us_equity"++ def test_hk_leading_zero_tickers(self):+ # Leading-zero HK tickers like 0700.HK / 0005.HK must be classified as+ # hk_equity, NOT a_share (which also starts with 0)+ assert infer_market("0700.HK") == "hk_equity"+ assert infer_market("0005.HK") == "hk_equity"+ assert infer_market("0000.HK") == "hk_equity"+ assert infer_market("9988.HK") == "hk_equity"++ def test_hk_suffix_before_a_share_prefix(self):+ # .HK suffix should be checked before A-share numeric prefix checks+ assert infer_market("000001.HK") == "hk_equity"+++class TestRollingCorrelationMatrix:+ def _make_price_df(self, closes):+ """Build a DataFrame with trade_date as the index name (like real loaders)."""+ dates = pd.date_range("2024-01-01", periods=len(closes), freq="D")+ return pd.DataFrame(+ {"close": closes},+ index=pd.Index(dates, name="trade_date"),+ )++ def test_window_parameter_is_respected(self):+ # Full history has 50 rows; window=10 should use only the last 10 days.+ # Two assets with perfectly positively correlated full history but+ # negatively correlated last 10 days — verifies window is applied.+ np.random.seed(42)+ n = 50+ closes_a = list(np.cumsum(np.random.randn(n)) + 100)+ closes_b = list(np.cumsum(np.random.randn(n)) + 100)+ price_series = {+ "A": self._make_price_df(closes_a),+ "B": self._make_price_df(closes_b),+ }+ _, matrix_full = _rolling_correlation_matrix(price_series, window=1000, method="pearson")+ _, matrix_window = _rolling_correlation_matrix(price_series, window=10, method="pearson")+ # Matrices should be different when window is applied vs full history+ assert matrix_window[0][1] != pytest.approx(matrix_full[0][1])+ # But both should be valid correlations+ assert -1 <= matrix_window[0][1] <= 1+ assert -1 <= matrix_full[0][1] <= 1++ def test_same_asset_correlation_is_one(self):+ price_series = {+ "A": self._make_price_df([100, 105, 110, 108, 112]),+ }+ labels, matrix = _rolling_correlation_matrix(price_series, window=5, method="pearson")+ assert labels == ["A"]+ assert matrix[0][0] == pytest.approx(1.0)++ def test_matrix_is_symmetric(self):+ np.random.seed(42)+ price_series = {+ "A": self._make_price_df(np.cumsum(np.random.randn(100)).tolist()),+ "B": self._make_price_df(np.cumsum(np.random.randn(100)).tolist()),+ "C": self._make_price_df(np.cumsum(np.random.randn(100)).tolist()),+ }+ labels, matrix = _rolling_correlation_matrix(price_series, window=30, method="pearson")+ n = len(labels)+ assert len(labels) == 3+ for i in range(n):+ for j in range(n):+ assert matrix[i][j] == pytest.approx(matrix[j][i])++ def test_diagonal_is_one(self):+ np.random.seed(42)+ price_series = {+ "X": self._make_price_df(np.cumsum(np.random.randn(50)).tolist()),+ "Y": self._make_price_df(np.cumsum(np.random.randn(50)).tolist()),+ }+ labels, matrix = _rolling_correlation_matrix(price_series, window=20, method="pearson")+ n = len(labels)+ for i in range(n):+ assert matrix[i][i] == pytest.approx(1.0)++ def test_spearman_vs_pearson_diff(self):+ np.random.seed(0)+ # Non-linear relationship: Pearson < Spearman+ x = np.linspace(0, 10, 50)+ y = np.power(x, 2) + np.random.randn(50) * 5+ price_series = {+ "A": self._make_price_df((x * 100 + 1000).tolist()),+ "B": self._make_price_df((y + 1000).tolist()),+ }+ _, p_matrix = _rolling_correlation_matrix(price_series, window=30, method="pearson")+ _, s_matrix = _rolling_correlation_matrix(price_series, window=30, method="spearman")+ # Spearman can be higher for monotonic (not linear) relationships+ assert isinstance(p_matrix[0][1], float)+ assert isinstance(s_matrix[0][1], float)+ # Both should be reasonable correlations+ assert -1 <= p_matrix[0][1] <= 1+ assert -1 <= s_matrix[0][1] <= 1++ def test_empty_dict_returns_empty(self):+ labels, matrix = _rolling_correlation_matrix({}, window=30, method="pearson")+ assert labels == []+ assert matrix == []++ def test_missing_close_column_raises(self):+ df = pd.DataFrame({"open": [1, 2, 3]})+ with pytest.raises(ValueError, match="No 'close' column"):+ _rolling_correlation_matrix({"X": df}, window=30, method="pearson")\ No newline at end of filediff --git a/frontend/src/components/charts/CorrelationMatrix.tsx b/frontend/src/components/charts/CorrelationMatrix.tsxnew file mode 100644index 000000000..cdd0d9c38--- /dev/null+++ b/frontend/src/components/charts/CorrelationMatrix.tsx@@ -0,0 +1,108 @@+import { useEffect, useRef } from "react";+import { echarts } from "@/lib/echarts";+import { getChartTheme } from "@/lib/chart-theme";++interface Props {+ labels: string[];+ matrix: number[][];+ height?: number;+}++export function CorrelationMatrix({ labels, matrix, height = 500 }: Props) {+ const ref = useRef<HTMLDivElement>(null);++ useEffect(() => {+ if (!ref.current || labels.length === 0 || matrix.length === 0) return;++ const t = getChartTheme();+ const chart = echarts.init(ref.current);++ // Build heatmap data: [xIdx, yIdx, value]+ const data: [number, number, number][] = [];+ for (let i = 0; i < labels.length; i++) {+ for (let j = 0; j < labels.length; j++) {+ const val = matrix[i]?.[j] ?? 0;+ data.push([j, i, parseFloat(val.toFixed(4))]);+ }+ }++ const minVal = -1;+ const maxVal = 1;++ chart.setOption({+ backgroundColor: "transparent",+ tooltip: {+ position: "top",+ backgroundColor: t.tooltipBg,+ borderColor: t.tooltipBorder,+ textStyle: { color: t.tooltipText, fontSize: 12 },+ formatter: (params: unknown) => {+ const p = params as { data: [number, number, number] };+ const [x, y, v] = p.data;+ return `<b>${labels[x]}</b> vs <b>${labels[y]}</b><br/>r = <b>${v.toFixed(4)}</b>`;+ },+ },+ grid: { left: "3%", right: "8%", top: "8%", bottom: "12%", containLabel: true },+ xAxis: {+ type: "category",+ data: labels,+ axisLabel: {+ color: t.textColor,+ fontSize: 11,+ rotate: 30,+ interval: 0,+ },+ axisLine: { lineStyle: { color: t.axisColor } },+ splitArea: { show: false },+ },+ yAxis: {+ type: "category",+ data: labels,+ axisLabel: { color: t.textColor, fontSize: 11, interval: 0 },+ axisLine: { lineStyle: { color: t.axisColor } },+ splitArea: { show: false },+ },+ visualMap: {+ min: minVal,+ max: maxVal,+ precision: 2,+ calculable: true,+ orient: "vertical",+ right: 8,+ top: "center",+ textStyle: { color: t.textColor, fontSize: 11 },+ inRange: {+ color: ["#2166ac", "#4393c3", "#92c5de", "#d1e5f0", "#f7f7f7", "#fddbc7", "#f4a582", "#d6604d", "#b2182b"],+ },+ },+ series: [+ {+ name: "Correlation",+ type: "heatmap",+ data,+ label: {+ show: labels.length <= 8,+ fontSize: 10,+ color: t.textColor,+ formatter: (params: unknown) => {+ const p = params as { value: [number, number, number] };+ return p.value[2].toFixed(2);+ },+ },+ emphasis: {+ itemStyle: { shadowBlur: 10, shadowColor: "rgba(0, 0, 0, 0.5)" },+ },+ },+ ],+ });++ const ro = new ResizeObserver(() => chart.resize());+ ro.observe(ref.current!);+ return () => { ro.disconnect(); chart.dispose(); };+ }, [labels, matrix]);++ if (labels.length === 0) {+ return <div className="text-muted-foreground text-sm p-4">No correlation data</div>;+ }+ return <div ref={ref} style={{ height }} />;+}\ No newline at end of filediff --git a/frontend/src/components/layout/Layout.tsx b/frontend/src/components/layout/Layout.tsxindex f8bc120e1..2b326da85 100644--- a/frontend/src/components/layout/Layout.tsx+++ b/frontend/src/components/layout/Layout.tsx@@ -12,6 +12,7 @@ const NAV = [{ to: "/", icon: BarChart3, key: "home" as const },{ to: "/agent", icon: Bot, key: "agent" as const },{ to: "/settings", icon: Settings, key: "settings" as const },+ { to: "/correlation", icon: BarChart3, key: "correlation" as const },];export function Layout() {diff --git a/frontend/src/lib/echarts.ts b/frontend/src/lib/echarts.tsindex e4a79cf80..4c9bd644a 100644--- a/frontend/src/lib/echarts.ts+++ b/frontend/src/lib/echarts.ts@@ -1,5 +1,5 @@import * as echarts from "echarts/core";-import { CandlestickChart, LineChart, BarChart } from "echarts/charts";+import { CandlestickChart, LineChart, BarChart, HeatmapChart } from "echarts/charts";import {GridComponent,TooltipComponent,@@ -9,14 +9,16 @@ import {ToolboxComponent,MarkLineComponent,MarkAreaComponent,+ VisualMapComponent,} from "echarts/components";import { CanvasRenderer } from "echarts/renderers";echarts.use([- CandlestickChart, LineChart, BarChart,+ CandlestickChart, LineChart, BarChart, HeatmapChart,GridComponent, TooltipComponent, LegendComponent,DataZoomComponent, MarkPointComponent,ToolboxComponent, MarkLineComponent, MarkAreaComponent,+ VisualMapComponent,CanvasRenderer,]);diff --git a/frontend/src/lib/i18n.tsx b/frontend/src/lib/i18n.tsxindex d6a8d17da..ed54c74f8 100644--- a/frontend/src/lib/i18n.tsx+++ b/frontend/src/lib/i18n.tsx@@ -150,6 +150,12 @@ const messages = {example1: "Dual MA crossover on 000001.SZ (5/20 day), backtest 2024",example2: "Build a dual MA crossover strategy for 000001.SZ, backtest 2024",example3: "Bollinger band mean-reversion on 600519.SH, backtest last 3 years",+ correlation: "Correlation Matrix",+ selectAssets: "Asset codes",+ windowLabel: "Window (days)",+ computeBtn: "Compute",+ methodLabel: "Method",+ noCorrelationData: "No correlation data available",} as const;type Messages = typeof messages;diff --git a/frontend/src/pages/Correlation.tsx b/frontend/src/pages/Correlation.tsxnew file mode 100644index 000000000..da14a7955--- /dev/null+++ b/frontend/src/pages/Correlation.tsx@@ -0,0 +1,139 @@+import { useState } from "react";+import { BarChart3 } from "lucide-react";+import { useI18n } from "@/lib/i18n";+import { api } from "@/lib/api";+import { CorrelationMatrix } from "@/components/charts/CorrelationMatrix";++const WINDOWS = [30, 60, 90, 180, 365] as const;++export function Correlation() {+ const { t } = useI18n();+ const [codes, setCodes] = useState("BTC-USDT,ETH-USDT,SPY,AAPL");+ const [days, setDays] = useState<number>(90);+ const [method, setMethod] = useState<"pearson" | "spearman">("pearson");+ const [loading, setLoading] = useState(false);+ const [error, setError] = useState<string | null>(null);++ const [labels, setLabels] = useState<string[]>([]);+ const [matrix, setMatrix] = useState<number[][]>([]);++ const compute = async () => {+ setError(null);+ setLoading(true);+ try {+ const result = await request<{ labels: string[]; matrix: number[][] }>(+ `/correlation?codes=${encodeURIComponent(codes)}&days=${days}&method=${method}`+ );+ setLabels(result.labels);+ setMatrix(result.matrix);+ } catch (e) {+ setError(e instanceof Error ? e.message : "Failed to compute correlation");+ } finally {+ setLoading(false);+ }+ };++ return (+ <div className="flex flex-col gap-6 p-6 max-w-5xl mx-auto">+ {/* Header */}+ <div className="flex items-center gap-3">+ <BarChart3 className="h-6 w-6 text-primary" />+ <h1 className="text-2xl font-bold">{t.correlation || "Correlation Matrix"}</h1>+ </div>++ {/* Controls */}+ <div className="flex flex-col gap-4 border rounded-lg p-4">+ <div className="flex flex-col gap-1.5">+ <label className="text-sm font-medium">{t.selectAssets || "Asset codes"}</label>+ <input+ type="text"+ value={codes}+ onChange={(e) => setCodes(e.target.value)}+ placeholder="BTC-USDT,ETH-USDT,SPY"+ className="w-full px-3 py-2 rounded-md border bg-background text-sm"+ />+ <p className="text-xs text-muted-foreground">+ Comma-separated ticker symbols, e.g. BTC-USDT,ETH-USDT,AAPL,SPY+ </p>+ </div>++ <div className="flex flex-wrap gap-4">+ <div className="flex flex-col gap-1.5">+ <label className="text-sm font-medium">{t.windowLabel || "Window (days)"}</label>+ <div className="flex gap-1.5">+ {WINDOWS.map((w) => (+ <button+ key={w}+ onClick={() => setDays(w)}+ className={`px-3 py-1.5 rounded text-sm border transition-colors ${+ days === w+ ? "bg-primary text-primary-foreground"+ : "border-muted-foreground/30 hover:border-primary"+ }`}+ >+ {w}d+ </button>+ ))}+ </div>+ </div>++ <div className="flex flex-col gap-1.5">+ <label className="text-sm font-medium">{t.methodLabel || "Method"}</label>+ <div className="flex gap-1.5">+ {(["pearson", "spearman"] as const).map((m) => (+ <button+ key={m}+ onClick={() => setMethod(m)}+ className={`px-3 py-1.5 rounded text-sm border transition-colors capitalize ${+ method === m+ ? "bg-primary text-primary-foreground"+ : "border-muted-foreground/30 hover:border-primary"+ }`}+ >+ {m}+ </button>+ ))}+ </div>+ </div>+ </div>++ <button+ onClick={compute}+ disabled={loading}+ className="self-start px-4 py-2 rounded-md bg-primary text-primary-foreground text-sm font-medium hover:opacity-90 disabled:opacity-50 transition-opacity"+ >+ {loading ? (t.loading || "Loading...") : (t.computeBtn || "Compute")}+ </button>+ </div>++ {/* Error */}+ {error && (+ <div className="text-sm text-danger border border-danger/30 rounded p-3 bg-danger/5">+ {error}+ </div>+ )}++ {/* Chart */}+ {labels.length > 0 && <CorrelationMatrix labels={labels} matrix={matrix} height={520} />}+ </div>+ );+}++// Minimal request helper (avoids importing the full api client which may have path issues)+async function request<T>(path: string, options?: RequestInit): Promise<T> {+ const BASE = "";+ const res = await fetch(`${BASE}${path}`, {+ headers: { "Content-Type": "application/json", ...options?.headers },+ ...options,+ });+ if (!res.ok) {+ let detail = `HTTP ${res.status}`;+ try {+ const body = await res.json();+ detail = body.detail || body.message || detail;+ } catch { /* ignore */ }+ throw new Error(detail);+ }+ const text = await res.text();+ return text ? JSON.parse(text) : ({} as T);+}\ No newline at end of filediff --git a/frontend/src/router.tsx b/frontend/src/router.tsxindex fe704939f..ec3ee86f5 100644--- a/frontend/src/router.tsx+++ b/frontend/src/router.tsx@@ -13,6 +13,9 @@ const Compare = lazy(() =>const Settings = lazy(() =>import("@/pages/Settings").then((m) => ({ default: m.Settings })),);+const Correlation = lazy(() =>+ import("@/pages/Correlation").then((m) => ({ default: m.Correlation })),+);function PageLoader() {return (@@ -39,6 +42,7 @@ export const router = createBrowserRouter([{ path: "/settings", element: wrap(Settings) },{ path: "/runs/:runId", element: wrap(RunDetail) },{ path: "/compare", element: wrap(Compare) },+ { path: "/correlation", element: wrap(Correlation) },],},]);