【Python × 精算】保險資料視覺化:自動繪製商品演進歷程圖(Matplotlib 套件)

簡單繪製保險商品發展時間軸圖!

Joseph Jiang
ActuaViz|Actualize Your Future
13 min readApr 17, 2024

--

【前言】

保險商品通常會在不同時期進行版本更新、修正。

如果有「保險商品演進歷程圖」的視覺化輔助,是不是就可以清一目了然地看到同一系列保險商品隨著時間演變的過程?甚至加入「重大法規變更」的時間點,就能使商品演進的全貌更加清晰明瞭。

以「小額終身壽險」為例,下圖解說自金融監督管理委員會(金管會)於民國 105 年底公布「小額終老保險商品相關規範」後的情況。

小額終身壽險保險商品演進歷程圖(2024 年 4 月 11 日資料)

從上圖可以看到,國泰人壽是第一家發行此類型商品的保險公司,隨後其他公司紛紛跟進。其中,最新發行者為法國巴黎人壽,時間為 112 年中。目前市場上共有 30 種不同的小額終身壽險商品可供選擇。

【資料說明】

我們使用 ActuaWorks 提供的保險商品資料集,其資料庫收錄大量的台灣壽險商品資料。若有興趣,可以參考文末關於 ActuaWorks 的介紹。

在這裡,我們提供您實作「小額終身壽險」的資料範本如下。

資料範本下載點】⬇️

小額終身壽險部分資料

以下是資料欄位說明:

  • product_line:商品線代碼,用於識別不同的商品線。
  • version:保險商品的版本序號,用於識別保險商品的部分變更。
  • product_line_name:商品線名稱。
  • insurer:保險公司名稱。
  • product_name:保險商品名稱。
  • sale_code:商品銷售代碼,請注意此資料可能有所遺漏。
  • launch_at:保險商品的發行日期。
  • close_at:保險商品的停售日期,無資料代表仍在銷售中。

【大流程】

  1. 資料讀取與整理:首先,從資料源下載檔案「taiwanese_small_amount_whole_life_insurance.csv」以取得相關資料。讀取資料後,需要對其進行整理和清理,以做好繪製時間軸圖的前置作業。這包括轉換日期格式、排序資料等操作。
  2. 繪製時間軸圖:利用 Python 套件如 Matplotlib,我們可以將整理後的資料以「時間軸圖」的形式呈現。此圖不僅展示了保險商品的發展時間軸,還標註了重大法規變更的時間點。
  3. 版面最佳化:最後,在呈現圖表時,請調整標題、標籤、文字等元素,以確保圖表的清晰易讀。這將有助於觀看者更容易理解圖表內容,並提升閱讀體驗。

【程式細流程】

1. 讀取資料:

import pandas as pd

# Read CSV file
df = pd.read_csv('taiwanese_small_amount_whole_life_insurance.csv')

# Convert to Date Format
df['launch_at'] = pd.to_datetime(df['launch_at'])
df['close_at'] = pd.to_datetime(df['close_at'])

# Get product lines and sort them
product_lines = df['product_line'].unique()
product_line_dates = [df[(df['version'] == 0) & (df['product_line'] == product_line)]['launch_at'].iloc[0] for product_line in product_lines]
product_lines = [x for _, x in sorted(zip(product_line_dates, product_lines))]

# Reorder product lines and get corresponding dates
product_line_dates = []
for product_line in product_lines:
insurer = df[df['product_line'] == product_line]['insurer'].iloc[0]
dates = df[(df['version'] == 0) & (df['insurer'] == insurer)]['launch_at'].tolist()
product_line_dates.append(min(dates))

sorted_indices = sorted(range(len(product_line_dates)), key=lambda i: product_line_dates[i])
product_lines = [product_lines[i] for i in sorted_indices]

(1) 使用 pandas 套件讀取檔案。

(2) 將欄位 launch_at、close_at 轉換成日期格式,因為繪圖需要使用數字。

(3) 進行資料排序,共進行兩次排序。排序原則如下:

— — a. 按最早發行日進行排序。

— — b. 同一家保險公司的商品放在一起。

第一次排序按最早發行日進行排列,第二次排序將同一家保險公司的保險商品聚在一起。

2–1. 繪製時間軸圖:

import matplotlib.pyplot as plt

# Set plot size
plt.figure(figsize=(16, 9))

# Plot product line data
on_sale = 0
for index, product_line in enumerate(product_lines):
product_data = df[df['product_line'] == product_line]

# Get x and y data
x_values = product_data['launch_at'].tolist()

max_version_index = product_data['version'].idxmax()
max_close_at_value = product_data.loc[max_version_index, 'close_at']
if pd.notna(max_close_at_value):
max_close_at_value = pd.to_datetime(max_close_at_value)
else:
max_close_at_value = datetime.now()
on_sale = on_sale + 1

x_values.append(max_close_at_value)

x_values = [datetime.combine(date, datetime.min.time()) for date in x_values]

y_values = [len(product_lines)+1 - index] * len(x_values)

plt.plot(x_values, y_values, marker='o')

# Add product name labels
for i in range(len(x_values)-1):
x_text = product_data.iloc[i]['product_name'].replace('小額終身壽險', '').replace('網路投保', '')
if len(x_text) <= 1:
x_text = x_text + '小額'
plt.text(x_values[i], y_values[i]+0.2, x_text, ha='center', va='bottom', fontsize=9)

