# Packages
import numpy as np
import numba
from typing import NamedTuple
from ogcore import utils
# set constants
MONTHS_IN_A_YEAR = 12
THOUSAND = 1000
[docs]
@numba.jit(nopython=True)
def earnings_band_at(x, lo, hi, period, age):
"""
Part of labor income ``x`` (w * e * n, in model units) that lies
between the cutoffs that applied to the earner's cohort in the
model period in which it was earned, min(max(x, lo), hi) - lo.
With ``lo = 0`` and ``hi = inf`` this returns ``x`` unchanged.
Args:
x (scalar or Numpy array): labor income, w * e * n
lo (Numpy array): lower cutoff by model period and age, in
model units of labor income (2-D; a single column applies
at every age)
hi (Numpy array): upper cutoff by model period and age, as lo
period (int): model period in which ``x`` was earned; periods
before or after the arrays read their first or last row
age (int): age (model period of life) at which ``x`` was earned
Returns:
band (scalar or Numpy array): part of ``x`` between the cutoffs
in effect at ``period`` and ``age``
"""
lo_t = lo[min(max(period, 0), lo.shape[0] - 1), min(age, lo.shape[1] - 1)]
hi_t = hi[min(max(period, 0), hi.shape[0] - 1), min(age, hi.shape[1] - 1)]
return np.minimum(np.maximum(x, lo_t), hi_t) - lo_t
def _period_age(x):
"""
A cutoff as a 2-D float array by model period and age: a single
value becomes 1 x 1 and a path by period a single column, which
``earnings_band_at`` applies at every age.
"""
x = np.asarray(x, dtype=float)
if x.ndim == 0:
return x.reshape(1, 1)
if x.ndim == 1:
return x[:, np.newaxis]
return x
def _band_paths(earn_lo, earn_hi, method):
"""
Earnings band cutoffs by model period and age used by
``DB_amount`` and ``NDC_amount``.
Args:
earn_lo (scalar, array_like, or None): lower cutoff, in model
units of labor income: a single value, a path by period, or
an array by period and age
earn_hi (scalar, array_like, or None): upper cutoff
method (str): 'SS', 'TPI', or 'TPI_scalar'
Returns:
lo, hi (Numpy arrays or None): None, None when no band is
set. Otherwise 2-D float arrays by period and age (see
``_period_age``): all rows for 'TPI', and the final
(steady-state) or first row for 'SS' or 'TPI_scalar',
matching the rows the other pension parameters are read
from.
"""
if earn_lo is None and earn_hi is None:
return None, None
lo = _period_age(0.0 if earn_lo is None else earn_lo)
hi = _period_age(np.inf if earn_hi is None else earn_hi)
if method == "SS":
lo, hi = lo[-1:], hi[-1:]
elif method == "TPI_scalar":
lo, hi = lo[:1], hi[:1]
return np.ascontiguousarray(lo), np.ascontiguousarray(hi)
def _path_from(path, t):
"""
The rows of a cutoff array by period and age starting in period t
(its last row if t is past its end), or None if ``path`` is None.
"""
if path is None:
return None
return np.ascontiguousarray(path[min(t, path.shape[0] - 1) :])
[docs]
def pension_earn_caps(p):
"""
The two earnings cutoffs, by model period and age, set by
``db_earn_cap_factor``, ``dc_earn_cap_factor``, and
``avg_labor_inc_t1_model_units``, in model units of labor income.
The hybrid DB-NDC system pays a defined benefit on labor income up
to the first cutoff and a notional defined contribution benefit on
labor income between the two. The hybrid DB-FDC system pays the
same defined benefit and collects funded defined contributions on
labor income between the two. With ``pension_earn_cap`` True, the
Defined Benefits system counts only labor income up to the first
cutoff toward the benefit, and the Notional Defined Contribution
system credits only labor income up to the second cutoff to the
notional account. The cutoffs do not depend on any endogenous
variable. The cutoff at period t and age s is the one that applies
to the cohort of that household (the factors are cohort pension
parameters that ``pension_regimes`` may change); it applies to the
labor income the household earns in that period.
Args:
p (OG-Core Specifications object): model parameters
Returns:
cut1, cut2 (Numpy arrays): the cutoffs,
``db_earn_cap_factor`` and ``dc_earn_cap_factor`` times
``avg_labor_inc_t1_model_units``, as 2-D arrays by period
and age ((T + S) x S once ``Specifications`` builds them; a
factor set by hand as a single value or a path by period
gives one column, applied at every age)
"""
avg_inc = float(p.avg_labor_inc_t1_model_units)
return (
_period_age(p.db_earn_cap_factor) * avg_inc,
_period_age(p.dc_earn_cap_factor) * avg_inc,
)
def cohort_array(name, p, by_j=False):
"""
Return the pension parameter ``name`` as an array by period and age.
After ``Specifications.compute_default_params`` the cohort pension
parameters (``retire``, ``avg_earn_num_years``, ``yr_contrib``,
``tau_p``, ``k_ret``, ``indR``, ``fdc_tau``, ``r_fdc_wedge``) are
(T + S) x S arrays holding, for the household of age s in period t,
the value that applies to its birth cohort, and ``alpha_db`` is
(T + S) x S x J.
This helper also accepts the forms a caller may set by hand: a
single number is broadcast to the full shape, and an array without
the age dimension (a path by period, or by period and lifetime
income group) is taken to hold the same value at every age in a
period.
Args:
name (str): attribute name on ``p``
p (OG-Core Specifications object): model parameters
by_j (bool): whether the parameter also varies by lifetime
income group, in which case the array is (T + S) x S x J
Returns:
arr (Numpy array): the parameter by period and age
Raises:
ValueError: if the attribute cannot be broadcast to that shape
"""
arr = np.asarray(getattr(p, name), dtype=float)
shape = (p.T + p.S, p.S, p.J) if by_j else (p.T + p.S, p.S)
if arr.ndim == len(shape) and arr.shape == shape:
return arr
if arr.ndim == 0 or (arr.size > 0 and np.all(arr == arr.flat[0])):
# a single value (possibly an array built for other dimensions,
# as when a test changes S after the object is created)
return np.broadcast_to(arr.flat[0], shape)
if arr.ndim == len(shape) - 1 and arr.shape[0] == shape[0]:
return np.broadcast_to(np.expand_dims(arr, 1), shape)
raise ValueError(
f"{name} must be a number or an array of shape {shape} (or the "
f"same without the age dimension), got shape {arr.shape}"
)
def cohort_path(arr, t, per_rmn, p):
"""
Lifetime path of a period-by-age array for one household.
The household has ``per_rmn`` periods of life remaining in period
t, so it is age S - per_rmn in period t and lives age u in period
t - (S - per_rmn) + u: its path runs down a diagonal of ``arr``.
Ages lived before the time path begins read the first row and ages
after it ends read the last row, matching how the DB and NDC
formulas treat wages and labor supply outside the path.
Args:
arr (Numpy array): (T + S) x S or (T + S) x S x J array
t (int): model period of the first of the remaining periods
per_rmn (int): number of periods of life remaining
p (OG-Core Specifications object): model parameters
Returns:
path (Numpy array): length S (or S x J) path by age
"""
age0 = p.S - per_rmn
rows = np.clip(t - age0 + np.arange(p.S), 0, arr.shape[0] - 1)
return arr[rows, np.arange(p.S)]
def _db_cohort_inputs(p, t, per_rmn, j):
"""
The Defined Benefits parameters along one household's lifetime.
Returns the retirement period, averaging window, years of
contribution and replacement rate in effect at each age of the
household that has ``per_rmn`` periods of life remaining in period
``t`` (see ``cohort_path``), and its effective labor units by age.
None of these depend on the household's choices, but the household
problem evaluates the pension many times while it solves, so they are
cached on ``p`` by household. The cache is emptied when any of the
arrays it is built from is reassigned (compared by identity, as in
``pension_periods``). The returned arrays are read-only.
Args:
p (OG-Core Specifications object): model parameters
t (int): model period of the first of the remaining periods
per_rmn (int): number of periods of life remaining
j (int): index of lifetime income group
Returns:
(tuple): (S_ret_u, ny_u, cy_u, alpha_db_u, e_S), each length S
"""
ny, cy, S_ret = pension_periods(p)
sources = (ny, cy, S_ret, p.alpha_db, p.e)
cache = getattr(p, "_db_cohort_cache", None)
if cache is None or not all(a is b for a, b in zip(cache[0], sources)):
cache = (sources, {})
p._db_cohort_cache = cache
key = (t, per_rmn, j)
found = cache[1].get(key)
if found is not None:
return found
alpha_db = cohort_array("alpha_db", p, by_j=True)
if np.ndim(p.e) == 3:
e_S = cohort_path(np.asarray(p.e), t, per_rmn, p)[:, j]
else:
e_S = p.e[:, j]
found = (
cohort_path(S_ret, t, per_rmn, p),
cohort_path(ny, t, per_rmn, p),
cohort_path(cy, t, per_rmn, p),
cohort_path(alpha_db, t, per_rmn, p)[:, j],
np.ascontiguousarray(e_S),
)
for arr in found:
arr.setflags(write=False)
cache[1][key] = found
return found
def pension_periods(p):
"""
Convert the pension parameters measured in calendar years into
integer model periods, by period and age.
Args:
p (OG-Core Specifications object): model parameters
Returns:
equiv_periods (Numpy array): (T + S) x S number of model periods
over which earnings are averaged (``avg_earn_num_years``)
equiv_yr_contrib (Numpy array): (T + S) x S number of model
periods of contributions credited (``yr_contrib``)
S_ret (Numpy array): (T + S) x S model period of retirement
Raises:
ValueError: if the averaging window is shorter than one model
period or longer than the working life for any household,
in which case the window would index before the start of
the lifetime
The result depends only on ``S``, ``T`` and the three parameters
above, which do not change while the model solves, yet the
household problem asks for it several times per evaluation. It is
therefore cached on ``p`` and recomputed only when one of them is
reassigned (each parameter is compared by identity, so changing an
array's elements in place is not detected). The returned arrays are
read-only, as they are shared between calls.
"""
key = (p.S, p.T, p.avg_earn_num_years, p.yr_contrib, p.retire)
cached = getattr(p, "_pension_periods_cache", None)
if (
cached is not None
and cached[0][:2] == key[:2]
and all(a is b for a, b in zip(cached[0][2:], key[2:]))
):
return cached[1]
per_year = p.S / 80.0
avg_years = cohort_array("avg_earn_num_years", p)
equiv_periods = np.rint(per_year * avg_years).astype(int)
equiv_yr_contrib = np.rint(
per_year * cohort_array("yr_contrib", p)
).astype(int)
S_ret = cohort_array("retire", p).astype(int)
if np.any(equiv_periods < 1):
raise ValueError(
"avg_earn_num_years must cover at least one model period: "
f"avg_earn_num_years={avg_years.min()} with S={p.S} "
f"gives {equiv_periods.min()} periods."
)
if np.any(equiv_periods > S_ret):
bad = np.argwhere(equiv_periods > S_ret)[0]
raise ValueError(
"avg_earn_num_years cannot exceed the working life: "
f"avg_earn_num_years={avg_years[tuple(bad)]} is "
f"{equiv_periods[tuple(bad)]} model periods, but the "
f"household of age {bad[1]} in period {bad[0]} retires after "
f"{S_ret[tuple(bad)]} periods."
)
result = (equiv_periods, equiv_yr_contrib, S_ret)
for arr in result:
arr.setflags(write=False)
p._pension_periods_cache = (key, result)
return result
[docs]
def replacement_rate_vals(nssmat, wss, factor_ss, j, p):
r"""
Calculates replacement rate values for the social security system.
.. math::
\theta_{j,R,t+R} =
\frac{PIA_{j,R,t+R} \times 12}{factor \times w_{t+R}}
Args:
nssmat (Numpy array): initial guess at labor supply, size = SxJ
new_w (scalar): steady state real wage rate
factor_ss (scalar): scaling factor converting model units to
dollars
j (int): index of lifetime income group
p (OG-Core Specifications object): model parameters
Returns:
theta (Numpy array): social security replacement rate value for
lifetime income group j
"""
if j is not None:
e = np.squeeze(p.e[-1, :, j]) # Only computes using SS earnings
dim2 = 1
else:
e = np.squeeze(p.e[-1, :, :]).reshape(
(p.S, p.J)
) # Only computes using SS earnings
dim2 = p.J
# adjust number of calendar years AIME computed from int model periods.
# The Social Security window keeps the one-period shift it has always
# used (so pinned steady-state and time-path results are unchanged);
# see pension_periods for the unshifted conversion the DB system uses.
# The shift is floored at one period so that a one-year window cannot
# produce a 0/0 replacement rate, and the window is bounds-checked.
equiv_periods, _, S_ret = pension_periods(p)
equiv_periods, S_ret = int(equiv_periods[-1, -1]), int(S_ret[-1, -1])
equiv_periods = max(equiv_periods - 1, 1)
earnings = (e * (wss * nssmat * factor_ss)).reshape(p.S, dim2)
# get highest earning years for number of years AIME computed from
highest_earn = (-1.0 * np.sort(-1.0 * earnings[:S_ret, :], axis=0))[
:equiv_periods
]
AIME = highest_earn.sum(0) / ((12.0 * (p.S / 80.0)) * equiv_periods)
PIA = np.zeros(dim2)
# Compute level of replacement using AIME brackets and PIA rates
for jj in range(dim2):
if AIME[jj] < p.AIME_bkt_1:
PIA[jj] = p.PIA_rate_bkt_1 * AIME[jj]
elif AIME[jj] < p.AIME_bkt_2:
PIA[jj] = p.PIA_rate_bkt_1 * p.AIME_bkt_1 + p.PIA_rate_bkt_2 * (
AIME[jj] - p.AIME_bkt_1
)
else:
PIA[jj] = (
p.PIA_rate_bkt_1 * p.AIME_bkt_1
+ p.PIA_rate_bkt_2 * (p.AIME_bkt_2 - p.AIME_bkt_1)
+ p.PIA_rate_bkt_3 * (AIME[jj] - p.AIME_bkt_2)
)
# Set the maximum monthly replacement rate from SS benefits tables
PIA[PIA > p.PIA_maxpayment] = p.PIA_maxpayment
if p.PIA_minpayment != 0.0:
PIA[PIA < p.PIA_minpayment] = p.PIA_minpayment
theta = (PIA * (12.0 * p.S / 80.0)) / (factor_ss * wss)
if not p.baseline and p.baseline_theta:
# use theta from the baseline solution
if j is not None:
theta = p.SS_theta[j]
else:
theta = p.SS_theta
return theta
def replacement_rate_adjustment(pension, t, j, method, p):
"""
Return the replacement rate adjustment, shaped to broadcast against
pension.
US-Style Social Security applies this itself inside SS_amount. The
other three systems do not, so pension_amount applies it for them.
Along the time path the multiplier varies with each cohort's own year,
so it is indexed at t + tt for row tt. A 1D pension array is one
cohort's remaining lifetime starting in period t, so entry tt is
paid in period t + tt and gets that year's multiplier.
The steady state uses the final value of the parameter, so a
permanent adjustment carries into the steady state that the time
path converges to.
The multiplier scales the whole pension array, while SS_amount scales
only the entries from retirement on. These are equivalent only because
DB, NDC, and PS benefits are zero before retirement; a system that
pays benefits before retirement would need the SS_amount treatment.
Args:
pension (Numpy array): pension amount for each household
t (int): model period
j (int): index of lifetime income group, None if all groups
method (str): 'SS', 'TPI', or 'TPI_scalar'
p (OG-Core Specifications object): model parameters
Returns:
adjustment (array_like): multiplier on the replacement rate
"""
adjust = p.replacement_rate_adjust
if method == "SS":
return adjust[-1, :] if j is None else adjust[-1, j]
if method == "TPI_scalar":
return adjust[0, j]
length = pension.shape[0]
if pension.ndim == 1:
return adjust[t : t + length, j]
if pension.ndim == 2:
return adjust[t : t + length, j].reshape(length, 1)
return adjust[t : t + length, :].reshape(length, 1, p.J)
[docs]
def pension_amount(
r, w, n, ndc_rates, theta, t, j, shift, method, e, factor, p
):
"""
Calculate public pension benefit amounts for each household.
Args:
r (array_like): real interest rate
w (array_like): real wage rate
n (Numpy array): labor supply
ndc_rates (NDCRates): calendar paths of the NDC credited and
discount rates (``ndc_rates_path``), used only by the
notional defined contribution system; None for the
steady-state rates
theta (Numpy array): social security replacement rate value for
lifetime income group j
t (int): time period
j (int): index of lifetime income group
shift (bool): whether computing for periods 0--s or 1--(s+1),
=True for 1--(s+1)
method (str): adjusts calculation dimensions based on 'SS' or
'TPI'
e (Numpy array): effective labor units
p (OG-Core Specifications object): model parameters
Returns:
pension (Numpy array): pension amount for each household
Under the Defined Benefits and Notional Defined Contribution
systems, ``p.pension_earn_cap`` True caps the labor income that
earns a benefit at the first and second cutoffs of
``pension_earn_caps`` (the same cutoffs that bound the two bands
of the hybrid DB-NDC system). False, the default, counts all
labor income.
"""
# TODO: think about how can allow for transition from one
# pension system to another along the time path
# Specifications objects pickled before pension_earn_cap existed
# have no such attribute; treat them as uncapped.
earn_cap = getattr(p, "pension_earn_cap", False)
if p.pension_system == "US-Style Social Security":
pension = SS_amount(w, n, theta, t, j, shift, method, e, p)
elif p.pension_system == "Defined Benefits":
earn_hi = pension_earn_caps(p)[0] if earn_cap else None
pension = DB_amount(w, e, n, t, j, method, p, earn_hi=earn_hi)
pension = pension * replacement_rate_adjustment(
pension, t, j, method, p
)
elif p.pension_system == "Notional Defined Contribution":
earn_hi = pension_earn_caps(p)[1] if earn_cap else None
pension = NDC_amount(
w, e, n, r, ndc_rates, t, j, method, p, earn_hi=earn_hi
)
pension = pension * replacement_rate_adjustment(
pension, t, j, method, p
)
elif p.pension_system == "Points System":
pension = PS_amount(w, e, n, j, factor, p)
pension = pension * replacement_rate_adjustment(
pension, t, j, method, p
)
elif p.pension_system == "Hybrid DB-NDC":
pension = DB_NDC_hybrid_amount(w, e, n, r, ndc_rates, t, j, method, p)
pension = pension * replacement_rate_adjustment(
pension, t, j, method, p
)
elif p.pension_system == "Hybrid DB-FDC":
pension = DB_FDC_hybrid_amount(w, e, n, t, j, method, p)
pension = pension * replacement_rate_adjustment(
pension, t, j, method, p
)
else:
raise ValueError(
"pension_system must be one of the following: "
"'US-Style Social Security', 'Defined Benefits', "
"'Notional Defined Contribution', 'Points System', "
"'Hybrid DB-NDC', 'Hybrid DB-FDC'"
)
return pension
def retirement_mask(t, length, shift, method, ndim, p):
"""
Boolean array marking the households that are at or past their own
retirement age.
``p.retire`` is a (T + S) x S integer array giving, for the household
of age s in period t, the model period at which it becomes eligible
for the public pension. A cohort's path runs down a diagonal of that
array, so the household path reads the cohort's own retirement age
rather than the one in force in a single calendar year.
Args:
t (int): first model period covered by the arrays (ignored for
'SS' and 'TPI_scalar')
length (int): number of periods covered by the arrays along the
time path; for a 1D cohort path this is the number of
periods of life remaining
shift (bool): whether computing for periods 0--s or 1--(s+1),
=True for 1--(s+1), which moves eligibility one age earlier
method (str): 'SS', 'TPI', or 'TPI_scalar'
ndim (int): number of dimensions of the labor supply array the
mask must broadcast against: 1 for a single cohort path or
an S vector, 2 for S x J or (length) x S, 3 for
(length) x S x J
p (OG-Core Specifications object): model parameters
Returns:
mask (Numpy array): boolean, shaped to broadcast against the
pension array
"""
retire = np.asarray(p.retire)
S = p.S
ages = np.arange(S)
offset = 1 if shift else 0
if method == "SS":
# the steady state uses the final period's retirement age
mask = ages >= retire[-1, :] - offset
if ndim == 2:
mask = mask.reshape(S, 1)
elif method == "TPI_scalar":
# the oldest household in period 0
mask = np.array(S - 1 >= retire[0, S - 1] - offset)
elif method == "TPI":
if ndim == 1:
# One cohort with ``length`` periods of life remaining,
# starting in period t at age S - length: its own retirement
# ages run down the diagonal of retire with offset
# S - length, the same extraction the household problem
# uses for chi_n and rho.
cohort_retire = np.diagonal(
retire[t : t + S, :], offset=S - length
)
mask = ages[S - length :] >= cohort_retire - offset
else:
# cross sections for periods t, ..., t + length - 1
mask = ages.reshape(1, S) >= retire[t : t + length, :] - offset
if ndim == 3:
mask = mask[:, :, np.newaxis]
else:
raise ValueError(
"method must be one of 'SS', 'TPI', or 'TPI_scalar', got "
f"{method!r}"
)
return mask
[docs]
def SS_amount(w, n, theta, t, j, shift, method, e, p):
r"""
Calculate public pension benefit amounts for each household under
a US-style social security system.
.. math::
pension_{j,s,t} = \theta_j \times w_t \quad \forall s \geq R_{t-s}
where $R_{t-s}$ is the retirement age of the cohort born in period
$t - s$, read from the (T + S) x S array ``p.retire``.
Args:
w (array_like): real wage rate
n (Numpy array): labor supply
theta (array_like): social security replacement rate before
replacement_rate_adjust scaling. A length J vector when j is
None; a scalar (or length 1 array) for group j when n is 1D
or method is 'TPI_scalar'
t (int): time period
j (int): index of lifetime income group
shift (bool): whether computing for periods 0--s or 1--(s+1),
=True for 1--(s+1)
method (str): adjusts calculation dimensions based on 'SS' or
'TPI'
e (Numpy array): effective labor units
p (OG-Core Specifications object): model parameters
Returns:
pension (Numpy array): pension amount for each household
Notes:
replacement_rate_adjust is applied here, and only here, for the
US-style system, so callers pass the unadjusted theta. Along the
time path the factor is indexed by the year the benefit is paid
and the retirement age by the household's own cohort, so the
single-cohort path agrees with the (T, S, J) array that the
aggregates use. The steady state uses the final values of both.
"""
n = np.asarray(n)
w = np.asarray(w)
theta = np.asarray(theta)
adjust = p.replacement_rate_adjust
if method == "SS":
# Depending on if we are looking at b_s or b_s+1, the
# entry for retirement will change (it shifts back one).
# The shift boolean makes sure we start replacement rates
# at the correct age.
if j is None:
# a scalar when J = 1 and n is an S vector, else (1, J)
benefit = np.squeeze(adjust[-1, :] * theta * w)
if n.ndim == 2:
benefit = benefit.reshape(1, -1)
else:
benefit = adjust[-1, j] * theta * w
benefit = np.broadcast_to(benefit, n.shape)
mask = retirement_mask(None, None, shift, method, n.ndim, p)
elif method == "TPI":
length = w.shape[0]
if n.ndim == 1:
# One cohort's remaining lifetime: entry tt is paid in
# period t + tt, so the adjustment is indexed by that year.
benefit = theta * adjust[t : t + length, j] * w
elif n.ndim == 2:
benefit = (
theta
* adjust[t : t + length, j].reshape(length, 1)
* w.reshape(length, 1)
)
else:
benefit = (
theta.reshape(1, 1, p.J)
* adjust[t : t + length, :].reshape(length, 1, p.J)
* utils.to_timepath_shape(w)
)
mask = retirement_mask(t, length, shift, method, n.ndim, p)
elif method == "TPI_scalar":
# The above methods won't work if scalars are used. This option
# is only called by the SS_TPI_firstdoughnutring function in TPI.
benefit = theta * adjust[0, j] * w
mask = retirement_mask(None, None, shift, method, 1, p)
else:
raise ValueError(
"method must be one of 'SS', 'TPI', or 'TPI_scalar', got "
f"{method!r}"
)
pension = np.where(mask, benefit, 0.0)
return pension
[docs]
def DB_amount(w, e, n, t, j, method, p, earn_lo=None, earn_hi=None):
r"""
Calculate public pension from a defined benefits system.
.. math::
pension_{j,s,t} = \biggl[\frac{\sum_{u=R-ny}^{R-1}w_{t-s+u}
e_{j,u,t-s+u}n_{j,u,t-s+u}}{ny}\biggr]\times Cy \times
\alpha^{DB}_{j,s,t} \quad \forall s \geq R
where the retirement age $R$, the averaging window $ny$
(``avg_earn_num_years``), the years of contribution $Cy$
(``yr_contrib``), and the replacement rate $\alpha^{DB}$
(``alpha_db``) are those of the household's own birth cohort at the
age and period the benefit is paid, read from the period-by-age
arrays that ``pension_regimes`` builds. With no regimes, $R$, $ny$,
and $Cy$ are the same for everyone and $\alpha^{DB}_{j,t}$ varies
only by lifetime income group and the calendar year of payment.
Args:
w (array_like): real wage rate
e (Numpy array): effective labor units
n (Numpy array): labor supply; may be a partial lifetime path
(length < S, for cohorts alive when the time path begins),
a steady-state vector (S,) or matrix (S, J), or the full
time path (T, S, J)
t (int): model period of the first element of ``n`` (for a
partial or full lifetime path) or of the first row of ``n``
(for the full time path)
j (int): index of lifetime income group, None if all groups
method (str): adjusts calculation dimensions based on 'SS',
'TPI', or 'TPI_scalar'
p (OG-Core Specifications object): model parameters
earn_lo (scalar, array_like, or None): only labor income
w * e * n above earn_lo enters the benefit (used by the
hybrid DB-NDC system, and by ``pension_amount`` when
``pension_earn_cap`` is True). In model units of labor income, a
single value, a path by model period of length T + S, or a
(T + S) x S array by period and age; the cutoff at the
period and age at which each income was earned applies.
None (the default) for no lower cutoff.
earn_hi (scalar, array_like, or None): only labor income below
earn_hi enters the benefit, as for earn_lo. None (the
default) for no upper cutoff.
Returns:
DB (Numpy array): pension amount for each household
"""
ny, cy, S_ret = pension_periods(p)
alpha_db = cohort_array("alpha_db", p, by_j=True)
# g_y is a scalar parameter, but the numba loops index it, so pass
# it as a 1-element array.
g_y_arr = np.atleast_1d(np.asarray(p.g_y, dtype=float)).ravel()
# The wage may arrive as a scalar (steady state, or one remaining
# period in the TPI); the loops index it as a path, so broadcast it
# to the length of the labor-supply vector.
if np.ndim(w) == 0:
w = np.full(n.shape[0], float(w))
earn_lo, earn_hi = _band_paths(earn_lo, earn_hi, method)
if n.shape[0] < p.S:
per_rmn = n.shape[0]
# Pre-time-path wages: the recent past is anchored to the
# period-0 wage of the current path (trend growth is handled
# by the de-trending inside the benefit formula); labor comes
# from the model's initial condition n_preTP (see Issue #1014)
w_S = np.append((w[0] * np.ones(p.S))[:(-per_rmn)], w)
n_S = np.append(p.n_preTP[:(-per_rmn), j], n)
# The first doughnut ring (method 'TPI_scalar') solves the
# household in its final period of life at t = 0 and passes
# t = None, as every other TPI_scalar branch indexes period 0
if method == "TPI_scalar":
t = 0
# This household is age S - per_rmn at time t, so its benefit
# at age u is paid in period t + u - (S - per_rmn); its own
# cohort's pension parameters run down that diagonal. Its
# effective labor units are the profile in effect in the period
# each age is lived in: ages before the time path begins use the
# period-0 profile (as the wage above) and ages beyond the end of
# the path use the final (steady-state) profile.
S_ret_u, ny_u, cy_u, alpha_db_u, e_S = _db_cohort_inputs(
p, t, per_rmn, j
)
DB = DB_1dim_loop(
w_S,
e_S,
n_S,
S_ret_u,
p.S,
g_y_arr,
np.zeros(p.S),
ny_u,
alpha_db_u,
cy_u,
earn_lo,
earn_hi,
t - (p.S - per_rmn),
)
DB = DB[-per_rmn:]
else:
if np.ndim(n) == 1:
if method == "SS":
row = -1
elif method == "TPI_scalar":
row = 0
else:
row = None
if row is None:
# full lifetime of a cohort that is age 0 at time t
S_ret_u, ny_u, cy_u, alpha_db_u, _ = _db_cohort_inputs(
p, t, p.S, j
)
else:
S_ret_u, ny_u, cy_u = S_ret[row], ny[row], cy[row]
alpha_db_u = alpha_db[row, :, j]
DB = DB_1dim_loop(
w,
e,
n,
S_ret_u,
p.S,
g_y_arr,
np.zeros(p.S),
ny_u,
alpha_db_u,
cy_u,
earn_lo,
earn_hi,
# period of age 0 (the band arrays of 'SS' and
# 'TPI_scalar' have a single value)
t if row is None else 0,
)
elif np.ndim(n) == 2:
# cross-section of all S x J households in a single period
if method == "SS":
row = -1
elif method == "TPI_scalar":
row = 0
else:
row = t
DB = DB_2dim_loop(
w,
e,
n,
S_ret[row],
p.S,
g_y_arr,
np.zeros((p.S, p.J)),
ny[row],
alpha_db[row],
cy[row],
earn_lo,
earn_hi,
max(row, 0),
)
elif np.ndim(n) == 3:
T = n.shape[0]
w_path = np.squeeze(np.asarray(w))
if w_path.ndim == 0:
w_path = np.full(T, float(w_path))
e_ss = p.e[-1] if np.ndim(p.e) == 3 else p.e
# parameters in effect for each (period, age) of the path
rows = np.clip(t + np.arange(T), 0, S_ret.shape[0] - 1)
DB = DB_3dim_loop(
w_path,
e_ss,
n,
p.n_preTP,
S_ret[rows],
p.S,
p.J,
float(g_y_arr[-1]),
ny[rows],
np.ascontiguousarray(alpha_db[rows]),
cy[rows],
# the loop counts periods from the first row of n
_path_from(earn_lo, t),
_path_from(earn_hi, t),
)
return DB
[docs]
def NDC_amount(
w, e, n, r, ndc_rates, t, j, method, p, earn_lo=None, earn_hi=None
):
r"""
Calculate public pension from a notional defined contribution
system.
.. math::
pension_{j,s,t} = \biggl[\sum_{u=E}^{R-1}\tau^{p}_{u,t-s+u}
w_{t-s+u}e_{j,u,t-s+u}n_{j,u,t-s+u}
\prod_{a=u+1}^{R}(1 + g_{NDC,t-s+a})
\biggr]\delta_{R,s,t} \quad \forall s \geq R
where the retirement age $R$ and the conversion coefficient
$\delta_{R,s,t}$ (through ``k_ret`` and ``indR``) are those of the
household's own birth cohort at the age and period the benefit is
paid, and the contribution rate $\tau^{p}_{u,t-s+u}$ is the one the
cohort faced at each working age u, all read from the period-by-age
arrays that ``pension_regimes`` builds. Each contribution earns
the rate credited in each period from the one after the
contribution through the retirement period, $g_{NDC,t}$ (the
balance is valued in the period of the first payment, as the
conversion coefficient assumes), and the conversion coefficient discounts
payments at the rate in the period the household retires.
Args:
w (array_like): real wage rate
e (Numpy array): effective labor units
n (Numpy array): labor supply; may be a partial lifetime path
(length < S, for cohorts alive when the time path begins),
a steady-state vector (S,) or matrix (S, J), or the full
time path (T, S, J)
r (array_like): interest rate, used for the steady-state rates
when ``ndc_rates`` is not given
ndc_rates (NDCRates): calendar paths of the credited and
discount rates from ``ndc_rates_path``; anything else (such
as None) uses the steady-state rates, with the 'r' options
reading the last element of ``r``
t (int): model period of the first element of ``n`` (for a
partial or full lifetime path) or of the first row of ``n``
(for the full time path)
j (int): index of lifetime income group, None if all groups
method (str): adjusts calculation dimensions based on 'SS',
'TPI', or 'TPI_scalar'
p (OG-Core Specifications object): model parameters
earn_lo (scalar, array_like, or None): only labor income
w * e * n above earn_lo enters the benefit (used by the
hybrid DB-NDC system, and by ``pension_amount`` when
``pension_earn_cap`` is True). In model units of labor income, a
single value, a path by model period of length T + S, or a
(T + S) x S array by period and age; the cutoff at the
period and age at which each income was earned applies.
None (the default) for no lower cutoff.
earn_hi (scalar, array_like, or None): only labor income below
earn_hi enters the benefit, as for earn_lo. None (the
default) for no upper cutoff.
Returns:
NDC (Numpy array): pension amount for each household
"""
if not isinstance(ndc_rates, NDCRates):
ndc_rates = NDCRates(
np.array([g_ndc(r, None, p)]), np.array([g_dir(r, None, p)])
)
credit = np.ascontiguousarray(ndc_rates.credit, dtype=float)
discount = ndc_rates.discount
S_ret = cohort_array("retire", p).astype(int)
tau_p = cohort_array("tau_p", p)
indR = cohort_array("indR", p)
k_ret = cohort_array("k_ret", p)
# g_y is a scalar but the numba loops index it; the steady-state
# wage is a scalar but the loops index it as a path.
g_y_arr = np.atleast_1d(np.asarray(p.g_y, dtype=float)).ravel()
if np.ndim(w) == 0:
w = np.full(n.shape[0], float(w))
earn_lo, earn_hi = _band_paths(earn_lo, earn_hi, method)
if n.shape[0] < p.S:
per_rmn = n.shape[0]
# Pre-time-path wages: the recent past is anchored to the
# period-0 wage of the current path (trend growth is handled
# by the de-trending inside the benefit formula); labor comes
# from the model's initial condition n_preTP (see Issue #1014)
w_S = np.append((w[0] * np.ones(p.S))[:(-per_rmn)], w)
n_S = np.append(p.n_preTP[:(-per_rmn), j], n)
# The first doughnut ring (method 'TPI_scalar') solves the
# household in its final period of life at t = 0 and passes
# t = None, as every other TPI_scalar branch indexes period 0
if method == "TPI_scalar":
t = 0
# this household's own cohort parameters, by age
S_ret_u = cohort_path(S_ret, t, per_rmn, p)
tau_p_u = cohort_path(tau_p, t, per_rmn, p)
# the household is age S - per_rmn in period t, so it reaches
# retirement age R in period t - (S - per_rmn) + R
t_birth = t - (p.S - per_rmn)
delta_ret_u = delta_ret(
r,
None,
p,
S_ret_u,
cohort_path(indR, t, per_rmn, p),
cohort_path(k_ret, t, per_rmn, p),
t_ret=t_birth + S_ret_u,
g_dir_path=discount,
)
NDC = NDC_1dim_loop(
w_S,
# steady-state earnings profile for now (see Issue #1014)
p.e[-1, :, j] if np.ndim(p.e) == 3 else p.e[:, j],
n_S,
S_ret_u,
p.S,
g_y_arr,
tau_p_u,
credit,
t_birth,
delta_ret_u,
np.zeros(p.S),
earn_lo,
earn_hi,
)
NDC = NDC[-per_rmn:]
else:
if np.ndim(n) == 1:
if method == "SS":
row = -1
elif method == "TPI_scalar":
row = 0
else:
row = None
if row is None:
# full lifetime of a cohort that is age 0 at time t
S_ret_u = cohort_path(S_ret, t, p.S, p)
tau_p_u = cohort_path(tau_p, t, p.S, p)
indR_u = cohort_path(indR, t, p.S, p)
k_ret_u = cohort_path(k_ret, t, p.S, p)
t_birth = t
else:
S_ret_u, tau_p_u = S_ret[row], tau_p[row]
indR_u, k_ret_u = indR[row], k_ret[row]
# the steady state (rates do not vary), or a household
# born in period 0
t_birth = 0
t_ret_u = None if row == -1 else t_birth + S_ret_u
NDC = NDC_1dim_loop(
w,
e,
n,
S_ret_u,
p.S,
g_y_arr,
tau_p_u,
credit,
t_birth,
delta_ret(
r,
None,
p,
S_ret_u,
indR_u,
k_ret_u,
t_ret_u,
g_dir_path=discount,
),
np.zeros(p.S),
earn_lo,
earn_hi,
)
elif np.ndim(n) == 2:
# cross-section of all S x J households in a single period
if method == "SS":
row = -1
elif method == "TPI_scalar":
row = 0
else:
row = t
# the household of age u in period `row` retired in period
# row - u + R (None in the steady state)
t_ret_u = None if row == -1 else row - np.arange(p.S) + S_ret[row]
NDC = NDC_2dim_loop(
w,
e,
n,
S_ret[row],
p.S,
g_y_arr,
tau_p[row],
credit,
0 if row == -1 else row,
delta_ret(
r,
None,
p,
S_ret[row],
indR[row],
k_ret[row],
t_ret_u,
g_dir_path=discount,
),
np.zeros((p.S, p.J)),
earn_lo,
earn_hi,
)
elif np.ndim(n) == 3:
T = n.shape[0]
w_path = np.squeeze(np.asarray(w))
if w_path.ndim == 0:
w_path = np.full(T, float(w_path))
e_ss = p.e[-1] if np.ndim(p.e) == 3 else p.e
# parameters in effect for each (period, age) of the path
rows = np.clip(t + np.arange(T), 0, S_ret.shape[0] - 1)
# the household of age u in period t + i retired in period
# t + i - u + R
t_ret_path = (
(t + np.arange(T))[:, None] - np.arange(p.S)[None, :]
) + S_ret[rows]
NDC = NDC_3dim_loop(
w_path,
e_ss,
n,
p.n_preTP,
S_ret[rows],
p.S,
p.J,
float(g_y_arr[-1]),
np.ascontiguousarray(tau_p[rows]),
# the loop counts periods from the first row of n
credit[min(t, credit.size - 1) :],
delta_ret(
r,
None,
p,
S_ret[rows],
indR[rows],
k_ret[rows],
t_ret_path,
g_dir_path=discount,
),
_path_from(earn_lo, t),
_path_from(earn_hi, t),
)
return NDC
[docs]
def hybrid_earn_cutoffs(p):
"""
The two earnings cutoffs of the hybrid systems (``Hybrid DB-NDC``
and ``Hybrid DB-FDC``), from ``pension_earn_caps``, checked to be
ordered in every period and at every age.
Args:
p (OG-Core Specifications object): model parameters
Returns:
cut1, cut2 (Numpy arrays): the cutoffs in model units of labor
income, by period and age ((T + S) x S once
``Specifications`` builds them; a single value or a path by
period, as a caller may set by hand, is also accepted)
Raises:
ValueError: if ``dc_earn_cap_factor`` is less than
``db_earn_cap_factor`` in any period
"""
cut1, cut2 = pension_earn_caps(p)
n_per = max(cut1.shape[0], cut2.shape[0])
n_age = max(cut1.shape[1], cut2.shape[1])
rows = np.arange(n_per)[:, np.newaxis]
cols = np.arange(n_age)[np.newaxis, :]
c1_full = cut1[
np.minimum(rows, cut1.shape[0] - 1),
np.minimum(cols, cut1.shape[1] - 1),
]
c2_full = cut2[
np.minimum(rows, cut2.shape[0] - 1),
np.minimum(cols, cut2.shape[1] - 1),
]
if np.any(c2_full < c1_full):
t_bad, s_bad = np.argwhere(c2_full < c1_full)[0]
raise ValueError(
"dc_earn_cap_factor must be at least db_earn_cap_factor "
f"in every period and at every age: in period {t_bad} at "
f"age period {s_bad}, the cutoffs are {c1_full[t_bad, s_bad]} "
f"and {c2_full[t_bad, s_bad]}"
)
return cut1, cut2
[docs]
def DB_NDC_hybrid_amount(w, e, n, r, ndc_rates, t, j, method, p):
r"""
Calculate public pension from a hybrid defined benefit and notional
defined contribution system.
Labor income $w_t e_{j,s,t} n_{j,s,t}$ is split into two bands at
the cutoffs $f_{1,t} \bar{y}$ and $f_{2,t} \bar{y}$, where
$f_{1,t}$ and $f_{2,t}$ are ``db_earn_cap_factor`` and
``dc_earn_cap_factor`` in period t and $\bar{y}$ is
``avg_labor_inc_t1_model_units``, the average labor income in the
first model period in model units, taken from outside the model.
The cutoffs therefore do not depend on any endogenous variable.
Both factors may vary over time; the cutoffs that apply to any
income are those of the period in which it was earned. Income up
to $f_{1,t} \bar{y}$ is subject to the payroll tax ``tau_payroll``
and earns a defined benefit computed with the ``DB_amount``
formula and parameters on that capped income. Income between
$f_{1,t} \bar{y}$ and $f_{2,t} \bar{y}$ is subject to the NDC
contribution rate ``tau_p`` and earns a notional defined
contribution benefit computed with the ``NDC_amount`` formula and
parameters. Income above $f_{2,t} \bar{y}$ earns no benefit. The
pension is the sum:
.. math::
pension_{j,s,t} = pension^{DB}_{j,s,t}\bigl(\min\{w e n,
f_1 \bar{y}\}\bigr) + pension^{NDC}_{j,s,t}\bigl(\max\{
\min\{w e n, f_2 \bar{y}\} - f_1 \bar{y}, 0\}\bigr)
\quad \forall s \geq R
where the argument of each term is the labor income that enters
that system, with the cutoffs of the period of each earning.
Args:
w (array_like): real wage rate
e (Numpy array): effective labor units
n (Numpy array): labor supply; same shapes as accepted by
``DB_amount`` and ``NDC_amount``
r (array_like): interest rate, used for the steady-state NDC
rates when ``ndc_rates`` is not given
ndc_rates (NDCRates): calendar paths of the NDC credited and
discount rates (``ndc_rates_path``), or None for the
steady-state rates; see ``NDC_amount``
t (int): model period of the first element of ``n``
j (int): index of lifetime income group, None if all groups
method (str): adjusts calculation dimensions based on 'SS',
'TPI', or 'TPI_scalar'
p (OG-Core Specifications object): model parameters
Returns:
pension (Numpy array): pension amount for each household
Raises:
ValueError: if ``dc_earn_cap_factor`` is less than
``db_earn_cap_factor`` in any period
"""
cut1, cut2 = hybrid_earn_cutoffs(p)
DB = DB_amount(w, e, n, t, j, method, p, earn_lo=0.0, earn_hi=cut1)
NDC = NDC_amount(
w,
e,
n,
r,
ndc_rates,
t,
j,
method,
p,
earn_lo=cut1,
earn_hi=cut2,
)
return DB + NDC
[docs]
def DB_FDC_hybrid_amount(w, e, n, t, j, method, p):
r"""
Calculate public pension from a hybrid defined benefit and funded
defined contribution system.
This system has the same structure as the hybrid DB-NDC system
(``DB_NDC_hybrid_amount``), with a funded defined contribution (FDC)
account in place of the notional one. Labor income
$w_t e_{j,s,t} n_{j,s,t}$ is split into two bands at the cutoffs
$f_{1,t} \bar{y}$ and $f_{2,t} \bar{y}$ of ``pension_earn_caps``.
Income up to $f_{1,t} \bar{y}$ earns a defined benefit computed
with the ``DB_amount`` formula and parameters on that capped
income, which this function returns. Income between
$f_{1,t} \bar{y}$ and $f_{2,t} \bar{y}$ pays the FDC contribution
rate ``fdc_tau`` into the household's individual account, which
buys an annuity at retirement (``fdc_earn_bands`` sets this band
under this system). The annuity is paid by the FDC fund, not the
government, so it is not part of this public pension; the household
receives it through the FDC pillar. Income above $f_{2,t} \bar{y}$
earns no benefit:
.. math::
pension_{j,s,t} = pension^{DB}_{j,s,t}\bigl(\min\{w e n,
f_1 \bar{y}\}\bigr) \quad \forall s \geq R
Args:
w (array_like): real wage rate
e (Numpy array): effective labor units
n (Numpy array): labor supply; same shapes as accepted by
``DB_amount``
t (int): model period of the first element of ``n``
j (int): index of lifetime income group, None if all groups
method (str): adjusts calculation dimensions based on 'SS',
'TPI', or 'TPI_scalar'
p (OG-Core Specifications object): model parameters
Returns:
pension (Numpy array): defined benefit pension amount for each
household
Raises:
ValueError: if ``dc_earn_cap_factor`` is less than
``db_earn_cap_factor`` in any period
"""
cut1, _ = hybrid_earn_cutoffs(p)
return DB_amount(w, e, n, t, j, method, p, earn_lo=0.0, earn_hi=cut1)
[docs]
def PS_amount(w, e, n, j, factor, p):
r"""
Calculate public pension from a points system.
.. math::
pension{j,s,t} = \sum_{s=E}^{R-1}w_{t}e_{j,s,t}n_{j,s,t}
\times v_{t} \quad \forall s > R
Args:
w (array_like): real wage rate
e (Numpy array): effective labor units
n (Numpy array): labor supply
j (int): index of lifetime income group
factor (scalar): scaling factor converting model units to
dollars
p (OG-Core Specifications object): model parameters
Returns:
PS (Numpy array): pension amount for each household
"""
# Single retirement age for now (see Issue #1014); g_y is
# a scalar but the numba loops index it; the steady-state wage is a
# scalar but the loops index it as a path.
S_ret = int(np.asarray(p.retire).flat[-1])
g_y_arr = np.atleast_1d(np.asarray(p.g_y, dtype=float)).ravel()
if np.ndim(w) == 0:
w = np.full(n.shape[0], float(w))
if n.shape[0] < p.S:
per_rmn = n.shape[0]
# Pre-time-path wages: the recent past is anchored to the
# period-0 wage of the current path (trend growth is handled
# by the de-trending inside the benefit formula); labor comes
# from the model's initial condition n_preTP (see Issue #1014)
w_S = np.append((w[0] * np.ones(p.S))[:(-per_rmn)], w)
n_S = np.append(p.n_preTP[:(-per_rmn), j], n)
L_inc_avg_s = np.zeros(S_ret)
PS = np.zeros(p.S)
PS = PS_1dim_loop(
w_S,
# steady-state earnings profile for now (see Issue #1014)
p.e[-1, :, j] if np.ndim(p.e) == 3 else p.e[:, j],
n_S,
S_ret,
p.S,
g_y_arr,
p.vpoint,
factor,
L_inc_avg_s,
PS,
)
PS = PS[-per_rmn:]
else:
if np.ndim(n) == 1:
L_inc_avg_s = np.zeros(S_ret)
PS = np.zeros(p.S)
PS = PS_1dim_loop(
w,
e,
n,
S_ret,
p.S,
g_y_arr,
p.vpoint,
factor,
L_inc_avg_s,
PS,
)
elif np.ndim(n) == 2:
L_inc_avg_sj = np.zeros((S_ret, p.J))
PS = np.zeros((p.S, p.J))
PS = PS_2dim_loop(
w,
e,
n,
S_ret,
p.S,
p.J,
g_y_arr,
p.vpoint,
factor,
L_inc_avg_sj,
PS,
)
return PS
[docs]
def deriv_theta(r, w, e, Y, per_rmn, factor, t, j, p):
"""
Change in pension benefits for another unit of labor supply for
pension system selected
Args:
r (array_like): interest rate
w (array_like): real wage rate
e (Numpy array): effective labor units
Y (array_like): GDP
per_rmn (int): number of periods remaining in the model
factor (scalar): scaling factor converting model units to
t (int): model period
j (int): index of lifetime income group
p (OG-Core Specifications object): model parameters
Returns:
d_theta (Numpy array): change in pension benefits for another
unit of labor supply
"""
# TODO: Add Social Security here...
if p.pension_system == "Defined Benefits":
d_theta = deriv_DB(w, e, per_rmn, t, j, p)
d_theta = d_theta[-per_rmn:]
elif p.pension_system == "Notional Defined Contribution":
d_theta = deriv_NDC(r, w, e, Y, per_rmn, p)
elif p.pension_system == "Points System":
d_theta = deriv_PS(w, e, per_rmn, factor, p)
else:
raise ValueError(
"pension_system must be one of the following: "
"'US-style Social Security', 'Defined Benefits', "
"'Notional Defined Contribution', 'Points System'"
)
return d_theta
[docs]
def deriv_NDC(r, w, e, Y, per_rmn, p):
r"""
Change in NDC pension benefits for another unit of labor supply
.. math::
\frac{\partial \theta_{j,u,t+u-s}}{\partial n_{j,s,t}} =
\begin{cases}
\tau^{p}_{t}w_{t}e_{j,s}(1+g_{NDC})^{R - s}\delta_{R},
& \text{if}\ s<R \\
0, & \text{if}\ s \geq R \\
\end{cases}
Args:
r (array_like): interest rate
w (array_like): real wage rate
e (Numpy array): effective labor units
Y (array_like): GDP
per_rmn (int): number of periods remaining in the model
p (OG-Core Specifications object): model parameters
Returns:
d_theta (Numpy array): change in NDC pension benefits for
another unit of labor supply
"""
# steady-state retirement age and contribution rate
S_ret = int(cohort_array("retire", p)[-1, -1])
tau_p = float(cohort_array("tau_p", p)[-1, -1])
if per_rmn == 1:
d_theta = 0
elif per_rmn < (p.S - S_ret + 1):
d_theta = np.zeros(per_rmn)
else:
d_theta_empty = np.zeros(per_rmn)
delta_ret_amount = delta_ret(r, Y, p)
g_ndc_amount = g_ndc(r, Y, p)
d_theta = deriv_NDC_loop(
w,
e,
per_rmn,
p.S,
S_ret,
tau_p,
g_ndc_amount,
delta_ret_amount,
d_theta_empty,
)
return d_theta
[docs]
def deriv_DB(w, e, per_rmn, t, j, p):
r"""
Change in DB pension benefits for another unit of labor supply
.. math::
\frac{\partial \theta_{j,u,t+u-s}}{\partial n_{j,s,t}} =
\begin{cases}
0 , & \text{if}\ s < R - Cy \\
w_{t}e_{j,s}\alpha^{DB}_{j,t+R-s}\times \frac{Cy}{ny},
& \text{if}\ R - Cy <= s < R \\
0, & \text{if}\ s \geq R \\
\end{cases}
With a replacement rate that varies over time, the change in the
benefit paid at each age u depends on the rate in effect at that
time. This function returns a single derivative for each working
age s, evaluated at the rate in effect when the household retires
(period t + R - s), as an approximation.
Args:
w (array_like): real wage rate
e (Numpy array): effective labor units
per_rmn (int): number of periods remaining in the model
t (int): model period
j (int): index of lifetime income group
p (OG-Core Specifications object): model parameters
Returns:
d_theta: change in DB pension benefits for another unit of labor
supply
"""
# steady-state values of the pension periods
equiv_periods, equiv_yr_contrib, S_ret = (
int(a[-1, -1]) for a in pension_periods(p)
)
alpha_db = cohort_array("alpha_db", p, by_j=True)
if per_rmn < (p.S - S_ret + 1):
d_theta = np.zeros(p.S)
else:
# element s of the loop is a household of age S - per_rmn + s
# at time t, which retires in period t + S_ret - age
age = p.S - per_rmn + np.arange(per_rmn)
idx = np.clip(t + S_ret - age, 0, alpha_db.shape[0] - 1)
alpha_db_s = alpha_db[idx, S_ret, j]
d_theta = deriv_DB_loop(
w,
e,
p.S,
S_ret,
per_rmn,
equiv_periods,
alpha_db_s,
equiv_yr_contrib,
)
return d_theta
[docs]
def deriv_PS(w, e, per_rmn, factor, p):
r"""
Change in points system pension benefits for another unit of
labor supply
.. math::
\frac{\partial \theta_{j,u,t+u-s}}{\partial n_{j,s,t}} =
\begin{cases}
0 , & \text{if}\ s < R \\
w_{t}e_{j,s}v_{t}, & \text{if}\ s \geq R \\
\end{cases}
Args:
w (array_like): real wage rate
e (Numpy array): effective labor units
per_rmn (int): number of periods remaining in the model
factor (scalar): scaling factor converting model units to
p (OG-Core Specifications object): model parameters
Returns:
d_theta (Numpy array): change in points system pension benefits
for another unit of labor supply
"""
# Single retirement age for now (see Issue #1014)
S_ret = int(np.asarray(p.retire).flat[-1])
if per_rmn < (p.S - S_ret + 1):
d_theta = np.zeros(p.S)
else:
d_theta_empty = np.zeros(p.S)
d_theta = deriv_PS_loop(
w, e, p.S, S_ret, per_rmn, d_theta_empty, p.vpoint, factor
)
d_theta = d_theta[-per_rmn:]
return d_theta
# TODO: can probably assign these growth rates in the if statements in
# the pension_amount function
# TODO: create a parameter for pension growth rates -- a single param should do
[docs]
def delta_point(r, Y, g_n, g_y, p):
r"""
Compute growth rate used for contributions to points system pension
Args:
r (array_like): interest rate
Y (array_like): GDP
g_n (array_like): population growth rate
g_y (array_like): GDP growth rate
p (OG-Core Specifications object): model parameters
Returns:
delta_point (Numpy array): growth rate used for contributions to
points
"""
# TODO: Add option to allow use to enter growth rate amount
# Also to allow rate to vary by year
# Do this for all these growth rates for each system
# Might also allow for option to grow at per capital GDP growth rate
if p.points_growth_rate == "r":
delta_point = r
elif p.points_growth_rate == "Curr GDP":
delta_point = (Y[1:] - Y[:-1]) / Y[:-1]
elif p.points_growth_rate == "LR GDP":
delta_point = g_y + g_n
else:
delta_point = g_y + g_n
return delta_point
NDC_GROWTH_CHOICES = (
"r",
"Curr GDP",
"LR GDP",
"wage bill",
"avg wage",
"exogenous",
)
[docs]
class NDCRates(NamedTuple):
"""
Calendar paths of the rates used in a notional defined contribution
system, built by ``ndc_rates_path``.
Both fields are length T + S on the time path, or length 1 for a
steady state. Periods before the path read the first element and
periods after it the last.
"""
#: Numpy array: rate credited to notional balances in each model
#: period, the growth realized from the previous period (after any
#: averaging set by ``ndc_growth_avg_years``)
credit: np.ndarray
#: Numpy array: rate used to discount payments in the conversion
#: coefficient of a household retiring in each model period
discount: np.ndarray
def _ss_growth_rate(choice, r, p, exog=None):
"""
Steady-state value of an NDC growth rate.
Stationarized aggregates are constant in the steady state, so GDP
and the wage bill grow at the rate of productivity and population
growth, exp(g_y)(1 + g_n) - 1, and the average wage at the rate of
productivity growth, exp(g_y) - 1. An 'exogenous' rate takes the
last value of its path.
Args:
choice (str): one of ``NDC_GROWTH_CHOICES``
r (array_like): interest rate; its last element is used
p (OG-Core Specifications object): model parameters
exog (array_like or None): model-period rate path used when
choice is 'exogenous'
Returns:
rate (scalar): steady-state growth rate per model period
"""
g_y = float(np.asarray(p.g_y).flat[-1])
g_n_ss = float(getattr(p, "g_n_ss", np.asarray(p.g_n).flat[-1]))
if choice == "r":
return float(np.asarray(r).flat[-1])
elif choice in ("LR GDP", "Curr GDP", "wage bill"):
return np.exp(g_y) * (1.0 + g_n_ss) - 1.0
elif choice == "avg wage":
return np.exp(g_y) - 1.0
elif choice == "exogenous":
return float(_exog_path(exog).flat[-1])
raise ValueError(
f"NDC growth rate must be one of {NDC_GROWTH_CHOICES}, got {choice!r}"
)
def _exog_path(exog):
"""
Check and return the user-specified rate path for an 'exogenous'
NDC growth rate.
Args:
exog (array_like or None): model-period rate path
Returns:
exog (Numpy array): the path as a 1D float array
"""
if exog is None:
raise ValueError(
"An 'exogenous' NDC growth rate requires a rate path "
"(ndc_growth_rate_exog or dir_growth_rate_exog)"
)
return np.atleast_1d(np.asarray(exog, dtype=float)).ravel()
[docs]
def growth_rate_path(choice, r, Y, w, L, p, method, exog=None):
r"""
Calendar path of an NDC growth rate.
Element t is the growth realized from period t - 1 to period t,
in real, non-stationarized terms. Stationarized aggregates are
divided by $e^{g_y t}$ and by population, and ``p.g_n[t]`` is
population growth from t to t + 1, so for an aggregate X
.. math::
g_{t} = \frac{\hat{X}_{t}}{\hat{X}_{t-1}}e^{g_y}
(1 + g_{n,t-1}) - 1
where X is GDP for 'Curr GDP' and the wage bill wL for
'wage bill'. 'avg wage' is the growth of earnings per person,
the same expression without population growth. 'r' is the
interest rate path and 'LR GDP' the constant steady-state growth
of GDP. 'exogenous' is the user-specified path ``exog``, not tied
to any variable in the model. Growth into period 0 uses the
period-0 level as the level of the period before.
Args:
choice (str): one of ``NDC_GROWTH_CHOICES``
r (array_like): interest rate path
Y (array_like): GDP path, used for 'Curr GDP'
w (array_like): real wage path, used for 'wage bill' and
'avg wage'
L (array_like): aggregate labor path, used for 'wage bill' and
'avg wage'
p (OG-Core Specifications object): model parameters
method (str): 'SS' for the steady-state value or 'TPI' for the
time path
exog (array_like or None): model-period rate path used when
choice is 'exogenous' (``p.ndc_growth_rate_exog`` or
``p.dir_growth_rate_exog``)
Returns:
rate (Numpy array): length 1 in the steady state, else T + S
"""
if method == "SS" or choice == "LR GDP":
return np.array([_ss_growth_rate(choice, r, p, exog)])
n_per = p.T + p.S
def _extend(x):
# paths may stop at T; hold the last value
x = np.atleast_1d(np.asarray(x, dtype=float)).ravel()[:n_per]
return np.append(x, np.full(n_per - x.size, x[-1]))
if choice == "r":
return _extend(r)
if choice == "exogenous":
return _extend(_exog_path(exog))
if choice == "Curr GDP":
X = _extend(Y)
elif choice in ("wage bill", "avg wage"):
X = _extend(w) * _extend(L)
else:
raise ValueError(
f"NDC growth rate must be one of {NDC_GROWTH_CHOICES}, got "
f"{choice!r}"
)
g_y = float(np.asarray(p.g_y).flat[-1])
X_prev = np.append(X[0], X[:-1])
rate = X / X_prev * np.exp(g_y)
if choice == "wage bill" or choice == "Curr GDP":
g_n_ss = float(getattr(p, "g_n_ss", np.asarray(p.g_n).flat[-1]))
g_n_preTP = float(getattr(p, "g_n_preTP", g_n_ss))
# population growth from t - 1 to t
g_n_prev = np.append(g_n_preTP, _extend_pop(p.g_n, n_per, g_n_ss))
rate = rate * (1.0 + g_n_prev[:n_per])
return rate - 1.0
def _extend_pop(g_n, n_per, g_n_ss):
"""
Population growth path g_n[t] (growth from t to t + 1) for
t = 0, ..., n_per - 2, padded with the steady-state rate.
"""
g_n = np.atleast_1d(np.asarray(g_n, dtype=float)).ravel()[: n_per - 1]
return np.append(g_n, np.full(n_per - 1 - g_n.size, g_n_ss))
[docs]
def ndc_rates_path(r, Y, w, L, p, method):
"""
Credited return and annuity discount rate paths for an NDC system.
The credited return is ``ndc_growth_rate`` averaged over the
``ndc_growth_avg_years`` years up to and including each period
(periods before the path take the period-0 rate). The discount
rate is ``dir_growth_rate``; a household's conversion coefficient
uses its value in the period the household retires.
Args:
r (array_like): interest rate path (scalar in the steady state)
Y (array_like): GDP path
w (array_like): real wage path
L (array_like): aggregate labor path
p (OG-Core Specifications object): model parameters
method (str): 'SS' or 'TPI'
Returns:
rates (NDCRates): credit and discount rate paths
"""
credit = growth_rate_path(
p.ndc_growth_rate,
r,
Y,
w,
L,
p,
method,
getattr(p, "ndc_growth_rate_exog", None),
)
years = float(getattr(p, "ndc_growth_avg_years", 1))
window = max(1, int(np.rint(years * p.S / 80.0)))
if window > 1 and credit.size > 1:
padded = np.append(np.full(window - 1, credit[0]), credit)
credit = np.convolve(padded, np.ones(window) / window, "valid")
discount = growth_rate_path(
p.dir_growth_rate,
r,
Y,
w,
L,
p,
method,
getattr(p, "dir_growth_rate_exog", None),
)
return NDCRates(credit, discount)
[docs]
def g_ndc(r, Y, p):
"""
Steady-state growth rate credited to NDC balances.
Args:
r (array_like): interest rate; its last element is used
Y (array_like): GDP (unused: GDP growth in the steady state
follows from g_y and g_n)
p (OG-Core Specifications object): model parameters
Returns:
g_ndc (scalar): growth rate credited to NDC balances
"""
return _ss_growth_rate(
p.ndc_growth_rate, r, p, getattr(p, "ndc_growth_rate_exog", None)
)
[docs]
def g_dir(r, Y, p):
"""
Steady-state rate used to discount payments in the NDC conversion
coefficient.
Args:
r (array_like): interest rate; its last element is used
Y (array_like): GDP (unused: GDP growth in the steady state
follows from g_y and g_n)
p (OG-Core Specifications object): model parameters
Returns:
g_dir (scalar): discount rate in the conversion coefficient
"""
return _ss_growth_rate(
p.dir_growth_rate, r, p, getattr(p, "dir_growth_rate_exog", None)
)
[docs]
def annuity_mort_rates(p):
"""
Mortality rates by period and age used to annuitize NDC balances.
These are the model's mortality rates ``rho``, averaged over
lifetime income groups with their population weights ``lambdas``,
so that a single conversion coefficient applies to every income
group. A ``mort_rates_SS`` attribute set on ``p`` by hand (a vector
by age) overrides ``rho`` and is used in every period.
Args:
p (OG-Core Specifications object): model parameters
Returns:
mort_rates (Numpy array): (T + S) x S mortality rates, where
row t, column s is the probability that a household of age
s in period t dies before period t + 1
"""
mort_rates_SS = getattr(p, "mort_rates_SS", None)
if mort_rates_SS is not None:
mort_rates_SS = np.asarray(mort_rates_SS, dtype=float).ravel()
return np.broadcast_to(
mort_rates_SS, (p.T + p.S, mort_rates_SS.shape[0])
)
rho = np.asarray(p.rho, dtype=float)
if rho.ndim == 3:
rho = rho @ np.asarray(p.lambdas, dtype=float).ravel()
return np.broadcast_to(rho, (p.T + p.S, rho.shape[-1]))
[docs]
def delta_ret(
r, Y, p, S_ret=None, indR=None, k_ret=None, t_ret=None, g_dir_path=None
):
r"""
Compute conversion coefficient for the NDC pension amount
.. math::
\delta_{R} = (dir_{R} + ind_{R} - k)^{-1}
The mortality rates entering $dir_{R}$ are set by the parameter
``ndc_mortality``:
* 'steady state': the steady-state mortality rates, for every
cohort
* 'period': the mortality rates by age in the period in which the
household retires (a period life table)
* 'cohort': the mortality rates the household's own birth cohort
faces at each age after retirement (a projected cohort life
table), the rates that also enter the household's problem
Payments are discounted at ``dir_growth_rate``. Given a calendar
path of that rate (``g_dir_path``), each household uses its value
in the period it retires, held fixed over the payments; otherwise
the steady-state rate is used.
Args:
r (array_like): interest rate
Y (array_like): GDP
p (OG-Core Specifications object): model parameters
S_ret (array_like): model period of retirement; any shape, or
None for the steady-state value (the final row of
``retire``)
indR (array_like): survivor benefit adjustment, broadcastable
against ``S_ret``, or None for the steady-state value
k_ret (array_like): payment frequency adjustment, broadcastable
against ``S_ret``, or None for the steady-state value
t_ret (array_like): model period in which the household reaches
age ``S_ret``, broadcastable against ``S_ret``; may lie
before 0 or after T + S - 1, in which case the first or
last row of the mortality rates is used. None for the
steady state.
g_dir_path (array_like): calendar path of the discount rate
(``NDCRates.discount``), read at ``t_ret`` (clipped to the
path); None to use the steady-state rate
Returns:
delta_ret (scalar or Numpy array): conversion coefficient for
the NDC pension amount, shaped like ``S_ret``
"""
mort_rates = annuity_mort_rates(p)
n_rows, n_ages = mort_rates.shape
if S_ret is None:
S_ret = cohort_array("retire", p)[-1, -1]
if indR is None:
indR = cohort_array("indR", p)[-1, -1]
if k_ret is None:
k_ret = cohort_array("k_ret", p)[-1, -1]
S_ret = np.asarray(S_ret, dtype=int)
# discount rate of each household: the rate in its retirement period
if g_dir_path is None or t_ret is None:
g_dir_value = np.full(S_ret.shape, g_dir(r, Y, p))
else:
g_dir_path = np.atleast_1d(np.asarray(g_dir_path, dtype=float))
idx = np.clip(np.asarray(t_ret, dtype=int), 0, g_dir_path.size - 1)
g_dir_value = np.broadcast_to(g_dir_path[idx], S_ret.shape)
method = getattr(p, "ndc_mortality", "steady state")
if t_ret is None or method == "steady state":
t_ret = np.full(S_ret.shape, n_rows - 1)
elif method == "period":
t_ret = np.clip(np.asarray(t_ret, dtype=int), 0, n_rows - 1)
elif method == "cohort":
# a cohort retiring S periods or more before the path begins
# reads the first row at every age, and one retiring after it
# ends reads the last row
t_ret = np.clip(np.asarray(t_ret, dtype=int), -p.S, n_rows - 1)
else:
raise ValueError(
"ndc_mortality must be one of 'steady state', 'period', "
f"or 'cohort', got {method!r}"
)
t_ret = np.broadcast_to(t_ret, S_ret.shape)
# the annuity factor depends only on the retirement age, the
# mortality rates' period of retirement, and the discount rate, so
# compute it once per distinct combination
keys, inverse = np.unique(
np.stack(
[S_ret.ravel(), t_ret.ravel(), np.ravel(g_dir_value)], axis=1
),
axis=0,
return_inverse=True,
)
ages = np.arange(n_ages)
dir_delta_pairs = np.zeros(keys.shape[0])
for i, (R, tR, g) in enumerate(keys):
R, tR = int(R), int(tR)
if method == "cohort":
# age a is reached in period tR + a - R
rows = np.clip(tR - R + ages, 0, n_rows - 1)
else:
rows = np.full(n_ages, tR)
surv_rates = np.ascontiguousarray(1.0 - mort_rates[rows, ages])
dir_delta_pairs[i] = delta_ret_loop(p.S, R, surv_rates, g)
dir_delta = dir_delta_pairs[np.ravel(inverse)].reshape(S_ret.shape)
delta_ret = 1 / (dir_delta + np.asarray(indR) - np.asarray(k_ret))
if delta_ret.ndim == 0:
return float(delta_ret)
return delta_ret
[docs]
@numba.jit(nopython=True)
def deriv_DB_loop(
w, e, S, S_ret, per_rmn, avg_earn_num_years, alpha_db, yr_contr
):
"""
Change in DB pension benefits for another unit of labor supply
Args:
w (array_like): real wage rate
e (Numpy array): effective labor units
S (int): number of periods in the model
S_ret (int): retirement age
per_rmn (int): number of periods remaining in the model
avg_earn_num_years (int): number of years AIME is computed from
alpha_db (Numpy array): replacement rate for each of the
per_rmn remaining periods
yr_contr (scalar): years of contribution
Returns:
d_theta (Numpy array): change in DB pension benefits for
another unit of labor supply
"""
d_theta = np.zeros(per_rmn)
# print("Year contribution: ", yr_contr)
# print("Average earnings years: ", avg_earn_num_years)
num_per_retire = S - S_ret
for s in range(per_rmn):
d_theta[s] = (
w[s] * e[s] * alpha_db[s] * (yr_contr / avg_earn_num_years)
)
d_theta[-num_per_retire:] = 0.0
return d_theta
[docs]
@numba.jit(nopython=True)
def deriv_PS_loop(w, e, S, S_ret, per_rmn, d_theta, vpoint, factor):
"""
Change in points system pension benefits for another unit of
labor supply
Args:
w (array_like): real wage rate
e (Numpy array): effective labor units
S (int): number of periods in the model
S_ret (int): retirement age
per_rmn (int): number of periods remaining in the model
d_theta (Numpy array): change in points system pension benefits
for another unit of labor supply
vpoint (scalar): value of points
factor (scalar): scaling factor converting model units to
local currency
Returns:
d_theta (Numpy array): change in points system pension benefits
for another unit of labor supply
"""
# TODO: do we need these constants or can we scale vpoint to annual??
for s in range((S - per_rmn), S_ret):
d_theta[s] = (w[s] * e[s] * vpoint * MONTHS_IN_A_YEAR) / (
factor * THOUSAND
)
return d_theta
[docs]
@numba.jit(nopython=True)
def deriv_NDC_loop(
w, e, per_rmn, S, S_ret, tau_p, g_ndc_value, delta_ret_value, d_theta
):
r"""
Change in NDC pension benefits for another unit of labor supply
The benefit rises with labor supply at working age s by
.. math::
\tau^{p}w_{s}e_{s}(1 + g_{NDC})^{R - s}\delta_{R}
since a contribution at age s is credited in each period from
s + 1 through the retirement period R.
Args:
w (array_like): real wage rate
e (Numpy array): effective labor units
per_rmn (int): number of periods remaining in the model
S (int): number of periods in the model
S_ret (int): retirement age
tau_p (scalar): tax rate
g_ndc_value (scalar): growth rate of NDC pension
delta_ret_value (scalar): conversion coefficient for the NDC
pension amount
d_theta (Numpy array): change in NDC pension benefits for
another unit of labor supply
Returns:
d_theta (Numpy array): change in NDC pension benefits for
another unit of labor supply
"""
for s in range((S - per_rmn), S_ret):
d_theta[s - (S - per_rmn)] = (
tau_p
* w[s - (S - per_rmn)]
* e[s - (S - per_rmn)]
* delta_ret_value
* (1 + g_ndc_value) ** (S_ret - s)
)
return d_theta
[docs]
@numba.jit(nopython=True)
def delta_ret_loop(S, S_ret, surv_rates, g_dir_value):
r"""
Compute the annuity factor in the NDC conversion coefficient
.. math::
dir_{R} = \sum_{k=0}^{S-R-1}\left[\prod_{i=0}^{k-1}
(1 - \hat{\rho}_{R+i})\right](1 + g_{dir})^{-k}
The pension is paid at ages R, ..., S - 1. Following the household
mortality convention, ``1 - rho[s]`` is the probability of
surviving from age s to age s + 1, so the payment at age R + k is
received with probability prod_{i=0}^{k-1} (1 - rho[R + i]) by a
household alive at retirement age R.
Args:
S (int): number of periods in the model
S_ret (int): retirement age
surv_rates (Numpy array): length S survival rates by age,
1 - rho
g_dir_value (scalar): discount rate used in the conversion
coefficient
Returns:
dir_delta (scalar): expected discounted number of pension
payments per unit of annual benefit
"""
dir_delta = 0.0
cumul_surv = 1.0
discount = 1.0
for k in range(S - S_ret):
dir_delta += cumul_surv * discount
cumul_surv *= surv_rates[S_ret + k]
discount /= 1 + g_dir_value
return dir_delta
[docs]
@numba.jit(nopython=True)
def PS_1dim_loop(w, e, n, S_ret, S, g_y, vpoint, factor, L_inc_avg_s, PS):
"""
Calculate public pension from a points system.
Args:
w (array_like): real wage rate
e (Numpy array): effective labor units
n (Numpy array): labor supply
S_ret (int): retirement age
S (int): number of periods in the model
g_y (array_like): GDP growth rate
vpoint (scalar): value of points
factor (scalar): scaling factor converting model units to
local currency
L_inc_avg_s (Numpy array): average labor income
PS (Numpy array): pension amount for each household
Returns:
PS (Numpy array): pension amount for each household
"""
# TODO: do we need these constants or can we scale vpoint to annual??
for u in range(S_ret, S):
# TODO: allow for g_y to be time varying
for s in range(S_ret):
L_inc_avg_s[s] = w[s] / np.exp(g_y[-1] * (u - s)) * e[s] * n[s]
PS[u] = (MONTHS_IN_A_YEAR * vpoint * L_inc_avg_s.sum()) / (
factor * THOUSAND
)
return PS
[docs]
@numba.jit(nopython=True)
def PS_2dim_loop(w, e, n, S_ret, S, J, g_y, vpoint, factor, L_inc_avg_sj, PS):
"""
Calculate public pension from a points system.
Args:
w (array_like): real wage rate
e (Numpy array): effective labor units
n (Numpy array): labor supply
S_ret (int): retirement age
S (int): number of periods in the model
J (int): number of lifetime income groups
g_y (array_like): GDP growth rate
vpoint (scalar): value of points
factor (scalar): scaling factor converting model units to
local currency
L_inc_avg_sj (Numpy array): average labor income
PS (Numpy array): pension amount for each household
Returns:
PS (Numpy array): pension amount for each household
"""
# TODO: do we need these constants or can we scale vpoint to annual??
for u in range(S_ret, S):
for s in range(S_ret):
L_inc_avg_sj[s, :] = (
w[s] / np.exp(g_y * (u - s)) * e[s, :] * n[s, :]
)
PS[u, :] = (MONTHS_IN_A_YEAR * vpoint * L_inc_avg_sj.sum(axis=0)) / (
factor * THOUSAND
)
return PS
[docs]
@numba.jit(nopython=True)
def DB_1dim_loop(
w,
e,
n,
S_ret,
S,
g_y,
DB,
avg_earn_num_years,
alpha_db,
yr_contr,
earn_lo=None,
earn_hi=None,
t_birth=0,
):
"""
Calculate public pension from a defined benefits system for one
household over its lifetime.
Args:
w (array_like): real wage rate at each age, length S
e (Numpy array): effective labor units at each age, length S
n (Numpy array): labor supply at each age, length S
S_ret (Numpy array): retirement period that applies to the
household at each age u, length S
S (int): number of periods in the model
g_y (array_like): GDP growth rate
DB (Numpy array): pension amount for each household (filled in
and returned), length S
avg_earn_num_years (Numpy array): number of periods earnings
are averaged over, by age u, length S
alpha_db (Numpy array): replacement rate in effect at each age
u, length S
yr_contr (Numpy array): periods of contribution credited, by
age u, length S
earn_lo (Numpy array): lower cutoff, by model period and age, of
the earnings band, in model units of labor income; only
labor income w * e * n above it counts. None (the default)
applies no band.
earn_hi (Numpy array): upper cutoff, by model period and age, of
the earnings band; only labor income below it counts
t_birth (int): model period in which the household is age 0,
so earnings at age s were made in period t_birth + s
Returns:
DB (Numpy array): pension amount for each household
"""
for u in range(S):
R = S_ret[u]
if u < R:
continue
ny = avg_earn_num_years[u]
L_inc_avg = 0.0
for s in range(R - ny, R):
if earn_lo is None:
L_inc_avg += w[s] * e[s] * n[s] / np.exp(g_y[-1] * (u - s))
else:
x = earnings_band_at(
w[s] * e[s] * n[s], earn_lo, earn_hi, t_birth + s, s
)
L_inc_avg += x / np.exp(g_y[-1] * (u - s))
DB[u] = yr_contr[u] * alpha_db[u] * L_inc_avg / ny
return DB
[docs]
@numba.jit(nopython=True)
def DB_2dim_loop(
w,
e,
n,
S_ret,
S,
g_y,
DB,
avg_earn_num_years,
alpha_db,
yr_contr,
earn_lo=None,
earn_hi=None,
t_cross=0,
):
"""
Calculate public pension from a defined benefits system for a
cross section of S x J households in one period.
Args:
w (array_like): real wage rate, length S
e (Numpy array): effective labor units, size S x J
n (Numpy array): labor supply, size S x J
S_ret (Numpy array): retirement period of the household of
each age u, length S
S (int): number of periods in the model
g_y (array_like): GDP growth rate
DB (Numpy array): pension amount for each household (filled in
and returned), size S x J
avg_earn_num_years (Numpy array): number of periods earnings
are averaged over, by age u, length S
alpha_db (Numpy array): replacement rate in effect at each age
u for each group j, size S x J
yr_contr (Numpy array): periods of contribution credited, by
age u, length S
earn_lo (Numpy array): lower cutoff, by model period and age, of
the earnings band, in model units of labor income; only
labor income w * e * n above it counts. None (the default)
applies no band.
earn_hi (Numpy array): upper cutoff, by model period and age, of
the earnings band; only labor income below it counts
t_cross (int): model period of the cross section; the
household of age u earned at age s in period t_cross - u + s
Returns:
DB (Numpy array): pension amount for each household
"""
for u in range(S):
R = S_ret[u]
if u < R:
continue
ny = avg_earn_num_years[u]
L_inc_avg = np.zeros(DB.shape[1])
for s in range(R - ny, R):
if earn_lo is None:
L_inc_avg += (
w[s] * e[s, :] * n[s, :] / np.exp(g_y[-1] * (u - s))
)
else:
x = earnings_band_at(
w[s] * e[s, :] * n[s, :],
earn_lo,
earn_hi,
t_cross - u + s,
s,
)
L_inc_avg += x / np.exp(g_y[-1] * (u - s))
DB[u, :] = yr_contr[u] * alpha_db[u, :] * L_inc_avg / ny
return DB
[docs]
@numba.jit(nopython=True)
def DB_3dim_loop(
w_path,
e_ss,
n,
n_preTP,
S_ret,
S,
J,
g_y,
avg_earn_num_years,
alpha_db,
yr_contr,
earn_lo=None,
earn_hi=None,
):
r"""
Calculate public pension from a defined benefits system over the
full time path.
Used when the TPI solution evaluates taxes for all periods at once
to compute aggregates. Each retiree's benefit is computed from their
own cohort's wage and labor history: the wage entering the average
for a household aged u at time t, earned at age s, is the wage at
time t - (u - s). Histories that predate the time path use the
period-0 wage (trend growth is handled by the de-trending in the
benefit formula) and the model's initial labor supply, so this
reproduces exactly what the per-cohort household solves compute and
household behavior and aggregates are consistent. The pension
parameters are read at (t, u), the cell of the period-by-age arrays
that belongs to the retiree's own cohort. The inner work is
vectorized rather than looped.
Args:
w_path (Numpy array): real wage rate path, length T
e_ss (Numpy array): effective labor units, size SxJ
n (Numpy array): labor supply, size TxSxJ
n_preTP (Numpy array): pre-time-path labor supply, size SxJ
S_ret (Numpy array): retirement period by period and age,
size T x S
S (int): number of periods in the model
J (int): number of lifetime income groups
g_y (scalar): growth rate of technology
avg_earn_num_years (Numpy array): number of periods earnings
are averaged over, by period and age, size T x S
alpha_db (Numpy array): replacement rate per year of
contribution by period, age, and group, size T x S x J
yr_contr (Numpy array): periods of contribution credited, by
period and age, size T x S
earn_lo (Numpy array): lower cutoff, by model period and age, of
the earnings band, in model units of labor income; only
labor income w * e * n above it counts. None (the default)
applies no band.
earn_hi (Numpy array): upper cutoff, by model period and age, of
the earnings band; only labor income below it counts
Both arrays start in the period of the first row of n.
Returns:
DB (Numpy array): pension amount for each household, size TxSxJ
"""
T = n.shape[0]
DB = np.zeros((T, S, J))
for t in range(T):
for u in range(S):
R = S_ret[t, u]
if u < R:
continue
ny = avg_earn_num_years[t, u]
s_idx = np.arange(R - ny, R)
tau = t - (u - s_idx)
w_hist = w_path[np.clip(tau, 0, T - 1)]
n_hist = np.where(
(tau >= 0)[:, None],
n[np.clip(tau, 0, T - 1), s_idx, :],
n_preTP[s_idx, :],
)
x = e_ss[s_idx, :] * n_hist
if earn_lo is None:
L = (w_hist[:, None] / np.exp(g_y * (u - s_idx))[:, None]) * x
else:
# band of labor income, with the cutoffs in effect in
# the period of each earning
x = w_hist[:, None] * x
for i in range(ny):
x[i, :] = earnings_band_at(
x[i, :], earn_lo, earn_hi, tau[i], s_idx[i]
)
L = x / np.exp(g_y * (u - s_idx))[:, None]
DB[t, u, :] = (
(L.sum(axis=0) / ny) * yr_contr[t, u] * alpha_db[t, u, :]
)
return DB
[docs]
@numba.jit(nopython=True)
def NDC_1dim_loop(
w,
e,
n,
S_ret,
S,
g_y,
tau_p,
g_ndc,
t_birth,
delta_ret,
NDC,
earn_lo=None,
earn_hi=None,
):
r"""
Calculate public pension from a notional defined contribution
system for one household over its lifetime.
The contribution made at working age s earns the rate credited in
each later period through the retirement period R, in which the
first benefit is paid:
.. math::
\prod_{a=s+1}^{R}(1 + g_{NDC,t_0 + a})
where $t_0$ is the household's period of birth (age 0).
Args:
w (array_like): real wage rate at each age, length S
e (Numpy array): effective labor units at each age, length S
n (Numpy array): labor supply at each age, length S
S_ret (Numpy array): retirement period that applies to the
household at each age u, length S
S (int): number of periods in the model
g_y (array_like): GDP growth rate
tau_p (Numpy array): contribution rate the household faced at
each working age s, length S
g_ndc (Numpy array): calendar path of the credited rate
(``NDCRates.credit``), a 1-D float array; periods outside
it read the first or last element
t_birth (int): model period in which the household is age 0
delta_ret (Numpy array): conversion coefficient for the NDC
pension amount that applies at each age u, length S
NDC (Numpy array): pension amount for each household (filled
in and returned), length S
earn_lo (Numpy array): lower cutoff, by model period and age, of
the earnings band, in model units of labor income; only
labor income w * e * n above it counts. None (the default)
applies no band.
earn_hi (Numpy array): upper cutoff, by model period and age, of
the earnings band; only labor income below it counts
The cutoffs are read at period t_birth + s and age s.
Returns:
NDC (Numpy array): pension amount for each household
"""
# credited rate at each age of the household's life
g_age = g_ndc[np.clip(t_birth + np.arange(S), 0, g_ndc.size - 1)]
for u in range(S):
R = S_ret[u]
if u < R:
continue
NDC_s = 0.0
# the balance is credited through the retirement period R, in
# which the first benefit is paid
growth = 1.0 + g_age[R]
for s in range(R - 1, -1, -1):
# TODO: update so can take g_y from period t
if earn_lo is None:
x = e[s] * n[s]
NDC_s += (
tau_p[s] * (w[s] / np.exp(g_y[-1] * (u - s))) * x * growth
)
else:
x = earnings_band_at(
w[s] * e[s] * n[s], earn_lo, earn_hi, t_birth + s, s
)
NDC_s += tau_p[s] * (x / np.exp(g_y[-1] * (u - s))) * growth
growth *= 1.0 + g_age[s]
NDC[u] = delta_ret[u] * NDC_s
return NDC
[docs]
@numba.jit(nopython=True)
def NDC_2dim_loop(
w,
e,
n,
S_ret,
S,
g_y,
tau_p,
g_ndc,
t_cross,
delta_ret,
NDC,
earn_lo=None,
earn_hi=None,
):
"""
Calculate public pension from a notional defined contribution
system for a cross section of S x J households in one period.
As in ``NDC_1dim_loop``, contributions compound at the rates
credited in the periods the household lived through: the household
of age u in period ``t_cross`` was age s in period
t_cross - u + s.
Args:
w (array_like): real wage rate, length S
e (Numpy array): effective labor units, size S x J
n (Numpy array): labor supply, size S x J
S_ret (Numpy array): retirement period of the household of
each age u, length S
S (int): number of periods in the model
g_y (array_like): GDP growth rate
tau_p (Numpy array): contribution rate of the household of each
age s, length S
g_ndc (Numpy array): calendar path of the credited rate
t_cross (int): model period of the cross section
delta_ret (Numpy array): conversion coefficient for the NDC
pension amount of the household of each age u, length S
NDC (Numpy array): pension amount for each household (filled
in and returned), size S x J
earn_lo (Numpy array): lower cutoff, by model period and age, of
the earnings band, in model units of labor income; only
labor income w * e * n above it counts. None (the default)
applies no band.
earn_hi (Numpy array): upper cutoff, by model period and age, of
the earnings band; only labor income below it counts
The cutoffs are read at period t_cross - u + s and age s.
Returns:
NDC (Numpy array): pension amount for each household
"""
n_g = g_ndc.shape[0]
for u in range(S):
R = S_ret[u]
if u < R:
continue
NDC_s = np.zeros(NDC.shape[1])
# credited through the retirement period, t_cross - u + R
growth = 1.0 + g_ndc[min(max(t_cross - u + R, 0), n_g - 1)]
for s in range(R - 1, -1, -1):
if earn_lo is None:
x = e[s, :] * n[s, :]
NDC_s += (
tau_p[s] * (w[s] / np.exp(g_y[-1] * (u - s))) * x * growth
)
else:
x = earnings_band_at(
w[s] * e[s, :] * n[s, :],
earn_lo,
earn_hi,
t_cross - u + s,
s,
)
NDC_s += tau_p[s] * (x / np.exp(g_y[-1] * (u - s))) * growth
idx = min(max(t_cross - u + s, 0), n_g - 1)
growth *= 1.0 + g_ndc[idx]
NDC[u, :] = delta_ret[u] * NDC_s
return NDC
@numba.jit(nopython=True)
def NDC_3dim_loop(
w_path,
e_ss,
n,
n_preTP,
S_ret,
S,
J,
g_y,
tau_p,
g_ndc,
delta_ret,
earn_lo=None,
earn_hi=None,
):
r"""
Calculate public pension from a notional defined contribution
system over the full time path.
Used when the TPI solution evaluates taxes for all periods at once
to compute aggregates. As in ``DB_3dim_loop``, each retiree's
benefit is built from their own cohort's history: the contribution
at age s of a household aged u at time t was made in period
t - (u - s), at that period's wage, labor supply, and contribution
rate, and earns the rates credited in periods t - (u - s) + 1
through t - (u - R), the retirement period. Histories that predate
the time path use the period-0 wage, contribution rate, and
credited rate and the model's initial labor supply, so this
reproduces what the per-cohort household solves compute.
Args:
w_path (Numpy array): real wage rate path, length T
e_ss (Numpy array): effective labor units, size SxJ
n (Numpy array): labor supply, size TxSxJ
n_preTP (Numpy array): pre-time-path labor supply, size SxJ
S_ret (Numpy array): retirement period by period and age,
size T x S
S (int): number of periods in the model
J (int): number of lifetime income groups
g_y (scalar): growth rate of technology
tau_p (Numpy array): contribution rate by period and age,
size T x S
g_ndc (Numpy array): calendar path of the credited rate
delta_ret (Numpy array): conversion coefficient for the NDC
pension amount by period and age, size T x S
earn_lo (Numpy array): lower cutoff, by model period and age, of
the earnings band, in model units of labor income; only
labor income w * e * n above it counts. None (the default)
applies no band.
earn_hi (Numpy array): upper cutoff, by model period and age, of
the earnings band; only labor income below it counts
Both arrays start in the period of the first row of n.
Returns:
NDC (Numpy array): pension amount for each household, size
TxSxJ
"""
T = n.shape[0]
n_g = g_ndc.shape[0]
NDC = np.zeros((T, S, J))
for t in range(T):
for u in range(S):
R = S_ret[t, u]
if u < R:
continue
s_idx = np.arange(R)
tau = t - (u - s_idx)
rows = np.clip(tau, 0, T - 1)
w_hist = w_path[rows]
n_hist = np.where(
(tau >= 0)[:, None],
n[rows, s_idx, :],
n_preTP[s_idx, :],
)
contrib = np.zeros(R)
# credited through the retirement period, t - (u - R)
growth = 1.0 + g_ndc[min(max(t - (u - R), 0), n_g - 1)]
for i in range(R - 1, -1, -1):
s = s_idx[i]
if earn_lo is None:
contrib[i] = (
tau_p[rows[i], s]
* w_hist[i]
/ np.exp(g_y * (u - s))
* growth
)
else:
# the wage enters through the band of labor income
contrib[i] = (
tau_p[rows[i], s] / np.exp(g_y * (u - s)) * growth
)
idx = min(max(tau[i], 0), n_g - 1)
growth *= 1.0 + g_ndc[idx]
x = e_ss[s_idx, :] * n_hist
if earn_lo is not None:
# band of labor income, with the cutoffs in effect in
# the period of each contribution
x = w_hist[:, None] * x
for i in range(R):
x[i, :] = earnings_band_at(
x[i, :], earn_lo, earn_hi, tau[i], s_idx[i]
)
L = contrib[:, None] * x
NDC[t, u, :] = delta_ret[t, u] * L.sum(axis=0)
return NDC
# ---------------------------------------------------------------------
# Funded defined contribution (FDC) accounts
#
# The FDC pillar runs alongside whatever ``pension_system`` is chosen.
# Each household pays ``fdc_tau`` of the labor income in its earnings
# band into an individual account that earns the FDC return
# r_fdc = r_p - r_fdc_wedge, the household portfolio return r_p less
# the wedge ``r_fdc_wedge``. At retirement the balance buys an
# actuarially fair life annuity. The functions below compute one
# household's account over its lifetime from its labor income and the
# paths of r_fdc and mortality. They do not depend on any other
# pension system.
# ---------------------------------------------------------------------
[docs]
class FDCLifetime(NamedTuple):
"""
A household's funded defined contribution account over its life,
returned by ``fdc_lifetime``. Every field except ``R`` is a length
S array by age; entries before the first age computed are zero.
"""
#: Numpy array: contribution paid at each age, out of that
#: period's resources (zero from the retirement age on)
contrib: np.ndarray
#: Numpy array: account balance at the start of each age, after
#: the return credited in that period and before that period's
#: contribution or benefit
balance: np.ndarray
#: Numpy array: annuity benefit received at each age (zero before
#: the retirement age)
benefit: np.ndarray
#: Numpy array: end-of-period holdings at each age, the balance
#: plus the contribution before retirement and the balance less
#: the benefit after; these are the fund's assets
holdings: np.ndarray
#: Numpy array: derivative of the contribution with respect to
#: labor supply n at each age
dcontrib_dn: np.ndarray
#: Numpy array: benefit at the retirement age per unit of
#: contribution made at each earlier age; the benefit at a later
#: age u is that times e^{-g_y (u - R)}
benefit_per_contrib: np.ndarray
#: int: age at which the balance is annuitized (S if the household
#: does not reach retirement within its life)
R: int
[docs]
def fdc_earn_bands(p):
"""
Lower and upper cutoffs, by model period and age, of the labor
income on which funded defined contribution (FDC) contributions
are paid, in model units of labor income.
The lower cutoff is ``fdc_earn_floor_factor`` times
``avg_labor_inc_t1_model_units``. The upper cutoff is the cap
shared with the other defined contribution systems,
``dc_earn_cap_factor`` times ``avg_labor_inc_t1_model_units``,
when ``pension_earn_cap`` is True, and infinite otherwise. Under
the hybrid DB-FDC system (``pension_system`` 'Hybrid DB-FDC'), the
band is instead the one between the two cutoffs of
``pension_earn_caps``, as for the notional band of the hybrid
DB-NDC system, whatever ``fdc_earn_floor_factor`` and
``pension_earn_cap``. The
cutoff at period t and age s is the one that applies to the cohort
of that household; it applies to the labor income the household
earns in that period.
Args:
p (OG-Core Specifications object): model parameters
Returns:
lo, hi (Numpy arrays): the cutoffs as 2-D arrays by period and
age ((T + S) x S once ``Specifications`` builds them; a
factor set by hand as a single value or a path by period
gives one column, applied at every age)
"""
if getattr(p, "pension_system", None) == "Hybrid DB-FDC":
# the FDC band of the hybrid system lies between its two cutoffs
return tuple(np.ascontiguousarray(c) for c in hybrid_earn_cutoffs(p))
avg_inc = float(p.avg_labor_inc_t1_model_units)
lo = _period_age(getattr(p, "fdc_earn_floor_factor", 0.0)) * avg_inc
if getattr(p, "pension_earn_cap", False):
hi = _period_age(p.dc_earn_cap_factor) * avg_inc
else:
hi = np.full((1, 1), np.inf)
return np.ascontiguousarray(lo), np.ascontiguousarray(hi)
def _cohort_diag(arr, t_birth, S):
"""
Value of a 2-D array by period and age at each age of a household
born in period t_birth, read down the cohort's diagonal (the last
row in the steady state); an array with a single column applies at
every age.
"""
rows = _cohort_rows(t_birth, arr.shape[0], S)
cols = np.minimum(np.arange(S), arr.shape[1] - 1)
return np.ascontiguousarray(arr[rows, cols], dtype=float)
[docs]
def fdc_mort_rates(p, j):
"""
Mortality rates by period and age that price the FDC annuity of
lifetime income group j.
The annuity is priced on the mortality of the household's own
income group, so that the annuity pool of each group pays out
exactly what it holds when mortality differs across groups.
Args:
p (OG-Core Specifications object): model parameters
j (int): lifetime income group, or None for the average over
groups weighted by ``lambdas``
Returns:
mort_rates (Numpy array): (T + S) x S mortality rates, where
row t, column s is the probability that a household of age
s in period t dies before period t + 1
"""
rho = np.asarray(p.rho, dtype=float)
if rho.ndim == 3:
if j is None:
rho = rho @ np.asarray(p.lambdas, dtype=float).ravel()
else:
rho = rho[:, :, j]
elif rho.ndim == 2 and rho.shape == (p.S, p.J):
# by age and group, the same in every period
rho = rho[:, j] if j is not None else rho.mean(axis=1)
return np.broadcast_to(rho, (p.T + p.S, p.S))
[docs]
@numba.jit(nopython=True)
def fdc_annuity_factor_loop(S, a, rho, r):
r"""
Price, at age a, of an annuity-due paying one unit of real income
at each age from a to S - 1 while the household lives:
.. math::
\ddot{a}_{a} = 1 + \frac{1 - \rho_{a}}{1 + r_{fdc,a+1}}
\ddot{a}_{a+1}, \quad \ddot{a}_{S-1} = 1
The benefit is fixed in real terms, which in detrended model units
is a benefit that falls by e^{-g_y} each period while the balance
behind it is also detrended by e^{-g_y}, so trend growth does not
enter the price.
Args:
S (int): number of periods of life
a (int): age at which the annuity is bought
rho (Numpy array): mortality rate at each age of the household's
life, length S
r (Numpy array): FDC return r_fdc = r_p - r_fdc_wedge credited
at each age of the household's life (r[s] is earned on
holdings carried from age s - 1 to age s), length S
Returns:
ann (scalar): annuity factor
"""
ann = 1.0
for s in range(S - 2, a - 1, -1):
ann = 1.0 + (1.0 - rho[s]) * ann / (1.0 + r[s + 1])
return ann
[docs]
@numba.jit(nopython=True)
def fdc_lifetime_loop(y, tau, lo, hi, r, rho, R, g_y, a0, A0, S):
r"""
Funded defined contribution account of one household from age a0
to the end of life, in detrended model units.
Before the retirement age R the household contributes
$C_s = \tau_s(\min(\max(y_s, lo_s), hi_s) - lo_s)$ out of period
resources, and its end-of-period holdings $H_s = A_s + C_s$ earn
the next period's return:
.. math::
A_{s+1} = (1 + r_{fdc,s+1})e^{-g_y}H_s
The account therefore earns the return in every period from the
period after each contribution through the retirement period R
itself, the same window over which the notional defined
contribution system credits. At age $\max(R, a_0)$ the balance buys
an annuity, $P = A/\ddot{a}$; a household already retired at a0
holds a remaining balance that is re-annuitized on the rates given.
After that $H_s = A_s - P_s$, $P_{s+1} = P_s e^{-g_y}$, and the holdings
of those who die stay in the annuity pool:
.. math::
A_{s+1} = \frac{(1 + r_{fdc,s+1})e^{-g_y}}{1 - \rho_s}H_s
Args:
y (Numpy array): labor income w * e * n at each age, length S
tau (Numpy array): contribution rate at each age, length S
lo (Numpy array): lower cutoff of the earnings band at each age
hi (Numpy array): upper cutoff of the earnings band at each age
r (Numpy array): FDC return r_fdc = r_p - r_fdc_wedge credited
at each age (on holdings carried in from the previous age),
length S
rho (Numpy array): mortality rate at each age, length S
R (int): retirement age (S for none within the household's life)
g_y (scalar): growth rate of labor augmenting technology
a0 (int): first age computed
A0 (scalar): balance at the start of age a0
S (int): number of periods of life
Returns:
(tuple): length S arrays by age
* C (Numpy array): contribution
* A (Numpy array): balance at the start of the period
* P (Numpy array): annuity benefit
* H (Numpy array): end-of-period holdings
* dC (Numpy array): derivative of C with respect to y
* m (Numpy array): benefit at age R per unit of
contribution at each age before R
"""
C = np.zeros(S)
A = np.zeros(S)
P = np.zeros(S)
H = np.zeros(S)
dC = np.zeros(S)
m = np.zeros(S)
detrend = np.exp(-g_y)
A[a0] = A0
first_payment = max(R, a0)
for s in range(a0, S):
if s < R:
x = min(max(y[s], lo[s]), hi[s]) - lo[s]
C[s] = tau[s] * x
if y[s] > lo[s] and y[s] < hi[s]:
dC[s] = tau[s]
H[s] = A[s] + C[s]
else:
if s == first_payment:
P[s] = A[s] / fdc_annuity_factor_loop(S, s, rho, r)
else:
P[s] = P[s - 1] * detrend
H[s] = A[s] - P[s]
if s + 1 < S:
grow = (1.0 + r[s + 1]) * detrend
if s >= R:
grow /= 1.0 - rho[s]
A[s + 1] = grow * H[s]
if a0 < R and R < S:
# a unit contributed at age s < R grows to sum of returns
# through R and buys 1 / annuity factor of benefit at R
G = 1.0 / fdc_annuity_factor_loop(S, R, rho, r)
for s in range(R - 1, a0 - 1, -1):
G *= (1.0 + r[s + 1]) * detrend
m[s] = G
return C, A, P, H, dC, m
def _cohort_rows(t_birth, n_rows, S):
"""
Rows of a calendar-indexed array that a household born in period
t_birth reads at each age, clipped to the array. With t_birth None
(the steady state) every age reads the last row.
"""
if t_birth is None:
return np.full(S, n_rows - 1)
return np.clip(t_birth + np.arange(S), 0, n_rows - 1)
def _calendar_by_age(x, t_birth, S):
"""
Value of a scalar or a calendar path at each age of a household
born in period t_birth (the last element in the steady state).
"""
x = np.atleast_1d(np.asarray(x, dtype=float)).ravel()
return np.ascontiguousarray(x[_cohort_rows(t_birth, x.size, S)])
[docs]
def fdc_lifetime(w, e, n, r_p, t_birth, j, p, a0=0, A0=0.0, by_age=False):
"""
Funded defined contribution account of one household over its
lifetime: contributions, balances, annuity benefits, end-of-period
holdings, and the derivatives the household's labor decision needs.
The household is born (age 0) in model period t_birth and lives
age s in period t_birth + s. Calendar inputs (the wage, the return,
and the parameters) are read in the period each age is lived;
periods before or after the time path read its first or last
element. With t_birth None every calendar input reads its last
element, which gives the steady state.
The contribution rate ``fdc_tau`` and the retirement age are the
household's own cohort values (from ``pension_regimes``), the
earnings band cutoffs are those the cohort faces in the period the
income is earned, and the annuity is priced on the mortality of income
group j along the cohort's life and on the path of the FDC return
the household foresees. The account earns the FDC return
r_fdc = r_p - r_fdc_wedge at each age, where ``r_fdc_wedge`` is the
value the household's cohort faces in the period that age is lived.
Args:
w (scalar or array_like): wage, a single value or a calendar
path by model period
e (Numpy array): effective labor units at each age, length S
n (Numpy array): labor supply at each age, length S; ages
before a0 are ignored
r_p (scalar or array_like): household portfolio return, a
single value or a calendar path by model period; the
element for period t is the return earned in t on holdings
carried from t - 1; the account earns this less
``r_fdc_wedge``
t_birth (int or None): model period in which the household is
age 0, None for the steady state
j (int or None): lifetime income group, which sets the
mortality rates that price the annuity (None for the
lambda-weighted average)
p (OG-Core Specifications object): model parameters
a0 (int): first age computed, for a household already alive
when the time path begins
A0 (scalar): account balance at the start of age a0; a
household already retired at a0 annuitizes this remaining
balance on the rates given
by_age (bool): if True, ``w`` and ``r_p`` are length S arrays
already indexed by the household's age (entries before a0
are ignored) rather than calendar paths; the parameters
are still read in the periods given by t_birth
Returns:
FDCLifetime: the account by age
"""
S = p.S
e = np.ascontiguousarray(np.asarray(e, dtype=float).ravel())
n = np.ascontiguousarray(np.asarray(n, dtype=float).ravel())
if by_age:
w_age = np.ascontiguousarray(np.asarray(w, dtype=float).ravel())
r_age = np.ascontiguousarray(np.asarray(r_p, dtype=float).ravel())
else:
w_age = _calendar_by_age(w, t_birth, S)
r_age = _calendar_by_age(r_p, t_birth, S)
ages = np.arange(S)
# FDC return r_fdc = r_p - r_fdc_wedge, with the wedge the
# household's cohort faces at each age
wedge_arr = fdc_wedge_path(p)
r_age = np.ascontiguousarray(
r_age - wedge_arr[_cohort_rows(t_birth, wedge_arr.shape[0], S), ages]
)
lo, hi = fdc_earn_bands(p)
lo_age = _cohort_diag(lo, t_birth, S)
hi_age = _cohort_diag(hi, t_birth, S)
tau_arr = cohort_array("fdc_tau", p)
rows = _cohort_rows(t_birth, tau_arr.shape[0], S)
tau_age = np.ascontiguousarray(tau_arr[rows, ages])
retire_arr = cohort_array("retire", p)
retire_age = retire_arr[
_cohort_rows(t_birth, retire_arr.shape[0], S), ages
].astype(int)
retired = ages >= retire_age
R = int(np.argmax(retired)) if retired.any() else S
mort = fdc_mort_rates(p, j)
rho_age = np.ascontiguousarray(
mort[_cohort_rows(t_birth, mort.shape[0], S), ages]
)
y = np.ascontiguousarray(w_age * e * n)
C, A, P, H, dC, m = fdc_lifetime_loop(
y,
tau_age,
lo_age,
hi_age,
r_age,
rho_age,
R,
float(np.squeeze(p.g_y)),
int(a0),
float(A0),
S,
)
return FDCLifetime(C, A, P, H, dC * w_age * e, m, R)
[docs]
def fdc_ss(r_p, w, e, n, p):
"""
Steady-state funded defined contribution accounts of every lifetime
income group.
Args:
r_p (scalar): steady-state household portfolio return; the
accounts earn r_fdc = r_p - r_fdc_wedge
w (scalar): steady-state wage
e (Numpy array): effective labor units, S x J
n (Numpy array): labor supply, S x J
p (OG-Core Specifications object): model parameters
Returns:
FDCLifetime: each array field S x J, and ``R`` the steady-state
retirement age
"""
e = np.asarray(e, dtype=float).reshape(p.S, -1)
n = np.asarray(n, dtype=float).reshape(p.S, -1)
J = n.shape[1]
if e.shape[1] != J:
e = np.broadcast_to(e[:, :1], (p.S, J))
out = [
fdc_lifetime(w, e[:, j], n[:, j], r_p, None, j, p) for j in range(J)
]
fields = {
name: np.stack([getattr(o, name) for o in out], axis=1)
for name in FDCLifetime._fields
if name != "R"
}
return FDCLifetime(R=out[0].R, **fields)
[docs]
def fdc_holdings(fdc):
"""
End-of-period holdings of funded defined contribution accounts,
the fund's assets, by age (and group).
Args:
fdc (FDCLifetime or None): the accounts, None when the pillar
is off
Returns:
H (Numpy array or scalar): holdings, or 0.0 when the
pillar is off
"""
if fdc is None:
return 0.0
return fdc.holdings
[docs]
def fdc_wedge_path(p):
"""
Wedge ``r_fdc_wedge`` between the portfolio return r_p and the FDC
return r_fdc by model period and age: element [t, s] is the wedge
on the return earned in period t at age s, by the household of
that age's cohort. ``fdc_lifetime`` reads a cohort's values down
the diagonal; periods after the array read its last row, the
steady state.
Args:
p (OG-Core Specifications object): model parameters
Returns:
wedge (Numpy array): wedge by period and age, (T + S) x S (a
single row of zeros if the parameter is absent)
"""
if not hasattr(p, "r_fdc_wedge"):
return np.zeros((1, p.S))
wedge_arr = np.asarray(cohort_array("r_fdc_wedge", p), dtype=float)
return wedge_arr.reshape(wedge_arr.shape[0], -1)[:, : p.S]
[docs]
def fdc_wedge_ss(p):
"""
Steady-state wedge ``r_fdc_wedge`` between the portfolio return
r_p and the FDC return r_fdc at each age, the value
``fdc_lifetime`` uses for a household with t_birth None (the last
row of ``fdc_wedge_path``).
Args:
p (OG-Core Specifications object): model parameters
Returns:
wedge (Numpy array): wedge at each age, length S (zeros if the
parameter is absent)
"""
return fdc_wedge_path(p)[-1, :]
[docs]
def fdc_bequeathable(fdc, r_p, p):
"""
End-of-period holdings that go to bequests if the household dies
before the next period: the account holdings at ages before the
retirement age. After retirement the holdings of those who die
stay in the annuity pool.
The account of a member who dies is credited the FDC return
r_fdc = r_p - r_fdc_wedge, like the account of a survivor, and the
fund keeps the spread. Because ``aggregates.get_BQ`` multiplies the
savings it is given by (1 + r_p), the holdings are scaled here by
(1 + r_fdc) / (1 + r_p), with r_fdc the return at the next age.
They are also returned in the next period's detrended units,
e^{-g_y} times the holdings, the units of the private savings
b_{s+1} they are added to.
Args:
fdc (FDCLifetime or None): the accounts, None when the pillar
is off
r_p (scalar): steady-state household portfolio return
p (OG-Core Specifications object): model parameters
Returns:
H_bq (Numpy array or scalar): holdings at ages before
the retirement age and zero after, in next-period units, or
0.0 when the pillar is off
"""
if fdc is None:
return 0.0
H = fdc.holdings
shape = (-1,) + (1,) * (H.ndim - 1)
ages = np.arange(H.shape[0]).reshape(shape)
r_p = float(np.squeeze(r_p))
wedge_next = np.append(fdc_wedge_ss(p)[1:], 0.0).reshape(shape)
scale = (1.0 + r_p - wedge_next) / (1.0 + r_p)
return np.where(ages < fdc.R, H * scale, 0.0) * np.exp(-p.g_y)
[docs]
def fdc_bequeathable_tpi(bq, r_p, p):
"""
Time-path counterpart of ``fdc_bequeathable``: scales the funded
defined contribution holdings bequeathed in each period so that the
accounts of members who die are credited the FDC return
r_fdc = r_p - r_fdc_wedge, like those of survivors, and the fund
keeps the spread. ``aggregates.get_BQ`` multiplies the holdings
it is given for period t by (1 + r_{p,t}), so the holdings carried
out of age s are scaled by (1 + r_{p,t} - w_{t,s+1}) / (1 + r_{p,t}),
with w_{t,s+1} the wedge on the return of age s + 1 in period t.
Args:
bq (Numpy array): holdings bequeathed in periods 0 to T - 1,
T x S x J, in each period's units (row 0 from
``p.fdc_bequeathable_preTP`` and the rest from
``FDCPath.bequeathable``)
r_p (Numpy array): household portfolio return in periods 0 to
T - 1
p (OG-Core Specifications object): model parameters
Returns:
bq_fdc (Numpy array): the scaled holdings, T x S x J
"""
T = bq.shape[0]
r_p = np.asarray(r_p, dtype=float).ravel()[:T].reshape(T, 1)
wedge_arr = fdc_wedge_path(p)
rows = np.minimum(np.arange(T), wedge_arr.shape[0] - 1)
wedge_next = np.append(wedge_arr[rows, 1:], np.zeros((T, 1)), axis=1)
scale = (1.0 + r_p - wedge_next) / (1.0 + r_p)
return bq * scale[:, :, None]
[docs]
def fdc_survivor_claims(fdc, rho, p):
r"""
Funded defined contribution holdings per survivor, carried into the
next period before its return: the end-of-period holdings before
the retirement age, and the holdings divided by the survival rate
after it, when the holdings of those who die are shared among the
survivors of the annuity pool.
Immigrants are taken to arrive with the same assets as the natives
of their age, so this is what an immigrant brings into the fund
(the counterpart of the private savings b that ``get_B`` credits
to immigrants). Like b_{s+1}, the claims are in the next period's
detrended units, e^{-g_y} times the holdings.
Args:
fdc (FDCLifetime or None): the accounts, None when the pillar
is off
rho (Numpy array): mortality rates, shaped like the holdings
p (OG-Core Specifications object): model parameters
Returns:
H_claims (Numpy array or scalar): holdings per survivor in
next-period units, or 0.0 when the pillar is off
"""
if fdc is None:
return 0.0
H = fdc.holdings
ages = np.arange(H.shape[0]).reshape((-1,) + (1,) * (H.ndim - 1))
surv = 1.0 - np.asarray(rho, dtype=float)
pooled = np.divide(H, surv, out=np.zeros_like(H), where=surv > 0)
return np.where(ages >= fdc.R, pooled, H) * np.exp(-p.g_y)
[docs]
class FDCPath(NamedTuple):
"""
Funded defined contribution accounts of every household along the
time path, returned by ``fdc_tpi``. Every field is a T x S x J
array indexed by model period, age, and lifetime income group.
"""
#: Numpy array: contribution paid
contrib: np.ndarray
#: Numpy array: annuity benefit received
benefit: np.ndarray
#: Numpy array: end-of-period holdings, in the period's units
holdings: np.ndarray
#: Numpy array: holdings per survivor carried into the next period,
#: in the next period's units (``fdc_survivor_claims``)
claims: np.ndarray
#: Numpy array: holdings bequeathed if the household dies before
#: the next period, in the next period's units, before
#: ``fdc_bequeathable_tpi`` credits them the FDC return
bequeathable: np.ndarray
[docs]
def fdc_initial_holdings(ss, p):
"""
Funded defined contribution holdings of the households alive when
the time path begins, from the baseline steady state, in the units
of the first model period.
The steady-state end-of-period holdings by age are scaled by
``scale`` (the same population adjustment applied to initial
private savings) and carried into period 0 with the mortality rates
of the period before the time path (``rho_preTP``).
Args:
ss (dict): baseline steady-state output; the holdings are zero
if it has no FDC output (the pillar off, or output saved
before the pillar existed)
p (OG-Core Specifications object): model parameters
Returns:
(tuple): S x J arrays
* holdings (Numpy array): end-of-period holdings in the
period before the time path, in that period's units
* claims (Numpy array): holdings per survivor carried into
period 0, in period-0 units
* bequeathable (Numpy array): holdings bequeathed in period
0 by those who die before it, in period-0 units
"""
zeros = np.zeros((p.S, p.J))
H = np.asarray(ss.get("fdc_holdings", zeros), dtype=float)
if H.shape != (p.S, p.J) or not np.any(H):
return zeros, zeros.copy(), zeros.copy()
R = int(ss.get("fdc_R", p.S))
ages = np.arange(p.S)[:, None]
surv = 1.0 - np.asarray(p.rho_preTP, dtype=float).reshape(p.S, -1)
surv = np.broadcast_to(surv, (p.S, p.J))
carried = H * np.exp(-p.g_y)
pooled = np.divide(
carried, surv, out=np.zeros_like(carried), where=surv > 0
)
claims = np.where(ages >= R, pooled, carried)
bequeathable = np.where(ages < R, carried, 0.0)
return H, claims, bequeathable
[docs]
def fdc_tpi(r_p, w, n_mat, p):
"""
Funded defined contribution accounts of every household along the
time path, cohort by cohort.
Each cohort's account is computed with ``fdc_lifetime`` along its
diagonal of ``n_mat``, from the r_p and wage paths it foresees.
Households alive when the path begins start from the claims of
their age in ``p.fdc_claims_preTP`` (set by
``TPI.get_initial_SS_values``), credited with the period-0 FDC
return r_fdc = r_p - r_fdc_wedge;
those already retired re-annuitize those balances on the path.
Args:
r_p (Numpy array): household portfolio return, length T + S
w (Numpy array): wage, length T + S
n_mat (Numpy array): labor supply, (T + S) x S x J
p (OG-Core Specifications object): model parameters
Returns:
FDCPath: the accounts by period, age, and income group
"""
from ogcore.household import _get_e_long
T, S = p.T, p.S
J = n_mat.shape[2]
r_p = np.asarray(r_p, dtype=float).ravel()
w = np.asarray(w, dtype=float).ravel()
e_long = _get_e_long(p)
wedge_arr = fdc_wedge_path(p)
claims0 = getattr(p, "fdc_claims_preTP", None)
if claims0 is None:
claims0 = np.zeros((S, J))
out = {
name: np.zeros((T, S, J))
for name in ("contrib", "benefit", "holdings", "claims", "bq")
}
g = float(np.squeeze(p.g_y))
ages = np.arange(S)
n_rows = n_mat.shape[0]
for j in range(J):
mort = fdc_mort_rates(p, j)
for tb in range(-(S - 1), T):
a0 = max(-tb, 0)
rows = tb + ages[a0:]
keep = rows < T
if not np.any(keep):
continue
n_full = np.zeros(S)
e_full = np.zeros(S)
n_full[a0:] = n_mat[np.minimum(rows, n_rows - 1), ages[a0:], j]
e_full[a0:] = e_long[
np.minimum(rows, e_long.shape[0] - 1), ages[a0:], j
]
# balances carried into period 0 earn the period-0 FDC
# return r_fdc = r_p - r_fdc_wedge of their age
A0 = (
(1.0 + r_p[0] - wedge_arr[0, a0]) * claims0[a0 - 1, j]
if a0 > 0
else 0.0
)
acct = fdc_lifetime(w, e_full, n_full, r_p, tb, j, p, a0=a0, A0=A0)
r_idx, s_idx = rows[keep], ages[a0:][keep]
out["contrib"][r_idx, s_idx, j] = acct.contrib[s_idx]
out["benefit"][r_idx, s_idx, j] = acct.benefit[s_idx]
H = acct.holdings[s_idx]
out["holdings"][r_idx, s_idx, j] = H
carried = H * np.exp(-g)
retired = s_idx >= acct.R
surv = 1.0 - mort[r_idx, s_idx]
pooled = np.divide(
carried, surv, out=np.zeros_like(carried), where=surv > 0
)
out["claims"][r_idx, s_idx, j] = np.where(retired, pooled, carried)
out["bq"][r_idx, s_idx, j] = np.where(retired, 0.0, carried)
return FDCPath(
out["contrib"],
out["benefit"],
out["holdings"],
out["claims"],
out["bq"],
)