Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,117 +2,146 @@ import gradio as gr
|
|
| 2 |
import pandas as pd
|
| 3 |
import numpy as np
|
| 4 |
from sklearn.cluster import KMeans
|
| 5 |
-
from sklearn.metrics import r2_score
|
| 6 |
import matplotlib.pyplot as plt
|
| 7 |
import io
|
|
|
|
| 8 |
|
| 9 |
-
def
|
| 10 |
-
# Basic checks and reads
|
| 11 |
try:
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
kmeans.fit(X_scaled)
|
| 30 |
-
policy_df['
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
metrics_text = (
|
| 89 |
-
f"R-squared for aggregated cashflows: {r2:.4f}\n"
|
| 90 |
-
f"Absolute percentage error in present value: {pv_error:.4f}%"
|
| 91 |
-
)
|
| 92 |
|
| 93 |
-
|
|
|
|
| 94 |
|
|
|
|
| 95 |
with gr.Blocks() as demo:
|
| 96 |
-
gr.Markdown("
|
| 97 |
-
|
| 98 |
with gr.Row():
|
| 99 |
with gr.Column():
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
run_btn = gr.Button("Run Clustering")
|
| 105 |
-
|
| 106 |
with gr.Column():
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
|
| 112 |
run_btn.click(
|
| 113 |
-
|
| 114 |
-
inputs=[
|
| 115 |
-
outputs=[output_csv,
|
| 116 |
)
|
| 117 |
|
| 118 |
-
demo.launch(
|
|
|
|
| 2 |
import pandas as pd
|
| 3 |
import numpy as np
|
| 4 |
from sklearn.cluster import KMeans
|
| 5 |
+
from sklearn.metrics import r2_score, pairwise_distances_argmin_min
|
| 6 |
import matplotlib.pyplot as plt
|
| 7 |
import io
|
| 8 |
+
import os
|
| 9 |
|
| 10 |
+
def run_cluster_analysis(policy_file, cashflow_file, pv_file, num_clusters, cluster_type):
|
|
|
|
| 11 |
try:
|
| 12 |
+
# Load data
|
| 13 |
+
policy_df = pd.read_excel(policy_file)
|
| 14 |
+
cashflow_df = pd.read_excel(cashflow_file, index_col=0)
|
| 15 |
+
pv_df = pd.read_excel(pv_file, index_col=0)
|
| 16 |
+
|
| 17 |
+
# Normalize column names for robustness
|
| 18 |
+
policy_df.columns = policy_df.columns.str.strip().str.lower()
|
| 19 |
+
pv_df.columns = pv_df.columns.str.strip().str.lower()
|
| 20 |
+
|
| 21 |
+
if cluster_type == "Policy Attributes":
|
| 22 |
+
required_cols = ['issueage', 'policyterm', 'sumassured', 'duration']
|
| 23 |
+
missing = [col for col in required_cols if col not in policy_df.columns]
|
| 24 |
+
if missing:
|
| 25 |
+
return (None, None, None, f"Policy data missing required columns: {missing}")
|
| 26 |
+
X = policy_df[required_cols].fillna(0)
|
| 27 |
+
elif cluster_type == "Net Cashflows":
|
| 28 |
+
X = cashflow_df.fillna(0)
|
| 29 |
+
elif cluster_type == "Present Values":
|
| 30 |
+
if 'pv_net_cf' not in pv_df.columns:
|
| 31 |
+
return (None, None, None, "Missing 'PV_Net_CF' column in PV file.")
|
| 32 |
+
X = pv_df[['pv_net_cf']].fillna(0)
|
| 33 |
+
else:
|
| 34 |
+
return (None, None, None, "Invalid clustering variable choice.")
|
| 35 |
+
|
| 36 |
+
# Scale data
|
| 37 |
+
X_scaled = (X - X.mean()) / X.std(ddof=0)
|
| 38 |
+
X_scaled = X_scaled.fillna(0)
|
| 39 |
+
|
| 40 |
+
# Run KMeans
|
| 41 |
+
kmeans = KMeans(n_clusters=num_clusters, random_state=42, n_init='auto')
|
| 42 |
kmeans.fit(X_scaled)
|
| 43 |
+
policy_df['cluster'] = kmeans.labels_
|
| 44 |
+
|
| 45 |
+
# Get closest policies (model points)
|
| 46 |
+
closest_idxs = pairwise_distances_argmin_min(kmeans.cluster_centers_, X_scaled)[0]
|
| 47 |
+
model_points = policy_df.iloc[closest_idxs].copy()
|
| 48 |
+
cluster_counts = policy_df['cluster'].value_counts()
|
| 49 |
+
model_points['weight'] = model_points['cluster'].map(cluster_counts)
|
| 50 |
+
|
| 51 |
+
# Aggregate comparisons
|
| 52 |
+
total_seriatim_cf = cashflow_df.sum(axis=0)
|
| 53 |
+
total_seriatim_pv = pv_df.sum(axis=0)
|
| 54 |
+
proxy_cf = cashflow_df.loc[model_points.index].multiply(model_points['weight'], axis=0).sum(axis=0)
|
| 55 |
+
proxy_pv = pv_df.loc[model_points.index].multiply(model_points['weight'], axis=0).sum(axis=0)
|
| 56 |
+
|
| 57 |
+
# Output CSV
|
| 58 |
+
csv_buf = io.StringIO()
|
| 59 |
+
model_points.to_csv(csv_buf, index=False)
|
| 60 |
+
csv_bytes = csv_buf.getvalue().encode()
|
| 61 |
+
|
| 62 |
+
# Cashflow plot
|
| 63 |
+
fig1, ax1 = plt.subplots()
|
| 64 |
+
total_seriatim_cf.plot(ax=ax1, label="Seriatim", color="blue")
|
| 65 |
+
proxy_cf.plot(ax=ax1, label="Proxy", linestyle="--", color="orange")
|
| 66 |
+
ax1.set_title("Aggregated Cashflows")
|
| 67 |
+
ax1.legend()
|
| 68 |
+
ax1.grid()
|
| 69 |
+
buf1 = io.BytesIO()
|
| 70 |
+
plt.savefig(buf1, format='png')
|
| 71 |
+
buf1.seek(0)
|
| 72 |
+
plt.close(fig1)
|
| 73 |
+
|
| 74 |
+
# PV plot
|
| 75 |
+
fig2, ax2 = plt.subplots()
|
| 76 |
+
pv_plot = pd.DataFrame({
|
| 77 |
+
"Seriatim PV": [total_seriatim_pv.iloc[0]],
|
| 78 |
+
"Proxy PV": [proxy_pv.iloc[0]]
|
| 79 |
+
})
|
| 80 |
+
pv_plot.plot(kind="bar", ax=ax2, color=["blue", "orange"])
|
| 81 |
+
ax2.set_title("Aggregated Present Values")
|
| 82 |
+
ax2.set_xticks([0])
|
| 83 |
+
ax2.set_xticklabels(["Total PV"])
|
| 84 |
+
ax2.grid(axis='y')
|
| 85 |
+
buf2 = io.BytesIO()
|
| 86 |
+
plt.savefig(buf2, format='png')
|
| 87 |
+
buf2.seek(0)
|
| 88 |
+
plt.close(fig2)
|
| 89 |
+
|
| 90 |
+
# Metrics
|
| 91 |
+
r2 = r2_score(total_seriatim_cf, proxy_cf)
|
| 92 |
+
pv_err = abs((proxy_pv.iloc[0] - total_seriatim_pv.iloc[0]) / total_seriatim_pv.iloc[0]) * 100
|
| 93 |
+
metrics = (
|
| 94 |
+
f"--- Accuracy Metrics ---\n"
|
| 95 |
+
f"R-squared (Cashflows): {r2:.4f}\n"
|
| 96 |
+
f"Absolute % Error (Present Value): {pv_err:.2f}%"
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
return csv_bytes, buf1, buf2, metrics
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
|
| 101 |
+
except Exception as e:
|
| 102 |
+
return (None, None, None, f"An error occurred: {str(e)}")
|
| 103 |
|
| 104 |
+
# Build UI
|
| 105 |
with gr.Blocks() as demo:
|
| 106 |
+
gr.Markdown("## Actuarial Model Point Selection via Cluster Analysis")
|
| 107 |
+
|
| 108 |
with gr.Row():
|
| 109 |
with gr.Column():
|
| 110 |
+
policy_file = gr.File(label="Upload Policy Data (.xlsx)", file_types=[".xlsx", ".xls"])
|
| 111 |
+
cashflow_file = gr.File(label="Upload Cashflow Data (.xlsx)", file_types=[".xlsx", ".xls"])
|
| 112 |
+
pv_file = gr.File(label="Upload Present Value Data (.xlsx)", file_types=[".xlsx", ".xls"])
|
| 113 |
+
|
|
|
|
|
|
|
| 114 |
with gr.Column():
|
| 115 |
+
num_clusters = gr.Slider(10, 2000, value=1000, step=10, label="Number of Model Points (k)")
|
| 116 |
+
cluster_type = gr.Dropdown(
|
| 117 |
+
["Policy Attributes", "Net Cashflows", "Present Values"],
|
| 118 |
+
value="Present Values",
|
| 119 |
+
label="Clustering Variable"
|
| 120 |
+
)
|
| 121 |
+
run_btn = gr.Button("Run Cluster Analysis")
|
| 122 |
+
|
| 123 |
+
with gr.Row():
|
| 124 |
+
output_csv = gr.File(label="Download Model Points (CSV)")
|
| 125 |
+
output_cf_plot = gr.Image(label="Cashflow Comparison")
|
| 126 |
+
output_pv_plot = gr.Image(label="PV Comparison")
|
| 127 |
+
output_metrics = gr.Textbox(label="Accuracy Metrics", lines=5)
|
| 128 |
+
|
| 129 |
+
def wrapper(policy_file, cashflow_file, pv_file, num_clusters, cluster_type):
|
| 130 |
+
csv_bytes, img_cf, img_pv, metrics = run_cluster_analysis(policy_file.name, cashflow_file.name, pv_file.name, num_clusters, cluster_type)
|
| 131 |
+
|
| 132 |
+
if csv_bytes is not None:
|
| 133 |
+
csv_path = "/tmp/model_points.csv"
|
| 134 |
+
with open(csv_path, "wb") as f:
|
| 135 |
+
f.write(csv_bytes)
|
| 136 |
+
else:
|
| 137 |
+
csv_path = None
|
| 138 |
+
|
| 139 |
+
return csv_path, img_cf, img_pv, metrics
|
| 140 |
|
| 141 |
run_btn.click(
|
| 142 |
+
fn=wrapper,
|
| 143 |
+
inputs=[policy_file, cashflow_file, pv_file, num_clusters, cluster_type],
|
| 144 |
+
outputs=[output_csv, output_cf_plot, output_pv_plot, output_metrics]
|
| 145 |
)
|
| 146 |
|
| 147 |
+
demo.launch()
|