Ir para o conteúdo

Referência da API

Nesta seção você encontra a documentação detalhada das funções e classes gerada automaticamente a partir do código fonte (Docstrings em Inglês).

Módulo Actuarial

pylifecontingencies.actuarial

Single-life actuarial present values.

All functions accept an ActuarialTable as first argument and return floats, matching the R lifecontingencies interface exactly.

Formulas use commutation columns from ActuarialTable for integer k=1 cases. For k>1 (m-thly payments) the UDD approximation is applied.

AExn(at, x, n, k=1)

Endowment insurance A_{x:n|} = A^1_{x:n|} + _n E_x.

Pays 1 at end of year of death (if within n years) or at age x+n.

Source code in src/pylifecontingencies/actuarial.py
129
130
131
132
133
134
135
136
137
138
139
140
def AExn(
    at: ActuarialTable,
    x: int,
    n: int,
    k: int = 1,
) -> float:
    """
    Endowment insurance  A_{x:n|} = A^1_{x:n|} + _n E_x.

    Pays 1 at end of year of death (if within n years) or at age x+n.
    """
    return Axn(at, x, n=n, k=k) + Exn(at, x, n)

Axn(at, x, n=None, k=1)

Actuarial present value of a term (or whole-life) insurance.

Pays 1 at end of year of death if death occurs within n years. If n is None or inf, a whole-life insurance is returned.

Parameters

k : int For k>1: A^(k) = (i / i^(k)) * A under UDD.

Source code in src/pylifecontingencies/actuarial.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
def Axn(
    at: ActuarialTable,
    x: int,
    n: float | None = None,
    k: int = 1,
) -> float:
    """
    Actuarial present value of a term (or whole-life) insurance.

    Pays 1 at end of year of death if death occurs within n years.
    If n is None or inf, a whole-life insurance is returned.

    Parameters
    ----------
    k : int
        For k>1: A^(k) = (i / i^(k)) * A  under UDD.
    """
    whole_life = (n is None) or math.isinf(float(n))
    n_int = at.omega - x if whole_life else int(n)

    if n_int <= 0:
        return 0.0

    Mx_val = at.Mx(x)
    Mx_n = at.Mx(x + n_int) if (x + n_int) <= at.omega else 0.0
    Dx_val = at.Dx(x)

    if k == 1:
        return (Mx_val - Mx_n) / Dx_val

    # UDD k-thly: A^(k) = (i / i^(k)) * A^(1)
    A_annual = (Mx_val - Mx_n) / Dx_val
    i = at.interest.i
    i_k = at.interest.i_m(k)
    return (i / i_k) * A_annual

DAxn(at, x, n, k=1)

Decreasing term insurance (DA)^1_{x:n|}.

Pays (n-k) if death occurs in year k+1 (k = 0, …, n-1). Identity: (DA)^1 + (IA)^1 = (n+1) A^1_{x:n|}.

Source code in src/pylifecontingencies/actuarial.py
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
def DAxn(
    at: ActuarialTable,
    x: int,
    n: int,
    k: int = 1,
) -> float:
    """
    Decreasing term insurance (DA)^1_{x:n|}.

    Pays (n-k) if death occurs in year k+1 (k = 0, …, n-1).
    Identity: (DA)^1 + (IA)^1 = (n+1) A^1_{x:n|}.
    """
    if n <= 0:
        return 0.0
    A_term = Axn(at, x, n=n, k=1)
    IA_term = IAxn(at, x, n=n, k=1)
    result = (n + 1) * A_term - IA_term

    if k == 1:
        return result
    i = at.interest.i
    i_k = at.interest.i_m(k)
    return (i / i_k) * result

Exn(at, x, n)

n-year pure endowment n E_x = v^n * _n p_x = D{x+n} / D_x.

Parameters

at : ActuarialTable x : int Attained age. n : int Term in years.

Source code in src/pylifecontingencies/actuarial.py
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
def Exn(at: ActuarialTable, x: int, n: int) -> float:
    """
    n-year pure endowment  _n E_x = v^n * _n p_x = D_{x+n} / D_x.

    Parameters
    ----------
    at : ActuarialTable
    x : int
        Attained age.
    n : int
        Term in years.
    """
    if x + n > at.omega:
        return 0.0
    return at.Dx(x + n) / at.Dx(x)

IAxn(at, x, n=None, k=1)

Increasing insurance (IA)_{x:n|}.

Pays (k+1) if death occurs in year k+1 (k = 0, 1, …, n-1). For whole-life (n=None): (IA)x = R_x / D_x. For term: (IA)^1{x:n|} = (R_x - R_{x+n} - n M_{x+n}) / D_x.

k parameter: k>1 uses UDD scaling as for Axn.

Source code in src/pylifecontingencies/actuarial.py
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
def IAxn(
    at: ActuarialTable,
    x: int,
    n: float | None = None,
    k: int = 1,
) -> float:
    """
    Increasing insurance (IA)_{x:n|}.

    Pays (k+1) if death occurs in year k+1  (k = 0, 1, …, n-1).
    For whole-life (n=None): (IA)_x = R_x / D_x.
    For term:  (IA)^1_{x:n|} = (R_x - R_{x+n} - n M_{x+n}) / D_x.

    k parameter: k>1 uses UDD scaling as for Axn.
    """
    whole_life = (n is None) or math.isinf(float(n))
    n_int = at.omega - x if whole_life else int(n)

    if n_int <= 0:
        return 0.0

    Rx_val = at.Rx(x)
    Dx_val = at.Dx(x)

    if whole_life:
        result = Rx_val / Dx_val
    else:
        Rx_n = at.Rx(x + n_int) if (x + n_int) <= at.omega else 0.0
        Mx_n = at.Mx(x + n_int) if (x + n_int) <= at.omega else 0.0
        result = (Rx_val - Rx_n - n_int * Mx_n) / Dx_val

    if k == 1:
        return result
    i = at.interest.i
    i_k = at.interest.i_m(k)
    return (i / i_k) * result

axn(at, x, n=None, k=1)

Actuarial present value of a life annuity-due.

Parameters

at : ActuarialTable x : int Attained age. n : float or None Term in years. None (default) = whole-life. k : int Payment frequency per year (k=1 annual-due, k=2 semi-annual, …). For k>1 the UDD approximation is used.

Source code in src/pylifecontingencies/actuarial.py
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
def axn(
    at: ActuarialTable,
    x: int,
    n: float | None = None,
    k: int = 1,
) -> float:
    """
    Actuarial present value of a life annuity-due.

    Parameters
    ----------
    at : ActuarialTable
    x : int
        Attained age.
    n : float or None
        Term in years. ``None`` (default) = whole-life.
    k : int
        Payment frequency per year (k=1 annual-due, k=2 semi-annual, …).
        For k>1 the UDD approximation is used.
    """
    whole_life = (n is None) or math.isinf(float(n))
    n_int = at.omega - x if whole_life else int(n)

    if n_int <= 0:
        return 0.0

    # Annual annuity-due (exact via commutation columns)
    if k == 1:
        Nx_val = at.Nx(x)
        Nx_n = at.Nx(x + n_int) if (x + n_int) <= at.omega else 0.0
        Dx_val = at.Dx(x)
        if whole_life:
            return Nx_val / Dx_val
        return (Nx_val - Nx_n) / Dx_val

    # k-thly via UDD: ä^(k) = α(k) ä - β(k)(1 - _n E_x)
    ann_annual = axn(at, x, n=None if whole_life else n_int, k=1)
    alpha = at.interest.alpha(k)
    beta = at.interest.beta(k)
    nEx = 0.0 if whole_life else Exn(at, x, n_int)
    return alpha * ann_annual - beta * (1.0 - nEx)

exn(at, x, n=None)

Curtate future lifetime expectation e_x (or temporary e_{x:n|}).

e_x = (l_{x+1} + l_{x+2} + ... + l_omega) / l_x — no discounting. e_{x:n|} = sum_{k=1}^{n} _k p_x.

Note: N_{x+1}/D_x gives the interest-discounted annuity-immediate, NOT e_x.

Source code in src/pylifecontingencies/actuarial.py
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
def exn(
    at: ActuarialTable,
    x: int,
    n: float | None = None,
) -> float:
    """
    Curtate future lifetime expectation e_x (or temporary e_{x:n|}).

    e_x = (l_{x+1} + l_{x+2} + ... + l_omega) / l_x  — no discounting.
    e_{x:n|} = sum_{k=1}^{n} _k p_x.

    Note: N_{x+1}/D_x gives the interest-discounted annuity-immediate, NOT e_x.
    """
    from .demographic import exn as _exn_demo
    return _exn_demo(at, x=x, n=n)

Tábua Atuarial

pylifecontingencies.actuarialtable

ActuarialTable

Life table combined with an interest rate.

Provides commutation columns (Dx, Nx, Cx, Mx, Rx) and delegates to the module-level actuarial functions (axn, Axn, …) via convenience methods.

Parameters

lifetable : LifeTable interest : float or InterestRate Annual effective interest rate (float) or InterestRate instance. name : str Optional label.

Source code in src/pylifecontingencies/actuarialtable.py
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
class ActuarialTable:
    """
    Life table combined with an interest rate.

    Provides commutation columns (Dx, Nx, Cx, Mx, Rx) and delegates to
    the module-level actuarial functions (axn, Axn, …) via convenience methods.

    Parameters
    ----------
    lifetable : LifeTable
    interest : float or InterestRate
        Annual effective interest rate (float) or InterestRate instance.
    name : str
        Optional label.
    """

    def __init__(
        self,
        lifetable: LifeTable,
        interest: float | InterestRate,
        name: str = "",
    ) -> None:
        self.lifetable = lifetable
        if isinstance(interest, (int, float)):
            interest = InterestRate(i=float(interest))
        self.interest = interest
        self.name = name or lifetable.name

    # ------------------------------------------------------------------ #
    # Convenience aliases matching R constructor keyword argument          #
    # ------------------------------------------------------------------ #

    @property
    def i(self) -> float:
        return self.interest.i

    @property
    def v(self) -> float:
        return self.interest.v

    @property
    def x_min(self) -> int:
        return self.lifetable.x_min

    @property
    def omega(self) -> int:
        return self.lifetable.omega

    # ------------------------------------------------------------------ #
    # Commutation columns (vectorised, cached)                            #
    # ------------------------------------------------------------------ #

    @functools.cached_property
    def _comm(self) -> dict[str, np.ndarray]:
        """Compute all commutation columns at once and cache them."""
        lt = self.lifetable
        v = self.interest.v

        ages = np.arange(lt.x_min, lt.omega + 1)
        lx_full = np.array([lt.lx(x) for x in ages], dtype=float)
        dx_full = -np.diff(lx_full)  # length = omega - x_min (no terminal age)

        # Dx = v^x * lx  (length: omega - x_min + 1, includes omega)
        Dx = v ** ages * lx_full

        # Nx = cumulative sum of Dx from right, length = omega - x_min + 1
        # N_x = sum_{t=x}^{omega} D_t  (includes D_omega = 0)
        Nx = np.cumsum(Dx[::-1])[::-1]

        # Cx = v^{x+1} * dx  (length: omega - x_min)
        Cx = v ** (ages[:-1] + 1) * dx_full

        # Mx = cumulative sum of Cx from right
        # M_x = sum_{t=x}^{omega-1} C_t
        Mx = np.concatenate([np.cumsum(Cx[::-1])[::-1], [0.0]])

        # Rx = cumulative sum of Mx from right  (same length as Mx)
        # R_x = sum_{t=x}^{omega-1} M_t  (R_omega = 0)
        Rx = np.concatenate([np.cumsum(Mx[:-1][::-1])[::-1], [0.0]])

        return {
            "ages": ages,
            "Dx": Dx,
            "Nx": Nx,
            "Cx": Cx,
            "Mx": Mx,
            "Rx": Rx,
        }

    def _idx(self, x: int) -> int:
        """Translate age to array index."""
        idx = int(x) - self.x_min
        if idx < 0 or idx >= len(self._comm["Dx"]):
            raise ValueError(
                f"Age {x} out of table range [{self.x_min}, {self.omega}]"
            )
        return idx

    def Dx(self, x: int) -> float:
        return float(self._comm["Dx"][self._idx(x)])

    def Nx(self, x: int) -> float:
        return float(self._comm["Nx"][self._idx(x)])

    def Cx(self, x: int) -> float:
        idx = self._idx(x)
        Cx_arr = self._comm["Cx"]
        if idx >= len(Cx_arr):
            return 0.0
        return float(Cx_arr[idx])

    def Mx(self, x: int) -> float:
        return float(self._comm["Mx"][self._idx(x)])

    def Rx(self, x: int) -> float:
        return float(self._comm["Rx"][self._idx(x)])

    # ------------------------------------------------------------------ #
    # Convenience method wrappers (import deferred to avoid circular)     #
    # ------------------------------------------------------------------ #

    def axn(self, x: int, n: float | None = None, k: int = 1) -> float:
        from .actuarial import axn
        return axn(self, x=x, n=n, k=k)

    def Axn(self, x: int, n: float | None = None, k: int = 1) -> float:
        from .actuarial import Axn
        return Axn(self, x=x, n=n, k=k)

    def Exn(self, x: int, n: int) -> float:
        from .actuarial import Exn
        return Exn(self, x=x, n=n)

    def AExn(self, x: int, n: int, k: int = 1) -> float:
        from .actuarial import AExn
        return AExn(self, x=x, n=n, k=k)

    def IAxn(self, x: int, n: float | None = None, k: int = 1) -> float:
        from .actuarial import IAxn
        return IAxn(self, x=x, n=n, k=k)

    def DAxn(self, x: int, n: int, k: int = 1) -> float:
        from .actuarial import DAxn
        return DAxn(self, x=x, n=n, k=k)

    def exn(self, x: int, n: float | None = None) -> float:
        from .actuarial import exn
        return exn(self, x=x, n=n)

    def simulate_pv(
        self,
        x: int,
        n: int | None = None,
        benefit: str = "term",
        n_sim: int = 10_000,
        random_state: int | np.random.Generator | None = None,
        k: int = 1,
        m: int = 0,
    ):
        """Monte Carlo present-value distribution for a static life-contingent benefit."""
        from .simulation import simulate_pv
        return simulate_pv(
            self, x=x, n=n, benefit=benefit, n_sim=n_sim,
            random_state=random_state, k=k, m=m,
        )

    def __repr__(self) -> str:
        return (
            f"ActuarialTable(name={self.name!r}, "
            f"x_min={self.x_min}, omega={self.omega}, i={self.i:.4g})"
        )

simulate_pv(x, n=None, benefit='term', n_sim=10000, random_state=None, k=1, m=0)

Monte Carlo present-value distribution for a static life-contingent benefit.

Source code in src/pylifecontingencies/actuarialtable.py
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
def simulate_pv(
    self,
    x: int,
    n: int | None = None,
    benefit: str = "term",
    n_sim: int = 10_000,
    random_state: int | np.random.Generator | None = None,
    k: int = 1,
    m: int = 0,
):
    """Monte Carlo present-value distribution for a static life-contingent benefit."""
    from .simulation import simulate_pv
    return simulate_pv(
        self, x=x, n=n, benefit=benefit, n_sim=n_sim,
        random_state=random_state, k=k, m=m,
    )

Modelos Dinâmicos

pylifecontingencies.dynamic

CBD

Cairns-Blake-Dowd (CBD) M5 two-factor mortality model.

Usage

::

