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

<channel>
	<title>生產力 &#8211; FinLab</title>
	<atom:link href="https://www.finlab.tw/category/%E7%94%9F%E7%94%A2%E5%8A%9B/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.finlab.tw</link>
	<description>深入淺出的量化投資，讓你在在茫茫股海中，找到專屬於自己的投資方法</description>
	<lastBuildDate>Fri, 25 Aug 2023 02:00:36 +0000</lastBuildDate>
	<language>zh-TW</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.0.9</generator>

<image>
	<url>https://www.finlab.tw/wp-content/uploads/2020/07/favicon.png</url>
	<title>生產力 &#8211; FinLab</title>
	<link>https://www.finlab.tw</link>
	<width>32</width>
	<height>32</height>
</image> 
<site xmlns="com-wordpress:feed-additions:1">179699571</site>	<item>
		<title>反思菲式思考 Part.1｜關鍵交易思維的啟發</title>
		<link>https://www.finlab.tw/phcebus-thinking-report-part1/</link>
					<comments>https://www.finlab.tw/phcebus-thinking-report-part1/#respond</comments>
		
		<dc:creator><![CDATA[Ben]]></dc:creator>
		<pubDate>Thu, 24 Aug 2023 04:26:50 +0000</pubDate>
				<category><![CDATA[投資新手]]></category>
		<category><![CDATA[FinLab 量化平台]]></category>
		<category><![CDATA[Python新手教學]]></category>
		<category><![CDATA[生產力]]></category>
		<category><![CDATA[股票策略]]></category>
		<category><![CDATA[事件交易]]></category>
		<category><![CDATA[交易思維]]></category>
		<category><![CDATA[菲式思考]]></category>
		<category><![CDATA[閱讀心得]]></category>
		<guid isPermaLink="false">https://www.finlab.tw/?p=5496</guid>

					<description><![CDATA[菲式思考 是近期非常火紅的財經書籍，想不到上市第一天就被秒殺，在出版業不景氣的現在十分罕見，可見「菲比斯」人氣 [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p class="has-medium-font-size"><a href="https://www.eslite.com/product/10012013192682417909008" target="_blank" rel="noopener">菲式思考</a> 是近期非常火紅的財經書籍，想不到上市第一天就被秒殺，在出版業不景氣的現在十分罕見，可見「菲比斯」人氣之高。<br>Ben 編在近期才收到書，閱讀完後有些啟發，將結合自身的交易經驗，撰寫數篇心得。<br>第 1 篇會聚焦在「菲式思考」第1~4章，關於交易員思維的部分。<br>第 2 篇會將「菲式思考」第 5 章關於量化策略的部分做一個量化分析總評與策略設計概論。<br>我想很多人看完書後也不知道如何實作，所以第 3 篇後會使用 FinLab 開發工具實作驗證、優化「菲式策略」的程式碼，教大家怎麼優化他人的策略成為適合自己的策略。</p>



<h2>菲比斯的崛起</h2>



<p class="has-medium-font-size">菲比斯是生物技術學歷出身，近 30 歲時投入券商工作，擔任期貨與證券從業人員，關鍵的交易歷程在 2013~2015年，花 3 年從 10 萬本金成長到 1000 萬的規模，十分驚人，資金到一定規模後離職，成為全職交易人。<br>初期由於低薪和本金不多，有靠信貸取代券商融資的高利率，操作股票期貨、週選擇權來擴大槓桿。<br>以上槓桿操作是否適合投資新手？有待思量～第一步的容錯率低，壓力大，如果用最低保證金壓滿小資金，稍不慎就會被清空帳戶，還會面臨欠債風險，進入賭徒輪迴。必須有一定交易實力、心理素質，對風險有所認知才適合此套方法，菲比斯也是在2013年以前花了幾年摸索，如果你是新手，無法承受槓桿的壓力，也對短期交易的勝率沒自信，可以參考「<strong><a href="https://www.finlab.tw/low_price_strategy_tw_stock/">給小資族的禮物｜低價股量化策略的實戰訣竅</a></strong>」一文，提供比較保守的做法。</p>



<h2>股票期貨的推薦</h2>



<p class="has-medium-font-size">「菲比斯」交易市場聚焦在台股，交易商品遍及上市櫃、 興櫃股票、股票期貨、台期指、選擇權、可轉換公司債資產交換 CBAS，不太碰權證與現股當沖。交易週期偏短。<br>其最推薦以股票期貨當作台股主要操作工具，如果標地有股期，就買股期，如果沒股期或股期流動性太低，才買現股。<br>股期優點是交易稅費低，具7.5倍左右的槓桿，方便資金調度，可多可空，且交易時段比較長，有機會領先現股先佈局。<br>股期空單的好處在沒融券強制回補的限制，也不用付借券費，是相當好的做空工具。另外股期多單也可替代存股操作，省去股利所得稅的問題。<br>股期缺點在標地只有200檔上下，其中有足夠交易流動性的，可能不到100檔，所以若策略以中小型股為主，可能很難在此工具佈局。<br>「菲式思考」贏的第一步重要思維挑選「低成本的工具、資金」來操作，還沒入市，選對工具就先贏在起跑點，反過來說滿共同基金的人，一開始就先輸「管理費3%」。</p>



<h2>成為全職投資人的標準</h2>



<p class="has-medium-font-size">「你必須掌握風險、穩定地賺錢，持續兩年賺的錢比原先工作所賺的高兩三倍。」(菲式思考：p.107)，其實這是比較鬆的標準了，更嚴謹的要求是要走過一個景氣循環(5~10年)，驗證自己在系統風險下的存活率。再來如果是高薪職業，如醫生、工程師，靠投資要賺到比原先工作高兩三倍，除非投入本金很高，不然很難達標，放棄工作的機會成本挺高的，高薪族群比較適合靠本業搭配保守的投資。<br>另一面思考，本業非高薪的人是否較適合投入全職投資？我認為既然行業有天花板，那投資交易確實是沒有上限的地方，靠工作薪資存到100萬容易，但要累積到千萬以上，又不想等很久，就難了，確實要靠投資來衝。<br>若本金太少，也很難做好基本的持股分散、多空雙向策略佈局。<br>以年薪36 萬來說，2~3 倍是 72~108 萬，以全職主動投資人50% 報酬率的水準，至少要累積到150~200萬的資金再考慮全職，你說沒有操作的頭期款怎麼辦？存頭期款、工作的期間就是你最好學習投資知識、認識風險的時候，才不會書到用時方恨少，到時輸一屁股。<br>另外你最好要有一個覺悟，要有隨時可以回職場的能力，讓你「全職投資人」失敗時，還有能力生存下去。</p>



<h2>菲式交易邏輯的啟發</h2>



<ul class="has-medium-font-size"><li>挑選成長性展望好、評價不太高的股票做多單。基本面與產業面為主，技術面與籌碼面為輔。</li><li>挑選未來展望不佳的股票做空，平衡部位趨向，有機會再大盤回檔時，降低整體資產回檔。</li><li>依營收、財報、法說會、產業新聞來追蹤標的展望，認為合理的獲利點達到，逐步出場，若展望不如預期，則不計結果出場。</li><li>多單與空單的比例隨整體大盤市況調整。</li><li>利用營收、財報公佈時程、股票期貨換月轉倉來調整持股組合。</li><li>分散投資，不要重注單押。</li></ul>



<p class="has-medium-font-size">以上內容參考書中 p.121 的部分。<br>在 FinLab 策略監控台上有基本面策略如「<a href="//ai.finlab.tw/strategyview/?uid=TJN4FDuqrwU8DML7DAjUYFIMutp2&amp;sid=營收股價雙渦輪">營收股價雙渦輪</a>」、「<a class="" 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>」，也有產業面的策略「<a class="" href="https://ai.finlab.tw/strategyview/?uid=TJN4FDuqrwU8DML7DAjUYFIMutp2&amp;sid=%E5%A4%9A%E7%94%A2%E6%A5%AD%E5%83%B9%E6%8A%95" target="_blank" rel="noopener">多產業價投&nbsp;</a>」，與菲式思考的基本面策略類似。<br><br> FinLab 比較缺少「事件型」與「做空避險」的策略，原因在「事件型」很難搜集到完整的各媒體的歷史新聞資料，法說會影音與簡報分析比數值資料複雜、混亂，但若不要求回測功能，而是將功能定位設定在讓 AI 學習菲比斯的解讀思維，下提示字 (Prompt) 讓 AI 變專業分析師，撥絲抽繭出新聞事件的關聯標地，增加質化分析的效率也是很有價值的，目前 ChatGPT 甚至能做到語音分析的功能，書中提到判斷公司內部人在法說會的語氣和表情，應都可用 AI 快速、大量處理，也許未來 FinLab 會有相關服務上線。<br>如果要做回測，目前公開資訊觀測站的重訊公告是比較完整的資料，可應用於策略開發。<br>另外菲比斯多看的是國內財經媒體的新聞，但若要看總經或國際金融，其實是要看過外媒體才有「<strong>夠快的時效性</strong>」，等國內翻譯外電太慢了，如Bloomberg、WSJ、CNBC，部分網站也提供 RSS 訂閱功能，很方便能下載資料供 AI 找出精華。<br><br>做空的回測由於過去10年是大多頭，很難找到績效漂亮的空方策略，但菲比斯提供幾個方向，例如增資股出籠、可轉債大量轉換、內部人申報轉讓就是一個可研究的方向，當市場籌碼供需出現嚴重的不平衡時，就有大行情出現。<br><br>未來 FinLab 會增加策略的豐富性，尤其是「事件型」、「做空避險」、「逆勢交易」的策略，增加策略佈局的平衡度。</p>



<h2>產業面選股的解析</h2>



<p class="has-medium-font-size">每個產業都有關鍵指標。</p>



<ul class="has-medium-font-size"><li>電力供應產業要追蹤「政府標案」。</li><li>營建業要追「合約負債」、「建案完工入帳時間點」。</li><li>設備業要追「合約負債」、「裝機驗收時間點」。</li><li>新藥要追「解盲時程」、「競品研發上市進度」。</li><li>電腦板要追「加密貨幣走勢」、「國外指標大廠財測與新品」。</li><li>航運要追「新船下水」、「重大景氣循環事件」。</li><li>金融業要看資產負債表，損益表是給外行看的。</li></ul>



<h2>撰寫交易日誌</h2>



<p class="has-medium-font-size">我認為書中第 235~239 頁交易日誌撰寫的部分除了抒發交易情緒外，更重要的是要寫下如何改進這些缺失？才能避免重蹈覆徹，這是書中缺漏的部分，稍可惜。<br>策略要定期驗證，追蹤績效是否與過去偏離，或有關鍵政策、規則改變市場。<br>如果選股進出都是靠量化程式，那交易的缺失就會在執行面，要學會策略驗證 (Validation) 與制定潛在威脅等級表，參考「藍月記事」撰寫的 <a href="https://www.maemfe.org/2020/08/validation.html" target="_blank" rel="noopener">交易人的基本功：驗證 (Validation) 與潛在威脅等級表</a>：</p>



<p class="has-medium-font-size">假設交易策略都沒什麼問題，而差異與缺失若主要來自實際交易的話<br>通常可能來自於四個方面：</p>



<p class="has-medium-font-size">1.&nbsp;<strong>重複發生</strong>的不穩定來源：交易成本的變化<br>2.&nbsp;<strong>偶爾發生</strong>的不穩定來源：價格的跳多、跳空<br>3.&nbsp;<strong>鮮少發生</strong>的不穩定來源：市場突然關閉、券商突然出問題、伺服器出狀況<br>4.&nbsp;<strong>不該發生</strong>的不穩定來源：交易程式的問題、整體風控的問題</p>



<p class="has-medium-font-size">並試著解決處理問題，設定碰到問題時的 SOP。</p>



<h2>結論</h2>



<p class="has-medium-font-size">以上是「菲式思考」第一部分的心得，「菲比斯」台股交易經驗涉獵很廣，提供許多面向的分析方法、交易工具的特性，啟發 Ben 未來開發的規劃。<br>其實很多人的起步都比「菲比斯」要好，他 30 歲才起飛，但很多人 20 歲就展開交易的旅程，不一定要和他一樣追求在10年內暴富，投入全職在嚴苛的交易工作、時刻盯盤與分析盤面。<br>從書中擷取適合自己的路線，照自己的節奏走，將啟發的觀點內化成自己的招式，一樣能走向自己理想的財富目標。</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/phcebus-thinking-report-part1/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">5496</post-id>	</item>
		<item>
		<title>客製化選股策略的回測價格序列 &#124; 比較進出場的時間點特性</title>
		<link>https://www.finlab.tw/customed-tw-stock-backtest-price/</link>
					<comments>https://www.finlab.tw/customed-tw-stock-backtest-price/#respond</comments>
		
		<dc:creator><![CDATA[Ben]]></dc:creator>
		<pubDate>Thu, 17 Aug 2023 05:08:58 +0000</pubDate>
				<category><![CDATA[FinLab 量化平台]]></category>
		<category><![CDATA[生產力]]></category>
		<category><![CDATA[回測價格]]></category>
		<category><![CDATA[客製化]]></category>
		<category><![CDATA[歷史回測]]></category>
		<guid isPermaLink="false">https://www.finlab.tw/?p=5481</guid>

					<description><![CDATA[FinLab Package 目前提供收盤價與開盤價序列的選擇，用來模擬回測的進出場，然而在實務上進行時，你會 [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p class="has-medium-font-size">FinLab Package 目前提供收盤價與開盤價序列的選擇，用來模擬回測的進出場，然而在實務上進行時，你會發現若要貼合回測，只有這兩種選擇的話，不一定能滿足操作上的彈性，造成回測與實彈有落差。這篇教學，會教你分析每一種序列選擇的優劣勢，並客製化地打造更多的回測價格序列選擇</p>



<h2>進出場價格序列的比較</h2>



<p class="has-medium-font-size">不同價格在進出上有不同的意義，整理給大家比較：</p>



<ul class="has-medium-font-size"><li>開盤價：此序列的特性是能在條件發生後，儘早入手，優點在超級利多發酵時，有比較高的機會用市價入手，若使用收盤價遇到漲停，就只能乖乖排隊。<br>缺點是價格的波動大，除了早盤當沖單的進場干擾，在某些特殊情況，例如開盤買在接近漲停，收盤跌停，隔日開盤再跌停，這樣短短一天就有30%的價差。在FinLab日週期的架構下，實際進場回延遲訊號日一天，波動大的時候可能造成巨大滑價風險。</li><li>收盤價：最常使用的回測價格序列，一般法人基金如 MSCI 也喜歡在尾盤大舉進場，使用收盤價是有些優點，像是日與日的波動差距最多只有10%，不像開盤價在特殊波動時會被擊殺，收盤價買進也比較能貼合技術指標K線分析。缺點是遇到強勢開盤鎖死的股票會買不到，碰到量少的冷門股票或本身資金較大，有流動性風險，為了買到一定數量，可能使成本拉高，並在賣出時，遇到賣到芭樂價的窘境。</li><li>收盤價與開盤價的均價：折衷收盤價與開盤價的優缺點，各進出一半，務實選擇。</li><li>最高價與最低價的均價：有些人想要慢慢在盤中佈局，不想集中在開盤與收盤，可以用此價格來模擬可能的最大範圍內的買賣均價。缺點是沒考慮到每個價位有不同成交量，若今日最高價只成交1張，實務上你賣到高價的機率較低。</li><li>成交均價：公式為「成交金額」/「成交股數」，解決「最高價與最低價的均價」未考慮到分價量表的問題，比較能貼合盤中進出場回測的模擬。</li></ul>



<h2>客製化 MarketInfo</h2>



<p class="has-medium-font-size">從<a href="https://doc.finlab.tw/reference/backtest/#finlab.backtest.sim" target="_blank" rel="noopener">回測API文件</a>可以知道，有兩個重要的參數我們需要調整：</p>



<figure class="wp-block-table has-medium-font-size"><table><tbody><tr><td><code>trade_at_price</code></td><td>選擇回測之還原股價以收盤價或開盤價計算，預設為&#8217;close&#8217;。可選&#8217;close&#8217;或&#8217;open&#8217;。<strong>TYPE:</strong>&nbsp;<code>str or pd.DataFrame</code><strong>DEFAULT:</strong>&nbsp;<code>'close'</code></td></tr><tr><td><code>market</code></td><td>可選擇<code>'TW_STOCK', 'CRYPTO'</code>，分別為台股或加密貨幣， 或繼承 finlab.market_info.MarketInfo 開發回測市場類別。<strong>TYPE:</strong>&nbsp;<code>str or MarketInfo</code><strong>DEFAULT:</strong>&nbsp;<code>'AUTO'</code></td></tr></tbody></table></figure>



<p class="has-medium-font-size">當 market 為預設的 <code>'TW_STOCK'</code> 時，程式會操作 <code> TWMarketInfo</code> 物件，此物件只有兩種回測序列選擇，分別是收盤價與開盤價，因此若我們想要多一點的選擇，像是「收盤價與開盤價的均價」、「最高價與最低價的均價」、「成交均價」，就必須繼承 <code> TWMarketInfo</code> 物件，去覆寫 <code>get_price() </code>方法，寫法如下，記得要針對不同序列未還原與還原的價格去寫，系統回測會抓<code> adj=True</code> 的價格來回測，策略面板顯示的進出場價格則使用未還原價格。</p>



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


class CustomedTWMarketInfo(TWMarketInfo):

    @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('price:成交股數')
            
            # 開盤價 or 收盤價 or 最高價 or 最低價
            if trade_at_price in ['open', 'close', 'high', 'low']:
                if adj:
                    table_name = 'etl:adj_'
                    price_name = trade_at_price
                else:
                    table_name = 'price:'
                    price_name = {'open': '開盤價', 'close': '收盤價', 'high': '最高價', 'low': '最低價'}[trade_at_price]

                price = data.get(f'{table_name}{price_name}')
                return price
            
            # 收盤價與開盤價的均價
            if trade_at_price=='close_open_avg':
                if adj:
                    adj_open = data.get('etl:adj_open')
                    adj_close = data.get('etl:adj_close')
                    adj_avg_price = round((adj_open + adj_close)/2,2)
                    return adj_avg_price 
                else:
                    open_ = data.get('price:開盤價')
                    close = data.get('price:收盤價')
                    avg_price = round((open_ + close)/2,2)
                    return avg_price 
            
            # 最高價與最低價的均價
            if trade_at_price=='high_low_avg':
                if adj:
                    adj_high = data.get('etl:adj_high')
                    adj_low = data.get('etl:adj_low')
                    adj_avg_price = round((adj_high + adj_low)/2,2)
                    return adj_avg_price 
                else:
                    high = data.get('price:最高價')
                    low = data.get('price:最低價')
                    avg_price = round((high + low)/2,2)
                    return avg_price 
            
            # 成交均價
            if trade_at_price=='transaction_avg':
                vol = data.get('price:成交股數')
                vol_price = data.get('price:成交金額')
                avg_price = round(vol_price/vol,2)
                if adj:
                    close = data.get('price:收盤價')
                    adj_close = data.get('etl:adj_close')
                    adj_avg_price = adj_close/close*avg_price
                    return adj_avg_price
                else:
                    return avg_price


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



<h2>客製化回測價格套入策略</h2>



<p class="has-medium-font-size">接著我們就可將寫好的 <code>CustomedTWMarketInfo </code>放入本益成長比的策略做測試，並使用「成交均價」來做價格回測。</p>



<h3>範例代碼</h3>



<pre class="wp-block-code"><code lang="python" class="language-python"># 本益成長比策略
def peg_strategy(trade_at_price='close'):
    pe = data.get('price_earning_ratio:本益比')
    rev = data.get('monthly_revenue:當月營收')
    rev_ma3 = rev.average(3)
    rev_ma12 = rev.average(12)
    營業利益成長率 = data.get('fundamental_features:營業利益成長率')
    peg = (pe/營業利益成長率)
    cond1 = rev_ma3/rev_ma12&gt;1.1
    cond2 = rev/rev.shift()&gt;0.9
    cond_all = cond1 &amp; cond2
    result = peg*cond_all
    position = result[result&gt;0].is_smallest(10).reindex(rev.index_str_to_date().index, method='ffill')
    report = sim(position, fee_ratio=1.425/1000/3, stop_loss=0.1, market=CustomedTWMarketInfo(), trade_at_price=trade_at_price, name=trade_at_price,upload=False)
    return report 


r = peg_strategy(trade_at_price='transaction_avg')
r.display()</code></pre>



<h3>回測結果</h3>



<figure class="wp-block-image size-large"><img width="1024" height="777" src="https://www.finlab.tw/wp-content/uploads/2023/08/截圖-2023-08-17-下午12.32.22-1024x777.png" alt="截圖 2023 08 17 下午12.32.22" class="wp-image-5482" srcset="https://www.finlab.tw/wp-content/uploads/2023/08/截圖-2023-08-17-下午12.32.22-1024x777.png 1024w, https://www.finlab.tw/wp-content/uploads/2023/08/截圖-2023-08-17-下午12.32.22-300x228.png 300w, https://www.finlab.tw/wp-content/uploads/2023/08/截圖-2023-08-17-下午12.32.22-768x583.png 768w, https://www.finlab.tw/wp-content/uploads/2023/08/截圖-2023-08-17-下午12.32.22-1536x1166.png 1536w, https://www.finlab.tw/wp-content/uploads/2023/08/截圖-2023-08-17-下午12.32.22.png 1914w" sizes="(max-width: 1024px) 100vw, 1024px" title="客製化選股策略的回測價格序列 | 比較進出場的時間點特性 1"></figure>



<h2>多重比較各種回測價格序列</h2>



<p class="has-medium-font-size">哪一種回測序列最好？可以用 FinLab 優化小工具快速檢測。</p>



<h3>範例代碼</h3>



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

reports = {n:peg_strategy(n) for n in ['close', 'open', 'close_open_avg', 'high_low_avg', 'transaction_avg']}
report_collection = ReportCollection(reports)
report_collection.plot_creturns().show()
report_collection.plot_stats('bar').show()
report_collection.plot_stats('heatmap')</code></pre>



<h3>回測結果</h3>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="195" src="https://www.finlab.tw/wp-content/uploads/2023/08/newplot-1-1024x195.png" alt="newplot 1" class="wp-image-5483" srcset="https://www.finlab.tw/wp-content/uploads/2023/08/newplot-1-1024x195.png 1024w, https://www.finlab.tw/wp-content/uploads/2023/08/newplot-1-300x57.png 300w, https://www.finlab.tw/wp-content/uploads/2023/08/newplot-1-768x146.png 768w, https://www.finlab.tw/wp-content/uploads/2023/08/newplot-1-1536x292.png 1536w, https://www.finlab.tw/wp-content/uploads/2023/08/newplot-1-2048x389.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="客製化選股策略的回測價格序列 | 比較進出場的時間點特性 2"></figure>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="195" src="https://www.finlab.tw/wp-content/uploads/2023/08/newplot-2-1024x195.png" alt="newplot 2" class="wp-image-5484" srcset="https://www.finlab.tw/wp-content/uploads/2023/08/newplot-2-1024x195.png 1024w, https://www.finlab.tw/wp-content/uploads/2023/08/newplot-2-300x57.png 300w, https://www.finlab.tw/wp-content/uploads/2023/08/newplot-2-768x146.png 768w, https://www.finlab.tw/wp-content/uploads/2023/08/newplot-2-1536x292.png 1536w, https://www.finlab.tw/wp-content/uploads/2023/08/newplot-2-2048x389.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="客製化選股策略的回測價格序列 | 比較進出場的時間點特性 3"></figure>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="524" src="https://www.finlab.tw/wp-content/uploads/2023/08/截圖-2023-08-17-下午12.34.39-1024x524.png" alt="截圖 2023 08 17 下午12.34.39" class="wp-image-5485" srcset="https://www.finlab.tw/wp-content/uploads/2023/08/截圖-2023-08-17-下午12.34.39-1024x524.png 1024w, https://www.finlab.tw/wp-content/uploads/2023/08/截圖-2023-08-17-下午12.34.39-300x153.png 300w, https://www.finlab.tw/wp-content/uploads/2023/08/截圖-2023-08-17-下午12.34.39-768x393.png 768w, https://www.finlab.tw/wp-content/uploads/2023/08/截圖-2023-08-17-下午12.34.39-1536x785.png 1536w, https://www.finlab.tw/wp-content/uploads/2023/08/截圖-2023-08-17-下午12.34.39-2048x1047.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="客製化選股策略的回測價格序列 | 比較進出場的時間點特性 4"></figure>



<p class="has-medium-font-size">可以發現使用「開盤價」序列擁有最高的報酬率，但整體來說，五種選擇都差異不會很大，但論夏普率與整體指標評價，則是「收盤價和開盤價的均價」表現最好，也就是「開盤價」與「收盤價」各進出一半，將夏普率從 1.14 提升到1.47，而 avg_mdd(每筆交易對的平均最大回檔) 也從 -10%降低到 -8.9%，能有效降低波動風險。</p>



<h2>結論</h2>



<p class="has-medium-font-size">還有更多回測價格序列想要打造嗎？可以反映給我們開發，或是按照附件的<a href="https://colab.research.google.com/drive/1FCx4ZAjF6Hh2pFy42ka6qHYu_B3ZmFpJ?usp=sharing" target="_blank" rel="noopener"> colab 檔</a> 來自行客製化，讓回測的選擇更有彈性。</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/customed-tw-stock-backtest-price/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">5481</post-id>	</item>
		<item>
		<title>產業資料庫的基礎應用</title>
		<link>https://www.finlab.tw/industry_themes_database_basic_application/</link>
					<comments>https://www.finlab.tw/industry_themes_database_basic_application/#respond</comments>
		
		<dc:creator><![CDATA[Ben]]></dc:creator>
		<pubDate>Tue, 20 Dec 2022 06:35:19 +0000</pubDate>
				<category><![CDATA[FinLab 量化平台]]></category>
		<category><![CDATA[Python新手教學]]></category>
		<category><![CDATA[基本面分析]]></category>
		<category><![CDATA[生產力]]></category>
		<category><![CDATA[pandas]]></category>
		<category><![CDATA[台股]]></category>
		<category><![CDATA[產業分析]]></category>
		<category><![CDATA[資料處理]]></category>
		<guid isPermaLink="false">https://www.finlab.tw/?p=4971</guid>

					<description><![CDATA[這篇教學文章將說明FinLab的「產業題材資料庫」的簡單應用，並教你如何用 Python 與 Pandas 基礎語法去「客製化」自己的產業分類，讓產業資料庫更豐富]]></description>
										<content:encoded><![CDATA[
<p class="has-medium-font-size">產業資料庫重要嗎？如果你想讓選股技巧更上一層樓，勢必會進階到產業分析。<br>投資標的的優劣評價，除了自己跟自己比，例如近期財報是否較過去改善，另一個判斷企業競爭力的評價方式，就是跟同業比，好壞都是比較而來的，選對比較基準才讓評價有意義。<br>除了同業個股比較，產業資料庫的另一個主要應用在找出族群趨勢，如果一個產業的企業的營收或股價趨勢都向上，那代表該產業蒸蒸日上，有產業景氣良好的基本面護體，更能增加投資判斷把握度與可解釋性，排除單一個股炒作的個別性，更進階的應用甚至可延伸到概念股落後補漲效應。<br>這一切的應用的基礎都建構在「產業資料庫」的分類，這篇教學文章將說明FinLab的「<a href="https://ai.finlab.tw/database#security_industry_themes" target="_blank" rel="noopener">產業題材資料庫</a>」的簡單應用，並教你如何用 Python 與 Pandas 基礎語法去「客製化」自己的產業分類，讓產業資料庫更豐富。</p>



<h2>產業資料</h2>



<p class="has-medium-font-size">FinLab 的細產業主題資料來源主要取自「<a href="https://ic.tpex.org.tw/" target="_blank" rel="noreferrer noopener">產業價值鍊資訊平台</a>」，少部分為自定義分類。從&nbsp;<a href="https://ai.finlab.tw/database#security_industry_themes" target="_blank" rel="noreferrer noopener">FinLab資料庫</a>&nbsp;只要一行程式碼就能下載全部的細產業資訊，讓你輕鬆以此基礎做後續應用。要注意的是此份資料僅限&nbsp;<a href="https://ai.finlab.tw/pricing" target="_blank" rel="noreferrer noopener">VIP</a>&nbsp;使用。<br><a href="https://ic.tpex.org.tw/" target="_blank" rel="noreferrer noopener">產業價值鍊資訊平台</a>&nbsp;會將主產業再分拆上下游的細產業，讓你更精細的去比較，否則證交所一般分類光半導體就近百檔，比較效果相對籠統。</p>



<figure class="wp-block-image"><img src="https://www.finlab.tw/wp-content/uploads/2022/11/%E6%88%AA%E5%9C%96-2022-11-02-%E4%B8%8A%E5%8D%887.30.52-1024x404.png" alt="截圖 2022 11 02 上午7.30.52" class="wp-image-4756" title="產業面選股策略｜同業本益比比較法 1"/><figcaption>資料庫欄位</figcaption></figure>



<p class="has-medium-font-size">每家公司所屬產業的資訊放在 catergory 內，category 欄位的型態是文字格式，所有產業分類會放入 List 後再包成文字型態，從該資料得知公司分別有哪些產業的標籤。<br>例如1101台泥的產業序列裡有主產業的水泥，也有細產業「水泥:水泥成品」、「水泥:水泥熟料」(格式為「主產業:細產業 or 主產業」)。</p>



<figure class="wp-block-image"><img src="https://www.finlab.tw/wp-content/uploads/2022/11/%E6%88%AA%E5%9C%96-2022-11-02-%E4%B8%8A%E5%8D%887.35.04-1024x810.png" alt="截圖 2022 11 02 上午7.35.04" class="wp-image-4757" title="產業面選股策略｜同業本益比比較法 2"/></figure>



<h2>簡單查詢應用</h2>



<p class="has-medium-font-size">如果我們想查詢哪些公司屬於水泥產業？我們可以運用pandas內的 <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.str.contains.html" target="_blank" rel="noopener">Series.str.contains</a>，讓我們快速分類出產業名單，如下範例，只要「category」欄位內含「水泥」兩字，就會被納入範圍。</p>



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

# 取出產業題材
themes = data.get('security_industry_themes')

# 選出產業包含「水泥」的公司
ind1 = themes[themes['category'].str.contains('水泥')]
</code></pre>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="513" src="https://www.finlab.tw/wp-content/uploads/2022/12/截圖-2022-12-20-下午12.36.55-1024x513.png" alt="截圖 2022 12 20 下午12.36.55" class="wp-image-4972" srcset="https://www.finlab.tw/wp-content/uploads/2022/12/截圖-2022-12-20-下午12.36.55-1024x513.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/12/截圖-2022-12-20-下午12.36.55-300x150.png 300w, https://www.finlab.tw/wp-content/uploads/2022/12/截圖-2022-12-20-下午12.36.55-768x384.png 768w, https://www.finlab.tw/wp-content/uploads/2022/12/截圖-2022-12-20-下午12.36.55-1536x769.png 1536w, https://www.finlab.tw/wp-content/uploads/2022/12/截圖-2022-12-20-下午12.36.55.png 1894w" sizes="(max-width: 1024px) 100vw, 1024px" title="產業資料庫的基礎應用 5"></figure>



<p class="has-medium-font-size">contains 語法支援 or 的運用，如果我們今天想選出產業包含「水泥」或「建材營造」的公司，可以使用以下語句，使用&#8217;|&#8217;的符號做邏輯運算串連：</p>



<p class="has-medium-font-size"> <code>ind2 = themes[themes['category'].str.contains('水泥|建材營造')]</code> </p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="532" src="https://www.finlab.tw/wp-content/uploads/2022/12/截圖-2022-12-20-下午12.37.48-1024x532.png" alt="截圖 2022 12 20 下午12.37.48" class="wp-image-4973" srcset="https://www.finlab.tw/wp-content/uploads/2022/12/截圖-2022-12-20-下午12.37.48-1024x532.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/12/截圖-2022-12-20-下午12.37.48-300x156.png 300w, https://www.finlab.tw/wp-content/uploads/2022/12/截圖-2022-12-20-下午12.37.48-768x399.png 768w, https://www.finlab.tw/wp-content/uploads/2022/12/截圖-2022-12-20-下午12.37.48-1536x799.png 1536w, https://www.finlab.tw/wp-content/uploads/2022/12/截圖-2022-12-20-下午12.37.48-2048x1065.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="產業資料庫的基礎應用 6"></figure>



<h2>簡單回測範例</h2>



<p class="has-medium-font-size">「想挑出水泥產業中，本益比低於水泥產業本益比中位數之個股當投資組合」</p>



<p class="has-medium-font-size">實作很簡單，用前述contains篩選的stock_id，套入本益比資料做欄位圈選，就能限定資料範圍，再運用 <code>median(axis=1)</code>，計算每日產業本益比中位數，axis=1的用途在取每一期(橫列)的中位數。</p>



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

# 取出產業題材
themes = data.get('security_industry_themes')

# 選出產業包含「水泥」公司
ind = themes[themes['category'].str.contains('水泥')]
pe = data.get('price_earning_ratio:本益比')
ind_pe = pe[list(ind['stock_id'])]

# 計算每日產業本益比中位數,axis=1的用途在取每一期(橫列)的中位數
ind_pe_med = ind_pe.median(axis=1)

# 選出本益比小於同業本益比中位數且本益比小於25的公司
position = (ind_pe &lt; ind_pe_med) &amp; (ind_pe &lt; 25)

# 回測
report = sim(position, upload=False)
report.display()</code></pre>



<figure class="wp-block-image"><img loading="lazy" width="800" height="600" src="https://www.finlab.tw/wp-content/uploads/2022/11/newplot-2.png" alt="newplot 2" class="wp-image-4758" title="產業面選股策略｜同業本益比比較法 3" srcset="https://www.finlab.tw/wp-content/uploads/2022/11/newplot-2.png 800w, https://www.finlab.tw/wp-content/uploads/2022/11/newplot-2-300x225.png 300w, https://www.finlab.tw/wp-content/uploads/2022/11/newplot-2-768x576.png 768w" sizes="(max-width: 800px) 100vw, 800px" /></figure>



<h2>自定義產業分類</h2>



<p class="has-medium-font-size">有時我們發現產業價值鏈資訊平台的分類仍不能滿足需求，像是他缺少概念股的標籤資料，學會Python 的好處在我們可以任意擴展資料，去自定義新增的分類。<br>使用開發好的 create_new_industry_themes 的函式去創建新的產業分類，其中 additional_themes 變數控制新增標籤，格式為<code>[([目標群],[標籤群]),...]</code>。<br><br>例如以下範例對&#8217;6684&#8242;, &#8216;6756&#8217;, &#8216;3014&#8217; 新增 &#8216;元宇宙:祖克柏概念股&#8217; 的標籤，對&#8217;1342&#8242;, &#8216;1584&#8217;新增&#8217;航太週邊:空中巴士概念股&#8217;的標籤，對&#8217;2342&#8242;, &#8216;3317&#8217;, &#8216;4923&#8217;, &#8216;5299&#8217;, &#8216;6287&#8217; 增加兩個標籤&#8217;半導體:基礎元件&#8217;, &#8216;通訊產業:通訊元件&#8217;。</p>



<pre class="wp-block-code"><code lang="python" class="language-python">def add_sub_group(dataframe, stock_list: list, theme_list: list):
    try:
        dataframe.loc[stock_list]['category'] = dataframe.loc[stock_list]['category'].apply(
            lambda s: s.extend(theme_list))
    except KeyError:
        print('stock_list not in index.')
    return dataframe


def process_sub_group_list(sub_group_list):
    sub_group_list.extend(list(set({i[:i.index(':')] for i in sub_group_list if ':' in i})))
    return sorted(list(set(sub_group_list)))


def create_new_industry_themes(additional_themes):

    df = data.get('security_industry_themes')
    df = df.set_index(['stock_id', 'name'])
    df['category'] = df['category'].apply(lambda s: eval(s))

    if additional_themes:
        for stock_list, theme_list in additional_themes:
            df = add_sub_group(df, stock_list, theme_list)

    df['category'] = df['category'].apply(lambda s: process_sub_group_list(s))
    df = df.astype(str)
    df = df.reset_index()
    return df


additional_themes = [
    (['6684', '6756', '3014'], ['元宇宙:祖克柏概念股']),
    (['1342', '1584'], ['航太週邊:空中巴士概念股']),
    (['2342', '3317', '4923', '5299', '6287'], ['半導體:基礎元件', '通訊產業:通訊元件']),
]


new_themes = create_new_industry_themes(additional_themes)
# 檢查6684 是否成功新增標籤
new_themes[new_themes['stock_id']=='6684']['category'].values</code></pre>



<p class="has-medium-font-size"><br><br></p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="699" src="https://www.finlab.tw/wp-content/uploads/2022/12/截圖-2022-12-20-下午2.02.42-1024x699.png" alt="截圖 2022 12 20 下午2.02.42" class="wp-image-4974" srcset="https://www.finlab.tw/wp-content/uploads/2022/12/截圖-2022-12-20-下午2.02.42-1024x699.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/12/截圖-2022-12-20-下午2.02.42-300x205.png 300w, https://www.finlab.tw/wp-content/uploads/2022/12/截圖-2022-12-20-下午2.02.42-768x524.png 768w, https://www.finlab.tw/wp-content/uploads/2022/12/截圖-2022-12-20-下午2.02.42-1536x1049.png 1536w, https://www.finlab.tw/wp-content/uploads/2022/12/截圖-2022-12-20-下午2.02.42.png 1797w" sizes="(max-width: 1024px) 100vw, 1024px" title="產業資料庫的基礎應用 7"></figure>



<p class="has-medium-font-size">執行完含式後，會發現 new_themes 已有新增資料～之後就可以用自定義後的 new_themes  做產業分析囉！</p>



<h2>小結</h2>



<p class="has-medium-font-size"><a href="https://colab.research.google.com/drive/15PQ_W_6xUZ1lHlDWaNZtZgsUPZPMiove?usp=sharing" target="_blank" rel="noopener">colab程式範例</a><br><br>學會基礎的產業資料的資料處理技巧後，就可以進行許多分析與策略開發，像是「<a href="https://www.finlab.tw/industry_pe_strategy/">產業面選股策略｜同業本益比比較法</a>」就是延伸的應用喔！<br>如果有自己的產業分類標籤可以加入，那就會進化成個人獨有的資料，可能創造出不易被模仿的策略或產業觀察指標。</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/industry_themes_database_basic_application/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">4971</post-id>	</item>
		<item>
		<title>FinLab 開發與研究月報 (2022-11)</title>
		<link>https://www.finlab.tw/finlab_monthly_dev_report_202211/</link>
					<comments>https://www.finlab.tw/finlab_monthly_dev_report_202211/#respond</comments>
		
		<dc:creator><![CDATA[Ben]]></dc:creator>
		<pubDate>Wed, 30 Nov 2022 05:40:35 +0000</pubDate>
				<category><![CDATA[VIP文章]]></category>
		<category><![CDATA[FinLab 量化平台]]></category>
		<category><![CDATA[投資新手]]></category>
		<category><![CDATA[生產力]]></category>
		<category><![CDATA[選股策略]]></category>
		<category><![CDATA[研究月報]]></category>
		<guid isPermaLink="false">https://www.finlab.tw/?p=4957</guid>

					<description><![CDATA[這個月我們發佈了許多研究與教學，希望讓大家上手 FinLab量化平台 ，並示範如何用Python實作出量化策略，除了程式範例，我們也在下述「關鍵研究報告」的文章中詳細寫出策略背後的巧思，讓你不僅知道如何寫程式，更進一步了解設計原理與細節規劃。
FinLab量化平台 的訂閱服務與過往課程最大的不同是內容會不斷加值並推陳出新，觀察市場變化，研發新的武器，陪大家在程式交易的路上一起成長茁壯！
如果您前些日子因忙碌而錯過內容，隨時都可以再回來複習，以下為本月研究月報。]]></description>
										<content:encoded><![CDATA[
<p>這個月我們發佈了許多研究與教學，希望讓大家上手<a href="https://ai.finlab.tw/pricing" target="_blank" rel="noopener"> FinLab量化平台</a> ，並示範如何用Python實作出量化策略，除了程式範例，我們也在下述「關鍵研究報告」的文章中詳細寫出策略背後的巧思，讓你不僅知道如何寫程式，更進一步了解設計原理與細節規劃。<br><a href="https://ai.finlab.tw/pricing" target="_blank" rel="noopener">FinLab量化平台</a> 的訂閱服務與過往課程最大的不同是內容會不斷加值並推陳出新，觀察市場變化，研發新的武器，陪大家在程式交易的路上一起成長茁壯！<br>如果您前些日子因忙碌而錯過內容，隨時都可以再回來複習，以下為本月研究月報：</p>



<h2>影音教學</h2>



<figure class="wp-block-image"><img src="https://i.ibb.co/pXZN2mP/f3.png" alt="f3" title="FinLab 開發與研究月報 (2022-11) 8"></figure>



<p><a href="https://ai.finlab.tw/course?cid=6cOSUvxOP39s3EPuCyc7" target="_blank" rel="noopener">策略選股優化神器！Finlab Optimize 教學 (Free)</a><br>當手上有了一堆選股條件條件，卻不知道該怎麼如何組成一支有用的選股策略嗎? 看這支影片就對了，我會談到該如何對條件進行排列組合，作為策略初始的雛形！</p>



<figure class="wp-block-image"><img src="https://i.ibb.co/gSf65fY/p2.png" alt="p2" title="FinLab 開發與研究月報 (2022-11) 9"></figure>



<p><a href="https://pse.is/4m5fnx" target="_blank" rel="noopener">Finlab主力動能策略</a><br>押寶股價領先營收突破。而究竟要如何分別運用營收、去年同比與上月環比數據、結合股價創新高篩出強悍的狗狗，繼續看下去吧！</p>



<figure class="wp-block-image"><img src="https://i.ibb.co/6R0LCGk/Picture1.png" alt="Picture1" title="FinLab 開發與研究月報 (2022-11) 10"></figure>



<p><a href="http://user89632.psee.io/4nbfsy" target="_blank" rel="noopener">使用相關性統計找出關鍵財報指標</a></p>



<p>在這次的直播中，你會學到</p>



<ol><li>如何篩選財務指標？</li><li>如何預防過擬合？</li><li>降低非系統性風險？</li></ol>



<h2>新策略上架</h2>



<ul><li><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></li><li><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%A7A" target="_blank" rel="noopener">財報指標20大</a></li><li><a href="https://ai.finlab.tw/strategyview/?uid=TJN4FDuqrwU8DML7DAjUYFIMutp2&amp;sid=%E5%A4%9A%E7%94%A2%E6%A5%AD%E5%83%B9%E6%8A%95" target="_blank" rel="noopener">多產業價投</a></li></ul>



<h2>關鍵研究報告</h2>



<ul><li><a href="https://www.finlab.tw/industry_pe_strategy/">產業面選股策略｜同業本益比比較法</a></li><li><a href="https://www.finlab.tw/low_volatility_stratgy_by_mae_mfe_ml/">低波動本益成長比策略 | MAE_MFE 機器學習選股</a></li><li><a href="https://www.finlab.tw/time_series_analysis_of_investment_trust_strategy/">投信買賣超選股策略｜時空序列分析的秘招｜停損怎麼設？</a></li><li><a href="https://www.finlab.tw/revenue_and_price_engine_strategy/">月營收選股｜股價創新高｜新手必學的雙動能策略</a></li><li><a href="https://www.finlab.tw/tw_monetary_aggregates_m1b_strategy/">用Python回測總經指標(1)｜M1B &amp; M2 年增率</a></li><li><a href="https://www.finlab.tw/us_unemployment_rate_seasonally_adjusted_sp500_backtest/">用Python回測總經指標(2)｜美國失業率 vs S&amp;P 500指數</a></li></ul>



<h2>新手上路</h2>



<ul><li><a href="https://ai.finlab.tw/course?cid=LqYTLW3KkXRSPnci47xe" target="_blank" rel="noopener">平台速成教學(Free)</a></li><li><a href="https://www.finlab.tw/stock_strategy_learning_system_for_beginner/">選股策略系統性學習(1)｜新手初訪(Free)</a></li><li><a href="https://www.finlab.tw/backtest_system_rule/">選股回測系統豆知識 (1)｜報酬率計算(Free)</a></li><li><a href="https://www.finlab.tw/backtest_system_position_limit/">選股回測系統豆知識 (2)｜持股比例上限設定(Free)</a></li></ul>



<h2>開發事項</h2>



<ul><li><a href="https://doc.finlab.tw/change-log/#0312-2022-11-29" target="_blank" rel="noopener">FinLab Package 更新日誌</a></li></ul>



<h2>未來開發</h2>



<ul><li>全自動下單解決方案</li><li>新一代策略數據儀表板</li><li>移動出場</li><li>可轉債</li></ul>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/finlab_monthly_dev_report_202211/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">4957</post-id>	</item>
		<item>
		<title>Python爬蟲教學｜美國勞動部統計局API｜失業率</title>
		<link>https://www.finlab.tw/us_unemployment_rate_seasonally_adjusted_crawler/</link>
					<comments>https://www.finlab.tw/us_unemployment_rate_seasonally_adjusted_crawler/#respond</comments>
		
		<dc:creator><![CDATA[Ben]]></dc:creator>
		<pubDate>Thu, 10 Nov 2022 07:47:00 +0000</pubDate>
				<category><![CDATA[總體經濟]]></category>
		<category><![CDATA[Python新手教學]]></category>
		<category><![CDATA[投資新手]]></category>
		<category><![CDATA[生產力]]></category>
		<category><![CDATA[失業率]]></category>
		<category><![CDATA[總經]]></category>
		<category><![CDATA[美國]]></category>
		<category><![CDATA[美國勞動統計局]]></category>
		<guid isPermaLink="false">https://www.finlab.tw/?p=4844</guid>

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



<h2>API 註冊</h2>



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



<h2>API 規範</h2>



<p class="has-medium-font-size">建議使用 <strong>API Version 2.0</strong>，權限開比較多。更多常見問題可見 <a href="https://www.bls.gov/developers/api_FAQs.htm" target="_blank" rel="noopener">Q&amp;A</a>。<br><strong>How is API Version 2.0 different from Version 1.0?</strong>API Version 2.0 requires registration, and it offers greater query limits. It also allows users to request net and percent changes and series description information. See below for more details.</p>



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



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



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



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



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



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



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



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



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



<pre class="wp-block-code"><code lang="python" class="language-python">import requests
import json
import pandas as pd

def crawl_data(start_year, end_year, api_key='xxxx'):

    headers = {'Content-type': 'application/json'}
    # seriesid：傳入目標資料
    data = json.dumps({"seriesid": ['LNS14000000'],"startyear":start_year, "endyear":end_year, "registrationkey":api_key})
    p = requests.post('https://api.bls.gov/publicAPI/v2/timeseries/data/', data=data, headers=headers)
    json_data = json.loads(p.text)

    # 將資料轉成dataframe
    df = pd.DataFrame(json_data['Results']['series'][0]['data'])

    # 將資料日期轉成公告日，當月失業率在下一個月才公告
    latest_year = int(df['year'].iloc[0])
    latest_month = int(df['period'].iloc[0].replace('M',''))
    start_year = int(df['year'].iloc[-1])
    start_month = int(df['period'].iloc[-1].replace('M',''))

    def process_date(year,month):
        if month == 12:
            month = 1
            year += 1
        else:
            month += 1
        return year,month

    latest_year, latest_month = process_date(latest_year, latest_month)
    start_year, start_month = process_date(start_year, start_month)
    issue_date = pd.date_range(f'{start_year}-{start_month}-1', f'{latest_year}-{latest_month}-1',
                               freq='MS') + pd.tseries.offsets.DateOffset(days=9)
    df_new = pd.DataFrame({'value': df['value'].values[::-1]}, index=issue_date)
    df_new['value'] = df_new['value'].astype(float)
    df_new.index.name = 'date'
    return df_new

df = crawl_data('2015', '2023')
df</code></pre>



<h2>小結</h2>



<p class="has-medium-font-size"><a href="https://colab.research.google.com/drive/1aRNLUTQi3AX6nLWn-Mp132GIFYTFFjhW?usp=sharing" target="_blank" rel="noopener">colab範例檔</a><br>美國勞動部統計局有許多非常重要的資料，除了就業相關數據如失業率、非農、就業津貼，還有物價指數CPI、PPI，都能幫助我們後續做分析，趕緊學會該 API 的使用法則，打造總經分析武器庫。<br>想知道美國失業率如何應用在美國指數的擇時回測嗎？可以繼續看「<a href="https://www.finlab.tw/us_unemployment_rate_seasonally_adjusted_sp500_backtest/">用Python回測總經指標(2)｜美國失業率 vs S&amp;P 500指數</a>」踏入更豐富的數據世界。<br></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/us_unemployment_rate_seasonally_adjusted_crawler/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">4844</post-id>	</item>
		<item>
		<title>台股財報資料豆知識 ｜ 時序索引操作</title>
		<link>https://www.finlab.tw/tw_stock_financial_statement_time_series_knowledge/</link>
					<comments>https://www.finlab.tw/tw_stock_financial_statement_time_series_knowledge/#respond</comments>
		
		<dc:creator><![CDATA[Ben]]></dc:creator>
		<pubDate>Fri, 28 Oct 2022 10:31:13 +0000</pubDate>
				<category><![CDATA[Python新手教學]]></category>
		<category><![CDATA[FinLab 量化平台]]></category>
		<category><![CDATA[生產力]]></category>
		<category><![CDATA[FinlabDataframe]]></category>
		<category><![CDATA[台股]]></category>
		<category><![CDATA[策略開發豆知識]]></category>
		<category><![CDATA[財報]]></category>
		<category><![CDATA[資料處理]]></category>
		<guid isPermaLink="false">https://www.finlab.tw/?p=4720</guid>

					<description><![CDATA[目前正逢財報季，有些公司已經上傳第三季財報，許多已基本面為選股主軸的用戶都開始緊盯自己的程式是否跑出新的指引？許多新手用戶對財報資料的發佈時間和資料操作不熟悉，這篇文章將娓娓道來台股財報資料的時序細節，花幾分鐘，你會了解財報「發布日、截止日、FinlabDataFrame的資料索引轉換方法，讓你上手財報資料選股策略。]]></description>
										<content:encoded><![CDATA[
<p class="has-medium-font-size">目前正逢財報季，有些公司已經上傳第三季財報，許多已基本面為選股主軸的用戶都開始緊盯自己的程式是否跑出新的指引？藉於新手用戶對財報資料的發佈時間和資料操作不熟悉，這篇文章將娓娓道來台股財報資料的時序細節，花幾分鐘，你會了解財報「發布日、截止日、FinlabDataFrame的資料索引轉換方法，讓你上手財報資料選股策略的前處理。</p>



<h2>財報發布日定義</h2>



<p class="has-medium-font-size">FinLab 資料庫系統會每天更新、檢查財報資料，財報發布日以<a href="https://doc.twse.com.tw/server-java/t57sb01?step=1&amp;colorchg=1&amp;co_id=1101&amp;year=&amp;seamon=&amp;mtype=A&amp;" target="_blank" rel="noopener">財報電子檔</a>內的資料上傳日當基準資料。你可能疑惑怎麼在新聞或公司重訊已看到 EPS 多少了，但抓下的財報或財報電子檔卻沒有當季資料？那是因為有些公司的財報電子檔上傳日會比董事會重訊發布晚個幾天，通常是因為公司內部或會計作業問題，某些會計項目可能還會再校對或微調等等，實際數字以公司財報完整電子檔上傳才是比較穩當的做法。 大部分的公司會在財報截止日前一週內才上傳完畢。</p>



<h2>財報截止日定義</h2>



<p class="has-medium-font-size">所有公司都必須在每季財報截止日前上傳財報電子書，若沒有即時上傳，通常代表財務狀況出問題、會計師審核上出狀況&#8230;若沒在規定期限內補正，後續面臨暫停交易或下市風險。<br>台股上市櫃公司一年要上傳4次財報，興櫃只要上傳第二季和第四季財報，監理強度不同。各產業截止日細節如下列供參：</p>



<h3>上市櫃一般公司</h3>



<p class="has-medium-font-size">季別/財報截止日對應為下列對應，遇假日則遞延到次一個交易日。</p>



<ul class="has-medium-font-size"><li>Q1：當年5/15</li><li>Q2：當年8/14。若為2021年後的KY股，因監管法規改變，改成8/31。</li><li>Q3：當年11/14</li><li>Q4：次年3/31</li></ul>



<h3>保險業</h3>



<p class="has-medium-font-size">季別/財報截止日對應為下列對應，遇假日則遞延到次一個交易日。</p>



<ul class="has-medium-font-size"><li>Q1：當年4/30</li><li>Q2：當年8/31</li><li>Q3：當年10/30</li><li>Q4：次年3/31</li></ul>



<h3>金融業</h3>



<p class="has-medium-font-size">這邊指的是非保險的金融業，如銀行、證券、票券、金控業者。季別/財報截止日對應為下列對應，遇假日則遞延到次一個交易日。</p>



<ul class="has-medium-font-size"><li>Q1：當年5/15</li><li>Q2：當年8/31</li><li>Q3：當年11/14</li><li>Q4：次年3/31</li></ul>



<h2>量化平台財報資料操作</h2>



<h3>取得資料</h3>



<p class="has-medium-font-size">至<a href="https://ai.finlab.tw/database/#financial_statement" target="_blank" rel="noopener">財報資料庫</a>複製財報項目的使用方法，即可取得財報資料。<br>欄位是每家公司的股號，包含所有公開發行公司，索引則是每季的季別，ex : 2013Q1。<br>新手會疑惑為什麼看到一堆NaN ?不要緊張，不是資料出問題，而是這些公司當時未上市櫃或按規定不用發布財報。</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="565" src="https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-28-下午5.25.31-1024x565.png" alt="截圖 2022 10 28 下午5.25.31" class="wp-image-4721" srcset="https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-28-下午5.25.31-1024x565.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-28-下午5.25.31-300x166.png 300w, https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-28-下午5.25.31-768x424.png 768w, https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-28-下午5.25.31-1536x848.png 1536w, https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-28-下午5.25.31-2048x1130.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="台股財報資料豆知識 ｜ 時序索引操作 13"></figure>



<p class="has-medium-font-size">另外提一個小技巧，如果你想要拿掉未上市櫃公司來方便觀察資料，可以使用pandas的<a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.dropna.html" target="_blank" rel="noopener">dropna</a>進行操作。下面的例子會排除掉每一欄位沒有20格有數值的欄位，篩出上市櫃有較久歷史的公司，就可以顯示中間部分的資料，像是1101台泥等等。</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="534" src="https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-28-下午5.34.53-1024x534.png" alt="截圖 2022 10 28 下午5.34.53" class="wp-image-4722" srcset="https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-28-下午5.34.53-1024x534.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-28-下午5.34.53-300x157.png 300w, https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-28-下午5.34.53-768x401.png 768w, https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-28-下午5.34.53-1536x802.png 1536w, https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-28-下午5.34.53-2048x1069.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="台股財報資料豆知識 ｜ 時序索引操作 14"></figure>



<h3>時序轉換</h3>



<p class="has-medium-font-size">上面原始財報數據的日期索引是如「2022-Q1」這類的文字格式，雖然回測將不同尺度的資料取交集時會自動將時序轉成財報發布日的datetime格式，但若有其他用途，想將時序索引從文字轉換成財報發布日的datetime格式，該如何做呢？</p>



<h4>季別文字轉財報發佈日</h4>



<p class="has-medium-font-size">轉非常的簡單，只要加上 <code>index_str_to_date()</code> ，就能將資料轉換，這是<a href="https://doc.finlab.tw/reference/dataframe/#finlab.dataframe.FinlabDataFrame.index_str_to_date" target="_blank" rel="noopener">FinlabDataFrame</a>類別內建的方法。<br>從下圖所示，可以看到加完 <code>index_str_to_date()</code>後，索引改變了。<br>要注意的是，如果公司還沒有正式上傳「<a href="https://doc.twse.com.tw/server-java/t57sb01?step=1&amp;colorchg=1&amp;co_id=1101&amp;year=&amp;seamon=&amp;mtype=A&amp;" target="_blank" rel="noopener">財報電子書</a>」，雖然<a href="https://mops.twse.com.tw/mops/web/t203sb02" target="_blank" rel="noopener">XBRL資訊平台</a>已經有數值可下載，但由於財報電子書上傳日資料未定，資料仍會被歸到截止日的欄位。<br>現在正臨2022-Q3財報季，沒有財報電子書上傳日的數值都會放到最後兩欄的財報截止日，2022-10-31是保險業Q3截止日、2022-11-14則是一般上市櫃公司的Q3截止日，不用擔心回測會用到未來資料，回測會再去與收盤價的交易日索引做對應，遇假日會遞延到下一個交易日。<br>你可能會好奇，公司每季只會發布一次財報，為何日期會那麼多天？那是因為只要A日有任一家公司有上傳紀錄，為方便回測，索引都會加入發布日，如果其他公司在A日沒發布財報，其他公司則會套用近一期數值做填充。</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="486" src="https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-28-下午5.48.13-1024x486.png" alt="截圖 2022 10 28 下午5.48.13" class="wp-image-4723" srcset="https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-28-下午5.48.13-1024x486.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-28-下午5.48.13-300x142.png 300w, https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-28-下午5.48.13-768x364.png 768w, https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-28-下午5.48.13-1536x728.png 1536w, https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-28-下午5.48.13-2048x971.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="台股財報資料豆知識 ｜ 時序索引操作 15"></figure>



<h4>季別文字轉財報截止日</h4>



<p class="has-medium-font-size">若想使用財報截止日做回測與選股，可以使用 <code>deadline()</code> ，就能將資料轉換，這是<a href="https://doc.finlab.tw/reference/dataframe/#finlab.dataframe.FinlabDataFrame.deadline" target="_blank" rel="noopener">FinlabDataFrame</a> 類別內建的方法。注意財報資料與其他時間尺度的資料做交集時，預設是使用財報發布日，所以若要使用截止日當條件，一定要加上 <code>deadline()</code>，使用範例如下。</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="366" src="https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-28-下午6.06.38-1024x366.png" alt="截圖 2022 10 28 下午6.06.38" class="wp-image-4724" srcset="https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-28-下午6.06.38-1024x366.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-28-下午6.06.38-300x107.png 300w, https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-28-下午6.06.38-768x274.png 768w, https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-28-下午6.06.38-1536x548.png 1536w, https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-28-下午6.06.38-2048x731.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="台股財報資料豆知識 ｜ 時序索引操作 16"></figure>



<p class="has-medium-font-size">截止日日期索引包括一般公司、保險業、金融業的規定日期，若當日沒數值，則會拿近一筆數值來補，以方便回測。</p>



<h2>結論</h2>



<p class="has-medium-font-size">經過上述說明，是不是對 FinLab 量化平台的財報資料操作與原理更為熟悉了呢？<br>如果想進一步學習用財報來選股，可參考這篇<a href="https://www.finlab.tw/basic_score_strategy/">財務指標計分法的教學</a>～<br>如果還有其他相關問題，歡迎隨時與我們討論喔！</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/tw_stock_financial_statement_time_series_knowledge/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">4720</post-id>	</item>
		<item>
		<title>史上最強大的台股板塊圖 &#124; 操作說明書</title>
		<link>https://www.finlab.tw/%e5%8f%b2%e4%b8%8a%e6%9c%80%e5%bc%b7%e5%a4%a7%e7%9a%84%e5%8f%b0%e8%82%a1%e6%9d%bf%e5%a1%8a%e5%9c%96-%e6%93%8d%e4%bd%9c%e8%aa%aa%e6%98%8e%e6%9b%b8/</link>
					<comments>https://www.finlab.tw/%e5%8f%b2%e4%b8%8a%e6%9c%80%e5%bc%b7%e5%a4%a7%e7%9a%84%e5%8f%b0%e8%82%a1%e6%9d%bf%e5%a1%8a%e5%9c%96-%e6%93%8d%e4%bd%9c%e8%aa%aa%e6%98%8e%e6%9b%b8/#respond</comments>
		
		<dc:creator><![CDATA[Ben]]></dc:creator>
		<pubDate>Tue, 02 Aug 2022 03:57:57 +0000</pubDate>
				<category><![CDATA[Python新手教學]]></category>
		<category><![CDATA[FinLab 量化平台]]></category>
		<category><![CDATA[生產力]]></category>
		<category><![CDATA[treemap]]></category>
		<category><![CDATA[台股]]></category>
		<category><![CDATA[板塊圖]]></category>
		<category><![CDATA[盤中資訊]]></category>
		<category><![CDATA[資料視覺化]]></category>
		<guid isPermaLink="false">https://www.finlab.tw/?p=4151</guid>

					<description><![CDATA[FinLab 在 2022/7/31 於量化平台的產業評選發佈了完整版台股板塊圖，在 FB 粉絲團的介紹文章引發了不小的迴響，著實嚇了 Ben 一大跳，沒想到如此多人對此功能這麼有興趣 ! 
其實以前就發布過 Treemap的教學文章，但比較偏程式教學，功能也比較沒那麼齊全，為了讓大家更方便看見Python的數據力，決定將板塊圖寫成網頁版，結合多年數據觀測實戰的經驗，將關鍵台股指標全放在這功能上了！]]></description>
										<content:encoded><![CDATA[
<p class="has-medium-font-size">FinLab 在 2022/7/31 於量化平台的產業評選發佈了<a href="https://ai.finlab.tw/industry?industry=LED%E7%85%A7%E6%98%8E%E7%94%A2%E6%A5%AD:%E5%85%89%E6%BA%90_%E7%A3%8A%E6%99%B6&amp;tab=%E6%9D%BF%E5%A1%8A%E5%9C%96" target="_blank" rel="noopener">完整版台股板塊圖</a>，在 FB 粉絲團的<a href="https://www.facebook.com/finlab.python/posts/pfbid0ZyNMQ8y4LRR3djcigTdfXbYyjVY7ZucLGYKdhLzWKe1pMBMqodM8PMJRth5Ejicil" target="_blank" rel="noopener">介紹文章</a>引發了不小的迴響，著實嚇了 Ben 一大跳，沒想到如此多人對此功能這麼有興趣 ! <br>其實以前就發布過 <a href="https://www.finlab.tw/dashboard2-plotly-treemap/">Treemap的教學文章</a>，但比較偏程式教學，功能也比較沒那麼齊全，為了讓大家更方便看見Python的數據力，決定將板塊圖寫成網頁版，結合多年數據觀測實戰的經驗，將關鍵台股指標全放在這功能上了！</p>



<p class="has-medium-font-size">台股板塊圖可以說是數據萬花筒，囊括了基本面、技術面、籌碼面的指標，有200多種變化可觀測，有別於市面上類似功能只有報酬率可看，滿足不了專業用戶需求。<br>透過呈現多維度資料、自由點擊互動、監控全市場的數據，應該在目前市場上找不到功能這麼完整的台股板塊圖。</p>



<p class="has-medium-font-size">雖然 FinLab 目前主打在策略開發和回測，比較少著墨在比較親民的資料查詢或視覺化，但未來會慢慢補上，這塊市面上做的人很多，要做就要做出特色才有價值！</p>



<h2>台股板塊圖操作說明</h2>



<h3>什麼是板塊圖</h3>



<p class="has-medium-font-size">板塊圖就像剝洋蔥，藉由顏色與面積顯示不同數據維度，分類一層層往內縮，像FinLab預設的圖表階層由外到內是台股全市場、上市或上櫃、產業類股、公司，父階層的數值會參考子數值的面積權重與顏色數值來顯示，FinLab 計算父階層是採用中位數的計算模式，像上市鋼鐵類股若有五檔漲幅分別是 1、2、3、3、10%，鋼鐵類股的顏色會以 3% 來計算，如此能排除少數公司的極端數據，對產業數據有更公允的衡量。</p>



<h3>簡易互動</h3>



<p class="has-medium-font-size">點擊 <a href="https://ai.finlab.tw/industry/" target="_blank" rel="noopener">量化平台</a> 左側導覽列進入產業分析頁面，Tab 點擊板塊圖模式即可啟用圖表。</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="597" src="https://www.finlab.tw/wp-content/uploads/2022/08/截圖-2022-08-02-上午10.30.38-1024x597.png" alt="截圖 2022 08 02 上午10.30.38" class="wp-image-4153" srcset="https://www.finlab.tw/wp-content/uploads/2022/08/截圖-2022-08-02-上午10.30.38-1024x597.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/08/截圖-2022-08-02-上午10.30.38-300x175.png 300w, https://www.finlab.tw/wp-content/uploads/2022/08/截圖-2022-08-02-上午10.30.38-768x447.png 768w, https://www.finlab.tw/wp-content/uploads/2022/08/截圖-2022-08-02-上午10.30.38-1536x895.png 1536w, https://www.finlab.tw/wp-content/uploads/2022/08/截圖-2022-08-02-上午10.30.38-2048x1193.png 2048w, https://www.finlab.tw/wp-content/uploads/2022/08/截圖-2022-08-02-上午10.30.38-1200x700.png 1200w" sizes="(max-width: 1024px) 100vw, 1024px" title="史上最強大的台股板塊圖 | 操作說明書 17"></figure>



<p class="has-medium-font-size">點擊不同的階層會自動縮放該階層內的資料，例如我想將上市半導體的區塊放大，可以點擊半導體業的小標題。另外游標拂過區塊會顯示對應數值資料。</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="748" src="https://www.finlab.tw/wp-content/uploads/2022/08/截圖-2022-08-02-上午11.00.30-1-1024x748.png" alt="截圖 2022 08 02 上午11.00.30 1" class="wp-image-4156" srcset="https://www.finlab.tw/wp-content/uploads/2022/08/截圖-2022-08-02-上午11.00.30-1-1024x748.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/08/截圖-2022-08-02-上午11.00.30-1-300x219.png 300w, https://www.finlab.tw/wp-content/uploads/2022/08/截圖-2022-08-02-上午11.00.30-1-768x561.png 768w, https://www.finlab.tw/wp-content/uploads/2022/08/截圖-2022-08-02-上午11.00.30-1-1536x1121.png 1536w, https://www.finlab.tw/wp-content/uploads/2022/08/截圖-2022-08-02-上午11.00.30-1.png 1789w" sizes="(max-width: 1024px) 100vw, 1024px" title="史上最強大的台股板塊圖 | 操作說明書 18"></figure>



<p class="has-medium-font-size">點擊後就可以得到放大的結果，如果想變回原來的樣子，再點擊一次半導體業的小標題，即可回到上一層。另外圖片的右上角照相機的圖案為下載圖片的功能，歡迎自由下載 FinLab 生成的圖片做多種應用喔！</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="724" src="https://www.finlab.tw/wp-content/uploads/2022/08/截圖-2022-08-02-上午11.00.47-1024x724.png" alt="截圖 2022 08 02 上午11.00.47" class="wp-image-4155" srcset="https://www.finlab.tw/wp-content/uploads/2022/08/截圖-2022-08-02-上午11.00.47-1024x724.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/08/截圖-2022-08-02-上午11.00.47-300x212.png 300w, https://www.finlab.tw/wp-content/uploads/2022/08/截圖-2022-08-02-上午11.00.47-768x543.png 768w, https://www.finlab.tw/wp-content/uploads/2022/08/截圖-2022-08-02-上午11.00.47-1536x1086.png 1536w, https://www.finlab.tw/wp-content/uploads/2022/08/截圖-2022-08-02-上午11.00.47.png 1816w" sizes="(max-width: 1024px) 100vw, 1024px" title="史上最強大的台股板塊圖 | 操作說明書 19"></figure>



<h2>盤後資料模式</h2>



<h3>產業模式</h3>



<ul class="has-medium-font-size"><li>主板類別<br>此類別使用的是證交所、櫃檯買賣中心的類股分類，大家券商 APP 上的類股劃分多依照此。這也是預設的產業模式。</li><li>產業鍊<br>此類別參考 <a href="https://ic.tpex.org.tw/index.php" target="_blank" rel="noopener">產業價值鏈資訊平台</a> 所編製，是證交算旗下的機構，將類股再拆分更細的產業，像是半導體類股再拆分IC設計、晶圓代工、記憶體等等。<br>產業鍊的資訊比較能劃分出公司業務，在追蹤族群性的數據分析時，能做更細緻的觀察。<br>彌補主板類別同一類股可能彼此差異很大的缺點是，像有些公司是借殼上市、業務轉型，早已不是最初的分類。<br>由於同一家公司如鴻海、台達電因業務包山包海，會出現在許多細產業，不像主板類別的每家公司只會出現一次，因此這類電子龍頭公司在產業鍊的權重較大，會對產業數值有較高影響力。<br>* 留意此模式會過濾成交量過小的企業與板塊，只會顯示代表性的產業與公司。<br></li></ul>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="555" src="https://www.finlab.tw/wp-content/uploads/2022/08/newplot-2-1024x555.png" alt="newplot 2" class="wp-image-4162" srcset="https://www.finlab.tw/wp-content/uploads/2022/08/newplot-2-1024x555.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/08/newplot-2-300x163.png 300w, https://www.finlab.tw/wp-content/uploads/2022/08/newplot-2-768x416.png 768w, https://www.finlab.tw/wp-content/uploads/2022/08/newplot-2.png 1200w" sizes="(max-width: 1024px) 100vw, 1024px" title="史上最強大的台股板塊圖 | 操作說明書 20"><figcaption>產業鍊模式</figcaption></figure>



<h3>板塊大小指標</h3>



<p class="has-medium-font-size">此數值會代表板塊面積的依據，你可以看目前市場資金流向、多空投機部隊集結在哪裡？<br>之前股癌提到融資集中的族群若沒大跌，融資不容易會斷頭，這用「融資餘額市值當面積」搭配不同天數的報酬率當顏色深淺，即可觀察。若想讓每家股票板塊權重一致，可選「家數」，這樣小型股就不會顯示太小。</p>



<ul class="has-medium-font-size"><li>資金流：<br>近一日成交金額</li><li>成交張數：</li><li>市值：<br>近一日收盤價*股本</li><li>融資餘額市值：<br>近一日收盤價*近一日融資餘額。常搭配融資使用率使用。</li><li>融券餘額市值：<br>近一日收盤價*近一日融券餘額。常搭配券資比維持率使用。</li><li>家數：<br>將個股權重一視同人都視為1，方便觀察全部類股，避免像用資金流，有些公司成交金額太小導致，面積佔比縮很小。</li></ul>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="798" src="https://www.finlab.tw/wp-content/uploads/2022/08/截圖-2022-08-02-上午11.20.12-1024x798.png" alt="截圖 2022 08 02 上午11.20.12" class="wp-image-4157" srcset="https://www.finlab.tw/wp-content/uploads/2022/08/截圖-2022-08-02-上午11.20.12-1024x798.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/08/截圖-2022-08-02-上午11.20.12-300x234.png 300w, https://www.finlab.tw/wp-content/uploads/2022/08/截圖-2022-08-02-上午11.20.12-768x599.png 768w, https://www.finlab.tw/wp-content/uploads/2022/08/截圖-2022-08-02-上午11.20.12-1536x1197.png 1536w, https://www.finlab.tw/wp-content/uploads/2022/08/截圖-2022-08-02-上午11.20.12.png 1688w" sizes="(max-width: 1024px) 100vw, 1024px" title="史上最強大的台股板塊圖 | 操作說明書 21"><figcaption>藉由融資餘額市值與融資使用率觀察投機資金集結在哪裡？</figcaption></figure>



<h3>顏色深淺指標</h3>



<p class="has-medium-font-size">總共有20種指標可選擇！<br>每個指標都有不同的顏色分界點，分界點數值為白色，高於分界點會越來越紅，低於則是越來越綠。若指標無特別說明，分界點為0，像報酬率是上漲偏紅、下跌偏綠、平盤附近為白色，某些指標為了明顯劃分顏色區隔，有設定特定的分界點，下述會說明。<br>若標地無資料，則區塊顯示黑色，像有些標的無法使用融資，則融資使用率就會呈現黑色。<br>若在月營收和財報季開獎階段，在數據持續開出的過程中，有些標地公告較慢，就會先是黑色。</p>



<h4>技術面</h4>



<p class="has-medium-font-size">觀察股價強弱勢與波動風險。</p>



<ul class="has-medium-font-size"><li>近1日報酬率</li><li>近5日報酬率</li><li>近20日報酬率</li><li>近1日震幅<br>近日股價最高與最低差額/前日收盤價。分界點為4%。</li><li>近10日真實波動率<br>近十日ATR/近日收盤價，也是震幅的一種方式，利用 <a href="https://www.finlab.tw/atr_keltner_channel/">ATR 技術指標</a> 的特性，除了當天高點點落差，考量隔日跳空因素去算入波動率。分界點為4%。</li></ul>



<h4>基本面</h4>



<ul class="has-medium-font-size"><li>近1月營收年增率<br>觀察營收短期趨勢，通常在每月1-10號月營收發佈期間作開獎觀察，若你觀察的公司還未開獎，但同一類股已開出的數字都不錯，那可能可考慮提前押寶喔。</li><li>近3月營收年增率<br>觀察營收短中期趨勢。像圖中的範例我們可明顯觀察出光電業和金融業的業績表現處於弱勢，網通、生技、航運處於強勢，基本面主觀選股可以留意族群性循環。<br></li></ul>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="781" src="https://www.finlab.tw/wp-content/uploads/2022/08/截圖-2022-08-02-下午4.01.56-1-1024x781.png" alt="截圖 2022 08 02 下午4.01.56 1" class="wp-image-4161" srcset="https://www.finlab.tw/wp-content/uploads/2022/08/截圖-2022-08-02-下午4.01.56-1-1024x781.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/08/截圖-2022-08-02-下午4.01.56-1-300x229.png 300w, https://www.finlab.tw/wp-content/uploads/2022/08/截圖-2022-08-02-下午4.01.56-1-768x586.png 768w, https://www.finlab.tw/wp-content/uploads/2022/08/截圖-2022-08-02-下午4.01.56-1-1536x1171.png 1536w, https://www.finlab.tw/wp-content/uploads/2022/08/截圖-2022-08-02-下午4.01.56-1.png 1892w" sizes="(max-width: 1024px) 100vw, 1024px" title="史上最強大的台股板塊圖 | 操作說明書 22"><figcaption>近3月營收年增率</figcaption></figure>



<ul class="has-medium-font-size"><li>近12月營收年增率<br>觀察營收長期趨勢。</li><li>本益比<br>分界點為15，高於此數值的是評價較高的，像生物科技產業就有高本益比特性。區塊反黑代表獲利為負數。</li><li>殖利率<br>分界點為 4%。存股族想看哪一個族群有高股息特性，選這就對了。</li><li>存貨季增率<br>我很常看 @Richard只談基本面-Richard&#8217;s Research Blog-信昕產研，版主對產業面觀察有洞見，他最近在盯「存貨季增率」，我也做上去了，每個產業的存貨堆積程度一目瞭然，可以再去對比近3月月營收是否衰退，有了板塊圖，就不用一個個單獨去查公開資訊觀測站。如果庫存大增、營收衰退，要注意基本面風險。像2022Q2 半導體前幾家開獎的情況，看來不妙啊！接下來相關產業的公司要留意利空。<br><img loading="lazy" width="1031" height="650" class="wp-image-4163" style="width: 600px;" src="https://www.finlab.tw/wp-content/uploads/2022/08/newplot-1.png" alt="newplot 1" srcset="https://www.finlab.tw/wp-content/uploads/2022/08/newplot-1.png 1031w, https://www.finlab.tw/wp-content/uploads/2022/08/newplot-1-300x189.png 300w, https://www.finlab.tw/wp-content/uploads/2022/08/newplot-1-1024x646.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/08/newplot-1-768x484.png 768w" sizes="(max-width: 1031px) 100vw, 1031px" title="史上最強大的台股板塊圖 | 操作說明書 23"><br></li></ul>



<h4>籌碼面</h4>



<ul class="has-medium-font-size"><li>外資買賣超/成交張數<br>觀察外資近一日買進力道，占比越高，代表短期外資影響力大。<br>板塊圖父階層採用平均數計算，較能凸顯產業買賣超力道。</li><li>投信買賣超/成交張數<br>觀察投信近一日買進力道，占比越高，代表短期投信影響力大。相較於外資，投信操作更具族群性，短期買超趨勢通常會持續幾天，是短線操作的重要觀察指標。<br>板塊圖父階層採用平均數計算，較能凸顯產業買賣超力道。<br>範例圖中可發現投信集火在右上角的電腦週邊產業，短線可以留意該族群。<br><br><img loading="lazy" width="1905" height="1408" class="wp-image-4164" style="width: 600px;" src="https://www.finlab.tw/wp-content/uploads/2022/08/截圖-2022-08-02-下午4.14.02.png" alt="截圖 2022 08 02 下午4.14.02" srcset="https://www.finlab.tw/wp-content/uploads/2022/08/截圖-2022-08-02-下午4.14.02.png 1905w, https://www.finlab.tw/wp-content/uploads/2022/08/截圖-2022-08-02-下午4.14.02-300x222.png 300w, https://www.finlab.tw/wp-content/uploads/2022/08/截圖-2022-08-02-下午4.14.02-1024x757.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/08/截圖-2022-08-02-下午4.14.02-768x568.png 768w, https://www.finlab.tw/wp-content/uploads/2022/08/截圖-2022-08-02-下午4.14.02-1536x1135.png 1536w" sizes="(max-width: 1905px) 100vw, 1905px" title="史上最強大的台股板塊圖 | 操作說明書 24"></li><li>融資增減張數/成交張數<br>內資短期多單指標，數值越高代表內資做多力道強。</li><li>融券增減張數/成交張數<br>內資短期空單指標，數值越高代表內資做多力道強。數值若為負值，越低代表空單回補力道大，觀察是否處於除權息或股東會的融券強制回補期間。</li><li>借券賣出增減張數/成交張數<br>法人空單指標，數值越高代表法人做空力道強，搭配法人買賣超觀察。</li><li>融資使用率<br>數值越高代表融資越多，代表投機資金入駐，通常該類股票波動都偏高。<br>分界點為15%。區塊反黑代表該標的無法融資券。</li><li>券資比<br>多空角力指標，若券資比飆高，股價也往上，可能有尬空行情。<br>分界點為15%。區塊反黑代表該標的無法融資券。</li><li>現股當沖率<br>當沖交易數/成交量，通常當沖參與度高的股票的投機性越強、波動大，喜歡操作當沖的話，可留意目前熱門標地有哪些。區塊反黑代表該標的無法當沖。<br>分界點為25%。</li><li>集保50張以下散戶持股占比<br>數值越高代表散戶持股越多，籌碼越不穩定，上漲趨勢通常延續性差。<br>分界點為25%。</li></ul>



<h2>盤中資料模式(2022/10新增)</h2>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="902" src="https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-26-上午9.43.48-1024x902.png" alt="截圖 2022 10 26 上午9.43.48" class="wp-image-4708" srcset="https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-26-上午9.43.48-1024x902.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-26-上午9.43.48-300x264.png 300w, https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-26-上午9.43.48-768x676.png 768w, https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-26-上午9.43.48-1536x1353.png 1536w, https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-26-上午9.43.48.png 1650w" sizes="(max-width: 1024px) 100vw, 1024px" title="史上最強大的台股板塊圖 | 操作說明書 25"><figcaption>盤中板塊圖</figcaption></figure>



<p class="has-medium-font-size">此板塊圖目前已放上量化平台網頁，限定「VIP」使用，如果你對 FinLab量化平台進階功能有興趣，請參考<a href="https://ai.finlab.tw/pricing" target="_blank" rel="noopener">訂閱方案</a>。<br>串接券商盤中即時報價，以監控盤中族群強弱，提供短線交易者當看盤小工具。每日0900~1330更新。更新頻率：3分鐘，重整網頁可得最新數據。「板塊大小指標」雷同盤後板塊圖，差異在「顏色深淺指標」以下做指標用途介紹：</p>



<ul class="has-medium-font-size"><li>報酬率<br>(市價 &#8211; 當日平盤價) / 前日收盤價，看族群漲跌強弱。</li><li>震幅<br>(當日最高價 &#8211; 當日最低價) / 前日收盤價，看波動率，越高代表投機資金聚集。</li><li>週轉率<br>當前成交總量 / 普通股發行數，週轉率越高代表交易越熱烈，大於20%要注意投機過熱情形，若板塊圖很少紅色區塊，代表市場交投冷清。</li><li>量增率<br>當前成交總量 / 前日成交總量 ，若比率大於1，代表出現量增情況。若盤中成交量就大於前日總成交量，代表攻擊力道變強，方向需搭配報酬率指標一同觀察。</li><li>均價支撐強度<br>市價 / 當日成交均價，若比率大於1，代表今日買方成交單多是獲利，盤中方向偏多方，壓力較小，反之則短線賣壓較大。</li><li>收盤 / 開盤_強度指標<br>(市價 &#8211; 當日開盤價) / 當日開盤價，觀察整體市場是否出現「開高走低」或「開低走高」，前者代表盤中力道偏空方，後者代表盤中力道偏多方。</li></ul>



<h2>盤中觀察實例演練</h2>



<p class="has-medium-font-size">拿觀察2022/10/26盤勢當應用範例</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="864" src="https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-26-下午12.12.33-1024x864.png" alt="截圖 2022 10 26 下午12.12.33" class="wp-image-4712" srcset="https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-26-下午12.12.33-1024x864.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-26-下午12.12.33-300x253.png 300w, https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-26-下午12.12.33-768x648.png 768w, https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-26-下午12.12.33-1536x1296.png 1536w, https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-26-下午12.12.33.png 1622w" sizes="(max-width: 1024px) 100vw, 1024px" title="史上最強大的台股板塊圖 | 操作說明書 26"><figcaption>週轉率</figcaption></figure>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="859" src="https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-26-下午12.07.47-1024x859.png" alt="截圖 2022 10 26 下午12.07.47" class="wp-image-4713" srcset="https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-26-下午12.07.47-1024x859.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-26-下午12.07.47-300x252.png 300w, https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-26-下午12.07.47-768x645.png 768w, https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-26-下午12.07.47-1536x1289.png 1536w, https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-26-下午12.07.47.png 1655w" sizes="(max-width: 1024px) 100vw, 1024px" title="史上最強大的台股板塊圖 | 操作說明書 27"><figcaption>收盤 / 開盤_強度指標</figcaption></figure>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="852" src="https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-26-下午12.14.53-1024x852.png" alt="截圖 2022 10 26 下午12.14.53" class="wp-image-4714" srcset="https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-26-下午12.14.53-1024x852.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-26-下午12.14.53-300x249.png 300w, https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-26-下午12.14.53-768x639.png 768w, https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-26-下午12.14.53-1536x1277.png 1536w, https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-26-下午12.14.53.png 1651w" sizes="(max-width: 1024px) 100vw, 1024px" title="史上最強大的台股板塊圖 | 操作說明書 28"><figcaption>均價支撐強度</figcaption></figure>



<ul class="has-medium-font-size"><li>週轉率<br>高週轉率的紅色家數很少，市況冷清，沒人玩。</li><li>收盤 / 開盤_強度指標<br>成交量多的標的多開高走低，弱勢盤。</li><li>均價支撐強度:<br>紅色偏多，搭配「收盤 / 開盤_強度指標」一同觀察，股價開高走低，買盤則是低接較多，比較少追高，所以成交均價低於市價。</li></ul>



<h2>小結</h2>



<p class="has-medium-font-size">一張圖貫穿所有關鍵指標，是不是很實用呢 ? 趕緊來探索這好用的功能。<br>覺得有幫助的話，可以將<a href="https://ai.finlab.tw/industry/?industry=%E5%8D%8A%E5%B0%8E%E9%AB%94%E6%A5%AD&amp;tab=%E6%9D%BF%E5%A1%8A%E5%9C%96" target="_blank" rel="noopener">台股板塊圖網頁</a>加入我的最愛，時常來關注喔！<br>預計每天晚上19:00、21:30 都會更新，21:30後才有融資融券相關數據喔。<br>有同學許願想學如何客製化自己的板塊圖，添入其他數據到到自己專屬圖表，或許不久的將來就能實現！大家一起享受資料視覺化的方便與美好吧！</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/%e5%8f%b2%e4%b8%8a%e6%9c%80%e5%bc%b7%e5%a4%a7%e7%9a%84%e5%8f%b0%e8%82%a1%e6%9d%bf%e5%a1%8a%e5%9c%96-%e6%93%8d%e4%bd%9c%e8%aa%aa%e6%98%8e%e6%9b%b8/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">4151</post-id>	</item>
		<item>
		<title>客製化流動性風險檢測 &#124; 策略可以實戰嗎?</title>
		<link>https://www.finlab.tw/customized_liquidityanalysis/</link>
					<comments>https://www.finlab.tw/customized_liquidityanalysis/#respond</comments>
		
		<dc:creator><![CDATA[Ben]]></dc:creator>
		<pubDate>Mon, 27 Jun 2022 00:39:19 +0000</pubDate>
				<category><![CDATA[FinLab 量化平台]]></category>
		<category><![CDATA[VIP文章]]></category>
		<category><![CDATA[生產力]]></category>
		<category><![CDATA[選股策略]]></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=4063</guid>

					<description><![CDATA[要讓實戰與回測貼合，流動性風險是必須要解決的，市面上的回測系統卻常忽略台股的流動性風險特性，導致開發者對策略回測的流動性風險是一頭霧水。FinLab對此開發了檢測模組，更細緻化呈現台股策略體質。]]></description>
										<content:encoded><![CDATA[
<p class="has-medium-font-size">回測用出好看的年化報酬率、夏普率並不是太難，但你有想過策略真的可以上線實戰嗎？會不會一切只是自嗨的紙上談兵，舉幾個戳破理想泡泡的例子:</p>



<ul class="has-medium-font-size"><li>選到很多開收盤就漲停的股票，回測都假設你有排到成交單，但實際上線卻是委託單大排長龍，常難以成交半張？</li><li>選到成交量或成交金額過低的標的，你的資金根本進不去，或進去後又難出來？</li><li>遇到處置股或全額交割股的情況，在 T+2 交割制度下，你手上不一定有現金可以馬上匯款，分盤交易的價差大，波動風險高，弄自動化下單也麻煩。</li></ul>



<p class="has-medium-font-size">如果你策略上線很常碰到此類問題，會導致你買賣點位的延遲，實戰績效與回測的偏差就有可能很大。要讓實戰與回測貼合，流動性風險是必須要解決的，市面上的回測系統卻常忽略台股的流動性風險特性，導致開發者對策略回測的流動性風險是一頭霧水。FinLab 對此開發了檢測模組，更細緻化呈現台股策略體質。</p>



<h2>流動性風險檢測API教學</h2>



<h3>檢測方法</h3>



<p class="has-medium-font-size">FinLab API 已有現成的<a href="https://doc.finlab.tw/reference/analysis/#finlab.analysis.liquidityAnalysis.LiquidityAnalysis" target="_blank" rel="noopener">流動性檢測的文件範例</a>。<br>利用DataFrame Style呈現數值，將多數人會用到的指標呈現出來。</p>



<figure class="wp-block-image size-full"><img loading="lazy" width="956" height="212" src="https://www.finlab.tw/wp-content/uploads/2022/08/liq-analysis.png" alt="liq analysis" class="wp-image-4178" srcset="https://www.finlab.tw/wp-content/uploads/2022/08/liq-analysis.png 956w, https://www.finlab.tw/wp-content/uploads/2022/08/liq-analysis-300x67.png 300w, https://www.finlab.tw/wp-content/uploads/2022/08/liq-analysis-768x170.png 768w" sizes="(max-width: 956px) 100vw, 956px" title="客製化流動性風險檢測 | 策略可以實戰嗎? 29"></figure>



<h2>如何打造自己的流動性檢測？</h2>



<p class="has-medium-font-size">如果我們想多新增一些指標，像原本FinLab模組的買遇漲跌停機率是依照回測的 trade_at 參數來選擇用開盤價和收盤價計算，但若想要同時呈現開盤價、收盤價，好一次比較用開盤價還是收盤價哪個比較好？以及想將圖表轉為Plotly的圖表形式該怎麼做呢？</p>



<p class="has-medium-font-size">其實很多策略檢測的數據都來自於`finlab.backtest.sim().get.trades()`，利用策略回測的逐筆交易表我們可以得知每次買賣點位與波動資訊，這張表可以做的應用非常多。<br>流動性檢測就是依照這張表的資料取出進出場日期，再去映射漲跌幅、成交量、當日為處置股等等資訊。</p>



<h3>程式範例</h3>



<p class="has-medium-font-size"><a href="https://drive.google.com/file/d/1vAKTOgQ9vc0VnHHzBTHhj33CLsJHoXZ-/view?usp=sharing" target="_blank" rel="noopener">colab 檔案連結</a></p>



<pre class="wp-block-code"><code lang="python" class="language-python">def get_liquidity_risk_data(return_bias=0.01, required_volume=200000, required_turnover=1000000,
                            simplified_metrics=False):
    adj_close = data.get('etl:adj_close')
    adj_open = data.get('etl:adj_open')
    close_return = ((adj_close / adj_close.shift()) - 1).fillna(0)
    open_return = ((adj_open / adj_close.shift()) - 1).fillna(0)

    def cal_return_gap(returns_df, up=True):
        if up:
            early_rule = returns_df[returns_df.index &lt; '2015-06-01'] &gt; (0.07 - return_bias)
            last_rule = returns_df[returns_df.index &gt;= '2015-06-01'] &gt; (0.1 - return_bias)
        else:
            early_rule = returns_df[returns_df.index &lt; '2015-06-01'] &lt; -(0.07 - return_bias)
            last_rule = returns_df[returns_df.index &gt;= '2015-06-01'] &lt; -(0.1 - return_bias)
        cond = pd.concat([early_rule, last_rule])
        return cond

    liq_risk_data = {
        "c/c-limit_up": cal_return_gap(close_return),
        "c/c-limit_down": cal_return_gap(close_return, up=False),
        "o/c-limit_up": cal_return_gap(open_return),
        "o/c-limit_down": cal_return_gap(open_return, up=False),
    }

    if simplified_metrics is False:
        vol = data.get('price:成交股數')
        turnover = data.get('price:成交金額')
        disposal_stock_filter = data.get('etl:disposal_stock_filter')
        noticed_stock_filter = data.get('etl:noticed_stock_filter')
        full_cash_delivery_stock_filter = data.get('etl:full_cash_delivery_stock_filter')
        oo_return = ((adj_open / adj_open.shift()) - 1).fillna(0)
        liq_risk_data.update({
            "o/o_limit_up": cal_return_gap(oo_return),
            "o/o_limit_down": cal_return_gap(oo_return, up=False),
            "volume": vol &lt; abs(required_volume),
            "turnover": turnover &lt; abs(required_turnover),
            "disposal": disposal_stock_filter.shift() &lt; 1,
            "noticed": noticed_stock_filter.shift() &lt; 1,
            "full_cash_delivery": full_cash_delivery_stock_filter.shift() &lt; 1
        })
    return liq_risk_data


def calculate_liquidity_risk(backtest_report,return_bias=0.01, required_volume=200000, required_turnover=1000000, simplified_metrics=False):
    liq_risk_data = get_liquidity_risk_data(return_bias, required_volume, required_turnover, simplified_metrics)
    trades = backtest_report.get_trades().copy()
    if (len(liq_risk_data) &lt; 1) or (len(trades) &lt; 1):
        return None
    trades['stock_id'] = trades['stock_id'].apply(lambda s: s[:s.index(' ')])
    entry_trades = trades.set_index(['stock_id', 'entry_date'])
    exit_trades = trades.set_index(['stock_id', 'exit_date'])

    def unstack_data(df):
        df = df.unstack()
        df.index.names = ['stock_id', 'date']
        return df

    stats_data = {'entry': {}, 'exit': {}}

    for k, v in liq_risk_data.items():
        risk_item = unstack_data(v)
        entry_trades[k] = risk_item
        exit_trades[k] = risk_item
        stats_data['entry'][k] = entry_trades[k].mean()
        stats_data['exit'][k] = exit_trades[k].mean()

    lr_data = round(pd.DataFrame(stats_data)*100,2).T
    if simplified_metrics:
        lr_data = {'close_liq_risk':lr_data.loc['entry','c/c-limit_up']+lr_data.loc['exit','c/c-limit_down'],
                   'open_liq_risk':lr_data.loc['entry','o/c-limit_up']+lr_data.loc['exit','o/c-limit_down']}
    return lr_data


def display_liquidity_risk(backtest_report,stats_data=None,return_bias=0.01, required_volume=200000, required_turnover=1000000,
                           color_continuous_scale='RdBu_r', cmax=25):
    import plotly.express as px
    if stats_data is None:
        stats_data = calculate_liquidity_risk(backtest_report,return_bias, required_volume, required_turnover, simplified_metrics=False)
    fig = px.imshow(stats_data, labels=dict(x="Risk", y="Point", color="Proportion(%)"), text_auto=True,
                    color_continuous_scale=color_continuous_scale)
    fig.update_layout(
        title={
            'text': "Liquidity Risk Statistics",
            'y': 0.9,
            'x': 0.5,
            'xanchor': 'center',
            'yanchor': 'top'},
        coloraxis={
            'cmin': 0,
            'cmax': cmax,
        },
        coloraxis_colorbar={
            'x': 0.5,
            'y': -0.15,
            'orientation': 'h',
        },
    )
    return fig</code></pre>



<h3>客製化display_liquidity_risk 參數設定</h3>



<ul class="has-medium-font-size"><li>return_bias (float) : 與漲跌停板的價格偏差，預設是0.01，也就是漲幅在0.09以上就算漲停板，會這樣設計是因為台股不同的價位會有不同的 tick 單位，像10元以下的股票是0.01為變動單位、10-50元的股票是0.05為變動單位，實際漲停板有可能小於10%。另外2015/6/1前台股的漲跌幅是 7% (<a href="https://www.twse.com.tw/zh/page/trading/information8.html" target="_blank" rel="noopener">證交所公告</a>) ，扣掉 return_bias 就會是以漲幅在0.06以上就算漲停，程式已針對不同歷史區段做檢測。保守的投資人可以將return_bias調大到 0.02-0.03 ，給漲跌停更寬的定義，等於不希望追高。</li><li>required_volume (int)  : 成交量最低要求股數 ，預設200000股 (200張)。</li><li>required_turnover (int) : 成交金額最低要求數 ，預設100萬元。</li><li>color_continuous_scale (str) : 熱力圖色階，預設為RdBu_r。</li><li>cmax (float) : 熱力圖色階上限，預設是25，設定越高代表可以接受的風險程度越高，色階中間點 (cmid) 為cmax/2，若以預設值為範例，低於12.5%的檢測項目會偏藍，高於12.5%的檢測項目會偏紅，cmid 會跟著cmax同步變化。</li></ul>



<h3>檢測項目</h3>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="371" src="https://www.finlab.tw/wp-content/uploads/2022/06/newplot-7-1024x371.png" alt="newplot 7" class="wp-image-4069" srcset="https://www.finlab.tw/wp-content/uploads/2022/06/newplot-7-1024x371.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/06/newplot-7-300x109.png 300w, https://www.finlab.tw/wp-content/uploads/2022/06/newplot-7-768x278.png 768w, https://www.finlab.tw/wp-content/uploads/2022/06/newplot-7-150x54.png 150w, https://www.finlab.tw/wp-content/uploads/2022/06/newplot-7.png 1449w" sizes="(max-width: 1024px) 100vw, 1024px" title="客製化流動性風險檢測 | 策略可以實戰嗎? 30"><figcaption>流動性風險檢測熱力圖</figcaption></figure>



<p class="has-medium-font-size"><br>Y軸為進出場，X軸為風險項目，依據每筆回測交易的進出場的價格來檢測，顏色越紅的代表是越需要注意的項目，後續對檢測項目及參數的細節說明。</p>



<ul class="has-medium-font-size"><li>c/c_limit_up : 收盤價遇到近漲停版的比例。進場時越少碰到越好。</li><li>c/c_limit_down : 收盤價遇到近跌停版的比例。出場時越少碰到越好。</li><li>o/c_limit_up : 開盤價遇到近漲停版的比例。進場時越少碰到越好。</li><li>o/c_limit_down : 開盤價遇到近跌停版的比例。出場時越少碰到越好。</li><li>o/o_limit_up : 開盤價和前日開盤價的漲跌幅超過漲停版的比例。越高代表月多標的是大波動。</li><li>o/o_limit_down : 開盤價和前日開盤價的漲跌幅超過跌停版的比例。越高代表月多標的是大波動。</li><li>volume : 成交量低於最低要求股數 (預設200000股) 的比例。越高代表選到冷門中小型股機率越高。</li><li>turnover : 成交金額低於最低要求金額 (預設100萬元) 的比例。此項檢測是要避免選到成交股數足夠，但是碰到低價股的狀況，這時可能會產生部位金額無法滿足的情況 ;  成交金額足夠，成交股數過低也不好，因為實務上不太可能每一股都買到。volume 與 turnover 最好都要同步符合要求 。</li><li>disposal : <a href="https://www.sinotrade.com.tw/richclub/freshman/%E6%B3%A8%E6%84%8F%E8%82%A1-%E8%99%95%E7%BD%AE%E8%82%A1%E6%98%AF%E4%BB%80%E9%BA%BC-%E4%B8%80%E6%AC%A1%E8%AE%93%E4%BD%A0%E6%90%9E%E6%87%82-%E8%82%A1%E6%B0%91%E9%83%BD%E6%83%B3%E7%9F%A5%E9%81%93%E7%9A%84%E8%82%A1%E7%A5%A8%E5%85%A5%E7%8D%84%E6%A2%9D%E4%BB%B6--60e55145ba4ba620cc092e37" target="_blank" rel="noopener">處置股</a>的比例。分盤交易會降低流動性，並拉大價差，造成買賣點位不好掌握。</li><li>noticed : <a href="https://www.sinotrade.com.tw/richclub/freshman/%E6%B3%A8%E6%84%8F%E8%82%A1-%E8%99%95%E7%BD%AE%E8%82%A1%E6%98%AF%E4%BB%80%E9%BA%BC-%E4%B8%80%E6%AC%A1%E8%AE%93%E4%BD%A0%E6%90%9E%E6%87%82-%E8%82%A1%E6%B0%91%E9%83%BD%E6%83%B3%E7%9F%A5%E9%81%93%E7%9A%84%E8%82%A1%E7%A5%A8%E5%85%A5%E7%8D%84%E6%A2%9D%E4%BB%B6--60e55145ba4ba620cc092e37" target="_blank" rel="noopener">注意股</a>的比例。注意股為處置股的前兆，連續進入注意股多次後會進處置。</li><li>full_cash_delivery : <a href="https://tw.news.yahoo.com/news/%E4%BB%80%E9%BA%BC%E6%98%AF%E5%85%A8%E9%A1%8D%E4%BA%A4%E5%89%B2%E8%82%A1%EF%BC%9F%E8%B7%9F%E8%99%95%E7%BD%AE%E8%82%A1%E7%A5%A8%E6%9C%89%E4%BD%95%E4%B8%8D%E5%90%8C%EF%BC%9F-043040582.html" target="_blank" rel="noopener">全額交割股</a>的比例。通常全額交割股都有財務風險的疑慮 (每股淨值低於５元)，部分處置股可能也會有全額交割的處置狀況。</li></ul>



<h2>檢測實際演練</h2>



<h3>範例1.<a href="https://ai.finlab.tw/strategyview/?uid=TJN4FDuqrwU8DML7DAjUYFIMutp2&amp;sid=%E7%87%9F%E6%94%B6%E5%BC%B7%E5%8B%A2%E5%8B%95%E8%83%BD%E7%98%8B%E7%8B%97" target="_blank" rel="noopener">營收動能瘋狗</a></h3>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="913" src="https://www.finlab.tw/wp-content/uploads/2022/06/截圖-2022-06-24-下午5.36.32-1024x913.png" alt="截圖 2022 06 24 下午5.36.32" class="wp-image-4071" srcset="https://www.finlab.tw/wp-content/uploads/2022/06/截圖-2022-06-24-下午5.36.32-1024x913.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/06/截圖-2022-06-24-下午5.36.32-300x267.png 300w, https://www.finlab.tw/wp-content/uploads/2022/06/截圖-2022-06-24-下午5.36.32-768x685.png 768w, https://www.finlab.tw/wp-content/uploads/2022/06/截圖-2022-06-24-下午5.36.32-150x134.png 150w, https://www.finlab.tw/wp-content/uploads/2022/06/截圖-2022-06-24-下午5.36.32.png 1272w" sizes="(max-width: 1024px) 100vw, 1024px" title="客製化流動性風險檢測 | 策略可以實戰嗎? 31"><figcaption>營收動能瘋狗 &#8211; 報酬率</figcaption></figure>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="371" src="https://www.finlab.tw/wp-content/uploads/2022/06/newplot-7-1-1024x371.png" alt="newplot 7 1" class="wp-image-4070" srcset="https://www.finlab.tw/wp-content/uploads/2022/06/newplot-7-1-1024x371.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/06/newplot-7-1-300x109.png 300w, https://www.finlab.tw/wp-content/uploads/2022/06/newplot-7-1-768x278.png 768w, https://www.finlab.tw/wp-content/uploads/2022/06/newplot-7-1-150x54.png 150w, https://www.finlab.tw/wp-content/uploads/2022/06/newplot-7-1.png 1449w" sizes="(max-width: 1024px) 100vw, 1024px" title="客製化流動性風險檢測 | 策略可以實戰嗎? 32"><figcaption>營收動能瘋狗 &#8211; 流動性風險</figcaption></figure>



<p class="has-medium-font-size">年化報酬率高達47%，夏普率1.6，乍看下非常不錯，真的可上線就太好了！<br>拿來照妖一下流動性風險 (我比較保守，cmax調成15，指標過7.5%就會偏紅)。<br>果然熱力圖有幾個紅區出現，應檢視風險並考慮作出對應調整：</p>



<ul class="has-medium-font-size"><li>策略追動能，大波動特性讓它用收盤價買進碰到漲停機率偏高，達13.26% ! 用收盤價出場的機率達4.6%，但若用開盤價進出，漲跌停流動性風險可以明顯縮減到5.25%、1.82%。顯示用開盤價比收盤價更能避免碰漲跌停的情況，比較能在回測的當日買到。若還是覺得碰漲跌停比例太高，那要考慮加上低波動濾網，去降低波動。</li><li>策略出場遇到成交股數低於200張的情況也稍高，顯示小型股佔一定比例，實戰時的資金要配置得宜。</li><li>策略遇到處置股、注意股的機率比一般策略高，又是一個高波動特質，不喜歡遭遇分盤買賣，失去交易彈性的人也要斟酌。</li></ul>



<p class="has-medium-font-size">若我們根據以上分析將策略改以開盤價進出場並加上處置股濾網以避免買進處置股的情況，策略報酬率會變如何呢？結果發現報酬率、夏普率、最大回撤都變差了一些，為何報酬率會變差，可能可從o/o_limit_up比例達14.73%的情況來解釋，開盤價間隔的波動風險更大於收盤價波動13.26%，用開盤價買賣可能碰上大震盪 (ex: 昨日開盤跌停 &#8211; 昨日收盤漲停 &#8211; 今日開盤小漲)的情況，如此波動可能在20-30％間，雖然今日開盤買進流動性風險較低，但追高風險不見得低喔。</p>



<p class="has-medium-font-size">這才是策略實戰比較真實的情況！雖然降低報酬率的相關指標，但也減少了流動性風險。</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="858" src="https://www.finlab.tw/wp-content/uploads/2022/06/截圖-2022-06-27-上午10.30.41-1024x858.png" alt="截圖 2022 06 27 上午10.30.41" class="wp-image-4072" srcset="https://www.finlab.tw/wp-content/uploads/2022/06/截圖-2022-06-27-上午10.30.41-1024x858.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/06/截圖-2022-06-27-上午10.30.41-300x251.png 300w, https://www.finlab.tw/wp-content/uploads/2022/06/截圖-2022-06-27-上午10.30.41-768x643.png 768w, https://www.finlab.tw/wp-content/uploads/2022/06/截圖-2022-06-27-上午10.30.41-150x126.png 150w, https://www.finlab.tw/wp-content/uploads/2022/06/截圖-2022-06-27-上午10.30.41.png 1256w" sizes="(max-width: 1024px) 100vw, 1024px" title="客製化流動性風險檢測 | 策略可以實戰嗎? 33"><figcaption>降低流動性風險的營收動能瘋狗策略</figcaption></figure>



<h3>範例2.<a href="https://ai.finlab.tw/strategyview/?uid=TJN4FDuqrwU8DML7DAjUYFIMutp2&amp;sid=%E6%9C%AC%E7%9B%8A%E6%88%90%E9%95%B7%E6%AF%94" target="_blank" rel="noopener">本益成長比</a></h3>



<p class="has-medium-font-size">假設是比較小資的投資人，我可能對成交金額下限的要求沒那麼高，但希望成交股數上限高於預設值的200張，調高到500張，成交金額下限調低成20萬，設定函數參數成<code> </code><br><code>display_liquidity_risk(required_volume=500000, required_turnover=200000)</code><br>這樣比較好隨時買。來看看回測結果:</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="859" src="https://www.finlab.tw/wp-content/uploads/2022/06/截圖-2022-06-27-上午10.36.30-1024x859.png" alt="截圖 2022 06 27 上午10.36.30" class="wp-image-4073" srcset="https://www.finlab.tw/wp-content/uploads/2022/06/截圖-2022-06-27-上午10.36.30-1024x859.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/06/截圖-2022-06-27-上午10.36.30-300x252.png 300w, https://www.finlab.tw/wp-content/uploads/2022/06/截圖-2022-06-27-上午10.36.30-768x645.png 768w, https://www.finlab.tw/wp-content/uploads/2022/06/截圖-2022-06-27-上午10.36.30-150x126.png 150w, https://www.finlab.tw/wp-content/uploads/2022/06/截圖-2022-06-27-上午10.36.30.png 1282w" sizes="(max-width: 1024px) 100vw, 1024px" title="客製化流動性風險檢測 | 策略可以實戰嗎? 34"><figcaption>本益成長比策略 &#8211; 報酬率</figcaption></figure>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="371" src="https://www.finlab.tw/wp-content/uploads/2022/06/newplot-10-1024x371.png" alt="newplot 10" class="wp-image-4074" srcset="https://www.finlab.tw/wp-content/uploads/2022/06/newplot-10-1024x371.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/06/newplot-10-300x109.png 300w, https://www.finlab.tw/wp-content/uploads/2022/06/newplot-10-768x278.png 768w, https://www.finlab.tw/wp-content/uploads/2022/06/newplot-10-150x54.png 150w, https://www.finlab.tw/wp-content/uploads/2022/06/newplot-10.png 1449w" sizes="(max-width: 1024px) 100vw, 1024px" title="客製化流動性風險檢測 | 策略可以實戰嗎? 35"><figcaption>本益成長比策略 &#8211; 流動性風險</figcaption></figure>



<p class="has-medium-font-size">流動性風險熱力圖顯示大部分的指標都偏低，比起上一個大波動策略的範例好上許多，一樣是開盤價比用收盤價進場遇漲跌停的風險低，但差異比較小，在差異不是很大的情況下，也不一定要堅持用開盤，自行斟酌。<br>這個策略主要的問題是大部分的交易都低於要求的成交股數，顯示有選到許多冷門中小型股，極端一點的可能一天才幾張量，通常此項數值會這麼高是因為沒有設定成交量的濾網。<br>如果我們將此策略加上近10日平均成交量大於500張、用開盤價進出場的條件回測，會變如何呢？</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="849" src="https://www.finlab.tw/wp-content/uploads/2022/06/截圖-2022-06-27-上午11.04.02-1024x849.png" alt="截圖 2022 06 27 上午11.04.02" class="wp-image-4075" srcset="https://www.finlab.tw/wp-content/uploads/2022/06/截圖-2022-06-27-上午11.04.02-1024x849.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/06/截圖-2022-06-27-上午11.04.02-300x249.png 300w, https://www.finlab.tw/wp-content/uploads/2022/06/截圖-2022-06-27-上午11.04.02-768x637.png 768w, https://www.finlab.tw/wp-content/uploads/2022/06/截圖-2022-06-27-上午11.04.02-150x124.png 150w, https://www.finlab.tw/wp-content/uploads/2022/06/截圖-2022-06-27-上午11.04.02.png 1285w" sizes="(max-width: 1024px) 100vw, 1024px" title="客製化流動性風險檢測 | 策略可以實戰嗎? 36"><figcaption>本益成長比策略排除流動性風險</figcaption></figure>



<p class="has-medium-font-size">結果發現報酬率相關數據差一大截！雖然還是優於大盤&#8230;但拿掉小型股後，報酬率明顯變差，顯示這隻策略多數績效由小型股貢獻，這時要思考該策略是不是不能實戰，又或是接受比較高的流動性風險。</p>



<h2>結論</h2>



<p class="has-medium-font-size">一個好的策略在沒有經過嚴刑拷打之前，你敢用嗎？小心能駛萬年船！好策略不是寫完幾行代碼就直接上了。<br>趕緊來檢測你的策略是不是有流動性風險過高的毛病，除了流動性風險，波動風險也是要留意的，FinLab 也有<a href="https://www.finlab.tw/display_mae_mfe_analysis/">波動分析模組</a>可以使用，都是使用一行程式碼就能執行檢測的好工具！</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/customized_liquidityanalysis/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">4063</post-id>	</item>
		<item>
		<title>Plotly-Sunburst｜輕鬆監控多策略部位｜DashBoard 應用教學(5)</title>
		<link>https://www.finlab.tw/plotly-sunburst-dashboard/</link>
					<comments>https://www.finlab.tw/plotly-sunburst-dashboard/#respond</comments>
		
		<dc:creator><![CDATA[Ben]]></dc:creator>
		<pubDate>Fri, 17 Jun 2022 00:34:08 +0000</pubDate>
				<category><![CDATA[生產力]]></category>
		<category><![CDATA[FinLab 量化平台]]></category>
		<category><![CDATA[Python新手教學]]></category>
		<category><![CDATA[Plotly]]></category>
		<category><![CDATA[sunburst]]></category>
		<category><![CDATA[多策略]]></category>
		<category><![CDATA[資料視覺化]]></category>
		<guid isPermaLink="false">https://www.finlab.tw/?p=3858</guid>

					<description><![CDATA[Plotly - Sunburst 是不是十分絢麗呢！可以作多層次是覺化呈現及圖表互動。利用FinLab套件的 StrategySunburst 可以很輕鬆地將多策略資料漂亮地呈現出來，並觀察裡面的insight，當作其中一個管理多策略的工具，不同的繪圖參數設定能玩出不同的效果，趕快來試試吧！]]></description>
										<content:encoded><![CDATA[
<h2>開發動機</h2>



<p class="has-medium-font-size">你的 FinLab 量化平台的策略儀表板上是不是有很多豐富的策略呢？<br>如果答案為是，代表你很棒，嘗試了許多量化策略的實驗，有些策略拿來實驗想法、有些是真的拿來實戰。這時你可能會有下面幾個問題想處理，我想監控儀表板上真正拿來實戰的策略，看每個策略綜整後的部位為何？策略們的標的集中在哪些類股？哪些標的被多個策略同時選中或是比重最大？這時 Sunburst (旭日圖) 可能是你監控策略部位最好的資料視覺化武器之一，FinLab 已開發好工具了！來看看怎麼使用吧！</p>



<h2>Sunburst 是怎樣的圖表？</h2>



<p class="has-medium-font-size">Sunburst 是圓餅圖的進化版，可以顯示分層數據的比例關係，不同的子資料對應於不同級別層次結構，你可以想成是 <a href="https://www.finlab.tw/dashboard2-plotly-treemap/">Treemap</a> 的變化版，都可以使用面積與顏色呈現不同維度的資料，Sunburst 與 Treemap 的差異在允許子資料缺角，不一定要填滿，像是以下的圖例，使用起來比 Treemap 更有彈性，Treemap 就一定要填滿部位。</p>



<figure class="wp-block-image size-full"><img loading="lazy" width="903" height="525" src="https://www.finlab.tw/wp-content/uploads/2022/06/newplot-11.png" alt="newplot 11" class="wp-image-3862" srcset="https://www.finlab.tw/wp-content/uploads/2022/06/newplot-11.png 903w, https://www.finlab.tw/wp-content/uploads/2022/06/newplot-11-300x174.png 300w, https://www.finlab.tw/wp-content/uploads/2022/06/newplot-11-768x447.png 768w, https://www.finlab.tw/wp-content/uploads/2022/06/newplot-11-150x87.png 150w" sizes="(max-width: 903px) 100vw, 903px" title="Plotly-Sunburst｜輕鬆監控多策略部位｜DashBoard 應用教學(5) 37"><figcaption>Sunburst 缺角圖<a href="https://plotly.com/python/sunburst-charts/" target="_blank" rel="noopener">https://plotly.com/python/sunburst-charts/</a></figcaption></figure>



<h2>Plotly-Sunburst 基礎教學</h2>



<h3>圖例</h3>



<p class="has-medium-font-size">plotly 官方文件提供了多元的 <a href="https://plotly.com/python/sunburst-charts/" target="_blank" rel="noopener">Sunburst 範例程式</a>，我們的多策略部位 Sunburst 會以色階型態的 Sunburst 範例為底，用色階變化呈現漲跌幅度，用面積顯示部位權重。</p>



<figure class="wp-block-image size-full"><img loading="lazy" width="903" height="525" src="https://www.finlab.tw/wp-content/uploads/2022/06/newplot-13.png" alt="newplot 13" class="wp-image-3863" srcset="https://www.finlab.tw/wp-content/uploads/2022/06/newplot-13.png 903w, https://www.finlab.tw/wp-content/uploads/2022/06/newplot-13-300x174.png 300w, https://www.finlab.tw/wp-content/uploads/2022/06/newplot-13-768x447.png 768w, https://www.finlab.tw/wp-content/uploads/2022/06/newplot-13-150x87.png 150w" sizes="(max-width: 903px) 100vw, 903px" title="Plotly-Sunburst｜輕鬆監控多策略部位｜DashBoard 應用教學(5) 38"><figcaption>色階型 SunBurst </figcaption></figure>



<h3>程式解構</h3>



<pre class="wp-block-code"><code lang="python" class="language-python">import plotly.express as px
import numpy as np
df = px.data.gapminder().query("year == 2007")
fig = px.sunburst(df, path=['continent', 'country'], values='pop',
                  color='lifeExp', hover_data=['iso_alpha'],
                  color_continuous_scale='RdBu',
                  color_continuous_midpoint=np.average(df['lifeExp'], weights=df['pop']))
fig.show()</code></pre>



<p class="has-medium-font-size"><code>plotly.express</code> 提供了高封裝程度的 API，讓我們可以用簡單的語法來繪圖，插入資料以 dataframe 來控制。接著說明一下 sunburst 裡的重要參數。</p>



<ul class="has-medium-font-size"><li>path：sunburst 分層路徑，list 資料是 dataframe 裡的欄位名稱，先後順序代表由裡到外的層級。</li><li>values：決定圓餅面積比例的欄位。</li><li>colors：決定圓餅色階的欄位。</li><li>hovers：游標滑過區塊部位時，想外加的顯示欄位。</li><li>color_continuous_scale：色階條樣式，RdBu 是常用樣式，可以自選<a href="https://plotly.com/python/builtin-colorscales/" target="_blank" rel="noopener">其他樣式</a>。</li><li>color_continuous_midpoint：色階中間決定斷點，用來控制色階深淺區間，範例是取平均壽命當中間點。</li></ul>



<h2>StrategySunburst 物件教學</h2>



<p class="has-medium-font-size"><code>finlab.plot.StrategySunburst()</code><br>提供了多策略的資料處理與視覺化功能，並將 plotly sunburst 的繪圖功能包裝進來。</p>



<h3>獲取多策略資料</h3>



<p class="has-medium-font-size">可以用s_data屬性連結到<code>finlab.data.get_strategies()</code>， 取得已上傳的策略資料，像是每個策略的報酬率曲線、策略報酬率統計、近期部位、近期換股日等等，就不用一個個策略回測取得，直接一把抓，並藉由以下範例取得策略名稱和單一策略部位，策略名稱會用於之後繪圖所用的策略框定。<br>取得策略名稱的範例如下：</p>



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

# 實例化物件
strategies = StrategySunburst()
s_data = strategy.s_data
print(f'已上傳的策略名稱:{s_data.keys()}')</code></pre>



<h3>獲取繪圖資料</h3>



<p class="has-medium-font-size"><code>StrategySunburst().get_strategy_df(select_strategy=None)</code></p>



<p class="has-medium-font-size">StrategySunburst 下的 get_strategy_df 方法可獲取繪圖資料所用的 dataframe，</p>



<p class="has-medium-font-size">參數說明如下：</p>



<ul class="has-medium-font-size"><li>select_strategy (dict)：選取的策略與策略對應權重，預設是策略全選，權重為每個策略的資金比例平均。也可以自訂匡選的策略，像若是只想看兩個實戰的策略，並分別設定6成語4成資金比重，可以這樣設定：{&#8216;低波動本益成長比&#8217;:0.6,&#8217;研發魔人&#8217;:0.4}。若有現金的空部位想加入資產配置，可以設定如下，策略名稱為現金，即可創造現金部位 {&#8216;低波動本益成長比&#8217;:0.5,&#8217;研發魔人&#8217;:0.2, &#8216;現金&#8217;:0.2}。</li></ul>



<p class="has-medium-font-size">回傳的 dataframe 中，資料欄位 &#8216;market&#8217; 為資產所屬的市場，目前有 tw_stock (台股) 或 crypto (加密貨幣) 或 現金 選項。</p>



<h3>Sunburst 繪圖</h3>



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

# 實例化物件
strategies = StrategySunburst()

strategies.plot().show()
strategies.plot(select_strategy={'高殖利率烏龜':0.5,'營收強勢動能瘋狗':0.3,'現金流價值成長':0.2}).show()
strategies.plot(select_strategy={'高殖利率烏龜':0.4,'營收強勢動能瘋狗':0.25,'現金流價值成長':0.2,'現金':0.15},path =  ['market', 'category','stock_id','s_name']).show()</code></pre>



<p class="has-medium-font-size"><code>StrategySunburst().plot(select_strategy=None, path=None, color_continuous_scale='RdBu_r')</code></p>



<p class="has-medium-font-size">StrategySunburst 下的 plot 方法提供了繪圖設定，使用短短的程式碼就可以顯示多策略部位圖表。參數承襲 <code>plotly.express.sunburst</code> ，說明如下：</p>



<ul class="has-medium-font-size"><li>select_strategy (dict)：設定選取的策略與策略對應的持股現值權重，預設策略是策略全選，權重策略數的平均值。也可以自訂匡選的策略，像是只想看兩個實戰的策略，並分別設定6成與4成持股現值比重，可以設定成 <code>{'低波動本益成長比':0.6,'研發魔人':0.4}</code> 。若有現金的空部位想加入資產配置，可以設定成 <code>{'低波動本益成長比':0.5,'研發魔人':0.2, '現金':0.2}</code> ，策略名稱為現金，即可創造現金部位。</li><li>path (list)：sunburst 分層路徑，預設由裡到外的分層是 <code>['s_name', 'market', 'category', 'stock_id']</code> ，可以觀察策略持有哪些類股為主。你可以自動設定分層，會有不同的效果，像是也可以設成 <code>['category','stock_id','s_name'] </code> 變成可以看標的被哪些策略同時選到。</li><li>color_continuous_scale (str)：預設為<code>'RdBu_r'</code>，可以自選<a href="https://plotly.com/python/builtin-colorscales/" target="_blank" rel="noreferrer noopener">其他樣式</a>。</li></ul>



<h3>繪圖範例</h3>



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

# 實例化物件
strategies = StrategySunburst()

# 範例1
strategies.plot().show()
# 範例2
strategies.plot(select_strategy={'高殖利率烏龜':0.5,'營收強勢動能瘋狗':0.3,'現金流價值成長':0.2}).show()
# 範例3
strategies.plot(select_strategy={'高殖利率烏龜':0.4,'營收強勢動能瘋狗':0.25,'現金流價值成長':0.2,'現金':0.15},path =  ['market', 'category','stock_id','s_name']).show()</code></pre>



<h4>範例1</h4>



<p class="has-medium-font-size"><code>strategies.plot().show()</code></p>



<p class="has-medium-font-size">不帶任何參數會顯示全部的已上傳策略部位，策略資金分配比率為策略平均分配。</p>



<figure class="wp-container-2 wp-block-gallery-1 wp-block-gallery has-nested-images columns-default is-cropped">
<figure class="wp-block-image size-large"><img loading="lazy" width="1000" height="800" data-id="3947" src="https://www.finlab.tw/wp-content/uploads/2022/06/newplot.png" alt="newplot" class="wp-image-3947" srcset="https://www.finlab.tw/wp-content/uploads/2022/06/newplot.png 1000w, https://www.finlab.tw/wp-content/uploads/2022/06/newplot-300x240.png 300w, https://www.finlab.tw/wp-content/uploads/2022/06/newplot-768x614.png 768w, https://www.finlab.tw/wp-content/uploads/2022/06/newplot-150x120.png 150w" sizes="(max-width: 1000px) 100vw, 1000px" title="Plotly-Sunburst｜輕鬆監控多策略部位｜DashBoard 應用教學(5) 39"><figcaption>顯示全部策略</figcaption></figure>
</figure>



<p></p>



<h4>範例2</h4>



<p class="has-medium-font-size"><code>strategies.plot(select_strategy={'高殖利率烏龜':0.5,'營收強勢動能瘋狗':0.3,'現金流價值成長':0.2}).show()</code><br><br>自選3個策略，設定不同權重，看策略比重、策略持股的產業分佈。面積越大代表市值權重越大。顏色越紅代表上漲幅度越大，越藍代表跌幅越大。點擊策略可以做圖表互動，放大可只看單一策略的 sunburst (右圖)，從圖表觀察到營收策略選到三檔網通股，佔比最大，獲利最高的是6470 宇智，網通族群可能有營收趨勢翻多的群聚性。若是某些族群佔比超過 50% 以上，可能要反過來思考策略是不是太過於相似？可能會有標的不夠分散的風險。</p>



<figure class="wp-container-4 wp-block-gallery-3 wp-block-gallery has-nested-images columns-default is-cropped">
<figure class="wp-block-image size-large"><img loading="lazy" width="1000" height="800" data-id="3865" src="https://www.finlab.tw/wp-content/uploads/2022/06/newplot-16.png" alt="newplot 16" class="wp-image-3865" srcset="https://www.finlab.tw/wp-content/uploads/2022/06/newplot-16.png 1000w, https://www.finlab.tw/wp-content/uploads/2022/06/newplot-16-300x240.png 300w, https://www.finlab.tw/wp-content/uploads/2022/06/newplot-16-768x614.png 768w, https://www.finlab.tw/wp-content/uploads/2022/06/newplot-16-150x120.png 150w" sizes="(max-width: 1000px) 100vw, 1000px" title="Plotly-Sunburst｜輕鬆監控多策略部位｜DashBoard 應用教學(5) 40"></figure>



<figure class="wp-block-image size-large"><img loading="lazy" width="1000" height="800" data-id="3864" src="https://www.finlab.tw/wp-content/uploads/2022/06/newplot-15.png" alt="newplot 15" class="wp-image-3864" srcset="https://www.finlab.tw/wp-content/uploads/2022/06/newplot-15.png 1000w, https://www.finlab.tw/wp-content/uploads/2022/06/newplot-15-300x240.png 300w, https://www.finlab.tw/wp-content/uploads/2022/06/newplot-15-768x614.png 768w, https://www.finlab.tw/wp-content/uploads/2022/06/newplot-15-150x120.png 150w" sizes="(max-width: 1000px) 100vw, 1000px" title="Plotly-Sunburst｜輕鬆監控多策略部位｜DashBoard 應用教學(5) 41"></figure>
</figure>



<p></p>



<h4>範例3</h4>



<p class="has-medium-font-size"><code>strategies.plot(select_strategy={'高殖利率烏龜':0.4,'營收強勢動能瘋狗':0.25,'現金流價值成長':0.2,'現金':0.15},path = ['market', 'category','stock_id','s_name']).show()</code></p>



<p class="has-medium-font-size"><br>自選3個策略並設定現金權重，設定不同權重，除了看策略持股的產業分佈，也可看看標的被哪些策略同時選到。像圖中的 4572 駐龍同時被兩個策略選到，可能是非常厲害的標的喔！</p>



<figure class="wp-block-image size-full"><img loading="lazy" width="1000" height="800" src="https://www.finlab.tw/wp-content/uploads/2022/06/newplot-18.png" alt="newplot 18" class="wp-image-3866" srcset="https://www.finlab.tw/wp-content/uploads/2022/06/newplot-18.png 1000w, https://www.finlab.tw/wp-content/uploads/2022/06/newplot-18-300x240.png 300w, https://www.finlab.tw/wp-content/uploads/2022/06/newplot-18-768x614.png 768w, https://www.finlab.tw/wp-content/uploads/2022/06/newplot-18-150x120.png 150w" sizes="(max-width: 1000px) 100vw, 1000px" title="Plotly-Sunburst｜輕鬆監控多策略部位｜DashBoard 應用教學(5) 42"></figure>



<h2>結論</h2>



<p class="has-medium-font-size">Plotly &#8211; Sunburst 是不是十分絢麗呢！可以作多層次是覺化呈現及圖表互動。利用 FinLab 套件的 StrategySunburst 可以很輕鬆地將多策略資料漂亮地呈現出來，並觀察裡面的 insight，當作其中一個管理多策略的工具，不同的繪圖參數設定能玩出不同的效果，趕快來試試吧！<br><br><a href="https://drive.google.com/file/d/16c_Oxy6X9qVYYVTTEGgy0fnjg-GI9TH-/view?usp=sharing" target="_blank" rel="noopener">colab 範例檔連結</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/plotly-sunburst-dashboard/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3858</post-id>	</item>
		<item>
		<title>Qlib-巨人級的AI量化投資平台</title>
		<link>https://www.finlab.tw/qlib-intro/</link>
					<comments>https://www.finlab.tw/qlib-intro/#respond</comments>
		
		<dc:creator><![CDATA[Ben]]></dc:creator>
		<pubDate>Fri, 10 Jun 2022 05:15:44 +0000</pubDate>
				<category><![CDATA[生產力]]></category>
		<category><![CDATA[AI看股票]]></category>
		<category><![CDATA[Github]]></category>
		<category><![CDATA[Qlib]]></category>
		<category><![CDATA[量化投資套件]]></category>
		<guid isPermaLink="false">https://www.finlab.tw/?p=3669</guid>

					<description><![CDATA[常有人詢問FinLab如何取得AI量化交易學習資源以持續精進？

今天來介紹科技巨頭「微軟」在 Github 佛心開源的 Python AI 導向的量化投資框架～Qlib (Github)，從資料流(美、中股市)、建模流程、策略風控數據分析應有盡有，一條龍處理量化投資的工作。]]></description>
										<content:encoded><![CDATA[
<p class="has-medium-font-size">常有人詢問FinLab如何取得AI量化交易學習資源以持續精進？<br>除了 Google Scholar 看論文，Github 更是寶庫，下對關鍵字 ( ex:algorithmic-trading,quantitative-trading )，找對開源者能站在巨人的肩膀上，節省開發的時間並發現新世界。<br>今天來介紹科技巨頭「微軟」佛心開源的 Python AI 導向的量化投資框架～<a href="https://github.com/microsoft/qlib" target="_blank" rel="noopener">Qlib (Github)</a>，從資料流(美、中股市)、建模流程、策略風控數據分析應有盡有，一條龍處理量化投資的工作。</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="598" src="https://www.finlab.tw/wp-content/uploads/2022/06/截圖-2022-06-10-下午12.44.18-1024x598.png" alt="截圖 2022 06 10 下午12.44.18" class="wp-image-3670" srcset="https://www.finlab.tw/wp-content/uploads/2022/06/截圖-2022-06-10-下午12.44.18-1024x598.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/06/截圖-2022-06-10-下午12.44.18-300x175.png 300w, https://www.finlab.tw/wp-content/uploads/2022/06/截圖-2022-06-10-下午12.44.18-768x448.png 768w, https://www.finlab.tw/wp-content/uploads/2022/06/截圖-2022-06-10-下午12.44.18-1536x897.png 1536w, https://www.finlab.tw/wp-content/uploads/2022/06/截圖-2022-06-10-下午12.44.18-1200x700.png 1200w, https://www.finlab.tw/wp-content/uploads/2022/06/截圖-2022-06-10-下午12.44.18.png 1715w" sizes="(max-width: 1024px) 100vw, 1024px" title="Qlib-巨人級的AI量化投資平台 43"></figure>



<h2>Qlib 特色</h2>



<h3>AI 演算法模型</h3>



<p class="has-medium-font-size">Qlib 最有價值的地方在降低了使用 AI 演算法的門檻，目前套件有十幾個AI演算法在股票交易下的應用範例，許多都是新穎的演算法，內容深度高。模型程式都已模組化，只要調整資料格式和參數。<br>不少Self-attention的架構，乾貨滿滿，像是TRA (Temporal Routing Adaptor) 將LSTM做延伸，讓模型去學習多策略風格，捕捉近期市場主流門派。</p>



<p class="has-medium-font-size">Github上除了提供程式碼，也附上相關paper在qlib/examples/benchmarks中，資源整理的很充分，供開發者參考，除了輕鬆 Fork外，也可以精進演算法內涵。</p>



<h3>特徵資料集</h3>



<p class="has-medium-font-size">AI 訓練的第一步是準備特徵資料集，要生成好的特徵並沒想像容易。可能䢎開發者多為中國人有關，Qlib 基於中國股市 (滬深300) 建構 Alpha360 and Alpha158 兩種資料集範例，可參考<a href="https://github.com/microsoft/qlib/blob/main/qlib/contrib/data/handler.py" target="_blank" rel="noopener">官方程式</a>來生成特徵集。</p>



<h3>Workflow 架構</h3>



<p class="has-medium-font-size">workflow layer處理模型的訓練與回測過程，尋找獲利因子Alpha和風險因子，之後進入資產配置、選股、下單的決策階段。<br>另一個好用的是的Recoder流程管理器，用來管理與儲存紀錄模型的訓練過程、結果。AI模型有時訓練時間長，不能及時的看到結果，有時還有其他原因中斷訓練，那此時可使用Recoder恢復並繼續之前的訓練，不需要從頭開始。<br></p>



<h2>結論</h2>



<p class="has-medium-font-size">Qlib Framework 架構值得 作為 FinLab 下一代的開發參考，尤其是ML WorkFlow 的部分是目前FinLab平台比較欠缺的，或是將台股資料應用到 Qlib 模型也值得來整合。<br><br>一個好的repo，除了 Star 和 Fork 數，commit history 也是指標，更新頻率看起來有積極維護，持續補充新的模型和技術進來，值得追蹤～<br></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/qlib-intro/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3669</post-id>	</item>
	</channel>
</rss>