每個商品線都需要獨立繪製一條時間軸。在這裡,我們需要特別注意 x_values 和 y_values 的設計技巧。

x_values 是以每個商品版本的發行日為基準,並在最後加入最後一版的停售日作為終點。若商品仍在銷售中,則終點取當天日期。

而 y_values 則是根據每個商品線在時間軸上的位置進行設計。在這裡,我們將最早發行的保險公司放在最高的位置,因此設計為 len(product_lines) + 1 — index 這個值。

最後,對於每個座標,我們要添加一個文字標籤。為了簡化文字標籤,我們將刪除「小額終身壽險」、「網路投保」等字詞。這裡也可以使用銷售代碼作為文字標籤,但考慮到銷售代碼的資料可能有遺漏,因此我們選擇以商品名稱為基礎去添加文字標籤。

2–2. 繪製重大時間點:

from datetime import datetime, timedelta

# Important dates and labels
important_dates = [datetime(2016, 12, 18), datetime(2019, 7, 1), datetime(2020, 1, 1), datetime(2021, 7, 1), datetime(2023, 5, 1), datetime.today()]
important_names = ['訂定小額\n終老規範','第一次\n規範修正', '第二次\n規範修正', '第三次\n規範修正', '第四次\n規範修正', f'現售商品\n共有{on_sale}個']

# Plot vertical lines and labels for important dates
for date in important_dates:
plt.axvline(x=date, color='gray', linestyle='--', linewidth=0.8)

for i, date in enumerate(important_dates):
plt.text(date, 0.7, important_names[i], ha='center', fontsize=10, weight='bold', color='red')

這裡手動建立了幾個與小額終身壽險相關的法規時間。此外,我們還對目前正在銷售中的商品進行了統計,以豐富整個版面的資訊。

相關法規可以參考這篇文章:

【小額終老保險】法規變動軌跡-保障內容大揭密|2016–2024

3. 版面優化:

from matplotlib.ticker import FuncFormatter

# Set plot title and font
plt.rcParams['font.sans-serif'] = ['Microsoft JhengHei']
plt.title('小額終身壽險發展時間軸圖', fontsize=16, weight='bold')

# Set y-axis labels
y_ticks = range(len(product_lines)+1, 1, -1)
y_labels = [df[df['product_line'] == index]['product_line_name'].iloc[0] for index in product_lines]
plt.yticks(y_ticks, y_labels, fontsize=11)
plt.grid(True, which='both', axis='y', linestyle='--')

# Set x-axis format
def convert_to_taiwan_year(x, pos = None):
start_date = datetime(1970, 1, 1)
days_to_add = timedelta(days=x)
result_date = start_date + days_to_add
result_year = result_date.year-1911
return f'{result_year}年'

plt.gca().xaxis.set_major_formatter(FuncFormatter(convert_to_taiwan_year))

plt.tight_layout()

plt.show()

(1) 設置圖表標題為「小額終身壽險保險商品演進歷程圖」,並使用 Microsoft JhengHei 字型,字型選用系統中已安裝的版本。

(2) 設置 y 軸標籤,將 y 軸刻度(y_ticks)與 y_values 中的商品線對應,並將商品線名稱用作標籤。同時,設置 y 軸線的格線,以提高圖表的可讀性。

(3) 使用 matplotlib.ticker.FuncFormatter 套件來自訂 x 軸標籤的格式。在 convert_to_taiwan_year 函式中,將西元日期轉換為台灣年份格式(民國年)。

(4) 最後,使用 tight_layout() 函式調整圖表的版面配置,以確保圖表元素不重疊。

這些程式碼調整可以使得時間軸圖更具備視覺化效果和易讀性。

【完整的程式碼】

【總結】

在本文中,我們介紹了如何使用 Python 中的 Matplotlib 套件來繪製「保險商品演進歷程圖」。透過這樣的圖表,我們可以清晰地了解保險商品在不同時期的版本變動情況,並加入重大法規變更的時間點,幫助掌握商品的長期發展脈絡。

期待您能透過本篇文章,設計出屬於自己的圖表,或是將手法應用到類似的情境中。若您有任何建議與指教,歡迎留言給我們!

歡迎「追蹤」、「拍手」,關注我們最新的消息 :)

【Contact Us】

【ActuaWorks】

本篇文章以「小額終身壽險」為例,使用了 ActuaWorks 的保險商品資料集來提供您資料範本。

如果您對這些資料內容有興趣,歡迎透過下面這篇介紹文章進一步了解細節,或是直接前往「ActuaWorks 網站」以及「Microsoft AppSource」下載使用。

【ActuaWorks 目前採人工開通制

因系統目前仍在測試階段,使用者帳號採人工開通制。
若您有興趣使用 ActuaWorks,歡迎署名寄信至:info@actuaviz.com。
我們將盡快提供一組使用帳號給您。

ActuaWorks 提供豐富的保險商品資訊,讓您能夠深入研究台灣保險市場的動態,掌握最新的趨勢和資訊,讓自己的決策握有更多的參考依據。

前往 ActuaWorks 下載更多商品資料,設計出屬於自己的圖表!

--

--