cbd = CBD().fit(rates)
forecast = cbd.forecast(horizon=30, ci=0.95)
Source code in src/pylifecontingencies/dynamic/cbd.py
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
class CBD:
    """
    Cairns-Blake-Dowd (CBD) M5 two-factor mortality model.

    Usage
    -----
    ::

        cbd = CBD().fit(rates)
        forecast = cbd.forecast(horizon=30, ci=0.95)
    """

    def __init__(self) -> None:
        self._fitted = False

    def fit(self, rates: MortalityRates) -> CBD:
        """
        Fit the CBD M5 model.

        Parameters
        ----------
        rates : MortalityRates
            Log mortality rate surface. The model internally works with
            q_x values derived from m_x via UDD.
        """
        ages = rates.ages
        years = rates.years
        mx_mat = rates.mx  # shape (n_ages, n_years)

        # Convert mx → qx via UDD
        qx_mat = mx_mat / (1.0 + 0.5 * mx_mat)
        # Clip for numerical stability (logit requires strict (0,1))
        qx_mat = np.clip(qx_mat, 1e-10, 1.0 - 1e-10)

        logit_qx = np.log(qx_mat / (1.0 - qx_mat))

        x_bar = float(ages.mean())
        n_years = len(years)

        k1 = np.empty(n_years)
        k2 = np.empty(n_years)

        age_centred = ages - x_bar
        X = np.column_stack([np.ones(len(ages)), age_centred])
        XtX_inv = np.linalg.inv(X.T @ X)

        for t_idx in range(n_years):
            y = logit_qx[:, t_idx]
            valid = np.isfinite(y)
            if valid.sum() < 2:
                k1[t_idx] = np.nan
                k2[t_idx] = np.nan
                continue
            beta = XtX_inv @ (X[valid].T @ y[valid])
            k1[t_idx] = beta[0]
            k2[t_idx] = beta[1]

        self.ages = ages
        self.x_bar = x_bar
        self.years = years
        self.k1 = k1
        self.k2 = k2
        self._fitted = True
        return self

    def forecast(
        self,
        horizon: int = 30,
        n_bootstrap: int = 0,
        ci: float = 0.95,
        seed: int | None = None,
    ) -> CBDForecast:
        """
        Forecast κ^1_t and κ^2_t as a bivariate random walk with drift.

        Drift and covariance are estimated from the historical differences
        Δκ_t = κ_t - κ_{t-1}.
        """
        if not self._fitted:
            raise RuntimeError("Model not fitted — call .fit() first")

        valid = np.isfinite(self.k1) & np.isfinite(self.k2)
        k1_v = self.k1[valid]
        k2_v = self.k2[valid]

        # Estimate drift and innovation covariance from first differences
        dk1 = np.diff(k1_v)
        dk2 = np.diff(k2_v)
        drift1 = dk1.mean()
        drift2 = dk2.mean()
        resid = np.column_stack([dk1 - drift1, dk2 - drift2])
        Sigma = (resid.T @ resid) / len(resid)

        last_year = int(self.years[-1])
        years_forecast = np.arange(last_year + 1, last_year + horizon + 1)

        k1_central = np.empty(horizon)
        k2_central = np.empty(horizon)
        k1_v_last = k1_v[-1]
        k2_v_last = k2_v[-1]

        for h in range(horizon):
            k1_central[h] = k1_v_last + (h + 1) * drift1
            k2_central[h] = k2_v_last + (h + 1) * drift2

        k1_lower = k1_upper = k2_lower = k2_upper = None

        if n_bootstrap > 0:
            rng = np.random.default_rng(seed)
            k1_boot = np.empty((n_bootstrap, horizon))
            k2_boot = np.empty((n_bootstrap, horizon))

            chol = np.linalg.cholesky(Sigma + 1e-12 * np.eye(2))
            for b in range(n_bootstrap):
                k1_path = k1_v_last
                k2_path = k2_v_last
                for h in range(horizon):
                    z = chol @ rng.standard_normal(2)
                    k1_path = k1_path + drift1 + z[0]
                    k2_path = k2_path + drift2 + z[1]
                    k1_boot[b, h] = k1_path
                    k2_boot[b, h] = k2_path

            alpha = (1.0 - ci) / 2.0
            k1_lower = np.quantile(k1_boot, alpha, axis=0)
            k1_upper = np.quantile(k1_boot, 1.0 - alpha, axis=0)
            k2_lower = np.quantile(k2_boot, alpha, axis=0)
            k2_upper = np.quantile(k2_boot, 1.0 - alpha, axis=0)

        return CBDForecast(
            ages=self.ages,
            x_bar=self.x_bar,
            years_calib=self.years,
            years_forecast=years_forecast,
            k1_calib=self.k1,
            k2_calib=self.k2,
            k1_central=k1_central,
            k2_central=k2_central,
            k1_lower=k1_lower,
            k2_lower=k2_lower,
            k1_upper=k1_upper,
            k2_upper=k2_upper,
            ci=ci,
        )

    def __repr__(self) -> str:
        if not self._fitted:
            return "CBD(not fitted)"
        return (
            f"CBD(ages={self.ages[0]}–{self.ages[-1]}, "
            f"years={self.years[0]}–{self.years[-1]}, x_bar={self.x_bar:.1f})"
        )

fit(rates)

Fit the CBD M5 model.

Parameters

rates : MortalityRates Log mortality rate surface. The model internally works with q_x values derived from m_x via UDD.

Source code in src/pylifecontingencies/dynamic/cbd.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
def fit(self, rates: MortalityRates) -> CBD:
    """
    Fit the CBD M5 model.

    Parameters
    ----------
    rates : MortalityRates
        Log mortality rate surface. The model internally works with
        q_x values derived from m_x via UDD.
    """
    ages = rates.ages
    years = rates.years
    mx_mat = rates.mx  # shape (n_ages, n_years)

    # Convert mx → qx via UDD
    qx_mat = mx_mat / (1.0 + 0.5 * mx_mat)
    # Clip for numerical stability (logit requires strict (0,1))
    qx_mat = np.clip(qx_mat, 1e-10, 1.0 - 1e-10)

    logit_qx = np.log(qx_mat / (1.0 - qx_mat))

    x_bar = float(ages.mean())
    n_years = len(years)

    k1 = np.empty(n_years)
    k2 = np.empty(n_years)

    age_centred = ages - x_bar
    X = np.column_stack([np.ones(len(ages)), age_centred])
    XtX_inv = np.linalg.inv(X.T @ X)

    for t_idx in range(n_years):
        y = logit_qx[:, t_idx]
        valid = np.isfinite(y)
        if valid.sum() < 2:
            k1[t_idx] = np.nan
            k2[t_idx] = np.nan
            continue
        beta = XtX_inv @ (X[valid].T @ y[valid])
        k1[t_idx] = beta[0]
        k2[t_idx] = beta[1]

    self.ages = ages
    self.x_bar = x_bar
    self.years = years
    self.k1 = k1
    self.k2 = k2
    self._fitted = True
    return self

forecast(horizon=30, n_bootstrap=0, ci=0.95, seed=None)

Forecast κ^1_t and κ^2_t as a bivariate random walk with drift.

Drift and covariance are estimated from the historical differences Δκ_t = κ_t - κ_{t-1}.

Source code in src/pylifecontingencies/dynamic/cbd.py
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
def forecast(
    self,
    horizon: int = 30,
    n_bootstrap: int = 0,
    ci: float = 0.95,
    seed: int | None = None,
) -> CBDForecast:
    """
    Forecast κ^1_t and κ^2_t as a bivariate random walk with drift.

    Drift and covariance are estimated from the historical differences
    Δκ_t = κ_t - κ_{t-1}.
    """
    if not self._fitted:
        raise RuntimeError("Model not fitted — call .fit() first")

    valid = np.isfinite(self.k1) & np.isfinite(self.k2)
    k1_v = self.k1[valid]
    k2_v = self.k2[valid]

    # Estimate drift and innovation covariance from first differences
    dk1 = np.diff(k1_v)
    dk2 = np.diff(k2_v)
    drift1 = dk1.mean()
    drift2 = dk2.mean()
    resid = np.column_stack([dk1 - drift1, dk2 - drift2])
    Sigma = (resid.T @ resid) / len(resid)

    last_year = int(self.years[-1])
    years_forecast = np.arange(last_year + 1, last_year + horizon + 1)

    k1_central = np.empty(horizon)
    k2_central = np.empty(horizon)
    k1_v_last = k1_v[-1]
    k2_v_last = k2_v[-1]

    for h in range(horizon):
        k1_central[h] = k1_v_last + (h + 1) * drift1
        k2_central[h] = k2_v_last + (h + 1) * drift2

    k1_lower = k1_upper = k2_lower = k2_upper = None

    if n_bootstrap > 0:
        rng = np.random.default_rng(seed)
        k1_boot = np.empty((n_bootstrap, horizon))
        k2_boot = np.empty((n_bootstrap, horizon))

        chol = np.linalg.cholesky(Sigma + 1e-12 * np.eye(2))
        for b in range(n_bootstrap):
            k1_path = k1_v_last
            k2_path = k2_v_last
            for h in range(horizon):
                z = chol @ rng.standard_normal(2)
                k1_path = k1_path + drift1 + z[0]
                k2_path = k2_path + drift2 + z[1]
                k1_boot[b, h] = k1_path
                k2_boot[b, h] = k2_path

        alpha = (1.0 - ci) / 2.0
        k1_lower = np.quantile(k1_boot, alpha, axis=0)
        k1_upper = np.quantile(k1_boot, 1.0 - alpha, axis=0)
        k2_lower = np.quantile(k2_boot, alpha, axis=0)
        k2_upper = np.quantile(k2_boot, 1.0 - alpha, axis=0)

    return CBDForecast(
        ages=self.ages,
        x_bar=self.x_bar,
        years_calib=self.years,
        years_forecast=years_forecast,
        k1_calib=self.k1,
        k2_calib=self.k2,
        k1_central=k1_central,
        k2_central=k2_central,
        k1_lower=k1_lower,
        k2_lower=k2_lower,
        k1_upper=k1_upper,
        k2_upper=k2_upper,
        ci=ci,
    )

CBDForecast

Forecast object returned by CBD.forecast().

Source code in src/pylifecontingencies/dynamic/cbd.py
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
class CBDForecast:
    """Forecast object returned by CBD.forecast()."""

    def __init__(
        self,
        ages: np.ndarray,
        x_bar: float,
        years_calib: np.ndarray,
        years_forecast: np.ndarray,
        k1_calib: np.ndarray,
        k2_calib: np.ndarray,
        k1_central: np.ndarray,
        k2_central: np.ndarray,
        k1_lower: np.ndarray | None,
        k2_lower: np.ndarray | None,
        k1_upper: np.ndarray | None,
        k2_upper: np.ndarray | None,
        ci: float,
    ) -> None:
        self.ages = ages
        self.x_bar = x_bar
        self.years_calib = years_calib
        self.years_forecast = years_forecast
        self.k1_calib = k1_calib
        self.k2_calib = k2_calib
        self.k1_central = k1_central
        self.k2_central = k2_central
        self.k1_lower = k1_lower
        self.k2_lower = k2_lower
        self.k1_upper = k1_upper
        self.k2_upper = k2_upper
        self.ci = ci

    def _get_kappa(self, year: int) -> tuple[float, float]:
        if year in self.years_calib:
            idx = list(self.years_calib).index(year)
            return float(self.k1_calib[idx]), float(self.k2_calib[idx])
        idx = list(self.years_forecast).index(year)
        return float(self.k1_central[idx]), float(self.k2_central[idx])

    def logit_qx(self, year: int) -> np.ndarray:
        k1, k2 = self._get_kappa(year)
        return k1 + (self.ages - self.x_bar) * k2

    def qx(self, year: int) -> np.ndarray:
        """Predicted q_x for a given year."""
        lgt = self.logit_qx(year)
        return 1.0 / (1.0 + np.exp(-lgt))

    def mx(self, year: int) -> np.ndarray:
        """Convert q_x to m_x via UDD approximation."""
        qx = self.qx(year)
        return qx / (1.0 - 0.5 * qx)

mx(year)

Convert q_x to m_x via UDD approximation.

Source code in src/pylifecontingencies/dynamic/cbd.py
70
71
72
73
def mx(self, year: int) -> np.ndarray:
    """Convert q_x to m_x via UDD approximation."""
    qx = self.qx(year)
    return qx / (1.0 - 0.5 * qx)

qx(year)

Predicted q_x for a given year.

Source code in src/pylifecontingencies/dynamic/cbd.py
65
66
67
68
def qx(self, year: int) -> np.ndarray:
    """Predicted q_x for a given year."""
    lgt = self.logit_qx(year)
    return 1.0 / (1.0 + np.exp(-lgt))

DynamicActuarialTable

Actuarial table built on top of a ProjectedLifeTable or DynamicLifeTable.

Wraps one or more ActuarialTable instances (one per scenario) and exposes the same EPV API. Returns float for single-path tables and StochasticResult for stochastic/PI tables.

Parameters

source : ProjectedLifeTable, DynamicLifeTable, or LifeTable list interest : float or InterestRate Annual effective interest rate.

Examples

From a ProjectedLifeTable::

plt = ProjectedLifeTable.from_mx(df, birth_year=1985)
dat = DynamicActuarialTable(plt, i=0.03)
dat.axn(x=40)   # → float

With prediction intervals::

plt = ProjectedLifeTable.from_mx(
    df, lower=df_lo, upper=df_hi, birth_year=1985
)
dat = DynamicActuarialTable(plt, i=0.03)
r = dat.axn(x=40)   # → StochasticResult (3 values: lo, central, hi)

Stochastic (N scenarios)::

