Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
932a707
feat: deprecate odims and ddims in favor of origin and development (#…
priyam0k Sep 5, 2026
2a889dd
fix ruff lints
priyam0k Sep 5, 2026
0727905
fix(development): check is_cumulative is False
priyam0k Sep 6, 2026
588a6bd
Fix rtest exception handling
priyam0k Oct 1, 2026
1d1397e
Format exponential tail test
priyam0k Oct 2, 2026
341a2af
Restore cumulative truthiness check
priyam0k Oct 3, 2026
d873612
Fix constant pattern deprecations
priyam0k Oct 18, 2026
fe12c35
Fix bugbot warnings
priyam0k Oct 19, 2026
619ef13
Prioritize raw pattern ages
priyam0k Oct 19, 2026
07a532f
Add missing patch tests
priyam0k Oct 19, 2026
9915608
Fix constant pattern ducktyping
priyam0k Oct 19, 2026
bfb0cee
Centralize axis descriptors
priyam0k Oct 2, 2026
491fc94
Add axis typing exports
priyam0k Oct 2, 2026
a43d7ad
Add axis edge tests
priyam0k Oct 2, 2026
9240759
Remove private axis dimensions
priyam0k Oct 24, 2026
18e862c
Fix development axis writes
priyam0k Oct 25, 2026
7f4464b
Fix ultimate pattern lag
priyam0k Oct 25, 2026
c845415
Refactor axis descriptors cleanup
priyam0k Nov 4, 2026
76cfd90
Fix pattern axis edge cases
priyam0k Nov 4, 2026
aab9baf
Fix development axis parsing
priyam0k Nov 4, 2026
9a94c2f
Fix grain development parsing
priyam0k Nov 4, 2026
ce045ac
Support sequence axis values
priyam0k Nov 4, 2026
4ecef24
Fix development lag ordinals
priyam0k Nov 4, 2026
d83cce3
Adopt unchecked axis setters
priyam0k Nov 9, 2026
329fca0
Merge upstream main
priyam0k Nov 9, 2026
f3cbaa3
Format axis helper signatures
priyam0k Nov 9, 2026
531a504
Support fractional development ages
priyam0k Nov 9, 2026
68c29c0
Parse fractional pattern lags
priyam0k Nov 9, 2026
0428f3c
Merge remote-tracking branch 'upstream/main' into feature/deprecate-d…
priyam0k Nov 10, 2026
fa0d1e1
Fix bugbot axis issues
priyam0k Nov 10, 2026
4559f5c
Fix valuation axis coverage
priyam0k Nov 10, 2026
54e1614
Merge upstream main
priyam0k Nov 19, 2026
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
2 changes: 1 addition & 1 deletion chainladder/adjustments/bootstrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ def fit(self, X, y=None, sample_weight=None):
xp = X.get_array_module()
if len(X) != 1:
raise ValueError("Only single index triangles are supported")
if type(X.ddims) is not np.ndarray:
if X.is_val_tri:
raise ValueError("Triangle must be expressed with development lags")
obj = Development(
n_periods=self.n_periods,
Expand Down
9 changes: 8 additions & 1 deletion chainladder/adjustments/tests/test_bootstrap.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import pytest
import chainladder as cl
import numpy as np
import pandas as pd
import pytest


def test_bs_sample(raa):
Expand Down Expand Up @@ -30,6 +30,13 @@ def test_multi_index(clrd):
pd.testing.assert_frame_equal(resampled_triangles.index, expected)


def test_bootstrap_odp_val_triangle_error(raa):
with pytest.raises(
ValueError, match="Triangle must be expressed with development lags"
):
cl.BootstrapODPSample().fit(raa.dev_to_val())


def test_hat_adjustment_is_zero_at_corners(genins):
"""
Check that the hat adjustment factor is exactly 0 at the two corner cells,
Expand Down
281 changes: 272 additions & 9 deletions chainladder/core/axis.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@
from __future__ import annotations

from typing import TYPE_CHECKING, Any, Callable
import numpy as np
import pandas as pd

from chainladder.core.base import TriangleBase
from chainladder.utils.utility_functions import _get_axis_name, _get_axis_number

if TYPE_CHECKING:
Expand Down Expand Up @@ -113,6 +115,23 @@ def __set__(self, obj: Triangle, value: Any) -> None:
if hasattr(obj, "virtual_columns"):
obj._set_slicers()

def set_unchecked(self, obj: Triangle, value: Any) -> None:
"""
Set the axis from a value, skipping the length check.

Used when an axis is widened ahead of ``values`` (arithmetic broadcast)
or when slicing/reindexing internal coordinates.
"""
if self.fset is _set_origin or self.fset is _set_development:
raw = self.fset(obj, value, check=False)
else:
raw = self.fset(obj, value) if self.fset else value
if not hasattr(obj, "_axes"):
obj._axes = {}
obj._axes[self.axis] = raw
if hasattr(obj, "virtual_columns"):
obj._set_slicers()


def _set_columns(obj: Triangle, value: Any) -> pd.Index:
"""
Expand All @@ -130,12 +149,17 @@ def _set_columns(obj: Triangle, value: Any) -> pd.Index:
pd.Index
A pandas Index named ``"columns"``.
"""
if isinstance(value, str):
if isinstance(value, (str, bytes)) or not hasattr(value, "__len__"):
value = [value]
if hasattr(obj, "values") and obj.values is not None:
obj._len_check(range(obj.values.shape[1]), value)
elif hasattr(obj, "_axes") and (1 in obj._axes or "columns" in obj._axes):
obj._len_check(obj.columns, value)
if hasattr(obj, "_len_check"):
if hasattr(obj, "values") and obj.values is not None:
obj._len_check(range(obj.values.shape[1]), value)
elif (
not isinstance(obj, TriangleBase)
and hasattr(obj, "_axes")
and (1 in obj._axes or "columns" in obj._axes)
):
obj._len_check(obj.columns, value)
return pd.Index(value, name="columns")


Expand All @@ -157,8 +181,247 @@ def _set_index(obj: Triangle, value: Any) -> pd.DataFrame:
"""
if not isinstance(value, pd.DataFrame):
raise TypeError("index must be a pandas DataFrame")
if hasattr(obj, "values") and obj.values is not None:
obj._len_check(range(obj.values.shape[0]), value)
elif hasattr(obj, "_axes") and (0 in obj._axes or "index" in obj._axes):
obj._len_check(obj.index, value)
if hasattr(obj, "_len_check"):
if hasattr(obj, "values") and obj.values is not None:
obj._len_check(range(obj.values.shape[0]), value)
elif (
not isinstance(obj, TriangleBase)
and hasattr(obj, "_axes")
and (0 in obj._axes or "index" in obj._axes)
):
obj._len_check(obj.index, value)
return value.copy().reset_index(drop=True)


def _get_origin(obj: Triangle, raw: Any) -> pd.PeriodIndex | pd.Series:
"""
Transform raw origin timestamp array into public PeriodIndex or Series.
"""
if obj.is_pattern and len(raw) == 1:
return pd.Series(["(All)"])
if raw is None:
return None
freq = {
"S": "2Q",
"H": "2Q",
}.get(obj.origin_grain, obj.origin_grain)
freq = freq if (freq == "M" or "-" in freq) else freq + "-" + obj.origin_close
return pd.DatetimeIndex(raw, name="origin").to_period(freq=freq)


def _set_origin(obj: Triangle, value: Any, check: bool = True) -> np.ndarray:
"""
Validate and transform assigned origin periods into internal timestamps array.
"""
if isinstance(value, (str, bytes)) or not hasattr(value, "__len__"):
value = [value]
if check and hasattr(obj, "_len_check"):
if hasattr(obj, "values") and obj.values is not None:
obj._len_check(range(obj.values.shape[2]), value)
elif (
not isinstance(obj, TriangleBase)
and hasattr(obj, "_axes")
and (2 in obj._axes or "origin" in obj._axes)
):
raw_orig = obj._axes.get(2, obj._axes.get("origin"))
if raw_orig is not None:
obj._len_check(raw_orig, value)
if isinstance(value, pd.PeriodIndex):
return value.to_timestamp().values
if isinstance(value, pd.DatetimeIndex):
return value.values
if isinstance(value, np.ndarray) and value.dtype.kind == "M":
return value
if len(value) == 1 and (
(isinstance(value[0], str) and value[0] == "(All)")
or (hasattr(value, "iloc") and str(value.iloc[0]) == "(All)")
):
if hasattr(obj, "_axes") and (2 in obj._axes or "origin" in obj._axes):
raw_orig = obj._axes.get(2, obj._axes.get("origin"))
if raw_orig is not None and len(raw_orig) == 1:
return raw_orig
return pd.date_range("2000", periods=1).values
origin_grain = getattr(obj, "origin_grain", "Y")
origin_close = getattr(obj, "origin_close", "DEC")
freq = {
"S": "2Q",
"H": "2Q",
}.get(origin_grain, origin_grain)
freq = freq if (freq == "M" or "-" in freq) else freq + "-" + origin_close
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
value = pd.PeriodIndex(value, freq=freq)
return value.to_timestamp().values


def _get_development(obj: Triangle, raw: Any) -> pd.Series:
"""
Transform raw development lags/timestamps into public Series.
"""
if raw is None:
return None
dev = raw.copy()
if obj.is_val_tri:
formats = {"Y": "%Y", "S": "%YQ%q", "Q": "%YQ%q", "M": "%Y-%m"}
dev = dev.to_period(freq=obj.development_grain.replace("S", "2Q")).strftime(
formats[obj.development_grain]
)
elif obj.is_pattern:
offset = obj._dstep()["M"][obj.development_grain]
if obj.is_ultimate:
dev[-1] = dev[-2] + offset
if obj.is_cumulative:
dev = ["{}-Ult".format(dev[i]) for i in range(len(dev))]
else:
dev = ["{}-{}".format(dev[i], dev[i] + offset) for i in range(len(dev))]
return pd.Series(list(dev), name="development")


def _set_development(obj: Triangle, value: Any, check: bool = True) -> Any:
"""
Validate and transform assigned development periods into internal lag/timestamp array.
"""
if isinstance(value, (str, bytes)) or not hasattr(value, "__len__"):
value = [value]
if check and hasattr(obj, "_len_check"):
if hasattr(obj, "values") and obj.values is not None:
obj._len_check(range(obj.values.shape[3]), value)
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
elif (
not isinstance(obj, TriangleBase)
and hasattr(obj, "_axes")
and (3 in obj._axes or "development" in obj._axes)
):
raw_dev = obj._axes.get(3, obj._axes.get("development"))
if raw_dev is not None:
obj._len_check(raw_dev, value)
if isinstance(value, pd.DatetimeIndex):
return value
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
if isinstance(value, pd.PeriodIndex):
return value.to_timestamp(how="end")
if isinstance(value, np.ndarray) and value.dtype.kind == "M":
return pd.DatetimeIndex(value)

val_arr = np.array(value)
if val_arr.dtype.kind in ("i", "u"):
return val_arr.astype(int)
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
if val_arr.dtype.kind == "f":
if np.all(np.equal(np.mod(val_arr, 1), 0)):
return val_arr.astype(int)
return val_arr

if getattr(obj, "is_val_tri", False):
# Try matching existing DatetimeIndex labels or parsing as PeriodIndex/DatetimeIndex
if hasattr(obj, "_axes") and isinstance(obj._axes.get(3), pd.DatetimeIndex):
current_dt = obj._axes[3]
current_labels = list(_get_development(obj, current_dt))
val_list_str = [str(v) for v in val_arr]
if all(v in current_labels for v in val_list_str):
indices = [current_labels.index(v) for v in val_list_str]
return current_dt[indices]

try:
freq = getattr(obj, "development_grain", "Y").replace("S", "2Q")
return pd.PeriodIndex(val_arr.astype(str), freq=freq).to_timestamp(
how="end"
)
except (ValueError, TypeError):
try:
return pd.DatetimeIndex(val_arr)
except (ValueError, TypeError):
pass
return val_arr

# Non-valuation triangle: development axis represents numeric lags or pattern intervals
val_list = [str(v).strip() for v in val_arr]
try:
lags = []
for s in val_list:
if s.lower() == "ult":
lags.append(9999)
elif "-" in s:
parts = s.split("-")
if len(parts) == 2:
p0 = parts[0].strip()
p1 = parts[1].strip()
try:
n0 = int(p0) if p0.isdigit() else float(p0)
except ValueError:
n0 = None
if p1.lower() == "ult":
n1 = 9999
else:
try:
n1 = int(p1) if p1.isdigit() else float(p1)
except ValueError:
n1 = None
if (
n0 is not None
and n1 is not None
and (n0 < 1000 or n0 == 9999)
and n1 <= 9999
):
lags.append(n0)
else:
raise ValueError(f"Not a development lag pattern: {s}")
else:
raise ValueError(f"Not a development lag pattern: {s}")
else:
try:
val_num = int(s)
except ValueError:
val_num = float(s)
if val_num >= 1000 and val_num != 9999:
raise ValueError(f"Year passed to development lag: {s}")
lags.append(val_num)
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved

raw_dev = getattr(obj, "_axes", {}).get(3)
if raw_dev is None and hasattr(obj, "_axes") and isinstance(obj._axes, dict):
raw_dev = obj._axes.get("development")
is_ult = getattr(obj, "is_ultimate", False) or (
raw_dev is not None
and len(raw_dev) == len(lags)
and len(raw_dev) > 0
and raw_dev[-1] == 9999
)
if is_ult and len(lags) > 0:
lags[-1] = 9999
lag_arr = np.array(lags)
if lag_arr.dtype.kind == "f" and np.all(np.equal(np.mod(lag_arr, 1), 0)):
lag_arr = lag_arr.astype(int)
return lag_arr
except (ValueError, TypeError):
pass

# If not parseable as numeric lags / patterns, try parsing as valuation periods / dates
try:
freq = getattr(obj, "development_grain", "Y").replace("S", "2Q")
return pd.PeriodIndex(val_arr.astype(str), freq=freq).to_timestamp(how="end")
except (ValueError, TypeError):
try:
return pd.DatetimeIndex(val_arr)
except (ValueError, TypeError):
pass

return val_arr


def _set_axis(obj: Triangle, axis: int | str, value: Any, check: bool = True) -> None:
"""
Set values on the specified axis of a Triangle instance.

Parameters
----------
obj : Triangle
The Triangle instance to update.
axis : int or str
Axis identifier (0..3 or 'index', 'columns', 'origin', 'development').
value : Any
New axis values.
check : bool, default True
Whether to perform length and consistency validation.
"""
axis_name = _get_axis_name(axis)
if not check:
descriptor = getattr(type(obj), axis_name, None)
if isinstance(descriptor, TriangleAxis):
descriptor.set_unchecked(obj, value)
return
setattr(obj, axis_name, value)
Loading