My Blog

My WordPress Blog

My Blog

My WordPress Blog

Predictive Analytics for Claims Forecasting

Install Required Libraries

To get started, install the necessary libraries via pip:

bashCopy codepip install flask flask-sqlalchemy scikit-learn pandas matplotlib seaborn flask-wtf
  • Flask-SQLAlchemy: For database management (we’ll store claims data).
  • Scikit-learn: For building predictive models.
  • Pandas: For data manipulation.
  • Matplotlib/Seaborn: For data visualization.
  • Flask-WTF: For creating forms for user input.

Step 2: Prepare the Data

For this tutorial, we will use a simple mock dataset. In practice, you would use real insurance data from your company or external sources. Here’s an example of what your data might look like:

Policyholder_IDClaim_TypeAgePremiumPast_ClaimsClaims_HistoryClaim_AmountClaim_Date
1Auto305002510002022-01-01
2Home45600000NULL
3Health60700125002021-05-10
4Auto254503412002023-03-15

Step 3: Set Up the Database

First, we need to define the database models. We will create models for storing Policyholders and their Claims history.

models.py

pythonCopy codefrom flask_sqlalchemy import SQLAlchemy
from datetime import datetime

db = SQLAlchemy()

class Policyholder(db.Model):
id = db.Column(db.Integer, primary_key=True)
policyholder_id = db.Column(db.Integer, unique=True, nullable=False)
age = db.Column(db.Integer, nullable=False)
premium = db.Column(db.Float, nullable=False)
past_claims = db.Column(db.Integer, nullable=False)
claims_history = db.Column(db.Integer, nullable=False)
claims = db.relationship('Claim', backref='policyholder', lazy=True)
class Claim(db.Model):
id = db.Column(db.Integer, primary_key=True)
claim_type = db.Column(db.String(50), nullable=False)
claim_amount = db.Column(db.Float, nullable=False)
claim_date = db.Column(db.DateTime, default=datetime.utcnow)
policyholder_id = db.Column(db.Integer, db.ForeignKey('policyholder.id'), nullable=False)

Step 4: Build the Machine Learning Model

Now let’s prepare the dataset and build the predictive model. We will use Scikit-learn to build a Random Forest classifier to predict the likelihood of a claim happening based on past data.

predictive_model.py

pythonCopy codeimport pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report, confusion_matrix

# Mock dataset for illustration
data = {
'age': [30, 45, 60, 25],
'premium': [500, 600, 700, 450],
'past_claims': [2, 0, 1, 3],
'claims_history': [5, 0, 2, 4],
'claim_type': ['auto', 'home', 'health', 'auto'],
'claim_amount': [1000, 0, 500, 1200],
'target': [1, 0, 1, 1]  # 1 = claim, 0 = no claim
} df = pd.DataFrame(data) # Feature Engineering df['claim_type'] = df['claim_type'].map({'auto': 0, 'home': 1, 'health': 2}) X = df[['age', 'premium', 'past_claims', 'claims_history', 'claim_type']] y = df['target'] # Train-test split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42) # Model Training model = RandomForestClassifier(n_estimators=100) model.fit(X_train, y_train) # Predictions y_pred = model.predict(X_test) # Print model evaluation metrics print("Classification Report:\n", classification_report(y_test, y_pred)) print("Confusion Matrix:\n", confusion_matrix(y_test, y_pred)) # Function to predict a new claim def predict_claim(features):
prediction = model.predict([features])
return prediction[0]

Step 5: Integrate with Flask Web Application

Now, we will integrate the machine learning model into a Flask web application to allow users to input their data and get predictions for insurance claims.

app.py

pythonCopy codefrom flask import Flask, render_template, request, redirect, url_for, flash
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
from predictive_model import predict_claim
from models import db, Policyholder, Claim

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///insurance_claims.db'
db.init_app(app)

login_manager = LoginManager(app)
login_manager.login_view = 'login'

# User Loader for Flask-Login
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
# Routes @app.route('/') def index():
return render_template('index.html')
@app.route('/predict', methods=['GET', 'POST']) def predict():
if request.method == 'POST':
    age = int(request.form['age'])
    premium = float(request.form['premium'])
    past_claims = int(request.form['past_claims'])
    claims_history = int(request.form['claims_history'])
    claim_type = request.form['claim_type']
    
    # Map claim type to numeric value
    claim_type_mapping = {'auto': 0, 'home': 1, 'health': 2}
    claim_type_num = claim_type_mapping.get(claim_type.lower(), 0)
    
    # Predict the claim outcome
    features = [age, premium, past_claims, claims_history, claim_type_num]
    prediction = predict_claim(features)
    
    if prediction == 1:
        flash("Your claim prediction is: Likely", 'success')
    else:
        flash("Your claim prediction is: Unlikely", 'danger')
    
    return redirect(url_for('predict'))
return render_template('predict.html')
@app.route('/login', methods=['GET', 'POST']) def login():
return render_template('login.html')
@app.route('/logout') def logout():
logout_user()
return redirect(url_for('index'))
if __name__ == '__main__':
app.run(debug=True)

Step 6: Create the Frontend Templates

templates/index.html

htmlCopy code<!DOCTYPE html>
<html lang="en">
<head>
&lt;meta charset="UTF-8"&gt;
&lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
&lt;title&gt;Insurance Claims Prediction&lt;/title&gt;
</head> <body>
&lt;h1&gt;Welcome to Insurance Claims Prediction&lt;/h1&gt;
&lt;a href="{{ url_for('predict') }}"&gt;Predict Claim Likelihood&lt;/a&gt;
</body> </html>

templates/predict.html

htmlCopy code<!DOCTYPE html>
<html lang="en">
<head>
&lt;meta charset="UTF-8"&gt;
&lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
&lt;title&gt;Predict Claim Likelihood&lt;/title&gt;
</head> <body>
&lt;h1&gt;Predict Claim Likelihood&lt;/h1&gt;
&lt;form method="POST"&gt;
    &lt;label for="age"&gt;Age:&lt;/label&gt;
    &lt;input type="number" name="age" id="age" required&gt;&lt;br&gt;&lt;br&gt;
    &lt;label for="premium"&gt;Premium:&lt;/label&gt;
    &lt;input type="number" step="0.01" name="premium" id="premium" required&gt;&lt;br&gt;&lt;br&gt;
    &lt;label for="past_claims"&gt;Past Claims:&lt;/label&gt;
    &lt;input type="number" name="past_claims" id="past_claims" required&gt;&lt;br&gt;&lt;br&gt;
    &lt;label for="claims_history"&gt;Claims History</code></code></pre>
Predictive Analytics for Claims Forecasting

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top