plt = ProjectedLifeTable.from_scenarios(paths, birth_year=1985)
dat = DynamicActuarialTable(plt, i=0.03)
r = dat.axn(x=40)
r.mean, r.std, r.ci(0.95)  # → StochasticResult
Source code in src/pylifecontingencies/dynamic/dynamic_actuarialtable.py
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
class DynamicActuarialTable:
    """
    Actuarial table built on top of a ProjectedLifeTable or DynamicLifeTable.

    Wraps one or more ActuarialTable instances (one per scenario) and
    exposes the same EPV API. Returns ``float`` for single-path tables
    and ``StochasticResult`` for stochastic/PI tables.

    Parameters
    ----------
    source : ProjectedLifeTable, DynamicLifeTable, or LifeTable list
    interest : float or InterestRate
        Annual effective interest rate.

    Examples
    --------
    From a ProjectedLifeTable::

        plt = ProjectedLifeTable.from_mx(df, birth_year=1985)
        dat = DynamicActuarialTable(plt, i=0.03)
        dat.axn(x=40)   # → float

    With prediction intervals::

        plt = ProjectedLifeTable.from_mx(
            df, lower=df_lo, upper=df_hi, birth_year=1985
        )
        dat = DynamicActuarialTable(plt, i=0.03)
        r = dat.axn(x=40)   # → StochasticResult (3 values: lo, central, hi)

    Stochastic (N scenarios)::

        plt = ProjectedLifeTable.from_scenarios(paths, birth_year=1985)
        dat = DynamicActuarialTable(plt, i=0.03)
        r = dat.axn(x=40)
        r.mean, r.std, r.ci(0.95)  # → StochasticResult
    """

    def __init__(
        self,
        source: ProjectedLifeTable | DynamicLifeTable,
        interest: float | InterestRate,
        name: str = "",
    ) -> None:
        # Accept both ProjectedLifeTable and DynamicLifeTable
        if isinstance(source, ProjectedLifeTable):
            self._source = source
            tables = source.tables
            self._is_stochastic = source.is_stochastic
        elif isinstance(source, DynamicLifeTable):
            self._source = source
            tables = source.tables
            self._is_stochastic = source.is_stochastic
        else:
            raise TypeError(
                f"Expected ProjectedLifeTable or DynamicLifeTable, "
                f"got {type(source).__name__}"
            )

        # Keep backward compat attribute
        self.dynamic_lifetable = source

        if isinstance(interest, (int, float)):
            interest = InterestRate(i=float(interest))
        self.interest = interest
        self.name = name

        # Pre-build one ActuarialTable per scenario
        self._ats: list[ActuarialTable] = [
            ActuarialTable(lt, interest) for lt in tables
        ]

    # ------------------------------------------------------------------ #
    # Internal dispatch                                                    #
    # ------------------------------------------------------------------ #

    def _map(self, fn, *args, label: str = "", **kwargs) -> _Result:
        """
        Apply fn(ActuarialTable, *args, **kwargs) across all scenarios.
        Returns float for single-path, StochasticResult for stochastic.
        """
        results = [fn(at, *args, **kwargs) for at in self._ats]
        if not self._is_stochastic:
            return results[0]
        return StochasticResult(np.array(results, dtype=float), label=label)

    # ------------------------------------------------------------------ #
    # Convenience properties                                               #
    # ------------------------------------------------------------------ #

    @property
    def i(self) -> float:
        return self.interest.i

    @property
    def is_stochastic(self) -> bool:
        return self._is_stochastic

    @property
    def n_scenarios(self) -> int:
        return len(self._ats)

    # ------------------------------------------------------------------ #
    # Pure endowment                                                       #
    # ------------------------------------------------------------------ #

    def Exn(self, x: int, n: int) -> _Result:
        """n-year pure endowment _n E_x."""
        from ..actuarial import Exn as _Exn
        return self._map(_Exn, x=x, n=n, label=f"Exn(x={x}, n={n})")

    # ------------------------------------------------------------------ #
    # Life annuities                                                       #
    # ------------------------------------------------------------------ #

    def axn(self, x: int, n: float | None = None, k: int = 1) -> _Result:
        """
        Actuarial present value of a life annuity-due ä_{x:n|}.

        Parameters
        ----------
        x : int   Attained age.
        n : float or None   Term (None = whole-life).
        k : int   Payment frequency per year.
        """
        from ..actuarial import axn as _axn
        label = f"axn(x={x}" + (f", n={n}" if n is not None else "") + f", k={k})"
        return self._map(_axn, x=x, n=n, k=k, label=label)

    # ------------------------------------------------------------------ #
    # Life insurances                                                      #
    # ------------------------------------------------------------------ #

    def Axn(self, x: int, n: float | None = None, k: int = 1) -> _Result:
        """Term (or whole-life) insurance A^1_{x:n|}."""
        from ..actuarial import Axn as _Axn
        label = f"Axn(x={x}" + (f", n={n}" if n is not None else "") + f", k={k})"
        return self._map(_Axn, x=x, n=n, k=k, label=label)

    def AExn(self, x: int, n: int, k: int = 1) -> _Result:
        """Endowment insurance A_{x:n|}."""
        from ..actuarial import AExn as _AExn
        return self._map(_AExn, x=x, n=n, k=k, label=f"AExn(x={x}, n={n}, k={k})")

    def IAxn(self, x: int, n: float | None = None, k: int = 1) -> _Result:
        """Increasing insurance (IA)_{x:n|}."""
        from ..actuarial import IAxn as _IAxn
        label = f"IAxn(x={x}" + (f", n={n}" if n is not None else "") + ")"
        return self._map(_IAxn, x=x, n=n, k=k, label=label)

    def DAxn(self, x: int, n: int, k: int = 1) -> _Result:
        """Decreasing term insurance (DA)^1_{x:n|}."""
        from ..actuarial import DAxn as _DAxn
        return self._map(_DAxn, x=x, n=n, k=k, label=f"DAxn(x={x}, n={n})")

    # ------------------------------------------------------------------ #
    # Life expectation                                                     #
    # ------------------------------------------------------------------ #

    def exn(self, x: int, n: float | None = None) -> _Result:
        """Curtate future lifetime expectation e_x (or temporary e_{x:n|})."""
        from ..actuarial import exn as _exn
        label = f"exn(x={x}" + (f", n={n}" if n is not None else "") + ")"
        return self._map(_exn, x=x, n=n, label=label)

    # ------------------------------------------------------------------ #
    # Premiums                                                             #
    # ------------------------------------------------------------------ #

    def net_premium(
        self,
        x: int,
        n: int | None = None,
        k: int = 1,
        benefit: str = "term",
    ) -> _Result:
        """Net (benefit) premium via the equivalence principle."""
        from ..premiums import net_premium as _np
        return self._map(
            lambda at: _np(at, x=x, n=n, k=k, benefit=benefit),
            label=f"net_premium(x={x}, n={n}, benefit={benefit!r})",
        )

    def gross_premium(
        self,
        x: int,
        n: int | None = None,
        k: int = 1,
        benefit: str = "term",
        expense_ratio: float = 0.0,
        per_policy: float = 0.0,
    ) -> _Result:
        """Gross premium including expense loading."""
        from ..premiums import gross_premium as _gp
        return self._map(
            lambda at: _gp(
                at, x=x, n=n, k=k, benefit=benefit,
                expense_ratio=expense_ratio, per_policy=per_policy,
            ),
            label=f"gross_premium(x={x}, n={n})",
        )

    # ------------------------------------------------------------------ #
    # Reserves                                                             #
    # ------------------------------------------------------------------ #

    def prospective_reserve(
        self,
        x: int,
        n: int,
        t: int,
        k: int = 1,
        benefit: str = "term",
        premium: float | None = None,
    ) -> _Result:
        """Prospective net reserve _t V at duration t."""
        from ..reserves import prospective_reserve as _pr
        return self._map(
            lambda at: _pr(at, x=x, n=n, t=t, k=k, benefit=benefit, premium=premium),
            label=f"reserve(x={x}, n={n}, t={t})",
        )

    def reserve_recursion(
        self,
        x: int,
        n: int,
        k: int = 1,
        benefit: str = "term",
    ) -> list[_Result]:
        """
        Full reserve vector [_0 V, _1 V, ..., _n V].

        Returns a list of floats (single-path) or a list of StochasticResult
        (stochastic), one element per duration t = 0, ..., n.
        """
        from ..reserves import reserve_recursion as _rr

        if not self._is_stochastic:
            return _rr(self._ats[0], x=x, n=n, k=k, benefit=benefit)

        # For each t collect values across scenarios
        per_scenario = [_rr(at, x=x, n=n, k=k, benefit=benefit) for at in self._ats]
        # Transpose: list[scenario][t] -> list[t][scenario]
        return [
            StochasticResult(
                np.array([per_scenario[s][t] for s in range(len(self._ats))]),
                label=f"reserve(t={t})",
            )
            for t in range(n + 1)
        ]

    # ------------------------------------------------------------------ #
    # Commutation columns (single-path only)                              #
    # ------------------------------------------------------------------ #

    def Dx(self, x: int) -> float:
        return self._ats[0].Dx(x)

    def Nx(self, x: int) -> float:
        return self._ats[0].Nx(x)

    def Mx(self, x: int) -> float:
        return self._ats[0].Mx(x)

    # ------------------------------------------------------------------ #
    # Repr                                                                 #
    # ------------------------------------------------------------------ #

    def __repr__(self) -> str:
        lt = self._ats[0].lifetable
        if self._is_stochastic:
            tag = f"stochastic, n={self.n_scenarios}"
        else:
            tag = "single-path"
        return (
            f"DynamicActuarialTable({tag}, "
            f"ages={lt.x_min}–{lt.omega - 1}, i={self.i:.4g})"
        )

AExn(x, n, k=1)

Endowment insurance A_{x:n|}.

Source code in src/pylifecontingencies/dynamic/dynamic_actuarialtable.py
171
172
173
174
def AExn(self, x: int, n: int, k: int = 1) -> _Result:
    """Endowment insurance A_{x:n|}."""
    from ..actuarial import AExn as _AExn
    return self._map(_AExn, x=x, n=n, k=k, label=f"AExn(x={x}, n={n}, k={k})")

Axn(x, n=None, k=1)

Term (or whole-life) insurance A^1_{x:n|}.

Source code in src/pylifecontingencies/dynamic/dynamic_actuarialtable.py
165
166
167
168
169
def Axn(self, x: int, n: float | None = None, k: int = 1) -> _Result:
    """Term (or whole-life) insurance A^1_{x:n|}."""
    from ..actuarial import Axn as _Axn
    label = f"Axn(x={x}" + (f", n={n}" if n is not None else "") + f", k={k})"
    return self._map(_Axn, x=x, n=n, k=k, label=label)

DAxn(x, n, k=1)

Decreasing term insurance (DA)^1_{x:n|}.

Source code in src/pylifecontingencies/dynamic/dynamic_actuarialtable.py
182
183
184
185
def DAxn(self, x: int, n: int, k: int = 1) -> _Result:
    """Decreasing term insurance (DA)^1_{x:n|}."""
    from ..actuarial import DAxn as _DAxn
    return self._map(_DAxn, x=x, n=n, k=k, label=f"DAxn(x={x}, n={n})")

Exn(x, n)

n-year pure endowment _n E_x.

Source code in src/pylifecontingencies/dynamic/dynamic_actuarialtable.py
138
139
140
141
def Exn(self, x: int, n: int) -> _Result:
    """n-year pure endowment _n E_x."""
    from ..actuarial import Exn as _Exn
    return self._map(_Exn, x=x, n=n, label=f"Exn(x={x}, n={n})")

IAxn(x, n=None, k=1)

Increasing insurance (IA)_{x:n|}.

Source code in src/pylifecontingencies/dynamic/dynamic_actuarialtable.py
176
177
178
179
180
def IAxn(self, x: int, n: float | None = None, k: int = 1) -> _Result:
    """Increasing insurance (IA)_{x:n|}."""
    from ..actuarial import IAxn as _IAxn
    label = f"IAxn(x={x}" + (f", n={n}" if n is not None else "") + ")"
    return self._map(_IAxn, x=x, n=n, k=k, label=label)

axn(x, n=None, k=1)

Actuarial present value of a life annuity-due ä_{x:n|}.

Parameters

x : int Attained age. n : float or None Term (None = whole-life). k : int Payment frequency per year.

Source code in src/pylifecontingencies/dynamic/dynamic_actuarialtable.py
147
148
149
150
151
152
153
154
155
156
157
158
159
def axn(self, x: int, n: float | None = None, k: int = 1) -> _Result:
    """
    Actuarial present value of a life annuity-due ä_{x:n|}.

    Parameters
    ----------
    x : int   Attained age.
    n : float or None   Term (None = whole-life).
    k : int   Payment frequency per year.
    """
    from ..actuarial import axn as _axn
    label = f"axn(x={x}" + (f", n={n}" if n is not None else "") + f", k={k})"
    return self._map(_axn, x=x, n=n, k=k, label=label)

exn(x, n=None)

Curtate future lifetime expectation e_x (or temporary e_{x:n|}).

Source code in src/pylifecontingencies/dynamic/dynamic_actuarialtable.py
191
192
193
194
195
def exn(self, x: int, n: float | None = None) -> _Result:
    """Curtate future lifetime expectation e_x (or temporary e_{x:n|})."""
    from ..actuarial import exn as _exn
    label = f"exn(x={x}" + (f", n={n}" if n is not None else "") + ")"
    return self._map(_exn, x=x, n=n, label=label)

gross_premium(x, n=None, k=1, benefit='term', expense_ratio=0.0, per_policy=0.0)

Gross premium including expense loading.

Source code in src/pylifecontingencies/dynamic/dynamic_actuarialtable.py
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
def gross_premium(
    self,
    x: int,
    n: int | None = None,
    k: int = 1,
    benefit: str = "term",
    expense_ratio: float = 0.0,
    per_policy: float = 0.0,
) -> _Result:
    """Gross premium including expense loading."""
    from ..premiums import gross_premium as _gp
    return self._map(
        lambda at: _gp(
            at, x=x, n=n, k=k, benefit=benefit,
            expense_ratio=expense_ratio, per_policy=per_policy,
        ),
        label=f"gross_premium(x={x}, n={n})",
    )

net_premium(x, n=None, k=1, benefit='term')

Net (benefit) premium via the equivalence principle.

Source code in src/pylifecontingencies/dynamic/dynamic_actuarialtable.py
201
202
203
204
205
206
207
208
209
210
211
212
213
def net_premium(
    self,
    x: int,
    n: int | None = None,
    k: int = 1,
    benefit: str = "term",
) -> _Result:
    """Net (benefit) premium via the equivalence principle."""
    from ..premiums import net_premium as _np
    return self._map(
        lambda at: _np(at, x=x, n=n, k=k, benefit=benefit),
        label=f"net_premium(x={x}, n={n}, benefit={benefit!r})",
    )

prospective_reserve(x, n, t, k=1, benefit='term', premium=None)

Prospective net reserve _t V at duration t.

Source code in src/pylifecontingencies/dynamic/dynamic_actuarialtable.py
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
def prospective_reserve(
    self,
    x: int,
    n: int,
    t: int,
    k: int = 1,
    benefit: str = "term",
    premium: float | None = None,
) -> _Result:
    """Prospective net reserve _t V at duration t."""
    from ..reserves import prospective_reserve as _pr
    return self._map(
        lambda at: _pr(at, x=x, n=n, t=t, k=k, benefit=benefit, premium=premium),
        label=f"reserve(x={x}, n={n}, t={t})",
    )

reserve_recursion(x, n, k=1, benefit='term')

Full reserve vector [_0 V, _1 V, ..., _n V].

Returns a list of floats (single-path) or a list of StochasticResult (stochastic), one element per duration t = 0, ..., n.

Source code in src/pylifecontingencies/dynamic/dynamic_actuarialtable.py
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
def reserve_recursion(
    self,
    x: int,
    n: int,
    k: int = 1,
    benefit: str = "term",
) -> list[_Result]:
    """
    Full reserve vector [_0 V, _1 V, ..., _n V].

    Returns a list of floats (single-path) or a list of StochasticResult
    (stochastic), one element per duration t = 0, ..., n.
    """
    from ..reserves import reserve_recursion as _rr

    if not self._is_stochastic:
        return _rr(self._ats[0], x=x, n=n, k=k, benefit=benefit)

    # For each t collect values across scenarios
    per_scenario = [_rr(at, x=x, n=n, k=k, benefit=benefit) for at in self._ats]
    # Transpose: list[scenario][t] -> list[t][scenario]
    return [
        StochasticResult(
            np.array([per_scenario[s][t] for s in range(len(self._ats))]),
            label=f"reserve(t={t})",
        )
        for t in range(n + 1)
    ]

DynamicLifeTable

A life table (or collection of life tables) built from an external mortality-rate forecast.

Parameters

tables : list[LifeTable] One LifeTable per scenario. Single-path tables have len(tables) == 1. is_stochastic : bool True when multiple scenarios are stored.

See Also

DynamicActuarialTable : wraps this with an interest rate and computes EPVs.

