### Install Chainladder with uv Source: https://github.com/casact/chainladder-python/blob/main/docs/getting_started/install.md Use uv to add the chainladder package to your project. This is the recommended installation method. ```bash uv add chainladder ``` -------------------------------- ### Set Up Development Environment with uv Source: https://github.com/casact/chainladder-python/blob/main/docs/library/contributing.md Installs uv, adds it to PATH, navigates to the project directory, and installs all development dependencies in an editable mode. ```bash # Install uv if you haven't already curl -LsSf https://astral.sh/uv/install.sh | sh # Add uv to your PATH echo 'export PATH="$HOME/.cargo/bin:$PATH"' >> ~/.zshrc source ~/.zshrc # Navigate to your working directory cd chainladder-python # Create virtual environment and install all dependencies uv sync --extra all ``` -------------------------------- ### Install Chainladder from GitHub Source: https://github.com/casact/chainladder-python/blob/main/docs/getting_started/install.md Install the latest development version of chainladder directly from its GitHub repository using pip. This is useful for accessing unreleased features. ```bash pip install git+https://github.com/casact/chainladder-python/ ``` -------------------------------- ### Install Chainladder with pip Source: https://github.com/casact/chainladder-python/blob/main/docs/getting_started/install.md Use pip to install the chainladder package from PyPI. This is a common alternative to uv. ```bash pip install chainladder ``` -------------------------------- ### Install and Import Chainladder Source: https://github.com/casact/chainladder-python/blob/main/docs/library/presentation_assets/demo-blank-concurrent.ipynb Install the chainladder package using pip and import necessary libraries. This step is typically performed in a terminal. ```shell pip install chainladder ``` ```python import numpy as np import pandas as pd import matplotlib.pyplot as plt import chainladder as cl print("chainladder", cl.__version__) ``` -------------------------------- ### Install Chainladder with conda Source: https://github.com/casact/chainladder-python/blob/main/docs/getting_started/install.md Use conda to install the chainladder package from the conda-forge channel. ```bash conda install -c conda-forge chainladder ``` -------------------------------- ### Install Chainladder Package Source: https://github.com/casact/chainladder-python/blob/main/docs/getting_started/online_sandbox/sandbox_workbook_blank.ipynb Install the chainladder package using pip. This command is typically run in a terminal, not a Python notebook. ```shell pip install __fill_in_code__ ``` -------------------------------- ### Build Chainladder Docs Locally Source: https://github.com/casact/chainladder-python/blob/main/docs/README.md Install the project with documentation dependencies, navigate to the docs directory, and build the documentation using Jupyter Book. The output will be in the `docs/_build/html/` directory. ```bash pip install -e .[docs] cd docs jb build . ``` -------------------------------- ### Import Libraries and Load Chainladder Source: https://github.com/casact/chainladder-python/blob/main/docs/getting_started/online_sandbox/sandbox_workbook_blank.ipynb Import necessary libraries including pandas, matplotlib, and chainladder. Prints the installed chainladder version. ```python import pandas as pd import matplotlib.pyplot as plt import chainladder as cl print("chainladder", cl.__version__) ``` -------------------------------- ### Import Libraries for Chainladder Source: https://github.com/casact/chainladder-python/blob/main/docs/gallery/plot_mack.ipynb Imports the pandas and chainladder libraries. Ensure these are installed before running. ```python import pandas as pd import chainladder as cl ``` -------------------------------- ### Apply ParallelogramOLF Transformer Source: https://github.com/casact/chainladder-python/blob/main/docs/library/releases.md Example demonstrating how to apply the new ParallelogramOLF transformer for onleveling. Refer to the official documentation for detailed usage. ```python clrd = cl.load_sample('clrd') # Example usage of ParallelogramOLF would go here, referencing the gallery example. ``` -------------------------------- ### Load Sample Data and Select Column Source: https://github.com/casact/chainladder-python/blob/main/docs/getting_started/tutorials/tail-tutorial.ipynb Loads the 'quarterly' sample dataset and selects the 'paid' column for analysis. This is a common starting point for tail fitting. ```python quarterly = cl.load_sample("quarterly") quarterly["paid"] ``` -------------------------------- ### Check Package Versions Source: https://github.com/casact/chainladder-python/blob/main/docs/getting_started/tutorials/development-tutorial.ipynb Prints the installed versions of pandas, numpy, and chainladder. Optional black linter import is commented out. ```python # Black linter, optional # import jupyter_black as jb # jb.load() import pandas as pd import numpy as np import chainladder as cl print("pandas: " + pd.__version__) print("numpy: " + np.__version__) print("chainladder: " + cl.__version__) ``` -------------------------------- ### List Available Sample Datasets Source: https://github.com/casact/chainladder-python/blob/main/docs/library/sample_data.ipynb Use `cl.list_samples()` to get a list of all available sample datasets and their attributes. This function reads from the package's manifest to ensure accuracy. ```python import chainladder as cl cl.list_samples() ``` -------------------------------- ### CapeCod Onleveling Example Source: https://github.com/casact/chainladder-python/blob/main/docs/user_guide/adjustments.ipynb Demonstrates how to use a ParallelogramOLF transformed Triangle as input for the CapeCod estimator, enabling on-leveling within the CapeCod analysis. ```python ppauto_loss = cl.load_sample('clrd').groupby('LOB').sum().loc['ppauto', 'CumPaidLoss'] ppauto_prem = cl.load_sample('clrd').groupby('LOB').sum() \ .loc['ppauto']['EarnedPremDIR'].latest_diagonal # Simple trend a = cl.CapeCod(trend=0.05).fit(ppauto_loss, sample_weight=ppauto_prem).ultimate_.sum() # Equivalent using a Trend Estimator. This allows us to convert to more complex trends b = cl.CapeCod().fit(cl.Trend(.05).fit_transform(ppauto_loss), sample_weight=ppauto_prem).ultimate_.sum() a == b ``` -------------------------------- ### Load and Transform Sample Data Source: https://github.com/casact/chainladder-python/blob/main/docs/user_guide/development.ipynb Loads the 'clrd' sample dataset and applies a development transformation. This is a basic setup for further analysis. ```python clrd = cl.load_sample('clrd')['CumPaidLoss'] clrd = cl.Development(groupby='LOB').fit_transform(clrd) clrd.shape, clrd.ldf_.shape ``` -------------------------------- ### Arithmetic Label Matching Example Source: https://github.com/casact/chainladder-python/blob/main/docs/library/releases.md Illustrates the improved arithmetic label matching for axes in chainladder, which aligns more closely with pandas functionality. ```python prism = cl.load_sample('prism') prism / prism.groupby('Line').sum() ``` -------------------------------- ### Setup Pipeline and GridSearch for Development Transformer Source: https://github.com/casact/chainladder-python/blob/main/docs/gallery/plot_development_periods.ipynb This code sets up a chainladder pipeline and a GridSearch to test different numbers of periods and averaging methods in the development transformer. It defines a scoring function to evaluate the influence on the ultimate estimate. ```python tri = cl.load_sample('abc') # Set up Pipeline pipe = cl.Pipeline(steps=[ ('dev',cl.Development()), ('chainladder',cl.Chainladder())]) # Develop scoring function that returns an Ultimate/Incurred Ratio # Set up a GridSearch space grid = cl.GridSearch( estimator=pipe, param_grid=dict( dev__n_periods=[item for item in range(2,11)], dev__average=['simple', 'volume', 'regression']), scoring=lambda x: ( x.named_steps.chainladder.ultimate_.sum() / tri.latest_diagonal.sum())) grid.fit(tri) # Plot data results = pd.pivot_table(grid.results_, index='dev__n_periods', columns='dev__average', values='score') ``` -------------------------------- ### Pipeline with Grouped Development Source: https://github.com/casact/chainladder-python/blob/main/docs/user_guide/workflow.ipynb This example shows how to create a Pipeline that performs grouped development by 'LOB' using the Development estimator. This streamlines reserving analysis by applying development patterns at a more granular level. ```python clrd = cl.load_sample('clrd')['CumPaidLoss'] pipe = cl.Pipeline( steps=[ ('dev', cl.Development(groupby='LOB')), ('tail', cl.TailCurve('exponential')), ('model', cl.Chainladder())]).fit(clrd) pipe.named_steps.model.ibnr_ ``` -------------------------------- ### Import Libraries and Check Versions Source: https://github.com/casact/chainladder-python/blob/main/docs/getting_started/tutorials/data-tutorial.ipynb Imports necessary libraries like pandas, numpy, and chainladder, and prints their versions. This is a common setup for data analysis tasks. ```python # Black linter, optional # import jupyter_black as jb # jb.load() import pandas as pd import numpy as np import chainladder as cl import matplotlib.pyplot as plt print("pandas: " + pd.__version__) print("numpy: " + np.__version__) print("chainladder: " + cl.__version__) ``` -------------------------------- ### Emulating CapeCod Apriori with BornhuetterFerguson Source: https://github.com/casact/chainladder-python/blob/main/docs/user_guide/methods.ipynb This example shows how to derive the 'apriori' implicit in the CapeCod estimate and then use it with the BornhuetterFerguson method. It calculates the 'apriori' based on the ratio of the latest diagonal sum to a weighted average of ultimate-to-latest-diagonal ratios. ```python cl_ult = cl.Chainladder().fit(loss).ultimate_ apriori = loss.latest_diagonal.sum() / (sample_weight/(cl_ult/loss.latest_diagonal)).sum() m2 = cl.BornhuetterFerguson(apriori).fit( X=clrd['CumPaidLoss'], sample_weight=clrd['EarnedPremDIR'].latest_diagonal) m2.ibnr_.sum() ``` -------------------------------- ### Load Sample Triangle Data Source: https://github.com/casact/chainladder-python/blob/main/docs/getting_started/tutorials/triangle-tutorial.ipynb Loads a pre-defined sample triangle dataset directly using the load_sample function. This is a convenient way to get started with example data. ```python import chainladder as cl raa = cl.load_sample("raa") raa ``` -------------------------------- ### Build Documentation with Jupyter Book Source: https://github.com/casact/chainladder-python/blob/main/docs/library/contributing.md Navigates to the docs directory and builds the documentation site using Jupyter Book. ```bash cd docs jb build . ``` -------------------------------- ### Import Libraries and Set Display Options Source: https://github.com/casact/chainladder-python/blob/main/docs/friedland/chapter_7.rst Imports necessary libraries (numpy, pandas, chainladder) and configures pandas display options for better data visualization. This is a common setup for data analysis tasks. ```python import numpy as np import pandas as pd import chainladder as cl pd.set_option('display.max_columns', None) pd.set_option('display.width', 1000) ``` -------------------------------- ### Load Sample Triangle and Check Backend Source: https://github.com/casact/chainladder-python/blob/main/docs/user_guide/triangle.ipynb Load a sample dataset ('prism') and inspect its default array backend, which is 'sparse' for this dataset. ```python prism = cl.load_sample('prism') prism.array_backend ``` -------------------------------- ### Load Data and Initialize Estimators Source: https://github.com/casact/chainladder-python/blob/main/docs/gallery/plot_voting_chainladder.ipynb Loads sample data and initializes Chainladder and CapeCod estimators. Sets up an apriori estimate for weighting. ```python import chainladder as cl import numpy as np import pandas as pd ``` ```python # Load the data raa = cl.load_sample('raa') cl_ult = cl.Chainladder().fit(raa).ultimate_ # Chainladder Ultimate apriori = cl_ult * 0 + (float(cl_ult.sum()) / 10) # Mean Chainladder Ultimate # Load estimators to vote between bcl = cl.Chainladder() cc = cl.CapeCod() estimators = [('bcl', bcl), ('cc', cc)] # Fit VotingChainladder using CC after 1987 and a blend of BCL and CC otherwise vot = cl.VotingChainladder( estimators=estimators, weights=lambda origin: (0, 1) if origin.year > 1987 else (0.5, 0.5) ) vot.fit(raa, sample_weight=apriori) # Plotting bcl_ibnr = bcl.fit(raa).ibnr_.to_frame(origin_as_datetime=False) cc_ibnr = cc.fit(raa, sample_weight=apriori).ibnr_.to_frame(origin_as_datetime=False) vot_ibnr = vot.ibnr_.to_frame(origin_as_datetime=False) plot_ibnr = pd.concat([bcl_ibnr, vot_ibnr, cc_ibnr], axis=1) plot_ibnr.columns = ['BCL', 'Voting', 'CC'] ``` -------------------------------- ### Create and Fit a Pipeline Source: https://github.com/casact/chainladder-python/blob/main/docs/getting_started/tutorials/tail-tutorial.ipynb Demonstrates how to create a Pipeline by sequencing transformers and fitting it to data. This is useful for applying multiple transformations sequentially. ```python sequence = [ ("simple_dev", cl.Development(average="simple")), ("inverse_power_tail", cl.TailCurve(curve="inverse_power")), ] pipe = cl.Pipeline(steps=sequence).fit(quarterly) ``` -------------------------------- ### Load Sample Data and Initialize Simple Development Source: https://github.com/casact/chainladder-python/blob/main/docs/user_guide/development.ipynb Loads the 'raa' sample dataset and initializes the Development class with the 'simple' averaging method. ```python raa = cl.load_sample('raa') cl.Development(average='simple') ``` -------------------------------- ### Multipart Trend Calculation Source: https://github.com/casact/chainladder-python/blob/main/docs/user_guide/adjustments.ipynb Calculate a multipart trend by passing a list of trends and corresponding dates. Dates should be represented as a list of tuples (start, end). The default start and end dates for a Triangle are its valuation_date and its earliest origin date. ```python ppauto_loss = cl.load_sample('clrd').groupby('LOB').sum().loc['ppauto', 'CumPaidLoss'] cl.Trend( trends=[.05, .03], dates=[('1997-12-31', '1995-01-01'),('1995-01-01', '1992-07-01')] ).fit(ppauto_loss).trend_.round(2) ``` -------------------------------- ### Get Latest Diagonal Source: https://github.com/casact/chainladder-python/blob/main/docs/library/presentation_assets/demo-blank-concurrent.ipynb Extract the latest diagonal from a chainladder triangle. ```python xyz_tri.latest_diagonal() ``` -------------------------------- ### Create and fit a Pipeline for reserving Source: https://github.com/casact/chainladder-python/blob/main/docs/user_guide/workflow.ipynb This snippet demonstrates creating a Pipeline that chains BootstrapODPSample, Development, TailCurve, and Chainladder estimators. It then fits the pipeline to sample data. ```python pipe = cl.Pipeline( steps=[ ('sample', cl.BootstrapODPSample(random_state=42)), ('dev', cl.Development(average='volume')), ('tail', cl.TailCurve('exponential')), ('model', cl.Chainladder())]) pipe.fit(cl.load_sample('genins')) ``` -------------------------------- ### Get Unique Accident Years Source: https://github.com/casact/chainladder-python/blob/main/docs/getting_started/online_sandbox/sandbox_workbook_blank.ipynb Retrieves all unique values from the 'AccidentYear' column of the DataFrame. ```python xyz_df["AccidentYear"].unique() ``` -------------------------------- ### Get Link Ratios for Incurred Triangle Source: https://github.com/casact/chainladder-python/blob/main/docs/getting_started/online_sandbox/sandbox_workbook_blank.ipynb Calculates and retrieves the link ratios for the 'Incurred' triangle. ```python xyz_tri["Incurred"].link_ratio ``` -------------------------------- ### Load Sample Data with Pandas Source: https://github.com/casact/chainladder-python/blob/main/docs/getting_started/online_sandbox/sandbox_workbook_blank.ipynb Loads the 'xyz' sample dataset from a URL into a pandas DataFrame and displays the first few rows. ```python xyz_df = pd.read_csv( "https://raw.githubusercontent.com/casact/chainladder-python/master/chainladder/utils/data/xyz.csv" ) xyz_df.head() ``` -------------------------------- ### Four-Dimensional Slicing with iloc Source: https://github.com/casact/chainladder-python/blob/main/docs/library/releases.md Example of four-dimensional slicing using the iloc indexer on a Triangle object. ```python clrd = cl.load_sample('clrd') clrd.iloc[[0,10, 3], 1:8, :5, :] ``` -------------------------------- ### Load jupyter_black Source: https://github.com/casact/chainladder-python/blob/main/docs/getting_started/tutorials/triangle-tutorial.ipynb Optional step to lint your Jupyter notebooks using jupyter_black. Ensure jupyter_black is installed. ```python # import jupyter_black as jb # jb.load() ``` -------------------------------- ### Loading Sample Data Source: https://github.com/casact/chainladder-python/blob/main/docs/user_guide/development.ipynb Loads the 'abc' sample dataset using the chainladder library. ```python abc = cl.load_sample('abc') ``` -------------------------------- ### Get Chainladder Model IBNR Source: https://github.com/casact/chainladder-python/blob/main/docs/library/presentation_assets/demo-blank-concurrent.ipynb Calculate the Incurred But Not Reported (IBNR) estimate from a fitted chainladder model. ```python cl_model.ibnr() ``` -------------------------------- ### Calculate Ultimate Costs with Chainladder Source: https://github.com/casact/chainladder-python/blob/main/docs/user_guide/methods.ipynb Demonstrates how to fit a Chainladder model to sample data and access the calculated ultimate costs using the `ultimate_` property. ```python import chainladder as cl import pandas as pd cl.Chainladder().fit(cl.load_sample('raa')).ultimate_ ``` -------------------------------- ### Get Latest Diagonal Data Source: https://github.com/casact/chainladder-python/blob/main/docs/getting_started/online_sandbox/sandbox_workbook_blank.ipynb Extracts the latest diagonal values from a specified triangle (e.g., 'Incurred'). ```python xyz_tri["Incurred"].latest_diagonal ``` -------------------------------- ### Load Sample Data and Initialize Chainladder Source: https://github.com/casact/chainladder-python/blob/main/docs/gallery/plot_bf_apriori_from_cl.ipynb Loads the RAA sample dataset and initializes the Chainladder model. This is a prerequisite for fitting the model. ```python import chainladder as cl import pandas as pd raa = cl.load_sample('RAA') cl_ult = cl.Chainladder().fit(raa).ultimate_ ``` -------------------------------- ### Get Model's Ultimate Estimate Source: https://github.com/casact/chainladder-python/blob/main/docs/getting_started/online_sandbox/sandbox_workbook_filled.ipynb Retrieve the ultimate estimate calculated by the fitted chainladder model. ```python cl_mod.ultimate_ ``` -------------------------------- ### Install Chainladder with pixi Source: https://github.com/casact/chainladder-python/blob/main/docs/getting_started/install.md Use pixi to add the chainladder package from conda-forge. Suitable for projects managed with pixi. ```bash pixi add chainladder ``` -------------------------------- ### Initialize Development with Combined Drop Arguments Source: https://github.com/casact/chainladder-python/blob/main/docs/user_guide/development.ipynb Initializes the Development class, specifying a single link ratio to drop ('1985', 12) and a valuation period to drop ('1988'), and then fits the model to the 'raa' data. ```python cl.Development(drop=('1985', 12), drop_valuation='1988').fit(raa) ``` -------------------------------- ### Get Global Ultimate Valuation Date Source: https://github.com/casact/chainladder-python/blob/main/docs/user_guide/methods.ipynb Retrieves the globally set ultimate valuation date from chainladder options. ```python cl.options.get_option('ULT_VAL') ``` -------------------------------- ### Get Unique Package Names Source: https://github.com/casact/chainladder-python/blob/main/docs/library/presentation_assets/star_history.ipynb Retrieves an array of unique package names present in the 'Package' column of the DataFrame. ```python data["Package"].unique() ``` -------------------------------- ### Four-Dimensional Slicing with loc Source: https://github.com/casact/chainladder-python/blob/main/docs/library/releases.md Example of four-dimensional slicing using the loc indexer on a Triangle object, with label-based slicing. ```python clrd = cl.load_sample('clrd') clrd.loc[:'Aegis Grp', 'CumPaidLoss':, '1990':'1994', > :48] ``` -------------------------------- ### Importing Chainladder and Matplotlib Source: https://github.com/casact/chainladder-python/blob/main/docs/user_guide/triangle.ipynb Imports the chainladder library as 'cl' and matplotlib for plotting. This is a common setup for using the library. ```python import chainladder as cl import matplotlib.pyplot as plt plt.style.use('ggplot') %config InlineBackend.figure_format = 'retina' ``` -------------------------------- ### Instantiate Chainladder Estimator Source: https://github.com/casact/chainladder-python/blob/main/docs/getting_started/tutorials/deterministic-tutorial.ipynb Initializes a standard Chainladder estimator. ```python cl_mod = cl.Chainladder() ``` -------------------------------- ### Instantiate Estimator with Parameters Source: https://github.com/casact/chainladder-python/blob/main/docs/user_guide/development.ipynb Configure an estimator with specific parameters before fitting. These parameters define the model's behavior. ```python estimator = Estimator(param1=1, param2=2) ``` -------------------------------- ### Calculate Bornhuetter-Ferguson Ultimates with Apriori Source: https://github.com/casact/chainladder-python/blob/main/docs/gallery/plot_bf_apriori_from_cl.ipynb Demonstrates using the output of one method (Chainladder ultimate) as the apriori selection for the Bornhuetter-Ferguson Method. Basic arithmetic is used to build the apriori. ```python # Create Aprioris as the mean AY chainladder ultimate raa = cl.load_sample('RAA') cl_ult = cl.Chainladder().fit(raa).ultimate_ # Chainladder Ultimate apriori = cl_ult * 0 + (cl_ult.sum() / 10) # Mean Chainladder Ultimate bf_ult = cl.BornhuetterFerguson(apriori=1).fit(raa, sample_weight=apriori).ultimate_ output = pd.concat( (cl_ult.to_frame().rename({'2261': 'Chainladder'}, axis=1), bf_ult.to_frame().rename({'2261': 'BornhuetterFerguson'}, axis=1)), axis=1) ``` -------------------------------- ### Find Minimum Record Date Source: https://github.com/casact/chainladder-python/blob/main/docs/library/presentation_assets/star_history.ipynb Determines the earliest date in the 'Record_Date_P' column, representing the start of the recorded star history. ```python data["Record_Date_P"].min() ``` -------------------------------- ### Load Sample Data and Prepare Assumptions Source: https://github.com/casact/chainladder-python/blob/main/docs/friedland/chapter_7.rst Loads a sample development triangle and prepares a dictionary of assumptions for the dev_exhibit function. This involves parsing assumption names to extract parameters like the number of periods and the averaging method. ```python import re tri = cl.load_sample('friedland_xyz_auto_bi') assumptions_list = ['simple_5','simple_3','simple_2','volume_4','volume_3','volume_2','geometric_3'] assumptions = {x:{'n_periods':int(re.match(r'.+_(.+)', x).group(1)),'average':re.match(r'(.+)_', x).group(1)} for x in assumptions_list} ``` -------------------------------- ### Instantiate Expected Loss Estimator Source: https://github.com/casact/chainladder-python/blob/main/docs/getting_started/tutorials/deterministic-tutorial.ipynb Initializes the Expected Loss estimator. Requires the 'apriori' argument. ```python el_mod = cl.ExpectedLoss(apriori=1) ``` -------------------------------- ### Load Sample Data and Create Triangle Pipeline Source: https://github.com/casact/chainladder-python/blob/main/docs/getting_started/tutorials/deterministic-tutorial.ipynb Loads the 'genins' sample dataset and creates a Triangle with 'Development' patterns and a 'TailCurve' using a Pipeline. This prepares the data for the Chainladder model. ```python genins = cl.load_sample("genins") genins_dev = cl.Pipeline( [("dev", cl.Development()), ("tail", cl.TailCurve())] ).fit_transform(genins) ``` -------------------------------- ### Plot Loss Ratios Source: https://github.com/casact/chainladder-python/blob/main/docs/gallery/plot_exposure_triangle.ipynb Generates a stem plot of loss ratios using matplotlib. Ensure matplotlib is installed and configured for inline plotting. ```python import matplotlib.pyplot as plt plt.style.use('ggplot') %config InlineBackend.figure_format = 'retina' fig, ax = plt.subplots() plt.stem(loss_ratios.index.astype(str), loss_ratios.iloc[:, 0]) ax.grid(axis='y') for spine in ax.spines: ax.spines[spine].set_visible(False) plt.show(); ``` -------------------------------- ### Load Quarterly Triangle Data Source: https://github.com/casact/chainladder-python/blob/main/docs/user_guide/triangle.ipynb Loads a sample 'quarterly' triangle. This is often a starting point for analyses requiring finer-grained data than yearly. ```python cl.load_sample('quarterly') ``` -------------------------------- ### Load Sample Triangle and Print Summary Source: https://github.com/casact/chainladder-python/blob/main/docs/user_guide/triangle.ipynb Load the 'CLRD' sample dataset and print its shape and summary. This illustrates the summary view when multiple index or column dimensions are present. ```python triangle = cl.load_sample('CLRD') print(triangle.shape) triangle ``` -------------------------------- ### Percent Reported Example Source: https://github.com/casact/chainladder-python/blob/main/docs/friedland/chapter_7.rst Illustrates the percentage of ultimate claims reported at each development period. This helps in understanding the reporting pattern of claims over time. ```text Percent Reported 0.392 0.661 0.836 0.922 0.940 0.987 0.997 1.008 1.008 1.001 1.0 ``` -------------------------------- ### Load and Prepare 'wkcomp' Data Source: https://github.com/casact/chainladder-python/blob/main/docs/getting_started/tutorials/deterministic-tutorial.ipynb Loads the 'clrd' sample dataset, groups it by 'LOB', sums the values, and selects the 'CumPaidLoss' and 'EarnedPremNet' columns for 'wkcomp'. ```python wkcomp = ( cl.load_sample("clrd") .groupby("LOB") .sum() .loc["wkcomp"][[ "CumPaidLoss", "EarnedPremNet"]] ) wkcomp ``` -------------------------------- ### Import Libraries and Print Versions Source: https://github.com/casact/chainladder-python/blob/main/docs/getting_started/tutorials/stochastic-tutorial.ipynb Imports necessary libraries for actuarial analysis and prints their versions. This is a common setup for data analysis tasks. ```python # Black linter, optional # import jupyter_black as jb # jb.load() import pandas as pd import numpy as np import chainladder as cl import matplotlib.pyplot as plt import statsmodels.api as sm print("pandas: " + pd.__version__) print("numpy: " + np.__version__) print("chainladder: " + cl.__version__) ``` -------------------------------- ### Load Sample Data and Fit Chainladder Model Source: https://github.com/casact/chainladder-python/blob/main/docs/gallery/plot_ibnr_runoff.ipynb Loads the 'genins' sample dataset and fits a Chainladder model to it. This is the initial step for IBNR analysis. ```python import chainladder as cl # Create a triangle triangle = cl.load_sample('genins') # Fit a model model = cl.Chainladder().fit(triangle) ``` -------------------------------- ### Activate Development Environment Source: https://github.com/casact/chainladder-python/blob/main/docs/library/contributing.md Activates the development environment using uv for running tools like Jupyter Lab or Python. ```bash # Activate the environment uv run jupyter-lab # or uv run python ``` -------------------------------- ### Plot Link Ratios Source: https://github.com/casact/chainladder-python/blob/main/docs/gallery/plot_triangle_slicing.ipynb Generates a plot of link ratios for medical malpractice data using matplotlib. Ensure matplotlib is installed and configured for plotting. ```python import matplotlib.pyplot as plt plt.style.use('ggplot') %config InlineBackend.figure_format = 'retina' # Plot ax = clrd.link_ratio.T.plot( marker='o', title='Medical Malpractice Link Ratios', ylabel='Link Ratio', xlabel='Accident Year'); ``` -------------------------------- ### Plot IBNR Runoff Results Source: https://github.com/casact/chainladder-python/blob/main/docs/gallery/plot_ibnr_runoff.ipynb Visualizes the calculated calendar year IBNR runoff using matplotlib. Ensure matplotlib is installed and configured for plotting. ```python import matplotlib.pyplot as plt plt.style.use('ggplot') %config InlineBackend.figure_format = 'retina' # Plot results ax = cal_yr_runoff.dropna().T.plot( kind='bar', legend=False, title='GenIns: IBNR Run-off', alpha=0.7, xlabel='Calendar Year', ylabel='IBNR'); ``` -------------------------------- ### Get Exposure Vector for Expected Loss Method Source: https://github.com/casact/chainladder-python/blob/main/docs/getting_started/tutorials/stochastic-tutorial.ipynb Extracts an exposure vector from the `clrd` dataframe, which is required for expected loss methods like Bornhuetter-Ferguson. ```python sample_weight = clrd["EarnedPremNet"].latest_diagonal ``` -------------------------------- ### Get Chainladder Model Ultimate Estimate Source: https://github.com/casact/chainladder-python/blob/main/docs/getting_started/online_sandbox/sandbox_workbook_blank.ipynb Retrieves the ultimate loss estimate from a fitted Chainladder model. Requires filling in the method to access the estimate. ```python cl_mod.__fill_in_code__ ``` -------------------------------- ### Import Chainladder Library Source: https://github.com/casact/chainladder-python/blob/main/docs/gallery/plot_berqsherm_case.ipynb Imports the chainladder library for use in actuarial calculations. ```python import chainladder as cl ``` -------------------------------- ### Multi-index Broadcasting for LOB Alignment Source: https://github.com/casact/chainladder-python/blob/main/docs/library/releases.md Example showing multi-index broadcasting, specifically aligning data by 'LOB' (Line of Business) using groupby and sum. ```python clrd = cl.load_sample('clrd') clrd / clrd.groupby('LOB').sum() # LOB alignment works now instead of throwing error ``` -------------------------------- ### Calculate Compound Trends Source: https://github.com/casact/chainladder-python/blob/main/docs/user_guide/triangle.ipynb Calculates compound trend factors by chaining multiple trend calculations with specified start and end dates, then divides by the original triangle. ```python tri.trend(0.05, axis='valuation', start=tri.valuation_date, end='2011-12-31') \ .trend(0.10, axis='valuation', start='2011-12-31')/tri ``` -------------------------------- ### Load Sample Data and Define On-Leveling Factors Source: https://github.com/casact/chainladder-python/blob/main/docs/gallery/plot_capecod_onlevel.ipynb Loads the 'xyz' sample triangle and defines rate history and tort reform data for on-leveling calculations. Ensure pandas and chainladder are imported. ```python import chainladder as cl import pandas as pd ``` ```python # Grab a triangle xyz = cl.load_sample('xyz') # Premium on-leveling factors rate_history = pd.DataFrame({ 'date': ['1/1/1999', '1/1/2000', '1/1/2001', '1/1/2002', '1/1/2003', '1/1/2004', '1/1/2005', '1/1/2006', '1/1/2007', '1/1/2008'], 'rate_change': [.02, .02, .02, .02, .05, .075, .15, .1, -.2, -.2] }) # Loss on-leveling factors tort_reform = pd.DataFrame({ 'date': ['1/1/2006', '1/1/2007'], 'rate_change': [-0.1067, -.25] }) ``` -------------------------------- ### Initialize Development with Mixed Averaging Methods Source: https://github.com/casact/chainladder-python/blob/main/docs/user_guide/development.ipynb Initializes the Development class with a list specifying 'volume' for the first period and 'simple' for the remaining eight development periods. ```python cl.Development(average=['volume']+['simple']*8) ``` -------------------------------- ### Accessing the Valuation Date Source: https://github.com/casact/chainladder-python/blob/main/docs/getting_started/tutorials/triangle-tutorial.ipynb Get the valuation date associated with the triangle. This date represents the end of the most recent development period and is typically the last moment of the year. ```python raa.valuation_date ``` -------------------------------- ### GridSearch with Multiple Estimators and Parameters Source: https://github.com/casact/chainladder-python/blob/main/docs/user_guide/workflow.ipynb Demonstrates using GridSearch to test multiple estimators (Chainladder, CapeCod) with varying parameters. This allows for comprehensive scenario testing of different modeling approaches. ```python clrd = cl.load_sample('clrd')[['CumPaidLoss', 'EarnedPremDIR']].groupby('LOB').sum().loc['medmal'] grid = cl.GridSearch( estimator = cl.Pipeline(steps=[ ('dev', None), ('model', None)]), param_grid = [ {'dev': [cl.Development()], 'dev__n_periods': [-1, 3, 7], 'model': [cl.Chainladder()]}, {'dev': [cl.Development()], 'dev__n_periods': [-1, 3, 7], 'model': [cl.CapeCod()], 'model__decay': [0, .5, 1]}], scoring=lambda x : x.named_steps.model.ibnr_.sum('origin') ) grid.fit( X=clrd['CumPaidLoss'], sample_weight=clrd['EarnedPremDIR'].latest_diagonal) grid.results_ ``` -------------------------------- ### Load and Aggregate a Sample Triangle Source: https://github.com/casact/chainladder-python/blob/main/docs/user_guide/triangle.ipynb Loads the 'clrd' sample triangle and performs a basic aggregation using `sum()`. This is useful for getting a summary of the entire triangle. ```python clrd = cl.load_sample('clrd') clrd.sum() ``` -------------------------------- ### Load and Prepare Data for Modeling Source: https://github.com/casact/chainladder-python/blob/main/docs/gallery/plot_benktander.ipynb Loads sample data, groups it by Line of Business (LOB), and extracts relevant columns for Paid Loss and Earned Premium. ```python # Load Data clrd = cl.load_sample('clrd').groupby('LOB').sum() X = clrd.loc['medmal', 'CumPaidLoss'] sample_weight = clrd.loc['medmal', 'EarnedPremDIR'].latest_diagonal ``` -------------------------------- ### Get Valuation Date for Ultimates Source: https://github.com/casact/chainladder-python/blob/main/docs/getting_started/tutorials/deterministic-tutorial.ipynb Retrieves the valuation date used by the chainladder package for ultimate values. This date represents the highest allowable date for valuation. ```python genins_model.full_triangle_.valuation_date ``` -------------------------------- ### Filtering and Displaying Triangle Data Source: https://github.com/casact/chainladder-python/blob/main/docs/user_guide/triangle.ipynb This example filters a triangle by origin date and then displays the resulting subset. It demonstrates how filtering can reduce the data to relevant periods. ```python raa = cl.load_sample('raa') raa[raa.origin>'1987-01-01'] ``` -------------------------------- ### Set Global Array Backend Source: https://github.com/casact/chainladder-python/blob/main/docs/user_guide/triangle.ipynb Configure the default array backend for all Triangle instances globally. Use 'cupy' for GPU acceleration or 'sparse' for memory efficiency with sparse data. ```python cl.options.set_option('ARRAY_BACKEND', 'cupy') cl.options.reset_option() ``` -------------------------------- ### Cumulative Factors Example Source: https://github.com/casact/chainladder-python/blob/main/docs/friedland/chapter_7.rst Shows cumulative factors to ultimate, representing the total development from a given age to the final ultimate value. This is derived from age-to-age factors. ```text 12-Ult 24-Ult 36-Ult 48-Ult 60-Ult 72-Ult 84-Ult 96-Ult 108-Ult 120-Ult 132-Ult CDF to Ultimate 2.551 1.512 1.196 1.085 1.064 1.013 1.003 0.992 0.992 0.999 1.0 ``` -------------------------------- ### Age-to-Age Factors Example Source: https://github.com/casact/chainladder-python/blob/main/docs/friedland/chapter_7.rst Presents age-to-age factors derived from the reported claims data triangle. These factors represent the average development from one period to the next. ```text PART 2 - Age-to-Age Factors 12-24 24-36 36-48 48-60 60-72 72-84 84-96 96-108 108-120 120-132 1998 NaN NaN 1.108227 1.067528 1.064392 1.044146 1.114243 0.987596 0.979707 0.999179 1999 NaN 1.237646 1.197135 1.144305 1.057447 1.055967 0.988085 1.011131 1.001436 NaN 2000 1.196032 1.168062 1.239452 1.086354 1.168543 1.072291 1.015048 0.993094 NaN NaN 2001 1.353175 1.313547 1.264295 1.286967 1.085689 1.037834 1.006668 NaN NaN NaN 2002 1.590040 1.308591 1.413078 1.179122 1.096524 0.989076 NaN NaN NaN NaN 2003 1.760957 1.786055 1.337353 1.089595 1.003210 NaN NaN NaN NaN NaN 2004 2.364225 1.465057 1.218140 0.980211 NaN NaN NaN NaN NaN NaN 2005 1.654181 1.482965 1.004478 NaN NaN NaN NaN NaN NaN NaN 2006 1.728479 1.043199 NaN NaN NaN NaN NaN NaN NaN NaN 2007 1.629204 NaN NaN NaN NaN NaN NaN NaN NaN NaN ``` -------------------------------- ### Simulate IBNR and Calculate VaR Source: https://github.com/casact/chainladder-python/blob/main/docs/gallery/plot_value_at_risk.ipynb Estimates 1000 IBNR values from the resampled triangles using Chainladder and calculates the Value at Risk by finding percentiles of the simulated IBNR distribution. ```python # Create 1000 IBNR estimates sim_ibnr = cl.Chainladder().fit(resampled_triangles).ibnr_.sum('origin') # X - mu sim_ibnr = (sim_ibnr - sim_ibnr.mean()).to_frame().sort_values() ``` -------------------------------- ### Groupby Summation on Triangle Data Source: https://github.com/casact/chainladder-python/blob/main/docs/library/releases.md Demonstrates advanced groupby operations on Triangle data. This example splits companies based on name length and then sums their data. ```python clrd = cl.load_sample('clrd') # Split companies with names less than 15 characters vs those above: clrd.groupby(clrd.index['GRNAME'].str.len()<15).sum() ``` -------------------------------- ### Load Sample Data Source: https://github.com/casact/chainladder-python/blob/main/docs/getting_started/tutorials/deterministic-tutorial.ipynb Loads the 'raa' dataset for use with chainladder models. ```python raa = cl.load_sample("raa") ``` -------------------------------- ### Complex Trends with Trend Transformer Source: https://github.com/casact/chainladder-python/blob/main/docs/library/releases.md Example showcasing the use of the Trend transformer for handling complex trends in estimators. Refer to the official documentation for detailed usage. ```python clrd = cl.load_sample('clrd') # Example usage of Trend transformer would go here, referencing the gallery example. ``` -------------------------------- ### Fit Chainladder Model and Calculate Emergence Source: https://github.com/casact/chainladder-python/blob/main/docs/gallery/plot_loss_development.ipynb Loads sample quarterly data, applies a development and tail curve pipeline, fits the Chainladder estimator, and calculates the actual and expected emergence patterns as a percentage of ultimate claims. ```python # Load sample data quarterly = cl.load_sample('quarterly')['incurred'] quarterly_dev = cl.Pipeline([ ("dev", cl.Development()), ("tail", cl.TailCurve(projection_period=0)) # neglect tail projection ]).fit_transform(quarterly) # Fit Chainladder estimator quarterly_model = cl.Chainladder().fit(quarterly_dev) # Calculate emergence triangle and expected emergence emergence = (quarterly / quarterly_model.ultimate_).T expected = (1 / quarterly_model.cdf_).T # Unify results in a single DataFrame expected.index = emergence.index expected.columns = ['Expected'] result = pd.concat([emergence, expected], axis=1, keys=['Actual', 'Expected']) ``` -------------------------------- ### Load Sample Dataset Source: https://github.com/casact/chainladder-python/blob/main/docs/getting_started/tutorials/data-tutorial.ipynb Loads the 'prism' dataset, which is a claim-level dataset with over 130,000 triangles. This dataset is used to demonstrate sparse data handling. ```python prism = cl.load_sample("prism") prism ``` -------------------------------- ### chainladder.utils Functions Source: https://github.com/casact/chainladder-python/blob/main/docs/library/api.md Utility functions for loading data, reading files, and performing basic operations. ```APIDOC ## Functions .. currentmodule:: chainladder .. autosummary:: :toctree: generated/ :template: function load_sample list_samples read_pickle read_json concat minimum maximum ``` -------------------------------- ### Plot Bondy Assumption Sensitivity Source: https://github.com/casact/chainladder-python/blob/main/docs/gallery/plot_bondy_sensitivity.ipynb Generates a plot showing the sensitivity of the Bondy exponent and tail factor to the 'earliest_age' assumption using matplotlib. Requires matplotlib to be installed. ```python import matplotlib.pyplot as plt plt.style.use('ggplot') %config InlineBackend.figure_format = 'retina' ax = results.plot(x='earliest_age', y='bondy_exponent', title='Bondy Assumption Sensitivity', marker='o') results.plot(x='earliest_age', y='tail_factor', grid=True, secondary_y=True, ax=ax, marker='o'); ``` -------------------------------- ### Re-fit Benktander Estimator Source: https://github.com/casact/chainladder-python/blob/main/docs/getting_started/tutorials/deterministic-tutorial.ipynb Demonstrates refitting the Benktander estimator with the same parameters, showing the fitting process is identical. ```python bk_model.fit( X=comauto["CumPaidLoss"], sample_weight=comauto["EarnedPremNet"].latest_diagonal ) ``` -------------------------------- ### Apply Pipeline to Bootstrapped Samples Source: https://github.com/casact/chainladder-python/blob/main/docs/getting_started/tutorials/stochastic-tutorial.ipynb Applies a predefined Pipeline, including Development and TailConstant steps, to the bootstrapped samples. This demonstrates that bootstrapped samples can be treated as regular triangles for further analysis. ```python pipe = cl.Pipeline( steps=[("dev", cl.Development(average="simple")), ("tail", cl.TailConstant(1.05))] ) pipe.fit(samples) ``` -------------------------------- ### Access Cumulative Paid Loss Data Source: https://github.com/casact/chainladder-python/blob/main/docs/getting_started/tutorials/stochastic-tutorial.ipynb Retrieves the cumulative paid loss data from the 'CumPaidLoss' column of the 'clrd' DataFrame. This is a common starting point for actuarial analysis. ```python clrd["CumPaidLoss"] ``` -------------------------------- ### Performance Comparison: Accumulating to Get Latest Diagonal Source: https://github.com/casact/chainladder-python/blob/main/docs/user_guide/triangle.ipynb Measures the time taken to accumulate a large triangle to obtain the latest diagonal, highlighting a less performant method. ```python # Accumulating a large triangle to get latest_diagonal - BAD timeit.timeit(lambda : prism.incr_to_cum().latest_diagonal, number=1) ``` -------------------------------- ### Bootstrap ODP Sample for Chainladder Source: https://github.com/casact/chainladder-python/blob/main/docs/getting_started/online_sandbox/sandbox_workbook_filled.ipynb This snippet generates 10,000 simulated incurred triangles using the BootstrapODPSample method. It requires the 'chainladder' library imported as 'cl' and the 'xyz_tri' DataFrame. ```python xyz_tri_sampled = ( cl.BootstrapODPSample(n_sims=10000).fit(xyz_tri["Incurred"])).resampled_triangles_ ``` -------------------------------- ### Fit Development Estimator and Get Standardized Residuals Source: https://github.com/casact/chainladder-python/blob/main/docs/user_guide/development.ipynb Loads sample data, fits the Development estimator, and accesses the standardized residuals. This is useful for diagnosing model fit. ```python raa = cl.load_sample('raa') model = cl.Development().fit(્રા) model.std_residuals_ ``` -------------------------------- ### Instantiate Benktander Estimator Source: https://github.com/casact/chainladder-python/blob/main/docs/getting_started/tutorials/deterministic-tutorial.ipynb Initializes the Benktander estimator. Requires 'apriori' and 'n_iters' arguments. ```python bk_mod = cl.Benktander(apriori=1, n_iters=2) ``` -------------------------------- ### Initialize and Fit Development Estimator Source: https://github.com/casact/chainladder-python/blob/main/docs/user_guide/development.ipynb Initialize a Development estimator and fit it to sample data. This process calculates fitted age-to-age factors (ldf_) and cumulative factors (cdf_). ```python import chainladder as cl import pandas as pd import matplotlib.pyplot as plt plt.style.use('ggplot') %config InlineBackend.figure_format = 'retina' dev = cl.Development().fit(cl.load_sample('ukmotor')) type(dev.cdf_) ``` -------------------------------- ### Initialize and Fit Benktander Estimator Source: https://github.com/casact/chainladder-python/blob/main/docs/getting_started/tutorials/deterministic-tutorial.ipynb Initializes and fits the Benktander estimator with specified apriori and number of iterations. This method generalizes Bornhuetter-Ferguson and Chainladder. ```python bk_model = cl.Benktander(apriori=0.75, n_iters=2) bk_model.fit( comauto["CumPaidLoss"], sample_weight=comauto["EarnedPremNet"].latest_diagonal ) ``` -------------------------------- ### Triangle Arithmetic with Array and Index Mismatch Source: https://github.com/casact/chainladder-python/blob/main/docs/user_guide/triangle.ipynb This example demonstrates arithmetic between a Triangle and a numpy array derived from a sorted Triangle, resulting in a mismatch due to index alignment. ```python s1 + s2.values == 2 * s1 ```