# 產業資料庫的基礎應用：用 Python 與 Pandas 客製化台股產業分類

台股研究 2022年12月20日 約 3 分鐘閱讀

教你用 FinLab 產業題材資料庫，搭配 Python 與 Pandas 的 str.contains 查詢同業、用 median(axis=1) 算產業本益比中位數做選股回測，並用 create\_new\_industry\_themes 客製化新增概念股標籤，打造個人獨有的台股產業分類與選股策略。

想讓選股技巧更上一層樓？學會用 Python 與 Pandas 操作 FinLab 產業題材資料庫，查詢同業、做本益比回測，甚至客製化自己的台股產業分類。

產業資料庫重要嗎？如果你想讓選股技巧更上一層樓，勢必會進階到產業分析。

投資標的的優劣評價，除了自己跟自己比，例如近期財報是否較過去改善，另一個判斷企業競爭力的評價方式，就是跟同業比，好壞都是比較而來的，選對比較基準才讓評價有意義。

除了同業個股比較，產業資料庫的另一個主要應用在找出族群趨勢，如果一個產業的企業的營收或股價趨勢都向上，那代表該產業蒸蒸日上，有產業景氣良好的基本面護體，更能增加投資判斷把握度與可解釋性，排除單一個股炒作的個別性，更進階的應用甚至可延伸到概念股落後補漲效應。