Source code in src/pylifecontingencies/dynamic/dynamic_lifetable.py
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
class DynamicLifeTable:
    """
    A life table (or collection of life tables) built from an external
    mortality-rate forecast.

    Parameters
    ----------
    tables : list[LifeTable]
        One LifeTable per scenario. Single-path tables have ``len(tables) == 1``.
    is_stochastic : bool
        True when multiple scenarios are stored.

    See Also
    --------
    DynamicActuarialTable : wraps this with an interest rate and computes EPVs.
    """

    def __init__(self, tables: list[LifeTable], is_stochastic: bool) -> None:
        if not tables:
            raise ValueError("tables must be a non-empty list")
        self._tables = tables
        self.is_stochastic = is_stochastic

    # ------------------------------------------------------------------ #
    # Constructors                                                         #
    # ------------------------------------------------------------------ #

    @classmethod
    def from_forecast_mx(
        cls,
        df_mx: pd.DataFrame,
        *,
        birth_year: int | None = None,
        period_year: int | None = None,
        fractional: FractionalAge = FractionalAge.UDD,
        name: str = "",
    ) -> DynamicLifeTable:
        """
        Build a single-path DynamicLifeTable from central death rates m_x.

        Parameters
        ----------
        df_mx : pd.DataFrame
            Ages as index (int), calendar years as columns (int),
            values are central death rates m_{x,t}.
        birth_year : int or None
            Extract cohort diagonal (age x → year birth_year + x).
        period_year : int or None
            Extract a period column (all ages from the same year).
        fractional : FractionalAge
            Fractional-age assumption for the resulting LifeTable.
        name : str
            Optional label for the LifeTable.

        Examples
        --------
        ::

            dlt = DynamicLifeTable.from_forecast_mx(df_mx, birth_year=1985)
            dat = DynamicActuarialTable(dlt, i=0.03)
            dat.axn(x=40)
        """
        lt = _build_lifetable(
            df_mx,
            birth_year=birth_year,
            period_year=period_year,
            input_type="mx",
            fractional=fractional,
            name=name or _auto_name(birth_year, period_year),
        )
        return cls([lt], is_stochastic=False)

    @classmethod
    def from_forecast_qx(
        cls,
        df_qx: pd.DataFrame,
        *,
        birth_year: int | None = None,
        period_year: int | None = None,
        fractional: FractionalAge = FractionalAge.UDD,
        name: str = "",
    ) -> DynamicLifeTable:
        """
        Build a single-path DynamicLifeTable from mortality rates q_x.

        Parameters
        ----------
        df_qx : pd.DataFrame
            Ages as index (int), calendar years as columns (int),
            values are annual mortality rates q_{x,t}.
        """
        lt = _build_lifetable(
            df_qx,
            birth_year=birth_year,
            period_year=period_year,
            input_type="qx",
            fractional=fractional,
            name=name or _auto_name(birth_year, period_year),
        )
        return cls([lt], is_stochastic=False)

    @classmethod
    def from_forecast_log_mx(
        cls,
        df_log_mx: pd.DataFrame,
        *,
        birth_year: int | None = None,
        period_year: int | None = None,
        fractional: FractionalAge = FractionalAge.UDD,
        name: str = "",
    ) -> DynamicLifeTable:
        """
        Build a single-path DynamicLifeTable from log central death rates log(m_x).

        This is the natural output of Lee-Carter and similar log-linear models.
        """
        lt = _build_lifetable(
            df_log_mx,
            birth_year=birth_year,
            period_year=period_year,
            input_type="log_mx",
            fractional=fractional,
            name=name or _auto_name(birth_year, period_year),
        )
        return cls([lt], is_stochastic=False)

    @classmethod
    def from_scenarios(
        cls,
        scenarios: Sequence[pd.DataFrame],
        *,
        birth_year: int | None = None,
        period_year: int | None = None,
        input_type: str = "mx",
        fractional: FractionalAge = FractionalAge.UDD,
    ) -> DynamicLifeTable:
        """
        Build a stochastic DynamicLifeTable from multiple forecast paths.

        Parameters
        ----------
        scenarios : sequence of pd.DataFrame
            Each DataFrame is a (ages × years) forecast surface. All must
            share the same index (ages) and columns (years).
        input_type : {'mx', 'qx', 'log_mx'}
            What the DataFrame values represent.

        Examples
        --------
        ::

            # 500 bootstrap paths
            dlt = DynamicLifeTable.from_scenarios(list_of_dfs, birth_year=1985)
            dat = DynamicActuarialTable(dlt, i=0.03)
            result = dat.axn(x=40)   # StochasticResult
            print(result.mean, result.std, result.ci(0.95))
        """
        tables = [
            _build_lifetable(
                df,
                birth_year=birth_year,
                period_year=period_year,
                input_type=input_type,
                fractional=fractional,
                name=f"scenario_{i}",
            )
            for i, df in enumerate(scenarios)
        ]
        return cls(tables, is_stochastic=True)

    @classmethod
    def from_scenarios_array(
        cls,
        arr: np.ndarray,
        *,
        ages: np.ndarray | list[int],
        years: np.ndarray | list[int],
        birth_year: int | None = None,
        period_year: int | None = None,
        input_type: str = "mx",
        fractional: FractionalAge = FractionalAge.UDD,
    ) -> DynamicLifeTable:
        """
        Build a stochastic DynamicLifeTable from a 3-D numpy array.

        Parameters
        ----------
        arr : np.ndarray, shape (n_samples, n_ages, n_years)
            Mortality-rate cube (central rates, raw rates, or log rates).
        ages : array-like of int
            Age labels for axis 1.
        years : array-like of int
            Year labels for axis 2.
        input_type : {'mx', 'qx', 'log_mx'}

        Examples
        --------
        ::

            # arr shape: (500, 80, 50)  — 500 scenarios, ages 20-99, years 2025-2074
            dlt = DynamicLifeTable.from_scenarios_array(
                arr, ages=range(20, 100), years=range(2025, 2075), birth_year=1985
            )
        """
        arr = np.asarray(arr, dtype=float)
        if arr.ndim != 3:
            raise ValueError(f"arr must be 3-D (n_samples, n_ages, n_years), got shape {arr.shape}")

        ages_arr = np.asarray(ages, dtype=int)
        years_arr = np.asarray(years, dtype=int)

        scenarios = [
            pd.DataFrame(arr[i], index=ages_arr, columns=years_arr)
            for i in range(arr.shape[0])
        ]
        return cls.from_scenarios(
            scenarios,
            birth_year=birth_year,
            period_year=period_year,
            input_type=input_type,
            fractional=fractional,
        )

    # ------------------------------------------------------------------ #
    # Properties                                                           #
    # ------------------------------------------------------------------ #

    @property
    def tables(self) -> list[LifeTable]:
        return self._tables

    @property
    def n_scenarios(self) -> int:
        return len(self._tables)

    @property
    def lifetable(self) -> LifeTable:
        """The single LifeTable — raises if stochastic."""
        if self.is_stochastic:
            raise ValueError(
                "This DynamicLifeTable has multiple scenarios. "
                "Access individual tables via .tables[i] or use DynamicActuarialTable."
            )
        return self._tables[0]

    def __repr__(self) -> str:
        lt = self._tables[0]
        tag = f"stochastic, n={self.n_scenarios}" if self.is_stochastic else "single-path"
        return (
            f"DynamicLifeTable({tag}, ages={lt.x_min}–{lt.omega - 1}, "
            f"fractional={lt.fractional.value})"
        )

lifetable property

The single LifeTable — raises if stochastic.

from_forecast_log_mx(df_log_mx, *, birth_year=None, period_year=None, fractional=FractionalAge.UDD, name='') classmethod

Build a single-path DynamicLifeTable from log central death rates log(m_x).

This is the natural output of Lee-Carter and similar log-linear models.

Source code in src/pylifecontingencies/dynamic/dynamic_lifetable.py
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
@classmethod
def from_forecast_log_mx(
    cls,
    df_log_mx: pd.DataFrame,
    *,
    birth_year: int | None = None,
    period_year: int | None = None,
    fractional: FractionalAge = FractionalAge.UDD,
    name: str = "",
) -> DynamicLifeTable:
    """
    Build a single-path DynamicLifeTable from log central death rates log(m_x).

    This is the natural output of Lee-Carter and similar log-linear models.
    """
    lt = _build_lifetable(
        df_log_mx,
        birth_year=birth_year,
        period_year=period_year,
        input_type="log_mx",
        fractional=fractional,
        name=name or _auto_name(birth_year, period_year),
    )
    return cls([lt], is_stochastic=False)

from_forecast_mx(df_mx, *, birth_year=None, period_year=None, fractional=FractionalAge.UDD, name='') classmethod

Build a single-path DynamicLifeTable from central death rates m_x.

Parameters

df_mx : pd.DataFrame Ages as index (int), calendar years as columns (int), values are central death rates m_{x,t}. birth_year : int or None Extract cohort diagonal (age x → year birth_year + x). period_year : int or None Extract a period column (all ages from the same year). fractional : FractionalAge Fractional-age assumption for the resulting LifeTable. name : str Optional label for the LifeTable.

Examples

::

dlt = DynamicLifeTable.from_forecast_mx(df_mx, birth_year=1985)
dat = DynamicActuarialTable(dlt, i=0.03)
dat.axn(x=40)
Source code in src/pylifecontingencies/dynamic/dynamic_lifetable.py
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
@classmethod
def from_forecast_mx(
    cls,
    df_mx: pd.DataFrame,
    *,
    birth_year: int | None = None,
    period_year: int | None = None,
    fractional: FractionalAge = FractionalAge.UDD,
    name: str = "",
) -> DynamicLifeTable:
    """
    Build a single-path DynamicLifeTable from central death rates m_x.

    Parameters
    ----------
    df_mx : pd.DataFrame
        Ages as index (int), calendar years as columns (int),
        values are central death rates m_{x,t}.
    birth_year : int or None
        Extract cohort diagonal (age x → year birth_year + x).
    period_year : int or None
        Extract a period column (all ages from the same year).
    fractional : FractionalAge
        Fractional-age assumption for the resulting LifeTable.
    name : str
        Optional label for the LifeTable.

    Examples
    --------
    ::

        dlt = DynamicLifeTable.from_forecast_mx(df_mx, birth_year=1985)
        dat = DynamicActuarialTable(dlt, i=0.03)
        dat.axn(x=40)
    """
    lt = _build_lifetable(
        df_mx,
        birth_year=birth_year,
        period_year=period_year,
        input_type="mx",
        fractional=fractional,
        name=name or _auto_name(birth_year, period_year),
    )
    return cls([lt], is_stochastic=False)

from_forecast_qx(df_qx, *, birth_year=None, period_year=None, fractional=FractionalAge.UDD, name='') classmethod

Build a single-path DynamicLifeTable from mortality rates q_x.

Parameters

df_qx : pd.DataFrame Ages as index (int), calendar years as columns (int), values are annual mortality rates q_{x,t}.

Source code in src/pylifecontingencies/dynamic/dynamic_lifetable.py
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
@classmethod
def from_forecast_qx(
    cls,
    df_qx: pd.DataFrame,
    *,
    birth_year: int | None = None,
    period_year: int | None = None,
    fractional: FractionalAge = FractionalAge.UDD,
    name: str = "",
) -> DynamicLifeTable:
    """
    Build a single-path DynamicLifeTable from mortality rates q_x.

    Parameters
    ----------
    df_qx : pd.DataFrame
        Ages as index (int), calendar years as columns (int),
        values are annual mortality rates q_{x,t}.
    """
    lt = _build_lifetable(
        df_qx,
        birth_year=birth_year,
        period_year=period_year,
        input_type="qx",
        fractional=fractional,
        name=name or _auto_name(birth_year, period_year),
    )
    return cls([lt], is_stochastic=False)

from_scenarios(scenarios, *, birth_year=None, period_year=None, input_type='mx', fractional=FractionalAge.UDD) classmethod

Build a stochastic DynamicLifeTable from multiple forecast paths.

Parameters

scenarios : sequence of pd.DataFrame Each DataFrame is a (ages × years) forecast surface. All must share the same index (ages) and columns (years). input_type : {'mx', 'qx', 'log_mx'} What the DataFrame values represent.

Examples

::

# 500 bootstrap paths
dlt = DynamicLifeTable.from_scenarios(list_of_dfs, birth_year=1985)
dat = DynamicActuarialTable(dlt, i=0.03)
result = dat.axn(x=40)   # StochasticResult
print(result.mean, result.std, result.ci(0.95))
Source code in src/pylifecontingencies/dynamic/dynamic_lifetable.py
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
@classmethod
def from_scenarios(
    cls,
    scenarios: Sequence[pd.DataFrame],
    *,
    birth_year: int | None = None,
    period_year: int | None = None,
    input_type: str = "mx",
    fractional: FractionalAge = FractionalAge.UDD,
) -> DynamicLifeTable:
    """
    Build a stochastic DynamicLifeTable from multiple forecast paths.

    Parameters
    ----------
    scenarios : sequence of pd.DataFrame
        Each DataFrame is a (ages × years) forecast surface. All must
        share the same index (ages) and columns (years).
    input_type : {'mx', 'qx', 'log_mx'}
        What the DataFrame values represent.

    Examples
    --------
    ::

        # 500 bootstrap paths
        dlt = DynamicLifeTable.from_scenarios(list_of_dfs, birth_year=1985)
        dat = DynamicActuarialTable(dlt, i=0.03)
        result = dat.axn(x=40)   # StochasticResult
        print(result.mean, result.std, result.ci(0.95))
    """
    tables = [
        _build_lifetable(
            df,
            birth_year=birth_year,
            period_year=period_year,
            input_type=input_type,
            fractional=fractional,
            name=f"scenario_{i}",
        )
        for i, df in enumerate(scenarios)
    ]
    return cls(tables, is_stochastic=True)

from_scenarios_array(arr, *, ages, years, birth_year=None, period_year=None, input_type='mx', fractional=FractionalAge.UDD) classmethod

Build a stochastic DynamicLifeTable from a 3-D numpy array.

Parameters

arr : np.ndarray, shape (n_samples, n_ages, n_years) Mortality-rate cube (central rates, raw rates, or log rates). ages : array-like of int Age labels for axis 1. years : array-like of int Year labels for axis 2. input_type : {'mx', 'qx', 'log_mx'}

Examples

::

# arr shape: (500, 80, 50)  — 500 scenarios, ages 20-99, years 2025-2074
dlt = DynamicLifeTable.from_scenarios_array(
    arr, ages=range(20, 100), years=range(2025, 2075), birth_year=1985
)
Source code in src/pylifecontingencies/dynamic/dynamic_lifetable.py
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
@classmethod
def from_scenarios_array(
    cls,
    arr: np.ndarray,
    *,
    ages: np.ndarray | list[int],
    years: np.ndarray | list[int],
    birth_year: int | None = None,
    period_year: int | None = None,
    input_type: str = "mx",
    fractional: FractionalAge = FractionalAge.UDD,
) -> DynamicLifeTable:
    """
    Build a stochastic DynamicLifeTable from a 3-D numpy array.

    Parameters
    ----------
    arr : np.ndarray, shape (n_samples, n_ages, n_years)
        Mortality-rate cube (central rates, raw rates, or log rates).
    ages : array-like of int
        Age labels for axis 1.
    years : array-like of int
        Year labels for axis 2.
    input_type : {'mx', 'qx', 'log_mx'}

    Examples
    --------
    ::

        # arr shape: (500, 80, 50)  — 500 scenarios, ages 20-99, years 2025-2074
        dlt = DynamicLifeTable.from_scenarios_array(
            arr, ages=range(20, 100), years=range(2025, 2075), birth_year=1985
        )
    """
    arr = np.asarray(arr, dtype=float)
    if arr.ndim != 3:
        raise ValueError(f"arr must be 3-D (n_samples, n_ages, n_years), got shape {arr.shape}")

    ages_arr = np.asarray(ages, dtype=int)
    years_arr = np.asarray(years, dtype=int)

    scenarios = [
        pd.DataFrame(arr[i], index=ages_arr, columns=years_arr)
        for i in range(arr.shape[0])
    ]
    return cls.from_scenarios(
        scenarios,
        birth_year=birth_year,
        period_year=period_year,
        input_type=input_type,
        fractional=fractional,
    )

