# Python爬蟲教學｜美國勞動部統計局 BLS API 抓取失業率總經數據

美股研究 2022年11月10日 約 2 分鐘閱讀

用 Python 串接美國勞動部統計局 BLS API 抓失業率 LNS14000000 時間序列，教你註冊金鑰把每日額度從 25 拉到 500 次，並用每月 10 日當公告日對齊、避免使用未來資料，為美股總經回測與失業率 vs S\&P 500 擇時打下乾淨數據基礎。

美國科技業近期大裁員，媒體上充滿失業率的話題，美國失業率的指標要去哪裡抓？ 本篇文章介紹如何使用「美國勞動部統計局」的 API 來撈取美國總經數據，把總經分析戰線擴充到國際市場。

## API 註冊

美國勞動部統計局有開放 [Python API](https://www.bls.gov/developers/home.htm) 給開發者使用，建議去用信箱註冊一個 API 帳號，不然未註冊月戶每天只有25次取資料的權限，實在是很少，申請過後每日就能有 500 次Request。 [註冊](https://data.bls.gov/registrationEngine/)只要填信箱，送出後就會寄出 API key 的生效確認信，點擊確認後即可生效。

## API 規範

建議使用 **API Version 2.0**，權限開比較多。更多常見問題可見 [Q\&A](https://www.bls.gov/developers/api_FAQs.htm)。 **How is API Version 2.0 different from Version 1.0?**&#x41;PI Version 2.0 requires registration, and it offers greater query limits. It also allows users to request net and percent changes and series description information. See below for more details.

| Service                                  | Version 2.0 (Registered)   | Version 1.0 (Unregistered) |
| ---------------------------------------- | -------------------------- | -------------------------- |
| Daily query limit                        | 500                        | 25                         |
| Series per query limit                   | 50                         | 25                         |
| Years per query limit                    | 20                         | 10                         |
| Request rate limit                       | 50 requests per 10 seconds | 50 requests per 10 seconds |
| Net/Percent Changes                      | Yes                        | No                         |
| Optional annual averages                 | Yes                        | No                         |
| Series description information (catalog) | Yes                        | No                         |

*美國勞動部統計局API版本差異*

## 如何使用 API ?

詳見[開發者文件範例](https://www.bls.gov/developers/api_signature_v2.htm)，以下舉爬取「失業率」當例子： 首先要傳入payload內的參數設定，seriesid 為 指標代號，常用指標代號可在官網[相關頁面](https://data.bls.gov/cgi-bin/surveymost?bls)查詢或透過 [API](https://api.bls.gov/publicAPI/v2/timeseries/popular) 取得常用代號列表。 startyear 為資料開始年度。 endyear 為資料結束年度。 registrationkey 為 api\_key，有註冊的話要記得填喔

[![美國勞動部統計局 API 取得失業率資料的 JSON response 結果](https://r2.finlab.finance/blog/us_unemployment_rate_seasonally_adjusted_crawler/%E6%88%AA%E5%9C%96-2022-11-10-%E4%B8%8B%E5%8D%882.58.05-1024x692.png)](https://r2.finlab.finance/blog/us_unemployment_rate_seasonally_adjusted_crawler/%E6%88%AA%E5%9C%96-2022-11-10-%E4%B8%8B%E5%8D%882.58.05-1024x692.png)

依本文重跑

## 執行這個策略

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

告訴你的AI：

幫我設定 FinLab，重現這篇文章，請讀：https\://finlab.finance/setup?relatedUrl=/blog/us-bls-api-unemployment-rate-python

[免安裝，開啟 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%2Fus-bls-api-unemployment-rate-python%22%7D)

*失業率response*

就這麼簡單將 json 檔下載下來，就可以取得時間序列資料。

## 失業率發布日

原始資料有一個問題是無法直接取得資料公告時間，只能知道數值是哪一個月份，以失業率來說，美國官方會預告[發佈時間](https://www.bls.gov/schedule/news_release/empsit.htm)，原則上失業率是每個月第一個星期五，但偶爾會因為假日或其他因素遞延。

[![美國勞動部統計局就業數據預計發布日期時程表](https://r2.finlab.finance/blog/us_unemployment_rate_seasonally_adjusted_crawler/%E6%88%AA%E5%9C%96-2022-11-10-%E4%B8%8B%E5%8D%884.51.51-1024x817.png)](https://r2.finlab.finance/blog/us_unemployment_rate_seasonally_adjusted_crawler/%E6%88%AA%E5%9C%96-2022-11-10-%E4%B8%8B%E5%8D%884.51.51-1024x817.png)

*勞動部統計局就業數據預計發布日*

為避免使用到未來資料，我們使用每月10日當安全數值。以下為Python爬蟲完整程式，主要加上處理發布日期的部分，發便未來回測使用。

顯示程式碼

```
import requests
import json
import pandas as pd
 
def crawl_data(start_year, end_year, api_key='xxxx'):
 
    headers = {'Content-type': 'application/json'}
    # seriesid：傳入目標資料
    data = json.dumps({"seriesid": ['LNS14000000'],"startyear":start_year, "endyear":end_year, "registrationkey":api_key})
    p = requests.post('https://api.bls.gov/publicAPI/v2/timeseries/data/', data=data, headers=headers)
    json_data = json.loads(p.text)
 
    # 將資料轉成dataframe
    df = pd.DataFrame(json_data['Results']['series'][0]['data'])
 
    # 將資料日期轉成公告日，當月失業率在下一個月才公告
    latest_year = int(df['year'].iloc[0])
    latest_month = int(df['period'].iloc[0].replace('M',''))
    start_year = int(df['year'].iloc[-1])
    start_month = int(df['period'].iloc[-1].replace('M',''))
 
    def process_date(year,month):
        if month == 12:
            month = 1
            year += 1
        else:
            month += 1
        return year,month
 
    latest_year, latest_month = process_date(latest_year, latest_month)
    start_year, start_month = process_date(start_year, start_month)
    issue_date = pd.date_range(f'{start_year}-{start_month}-1', f'{latest_year}-{latest_month}-1',
                               freq='MS') + pd.tseries.offsets.DateOffset(days=9)
    df_new = pd.DataFrame({'value': df['value'].values[::-1]}, index=issue_date)
    df_new['value'] = df_new['value'].astype(float)
    df_new.index.name = 'date'
    return df_new
 
df = crawl_data('2015', '2023')
df
```

## 小結

[colab範例檔](https://colab.research.google.com/drive/1aRNLUTQi3AX6nLWn-Mp132GIFYTFFjhW?usp=sharing) 美國勞動部統計局有許多非常重要的資料，除了就業相關數據如失業率、非農、就業津貼，還有物價指數CPI、PPI，都能幫助我們後續做分析，趕緊學會該 API 的使用法則，打造總經分析武器庫。 想知道總經與情緒指標如何應用在美國指數的擇時回測嗎？可以繼續看「[VIX 恐慌指數抄底美股有用嗎？1990-2026 回測實測](https://finlab.finance/blog/vix-us-stock-crash-investing-python)」踏入更豐富的數據世界。

***

## 延伸閱讀

* [VIX 恐慌指數抄底美股有用嗎？1990-2026 回測實測](https://finlab.finance/blog/vix-us-stock-crash-investing-python)
* [FRED API 總體經濟指標教學與美股回測](https://finlab.finance/blog/fred-api-economic-indicators-us-stock-backtest)
* [程式交易入門指南](https://finlab.finance/tools/program-trading)

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

![韓承佑](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/macro)

* [![國安基金進場後買什麼？改抱 0050 正2 一年，日夏普 1.37 勝 0050](https://r2.finlab.finance/blog/national-stabilization-fund-00631l-strategy/chart_equity.png) 國安基金進場後買什麼？改抱 0050 正2 一年，日夏普 1.37 勝 0050 年化報酬 38.6% · 台股](https://finlab.finance/blog/national-stabilization-fund-00631l-strategy)
* [![庫藏股實施家數抄底訊號回測：只買 0050 全輸，改抱正2 日夏普 1.36](https://r2.finlab.finance/blog/treasury-stock-buyback-bottom-signal/chart_buyback_count_2026.png) 庫藏股實施家數抄底訊號回測：只買 0050 全輸，改抱正2 日夏普 1.36 年化報酬 36.9% · 台股](https://finlab.finance/blog/treasury-stock-buyback-bottom-signal)
* [![LPPL 泡沫模型實測：股市崩盤預測原理、Python 實作與 0050 擇時回測（八年僅一次警報且為誤報）](https://r2.finlab.finance/blog/lppl-bubble-crash-prediction-python/chart1_equity_thumbnail.png) LPPL 泡沫模型實測：股市崩盤預測原理、Python 實作與 0050 擇時回測（八年僅一次警報且為誤報） 年化報酬 23.9% · 台股](https://finlab.finance/blog/lppl-bubble-crash-prediction-python)
* [![星期幾買股票最好？週一效應回測：美股星期一最強，台股星期三最強](https://r2.finlab.finance/blog/best-day-of-the-week-to-buy-stocks/chart1_weekday_returns.png) 星期幾買股票最好？週一效應回測：美股星期一最強，台股星期三最強 年化報酬 — · 美股](https://finlab.finance/blog/best-day-of-the-week-to-buy-stocks)

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