"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(quantlib): add Ornstein-Uhlenbeck continuous process exact calibration
santhrealfad50c719f3a
diff --git a/agent/src/quantlib/timeseries.py b/agent/src/quantlib/timeseries.pyindex 822265ecd..ddc0d30af 100644--- a/agent/src/quantlib/timeseries.py+++ b/agent/src/quantlib/timeseries.py@@ -44,6 +44,7 @@ __all__ = ["cointegration_test","find_hedge_ratio","compute_half_life",+ "fit_ornstein_uhlenbeck","granger_test","fit_garch","fit_markov_regime",@@ -230,6 +231,103 @@ def compute_half_life(spread: pd.Series) -> float:return float(-np.log(2) / reversion)++def fit_ornstein_uhlenbeck(series: pd.Series, dt: float = 1.0) -> dict:+ """Fit an Ornstein-Uhlenbeck (OU) mean-reverting process by exact discrete MLE.++ The continuous-time OU process is:+ dX_t = θ(μ - X_t)dt + σ dW_t++ Under discrete sampling with interval ``dt``, this maps to an exact AR(1) model:+ X_{t+1} = a + b X_t + ε_t, ε_t ~ N(0, σ_ε^2)++ where:+ b = exp(-θ dt) => θ = -ln(b) / dt+ a = μ(1 - b) => μ = a / (1 - b)+ σ_ε^2 = σ^2 / (2θ) * (1 - exp(-2θ dt)) = σ^2 / (2θ) * (1 - b^2)+ σ = sqrt(2θ * σ_ε^2 / (1 - b^2))+ Half-life = ln(2) / θ+ Stationary Variance = σ^2 / (2θ) = σ_ε^2 / (1 - b^2)++ Args:+ series: Spread or asset price/level time series.+ dt: Sampling time step in desired units (e.g. 1.0 for daily, 1/252 for annualised).+ Must be strictly positive.++ Returns:+ Dict with keys:+ * ``theta`` (float): Mean-reversion rate θ.+ * ``mu`` (float): Long-term equilibrium mean μ.+ * ``sigma`` (float): Continuous diffusion volatility σ.+ * ``half_life`` (float): Mean-reversion half-life (in time units).+ * ``stationary_variance`` (float): Long-run stationary variance.+ * ``stationary_std`` (float): Long-run stationary standard deviation.+ * ``ar1_a`` (float): Discrete AR(1) intercept a.+ * ``ar1_b`` (float): Discrete AR(1) slope b.+ * ``residual_std`` (float): Discrete error standard deviation σ_ε.+ * ``is_mean_reverting`` (bool): True if 0 < b < 1 (reverting).++ Raises:+ ImportError: If ``statsmodels`` is not installed.+ ValueError: If ``dt <= 0``, fewer than 3 valid lag pairs remain, or series is constant.+ """+ if dt <= 0:+ raise ValueError(f"dt must be strictly positive, got {dt}")++ sm = _require("statsmodels.api", "statsmodels", "fit_ornstein_uhlenbeck")+ s = pd.Series(series, dtype=float).dropna()+ if not np.isfinite(s.values).all():+ raise ValueError("series contains non-finite values")++ lagged = s.shift(1)+ frame = pd.concat({"curr": s, "lag": lagged}, axis=1).dropna()+ if len(frame) < 3:+ raise ValueError(f"fit_ornstein_uhlenbeck needs at least 3 lag pairs, got {len(frame)}")+ if frame["lag"].std(ddof=0) == 0:+ raise ValueError("fit_ornstein_uhlenbeck needs a series that varies; this one is constant")++ exog = sm.add_constant(frame[["lag"]])+ params = _ols_params(frame["curr"], exog)+ a = float(params[0])+ b = float(params[1])++ residuals = frame["curr"] - (a + b * frame["lag"])+ n = len(frame)+ dof = max(1, n - 2)+ sigma_eps_sq = float(np.sum(residuals**2) / dof)+ sigma_eps = float(np.sqrt(sigma_eps_sq))++ if 0.0 < b < 1.0:+ theta = float(-np.log(b) / dt)+ mu = float(a / (1.0 - b))+ half_life = float(np.log(2.0) / theta)+ one_minus_b2 = float(1.0 - b**2)+ stat_var = float(sigma_eps_sq / one_minus_b2)+ stat_std = float(np.sqrt(stat_var))+ sigma = float(np.sqrt(2.0 * theta * stat_var))+ is_reverting = True+ else:+ theta = 0.0 if b >= 1.0 else float("nan")+ mu = float("nan") if b == 1.0 else float(a / (1.0 - b))+ half_life = float("inf")+ stat_var = float("inf")+ stat_std = float("inf")+ sigma = float("nan")+ is_reverting = False++ return {+ "theta": theta,+ "mu": mu,+ "sigma": sigma,+ "half_life": half_life,+ "stationary_variance": stat_var,+ "stationary_std": stat_std,+ "ar1_a": a,+ "ar1_b": b,+ "residual_std": sigma_eps,+ "is_mean_reverting": is_reverting,+ }+def find_hedge_ratio(y: pd.Series, x: pd.Series) -> dict:"""Fit the pair-trading hedge ratio ``y = α + β·x + ε``.diff --git a/agent/tests/quantlib/test_timeseries.py b/agent/tests/quantlib/test_timeseries.pyindex 15d0b8a55..c939ab5f9 100644--- a/agent/tests/quantlib/test_timeseries.py+++ b/agent/tests/quantlib/test_timeseries.py@@ -24,6 +24,7 @@ from src.quantlib.timeseries import (find_hedge_ratio,fit_garch,fit_markov_regime,+ fit_ornstein_uhlenbeck,granger_test,heteroscedasticity_test,vif_test,@@ -702,7 +703,7 @@ def test_importing_the_module_does_not_require_the_optional_backends():module = importlib.import_module("src.quantlib.timeseries")- assert len(module.__all__) == 12+ assert len(module.__all__) == 13assert "statsmodels" not in module.__dict__assert "arch" not in module.__dict__@@ -838,3 +839,68 @@ def test_markov_raises_an_actionable_error_when_statsmodels_is_absent():with pytest.raises(ImportError, match="pip install"):fit_markov_regime(pd.Series(np.random.default_rng(37).normal(0, 0.01, 100)))++# --- Ornstein-Uhlenbeck calibration ---+++@requires_statsmodels+def test_ornstein_uhlenbeck_recovers_known_parameters():+ rng = np.random.default_rng(42)+ true_theta = 0.5+ true_mu = 10.0+ true_sigma = 1.2+ dt = 1.0+ n = 2000++ # Exact AR(1) simulation for OU+ b = np.exp(-true_theta * dt)+ a = true_mu * (1.0 - b)+ sigma_eps = np.sqrt(true_sigma**2 / (2 * true_theta) * (1.0 - b**2))++ x = np.zeros(n)+ x[0] = true_mu+ for t in range(1, n):+ x[t] = a + b * x[t - 1] + rng.normal(0, sigma_eps)++ series = pd.Series(x)+ result = fit_ornstein_uhlenbeck(series, dt=dt)++ assert result["is_mean_reverting"] is True+ assert result["theta"] == pytest.approx(true_theta, rel=0.15)+ assert result["mu"] == pytest.approx(true_mu, rel=0.05)+ assert result["sigma"] == pytest.approx(true_sigma, rel=0.15)+ assert result["half_life"] == pytest.approx(np.log(2) / result["theta"], abs=1e-12)+ assert result["stationary_variance"] == pytest.approx(+ result["sigma"] ** 2 / (2 * result["theta"]), rel=1e-6+ )+ assert result["stationary_std"] == pytest.approx(+ np.sqrt(result["stationary_variance"]), abs=1e-12+ )+++@requires_statsmodels+def test_ornstein_uhlenbeck_random_walk_reports_non_reverting():+ rng = np.random.default_rng(43)+ # Random walk: b = 1.0+ rw = np.cumsum(rng.normal(0, 1, 500))+ result = fit_ornstein_uhlenbeck(pd.Series(rw))++ if not result["is_mean_reverting"]:+ assert result["half_life"] == float("inf")+++@requires_statsmodels+def test_ornstein_uhlenbeck_input_validation():+ series = pd.Series([1.0, 2.0, 3.0, 2.5, 2.0])++ with pytest.raises(ValueError, match="dt must be strictly positive"):+ fit_ornstein_uhlenbeck(series, dt=0.0)++ with pytest.raises(ValueError, match="dt must be strictly positive"):+ fit_ornstein_uhlenbeck(series, dt=-1.0)++ with pytest.raises(ValueError, match="at least 3 lag pairs"):+ fit_ornstein_uhlenbeck(pd.Series([1.0, 2.0]))++ with pytest.raises(ValueError, match="constant"):+ fit_ornstein_uhlenbeck(pd.Series([5.0, 5.0, 5.0, 5.0]))