LeeCarter

Lee-Carter mortality model.

Usage

::

lc = LeeCarter().fit(rates)   # rates: MortalityRates
forecast = lc.forecast(horizon=30, n_bootstrap=500, ci=0.95)
Source code in src/pylifecontingencies/dynamic/leecarter.py
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
class LeeCarter:
    """
    Lee-Carter mortality model.

    Usage
    -----
    ::

        lc = LeeCarter().fit(rates)   # rates: MortalityRates
        forecast = lc.forecast(horizon=30, n_bootstrap=500, ci=0.95)
    """

    def __init__(self, centre_kappa: bool = True) -> None:
        self.centre_kappa = centre_kappa
        self._fitted = False

    def fit(self, rates: MortalityRates) -> LeeCarter:
        """
        Fit the Lee-Carter model by SVD.

        Parameters
        ----------
        rates : MortalityRates
            Log mortality rates surface (ages × years).
        """
        log_mx = rates.log_mx  # shape (n_ages, n_years)
        ages = rates.ages
        years = rates.years

        # Handle NaN (open age groups, censored data) by mean-imputation per age
        col_valid = np.all(np.isfinite(log_mx), axis=0)
        if not np.all(col_valid):
            log_mx = log_mx[:, col_valid]
            years = years[col_valid]

        n_ages, n_years = log_mx.shape

        # α_x = row means
        ax = log_mx.mean(axis=1)

        # Centre the matrix
        centred = log_mx - ax[:, np.newaxis]

        # Rank-1 SVD
        U, s, Vt = np.linalg.svd(centred, full_matrices=False)
        bx_raw = U[:, 0]
        kt_raw = s[0] * Vt[0, :]

        # Normalise: sum(bx) = 1
        bx_sum = bx_raw.sum()
        if bx_sum == 0.0:
            raise ValueError("SVD produced zero bx — check input data")
        bx = bx_raw / bx_sum
        kt = kt_raw * bx_sum

        if self.centre_kappa:
            kt_mean = kt.mean()
            ax = ax + bx * kt_mean
            kt = kt - kt_mean

        self.ax = ax
        self.bx = bx
        self.kt = kt
        self.ages = ages
        self.years = years
        self._residuals = centred - np.outer(bx_raw, kt_raw / bx_sum * bx_sum)
        self._log_mx_fit = log_mx
        self._fitted = True
        return self

    def fitted_log_mx(self) -> np.ndarray:
        """Fitted log(m_{x,t}) = α_x + β_x κ_t."""
        if not self._fitted:
            raise RuntimeError("Model not fitted — call .fit() first")
        return self.ax[:, np.newaxis] + np.outer(self.bx, self.kt)

    def forecast(
        self,
        horizon: int = 30,
        arima_order: tuple[int, int, int] = (0, 1, 0),
        n_bootstrap: int = 0,
        ci: float = 0.95,
        seed: int | None = None,
    ) -> LeeCarterForecast:
        """
        Forecast kt forward using ARIMA and return a LeeCarterForecast.

        Parameters
        ----------
        horizon : int
            Number of years ahead.
        arima_order : (p, d, q)
            ARIMA order for kt. Default (0,1,0) = random walk with drift.
        n_bootstrap : int
            Number of bootstrap samples for prediction intervals. 0 = no PI.
        ci : float
            Confidence level for prediction intervals (e.g. 0.95).
        seed : int or None
            Random seed for bootstrap reproducibility.
        """
        if not self._fitted:
            raise RuntimeError("Model not fitted — call .fit() first")

        from statsmodels.tsa.arima.model import ARIMA

        model = ARIMA(self.kt, order=arima_order)
        result = model.fit()

        forecast_obj = result.forecast(steps=horizon)
        kt_central = np.asarray(forecast_obj)

        last_year = int(self.years[-1])
        years_forecast = np.arange(last_year + 1, last_year + horizon + 1)

        kt_lower: np.ndarray | None = None
        kt_upper: np.ndarray | None = None

        if n_bootstrap > 0:
            alpha = 1.0 - ci
            kt_lower, kt_upper = residual_bootstrap(
                kt=self.kt,
                kt_central=kt_central,
                residuals=self._residuals,
                n_bootstrap=n_bootstrap,
                horizon=horizon,
                arima_order=arima_order,
                ci=ci,
                seed=seed,
            )

        return LeeCarterForecast(
            ages=self.ages,
            years_calib=self.years,
            years_forecast=years_forecast,
            ax=self.ax,
            bx=self.bx,
            kt_calib=self.kt,
            kt_central=kt_central,
            kt_lower=kt_lower,
            kt_upper=kt_upper,
            ci=ci,
            n_bootstrap=n_bootstrap,
        )

    def __repr__(self) -> str:
        if not self._fitted:
            return "LeeCarter(not fitted)"
        return (
            f"LeeCarter(ages={self.ages[0]}–{self.ages[-1]}, "
            f"years={self.years[0]}–{self.years[-1]})"
        )

fit(rates)

Fit the Lee-Carter model by SVD.

Parameters

rates : MortalityRates Log mortality rates surface (ages × years).

Source code in src/pylifecontingencies/dynamic/leecarter.py
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
def fit(self, rates: MortalityRates) -> LeeCarter:
    """
    Fit the Lee-Carter model by SVD.

    Parameters
    ----------
    rates : MortalityRates
        Log mortality rates surface (ages × years).
    """
    log_mx = rates.log_mx  # shape (n_ages, n_years)
    ages = rates.ages
    years = rates.years

    # Handle NaN (open age groups, censored data) by mean-imputation per age
    col_valid = np.all(np.isfinite(log_mx), axis=0)
    if not np.all(col_valid):
        log_mx = log_mx[:, col_valid]
        years = years[col_valid]

    n_ages, n_years = log_mx.shape

    # α_x = row means
    ax = log_mx.mean(axis=1)

    # Centre the matrix
    centred = log_mx - ax[:, np.newaxis]

    # Rank-1 SVD
    U, s, Vt = np.linalg.svd(centred, full_matrices=False)
    bx_raw = U[:, 0]
    kt_raw = s[0] * Vt[0, :]

    # Normalise: sum(bx) = 1
    bx_sum = bx_raw.sum()
    if bx_sum == 0.0:
        raise ValueError("SVD produced zero bx — check input data")
    bx = bx_raw / bx_sum
    kt = kt_raw * bx_sum

    if self.centre_kappa:
        kt_mean = kt.mean()
        ax = ax + bx * kt_mean
        kt = kt - kt_mean

    self.ax = ax
    self.bx = bx
    self.kt = kt
    self.ages = ages
    self.years = years
    self._residuals = centred - np.outer(bx_raw, kt_raw / bx_sum * bx_sum)
    self._log_mx_fit = log_mx
    self._fitted = True
    return self

fitted_log_mx()

Fitted log(m_{x,t}) = α_x + β_x κ_t.

Source code in src/pylifecontingencies/dynamic/leecarter.py
151
152
153
154
155
def fitted_log_mx(self) -> np.ndarray:
    """Fitted log(m_{x,t}) = α_x + β_x κ_t."""
    if not self._fitted:
        raise RuntimeError("Model not fitted — call .fit() first")
    return self.ax[:, np.newaxis] + np.outer(self.bx, self.kt)

forecast(horizon=30, arima_order=(0, 1, 0), n_bootstrap=0, ci=0.95, seed=None)

Forecast kt forward using ARIMA and return a LeeCarterForecast.

Parameters

horizon : int Number of years ahead. arima_order : (p, d, q) ARIMA order for kt. Default (0,1,0) = random walk with drift. n_bootstrap : int Number of bootstrap samples for prediction intervals. 0 = no PI. ci : float Confidence level for prediction intervals (e.g. 0.95). seed : int or None Random seed for bootstrap reproducibility.

Source code in src/pylifecontingencies/dynamic/leecarter.py
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
def forecast(
    self,
    horizon: int = 30,
    arima_order: tuple[int, int, int] = (0, 1, 0),
    n_bootstrap: int = 0,
    ci: float = 0.95,
    seed: int | None = None,
) -> LeeCarterForecast:
    """
    Forecast kt forward using ARIMA and return a LeeCarterForecast.

    Parameters
    ----------
    horizon : int
        Number of years ahead.
    arima_order : (p, d, q)
        ARIMA order for kt. Default (0,1,0) = random walk with drift.
    n_bootstrap : int
        Number of bootstrap samples for prediction intervals. 0 = no PI.
    ci : float
        Confidence level for prediction intervals (e.g. 0.95).
    seed : int or None
        Random seed for bootstrap reproducibility.
    """
    if not self._fitted:
        raise RuntimeError("Model not fitted — call .fit() first")

    from statsmodels.tsa.arima.model import ARIMA

    model = ARIMA(self.kt, order=arima_order)
    result = model.fit()

    forecast_obj = result.forecast(steps=horizon)
    kt_central = np.asarray(forecast_obj)

    last_year = int(self.years[-1])
    years_forecast = np.arange(last_year + 1, last_year + horizon + 1)

    kt_lower: np.ndarray | None = None
    kt_upper: np.ndarray | None = None

    if n_bootstrap > 0:
        alpha = 1.0 - ci
        kt_lower, kt_upper = residual_bootstrap(
            kt=self.kt,
            kt_central=kt_central,
            residuals=self._residuals,
            n_bootstrap=n_bootstrap,
            horizon=horizon,
            arima_order=arima_order,
            ci=ci,
            seed=seed,
        )

    return LeeCarterForecast(
        ages=self.ages,
        years_calib=self.years,
        years_forecast=years_forecast,
        ax=self.ax,
        bx=self.bx,
        kt_calib=self.kt,
        kt_central=kt_central,
        kt_lower=kt_lower,
        kt_upper=kt_upper,
        ci=ci,
        n_bootstrap=n_bootstrap,
    )

LeeCarterForecast

Forecast object returned by LeeCarter.forecast().

Source code in src/pylifecontingencies/dynamic/leecarter.py
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
class LeeCarterForecast:
    """Forecast object returned by LeeCarter.forecast()."""

    def __init__(
        self,
        ages: np.ndarray,
        years_calib: np.ndarray,
        years_forecast: np.ndarray,
        ax: np.ndarray,
        bx: np.ndarray,
        kt_calib: np.ndarray,
        kt_central: np.ndarray,
        kt_lower: np.ndarray | None,
        kt_upper: np.ndarray | None,
        ci: float,
        n_bootstrap: int,
    ) -> None:
        self.ages = ages
        self.years_calib = years_calib
        self.years_forecast = years_forecast
        self.ax = ax
        self.bx = bx
        self.kt_calib = kt_calib
        self.kt_central = kt_central
        self.kt_lower = kt_lower
        self.kt_upper = kt_upper
        self.ci = ci
        self.n_bootstrap = n_bootstrap

    def log_mx(self, year: int) -> np.ndarray:
        """Predicted log(m_x) for a given forecast year."""
        if year in self.years_calib:
            t_idx = list(self.years_calib).index(year)
            kt = self.kt_calib[t_idx]
        else:
            t_idx = list(self.years_forecast).index(year)
            kt = self.kt_central[t_idx]
        return self.ax + self.bx * kt

    def mx(self, year: int) -> np.ndarray:
        return np.exp(self.log_mx(year))

    def qx(self, year: int) -> np.ndarray:
        """Approximate q_x from m_x via UDD: q_x = m_x / (1 + 0.5 m_x)."""
        mx_val = self.mx(year)
        return mx_val / (1.0 + 0.5 * mx_val)

    def to_dataframe(self) -> pd.DataFrame:
        """Return a long-format DataFrame (year, age, log_mx_central, log_mx_lower, log_mx_upper)."""
        rows = []
        all_years = np.concatenate([self.years_calib, self.years_forecast])
        for yr in all_years:
            log_mu = self.log_mx(yr)
            for i, age in enumerate(self.ages):
                row = {"year": yr, "age": age, "log_mx_central": log_mu[i]}
                rows.append(row)
        return pd.DataFrame(rows)

log_mx(year)

Predicted log(m_x) for a given forecast year.

Source code in src/pylifecontingencies/dynamic/leecarter.py
51
52
53
54
55
56
57
58
59
def log_mx(self, year: int) -> np.ndarray:
    """Predicted log(m_x) for a given forecast year."""
    if year in self.years_calib:
        t_idx = list(self.years_calib).index(year)
        kt = self.kt_calib[t_idx]
    else:
        t_idx = list(self.years_forecast).index(year)
        kt = self.kt_central[t_idx]
    return self.ax + self.bx * kt

qx(year)

Approximate q_x from m_x via UDD: q_x = m_x / (1 + 0.5 m_x).

Source code in src/pylifecontingencies/dynamic/leecarter.py
64
65
66
67
def qx(self, year: int) -> np.ndarray:
    """Approximate q_x from m_x via UDD: q_x = m_x / (1 + 0.5 m_x)."""
    mx_val = self.mx(year)
    return mx_val / (1.0 + 0.5 * mx_val)

to_dataframe()

Return a long-format DataFrame (year, age, log_mx_central, log_mx_lower, log_mx_upper).

Source code in src/pylifecontingencies/dynamic/leecarter.py
69
70
71
72
73
74
75
76
77
78
def to_dataframe(self) -> pd.DataFrame:
    """Return a long-format DataFrame (year, age, log_mx_central, log_mx_lower, log_mx_upper)."""
    rows = []
    all_years = np.concatenate([self.years_calib, self.years_forecast])
    for yr in all_years:
        log_mu = self.log_mx(yr)
        for i, age in enumerate(self.ages):
            row = {"year": yr, "age": age, "log_mx_central": log_mu[i]}
            rows.append(row)
    return pd.DataFrame(rows)

MortalityRates

Mortality rate surface: log(m_{x,t}) indexed by (age, year).

The underlying data is a DataFrame with ages as the index and calendar years as columns.

Parameters

data : pd.DataFrame log(m_{x,t}) with integer ages as index and integer years as columns. label : str Optional description (e.g. "USA Female 1950-2020").

