Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
286 changes: 286 additions & 0 deletions core/janus/forecast/gbdt.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,286 @@
"""Gradient-boosted quantile regression, numpy only (#128).

A nonlinear baseline beside :class:`~janus.forecast.quantiles.EmpiricalQuantileModel`.
Each requested quantile gets its own additive model of shallow regression trees
fitted on the pinball-loss gradient, so the output is the same ``QuantileForecast``
every other quantile model returns.

Deliberately small and auditable: histogram split candidates, no randomness, no
sklearn / lightgbm / xgboost, and ``predict`` is a pure function of the fitted
state. The pinball loss has a zero second derivative almost everywhere, so the
Newton leaf ``sum(g) / sum(h)`` reduces to the mean gradient, which is what
``_build`` stores.
"""

from __future__ import annotations

from dataclasses import dataclass
from typing import Any, Sequence

import numpy as np

from .quantiles import QuantileForecast, _validate_probabilities


@dataclass(frozen=True)
class _Tree:
"""One shallow regression tree; leaves carry a constant gradient mean."""

value: float
feature: int = -1
threshold: float = 0.0
left: "_Tree | None" = None
right: "_Tree | None" = None

def predict(self, rows: np.ndarray) -> np.ndarray:
if self.left is None or self.right is None:
return np.full(rows.shape[0], self.value)
mask = rows[:, self.feature] <= self.threshold
out = np.empty(rows.shape[0])
out[mask] = self.left.predict(rows[mask])
out[~mask] = self.right.predict(rows[~mask])
return out

def to_dict(self) -> dict[str, Any]:
if self.left is None or self.right is None:
return {"value": self.value}
return {
"value": self.value,
"feature": self.feature,
"threshold": self.threshold,
"left": self.left.to_dict(),
"right": self.right.to_dict(),
}

@classmethod
def from_dict(cls, payload: Any) -> "_Tree":
if not isinstance(payload, dict) or "value" not in payload:
raise ValueError("tree payload field 'value' is missing or not an object")
children = [key for key in ("left", "right") if key in payload]
if not children:
return cls(float(payload["value"]))
if len(children) != 2:
raise ValueError("tree payload must carry both children or neither")
for key in ("feature", "threshold"):
if key not in payload:
raise ValueError(f"tree payload is missing {key!r}")
return cls(
float(payload["value"]),
int(payload["feature"]),
float(payload["threshold"]),
cls.from_dict(payload["left"]),
cls.from_dict(payload["right"]),
)


def _build(
x: np.ndarray,
residual: np.ndarray,
*,
depth: int,
max_depth: int,
min_samples_leaf: int,
n_bins: int,
) -> _Tree:
value = float(residual.mean())
if depth >= max_depth or residual.size < 2 * min_samples_leaf:
return _Tree(value=value)
best: tuple[float, int, float] | None = None
for feature in range(x.shape[1]):
column = x[:, feature]
cuts = np.unique(np.quantile(column, np.linspace(0.0, 1.0, n_bins + 1)[1:-1]))
for threshold in cuts:
mask = column <= threshold
left, right = residual[mask], residual[~mask]
if left.size < min_samples_leaf or right.size < min_samples_leaf:
continue
gain = left.size * (left.mean() - value) ** 2 + right.size * (
right.mean() - value
) ** 2
if best is None or gain > best[0]:
best = (float(gain), feature, float(threshold))
if best is None:
return _Tree(value=value)
_, feature, threshold = best
mask = x[:, feature] <= threshold
return _Tree(
value=value,
feature=feature,
threshold=threshold,
left=_build(
x[mask], residual[mask], depth=depth + 1, max_depth=max_depth,
min_samples_leaf=min_samples_leaf, n_bins=n_bins,
),
right=_build(
x[~mask], residual[~mask], depth=depth + 1, max_depth=max_depth,
min_samples_leaf=min_samples_leaf, n_bins=n_bins,
),
)


class GradientBoostedQuantileModel:
"""Per-quantile gradient boosting on the pinball loss."""

