<?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>財經PYTHON教學 &#8211; FinLab</title>
	<atom:link href="https://www.finlab.tw/category/%E8%B2%A1%E7%B6%93python%E6%95%99%E5%AD%B8/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.finlab.tw</link>
	<description>深入淺出的量化投資，讓你在在茫茫股海中，找到專屬於自己的投資方法</description>
	<lastBuildDate>Wed, 08 Oct 2025 02:05:33 +0000</lastBuildDate>
	<language>zh-TW</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.0.11</generator>

<image>
	<url>https://www.finlab.tw/wp-content/uploads/2020/07/favicon.png</url>
	<title>財經PYTHON教學 &#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>把「靈感」煉成「因子」：從感覺到證據的逆襲</title>
		<link>https://www.finlab.tw/factor_analysis_3_factor/</link>
					<comments>https://www.finlab.tw/factor_analysis_3_factor/#respond</comments>
		
		<dc:creator><![CDATA[Andy]]></dc:creator>
		<pubDate>Fri, 22 Aug 2025 04:09:08 +0000</pubDate>
				<category><![CDATA[FinLab 量化平台]]></category>
		<category><![CDATA[Python新手教學]]></category>
		<category><![CDATA[PYTHON財經]]></category>
		<category><![CDATA[基本面分析]]></category>
		<category><![CDATA[投資新手]]></category>
		<category><![CDATA[股票策略]]></category>
		<category><![CDATA[財經PYTHON教學]]></category>
		<category><![CDATA[PYTHON]]></category>
		<category><![CDATA[程式交易]]></category>
		<category><![CDATA[股票]]></category>
		<category><![CDATA[量化投資]]></category>
		<guid isPermaLink="false">https://www.finlab.tw/?p=6685</guid>

					<description><![CDATA[你一定懂那種瞬間——螢幕上跳出一檔飆股，心裡直覺「它會漲」。但直覺不會每次都對。於是我們決定反過來做：把靈感拆 [&#8230;]]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-image size-large"><img width="683" height="1024" src="https://www.finlab.tw/wp-content/uploads/2025/08/image-2-683x1024.png" alt="image 2" class="wp-image-6701" srcset="https://www.finlab.tw/wp-content/uploads/2025/08/image-2-683x1024.png 683w, https://www.finlab.tw/wp-content/uploads/2025/08/image-2-200x300.png 200w, https://www.finlab.tw/wp-content/uploads/2025/08/image-2-768x1152.png 768w, https://www.finlab.tw/wp-content/uploads/2025/08/image-2.png 1024w" sizes="(max-width: 683px) 100vw, 683px" title="把「靈感」煉成「因子」：從感覺到證據的逆襲 1"><figcaption>封面圖片</figcaption></figure>



<p></p>



<p>你一定懂那種瞬間——螢幕上跳出一檔飆股，心裡直覺「它會漲」。但直覺不會每次都對。於是我們決定反過來做：把靈感拆成可驗證的「因子」，把「為什麼漲」說清楚，然後用資料驗證。</p>



<p>難嗎？不簡單。因為我們有工具可以把難的事做得乾淨俐落。</p>



<h2><strong>和一般做法，哪裡不一樣？</strong></h2>



<p>一般做法：先選幾個看起來厲害的指標，湊一套回測；結果好就覺得是神功，結果差就再換一套。</p>



<p>我們的做法：先把策略拆解，再逐一檢驗每個因子的線索：它帶來的超額報酬是多少？在什麼狀態下有效？會不會太擁擠（大家都在用）？彼此相關性高不高？</p>



<p>沒有 Finlab 我們得自己處理：資料下載、清洗、對齊、換股對齊、月/季頻率對接… 一個環節錯了，結果就不可信。</p>



<p>有了 finlab，我們可以直接用一致頻率的資料集與安全的 resample 邏輯，把時間對齊、避免偷看未來；剩下的，就是認真跟資料搏鬥。</p>



<h2><strong>我們的範例策略：</strong></h2>



<p>三個最基本、卻常被忽略「為什麼」的因子：市值、營收動能、價格動能。</p>



<ul><li>為什麼要小市值？因為小市值在資訊修正與資金挹注時，彈性常常更大。</li><li>為什麼看營收加速？因為是最扎實的推力。</li><li>為什麼要動能？因為市場的從眾與慣性，往往延長趨勢。</li></ul>



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

marketcap = data.get('etl:market_value')
revenue   = data.get('monthly_revenue:當月營收')
close     = data.get('price:收盤價')

cond_smallcap = marketcap.rank(pct=True, axis=1) &lt; 0.3
cond_revgro   = (revenue.average(3) / revenue.average(12)).rank(pct=True, axis=1) &gt; 0.7
cond_momentum = (close / close.shift(20)).rank(pct=True, axis=1) &gt; 0.7

pos = cond_smallcap &amp; cond_revgro &amp; cond_momentum
report = backtest.sim(pos, resample='ME', upload=False)
report.display()</code></pre>



<blockquote class="wp-block-quote"><p><strong>為什麼要用 rank？</strong>比較的是「相對位置」，而不是絕對數值。</p></blockquote>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="1011" src="https://www.finlab.tw/wp-content/uploads/2025/08/CleanShot-2025-08-22-at-10.46.02@2x-1024x1011.png" alt="CleanShot 2025 08 22 at 10.46.02@2x" class="wp-image-6687" srcset="https://www.finlab.tw/wp-content/uploads/2025/08/CleanShot-2025-08-22-at-10.46.02@2x-1024x1011.png 1024w, https://www.finlab.tw/wp-content/uploads/2025/08/CleanShot-2025-08-22-at-10.46.02@2x-300x296.png 300w, https://www.finlab.tw/wp-content/uploads/2025/08/CleanShot-2025-08-22-at-10.46.02@2x-768x758.png 768w, https://www.finlab.tw/wp-content/uploads/2025/08/CleanShot-2025-08-22-at-10.46.02@2x-1536x1516.png 1536w, https://www.finlab.tw/wp-content/uploads/2025/08/CleanShot-2025-08-22-at-10.46.02@2x.png 1544w" sizes="(max-width: 1024px) 100vw, 1024px" title="把「靈感」煉成「因子」：從感覺到證據的逆襲 2"><figcaption>回測結果</figcaption></figure>



<h2><strong>把策略拆成可驗證的語言：特徵 &amp; 標籤</strong></h2>



<p>先定義我們「到底要預測什麼」：未來一段時間的超額報酬（相對市場平均）。這是策略的真目標，而不是單看漲跌。</p>



<pre class="wp-block-code"><code lang="python" class="language-python">from finlab import data
import finlab.ml.feature as feature
import finlab.ml.label as label

features = feature.combine({
    'marketcap' : cond_smallcap,
    'revenue'   : cond_revgro,
    'momentum'  : cond_momentum
}, resample='ME')

labels = label.excess_over_mean(index=features.index, resample='ME')</code></pre>



<blockquote class="wp-block-quote"><p>為什麼用超額報酬？ 因為我們將焦點從「追隨市場」轉向「超越對手」。我們比較的不是大盤的絕對速度，而是相對於競爭者的反應速度。</p></blockquote>



<h2><strong>因子報酬（Factor Return）：它到底有沒有賺到「解釋力」？</strong></h2>



<p>把每個因子的「獨立效果」抽出來，看長期累積報酬線條。線條不只代表報酬，更是「這個因子值得被相信」的證詞。</p>



<pre class="wp-block-code"><code lang="python" class="language-python">from finlab.tools.factor_analysis import calc_factor_return
from finlab.plot import plot_line

factor_return = calc_factor_return(features, labels).cumsum()
plot_line(factor_return, unit='.0%', title='因子累積報酬')</code></pre>



<figure class="wp-block-image size-full"><img loading="lazy" width="788" height="435" src="https://www.finlab.tw/wp-content/uploads/2025/08/CleanShot-2025-08-22-at-11.03.52.png" alt="CleanShot 2025 08 22 at 11.03.52" class="wp-image-6688" srcset="https://www.finlab.tw/wp-content/uploads/2025/08/CleanShot-2025-08-22-at-11.03.52.png 788w, https://www.finlab.tw/wp-content/uploads/2025/08/CleanShot-2025-08-22-at-11.03.52-300x166.png 300w, https://www.finlab.tw/wp-content/uploads/2025/08/CleanShot-2025-08-22-at-11.03.52-768x424.png 768w" sizes="(max-width: 788px) 100vw, 788px" title="把「靈感」煉成「因子」：從感覺到證據的逆襲 3"><figcaption>因子累積報酬</figcaption></figure>



<blockquote class="wp-block-quote"><p><strong>為什麼先看累積線？</strong> 因為短期雜訊會騙人，長期線條的斜率與轉折，才能看出它是偶然還是規律。</p></blockquote>



<h2><strong>因子集中度（Centrality）：因子擁擠嗎？</strong></h2>



<p>當一個因子被同時大量採用，接著因子趨向擁擠、碰到回檔風險上升。我們用主成分分析的權重，量化「共同性」。</p>



<ul><li>數值大：近期用它選股都賺，表示擁擠；下一步要<strong>警戒回檔</strong>。</li><li>數值小：近期表現差，反而可能接近「冷門反擊」的起點。</li></ul>



<pre class="wp-block-code"><code lang="python" class="language-python">from finlab.tools.factor_analysis import calc_centrality
centrality = calc_centrality(calc_factor_return(features, labels), 12)

plot_line(centrality, title='因子集中度')</code></pre>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="576" src="https://www.finlab.tw/wp-content/uploads/2025/08/CleanShot-2025-08-22-at-11.12.41@2x-1024x576.png" alt="CleanShot 2025 08 22 at 11.12.41@2x" class="wp-image-6689" srcset="https://www.finlab.tw/wp-content/uploads/2025/08/CleanShot-2025-08-22-at-11.12.41@2x-1024x576.png 1024w, https://www.finlab.tw/wp-content/uploads/2025/08/CleanShot-2025-08-22-at-11.12.41@2x-300x169.png 300w, https://www.finlab.tw/wp-content/uploads/2025/08/CleanShot-2025-08-22-at-11.12.41@2x-768x432.png 768w, https://www.finlab.tw/wp-content/uploads/2025/08/CleanShot-2025-08-22-at-11.12.41@2x-1536x863.png 1536w, https://www.finlab.tw/wp-content/uploads/2025/08/CleanShot-2025-08-22-at-11.12.41@2x-800x450.png 800w, https://www.finlab.tw/wp-content/uploads/2025/08/CleanShot-2025-08-22-at-11.12.41@2x.png 1580w" sizes="(max-width: 1024px) 100vw, 1024px" title="把「靈感」煉成「因子」：從感覺到證據的逆襲 4"><figcaption>因子集中度</figcaption></figure>



<blockquote class="wp-block-quote"><p>為什麼要看擁擠度？ 因為市場是動態的，當所有人一起衝進同一個因子，邊際報酬就會變脆弱。</p></blockquote>



<h2>因子貢獻度 (<strong>Shapley Values)：把功勞分清楚</strong></h2>



<p>我們不只看「有賺」，還要知道「誰在出力」。Shapley 用公平分配的方式，拆解各因子的邊際貢獻。</p>



<pre class="wp-block-code"><code lang="python" class="language-python">from finlab.tools.factor_analysis import calc_shapley_values
shapley = calc_shapley_values(features, labels)
plot_line(shapley, title='因子貢獻度')</code></pre>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="572" src="https://www.finlab.tw/wp-content/uploads/2025/08/CleanShot-2025-08-22-at-11.16.23@2x-1024x572.png" alt="CleanShot 2025 08 22 at 11.16.23@2x" class="wp-image-6690" srcset="https://www.finlab.tw/wp-content/uploads/2025/08/CleanShot-2025-08-22-at-11.16.23@2x-1024x572.png 1024w, https://www.finlab.tw/wp-content/uploads/2025/08/CleanShot-2025-08-22-at-11.16.23@2x-300x168.png 300w, https://www.finlab.tw/wp-content/uploads/2025/08/CleanShot-2025-08-22-at-11.16.23@2x-768x429.png 768w, https://www.finlab.tw/wp-content/uploads/2025/08/CleanShot-2025-08-22-at-11.16.23@2x-1536x859.png 1536w, https://www.finlab.tw/wp-content/uploads/2025/08/CleanShot-2025-08-22-at-11.16.23@2x.png 1578w" sizes="(max-width: 1024px) 100vw, 1024px" title="把「靈感」煉成「因子」：從感覺到證據的逆襲 5"><figcaption>因子貢獻度</figcaption></figure>



<blockquote class="wp-block-quote"><p>為什麼要拆貢獻？ 因為多因子策略容易「誰都沾一點」，但在壓力時刻，你要知道要砍誰、留誰。</p></blockquote>



<h2><strong>IC（Information Coefficient）：預測力的體檢表</strong></h2>



<p>我們把分數和未來報酬做相關（可用 rank），長期 IC 穩定偏正、且不是只靠少數極端時期拉高，才叫做真正的「可預測」。</p>



<pre class="wp-block-code"><code lang="python" class="language-python">from finlab.tools.factor_analysis import calc_ic

features_ic = {
    'marketcap': -marketcap,  # 小市值用負號
    'revenue'  : revenue.average(3) / revenue.average(12),
    'momentum' : close / close.shift(20),
}
features_ic = feature.combine(features_ic, resample='ME')

ic_df = calc_ic(features_ic, labels, rank=True)
plot_line(ic_df, title='因子相關性')</code></pre>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="572" src="https://www.finlab.tw/wp-content/uploads/2025/08/CleanShot-2025-08-22-at-11.35.02@2x-1024x572.png" alt="CleanShot 2025 08 22 at 11.35.02@2x" class="wp-image-6692" srcset="https://www.finlab.tw/wp-content/uploads/2025/08/CleanShot-2025-08-22-at-11.35.02@2x-1024x572.png 1024w, https://www.finlab.tw/wp-content/uploads/2025/08/CleanShot-2025-08-22-at-11.35.02@2x-300x168.png 300w, https://www.finlab.tw/wp-content/uploads/2025/08/CleanShot-2025-08-22-at-11.35.02@2x-768x429.png 768w, https://www.finlab.tw/wp-content/uploads/2025/08/CleanShot-2025-08-22-at-11.35.02@2x-1536x858.png 1536w, https://www.finlab.tw/wp-content/uploads/2025/08/CleanShot-2025-08-22-at-11.35.02@2x.png 1582w" sizes="(max-width: 1024px) 100vw, 1024px" title="把「靈感」煉成「因子」：從感覺到證據的逆襲 6"><figcaption>因子相關性</figcaption></figure>



<blockquote class="wp-block-quote"><p><strong>為什麼要看 IC？</strong> 因為報酬可能來自風格或偶然，但「相關性」在長期裡更難偽裝。</p></blockquote>



<h2><strong>趨勢偵測：隨時間變化數值</strong></h2>



<p>我們用回歸去看「集中度、貢獻、IC」的趨勢：上升？下降？還是平？</p>



<pre class="wp-block-code"><code lang="python" class="language-python">from finlab.tools.factor_analysis import calc_regression_stats
centrality_trend = calc_regression_stats(centrality)</code></pre>



<p></p>



<ul><li><strong>p 值小 + 斜率正</strong>：真正在升溫；</li><li><strong>p 值小 + 斜率負</strong>：退潮真正發生；</li><li><strong>解釋力低（R²小）</strong>：暫時別下定論，當它不存在。</li></ul>



<figure class="wp-block-table"><table><thead><tr><th><strong>p_value</strong></th><th><strong>r_squared</strong></th><th><strong>slope</strong></th><th><strong>trend</strong></th><th><strong>含義</strong></th></tr></thead><tbody><tr><td><strong>小</strong></td><td><strong>高</strong></td><td><strong>正</strong></td><td>up</td><td>強烈且穩定的上升趨勢</td></tr><tr><td><strong>小</strong></td><td><strong>高</strong></td><td><strong>負</strong></td><td>down</td><td>強烈且穩定的下降趨勢</td></tr><tr><td><strong>小</strong></td><td><strong>低</strong></td><td>任意</td><td>flat</td><td>趨勢存在但效果小/雜訊大</td></tr><tr><td><strong>大</strong></td><td><strong>高</strong></td><td>任意</td><td>flat</td><td>樣本少，雜訊高，無法判斷</td></tr><tr><td><strong>大</strong></td><td><strong>低</strong></td><td>任意</td><td>flat</td><td>基本無趨勢且模型無解釋力</td></tr></tbody></table></figure>



<h3><strong>實例分析</strong></h3>



<ul><li><strong>Marketcap (市值因子)</strong></li></ul>



<p><code>slope: -0.000111 (負值) </code><br><code>p_value: 3.10e-17 (極度顯著) </code><br><code>r_squared: 0.40 (中等偏強解釋力) </code><br><code>trend: down</code></p>



<p><strong>解讀</strong>: 市值因子的集中度呈現非常強烈且統計上極度顯著的下降趨勢。</p>



<ul><li><strong>Revenue (營收因子)</strong></li></ul>



<p><code>slope: 0.000018 (正值)</code><br><code>p_value: 0.0048 (顯著) </code><br><code>r_squared: 0.056 (解釋力較弱) </code><br><code>trend: flat (因 r_squared &lt; 0.1)</code></p>



<p><strong>解讀</strong>: 營收因子有統計上顯著的上升趨勢，但由於解釋力不足 (r_squared &lt; 0.1)，被歸類為 flat。</p>



<ul><li><strong>Momentum (動能因子)</strong></li></ul>



<p><code>slope: 0.000093 (顯著正值) </code><br><code>p_value: 1.14e-17 (極度顯著) </code><br><code>r_squared: 0.41 (中等偏強解釋力) </code><br><code>trend: up</code></p>



<p><strong>解讀</strong>: 動能因子的集中度呈現非常強烈且統計上極度顯著的上升趨勢。這是一個明確的信號，表明動能因子非常「熱門」，大量資金正在追逐這個策略。</p>



<blockquote class="wp-block-quote"><p><strong>為什麼做趨勢？</strong> 因為資金有輪動。與其死守某一信仰，不如跟著證據調整權重。</p></blockquote>



<h2>總結</h2>



<h3>解決分析前的難點</h3>



<ul><li>多頻資料對齊：日價、月營收、季財報……沒有統一索引會災難。</li><li>風險：偷看未來、不同頻率窗口誤用，都會讓結果「看起來很美」。</li><li>擁擠：策略跑出來以後，大家都用，它就不香了。這就是為什麼<strong>Centrality</strong>與<strong>趨勢偵測</strong>是必要的。</li><li>因子工具把「報酬、擁擠、貢獻、IC」變成<strong>可重複</strong>的研究流程。</li></ul>



<h3><strong>行動建議：你可以直接用這篇當「研究框架」模板</strong></h3>



<ol><li>用 feature.combine/label.excess_over_mean 定義問題；</li><li>跑 因子報酬 / 集中度 / Shapley / IC / 趨勢 五件套；</li><li>用趨勢結果去<strong>調整權重</strong>，而不是迷信單因子。</li></ol>



<p>歡迎參考&nbsp;<a href="https://colab.research.google.com/drive/1pa27imv0k_O-qRKjg4fSr9Eq4tx-GwyL?usp=sharing" data-type="URL" data-id="https://colab.research.google.com/drive/1pa27imv0k_O-qRKjg4fSr9Eq4tx-GwyL?usp=sharing" target="_blank" rel="noopener">Colab 範例檔</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/factor_analysis_3_factor/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">6685</post-id>	</item>
		<item>
		<title>復刻與優化 00900 ：使用 IC Decay 優化高股息策略成「長跑軍火庫」</title>
		<link>https://www.finlab.tw/%e5%be%a9%e5%88%bb%e8%88%87%e5%84%aa%e5%8c%96-00900-%ef%bc%9a%e4%bd%bf%e7%94%a8-ic-decay-%e5%84%aa%e5%8c%96%e9%ab%98%e8%82%a1%e6%81%af%e7%ad%96%e7%95%a5%e6%88%90%e3%80%8c%e9%95%b7%e8%b7%91%e8%bb%8d/</link>
					<comments>https://www.finlab.tw/%e5%be%a9%e5%88%bb%e8%88%87%e5%84%aa%e5%8c%96-00900-%ef%bc%9a%e4%bd%bf%e7%94%a8-ic-decay-%e5%84%aa%e5%8c%96%e9%ab%98%e8%82%a1%e6%81%af%e7%ad%96%e7%95%a5%e6%88%90%e3%80%8c%e9%95%b7%e8%b7%91%e8%bb%8d/#respond</comments>
		
		<dc:creator><![CDATA[Andy]]></dc:creator>
		<pubDate>Tue, 03 Jun 2025 08:02:23 +0000</pubDate>
				<category><![CDATA[VIP文章]]></category>
		<category><![CDATA[FinLab 量化平台]]></category>
		<category><![CDATA[Python新手教學]]></category>
		<category><![CDATA[PYTHON財經]]></category>
		<category><![CDATA[基本面分析]]></category>
		<category><![CDATA[投資新手]]></category>
		<category><![CDATA[股票策略]]></category>
		<category><![CDATA[財經PYTHON教學]]></category>
		<category><![CDATA[PYTHON]]></category>
		<category><![CDATA[VIP限定]]></category>
		<category><![CDATA[程式交易]]></category>
		<category><![CDATA[股票]]></category>
		<category><![CDATA[選股策略]]></category>
		<category><![CDATA[量化投資]]></category>
		<guid isPermaLink="false">https://www.finlab.tw/?p=6620</guid>

					<description><![CDATA[前言 市場上的高股息 ETF 各有特色，這次將以富邦特選高股息30（00900）為例，分析其追蹤的「臺灣指數公 [&#8230;]]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-image size-large"><img loading="lazy" width="820" height="1024" src="https://www.finlab.tw/wp-content/uploads/2025/05/CleanShot-2025-05-22-at-10.03.35@2x-820x1024.png" alt="CleanShot 2025 05 22 at 10.03.35@2x" class="wp-image-6648" srcset="https://www.finlab.tw/wp-content/uploads/2025/05/CleanShot-2025-05-22-at-10.03.35@2x-820x1024.png 820w, https://www.finlab.tw/wp-content/uploads/2025/05/CleanShot-2025-05-22-at-10.03.35@2x-240x300.png 240w, https://www.finlab.tw/wp-content/uploads/2025/05/CleanShot-2025-05-22-at-10.03.35@2x-768x959.png 768w, https://www.finlab.tw/wp-content/uploads/2025/05/CleanShot-2025-05-22-at-10.03.35@2x-1229x1536.png 1229w, https://www.finlab.tw/wp-content/uploads/2025/05/CleanShot-2025-05-22-at-10.03.35@2x.png 1436w" sizes="(max-width: 820px) 100vw, 820px" title="復刻與優化 00900 ：使用 IC Decay 優化高股息策略成「長跑軍火庫」 7"><figcaption>封面圖片</figcaption></figure>



<h2>前言</h2>



<p>市場上的高股息 ETF 各有特色，這次將以富邦特選高股息30（00900）為例，分析其追蹤的「<strong>臺灣指數公司特選臺灣上市上櫃高股息30指數</strong>」。這檔ETF 的選股邏輯強調多次審核與財務、流動性標準，選擇高股息且具備穩定配息能力的個股。</p>



<h3>00900 特色整理</h3>



<blockquote class="wp-block-quote"><p>一年三次審核，嚴選 30 檔高息股；納入市值＋流動性＋營業利益安全閥。</p></blockquote>



<figure class="wp-block-table"><table><thead><tr><th>特色</th><th>說明</th><th>帶來的好處</th></tr></thead><tbody><tr><td><strong>三次定審（4 / 7 / 12 月）</strong></td><td>每次重新計算股利率</td><td>配息資訊更新更即時</td></tr><tr><td><strong>流動性硬指標</strong></td><td>近 3 個月日均成交金額前 90 %</td><td>降低買賣滑價</td></tr><tr><td><strong>營業利益必須為正</strong></td><td>最近四季 &gt; 0</td><td>過濾偽高息股</td></tr></tbody></table></figure>



<h2><strong>復刻 00900：研究流程全解析</strong></h2>



<h3><strong>資料來源與規則拆解</strong></h3>



<p>根據<a style="font-weight: bold;" href="https://etrade.fsit.com.tw/homelink/Prospectus/94.pdf" target="_blank" rel="noopener">公開說明書</a>，復刻「<strong>特選臺灣上市上櫃高股息30指數（00900）</strong>」的成分股篩選與調整流程，重點如下：</p>



<h3><strong><strong>初始採樣母體</strong></strong></h3>



<ul><li>臺灣上市與上櫃普通股股票為基礎。</li><li>選取發行市值前 200 大股票。</li></ul>



<h3><strong>流動性條件</strong></h3>



<ul><li>最近三個月日均成交金額排名前 90%者</li></ul>



<h3><strong>財務健全性與指標篩選</strong></h3>



<ul><li><strong>定期審核</strong>（四月、七月、十二月）：最近四季營業利益總和須為正</li></ul>



<h3><strong>股利率計算</strong></h3>



<ul><li><strong>四月定審（第一次）</strong><ul><li><strong>已公告現金股利者</strong>：股利率 = 最近四季現金股利總和 ÷ 審核資料截止日股價</li><li><strong>未公告現金股利者</strong>：股利率 = 最近四季 EPS 總和 × 過去三年平均現金股利發放率 ÷ 審核資料截止日股價</li></ul></li><li><strong>七月定審（第二次）</strong><ul><li>股利率 = 最近四季現金股利總和 ÷ 審核資料截止日股價</li></ul></li><li><strong>十二月定審（第三次）</strong><ul><li>股利率 = 最近四季 EPS 總和 × 過去三年平均現金股利發放率 ÷ 審核資料截止日股價</li></ul></li></ul>



<h3><strong>成分股數量</strong></h3>



<ul><li><strong>每次均固定 30 檔</strong></li></ul>



<h3><strong>指數調整與生效時點</strong></h3>



<ul><li><strong>每年三次定期審核</strong>：4月、7月、12月第7個交易日為基準日</li></ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h1>復刻結果</h1>



<p>在經過一連串比對後，復刻而得的策略股池與原版 00900 報酬率曲線有高度相關。這意味著，我們的 復刻版 00900 確實能有效重現 00900 的選股結果。</p>



<p><strong>相關性分析：</strong></p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" width="691" height="1024" src="https://www.finlab.tw/wp-content/uploads/2025/05/CleanShot-2025-05-22-at-11.25.29@2x-691x1024.png" alt="CleanShot 2025 05 22 at 11.25.29@2x" class="wp-image-6664" srcset="https://www.finlab.tw/wp-content/uploads/2025/05/CleanShot-2025-05-22-at-11.25.29@2x-691x1024.png 691w, https://www.finlab.tw/wp-content/uploads/2025/05/CleanShot-2025-05-22-at-11.25.29@2x-202x300.png 202w, https://www.finlab.tw/wp-content/uploads/2025/05/CleanShot-2025-05-22-at-11.25.29@2x.png 758w" sizes="(max-width: 691px) 100vw, 691px" title="復刻與優化 00900 ：使用 IC Decay 優化高股息策略成「長跑軍火庫」 8"><figcaption>相關性分析</figcaption></figure></div>


<p><strong>復刻 00900 報酬</strong>&nbsp;:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" width="1024" height="886" src="https://www.finlab.tw/wp-content/uploads/2025/05/CleanShot-2025-05-22-at-11.26.49@2x-1024x886.png" alt="CleanShot 2025 05 22 at 11.26.49@2x" class="wp-image-6666" srcset="https://www.finlab.tw/wp-content/uploads/2025/05/CleanShot-2025-05-22-at-11.26.49@2x-1024x886.png 1024w, https://www.finlab.tw/wp-content/uploads/2025/05/CleanShot-2025-05-22-at-11.26.49@2x-300x260.png 300w, https://www.finlab.tw/wp-content/uploads/2025/05/CleanShot-2025-05-22-at-11.26.49@2x-768x664.png 768w, https://www.finlab.tw/wp-content/uploads/2025/05/CleanShot-2025-05-22-at-11.26.49@2x-1536x1329.png 1536w, https://www.finlab.tw/wp-content/uploads/2025/05/CleanShot-2025-05-22-at-11.26.49@2x.png 1542w" sizes="(max-width: 1024px) 100vw, 1024px" title="復刻與優化 00900 ：使用 IC Decay 優化高股息策略成「長跑軍火庫」 9"><figcaption><strong>復刻 00900 報酬</strong></figcaption></figure></div>


<p>我們的「<strong>復刻版 00900</strong>」與官方版本高相關，證明邏輯拆解合理。</p>



<h2>進階優化</h2>



<h3>IC Decay：讓「好因子」真正常駐</h3>



<h4>什麼是IC Decay？為什麼分析IC Decay很重要？</h4>



<blockquote class="wp-block-quote"><p>想像一下：同一份藏寶圖，今天不只告訴你哪裡有金礦，還附上一張「礦脈多久才會枯竭」的熱力圖——這就是 IC Decay 帶來的視野。</p></blockquote>



<p>「IC」（Information Coefficient，資訊係數）是用來衡量一個因子對未來報酬預測力的重要指標，IC 高代表這個因子和未來報酬關聯性強。</p>



<p><strong>IC Decay</strong>，則是指「這個預測力會隨時間流逝而衰退嗎？衰退速度如何？」</p>



<p>簡單來說，我們不僅看因子對短期報酬有沒有預測力，也要觀察對長期如 60天、120天以後的報酬還有沒有預測力。</p>



<ul><li><strong>IC Decay 平緩：</strong> 這個因子在不同持有期間都有效，適合長線</li><li><strong>IC Decay 快：</strong> 因子適合短線，長線預測力不佳</li></ul>



<p><strong>應用在多因子策略：</strong></p>



<ul><li>幫助我們挑出「<strong>耐久型</strong>」的好因子</li><li>可以依照持股週期調整因子組合，強化策略穩定性</li></ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2>用 IC Decay 檢驗 00900 因子品質</h2>



<p>我們針對前述幾個因子，進行 IC Decay分析，步驟如下：</p>



<ol><li>計算各因子對不同持有期（如20天、60天、120天）的 IC</li><li>畫出IC Decay曲線，觀察哪些因子「<strong>報酬預測力持久</strong>」</li><li>排除短線效應太明顯、容易失效的因子</li></ol>



<figure class="wp-block-image size-full"><img loading="lazy" width="1000" height="800" src="https://www.finlab.tw/wp-content/uploads/2025/05/newplot.png" alt="newplot" class="wp-image-6625" srcset="https://www.finlab.tw/wp-content/uploads/2025/05/newplot.png 1000w, https://www.finlab.tw/wp-content/uploads/2025/05/newplot-300x240.png 300w, https://www.finlab.tw/wp-content/uploads/2025/05/newplot-768x614.png 768w" sizes="(max-width: 1000px) 100vw, 1000px" title="復刻與優化 00900 ：使用 IC Decay 優化高股息策略成「長跑軍火庫」 10"><figcaption>IC mean &amp;  ICIR Decay</figcaption></figure>



<h4><strong>重點解讀：</strong></h4>



<ul><li><strong>市值</strong>：IC IR 明顯是負值，且隨預測天數加長而下降，代表市值這個因子的預測不只失準，而且不穩定。</li><li><strong>七月股利率</strong>、<strong>十二月股利率</strong>：IC IR 明顯隨持有天數增加而上升（橘線到 1.5 以上），代表這兩個因子隨時間拉長後，預測力不只穩定，甚至更強。</li></ul>



<h2>多因子組合 IC Decay</h2>



<p>接下來，我們將這些因子進行整合，<strong>以組合分析的方式評估其綜合效果</strong>。</p>



<h4>分析 120 天預測期的前三名因子組合: </h4>



<ul><li><strong>七月股利率</strong></li><li><strong>七月股利率</strong> + <strong>十二月股利率 </strong></li><li><strong>四月股利率</strong> + <strong>七月股利率</strong></li></ul>



<figure class="wp-block-image size-full"><img loading="lazy" width="1000" height="800" src="https://www.finlab.tw/wp-content/uploads/2025/05/newplot2.png" alt="newplot2" class="wp-image-6627" srcset="https://www.finlab.tw/wp-content/uploads/2025/05/newplot2.png 1000w, https://www.finlab.tw/wp-content/uploads/2025/05/newplot2-300x240.png 300w, https://www.finlab.tw/wp-content/uploads/2025/05/newplot2-768x614.png 768w" sizes="(max-width: 1000px) 100vw, 1000px" title="復刻與優化 00900 ：使用 IC Decay 優化高股息策略成「長跑軍火庫」 11"><figcaption>120天預測期 &#8211; 最佳因子組合的IC和IC IR衰減分析</figcaption></figure>



<p><strong>綜合解讀 ：</strong></p>



<ul><li><strong>組合因子</strong>（如「<strong>七月股利率 + 十二月股利率</strong>」）能提供更高的平均預測能力 (IC Mean)。</li><li>單因子「<strong>七月股利率</strong>」或「<strong>七月股利率+十二月股利率</strong>」的組合，在預測的穩定性 (IC IR) 上可能更優，尤其是在較長的預測期。</li><li>整體來看，這些以股利率為基礎的因子組合在中長期（如 60 天至 200 天）展現出較好的預測潛力，並且其預測的穩定性隨時間增長。</li></ul>



<h4>分析最佳單一因子 IC Decay : 七月股利率 ,十二月股利率 </h4>



<figure class="wp-block-image size-full is-resized"><img loading="lazy" src="https://www.finlab.tw/wp-content/uploads/2025/05/newplot3.png" alt="newplot3" class="wp-image-6629" width="840" height="672" srcset="https://www.finlab.tw/wp-content/uploads/2025/05/newplot3.png 1000w, https://www.finlab.tw/wp-content/uploads/2025/05/newplot3-300x240.png 300w, https://www.finlab.tw/wp-content/uploads/2025/05/newplot3-768x614.png 768w" sizes="(max-width: 840px) 100vw, 840px" title="復刻與優化 00900 ：使用 IC Decay 優化高股息策略成「長跑軍火庫」 12"><figcaption>最佳單一因子 IC Decay</figcaption></figure>



<h4><br></h4>



<h3><strong>綜合解讀 ：</strong></h3>



<ul><li>在單因子比較中，「<strong>七月股利率</strong>」無論是在平均預測能力 (IC Mean) 還是預測穩定性 (IC IR) 上，都優於「<strong>十二月股利率</strong>」。</li><li>「<strong>七月股利率</strong>」的 IC IR 隨預測天數增加而上升的特性。</li></ul>



<h3><strong>總體結論：</strong></h3>



<ol><li><strong>「七月股利率」是核心強勢因子：</strong> 無論是作為單因子還是組合的一部分，「<strong>七月股利率</strong>」都表現出強勁的預測能力和非常好的穩定性（尤其是其 IC IR 持續上升）。</li><li><strong>因子組合的價值：</strong> 將不同月份的股利率因子進行組合，有潛力獲得比單一因子更高的 IC Mean，即更強的平均預測信號。</li><li><strong>IC Mean vs. IC IR 的考量：</strong><ul><li>「<strong>七月股利率 + 十二月股利率</strong>」組合擁有最高的 IC Mean，如果追求最強的平均預測信號，這是一個好選擇。</li><li>但若更看重預測的穩定性，「<strong>七月股利率</strong>」（單獨或與十二月股利率組合）則因其較高的 IC IR 而更具吸引力。這是策略構建中需要權衡的一點。</li></ul></li><li><strong>適用的預測週期：</strong> 這些因子/組合的 IC Mean 大多在約120天至160天達到高峰或保持強勢，而 IC IR 甚至在200天時仍在上升。這暗示它們更適合中長期的投資策略，而非短期的預測。IC Mean 初期（20天至~120天）的上升趨勢值得注意，可能表示因子效應的滯後性。</li><li><strong>潛力因子/組合：</strong> 「七月股利率 + 十二月股利率」因其高 IC Mean 顯示出很好的潛力。而「七月股利率」因子本身因其優異的 IC IR 表現，是構建因子模型時的重要候選。<br>另外也附上同<a href="https://www.finlab.tw/%e5%be%a9%e5%88%bb%e8%88%87%e5%84%aa%e5%8c%96-00919%ef%bc%9a%e7%8e%a9%e8%bd%89%e9%ab%98%e8%82%a1%e6%81%af-etf/">前一篇</a>的分析結果，整理出各預測週期內，因子在前10名組合中的出現頻率，以及120天預測期下，不同因子數量與 ICIR 的關係，並列出120天預測期的前10組最佳因子組合。</li></ol>



<figure class="wp-block-image size-full"><img loading="lazy" width="1000" height="500" src="https://www.finlab.tw/wp-content/uploads/2025/05/newplot-1.png" alt="newplot 1" class="wp-image-6631" srcset="https://www.finlab.tw/wp-content/uploads/2025/05/newplot-1.png 1000w, https://www.finlab.tw/wp-content/uploads/2025/05/newplot-1-300x150.png 300w, https://www.finlab.tw/wp-content/uploads/2025/05/newplot-1-768x384.png 768w" sizes="(max-width: 1000px) 100vw, 1000px" title="復刻與優化 00900 ：使用 IC Decay 優化高股息策略成「長跑軍火庫」 13"><figcaption>各預測週期中因子在前10名組合中的出現頻率</figcaption></figure>



<figure class="wp-block-image size-full"><img loading="lazy" width="800" height="600" src="https://www.finlab.tw/wp-content/uploads/2025/05/newplot2-2.png" alt="newplot2 2" class="wp-image-6635" srcset="https://www.finlab.tw/wp-content/uploads/2025/05/newplot2-2.png 800w, https://www.finlab.tw/wp-content/uploads/2025/05/newplot2-2-300x225.png 300w, https://www.finlab.tw/wp-content/uploads/2025/05/newplot2-2-768x576.png 768w" sizes="(max-width: 800px) 100vw, 800px" title="復刻與優化 00900 ：使用 IC Decay 優化高股息策略成「長跑軍火庫」 14"><figcaption>120天預測期 – 因子數量與ICIR關係</figcaption></figure>



<figure class="wp-block-image size-full"><img loading="lazy" width="900" height="600" src="https://www.finlab.tw/wp-content/uploads/2025/05/newplot3-3.png" alt="newplot3 3" class="wp-image-6636" srcset="https://www.finlab.tw/wp-content/uploads/2025/05/newplot3-3.png 900w, https://www.finlab.tw/wp-content/uploads/2025/05/newplot3-3-300x200.png 300w, https://www.finlab.tw/wp-content/uploads/2025/05/newplot3-3-768x512.png 768w" sizes="(max-width: 900px) 100vw, 900px" title="復刻與優化 00900 ：使用 IC Decay 優化高股息策略成「長跑軍火庫」 15"><figcaption>120 天預測期 – 前10個最佳因子組合</figcaption></figure>



<h2>優化後的成績單</h2>



<p>最後我們使用表現較好的 <strong>七月股利率 + 十二月股利率</strong> <strong>+  yield_ratio</strong> 組合進行優化，可以發現績效、夏普值、最大回檔都有更好的結果。</p>



<p><strong>獲利能力分析：</strong></p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" width="1024" height="943" src="https://www.finlab.tw/wp-content/uploads/2025/05/CleanShot-2025-05-22-at-11.33.06@2x-1024x943.png" alt="CleanShot 2025 05 22 at 11.33.06@2x" class="wp-image-6667" srcset="https://www.finlab.tw/wp-content/uploads/2025/05/CleanShot-2025-05-22-at-11.33.06@2x-1024x943.png 1024w, https://www.finlab.tw/wp-content/uploads/2025/05/CleanShot-2025-05-22-at-11.33.06@2x-300x276.png 300w, https://www.finlab.tw/wp-content/uploads/2025/05/CleanShot-2025-05-22-at-11.33.06@2x-768x707.png 768w, https://www.finlab.tw/wp-content/uploads/2025/05/CleanShot-2025-05-22-at-11.33.06@2x-1536x1414.png 1536w, https://www.finlab.tw/wp-content/uploads/2025/05/CleanShot-2025-05-22-at-11.33.06@2x.png 1540w" sizes="(max-width: 1024px) 100vw, 1024px" title="復刻與優化 00900 ：使用 IC Decay 優化高股息策略成「長跑軍火庫」 16"><figcaption>獲利能力分析</figcaption></figure></div>


<p><strong>抗風險能力分析：</strong></p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" width="1024" height="853" src="https://www.finlab.tw/wp-content/uploads/2025/05/CleanShot-2025-05-22-at-11.33.36@2x-1024x853.png" alt="CleanShot 2025 05 22 at 11.33.36@2x" class="wp-image-6668" srcset="https://www.finlab.tw/wp-content/uploads/2025/05/CleanShot-2025-05-22-at-11.33.36@2x-1024x853.png 1024w, https://www.finlab.tw/wp-content/uploads/2025/05/CleanShot-2025-05-22-at-11.33.36@2x-300x250.png 300w, https://www.finlab.tw/wp-content/uploads/2025/05/CleanShot-2025-05-22-at-11.33.36@2x-768x640.png 768w, https://www.finlab.tw/wp-content/uploads/2025/05/CleanShot-2025-05-22-at-11.33.36@2x-1536x1279.png 1536w, https://www.finlab.tw/wp-content/uploads/2025/05/CleanShot-2025-05-22-at-11.33.36@2x.png 1544w" sizes="(max-width: 1024px) 100vw, 1024px" title="復刻與優化 00900 ：使用 IC Decay 優化高股息策略成「長跑軍火庫」 17"><figcaption><strong>抗風險能力分析</strong></figcaption></figure></div>


<p><strong>風險報酬分析：</strong></p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" width="1024" height="353" src="https://www.finlab.tw/wp-content/uploads/2025/05/CleanShot-2025-05-22-at-11.34.34@2x-1024x353.png" alt="CleanShot 2025 05 22 at 11.34.34@2x" class="wp-image-6669" srcset="https://www.finlab.tw/wp-content/uploads/2025/05/CleanShot-2025-05-22-at-11.34.34@2x-1024x353.png 1024w, https://www.finlab.tw/wp-content/uploads/2025/05/CleanShot-2025-05-22-at-11.34.34@2x-300x104.png 300w, https://www.finlab.tw/wp-content/uploads/2025/05/CleanShot-2025-05-22-at-11.34.34@2x-768x265.png 768w, https://www.finlab.tw/wp-content/uploads/2025/05/CleanShot-2025-05-22-at-11.34.34@2x.png 1530w" sizes="(max-width: 1024px) 100vw, 1024px" title="復刻與優化 00900 ：使用 IC Decay 優化高股息策略成「長跑軍火庫」 18"><figcaption><strong>風險報酬分析</strong></figcaption></figure></div>


<p><strong>勝率期望值分析：</strong></p>



<figure class="wp-block-image size-large"><img loading="lazy" width="968" height="1024" src="https://www.finlab.tw/wp-content/uploads/2025/05/CleanShot-2025-05-22-at-11.35.06@2x-968x1024.png" alt="CleanShot 2025 05 22 at 11.35.06@2x" class="wp-image-6670" srcset="https://www.finlab.tw/wp-content/uploads/2025/05/CleanShot-2025-05-22-at-11.35.06@2x-968x1024.png 968w, https://www.finlab.tw/wp-content/uploads/2025/05/CleanShot-2025-05-22-at-11.35.06@2x-283x300.png 283w, https://www.finlab.tw/wp-content/uploads/2025/05/CleanShot-2025-05-22-at-11.35.06@2x-768x813.png 768w, https://www.finlab.tw/wp-content/uploads/2025/05/CleanShot-2025-05-22-at-11.35.06@2x-1451x1536.png 1451w, https://www.finlab.tw/wp-content/uploads/2025/05/CleanShot-2025-05-22-at-11.35.06@2x.png 1544w" sizes="(max-width: 968px) 100vw, 968px" title="復刻與優化 00900 ：使用 IC Decay 優化高股息策略成「長跑軍火庫」 19"><figcaption><strong>勝率期望值分析</strong></figcaption></figure>



<h2>結論</h2>



<p><strong>00900 高股息ETF</strong>的選股規則已經相當嚴謹，但我們透過 <strong>IC Decay 分析</strong>，能夠再進一步挑選出「<strong>預測力持久</strong>」的黃金因子組合，打造更穩健、具備長期優勢的量化策略。未來也能持續利用 <strong>IC Decay</strong>動態追蹤因子表現，讓自己的策略不斷升級，也歡迎參考&nbsp;<a href="https://colab.research.google.com/drive/1rw86fwPLxq-nAPN-YCHABDpRaJ7lXCJU?usp=sharing" data-type="URL" data-id="https://colab.research.google.com/drive/1rw86fwPLxq-nAPN-YCHABDpRaJ7lXCJU?usp=sharing" target="_blank" rel="noopener">Colab 範例檔</a>。</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/%e5%be%a9%e5%88%bb%e8%88%87%e5%84%aa%e5%8c%96-00900-%ef%bc%9a%e4%bd%bf%e7%94%a8-ic-decay-%e5%84%aa%e5%8c%96%e9%ab%98%e8%82%a1%e6%81%af%e7%ad%96%e7%95%a5%e6%88%90%e3%80%8c%e9%95%b7%e8%b7%91%e8%bb%8d/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">6620</post-id>	</item>
		<item>
		<title>復刻與優化 00919：玩轉高股息 ETF</title>
		<link>https://www.finlab.tw/%e5%be%a9%e5%88%bb%e8%88%87%e5%84%aa%e5%8c%96-00919%ef%bc%9a%e7%8e%a9%e8%bd%89%e9%ab%98%e8%82%a1%e6%81%af-etf/</link>
					<comments>https://www.finlab.tw/%e5%be%a9%e5%88%bb%e8%88%87%e5%84%aa%e5%8c%96-00919%ef%bc%9a%e7%8e%a9%e8%bd%89%e9%ab%98%e8%82%a1%e6%81%af-etf/#respond</comments>
		
		<dc:creator><![CDATA[Andy]]></dc:creator>
		<pubDate>Tue, 06 May 2025 08:08:01 +0000</pubDate>
				<category><![CDATA[VIP文章]]></category>
		<category><![CDATA[FinLab 量化平台]]></category>
		<category><![CDATA[Python新手教學]]></category>
		<category><![CDATA[基本面分析]]></category>
		<category><![CDATA[投資新手]]></category>
		<category><![CDATA[股票策略]]></category>
		<category><![CDATA[財經PYTHON教學]]></category>
		<category><![CDATA[選股策略]]></category>
		<category><![CDATA[PYTHON]]></category>
		<category><![CDATA[VIP限定]]></category>
		<category><![CDATA[程式交易]]></category>
		<category><![CDATA[股票]]></category>
		<category><![CDATA[量化投資]]></category>
		<guid isPermaLink="false">https://www.finlab.tw/?p=6561</guid>

					<description><![CDATA[前言 市面上的高股息 ETF 百花齊放，這次要來復刻 00919 群益台灣精選高息 ETF，如果 0056 是 [&#8230;]]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-image size-large"><img loading="lazy" width="683" height="1024" src="https://www.finlab.tw/wp-content/uploads/2025/04/ChatGPT-Image-2025年4月20日-下午01_52_50-1-683x1024.png" alt="ChatGPT Image 2025年4月20日 下午01 52 50 1" class="wp-image-6596" srcset="https://www.finlab.tw/wp-content/uploads/2025/04/ChatGPT-Image-2025年4月20日-下午01_52_50-1-683x1024.png 683w, https://www.finlab.tw/wp-content/uploads/2025/04/ChatGPT-Image-2025年4月20日-下午01_52_50-1-200x300.png 200w, https://www.finlab.tw/wp-content/uploads/2025/04/ChatGPT-Image-2025年4月20日-下午01_52_50-1-768x1152.png 768w, https://www.finlab.tw/wp-content/uploads/2025/04/ChatGPT-Image-2025年4月20日-下午01_52_50-1.png 1024w" sizes="(max-width: 683px) 100vw, 683px" title="復刻與優化 00919：玩轉高股息 ETF 20"><figcaption>封面圖片</figcaption></figure>



<h2>前言</h2>



<p>市面上的高股息 ETF 百花齊放，這次要來復刻 <strong>00919</strong> <strong>群益台灣精選高息 ETF，</strong>如果 <strong>0056</strong> 是台股存股族的啟蒙，<strong>00919 </strong> 就像下一代改裝版。它主打「<strong>精準高息、精準卡位、精準領息</strong>」三大賣點，看似簡單，其實暗藏許多量化細節。本文帶你：</p>



<ol><li><strong>完整拆解官方邏輯</strong>，一步步復刻 00919 的選股流程。</li><li><strong>用量化工具驗證</strong>：驗證相關性和重疊率。</li><li><strong>再往前優化</strong>：刪掉雜訊因子、加入高效指標，打造報酬更高、回撤更低的 <strong>00919 優化版</strong>。</li></ol>



<h2>一、00919 三大「精準」拆解</h2>



<p>查看<a href="https://www.capitalfund.com.tw/etf/product/detail/195/basic" data-type="URL" data-id="https://www.capitalfund.com.tw/etf/product/detail/195/basic" target="_blank" rel="noopener">基金介紹</a>發現有幾個特色</p>



<ul><li><strong>精準高息：用「實際宣告」取代「預估數字」</strong></li></ul>



<p>00919 選擇鎖定「<strong>已公告現金股利</strong>」的企業，<strong>從確定的金額計算真實殖利率</strong>，進一步提升股息來源的可靠度與穩定性。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<ul><li><strong> 精準卡位：提前布局的策略優勢</strong></li></ul>



<p>00919 採雙階段審核機制，五月、十二月<strong>雙審核</strong>，透過這種<strong>快與早並重</strong>的選股機制，達到真正「買在除息前」與「走在市場前」的投資節奏。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<ul><li><strong>精準領息：每一分股息都不浪費</strong></li></ul>



<p>選股時機對應企業除息時程，投資人持有期間能真正參與除息、獲取現金配息，<strong>讓每一分錢都落袋為安</strong>。</p>



<blockquote class="wp-block-quote"><p><strong>名詞解釋 &#8211; 殖利率</strong>：每股現金股利 ÷ 股價。殖利率越高，代表用相對便宜的股價就能拿到較高現金回報。</p></blockquote>



<h2>二、復刻 00919：研究流程</h2>



<ol><li><strong>資料擷取</strong><ul><li>00919 <a href="https://www.capitalfund.com.tw/ECStorge/fund/ec/event/00919Prospectus/Prospectus.pdf" data-type="URL" data-id="https://www.capitalfund.com.tw/ECStorge/fund/ec/event/00919Prospectus/Prospectus.pdf" target="_blank" rel="noopener">公開說明書</a></li></ul></li><li><strong>邏輯拆解</strong><ul><li>採樣母體 → 流動性 / 財務健全性 → 股利資訊 → 排序 → 替換規則。</li></ul></li></ol>



<h2>三、復刻 00919 的關鍵步驟</h2>



<ol><li><strong>初始採樣母體</strong>：<ul><li>臺灣上市與上櫃普通股股票為基礎。</li></ul><ul><li>選取發行市值前 300 大股票。</li></ul></li><li><strong>基本條件篩選</strong>：<ul><li>日平均成交金額需高於 8,000 萬元。</li><li>近四季稅後股東權益報酬率 (ROE) 皆為正數。</li></ul></li><li><strong>股利資訊篩選（五月定審限定）</strong>：<ul><li>排除董事會尚未決定股利金額的公司。</li><li>排除已除息且於審核生效日前已完成發放的股票。</li></ul></li><li><strong>排序並選取成分股</strong>：<ul><li><strong>五月定審</strong>：依近四季股利率排序，選出前 30 檔。</li><li><strong>十二月定審</strong>：依據預估股利率排序，選出前 30 檔。</li></ul></li></ol>



<pre class="wp-block-code"><code lang="python" class="language-python">def calculate_ranks(date, is_may_review=True):
    """計算特定審核日期的股票排名"""
    nearest_date = get_nearest_past_trading_date(date, all_trading_dates)
    if nearest_date is None:
        return pd.Series(dtype=float)  # 空序列
        
    if is_may_review:  # 5月定審
        # 計算排名 - 5月定審使用股利率
        score = (市值.rank(axis=1, pct=True) + 股利率.rank(axis=1, pct=True) + yield_ratio.rank(axis=1, pct=True))[conds &amp; (board_cash_dividend &gt; 0)]
    else:  # 12月定審
        # 計算排名 - 12月定審使用預估股利率
        score = (市值.rank(axis=1, pct=True) + 預估股利率.rank(axis=1, pct=True) + yield_ratio.rank(axis=1, pct=True))[conds]
        
    if nearest_date not in score.index:
        return pd.Series(dtype=float)  # 空序列
        
    return score.loc[nearest_date].dropna().rank(ascending=False, method='min')</code></pre>



<ol><li><strong>成分股替換規則</strong>：<ul><li>排名前 15 名直接納入成分股。</li><li>既有成分股若跌出 46 名以外則剔除。</li><li>排名 16 至 45 名的股票列為候補，優先保留既有成分股。</li><li>十二月定審單次最多更替 8 檔股票。</li></ul></li></ol>



<pre class="wp-block-code"><code lang="python" class="language-python"># 建立空的結果DataFrame
position = pd.DataFrame(False, index=effective_dates, columns=close.columns)

# 處理所有調倉日期和排名數據
all_ranks = {}
valid_dates = []

for date in effective_dates:
    try:
        is_may_review = (date.month == 5)
        ranks = calculate_ranks(date, is_may_review)
        if not ranks.empty:
            all_ranks[date] = ranks
            valid_dates.append(date)
    except Exception as e:
        print(f"處理 {date} 時發生錯誤: {e}")

valid_dates = sorted(valid_dates)  # 確保日期順序

if not valid_dates:
    print("沒有有效的調倉日期，無法進行模擬")
else:
# 使用 Pandas 向量化處理成分股替換
    prev_components = None
    target_component_count = 30 # 設定目標成分股數量

    for i, date in enumerate(valid_dates):
                ranks = all_ranks[date]

                # 1. 排名在第15名以內者納入成分股
                top_15 = set(ranks[ranks &lt;= 15].index)

                # 2. 排名16至45名為候補名單
                candidates = set(ranks[(ranks &gt; 15) &amp; (ranks &lt;= 45)].index)

                # 暫定的成分股 (先加入前15名)
                current_components_tentative = set(top_15)

                # 如果不是第一次調倉
                if prev_components is not None:
                        # 加入排名16-45之間的既有成分股
                        existing_in_candidates = prev_components.intersection(candidates)
                        current_components_tentative.update(existing_in_candidates)

                        # 對於12月定審，額外限制最多替換8檔
                        if date.month == 12:
                                # 計算基於 Top15 + 既有候補 所得的新增股票
                                added = current_components_tentative - prev_components

                                # 如果新增超過8檔，需要減少替換數量
                                if len(added) &gt; 8:
                                        # 取出新增的股票並按排名排序 (rank越小越好)
                                        added_with_rank = pd.Series({stock: ranks.get(stock, float('inf')) for stock in added})
                                        # 只保留排名最好的前8名新增的股票
                                        to_keep = set(added_with_rank.sort_values().index[:8])
                                        to_remove_due_to_limit = added - to_keep

                                        # 從暫定名單中移除因超過8檔限制而被剔除的股票
                                        current_components_tentative = current_components_tentative - to_remove_due_to_limit

                # --- 補滿至目標數量 ---
                num_needed = target_component_count - len(current_components_tentative)
                if num_needed &gt; 0:
                        # 找出所有排名16-45，但尚未被選入的股票
                        remaining_candidates = candidates - current_components_tentative
                        if remaining_candidates: # 確保還有候選股可補
                                # 依排名排序這些候選股
                                remaining_candidates_with_rank = pd.Series({stock: ranks.get(stock, float('inf')) for stock in remaining_candidates})
                                sorted_remaining_candidates = remaining_candidates_with_rank.sort_values().index

                                # 選取排名最好的 num_needed 檔來補滿
                                stocks_to_add = set(sorted_remaining_candidates[:num_needed])
                                current_components_tentative.update(stocks_to_add)
                # --- 補滿邏輯結束 ---

                # 最終確認的成分股
                current_components = current_components_tentative

                # 設定成分股
                # 確保只設定存在的欄位
                valid_cols = [col for col in current_components if col in position.columns]
                position.loc[date, valid_cols] = True

                # 更新前一期成分股
                prev_components = current_components

    # 5. 前向填充空值，確保非調倉日也有持股
    position = position.loc[valid_dates]</code></pre>



<ol><li><strong>生效日期計算</strong>：<ul><li>審核基準日後第 5 個交易日正式生效。</li></ul></li></ol>



<pre class="wp-block-code"><code lang="python" class="language-python">def calculate_review_dates(trading_dates: pd.DatetimeIndex):
    """
    計算台灣高股息指數的審核與調倉日期
    
    台灣高股息指數規則:
    - 5月: 第17個交易日為審核基準日，審核資料截至5月第10個交易日
    - 12月: 第7個交易日為審核基準日，審核資料截至11月最後交易日
    - 生效日: 審核基準日後第5個交易日
    """
    review_dates_info = []
    start_year = trading_dates[0].year
    end_year = trading_dates[-1].year

    for year in range(start_year, end_year + 1):
        # 5月定審
        may_review_basis_day = get_trading_day_of_month(year, 5, 17, trading_dates)
        may_data_cutoff_day = get_trading_day_of_month(year, 5, 10, trading_dates)
        
        if may_review_basis_day and may_data_cutoff_day:
            target_effective_day_index = trading_dates.searchsorted(may_review_basis_day) + 5
            if target_effective_day_index &lt; len(trading_dates):
                may_effective_day_target = trading_dates[target_effective_day_index]
                may_effective_day = get_nearest_future_trading_date(may_effective_day_target, trading_dates)
                if may_effective_day:
                    review_dates_info.append({
                        'year': year, 
                        'month': 5,
                        'cutoff_date': may_data_cutoff_day,
                        'basis_date': may_review_basis_day,
                        'effective_date': may_effective_day
                    })

        # 12月定審
        dec_review_basis_day = get_trading_day_of_month(year, 12, 7, trading_dates)
        nov_data_cutoff_day = get_last_trading_day_of_month(year, 11, trading_dates)
        
        if dec_review_basis_day and nov_data_cutoff_day:
            target_effective_day_index = trading_dates.searchsorted(dec_review_basis_day) + 5
            if target_effective_day_index &lt; len(trading_dates):
                dec_effective_day_target = trading_dates[target_effective_day_index]
                dec_effective_day = get_nearest_future_trading_date(dec_effective_day_target, trading_dates)
                if dec_effective_day:
                    review_dates_info.append({
                        'year': year, 
                        'month': 12,
                        'cutoff_date': nov_data_cutoff_day,
                        'basis_date': dec_review_basis_day,
                        'effective_date': dec_effective_day
                    })

    # 按生效日期排序
    review_dates_info = sorted(review_dates_info, key=lambda x: x['effective_date'])
    # 移除無效日期
    review_dates_info = [info for info in review_dates_info if info['effective_date'] is not None]
    
    if not review_dates_info:
        raise ValueError("無法計算出任何有效的審核與生效日期，請檢查日期計算邏輯或資料範圍。")
    
    return review_dates_info</code></pre>



<h2>四、復刻結果</h2>



<p><br>在經過一連串比對後，復刻而得的策略股池與原版 00919 報酬率曲線有高度相關。這意味著，我們的 復刻版 00919 確實能有效重現 00919 的選股結果。</p>



<p><strong>相關性分析：</strong></p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" width="382" height="549" src="https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-11.48.55.png" alt="CleanShot 2025 04 20 at 11.48.55" class="wp-image-6566" srcset="https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-11.48.55.png 382w, https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-11.48.55-209x300.png 209w" sizes="(max-width: 382px) 100vw, 382px" title="復刻與優化 00919：玩轉高股息 ETF 21"><figcaption>相關性分析</figcaption></figure></div>


<p><strong>復刻 00919 報酬</strong> : </p>



<figure class="wp-block-image size-full"><img loading="lazy" width="761" height="599" src="https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-11.59.52.png" alt="CleanShot 2025 04 20 at 11.59.52" class="wp-image-6568" srcset="https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-11.59.52.png 761w, https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-11.59.52-300x236.png 300w" sizes="(max-width: 761px) 100vw, 761px" title="復刻與優化 00919：玩轉高股息 ETF 22"><figcaption><strong>復刻 00919 報酬</strong></figcaption></figure>



<p><strong>長期持有 00919&nbsp;報酬</strong> :</p>



<figure class="wp-block-image size-full"><img loading="lazy" width="770" height="772" src="https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-12.01.12.png" alt="CleanShot 2025 04 20 at 12.01.12" class="wp-image-6569" srcset="https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-12.01.12.png 770w, https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-12.01.12-300x300.png 300w, https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-12.01.12-150x150.png 150w, https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-12.01.12-768x770.png 768w" sizes="(max-width: 770px) 100vw, 770px" title="復刻與優化 00919：玩轉高股息 ETF 23"><figcaption><strong>長期持有 00919&nbsp;報酬</strong></figcaption></figure>



<p>我們的「<strong>復刻版 00919</strong>」與官方版本高相關，證明邏輯拆解合理。</p>



<h2>五、進階優化：</h2>



<p>雖然我們已成功復刻 00919 的選股邏輯，但這僅是起點。在接下來的優化階段，我們希望<strong>進一步提升策略效率與穩定性</strong>。因此，我們先行<strong>剔除效度不高的條件，以降低雜訊與過度擬合（overfitting）的風險</strong>，同時<strong>納入經過 IC/IR 驗證、具高預測力的關鍵因子</strong>，讓策略在維持高息特性的同時，具備更好的長期報酬潛力。</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" width="662" height="480" src="https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-12.04.40@2x.png" alt="CleanShot 2025 04 20 at" class="wp-image-6570" srcset="https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-12.04.40@2x.png 662w, https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-12.04.40@2x-300x218.png 300w" sizes="(max-width: 662px) 100vw, 662px" title="復刻與優化 00919：玩轉高股息 ETF 24"><figcaption>IC / IR 分析</figcaption></figure></div>


<p><strong>IC/IR</strong> 指標告訴我們，有些條件不但沒幫忙，還在拖後腿，列如：</p>



<ul><li>市值條件 IC 為 <strong>負值</strong></li><li>流動性條件 IC 也是 <strong>負值</strong></li></ul>



<blockquote class="wp-block-quote"><p><strong>名詞小辭典 </strong>&#8211; <strong>IC / IR</strong> <br>• <strong>IC</strong>（Information Coefficient）：因子對未來報酬的預測能力，&gt;0 正向、&lt;0 反向。 <br>• <strong>IR</strong>（Information Ratio）：IC 均值 ÷ IC 標準差，衡量穩定度，&gt;1 代表因子「又準又穩」。</p></blockquote>



<p></p>



<p>當我們發現市值與流動性條件的 IC 為負時，決定剔除。這樣的做法其實也呼應了我們作為一般投資人的一項優勢，<strong>不像 ETF 必須考量大規模資金進出時的流動性風險</strong>，我們可以更靈活地聚焦在報酬潛力本身，因此不再納入這些與 ETF 結構相關的限制性條件，也是合理的選擇。</p>



<p>接下來，我們回頭檢視先前 <a href="https://www.finlab.tw/%e5%a6%82%e4%bd%95%e5%be%a9%e5%88%bb0056%e9%ab%98%e8%82%a1%e6%81%afetf%ef%bc%8c%e4%b8%a6%e6%89%93%e9%80%a0%e8%b6%85%e8%b6%8a%e5%b8%82%e5%a0%b4%e7%9a%84%e9%80%b2%e9%9a%8e%e7%ad%96%e7%95%a5%ef%bc%81/">先前文章</a>， 「復刻 0056 ETF」文章中表現優異的因子，將這些經驗延伸應用到本次策略中。透過重新分析其 IC 與 IR 指標，我們挑選出具有預測力的關鍵因子，<strong>將其納入排序邏輯中與原有條件結合</strong>。</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" width="838" height="1024" src="https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.08.07@2x-838x1024.png" alt="CleanShot 2025 04 20 at 13.08.07@2x" class="wp-image-6572" srcset="https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.08.07@2x-838x1024.png 838w, https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.08.07@2x-246x300.png 246w, https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.08.07@2x-768x938.png 768w, https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.08.07@2x.png 866w" sizes="(max-width: 838px) 100vw, 838px" title="復刻與優化 00919：玩轉高股息 ETF 25"><figcaption>因子 IC IR 分析</figcaption></figure></div>


<p>可以發現，<strong>股利率、預估股利率、cash_dividend_annual 以及 ROE</strong> 都展現出良好的表現，屬於具有預測力的優質因子。</p>



<p>接下來，我們將這些表現突出的因子進行整合，<strong>以組合分析的方式評估其綜合效果</strong>，並驗證是否能進一步提升選股策略的穩定性與報酬潛力。</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="498" src="https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.13.50@2x-1024x498.png" alt="CleanShot 2025 04 20 at 13.13.50@2x" class="wp-image-6577" srcset="https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.13.50@2x-1024x498.png 1024w, https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.13.50@2x-300x146.png 300w, https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.13.50@2x-768x374.png 768w, https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.13.50@2x-1536x747.png 1536w, https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.13.50@2x.png 1982w" sizes="(max-width: 1024px) 100vw, 1024px" title="復刻與優化 00919：玩轉高股息 ETF 26"><figcaption>各預測週期中因子在前10名組合中的出現頻率</figcaption></figure>



<figure class="wp-block-image size-large is-resized"><img loading="lazy" src="https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.12.34@2x-1024x763.png" alt="CleanShot 2025 04 20 at 13.12.34@2x" class="wp-image-6573" width="840" height="625" srcset="https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.12.34@2x-1024x763.png 1024w, https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.12.34@2x-300x224.png 300w, https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.12.34@2x-1536x1145.png 1536w, https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.12.34@2x.png 1540w" sizes="(max-width: 840px) 100vw, 840px" title="復刻與優化 00919：玩轉高股息 ETF 27"><figcaption>60天預測期 &#8211; 因子數量與ICIR關係</figcaption></figure>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="760" src="https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.13.02@2x-1024x760.png" alt="CleanShot 2025 04 20 at 13.13.02@2x" class="wp-image-6574" srcset="https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.13.02@2x-1024x760.png 1024w, https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.13.02@2x-300x223.png 300w, https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.13.02@2x-768x570.png 768w, https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.13.02@2x.png 1520w" sizes="(max-width: 1024px) 100vw, 1024px" title="復刻與優化 00919：玩轉高股息 ETF 28"><figcaption>120天預測期 &#8211; 因子數量與ICIR關係</figcaption></figure>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="679" src="https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.13.22@2x-1024x679.png" alt="CleanShot 2025 04 20 at 13.13.22@2x" class="wp-image-6575" srcset="https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.13.22@2x-1024x679.png 1024w, https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.13.22@2x-300x199.png 300w, https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.13.22@2x-768x509.png 768w, https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.13.22@2x-1536x1018.png 1536w, https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.13.22@2x.png 1780w" sizes="(max-width: 1024px) 100vw, 1024px" title="復刻與優化 00919：玩轉高股息 ETF 29"><figcaption>60 天預測期 &#8211; 前10個最佳因子組合</figcaption></figure>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="677" src="https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.13.34@2x-1024x677.png" alt="CleanShot 2025 04 20 at 13.13.34@2x" class="wp-image-6576" srcset="https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.13.34@2x-1024x677.png 1024w, https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.13.34@2x-300x198.png 300w, https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.13.34@2x-768x508.png 768w, https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.13.34@2x-1536x1015.png 1536w, https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.13.34@2x.png 1782w" sizes="(max-width: 1024px) 100vw, 1024px" title="復刻與優化 00919：玩轉高股息 ETF 30"><figcaption>120 天預測期 &#8211; 前10個最佳因子組合</figcaption></figure>



<p>可以發現，無論是在 60 天或 120 天的時間尺度下，<strong>ROE 與年化股息率的組合表現穩定且亮眼</strong>。因此我們將這組優勢因子正式納入五月與十二月的選股排序邏輯中。接著，我們<strong>進一步精簡成分股數量，並取消複雜的替換規則</strong>，打造出更簡潔、集中、操作效率更高的「終極策略版本」。這樣的設計，能兼顧高勝率與操作彈性，真正貼近一般投資人的實戰需求。</p>



<h2><br>六、優化後的成績單</h2>



<ol><li><strong>年化報酬率：</strong>&nbsp;提高至約&nbsp;<strong>47%</strong>，相較於原版明顯領先。</li><li><strong>夏普比率：</strong>&nbsp;從遠本的 <strong>1.16 </strong>提高至約&nbsp;<strong>1.83</strong>，相較於原版明顯領先。</li></ol>



<p>更難能可貴的是在差不多的最大下跌風險下，提高報酬率和穩定性，不必日日擔心股價大幅震盪。如此一來，投資人就能同時享有領股利的安心感，又能捕捉股價成長的爆發力。<br><strong>獲利能力分析：</strong></p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" width="1024" height="930" src="https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.24.40@2x-1024x930.png" alt="CleanShot 2025 04 20 at 13.24.40@2x" class="wp-image-6579" srcset="https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.24.40@2x-1024x930.png 1024w, https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.24.40@2x-300x273.png 300w, https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.24.40@2x-768x698.png 768w, https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.24.40@2x-1536x1395.png 1536w, https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.24.40@2x.png 1550w" sizes="(max-width: 1024px) 100vw, 1024px" title="復刻與優化 00919：玩轉高股息 ETF 31"><figcaption>獲利能力分析</figcaption></figure></div>


<p><strong>抗風險能力分析：</strong></p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" width="1024" height="942" src="https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.25.36@2x-1024x942.png" alt="CleanShot 2025 04 20 at 13.25.36@2x" class="wp-image-6580" srcset="https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.25.36@2x-1024x942.png 1024w, https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.25.36@2x-300x276.png 300w, https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.25.36@2x-768x707.png 768w, https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.25.36@2x-1536x1413.png 1536w, https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.25.36@2x.png 1552w" sizes="(max-width: 1024px) 100vw, 1024px" title="復刻與優化 00919：玩轉高股息 ETF 32"><figcaption><strong>抗風險能力分析</strong></figcaption></figure></div>


<p><strong>風險報酬分析：</strong></p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="347" src="https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.26.13@2x-1024x347.png" alt="CleanShot 2025 04 20 at 13.26.13@2x" class="wp-image-6581" srcset="https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.26.13@2x-1024x347.png 1024w, https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.26.13@2x-300x102.png 300w, https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.26.13@2x-768x260.png 768w, https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.26.13@2x.png 1534w" sizes="(max-width: 1024px) 100vw, 1024px" title="復刻與優化 00919：玩轉高股息 ETF 33"><figcaption><strong>風險報酬分析</strong></figcaption></figure>



<p><strong>勝率期望值分析：</strong></p>



<figure class="wp-block-image size-large"><img loading="lazy" width="960" height="1024" src="https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.26.40@2x-960x1024.png" alt="CleanShot 2025 04 20 at 13.26.40@2x" class="wp-image-6582" srcset="https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.26.40@2x-960x1024.png 960w, https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.26.40@2x-281x300.png 281w, https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.26.40@2x-768x819.png 768w, https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.26.40@2x-1440x1536.png 1440w, https://www.finlab.tw/wp-content/uploads/2025/04/CleanShot-2025-04-20-at-13.26.40@2x.png 1522w" sizes="(max-width: 960px) 100vw, 960px" title="復刻與優化 00919：玩轉高股息 ETF 34"><figcaption><strong>勝率期望值分析</strong></figcaption></figure>



<p>在不犧牲「領息」特色的前提下，<strong>獲利更高、風險更低</strong>。</p>



<h2>七、行動建議</h2>



<ol><li><strong>進階派</strong>：跟著本文邏輯，自行用FinLab 復刻並優化。</li><li><strong>客製派</strong>：把優化後因子丟進量化平台，持續調參，打造專屬高息策略。</li></ol>



<blockquote class="wp-block-quote"><p>風險提醒：高息 ≠ 無風險。股息遞延、宏觀逆風都可能影響績效。請按自身資金配置與風險承受度操作。</p></blockquote>



<h2>結語：高息，也可以很聰明</h2>



<p>復刻只是起點，希望這篇文章能點燃你的研究慾望，讓「領息」不再只是被動等待，而成為可以精雕細琢、持續進化的好策略。</p>



<p>若你已經迫不及待想動手，接下來：</p>



<ul><li>依本文框架補上程式碼段並回測驗證。</li><li>加入自己的好因子和條件，調整策略。</li><li>也歡迎參考 <a href="https://colab.research.google.com/drive/1uD2DkcugVXwHLZvHEceMG2BQWTRDRypA?usp=sharing" data-type="URL" data-id="https://colab.research.google.com/drive/1uD2DkcugVXwHLZvHEceMG2BQWTRDRypA?usp=sharing" target="_blank" rel="noopener">Colab 範例檔</a>。</li></ul>



<p>祝你在下一個除息季，順利把每一分股息都握在手中！</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/%e5%be%a9%e5%88%bb%e8%88%87%e5%84%aa%e5%8c%96-00919%ef%bc%9a%e7%8e%a9%e8%bd%89%e9%ab%98%e8%82%a1%e6%81%af-etf/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">6561</post-id>	</item>
		<item>
		<title>如何復刻0056高股息ETF，並打造超越市場的進階策略！</title>
		<link>https://www.finlab.tw/%e5%a6%82%e4%bd%95%e5%be%a9%e5%88%bb0056%e9%ab%98%e8%82%a1%e6%81%afetf%ef%bc%8c%e4%b8%a6%e6%89%93%e9%80%a0%e8%b6%85%e8%b6%8a%e5%b8%82%e5%a0%b4%e7%9a%84%e9%80%b2%e9%9a%8e%e7%ad%96%e7%95%a5%ef%bc%81/</link>
					<comments>https://www.finlab.tw/%e5%a6%82%e4%bd%95%e5%be%a9%e5%88%bb0056%e9%ab%98%e8%82%a1%e6%81%afetf%ef%bc%8c%e4%b8%a6%e6%89%93%e9%80%a0%e8%b6%85%e8%b6%8a%e5%b8%82%e5%a0%b4%e7%9a%84%e9%80%b2%e9%9a%8e%e7%ad%96%e7%95%a5%ef%bc%81/#respond</comments>
		
		<dc:creator><![CDATA[Andy]]></dc:creator>
		<pubDate>Tue, 25 Mar 2025 05:09:58 +0000</pubDate>
				<category><![CDATA[VIP文章]]></category>
		<category><![CDATA[FinLab 量化平台]]></category>
		<category><![CDATA[Python新手教學]]></category>
		<category><![CDATA[PYTHON財經]]></category>
		<category><![CDATA[基本面分析]]></category>
		<category><![CDATA[股票策略]]></category>
		<category><![CDATA[財經PYTHON教學]]></category>
		<category><![CDATA[選股策略]]></category>
		<category><![CDATA[PYTHON]]></category>
		<category><![CDATA[VIP限定]]></category>
		<category><![CDATA[歷史回測]]></category>
		<category><![CDATA[程式交易]]></category>
		<category><![CDATA[股票]]></category>
		<category><![CDATA[量化投資]]></category>
		<guid isPermaLink="false">https://www.finlab.tw/?p=6547</guid>

					<description><![CDATA[復刻0056高股息ETF，並打造超越市場的進階策略]]></description>
										<content:encoded><![CDATA[
<h1>一、復刻0056高股息ETF的核心邏輯</h1>



<p>市面上最受投資人青睞的高股息 ETF，莫過於&nbsp;<strong>元大高股息 ETF（0056）</strong>。它是許多台灣投資人「存股領股利」的代表標的。0056 的選股方法，是從<strong>臺灣50指數</strong>與<strong>臺灣中型100指數</strong>為母體，優先篩選出具備相對高殖利率（預期下一年股息）之公司，最終組成 50 檔成分股。</p>



<p>然而，許多人只知道它「<strong>給股利</strong>」、風險似乎不高，卻很少真正挖掘其選股邏輯背後的細節和可能的缺陷。為了讓大家更深入了解這套機制，我們運用量化交易的方法，去「<strong>復刻</strong>」0056 的篩選邏輯，並嘗試更進一步的優化。這項研究花了相當多時間精力，從龐大資料的爬取、清洗、到回測比對，都一一經歷反覆測試，只為了呈現給投資人更清晰且更具行動價值的策略思路。</p>



<h3>復刻 0056 的關鍵步驟</h3>



<ul><li><strong>市值排名前 150 名股票作為初始篩選標的這代表先從台灣市值規模較大、較有流動性的公司中著手，排除一些可能成交量低、營運風險較高的股票。</strong></li><li><strong>近三年皆穩定發放現金股利0056 著重於「股息」，因此公司能否穩定配發現金股息，就顯得至關重要。</strong></li><li><strong>毛利率持續成長反映公司基本營運體質是否健康；若毛利率維持增長，通常代表公司具備較佳的競爭力。</strong></li><li><strong>設定交易流通性條件確保標的能有效買賣，避免「有好策略，卻掛不到單」的尷尬情況。</strong></li><li><strong>最終根據現金股利殖利率和現金股息年化報酬，選出前 50 檔股票這基本就複製了 0056 的核心精神：高殖利率作為重要排序依據。</strong></li></ul>



<p>在經過一連串比對後，復刻而得的策略股池與原版 0056 股池有&nbsp;<strong>72%</strong>&nbsp;的重疊率，報酬率曲線也高度相關。這意味著，我們的 復刻版 0056 確實能<strong>有效重現 0056 的選股結果</strong>。</p>



<h3>相關性分析：</h3>


<div class="wp-block-image">
<figure class="aligncenter is-resized"><img loading="lazy" src="https://www.finlab.tw/wp-content/uploads/2025/03/CleanShot-2025-03-17-at-11.50.56.png" alt="CleanShot 2025 03 17 at 11.50.56" width="354" height="705" title="如何復刻0056高股息ETF，並打造超越市場的進階策略！ 35"><figcaption>相關性分析</figcaption></figure></div>


<h1><br>二、為什麼要優化 0056？</h1>



<p>雖然 0056 深受大眾喜愛，但其單一依賴「殖利率」的選股標準，也帶來了不少潛在問題。<strong>最常見的疑問在於：如果公司未來的獲利或股價下滑，殖利率再高也未必保得住報酬。</strong>&nbsp;因此，僅看現金股利殖利率，有時候會忽略公司實際的成長動能與股價穩定度。</p>



<ul><li><strong>缺乏成長潛力考量：</strong> 0056 更重視「現在」的高股息，卻無法保證公司未來能維持同等配息水準。</li><li><strong>忽略股價風險：</strong> 有些殖利率高的公司，股價可能因營運不佳或大環境衝擊而下跌，使投資人因價差損失抵銷了領股息的好處。</li></ul>



<p>事實上，根據許多長期回測的結果，0056 的投資績效常<strong>落後大盤</strong>。</p>



<h3><strong>復刻 0056 報酬：</strong></h3>


<div class="wp-block-image">
<figure class="aligncenter"><img src="https://www.finlab.tw/wp-content/uploads/2025/03/CleanShot-2025-03-17-at-11.39.43@2x-1024x729.png" alt="CleanShot 2025 03 17 at 11.39.43@2x" title="如何復刻0056高股息ETF，並打造超越市場的進階策略！ 36"><figcaption>復刻 0056 報酬</figcaption></figure></div>


<h3><strong>長期持有 0056&nbsp;報酬：</strong></h3>


<div class="wp-block-image">
<figure class="aligncenter"><img src="https://www.finlab.tw/wp-content/uploads/2025/03/CleanShot-2025-03-17-at-11.47.46@2x-1024x790.png" alt="CleanShot 2025 03 17 at 11.47.46@2x" title="如何復刻0056高股息ETF，並打造超越市場的進階策略！ 37"><figcaption><strong>長期持有 0056&nbsp;報酬</strong></figcaption></figure></div>


<p>這也是為什麼我們要繼續進行第二階段的<strong>策略優化</strong>，希望既能拿到<strong>股利</strong>，也能兼顧成長與風險控管。</p>



<p></p>



<h1>三、策略的優化方向</h1>



<p>為了進一步提升報酬並減少下跌風險，我們引入了更全面的選股因子與風險控管條件，包括：</p>



<ol><li><strong>營收成長指標</strong><ul><li><strong>為什麼重要？</strong> 相較於只看當前股息，營收成長能更直接反映公司未來的成長動能。假如一家公司營收年年進步，往後維持股息或提高配息的機率也相對提高。</li></ul></li><li><strong>長期均線條件</strong><ul><li><strong>為什麼重要？</strong> 均線是一種技術分析常用的趨勢判定法。挑選「股價在長期均線之上」的公司，能有效排除股價長期走弱或進入空頭趨勢的標的。</li></ul></li><li><strong>股價波動率限制</strong><ul><li><strong>為什麼重要？</strong> 高波動可能意味著市場對公司基本面有疑慮，或財務體質波動度較大。過高的波動率會拉大投資組合的風險，限制波動度有助於穩定心態與獲利表現。</li></ul></li><li><strong>殖利率門檻</strong><ul><li><strong>為什麼重要？</strong> 雖然不能只看殖利率，但也不應該放棄。透過設置「殖利率至少在前 40%（或 60 百分位數以上）」的條件，既能保有高股息優勢，又不至於過度犧牲穩定度與成長性。</li></ul></li></ol>



<p>這些篩選條件的核心邏輯，就在於想同時享受「<strong>股利</strong>」與「<strong>成長</strong>」。最終，我們挑出能在長期維持向上趨勢、營運持續成長、且具有一定股利保證的股票，打造一個較能兼顧「<strong>領息</strong>」與「<strong>資本利得</strong>」的投資組合。<br></p>



<h1>四、優化後的策略範例</h1>



<p>以下程式碼範例，示範如何在量化平台上落實上述篩選邏輯。除了維持原先 0056「市值前 150 名」、「三年皆有發放股利」等規範，我們另外納入了<strong>營收成長</strong>、<strong>長期均線</strong>、<strong>波動度</strong>及<strong>殖利率門檻</strong>等條件。最後再綜合每檔股票的排名結果，只選擇前 20 檔表現優異的公司。</p>



<pre class="wp-block-code"><code class="">base_stocks = 市值.is_largest(150)
yield_ratio = data.get('price_earning_ratio:殖利率(%)')
殖利率條件 = (yield_ratio &gt;= yield_ratio.quantile(0.6, axis=1))
去年同月增減 = data.get("monthly_revenue:去年同月增減(%)")
rev = data.get('monthly_revenue:當月營收')
營收成長 = (rev.average(3) &gt; rev.average(12))
均線條件 = (close&gt;close.average(120)) &amp; (close&gt;close.average(240))
std = close.pct_change().rolling(60).std().rank(axis=1, pct=True)
波動條件 = (std &lt; 0.5)

conds = (
 (close&gt;0)
 &amp; base_stocks
 &amp; vol_cond
 &amp; eps_cond
 &amp; 近三年皆有發放現金股利
 &amp; 毛利成長率優良
 &amp; 營收成長
 &amp; 均線條件
 &amp; 波動條件
 &amp; 殖利率條件
)
position =  (cash_dividend_annual.rank(axis=1, pct=True) + 現金股利殖利率.rank(axis=1, pct=True) + 去年同月增減.rank(axis=1, pct=True))[conds].is_largest(20)
dates = []
y_start = position.index[0].year
y_end = position.index[-1].year
for y in range(y_start, y_end+1):
  dates.append(f"{y}-05-31")
  dates.append(f"{y}-12-27")
resample = pd.to_datetime(dates)
report2 = sim(position.reindex(resample, method='ffill'), resample=resample, upload=False)
report2.display()</code></pre>



<p>以上範例，用來呈現大致邏輯。重點在於「<strong>為什麼要加入這些條件</strong>」，而不只是條件本身。唯有理解每一步驟背後的意義，才能在投資時有所依據，也更能說服自己這樣嘗試，也歡迎大家優化加入更多因子或是優化相關的參數。</p>



<p></p>



<h1>五、因子IC/IR分析</h1>



<p>在量化投資的領域，經常會透過「<strong>Information Coefficient</strong>&nbsp;<strong>資訊係數</strong>」來確認某個因子是否確實能帶來正向貢獻。以下名詞簡單解釋：</p>



<ul><li><strong>IC（Information Coefficient，訊息係數）：</strong> 量度某因子的預測能力，IC &gt; 0 代表該因子對未來報酬有正向預測力。</li><li><strong>IR（Information Ratio，訊息比率）：</strong> 代表因子收益與風險的平衡程度，IR &gt; 1 通常表示該因子效果不錯。</li></ul>



<p>更詳細的內容歡迎參考之前的文章，<a href="https://www.finlab.tw/information-coefficient/">Information Coefficient 是什麼，要如何使用？</a></p>



<p>經分析顯示，<strong>營收成長</strong>、<strong>現金股息年化報酬</strong>、<strong>殖利率條件</strong>等因子都對整體績效貢獻較大，尤其是營收成長與長期均線兩因子的 IC/IR 表現最亮眼。這進一步佐證了「高息 + 成長 + 走勢向上」的組合，更能帶來勝率與報酬的提升。</p>



<h3><strong>因子 IC / IR 分析：</strong></h3>


<div class="wp-block-image is-style-default">
<figure class="aligncenter is-resized"><img loading="lazy" src="https://www.finlab.tw/wp-content/uploads/2025/03/CleanShot-2025-03-17-at-11.38.57.png" alt="CleanShot 2025 03 17 at 11.38.57" width="315" height="468" title="如何復刻0056高股息ETF，並打造超越市場的進階策略！ 38"><figcaption><strong>因子 IC / IR 分析</strong></figcaption></figure></div>


<p></p>



<h1>六、終極版策略的績效分析</h1>



<p>把所有優化條件整合後，使用強大的&nbsp;<a href="https://doc.finlab.tw/reference/optimize/#finlab.optimize.combinations.sim_conditions" target="_blank" rel="noopener"><code>finlab.optimize</code></a>&nbsp;「<a href="https://doc.finlab.tw/reference/optimize/#finlab.optimize.combinations.sim_conditions" target="_blank" rel="noopener">文檔連結</a>」可以更方便的進行<strong>條件排列組合</strong>與大規模回測，最終得到「<strong>終極版</strong>」的選股策略。其結果遠遠優於單純追求殖利率的 0056，以下為量化回測的關鍵指標：</p>



<ol><li><strong>年化報酬率：</strong>&nbsp;提高至約&nbsp;<strong>31%</strong>，相較於原版 0056 明顯領先。</li><li><strong>最大回撤：</strong>&nbsp;降至&nbsp;<strong>24.3%</strong>，顯示波動與下跌風險獲得更佳控管。</li><li><strong>夏普比率：</strong>&nbsp;超過&nbsp;<strong>2</strong>&nbsp;以上，代表收益相對於風險具高度吸引力。</li></ol>



<p>除了高報酬率，更難能可貴的是兼顧到風險面與投資體驗：投資組合的走勢相對平穩，不必日日擔心股價大幅震盪。如此一來，投資人就能同時享有領股利的安心感，又能捕捉股價成長的爆發力。</p>



<h3><strong>獲利能力分析：</strong></h3>


<div class="wp-block-image">
<figure class="aligncenter"><img src="https://www.finlab.tw/wp-content/uploads/2025/03/CleanShot-2025-03-17-at-11.42.27.png" alt="CleanShot 2025 03 17 at 11.42.27" title="如何復刻0056高股息ETF，並打造超越市場的進階策略！ 39"><figcaption><strong>獲利能力分析</strong></figcaption></figure></div>


<h3><strong>抗風險能力分析：</strong></h3>


<div class="wp-block-image">
<figure class="aligncenter"><img src="https://www.finlab.tw/wp-content/uploads/2025/03/CleanShot-2025-03-17-at-11.42.51.png" alt="CleanShot 2025 03 17 at 11.42.51" title="如何復刻0056高股息ETF，並打造超越市場的進階策略！ 40"><figcaption><strong>抗風險能力分析</strong></figcaption></figure></div>


<h3><strong>風險報酬分析：</strong></h3>


<div class="wp-block-image">
<figure class="aligncenter"><img src="https://www.finlab.tw/wp-content/uploads/2025/03/CleanShot-2025-03-17-at-11.43.13.png" alt="CleanShot 2025 03 17 at 11.43.13" title="如何復刻0056高股息ETF，並打造超越市場的進階策略！ 41"><figcaption><strong>風險報酬分析</strong></figcaption></figure></div>


<h3><strong>勝率期望值分析：</strong></h3>


<div class="wp-block-image">
<figure class="aligncenter"><img src="https://www.finlab.tw/wp-content/uploads/2025/03/CleanShot-2025-03-17-at-11.43.45.png" alt="CleanShot 2025 03 17 at 11.43.45" title="如何復刻0056高股息ETF，並打造超越市場的進階策略！ 42"><figcaption><strong>勝率期望值分析</strong></figcaption></figure></div>


<h1><br>七、結語與投資行動建議</h1>



<p>從最初單純「<strong>復刻 0056 高股息</strong>」的思路，到後來發現 0056 可能有所不足，再進一步優化篩選條件並不斷迭代測試。正是因為投入了大量的程式回測、因子分析，才有這次所呈現的量化成果。</p>



<p>對於想靠股息過日子，或喜歡「<strong>領息 + 穩定增值</strong>」的投資人而言，本文提供了另一個思考角度：</p>



<ul><li>高殖利率當然好，但若同時輔以「<strong>營收成長</strong>」、「<strong>股價走勢</strong>」以及「<strong>風險控管</strong>」等條件，也許能得到更好的投資體驗與回報。</li><li>0056 作為大眾入門選擇並無不可，但若你願意花些心思了解量化策略，自己動手選股或透過更進階的工具優化組合，或許就能在領股期的同時「多賺一點，少跌一點」，甚至大大超越原始 ETF 的表現。</li></ul>



<p>最後，若對量化選股或因子策略有更多好奇心，不妨實際嘗試應用文中提到的篩選方式，或直接透過量化平台進行回測調整，也歡迎參考&nbsp;<a href="https://colab.research.google.com/drive/1Gkz7n7jniMAqqEzwh96eV3JI1YTplS3g" target="_blank" rel="noopener">Colab範例檔</a>&nbsp;。<strong>祝大家研究和投資順利、盈收長紅！</strong></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/%e5%a6%82%e4%bd%95%e5%be%a9%e5%88%bb0056%e9%ab%98%e8%82%a1%e6%81%afetf%ef%bc%8c%e4%b8%a6%e6%89%93%e9%80%a0%e8%b6%85%e8%b6%8a%e5%b8%82%e5%a0%b4%e7%9a%84%e9%80%b2%e9%9a%8e%e7%ad%96%e7%95%a5%ef%bc%81/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">6547</post-id>	</item>
		<item>
		<title>大跌後的底氣 &#8211; 獨家主力波動指標</title>
		<link>https://www.finlab.tw/broker_transaction_indicator/</link>
					<comments>https://www.finlab.tw/broker_transaction_indicator/#respond</comments>
		
		<dc:creator><![CDATA[FinLab - 韓承佑]]></dc:creator>
		<pubDate>Wed, 07 Aug 2024 04:06:32 +0000</pubDate>
				<category><![CDATA[FinLab 量化平台]]></category>
		<category><![CDATA[Python新手教學]]></category>
		<category><![CDATA[籌碼面]]></category>
		<category><![CDATA[股票策略]]></category>
		<category><![CDATA[財經PYTHON教學]]></category>
		<category><![CDATA[PYTHON]]></category>
		<category><![CDATA[VIP限定]]></category>
		<category><![CDATA[歷史回測]]></category>
		<category><![CDATA[程式交易]]></category>
		<category><![CDATA[量化投資]]></category>
		<guid isPermaLink="false">https://www.finlab.tw/?p=6277</guid>

					<description><![CDATA[券商分點理論上是非常有效果的數據，應用得當，可以用來預測股價的走勢，然而，市場上主要將券商分點資料來計算「主力買賣超」、「買賣家數差」，該指標在選股的有效程度上，並非顯著。

本文將提出一種新的方式，來提取券商分點資料，製作更有效的選股指標，其效果非常顯著，搭配回測策略能夠有效獲得卓越的效果。]]></description>
										<content:encoded><![CDATA[
<h1>介紹</h1>



<p>券商分點理論上是非常有效果的數據，應用得當，可以用來預測股價的走勢，然而，市場上主要將券商分點資料來計算「主力買賣超」、「買賣家數差」，該指標在選股上，效果不好。</p>



<p>本文將提出一種新的方式，來提取券商分點資料，製作更有效的選股指標，其效果非常顯著，搭配回測策略能夠有效獲得卓越的效果。本文將詳細說明這些概念的定義、計算方法及應用，並展示如何將這些知識綜合應用於投資策略的設計與回測。</p>



<p>建議讀者可以自行修改，將策略調整後，有很大的進步空間。</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="585" src="https://www.finlab.tw/wp-content/uploads/2024/08/DALL·E-2024-08-07-12.04.12-A-minimalist-stock-price-V-shaped-recovery-chart-on-a-black-background.-The-V-shape-is-prominently-illuminated-giving-it-a-sleek-high-end-look.-The--1024x585.webp" alt="DALL·E 2024 08 07 12.04.12 A minimalist stock price V shaped recovery chart on a black background. The V shape is prominently illuminated giving it a sleek high end look. The" class="wp-image-6299" srcset="https://www.finlab.tw/wp-content/uploads/2024/08/DALL·E-2024-08-07-12.04.12-A-minimalist-stock-price-V-shaped-recovery-chart-on-a-black-background.-The-V-shape-is-prominently-illuminated-giving-it-a-sleek-high-end-look.-The--1024x585.webp 1024w, https://www.finlab.tw/wp-content/uploads/2024/08/DALL·E-2024-08-07-12.04.12-A-minimalist-stock-price-V-shaped-recovery-chart-on-a-black-background.-The-V-shape-is-prominently-illuminated-giving-it-a-sleek-high-end-look.-The--300x171.webp 300w, https://www.finlab.tw/wp-content/uploads/2024/08/DALL·E-2024-08-07-12.04.12-A-minimalist-stock-price-V-shaped-recovery-chart-on-a-black-background.-The-V-shape-is-prominently-illuminated-giving-it-a-sleek-high-end-look.-The--768x439.webp 768w, https://www.finlab.tw/wp-content/uploads/2024/08/DALL·E-2024-08-07-12.04.12-A-minimalist-stock-price-V-shaped-recovery-chart-on-a-black-background.-The-V-shape-is-prominently-illuminated-giving-it-a-sleek-high-end-look.-The--1536x878.webp 1536w, https://www.finlab.tw/wp-content/uploads/2024/08/DALL·E-2024-08-07-12.04.12-A-minimalist-stock-price-V-shaped-recovery-chart-on-a-black-background.-The-V-shape-is-prominently-illuminated-giving-it-a-sleek-high-end-look.-The-.webp 1792w" sizes="(max-width: 1024px) 100vw, 1024px" title="大跌後的底氣 - 獨家主力波動指標 43"></figure>



<h1>籌碼分點資料（Broker Transactions）</h1>



<h2>什麼是籌碼分點資料</h2>



<p>籌碼分點資料是指某一股票在不同券商之間的買賣交易情況。這些資料包括買入量、賣出量等，反映了不同券商在特定時間段內的交易行為。這些數據能提供市場上資金流動的資訊，有助於投資者理解市場動向。</p>



<h2>資料來源與取得方式</h2>



<p>在台灣，投資者可以通過一些金融資料平台，如Finlab，來獲取籌碼分點資料。這些平台提供了方便的API接口，使投資者能夠輕鬆下載和分析數據。</p>



<pre class="wp-block-code"><code lang="python" class="language-python">from finlab import data
bt = data.get('broker_transactions', force_download=True)

buysell = bt.groupby(['date', 'stock_id']).agg({'buy': 'sum', 'sell': 'sum'})\
  .reset_index().pivot(columns='stock_id', index='date', values=['buy', 'sell'])

buysell.head()</code></pre>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="254" src="https://www.finlab.tw/wp-content/uploads/2024/08/image-1-1024x254.png" alt="image 1" class="wp-image-6279" srcset="https://www.finlab.tw/wp-content/uploads/2024/08/image-1-1024x254.png 1024w, https://www.finlab.tw/wp-content/uploads/2024/08/image-1-300x74.png 300w, https://www.finlab.tw/wp-content/uploads/2024/08/image-1-768x190.png 768w, https://www.finlab.tw/wp-content/uploads/2024/08/image-1-1536x381.png 1536w, https://www.finlab.tw/wp-content/uploads/2024/08/image-1-2048x508.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="大跌後的底氣 - 獨家主力波動指標 44"></figure>



<p></p>



<h2>籌碼分點資料的深度分析</h2>



<h3>過往如何通過籌碼分點資料識別主力資金動向</h3>



<p>主力資金的動向通常對市場影響巨大。通過分析籌碼分點資料中的大額交易，可以識別出主力資金的買賣行為，從而提前佈局。</p>



<h3>過往的券商分點指標</h3>



<p>過往有一些券商分點指標，對於選股有一些效果，然而實測上，顯著程度有限。以下列舉最常見的兩種指標：</p>



<h3>主力買賣超</h3>



<p><strong>定義</strong>：</p>



<p>主力買賣超是指某一特定時間段內，主要券商的買入量與賣出量之差。</p>



<p><strong>計算公式</strong>： </p>



<p>主力買賣超=∑(主要券商買入量)−∑(主要券商賣出量)</p>



<p><strong>效用：</strong></p>



<ul><li><strong>資金動向指標</strong>：主力買賣超反映了市場中資金流向的變化，主要券商的大額買入或賣出行為通常代表著市場主力資金的動向，能夠影響股票價格。</li><li><strong>市場情緒指標</strong>：通過觀察主力買賣超，投資者可以了解市場主力的投資情緒，進而做出相應的投資決策。</li></ul>



<h3>買賣家數差</h3>



<p><strong>定義</strong>：</p>



<p>買賣家數差是指買入股票的券商家數與賣出股票的券商家數之差。</p>



<p><strong>計算公式</strong>： </p>



<p>買賣家數差=買入券商家數−賣出券商家數</p>



<p><strong>效用：</strong></p>



<p><strong>市場參與度指標</strong>：買賣家數差反映了市場中多空雙方的力量對比，當買入券商家數多於賣出券商家數時，表示市場散戶的偏好。</p>



<p><strong>供需平衡指標</strong>：買賣家數差能夠幫助投資者判斷市場供需平衡狀況，從而預測未來價格走勢。</p>



<p>上述指標效果平平，接下來，我們將藉由 ChatGPT 發想更優秀的指標。</p>



<h1>券商分點資料建構指標</h1>



<h2>利用 ChatGPT 發想相關想法</h2>



<p>為了創建更好的指標，我們可以透過 ChatGPT 來輔助產生不同的 factor 進行運算，這種方法並非標新立異，其實早就在</p>



<blockquote class="wp-block-quote"><p>Cheng, Yuhan, and Ke Tang. &#8220;GPT&#8217;s idea of stock factors.&#8221;&nbsp;<em>Quantitative Finance</em>&nbsp;(2024): 1-26.</p></blockquote>



<p>被介紹過。</p>



<h2>指標種類與計算方式</h2>



<p>以下為 ChatGPT 產生的指標，其中有一些是滿有參考性的，我們可以拿來使用看看，下圖中，雖然它誤以為 ICIR 是一種協會（等等介紹這是什麼），然而也提供了一些不錯的指標：</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="941" height="1024" src="https://www.finlab.tw/wp-content/uploads/2024/08/image-5-941x1024.png" alt="image 5" class="wp-image-6293" srcset="https://www.finlab.tw/wp-content/uploads/2024/08/image-5-941x1024.png 941w, https://www.finlab.tw/wp-content/uploads/2024/08/image-5-276x300.png 276w, https://www.finlab.tw/wp-content/uploads/2024/08/image-5-768x835.png 768w, https://www.finlab.tw/wp-content/uploads/2024/08/image-5.png 1412w" sizes="(max-width: 941px) 100vw, 941px" title="大跌後的底氣 - 獨家主力波動指標 45"></figure>



<h2>產生程式碼</h2>



<p>ChatGPT 除了可以幫忙發想指標外，也可以用來產生出相對應的程式，這樣就不需要親自撰寫程式。</p>



<p></p>



<pre class="wp-block-code"><code lang="python" class="language-python">import warnings
warnings.filterwarnings('ignore')

net_volume = buysell['buy'] - buysell['sell']
buy_sell_ratio = buysell['buy'] / buysell['sell']
balance_index = (buysell['buy'] - buysell['sell']) / (buysell['buy'] + buysell['sell'])

feature_dfs = {
    'net_volume': net_volume,
    'buy_sell_ratio': buy_sell_ratio,
    'balance_index': balance_index,

}</code></pre>



<p></p>



<h2>有效性</h2>



<p>我們當然會希望這些指標是有效的，需要有一個衡量標準，能夠一致性的對於這些不同的指標進行評分，方便我們從中選出最適合選股的指標，通常我們會使用 IC、ICIR 來衡量這些指標是否對於未來的股價有相關性。</p>



<h1>Information Coefficient (IC)</h1>



<h2>介紹</h2>



<p>IC，即Information Coefficient，是衡量一個指標在預測資產回報方面的能力的數值。簡單來說，IC代表了預測回報與實際回報之間的相關性。IC的範圍一般在-1到1之間，其中正值表示預測回報與實際回報正相關，負值表示兩者負相關。IC的絕對值越高，表示預測能力越強。</p>



<p>IC的計算方法如下：</p>



<p>IC = Cov(r,x) / σrσx</p>



<p>其中，r 為實際回報，x 為預測回報，Cov(r,x) 為兩者的協方差，σr、σx​ 分別為實際回報和預測回報的標準差。</p>



<p>IC主要用於衡量單一時點上的預測能力，而ICIR則進一步綜合多個時點上的IC，評估一段時間內的整體預測能力。</p>



<h2>ICIR</h2>



<h2>如何計算ICIR</h2>



<p>ICIR的計算主要基於Information Coefficient（IC），其公式如下：</p>



<p>ICIR = Mean(IC) × Std(IC)</p>



<h2>在投資中的應用</h2>



<p>ICIR能幫助投資者評估不同策略或指標的預測能力，從而選擇具有較穩定的預測能力的策略。高ICIR值通常表示策略具有穩定的預測能力，適合在實際投資中應用。</p>



<h3>程式碼</h3>



<pre class="wp-block-code"><code lang="python" class="language-python">from finlab.tools.factor_analysis import ic

adj_close = data.get('etl:adj_close')
# 每個時間點的IC
ics = ic(feature_dfs, adj_close, days=[10, 20, 60]) 

# 取平均
ics.mean()

# 取得ICIR
ics.mean() / ics.std()</code></pre>



<h3>遞迴優化參數</h3>



<p>藉由 ICIR，我們可以疊代不同的公式，產生出更好的指標：</p>



<ol><li>產生指標庫：先計算與發想指標</li><li>計算IC、ICIR</li><li>更新指標指標庫<ol><li>移除沒有效果的指標</li><li>有效果的指標進行參數優化，列舉多個變體</li></ol></li><li>重複步驟 1</li></ol>



<h2>成果</h2>



<pre class="wp-block-code"><code lang="python" class="language-python">import numpy as np

def std(df, n):
  return df.rolling(n).std().replace(0, np.nan)

buy_change = buysell['buy'] - buysell['buy'].shift(1)
sell_change = buysell['sell'] - buysell['sell'].shift(1)
net_volume_change = net_volume - net_volume.shift(1)

feature_dfs = {
    'net_volume': net_volume,
    'buy_sell_ratio': buy_sell_ratio,
    'balance_index': balance_index,

    'avg20_net_volume': net_volume / net_volume.rolling(20).mean(),
    'avg20_buy_sell_ratio': buy_sell_ratio.rolling(20).mean(),
    'avg20_balance_index': balance_index.rolling(20).mean(),

    'sharpe5_net_volume': net_volume.rolling(5).mean() / std(net_volume, 5),
    'sharpe10_net_volume': net_volume.rolling(10).mean() / std(net_volume, 10),
    'sharpe20_net_volume': net_volume.rolling(20).mean() / std(net_volume, 20),
    'sharpe60_net_volume': net_volume.rolling(60).mean() / std(net_volume, 60),
    
    'sharpe5_balance_index': balance_index.rolling(5).mean() / std(balance_index, 5),
    'sharpe10_balance_index': balance_index.rolling(10).mean() / std(balance_index, 10),
    'sharpe20_balance_index': balance_index.rolling(20).mean() / std(balance_index, 20),
    'sharpe60_balance_index': balance_index.rolling(60).mean() / std(balance_index, 60),
    
    'sharpe5_buy_sell_ratio': buy_sell_ratio.rolling(5).mean() / std(buy_sell_ratio, 5),
    'sharpe10_buy_sell_ratio': buy_sell_ratio.rolling(10).mean() / std(buy_sell_ratio, 10),
    'sharpe20_buy_sell_ratio': buy_sell_ratio.rolling(20).mean() / std(buy_sell_ratio, 20),
    'sharpe30_buy_sell_ratio': buy_sell_ratio.rolling(30).mean() / std(buy_sell_ratio, 30),
    'sharpe60_buy_sell_ratio': buy_sell_ratio.rolling(60).mean() / std(buy_sell_ratio, 60),
}

from finlab.tools.factor_analysis import ic

adj_close = data.get('etl:adj_close')
ics = ic(feature_dfs, adj_close, days=[10, 20, 60])</code></pre>



<figure class="wp-block-image size-full"><img loading="lazy" width="559" height="596" src="https://www.finlab.tw/wp-content/uploads/2024/08/image-6.png" alt="image 6" class="wp-image-6307" srcset="https://www.finlab.tw/wp-content/uploads/2024/08/image-6.png 559w, https://www.finlab.tw/wp-content/uploads/2024/08/image-6-281x300.png 281w" sizes="(max-width: 559px) 100vw, 559px" title="大跌後的底氣 - 獨家主力波動指標 46"></figure>



<p>上圖中可以發現，最終做出來的指標，其 IC 最高，高達 0.04，其中一種指標，雖然表現並不是非常理想，但用選股策略上非常有效果，我把它叫做「主力波動指標」。</p>



<h1>主力波動與穩定性</h1>



<p>主力常常上攻後又迅速熄火，讓投資者難以捕捉到持續的上漲機會。甚至是隔日沖主力，常常當天買、隔天賣，使得券商分點特別難用。為了克服這一問題，我們需要構建一個更為有效的指標，以更準確地識別市場中的主力動向，特別是穩定買入、持續買入的主力，並提高投資決策的穩定性。</p>



<h2>指標的需求</h2>



<p>指標必須滿足以下需求：</p>



<ol><li><strong>主力買賣比率</strong>：滾動平均值（rolling mean）能夠平滑短期波動，使得我們能夠觀察到買賣比率的中期趨勢。通過計算10日滾動平均值，我們可以避免因單日大幅波動而帶來的誤判，更清晰地看到市場主力的買入行為。</li><li><strong>買入波動性</strong>：標準差（std）是衡量數據波動性的重要指標。當買賣比率的標準差較低時，意味著買賣比率在這段時間內波動較小，主力行為相對穩定。低波動性通常表明市場中存在持續且穩定的買入或賣出行為。</li><li><strong>識別持續買入</strong>：該指標將滾動平均值與標準差進行比值計算，即買賣比率的均值除以其標準差。當這個比值較高時，說明在這段時間內，買賣比率不僅處於較高水準，且波動較小，這表明市場中可能存在持續且穩定的買入行為。這些行為通常是由市場主力資金推動的，因為他們在積極且穩定地買入股票，從而推高買賣比率並保持其穩定性。</li></ol>



<h2>公式如下</h2>



<p>買賣比率 = 前 15 大主力買入 / 前 15 大主力賣出</p>



<p>主力波動 = 買賣比率的10日平均 / 買賣比率的10日​標準差</p>



<h2>效果</h2>



<p>當該指標數值較高時，說明在過去的10日內，主力買入大量且不輕易變化，這表明市場中可能存在持續且穩定的買入行為，這些行為通常由主力資金推動。相反，若該指標數值較低，則表示買賣比率波動較大且不穩定，市場中可能缺乏持續的買入力量、或是有隔日沖的行為。</p>



<p>該指標能夠獲得非常高的 IC，並且利用該指標，可以輕易做出效果顯著的策略。</p>



<h1>回測</h1>



<p>以下是一個簡單的回測範例，展示如何通過籌碼分點資料來進行策略回測，我們利用「主力波動指標」為主體，月營收YOY為輔助，來尋找短期具有爆發力的股票標的。值得一提的是，這個策略當前並非最佳解，還有很多種方式可以大幅優化此策略的效果，建議讀者可以稍做調整，而非直接使用。</p>



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

ind = FinlabDataFrame(feature_dfs['sharpe10_buy_sell_ratio'])

close = data.get('price:收盤價')
volume = data.get('price:成交股數')
rev = data.get('monthly_revenue:當月營收')

# 1. 尋找月營收YOY大於1.5的股票標的
# 2. 成交量來到 300 張，確保流動性
# 3. 以主力波動指標進行排序，選最高的 20 檔
pos = (ind)[(rev / rev.shift(12) &gt; 1.5)
  &amp; (volume &gt; 300_000)
].is_largest(20)

r = sim(pos, resample=rev.index)</code></pre>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="1008" src="https://www.finlab.tw/wp-content/uploads/2024/08/image-3-1024x1008.png" alt="image 3" class="wp-image-6281" srcset="https://www.finlab.tw/wp-content/uploads/2024/08/image-3-1024x1008.png 1024w, https://www.finlab.tw/wp-content/uploads/2024/08/image-3-300x295.png 300w, https://www.finlab.tw/wp-content/uploads/2024/08/image-3-768x756.png 768w, https://www.finlab.tw/wp-content/uploads/2024/08/image-3-1536x1511.png 1536w, https://www.finlab.tw/wp-content/uploads/2024/08/image-3.png 1742w" sizes="(max-width: 1024px) 100vw, 1024px" title="大跌後的底氣 - 獨家主力波動指標 47"></figure>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="979" src="https://www.finlab.tw/wp-content/uploads/2024/08/image-4-1024x979.png" alt="image 4" class="wp-image-6282" srcset="https://www.finlab.tw/wp-content/uploads/2024/08/image-4-1024x979.png 1024w, https://www.finlab.tw/wp-content/uploads/2024/08/image-4-300x287.png 300w, https://www.finlab.tw/wp-content/uploads/2024/08/image-4-768x734.png 768w, https://www.finlab.tw/wp-content/uploads/2024/08/image-4-1536x1468.png 1536w, https://www.finlab.tw/wp-content/uploads/2024/08/image-4.png 1636w" sizes="(max-width: 1024px) 100vw, 1024px" title="大跌後的底氣 - 獨家主力波動指標 48"></figure>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/broker_transaction_indicator/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">6277</post-id>	</item>
		<item>
		<title>僅用財報製作 30% 年報酬的美股多空對沖策略</title>
		<link>https://www.finlab.tw/financial-report-strategy-long-short/</link>
					<comments>https://www.finlab.tw/financial-report-strategy-long-short/#respond</comments>
		
		<dc:creator><![CDATA[FinLab - 韓承佑]]></dc:creator>
		<pubDate>Sat, 07 Oct 2023 13:40:25 +0000</pubDate>
				<category><![CDATA[股票策略]]></category>
		<category><![CDATA[AI看股票]]></category>
		<category><![CDATA[FinLab 量化平台]]></category>
		<category><![CDATA[Python新手教學]]></category>
		<category><![CDATA[財經PYTHON教學]]></category>
		<category><![CDATA[PYTHON]]></category>
		<category><![CDATA[歷史回測]]></category>
		<category><![CDATA[程式交易]]></category>
		<guid isPermaLink="false">https://www.finlab.tw/?p=5806</guid>

					<description><![CDATA[本文中產生了 1000 組多空財務指標，並且利用財務指標進行多空對沖策略，回測績效高達年報酬 30%！在全球資 [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>本文中產生了 1000 組多空財務指標，並且利用財務指標進行多空對沖策略，回測績效高達年報酬 30%！在全球資本市場中，美國股市佔據著不可忽視的地位，其規模與活躍度長期以來都是全球最領先的。尤其在科技、金融和消費等多個重要行業，美股市場都匯聚了眾多具有全球影響力的領先企業。對投資者而言，深入了解並善用財務指標來分析和評估美股市場的投資機會，是提高投資效益、降低投資風險的重要手段。FinLab 網站中有一個 <a href="https://ai.finlab.tw/strategyview/?uid=TJN4FDuqrwU8DML7DAjUYFIMutp2&amp;sid=%E8%B2%A1%E5%A0%B1%E6%8C%87%E6%A8%9920%E5%A4%A7" target="_blank" rel="noopener">財報 20 大的選股</a> 策略，是否能夠用在美股之中呢？效果如何呢？就讓我們來研究研究。</p>



<h2>美股策略研究簡單嗎？</h2>



<p>財務指標是反映企業經營狀況、財務健康和投資價值的重要工具。透過財務指標的分析，我們可以更加清晰地理解企業的盈利能力、資產負債狀態、營運效率以及現金流狀況，從而作出更為理性和科學的投資決策。然而當前美股已經有非常多的量化交易團隊與機構從中找尋超額報酬，所以我們在實驗中，發現並沒有像是台股一樣簡單做得出好策略。</p>



<h2>台股美股的差異？</h2>



<p>台股一般來說，我們用均線濾網就可以很有效的篩選股票，用 EPS 一定是要找 EPS 每季上升的的股票標的。然而在美股竟然發生一百八十度的轉變，例如，美股跟台股在均線的使用上，幾乎是完全相反，也就是很容易有均線回歸，漲多了就跌回去的狀況發生。而創新高的 EPS 不要以為接下來股價也會創新高，因為當天股價可能都已經反應完畢了，甚至過度反應而導致超漲。</p>



<h2>美股的財報指標還有用嗎？</h2>



<p>這就是這篇文章想要來探討的，我們使用 quandl 所有的美股指標，來預測看看究竟是否有能力做出不錯的策略。假如你是 VIP 會員，可以參考我們的財務指標 20 大策略，並且嘗試換成美股版本喔！</p>



<h2>資料分析</h2>



<p>首先，我們先取得想要來研究的資料，由於資料授權的問題，目前只能在  <a href="https://ai.finlab.tw" target="_blank" rel="noopener">finlab平台</a> 上進行程式的撰寫，不過我們近期想到一些方法來避免授權問題，當前請大家不要使用 colab ，而是直接用網頁版來執行，不然會無法運行喔！可以透過以下的程式碼拿到你想要的財報指標，我們以四種財報指標為例：</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">from finlab import data

menu = """非控制股權	data.get('us_fundamental:accoci')	float	
資產總額	data.get('us_fundamental:assets')	float	
流動資產	data.get('us_fundamental:assetsc')	float	
非流動資產	data.get('us_fundamental:assetsnc')	float	
"""

with data.us_universe('Common Stock'):
    code = menu.split('\t')[1::3]
    name = [n.replace('\n', '') for n in menu.split('\t')[0::3]]
    for n, c in zip(name, code):
        dfs[n] = eval(c)</code></pre>



<p>接下來，我們想要進行資料處理，讓財報資料做斜率、取變異等方法，提取出可能有效的資料：</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">
new_feat_dfs = {}

for fname, df in dfs.items():

    if df.dtypes[0] != 'float64':
        continue

    print(fname)

    avg2 = df.average(2)
    avg4 = df.average(4)
    new_feat_dfs[fname + '_avg2'] = avg2
    new_feat_dfs[fname + '_avg4'] = avg4
    new_feat_dfs[fname + '_diff4'] = df / df.shift(4)
    new_feat_dfs[fname + '_1_avg4'] = df / avg4
    new_feat_dfs[fname + '_avg2_avg4'] = avg2 / avg4
    new_feat_dfs[fname + '_avg2_diff4'] = avg2 / avg2.shift(4)
    new_feat_dfs[fname + '_avg4_diff4'] = avg4 / avg4.shift(4)
    new_feat_dfs[fname + '_df_max4'] = df / df.rolling(4).max()
    new_feat_dfs[fname + '_df_max8'] = df / df.rolling(8).max()


feat_dfs = {**dfs, **new_feat_dfs}

with data.us_universe('Common Stock'):
    feat_dfs['money_flow'] = data.get('us_price:close') * data.get('us_price:volume')

del new_feat_dfs</code></pre>



<p>然而我們也不知道這些資料，效果究竟如何，所以可以利用機器學習的方式進行 feature 分析：</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">from finlab.ml import feature

features = feature.combine(feat_dfs, resample='Q')

# 過濾成交量太小的股票
features = features[features['money_flow'] > 1e7]
features.head()</code></pre>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="362" src="https://www.finlab.tw/wp-content/uploads/2023/10/image-3-1024x362.png" alt="image 3" class="wp-image-5807" srcset="https://www.finlab.tw/wp-content/uploads/2023/10/image-3-1024x362.png 1024w, https://www.finlab.tw/wp-content/uploads/2023/10/image-3-300x106.png 300w, https://www.finlab.tw/wp-content/uploads/2023/10/image-3-768x272.png 768w, https://www.finlab.tw/wp-content/uploads/2023/10/image-3.png 1328w" sizes="(max-width: 1024px) 100vw, 1024px" title="僅用財報製作 30% 年報酬的美股多空對沖策略 49"><figcaption>資料整理成機器學習中的特徵格式</figcaption></figure>



<p>除了有這些財報的特徵外，我們也必須知道這些數值會如何影響將來的股價，所以我們可以將上圖每一個橫軸所對映的未來長跌幅給計算出來，並且計算相關性 <code>corr</code> 假如 1 代表正相關，該數值高意味著未來會上漲，假如是 -1 就代表負相關，數值高反而意味著未來會跌：</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">from finlab.ml import label

labels = label.return_percentage(features.index, period=60, trade_at_price='open')

corr = features.corrwith(labels).dropna().sort_values()</code></pre>



<p>雖然給大家的例子中只有一小部分的資料，但我們自己實驗是產生了 1000 組不同的財報數值。我們只想要提取有用的資料，將其他沒用的資料過濾。也就是我們想找高度相關，或高度負相關的特徵，來進行股票的預測：</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">print(corr.head(10))
print(corr.tail(10))</code></pre>



<figure class="wp-block-image size-full"><img loading="lazy" width="531" height="554" src="https://www.finlab.tw/wp-content/uploads/2023/10/image-4.png" alt="image 4" class="wp-image-5808" srcset="https://www.finlab.tw/wp-content/uploads/2023/10/image-4.png 531w, https://www.finlab.tw/wp-content/uploads/2023/10/image-4-288x300.png 288w" sizes="(max-width: 531px) 100vw, 531px" title="僅用財報製作 30% 年報酬的美股多空對沖策略 50"><figcaption>最負相關，最正相關</figcaption></figure>



<p>上圖發現一些有趣的現象，我們挑最低負相關，與最高相關的來說明。</p>



<h2>市值衝吧！</h2>



<p>在這個實驗中，「市值_1_avg4」是最高度相關的，其代表的運算方式，是「市值 / 近四季的平均市值」。為什麼近四季市值增加越多，代表未來報酬率越好呢？若一家公司近期的營運表現優於過去，其市值可能會上升，從而使得「市值 / 近四季的平均市值」的比例增加。這也反映了市場對公司未來盈利能力的信心增強。</p>



<h2>小心獲利太多啦！</h2>



<p>在上圖當中，營收_max4 是最負相關的資訊，代表此數值越高，未來股價越危險，潛在隱含可能營收會有均值回歸的效應產生，導致股價下跌。</p>



<h2>數據所代表的含意，跟常識不符合時，如何是好？</h2>



<p>當然聽數據的呀！因為金融市場裡並沒有什麼常識可言，以常識來說期貨原油結算應該是正的？（但曾經發生負的狀況）。以常識來說，股價漲太高應該不要再追了（但在台股完全就是要追上去，實驗與實際都如此證明）。為什麼常識不管用？因為在一個效率市場下，任何所謂的「常識」都會被機構交易者各種套利，例如一個常識： ROE 高是好股票，所以當公司發布時，大家知道這個常識而瞬間買入此股票，造成必須要去比拼高頻交易，看誰買的早，就能用比較低的價格買到，才能比別人更早去交易這個「常識」，但對於我這種慢半拍的人來說，當我發現這家公司很好時，股價已經反映了財報，所以這個「常識」就不符合當前科技技術橫行的市場了。雖然速度比不贏別人，那就只好去探勘一些「反常識」，「反常識」沒有人做，所以也是有很多潛在的獲利機會！但是反常識也很容易因為數據處理、探勘的方式不正確，而意外的被產生出來，所以有好的資料驗證步驟，是非常重要的，不過有點離題，我們接著繼續來做策略。</p>



<h2>去除相似的資料</h2>



<p>在上圖中我們可以看到「市值_1_avg4」以及「市值_df_max4」，其實這兩筆資料是用類似的方法來計算的，雖然都很重要，但只要用其中一種即可，沒必要兩個都用，可以把其中一筆換成其他更有意義的數據，所以我們可以驗證 features 財報數據間的相關性，將相關性高的財報數據給剔除，留下比較有代表性的即可：</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">import numpy as np

cor_matrix = features[corr.index].corr().abs()
upper_tri = cor_matrix.where(np.triu(np.ones(cor_matrix.shape),k=1).astype(bool))
to_drop = [column for column in upper_tri.columns if any(upper_tri[column] > 0.8)]

long_names = corr[corr.index.isin(to_drop)].tail(30)
short_names = corr[corr.index.isin(to_drop)].head(30)</code></pre>



<p>上面程式碼中， 我們找到 long_names 以及 short_names 代表與未來價格高度正相關的指標，以及高度負相關的指標。我們將這些指標對於每個股票去評分，並且加總起來：</p>



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

score = sum([feat_dfs[f].rank(axis=1, pct=True).fillna(0) for f in long_names.index])
short_score = sum([feat_dfs[f].rank(axis=1, pct=True).fillna(0) for f in short_names.index])

score = score.index_str_to_date()
short_score = short_score.index_str_to_date()</code></pre>



<p>就可以得到每個股票的總分了！最後將總分最高的股票做多、最低的股票做空，就可以獲得更穩定的報酬率：</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">import numpy as np
from finlab.dataframe import FinlabDataFrame


with data.us_universe('Common Stock'):
    close = data.get('us_price:close')
    vol = data.get('us_price:volume')

    cond1 = (close * vol).average(60) > 1e7
    cond2 = vol > 5000
    
    cond = cond1 * cond2 * (close.notna())
    pos = (FinlabDataFrame(score-short_score) * cond).is_largest(10).astype(int) * 2
    neg_pos = (FinlabDataFrame(score-short_score) * cond).is_smallest(20).astype(int)

    pos *= close.pct_change().rolling(20).std()
    neg_pos *= close.pct_change().rolling(20).std()

    pos /= pos.sum(axis=1)
    neg_pos /= neg_pos.sum(axis=1)

    total_pos = pos - neg_pos
    
    r0 = backtest.sim(total_pos, resample='W', position_limit=0.1)</code></pre>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="479" src="https://www.finlab.tw/wp-content/uploads/2023/10/image-5-1024x479.png" alt="image 5" class="wp-image-5809" srcset="https://www.finlab.tw/wp-content/uploads/2023/10/image-5-1024x479.png 1024w, https://www.finlab.tw/wp-content/uploads/2023/10/image-5-300x140.png 300w, https://www.finlab.tw/wp-content/uploads/2023/10/image-5-768x359.png 768w, https://www.finlab.tw/wp-content/uploads/2023/10/image-5.png 1150w" sizes="(max-width: 1024px) 100vw, 1024px" title="僅用財報製作 30% 年報酬的美股多空對沖策略 51"><figcaption>美股策略實做</figcaption></figure>



<p>不過這個策略滿奇怪的，2020年以前都不太會賺，雖然也沒賠太多錢（相較於純做多的策略）但我自己個人會有點忍受不了這麼多年的績效平平，可能還有改進的空間，假如讀者知道為什麼2020 年前後會有這麼大的差異，歡迎留言或在 Discord 跟我們一起討論！</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/financial-report-strategy-long-short/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">5806</post-id>	</item>
		<item>
		<title>月營收選股｜股價創新高｜新手必學的雙動能策略</title>
		<link>https://www.finlab.tw/revenue_and_price_engine_strategy/</link>
					<comments>https://www.finlab.tw/revenue_and_price_engine_strategy/#respond</comments>
		
		<dc:creator><![CDATA[Ben]]></dc:creator>
		<pubDate>Wed, 16 Nov 2022 06:55:47 +0000</pubDate>
				<category><![CDATA[Python新手教學]]></category>
		<category><![CDATA[FinLab 量化平台]]></category>
		<category><![CDATA[VIP文章]]></category>
		<category><![CDATA[基本面分析]]></category>
		<category><![CDATA[技術面]]></category>
		<category><![CDATA[投資新手]]></category>
		<category><![CDATA[財經PYTHON教學]]></category>
		<category><![CDATA[VIP限定]]></category>
		<category><![CDATA[創新高]]></category>
		<category><![CDATA[動能]]></category>
		<category><![CDATA[月營收]]></category>
		<guid isPermaLink="false">https://www.finlab.tw/?p=4884</guid>

					<description><![CDATA[月營收是台股獨特的基本面因子，操作台股的玩家，都知道月營收的影響性，常可先預判季財報，究竟月營收選股條件要怎麼寫？這篇就用超簡單的語法，結合「突破策略豆知識」技巧寫出15年來年化報酬37%的高報酬率策略，讓你迅速上手月營收突破這個台股經典的策略。]]></description>
										<content:encoded><![CDATA[
<p class="has-medium-font-size">月營收是台股獨特的基本面因子，操作台股的玩家，都知道月營收的影響性，常可先預判季財報，究竟月營收選股條件要怎麼寫？這篇就用超簡單的語法，結合「<a href="https://www.finlab.tw/breakthrough_stock_picking_strategies/">突破策略豆知識</a>」技巧寫出15年來年化報酬37%的高報酬率策略，讓你迅速上手月營收突破這個台股經典的策略。</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="654" src="https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-16-下午12.47.28-e1668593619128-1024x654.png" alt="截圖 2022 11 16 下午12.47.28 e1668593619128" class="wp-image-4885" srcset="https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-16-下午12.47.28-e1668593619128-1024x654.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-16-下午12.47.28-e1668593619128-300x192.png 300w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-16-下午12.47.28-e1668593619128-768x491.png 768w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-16-下午12.47.28-e1668593619128.png 1396w" sizes="(max-width: 1024px) 100vw, 1024px" title="月營收選股｜股價創新高｜新手必學的雙動能策略 52"></figure>



<h2>月營收選股策略 &#8211; 創高基礎型態</h2>



<h3>程式範例</h3>



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

rev = data.get('monthly_revenue:當月營收')
rev_yoy_growth = data.get('monthly_revenue:去年同月增減(%)')

# 近2月平均營收
rev_ma = rev.average(2)

# 近2月平均營收創12個月來新高
condition = rev_ma == rev_ma.rolling(12, min_periods=6).max()

# 單月營收年增率與訊號相乘，若訊號為False，相乘結果為0
position= rev_yoy_growth*condition

# 符合選股條件的名單中，再選出單月營收年增率前10強，並在營收公告截止日換股。
position=position[position&gt;0].is_largest(10)

report=sim(position ,name="營收動能",upload=False)
report.display()</code></pre>



<p class="has-medium-font-size">程式非常簡單，只有10來行。說明幾個關鍵處。<br>月營收有個關鍵在要注意過年效應，有時候年假在1月、有時在2月中旬前，由於台股多數企業的營運區域都在華人地區，年假通常會停工或減班，如果是在1月過年，訂單常遞延到2月。因此在比較營收時，為了平滑過年效應，我會習慣取近2月平均營收來取代單月營收，不然1、2月若碰到年假，單月營收要創近12月新高的可能性實在太低。</p>



<p class="has-medium-font-size"><br>如果策略要實戰，縮減檔數是必須的，因為多數人沒那麼多資金全買，所以範例簡單用單月月營收來選最後10強。你可能會疑惑為何要寫<code>position[position&gt;0].is_largest(10)</code>，而不是<code>position.is_largest(10)</code>就好？那是因為<code>is_largest(10)</code>會選數值前10高的，若沒有排除不符合營收創高的標的，前10高的數值可能會選到不合條件的，會從股號小的標的開始補到10檔為止。</p>



<p class="has-medium-font-size">此策略的換股週期是用月營收索引，也就是月營收公告截止日，好處是貼近營收因子發酵期。<br>來看看策略的表現，非常不錯，15年來，年化高達 26% ! <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-36.png" alt="newplot 36" class="wp-image-4886" srcset="https://www.finlab.tw/wp-content/uploads/2022/11/newplot-36.png 800w, https://www.finlab.tw/wp-content/uploads/2022/11/newplot-36-300x225.png 300w, https://www.finlab.tw/wp-content/uploads/2022/11/newplot-36-768x576.png 768w" sizes="(max-width: 800px) 100vw, 800px" title="月營收選股｜股價創新高｜新手必學的雙動能策略 53"></figure>



<h2>營收股價雙創高的渦輪效應</h2>



<h3>股價創新高動能</h3>



<p class="has-medium-font-size">營收利多，最怕利多不漲，那很可能是市場早就反應，因此我們的目標是股價與營收連動，一同創高，代表股價的動能和營收創新高的關聯較大，如何寫出好棒棒的股價創新高動能策略，可以看先前的文章「<a href="https://www.finlab.tw/breakthrough_stock_picking_strategies/">突破策略豆知識</a>」，運用FinlabDataframe好用的sustiain方法確認突破強度。<br>程式與回測結果如下：</p>



<pre class="wp-block-code"><code lang="python" class="language-python">from finlab.backtest import sim
from finlab import data
with data.universe(market='TSE_OTC'):
    close = data.get("price:收盤價")
    # 近5日內有3日以上的股價創前200日新高
    position = (close == close.rolling(200).max()).sustain(5,2)
    report = sim(position, resample="M", name="創新高延續動能策略", upload=False)
    report.display()</code></pre>



<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-38.png" alt="newplot 38" class="wp-image-4887" srcset="https://www.finlab.tw/wp-content/uploads/2022/11/newplot-38.png 800w, https://www.finlab.tw/wp-content/uploads/2022/11/newplot-38-300x225.png 300w, https://www.finlab.tw/wp-content/uploads/2022/11/newplot-38-768x576.png 768w" sizes="(max-width: 800px) 100vw, 800px" title="月營收選股｜股價創新高｜新手必學的雙動能策略 54"></figure>



<h3>雙渦輪</h3>



<p class="has-medium-font-size">如果把營收創新高和股價創新高的程式做結合，會發生什麼事？</p>



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

close = data.get('price:收盤價')
vol = data.get('price:成交股數')
rev = data.get('monthly_revenue:當月營收')
rev_yoy_growth = data.get('monthly_revenue:去年同月增減(%)')

# 近2月平均營收
rev_ma = rev.average(2)

# 近2月平均營收創12個月來新高
condition1 = rev_ma == rev_ma.rolling(12, min_periods=6).max()
# 近5日內有2日股價創新高
condition2 = (close == close.rolling(200).max()).sustain(5,2)
# 近五日成交均量大於500張
condition3 = vol.average(5) &gt; 500*1000
conditions = condition1 &amp; condition2 &amp; condition3

# 符合選股條件的名單中，再選出單月營收年增率前10強，並在營收公告截止日換股。
position= rev_yoy_growth*conditions

position=position[position&gt;0].is_largest(10).reindex(rev.index_str_to_date().index, method='ffill')

# 設定position_limit避免重壓
report = sim(position=position,stop_loss=0.2,take_profit=0.8, position_limit=0.25, fee_ratio=1.425/1000*0.3,name="營收股價雙渦輪",upload=False)
report.display()</code></pre>



<p class="has-medium-font-size">上面程式要注意的小地方是有加上流動性條件，只買近五日成交均量大於500張的標的，避免太冷門的標的很難入手。由於月營收創高和股價創高的條件交集後，會轉成日週期索引，若要使用月營收截止日換股，必須要做reindex的動作，<code>rev.index_str_to_date</code> 會將月營收文字格式日期轉成月營收公告截止日，例如 2022-M10 變成 2022-11-11。<br><br>最後為避免重壓標地，設定position_limit=0.25，代表單擋持股上限為25%，避免只選到1-2檔全壓的大波動狀況。如果偏好降低波動，也可調成0.1，如此一來若只選到4檔標的，總持股比例只會有40%，在熊市時由於創新高標的本來就少，因此持股比例自然降低，具自然避險躲空頭的效果。<br><br>停損不建議設定小，此策略波動較大，設太小容易被洗掉。最後來看看加乘的效果吧！<br>15年來年化報酬37%！夏普率1.3，幾乎每一年都獲利，比前述單因子選股的表現優異許多，熊市年 2022 竟然還有16%正報酬，以條件這麼簡單的策略來說，算是很神的成績！</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-39.png" alt="newplot 39" class="wp-image-4888" srcset="https://www.finlab.tw/wp-content/uploads/2022/11/newplot-39.png 800w, https://www.finlab.tw/wp-content/uploads/2022/11/newplot-39-300x225.png 300w, https://www.finlab.tw/wp-content/uploads/2022/11/newplot-39-768x576.png 768w" sizes="(max-width: 800px) 100vw, 800px" title="月營收選股｜股價創新高｜新手必學的雙動能策略 55"></figure>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="654" src="https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-16-下午12.47.28-e1668593619128-1024x654.png" alt="截圖 2022 11 16 下午12.47.28 e1668593619128" class="wp-image-4885" srcset="https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-16-下午12.47.28-e1668593619128-1024x654.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-16-下午12.47.28-e1668593619128-300x192.png 300w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-16-下午12.47.28-e1668593619128-768x491.png 768w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-16-下午12.47.28-e1668593619128.png 1396w" sizes="(max-width: 1024px) 100vw, 1024px" title="月營收選股｜股價創新高｜新手必學的雙動能策略 52"></figure>



<h2>結論</h2>



<p class="has-medium-font-size"><a href="https://colab.research.google.com/drive/1qp-5ZPtJXFIc6x4EkCJezzMcwpFdc5jY?usp=sharing" target="_blank" rel="noopener">colab 範例</a><br><a href="https://ai.finlab.tw/strategyview/?uid=TJN4FDuqrwU8DML7DAjUYFIMutp2&amp;sid=%E7%87%9F%E6%94%B6%E8%82%A1%E5%83%B9%E9%9B%99%E6%B8%A6%E8%BC%AA" target="_blank" rel="noopener">量化平台部署範例</a><br>簡單卻很有實戰性，這就是FinLab與其他地方不同之處，不走太學術的路線，考慮實戰面，除了完整公開程式碼，還跟你講策略背後的思維。<br>此策略當然還有優化的空間～但這就是大家各自的功課了，Ben 把最核心的條件交給你了，一起去找股海的大秘寶吧！</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/revenue_and_price_engine_strategy/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">4884</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指數 57"></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指數 58"></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指數 59"></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指數 60"></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指數 61"></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指數 62"></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爬蟲教學｜台股數據｜集保戶股權分散表</title>
		<link>https://www.finlab.tw/python_crawler_tdcc_inventory/</link>
					<comments>https://www.finlab.tw/python_crawler_tdcc_inventory/#respond</comments>
		
		<dc:creator><![CDATA[Ben]]></dc:creator>
		<pubDate>Wed, 09 Nov 2022 04:44:46 +0000</pubDate>
				<category><![CDATA[Python新手教學]]></category>
		<category><![CDATA[投資新手]]></category>
		<category><![CDATA[財經PYTHON教學]]></category>
		<category><![CDATA[爬蟲]]></category>
		<category><![CDATA[集保]]></category>
		<guid isPermaLink="false">https://www.finlab.tw/?p=4834</guid>

					<description><![CDATA[籌碼數據豐富是台股一大特色~
集保餘額可以幫助我們判斷不同持股分級的持股者間的資金流動變化，每週公佈的特性可當較同步的指標，也減低日週期資料如「分點籌碼」的雜訊。
分析前得先要有資料，讓我們開始執行我們的Python爬蟲吧！]]></description>
										<content:encoded><![CDATA[
<p class="has-medium-font-size">籌碼數據豐富是台股一大特色，像美國只有「每季」公告的 13F 報告揭露大機構(資產管理規模超過 1 億美元)的資金動向，且截止申報日是每個季度 (三個月) 結束之後的 45 天之內，實在落後太久，很難當即時指標。<br>但台股則是有日週期的「法人買賣超」、「融資融券」、「借還券」、「當沖」、「分點券商進出」&#8230;，週週期的則有本篇要抓的「集保戶股權分散表」、月週期則有「董監內部人持股變動與質押」，可說有許多工具可分析籌碼。<br>集保餘額可以幫助我們判斷不同持股分級的持股者間的資金流動變化，每週公佈的特性可當較同步的指標，也減低日週期資料如「分點籌碼」的雜訊。<br>分析前得先要有資料，讓我們開始執行我們的Python爬蟲吧！</p>



<h2>資料源</h2>



<p class="has-medium-font-size"><a href="https://www.tdcc.com.tw/portal/zh/about/about" target="_blank" rel="noopener">台灣集中保管結算所</a> 簡單說就是統計籌碼的單位，服務項目包括有價證券集中保管帳簿劃撥、集中交易及櫃檯買賣市場有價證券交割、興櫃股票款券結算交割、期貨結算電腦處理、無實體有價證券登錄、參加人有價證券電腦帳務處理等，並接受金融監督管理委員會證券期貨局委託辦理股務查核作業。</p>



<p class="has-medium-font-size">「<a href="https://www.tdcc.com.tw/portal/zh/smWeb/qryStock" target="_blank" rel="noopener">集保戶股權分散表</a>」是官方公開資料，每週六早上有新數據，資料查詢分兩種，一種是單一標的歷史資料查詢 (資料僅1年份) ; 另一種是總表查詢，可以一次抓全部資料，要注意總標指提供單週資料。所以若要歷史數據得自己每一檔慢慢搜集，或參考 <a href="https://ai.finlab.tw/database#inventory" target="_blank" rel="noopener">FinLab 資料庫</a>。</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="647" src="https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-09-上午11.06.43-1024x647.png" alt="截圖 2022 11 09 上午11.06.43" class="wp-image-4835" srcset="https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-09-上午11.06.43-1024x647.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-09-上午11.06.43-300x190.png 300w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-09-上午11.06.43-768x485.png 768w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-09-上午11.06.43-1536x971.png 1536w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-09-上午11.06.43-2048x1294.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="Python爬蟲教學｜台股數據｜集保戶股權分散表 63"></figure>



<h2>Python爬蟲程式範例</h2>



<p class="has-medium-font-size">「集保戶股權分散表」爬蟲的資料處理細節見註解。</p>



<pre class="wp-block-code"><code lang="python" class="language-python">def crawl():
    
    # 將網站回傳資料轉到 read_csv 解析，加入 headers 的功能為防止反爬蟲辨識，官方有時會擋 
    headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_1\
    0_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} 
    res = requests.get("https://smart.tdcc.com.tw/opendata/getOD.ashx?id=1-5", headers=headers)
    df = pd.read_csv(StringIO(res.text))
    df = df.astype(str)
    df = df.rename(columns={
        '證券代號': 'stock_id',
        '股數': '持有股數', '占集保庫存數比例%': '占集保庫存數比例'
    })
    
    # 移除「公債」相關的id
    debt_id = list(set([i for i in df['stock_id'] if i[0] == 'Y']))
    df = df[~df['stock_id'].isin(debt_id)]
    
    # 官方有時會有不同格式誤傳，做例外處理
    if '占集保庫存數比例' not in df.columns:
        df = df.rename(columns={'佔集保庫存數比例%': '占集保庫存數比例'})
        
    # 持股分級=16時，資料都為0，要拿掉
    df = df[df['持股分級'] != '16']
    
    # 資料轉數字
    float_cols = ['人數', '持有股數', '占集保庫存數比例']
    df[float_cols] = df[float_cols].apply(lambda s: pd.to_numeric(s, errors="coerce"))
    
    # 抓表格上的時間資料做處理
    df['date'] = datetime.datetime.strptime(df[df.columns[0]][0], '%Y%m%d')
    
    #只要第二層欄位名稱
    df = df.drop(columns=df.columns[0])
    
    # 索引設置 unique index
    df = df.set_index(['stock_id', 'date', '持股分級'])
    return df</code></pre>



<h3>輸出格式</h3>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="941" src="https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-09-上午11.44.52-1024x941.png" alt="截圖 2022 11 09 上午11.44.52" class="wp-image-4836" srcset="https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-09-上午11.44.52-1024x941.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-09-上午11.44.52-300x276.png 300w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-09-上午11.44.52-768x706.png 768w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-09-上午11.44.52.png 1537w" sizes="(max-width: 1024px) 100vw, 1024px" title="Python爬蟲教學｜台股數據｜集保戶股權分散表 64"><figcaption>Python爬蟲輸出結果</figcaption></figure>



<h2>未來開發</h2>



<p class="has-medium-font-size">Python爬蟲蒐集完資料後，我們就可以用資料來撰寫策略或做資料視覺化～究竟「集保戶股權分散表」有沒有用？讓我們繼續看下去。<br>了解更多 <a href="https://www.finlab.tw/?s=%E7%88%AC%E8%9F%B2">爬蟲實做</a> ～</p>



<p></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/python_crawler_tdcc_inventory/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">4834</post-id>	</item>
		<item>
		<title>Python爬蟲教學｜ 財經數據｜台灣貨幣總計數 M1B &#038; M2</title>
		<link>https://www.finlab.tw/tw_monetary_aggregates_m1b_crawler/</link>
					<comments>https://www.finlab.tw/tw_monetary_aggregates_m1b_crawler/#respond</comments>
		
		<dc:creator><![CDATA[Ben]]></dc:creator>
		<pubDate>Thu, 03 Nov 2022 01:43:39 +0000</pubDate>
				<category><![CDATA[財經PYTHON教學]]></category>
		<category><![CDATA[總體經濟]]></category>
		<category><![CDATA[m1b]]></category>
		<category><![CDATA[PYTHON]]></category>
		<category><![CDATA[主計處]]></category>
		<category><![CDATA[台灣]]></category>
		<category><![CDATA[央行]]></category>
		<category><![CDATA[爬蟲]]></category>
		<category><![CDATA[貨幣總計數]]></category>
		<guid isPermaLink="false">https://www.finlab.tw/?p=4792</guid>

					<description><![CDATA[全球經濟面臨空頭襲擊，資金行情被美國聯準會升息潮打擊，很多人說 2022 是總經盤， 牛市階段，個股棒棒開花，投資人反倒覺得總經不夠靈敏，而現今熊市時刻，覆巢之下無完卵 ，投資人開始注意總經的影響力。市面上有不錯的總經平台，如「財經Ｍ平方」提供數據圖表，可惜沒提供財經數據API的服務，若要使用總經數據，還是得自己想辦法，所幸有Python爬蟲可以幫我們解決需求。貨幣總計數M1B和M2象徵「流動資金」與「保守資金」的消長，或能幫助資金行情判斷，這篇文章將示範如何爬取M1B和M2的年增率。]]></description>
										<content:encoded><![CDATA[
<p class="has-medium-font-size">全球經濟面臨空頭襲擊，資金行情被美國聯準會升息潮打擊，很多人說 2022 是總經盤， 牛市階段，個股棒棒開花，投資人反倒覺得總經不夠靈敏，而現今熊市時刻，覆巢之下無完卵 ，投資人開始注意總經的影響力。市面上有不錯的總經平台，如「<a href="https://www.macromicro.me/collections/11/tw-gdp-relative/133/tw-m1b-m2" target="_blank" rel="noopener">財經Ｍ平方</a>」提供數據圖表，可惜沒提供財經數據API的服務，若要使用總經數據，還是得自己想辦法，所幸有Python爬蟲可以幫我們解決需求。貨幣總計數M1B和M2象徵「流動資金」與「保守資金」的消長，或能幫助資金行情判斷，這篇文章將示範如何爬取M1B和M2的年增率。</p>



<h2>財經數據資料源</h2>



<p class="has-medium-font-size">貨幣總計數的資料最源頭來自台灣<a href="https://www.cbc.gov.tw/tw/lp-302-1.html" target="_blank" rel="noopener">中央銀行的新聞稿</a>，每月23-30號間發布「<a href="https://www.cbc.gov.tw/tw/cp-302-155810-06170-1.html" target="_blank" rel="noopener">上月金融狀況</a>」，頁內有M1B和M2的年增率的表格資料。然而新聞稿區的早期資料不是那麼完全，網頁格式也變動多次，如果要在此爬蟲所有歷史資料，並非最佳解。</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="622" src="https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-03-上午8.25.25-1024x622.png" alt="截圖 2022 11 03 上午8.25.25" class="wp-image-4793" srcset="https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-03-上午8.25.25-1024x622.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-03-上午8.25.25-300x182.png 300w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-03-上午8.25.25-768x466.png 768w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-03-上午8.25.25-1536x933.png 1536w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-03-上午8.25.25-2048x1244.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="Python爬蟲教學｜ 財經數據｜台灣貨幣總計數 M1B &amp; M2 65"><figcaption>央行每月金融情況新聞稿</figcaption></figure>



<p class="has-medium-font-size"><br>所幸 <a href="https://www.dgbas.gov.tw/point.asp?index=10" target="_blank" rel="noopener">行政院主計處</a> 也有M1B和M2的數據，而且看來是可以一次抓下JS圖表內的所有數據，會比央行省事省力的許多。然而不幸的是此資料並非完美，現在都已經2022/11/3了，主計處資料還停在8月數據，但中央銀行早在10/24就發布了，怎麼更新同步基調差那麼多？如果是10/31前公佈都還好，拖到11月就真的太慢了。<br>所以我們需要兩個Python爬蟲，一個爬主計處的財經數據歷史資料。一個爬中央銀行當月的貨幣總計數，作為之後更新最新資料使用。</p>



<h2>主計處Python爬蟲</h2>



<p class="has-medium-font-size">爬蟲開發的第一步是觀察網頁結構，如果資料是以html的table來呈現，那是用pandas的read_html，就非常好解析，據經驗，80％情況都是如此。然而如果不是table，就比較麻煩，若財經數據有直接渲染在網頁，可以用 Beatifulsoup 解析整份 html 檔，再定位標籤抓資料。<br>可以看到 <a href="https://www.dgbas.gov.tw/point.asp?index=10" target="_blank" rel="noopener">行政院主計處</a> 的最新M1B數據是7.55，我們可以在Chrome瀏覽器按右鍵選擇檢查，搜尋「7.55」放在哪邊？之後可以發現7.55出現在4個地方，然而table內只有一筆資料，由於我們要抓到歷史資料是放在圖表，圖表資料一般都放在&lt;scripttype type=&#8221;text/javascript&#8221;>標籤裡的變數，經過搜尋發現我們要把chartValue變數內的資料解析出來。</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="682" src="https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-03-上午8.26.47-1024x682.png" alt="截圖 2022 11 03 上午8.26.47" class="wp-image-4794" srcset="https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-03-上午8.26.47-1024x682.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-03-上午8.26.47-300x200.png 300w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-03-上午8.26.47-768x511.png 768w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-03-上午8.26.47-1536x1022.png 1536w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-03-上午8.26.47-2048x1363.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="Python爬蟲教學｜ 財經數據｜台灣貨幣總計數 M1B &amp; M2 66"><figcaption>行政院主計處M1B年增率</figcaption></figure>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="490" src="https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-03-上午8.38.35-1024x490.png" alt="截圖 2022 11 03 上午8.38.35" class="wp-image-4795" srcset="https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-03-上午8.38.35-1024x490.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-03-上午8.38.35-300x143.png 300w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-03-上午8.38.35-768x367.png 768w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-03-上午8.38.35-1536x734.png 1536w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-03-上午8.38.35-2048x979.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="Python爬蟲教學｜ 財經數據｜台灣貨幣總計數 M1B &amp; M2 67"></figure>



<h3>Python爬蟲程式範例</h3>



<p class="has-medium-font-size">流程和細節看程式註解，重點在BeautifulSoup網頁解析，和pandas如何產生目標時間序列。下列幾個要熟悉的工具說明。</p>



<ul class="has-medium-font-size"><li><a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/" target="_blank" rel="noopener">BeautifulSoup</a></li><li><a href="https://pandas.pydata.org/docs/reference/api/pandas.date_range.html" target="_blank" rel="noopener">pandas.date_range</a></li><li><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.tseries.offsets.MonthEnd.html" target="_blank" rel="noopener">pandas.tseries.offsets.MonthEnd</a></li></ul>



<pre class="wp-block-code"><code lang="python" class="language-python">from bs4 import BeautifulSoup
import pandas as pd
import requests
from datetime import datetime


def crawl_history_from_dgbas():
    # 抓下網頁回傳資料
    response = requests.get('https://www.dgbas.gov.tw/point.asp?index=10')
    # 解析網頁
    parsed_file = BeautifulSoup(response.text)
    # 找出javascript區塊
    js_text = parsed_file.find_all('script', type="text/javascript")
    # 抓財經數據定位，資料為餘第3個javascript
    data = js_text[3].string

    # 文字資料定位，擷取數據部分，將js的日期型態Date.UTC取代成空白
    m1b = data[data.index('chartValue[6]') + len('chartValue[6]='):data.index(';\r\nchartValue[7]')].replace(
        'Date.UTC', '')
    # 將文字轉陣列
    eval_m1b = eval(m1b)
    # 取出數值，迴圈內d變數已被轉成空白，無意義
    m1b_values = [v for d, v in eval_m1b]

    # 重複上述動作，觀察chartValue內陣列定位，抓出M2數據
    m2 = data[data.index('chartValue[7]') + len('chartValue[7]='):data.index(';\r\nchartValue[8]')].replace(
        'Date.UTC', '')
    eval_m2 = eval(m2)
    m2_values = [v for d, v in eval_m2]
    
    # 日期處理，由於無法抓到即時公告日期，且央行公告日前每月不定，都在每月25號左右公告上月數據，為作業方便，目標將日期設為每月最後一天
    # 取出陣列內起始日期、結束日期
    start_date = eval_m1b[0][0]
    end_date = eval_m1b[-1][0]
    # 將日期格式轉為 pandas date_range 的參數格式，產生每月日期序列
    start = f'{start_date[0]}-{start_date[1]}-{start_date[2]}'
    end = f'{end_date[0]}-{end_date[1] + 1}-{end_date[2]}'
    # 日期序列為每月1日，為產生本月底公告去年數據的效果，使用tseries.offsets將日期後推
    dates = pd.date_range(start, end, freq='M') + pd.tseries.offsets.MonthEnd(2)
    
    # 產生m1b與m2數據，將數據併表
    m1b_df = pd.DataFrame({'stock_id': '貨幣總計數M1B', 'date': dates, '年增率(%)': m1b_values})
    m2_df = pd.DataFrame({'stock_id': '貨幣總計數M2', 'date': dates, '年增率(%)': m2_values})
    concat_df = pd.concat([m1b_df, m2_df])
    concat_df = concat_df.set_index(['stock_id', 'date'])
    return concat_df</code></pre>



<p></p>



<h3>Python爬蟲輸出結果</h3>



<figure class="wp-block-image size-full"><img loading="lazy" width="534" height="618" src="https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-03-上午9.08.26.png" alt="截圖 2022 11 03 上午9.08.26" class="wp-image-4796" srcset="https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-03-上午9.08.26.png 534w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-03-上午9.08.26-259x300.png 259w" sizes="(max-width: 534px) 100vw, 534px" title="Python爬蟲教學｜ 財經數據｜台灣貨幣總計數 M1B &amp; M2 68"></figure>



<h2>中央銀行Python爬蟲</h2>



<p class="has-medium-font-size">這個爬蟲要分兩步驟，首先由於每月金融情況新聞稿的連結沒有規律，所以要先解析<a href="https://www.cbc.gov.tw/tw/lp-302-1.html" target="_blank" rel="noopener">最新消息的>新聞稿的首頁</a>，取出近月新聞稿的超連結，再將連結傳到 python requests 取得表格數據，之後再將資料稍微整理成前面主計處爬蟲的資料格式。<br>另外要注意若每月25號前就執行此爬蟲，可能會有當月資料還沒公告的問題，所以要加上例外狀況處理，回傳一個空的dataframe。</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="948" src="https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-03-上午9.24.01-1024x948.png" alt="截圖 2022 11 03 上午9.24.01" class="wp-image-4797" srcset="https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-03-上午9.24.01-1024x948.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-03-上午9.24.01-300x278.png 300w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-03-上午9.24.01-768x711.png 768w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-03-上午9.24.01-1536x1422.png 1536w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-03-上午9.24.01.png 1657w" sizes="(max-width: 1024px) 100vw, 1024px" title="Python爬蟲教學｜ 財經數據｜台灣貨幣總計數 M1B &amp; M2 69"></figure>



<h3>Python爬蟲程式範例</h3>



<pre class="wp-block-code"><code lang="python" class="language-python">def central_bank_crawl():
    
    # 資料目標日期，轉成民國型態的上月日期
    now = datetime.now()
    year = now.year - 1911
    month = (now.month + 10) % 12 + 1
    if month == 12:
        year -= 1
    
    # 解析出最新消息內近月金融情況新聞稿的超連結
    menu_response = requests.get('https://www.cbc.gov.tw/tw/lp-302-1.html')
    parsed_file = BeautifulSoup(menu_response.text)
    text = parsed_file.find('a', title=f"{year}年{month}月金融情況")

    # 沒資料則回傳空表
    if text is None:
        return pd.DataFrame()

    # 取出超連結
    href = text['href']
    
    # read_html 解析表格數據
    report_response = requests.get(f'https://www.cbc.gov.tw/{href}')
    report_df = pd.read_html(report_response.text)[0]
    report_df.columns = report_df.columns.get_level_values(1)
    report_df = report_df.iloc[:, :3]
    report_df = report_df.rename(columns={'項 目': 'stock_id', '年增率': '年增率(%)'})
    report_df = report_df[['stock_id', '年增率(%)']]
    report_df['date'] = datetime(now.year, now.month, 1) + pd.tseries.offsets.MonthEnd(1)
    report_df = report_df.set_index(['stock_id', 'date'])
    return report_df
</code></pre>



<p></p>



<h2>結論</h2>



<p class="has-medium-font-size"><a href="https://colab.research.google.com/drive/1RIp8diM2WQ2NFjVFGiS9fr3etoavqvB0?usp=sharing" target="_blank" rel="noopener">colab程式範例</a><br>這個爬蟲和證交所那類好爬的表格與穩定資料相比，有一些要注意的坑，處理上也比較多層，所以特別記錄一下。行政院主計處和央行還有許多總經數據，如果你有需求，可以自己用上述範例練習抓抓看，或直接使用 <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">FinLab資料庫</a> 來抓喔。</p>



<p class="has-medium-font-size">如果你對爬蟲想知道更多，可參考我們其他教學文章</p>



<p class="has-medium-font-size"><a href="https://www.finlab.tw/%e8%b6%85%e7%b0%a1%e5%96%ae%e5%8f%b0%e8%82%a1%e6%af%8f%e6%97%a5%e7%88%ac%e8%9f%b2%e6%95%99%e5%ad%b8/">超簡單台股每日爬蟲教學</a><br><a href="https://www.finlab.tw/%e8%b6%85%e7%b0%a1%e5%96%ae%e7%94%a8python%e6%8a%93%e5%8f%96%e6%af%8f%e6%9c%88%e7%87%9f%e6%94%b6/">超簡單用python抓取每月營收</a><br><a href="https://www.finlab.tw/%e4%b8%89%e5%a4%a7%e6%b3%95%e4%ba%ba%e7%88%ac%e8%9f%b2/">三大法人爬蟲：Python實作教學</a><br><a href="https://www.finlab.tw/%e7%b0%a1%e5%96%aepython%e4%b8%8a%e6%ab%83%e8%b3%87%e6%96%99%e7%88%ac%e8%9f%b2%e5%af%a6%e5%81%9a/">python上櫃資料爬蟲輕鬆做</a><br><a href="https://www.finlab.tw/python-%e8%b2%a1%e5%a0%b1%e7%88%ac%e8%9f%b2-1-%e7%b6%9c%e5%90%88%e6%90%8d%e7%9b%8a%e8%a1%a8/">財報爬蟲超簡單 – 用Python一次抓綜合損益、資產負債、營利分析</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/tw_monetary_aggregates_m1b_crawler/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">4792</post-id>	</item>
	</channel>
</rss>