Source code in src/pylifecontingencies/dynamic/rates.py
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
class MortalityRates:
    """
    Mortality rate surface: log(m_{x,t}) indexed by (age, year).

    The underlying data is a DataFrame with ages as the index and
    calendar years as columns.

    Parameters
    ----------
    data : pd.DataFrame
        log(m_{x,t}) with integer ages as index and integer years as columns.
    label : str
        Optional description (e.g. "USA Female 1950-2020").
    """

    def __init__(self, data: pd.DataFrame, label: str = "") -> None:
        if not isinstance(data.index, pd.Index) or not isinstance(data.columns, pd.Index):
            raise TypeError("data must be a DataFrame with age index and year columns")
        self.data = data.copy().astype(float)
        self.label = label

    # ------------------------------------------------------------------ #
    # Constructors                                                         #
    # ------------------------------------------------------------------ #

    @classmethod
    def from_dataframe(
        cls,
        df: pd.DataFrame,
        label: str = "",
    ) -> MortalityRates:
        """
        Construct from a DataFrame already shaped (ages × years) of log(mx).

        Index should be integer ages; columns should be integer years.
        """
        return cls(df, label=label)

    @classmethod
    def from_mx_dataframe(
        cls,
        df: pd.DataFrame,
        label: str = "",
    ) -> MortalityRates:
        """Construct from a (ages × years) DataFrame of raw m_x values (not log)."""
        log_df = np.log(df.replace(0, np.nan))
        return cls(log_df, label=label)

    @classmethod
    def from_qx_dataframe(
        cls,
        df: pd.DataFrame,
        label: str = "",
    ) -> MortalityRates:
        """Construct from a (ages × years) DataFrame of q_x values."""
        mx_df = df / (1.0 - 0.5 * df)
        return cls.from_mx_dataframe(mx_df, label=label)

    @classmethod
    def from_hmd_file(
        cls,
        path: str | Path,
        *,
        sex: str = "Female",
        label: str = "",
    ) -> MortalityRates:
        """
        Load from an HMD-format Mx (central death rates) flat text file.

        HMD files have columns: Year, Age, Female, Male, Total.
        Download from https://www.mortality.org (requires free account).
        """
        path = Path(path)
        df_raw = pd.read_csv(path, sep=r"\s+", skiprows=2, na_values=".")
        df_raw.columns = df_raw.columns.str.strip()
        df_raw["Age"] = (
            df_raw["Age"].astype(str).str.replace("+", "", regex=False).astype(int)
        )
        df_raw[sex] = pd.to_numeric(df_raw[sex], errors="coerce")
        pivot = df_raw.pivot(index="Age", columns="Year", values=sex).astype(float)
        log_mx = np.log(pivot.replace(0, np.nan))
        return cls(log_mx, label=label or f"HMD {sex}")

    # ------------------------------------------------------------------ #
    # Properties                                                           #
    # ------------------------------------------------------------------ #

    @property
    def ages(self) -> np.ndarray:
        return np.array(self.data.index, dtype=int)

    @property
    def years(self) -> np.ndarray:
        return np.array(self.data.columns, dtype=int)

    @property
    def log_mx(self) -> np.ndarray:
        """log(mx) matrix, shape (n_ages, n_years)."""
        return self.data.values

    @property
    def mx(self) -> np.ndarray:
        """Central death rates m_x, shape (n_ages, n_years)."""
        return np.exp(self.data.values)

    def subset(
        self,
        ages: list[int] | None = None,
        years: list[int] | None = None,
    ) -> MortalityRates:
        """Return a sub-surface restricted to the given ages and/or years."""
        df = self.data
        if ages is not None:
            df = df.loc[ages]
        if years is not None:
            df = df[years]
        return MortalityRates(df, label=self.label)

    # ------------------------------------------------------------------ #
    # Serialisation                                                        #
    # ------------------------------------------------------------------ #

    def to_dataframe(self) -> pd.DataFrame:
        """Return the underlying DataFrame (ages × years)."""
        return self.data.copy()

    def __repr__(self) -> str:
        return (
            f"MortalityRates(ages={self.ages[0]}–{self.ages[-1]}, "
            f"years={self.years[0]}–{self.years[-1]}, label={self.label!r})"
        )

log_mx property

log(mx) matrix, shape (n_ages, n_years).

mx property

Central death rates m_x, shape (n_ages, n_years).

from_dataframe(df, label='') classmethod

Construct from a DataFrame already shaped (ages × years) of log(mx).

Index should be integer ages; columns should be integer years.

Source code in src/pylifecontingencies/dynamic/rates.py
38
39
40
41
42
43
44
45
46
47
48
49
@classmethod
def from_dataframe(
    cls,
    df: pd.DataFrame,
    label: str = "",
) -> MortalityRates:
    """
    Construct from a DataFrame already shaped (ages × years) of log(mx).

    Index should be integer ages; columns should be integer years.
    """
    return cls(df, label=label)

from_hmd_file(path, *, sex='Female', label='') classmethod

Load from an HMD-format Mx (central death rates) flat text file.

HMD files have columns: Year, Age, Female, Male, Total. Download from https://www.mortality.org (requires free account).

Source code in src/pylifecontingencies/dynamic/rates.py
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
@classmethod
def from_hmd_file(
    cls,
    path: str | Path,
    *,
    sex: str = "Female",
    label: str = "",
) -> MortalityRates:
    """
    Load from an HMD-format Mx (central death rates) flat text file.

    HMD files have columns: Year, Age, Female, Male, Total.
    Download from https://www.mortality.org (requires free account).
    """
    path = Path(path)
    df_raw = pd.read_csv(path, sep=r"\s+", skiprows=2, na_values=".")
    df_raw.columns = df_raw.columns.str.strip()
    df_raw["Age"] = (
        df_raw["Age"].astype(str).str.replace("+", "", regex=False).astype(int)
    )
    df_raw[sex] = pd.to_numeric(df_raw[sex], errors="coerce")
    pivot = df_raw.pivot(index="Age", columns="Year", values=sex).astype(float)
    log_mx = np.log(pivot.replace(0, np.nan))
    return cls(log_mx, label=label or f"HMD {sex}")

from_mx_dataframe(df, label='') classmethod

Construct from a (ages × years) DataFrame of raw m_x values (not log).

Source code in src/pylifecontingencies/dynamic/rates.py
51
52
53
54
55
56
57
58
59
@classmethod
def from_mx_dataframe(
    cls,
    df: pd.DataFrame,
    label: str = "",
) -> MortalityRates:
    """Construct from a (ages × years) DataFrame of raw m_x values (not log)."""
    log_df = np.log(df.replace(0, np.nan))
    return cls(log_df, label=label)

from_qx_dataframe(df, label='') classmethod

Construct from a (ages × years) DataFrame of q_x values.

Source code in src/pylifecontingencies/dynamic/rates.py
61
62
63
64
65
66
67
68
69
@classmethod
def from_qx_dataframe(
    cls,
    df: pd.DataFrame,
    label: str = "",
) -> MortalityRates:
    """Construct from a (ages × years) DataFrame of q_x values."""
    mx_df = df / (1.0 - 0.5 * df)
    return cls.from_mx_dataframe(mx_df, label=label)

subset(ages=None, years=None)

Return a sub-surface restricted to the given ages and/or years.

Source code in src/pylifecontingencies/dynamic/rates.py
118
119
120
121
122
123
124
125
126
127
128
129
def subset(
    self,
    ages: list[int] | None = None,
    years: list[int] | None = None,
) -> MortalityRates:
    """Return a sub-surface restricted to the given ages and/or years."""
    df = self.data
    if ages is not None:
        df = df.loc[ages]
    if years is not None:
        df = df[years]
    return MortalityRates(df, label=self.label)

to_dataframe()

Return the underlying DataFrame (ages × years).

Source code in src/pylifecontingencies/dynamic/rates.py
135
136
137
def to_dataframe(self) -> pd.DataFrame:
    """Return the underlying DataFrame (ages × years)."""
    return self.data.copy()

ProjectedLifeTable

Model-agnostic life table built from any mortality-rate forecast.

Stores one or more LifeTable objects internally: - Single-path: one table (central forecast). - With prediction intervals: three tables (lower, central, upper). - Stochastic: N tables (one per scenario).

Parameters

forecast : object with .qx(year), .ages, .years_calib, .years_forecast A model forecast object (LeeCarterForecast, CBDForecast, or compatible). For raw DataFrame input, use the from_mx / from_qx class methods instead. birth_year : int or None Birth year for cohort extraction. period_year : int or None Calendar year for period extraction. ages : list[int] or None Ages to include. Defaults to all available ages. fractional : FractionalAge Fractional-age assumption for the resulting LifeTable(s). extrapolation : str "clamp", "constant_slope", or "none".

Source code in src/pylifecontingencies/dynamic/projected_table.py
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
class ProjectedLifeTable:
    """
    Model-agnostic life table built from any mortality-rate forecast.

    Stores one or more ``LifeTable`` objects internally:
    - **Single-path**: one table (central forecast).
    - **With prediction intervals**: three tables (lower, central, upper).
    - **Stochastic**: N tables (one per scenario).

    Parameters
    ----------
    forecast : object with ``.qx(year)``, ``.ages``, ``.years_calib``, ``.years_forecast``
        A model forecast object (LeeCarterForecast, CBDForecast, or compatible).
        For raw DataFrame input, use the ``from_mx`` / ``from_qx`` class methods instead.
    birth_year : int or None
        Birth year for cohort extraction.
    period_year : int or None
        Calendar year for period extraction.
    ages : list[int] or None
        Ages to include. Defaults to all available ages.
    fractional : FractionalAge
        Fractional-age assumption for the resulting LifeTable(s).
    extrapolation : str
        ``"clamp"``, ``"constant_slope"``, or ``"none"``.
    """

    def __init__(
        self,
        forecast=None,
        *,
        birth_year: int | None = None,
        period_year: int | None = None,
        ages: list[int] | None = None,
        fractional: FractionalAge = FractionalAge.UDD,
        extrapolation: ExtrapolationMode = "clamp",
        # Internal — used by class methods:
        _tables: list[LifeTable] | None = None,
        _is_stochastic: bool = False,
        _has_pi: bool = False,
    ) -> None:
        if _tables is not None:
            # Internal construction from class methods
            self._tables = _tables
            self._is_stochastic = _is_stochastic
            self._has_pi = _has_pi
            self.birth_year = birth_year
            self.period_year = period_year
            self.fractional = fractional
            self.extrapolation = extrapolation
            return

        # Public construction from a forecast object (backward compat)
        if forecast is None:
            raise TypeError(
                "Provide a forecast object, or use a class method "
                "(from_mx, from_qx, from_scenarios, etc.)"
            )
        if (birth_year is None) == (period_year is None):
            raise ValueError("Provide exactly one of birth_year or period_year")

        self.birth_year = birth_year
        self.period_year = period_year
        self.fractional = fractional
        self.extrapolation = extrapolation
        self._has_pi = False
        self._is_stochastic = False

        # Wrap the forecast object in a _ForecastAdapter
        adapter = _ForecastAdapter(forecast)
        f_ages = np.asarray(ages, dtype=int) if ages is not None else forecast.ages
        lt = self._build_lifetable(adapter, f_ages)
        self._tables = [lt]

    # ================================================================== #
    # Class methods: raw DataFrame input                                   #
    # ================================================================== #

    @classmethod
    def from_mx(
        cls,
        df_mx: pd.DataFrame,
        *,
        lower: pd.DataFrame | None = None,
        upper: pd.DataFrame | None = None,
        birth_year: int | None = None,
        period_year: int | None = None,
        ages: list[int] | None = None,
        fractional: FractionalAge = FractionalAge.UDD,
        extrapolation: ExtrapolationMode = "clamp",
    ) -> ProjectedLifeTable:
        """
        Build from a DataFrame of central death rates m_{x,t}.

        Parameters
        ----------
        df_mx : pd.DataFrame
            Ages as index (int), calendar years as columns (int),
            values are central death rates m_{x,t}.
        lower : pd.DataFrame or None
            Lower prediction interval (same shape as df_mx).
        upper : pd.DataFrame or None
            Upper prediction interval (same shape as df_mx).
        birth_year, period_year, ages, fractional, extrapolation :
            See class docstring.

        Examples
        --------
        ::

            # Central only
            plt = ProjectedLifeTable.from_mx(df_mx, birth_year=1985)

            # With 95% prediction intervals
            plt = ProjectedLifeTable.from_mx(
                df_central, lower=df_lo, upper=df_hi, birth_year=1985
            )
        """
        return cls._from_df(
            df_mx, input_type="mx", lower=lower, upper=upper,
            birth_year=birth_year, period_year=period_year,
            ages=ages, fractional=fractional, extrapolation=extrapolation,
        )

    @classmethod
    def from_qx(
        cls,
        df_qx: pd.DataFrame,
        *,
        lower: pd.DataFrame | None = None,
        upper: pd.DataFrame | None = None,
        birth_year: int | None = None,
        period_year: int | None = None,
        ages: list[int] | None = None,
        fractional: FractionalAge = FractionalAge.UDD,
        extrapolation: ExtrapolationMode = "clamp",
    ) -> ProjectedLifeTable:
        """
        Build from a DataFrame of mortality rates q_{x,t}.

        Parameters
        ----------
        df_qx : pd.DataFrame
            Ages as index (int), calendar years as columns (int),
            values are annual mortality rates q_{x,t}.
        lower, upper : pd.DataFrame or None
            Prediction interval bounds.
        """
        return cls._from_df(
            df_qx, input_type="qx", lower=lower, upper=upper,
            birth_year=birth_year, period_year=period_year,
            ages=ages, fractional=fractional, extrapolation=extrapolation,
        )

    @classmethod
    def from_log_mx(
        cls,
        df_log_mx: pd.DataFrame,
        *,
        lower: pd.DataFrame | None = None,
        upper: pd.DataFrame | None = None,
        birth_year: int | None = None,
        period_year: int | None = None,
        ages: list[int] | None = None,
        fractional: FractionalAge = FractionalAge.UDD,
        extrapolation: ExtrapolationMode = "clamp",
    ) -> ProjectedLifeTable:
        """
        Build from a DataFrame of log(m_{x,t}).

        The natural output of Lee-Carter and similar log-linear models.
        """
        return cls._from_df(
            df_log_mx, input_type="log_mx", lower=lower, upper=upper,
            birth_year=birth_year, period_year=period_year,
            ages=ages, fractional=fractional, extrapolation=extrapolation,
        )

    @classmethod
    def from_scenarios(
        cls,
        scenarios: Sequence[pd.DataFrame],
        *,
        birth_year: int | None = None,
        period_year: int | None = None,
        input_type: str = "mx",
        ages: list[int] | None = None,
        fractional: FractionalAge = FractionalAge.UDD,
        extrapolation: ExtrapolationMode = "clamp",
    ) -> ProjectedLifeTable:
        """
        Build from multiple forecast paths (stochastic analysis).

        Parameters
        ----------
        scenarios : sequence of pd.DataFrame
            Each DataFrame is an (ages × years) forecast surface.
        input_type : {'mx', 'qx', 'log_mx'}
            What the DataFrame values represent.

        Examples
        --------
        ::

            # 500 bootstrap paths
            plt = ProjectedLifeTable.from_scenarios(
                list_of_dfs, birth_year=1985, input_type="mx"
            )
            dat = DynamicActuarialTable(plt, i=0.03)
            result = dat.axn(x=40)   # StochasticResult
        """
        if (birth_year is None) == (period_year is None):
            raise ValueError("Provide exactly one of birth_year or period_year")
        if not scenarios:
            raise ValueError("scenarios must be a non-empty sequence")

        tables = []
        for i, df in enumerate(scenarios):
            adapter = _DataFrameAdapter(df, input_type=input_type)
            f_ages = (
                np.asarray(ages, dtype=int) if ages is not None
                else np.array(df.index, dtype=int)
            )
            instance = cls.__new__(cls)
            instance.birth_year = birth_year
            instance.period_year = period_year
            instance.fractional = fractional
            instance.extrapolation = extrapolation
            lt = instance._build_lifetable(adapter, f_ages, name=f"scenario_{i}")
            tables.append(lt)

        return cls(
            birth_year=birth_year, period_year=period_year,
            fractional=fractional, extrapolation=extrapolation,
            _tables=tables, _is_stochastic=True, _has_pi=False,
        )

    @classmethod
    def from_scenarios_array(
        cls,
        arr: np.ndarray,
        *,
        ages: np.ndarray | list[int],
        years: np.ndarray | list[int],
        birth_year: int | None = None,
        period_year: int | None = None,
        input_type: str = "mx",
        fractional: FractionalAge = FractionalAge.UDD,
        extrapolation: ExtrapolationMode = "clamp",
    ) -> ProjectedLifeTable:
        """
        Build from a 3-D numpy array (n_samples × n_ages × n_years).

        Parameters
        ----------
        arr : np.ndarray, shape (n_samples, n_ages, n_years)
        ages : array-like of int
        years : array-like of int
        """
        arr = np.asarray(arr, dtype=float)
        if arr.ndim != 3:
            raise ValueError(
                f"arr must be 3-D (n_samples, n_ages, n_years), got shape {arr.shape}"
            )
        ages_arr = np.asarray(ages, dtype=int)
        years_arr = np.asarray(years, dtype=int)

        scenarios = [
            pd.DataFrame(arr[i], index=ages_arr, columns=years_arr)
            for i in range(arr.shape[0])
        ]
        return cls.from_scenarios(
            scenarios,
            birth_year=birth_year,
            period_year=period_year,
            input_type=input_type,
            ages=list(ages_arr),
            fractional=fractional,
            extrapolation=extrapolation,
        )

    # ================================================================== #
    # Internal: build from DataFrames with optional PI                     #
    # ================================================================== #

    @classmethod
    def _from_df(
        cls,
        df: pd.DataFrame,
        *,
        input_type: str,
        lower: pd.DataFrame | None,
        upper: pd.DataFrame | None,
        birth_year: int | None,
        period_year: int | None,
        ages: list[int] | None,
        fractional: FractionalAge,
        extrapolation: ExtrapolationMode,
    ) -> ProjectedLifeTable:
        """Shared implementation for from_mx / from_qx / from_log_mx."""
        if (birth_year is None) == (period_year is None):
            raise ValueError("Provide exactly one of birth_year or period_year")

        has_pi = (lower is not None) and (upper is not None)
        if (lower is None) != (upper is None):
            raise ValueError("Provide both lower and upper, or neither")

        dfs = [df] if not has_pi else [lower, df, upper]
        labels = ["central"] if not has_pi else ["lower", "central", "upper"]

        tables = []
        for sub_df, label in zip(dfs, labels):
            adapter = _DataFrameAdapter(sub_df, input_type=input_type)
            f_ages = (
                np.asarray(ages, dtype=int) if ages is not None
                else np.array(sub_df.index, dtype=int)
            )
            instance = cls.__new__(cls)
            instance.birth_year = birth_year
            instance.period_year = period_year
            instance.fractional = fractional
            instance.extrapolation = extrapolation
            lt = instance._build_lifetable(adapter, f_ages, name=label)
            tables.append(lt)

        return cls(
            birth_year=birth_year, period_year=period_year,
            fractional=fractional, extrapolation=extrapolation,
            _tables=tables, _is_stochastic=has_pi, _has_pi=has_pi,
        )

    # ================================================================== #
    # Properties                                                           #
    # ================================================================== #

    @property
    def tables(self) -> list[LifeTable]:
        """All underlying LifeTable objects."""
        return self._tables

    @property
    def n_scenarios(self) -> int:
        """Number of scenarios / tables stored."""
        return len(self._tables)

    @property
    def is_stochastic(self) -> bool:
        """True when multiple tables are stored (PI or scenarios)."""
        return self._is_stochastic

    @property
    def has_prediction_interval(self) -> bool:
        """True when lower/central/upper prediction interval tables are stored."""
        return self._has_pi

    @property
    def lifetable(self) -> LifeTable:
        """
        The central (or only) LifeTable.

        For single-path: the sole table.
        For PI: the central table (index 1 of [lower, central, upper]).
        For scenarios: raises ValueError (use ``.tables`` instead).
        """
        if self._has_pi:
            return self._tables[1]
        if self._is_stochastic and not self._has_pi:
            raise ValueError(
                "This ProjectedLifeTable has multiple scenarios. "
                "Use .tables[i] or pass to DynamicActuarialTable."
            )
        return self._tables[0]

    @property
    def lower(self) -> LifeTable | None:
        """Lower prediction interval LifeTable, or None."""
        return self._tables[0] if self._has_pi else None

    @property
    def upper(self) -> LifeTable | None:
        """Upper prediction interval LifeTable, or None."""
        return self._tables[2] if self._has_pi else None

    # ================================================================== #
    # Conversion                                                           #
    # ================================================================== #

    def to_life_table(self, name: str = "") -> LifeTable:
        """
        Return the central LifeTable (backward compatibility).

        Identical to ``.lifetable`` for single-path and PI tables.
        """
        lt = self.lifetable
        if name:
            lt.name = name
        return lt

    # ================================================================== #
    # Core: build a LifeTable from a forecast adapter                      #
    # ================================================================== #

    def _build_lifetable(
        self,
        adapter,
        ages: np.ndarray,
        name: str = "",
    ) -> LifeTable:
        """Build a single LifeTable from a forecast-like adapter."""
        all_years = np.concatenate([adapter.years_calib, adapter.years_forecast])
        year_min = int(all_years.min())
        year_max = int(all_years.max())

        qx_values = []
        for age in ages:
            if self.birth_year is not None:
                target_year = self.birth_year + age
            else:
                target_year = self.period_year

            if target_year < year_min or target_year > year_max:
                qx_val = self._extrapolate_qx(
                    adapter, ages, age, target_year, year_min, year_max
                )
            else:
                qx_val = _lookup_qx(adapter, age, target_year)

            qx_values.append(np.clip(qx_val, 0.0, 1.0))

        qx_arr = np.asarray(qx_values)
        if qx_arr[-1] < 1.0:
            qx_arr[-1] = 1.0

        x_min = int(ages[0])
        label = name or (
            f"cohort_{self.birth_year}" if self.birth_year else f"period_{self.period_year}"
        )
        return LifeTable.from_qx(
            qx_arr, x_min=x_min, name=label, fractional=self.fractional
        )

    def _extrapolate_qx(
        self, adapter, ages, age, target_year, year_min, year_max
    ) -> float:
        """Handle out-of-range years according to self.extrapolation."""
        if self.extrapolation == "none":
            raise ValueError(
                f"Age {age} maps to year {target_year} which is outside the "
                f"forecast range [{year_min}, {year_max}]. "
                "Set extrapolation='clamp' or 'constant_slope'."
            )

        if self.extrapolation == "clamp":
            clamped = int(np.clip(target_year, year_min, year_max))
            return _lookup_qx(adapter, age, clamped)

        if self.extrapolation == "constant_slope":
            return _extrapolate_constant_slope(
                adapter, age, target_year, year_min, year_max
            )

        raise ValueError(
            f"extrapolation must be 'clamp', 'constant_slope', or 'none', "
            f"got {self.extrapolation!r}"
        )

    def __repr__(self) -> str:
        lt = self._tables[0]
        mode = f"birth={self.birth_year}" if self.birth_year else f"period={self.period_year}"
        if self._has_pi:
            tag = "PI: lower/central/upper"
        elif self._is_stochastic:
            tag = f"stochastic, n={self.n_scenarios}"
        else:
            tag = "single-path"
        return f"ProjectedLifeTable({mode}, {tag}, ages={lt.x_min}–{lt.omega - 1})"