這一切的應用的基礎都建構在「產業資料庫」的分類，這篇教學文章將說明 FinLab 的「[產業題材資料庫](https://ai.finlab.tw/database#security_industry_themes)」的簡單應用，並教你如何用 Python 與 Pandas 基礎語法去「客製化」自己的產業分類，讓產業資料庫更豐富。

## 產業資料

FinLab 的細產業主題資料來源主要取自「[產業價值鍊資訊平台](https://ic.tpex.org.tw/)」，少部分為自定義分類。從 [FinLab資料庫](https://ai.finlab.tw/database#security_industry_themes) 只要一行程式碼就能下載全部的細產業資訊，讓你輕鬆以此基礎做後續應用。要注意的是此份資料僅限 [VIP](https://ai.finlab.tw/pricing) 使用。

[產業價值鍊資訊平台](https://ic.tpex.org.tw/) 會將主產業再分拆上下游的細產業，讓你更精細的去比較，否則證交所一般分類光半導體就近百檔，比較效果相對籠統。

[![產業題材資料庫的資料庫欄位](https://r2.finlab.finance/blog/industry_themes_database_basic_application/%E6%88%AA%E5%9C%96-2022-11-02-%E4%B8%8A%E5%8D%887.30.52-1024x404.png)](https://r2.finlab.finance/blog/industry_themes_database_basic_application/%E6%88%AA%E5%9C%96-2022-11-02-%E4%B8%8A%E5%8D%887.30.52-1024x404.png)

依本文重跑

## 執行這個策略

複製提示詞，讓 AI 依照上方證據的資料、條件與風險檢查重跑一次。

告訴你的AI：

幫我設定 FinLab，重現這篇文章，請讀：https\://finlab.finance/setup?relatedUrl=/blog/industry-database-python-pandas

[免安裝，開啟 FinLab Studio](https://studio.finlab.finance/chat?lang=zh\&research_context=%7B%22v%22%3A1%2C%22source_url%22%3A%22https%3A%2F%2Ffinlab.finance%2Fblog%2Findustry-database-python-pandas%22%7D)

*資料庫欄位*

每家公司所屬產業的資訊放在 catergory 內，category 欄位的型態是文字格式，所有產業分類會放入 List 後再包成文字型態，從該資料得知公司分別有哪些產業的標籤。

例如 1101 台泥的產業序列裡有主產業的水泥，也有細產業「水泥：水泥成品」、「水泥：水泥熟料」（格式為「主產業：細產業 or 主產業」）。

[![1101 台泥的產業序列與細產業標籤範例](https://r2.finlab.finance/blog/industry_themes_database_basic_application/%E6%88%AA%E5%9C%96-2022-11-02-%E4%B8%8A%E5%8D%887.35.04-1024x810.png)](https://r2.finlab.finance/blog/industry_themes_database_basic_application/%E6%88%AA%E5%9C%96-2022-11-02-%E4%B8%8A%E5%8D%887.35.04-1024x810.png)

## 簡單查詢應用

如果我們想查詢哪些公司屬於水泥產業？我們可以運用 pandas 內的 [Series.str.contains](https://pandas.pydata.org/docs/reference/api/pandas.Series.str.contains.html)，讓我們快速分類出產業名單，如下範例，只要「category」欄位內含「水泥」兩字，就會被納入範圍。

顯示程式碼

```
from finlab import data
from finlab.backtest import sim
 
# 取出產業題材
themes = data.get('security_industry_themes')
 
# 選出產業包含「水泥」的公司
ind1 = themes[themes['category'].str.contains('水泥')]
```

[![篩選出產業包含水泥的公司查詢結果](https://r2.finlab.finance/blog/industry_themes_database_basic_application/%E6%88%AA%E5%9C%96-2022-12-20-%E4%B8%8B%E5%8D%8812.36.55-1024x513.png)](https://r2.finlab.finance/blog/industry_themes_database_basic_application/%E6%88%AA%E5%9C%96-2022-12-20-%E4%B8%8B%E5%8D%8812.36.55-1024x513.png)

contains 語法支援 or 的運用，如果我們今天想選出產業包含「水泥」或「建材營造」的公司，可以使用以下語句，使用 '|' 的符號做邏輯運算串連：

`ind2 = themes[themes['category'].str.contains('水泥|建材營造')]`

[![篩選出產業包含水泥或建材營造公司的查詢結果](https://r2.finlab.finance/blog/industry_themes_database_basic_application/%E6%88%AA%E5%9C%96-2022-12-20-%E4%B8%8B%E5%8D%8812.37.48-1024x532.png)](https://r2.finlab.finance/blog/industry_themes_database_basic_application/%E6%88%AA%E5%9C%96-2022-12-20-%E4%B8%8B%E5%8D%8812.37.48-1024x532.png)

## 簡單回測範例

「想挑出水泥產業中，本益比低於水泥產業本益比中位數之個股當投資組合」

實作很簡單，用前述 contains 篩選的 stock\_id，套入本益比資料做欄位圈選，就能限定資料範圍，再運用 `median(axis=1)`，計算每日產業本益比中位數，axis=1 的用途在取每一期（橫列）的中位數。

顯示程式碼

```
from finlab import data
from finlab.backtest import sim
 
# 取出產業題材
themes = data.get('security_industry_themes')
 
# 選出產業包含「水泥」公司
ind = themes[themes['category'].str.contains('水泥')]
pe = data.get('price_earning_ratio:本益比')
ind_pe = pe[list(ind['stock_id'])]
 
# 計算每日產業本益比中位數,axis=1的用途在取每一期(橫列)的中位數
ind_pe_med = ind_pe.median(axis=1)
 
# 選出本益比小於同業本益比中位數且本益比小於25的公司
position = (ind_pe < ind_pe_med) & (ind_pe < 25)
 
# 回測
report = sim(position, upload=False)
report.display()
```

[![水泥產業同業本益比比較法回測績效圖](https://r2.finlab.finance/blog/industry_themes_database_basic_application/newplot-2.png)](https://r2.finlab.finance/blog/industry_themes_database_basic_application/newplot-2.png)

## 自定義產業分類

有時我們發現產業價值鏈資訊平台的分類仍不能滿足需求，像是他缺少概念股的標籤資料，學會 Python 的好處在我們可以任意擴展資料，去自定義新增的分類。

使用開發好的 create\_new\_industry\_themes 的函式去創建新的產業分類，其中 additional\_themes 變數控制新增標籤，格式為 `[([目標群],[標籤群]),...]`。

例如以下範例對 '6684', '6756', '3014' 新增 '元宇宙：祖克柏概念股' 的標籤，對 '1342', '1584' 新增 '航太週邊：空中巴士概念股' 的標籤，對 '2342', '3317', '4923', '5299', '6287' 增加兩個標籤 '半導體：基礎元件', '通訊產業：通訊元件'。

顯示程式碼

```
def add_sub_group(dataframe, stock_list: list, theme_list: list):
    try:
        dataframe.loc[stock_list]['category'] = dataframe.loc[stock_list]['category'].apply(
            lambda s: s.extend(theme_list))
    except KeyError:
        print('stock_list not in index.')
    return dataframe
 
 
def process_sub_group_list(sub_group_list):
    sub_group_list.extend(list(set({i[:i.index(':')] for i in sub_group_list if ':' in i})))
    return sorted(list(set(sub_group_list)))
 
 
def create_new_industry_themes(additional_themes):
 
    df = data.get('security_industry_themes')
    df = df.set_index(['stock_id', 'name'])
    df['category'] = df['category'].apply(lambda s: eval(s))
 
    if additional_themes:
        for stock_list, theme_list in additional_themes:
            df = add_sub_group(df, stock_list, theme_list)
 
    df['category'] = df['category'].apply(lambda s: process_sub_group_list(s))
    df = df.astype(str)
    df = df.reset_index()
    return df
 
 
additional_themes = [
    (['6684', '6756', '3014'], ['元宇宙:祖克柏概念股']),
    (['1342', '1584'], ['航太週邊:空中巴士概念股']),
    (['2342', '3317', '4923', '5299', '6287'], ['半導體:基礎元件', '通訊產業:通訊元件']),
]
 
 
new_themes = create_new_industry_themes(additional_themes)
# 檢查6684 是否成功新增標籤
new_themes[new_themes['stock_id']=='6684']['category'].values
```

[![自定義新增產業標籤後檢查 6684 的 category 結果](https://r2.finlab.finance/blog/industry_themes_database_basic_application/%E6%88%AA%E5%9C%96-2022-12-20-%E4%B8%8B%E5%8D%882.02.42-1024x699.png)](https://r2.finlab.finance/blog/industry_themes_database_basic_application/%E6%88%AA%E5%9C%96-2022-12-20-%E4%B8%8B%E5%8D%882.02.42-1024x699.png)

執行完含式後，會發現 new\_themes 已有新增資料～之後就可以用自定義後的 new\_themes 做產業分析囉！

## 小結

[colab程式範例](https://colab.research.google.com/drive/15PQ_W_6xUZ1lHlDWaNZtZgsUPZPMiove?usp=sharing)

學會基礎的產業資料的資料處理技巧後，就可以進行許多分析與策略開發，像是「[產業面選股策略｜同業本益比比較法](https://finlab.finance/blog/industry-pe-comparison-stock-strategy)」就是延伸的應用喔！

如果有自己的產業分類標籤可以加入，那就會進化成個人獨有的資料，可能創造出不易被模仿的策略或產業觀察指標。

***

## 延伸閱讀

* [利用 Pandas 輕鬆選股：Python 實作教學](https://finlab.finance/blog/pandas-stock-screening-python-tutorial)
* [產業面選股：同業本益比比較法實戰回測](https://finlab.finance/blog/industry-pe-comparison-stock-strategy)
* [台股怎麼選股？完整指南](https://finlab.finance/tools/stock-selection)

**投資警語：本文僅供教學參考，不構成投資建議。過去績效不代表未來表現，投資有風險。**

![韓承佑](https://finlab.finance/people/cheng-yu-han-avatar.jpg)

韓承佑

創辦人 & 量化研究員

韓承佑是 FinLab 創辦人，也是開源 Python 量化套件 finlab 的作者，長年投入台股與美股的量化策略研究、回測與教學。

[在 GitHub 上追蹤 →](https://github.com/koreal6803) [在 LinkedIn 上連結 →](https://www.linkedin.com/in/cheng-yu-han/)

FinLab AI

### 想建立自己的策略？

用自然語言描述你的選股想法，AI 自動驗證、回測、給你答案

[免費開始](https://finlab.finance/#get-started)

## 更多價值與基本面研究

[查看全部](https://finlab.finance/blog/category/value)

* [![現金股利調高選股：加進月營收動能，7 年年化 59.9%、夏普 1.83](https://r2.finlab.finance/blog/cash-dividend-increase-stock-selection/chart_equity.png) 現金股利調高選股：加進月營收動能，7 年年化 59.9%、夏普 1.83 年化報酬 59.9% · 台股](https://finlab.finance/blog/cash-dividend-increase-stock-selection)
* [![營收創新高選股：月營收動能優先買營收創 12 個月新高，年化 52.4%、夏普 1.62](https://r2.finlab.finance/blog/revenue-new-high-stock-selection/chart_equity.png) 營收創新高選股：月營收動能優先買營收創 12 個月新高，年化 52.4%、夏普 1.62 年化報酬 52.4% · 台股](https://finlab.finance/blog/revenue-new-high-stock-selection)
* [![月營收動能選股：台股 11 年回測年化 50%，夏普 1.46（附程式碼）](https://r2.finlab.finance/blog/monthly-revenue-momentum/chart_summary.png) 月營收動能選股：台股 11 年回測年化 50%，夏普 1.46（附程式碼） 年化報酬 50.0% · 台股](https://finlab.finance/blog/monthly-revenue-momentum)
* [![財報選股 3 指標回測：2020 年起年化 45.6%，近三年輸 0050](https://r2.finlab.finance/blog/fundamental-3-indicators/image-4-1024x938.png) 財報選股 3 指標回測：2020 年起年化 45.6%，近三年輸 0050 年化報酬 45.6% · 台股](https://finlab.finance/blog/fundamental-3-indicators)

來源：https://finlab.finance/blog/industry-database-python-pandas｜資料日期：依上文各表格與段落標示｜頁面更新：2026-11-25
