<?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%B8%BD%E7%B6%93/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.finlab.tw</link>
	<description>深入淺出的量化投資，讓你在在茫茫股海中，找到專屬於自己的投資方法</description>
	<lastBuildDate>Thu, 29 Dec 2022 12:02:28 +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回測總經指標(3)｜台灣景氣燈號｜加減碼策略</title>
		<link>https://www.finlab.tw/tw_business_indicator_changed_weight_strategy/</link>
					<comments>https://www.finlab.tw/tw_business_indicator_changed_weight_strategy/#respond</comments>
		
		<dc:creator><![CDATA[Ben]]></dc:creator>
		<pubDate>Thu, 29 Dec 2022 11:26:10 +0000</pubDate>
				<category><![CDATA[FinLab 量化平台]]></category>
		<category><![CDATA[VIP文章]]></category>
		<category><![CDATA[總體經濟]]></category>
		<category><![CDATA[選股策略]]></category>
		<category><![CDATA[0050]]></category>
		<category><![CDATA[加減碼]]></category>
		<category><![CDATA[景氣燈號]]></category>
		<category><![CDATA[總經]]></category>
		<guid isPermaLink="false">https://www.finlab.tw/?p=5072</guid>

					<description><![CDATA[國發會在12月底發布了上月景氣燈號數據，這個指標可以視為台灣總經的風向球。現進入低迷的藍燈，數值非常低，剩下1 [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p class="has-medium-font-size">國發會在12月底發布了上月景氣燈號數據，這個指標可以視為台灣總經的風向球。現進入低迷的藍燈，數值非常低，剩下12分，很久沒有這麼慘了。</p>



<figure class="wp-block-image size-large"><img width="1024" height="717" src="https://www.finlab.tw/wp-content/uploads/2022/12/截圖-2022-12-29-下午6.04.34-1024x717.png" alt="截圖 2022 12 29 下午6.04.34" class="wp-image-5073" srcset="https://www.finlab.tw/wp-content/uploads/2022/12/截圖-2022-12-29-下午6.04.34-1024x717.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/12/截圖-2022-12-29-下午6.04.34-300x210.png 300w, https://www.finlab.tw/wp-content/uploads/2022/12/截圖-2022-12-29-下午6.04.34-768x537.png 768w, https://www.finlab.tw/wp-content/uploads/2022/12/截圖-2022-12-29-下午6.04.34-1536x1075.png 1536w, https://www.finlab.tw/wp-content/uploads/2022/12/截圖-2022-12-29-下午6.04.34-2048x1433.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="用Python回測總經指標(3)｜台灣景氣燈號｜加減碼策略 1"><figcaption><a href="https://index.ndc.gov.tw/n/zh_tw" target="_blank" rel="noopener">取自國發會</a></figcaption></figure>



<figure class="wp-block-image size-large"><img loading="lazy" width="825" height="1024" src="https://www.finlab.tw/wp-content/uploads/2022/12/截圖-2022-12-29-下午6.14.43-825x1024.png" alt="截圖 2022 12 29 下午6.14.43" class="wp-image-5075" srcset="https://www.finlab.tw/wp-content/uploads/2022/12/截圖-2022-12-29-下午6.14.43-825x1024.png 825w, https://www.finlab.tw/wp-content/uploads/2022/12/截圖-2022-12-29-下午6.14.43-242x300.png 242w, https://www.finlab.tw/wp-content/uploads/2022/12/截圖-2022-12-29-下午6.14.43-768x953.png 768w, https://www.finlab.tw/wp-content/uploads/2022/12/截圖-2022-12-29-下午6.14.43.png 1036w" sizes="(max-width: 825px) 100vw, 825px" title="用Python回測總經指標(3)｜台灣景氣燈號｜加減碼策略 2"><figcaption>取自<a href="https://www.facebook.com/macromicro.me/posts/pfbid02S2hEbWiLi7Wt3c5My2qmvHPuHJPhXqzaacLM1mkgBMPvx7xoK4YE5seyvN8LfXnMl" target="_blank" rel="noopener">財經M平方臉書粉絲團</a></figcaption></figure>



<p class="has-medium-font-size">然而今年股市也回檔了超過20%，如果在景氣熱絡時進場，像是去年底，那你今年肯定很難過，現在你看到藍燈，是不是認為為總經環境差，要趕緊脫出股票？<br>市場老手「麥克風」則有不一樣的看法，認為「藍燈」反而是末跌段買點，只是要分批進場會比較安全。我的看法也是如此，通常進入藍燈時，股市早就反映一大段了，當未來爛無可爛，反而容易出現轉機，市場經常領先經濟數據。</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="933" src="https://www.finlab.tw/wp-content/uploads/2022/12/截圖-2022-12-29-下午6.12.42-1024x933.png" alt="截圖 2022 12 29 下午6.12.42" class="wp-image-5074" srcset="https://www.finlab.tw/wp-content/uploads/2022/12/截圖-2022-12-29-下午6.12.42-1024x933.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/12/截圖-2022-12-29-下午6.12.42-300x273.png 300w, https://www.finlab.tw/wp-content/uploads/2022/12/截圖-2022-12-29-下午6.12.42-768x700.png 768w, https://www.finlab.tw/wp-content/uploads/2022/12/截圖-2022-12-29-下午6.12.42-1536x1400.png 1536w, https://www.finlab.tw/wp-content/uploads/2022/12/截圖-2022-12-29-下午6.12.42.png 1545w" sizes="(max-width: 1024px) 100vw, 1024px" title="用Python回測總經指標(3)｜台灣景氣燈號｜加減碼策略 3"><figcaption>取自<a href="https://www.facebook.com/mktsurvivalkit/posts/pfbid0Y3czh2MLSYZxG6Utjr6povtP1R2Cq2vmAfncyiTMnuqGBJ1kSLmVU7p4rVnWn9Lrl" target="_blank" rel="noopener">麥克風臉書粉絲團</a></figcaption></figure>



<h2>景氣燈號如何撰寫加減碼？</h2>



<p class="has-medium-font-size">重點來了，許多人都知道要在藍燈分批買進，但分批加減碼究竟要如何撰寫？<br>通常寫策略都是一布林訊號通到底，100%持有。這就是FinLab量化平台的優勢，可以自動調控加減碼，可以自動調控加減碼，不限於固定部位，可靈活運用總經數據，把策略都自動化起來，比起外面的總經課程，更貼近實戰。<br><br><a href="https://doc.finlab.tw/reference/backtest/#finlab.backtest.sim" target="_blank" rel="noopener">回測函數</a> 當position 的數值除了可為布林訊號，也可以填入數值當持有部位調控，例如 0.2 為持有20%。</p>



<p class="has-medium-font-size">示範的景氣燈號加減碼策略邏輯為分5批進場。<br>只要近12個月內每一月景氣指標分數小於等於18時，分批買進20%部位。若景氣指標分數大於等於40時則全數賣出。舉例：若近12月內有3個月滿足條件，則持有60%，若近12月內有5個月以上滿足條件，則持有100%。<br>這個策略設計的背後思維在如果近12月內景氣燈號低於18分的月份越少，代表脫離藍燈谷底越遠，若近12月內景氣燈號低於18分的月份越多，則代表貼近景氣谷底，利用訊號數量去加乘持股部位。<br>另一個小重點在為何指標是用18與40分，而不是官方藍紅燈上下限的16分與38分？原因在策略若想要比人早一步，就要微調數值，且進入紅燈的熱絡階段，往往有所謂邪惡第五波，延遲出場有機會獲得更高報酬，而若用官方的16分當衰退指標，會發現低於16分的情況不多，所以往上微調，以增加訊號數。</p>



<pre class="wp-block-code"><code lang="python" class="language-python">from finlab import data
import pandas as pd
import numpy as np

df = data.get('tw_business_indicators:景氣對策信號(分)')
df = df[list(df['tw_business_indicators'] &gt; 0)]

# 只要近12個月內每一月景氣指標分數小於等於18時，分批買進20%部位。舉例：若近12月內有3個月滿足條件，則持有60%，若近12月內有5個月滿足條件，則持有100%。若景氣指標分數大於等於40時則全數賣出
batches = 5
ind = df['tw_business_indicators']
sig = pd.Series([True if i &lt;= 18 else False if i &gt;= 40 else np.nan for i in ind], index=ind.index)
position = (((sig / batches).rolling(12,min_periods=1).sum()) * sig).ffill().clip(0,1)
position.astype(float).plot()</code></pre>



<h2>景氣燈號加減碼訊號曲線變化</h2>



<p class="has-medium-font-size">可以發現加減碼曲線控制在 0%到100%，隨著時間不同而有不同持股部位變化。</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="703" src="https://www.finlab.tw/wp-content/uploads/2022/12/截圖-2022-12-29-下午6.33.30-1024x703.png" alt="截圖 2022 12 29 下午6.33.30" class="wp-image-5076" srcset="https://www.finlab.tw/wp-content/uploads/2022/12/截圖-2022-12-29-下午6.33.30-1024x703.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/12/截圖-2022-12-29-下午6.33.30-300x206.png 300w, https://www.finlab.tw/wp-content/uploads/2022/12/截圖-2022-12-29-下午6.33.30-768x527.png 768w, https://www.finlab.tw/wp-content/uploads/2022/12/截圖-2022-12-29-下午6.33.30.png 1420w" sizes="(max-width: 1024px) 100vw, 1024px" title="用Python回測總經指標(3)｜台灣景氣燈號｜加減碼策略 4"></figure>



<h2>回測程式</h2>



<p class="has-medium-font-size"><a href="https://colab.research.google.com/drive/1NbxeJydvdSyD_3zxYulvPJiJfb7UpOOw?usp=sharing" target="_blank" rel="noopener">colab 範例檔</a><br>回測程式很簡單，我們以 0050 元大台灣50 當操作台灣總經策略的標地，將上述的景氣燈號加減碼訊號傳入 0050 的 DataFrame，就會以該加減碼訊號靈活操作 0050 ，在景氣低迷時逐步入手，在景氣熱絡時拖出。<br>小細節是帶入回測時把交易稅率調成 ETF 適用的 1/1000。</p>



<pre class="wp-block-code"><code lang="python" class="language-python">from finlab.backtest import sim

# 將持有部位帶進0050
close = data.get('price:收盤價')
buy = pd.DataFrame({'0050':position})
buy = buy.reindex(close.index, method='ffill')
report = sim(buy, upload=False, tax_ratio=1/1000)
report.display()</code></pre>



<p class="has-medium-font-size">回測結果發現該策略可以取得比長期持有0050還好的績效，熊市時期的2007與2022回檔幅度較小，波動曲線更為漂亮。</p>



<figure class="wp-block-image size-full"><img loading="lazy" width="800" height="600" src="https://www.finlab.tw/wp-content/uploads/2022/12/newplot-49.png" alt="newplot 49" class="wp-image-5077" srcset="https://www.finlab.tw/wp-content/uploads/2022/12/newplot-49.png 800w, https://www.finlab.tw/wp-content/uploads/2022/12/newplot-49-300x225.png 300w, https://www.finlab.tw/wp-content/uploads/2022/12/newplot-49-768x576.png 768w" sizes="(max-width: 800px) 100vw, 800px" title="用Python回測總經指標(3)｜台灣景氣燈號｜加減碼策略 5"></figure>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/tw_business_indicator_changed_weight_strategy/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">5072</post-id>	</item>
		<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 loading="lazy" 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指數 6"></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指數 7"></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指數 8"></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指數 9"></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指數 10"></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指數 11"></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｜失業率 12"><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｜失業率 13"><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>
		<item>
		<title>用Python回測總經指標(1)｜M1B &#038; M2 年增率</title>
		<link>https://www.finlab.tw/tw_monetary_aggregates_m1b_strategy/</link>
					<comments>https://www.finlab.tw/tw_monetary_aggregates_m1b_strategy/#respond</comments>
		
		<dc:creator><![CDATA[Ben]]></dc:creator>
		<pubDate>Fri, 04 Nov 2022 13:53:48 +0000</pubDate>
				<category><![CDATA[總體經濟]]></category>
		<category><![CDATA[FinLab 量化平台]]></category>
		<category><![CDATA[技術面]]></category>
		<category><![CDATA[選股策略]]></category>
		<category><![CDATA[m1b]]></category>
		<category><![CDATA[動能策略]]></category>
		<category><![CDATA[總經]]></category>
		<guid isPermaLink="false">https://www.finlab.tw/?p=4809</guid>

					<description><![CDATA[利用上一篇「Python爬蟲教學｜台灣貨幣總計數 M1B &#038; M2」的資料，我們可以用來回測該指標是否為具有領先性的大盤濾網，並測試看看資金流動性指標是否能優化股價動能策略，在市場資金變保守時，能否減低動能策略回檔的殺傷力？]]></description>
										<content:encoded><![CDATA[
<p class="has-medium-font-size">利用上一篇「<a href="https://www.finlab.tw/tw_monetary_aggregates_m1b_crawler/">Python爬蟲教學｜台灣貨幣總計數 M1B &amp; M2</a>」的<a href="https://ai.finlab.tw/database#%E8%B2%A8%E5%B9%A3%E7%B8%BD%E8%A8%88%E6%95%B8%E5%B9%B4%E5%A2%9E%E7%8E%87" target="_blank" rel="noopener">資料</a>，我們可以用來回測該指標是否為具有領先性的大盤濾網，並測試看看資金流動性指標是否能優化股價動能策略，在市場資金變保守時，能否減低動能策略回檔的殺傷力？</p>



<h2>指標意義</h2>



<blockquote class="wp-block-quote has-medium-font-size"><p>M1B＝M1A（通貨淨額 ＋ 支票存款 ＋ 活期存款）＋活期儲蓄存款，為人民手邊可隨時動用的資金。 </p><p>M2＝M1B＋準備貨幣（如定期存款、郵政儲金及外匯存款），流動性較 M1B 低，代表整體市場的資金。 <br>當 M1B 年增率 &#8211; M2 年增率 ＞ 0，表示流動資金成長較定存快，台股資金越活絡。 當 M1B 年增率 &#8211; M2 年增率 &lt; 0，表示流動資金成長較定存慢，台股資金越趨緩。 在過去幾次循環中，M1B 減 M2（年增率）常領先台股三至六個月前出現上漲，在 M1B 減 M2 出現向下走勢時，台股亦出現下跌（資料來源：<a href="https://www.macromicro.me/charts/718/tw-m1b-m2-twse" target="_blank" rel="noopener">財經M平方</a>）。</p></blockquote>



<p class="has-medium-font-size">總經平台「<a href="https://www.macromicro.me/" target="_blank" rel="noopener">財經M平方</a>」有豐富的總經資訊，如果對總經指標不熟悉，可以在該平台習得知識，了解概念後，就可以使用「<a href="https://doc.finlab.tw/getting-start/" target="_blank" rel="noopener"> FinLab 回測模組</a>」來驗證。「 M1B 年增率 &#8211; M2 年增率 ＞ 0」這個指標有用嗎？</p>



<h2>圖表觀察</h2>



<p class="has-medium-font-size">寫回測之前，可以先將數據視覺化簡單觀測一下「資金指標與加權報酬指數關係圖」。<br>灰色區塊是每次「 M1B 年增率 &#8211; M2 年增率 剛小於 0」到「 M1B 年增率 &#8211; M2 年增率 剛大於 0」的區間。<br>圖中可發現 2000 以前由於銀行利率很高，在那個定存5%的年代，M2 年增率好長一陣子都大於M1B年增率。<br>2000 以後，利率開始降，資金開始流入股市，展開台股大多頭。<br>2006-2007 指標出現好幾次震盪，但看起來是提早被洗掉。<br>2008 該指標領先崩盤訊號，成功躲掉崩盤，但股市反轉一大段後，該指標才翻多，看起來也躲掉大漲。金融海嘯後全球開始印鈔，降息降到極限，維持好長一段「 M1B 年增率 &#8211; M2 年增率 ＞ 0」，2012-2013 的訊號失靈，2015 的訊號有領先，2017-2018 出現極短循環。<br>而 2022 這次崩盤，雖然美國狂升息，但 M2年增率 由於「台灣央行」升息很慢，所以增幅並不明顯，由於之前M1B增幅很快，收斂要時間，所以直到崩了好一大段後，現在才又轉負，<strong>沒能提早示警</strong>。</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="378" src="https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-04-下午9.06.12-1024x378.png" alt="截圖 2022 11 04 下午9.06.12" class="wp-image-4817" srcset="https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-04-下午9.06.12-1024x378.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-04-下午9.06.12-300x111.png 300w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-04-下午9.06.12-768x283.png 768w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-04-下午9.06.12-1536x567.png 1536w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-04-下午9.06.12-2048x756.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="用Python回測總經指標(1)｜M1B &amp; M2 年增率 14"><figcaption>資金指標與加權報酬指數關係圖</figcaption></figure>



<h2>M1與Ｍ2交叉訊號回測</h2>



<p class="has-medium-font-size">圖表訊號看起來實用性是55波。寫程式回測一下，操作標的為「0050 元大台灣50 (藍線)」。<br>結果和一直持有(灰線)的結果是差不多的&#8230;雖然可能會躲崩，但也會落後進場。然後慘烈的 2022 整段回檔吃下來，是不是不用那麼忙？</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-20.png" alt="newplot 20" class="wp-image-4819" srcset="https://www.finlab.tw/wp-content/uploads/2022/11/newplot-20.png 800w, https://www.finlab.tw/wp-content/uploads/2022/11/newplot-20-300x225.png 300w, https://www.finlab.tw/wp-content/uploads/2022/11/newplot-20-768x576.png 768w" sizes="(max-width: 800px) 100vw, 800px" title="用Python回測總經指標(1)｜M1B &amp; M2 年增率 15"></figure>



<h2>M1均線指標</h2>



<p class="has-medium-font-size">為何「 M1B 年增率 &#8211; M2 年增率 ＞ 0」會沒傳說中的有用？<br>我想關鍵在於跟<strong>「M2 年增率」的波動不大</strong>有關，「M1B 年增率」波動才是關鍵，像 2022 由於 2021 資金行情讓兩者差距太大，在 M2 上升不夠下，M1B 要收斂向下穿過 M2 要花的時間太長。<br>實際要使用的話，我會試試單用「M1B 均線訊號來回測」，例如當月「M1B 年增率」穿越「M1B 年增率近6月平均年增率」當訊號，產生更靈敏的指標，訊號也變多。將條件修改回測結果如下，確實能解決「M2 年增率」太遲緩的問題，以此操作 0050 或是長期投資台股指數，會有擇時進出場的優勢。</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-21.png" alt="newplot 21" class="wp-image-4820" srcset="https://www.finlab.tw/wp-content/uploads/2022/11/newplot-21.png 800w, https://www.finlab.tw/wp-content/uploads/2022/11/newplot-21-300x225.png 300w, https://www.finlab.tw/wp-content/uploads/2022/11/newplot-21-768x576.png 768w" sizes="(max-width: 800px) 100vw, 800px" title="用Python回測總經指標(1)｜M1B &amp; M2 年增率 16"></figure>



<h2>Top Down 選股策略實測</h2>



<p class="has-medium-font-size">Top Down 選股法簡單說是先分析最上層的總經，大環境若逆風，則不再後續選股動作。要確認大環境好，才進行選股，不是硬要靠選股能力待在市場，而是選最順風的時候。<br>動能策略在資金行情時，往往衝第一，然而當資金消退時，也是跌勢驚人！究竟「M1B 均線指標」能不能進一步提升「動能策略」的績效？</p>



<h3>動能策略範例</h3>



<p class="has-medium-font-size">範例選定為「<a href="https://www.finlab.tw/breakthrough_stock_picking_strategies/">突破策略豆知識 | 如何避免假突破?</a>」文章中的「<a href="https://doc.finlab.tw/tools/%E8%82%A1%E5%83%B9%E5%89%B5%E6%96%B0%E9%AB%98%E5%8B%95%E8%83%BD/" target="_blank" rel="noopener">創新高延續動能策略</a>」。<br>回測績效如下，很兇猛。</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-22.png" alt="newplot 22" class="wp-image-4821" srcset="https://www.finlab.tw/wp-content/uploads/2022/11/newplot-22.png 800w, https://www.finlab.tw/wp-content/uploads/2022/11/newplot-22-300x225.png 300w, https://www.finlab.tw/wp-content/uploads/2022/11/newplot-22-768x576.png 768w" sizes="(max-width: 800px) 100vw, 800px" title="用Python回測總經指標(1)｜M1B &amp; M2 年增率 17"></figure>



<h3>動能策略＊資金行情指標回測</h3>



<p class="has-medium-font-size">下圖中是套上「M1B 均線指標」當大盤濾網，可以發現雖然 2022 成功躲過，但前幾年也錯過不少飆股機會，累積報酬率少了7倍，且最後與一直持有指數是一樣的，白忙一場。長期待在市場衝鋒陷陣才是王道？</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-23.png" alt="newplot 23" class="wp-image-4822" srcset="https://www.finlab.tw/wp-content/uploads/2022/11/newplot-23.png 800w, https://www.finlab.tw/wp-content/uploads/2022/11/newplot-23-300x225.png 300w, https://www.finlab.tw/wp-content/uploads/2022/11/newplot-23-768x576.png 768w" sizes="(max-width: 800px) 100vw, 800px" title="用Python回測總經指標(1)｜M1B &amp; M2 年增率 18"></figure>



<h2>結論</h2>



<ul class="has-medium-font-size"><li>「 M1B 年增率 &#8211; M2 年增率 ＞ 0」不夠靈敏。</li><li>「M1B 年增率」穿越「M1B 年增率近6月平均年增率」較能解決「M2 年增率」不靈敏的問題，有助於台股指數擇時操作，但個股策略則無明顯效果。</li></ul>



<p class="has-medium-font-size"><a href="https://colab.research.google.com/drive/1M7udDTTckhdfgQyAlKOzpepI-hSWiAAT?usp=sharing" target="_blank" rel="noopener">colab 範例程式檔</a> 提供大家自己驗證，之後會繼續研究其他總經指標。</p>



<p></p>



<p></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/tw_monetary_aggregates_m1b_strategy/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">4809</post-id>	</item>
	</channel>
</rss>