has_prediction_interval property

True when lower/central/upper prediction interval tables are stored.

is_stochastic property

True when multiple tables are stored (PI or scenarios).

lifetable property

The central (or only) LifeTable.

For single-path: the sole table. For PI: the central table (index 1 of [lower, central, upper]). For scenarios: raises ValueError (use .tables instead).

lower property

Lower prediction interval LifeTable, or None.

n_scenarios property

Number of scenarios / tables stored.

tables property

All underlying LifeTable objects.

upper property

Upper prediction interval LifeTable, or None.

from_log_mx(df_log_mx, *, lower=None, upper=None, birth_year=None, period_year=None, ages=None, fractional=FractionalAge.UDD, extrapolation='clamp') classmethod

Build from a DataFrame of log(m_{x,t}).

The natural output of Lee-Carter and similar log-linear models.

Source code in src/pylifecontingencies/dynamic/projected_table.py
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
@classmethod
def from_log_mx(
    cls,
    df_log_mx: pd.DataFrame,
    *,
    lower: pd.DataFrame | None = None,
    upper: pd.DataFrame | None = None,
    birth_year: int | None = None,
    period_year: int | None = None,
    ages: list[int] | None = None,
    fractional: FractionalAge = FractionalAge.UDD,
    extrapolation: ExtrapolationMode = "clamp",
) -> ProjectedLifeTable:
    """
    Build from a DataFrame of log(m_{x,t}).

    The natural output of Lee-Carter and similar log-linear models.
    """
    return cls._from_df(
        df_log_mx, input_type="log_mx", lower=lower, upper=upper,
        birth_year=birth_year, period_year=period_year,
        ages=ages, fractional=fractional, extrapolation=extrapolation,
    )

from_mx(df_mx, *, lower=None, upper=None, birth_year=None, period_year=None, ages=None, fractional=FractionalAge.UDD, extrapolation='clamp') classmethod

Build from a DataFrame of central death rates m_{x,t}.

Parameters

df_mx : pd.DataFrame Ages as index (int), calendar years as columns (int), values are central death rates m_{x,t}. lower : pd.DataFrame or None Lower prediction interval (same shape as df_mx). upper : pd.DataFrame or None Upper prediction interval (same shape as df_mx). birth_year, period_year, ages, fractional, extrapolation : See class docstring.

Examples

::

# Central only
plt = ProjectedLifeTable.from_mx(df_mx, birth_year=1985)

# With 95% prediction intervals
plt = ProjectedLifeTable.from_mx(
    df_central, lower=df_lo, upper=df_hi, birth_year=1985
)
Source code in src/pylifecontingencies/dynamic/projected_table.py
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
@classmethod
def from_mx(
    cls,
    df_mx: pd.DataFrame,
    *,
    lower: pd.DataFrame | None = None,
    upper: pd.DataFrame | None = None,
    birth_year: int | None = None,
    period_year: int | None = None,
    ages: list[int] | None = None,
    fractional: FractionalAge = FractionalAge.UDD,
    extrapolation: ExtrapolationMode = "clamp",
) -> ProjectedLifeTable:
    """
    Build from a DataFrame of central death rates m_{x,t}.

    Parameters
    ----------
    df_mx : pd.DataFrame
        Ages as index (int), calendar years as columns (int),
        values are central death rates m_{x,t}.
    lower : pd.DataFrame or None
        Lower prediction interval (same shape as df_mx).
    upper : pd.DataFrame or None
        Upper prediction interval (same shape as df_mx).
    birth_year, period_year, ages, fractional, extrapolation :
        See class docstring.

    Examples
    --------
    ::

        # Central only
        plt = ProjectedLifeTable.from_mx(df_mx, birth_year=1985)

        # With 95% prediction intervals
        plt = ProjectedLifeTable.from_mx(
            df_central, lower=df_lo, upper=df_hi, birth_year=1985
        )
    """
    return cls._from_df(
        df_mx, input_type="mx", lower=lower, upper=upper,
        birth_year=birth_year, period_year=period_year,
        ages=ages, fractional=fractional, extrapolation=extrapolation,
    )

from_qx(df_qx, *, lower=None, upper=None, birth_year=None, period_year=None, ages=None, fractional=FractionalAge.UDD, extrapolation='clamp') classmethod

Build from a DataFrame of mortality rates q_{x,t}.

Parameters

df_qx : pd.DataFrame Ages as index (int), calendar years as columns (int), values are annual mortality rates q_{x,t}. lower, upper : pd.DataFrame or None Prediction interval bounds.

Source code in src/pylifecontingencies/dynamic/projected_table.py
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
@classmethod
def from_qx(
    cls,
    df_qx: pd.DataFrame,
    *,
    lower: pd.DataFrame | None = None,
    upper: pd.DataFrame | None = None,
    birth_year: int | None = None,
    period_year: int | None = None,
    ages: list[int] | None = None,
    fractional: FractionalAge = FractionalAge.UDD,
    extrapolation: ExtrapolationMode = "clamp",
) -> ProjectedLifeTable:
    """
    Build from a DataFrame of mortality rates q_{x,t}.

    Parameters
    ----------
    df_qx : pd.DataFrame
        Ages as index (int), calendar years as columns (int),
        values are annual mortality rates q_{x,t}.
    lower, upper : pd.DataFrame or None
        Prediction interval bounds.
    """
    return cls._from_df(
        df_qx, input_type="qx", lower=lower, upper=upper,
        birth_year=birth_year, period_year=period_year,
        ages=ages, fractional=fractional, extrapolation=extrapolation,
    )

from_scenarios(scenarios, *, birth_year=None, period_year=None, input_type='mx', ages=None, fractional=FractionalAge.UDD, extrapolation='clamp') classmethod

Build from multiple forecast paths (stochastic analysis).

Parameters

scenarios : sequence of pd.DataFrame Each DataFrame is an (ages × years) forecast surface. input_type : {'mx', 'qx', 'log_mx'} What the DataFrame values represent.

Examples

::

# 500 bootstrap paths
plt = ProjectedLifeTable.from_scenarios(
    list_of_dfs, birth_year=1985, input_type="mx"
)
dat = DynamicActuarialTable(plt, i=0.03)
result = dat.axn(x=40)   # StochasticResult
Source code in src/pylifecontingencies/dynamic/projected_table.py
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
@classmethod
def from_scenarios(
    cls,
    scenarios: Sequence[pd.DataFrame],
    *,
    birth_year: int | None = None,
    period_year: int | None = None,
    input_type: str = "mx",
    ages: list[int] | None = None,
    fractional: FractionalAge = FractionalAge.UDD,
    extrapolation: ExtrapolationMode = "clamp",
) -> ProjectedLifeTable:
    """
    Build from multiple forecast paths (stochastic analysis).

    Parameters
    ----------
    scenarios : sequence of pd.DataFrame
        Each DataFrame is an (ages × years) forecast surface.
    input_type : {'mx', 'qx', 'log_mx'}
        What the DataFrame values represent.

    Examples
    --------
    ::

        # 500 bootstrap paths
        plt = ProjectedLifeTable.from_scenarios(
            list_of_dfs, birth_year=1985, input_type="mx"
        )
        dat = DynamicActuarialTable(plt, i=0.03)
        result = dat.axn(x=40)   # StochasticResult
    """
    if (birth_year is None) == (period_year is None):
        raise ValueError("Provide exactly one of birth_year or period_year")
    if not scenarios:
        raise ValueError("scenarios must be a non-empty sequence")

    tables = []
    for i, df in enumerate(scenarios):
        adapter = _DataFrameAdapter(df, input_type=input_type)
        f_ages = (
            np.asarray(ages, dtype=int) if ages is not None
            else np.array(df.index, dtype=int)
        )
        instance = cls.__new__(cls)
        instance.birth_year = birth_year
        instance.period_year = period_year
        instance.fractional = fractional
        instance.extrapolation = extrapolation
        lt = instance._build_lifetable(adapter, f_ages, name=f"scenario_{i}")
        tables.append(lt)

    return cls(
        birth_year=birth_year, period_year=period_year,
        fractional=fractional, extrapolation=extrapolation,
        _tables=tables, _is_stochastic=True, _has_pi=False,
    )

