一个用Python类计算车险保费的例子

• 这个例子希望能输入费率表，定价variable 等就能实现查询。变动保费可以用短期费率因子等查出来。

• 定义这个类打算实现以下功能

• 输入费率表，rating factor和其对应的值，以及sum assured，就能算出相对应的保费。
• 在保单变动的时候，通过输入movement date和短期费率表可以算出变动保费
• 如果把两个这样的class相加，可以得到它们的保费和
• 一个info的方法可以print出保单信息
class premium_cal:
# initilize with its rate_table, initial_date, rating_factors, values, sum_assured
def __init__(self, rate_table, initial_date, rating_factors, values, sum_assured):
self.rate_table = rate_table
self.initial_date = initial_date
self.rating_factors = rating_factors
self.sum_assured = sum_assured
self.values = values
# filter out the required row
for idx, i in enumerate(self.rating_factors):
self.rate_table = self.rate_table[self.rate_table.loc[:,i] == self.values[idx]]
if self.rate_table.shape[0] == 1:
self.rate = self.rate_table.rate.values
else:
print("warning! more than one row satisfies the condition")

# print the infomation of the policy
def info(self):
info = """
This policy starts from
{}
sum assured is
{}
Basic policy info
""".format(self.initial_date, self.sum_assured)
print(info)
info_sub = ""
for idx, i in enumerate(self.rating_factors):
info_sub = info_sub +"""
{} is {}
""".format(i,self.values[idx])
print(info_sub)

#Calculate premium rounded to 2 digital points

self.short_rate_table = short_rate_table
self.movement_date = movement_date
self.month_passed = (self.movement_date.year - self.initial_date.year) * 12 + self.movement_date.month - self.initial_date.month
self.short_rate_table = self.short_rate_table[short_rate_table["Month"] == self.month_passed]
if self.short_rate_table.shape[0] == 1:
self.short_rate = self.short_rate_table.rate.values
else:
print("warning! more than one row satisfies the condition")



• 查看结果

from datetime import datetime
initial_date = '2017-10-31'
initial_date = datetime.strptime(initial_date, "%Y-%m-%d")

initial_date = initial_date,
rating_factors=["car_model","car_age","past_claims"],
values = ["D", 0, 4], sum_assured=10000)

initial_date = '2018-10-31'
initial_date = datetime.strptime(initial_date, "%Y-%m-%d")

initial_date = initial_date,
rating_factors=["car_model","car_age","past_claims"],
values = ["C", 4, 2], sum_assured=10000)

movement_date = '2017-11-31'
movement_date = datetime.strptime(initial_date, "%Y-%m-%d")