From e46dc0b063e118d05a106e9fb962c5bf3c4465dd Mon Sep 17 00:00:00 2001 From: hutch3232 Date: Tue, 20 Jan 2026 22:10:57 -0500 Subject: [PATCH] rm all bare excepts and trailing whitespace --- chainladder/adjustments/bootstrap.py | 2 +- .../adjustments/tests/test_berqsherm.py | 2 +- chainladder/core/base.py | 8 ++--- chainladder/core/display.py | 2 +- chainladder/core/dunders.py | 22 ++++++------- chainladder/core/pandas.py | 2 +- chainladder/core/slice.py | 2 +- chainladder/core/tests/rtest_correlation.py | 4 +-- chainladder/core/tests/test_correlation.py | 2 +- chainladder/core/tests/test_display.py | 4 +-- chainladder/core/tests/test_triangle.py | 32 +++++++++---------- chainladder/core/triangle.py | 14 ++++---- chainladder/development/incremental.py | 6 ++-- chainladder/development/learning.py | 8 ++--- chainladder/development/tests/rtest_clark.py | 4 +-- .../development/tests/rtest_development.py | 4 +-- chainladder/development/tests/rtest_munich.py | 6 ++-- .../development/tests/test_barnzehn.py | 6 ++-- .../development/tests/test_development.py | 4 +-- chainladder/development/tests/test_glm.py | 4 +-- .../development/tests/test_learning.py | 2 +- chainladder/methods/base.py | 2 +- chainladder/methods/capecod.py | 2 +- chainladder/methods/chainladder.py | 4 +-- chainladder/methods/tests/rtest_mack.py | 6 ++-- chainladder/methods/tests/test_benktander.py | 2 +- chainladder/methods/tests/test_capecod.py | 12 +++---- chainladder/methods/tests/test_mack.py | 4 +-- chainladder/methods/tests/test_predict.py | 4 +-- chainladder/tails/tests/rtest_exponential.py | 4 +-- chainladder/utils/cupy.py | 2 +- chainladder/utils/dask.py | 2 +- chainladder/utils/tests/test_utilities.py | 4 +-- chainladder/utils/utility_functions.py | 8 ++--- chainladder/workflow/gridsearch.py | 2 +- docs/gallery/plot_ave_analysis.ipynb | 4 +-- docs/gallery/plot_benktander.ipynb | 10 +++--- docs/gallery/plot_berqsherm_case.ipynb | 2 +- docs/gallery/plot_bf_apriori_from_cl.ipynb | 2 +- docs/gallery/plot_bootstrap.ipynb | 2 +- docs/gallery/plot_bootstrap_comparison.ipynb | 4 +-- docs/gallery/plot_capecod_onlevel.ipynb | 2 +- docs/gallery/plot_elrf_resid.ipynb | 4 +-- docs/gallery/plot_ptf_resid.ipynb | 2 +- docs/gallery/plot_stochastic_bornferg.ipynb | 2 +- docs/gallery/plot_triangle_slicing.ipynb | 2 +- docs/gallery/plot_voting_chainladder.ipynb | 2 +- .../sandbox_workbook_filled.ipynb | 2 +- docs/user_guide/development.ipynb | 12 +++---- docs/user_guide/methods.ipynb | 6 ++-- docs/user_guide/tails.ipynb | 14 ++++---- docs/user_guide/triangle.ipynb | 4 +-- docs/user_guide/workflow.ipynb | 6 ++-- 53 files changed, 140 insertions(+), 140 deletions(-) diff --git a/chainladder/adjustments/bootstrap.py b/chainladder/adjustments/bootstrap.py index 1ad6b096..cc9ab920 100644 --- a/chainladder/adjustments/bootstrap.py +++ b/chainladder/adjustments/bootstrap.py @@ -108,7 +108,7 @@ def fit(self, X, y=None, sample_weight=None): if self.hat_adj: try: self.hat_ = self._get_hat(X, exp_incr_triangle) - except: + except Exception: warn("Could not compute hat matrix. Setting hat_adj to False") self.had_adj = False self.hat_ = None diff --git a/chainladder/adjustments/tests/test_berqsherm.py b/chainladder/adjustments/tests/test_berqsherm.py index e42bd6c9..e220a369 100644 --- a/chainladder/adjustments/tests/test_berqsherm.py +++ b/chainladder/adjustments/tests/test_berqsherm.py @@ -40,4 +40,4 @@ def test_adjusted_values(): berq_triangle["Incurred"].values.sum(), 1126985253.661, atol=1e-2 ) assert np.isclose(berq_triangle["Paid"].values.sum(), 182046766.054, atol=1e-2) - assert np.isclose(berq_triangle["Closed"].values.sum(), 8798.982, atol=1e-2) \ No newline at end of file + assert np.isclose(berq_triangle["Closed"].values.sum(), 8798.982, atol=1e-2) diff --git a/chainladder/core/base.py b/chainladder/core/base.py index e50bb7f2..2a15948d 100644 --- a/chainladder/core/base.py +++ b/chainladder/core/base.py @@ -290,24 +290,24 @@ def _get_date_axes( end=origin_date.max(), freq=origin_grain ).to_timestamp(how="s") - + development_range: DatetimeIndex = pd.period_range( start=development_date.min(), end=development_date.max(), freq=development_grain, ).to_timestamp(how="e") - + # If the development is semi-annual, we need to adjust further because of "2Q-DEC". if development_grain[:2] == "2Q": from pandas.tseries.offsets import DateOffset development_range += DateOffset(months=-3) - + c = pd.DataFrame( TriangleBase._cartesian_product(origin_range, development_range), columns=["__origin__", "__development__"], ) - + return c[c["__development__"] > c["__origin__"]] @property diff --git a/chainladder/core/display.py b/chainladder/core/display.py index d94cbbba..ce34b323 100644 --- a/chainladder/core/display.py +++ b/chainladder/core/display.py @@ -239,4 +239,4 @@ def _dimensionality(self) -> str: return 'single' else : - return 'multi' \ No newline at end of file + return 'multi' diff --git a/chainladder/core/dunders.py b/chainladder/core/dunders.py index c7a6eddb..ca58d05a 100644 --- a/chainladder/core/dunders.py +++ b/chainladder/core/dunders.py @@ -63,7 +63,7 @@ def _compatibility_check(self, x, y): x, y = set_common_backend([x, y]) if ( x.origin_grain != y.origin_grain - or (x.development_grain != y.development_grain and + or (x.development_grain != y.development_grain and min(x.shape[-1], y.shape[-1]) > 1) ): raise ValueError( @@ -100,7 +100,7 @@ def _prep_index(self, x, y): x = x.sort_index() try: y = y.loc[x.index] - except: + except Exception: x = x.groupby(list(common)) y = y.groupby(list(common)) return x, y @@ -112,7 +112,7 @@ def _prep_index(self, x, y): def _prep_columns(self, x, y): x_backend, y_backend = x.array_backend, y.array_backend - + if len(x.columns) == 1 and len(y.columns) > 1: x.vdims = y.vdims elif len(y.columns) == 1 and len(x.columns) > 1: @@ -121,30 +121,30 @@ def _prep_columns(self, x, y): y.vdims = x.vdims elif x.shape[1] == y.shape[1] and np.array_equal(x.columns, y.columns): return x, y - else: + else: # Find columns to add to each triangle - cols_to_add_to_x = [col for col in y.columns if col not in x.columns] - cols_to_add_to_y = [col for col in x.columns if col not in y.columns] - + cols_to_add_to_x = [col for col in y.columns if col not in x.columns] + cols_to_add_to_y = [col for col in x.columns if col not in y.columns] + # Create new columns only if necessary if cols_to_add_to_x: new_x_cols = list(x.columns) + list(cols_to_add_to_x) x = x.reindex(columns=new_x_cols, fill_value=0) - + if cols_to_add_to_y: new_y_cols = list(y.columns) + list(cols_to_add_to_y) y = y.reindex(columns=new_y_cols, fill_value=0) - + # Ensure both triangles have the same column order x = x[new_x_cols] y = y[new_x_cols] - + # Reset backends only if they've changed if x.array_backend != x_backend: x = x.set_backend(x_backend, inplace=True) if y.array_backend != y_backend: y = y.set_backend(y_backend, inplace=True) - + return x, y def _prep_origin_development(self, obj, other): diff --git a/chainladder/core/pandas.py b/chainladder/core/pandas.py index 26a9e6ee..ab1f9524 100644 --- a/chainladder/core/pandas.py +++ b/chainladder/core/pandas.py @@ -91,7 +91,7 @@ def to_frame(self, origin_as_datetime=True, keepdims=False, valuation = pd.DataFrame( obj.valuation.values.reshape(obj.shape[-2:], order='F'), - index=obj.odims if origin_as_datetime else obj.origin, + index=obj.odims if origin_as_datetime else obj.origin, columns=obj.ddims ).unstack().rename('valuation').reset_index().rename( columns={'level_0': 'development', 'level_1': 'origin'}) diff --git a/chainladder/core/slice.py b/chainladder/core/slice.py index 3aeeeab4..eb3809cf 100644 --- a/chainladder/core/slice.py +++ b/chainladder/core/slice.py @@ -248,7 +248,7 @@ def __setitem__(self, key, value): self.vdims = self.vdims if key in self.vdims else np.append(self.vdims, key) try: self.values = xp.concatenate((self.values, value.values), axis=1) - except: + except Exception: # For misaligned triangle support conc = (self.values, (self.iloc[:, 0] * 0 + value).values) self.values = xp.concatenate(conc, axis=1) diff --git a/chainladder/core/tests/rtest_correlation.py b/chainladder/core/tests/rtest_correlation.py index 20630666..7538c04b 100644 --- a/chainladder/core/tests/rtest_correlation.py +++ b/chainladder/core/tests/rtest_correlation.py @@ -1,5 +1,5 @@ ### Building out a dev environment with a working copy -### of R ChainLadder is difficult. These tests are +### of R ChainLadder is difficult. These tests are ### Currently inactive, but available should the compatibility ### of the installs improve at a later date. @@ -11,7 +11,7 @@ from rpy2.robjects.packages import importr from rpy2.robjects import r CL = importr("ChainLadder") -except: +except Exception: pass def dev_corr_r(data, ci): diff --git a/chainladder/core/tests/test_correlation.py b/chainladder/core/tests/test_correlation.py index 8b10a460..a0620e70 100644 --- a/chainladder/core/tests/test_correlation.py +++ b/chainladder/core/tests/test_correlation.py @@ -17,4 +17,4 @@ def test_dev_corr_sparse(): def test_validate_critical(): with pytest.raises(ValueError): - raa.valuation_correlation(p_critical=1.5, total=True) \ No newline at end of file + raa.valuation_correlation(p_critical=1.5, total=True) diff --git a/chainladder/core/tests/test_display.py b/chainladder/core/tests/test_display.py index b2cdebac..d6d648b1 100644 --- a/chainladder/core/tests/test_display.py +++ b/chainladder/core/tests/test_display.py @@ -7,7 +7,7 @@ def test_heatmap_render(raa): try: raa.heatmap() - except: + except Exception: assert False @@ -24,7 +24,7 @@ def test_to_frame(raa): cl.Chainladder().fit(raa).ultimate_.to_frame(origin_as_datetime=False) cl.Chainladder().fit(raa).ultimate_.to_frame(origin_as_datetime=True) - except: + except Exception: assert False diff --git a/chainladder/core/tests/test_triangle.py b/chainladder/core/tests/test_triangle.py index 47cc59df..d3a8ce9f 100644 --- a/chainladder/core/tests/test_triangle.py +++ b/chainladder/core/tests/test_triangle.py @@ -7,7 +7,7 @@ try: from IPython.core.display import HTML -except: +except Exception: HTML = None @@ -787,17 +787,17 @@ def test_semi_annual_grain(): "2009-01-01", "2009-07-01", "2010-01-01", "2009-07-01", "2010-01-01", "2010-01-01"], - 'loss': [100, 200, 300, 400, 500, 600, 700, - 150, 300, 450, 500, 550, 600, - 200, 250, 350, 400, 450, + 'loss': [100, 200, 300, 400, 500, 600, 700, + 150, 300, 450, 500, 550, 600, + 200, 250, 350, 400, 450, 50, 100, 150, 200, 100, 200, 300, - 50, 150, + 50, 150, 100] } Stri = cl.Triangle( - pd.DataFrame(Sdata), + pd.DataFrame(Sdata), origin='origin', development='development', columns='loss', @@ -813,14 +813,14 @@ def test_semi_annual_grain(): "2008-01-01", "2009-01-01", "2010-01-01", "2009-01-01", "2010-01-01", "2010-01-01"], - 'loss': [100, 600, 1000, 1300, - 200, 450, 650, + 'loss': [100, 600, 1000, 1300, + 200, 450, 650, 100, 450, 100] } Atri = cl.Triangle( - pd.DataFrame(Adata), + pd.DataFrame(Adata), origin='origin', development='development', columns='loss', @@ -833,7 +833,7 @@ def test_odd_quarter_end(): ["5/1/2023", 12, '4/30/2024', 100], ["8/1/2023", 9, "4/30/2024", 130], ["11/1/2023", 6, "4/30/2024", 160], - ["2/1/2024", 3, "4/30/2024", 140]], + ["2/1/2024", 3, "4/30/2024", 140]], columns = ['origin', 'development', 'valuation', 'EarnedPremium']) triangle = cl.Triangle( data, origin='origin', origin_format='%Y-%m-%d', development='valuation', columns='EarnedPremium', trailing=True, cumulative=True @@ -867,7 +867,7 @@ def test_single_valuation_date_preserves_exact_date(): assert triangle.development_grain == 'M' assert int(triangle.valuation_date.strftime('%Y%m')) == 202510 def test_OXDX_triangle(): - + for x in [12,6,3,1]: for y in [i for i in [12,6,3,1] if i <= x]: first_orig = '2020-01-01' @@ -881,13 +881,13 @@ def test_OXDX_triangle(): for i in range(12): for j in range(y): test_data = tri_df.copy() - test_data['origin_date'] += pd.DateOffset(months=i) + test_data['origin_date'] += pd.DateOffset(months=i) test_data['development_date'] += pd.DateOffset(months=i-j) tri = cl.Triangle( - test_data, - origin='origin_date', - development='development_date', - columns='value', + test_data, + origin='origin_date', + development='development_date', + columns='value', cumulative=True ) assert tri.shape == (1,1,2,width) diff --git a/chainladder/core/triangle.py b/chainladder/core/triangle.py index 041f9111..f23cdae5 100644 --- a/chainladder/core/triangle.py +++ b/chainladder/core/triangle.py @@ -151,7 +151,7 @@ def __init__( # Store dimension metadata. self.columns_label: list = columns self.origin_label: list = origin - + # Handle any ultimate vectors in triangles separately. data, ult = self._split_ult( data=data, @@ -195,11 +195,11 @@ def __init__( # Ensure that origin_date values represent the beginning of the period. # i.e., 1990 means the start of 1990. origin_date: Series = to_period(origin_date,self.origin_grain).dt.to_timestamp(how="s") - + # Ensure that development_date values represent the end of the period. # i.e., 1990 means the end of 1990 assuming annual development periods. development_date: Series = to_period(development_date,self.development_grain).dt.to_timestamp(how="e") - + # Aggregate dates to the origin/development grains. data_agg: DataFrame = self._aggregate_data( data=data, @@ -208,7 +208,7 @@ def __init__( index=index, columns=columns, ) - + # Fill in missing periods with zeros. date_axes: DataFrame = self._get_date_axes( data_agg["__origin__"], @@ -253,7 +253,7 @@ def __init__( self.is_cumulative: bool = cumulative self.virtual_columns = VirtualColumns(self) self.is_pattern: bool = pattern - + split: list[str] = self.origin_grain.split("-") self.origin_grain: str = {"A": "Y", "2Q": "S"}.get(split[0], split[0]) @@ -831,7 +831,7 @@ def grain(self, grain="", trailing=False, inplace=False): addl.ddims = addl_ts obj = concat((addl, obj), axis=-1) obj.values = num_to_nan(obj.values) - + if dgrain_old != dgrain_new and obj.shape[-1] > 1: step = self._dstep()[dgrain_old][dgrain_new] d = np.sort( @@ -847,7 +847,7 @@ def grain(self, grain="", trailing=False, inplace=False): obj.ddims = ddims obj.development_grain = dgrain_new - + obj = obj.dev_to_val() if self.is_val_tri else obj.val_to_dev() if inplace: diff --git a/chainladder/development/incremental.py b/chainladder/development/incremental.py index fb0537e0..d4357b7c 100644 --- a/chainladder/development/incremental.py +++ b/chainladder/development/incremental.py @@ -146,7 +146,7 @@ def fit(self, X, y=None, sample_weight=None): self.sample_weight = sample_weight self.fit_zeta_ = self.tri_zeta * self.w_ self.zeta_ = self._param_property(x,self.params_.slope_[...,0][..., None, :]) - + #to consolidate under full_triangle_ y_ = xp.repeat(self.zeta_.values, len(x.odims), -2) obj = x.copy() @@ -170,7 +170,7 @@ def fit(self, X, y=None, sample_weight=None): self.incremental_ = self.incremental_.trend( 1/(1+future_trend)-1, axis='valuation', start=X.valuation_date, end=self.incremental_.valuation_date) - + #to migrate under _zeta_to_ldf method under common, so ldf_ can be correct after tail self.ldf_ = obj.incr_to_cum().link_ratio return self @@ -195,7 +195,7 @@ def transform(self, X): def _param_property(self, factor, params): from chainladder import options - + obj = factor[factor.origin == factor.origin.min()] xp = factor.get_array_module() obj.values = params diff --git a/chainladder/development/learning.py b/chainladder/development/learning.py index 041a9abc..a56f4485 100644 --- a/chainladder/development/learning.py +++ b/chainladder/development/learning.py @@ -156,13 +156,13 @@ def _prep_X_ml(self, X): def _prep_w_ml(self,X,sample_weight=None): weight_base = (~np.isnan(X.values)).astype(float) - weight = weight_base.copy() + weight = weight_base.copy() if self.drop is not None: weight = weight * self._drop_func(X) if self.drop_valuation is not None: weight = weight * self._drop_valuation_func(X) if sample_weight is not None: - weight = weight * sample_weight.values + weight = weight * sample_weight.values return weight.flatten()[weight_base.flatten()>0] def fit(self, X, y=None, sample_weight=None): @@ -206,7 +206,7 @@ def fit(self, X, y=None, sample_weight=None): sample_weights = {self.weighted_step + '__sample_weight':weight} # Fit model self.estimator_ml.fit(df, self.y_ml_.fit_transform(df).squeeze(),**sample_weights) - #return selffit_incrementals + #return selffit_incrementals self.triangle_ml_, self.predicted_data_ = self._get_triangle_ml(df) return self @@ -238,4 +238,4 @@ def transform(self, X): X_new.ldf_.valuation_date = pd.to_datetime(options.ULT_VAL) X_new._set_slicers() X_new.predicted_data_ = predicted_data - return X_new \ No newline at end of file + return X_new diff --git a/chainladder/development/tests/rtest_clark.py b/chainladder/development/tests/rtest_clark.py index ff2229f7..ceca0340 100644 --- a/chainladder/development/tests/rtest_clark.py +++ b/chainladder/development/tests/rtest_clark.py @@ -1,5 +1,5 @@ ### Building out a dev environment with a working copy -### of R ChainLadder is difficult. These tests are +### of R ChainLadder is difficult. These tests are ### Currently inactive, but available should the compatibility ### of the installs improve at a later date. @@ -11,7 +11,7 @@ from rpy2.robjects.packages import importr from rpy2.robjects import r CL = importr("ChainLadder") -except: +except Exception: pass @pytest.mark.r diff --git a/chainladder/development/tests/rtest_development.py b/chainladder/development/tests/rtest_development.py index 30960bfa..b17f9b54 100644 --- a/chainladder/development/tests/rtest_development.py +++ b/chainladder/development/tests/rtest_development.py @@ -1,5 +1,5 @@ ### Building out a dev environment with a working copy -### of R ChainLadder is difficult. These tests are +### of R ChainLadder is difficult. These tests are ### Currently inactive, but available should the compatibility ### of the installs improve at a later date. @@ -12,7 +12,7 @@ from rpy2.robjects import r CL = importr("ChainLadder") -except: +except Exception: pass diff --git a/chainladder/development/tests/rtest_munich.py b/chainladder/development/tests/rtest_munich.py index ee7e2fbd..24fcda6e 100644 --- a/chainladder/development/tests/rtest_munich.py +++ b/chainladder/development/tests/rtest_munich.py @@ -1,5 +1,5 @@ ### Building out a dev environment with a working copy -### of R ChainLadder is difficult. These tests are +### of R ChainLadder is difficult. These tests are ### Currently inactive, but available should the compatibility ### of the installs improve at a later date. @@ -11,7 +11,7 @@ from rpy2.robjects.packages import importr from rpy2.robjects import r CL = importr("ChainLadder") -except: +except Exception: pass @@ -34,4 +34,4 @@ def test_mcl_incurred(): ) xp = p.ldf_.get_array_module() arr = xp.array(df[0]) - assert xp.allclose(arr, p.munich_full_triangle_[1, 0, 0, :, :], atol=1e-5) \ No newline at end of file + assert xp.allclose(arr, p.munich_full_triangle_[1, 0, 0, :, :], atol=1e-5) diff --git a/chainladder/development/tests/test_barnzehn.py b/chainladder/development/tests/test_barnzehn.py index a1c4bba8..9d82a717 100644 --- a/chainladder/development/tests/test_barnzehn.py +++ b/chainladder/development/tests/test_barnzehn.py @@ -43,11 +43,11 @@ def test_bz_2008(): origin_buckets = [(0,1),(2,2),(3,4),(5,10)] dev_buckets = [(24,36),(36,48),(48,84),(84,108),(108,144)] val_buckets = [(1,8),(8,9),(9,12)] - + abc_formula = PTF_formula(abc_adj,alpha=origin_buckets,gamma=dev_buckets,iota=val_buckets) - + model=cl.BarnettZehnwirth(formula=abc_formula, drop=('1982',72)).fit(abc_adj) assert np.all( np.around(model.coef_.values,4).flatten() == np.array([11.1579,0.1989,0.0703,0.0919,0.1871,-0.3771,-0.4465,-0.3727,-0.3154,0.0432,0.0858,0.1464]) - ) \ No newline at end of file + ) diff --git a/chainladder/development/tests/test_development.py b/chainladder/development/tests/test_development.py index 54086cce..32bd0dc9 100644 --- a/chainladder/development/tests/test_development.py +++ b/chainladder/development/tests/test_development.py @@ -40,7 +40,7 @@ def test_drop2(raa): def test_n_periods(): d = cl.load_sample("usauto")["incurred"] xp = np if d.array_backend == "sparse" else d.get_array_module() - return xp.all( + assert xp.all( xp.around( xp.unique( cl.Development(n_periods=3, average="volume").fit(d).ldf_.values, @@ -316,7 +316,7 @@ def test_new_drop_8(): try: cl.Development(drop_high=False).fit_transform(tri) - except: + except Exception: assert False diff --git a/chainladder/development/tests/test_glm.py b/chainladder/development/tests/test_glm.py index 34532871..6f488476 100644 --- a/chainladder/development/tests/test_glm.py +++ b/chainladder/development/tests/test_glm.py @@ -5,9 +5,9 @@ def test_basic_odp_cl(genins): (cl.Chainladder().fit(genins).ultimate_ - cl.Chainladder().fit(cl.TweedieGLM().fit_transform(genins)).ultimate_) / genins.latest_diagonal).max()< 1e-2 - + def test_sample_weight(genins): assert abs( (cl.Chainladder().fit(genins).ultimate_ - cl.Chainladder().fit(cl.TweedieGLM().fit_transform(genins,sample_weight=genins/genins)).ultimate_) / - genins.latest_diagonal).max()< 1e-2 \ No newline at end of file + genins.latest_diagonal).max()< 1e-2 diff --git a/chainladder/development/tests/test_learning.py b/chainladder/development/tests/test_learning.py index 0b411aca..206edf27 100644 --- a/chainladder/development/tests/test_learning.py +++ b/chainladder/development/tests/test_learning.py @@ -16,4 +16,4 @@ def test_misc(genins): ('design_matrix', PatsyFormula('C(development)')), ('model', LinearRegression(fit_intercept=False))]), weighted_step = ['model'], fit_incrementals=False).fit(genins, sample_weight=genins/genins) - assert abs(model.triangle_ml_.loc[:,:,'2010',:] - genins.mean()).max() < 1e2 \ No newline at end of file + assert abs(model.triangle_ml_.loc[:,:,'2010',:] - genins.mean()).max() < 1e2 diff --git a/chainladder/methods/base.py b/chainladder/methods/base.py index 26bf84fb..31a897a3 100644 --- a/chainladder/methods/base.py +++ b/chainladder/methods/base.py @@ -116,7 +116,7 @@ def predict(self, X, sample_weight=None): X_new.ldf_ = self.ldf_ X_new, X_new.ldf_ = self.intersection(X_new, X_new.ldf_) return X_new - + def intersection(self, a, b): """ Given two Triangles with mismatched indices, this method aligns their indices """ diff --git a/chainladder/methods/capecod.py b/chainladder/methods/capecod.py index 943fdd3f..6e42e3de 100644 --- a/chainladder/methods/capecod.py +++ b/chainladder/methods/capecod.py @@ -146,7 +146,7 @@ def predict(self, X, sample_weight=None): # If model was fit at a higher grain, then need to aggregate predicted aprioris too if len(set(sample_weight.key_labels) - set(self.apriori_.key_labels)) > 1: apriori_, detrended_apriori_ = self._get_capecod_aprioris( - X_new.groupby(self.apriori_.key_labels).sum(), + X_new.groupby(self.apriori_.key_labels).sum(), sample_weight.groupby(self.apriori_.key_labels).sum()) else: apriori_, detrended_apriori_ = self._get_capecod_aprioris(X_new, sample_weight) diff --git a/chainladder/methods/chainladder.py b/chainladder/methods/chainladder.py index 29bad4bc..01c99b90 100644 --- a/chainladder/methods/chainladder.py +++ b/chainladder/methods/chainladder.py @@ -71,6 +71,6 @@ def _get_ultimate(self, X, sample_weight=None): """ Private method that uses CDFs to obtain an ultimate vector """ ld = X.incr_to_cum().latest_diagonal ultimate = X.incr_to_cum().copy() - cdf = self._align_cdf(ultimate, sample_weight) - ultimate = ld * cdf + cdf = self._align_cdf(ultimate, sample_weight) + ultimate = ld * cdf return self._set_ult_attr(ultimate) diff --git a/chainladder/methods/tests/rtest_mack.py b/chainladder/methods/tests/rtest_mack.py index 6fa99a6a..9110b7d5 100644 --- a/chainladder/methods/tests/rtest_mack.py +++ b/chainladder/methods/tests/rtest_mack.py @@ -1,5 +1,5 @@ ### Building out a dev environment with a working copy -### of R ChainLadder is difficult. These tests are +### of R ChainLadder is difficult. These tests are ### Currently inactive, but available should the compatibility ### of the installs improve at a later date. @@ -11,7 +11,7 @@ from rpy2.robjects.packages import importr from rpy2.robjects import r CL = importr("ChainLadder") -except: +except Exception: pass @@ -140,4 +140,4 @@ def test_mack_asymmetric(): xp = tri.get_array_module() assert round(float(xp.array(out.rx("Mack.S.E")[0])[-1, -1]), 2) == round( float(cl.MackChainladder().fit(tri).summary_.to_frame(origin_as_datetime=False).iloc[-1, -1]), 2 - ) \ No newline at end of file + ) diff --git a/chainladder/methods/tests/test_benktander.py b/chainladder/methods/tests/test_benktander.py index 0b320a2a..86119a99 100644 --- a/chainladder/methods/tests/test_benktander.py +++ b/chainladder/methods/tests/test_benktander.py @@ -75,4 +75,4 @@ def test_odd_shaped_triangle(): atr = tr.grain("OYDQ") ult1 = cl.Benktander(apriori = 1,n_iters=10000).fit(cl.Development(average="volume").fit_transform(atr),sample_weight = atr.latest_diagonal).ultimate_.sum() ult2 = cl.Benktander(apriori = 1,n_iters=10000).fit(cl.Development(average="volume").fit_transform(tr),sample_weight = tr.latest_diagonal).ultimate_.grain("OYDQ").sum() - assert abs(ult1 - ult2) < 1e-5 \ No newline at end of file + assert abs(ult1 - ult2) < 1e-5 diff --git a/chainladder/methods/tests/test_capecod.py b/chainladder/methods/tests/test_capecod.py index 70becc87..457aa9ce 100644 --- a/chainladder/methods/tests/test_capecod.py +++ b/chainladder/methods/tests/test_capecod.py @@ -50,12 +50,12 @@ def test_capecod_predict1(prism): ('model', cl.CapeCod())] ) cc_pipe.fit( - X=prism.groupby('Line')['Paid'].sum(), + X=prism.groupby('Line')['Paid'].sum(), sample_weight=prism.groupby('Line')['reportedCount'].sum().sum('development')) - assert abs(cc_pipe.predict(prism['Paid'], sample_weight=prism['reportedCount'].sum('development')).ultimate_.sum() - + assert abs(cc_pipe.predict(prism['Paid'], sample_weight=prism['reportedCount'].sum('development')).ultimate_.sum() - cc_pipe.named_steps.model.ultimate_.sum()).sum() < 1e-6 - + def test_capecod_predict2(prism): """ github issue #400 @@ -69,7 +69,7 @@ def test_capecod_predict2(prism): ('model', cl.CapeCod(groupby='Line'))] ) pipe1.fit( - X=prism['Paid'], + X=prism['Paid'], sample_weight=prism['reportedCount'].sum('development')) pipe2 = cl.Pipeline( @@ -77,10 +77,10 @@ def test_capecod_predict2(prism): ('model', cl.CapeCod())] ) pipe2.fit( - X=prism.groupby('Line')['Paid'].sum(), + X=prism.groupby('Line')['Paid'].sum(), sample_weight=prism.groupby('Line')['reportedCount'].sum().sum('development')) pred1 = pipe1.named_steps.model.ultimate_.sum() pred2 = pipe2.predict(prism['Paid'], sample_weight=prism['reportedCount'].sum('development')).ultimate_.sum() - assert np.nan_to_num(abs(pred1 - pred2).values).sum() <= 1e-6 \ No newline at end of file + assert np.nan_to_num(abs(pred1 - pred2).values).sum() <= 1e-6 diff --git a/chainladder/methods/tests/test_mack.py b/chainladder/methods/tests/test_mack.py index c9adc020..743601bf 100644 --- a/chainladder/methods/tests/test_mack.py +++ b/chainladder/methods/tests/test_mack.py @@ -18,6 +18,6 @@ def test_mack_to_triangle(): def test_mack_malformed(): a = cl.load_sample('raa') b = a.iloc[:, :, :-1] - x = cl.MackChainladder().fit(a) + x = cl.MackChainladder().fit(a) y = cl.MackChainladder().fit(b) - assert x.process_risk_.iloc[:,:,:-1] == y.process_risk_ \ No newline at end of file + assert x.process_risk_.iloc[:,:,:-1] == y.process_risk_ diff --git a/chainladder/methods/tests/test_predict.py b/chainladder/methods/tests/test_predict.py index 6e9b852f..84c06d8b 100644 --- a/chainladder/methods/tests/test_predict.py +++ b/chainladder/methods/tests/test_predict.py @@ -1,6 +1,6 @@ import chainladder as cl import pandas as pd -import pytest +import pytest raa = cl.load_sample("RAA") raa_1989 = raa[raa.valuation < raa.valuation_date] @@ -186,4 +186,4 @@ def test_odd_shaped_triangle(): ) ult1 = cl.Chainladder().fit(cl.Development(average="volume").fit_transform(tr.grain("OYDQ"))).ultimate_.sum() ult2 = cl.Chainladder().fit(cl.Development(average="volume").fit_transform(tr)).ultimate_.grain("OYDQ").sum() - assert abs(ult1 - ult2) < 1e-5 \ No newline at end of file + assert abs(ult1 - ult2) < 1e-5 diff --git a/chainladder/tails/tests/rtest_exponential.py b/chainladder/tails/tests/rtest_exponential.py index 6ea6a292..affdfcfc 100644 --- a/chainladder/tails/tests/rtest_exponential.py +++ b/chainladder/tails/tests/rtest_exponential.py @@ -6,7 +6,7 @@ from rpy2.robjects.packages import importr from rpy2.robjects import r CL = importr("ChainLadder") -except: +except Exception: pass @@ -113,4 +113,4 @@ def test_tail_doesnt_mutate_sigma_(data, averages, est_sigma): p = mack_p(data, averages[0], est_sigma[0]).sigma_ xp = p.get_array_module() p_no_tail = mack_p_no_tail(data, averages[0], est_sigma[0]).sigma_.values - xp.testing.assert_array_equal(p_no_tail, p.values[:, :, :, :-1]) \ No newline at end of file + xp.testing.assert_array_equal(p_no_tail, p.values[:, :, :, :-1]) diff --git a/chainladder/utils/cupy.py b/chainladder/utils/cupy.py index df49cbec..fc065f4e 100644 --- a/chainladder/utils/cupy.py +++ b/chainladder/utils/cupy.py @@ -11,7 +11,7 @@ cp.array([1]) module = "cupy" -except: +except Exception: if options.ARRAY_BACKEND == "cupy": import warnings diff --git a/chainladder/utils/dask.py b/chainladder/utils/dask.py index fad071f2..8f309b55 100644 --- a/chainladder/utils/dask.py +++ b/chainladder/utils/dask.py @@ -8,7 +8,7 @@ import dask.array as dp dp.array([1]) module = "dask" -except: +except Exception: if options.ARRAY_BACKEND == "dask": import warnings diff --git a/chainladder/utils/tests/test_utilities.py b/chainladder/utils/tests/test_utilities.py index d3989920..f62994f1 100644 --- a/chainladder/utils/tests/test_utilities.py +++ b/chainladder/utils/tests/test_utilities.py @@ -158,7 +158,7 @@ def test_json_df(): def test_read_csv_single(raa): # Test the read_csv function for a single dimensional input. - + # Read in the csv file. from pathlib import Path raa_csv_path = Path(__file__).parent.parent / "data" / "raa.csv" @@ -192,7 +192,7 @@ def test_read_csv_multi(clrd): ], index = ["GRNAME","LOB"], cumulative = True - ) + ) def test_concat(clrd): tri = clrd.groupby("LOB").sum() diff --git a/chainladder/utils/utility_functions.py b/chainladder/utils/utility_functions.py index fea2a552..9704e8ba 100644 --- a/chainladder/utils/utility_functions.py +++ b/chainladder/utils/utility_functions.py @@ -193,7 +193,7 @@ def read_csv( array_backend: str = None, pattern=False, trailing: bool = True, - *args, + *args, **kwargs ) -> Triangle: """ @@ -295,9 +295,9 @@ def read_csv( #create a data frame using the *args and **kwargs that the user specified local_dataframe = pd.read_csv(filepath_or_buffer,*args, **kwargs) - #pass the created local_dataframe in the Triangle constructor + #pass the created local_dataframe in the Triangle constructor local_triangle = Triangle( - data = local_dataframe, + data = local_dataframe, origin=origin, development=development, columns=columns, @@ -468,7 +468,7 @@ def parallelogram_olf( combined["is_leap"] = pd.to_datetime( combined["Origin_non_leaps"], format="%Y" + ("-%M" if grain == "M" else "") ).dt.is_leap_year - + if approximation_grain == "M": combined["final_OLF"] = combined["OLF_non_leaps"] diff --git a/chainladder/workflow/gridsearch.py b/chainladder/workflow/gridsearch.py index 227a84fb..61296777 100644 --- a/chainladder/workflow/gridsearch.py +++ b/chainladder/workflow/gridsearch.py @@ -93,7 +93,7 @@ def _fit_single_estimator(estimator, fit_params, X, y, scoring, item): for score in scoring.keys(): item[score] = scoring[score](model) return item - + results_ = Parallel(n_jobs=self.n_jobs)(delayed(_fit_single_estimator)( self.estimator, fit_params, X, y, scoring, item) for item in grid) diff --git a/docs/gallery/plot_ave_analysis.ipynb b/docs/gallery/plot_ave_analysis.ipynb index a919c50c..49d452bd 100644 --- a/docs/gallery/plot_ave_analysis.ipynb +++ b/docs/gallery/plot_ave_analysis.ipynb @@ -123,8 +123,8 @@ "fig, ax = plt.subplots()\n", "ax.grid(axis='x')\n", "plt.hlines(\n", - " y=df.index.astype(str), \n", - " xmin=df['Actual'], \n", + " y=df.index.astype(str),\n", + " xmin=df['Actual'],\n", " xmax=df['Expected'],\n", " color='grey', alpha=0.4)\n", "plt.scatter(df['Actual'], df.index.astype(str), alpha=1, label='Actual')\n", diff --git a/docs/gallery/plot_benktander.ipynb b/docs/gallery/plot_benktander.ipynb index 8ac4c46e..b15d93de 100644 --- a/docs/gallery/plot_benktander.ipynb +++ b/docs/gallery/plot_benktander.ipynb @@ -55,10 +55,10 @@ " estimator=cl.Pipeline(steps=[\n", " ('dev', cl.Development()),\n", " ('tail', cl.TailCurve()),\n", - " ('model', cl.Benktander())]), \n", + " ('model', cl.Benktander())]),\n", " param_grid = dict(\n", " model__n_iters=list(range(1, 100, 2)),\n", - " model__apriori=[0.50, 0.75, 1.00]), \n", + " model__apriori=[0.50, 0.75, 1.00]),\n", " scoring={'IBNR': lambda x: x.named_steps.model.ibnr_.sum()},\n", " n_jobs=-1)" ] @@ -225,9 +225,9 @@ "\n", "# Analyze results\n", "output = grid.results_.pivot(\n", - " index='model__n_iters', \n", - " columns='model__apriori', \n", - " values='IBNR') \n", + " index='model__n_iters',\n", + " columns='model__apriori',\n", + " values='IBNR')\n", "output.head()" ] }, diff --git a/docs/gallery/plot_berqsherm_case.ipynb b/docs/gallery/plot_berqsherm_case.ipynb index 9dce9b49..7d86a819 100644 --- a/docs/gallery/plot_berqsherm_case.ipynb +++ b/docs/gallery/plot_berqsherm_case.ipynb @@ -95,7 +95,7 @@ "ax = (berq_cdf / orig_cdf).T.plot(\n", " kind='bar', grid=True, legend=False,\n", " title='Berquist Sherman CDF to Unadjusted CDF',\n", - " xlabel='Age to Ultimate', \n", + " xlabel='Age to Ultimate',\n", " ylabel='Case Incurred CDF Adjustment');" ] }, diff --git a/docs/gallery/plot_bf_apriori_from_cl.ipynb b/docs/gallery/plot_bf_apriori_from_cl.ipynb index 5b36109b..b30fab0a 100644 --- a/docs/gallery/plot_bf_apriori_from_cl.ipynb +++ b/docs/gallery/plot_bf_apriori_from_cl.ipynb @@ -91,7 +91,7 @@ "\n", "# Plot of Ultimates\n", "\n", - "ax = output.plot(grid=True, marker='o', \n", + "ax = output.plot(grid=True, marker='o',\n", " xlabel='Accident Year', ylabel='Ultimate');" ] }, diff --git a/docs/gallery/plot_bootstrap.ipynb b/docs/gallery/plot_bootstrap.ipynb index bb92e7fd..3e587201 100644 --- a/docs/gallery/plot_bootstrap.ipynb +++ b/docs/gallery/plot_bootstrap.ipynb @@ -100,7 +100,7 @@ "plot2.plot(ax=ax01, title='Mean Simulation (Millions)', xlabel='Development')\n", "\n", "# Plot 3\n", - "plot3a.plot(legend=False, color='lightgray', ax=ax10, \n", + "plot3a.plot(legend=False, color='lightgray', ax=ax10,\n", " title='Simulated LDF', xlabel='Development', ylabel='LDF')\n", "plot3b.plot(legend=False, ax=ax10, grid=True)\n", "\n", diff --git a/docs/gallery/plot_bootstrap_comparison.ipynb b/docs/gallery/plot_bootstrap_comparison.ipynb index 054accda..7ae473eb 100644 --- a/docs/gallery/plot_bootstrap_comparison.ipynb +++ b/docs/gallery/plot_bootstrap_comparison.ipynb @@ -51,7 +51,7 @@ "## Alternatively use fit_transform() to access resampled triangles dropping\n", "# outlier link-ratios from resampler\n", "s2 = cl.BootstrapODPSample(\n", - " drop_high=[True] * 5+ [False] * 4, \n", + " drop_high=[True] * 5+ [False] * 4,\n", " drop_low=[True] * 5 + [False] * 4,\n", " n_sims=5000, random_state=42).fit_transform(triangle)\n", "\n", @@ -92,7 +92,7 @@ "%config InlineBackend.figure_format = 'retina'\n", "# Plot both IBNR distributions\n", "ax = results.to_frame().plot(\n", - " kind='hist', bins=50, alpha=0.5, \n", + " kind='hist', bins=50, alpha=0.5,\n", " grid=True, xlabel='Ultimate',\n", " title='Reserve Variability')" ] diff --git a/docs/gallery/plot_capecod_onlevel.ipynb b/docs/gallery/plot_capecod_onlevel.ipynb index 2d391295..66c6d4d6 100644 --- a/docs/gallery/plot_capecod_onlevel.ipynb +++ b/docs/gallery/plot_capecod_onlevel.ipynb @@ -125,7 +125,7 @@ "%config InlineBackend.figure_format = 'retina'\n", "\n", "ax = results.plot(\n", - " kind='bar', title='Cape Cod sensitivity to on-leveling', \n", + " kind='bar', title='Cape Cod sensitivity to on-leveling',\n", " subplots=True, legend=False);" ] }, diff --git a/docs/gallery/plot_elrf_resid.ipynb b/docs/gallery/plot_elrf_resid.ipynb index a2304ef1..38504faf 100644 --- a/docs/gallery/plot_elrf_resid.ipynb +++ b/docs/gallery/plot_elrf_resid.ipynb @@ -68,7 +68,7 @@ "plot3a = model.std_residuals_.dev_to_val().T\n", "plot3b = model.std_residuals_.dev_to_val().mean('origin').T\n", "plot4 = pd.concat((\n", - " (raa[raa.valuation < raa.valuation_date] * \n", + " (raa[raa.valuation < raa.valuation_date] *\n", " model.ldf_.values).unstack().rename('Fitted Values'),\n", " model.std_residuals_.unstack().rename('Residual')), axis=1).dropna()" ] @@ -120,7 +120,7 @@ " style='.', color='gray', legend=False, ax=ax10,\n", " xlabel='Valuation Date', ylabel='Weighted Standardized Residuals')\n", "plot3b.plot(color='red', legend=False, grid=True, ax=ax10)\n", - "plot4.plot(kind='scatter', marker='o', color='gray', \n", + "plot4.plot(kind='scatter', marker='o', color='gray',\n", " x='Fitted Values', y='Residual', ax=ax11, sharey=True);\n" ] } diff --git a/docs/gallery/plot_ptf_resid.ipynb b/docs/gallery/plot_ptf_resid.ipynb index 69454734..060e775c 100644 --- a/docs/gallery/plot_ptf_resid.ipynb +++ b/docs/gallery/plot_ptf_resid.ipynb @@ -115,7 +115,7 @@ " xlabel='Valuation Date', ylabel='Weighted Standardized Residuals')\n", "plot3b.plot(color='red', legend=False, ax=ax10)\n", "\n", - "plot4.plot(kind='scatter', marker='o', color='gray', \n", + "plot4.plot(kind='scatter', marker='o', color='gray',\n", " x='Fitted Values', y='Residual', ax=ax11, sharey=True);" ] }, diff --git a/docs/gallery/plot_stochastic_bornferg.ipynb b/docs/gallery/plot_stochastic_bornferg.ipynb index a8d2a938..7b163bdc 100644 --- a/docs/gallery/plot_stochastic_bornferg.ipynb +++ b/docs/gallery/plot_stochastic_bornferg.ipynb @@ -101,7 +101,7 @@ "\n", "# Plot the data\n", "ax = current_year.iloc[:-1, :300].plot(\n", - " legend=False, alpha=0.1, color='red', \n", + " legend=False, alpha=0.1, color='red',\n", " xlabel='Development Age', ylabel='Loss Ratio',\n", " title='Current Accident Year BornFerg Distribution');" ] diff --git a/docs/gallery/plot_triangle_slicing.ipynb b/docs/gallery/plot_triangle_slicing.ipynb index 819c368f..b57ec561 100644 --- a/docs/gallery/plot_triangle_slicing.ipynb +++ b/docs/gallery/plot_triangle_slicing.ipynb @@ -310,7 +310,7 @@ "\n", "# Plot\n", "ax = clrd.link_ratio.T.plot(\n", - " marker='o', \n", + " marker='o',\n", " title='Medical Malpractice Link Ratios',\n", " ylabel='Link Ratio', xlabel='Accident Year');" ] diff --git a/docs/gallery/plot_voting_chainladder.ipynb b/docs/gallery/plot_voting_chainladder.ipynb index 1cfa74ba..0a198cfc 100644 --- a/docs/gallery/plot_voting_chainladder.ipynb +++ b/docs/gallery/plot_voting_chainladder.ipynb @@ -101,7 +101,7 @@ "\n", "\n", "ax = plot_ibnr.plot(\n", - " kind='bar', ylim=(0, None), \n", + " kind='bar', ylim=(0, None),\n", " title='Voting Chainladder IBNR',\n", " xlabel='Accident Year', ylabel='Loss');" ] diff --git a/docs/getting_started/online_sandbox/sandbox_workbook_filled.ipynb b/docs/getting_started/online_sandbox/sandbox_workbook_filled.ipynb index 5f8b31f9..d214b704 100644 --- a/docs/getting_started/online_sandbox/sandbox_workbook_filled.ipynb +++ b/docs/getting_started/online_sandbox/sandbox_workbook_filled.ipynb @@ -3984,7 +3984,7 @@ ").to_frame()\n", "\n", "plt.plot(\n", - " cc_result.index.year, \n", + " cc_result.index.year,\n", " cc_result[\"2261\"]\n", ")" ] diff --git a/docs/user_guide/development.ipynb b/docs/user_guide/development.ipynb index eb059880..81eb6e1b 100644 --- a/docs/user_guide/development.ipynb +++ b/docs/user_guide/development.ipynb @@ -360,7 +360,7 @@ ], "source": [ "cl.Development(\n", - " drop_high=[True]*5+[False]*4, \n", + " drop_high=[True]*5+[False]*4,\n", " drop_low=[True]*5+[False]*4).fit(raa)" ] }, @@ -3853,7 +3853,7 @@ "source": [ "tri = cl.load_sample(\"ia_sample\")\n", "ia = cl.IncrementalAdditive().fit(\n", - " X=tri['loss'], \n", + " X=tri['loss'],\n", " sample_weight=tri['exposure'].latest_diagonal)\n", "ia.incremental_.round(0)" ] @@ -3972,7 +3972,7 @@ "outputs": [], "source": [ "cl.IncrementalAdditive(trend=0.02, future_trend=0.05).fit(\n", - " X=tri['loss'], \n", + " X=tri['loss'],\n", " sample_weight=tri['exposure'].latest_diagonal\n", ").incremental_.round(0)" ] @@ -4158,7 +4158,7 @@ "outputs": [], "source": [ "cl.ClarkLDF().fit(\n", - " X=clrd['CumPaidLoss'], \n", + " X=clrd['CumPaidLoss'],\n", " sample_weight=clrd['EarnedPremDIR'].latest_diagonal\n", ").elr_" ] @@ -5198,7 +5198,7 @@ } ], "source": [ - "((dev.cdf_.iloc[..., 0, :] / \n", + "((dev.cdf_.iloc[..., 0, :] /\n", " cl.Development().fit(clrd).cdf_) - 1\n", ").to_frame().round(3)" ] @@ -5430,7 +5430,7 @@ " ('model', RandomForestRegressor())\n", "])\n", "cl.DevelopmentML(\n", - " estimator_ml=estimator_ml, \n", + " estimator_ml=estimator_ml,\n", " y_ml='CumPaidLoss').fit(clrd).ldf_.iloc[0, 0, 0].round(2)" ] }, diff --git a/docs/user_guide/methods.ipynb b/docs/user_guide/methods.ipynb index 6e8fefe6..97998d46 100644 --- a/docs/user_guide/methods.ipynb +++ b/docs/user_guide/methods.ipynb @@ -595,7 +595,7 @@ "raa = cl.load_sample('raa')\n", "sample_weight = raa.latest_diagonal*0+40_000\n", "cl.BornhuetterFerguson(apriori=0.7).fit(\n", - " X=raa, \n", + " X=raa,\n", " sample_weight=sample_weight\n", ").ibnr_.sum()\n" ] @@ -777,7 +777,7 @@ "triangle = cl.load_sample('ukmotor')\n", "exposure = triangle.latest_diagonal*0 + 25_000\n", "cl.Benktander(apriori=0.75, n_iters=0).fit(\n", - " X=triangle, \n", + " X=triangle,\n", " sample_weight=exposure\n", ").full_triangle_.round(0)" ] @@ -845,7 +845,7 @@ "cl_ult = cl.Chainladder().fit(loss).ultimate_\n", "apriori = loss.latest_diagonal.sum() / (sample_weight/(cl_ult/loss.latest_diagonal)).sum()\n", "m2 = cl.BornhuetterFerguson(apriori).fit(\n", - " X=clrd['CumPaidLoss'], \n", + " X=clrd['CumPaidLoss'],\n", " sample_weight=clrd['EarnedPremDIR'].latest_diagonal)\n", "m2.ibnr_.sum()" ] diff --git a/docs/user_guide/tails.ipynb b/docs/user_guide/tails.ipynb index 8d1a2dbe..9d0296ef 100644 --- a/docs/user_guide/tails.ipynb +++ b/docs/user_guide/tails.ipynb @@ -706,7 +706,7 @@ "np.prod(\n", " (1+np.exp(\n", " np.arange(triangle.shape[-1],\n", - " triangle.shape[-1] + tail.extrap_periods) * \n", + " triangle.shape[-1] + tail.extrap_periods) *\n", " tail.slope_.values + tail.intercept_.values)\n", " )\n", ")" @@ -793,10 +793,10 @@ ], "source": [ "np.prod(\n", - " 1 + np.exp(tail.intercept_.values) * \n", + " 1 + np.exp(tail.intercept_.values) *\n", " (\n", " np.arange(\n", - " triangle.shape[-1], \n", + " triangle.shape[-1],\n", " triangle.shape[-1] + tail.extrap_periods\n", " ) ** tail.slope_.values)\n", ")" @@ -922,13 +922,13 @@ "ax = np.log(obs).rename('Selected LDF').plot(\n", " style=' ', marker='o', title=f'Fit Period affect on Tail Estimate');\n", "pd.Series(\n", - " np.arange(1, dev.ldf_.shape[-1] + 1) * exclude.slope_.sum().values + exclude.intercept_.sum().values, \n", - " index=dev.ldf_.development, \n", + " np.arange(1, dev.ldf_.shape[-1] + 1) * exclude.slope_.sum().values + exclude.intercept_.sum().values,\n", + " index=dev.ldf_.development,\n", " name=f'Ages after 36: {round(exclude.tail_.values[0,0], 3)}').plot(\n", " ax=ax, style = '--', legend=True);\n", "pd.Series(\n", - " np.arange(1, dev.ldf_.shape[-1] + 1) * fit_all.slope_.sum().values + fit_all.intercept_.sum().values, \n", - " index=dev.ldf_.development, \n", + " np.arange(1, dev.ldf_.shape[-1] + 1) * fit_all.slope_.sum().values + fit_all.intercept_.sum().values,\n", + " index=dev.ldf_.development,\n", " name=f'All Periods: {round(fit_all.tail_.values[0,0], 3)}').plot(\n", " ax=ax, style = '-.', legend=True);" ] diff --git a/docs/user_guide/triangle.ipynb b/docs/user_guide/triangle.ipynb index bf6903c0..b21b81b2 100644 --- a/docs/user_guide/triangle.ipynb +++ b/docs/user_guide/triangle.ipynb @@ -3850,9 +3850,9 @@ ], "source": [ "cl.Triangle(\n", - " df.reset_index(), index=['GRNAME', 'LOB'], \n", + " df.reset_index(), index=['GRNAME', 'LOB'],\n", " origin='origin', development='valuation',\n", - " columns=['BulkLoss', 'CumPaidLoss', 'EarnedPremCeded', \n", + " columns=['BulkLoss', 'CumPaidLoss', 'EarnedPremCeded',\n", " 'EarnedPremDIR', 'EarnedPremNet', 'IncurLoss']\n", ").incr_to_cum()" ] diff --git a/docs/user_guide/workflow.ipynb b/docs/user_guide/workflow.ipynb index c01ff139..834fb016 100644 --- a/docs/user_guide/workflow.ipynb +++ b/docs/user_guide/workflow.ipynb @@ -1638,8 +1638,8 @@ "# Vary the 'earliest_age' assumption in GridSearch\n", "param_grid=dict(earliest_age=list(range(12, 120, 12)))\n", "grid = cl.GridSearch(\n", - " estimator=cl.TailBondy(), \n", - " param_grid=param_grid, \n", + " estimator=cl.TailBondy(),\n", + " param_grid=param_grid,\n", " scoring=scoring)\n", "\n", "grid.fit(dev).results_" @@ -1860,7 +1860,7 @@ ")\n", "\n", "grid.fit(\n", - " X=clrd['CumPaidLoss'], \n", + " X=clrd['CumPaidLoss'],\n", " sample_weight=clrd['EarnedPremDIR'].latest_diagonal)\n", "\n", "grid.results_"