from_scenarios_array(arr, *, ages, years, birth_year=None, period_year=None, input_type='mx', fractional=FractionalAge.UDD, extrapolation='clamp') classmethod

Build from a 3-D numpy array (n_samples × n_ages × n_years).

Parameters

arr : np.ndarray, shape (n_samples, n_ages, n_years) ages : array-like of int years : array-like of int

Source code in src/pylifecontingencies/dynamic/projected_table.py
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
@classmethod
def from_scenarios_array(
    cls,
    arr: np.ndarray,
    *,
    ages: np.ndarray | list[int],
    years: np.ndarray | list[int],
    birth_year: int | None = None,
    period_year: int | None = None,
    input_type: str = "mx",
    fractional: FractionalAge = FractionalAge.UDD,
    extrapolation: ExtrapolationMode = "clamp",
) -> ProjectedLifeTable:
    """
    Build from a 3-D numpy array (n_samples × n_ages × n_years).

    Parameters
    ----------
    arr : np.ndarray, shape (n_samples, n_ages, n_years)
    ages : array-like of int
    years : array-like of int
    """
    arr = np.asarray(arr, dtype=float)
    if arr.ndim != 3:
        raise ValueError(
            f"arr must be 3-D (n_samples, n_ages, n_years), got shape {arr.shape}"
        )
    ages_arr = np.asarray(ages, dtype=int)
    years_arr = np.asarray(years, dtype=int)

    scenarios = [
        pd.DataFrame(arr[i], index=ages_arr, columns=years_arr)
        for i in range(arr.shape[0])
    ]
    return cls.from_scenarios(
        scenarios,
        birth_year=birth_year,
        period_year=period_year,
        input_type=input_type,
        ages=list(ages_arr),
        fractional=fractional,
        extrapolation=extrapolation,
    )

to_life_table(name='')

Return the central LifeTable (backward compatibility).

Identical to .lifetable for single-path and PI tables.

Source code in src/pylifecontingencies/dynamic/projected_table.py
458
459
460
461
462
463
464
465
466
467
def to_life_table(self, name: str = "") -> LifeTable:
    """
    Return the central LifeTable (backward compatibility).

    Identical to ``.lifetable`` for single-path and PI tables.
    """
    lt = self.lifetable
    if name:
        lt.name = name
    return lt

StochasticResult dataclass

Distribution of a scalar actuarial quantity across N scenarios.

Returned by DynamicActuarialTable methods when the table was built from multiple forecast paths.

Attributes

samples : np.ndarray 1-D array of length N (one value per scenario). label : str Optional label (e.g. "axn(x=40, n=25)").

Source code in src/pylifecontingencies/dynamic/stochastic.py
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
@dataclass
class StochasticResult:
    """
    Distribution of a scalar actuarial quantity across N scenarios.

    Returned by DynamicActuarialTable methods when the table was built
    from multiple forecast paths.

    Attributes
    ----------
    samples : np.ndarray
        1-D array of length N (one value per scenario).
    label : str
        Optional label (e.g. ``"axn(x=40, n=25)"``).
    """

    samples: np.ndarray
    label: str = ""

    def __post_init__(self) -> None:
        self.samples = np.asarray(self.samples, dtype=float)
        if self.samples.ndim != 1:
            raise ValueError("samples must be a 1-D array")

    # ------------------------------------------------------------------ #
    # Summary statistics                                                   #
    # ------------------------------------------------------------------ #

    @property
    def n(self) -> int:
        """Number of scenarios."""
        return len(self.samples)

    @property
    def mean(self) -> float:
        return float(np.mean(self.samples))

    @property
    def std(self) -> float:
        return float(np.std(self.samples, ddof=1) if self.n > 1 else 0.0)

    @property
    def median(self) -> float:
        return float(np.median(self.samples))

    @property
    def min(self) -> float:
        return float(np.min(self.samples))

    @property
    def max(self) -> float:
        return float(np.max(self.samples))

    def quantile(self, q: float) -> float:
        """Return the q-th quantile (0 ≤ q ≤ 1)."""
        return float(np.quantile(self.samples, q))

    def ci(self, level: float = 0.95) -> tuple[float, float]:
        """Symmetric (1-level)/2 credible interval: (lower, upper)."""
        alpha = (1.0 - level) / 2.0
        return self.quantile(alpha), self.quantile(1.0 - alpha)

    def summary(self) -> dict[str, float]:
        """Return a dict with key percentiles — useful for quick inspection."""
        return {
            "mean":   self.mean,
            "std":    self.std,
            "median": self.median,
            "p05":    self.quantile(0.05),
            "p25":    self.quantile(0.25),
            "p75":    self.quantile(0.75),
            "p95":    self.quantile(0.95),
            "min":    self.min,
            "max":    self.max,
            "n":      float(self.n),
        }

    def var(self, alpha: float) -> float:
        """
        Value at Risk at confidence level ``alpha``.

        Equal to the ``alpha``-quantile of the PV distribution.
        """
        return self.quantile(alpha)

    def tvar(self, alpha: float) -> float:
        """
        Tail Value at Risk (Expected Shortfall) at confidence level ``alpha``.

        ``TVaR_α = E[X | X > VaR_α]``

        Returns ``var(alpha)`` when no sample exceeds it (degenerate tail).
        """
        v = self.var(alpha)
        tail = self.samples[self.samples > v]
        return float(np.mean(tail)) if len(tail) > 0 else v

    def to_dataframe(self) -> "pd.DataFrame":
        """Return samples as a one-column ``pandas.DataFrame`` with column ``'pv'``."""
        import pandas as pd
        return pd.DataFrame({"pv": self.samples})

    # ------------------------------------------------------------------ #
    # Visualisation                                                        #
    # ------------------------------------------------------------------ #

    def hist(
        self,
        bins: int = 50,
        ax: "Axes | None" = None,
        ci: bool = True,
        **kwargs,
    ) -> "Axes":
        """
        Histogram of the PV distribution.

        Parameters
        ----------
        bins : int
            Number of histogram bins (default 50).
        ax : matplotlib Axes or None
            Axes to draw on; a new figure is created when ``None``.
        ci : bool
            If True, draw vertical lines for the mean and 95 % CI.
        **kwargs
            Forwarded to ``ax.hist()``.

        Returns
        -------
        matplotlib.axes.Axes
        """
        import matplotlib.pyplot as plt

        if ax is None:
            _, ax = plt.subplots()

        kwargs.setdefault("edgecolor", "white")
        ax.hist(self.samples, bins=bins, **kwargs)

        if ci:
            lo, hi = self.ci(0.95)
            ax.axvline(self.mean, color="crimson", linestyle="--",
                       linewidth=1.5, label=f"mean = {self.mean:.4f}")
            ax.axvline(lo, color="steelblue", linestyle=":",
                       linewidth=1.2, label=f"p5 = {lo:.4f}")
            ax.axvline(hi, color="steelblue", linestyle=":",
                       linewidth=1.2, label=f"p95 = {hi:.4f}")
            ax.legend(fontsize=8)

        ax.set_title(self.label or "PV Distribution")
        ax.set_xlabel("Present Value")
        ax.set_ylabel("Frequency")
        return ax

    def plot(
        self,
        ax: "Axes | None" = None,
        **kwargs,
    ) -> "Axes":
        """
        Empirical CDF of the PV distribution.

        Draws the step-wise ECDF and a dashed vertical line at the mean.

        Parameters
        ----------
        ax : matplotlib Axes or None
            Axes to draw on; a new figure is created when ``None``.
        **kwargs
            Forwarded to ``ax.plot()``.

        Returns
        -------
        matplotlib.axes.Axes
        """
        import matplotlib.pyplot as plt

        if ax is None:
            _, ax = plt.subplots()

        sorted_s = np.sort(self.samples)
        cdf = np.arange(1, self.n + 1) / self.n

        kwargs.setdefault("drawstyle", "steps-post")
        ax.plot(sorted_s, cdf, **kwargs)
        ax.axvline(self.mean, color="crimson", linestyle="--",
                   linewidth=1.5, label=f"mean = {self.mean:.4f}")
        ax.legend(fontsize=8)
        ax.set_title(self.label or "Empirical CDF")
        ax.set_xlabel("Present Value")
        ax.set_ylabel("Cumulative Probability")
        return ax

    # ------------------------------------------------------------------ #
    # Operator interop                                                     #
    # ------------------------------------------------------------------ #

    def __float__(self) -> float:
        """Coerce to float via the mean — allows use in scalar contexts."""
        return self.mean

    def __repr__(self) -> str:
        tag = f" [{self.label}]" if self.label else ""
        lo, hi = self.ci(0.95)
        return (
            f"StochasticResult{tag}("
            f"mean={self.mean:.4f}, std={self.std:.4f}, "
            f"95% CI=[{lo:.4f}, {hi:.4f}], n={self.n})"
        )

n property

Number of scenarios.

__float__()

Coerce to float via the mean — allows use in scalar contexts.

Source code in src/pylifecontingencies/dynamic/stochastic.py
210
211
212
def __float__(self) -> float:
    """Coerce to float via the mean — allows use in scalar contexts."""
    return self.mean

ci(level=0.95)

Symmetric (1-level)/2 credible interval: (lower, upper).

Source code in src/pylifecontingencies/dynamic/stochastic.py
70
71
72
73
def ci(self, level: float = 0.95) -> tuple[float, float]:
    """Symmetric (1-level)/2 credible interval: (lower, upper)."""
    alpha = (1.0 - level) / 2.0
    return self.quantile(alpha), self.quantile(1.0 - alpha)

hist(bins=50, ax=None, ci=True, **kwargs)

Histogram of the PV distribution.

Parameters

bins : int Number of histogram bins (default 50). ax : matplotlib Axes or None Axes to draw on; a new figure is created when None. ci : bool If True, draw vertical lines for the mean and 95 % CI. **kwargs Forwarded to ax.hist().

Returns

matplotlib.axes.Axes

Source code in src/pylifecontingencies/dynamic/stochastic.py
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
def hist(
    self,
    bins: int = 50,
    ax: "Axes | None" = None,
    ci: bool = True,
    **kwargs,
) -> "Axes":
    """
    Histogram of the PV distribution.

    Parameters
    ----------
    bins : int
        Number of histogram bins (default 50).
    ax : matplotlib Axes or None
        Axes to draw on; a new figure is created when ``None``.
    ci : bool
        If True, draw vertical lines for the mean and 95 % CI.
    **kwargs
        Forwarded to ``ax.hist()``.

    Returns
    -------
    matplotlib.axes.Axes
    """
    import matplotlib.pyplot as plt

    if ax is None:
        _, ax = plt.subplots()

    kwargs.setdefault("edgecolor", "white")
    ax.hist(self.samples, bins=bins, **kwargs)

    if ci:
        lo, hi = self.ci(0.95)
        ax.axvline(self.mean, color="crimson", linestyle="--",
                   linewidth=1.5, label=f"mean = {self.mean:.4f}")
        ax.axvline(lo, color="steelblue", linestyle=":",
                   linewidth=1.2, label=f"p5 = {lo:.4f}")
        ax.axvline(hi, color="steelblue", linestyle=":",
                   linewidth=1.2, label=f"p95 = {hi:.4f}")
        ax.legend(fontsize=8)

    ax.set_title(self.label or "PV Distribution")
    ax.set_xlabel("Present Value")
    ax.set_ylabel("Frequency")
    return ax

plot(ax=None, **kwargs)

Empirical CDF of the PV distribution.

Draws the step-wise ECDF and a dashed vertical line at the mean.

Parameters

ax : matplotlib Axes or None Axes to draw on; a new figure is created when None. **kwargs Forwarded to ax.plot().

Returns

matplotlib.axes.Axes

Source code in src/pylifecontingencies/dynamic/stochastic.py
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
def plot(
    self,
    ax: "Axes | None" = None,
    **kwargs,
) -> "Axes":
    """
    Empirical CDF of the PV distribution.

    Draws the step-wise ECDF and a dashed vertical line at the mean.

    Parameters
    ----------
    ax : matplotlib Axes or None
        Axes to draw on; a new figure is created when ``None``.
    **kwargs
        Forwarded to ``ax.plot()``.

    Returns
    -------
    matplotlib.axes.Axes
    """
    import matplotlib.pyplot as plt

    if ax is None:
        _, ax = plt.subplots()

    sorted_s = np.sort(self.samples)
    cdf = np.arange(1, self.n + 1) / self.n

    kwargs.setdefault("drawstyle", "steps-post")
    ax.plot(sorted_s, cdf, **kwargs)
    ax.axvline(self.mean, color="crimson", linestyle="--",
               linewidth=1.5, label=f"mean = {self.mean:.4f}")
    ax.legend(fontsize=8)
    ax.set_title(self.label or "Empirical CDF")
    ax.set_xlabel("Present Value")
    ax.set_ylabel("Cumulative Probability")
    return ax

quantile(q)

Return the q-th quantile (0 ≤ q ≤ 1).

Source code in src/pylifecontingencies/dynamic/stochastic.py
66
67
68
def quantile(self, q: float) -> float:
    """Return the q-th quantile (0 ≤ q ≤ 1)."""
    return float(np.quantile(self.samples, q))

summary()

Return a dict with key percentiles — useful for quick inspection.

Source code in src/pylifecontingencies/dynamic/stochastic.py
75
76
77
78
79
80
81
82
83
84
85
86
87
88
def summary(self) -> dict[str, float]:
    """Return a dict with key percentiles — useful for quick inspection."""
    return {
        "mean":   self.mean,
        "std":    self.std,
        "median": self.median,
        "p05":    self.quantile(0.05),
        "p25":    self.quantile(0.25),
        "p75":    self.quantile(0.75),
        "p95":    self.quantile(0.95),
        "min":    self.min,
        "max":    self.max,
        "n":      float(self.n),
    }

to_dataframe()

Return samples as a one-column pandas.DataFrame with column 'pv'.

Source code in src/pylifecontingencies/dynamic/stochastic.py
110
111
112
113
def to_dataframe(self) -> "pd.DataFrame":
    """Return samples as a one-column ``pandas.DataFrame`` with column ``'pv'``."""
    import pandas as pd
    return pd.DataFrame({"pv": self.samples})

tvar(alpha)

Tail Value at Risk (Expected Shortfall) at confidence level alpha.

TVaR_α = E[X | X > VaR_α]

Returns var(alpha) when no sample exceeds it (degenerate tail).

Source code in src/pylifecontingencies/dynamic/stochastic.py
 98
 99
100
101
102
103
104
105
106
107
108
def tvar(self, alpha: float) -> float:
    """
    Tail Value at Risk (Expected Shortfall) at confidence level ``alpha``.

    ``TVaR_α = E[X | X > VaR_α]``

    Returns ``var(alpha)`` when no sample exceeds it (degenerate tail).
    """
    v = self.var(alpha)
    tail = self.samples[self.samples > v]
    return float(np.mean(tail)) if len(tail) > 0 else v

var(alpha)

Value at Risk at confidence level alpha.

Equal to the alpha-quantile of the PV distribution.

Source code in src/pylifecontingencies/dynamic/stochastic.py
90
91
92
93
94
95
96
def var(self, alpha: float) -> float:
    """
    Value at Risk at confidence level ``alpha``.

    Equal to the ``alpha``-quantile of the PV distribution.
    """
    return self.quantile(alpha)