<?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>MAE_MFE &#8211; FinLab</title>
	<atom:link href="https://www.finlab.tw/tag/mae_mfe/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.finlab.tw</link>
	<description>深入淺出的量化投資，讓你在在茫茫股海中，找到專屬於自己的投資方法</description>
	<lastBuildDate>Wed, 01 Feb 2023 17:05:46 +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>MAE_MFE &#8211; FinLab</title>
	<link>https://www.finlab.tw</link>
	<width>32</width>
	<height>32</height>
</image> 
<site xmlns="com-wordpress:feed-additions:1">179699571</site>	<item>
		<title>投信買賣超選股策略｜時空序列分析的秘招｜停損怎麼設？</title>
		<link>https://www.finlab.tw/time_series_analysis_of_investment_trust_strategy/</link>
					<comments>https://www.finlab.tw/time_series_analysis_of_investment_trust_strategy/#respond</comments>
		
		<dc:creator><![CDATA[Ben]]></dc:creator>
		<pubDate>Tue, 15 Nov 2022 08:47:06 +0000</pubDate>
				<category><![CDATA[FinLab 量化平台]]></category>
		<category><![CDATA[VIP文章]]></category>
		<category><![CDATA[籌碼面]]></category>
		<category><![CDATA[選股策略]]></category>
		<category><![CDATA[MAE_MFE]]></category>
		<category><![CDATA[VIP限定]]></category>
		<category><![CDATA[台股]]></category>
		<category><![CDATA[投信]]></category>
		<guid isPermaLink="false">https://www.finlab.tw/?p=4870</guid>

					<description><![CDATA[帝牙盧卡有著控制時間的能力，被稱作時間之神。牠可以扭曲時間以讓時間加快或減慢甚至停止。 帕路奇亞擁有扭曲空間的 [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p class="has-medium-font-size"><br></p>



<blockquote class="wp-block-quote"><p>帝牙盧卡有著控制時間的能力，被稱作時間之神。牠可以扭曲時間以讓時間加快或減慢甚至停止。</p><p>帕路奇亞擁有扭曲空間的能力，在<a href="https://wiki.52poke.com/wiki/%E7%A5%9E%E5%A5%A5%E5%9C%B0%E5%8C%BA" target="_blank" rel="noopener">神奧地區</a>的神話裡被描述成神。它可以憑藉自己操縱空間的連接從而能夠移動到遠處的異空間～寶可夢</p></blockquote>



<figure class="wp-block-image size-full"><img width="1024" height="520" src="https://www.finlab.tw/wp-content/uploads/2022/11/img_story_210928_01_01.png" alt="https://reurl.cc/bGEQEX" class="wp-image-4880" srcset="https://www.finlab.tw/wp-content/uploads/2022/11/img_story_210928_01_01.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/11/img_story_210928_01_01-300x152.png 300w, https://www.finlab.tw/wp-content/uploads/2022/11/img_story_210928_01_01-768x390.png 768w" sizes="(max-width: 1024px) 100vw, 1024px" title="投信買賣超選股策略｜時空序列分析的秘招｜停損怎麼設？ 1"></figure>



<p class="has-medium-font-size">交易者和寶可夢訓練家的世界其實有異曲同工之妙，如果你收服「帝牙盧卡」和「帕路奇亞」，等同擁有掌握時間與空間的能力，在對戰上佔盡優勢。<br>在交易的世界裡，時間與空間指的是什麼呢？股海有句老話是「獲利是等出來的」，然而真的每個催化劑都適合等嗎？什麼樣的換股間隔才最適合？為什麼有些策略是用一週，有些用每月底？<br>在股價波動的空間裡，什麼樣的停損才適當？如何保留多數獲利、減低多數虧損？<br>如果你掌握投資市場分析時空序列的能力，等同在擁有犯規的神獸啊～</p>



<p class="has-medium-font-size">看過FinLab的「<a href="https://ai.finlab.tw/notebook/?uid=TJN4FDuqrwU8DML7DAjUYFIMutp2&amp;sid=%E6%8A%95%E4%BF%A1%E5%A4%A7%E5%93%A5%E8%B7%9F%E5%B1%81%E8%9F%B2&amp;cid=f0A8du1VqXMGVEa2u8si" target="_blank" rel="noopener">投信大哥跟屁蟲</a>」教學影片了嗎？沒看過的人，請先趕緊去看。相信看過的人都能快速掌握 Python 語法，了解策略的設定，看完後再來學這篇文章進階的小工具，了解投信大哥跟屁蟲的秘密。</p>



<h2>時間分析</h2>



<p class="has-medium-font-size">為什麼<a href="https://ai.finlab.tw/notebook/?uid=TJN4FDuqrwU8DML7DAjUYFIMutp2&amp;sid=%E6%8A%95%E4%BF%A1%E5%A4%A7%E5%93%A5%E8%B7%9F%E5%B1%81%E8%9F%B2&amp;cid=f0A8du1VqXMGVEa2u8si" target="_blank" rel="noopener">投信大哥跟屁蟲</a>換股是3天，而不是5天、10天、20天？<br>要分析其實很簡單，使用FinLab模組的 <a href="https://doc.finlab.tw/reference/optimize/#finlab.optimize.combinations.ReportCollection" target="_blank" rel="noopener">ReportCollection</a> 即可取得回測報告集合，判斷策略組合數據優劣，從策略海中快速找到體質最強的策略。 也可以觀察在同條件下的策略疊加更多條件後會有什麼變化？以下程式範例將策略程式封裝成函數，變數為換股間隔，來跑跑看2~20天不同換股週期的回測效果。</p>



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

def run_strategy(interval:int):
    close = data.get("price:收盤價")
    vol = data.get('price:成交股數')
    投信買賣超股數 = data.get('institutional_investors_trading_summary:投信買賣超股數')

    c1 = 投信買賣超股數 >= 800000
    c2 = 投信買賣超股數/vol >= 0.05

    position = c1 &amp; c2 
    position = position * close
    position = position[position>0]
    position = position.is_smallest(8)

    # 每3個交易日再平衡，與resample='3D'差異在後者是隔3日，而非3個交易日。
    position = position.loc[list(position.index)[::interval]]
    report = sim(position,trade_at_price='open', position_limit=1/3, fee_ratio=1.425/1000/3, upload=False, mae_mfe_window=40)
    return report 

from finlab.optimize.combinations import ReportCollection

# 回測2~20間隔
reports = {i:run_strategy(i) for i in range(2,21)}
# 回測報告視覺化
collection = ReportCollection(reports)
collection.plot_creturns()</code></pre>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="265" src="https://www.finlab.tw/wp-content/uploads/2022/11/newplot-38-1-1024x265.png" alt="newplot 38 1" class="wp-image-4905" srcset="https://www.finlab.tw/wp-content/uploads/2022/11/newplot-38-1-1024x265.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/11/newplot-38-1-300x78.png 300w, https://www.finlab.tw/wp-content/uploads/2022/11/newplot-38-1-768x199.png 768w, https://www.finlab.tw/wp-content/uploads/2022/11/newplot-38-1-1536x397.png 1536w, https://www.finlab.tw/wp-content/uploads/2022/11/newplot-38-1.png 2029w" sizes="(max-width: 1024px) 100vw, 1024px" title="投信買賣超選股策略｜時空序列分析的秘招｜停損怎麼設？ 2"></figure>



<p class="has-medium-font-size">跑完後發現當間隔為3天時，累積報酬率明顯優於其他天數表現。為了更確認分析，我們可以再執行<code>reports[3].display_mae_mfe_analysis()</code>來看<a href="https://www.finlab.tw/edge-ratio-follow-application/"> Edge Ratio </a>(下圖第一排中間子圖)的表現，<a href="https://www.finlab.tw/edge-ratio-follow-application/">Edge Ratio </a>簡而言之是綜合交易時間與波動關係的判斷指標，可以發現投信策略在一開始進場就有優勢 (大於1) ，但優勢隨著持有時間 (x軸) 拉長急速下降，直到第20天後才又拉升到持有3天時的高峰，可見投信買賣超的因子在短期較具有影響性，考量換股效率，持有3天是不錯的選項，可以用多次小獲利不斷去滾。</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="1024" src="https://www.finlab.tw/wp-content/uploads/2022/11/newplot-31-1024x1024.png" alt="newplot 31" class="wp-image-4874" srcset="https://www.finlab.tw/wp-content/uploads/2022/11/newplot-31-1024x1024.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/11/newplot-31-300x300.png 300w, https://www.finlab.tw/wp-content/uploads/2022/11/newplot-31-150x150.png 150w, https://www.finlab.tw/wp-content/uploads/2022/11/newplot-31-768x768.png 768w, https://www.finlab.tw/wp-content/uploads/2022/11/newplot-31-600x600.png 600w, https://www.finlab.tw/wp-content/uploads/2022/11/newplot-31.png 1200w" sizes="(max-width: 1024px) 100vw, 1024px" title="投信買賣超選股策略｜時空序列分析的秘招｜停損怎麼設？ 3"></figure>



<h2>空間分析</h2>



<h2>勝敗手MAE分佈圖</h2>



<p class="has-medium-font-size">分析完時間，我們把換股週期3天保留下來，接下來要研究停損怎麼設定才好？好的停損是保留多數獲利，避免提早被洗掉，並能將大虧損變小虧損，降低損失，進而優化策略體質。<br>分析的第一步可以先看勝敗手的 MAE Distribution (若不知道 MAE ，請見此篇<a href="https://www.finlab.tw/display_mae_mfe_analysis/">教學文章</a>)，MAE簡單說是每筆交易持有歷程的最大虧損。<br>數據呈現一樣用 <a href="https://doc.finlab.tw/reference/analysis/#finlab.analysis.Report.display_mae_mfe_analysis" target="_blank" rel="noopener">display_mae_mfe_analysis()</a> 可以叫出。我們將圖片放大來看，可以發現贏錢的交易(藍色)的第75百分位數很小，只有0.51%，代表多數贏錢的交易在持有過程中很少碰到虧損，而輸錢的交易(紅色)的第75百分位數也不大，只有 4.2%，代表有 25% 的虧損交易的 MAE 大於 4.2%。由上述分析，我們合適的停損應落於 0.51%~4.2% 之間，只要停損設超過 0.51%，就能保留多數獲利，因為這些少數的獲利交易才會超過 0.51%，而停損設小於 4.2% ，可以將MAE 高的標地往內縮，降低潛在損失。</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="862" src="https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-15-下午4.03.47-1024x862.png" alt="截圖 2022 11 15 下午4.03.47" class="wp-image-4875" srcset="https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-15-下午4.03.47-1024x862.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-15-下午4.03.47-300x253.png 300w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-15-下午4.03.47-768x646.png 768w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-15-下午4.03.47.png 1289w" sizes="(max-width: 1024px) 100vw, 1024px" title="投信買賣超選股策略｜時空序列分析的秘招｜停損怎麼設？ 4"></figure>



<h2>停損回測集</h2>



<p class="has-medium-font-size">依據上述分析，可以知道波動空間與合適的停損範圍大概在 0.51%~4.2%(可在後推一點)上下 ，我們一樣用前面示範過的方法，改將停損設定設為變數，再看停損哪一個數字最棒。FinLab 模組的 <a href="https://doc.finlab.tw/reference/optimize/#finlab.optimize.combinations.ReportCollection" target="_blank" rel="noopener">ReportCollection</a> 有熱力圖與統計數據可以幫握們分析，使用方式如下：</p>



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

def run_strategy_with_stop_loss(stop_loss:float):
    close = data.get("price:收盤價")
    vol = data.get('price:成交股數')
    投信買賣超股數 = data.get('institutional_investors_trading_summary:投信買賣超股數')

    c1 = 投信買賣超股數 >= 800000
    c2 = 投信買賣超股數/vol >= 0.05

    position = c1 &amp; c2 
    position = position * close
    position = position[position>0]
    position = position.is_smallest(8)

    # 每3個交易日再平衡，與resample='3D'差異在後者是隔3日，而非3個交易日。
    position = position.loc[list(position.index)[::3]]
    report = sim(position,trade_at_price='open', position_limit=1/3, fee_ratio=1.425/1000/3, upload=False, mae_mfe_window=40, stop_loss=stop_loss)
    return report 

from finlab.optimize.combinations import ReportCollection

stop_loss_reports = {i/1000:run_strategy_with_stop_loss(i/1000) for i in range(0,50,5)}
stop_loss_collection = ReportCollection(stop_loss_reports)
stop_loss_collection.plot_creturns().show()
stop_loss_collection.plot_stats(mode='heatmap', heatmap_sort_by='daily_mean').show()</code></pre>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="265" src="https://www.finlab.tw/wp-content/uploads/2022/11/newplot-39-1-1024x265.png" alt="newplot 39 1" class="wp-image-4906" srcset="https://www.finlab.tw/wp-content/uploads/2022/11/newplot-39-1-1024x265.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/11/newplot-39-1-300x78.png 300w, https://www.finlab.tw/wp-content/uploads/2022/11/newplot-39-1-768x199.png 768w, https://www.finlab.tw/wp-content/uploads/2022/11/newplot-39-1-1536x397.png 1536w, https://www.finlab.tw/wp-content/uploads/2022/11/newplot-39-1.png 2029w" sizes="(max-width: 1024px) 100vw, 1024px" title="投信買賣超選股策略｜時空序列分析的秘招｜停損怎麼設？ 5"></figure>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="712" src="https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-18-下午12.58.09-1024x712.png" alt="截圖 2022 11 18 下午12.58.09" class="wp-image-4907" srcset="https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-18-下午12.58.09-1024x712.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-18-下午12.58.09-300x209.png 300w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-18-下午12.58.09-768x534.png 768w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-18-下午12.58.09-1536x1068.png 1536w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-18-下午12.58.09.png 1738w" sizes="(max-width: 1024px) 100vw, 1024px" title="投信買賣超選股策略｜時空序列分析的秘招｜停損怎麼設？ 6"></figure>



<p class="has-medium-font-size">最終結果發現停損在 4.5% 的報酬率與夏普率效果最好，但很明顯可發現這個策略無論停損參數射哪一組，max_drawdown (最大回撤)都很大，超過 -40%，雖然年化報酬有 29%，但實戰上可能會扛不住大波動。</p>



<h2>大盤時空</h2>



<p class="has-medium-font-size">拉出報酬率序列來看，可以發現投信跟屁蟲策略在多頭時很猛，但在 2022 空頭時可能會碰上瘋狂停損的局面，台股中期回檔的 2015、2018 年份，該策略也有不小回檔，可能要加上大盤濾網來判斷市況是否適合順勢追擊。</p>



<figure class="wp-block-image size-full"><img loading="lazy" width="800" height="600" src="https://www.finlab.tw/wp-content/uploads/2022/11/newplot-33.png" alt="newplot 33" class="wp-image-4877" srcset="https://www.finlab.tw/wp-content/uploads/2022/11/newplot-33.png 800w, https://www.finlab.tw/wp-content/uploads/2022/11/newplot-33-300x225.png 300w, https://www.finlab.tw/wp-content/uploads/2022/11/newplot-33-768x576.png 768w" sizes="(max-width: 800px) 100vw, 800px" title="投信買賣超選股策略｜時空序列分析的秘招｜停損怎麼設？ 7"></figure>



<p class="has-medium-font-size">於是我們可以考慮加上大盤濾網，由於投信策略屬於短線的策略，會偏好使用較靈敏的大盤指標：整體市場多空排列家數來判斷，想了解其他指標，可見「<a href="https://www.finlab.tw/index_filter/">4種均線指標 | 讓你在大盤崩崩前高歌離席!</a>」。可以發現雖然犧牲了報酬率，但回撤曲線大幅優化，年化報酬你要追求報酬率極大化，還是追求穩定度？</p>



<figure class="wp-block-image size-full"><img loading="lazy" width="800" height="600" src="https://www.finlab.tw/wp-content/uploads/2022/11/newplot-37.png" alt="newplot 37" class="wp-image-4904" srcset="https://www.finlab.tw/wp-content/uploads/2022/11/newplot-37.png 800w, https://www.finlab.tw/wp-content/uploads/2022/11/newplot-37-300x225.png 300w, https://www.finlab.tw/wp-content/uploads/2022/11/newplot-37-768x576.png 768w" sizes="(max-width: 800px) 100vw, 800px" title="投信買賣超選股策略｜時空序列分析的秘招｜停損怎麼設？ 8"></figure>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="641" src="https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-18-下午1.00.30-1024x641.png" alt="截圖 2022 11 18 下午1.00.30" class="wp-image-4908" srcset="https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-18-下午1.00.30-1024x641.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-18-下午1.00.30-300x188.png 300w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-18-下午1.00.30-768x481.png 768w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-18-下午1.00.30.png 1388w" sizes="(max-width: 1024px) 100vw, 1024px" title="投信買賣超選股策略｜時空序列分析的秘招｜停損怎麼設？ 9"><figcaption>套入大盤濾網的策略表現</figcaption></figure>



<h2>結論</h2>



<p class="has-medium-font-size"><a href="https://colab.research.google.com/drive/1srVhlqC2MFuGF93EMVpFN1XScfefTrb8?usp=sharing" target="_blank" rel="noopener">colab 範例檔</a></p>



<p class="has-medium-font-size">是不是領略到「<a href="https://ai.finlab.tw/notebook/?uid=TJN4FDuqrwU8DML7DAjUYFIMutp2&amp;sid=%E6%8A%95%E4%BF%A1%E5%A4%A7%E5%93%A5%E8%B7%9F%E5%B1%81%E8%9F%B2&amp;cid=f0A8du1VqXMGVEa2u8si" target="_blank" rel="noopener">投信大哥跟屁蟲</a>」背後的秘密了呢？趕緊把學到的招式用在你的策略，找找最適合的換股週期和停損設定，學會時空序列分析的技巧，真的會有寶可夢等級大幅提升的感覺啊！</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/time_series_analysis_of_investment_trust_strategy/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">4870</post-id>	</item>
		<item>
		<title>低波動本益成長比策略 &#124; MAE_MFE 機器學習選股</title>
		<link>https://www.finlab.tw/low_volatility_stratgy_by_mae_mfe_ml/</link>
					<comments>https://www.finlab.tw/low_volatility_stratgy_by_mae_mfe_ml/#respond</comments>
		
		<dc:creator><![CDATA[Ben]]></dc:creator>
		<pubDate>Mon, 07 Nov 2022 23:33:00 +0000</pubDate>
				<category><![CDATA[AI看股票]]></category>
		<category><![CDATA[FinLab 量化平台]]></category>
		<category><![CDATA[VIP文章]]></category>
		<category><![CDATA[基本面分析]]></category>
		<category><![CDATA[技術面]]></category>
		<category><![CDATA[籌碼面]]></category>
		<category><![CDATA[選股策略]]></category>
		<category><![CDATA[Kmeans]]></category>
		<category><![CDATA[MAE_MFE]]></category>
		<category><![CDATA[PEG]]></category>
		<category><![CDATA[scikit-learn]]></category>
		<category><![CDATA[VIP限定]]></category>
		<category><![CDATA[低波動]]></category>
		<category><![CDATA[台股]]></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=3687</guid>

					<description><![CDATA[有時我們有了初始策略輪廓，寫出來發現年化報酬率不錯，但夏普率不高、最大回撤率過大，若拿去實戰，持有歷程會遇上信心考驗，績效跳動範圍也大。有沒有辦法讓策略能夠報酬率更高、波動更低？

本篇範例會利用基礎的機器學習演算法 Kmeans 分群 mae_mfe 指標，製作決策樹使用的 Labels，優化原本的"本益成長比"策略，示範 scikit-learn 搭配 finlab 模組是多麼強大又簡單！]]></description>
										<content:encoded><![CDATA[
<p class="has-medium-font-size">有時我們有了初始策略輪廓，寫出來發現年化報酬率不錯，但夏普率不高、最大回撤率過大，若拿去實戰，持有歷程會遇上信心考驗，績效跳動範圍也大。有沒有辦法讓策略能夠報酬率更高、波動更低？ 但選股條件那麼多，單因子策略不停去 try error 組合很沒效率，這時就是&#8221;機器學習選股&#8221;的優勢，高效分析影響性大的特徵。<br>很多人對如何將機器學習應用到投資領域很有興趣，但實作要怎麼設計？用報酬率當Label真的好嗎？太難的演算法又看不懂或難消化，到底怎麼辦？<br>本篇範例會利用基礎的機器學習演算法 Kmeans 分群 mae_mfe 指標，製作決策樹使用的 Labels，優化原本的&#8221;本益成長比&#8221;策略，示範 scikit-learn 搭配 finlab 模組是多麼強大又簡單！</p>



<h2>選定待優化的策略</h2>



<p class="has-medium-font-size"><a href="https://www.finlab.tw/finlab-tw-stock-peg-strategy/">進化後的本益比｜本益成長比選股策略</a> 一文中用簡單的單因子回歸產生一個簡潔卻有效的選股策略。為了製造比較多的回測樣本，我們將之前的策略調成每月選取20檔標的。<br><strong>留意本篇的測試資料結果可能隨著資料集增長而產生差異，回測僅供參考。</strong><br>回測年化報酬率23%是不錯的水準，夏普率勉強優於大盤的0.9，但最大回撤率蠻高的，報酬率曲線震盪有點劇烈，好幾次回檔30%，實戰的持有過程肯定會備受考驗，可以加上哪些條件解決波動的問題呢？</p>



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

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:營業利益成長率').deadline()
peg = (pe/營業利益成長率)
cond1 = rev_ma3/rev_ma12 &gt; 1.1
cond2 = rev/rev.shift(1) &gt; 0.9

cond_all = cond1 &amp; cond2
result = peg*(cond_all)
position = result[result&gt;0].is_smallest(20).reindex(rev.index_str_to_date().index, method='ffill')


report = sim(position=position,name="本益成長比", fee_ratio=1.425/1000/3,upload=True,mae_mfe_window=30,position_limit=0.05)
report.display()</code></pre>



<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="1024" height="645" data-id="4735" src="https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-30-下午9.19.18-1024x645.png" alt="截圖 2022 10 30 下午9.19.18" class="wp-image-4735" srcset="https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-30-下午9.19.18-1024x645.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-30-下午9.19.18-300x189.png 300w, https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-30-下午9.19.18-768x483.png 768w, https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-30-下午9.19.18.png 1390w" sizes="(max-width: 1024px) 100vw, 1024px" title="低波動本益成長比策略 | MAE_MFE 機器學習選股 10"></figure>
</figure>



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



<h2>製作波動性 Labels </h2>



<p class="has-medium-font-size">給對的學習目標很重要！選擇比努力更重要！<br>一般機器學習選股策略使用報酬率做 label ，但演算法只會判斷報酬率的賺賠高低，並沒有辦法學習波動特性，若給定的 label 一開始就有所限制，再怎麼學也是無法跳脫只追求高報酬的風險。 </p>



<h3>MAE &amp; MFE</h3>



<p class="has-medium-font-size"><a href="https://www.finlab.tw/display_mae_mfe_analysis/">揭開策略的波動面紗｜MAE&amp;MFE分析圖組使用指南</a> 一文中解釋了 MAE 與 MFE 的可幫助我們分析策略波動和基本應用，我們可以輕鬆由FinLab模組中的<a href="https://doc.finlab.tw/reference/analysis/#finlab.analysis.Report.get_trades" target="_blank" rel="noopener"> <code>report.get_trades()</code></a> 取得策略標的持有歷程的 MAE 與 MFE 與其他交易資料。<a href="https://doc.finlab.tw/reference/analysis/#finlab.analysis.Report.display_mae_mfe_analysis" target="_blank" rel="noopener"> <code>report.display_mae_mfe_analysis()</code></a> 則可顯示波動率分析圖組，幫助我們觀察波動分佈。</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="1200" height="1200" data-id="4729" src="https://www.finlab.tw/wp-content/uploads/2022/10/newplot-1.png" alt="newplot 1" class="wp-image-4729" srcset="https://www.finlab.tw/wp-content/uploads/2022/10/newplot-1.png 1200w, https://www.finlab.tw/wp-content/uploads/2022/10/newplot-1-300x300.png 300w, https://www.finlab.tw/wp-content/uploads/2022/10/newplot-1-1024x1024.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/10/newplot-1-150x150.png 150w, https://www.finlab.tw/wp-content/uploads/2022/10/newplot-1-768x768.png 768w, https://www.finlab.tw/wp-content/uploads/2022/10/newplot-1-600x600.png 600w" sizes="(max-width: 1200px) 100vw, 1200px" title="低波動本益成長比策略 | MAE_MFE 機器學習選股 11"></figure>
</figure>



<p class="has-medium-font-size"><br>從上圖中的 GMFE / MAE 子圖可以發現波動分佈分為三塊：</p>



<ul class="has-medium-font-size"><li>最多聚集的一塊是在左下角小賺小賠的標的。</li><li>策略獲利的標的有些是「高 GMFE 低 MAE (往上高波動、往下低波動)」，給我們帶來極高獲利，這在趨勢策略較常出現，是我們想保留的。</li><li>虧損的標的大多是 「低 GMFE 高 MAE  (往下高波動、往上低波動)」的族群，有些標的持有紀錄還有 -50% 以上不利跌幅，這些會影響到策略的波動穩定度，是我們想淘汰的拖油瓶。</li></ul>



<p class="has-medium-font-size">若能用MAE &amp; MFE 取代報酬率作為 label，就可以讓模型學習判斷波動度與報酬率，若三個分群有特徵共通性，那之後做機器學習可能可找到有效分類 「高 GMFE 低 MAE 」 與 「低 GMFE 高 MAE」的特徵。</p>



<h3>Kmeans 分群</h3>



<p class="has-medium-font-size">如何界定「高 GMFE 低 MAE 」與 「低 GMFE 高 MAE 」 ？<br>這時<a href="https://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html" target="_blank" rel="noopener">非監督學習演算法Kmeans</a>就可以粉墨登場，幫我們去做分群的動作，讓模型自動幫我們藉由 GMFE 低 MAE 兩項特徵分出三個群集。<br><strong>注意分群給的數字具有隨機性！</strong>比如「高 GMFE 低 MAE 」可能分類標註為1，下次執行跳為2。<br>在模型訓練前，因用有少數大幅獲利與多數群集分太開，先使用 <code>from sklearn.preprocessing import StandardScaler</code> 將資料做正規化，將資料傳入 Kmeans 分群，並將結果繪圖呈現分佈。<br>我們把預設值 y_pred 放入原本的 trade dataframe，設為 group，就完成 label 標記了，輸出結果可以發現 Kmeans 成功幫我們分出三個顏色區塊。</p>



<pre class="wp-block-code"><code lang="python" class="language-python">import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans

from sklearn.preprocessing import StandardScaler

def scale_data(data):
    scaler = StandardScaler().fit(data)
    X_scaled = scaler.transform(data)
    return X_scaled

scale_mae = scale_data(trades['mae'].values.reshape(-1, 1))
scale_gmfe = scale_data(trades['gmfe'].values.reshape(-1, 1))


plt.figure(figsize = (8, 8))
random_state = 100
X = np.hstack((scale_mae,scale_gmfe))
y_pred = KMeans(n_clusters=3,random_state=random_state).fit_predict(X)

scatter = plt.scatter(X[:, 0], X[:, 1], c=y_pred)
plt.legend(*scatter.legend_elements())
plt.title("mae_gmfe kmeans")
plt.xlabel("mae")
plt.ylabel("gmfe")</code></pre>



<figure class="wp-block-image size-full"><img loading="lazy" width="942" height="855" src="https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-30-下午9.00.52.png" alt="截圖 2022 10 30 下午9.00.52" class="wp-image-4731" srcset="https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-30-下午9.00.52.png 942w, https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-30-下午9.00.52-300x272.png 300w, https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-30-下午9.00.52-768x697.png 768w" sizes="(max-width: 942px) 100vw, 942px" title="低波動本益成長比策略 | MAE_MFE 機器學習選股 12"></figure>



<p class="has-medium-font-size">為了讓模型更專注於「高 GMFE 低 MAE 」與 「低 GMFE 高 MAE 」 的學習，只保留 group 為1、2 (藍綠點) 的部分，我們把白點的區塊視為不影響大局的雜訊，藍色和綠色的點才是影響策略波動的關鍵</p>



<pre class="wp-block-code"><code lang="python" class="language-python">cluster_trades = trades.copy()
cluster_trades['group'] = y_pred
cluster_trades['stock_id'] = cluster_trades['stock_id'].apply(lambda s:s[:s.index(' ')])
ana_targets = cluster_trades[cluster_trades['group'].isin([1,2])]
ana_targets = ana_targets.reset_index().set_index(['stock_id', 'entry_sig_date'])</code></pre>



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



<h2>決策樹-探索低波動因子</h2>



<p class="has-medium-font-size">標注完了 label 後，就可以進行下一步，尋找有沒有選股條件能辨識label ，這就要換監督式學習登場。這部分的程式主要參考 <a href="https://hahow.in/courses/5b9d3a6dca498a001e917383/discussions" target="_blank" rel="noopener">Python 理財：打造自己的 AI 股票理專課程</a>  單元 3-7-隨機森林選股策略實作，因資料量級較小，把隨機森林換成決策樹。</p>



<h3>製作 Features</h3>



<p class="has-medium-font-size">將想測試的資料或可能的低波動因子並成 dataframe 準備進入模型訓練，特徵可以使用 <a href="https://ai.finlab.tw/database" target="_blank" rel="noopener">Finlab 資料庫</a> 取得，並將資料以 2019 年為分界點，切成訓練及測試資料集。</p>



<figure class="wp-block-image"><img alt=""/></figure>



<h3>模型測試結果</h3>



<p class="has-medium-font-size">將資料集套入 sklearn 決策樹，驗證目標為label=1的集群(低 GMFE 高 MAE )，若找到機率越高，能有效躲避波動。<br>測試結果放入 <a href="https://www.ycc.idv.tw/confusion-matrix.html" target="_blank" rel="noopener">confusion-matrix</a> 驗證結果，抓出「低 GMFE 高 MAE 」的準確度達75%，預測45(34+11) 次內有34次正確。<br>指標意義詳見～<a href="https://medium.com/nlp-tsupei/precision-recall-f1-score%E7%B0%A1%E5%96%AE%E4%BB%8B%E7%B4%B9-f87baa82a47" target="_blank" rel="noopener">Precision, Recall, F1-score簡單介紹</a>。<br></p>



<pre class="wp-block-code"><code lang="python" class="language-python">import pandas as pd
from sklearn import metrics
from sklearn.tree import DecisionTreeClassifier

label = ana_targets[ana_targets['mae']&gt; ana_targets['gmfe']]['group'].values[0]
features_name = list(features.keys())
cf = DecisionTreeClassifier(max_depth=3)
cf.fit(dataset_train[features_name], dataset_train['group'] ==label)


prediction = cf.predict(dataset_test[features_name])
confusion_matrix = metrics.confusion_matrix(dataset_test['group'] == label, prediction)
tn, fp, fn, tp = confusion_matrix.ravel()
confusion_matrix = np.array([[tp, fp],[fn, tn]])


print('f1 score:',metrics.f1_score(dataset_test['group'] == label, prediction))
print('precision score(p):',metrics.precision_score(dataset_test['group'] == label, prediction))
print('recall score(p):',metrics.recall_score(dataset_test['group'] == label, prediction))


plt.figure(figsize=(10, 6))
sns.set(font_scale=2)

ax = sns.heatmap(confusion_matrix, annot=True, cmap='Blues')
ax.set_title('Confusion Matrix with labels\n\n');
ax.set_xlabel('Actual Values')
ax.set_ylabel('Predicted Values');

## Ticket labels - List must be in alphabetical order
ax.xaxis.set_ticklabels(['True','False'])
ax.yaxis.set_ticklabels(['True','False'])

## Display the visualization of the Confusion Matrix.
plt.show()
</code></pre>



<figure class="wp-container-6 wp-block-gallery-5 wp-block-gallery has-nested-images columns-default is-cropped">
<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="954" data-id="4866" src="https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-13-下午7.16.34-1024x954.png" alt="截圖 2022 11 13 下午7.16.34" class="wp-image-4866" srcset="https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-13-下午7.16.34-1024x954.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-13-下午7.16.34-300x280.png 300w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-13-下午7.16.34-768x716.png 768w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-13-下午7.16.34.png 1422w" sizes="(max-width: 1024px) 100vw, 1024px" title="低波動本益成長比策略 | MAE_MFE 機器學習選股 13"></figure>
</figure>



<p></p>



<h3>因子重要性</h3>



<p class="has-medium-font-size"><code>from sklearn.tree import plot_tree</code>  可繪製出決策樹的機器學習選股決策流程，最上頭的X[8]為&#8217;融資使用率&#8217;，使用33.6當數值分界點，X序列等同features_name排序。<br><code>cf.feature_importances_</code>  可得知重要因子的影響性分數。</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="751" src="https://www.finlab.tw/wp-content/uploads/2022/10/下載-1-1024x751.png" alt="下載 1" class="wp-image-4733" srcset="https://www.finlab.tw/wp-content/uploads/2022/10/下載-1-1024x751.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/10/下載-1-300x220.png 300w, https://www.finlab.tw/wp-content/uploads/2022/10/下載-1-768x563.png 768w, https://www.finlab.tw/wp-content/uploads/2022/10/下載-1.png 1130w" sizes="(max-width: 1024px) 100vw, 1024px" title="低波動本益成長比策略 | MAE_MFE 機器學習選股 14"><figcaption>決策樹分類流程</figcaption></figure>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="409" src="https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-30-下午9.10.47-1024x409.png" alt="截圖 2022 10 30 下午9.10.47" class="wp-image-4734" srcset="https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-30-下午9.10.47-1024x409.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-30-下午9.10.47-300x120.png 300w, https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-30-下午9.10.47-768x307.png 768w, https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-30-下午9.10.47-1536x613.png 1536w, https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-30-下午9.10.47.png 2034w" sizes="(max-width: 1024px) 100vw, 1024px" title="低波動本益成長比策略 | MAE_MFE 機器學習選股 15"></figure>



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



<h3>優化測試</h3>



<p class="has-medium-font-size">參考 features_name 、 plot_tree 設定條件數值，加入條件到原本的策略，檢測能否優化。<br>檔數、部位上限、週期設定不變，只加上選股條件。數據會因資料集擴增而有差異，僅供參考。</p>



<h4 class="has-medium-font-size">低融資使用率</h4>



<p class="has-medium-font-size">加入 (融資使用率 &lt;= 34) 條件。</p>



<figure class="wp-container-8 wp-block-gallery-7 wp-block-gallery has-nested-images columns-default is-cropped">
<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="690" data-id="4737" src="https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-30-下午9.26.22-1024x690.png" alt="截圖 2022 10 30 下午9.26.22" class="wp-image-4737" srcset="https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-30-下午9.26.22-1024x690.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-30-下午9.26.22-300x202.png 300w, https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-30-下午9.26.22-768x518.png 768w, https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-30-下午9.26.22.png 1383w" sizes="(max-width: 1024px) 100vw, 1024px" title="低波動本益成長比策略 | MAE_MFE 機器學習選股 16"></figure>
</figure>



<h4 class="has-medium-font-size">低進場波動率</h4>



<p class="has-medium-font-size">加入 ( entry_volatility &lt;= 0.032) 條件。</p>



<figure class="wp-container-10 wp-block-gallery-9 wp-block-gallery has-nested-images columns-default is-cropped">
<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="701" data-id="4738" src="https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-30-下午9.29.17-1024x701.png" alt="截圖 2022 10 30 下午9.29.17" class="wp-image-4738" srcset="https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-30-下午9.29.17-1024x701.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-30-下午9.29.17-300x205.png 300w, https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-30-下午9.29.17-768x526.png 768w, https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-30-下午9.29.17.png 1385w" sizes="(max-width: 1024px) 100vw, 1024px" title="低波動本益成長比策略 | MAE_MFE 機器學習選股 17"></figure>
</figure>



<h4 class="has-medium-font-size"> </h4>



<h4 class="has-medium-font-size">低融資使用率 ＆ 低進場波動率<br></h4>



<figure class="wp-container-12 wp-block-gallery-11 wp-block-gallery has-nested-images columns-default is-cropped">
<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="692" data-id="4736" src="https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-30-下午9.24.29-1024x692.png" alt="截圖 2022 10 30 下午9.24.29" class="wp-image-4736" srcset="https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-30-下午9.24.29-1024x692.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-30-下午9.24.29-300x203.png 300w, https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-30-下午9.24.29-768x519.png 768w, https://www.finlab.tw/wp-content/uploads/2022/10/截圖-2022-10-30-下午9.24.29.png 1387w" sizes="(max-width: 1024px) 100vw, 1024px" title="低波動本益成長比策略 | MAE_MFE 機器學習選股 18"></figure>
</figure>



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



<h3>回測分析</h3>



<p class="has-medium-font-size">單因子中「低融資使用率」效果最強，明顯提升「夏普率」，「最大回撤率」則變動不大。可能代表原本的策略蠻多虧損或大幅低檔震盪的源在選到高融資使用率的股票，這類股票通常是市場的大波動熱門股，持有者偏向短線操作，很不穩定。<br><br>「低進場波動度」雖然讓「年化報酬率」減少，但是「夏普率」和「最大回撤率」提升效果比「低融資使用率」更優。低進場波動度代表買入時波動穩定，比較不會碰上已漲一大段的飛天股之後的乖離過大修正，若之後要加上停損條件，也比較不會在持有初期頻繁停損被洗出場。<br><br>「低融資使用率」若與「低進場波動度」因子結合，「夏普率」 從原先策略的 0.9 拉升到1.5，「最大回撤率」降到 -17% 的水準，明顯優化回撤波動。幾乎每一年回測都是正報酬穩定度明顯提升。</p>



<h2>結論</h2>



<p class="has-medium-font-size">這樣的優化策略思路是不是很有趣呢？藉由多元 label 的設定，讓機器學習能考慮多方面去強化策略，只用 scikit learn 最基本的機器學習演算法，非監督式學習與監督式的雙流分工，就能讓優化策略的流程省時省力，趕緊來試試用機器學習選股讓策略更上一層樓吧～<br><a href="https://colab.research.google.com/drive/1Sag1kIoHY2TDXJWWbugRIz1Mq8BcCi2f?usp=sharing" target="_blank" rel="noopener">colab 範例檔</a><br><a href="https://ai.finlab.tw/strategyview/?uid=TJN4FDuqrwU8DML7DAjUYFIMutp2&amp;sid=%E4%BD%8E%E6%B3%A2%E5%8B%95%E6%9C%AC%E7%9B%8A%E6%88%90%E9%95%B7%E6%AF%94" target="_blank" rel="noopener">低波動本益成長比策略部署</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/low_volatility_stratgy_by_mae_mfe_ml/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3687</post-id>	</item>
		<item>
		<title>彈性進出場的判斷 ｜ 優勢比率應用</title>
		<link>https://www.finlab.tw/edge-ratio-follow-application/</link>
					<comments>https://www.finlab.tw/edge-ratio-follow-application/#respond</comments>
		
		<dc:creator><![CDATA[Ben]]></dc:creator>
		<pubDate>Thu, 01 Sep 2022 04:04:37 +0000</pubDate>
				<category><![CDATA[技術面]]></category>
		<category><![CDATA[edge_ratio]]></category>
		<category><![CDATA[MAE_MFE]]></category>
		<guid isPermaLink="false">https://www.finlab.tw/?p=4320</guid>

					<description><![CDATA[當你開發完策略，也跑完統計清單，有沒有碰過一種狀況是策略換股週期在月初每月換股，但現在已經月中，你在猶豫適不適 [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p class="has-medium-font-size">當你開發完策略，也跑完統計清單，有沒有碰過一種狀況是策略換股週期在月初每月換股，但現在已經月中，你在猶豫適不適合中途進場？<br>你一定想過若點位和日期不同，雖然是同一檔標的，但不同價位所面臨的風險完全不一樣，可能策略回測賺錢，但你中途進價太高，導致最後是虧損的局面。</p>



<p class="has-medium-font-size">或是你害怕中途進場買高，結果策略一路走高，你只能看著他一路飆，錯過補票機會。<br>雖然保守一點來看，其實這也沒什麼不好，少賺總比賠錢好，想貼合回測曲線，下次換股日再注意也是選項，但有沒有辦法讓我們判斷策略的進出場彈性，做更積極的決策？</p>



<h2>優勢比率定義</h2>



<p class="has-medium-font-size">要如何判斷策略適不適合補票(中途進場或加碼)？可以藉由海龜交易法則的 Edge Ratio (優勢比率來判斷)。<br>優勢比率為平均 GMFE (策略每筆交易紀錄的最大有利幅度) 除以平均 MAE (策略每筆交易紀錄的最大不利幅度)。這可以藉此評估進場優勢，一個隨機性的訊號大致上會帶來相等的  MFE 與 MAE。</p>



<p class="has-medium-font-size">若大於1，代表存在正優勢，潛在最大獲利空間比最大虧損多，在持有過程中保有優勢可以中途停利或做其他操作，也就是策略的容錯率較高。反之則為劣勢，可能要抗衡較多的虧損狀態。</p>



<h2>優勢比率時序分析</h2>



<p class="has-medium-font-size">我們加上時序分析，判斷策略每筆歷史交易持有過程 n 天內的優勢比率變化，看看隨著持有時間變長，優勢比率是不是會走高？通常一個好的趨勢策略，都會逐步拉開優勢空間。</p>



<h3>如何使用 FinLab Package 顯示策略的優勢比率?</h3>



<p class="has-medium-font-size">回測函數<a href="https://doc.finlab.tw/reference/backtest/#finlab.backtest.sim" target="_blank" rel="noopener">sim </a>裡面的參數「mae_mfe_window」控制「優勢比率時序圖」的時間長度，設定40就是看40天的變化，為了加快回測運算，此參數預設為None，如果要顯示優勢比率，且既一定要自己設定「mae_mfe_window」數值。<br>一般來說若是月週期 (20交易日) 的策略，我都會拉長一點到40，看策略有沒有可能20天後的edge_ratio持續走升，若是此情況，可以著墨策略延後出場，獲取更多報酬的可能性。<br>sim會回傳<a href="https://doc.finlab.tw/reference/analysis/#finlab.analysis.Report.display_mae_mfe_analysis" target="_blank" rel="noopener">report物件</a>，使用report物件內的<code>display_mae_mfe_analysis()</code>方法即可顯示「波動分析圖」。想知道「波動分析圖」更多應用可參考此篇<a href="https://www.finlab.tw/display_mae_mfe_analysis/">文章</a>。</p>



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

report=sim(position=position, mae_mfe_window=40)
report.display_mae_mfe_analysis()
</code></pre>



<p class="has-medium-font-size">回傳圖表的最上排第二張子圖即是「優勢比率時序圖」。</p>



<figure class="wp-container-14 wp-block-gallery-13 wp-block-gallery has-nested-images columns-default is-cropped">
<figure class="wp-block-image size-large"><img loading="lazy" width="1200" height="1200" data-id="4125" src="https://www.finlab.tw/wp-content/uploads/2022/07/newplot-1-1.png" alt="newplot 1 1" class="wp-image-4125" srcset="https://www.finlab.tw/wp-content/uploads/2022/07/newplot-1-1.png 1200w, https://www.finlab.tw/wp-content/uploads/2022/07/newplot-1-1-300x300.png 300w, https://www.finlab.tw/wp-content/uploads/2022/07/newplot-1-1-1024x1024.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/07/newplot-1-1-150x150.png 150w, https://www.finlab.tw/wp-content/uploads/2022/07/newplot-1-1-768x768.png 768w, https://www.finlab.tw/wp-content/uploads/2022/07/newplot-1-1-600x600.png 600w" sizes="(max-width: 1200px) 100vw, 1200px" title="彈性進出場的判斷 ｜ 優勢比率應用 19"><figcaption>「波動分析圖</figcaption></figure>
</figure>



<p></p>



<h2>分析案例</h2>



<p class="has-medium-font-size">舉幾個FinLab策略的時序圖來示範「優勢比率時序圖」如何分析 ?</p>



<h3>營收動能瘋狗策略 </h3>



<figure class="wp-container-16 wp-block-gallery-15 wp-block-gallery has-nested-images columns-default is-cropped">
<figure class="wp-block-image size-large"><img loading="lazy" width="317" height="261" data-id="4321" src="https://www.finlab.tw/wp-content/uploads/2022/09/edge_ratio_1.png" alt="edge ratio 1" class="wp-image-4321" srcset="https://www.finlab.tw/wp-content/uploads/2022/09/edge_ratio_1.png 317w, https://www.finlab.tw/wp-content/uploads/2022/09/edge_ratio_1-300x247.png 300w" sizes="(max-width: 317px) 100vw, 317px" title="彈性進出場的判斷 ｜ 優勢比率應用 20"></figure>
</figure>



<p class="has-medium-font-size">優勢比率開高一路走升，優勢空間隨著時間放大，擁有不錯的趨勢策略特質，有較高的近場彈性，但接近第20天左右(下次營收截止日換股)有高峰，這時就不建議中途進場，容易在高點套住，應等下期緩股訊號出現。<br><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>。</p>



<h3>投信大哥跟屁蟲策略 </h3>



<figure class="wp-container-18 wp-block-gallery-17 wp-block-gallery has-nested-images columns-default is-cropped">
<figure class="wp-block-image size-large"><img loading="lazy" width="333" height="261" data-id="4322" src="https://www.finlab.tw/wp-content/uploads/2022/09/edge_ratio_2.png" alt="edge ratio 2" class="wp-image-4322" srcset="https://www.finlab.tw/wp-content/uploads/2022/09/edge_ratio_2.png 333w, https://www.finlab.tw/wp-content/uploads/2022/09/edge_ratio_2-300x235.png 300w" sizes="(max-width: 333px) 100vw, 333px" title="彈性進出場的判斷 ｜ 優勢比率應用 21"></figure>
</figure>



<p class="has-medium-font-size">三天決勝負的短線策略。<br>優勢開高後一路走跌，優勢空間隨著時間快速縮小，越慢進場的局面越不利。<br>極度不適合延遲進場，沒跟到第一天就別跟了。<br>投信買賣超這個因子對短線較有影響力，過去市場應有不少人在投信短期大買後跟單，導致此現象，但這項催化劑也退的很快，長期走勢的影響力就不大，容易被其他變數干擾，較不適合當中長期因子。<br><a href="https://ai.finlab.tw/strategyview/?uid=TJN4FDuqrwU8DML7DAjUYFIMutp2&amp;sid=%E6%8A%95%E4%BF%A1%E5%A4%A7%E5%93%A5%E8%B7%9F%E5%B1%81%E8%9F%B2" target="_blank" rel="noopener">策略連結</a>。</p>



<h3>藏獒策略 </h3>



<figure class="wp-container-20 wp-block-gallery-19 wp-block-gallery has-nested-images columns-default is-cropped">
<figure class="wp-block-image size-large"><img loading="lazy" width="334" height="257" data-id="4323" src="https://www.finlab.tw/wp-content/uploads/2022/09/edge_ratio_3.png" alt="edge ratio 3" class="wp-image-4323" srcset="https://www.finlab.tw/wp-content/uploads/2022/09/edge_ratio_3.png 334w, https://www.finlab.tw/wp-content/uploads/2022/09/edge_ratio_3-300x231.png 300w" sizes="(max-width: 334px) 100vw, 334px" title="彈性進出場的判斷 ｜ 優勢比率應用 22"></figure>
</figure>



<p class="has-medium-font-size">類似營收動能瘋狗策略，但不強調營收創新高，比較多轉機股條件。<br>優勢比率在第五天創出小高峰後，會有一段明顯回撤，也就是延遲第8天進場的話，甚至有機會買的比第一天成本比，過了這個小低谷後，優勢空間開始走出大波段。<br><a href="https://ai.finlab.tw/strategyview/?uid=TJN4FDuqrwU8DML7DAjUYFIMutp2&amp;sid=%E8%97%8F%E7%8D%92" target="_blank" rel="noopener">策略連結</a>。</p>



<h2>結論</h2>



<p class="has-medium-font-size">你的策略有什麼樣子的「優勢比率時序圖」呢？趕緊用FinLab Package 來實做看看，會夠了解你策略的細節喔！</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/edge-ratio-follow-application/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">4320</post-id>	</item>
	</channel>
</rss>
