<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	
	xmlns:georss="http://www.georss.org/georss"
	xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#"
	>

<channel>
	<title>美國勞動統計局 &#8211; FinLab</title>
	<atom:link href="https://www.finlab.tw/tag/%E7%BE%8E%E5%9C%8B%E5%8B%9E%E5%8B%95%E7%B5%B1%E8%A8%88%E5%B1%80/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.finlab.tw</link>
	<description>深入淺出的量化投資，讓你在在茫茫股海中，找到專屬於自己的投資方法</description>
	<lastBuildDate>Thu, 10 Nov 2022 08:55:51 +0000</lastBuildDate>
	<language>zh-TW</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.0.9</generator>

<image>
	<url>https://www.finlab.tw/wp-content/uploads/2020/07/favicon.png</url>
	<title>美國勞動統計局 &#8211; FinLab</title>
	<link>https://www.finlab.tw</link>
	<width>32</width>
	<height>32</height>
</image> 
<site xmlns="com-wordpress:feed-additions:1">179699571</site>	<item>
		<title>Python爬蟲教學｜美國勞動部統計局API｜失業率</title>
		<link>https://www.finlab.tw/us_unemployment_rate_seasonally_adjusted_crawler/</link>
					<comments>https://www.finlab.tw/us_unemployment_rate_seasonally_adjusted_crawler/#respond</comments>
		
		<dc:creator><![CDATA[Ben]]></dc:creator>
		<pubDate>Thu, 10 Nov 2022 07:47:00 +0000</pubDate>
				<category><![CDATA[總體經濟]]></category>
		<category><![CDATA[Python新手教學]]></category>
		<category><![CDATA[投資新手]]></category>
		<category><![CDATA[生產力]]></category>
		<category><![CDATA[失業率]]></category>
		<category><![CDATA[總經]]></category>
		<category><![CDATA[美國]]></category>
		<category><![CDATA[美國勞動統計局]]></category>
		<guid isPermaLink="false">https://www.finlab.tw/?p=4844</guid>

					<description><![CDATA[美國科技業近期大裁員，媒體上充滿失業率的話題，美國失業率的指標要去哪裡抓？
本篇文章介紹如何使用「美國勞動部統計局」的 API 來撈取美國總經數據，把總經分析戰線擴充到國際市場。
除了就業相關數據如失業率、非農、就業津貼，還有物價指數CPI、PPI，都能幫助我們後續做分析，趕緊學會該 API 的使用法則，打造總經分析武器庫。]]></description>
										<content:encoded><![CDATA[
<p class="has-medium-font-size">美國科技業近期大裁員，媒體上充滿失業率的話題，美國失業率的指標要去哪裡抓？<br>本篇文章介紹如何使用「美國勞動部統計局」的 API 來撈取美國總經數據，把總經分析戰線擴充到國際市場。</p>



<h2>API 註冊</h2>



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



<h2>API 規範</h2>



<p class="has-medium-font-size">建議使用 <strong>API Version 2.0</strong>，權限開比較多。更多常見問題可見 <a href="https://www.bls.gov/developers/api_FAQs.htm" target="_blank" rel="noopener">Q&amp;A</a>。<br><strong>How is API Version 2.0 different from Version 1.0?</strong>API 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.</p>



<figure class="wp-block-table has-medium-font-size"><table><tbody><tr><th>Service</th><th>Version 2.0<br>(Registered)</th><th>Version 1.0<br>(Unregistered)</th></tr><tr><td>Daily query limit</td><td>500</td><td>25</td></tr><tr><td>Series per query limit</td><td>50</td><td>25</td></tr><tr><td>Years per query limit</td><td>20</td><td>10</td></tr><tr><td>Request rate limit</td><td>50 requests per 10 seconds</td><td>50 requests per 10 seconds</td></tr><tr><td>Net/Percent Changes</td><td>Yes</td><td>No</td></tr><tr><td>Optional annual averages</td><td>Yes</td><td>No</td></tr><tr><td>Series description information (catalog)</td><td>Yes</td><td>No</td></tr></tbody></table><figcaption>美國勞動部統計局API版本差異</figcaption></figure>



<h2>如何使用 API ?</h2>



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



<figure class="wp-block-image size-large"><img width="1024" height="692" src="https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-10-下午2.58.05-1024x692.png" alt="截圖 2022 11 10 下午2.58.05" class="wp-image-4845" srcset="https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-10-下午2.58.05-1024x692.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-10-下午2.58.05-300x203.png 300w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-10-下午2.58.05-768x519.png 768w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-10-下午2.58.05.png 1495w" sizes="(max-width: 1024px) 100vw, 1024px" title="Python爬蟲教學｜美國勞動部統計局API｜失業率 1"><figcaption>失業率response</figcaption></figure>



<p class="has-medium-font-size">就這麼簡單將 json 檔下載下來，就可以取得時間序列資料。</p>



<h2>失業率發布日</h2>



<p class="has-medium-font-size">原始資料有一個問題是無法直接取得資料公告時間，只能知道數值是哪一個月份，以失業率來說，美國官方會預告<a href="https://www.bls.gov/schedule/news_release/empsit.htm" target="_blank" rel="noopener">發佈時間</a>，原則上失業率是每個月第一個星期五，但偶爾會因為假日或其他因素遞延。</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="817" src="https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-10-下午4.51.51-1024x817.png" alt="截圖 2022 11 10 下午4.51.51" class="wp-image-4858" srcset="https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-10-下午4.51.51-1024x817.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-10-下午4.51.51-300x239.png 300w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-10-下午4.51.51-768x613.png 768w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-10-下午4.51.51-1536x1226.png 1536w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-10-下午4.51.51.png 1678w" sizes="(max-width: 1024px) 100vw, 1024px" title="Python爬蟲教學｜美國勞動部統計局API｜失業率 2"><figcaption>勞動部統計局就業數據預計發布日</figcaption></figure>



<p class="has-medium-font-size"><br>為避免使用到未來資料，我們使用每月10日當安全數值。以下為Python爬蟲完整程式，主要加上處理發布日期的部分，發便未來回測使用。</p>



<pre class="wp-block-code"><code lang="python" class="language-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</code></pre>



<h2>小結</h2>



<p class="has-medium-font-size"><a href="https://colab.research.google.com/drive/1aRNLUTQi3AX6nLWn-Mp132GIFYTFFjhW?usp=sharing" target="_blank" rel="noopener">colab範例檔</a><br>美國勞動部統計局有許多非常重要的資料，除了就業相關數據如失業率、非農、就業津貼，還有物價指數CPI、PPI，都能幫助我們後續做分析，趕緊學會該 API 的使用法則，打造總經分析武器庫。<br>想知道美國失業率如何應用在美國指數的擇時回測嗎？可以繼續看「<a href="https://www.finlab.tw/us_unemployment_rate_seasonally_adjusted_sp500_backtest/">用Python回測總經指標(2)｜美國失業率 vs S&amp;P 500指數</a>」踏入更豐富的數據世界。<br></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/us_unemployment_rate_seasonally_adjusted_crawler/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">4844</post-id>	</item>
	</channel>
</rss>
