<?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/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.finlab.tw</link>
	<description>深入淺出的量化投資，讓你在在茫茫股海中，找到專屬於自己的投資方法</description>
	<lastBuildDate>Thu, 17 Nov 2022 06:28:23 +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回測總經指標(2)｜美國失業率 vs S&#038;P 500指數</title>
		<link>https://www.finlab.tw/us_unemployment_rate_seasonally_adjusted_sp500_backtest/</link>
					<comments>https://www.finlab.tw/us_unemployment_rate_seasonally_adjusted_sp500_backtest/#respond</comments>
		
		<dc:creator><![CDATA[Ben]]></dc:creator>
		<pubDate>Thu, 10 Nov 2022 08:48:37 +0000</pubDate>
				<category><![CDATA[總體經濟]]></category>
		<category><![CDATA[FinLab 量化平台]]></category>
		<category><![CDATA[VIP文章]]></category>
		<category><![CDATA[財經PYTHON教學]]></category>
		<category><![CDATA[選股策略]]></category>
		<category><![CDATA[sp500]]></category>
		<category><![CDATA[失業率]]></category>
		<category><![CDATA[總經]]></category>
		<category><![CDATA[總經回測]]></category>
		<category><![CDATA[美國]]></category>
		<guid isPermaLink="false">https://www.finlab.tw/?p=4848</guid>

					<description><![CDATA[FED 打通膨不擇手段地升息，開始影響到實體經濟，除了一連串財爆，10-11月許多著名科技業如 Twitter、Meta都開始為了蹲節而裁員滾滾，從 裁員統整網站 資料可以見到一串觸目驚心的數字，10月的美國失業率是3.7%，還不是特別高，這個月失業率會不會噴出要等12月初才知道。究竟美國失業率要如何應用到策略上？FinLab量化平台能否支援 S&#038;P 500指數 的回測？本篇文章帶給你相關洞見與程式撰寫方法。]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-image size-full"><img width="960" height="540" src="https://www.finlab.tw/wp-content/uploads/2022/11/thumbnail.jpg" alt="thumbnail" class="wp-image-4849" srcset="https://www.finlab.tw/wp-content/uploads/2022/11/thumbnail.jpg 960w, https://www.finlab.tw/wp-content/uploads/2022/11/thumbnail-300x169.jpg 300w, https://www.finlab.tw/wp-content/uploads/2022/11/thumbnail-768x432.jpg 768w, https://www.finlab.tw/wp-content/uploads/2022/11/thumbnail-800x450.jpg 800w" sizes="(max-width: 960px) 100vw, 960px" title="用Python回測總經指標(2)｜美國失業率 vs S&amp;P 500指數 1"></figure>



<p class="has-medium-font-size">FED 打通膨不擇手段地升息，開始影響到實體經濟，除了一連串財爆，10-11月許多著名科技業如 Twitter、Meta都開始為了蹲節而裁員滾滾，從 <a href="https://layoffs.fyi/?fbclid=IwAR0_Q_xFJOu8JBnBKjosQ-gwnrkD3_HXK_wiVP17u4TEw85JfJWNhzXWDx8" target="_blank" rel="noopener">裁員統整網站 </a>資料可以見到一串觸目驚心的數字，10月的美國失業率是3.7%，還不是特別高，這個月失業率會不會噴出要等12月初才知道。究竟美國失業率要如何應用到策略上？FinLab量化平台能否支援 S&amp;P 500指數 的回測？本篇文章帶給你相關洞見與程式撰寫方法。</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="612" src="https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-10-下午3.55.42-1024x612.png" alt="截圖 2022 11 10 下午3.55.42" class="wp-image-4850" srcset="https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-10-下午3.55.42-1024x612.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-10-下午3.55.42-300x179.png 300w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-10-下午3.55.42-768x459.png 768w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-10-下午3.55.42-1536x919.png 1536w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-10-下午3.55.42-2048x1225.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="用Python回測總經指標(2)｜美國失業率 vs S&amp;P 500指數 2"></figure>



<h2>資料取得</h2>



<p class="has-medium-font-size">透過<a href="https://ai.finlab.tw/database/#us_unemployment_rate_seasonally_adjusted" target="_blank" rel="noopener">FinLab資料庫</a>即可一行取得失業率資料<br><code>data.get('us_unemployment_rate_seasonally_adjusted:value)'</code><br>如果你對抓取美國就業相關總經數據有興趣，可以參考此篇<a href="https://www.finlab.tw/us_unemployment_rate_seasonally_adjusted_crawler/">爬蟲教學</a>。</p>



<h2>圖表觀測</h2>



<p class="has-medium-font-size">美國數據比台灣數據好的地方在資料很早就有統計，可以做長時間回測，圖中可以發現失業率指標大致在3~10%擺盪，歷史失業率接近10%時，往往是股市低點，有人說目前的通盤環境類似1983年，但目前的失業率還在低檔，離10%高檔還很遠，是不是還沒末跌段？<br>失業率循環的週期普遍在5年以上，是蠻長線的指標，2000年以後，失業率與股市表現有明顯負相關，2000年以前股市和失業率關聯不大，S&amp;P 500幾乎一路往上衝。。</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="353" src="https://www.finlab.tw/wp-content/uploads/2022/11/newplot-24-1024x353.png" alt="newplot 24" class="wp-image-4851" srcset="https://www.finlab.tw/wp-content/uploads/2022/11/newplot-24-1024x353.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/11/newplot-24-300x103.png 300w, https://www.finlab.tw/wp-content/uploads/2022/11/newplot-24-768x265.png 768w, https://www.finlab.tw/wp-content/uploads/2022/11/newplot-24-1536x530.png 1536w, https://www.finlab.tw/wp-content/uploads/2022/11/newplot-24.png 2029w" sizes="(max-width: 1024px) 100vw, 1024px" title="用Python回測總經指標(2)｜美國失業率 vs S&amp;P 500指數 3"></figure>



<p class="has-medium-font-size"><br>為了方便長短期失業率趨勢，我們可將失業率化成均線，看MA6與MA2的差額，讓我們更能方便觀測短期失業率是否變嚴重，負值越高代表短期失業率越嚴重，可以發現指標由正轉負時，會領先預告股價崩跌，但由於訊號週期長，由負轉正也往往會錯過V轉反彈，2022由於就業市場太好，死叉訊號落後股市崩跌很多。</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="353" src="https://www.finlab.tw/wp-content/uploads/2022/11/newplot-25-1024x353.png" alt="newplot 25" class="wp-image-4852" srcset="https://www.finlab.tw/wp-content/uploads/2022/11/newplot-25-1024x353.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/11/newplot-25-300x103.png 300w, https://www.finlab.tw/wp-content/uploads/2022/11/newplot-25-768x265.png 768w, https://www.finlab.tw/wp-content/uploads/2022/11/newplot-25-1536x530.png 1536w, https://www.finlab.tw/wp-content/uploads/2022/11/newplot-25.png 2029w" sizes="(max-width: 1024px) 100vw, 1024px" title="用Python回測總經指標(2)｜美國失業率 vs S&amp;P 500指數 4"></figure>



<h2>總經指標回測</h2>



<h2>程式範例</h2>



<p class="has-medium-font-size">若我們想要用失業率回測 S&amp;P 500 指數，第一個面臨到的問題是 FinLab 量化平台可否回測台股以外的交易資料？<br>答案是可以的，只要繼承MarketInfo類別，客製化回測市場的資料，修改一下市場類別回傳的方法，最後將新類別傳入sim的market參數即可。範例將台股的資料換成世界指數的資料。<br>訊號條件只有一個失業率 MA2 小於 MA6 時持有<strong> S&amp;P 500 指數</strong></p>



<pre class="wp-block-code"><code lang="python" class="language-python">from finlab import data
from finlab.market_info import MarketInfo
from finlab.backtest import sim
import pandas as pd

class WorldIndexMarketInfo(MarketInfo):

    @staticmethod
    def get_benchmark():
        world_index = data.get('world_index:close')
        sp500 = world_index['^GSPC'].ffill()
        return sp500

    @staticmethod
    def get_asset_id_to_name():
        return {}

    @staticmethod
    def get_price(trade_at_price, adj=True):
        if isinstance(trade_at_price, pd.Series):
            return trade_at_price.to_frame()

        if isinstance(trade_at_price, pd.DataFrame):
            return trade_at_price

        if isinstance(trade_at_price, str):
            if trade_at_price == 'volume':
                return data.get('world_index:vol')

            if adj:
                table_name = 'world_index:adj_'
                price_name = trade_at_price
            else:
                table_name = 'world_index:'
                price_name = trade_at_price

            price = data.get(f'{table_name}{price_name}')
            return price

        raise Exception(f'**ERROR: trade_at_price is not allowed (accepted types: pd.DataFrame, pd.Series, str).')


from finlab import data

unemployment_rate = data.get('us_unemployment_rate_seasonally_adjusted:value')
close = data.get('world_index:close')
cond1 = (close.ffill() &gt; 0)[['^GSPC']]
cond2 = (unemployment_rate.average(2) &lt; unemployment_rate.average(6))['美國失業率(季調)'].reindex(cond1.index,method='ffill')

position = cond1 &amp; cond2

report = sim(position,resample='D', market=WorldIndexMarketInfo, name='us_unemplyment_rate', tax_ratio=0, fee_ratio=0, upload=False)
report.benchmark = close['^GSPC'].ffill()
report.display()</code></pre>



<h2>回測結果</h2>



<h3>全歷史</h3>



<p class="has-medium-font-size">使用失業率指標來擇時，沒有比一直持有好，但橘線的回檔曲線明顯優於一直持有，閃崩要閃V轉，報酬率與穩定度你選哪一個？</p>



<figure class="wp-block-image size-full"><img loading="lazy" width="800" height="600" src="https://www.finlab.tw/wp-content/uploads/2022/11/newplot-26.png" alt="newplot 26" class="wp-image-4853" srcset="https://www.finlab.tw/wp-content/uploads/2022/11/newplot-26.png 800w, https://www.finlab.tw/wp-content/uploads/2022/11/newplot-26-300x225.png 300w, https://www.finlab.tw/wp-content/uploads/2022/11/newplot-26-768x576.png 768w" sizes="(max-width: 800px) 100vw, 800px" title="用Python回測總經指標(2)｜美國失業率 vs S&amp;P 500指數 5"></figure>



<h3>2000年至今</h3>



<p class="has-medium-font-size">2000年以後的回測，失業率指標就明顯有效果，報酬率和回檔曲線都比一直持有好。</p>



<figure class="wp-block-image size-full"><img loading="lazy" width="800" height="600" src="https://www.finlab.tw/wp-content/uploads/2022/11/newplot-27.png" alt="newplot 27" class="wp-image-4854" srcset="https://www.finlab.tw/wp-content/uploads/2022/11/newplot-27.png 800w, https://www.finlab.tw/wp-content/uploads/2022/11/newplot-27-300x225.png 300w, https://www.finlab.tw/wp-content/uploads/2022/11/newplot-27-768x576.png 768w" sizes="(max-width: 800px) 100vw, 800px" title="用Python回測總經指標(2)｜美國失業率 vs S&amp;P 500指數 6"></figure>



<h2>結論</h2>



<p class="has-medium-font-size"><a href="https://colab.research.google.com/drive/1POSNOduTkTR053Y5ezqFw0duCHtOPkZB?usp=sharing" target="_blank" rel="noopener">colab 範例檔</a><br>world_index 資歷集內還有其他指數資料，趕快來探索更廣的應用！如果你對總經指標回測有興趣，可以參考參考之前類似的文章「<a href="https://www.finlab.tw/tw_monetary_aggregates_m1b_strategy/">用Python回測總經指標(1)｜M1B &amp; M2 年增率</a>」，如果有想要的總經指標，卻在 FinLab資料庫找不到，也歡迎到 <a href="http://Discord 聊天室" target="_blank">Discord</a> 與我們討論與許願喔。<br>失業率指標何時噴上來？會是末跌段一個重要指標，讓我們繼續看下去。</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/us_unemployment_rate_seasonally_adjusted_sp500_backtest/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">4848</post-id>	</item>
		<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 loading="lazy" 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｜失業率 7"><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｜失業率 8"><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>