def __init__(
self,
quantiles: Sequence[float] = (0.1, 0.5, 0.9),
*,
n_estimators: int = 50,
learning_rate: float = 0.1,
max_depth: int = 3,
min_samples_leaf: int = 5,
n_bins: int = 32,
seed: int = 0,
feature_names: Sequence[str] | None = None,
) -> None:
self.quantiles = _validate_probabilities(quantiles)
rules = {
"n_estimators": (n_estimators, int(n_estimators) >= 1, ">= 1"),
"learning_rate": (learning_rate, 0.0 < learning_rate <= 1.0, "in (0, 1]"),
"max_depth": (max_depth, int(max_depth) >= 1, ">= 1"),
"min_samples_leaf": (min_samples_leaf, int(min_samples_leaf) >= 1, ">= 1"),
"n_bins": (n_bins, int(n_bins) >= 2, ">= 2"),
}
for name, (value, ok, rule) in rules.items():
if not ok:
raise ValueError(f"{name} must be {rule}, got {value}")
self.n_estimators = int(n_estimators)
self.learning_rate = float(learning_rate)
self.max_depth = int(max_depth)
self.min_samples_leaf = int(min_samples_leaf)
self.n_bins = int(n_bins)
self.seed = int(seed)
self.feature_names = list(feature_names) if feature_names is not None else None
self.baselines_: list[float] | None = None
self.trees_: list[list[_Tree]] | None = None
self.n_features_in_: int | None = None
self.n_samples_: int = 0

def _matrix(self, x: Any, y: Sequence[float] | None = None) -> tuple[np.ndarray, np.ndarray | None]:
rows = np.asarray(x, dtype=float)
if rows.ndim != 2:
raise ValueError(f"X must be two-dimensional, got {rows.ndim} dimension(s)")
bad = np.argwhere(~np.isfinite(rows))
if bad.size:
row, column = int(bad[0][0]), int(bad[0][1])
label = (
self.feature_names[column]
if self.feature_names is not None and column < len(self.feature_names)
else f"column {column}"
)
raise ValueError(f"X has a non-finite value at row {row}, {label}")
if y is None:
return rows, None
target = np.asarray(list(y), dtype=float)
if target.ndim != 1:
raise ValueError("y must be one-dimensional")
if target.size != rows.shape[0]:
raise ValueError(f"X has {rows.shape[0]} rows but y has {target.size} values")
if not np.isfinite(target).all():
raise ValueError("y contains a non-finite value")
return rows, target

def fit(self, x: Any, y: Sequence[float]) -> "GradientBoostedQuantileModel":
rows, target = self._matrix(x, y)
assert target is not None
required = 2 * self.min_samples_leaf
if rows.shape[0] < required:
raise ValueError(
f"at least {required} samples are required "
f"(2 * min_samples_leaf), got {rows.shape[0]}"
)
self.n_features_in_ = rows.shape[1]
self.n_samples_ = int(rows.shape[0])
self.baselines_, self.trees_ = [], []
for probability in self.quantiles:
baseline = float(np.quantile(target, probability))
prediction = np.full(rows.shape[0], baseline)
forests: list[_Tree] = []
for _ in range(self.n_estimators):
gradient = np.where(target > prediction, probability, probability - 1.0)
tree = _build(
rows, gradient, depth=0, max_depth=self.max_depth,
min_samples_leaf=self.min_samples_leaf, n_bins=self.n_bins,
)
prediction = prediction + self.learning_rate * tree.predict(rows)
forests.append(tree)
self.baselines_.append(baseline)
self.trees_.append(forests)
return self

def _raw(self, rows: np.ndarray) -> np.ndarray:
assert self.trees_ is not None and self.baselines_ is not None
columns = []
for baseline, forests in zip(self.baselines_, self.trees_):
prediction = np.full(rows.shape[0], baseline)
for tree in forests:
prediction = prediction + self.learning_rate * tree.predict(rows)
columns.append(prediction)
# Non-crossing is a property of the output, not a hope.
return np.sort(np.column_stack(columns), axis=1)

def predict(self, x: Any, *, horizon: int = 1) -> list[QuantileForecast]:
if self.trees_ is None or self.baselines_ is None:
raise RuntimeError("model is not fitted")
if horizon < 1:
raise ValueError("horizon must be >= 1")
rows, _ = self._matrix(x)
if self.n_features_in_ is not None and rows.shape[1] != self.n_features_in_:
raise ValueError(
f"X has {rows.shape[1]} features but the model was fitted on "
f"{self.n_features_in_}"
)
values = self._raw(rows) * float(np.sqrt(horizon))
return [
QuantileForecast.from_values(
self.quantiles, row, observations=int(self.n_samples_)
)
for row in values
]

def to_dict(self) -> dict[str, Any]:
if self.trees_ is None or self.baselines_ is None:
raise RuntimeError("model is not fitted")
return {
"quantiles": list(self.quantiles),
"n_estimators": self.n_estimators,
"learning_rate": self.learning_rate,
"max_depth": self.max_depth,
"min_samples_leaf": self.min_samples_leaf,
"n_bins": self.n_bins,
"seed": self.seed,
"feature_names": self.feature_names,
"n_samples": self.n_samples_,
"baselines": list(self.baselines_),
"trees": [[tree.to_dict() for tree in forests] for forests in self.trees_],
}

