Repository navigation
[ENH] Accept Series and Triangles in DevelopmentConstant patterns #1484
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
priyam0k
wants to merge
2
commits into
main
Choose a base branch
from
feature/issue-1483-development-constant-patterns
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,10 @@ | ||
| # This Source Code Form is subject to the terms of the Mozilla Public | ||
| # License, v. 2.0. If a copy of the MPL was not distributed with this | ||
| # file, You can obtain one at https://mozilla.org/MPL/2.0/. | ||
| from __future__ import annotations | ||
|
|
||
| from typing import Any, Literal | ||
|
|
||
| from chainladder.development.base import DevelopmentBase | ||
| import numpy as np | ||
| import pandas as pd | ||
|
|
@@ -14,9 +18,12 @@ class DevelopmentConstant(DevelopmentBase): | |
|
|
||
| Parameters | ||
| ---------- | ||
| patterns: dict or callable | ||
| A dictionary key:value representation of age(in months):value. If callable | ||
| is supplied, callable must return a dict for each element of the callable axis | ||
| patterns: dict, Series, DataFrame, Triangle, estimator, or callable | ||
| A representation of development factors indexed by age (in months). Can be | ||
| a dictionary of age:value, a pandas Series, a 1-row or 1-column DataFrame, | ||
| a 1D Triangle pattern (such as another estimator's ``ldf_`` or ``cdf_``), | ||
| or a fitted estimator. If callable is supplied, callable must return a dict | ||
| for each element of the callable axis. | ||
| style: Literal['cdf', 'ldf'], optional (default='ldf') | ||
| Type of pattern given to the Estimator. `cdf` for cumulative development factors | ||
| and `ldf` for (non-cumulative) loss development factors. | ||
|
|
@@ -107,7 +114,13 @@ class DevelopmentConstant(DevelopmentBase): | |
|
|
||
| """ | ||
|
|
||
| def __init__(self, patterns=None, style="ldf", callable_axis=0, groupby=None): | ||
| def __init__( | ||
| self, | ||
| patterns: Any = None, | ||
| style: Literal["cdf", "ldf"] = "ldf", | ||
| callable_axis: int = 0, | ||
| groupby: Any = None, | ||
| ): | ||
| self.patterns = patterns | ||
| self.style = style | ||
| self.callable_axis = callable_axis | ||
|
|
@@ -152,9 +165,11 @@ def fit(self, X, y=None, sample_weight=None): | |
| raise ValueError("callable axis needs to be 0 or 1") | ||
| pattern_length = len(sample_pattern) | ||
| pattern_ddims = sorted(sample_pattern.keys()) | ||
| patterns_dict = None | ||
| else: | ||
| pattern_length = len(self.patterns) | ||
| pattern_ddims = sorted(self.patterns.keys()) | ||
| patterns_dict = self._normalize_patterns(self.patterns, self.style) | ||
| pattern_length = len(patterns_dict) | ||
| pattern_ddims = sorted(patterns_dict.keys()) | ||
|
|
||
| # pattern supplied is much shorter than the triangle | ||
| if pattern_length < len(obj.ddims) - 1: | ||
|
|
@@ -198,7 +213,7 @@ def fit(self, X, y=None, sample_weight=None): | |
| else: | ||
| raise ValueError("callable axis needs to be 0 or 1") | ||
| else: | ||
| ldf = xp.array([self.patterns.get(item, 1.0) for item in obj.ddims]) | ||
| ldf = xp.array([patterns_dict.get(item, 1.0) for item in obj.ddims]) | ||
| ldf = ldf[None, None, None, :] | ||
|
|
||
| if self.style == "cdf": | ||
|
|
@@ -213,6 +228,55 @@ def fit(self, X, y=None, sample_weight=None): | |
| self.ldf_.valuation_date = pd.to_datetime(options.ULT_VAL) | ||
| return self | ||
|
|
||
| @staticmethod | ||
| def _normalize_patterns(patterns, style="ldf"): | ||
| """Normalize pattern input (dict, Series, DataFrame, Triangle, estimator) into a dict.""" | ||
| if hasattr(patterns, "cdf_") and style == "cdf": | ||
| patterns = patterns.cdf_ | ||
| elif hasattr(patterns, "ldf_") and style == "ldf": | ||
| patterns = patterns.ldf_ | ||
| elif hasattr(patterns, "cdf_") and not hasattr(patterns, "ldf_"): | ||
| patterns = patterns.cdf_ | ||
| elif hasattr(patterns, "ldf_") and not hasattr(patterns, "cdf_"): | ||
| patterns = patterns.ldf_ | ||
|
|
||
| if hasattr(patterns, "values") and hasattr(patterns, "ddims"): | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. a transformed triangle may have |
||
| if ( | ||
| hasattr(patterns, "shape") | ||
| and len(patterns.shape) >= 3 | ||
| and patterns.shape[2] > 1 | ||
| ): | ||
| raise ValueError( | ||
| "Triangle pattern must have a single origin row (e.g. model.ldf_ or model.cdf_)." | ||
| ) | ||
| vals = patterns.values[0, 0, 0, :] | ||
| s = pd.Series(vals, index=patterns.ddims, dtype=float) | ||
| elif isinstance(patterns, pd.DataFrame): | ||
| if patterns.shape[0] == 1: | ||
| s = patterns.iloc[0].astype(float) | ||
| elif patterns.shape[1] == 1: | ||
| s = patterns.iloc[:, 0].astype(float) | ||
| else: | ||
| raise ValueError("DataFrame pattern must have 1 row or 1 column.") | ||
| elif isinstance(patterns, pd.Series): | ||
| s = patterns.astype(float).copy() | ||
| elif isinstance(patterns, dict): | ||
| s = pd.Series(patterns, dtype=float) | ||
| else: | ||
| raise TypeError( | ||
| f"Unsupported pattern type: {type(patterns)}. " | ||
| f"Expected dict, Series, DataFrame, Triangle, estimator, or callable." | ||
| ) | ||
|
|
||
| parsed_index = [] | ||
| for x in s.index: | ||
| try: | ||
| parsed_index.append(int(str(x).split("-")[0])) | ||
| except (ValueError, TypeError): | ||
| parsed_index.append(x) | ||
| s.index = parsed_index | ||
| return s.to_dict() | ||
|
|
||
| def transform(self, X): | ||
| """ | ||
| If X and self are of different shapes, align self to X, else | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
this is a neat convenience feature. could you please either document it in the docstring or throw a warning?