Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 14 additions & 12 deletions docs/gallery/plot_advanced_triangle.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -44,23 +44,23 @@
},
"outputs": [],
"source": [
"clrd = cl.load_sample('clrd')\n",
"clrd = clrd[clrd['LOB']=='comauto']\n",
"clrd = cl.load_sample(\"clrd\")\n",
"clrd = clrd[clrd[\"LOB\"] == \"comauto\"]\n",
"\n",
"# Create a loss ratio virtual column\n",
"clrd['LossRatio'] = lambda clrd: clrd['IncurLoss'] / clrd['EarnedPremDIR']\n",
"clrd[\"LossRatio\"] = lambda clrd: clrd[\"IncurLoss\"] / clrd[\"EarnedPremDIR\"]\n",
"\n",
"# Identify the largest companies (by premium) for 1997\n",
"top_10 = clrd['EarnedPremDIR'].groupby('GRNAME').sum().latest_diagonal\n",
"top_10 = top_10.loc[..., '1997', :].to_frame().nlargest(10)\n",
"top_10 = clrd[\"EarnedPremDIR\"].groupby(\"GRNAME\").sum().latest_diagonal\n",
"top_10 = top_10.loc[..., \"1997\", :].to_frame().nlargest(10)\n",
"\n",
"# Group any companies together that are not in the top 10\n",
"clrd = clrd.groupby(clrd.index['GRNAME'].map(\n",
" lambda x: x if x in top_10.index else 'Remainder')).sum()\n",
"clrd = clrd.groupby(\n",
" clrd.index[\"GRNAME\"].map(lambda x: x if x in top_10.index else \"Remainder\")\n",
").sum()\n",
"\n",
"# Sort by company volume, but keep Remainder as last entry\n",
"clrd = clrd.loc[top_10.index.to_list() + ['Remainder']].iloc[::-1]\n",
"\n"
"clrd = clrd.loc[top_10.index.to_list() + [\"Remainder\"]].iloc[::-1]"
]
},
{
Expand Down Expand Up @@ -90,12 +90,14 @@
],
"source": [
"import matplotlib.pyplot as plt\n",
"plt.style.use('ggplot')\n",
"\n",
"plt.style.use(\"ggplot\")\n",
"%config InlineBackend.figure_format = 'retina'\n",
"\n",
"\n",
"ax = clrd.latest_diagonal.sum('origin')['LossRatio'].plot(\n",
" kind='barh', title='Loss Ratio');"
"ax = clrd.latest_diagonal.sum(\"origin\")[\"LossRatio\"].plot(\n",
" kind=\"barh\", title=\"Loss Ratio\"\n",
");"
]
},
{
Expand Down
33 changes: 18 additions & 15 deletions docs/gallery/plot_ave_analysis.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,8 @@
},
"outputs": [],
"source": [
"tri_1997 = cl.load_sample('clrd')\n",
"tri_1997 = tri_1997.groupby('LOB').sum().loc['medmal']['CumPaidLoss']"
"tri_1997 = cl.load_sample(\"clrd\")\n",
"tri_1997 = tri_1997.groupby(\"LOB\").sum().loc[\"medmal\"][\"CumPaidLoss\"]"
]
},
{
Expand All @@ -62,12 +62,12 @@
"outputs": [],
"source": [
"# Create a triangle as of the previous valuation and build IBNR model\n",
"tri_1996 = tri_1997[tri_1997.valuation < '1997']\n",
"tri_1996 = tri_1997[tri_1997.valuation < \"1997\"]\n",
"model_1996 = cl.Chainladder().fit(cl.TailCurve().fit_transform(tri_1996))\n",
"\n",
"# Slice the expected losses from the 1997 calendar period of the model\n",
"ave = model_1996.full_triangle_.dev_to_val()\n",
"ave = ave[ave.valuation==tri_1997.valuation_date].rename('columns', 'Expected')"
"ave = ave[ave.valuation == tri_1997.valuation_date].rename(\"columns\", \"Expected\")"
]
},
{
Expand All @@ -85,7 +85,7 @@
"outputs": [],
"source": [
"# Slice the actual losses from the 1997 calendar period for prior AYs\n",
"ave['Actual'] = tri_1997.latest_diagonal[tri_1997.origin < '1997']\n",
"ave[\"Actual\"] = tri_1997.latest_diagonal[tri_1997.origin < \"1997\"]\n",
"df = ave.to_frame().T.iloc[::-1]"
]
},
Expand Down Expand Up @@ -116,23 +116,26 @@
],
"source": [
"import matplotlib.pyplot as plt\n",
"plt.style.use('ggplot')\n",
"\n",
"plt.style.use(\"ggplot\")\n",
"%config InlineBackend.figure_format = 'retina'\n",
"\n",
"# Plotting\n",
"fig, ax = plt.subplots()\n",
"ax.grid(axis='x')\n",
"ax.grid(axis=\"x\")\n",
"plt.hlines(\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",
"plt.scatter(df['Expected'], df.index.astype(str), alpha=0.8 , label='Expected')\n",
" y=df.index.astype(str),\n",
" xmin=df[\"Actual\"],\n",
" xmax=df[\"Expected\"],\n",
" color=\"grey\",\n",
" alpha=0.4,\n",
")\n",
"plt.scatter(df[\"Actual\"], df.index.astype(str), alpha=1, label=\"Actual\")\n",
"plt.scatter(df[\"Expected\"], df.index.astype(str), alpha=0.8, label=\"Expected\")\n",
"plt.legend()\n",
"plt.title(\"Actual vs Expected results in 1997\")\n",
"plt.xlabel('Difference')\n",
"plt.ylabel('Origin');"
"plt.xlabel(\"Difference\")\n",
"plt.ylabel(\"Origin\");"
]
},
{
Expand Down
46 changes: 26 additions & 20 deletions docs/gallery/plot_benktander.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -46,21 +46,25 @@
"outputs": [],
"source": [
"# Load Data\n",
"clrd = cl.load_sample('clrd').groupby('LOB').sum()\n",
"X = clrd.loc['medmal', 'CumPaidLoss']\n",
"sample_weight = clrd.loc['medmal', 'EarnedPremDIR'].latest_diagonal\n",
"clrd = cl.load_sample(\"clrd\").groupby(\"LOB\").sum()\n",
"X = clrd.loc[\"medmal\", \"CumPaidLoss\"]\n",
"sample_weight = clrd.loc[\"medmal\", \"EarnedPremDIR\"].latest_diagonal\n",
"\n",
"# Specify Model\n",
"grid = cl.GridSearch(\n",
" estimator=cl.Pipeline(steps=[\n",
" ('dev', cl.Development()),\n",
" ('tail', cl.TailCurve()),\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",
" scoring={'IBNR': lambda x: x.named_steps.model.ibnr_.sum()},\n",
" n_jobs=-1)"
" estimator=cl.Pipeline(\n",
" steps=[\n",
" (\"dev\", cl.Development()),\n",
" (\"tail\", cl.TailCurve()),\n",
" (\"model\", cl.Benktander()),\n",
" ]\n",
" ),\n",
" param_grid=dict(\n",
" model__n_iters=list(range(1, 100, 2)), model__apriori=[0.50, 0.75, 1.00]\n",
" ),\n",
" scoring={\"IBNR\": lambda x: x.named_steps.model.ibnr_.sum()},\n",
" n_jobs=-1,\n",
")"
]
},
{
Expand Down Expand Up @@ -120,7 +124,8 @@
],
"source": [
"from sklearn import set_config\n",
"set_config(display='diagram')\n",
"\n",
"set_config(display=\"diagram\")\n",
"grid"
]
},
Expand Down Expand Up @@ -225,9 +230,8 @@
"\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\", columns=\"model__apriori\", values=\"IBNR\"\n",
")\n",
"output.head()"
]
},
Expand Down Expand Up @@ -266,13 +270,15 @@
],
"source": [
"import matplotlib.pyplot as plt\n",
"plt.style.use('ggplot')\n",
"\n",
"plt.style.use(\"ggplot\")\n",
"%config InlineBackend.figure_format = 'retina'\n",
"\n",
"ax = (output / 1e6).plot(\n",
" ylabel='IBNR (Millions)',\n",
" xlabel='Number of Iterations',\n",
" title='Benktander convergence to Chainladder');"
" ylabel=\"IBNR (Millions)\",\n",
" xlabel=\"Number of Iterations\",\n",
" title=\"Benktander convergence to Chainladder\",\n",
");"
]
},
{
Expand Down
30 changes: 18 additions & 12 deletions docs/gallery/plot_bondy_sensitivity.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -47,19 +47,19 @@
"outputs": [],
"source": [
"# Fit basic development to a triangle\n",
"tri = cl.load_sample('tail_sample')['paid']\n",
"dev = cl.Development(average='simple').fit_transform(tri)\n",
"tri = cl.load_sample(\"tail_sample\")[\"paid\"]\n",
"dev = cl.Development(average=\"simple\").fit_transform(tri)\n",
"\n",
"# Return both the tail factor and the Bondy exponent in the scoring function\n",
"scoring = {\n",
" 'tail_factor': lambda x: x.tail_.values[0,0],\n",
" 'bondy_exponent': lambda x : x.b_.values[0,0]}\n",
" \"tail_factor\": lambda x: x.tail_.values[0, 0],\n",
" \"bondy_exponent\": lambda x: x.b_.values[0, 0],\n",
"}\n",
"\n",
"# Vary the 'earliest_age' assumption in GridSearch\n",
"param_grid=dict(earliest_age=list(range(12, 120, 12)))\n",
"param_grid = dict(earliest_age=list(range(12, 120, 12)))\n",
"grid = cl.GridSearch(cl.TailBondy(), param_grid, scoring)\n",
"results = grid.fit(dev).results_\n",
"\n"
"results = grid.fit(dev).results_"
]
},
{
Expand Down Expand Up @@ -89,13 +89,19 @@
],
"source": [
"import matplotlib.pyplot as plt\n",
"plt.style.use('ggplot')\n",
"\n",
"plt.style.use(\"ggplot\")\n",
"%config InlineBackend.figure_format = 'retina'\n",
"\n",
"ax = results.plot(x='earliest_age', y='bondy_exponent',\n",
" title='Bondy Assumption Sensitivity', marker='o')\n",
"results.plot(x='earliest_age', y='tail_factor', grid=True,\n",
" secondary_y=True, ax=ax, marker='o');"
"ax = results.plot(\n",
" x=\"earliest_age\",\n",
" y=\"bondy_exponent\",\n",
" title=\"Bondy Assumption Sensitivity\",\n",
" marker=\"o\",\n",
")\n",
"results.plot(\n",
" x=\"earliest_age\", y=\"tail_factor\", grid=True, secondary_y=True, ax=ax, marker=\"o\"\n",
");"
]
},
{
Expand Down
36 changes: 24 additions & 12 deletions docs/gallery/plot_bootstrap.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,8 @@
},
"outputs": [],
"source": [
"import chainladder as cl\n",
"\n",
"# Grab a Triangle\n",
"tri = cl.load_sample('genins')\n",
"tri = cl.load_sample(\"genins\")\n",
"\n",
"# Generate bootstrap samples\n",
"sims = cl.BootstrapODPSample(random_state=42).fit_transform(tri)\n",
Expand All @@ -57,7 +55,7 @@
"plot2 = (sims.sum() / 1000).T / 1e6\n",
"plot3a = sim_ldf.T\n",
"plot3b = cl.Development().fit(tri).ldf_.drop_duplicates().T\n",
"plot4 = sim_ldf.T.loc['12-24']"
"plot4 = sim_ldf.T.loc[\"12-24\"]"
]
},
{
Expand Down Expand Up @@ -87,27 +85,41 @@
],
"source": [
"import matplotlib.pyplot as plt\n",
"plt.style.use('ggplot')\n",
"\n",
"plt.style.use(\"ggplot\")\n",
"%config InlineBackend.figure_format = 'retina'\n",
"\n",
"# Plot the Data\n",
"fig, ((ax00, ax01), (ax10, ax11)) = plt.subplots(ncols=2, nrows=2, figsize=(10,10))\n",
"fig, ((ax00, ax01), (ax10, ax11)) = plt.subplots(ncols=2, nrows=2, figsize=(10, 10))\n",
"\n",
"# Plot 1\n",
"plot1.plot(ax=ax00, title='Raw Data', xlabel='Development', ylabel='Incurred (Millions)')\n",
"plot1.plot(\n",
" ax=ax00, title=\"Raw Data\", xlabel=\"Development\", ylabel=\"Incurred (Millions)\"\n",
")\n",
"\n",
"# Plot 2\n",
"plot2.plot(ax=ax01, title='Mean Simulation (Millions)', xlabel='Development')\n",
"plot2.plot(ax=ax01, title=\"Mean Simulation (Millions)\", xlabel=\"Development\")\n",
"\n",
"# Plot 3\n",
"plot3a.plot(legend=False, color='lightgray', ax=ax10, \n",
" title='Simulated LDF', xlabel='Development', ylabel='LDF')\n",
"plot3a.plot(\n",
" legend=False,\n",
" color=\"lightgray\",\n",
" ax=ax10,\n",
" title=\"Simulated LDF\",\n",
" xlabel=\"Development\",\n",
" ylabel=\"LDF\",\n",
")\n",
"plot3b.plot(legend=False, ax=ax10, grid=True)\n",
"\n",
"# Plot 4\n",
"plot4.plot(\n",
" kind='hist', bins=50, alpha=0.5, ax=ax11,\n",
" title='Age 12-24 LDF Distribution', xlabel='LDF');"
" kind=\"hist\",\n",
" bins=50,\n",
" alpha=0.5,\n",
" ax=ax11,\n",
" title=\"Age 12-24 LDF Distribution\",\n",
" xlabel=\"LDF\",\n",
");"
]
},
{
Expand Down
35 changes: 23 additions & 12 deletions docs/gallery/plot_bootstrap_comparison.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -42,23 +42,29 @@
"outputs": [],
"source": [
"# Load triangle\n",
"triangle = cl.load_sample('genins')\n",
"triangle = cl.load_sample(\"genins\")\n",
"\n",
"# Use bootstrap sampler to get resampled triangles\n",
"s1 = cl.BootstrapODPSample(\n",
" n_sims=5000, random_state=42).fit(triangle).resampled_triangles_\n",
"s1 = (\n",
" cl\n",
" .BootstrapODPSample(n_sims=5000, random_state=42)\n",
" .fit(triangle)\n",
" .resampled_triangles_\n",
")\n",
"\n",
"## Alternatively use fit_transform() to access resampled triangles dropping\n",
"# 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_sims=5000,\n",
" random_state=42,\n",
").fit_transform(triangle)\n",
"\n",
"# Summarize results of first model\n",
"results = cl.Chainladder().fit(s1).ibnr_.sum('origin').rename('columns', ['Original'])\n",
"results = cl.Chainladder().fit(s1).ibnr_.sum(\"origin\").rename(\"columns\", [\"Original\"])\n",
"# Add another column to triangle with second set of results.\n",
"results['Dropped'] = cl.Chainladder().fit(s2).ibnr_.sum('origin')"
"results[\"Dropped\"] = cl.Chainladder().fit(s2).ibnr_.sum(\"origin\")"
]
},
{
Expand Down Expand Up @@ -88,13 +94,18 @@
],
"source": [
"import matplotlib.pyplot as plt\n",
"plt.style.use('ggplot')\n",
"\n",
"plt.style.use(\"ggplot\")\n",
"%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",
" grid=True, xlabel='Ultimate',\n",
" title='Reserve Variability')"
" kind=\"hist\",\n",
" bins=50,\n",
" alpha=0.5,\n",
" grid=True,\n",
" xlabel=\"Ultimate\",\n",
" title=\"Reserve Variability\",\n",
")"
]
}
],
Expand Down
Loading
Loading