@classmethod
def from_dict(cls, payload: Any) -> "GradientBoostedQuantileModel":
if not isinstance(payload, dict):
raise ValueError("model payload must be an object")
required = (
"quantiles", "n_estimators", "learning_rate", "max_depth",
"min_samples_leaf", "n_bins", "seed", "baselines", "trees",
)
for field in required:
if field not in payload:
raise ValueError(f"model payload is missing {field!r}")
model = cls(
payload["quantiles"],
n_estimators=int(payload["n_estimators"]),
learning_rate=float(payload["learning_rate"]),
max_depth=int(payload["max_depth"]),
min_samples_leaf=int(payload["min_samples_leaf"]),
n_bins=int(payload["n_bins"]),
seed=int(payload["seed"]),
feature_names=payload.get("feature_names"),
)
trees = payload["trees"]
if not isinstance(trees, list) or len(trees) != len(model.quantiles):
raise ValueError("model payload field 'trees' needs one forest per quantile")
model.baselines_ = [float(value) for value in payload["baselines"]]
model.trees_ = [[_Tree.from_dict(node) for node in forest] for forest in trees]
model.n_samples_ = int(payload.get("n_samples", 0))
model.n_features_in_ = None
return model
70 changes: 63 additions & 7 deletions core/janus/forecast/quantiles.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,77 @@
from __future__ import annotations

import math
from dataclasses import dataclass
from typing import Iterable, Sequence
from typing import Any, Iterable, Protocol, Sequence

import numpy as np


def _validate_probabilities(probabilities: Iterable[float]) -> tuple[float, ...]:
values = tuple(float(value) for value in probabilities)
if not values or any(not 0.0 < value < 1.0 for value in values):
raise ValueError("quantiles must be strictly between 0 and 1")
if list(values) != sorted(values):
raise ValueError("quantiles must be sorted")
keys = [f"{value:.2f}" for value in values]
if len(set(keys)) != len(keys):
raise ValueError("quantiles must be at least 0.01 apart")
return values


class QuantileModel(Protocol):
"""The interface every quantile model shares: ``fit`` then ``predict``.

Models that condition on features or on a regime still return
:class:`QuantileForecast`, so a caller (backtest, scenario tree, MCP tool)
can swap an empirical baseline for a learned one without changing its code.
"""

def fit(self, *args: Any, **kwargs: Any) -> "QuantileModel": ...

def predict(self, *, horizon: int = 1) -> QuantileForecast: ...


@dataclass(frozen=True)
class QuantileForecast:
quantiles: dict[str, float]
level: float
observations: int

@classmethod
def from_values(
cls,
probabilities: Sequence[float],
values: Sequence[float],
*,
observations: int,
) -> "QuantileForecast":
"""Build a forecast from already-computed quantile values.

The same checks every model owes its caller: probabilities inside
``(0, 1)``, sorted, one value each, finite and non-decreasing (a
crossing forecast is a bug, not a shape).
"""

probs = _validate_probabilities(probabilities)
numbers = tuple(float(value) for value in values)
if len(numbers) != len(probs):
raise ValueError(
f"quantiles and values must have the same length: "
f"{len(probs)} != {len(numbers)}"
)
if any(not math.isfinite(value) for value in numbers):
raise ValueError("quantile values must be finite")
if any(right < left for left, right in zip(numbers, numbers[1:])):
raise ValueError("quantile values must be non-decreasing")
if observations < 1:
raise ValueError("observations must be >= 1")
return cls(
quantiles={f"{value:.2f}": number for value, number in zip(probs, numbers)},
level=probs[-1] - probs[0],
observations=int(observations),
)

@property
def width(self) -> float:
keys = sorted(self.quantiles, key=float)
Expand All @@ -20,6 +80,7 @@ def width(self) -> float:
return self.quantiles[keys[-1]] - self.quantiles[keys[0]]



class EmpiricalQuantileModel:
"""Distribution-free return quantiles from point-in-time history.

Expand All @@ -29,12 +90,7 @@ class EmpiricalQuantileModel:
"""

def __init__(self, quantiles: Sequence[float] = (0.1, 0.5, 0.9)) -> None:
values = tuple(float(value) for value in quantiles)
if not values or any(not 0.0 < value < 1.0 for value in values):
raise ValueError("quantiles must be strictly between 0 and 1")
if list(values) != sorted(values):
raise ValueError("quantiles must be sorted")
self.quantiles = values
self.quantiles = _validate_probabilities(quantiles)
self.returns_: np.ndarray | None = None

def fit(self, returns: Iterable[float]) -> "EmpiricalQuantileModel":
Expand Down
Loading
Loading