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

<channel>
	<title>機器學習 &#8211; FinLab</title>
	<atom:link href="https://www.finlab.tw/tag/%E6%A9%9F%E5%99%A8%E5%AD%B8%E7%BF%92/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.finlab.tw</link>
	<description>深入淺出的量化投資，讓你在在茫茫股海中，找到專屬於自己的投資方法</description>
	<lastBuildDate>Tue, 04 Nov 2025 16:39:46 +0000</lastBuildDate>
	<language>zh-TW</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.0.11</generator>

<image>
	<url>https://www.finlab.tw/wp-content/uploads/2020/07/favicon.png</url>
	<title>機器學習 &#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>Alpha Arena 背後的技術解析、缺陷與潛力</title>
		<link>https://www.finlab.tw/alpha-arena-%e8%83%8c%e5%be%8c%e7%9a%84%e6%8a%80%e8%a1%93%e8%a7%a3%e6%9e%90%e3%80%81%e7%bc%ba%e9%99%b7%e8%88%87%e6%bd%9b%e5%8a%9b/</link>
					<comments>https://www.finlab.tw/alpha-arena-%e8%83%8c%e5%be%8c%e7%9a%84%e6%8a%80%e8%a1%93%e8%a7%a3%e6%9e%90%e3%80%81%e7%bc%ba%e9%99%b7%e8%88%87%e6%bd%9b%e5%8a%9b/#respond</comments>
		
		<dc:creator><![CDATA[Andy]]></dc:creator>
		<pubDate>Tue, 04 Nov 2025 16:39:43 +0000</pubDate>
				<category><![CDATA[PYTHON財經]]></category>
		<category><![CDATA[加密貨幣]]></category>
		<category><![CDATA[技術面]]></category>
		<category><![CDATA[投資新手]]></category>
		<category><![CDATA[PYTHON]]></category>
		<category><![CDATA[機器學習]]></category>
		<category><![CDATA[程式交易]]></category>
		<guid isPermaLink="false">https://www.finlab.tw/?p=6730</guid>

					<description><![CDATA[近期熱門的 Alpha Arena 專案，將 ChatGPT、Gemini、Grok 等不同的大型語言模型 ( [&#8230;]]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-image size-large"><img width="1024" height="699" src="https://www.finlab.tw/wp-content/uploads/2025/11/image-2-1024x699.png" alt="image 2" class="wp-image-6735" srcset="https://www.finlab.tw/wp-content/uploads/2025/11/image-2-1024x699.png 1024w, https://www.finlab.tw/wp-content/uploads/2025/11/image-2-300x205.png 300w, https://www.finlab.tw/wp-content/uploads/2025/11/image-2-768x524.png 768w, https://www.finlab.tw/wp-content/uploads/2025/11/image-2-1536x1049.png 1536w, https://www.finlab.tw/wp-content/uploads/2025/11/image-2-2048x1398.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="Alpha Arena 背後的技術解析、缺陷與潛力 1"></figure>



<p>近期熱門的 <a href="https://nof1.ai/" target="_blank" rel="noopener">Alpha Arena</a> 專案，將 ChatGPT、Gemini、Grok 等不同的大型語言模型 (LLM)，推上了金融交易的競技場，讓這些前沿 AI 模型槓桿交易Crypto，網頁是公開顯示歷史資金和持倉變化。這個概念極具吸引力：讓最強的 AI 們同台競技，比較它們的交易績效。</p>



<p>在令人興奮的「<strong>AI 交易</strong>」敘事之下，本文將從技術層面拆解 Alpha Arena 的運作機制，看看技術原理是否真的無懈可擊 ？</p>



<h2>一、 運作機制：當 LLM 成為量化交易員</h2>



<p>Alpha Arena 的核心是利用呼叫大型語言模型 API，讓多個 LLM 扮演交易決策者的角色。其運作流程可以拆解為「輸入」、「處理」與「輸出」三階段。</p>



<h3>輸入：將市場「<strong>文本化</strong>」的提示詞 </h3>



<p>系統會向 LLM 發送一個設計好的提示詞，其內容包含：</p>



<ul><li><strong>狀態數據 :</strong> 當前帳戶績效、倉位、交易次數等。<br></li></ul>



<figure class="wp-block-image size-full"><img loading="lazy" width="918" height="410" src="https://www.finlab.tw/wp-content/uploads/2025/11/image.png" alt="image" class="wp-image-6731" srcset="https://www.finlab.tw/wp-content/uploads/2025/11/image.png 918w, https://www.finlab.tw/wp-content/uploads/2025/11/image-300x134.png 300w, https://www.finlab.tw/wp-content/uploads/2025/11/image-768x343.png 768w" sizes="(max-width: 918px) 100vw, 918px" title="Alpha Arena 背後的技術解析、缺陷與潛力 2"><figcaption>交易狀態提示詞範例</figcaption></figure>



<ul><li><strong>市場數據 :</strong> 中間價、EMA (指數移動平均線) 等技術指標資料。<br></li></ul>



<figure class="wp-block-image size-full"><img loading="lazy" width="898" height="1018" src="https://www.finlab.tw/wp-content/uploads/2025/11/image-1.png" alt="image 1" class="wp-image-6732" srcset="https://www.finlab.tw/wp-content/uploads/2025/11/image-1.png 898w, https://www.finlab.tw/wp-content/uploads/2025/11/image-1-265x300.png 265w, https://www.finlab.tw/wp-content/uploads/2025/11/image-1-768x871.png 768w" sizes="(max-width: 898px) 100vw, 898px" title="Alpha Arena 背後的技術解析、缺陷與潛力 3"><figcaption>市場狀態提示詞範例</figcaption></figure>



<ul><li><strong>關鍵指標文本化:</strong> 這是本專案的特色之一。它將 MACD、RSI 這類傳統的時間序列數據，用<strong>自然語言</strong>描述出來（例如：「RSI 目前為 46.4」），強迫 LLM 在文本層面理解技術指標。</li></ul>



<h3>處理：模型的「思考鏈」 (Chain of Thought)</h3>



<p>下面是網頁上實際的 GPT-5 API 回應結果:</p>



<pre class="wp-block-code"><code lang="json" class="language-json">{"cot_trace": "**Examining liquidation risk**\n\nWhen it comes to a short position, liquidation happens if the price rises above a certain level. In my case, the liquidation price is 0.17 and it matches the entry, which gives me pause. Since the current price is 0.167, I’m feeling safe for now. Yet, the liquidation price being so close means I can't widen my stop, especially since it is set at 0.171712. That puts me at critical risk, as the stop is above the liquidation price.\n**Assessing long position risks**\n\nIt seems the liquidation price might be rounded, like 0.170 when it could have more decimals. If liquidation happens at 0.17, hitting 0.1717 would liquidate before the stop, which doesn’t seem feasible. While we shouldn't close early, I’m checking my long position in BNB. Invalidation requires a 4-hour candle close below 990 and open interest over 62000. Currently, the price is 993.635 and OI is 65954.12, which doesn’t trigger invalidation. Although the 4-hour trend is negative, I’ll stick to my strategy.\n**Confirming holding positions**\n\nI need to hold all six positions without any adjustments since modifications like adjusting stops or profit targets aren’t allowed. For each coin, I have to provide an object that includes several fields: coin, signal (which will be 'hold'), the full quantity size, profit target, stop loss, invalidation condition, leverage, confidence, and risk in USD. \n\nFor example, with ETH having a quantity of -1.3, I’m writing it as is since the instructions specify using the full current size. There’s a bit of confusion about sign conventions, but I’ll follow the guidelines provided for holding.\n**Finalizing position details**\n\nI’m confirming the details for short positions, where negative quantities matter. For example, the quantity for my first position is -1.3, so I’ll output that. The profit target is 3407.47, the stop loss is 3719.44, the leverage is 12, confidence is 0.63, and the risk is 156.53. \n\nI’ll check other positions too, like SOL with quantity -35.79, XRP -1509.0, and BTC -0.02. For BNB, I have a quantity of 3.5, a profit target of 1073.65, and a specific invalidation condition related to open interest that isn’t met yet.\n**Creating hold signal JSON**\n\nI need to ensure the hold signal is set correctly. If any stops or targets were triggered since entry, the system will handle that automatically. I won't enter new trades since we have existing positions in all symbols, and we can't increase size. \n\nThe output will be a single JSON object with keys for each coin: ETH, SOL, XRP, BTC, DOGE, and BNB. Each will have the required fields formatted as floats. I'll ensure precision and check if any invalidation for BNB has triggered, but we can't infer anything from the current status. Now, I’ll produce the JSON accordingly.\n",
"cot_trace_summary": "My current strategy is to hold all positions as my analysis suggests current market conditions do not warrant adjustments despite a significant overall loss. I'm maintaining my short positions in ETH, SOL, XRP, BTC, and DOGE, as well as my long position in BNB, focusing on their individual exit plans and risk management parameters."}</code></pre>



<p>如 <code>cot_trace</code> 所示，LLM 會接收提示詞，並進行一段類似人類的「思考過程」。它會評估風險（&#8221;Examining liquidation risk&#8221;）、評估倉位（&#8221;Assessing long position risks&#8221;），並最終決定其行動。</p>



<h3>輸出：結構化的 JSON 交易決策</h3>



<p>LLM 最終會回傳一個標準化的 JSON 物件，作為其交易指令。這個 JSON 包含了所有關鍵決策：</p>



<ul><li><strong>交易訊號 (Signal):</strong> <code>hold</code> (持有) 或 <code>sell</code> (賣出)。</li><li><strong>風險參數 (Risk Parameters):</strong> <code>profit_target</code> (止盈) 和 <code>stop_loss</code> (止損)。</li><li><strong>退出條件 (Invalidation Condition):</strong> 一個 LLM <strong>即時生成</strong>的、基於技術指標的出場規則（例如：「4 小時 K 線收盤價高於 3800 並且 4 小時的 MACD 柱狀圖連續 2 根為正值」）。</li><li><strong>信心指數 (Confidence):</strong> 一個 0 到 1 的數字，表示模型對此決策的信心。</li></ul>



<p>範例格式如下：</p>



<pre class="wp-block-code"><code lang="json" class="language-json">{
"ETH": {
          "risk_usd": 156.53,
          "leverage": 12,
          "confidence": 0.63,
          "quantity": -1.3,
          "invalidation_condition": "Close early only if a 4h candle closes above 3800 AND the 4h MACD histogram turns positive for 2 consecutive bars.",
          "profit_target": 3407.47,
          "stop_loss": 3719.44,
          "justification": "",
          "coin": "ETH",
          "signal": "hold"
        }
}</code></pre>



<h2>二、 方法論缺陷：是「策略」還是「幻覺」？</h2>



<p>儘管機制看似完整，但從嚴謹的量化交易角度審視，Alpha Arena 在方法論上存在幾個根本性的缺陷。</p>



<h3>缺陷一：策略是「幻覺」，而非「回測」的產物</h3>



<p>這是最核心的問題。LLM 產出的 <code>invalidation_condition</code>（退出條件）並<strong>不是一個經過系統性回測證明其有效的策略</strong>。</p>



<p>相反地，它更像是 LLM 基於其龐大的訓練數據（網路論壇、分析文章），「<strong>幻覺</strong>」或「<strong>拼湊</strong>」出來的、<strong>當下聽起來最合理的交易規則</strong>。這如同要求 AI「<strong>即時創造</strong>」一道新菜，而非嚴格執行一道經過千次測試的米其林食譜——聽起來很棒，但穩定性與安全性存疑。</p>



<h3>缺陷二：缺乏一致性與可重複性</h3>



<p>傳統的量化交易程式是確定性的：相同的輸入（RSI &gt; 70）永遠會觸發相同的條件。</p>



<p>但 LLM 本質上是機率性的。這意味著，即使下次遇到完全相同的市場數據和提示詞，LLM 也不保證會生成完全相同的 <code>cot_trace</code> 或 <code>invalidation_condition</code>。它下一次可能認為「RSI 跌破 50」才是出場條件。這使得整個系統極度不穩定、無法驗證，也無法回測一個「隨機變動」的策略。</p>



<h3>缺陷三：不科學的「自信度」評分</h3>



<p>經過分析顯示，模型給出的 <code>confidence</code> 分數高度集中在 0.6-0.7 之間，且未見低於 0.6 的分佈。這種集中的數值分佈，不像科學計算的結果，反而更像 LLM 作為評判者（LLM as a judge）時產生的「幻覺分數」。<br>我們直接去抓取網頁的 api 回應，實際去分析 LLM 的輸出，統計所有模型的 LLM Response ，分析發現 0.6-0.7 出現的頻率非常高且頻繁，且沒有出現低於 0.6 信心的分佈，不是很合理情況。</p>



<p>正常情況下，如果分數是經過科學計算的，它應該是一個連續的分佈。<br></p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="610" src="https://www.finlab.tw/wp-content/uploads/2025/11/CleanShot-2025-11-04-at-15.49.10@2x-1024x610.png" alt="CleanShot 2025 11 04 at 15.49.10@2x" class="wp-image-6733" srcset="https://www.finlab.tw/wp-content/uploads/2025/11/CleanShot-2025-11-04-at-15.49.10@2x-1024x610.png 1024w, https://www.finlab.tw/wp-content/uploads/2025/11/CleanShot-2025-11-04-at-15.49.10@2x-300x179.png 300w, https://www.finlab.tw/wp-content/uploads/2025/11/CleanShot-2025-11-04-at-15.49.10@2x-768x458.png 768w, https://www.finlab.tw/wp-content/uploads/2025/11/CleanShot-2025-11-04-at-15.49.10@2x-1536x915.png 1536w, https://www.finlab.tw/wp-content/uploads/2025/11/CleanShot-2025-11-04-at-15.49.10@2x.png 1990w" sizes="(max-width: 1024px) 100vw, 1024px" title="Alpha Arena 背後的技術解析、缺陷與潛力 4"><figcaption>信心分布統計</figcaption></figure>



<pre class="wp-block-code"><code class="">--- confidence 分數的出現次數 ---
分數 0.62: 48 次
分數 0.63: 32 次
分數 0.64: 16 次
分數 0.65: 85 次
分數 0.67: 17 次
分數 0.7: 100 次
分數 0.75: 62 次
分數 0.78: 24 次
分數 0.8: 12 次
分數 0.85: 12 次
分數 0.9: 12 次</code></pre>



<h3>缺陷四：時間序列「文本化」導致時間意義缺失</h3>



<p>將 MACD、RSI 這類時序數據轉換為文本序列，是為了迎合 LLM 的輸入格式。然而，Transformer 架構是基於 <em>token</em> 的順序去預測下一個 <em>token</em>，它<strong>無法真正理解「時間的連續性」</strong>。</p>



<p>當時間序列被「壓平」成文字時，LLM 的「腦海」中缺乏了時間的維度。雖然它可能在預訓練中學到了 MACD 和 RSI 的基本概念（這或許能解釋 Deepseek 表現較好的原因），但要求它基於這種「<strong>無時間感</strong>」的文本去做出精確的時序預測，是有難度的。</p>



<h2>三、 潛在價值：為何 Alpha Arena 仍有價值</h2>



<p>儘管缺陷明顯， Alpha Arena 也是有其價值。它的真正價值不在於當下的交易績效，而在於它展示的潛力：</p>



<h3>潛力一：革命性的「可解釋性」 (Explainable AI)</h3>



<p>LLM 的<strong>思維鏈</strong>是這個專案最有趣的部分。傳統量化交易的「黑盒子」模型（例如 SVM 或神經網路）很難解釋為什麼它要買入。</p>



<p>而 Alpha Arena 迫使 LLM 用人類可讀的語言來「解釋」它的決策過程（&#8221;Examining liquidation risk&#8230;&#8221;）。對於某些機構而言，這種<strong>決策過程透明化</strong>的特性是有價值的，可以使用 AI 輔助決策。</p>



<h3>2. 潛力二：「非結構化數據」的巨大潛力</h3>



<p>目前專案僅將「<strong>結構化</strong>」的技術指標文本化，這確實是上面說的缺陷之一。</p>



<p>但如果在這個框架中，讓 LLM 在 Prompt 中加入，去處理<strong>非結構化數據</strong>，這就是 LLM 相較於傳統模型，最具壓倒性優勢的地方。<br>例如：</p>



<ul><li>「這是過去 1 小時社群平台上關於 BTC 的恐慌指數」</li><li>「聯準會主席在 5 分鐘前的發言偏向鷹派」</li></ul>



<p>傳統模型難以理解這些文本的語意和情緒。而 LLM 交易機器人是有潛力將「<strong>市場情緒</strong>」、「<strong>新聞事件</strong>」和「<strong>技術指標</strong>」真正融合在同一個決策模型中的架構。</p>



<h3>潛力三：一個極具價值的「元實驗」</h3>



<p>Alpha Arena（阿爾法競技場）這個名字本身就點出了其價值。它不是在宣稱誰是最好的交易模型，而是建立了一個「競技場」讓所有模型同台競技。</p>



<p>這本身就是一個非常有價值的實驗。它讓我們首次有機會在相同的規則下，橫向比較不同 LLM（GPT-5, Gemini,Grok&#8230;）的金融推理能力。</p>



<h2>四、 結論：一個「有趣」但尚未成熟的未來</h2>



<p>從技術層面分析來看，Alpha Arena 目前更像是一台令人興奮的「概念車」。它存在「策略幻覺」、「缺乏一致性」等根本性的方法論缺陷，使其目前的交易結果不具備嚴謹的科學意義。</p>



<p>然而，它的價值絕非零。Alpha Arena 成功地展示了 LLM 在<strong>決策可解釋性和融合非結構化數據</strong>方面的巨大潛力。它作為一個「AI 競技場」的實驗，其價值遠高於它產生的帳面損益。</p>



<p>總體而言，這是一個「<strong>好玩有趣</strong>」且極具啟發性的專案，它為我們揭開了 AI 金融交易未來樣貌。</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/alpha-arena-%e8%83%8c%e5%be%8c%e7%9a%84%e6%8a%80%e8%a1%93%e8%a7%a3%e6%9e%90%e3%80%81%e7%bc%ba%e9%99%b7%e8%88%87%e6%bd%9b%e5%8a%9b/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">6730</post-id>	</item>
		<item>
		<title>Qlib 與 FinLab 整合，展現 AI 選股的神蹟。</title>
		<link>https://www.finlab.tw/qlib-finlab-implementation-source-code/</link>
					<comments>https://www.finlab.tw/qlib-finlab-implementation-source-code/#respond</comments>
		
		<dc:creator><![CDATA[FinLab - 韓承佑]]></dc:creator>
		<pubDate>Mon, 06 Jan 2025 15:47:50 +0000</pubDate>
				<category><![CDATA[AI看股票]]></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=6410</guid>

					<description><![CDATA[雖然 FinLab 支援 Qlib 很久了，但一直沒有好好的跟大家介紹如何使用，於是乎，最近中小股票真的表現令 [&#8230;]]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="585" src="https://www.finlab.tw/wp-content/uploads/2025/01/image-1-1024x585.png" alt="image 1" class="wp-image-6412" srcset="https://www.finlab.tw/wp-content/uploads/2025/01/image-1-1024x585.png 1024w, https://www.finlab.tw/wp-content/uploads/2025/01/image-1-300x171.png 300w, https://www.finlab.tw/wp-content/uploads/2025/01/image-1-768x439.png 768w, https://www.finlab.tw/wp-content/uploads/2025/01/image-1-1536x878.png 1536w, https://www.finlab.tw/wp-content/uploads/2025/01/image-1.png 1792w" sizes="(max-width: 1024px) 100vw, 1024px" title="Qlib 與 FinLab 整合，展現 AI 選股的神蹟。 5"></figure>



<p>雖然 FinLab 支援 Qlib 很久了，但一直沒有好好的跟大家介紹如何使用，於是乎，最近中小股票真的表現令人窒息，所以就好好做研究，相信總會時來運轉的。台股權值股與中小型股差異，來到20年來最大，台積電創新高之際，已經有很多股票跌破年線了，老實說，虧很多嗎？是還好，但就是很悶，心情不受影響是不可能的，然而人生在世，就是來體驗這些喜怒哀樂，就讓我們繼續努力，看結果如何，雖然很煩，但是我還是對於未來非常樂觀！</p>



<h1>Qlib</h1>



<p>Qlib 是由微軟開源的量化投資工具庫，專注於基於機器學習的投資研究。它提供了資料處理、策略建模、回測及評估的一站式解決方案。</p>



<h1>Qlib 在 FinLab 中的應用</h1>



<p>Qlib 的演算法有非常多前人研究的心血，不是我們能夠短時間比擬的，所以要站在巨人的肩膀上，才能事半功倍！Qlib 的最大特點，就是在於</p>



<p>1. 特徵的建構 </p>



<p>2. 模型的多樣選擇</p>



<p>基於以上兩點，你都可以透過 FinLab package 將它們給接入進來使用。然而我覺得 Qlib 架構比較難與其它的生態系或 Package 整合，因為整個框架以程式系統來說，是比較封閉，沒辦法與傳統的 sklearn，或是 lgb、xgb 整合，所以才需要使用 FinLab 將其解放。</p>



<h1>Qlib vs FinLab</h1>



<p>Qlib 是通用型的 package，所以特徵都是使用價格來製作，而 FinLab 本身支援台股多樣的資料與指標，所以延伸的部分非常多！歡迎將以下的功能當成基礎版本，自己加入更多特徵來增進模型的運測能力！</p>



<h1>安裝</h1>



<p>接下來，將會使用 Colab 來進行設定，但以下範例需要 Colab Pro 版本，才能順利運行，因為 RAM 的需求太大了。假如各位沒有買 Colab 付費版，也可以在自己的主機上試試看，初次安裝，需要有以下的套件：</p>



<pre class="wp-block-code"><code lang="bash" class="language-bash">!pip install finlab &gt; log.txt
!pip install ta-lib-bin &gt; log.txt
!pip install catboost &gt; log.txt</code></pre>



<p>上面的程式中，安裝 talib 的方法，是使用 ta-lib-bin，是 colab 上特別的安裝方法，假如你是在桌機上使用，要用</p>



<pre class="wp-block-code"><code lang="bash" class="language-bash">conda install conda-forge::ta-lib</code></pre>



<p>來取代。</p>



<h1>安裝 Qlib</h1>



<p>安裝 Qlib 的方式，有很多種，一種是直接將 github 上的最新版本下載下來安裝：</p>



<pre class="wp-block-code"><code lang="bash" class="language-bash">!git clone https://github.com/microsoft/qlib.git
%cd qlib
!make install
!pip install .
%cd ..</code></pre>



<p>要注意，以上的程式碼是在 terminal 中使用，不是 python 語法喔！</p>



<h1>製作特徵</h1>



<p>我們可以使用 qlib 內建的功能，產生出158種，或是360種不同的價格訊號，只需要三行即可完成：</p>



<pre class="wp-block-code"><code lang="python" class="language-python">from finlab.ml import qlib as q


q.init()
q.dump()
f158 = q.alpha("Alpha158")</code></pre>



<p>然而這樣的資料量，實在是太大了，所以我們可以將資料的頻率改成「週」，大約可以減少80％的資料量，這樣的訓練方式，勉強能夠在 Colab Pro 上執行（50GB RAM）。假如是 alpha360 資料集，基本上會需要上百GB，就請有這樣硬體能力的玩家自行上手了！</p>



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

features = mlf.combine({
    'qlib': f158,
}, resample='W')
labels = mll.return_percentage(features.index, period=2)

is_train = features.index.get_level_values('datetime') &lt; '2020-01-01'</code></pre>



<p>接下來，我們發現，f158之中，有一個特徵都是 NaN（也就是空值），我們必須要將它刪除：</p>



<pre class="wp-block-code"><code lang="python" class="language-python">features = features.drop('VWAP0', axis=1)</code></pre>



<p>目前原因不明，應該還有一些 BUG 需要釐清，也可以利用 `mlf.combine` 自行計算補上 VWAP 的資料。</p>



<h1>訓練模型</h1>



<p>訓練模型的環節，FinLab 提供一個超級好用的功能</p>



<pre class="wp-block-code"><code class="">model_templates = q.get_models()</code></pre>



<p>就可以將 qlib 所有的模型導入，並且直接用來訓練：</p>



<pre class="wp-block-code"><code lang="python" class="language-python">import gc
import numpy as np
import pickle
from finlab.ml import qlib as q

model_templates = q.get_models()
is_train = features.index.get_level_values('datetime') &lt; '2020-01-01'


model_path = './models.pkl'

if os.path.isfile(model_path):
  with open(model_path, 'rb') as f:
    models = pickle.load(f)
else:
  models = {}


for name, Model in model_templates.items():
    print(name)

    if name in models:
      continue

    if name == 'DNNModel':
      continue

    try:
      X_train = features.loc[is_train]
      y_train = labels.loc[is_train]
      model = Model()
      model.fit(X_train, y_train)

    except:
      notna = X_train.replace([np.inf, -np.inf], np.nan).notna().all(axis=1) &amp; y_train.replace([np.inf, -np.inf], np.nan).notna()
      X_train = X_train.loc[notna]
      y_train = y_train.loc[notna]
      model = Model()
      model.fit(X_train, y_train)


    with open(f'models.pkl', 'wb') as f:
      pickle.dump(models, f)

    models[name] = model

    gc.collect()</code></pre>



<p>訓練的過程中，可能訓練到一半 RAM 會掛掉，所以每次訓練好新的模型，程式會將所有模型都儲存起來，方便下一次直接調用。訓練時，會將 training data 自動切出 validation data，來確保訓練時避免 overfitting。</p>



<h1>測試</h1>



<p>最後我們可以回測看看模型得效果如何：</p>



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

model_path = './models.pkl'

if os.path.isfile(model_path):
  with open(model_path, 'rb') as f:
    models = pickle.load(f)


ys = {}

for name, model in models.items():

  try:
    y = model.predict(features[~is_train])
    ys[name] = y
  except:
    y = model.predict(features[~is_train].replace([np.inf, -np.inf], np.nan).fillna(0))
    ys[name] = y

from finlab.backtest import sim
import matplotlib.pyplot as plt
from finlab import data

reports = {}
for name, y in ys.items():
  print(name)
  with data.universe('TSE_OTC'):
    close = data.get('price:收盤價')
    report = sim(y[close.notna()].is_largest(20), resample='M', upload=False)
    reports[name] = report
    report.creturn.plot(label=name)

plt.legend()
plt.show()</code></pre>



<figure class="wp-block-image size-full"><img loading="lazy" width="543" height="407" src="https://www.finlab.tw/wp-content/uploads/2025/01/image.png" alt="image" class="wp-image-6411" srcset="https://www.finlab.tw/wp-content/uploads/2025/01/image.png 543w, https://www.finlab.tw/wp-content/uploads/2025/01/image-300x225.png 300w" sizes="(max-width: 543px) 100vw, 543px" title="Qlib 與 FinLab 整合，展現 AI 選股的神蹟。 6"></figure>



<p>其實效果算是滿不錯的，實單上，經過更多的調教，我的經驗，會比當前的成果更好，有興趣的玩家可以多多嘗試！其中一些策略回測甚至可以有 40％到50％的平均年報酬率。</p>



<p>話說最近 AI 模型，這幾個月的表現可能都不太好，然而換一種想法，就是當前可能不太適合使用 AI 模型吧～不代表它以後都沒效果，而是時運不佳的關係，反而讓我的心裡有點釋懷。</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="937" src="https://www.finlab.tw/wp-content/uploads/2025/01/image-2-1024x937.png" alt="image 2" class="wp-image-6413" srcset="https://www.finlab.tw/wp-content/uploads/2025/01/image-2-1024x937.png 1024w, https://www.finlab.tw/wp-content/uploads/2025/01/image-2-300x275.png 300w, https://www.finlab.tw/wp-content/uploads/2025/01/image-2-768x703.png 768w, https://www.finlab.tw/wp-content/uploads/2025/01/image-2.png 1464w" sizes="(max-width: 1024px) 100vw, 1024px" title="Qlib 與 FinLab 整合，展現 AI 選股的神蹟。 7"></figure>



<p>由上表可知，我們可以選擇 LightGBM 模型來選股，效果最好。</p>



<p></p>



<p>以下示範一個年平均報酬 +50%的策略，這絕對是價值數萬元的程式碼，就這麼隨便的放在這邊讓大家取用，請你跟我說，在世界上的哪一個角落，可以找到這麼神乎其技的AI模型選股績效？找不到吧！只好請大家繼續支持 FinLab，讓我們可以活下去，謝謝：</p>



<pre class="wp-block-code"><code lang="python" class="language-python">y = ys['LGBModel']

with data.universe('TSE_OTC'):

  close = data.get('price:收盤價')
  vol = data.get('price:成交股數')
  pos = y[((vol.average(20) &gt; 200_000)) &amp; (close &gt;= close.rolling(10).max())].is_largest(10)
  report = sim(pos, resample='M', upload=False)
  report.display()</code></pre>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="994" src="https://www.finlab.tw/wp-content/uploads/2025/01/image-3-1024x994.png" alt="image 3" class="wp-image-6414" srcset="https://www.finlab.tw/wp-content/uploads/2025/01/image-3-1024x994.png 1024w, https://www.finlab.tw/wp-content/uploads/2025/01/image-3-300x291.png 300w, https://www.finlab.tw/wp-content/uploads/2025/01/image-3-768x746.png 768w, https://www.finlab.tw/wp-content/uploads/2025/01/image-3-1536x1491.png 1536w, https://www.finlab.tw/wp-content/uploads/2025/01/image-3.png 1574w" sizes="(max-width: 1024px) 100vw, 1024px" title="Qlib 與 FinLab 整合，展現 AI 選股的神蹟。 8"></figure>



<p></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/qlib-finlab-implementation-source-code/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">6410</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 機器學習選股 9"></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 機器學習選股 10"></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 機器學習選股 11"></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 機器學習選股 12"></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 機器學習選股 13"><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 機器學習選股 14"></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 機器學習選股 15"></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 機器學習選股 16"></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 機器學習選股 17"></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>機器學習 Python 做比特幣交易，如何找到好的特徵？增進模型的有效工具</title>
		<link>https://www.finlab.tw/python-machine-learning-bitcoin-feature-engineering/</link>
					<comments>https://www.finlab.tw/python-machine-learning-bitcoin-feature-engineering/#respond</comments>
		
		<dc:creator><![CDATA[FinLab - 韓承佑]]></dc:creator>
		<pubDate>Wed, 11 May 2022 05:30:26 +0000</pubDate>
				<category><![CDATA[AI看股票]]></category>
		<category><![CDATA[BTC]]></category>
		<category><![CDATA[PYTHON]]></category>
		<category><![CDATA[機器學習]]></category>
		<category><![CDATA[比特幣]]></category>
		<category><![CDATA[程式交易]]></category>
		<category><![CDATA[量化投資]]></category>
		<guid isPermaLink="false">https://www.finlab.tw/?p=3520</guid>

					<description><![CDATA[這篇文章用機器學習實作能獲利的 BTCUSDT 交易模型，使用 Tunta 優化特徵，獲得更好的交易預測能力， [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>這篇文章用<a href="https://www.finlab.tw/category/ai%e7%9c%8b%e8%82%a1%e7%a5%a8/">機器學習</a>實作能獲利的 <a href="https://www.finlab.tw/category/%e5%8a%a0%e5%af%86%e8%b2%a8%e5%b9%a3/">BTCUSDT</a> 交易模型，使用 Tunta 優化特徵，獲得更好的交易預測能力，會有機器學習範例講解。現在的機器學習，已經越來越複雜，一個能夠實戰的模型，最好是有數百甚至是上千個 features。然而這麼多 features，並不是常人用手工一個個產生出來的，必須要大量的仰賴自動化生成。例如像是 Numerai 平台，最近更新的 <a href="https://forum.numer.ai/t/super-massive-data-release-deep-dive/4053" target="_blank" rel="noopener">features 數量都已經破千了</a>，代表更多的 features 確實會對於訓練模型有所幫助。</p>



<p>Numerai 提供股票的 features，由資料科學家（我們）訓練模型並產生結果，上傳後匯聚成最後的權重，來控制對沖基金的部位。我們沒辦法知道每檔股票的名稱，所以沒辦法用 Numerai 的 features 來做交易，但我們上傳到平台上，假如績效好的話，Numerai 會額外給我們加密貨幣 NMR 當作獎勵，雖然 Numerai 是很棒的練兵的地方，但是由於要用 Stake NMR 加密貨幣才能獲利，而且 NMR 的價格波動會導致獲利的風險偏高。所以還是自己做交易比較實在，想要機器學習自學，就看這篇吧！</p>



<p>那要怎麼樣產生出上千個 features 呢？好在用 Python 製作 features 是很簡單的，只要用常見的 Packages 像是 Talib 或 pandas_ta ，加上參數的變化，就可以隨機產生出很多的 features。但困難在於，做了好幾千個 features，究竟哪些是重要的呢？假如用了沒意義的 features，反而混淆訓練結果，造成模型的績效效果不好。</p>



<h2>Tuneta 介紹</h2>



<p>介紹給大家 <a class="rank-math-link" href="https://github.com/jmrichardson/tuneta/tree/53960a8d83cec586a3d91e2667dcf0f364522533" target="_blank" rel="noopener">Tuneta</a> 這個工具可以幫我們最佳化技術指標的參數。它有以下幾個功能：</p>



<ol><li>支援 <a href="https://www.finlab.tw/python-%e7%b0%a1%e5%96%ae158%e7%a8%ae%e6%8a%80%e8%a1%93%e6%8c%87%e6%a8%99%e8%a8%88%e7%ae%97/">Talib</a>、Pandas_ta、finta，這三種不同的函式庫，有統一的接口，你再也不用擔心不同函式庫整合的問題。</li><li>針對每種技術指標，可以最佳化參數，讓產生出來的 feature 跟 lable 之間有最高的 correlation</li><li>並不是使用一般的 Pearson correlation coefficient 來判斷，而是使用一種叫做 distance correlation 的判斷機制，就算是非線性的關係也會被納入考慮。</li><li>使用 KNN 將搜尋的參數分群 Cluster，然後針對每一個 Cluster 找出中心點，這個作法可以找到參數高原。</li><li>產生每個 features 後，支援 sklearn 的 pipeline 格式，可以快速的引入當前的項目之中，點也不費力。</li></ol>



<h2>Tuneta 的效果</h2>



<p>以下是 Tuneta 做機器學習例子，加入我自己的機器學習系統中，確實對於 Model 的判斷有顯著的增長，並且使用 feature importance 分析，這些 tuneta 產生的 feature 確實分數都滿高的：</p>



<figure class="wp-block-image size-full"><img loading="lazy" width="974" height="455" src="https://www.finlab.tw/wp-content/uploads/2022/05/image-8.png" alt="image 8" class="wp-image-3551" srcset="https://www.finlab.tw/wp-content/uploads/2022/05/image-8.png 974w, https://www.finlab.tw/wp-content/uploads/2022/05/image-8-300x140.png 300w, https://www.finlab.tw/wp-content/uploads/2022/05/image-8-768x359.png 768w" sizes="(max-width: 974px) 100vw, 974px" title="機器學習 Python 做比特幣交易，如何找到好的特徵？增進模型的有效工具 18"><figcaption>機器學習 LightGBM 特徵重要性分析</figcaption></figure>



<p>機器學習深度學習，我覺得在做交易時比較少用到。比較常使用的是傳統 treebase 的模型，而非神經網路。我覺得這個 Package 的缺點在於，有時候我們會需要重複的指標當作 features，例如「sma(10)」和「sma(60)」，但是它只能幫我們產生出單個技術指標的最佳解。不過經過驗證，產生出來的 features，確實效果都還不錯！接下來我們就真的來建構一個模型吧！</p>



<h2>實驗設計</h2>



<p>機器學習python實作，我們使用 pandas_ta 的 default 參數，將所有 pandas_ta 的技術指標計算出來。另外對比 tuneta 優化後產生的技術指標，比較兩個模型的預測結果，並且用回測來驗證是否能真正幫助到獲利。</p>



<p>使用 colab 來建構統一的環境，方便大家還原實驗的結果。首先我們要先來下載 tuneta，但除了 tuneta 以外，還要有歷史資料，可以安裝 finlab-crypto 來獲得。</p>



<pre title="環境架設" class="wp-block-code"><code lang="bash" class="language-bash line-numbers">!pip install finlab-crypto -q
!wget http://prdownloads.sourceforge.net/ta-lib/ta-lib-0.4.0-src.tar.gz
!tar -xzvf ta-lib-0.4.0-src.tar.gz
%cd ta-lib
!./configure --prefix=/usr
!make
!make install
!pip install Ta-Lib
!pip install -U tuneta
!pip uninstall numpy --yes
!pip install numpy</code></pre>



<h2>下載歷史資料和 feature 建構</h2>



<p>安裝了所需的 Package ，就可以來下載歷史資料：</p>



<pre title="下載歷史資料" class="wp-block-code"><code lang="python" class="language-python line-numbers">from finlab_crypto import crawler

ohlcv = crawler.get_all_binance('BTCUSDT', '4h')
ohlcv.head()</code></pre>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="242" src="https://www.finlab.tw/wp-content/uploads/2022/05/image-1-1024x242.png" alt="image 1" class="wp-image-3530" srcset="https://www.finlab.tw/wp-content/uploads/2022/05/image-1-1024x242.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/05/image-1-300x71.png 300w, https://www.finlab.tw/wp-content/uploads/2022/05/image-1-768x182.png 768w, https://www.finlab.tw/wp-content/uploads/2022/05/image-1.png 1133w" sizes="(max-width: 1024px) 100vw, 1024px" title="機器學習 Python 做比特幣交易，如何找到好的特徵？增進模型的有效工具 19"><figcaption>下載BTC歷史資料</figcaption></figure>



<h3>使用 Pandas_ta 產生 features</h3>



<p>接下來我們先用 pandas_ta 自動產生出預設的技術指標，當作對照組：</p>



<pre title="產生技術指標的 features" class="wp-block-code"><code lang="python" class="language-python line-numbers">import pandas_ta as ta
ohlcv.ta.strategy("Momentum")

default_features = ohlcv.iloc[:, 11:]
ohlcv = ohlcv.iloc[:, :11]
default_features.head()</code></pre>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="325" src="https://www.finlab.tw/wp-content/uploads/2022/05/image-2-1024x325.png" alt="image 2" class="wp-image-3531" srcset="https://www.finlab.tw/wp-content/uploads/2022/05/image-2-1024x325.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/05/image-2-300x95.png 300w, https://www.finlab.tw/wp-content/uploads/2022/05/image-2-768x244.png 768w, https://www.finlab.tw/wp-content/uploads/2022/05/image-2.png 1043w" sizes="(max-width: 1024px) 100vw, 1024px" title="機器學習 Python 做比特幣交易，如何找到好的特徵？增進模型的有效工具 20"><figcaption>產生出 features</figcaption></figure>



<h3>使用 Tuneta 產生 features</h3>



<p>接下來我們用 tuneta 產生實驗組，眼尖的人會發現我是用 tta，也就是 talib 函式庫來產生 features，你也可以用 pta，也就是 pandas_ta 函式庫。但是在 colab 上要跑很久，所以我擅自改成 tta。在這邊實驗有點不完備，但留給大家自行發揮。</p>



<pre title="tuneta 產生 features" class="wp-block-code"><code lang="python" class="language-python line-numbers">from tuneta.tune_ta import TuneTA

train_test_split = '2021-1-1'

X1 = ohlcv.loc[:train_test_split].iloc[:-8]
y1 = (ohlcv.close.shift(-2) / ohlcv.close).loc[:train_test_split].iloc[:-8]

tt = TuneTA(n_jobs=4, verbose=True)
tt.fit(X1, y1,
    indicators=['tta'],
    ranges=[(2, 30)],
    trials=100,
    early_stop=20,
)
tt.prune()
print(tt.report())

tt_features = tt.transform(ohlcv)
tt_features.tail()</code></pre>



<figure class="wp-block-image size-full"><img loading="lazy" width="578" height="524" src="https://www.finlab.tw/wp-content/uploads/2022/05/image-3.png" alt="image 3" class="wp-image-3532" srcset="https://www.finlab.tw/wp-content/uploads/2022/05/image-3.png 578w, https://www.finlab.tw/wp-content/uploads/2022/05/image-3-300x272.png 300w" sizes="(max-width: 578px) 100vw, 578px" title="機器學習 Python 做比特幣交易，如何找到好的特徵？增進模型的有效工具 21"><figcaption>tuneta 產生出來的 feature 和相關性分析</figcaption></figure>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="258" src="https://www.finlab.tw/wp-content/uploads/2022/05/image-4-1024x258.png" alt="image 4" class="wp-image-3533" srcset="https://www.finlab.tw/wp-content/uploads/2022/05/image-4-1024x258.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/05/image-4-300x76.png 300w, https://www.finlab.tw/wp-content/uploads/2022/05/image-4-768x194.png 768w, https://www.finlab.tw/wp-content/uploads/2022/05/image-4.png 1249w" sizes="(max-width: 1024px) 100vw, 1024px" title="機器學習 Python 做比特幣交易，如何找到好的特徵？增進模型的有效工具 22"></figure>



<p>最後我們來比較兩種不同的 feature 做出來的效果。像是一般的方法訓練即可。</p>



<h2>模型訓練</h2>



<pre title="模型建構" class="wp-block-code"><code lang="python" class="language-python line-numbers">import lightgbm as lgb

# generate training data
X1_train, y1_train = default_features.loc[:train_test_split].iloc[:-8], ohlcv.close.pct_change(-2).loc[:train_test_split].iloc[:-8]
X2_train, y2_train = tt_features.loc[:train_test_split].iloc[:-8], ohlcv.close.pct_change(-2).loc[:train_test_split].iloc[:-8]

# train
model1 = lgb.LGBMRegressor()
model1.fit(X1_train, y1_train)

model2 = lgb.LGBMRegressor()
model2.fit(X2_train, y2_train)

# test and predict
X1_test, y1_test = default_features.loc[train_test_split:], ohlcv.close.pct_change(-2).loc[train_test_split:]
X2_test, y2_test = tt_features.loc[train_test_split:], ohlcv.close.pct_change(-2).loc[train_test_split:]

y1 = pd.Series(model1.predict(X1_test), X1_test.index)
y2 = pd.Series(model2.predict(X2_test), X2_test.index)</code></pre>



<p>最後我們來看一下究竟效果如何，可以用真實報酬跟預測結果的相關性來比較，越高代表越好。下面的實驗中，我們可以看到對照組的模型 ( model2 ) 比實驗組好很多。</p>



<pre title="比較兩個模型的相關性" class="wp-block-code"><code lang="python" class="language-python line-numbers">import pandas as pd

pd.DataFrame({'real': y1_test, 'pred': y1}).corr().iloc[1,0], pd.DataFrame({'real': y2_test, 'pred': y2}).corr().iloc[1,0]</code></pre>



<pre class="wp-block-preformatted">(0.007258040702236883, 0.02274027435611208)</pre>



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



<p>最後我們可以做一個簡單的回測，試試看用這兩個模型做交易，績效會有什麼不一樣。首先，要決定進場的時機，將模型預測的分布顯示出來：</p>



<figure class="wp-block-image size-full"><img loading="lazy" width="798" height="426" src="https://www.finlab.tw/wp-content/uploads/2022/05/image-5.png" alt="image 5" class="wp-image-3534" srcset="https://www.finlab.tw/wp-content/uploads/2022/05/image-5.png 798w, https://www.finlab.tw/wp-content/uploads/2022/05/image-5-300x160.png 300w, https://www.finlab.tw/wp-content/uploads/2022/05/image-5-768x410.png 768w" sizes="(max-width: 798px) 100vw, 798px" title="機器學習 Python 做比特幣交易，如何找到好的特徵？增進模型的有效工具 23"><figcaption>模型預測分布</figcaption></figure>



<p>有了上圖，就可以設計進場時機，為預測結果大於 0.04 時進場8小時。接下來撰寫回測模擬：</p>



<pre title="回測" class="wp-block-code"><code lang="python" class="language-python line-numbers">y1_test[y1 &gt; 0.04].add(1).cumprod().plot()
y2_test[y2 &gt; 0.04].add(1).cumprod().plot()</code></pre>



<figure class="wp-block-image size-full"><img loading="lazy" width="507" height="340" src="https://www.finlab.tw/wp-content/uploads/2022/05/image-6.png" alt="image 6" class="wp-image-3535" srcset="https://www.finlab.tw/wp-content/uploads/2022/05/image-6.png 507w, https://www.finlab.tw/wp-content/uploads/2022/05/image-6-300x201.png 300w" sizes="(max-width: 507px) 100vw, 507px" title="機器學習 Python 做比特幣交易，如何找到好的特徵？增進模型的有效工具 24"></figure>



<p>上圖的回測結果中，綠色為實驗組，比對照組的報酬率顯著上升不少。</p>



<h4>小節</h4>



<p>由以上的實驗，可以證明對於 feature ，使用 Tuneta 參數優化是非常有效的。現在行情不好，大家可以趁現在默默耕耘，等時機到的時候，馬上就賺回來了！</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/python-machine-learning-bitcoin-feature-engineering/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3520</post-id>	</item>
		<item>
		<title>ROE怎麼看? 機器學習告訴你！</title>
		<link>https://www.finlab.tw/roe%e6%80%8e%e9%ba%bc%e7%9c%8b-%e6%a9%9f%e5%99%a8%e5%ad%b8%e7%bf%92%e5%91%8a%e8%a8%b4%e4%bd%a0/</link>
					<comments>https://www.finlab.tw/roe%e6%80%8e%e9%ba%bc%e7%9c%8b-%e6%a9%9f%e5%99%a8%e5%ad%b8%e7%bf%92%e5%91%8a%e8%a8%b4%e4%bd%a0/#respond</comments>
		
		<dc:creator><![CDATA[FinLab - 韓承佑]]></dc:creator>
		<pubDate>Wed, 22 Jul 2020 23:05:39 +0000</pubDate>
				<category><![CDATA[AI看股票]]></category>
		<category><![CDATA[MACHINE LEARNING]]></category>
		<category><![CDATA[PYTHON]]></category>
		<category><![CDATA[機器學習]]></category>
		<category><![CDATA[程式交易]]></category>
		<category><![CDATA[股票]]></category>
		<category><![CDATA[股票分析]]></category>
		<guid isPermaLink="false">http://34.96.136.135/?p=794</guid>

					<description><![CDATA[機器學習究竟能不能輔助人類買賣股票？答案一定是可以的，我們可以藉由機器學習歸納出結果，來優化我們的選股方式，今天這篇文章沒有非常高深的數學，也沒有困難的程式，只會有做完研究的心得，幫助大家選股更順利！]]></description>
										<content:encoded><![CDATA[
<p>機器學習究竟能不能輔助人類買賣股票？答案一定是可以的，我們可以藉由機器學習歸納出結果，來優化我們的選股方式，今天這篇文章沒有非常高深的數學，也沒有困難的程式，只會有做完研究的心得，幫助大家選股更順利！<br><a href="https://www.finlab.tw/ROE%E6%80%8E%E9%BA%BC%E7%9C%8B-%E6%A9%9F%E5%99%A8%E5%AD%B8%E7%BF%92%E5%91%8A%E8%A8%B4%E4%BD%A0/thumbnail.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="669" src="http://34.96.136.135/wp-content/uploads/2020/07/thumbnail-1-5-1024x669.png" alt="thumbnail 1 5" class="wp-image-796" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-1-5-1024x669.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-1-5-300x196.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-1-5-768x502.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-1-5.png 1518w" sizes="(max-width: 1024px) 100vw, 1024px" title="ROE怎麼看? 機器學習告訴你！ 25"></figure></div>



<p>這篇文章中，我把市值跟ROE拿來做比較，並且利用SVM來訓練判斷，看看市值跟ROE對於股價漲跌的關連！</p>



<h3 id="什麼是SVM？">什麼是SVM？</h3>



<p>SVM的全名叫做&nbsp;<a href="https://en.wikipedia.org/wiki/Support_vector_machine" rel="noreferrer noopener" target="_blank">Support Vector Machine</a>，而這類的機器學習，會用 hyperplane 將空間切開，進而將空間中的座標進行分類，所以當我們有2個features時，就可以將第一個feature當作 x 軸，第二個 feature 當作 y 軸，然後顏色代表漲跌，畫出一張圖：<a href="https://www.finlab.tw/ROE%E6%80%8E%E9%BA%BC%E7%9C%8B-%E6%A9%9F%E5%99%A8%E5%AD%B8%E7%BF%92%E5%91%8A%E8%A8%B4%E4%BD%A0/svm.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="356" src="http://34.96.136.135/wp-content/uploads/2020/07/svm-1024x356.png" alt="svm" class="wp-image-797" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/svm-1024x356.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/svm-300x104.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/svm-768x267.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/svm-1536x534.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/svm.png 1560w" sizes="(max-width: 1024px) 100vw, 1024px" title="ROE怎麼看? 機器學習告訴你！ 26"></figure></div>



<p>其中的綠色點，就是代表下跌的股票，而紅色的點，則代表了上漲的股票，而hyperplane 就是黃色的時線，將這個平面上畫出精準的一刀，切成兩個部分，右半部份，代表SVM覺得未來會上漲，左半部份代表SVM覺得未來會下跌的股票。</p>



<p>以上是由視覺的方式來說明SVM，數學的部分，其實大家國中高中都有學過，其實就是點與 hyperplane 的長度，SVM會計算「點到線」之間的長度，來決定誤差。當有越多點歸類錯誤的時候，SVM就會將這些「點到線的距離加總」，當作是錯誤總分，越大越不好，於是演算法不斷的移動這個切割線（hyperplane），來達到最完美的狀態，使得錯誤總分最低。</p>



<h3 id="SVM-的-Kernel-Trick">SVM 的 Kernel Trick</h3>



<p>我們上述的都是一條直線的 hyperplane ，但其實它不一定得是直的，只要能夠切分出不同的區域來分類即可。下圖就是使用linear的kernel跟曲線的kernel的範例：<a href="https://www.finlab.tw/ROE%E6%80%8E%E9%BA%BC%E7%9C%8B-%E6%A9%9F%E5%99%A8%E5%AD%B8%E7%BF%92%E5%91%8A%E8%A8%B4%E4%BD%A0/kernel.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="345" src="http://34.96.136.135/wp-content/uploads/2020/07/kernel-1-1024x345.png" alt="kernel 1" class="wp-image-799" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/kernel-1-1024x345.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/kernel-1-300x101.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/kernel-1-768x259.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/kernel-1.png 1234w" sizes="(max-width: 1024px) 100vw, 1024px" title="ROE怎麼看? 機器學習告訴你！ 27"></figure></div>



<p>接下來，我們就來使用不同的kernel，來將股票做歸類，看它們究竟會上漲還是下跌？我們所使用的 features 只有：ROE、市值<br>方便我們以圖形化的方式呈現並理解，以下是結果：</p>



<h3 id="使用線性的kernel">使用線性的kernel</h3>



<p>此時 hyperplane 就是很簡單的一條線。雖然是簡單的一條線，但它還是非常有用處，我們可以藉由這條線的斜率，來瞭解 ROE 跟市值的關係：<a href="https://www.finlab.tw/ROE%E6%80%8E%E9%BA%BC%E7%9C%8B-%E6%A9%9F%E5%99%A8%E5%AD%B8%E7%BF%92%E5%91%8A%E8%A8%B4%E4%BD%A0/linear.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="548" src="http://34.96.136.135/wp-content/uploads/2020/07/linear-1-1024x548.png" alt="linear 1" class="wp-image-801" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/linear-1-1024x548.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/linear-1-300x160.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/linear-1-768x411.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/linear-1.png 1234w" sizes="(max-width: 1024px) 100vw, 1024px" title="ROE怎麼看? 機器學習告訴你！ 28"></figure></div>



<p>程式自動最佳化後，上圖就是程式找到一刀最完美的切法，</p>



<ul><li>黃色三角形為上漲的股票</li><li>藍色正方形為下跌的股票</li><li>黃色平面是SVM認為會上漲的股票</li><li>藍色平面是SVM認為會下跌的股票</li></ul>



<p>這邊的市值跟ROE都已經經過preprocessing，所以跟我們平常看到的數值不太一樣，我們由上圖可以看出程式在想什麼：</p>



<h4 id="機器學習：市值越高的股票，ROE也要越高">機器學習：市值越高的股票，ROE也要越高</h4>



<p>可以看到上圖中，斜率是正的，代表當市值越高時，SVM 會傾向於選擇 ROE 高一點的股票，而且此條線偏上方，代表ROE比較高比較好，所以我們可以做一些歸納；</p>



<h4 id="假如有一檔股票「市值高，但是ROE低」，不會被選進來">假如有一檔股票「市值高，但是ROE低」，不會被選進來</h4>



<p>這樣的想法算滿合理的，因為大家對市值高的股票期望比較高，或是公司的規模比較大，但此公司坐擁資源竟然還沒辦法為股東賺錢，於是期望可能轉換為失望，所以SVM表示看跌。</p>



<p>當然這個理由是我自己加的，SVM 是無情的最佳化結果而已。<br>另外我們也可以看到：</p>



<h4 id="對於「市值低，ROE低」的公司，SVM會比較寬容">對於「市值低，ROE低」的公司，SVM會比較寬容</h4>



<p>一檔「市值低，ROE低」的公司，SVM會比較寬容一些些（但還是有一定的門檻）只是不如市值高的公司那麼嚴苛罷了。</p>



<p>我們來看一下以此種邏輯回測的結果，紅色為預測會漲的股票，綠色為預測會跌的股票，每季獲利的平均<a href="https://www.finlab.tw/ROE%E6%80%8E%E9%BA%BC%E7%9C%8B-%E6%A9%9F%E5%99%A8%E5%AD%B8%E7%BF%92%E5%91%8A%E8%A8%B4%E4%BD%A0/eq1.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="375" height="242" src="http://34.96.136.135/wp-content/uploads/2020/07/eq1-1-1.png" alt="eq1 1 1" class="wp-image-802" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/eq1-1-1.png 375w, https://www.finlab.tw/wp-content/uploads/2020/07/eq1-1-1-300x194.png 300w" sizes="(max-width: 375px) 100vw, 375px" title="ROE怎麼看? 機器學習告訴你！ 29"></figure></div>



<p>效果很不錯，但是這個邏輯是否是完美的呢？<br>我們再來使用不同的kernel，試試看：</p>



<h3 id="使用曲線的kernel">使用曲線的kernel</h3>



<p>下圖為使用不同的kernel，所做出來的分類結果，我們使用2次多項式來對股票進行分類：<a href="https://www.finlab.tw/ROE%E6%80%8E%E9%BA%BC%E7%9C%8B-%E6%A9%9F%E5%99%A8%E5%AD%B8%E7%BF%92%E5%91%8A%E8%A8%B4%E4%BD%A0/poly.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="539" src="http://34.96.136.135/wp-content/uploads/2020/07/poly-1024x539.png" alt="poly" class="wp-image-803" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/poly-1024x539.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/poly-300x158.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/poly-768x404.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/poly.png 1224w" sizes="(max-width: 1024px) 100vw, 1024px" title="ROE怎麼看? 機器學習告訴你！ 30"></figure></div>



<p>怎麼分出來完全不一樣呀！我們來看第二個實驗，SVM又告訴了我們什麼：</p>



<h4 id="市值高的股票-ROE-不要太高">市值高的股票 ROE 不要太高</h4>



<p>這其實還是有些道理的，ROE 太高的股票不要買，這個是很多實驗都有做出來的結果，因為大公司的獲利，好歹也是龐大而穩定的系統，ROE高是會有上限的，不可能一直成長，當今天ROE已經很高時，代表接下來不會更高了，甚至還有可能會衰退。</p>



<p>所以買市值高的股票時，SVM傾向「ROE 不要太高」！</p>



<h4 id="市值低的股票-ROE-越高越好">市值低的股票 ROE 越高越好</h4>



<p>然而本實驗的另一個特點，就是SVM統計出來，發現市值低的股票ROE高是沒有關係的，至於原因可能是因為，市值低的股票，大家對於該公司期望並不高，在此狀況下，高 ROE 的數值跌破大家的眼鏡，所以造成長期的後市看好。（只是推測）</p>



<p>所以買市值低的股票時，SVM傾向「ROE 盡量高一點」！</p>



<h4 id="市值中間的股票，不要買">市值中間的股票，不要買</h4>



<p>這個條件是最詭異的一個，我還是不要亂解釋好了XDD。</p>



<h3 id="回測結果">回測結果</h3>



<p>這樣的邏輯可以獲利嗎？我們可以看以下的結果，紅色為持有預測會漲的股票，綠色為持有預測會跌的股票，每季獲利的平均：<a href="https://www.finlab.tw/ROE%E6%80%8E%E9%BA%BC%E7%9C%8B-%E6%A9%9F%E5%99%A8%E5%AD%B8%E7%BF%92%E5%91%8A%E8%A8%B4%E4%BD%A0/eq2.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="375" height="242" src="http://34.96.136.135/wp-content/uploads/2020/07/eq2-4.png" alt="eq2 4" class="wp-image-804" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/eq2-4.png 375w, https://www.finlab.tw/wp-content/uploads/2020/07/eq2-4-300x194.png 300w" sizes="(max-width: 375px) 100vw, 375px" title="ROE怎麼看? 機器學習告訴你！ 31"></figure></div>



<p>也是有不錯的獲利！<br>利用 SVM 來分辨漲跌的股票，真的還滿有趣的，本文利用了兩種不同的 kernel：</p>



<ul><li>linear</li><li>polynomial<br>來進行分類，結果顯示 linear 的分類，跑出來的回測獲利比較優秀，但由這兩種不同的kernel，製作出來的模型，都可以拿來獲利。</li></ul>



<p>雖然兩個模型的闡述「相互矛盾」「有點道理、但又有點詭異」，就像是投資界眾說紛紜的理論一樣，所以以後看到相互矛盾的論點，其實不一定誰好誰壞，甚至說不定都能夠獲利，這就是股票市場的有趣之處。</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/roe%e6%80%8e%e9%ba%bc%e7%9c%8b-%e6%a9%9f%e5%99%a8%e5%ad%b8%e7%bf%92%e5%91%8a%e8%a8%b4%e4%bd%a0/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">794</post-id>	</item>
		<item>
		<title>論文導讀：利用CNN神經網路來交易ETF</title>
		<link>https://www.finlab.tw/cnn-time-series-image-conversion-approach/</link>
					<comments>https://www.finlab.tw/cnn-time-series-image-conversion-approach/#respond</comments>
		
		<dc:creator><![CDATA[FinLab - 韓承佑]]></dc:creator>
		<pubDate>Wed, 22 Jul 2020 07:05:54 +0000</pubDate>
				<category><![CDATA[AI看股票]]></category>
		<category><![CDATA[MACHINE LEARNING]]></category>
		<category><![CDATA[PYTHON]]></category>
		<category><![CDATA[機器學習]]></category>
		<category><![CDATA[選股]]></category>
		<guid isPermaLink="false">http://34.96.136.135/?p=943</guid>

					<description><![CDATA[文章導讀：機器學習用來投資一直都是非常熱門的學問，近年來深度學習模型開始受到非常多的矚目，尤其是在電腦視覺方面，所以接下來導讀的這篇文章，就是提供了一個全新的方式，將目前最火紅的 視覺神經網路CNN，用來預測股票的漲跌。]]></description>
										<content:encoded><![CDATA[
<p>文章導讀：機器學習用來投資一直都是非常熱門的學問，近年來深度學習模型開始受到非常多的矚目，尤其是在電腦視覺方面，所以接下來導讀的這篇文章，就是提供了一個全新的方式，將目前最火紅的 視覺神經網路：Convolutional Neural Network（CNN）用來預測股票的漲跌。實驗解果表示效果比一般的神經網路要好。<a href="https://www.finlab.tw/cnn-time-series-image-conversion-approach/title.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="706" src="http://34.96.136.135/wp-content/uploads/2020/07/title-1024x706.png" alt="title" class="wp-image-946" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/title-1024x706.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/title-300x207.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/title-768x530.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/title-1536x1059.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/title.png 1636w" sizes="(max-width: 1024px) 100vw, 1024px" title="論文導讀：利用CNN神經網路來交易ETF 32"></figure></div>



<p>你可能會問，以time series來說，明明神經網路可以使用 LSTM，為何要用 CNN？LSTM應該比較適合處理時間序列呀！（畢竟LSTM是拿來處理文字字串的神經網路，字串也是一種時間序列，所以通常預測股價，大家會用LSTM）。但文章中說明，目前CNN用於圖像處理比起其他的模型，被研究的更透徹，也有大量的研發，所以說不定效果更好，所以採用了 CNN 神經網路來預測股價的漲跌</p>



<p>他們用15個技術指標 X 15 天，產生出一個 15&#215;15 的影像，將這個影像丟入 CNN 神經網路中做訓練，下圖就是神經網路所「看到」的input：<a href="https://www.finlab.tw/cnn-time-series-image-conversion-approach/input.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="445" src="http://34.96.136.135/wp-content/uploads/2020/07/input-1024x445.png" alt="input" class="wp-image-948" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/input-1024x445.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/input-300x130.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/input-768x334.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/input.png 1500w" sizes="(max-width: 1024px) 100vw, 1024px" title="論文導讀：利用CNN神經網路來交易ETF 33"></figure></div>



<p>想想對於人類來說，這個影像對我們來講沒什麼意義，但是對於電腦來說，就可以拿來判斷股價的漲跌喔！還滿酷的！我只是在想為何是15&#215;15為何不將圖像變的大一點？</p>



<p>我們會將上面這些圖片稱之為features，也就是電腦用來判斷買賣的資訊，電腦用這些資訊，就可以預測交易訊號，也就是這個神經網路的label。作者提供了一個簡單的方式，使用rolling window，去找每段時間的最大值最小值，以下是大致上的程式碼，有興趣的話可以深入研究，不過我們在這邊就點到為止。<a href="https://www.finlab.tw/cnn-time-series-image-conversion-approach/label.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="740" src="http://34.96.136.135/wp-content/uploads/2020/07/label-1-1024x740.png" alt="label 1" class="wp-image-950" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/label-1-1024x740.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/label-1-300x217.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/label-1-768x555.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/label-1-1536x1111.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/label-1.png 1712w" sizes="(max-width: 1024px) 100vw, 1024px" title="論文導讀：利用CNN神經網路來交易ETF 34"></figure></div>



<p>上述的方法，會產生（-1, 0, 1）的訊號，分別代表（賣、不做動作、買），但是由上述程式碼產生出來的訊號，必然會有imbalance的問題，也就是三種class的數量不一致，所以本篇文章使用random resampling的方式，隨機取出相同數量的 label 對應到的 testcase，來避免 0 太多的問題。</p>



<p>此篇 paper 中用了美股的 ETF 和 道瓊 30 檔成分股當訓練的標的。<br>有了 feature 跟 label，很理所當然的，我們就可以開始訓練了！<br>此篇 paper 的神經網路如下：<a href="https://www.finlab.tw/cnn-time-series-image-conversion-approach/cnn.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="427" src="http://34.96.136.135/wp-content/uploads/2020/07/cnn-1-1024x427.png" alt="cnn 1" class="wp-image-952" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/cnn-1-1024x427.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/cnn-1-300x125.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/cnn-1-768x320.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/cnn-1-1536x640.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/cnn-1.png 1546w" sizes="(max-width: 1024px) 100vw, 1024px" title="論文導讀：利用CNN神經網路來交易ETF 35"></figure></div>



<ul><li>input layer (15&#215;15),</li><li>two convolutional layers (15x15x32, 15x15x64),</li><li>max pooling (7x7x64),</li><li>two dropout (0.25, 0.50),</li><li>fully connected layers (128),</li><li>output layer (3)</li></ul>



<p>上面的架構中，input就是單純的 15 x 15 的圖片，output 有3個，分別是買、賣、不做動作。<br>中間的 convolutional layers 跟 pooling<br>作者說由於training dataset不大的關係，所以神經網路不用太大，不然會造成overfitting的狀況。</p>



<p>這篇 paper 使用 walk forward 的方式來測試，好處是可以產生時間較長的回測結果，<br>以下就是他們的回測績效（其中兩檔ETF）：<a href="https://www.finlab.tw/cnn-time-series-image-conversion-approach/backtest.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="325" src="http://34.96.136.135/wp-content/uploads/2020/07/backtest-2-1024x325.png" alt="backtest 2" class="wp-image-953" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/backtest-2-1024x325.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/backtest-2-300x95.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/backtest-2-768x244.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/backtest-2-1536x487.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/backtest-2.png 1588w" sizes="(max-width: 1024px) 100vw, 1024px" title="論文導讀：利用CNN神經網路來交易ETF 36"></figure></div>



<p>而他們也有將效果跟其他的神經網路作比較，幾種常用的方法：</p>



<ul><li>CNN-TAr 作者使用的方法</li><li>BaHr 所謂的 buy and Hold 長期持有</li><li>RSIr 利用 RSI技術指標做出來的策略</li><li>SMAr 均線策略</li><li>LSTMr 神經網路策略pip</li><li>MLPr 一般神經網路策略</li></ul>



<p>下圖就是商品（每一個row）和不同策略（每一個column）所對應到的年報酬率：<a href="https://www.finlab.tw/cnn-time-series-image-conversion-approach/compare.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="385" src="http://34.96.136.135/wp-content/uploads/2020/07/compare-1-1024x385.png" alt="compare 1" class="wp-image-954" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/compare-1-1024x385.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/compare-1-300x113.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/compare-1-768x289.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/compare-1.png 1282w" sizes="(max-width: 1024px) 100vw, 1024px" title="論文導讀：利用CNN神經網路來交易ETF 37"></figure></div>



<p>可以發現這種神經網路的效果比其他的更好！在大部分的商品都有比較好的年報酬率喔～</p>



<p>更多內容都可以參考該<a href="https://www.researchgate.net/profile/Omer_Sezer/publication/324802031_Algorithmic_Financial_Trading_with_Deep_Convolutional_Neural_Networks_Time_Series_to_Image_Conversion_Approach/links/5ae4ade9a6fdcc3bea95d2fd/Algorithmic-Financial-Trading-with-Deep-Convolutional-Neural-Networks-Time-Series-to-Image-Conversion-Approach.pdf" rel="noreferrer noopener" target="_blank">論文的連結</a>喔！</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/cnn-time-series-image-conversion-approach/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">943</post-id>	</item>
		<item>
		<title>利用機器學習預測漲跌-優化方式</title>
		<link>https://www.finlab.tw/generate-labels-stop-loss-stop-profit/</link>
					<comments>https://www.finlab.tw/generate-labels-stop-loss-stop-profit/#respond</comments>
		
		<dc:creator><![CDATA[FinLab - 韓承佑]]></dc:creator>
		<pubDate>Wed, 22 Jul 2020 07:05:54 +0000</pubDate>
				<category><![CDATA[AI看股票]]></category>
		<category><![CDATA[財經PYTHON教學]]></category>
		<category><![CDATA[PYTHON]]></category>
		<category><![CDATA[機器學習]]></category>
		<category><![CDATA[程式交易]]></category>
		<guid isPermaLink="false">http://34.96.136.135/?p=956</guid>

					<description><![CDATA[這一篇文章中，我們要針對以往的labeling方式進行優化，讓訓練出來的模型，可以有更準確的預測。沒有參加課程的同學，也可以跟我們一起學習，下方的程式碼都是完全公開的！請大家自行拿取玩玩看喔！]]></description>
										<content:encoded><![CDATA[
<p>第二堂課程最近也終於走向穩定了，剛開始有一些的bug、RAM的優化上的問題，還請同學們多多擔待，我們也會持許推出新的介紹，讓大家有更多可以加強機器學習的方式，這一篇文章中，我們要針對以往的labeling方式進行優化，讓訓練出來的模型，可以有更準確的預測。</p>



<p>沒有參加課程的同學，也可以跟我們一起學習，下方的程式碼都是完全公開的！請大家自行拿取玩玩看喔！<a href="https://www.finlab.tw/generate-labels-stop-loss-stop-profit/thumbnail.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="558" src="http://34.96.136.135/wp-content/uploads/2020/07/thumbnail-11-1024x558.png" alt="thumbnail 11" class="wp-image-958" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-11-1024x558.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-11-300x164.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-11-768x419.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-11-1536x837.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-11.png 1574w" sizes="(max-width: 1024px) 100vw, 1024px" title="利用機器學習預測漲跌-優化方式 38"></figure></div>



<h1 id="機器學習-「features-和-labels」">機器學習 「features 和 labels」</h1>



<p>假如您不知道Labeling是什麼，那我們這邊還是先簡單的介紹一下supervise機器學習(監督式機器學習)：</p>



<p>這一類的機器學習模型，可以想像是一個函式 function f，我們想要計算&nbsp;<code>y = f(x)</code>，其中 x 就是 features，另外 y 就是 labels，假如我們想要預測天氣，則 x 就是 溫度 濕度 等等，而 y 就是 0 或 1 代表是否會下雨，假如我們想要預測股價，則 x 就是 技術指標、財報等等，而 y 就是股價。<br>機器學習就是產生這麼一個 function f，可以藉由 x 來推估 y，也就是&nbsp;<code>y = f(x)</code>，下方就是機器學習用來訓練的資料（x, y）的示意圖，其中 x 就是一些技術指標，而y就是買賣訊號：<a href="https://www.finlab.tw/generate-labels-stop-loss-stop-profit/fl.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="376" src="http://34.96.136.135/wp-content/uploads/2020/07/fl-1024x376.png" alt="fl" class="wp-image-959" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/fl-1024x376.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/fl-300x110.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/fl-768x282.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/fl-1536x565.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/fl.png 1676w" sizes="(max-width: 1024px) 100vw, 1024px" title="利用機器學習預測漲跌-優化方式 39"></figure></div>



<p>機器學習模型（f）大部分是一個黑盒子，也就是我們不需要知道 f 的公式是什麼<br>（也不太可能顯示出來，因為太複雜了）</p>



<p>而我們就會先給一些 x 跟 y，並且讓演算法去產生 f，<br>這個就是 supervise 機器學習模型的基本概念</p>



<p>假如我們要用機器學習來預測股票，就要先有 x 跟 y，也就是 features 跟 labels<br>假如我們想要預測股價，要怎麼樣來製作 feature 跟 labels 呢？</p>



<h1 id="製作-Features">製作 Features</h1>



<p>製作 feature 的資料，可以是一些財報、技術指標、我們課程中也有很多製作這些指標的方式，相信網路上也有很多的介紹，由於不是此篇的重點，所以我就不多說明了XD</p>



<h1 id="製作-Labels">製作 Labels</h1>



<p>製作 label 其實是非常至關重要的，假如 label 太難預測的話，模型會無法有效的訓練，以往最基本的 label 製作方式是使用 fixed time horizon 來預測 w 個時間單位後的漲跌，下圖就是 fixed time horizon 的 Labeling 方式：<a href="https://www.finlab.tw/generate-labels-stop-loss-stop-profit/fixedtimehorizon.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="415" src="http://34.96.136.135/wp-content/uploads/2020/07/fixedtimehorizon-1024x415.png" alt="fixedtimehorizon" class="wp-image-960" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/fixedtimehorizon-1024x415.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/fixedtimehorizon-300x122.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/fixedtimehorizon-768x311.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/fixedtimehorizon.png 1288w" sizes="(max-width: 1024px) 100vw, 1024px" title="利用機器學習預測漲跌-優化方式 40"></figure></div>



<p>上圖中在 p(t) 的時候，我們希望預測 p(t+w) 的股價，是比較高還是比較低<br>我們可以使用分類的方式，將股價的漲跌分成三個部分，也就是─1（跌）、0（不漲不跌）、1（漲），這樣子我們就可以讓機器學習來預測，上面圖中，我們可以發現股價比之前的高，所以把它歸類在 1 ，也就是之後會漲。</p>



<h2 id="缺點">缺點</h2>



<p>然而這種方式有一個缺點，就是當今天模型叫我們買入的時候，一買就是持有 w 個時間單位，不論股價大漲或大跌都必須繼續持有，不能停損停利，這樣就會導致風險無法控制。</p>



<p>當然我們可以在事後回測時加上停損停利，但是這樣就跟模型的初衷有違背，模型產生的label明明就是持有 w 個時間單位，沒有停損停利。</p>



<p>為了解決上述問題，[Prado 2018] Advances in Financial Machine Learning 提出了以下的新方法：</p>



<h2 id="Triple-Barrier">Triple Barrier</h2>



<p>這個方法的示意圖如下：<a href="https://www.finlab.tw/generate-labels-stop-loss-stop-profit/triplebarrier.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="335" src="http://34.96.136.135/wp-content/uploads/2020/07/triplebarrier-1-1024x335.png" alt="triplebarrier 1" class="wp-image-962" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/triplebarrier-1-1024x335.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/triplebarrier-1-300x98.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/triplebarrier-1-768x251.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/triplebarrier-1-1536x503.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/triplebarrier-1.png 1852w" sizes="(max-width: 1024px) 100vw, 1024px" title="利用機器學習預測漲跌-優化方式 41"></figure></div>



<p>乍看之下跟 fixed time horizon 有點類似，不過這個方法將分類的方式做了一些改進，上圖中，用了三種不同顏色的「柵欄」，當股價從 p(t) 開始出發，隨時間不斷延伸，一定會碰到三個柵欄中的其中一個，而這三個柵欄分別代表了不同的意義：</p>



<ul><li>1（停利）</li><li>0（持有 w 個時間單位）</li><li>─1（停損）</li></ul>



<p>如此一來，我們就可以讓機器學習來預測「包含停損停利獲利狀況」，訓練出來的模型就可以跟回測的設定相符，增加機器學習的可預測性！<br>雖然概念很好理解，但要寫成程式碼還是需要一點功力，尤其是執行速度快一點的程式碼，下面就分享如何產生此類的label。</p>



<h2 id="程式碼">程式碼</h2>



<p>首先我們可以藉由<a href="https://www.finlab.tw/Python%E6%96%B0%E6%89%8B%E6%95%99%E5%AD%B82%E5%85%A8%E7%90%83%E6%8C%87%E6%95%B8%E4%B8%80%E6%AC%A1%E6%8A%93/">股價爬蟲這篇</a>裡面介紹的程式碼，來獲得股價，</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">df = crawl_price("2354.TW")
df.Close.plot()</code></pre>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="520" src="http://34.96.136.135/wp-content/uploads/2020/07/price-1024x520.png" alt="price" class="wp-image-963" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/price-1024x520.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/price-300x152.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/price-768x390.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/price.png 1036w" sizes="(max-width: 1024px) 100vw, 1024px" title="利用機器學習預測漲跌-優化方式 42"></figure></div>



<p><a href="https://www.finlab.tw/generate-labels-stop-loss-stop-profit/price.png"></a>針對以上的程式碼，<br>假如想知道&nbsp;<code>crawl_price</code>&nbsp;的實做，可以點入<a href="https://www.finlab.tw/Python%E6%96%B0%E6%89%8B%E6%95%99%E5%AD%B82%E5%85%A8%E7%90%83%E6%8C%87%E6%95%B8%E4%B8%80%E6%AC%A1%E6%8A%93/">股價爬蟲這篇</a></p>



<p>接下來就可以來製作 labels 了！<br>在我們的機器學習影音課程中，使用的是 fixed time horizon 的方式，先來看看效果如何：</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">date = '2017'
df.Close[date].plot()
(df.Close.shift(-20) / df.Close > 1).astype(int)[date].plot(secondary_y=True)</code></pre>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="492" src="http://34.96.136.135/wp-content/uploads/2020/07/signal1-1024x492.png" alt="signal1" class="wp-image-964" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/signal1-1024x492.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/signal1-300x144.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/signal1-768x369.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/signal1.png 1094w" sizes="(max-width: 1024px) 100vw, 1024px" title="利用機器學習預測漲跌-優化方式 43"></figure></div>



<p><a href="https://www.finlab.tw/generate-labels-stop-loss-stop-profit/signal1.png"></a>上圖中藍色的為股價，對應到左邊的y軸，黃色的是訊號，對應到右邊的y軸，也就是機器學習要學的 label，其中 1 代表買入，0 代表賣出，看起來效果有些不OK，因為訊號會在短時間內上下跳動，讓我們不知道到底該買還是賣，所以接下來我們就來試試看剛剛所介紹的 triple barrier 產生出來的 label。</p>



<p>下面這段是非常珍貴的程式碼，就連 Advances in Financial Machine Learning 書中附帶的程式碼，都沒有以下的程式碼更簡潔、更完整、更有效率，假如你的 pandas 技巧不夠好的話，請直接拿去使用就可以了XD，不用太深究此 function 中的程式碼！</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">import numpy as np
import math
def triple_barrier(price, ub, lb, max_period):

    def end_price(s):
        return np.append(s[(s / s[0] > ub) | (s / s[0] &lt; lb)], s[-1])[0]/s[0]
    
    r = np.array(range(max_period))
    
    def end_time(s):
        return np.append(r[(s / s[0] > ub) | (s / s[0] &lt; lb)], max_period-1)[0]

    p = price.rolling(max_period).apply(end_price, raw=True).shift(-max_period+1)
    t = price.rolling(max_period).apply(end_time, raw=True).shift(-max_period+1)
    t = pd.Series([t.index[int(k+i)] if not math.isnan(k+i) else np.datetime64('NaT') 
                   for i, k in enumerate(t)], index=t.index).dropna()

    signal = pd.Series(0, p.index)
    signal.loc[p > ub] = 1
    signal.loc[p &lt; lb] = -1
    ret = pd.DataFrame({'triple_barrier_profit':p, 'triple_barrier_sell_time':t, 'triple_barrier_signal':signal})

    return ret

ret = triple_barrier(df.Close, 1.07, 0.97, 20)</code></pre>



<p>這個 function 的使用方法，就是將</p>



<ul><li>時間序列（程式碼中的<code>df.Close</code>）</li><li>停利(程式碼中<code>1.07</code>是指7％停利）</li><li>停損(程式碼中<code>0.97</code>是指3％停損）</li><li>最大持有時間（20天）</li></ul>



<p>分別丟入&nbsp;<code>triple_barrier</code>&nbsp;函式當中，就可以計算出以下的&nbsp;<code>Dataframe</code></p>



<pre class="wp-block-code"><code class="">ret.head()</code></pre>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="295" src="http://34.96.136.135/wp-content/uploads/2020/07/result-3-1024x295.png" alt="result 3" class="wp-image-965" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/result-3-1024x295.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/result-3-300x86.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/result-3-768x221.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/result-3.png 1422w" sizes="(max-width: 1024px) 100vw, 1024px" title="利用機器學習預測漲跌-優化方式 44"></figure></div>



<p><a href="https://www.finlab.tw/generate-labels-stop-loss-stop-profit/result.png"></a>上圖中有三條序列，其中&nbsp;<code>index</code>&nbsp;是日期，另外三條時間序列分別是：</p>



<ul><li>triple_barrier_profit 當天買入，直到停損停利後，未來的獲利狀況</li><li>triple_barrier_sell_time 當天買入，未來會持有的時間</li><li>triple_barrier_signal 當天買入，未來觸發的是停損停利</li></ul>



<p>我們可以將&nbsp;<code>triple_barrier_signal</code>&nbsp;訊號跟股價一起畫出來比較一下：</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">date = '2017'
df.Close[date].plot()
ret.triple_barrier_signal[date].plot(secondary_y=True)</code></pre>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="499" src="http://34.96.136.135/wp-content/uploads/2020/07/signal2-1024x499.png" alt="signal2" class="wp-image-966" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/signal2-1024x499.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/signal2-300x146.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/signal2-768x374.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/signal2.png 1096w" sizes="(max-width: 1024px) 100vw, 1024px" title="利用機器學習預測漲跌-優化方式 45"></figure></div>



<p><a href="https://www.finlab.tw/generate-labels-stop-loss-stop-profit/signal2.png"></a>label 的訊號變得比較乾淨，試試看訓練出更好的模型吧！<br>可以使用&nbsp;<a rel="noreferrer noopener" href="https://colab.research.google.com/drive/1D_UuxCc7zkfv_FkHig29SXTxwlxhle6u" target="_blank">google colab 線上編輯此代碼</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/generate-labels-stop-loss-stop-profit/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">956</post-id>	</item>
		<item>
		<title>論文導讀：利用MI-LSTM預測股價</title>
		<link>https://www.finlab.tw/%e5%88%a9%e7%94%a8mi-lstm%e9%a0%90%e6%b8%ac%e8%82%a1%e5%83%b9/</link>
					<comments>https://www.finlab.tw/%e5%88%a9%e7%94%a8mi-lstm%e9%a0%90%e6%b8%ac%e8%82%a1%e5%83%b9/#respond</comments>
		
		<dc:creator><![CDATA[FinLab - 韓承佑]]></dc:creator>
		<pubDate>Wed, 22 Jul 2020 07:05:39 +0000</pubDate>
				<category><![CDATA[AI看股票]]></category>
		<category><![CDATA[MACHINE LEARNING]]></category>
		<category><![CDATA[機器學習]]></category>
		<category><![CDATA[程式交易]]></category>
		<category><![CDATA[量化投資]]></category>
		<guid isPermaLink="false">http://34.96.136.135/?p=834</guid>

					<description><![CDATA[這篇文章是2018年剛發表的paper，算是非常新但是滿有趣的方法，針對一般的股票建構一個預測隔日價格的LSTM模型，以下就是他的方法思路。]]></description>
										<content:encoded><![CDATA[
<p>這篇文章是2018年剛發表的paper，算是非常新但是滿有趣的方法，針對一般的股票建構一個預測隔日價格的LSTM模型，以下就是他的方法思路。</p>



<h3 id="動機">動機</h3>



<p>股價預測一直都是非常熱門但具有挑戰性的機器學習題目，通常這類的文章不乏是使用各種的資訊，例如股價、技術指標、公司獲利、新聞資訊，並將這些資料餵給一些模型，例如 linear regression, SVM, 或是 NN 來預測未來股價。雖然這些方法被證實是可以使用的，但是預測能力不佳。因為當中有些資訊不但對於預測未來股價沒有幫助，反而會擾亂預測的準確度。</p>



<h3 id="此篇文章的貢獻">此篇文章的貢獻</h3>



<p>這篇文章提出了 multi-input LSTM model，來使用額外的神經網路額外架構，從低相關連的資訊找出有價值的，並且濾掉不必要的雜訊。並且利用了額外的LSTM邏輯來建構「mainstream」的結構，並用「mainstream」所計算出來的資訊，來遺忘或記憶有用的資訊（gates）。此架構比原本的LSTM效果要更好。</p>



<h3 id="MI-LSTM">MI-LSTM</h3>



<p>這是個特別針對金融股價預測所研發的架構，其原理是先找出想要預測的timeseries，並且找出N條高度正相關的timeseries（以股票而言，就可能是同類型的公司股價），還有N條最負相關的timeseries當作是此預測模型的輸入資料。有了這些資料後，下圖就是MILSTM的整體架構，其中 <strong>Y</strong>&nbsp;是欲預測的股票的歷史股價，而&nbsp;<img loading="lazy" width="13" height="16" src="" alt="" title="論文導讀：利用MI-LSTM預測股價 46">​​\bold{X}_n^i<strong>X</strong>​<em>n</em>​<em>i</em> ​​就是第 i 個高度正相關的timeseries，而\bold{X}_n^i<strong>X</strong>​<em>n</em>​<em>i</em>​​&nbsp;就是高度負相關的 timeseries。最後&nbsp;<strong><strong>X</strong></strong><em><strong><em><em><sub>i</sub></em></em></strong></em>&nbsp;是大盤的 timeseries。<a href="https://www.finlab.tw/%E5%88%A9%E7%94%A8MI-LSTM%E9%A0%90%E6%B8%AC%E8%82%A1%E5%83%B9/structure.jpg"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="905" height="395" src="http://34.96.136.135/wp-content/uploads/2020/07/structure.jpg" alt="structure" class="wp-image-835" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/structure.jpg 905w, https://www.finlab.tw/wp-content/uploads/2020/07/structure-300x131.jpg 300w, https://www.finlab.tw/wp-content/uploads/2020/07/structure-768x335.jpg 768w" sizes="(max-width: 905px) 100vw, 905px" title="論文導讀：利用MI-LSTM預測股價 47"></figure></div>



<p>上圖從左到右的解說如下</p>



<ul><li>LSTM：此圖中的最左邊部分，就是簡單的LSTM計算而已，假如想要知道什麼是LSTM，可以參考<a rel="noreferrer noopener" href="https://colah.github.io/posts/2015-08-Understanding-LSTMs/" target="_blank">這篇關於LSTM的詳細解說</a>。</li><li>Average：往右，可以看到高度正負相關的timeseries的LSTM，額外經過平均的運算，至於為什麼要這樣做，相信是效果比較好的緣故，當然實做時也可以拿掉、或是使用不一樣的的計算方式。</li><li>Multi-Input LSTM：而比較有趣的地方，在於其中紅色的Multi-Input LSTM這個部分，在於它像是一個變種的LSTM架構，多了很多的 gate（請參考LSTM文章來瞭解什麼是「gate」）。此MILSTM可以額外展開如下圖，可以發現跟一般的LSTM長的差不多，但是多了有顏色的三條資訊流，並且此三條資訊流都有額外的gates來篩選要儲存的資訊。</li></ul>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="493" src="http://34.96.136.135/wp-content/uploads/2020/07/MIstructure-1024x493.jpg" alt="MIstructure" class="wp-image-836" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/MIstructure-1024x493.jpg 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/MIstructure-300x144.jpg 300w, https://www.finlab.tw/wp-content/uploads/2020/07/MIstructure-768x370.jpg 768w, https://www.finlab.tw/wp-content/uploads/2020/07/MIstructure.jpg 1047w" sizes="(max-width: 1024px) 100vw, 1024px" title="論文導讀：利用MI-LSTM預測股價 48"></figure></div>



<ul><li><a href="https://www.finlab.tw/%E5%88%A9%E7%94%A8MI-LSTM%E9%A0%90%E6%B8%AC%E8%82%A1%E5%83%B9/MIstructure.jpg"></a>接下來是Attention Layer，其實跟LSTM原本的Attention是非常類似的，還是非常建議現瞭解<a rel="noreferrer noopener" href="https://colah.github.io/posts/2015-08-Understanding-LSTMs/" target="_blank">LSTM是什麼</a>，不然到這邊你應該已經頭很昏了XD。</li></ul>



<p>實驗結果</p>



<p>這篇文章使用了300檔股票的歷史股價進行訓練，單一一檔的股票歷史資料一定不足，但是假如300檔串在一起，則樣本數應該就足夠了，既然都已經發了期刊，當然實驗結果要比別人好，所以以下是實驗的結果，當中的MSE就是誤差（mean square error）的意思：<a href="https://www.finlab.tw/%E5%88%A9%E7%94%A8MI-LSTM%E9%A0%90%E6%B8%AC%E8%82%A1%E5%83%B9/table.jpg"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1023" height="287" src="http://34.96.136.135/wp-content/uploads/2020/07/table.jpg" alt="table" class="wp-image-837" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/table.jpg 1023w, https://www.finlab.tw/wp-content/uploads/2020/07/table-300x84.jpg 300w, https://www.finlab.tw/wp-content/uploads/2020/07/table-768x215.jpg 768w" sizes="(max-width: 1023px) 100vw, 1023px" title="論文導讀：利用MI-LSTM預測股價 49"></figure></div>



<p>可以發現MI-LSTM獲得了最小的實驗誤差，相比起其它的model效果更好，而其它的model屬於LSTM的變形，這邊就先不介紹了。可以參考這篇LSTM文章。接下來，他們進一步分析了MI-LSTM中，每一類input的效果，種共有以下四類：</p>



<ol><li>Mainstream：欲預測的股票其歷史股價</li><li>Positive：高度正相關的一群股票</li><li>Negative：高度付相關的一群股票</li><li>Index：大盤</li></ol>



<p>下圖就是這四種不同的資訊流在神經網路中，通過softmax的時候的權重隨著訓練次數的變化：</p>



<p>最後可以發現Mainstream跟Index的資訊是最有效的，大盤對於股價的影響是非常大的，與投資時的狀況符合一致，大盤漲跌對於個股的影響很大。另外可以發現Positive跟Negative的權重被降低了，代表雖然這些資訊有很價值，但是當中也有很多的雜訊，所以權重被有效的分配。</p>



<h3 id="選股策略">選股策略</h3>



<p>這篇文章提出了一種選股的策略，對於所有股票，都判斷明日的漲跌，並且每日選出漲跌最佳的20檔股票，不考慮手續費，可以得到以下每段時間的歷史報酬：<a href="https://www.finlab.tw/%E5%88%A9%E7%94%A8MI-LSTM%E9%A0%90%E6%B8%AC%E8%82%A1%E5%83%B9/table2.jpg"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="981" height="175" src="http://34.96.136.135/wp-content/uploads/2020/07/table2.jpg" alt="table2" class="wp-image-838" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/table2.jpg 981w, https://www.finlab.tw/wp-content/uploads/2020/07/table2-300x54.jpg 300w, https://www.finlab.tw/wp-content/uploads/2020/07/table2-768x137.jpg 768w" sizes="(max-width: 981px) 100vw, 981px" title="論文導讀：利用MI-LSTM預測股價 50"></figure></div>



<p>可以看到MI-LSTM的效果比傳統的LSTM和大盤還要好，當然考慮了手續費後效果可能會打很多折扣，甚至是虧損。要是我的話，會想辦法增加預測時間的長度（但預測難度也可能會增加），從每天變成每個禮拜，這樣手續費可能比較不那麼誇張多。但我猜他們可能也有做過類似的實驗，但沒有成功？或是他們覺得這樣已經很好了？</p>



<p>實做上建議使用pytorch或是tensorflow會比較簡單，這篇文章只是簡單的介紹其架構，然而要寫程式的話，還是利用paper中的數學公式，會比直接看架構圖更好理解和實做，會比較好喔！</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/%e5%88%a9%e7%94%a8mi-lstm%e9%a0%90%e6%b8%ac%e8%82%a1%e5%83%b9/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">834</post-id>	</item>
		<item>
		<title>用Machine learning 學習看技術指標</title>
		<link>https://www.finlab.tw/machine-learning%ef%bc%9a%e4%bd%bf%e7%94%a8%e6%8a%80%e8%a1%93%e6%8c%87%e6%a8%99%e9%a0%90%e6%b8%ac%e5%a4%a7%e7%9b%a4/</link>
					<comments>https://www.finlab.tw/machine-learning%ef%bc%9a%e4%bd%bf%e7%94%a8%e6%8a%80%e8%a1%93%e6%8c%87%e6%a8%99%e9%a0%90%e6%b8%ac%e5%a4%a7%e7%9b%a4/#respond</comments>
		
		<dc:creator><![CDATA[FinLab - 韓承佑]]></dc:creator>
		<pubDate>Wed, 22 Jul 2020 07:05:39 +0000</pubDate>
				<category><![CDATA[AI看股票]]></category>
		<category><![CDATA[MACHINE LEARNING]]></category>
		<category><![CDATA[機器學習]]></category>
		<category><![CDATA[程式交易]]></category>
		<guid isPermaLink="false">http://34.96.136.135/?p=788</guid>

					<description><![CDATA[這篇文章是印度指數預測，2015年發表的就能有191個citation，算是很有名的paper之一，全文特點是只使用了技術指標，來預測大盤每天漲跌，提出了一個有效的優化方式。]]></description>
										<content:encoded><![CDATA[
<p><a href="https://www.sciencedirect.com/science/article/pii/S0957417414004473" rel="noreferrer noopener" target="_blank">這篇文章是印度指數預測</a>，2015年發表的就能有191個citation，算是很有名的paper之一，全文特點是只使用了技術指標，來預測大盤每天漲跌，提出了一個有效的優化方式。<a href="https://www.finlab.tw/Machine-learning%EF%BC%9A%E4%BD%BF%E7%94%A8%E6%8A%80%E8%A1%93%E6%8C%87%E6%A8%99%E9%A0%90%E6%B8%AC%E5%A4%A7%E7%9B%A4/thumbnail.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="992" height="640" src="http://34.96.136.135/wp-content/uploads/2020/07/thumbnail-7.png" alt="thumbnail 7" class="wp-image-789" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-7.png 992w, https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-7-300x194.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-7-768x495.png 768w" sizes="(max-width: 992px) 100vw, 992px" title="用Machine learning 學習看技術指標 51"></figure></div>



<p>這篇paper的作者非常的認真，總共訓練四種不同的模型：Artificial Neural Network (ANN), support vector machine (SVM), random forest (RF) 和 Naive-Bayes (NB)。</p>



<p>這邊假如看不懂沒有關係，可以想像「模型」就是「電腦的大腦」，負責學習每種指標怎麼對應到未來的漲跌。之後有空再來慢慢介紹這些不同的「大腦」背後的數學原理。</p>



<p>此論文主要建構製作兩組traning data：</p>



<ul><li>包含十種技術指標</li><li>為這十種技術指標的看漲看跌<br>前者為 float （被normalize成-1～1）<br>而後者為 boolean （也就是只有輸入True和False）。</li></ul>



<p>究竟這些排列組合會迸出什麼樣的火花呢？</p>



<h3 id="選擇模型">選擇模型</h3>



<p>研究發現Random Forest的表現是最好的，而ANN差了一點，<br>這是滿正常的，畢竟data set還是太小，神經網路很難訓練的非常好。<br>至於傳統的NB則是最差的。</p>



<p>其實也可以考慮一下LSTM，說不定效果也不錯？<br>（但因為LSTM還是基於ANN，所以有可能遇到traning set太小的問題）</p>



<h3 id="選擇traning-data">選擇traning data</h3>



<p>如同上面所述，此篇論文總共先用了十種技術指標，以下是這十種常見的指標，為了讓文章不會太冗長，我就不一一解釋了，之後有空再來介紹每種指標的用法。<a href="https://www.finlab.tw/Machine-learning%EF%BC%9A%E4%BD%BF%E7%94%A8%E6%8A%80%E8%A1%93%E6%8C%87%E6%A8%99%E9%A0%90%E6%B8%AC%E5%A4%A7%E7%9B%A4/p1.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="408" src="http://34.96.136.135/wp-content/uploads/2020/07/p1-1024x408.png" alt="p1" class="wp-image-790" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/p1-1024x408.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/p1-300x120.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/p1-768x306.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/p1-1536x612.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/p1.png 1906w" sizes="(max-width: 1024px) 100vw, 1024px" title="用Machine learning 學習看技術指標 52"></figure></div>



<p>這篇paper會將這些技術指標的數值，每一項做normalize在-1～1之間，這樣的優化主要是為了ANN和SVM。以下是這個model的架構：</p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="549" src="http://34.96.136.135/wp-content/uploads/2020/07/p2-1024x549.png" alt="p2" class="wp-image-791" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/p2-1024x549.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/p2-300x161.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/p2-768x412.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/p2.png 1320w" sizes="(max-width: 1024px) 100vw, 1024px" title="用Machine learning 學習看技術指標 53"></figure></div>



<p>另外，全文的特點是使用了提出了 「Trend Deterministic Data Preparation」，看起來非常的厲害，簡單講就是將這些指標的數值究竟是「看漲」還是「看跌」拿來訓練，而不是訓練指標本身的數值。</p>



<p>例如均線好了，與其拿均線的值來訓練，不如看「股價跟均線的關係」，假如股價在均線之上，就是「看漲」（True），反之則「看跌」（False）。其他指標都能以此類推！</p>



<p>以下就是新增了一層資料的修改的架構：</p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="512" src="http://34.96.136.135/wp-content/uploads/2020/07/p3-1024x512.png" alt="p3" class="wp-image-792" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/p3-1024x512.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/p3-300x150.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/p3-768x384.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/p3.png 1500w" sizes="(max-width: 1024px) 100vw, 1024px" title="用Machine learning 學習看技術指標 54"></figure></div>



<p>最後發現使用了「Trend Deterministic Data Preparation」<br>效果好很多！</p>



<h3 id="結論">結論</h3>



<p>這篇文章中，可以大概知道每一種model對於技術性指標的數據的效果如何。並且了解了用「Trend Deterministic Data Preparation」來進行優化。經過了非常多參數的比對，發現使用RF model做出來的策略效果最好。然而這只限於頻率為「天」的股價，假如頻率不是「天」，則可能會不一樣～。</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/machine-learning%ef%bc%9a%e4%bd%bf%e7%94%a8%e6%8a%80%e8%a1%93%e6%8c%87%e6%a8%99%e9%a0%90%e6%b8%ac%e5%a4%a7%e7%9b%a4/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">788</post-id>	</item>
		<item>
		<title>如何用machine learning學習 總體經濟？</title>
		<link>https://www.finlab.tw/%e6%a9%9f%e5%99%a8%e5%ad%b8%e7%bf%92-%e7%b8%bd%e9%ab%94%e7%b6%93%e6%bf%9f/</link>
					<comments>https://www.finlab.tw/%e6%a9%9f%e5%99%a8%e5%ad%b8%e7%bf%92-%e7%b8%bd%e9%ab%94%e7%b6%93%e6%bf%9f/#respond</comments>
		
		<dc:creator><![CDATA[FinLab - 韓承佑]]></dc:creator>
		<pubDate>Wed, 22 Jul 2020 07:05:38 +0000</pubDate>
				<category><![CDATA[AI看股票]]></category>
		<category><![CDATA[MACHINE LEARNING]]></category>
		<category><![CDATA[機器學習]]></category>
		<category><![CDATA[程式交易]]></category>
		<category><![CDATA[量化投資]]></category>
		<guid isPermaLink="false">http://34.96.136.135/?p=779</guid>

					<description><![CDATA[今天這篇paper是介紹總體經濟，現在全球的經濟是連動的，例如中美貿易大戰影響到全球股價，金價油價對於美國股市也有很大的影響，今天這篇paper就是要來研究不同的指數，對於NASDAQ指數的影響。]]></description>
										<content:encoded><![CDATA[
<p>今天<a href="https://pdfs.semanticscholar.org/b68e/8d2f4d2c709bb5919b82effcb6a7bbd3db37.pdf" rel="noreferrer noopener" target="_blank">這篇paper</a>是介紹總體經濟，現在全球的經濟是連動的，例如中美貿易大戰影響到全球股價，金價油價對於美國股市也有很大的影響，今天這篇paper就是要來研究不同的指數，對於NASDAQ指數的影響。</p>



<p>這篇文章利用美股開盤前的所有重要指數，例如油價、貴金屬價格、以及全球股市的對於美股的影響，既然全球市場是連動的，那這其中必定有一些關聯，下圖就是這篇paper所使用的重要指數：<a href="https://www.finlab.tw/%E6%A9%9F%E5%99%A8%E5%AD%B8%E7%BF%92-%E7%B8%BD%E9%AB%94%E7%B6%93%E6%BF%9F/data.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="592" src="http://34.96.136.135/wp-content/uploads/2020/07/data-1-1024x592.png" alt="data 1" class="wp-image-780" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/data-1-1024x592.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/data-1-300x173.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/data-1-768x444.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/data-1.png 1522w" sizes="(max-width: 1024px) 100vw, 1024px" title="如何用machine learning學習 總體經濟？ 55"></figure></div>



<h3 id="建構features">建構features</h3>



<p>這篇文章想要找出股價的趨勢，而不是絕對數值，所以其features除了股價外，也有一段時間股價的變化，這邊先叫做window size w，並且對於價格的變化進行normalize。</p>



<h3 id="分析features">分析features</h3>



<p>我覺得本文值得讚許的地方在於有提供一些簡單的方法做features的分析，可以由這些方法知道哪些features對於預測是非常有幫助的！</p>



<p>論文中使用了cross correlation來分析各種不同商品的價格對於NASDAQ影響。要說明cross correlation，就要先從correlation說起，correlation是兩種不同的數據，其相關性的係數。correlation介於-1到1之間，分別代表這兩種時間序列之間的關聯性：</p>



<ul><li>correlation = -1：代表數據完全負相關，也就是A漲B就跌的概念</li><li>correlation = 0：代表數據之間沒什麼關聯，也就是A漲跌跟B漲跌完全沒關係</li><li>correlation = +1：代表數據之間是正相關，也就是AB同漲同跌的關係</li></ul>



<p>那「cross」又是什麼意思呢？就是將兩組時間序列的時間錯開，差N天，並且觀察其correlation。</p>



<p>下圖就是所有的商品對於NASDAQ的cross correlation 分析，X軸就是差N天的N，而Y軸就是correlation，可以看到，在X = 0 時，NASDAQ跟NASDAQ的相關性是1，代表NASDAQ與自己的指數完全正相關，而很多商品都會在N = 0時有正相關性！<a href="https://www.finlab.tw/%E6%A9%9F%E5%99%A8%E5%AD%B8%E7%BF%92-%E7%B8%BD%E9%AB%94%E7%B6%93%E6%BF%9F/crosscorrelation.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="791" src="http://34.96.136.135/wp-content/uploads/2020/07/crosscorrelation-1024x791.png" alt="crosscorrelation" class="wp-image-781" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/crosscorrelation-1024x791.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/crosscorrelation-300x232.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/crosscorrelation-768x593.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/crosscorrelation.png 1108w" sizes="(max-width: 1024px) 100vw, 1024px" title="如何用machine learning學習 總體經濟？ 56"></figure></div>



<p>所以我們使用N = 0來預測NASDAQ的股價會是最好的，但是N = 0的資料是沒有辦法使用的，因為你不能在當天的開盤就知道NASDAQ的收盤價，這樣就代表用到未來數據了。</p>



<p>所以我們只能退而求其次，用 N &lt; 0 的資料，也就是前N天的資料，我們可以發現N = -1的地方有一點小突起，代表某些資料對於NASDAQ的correlation也是很高的，可以拿來利用！</p>



<p>唯一想吐槽的是這張圖很多顏色都重複，所以根本看不太清楚是哪些商品，拿來預測NASDAQ比較準。</p>



<h3 id="三個維度的-cross-correlation">三個維度的 cross-correlation</h3>



<p>另外，這篇paper也提供了不同股價區間差w對於漲跌的correlation：<a href="https://www.finlab.tw/%E6%A9%9F%E5%99%A8%E5%AD%B8%E7%BF%92-%E7%B8%BD%E9%AB%94%E7%B6%93%E6%BF%9F/crosscorrelation3d.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="745" src="http://34.96.136.135/wp-content/uploads/2020/07/crosscorrelation3d-1024x745.png" alt="crosscorrelation3d" class="wp-image-782" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/crosscorrelation3d-1024x745.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/crosscorrelation3d-300x218.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/crosscorrelation3d-768x559.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/crosscorrelation3d-1536x1118.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/crosscorrelation3d.png 1800w" sizes="(max-width: 1024px) 100vw, 1024px" title="如何用machine learning學習 總體經濟？ 57"></figure></div>



<p>可以發現商品價格與NASDAQ股價之間是有一定的關係的，假如商品之間彼此沒有關聯，這張圖就不會呈現三角形的山丘狀，而是會看起來像是隨機的樣子。</p>



<p>上面這張圖說明了一件事情，股價變化越長時間來觀察(w 越長)，NASDQL跟許多商品的前一天的correlation是越高的，可以藉由提高精準度！</p>



<p>藉由上述的兩個實驗，我們知道股價變化量的重要性，重點不是股價本身，而是股價的漲跌幅度才有辦法更好的預測股價～</p>



<p>除此之外，作者想要進一步知道哪些時間序列對於NASDQL是重要的，所以進行了一個簡單的預測實驗</p>



<h3 id="預測明天的價格">預測明天的價格</h3>



<p>作者也利用每一個單一序列當作單一feature，來預測隔天的漲跌，發現利用DAX這個時間序列來預估NASDQL會得到最好的結果：<a href="https://www.finlab.tw/%E6%A9%9F%E5%99%A8%E5%AD%B8%E7%BF%92-%E7%B8%BD%E9%AB%94%E7%B6%93%E6%BF%9F/importance.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="462" src="http://34.96.136.135/wp-content/uploads/2020/07/importance-1024x462.png" alt="importance" class="wp-image-783" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/importance-1024x462.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/importance-300x135.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/importance-768x346.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/importance.png 1056w" sizes="(max-width: 1024px) 100vw, 1024px" title="如何用machine learning學習 總體經濟？ 58"></figure></div>



<p>作者並沒有說這邊的model是哪一種，我猜應該是SVM，因為feature_size很小。<br>這樣我們就可以找到比較重要跟不重要的時間序列，之所以要這樣是因為此篇paper有用SVM當作model，而SVM比較適用於小feature_size的traning set。</p>



<h3 id="預測N天後的價格">預測N天後的價格</h3>



<p>除了每天的價格外，此paper也研究K天後的價格漲跌，發現K越大，則預測的能力越好，下圖中 K 為 x 軸<a href="https://www.finlab.tw/%E6%A9%9F%E5%99%A8%E5%AD%B8%E7%BF%92-%E7%B8%BD%E9%AB%94%E7%B6%93%E6%BF%9F/multiple_day.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="511" src="http://34.96.136.135/wp-content/uploads/2020/07/multiple_day-1024x511.png" alt="multiple day" class="wp-image-784" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/multiple_day-1024x511.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/multiple_day-300x150.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/multiple_day-768x383.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/multiple_day.png 1126w" sizes="(max-width: 1024px) 100vw, 1024px" title="如何用machine learning學習 總體經濟？ 59"></figure></div>



<h3 id="測試-w-的大小">測試 w 的大小</h3>



<p>接下來，此paper也測試了不同的 w 對於訓練的成效：&nbsp;<a href="https://en.wikipedia.org/wiki/F1_score" rel="noreferrer noopener" target="_blank">f1 score</a>&nbsp;的影響，f1 score是precision跟recall的綜合分數，其中：</p>



<ul><li>precision 是所有 model 顯示為 true，而真正為 true 的比例</li><li>recall 是所有真正為 true 的資料，被 model 標示為 true 的比例</li></ul>



<p>f1 score 就是 precision 和 recall 的 harmonic mean。<a href="https://en.wikipedia.org/wiki/Harmonic_mean#Harmonic_mean_of_two_numbers" rel="noreferrer noopener" target="_blank">harmonic mean</a>同時也被用在電阻的並聯計算上，你可以想像電阻並聯時，假如任何一個電阻太小，電流就會傾向從那裡通過，造成等效電阻很小。同理，你可以想像有一顆電阻叫做precision，另一顆叫做recall，任何一方太小，都會導致f1 score 變得很小。於是 f1 score 就是同時可以兼具 recall 和 accuracy 的一個優化指標。<a href="https://www.finlab.tw/%E6%A9%9F%E5%99%A8%E5%AD%B8%E7%BF%92-%E7%B8%BD%E9%AB%94%E7%B6%93%E6%BF%9F/w.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="394" src="http://34.96.136.135/wp-content/uploads/2020/07/w-1024x394.png" alt="w" class="wp-image-785" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/w-1024x394.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/w-300x115.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/w-768x295.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/w-1536x591.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/w-2048x788.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="如何用machine learning學習 總體經濟？ 60"></figure></div>



<p>上圖中的兩條線分別是 positive 和 negative 的 f1 score。當 w 在 0 或是 50 時，f1 score 相對來說比較好。</p>



<p>以上就是分析 w、K、等參數怎麼設定比較好的一些分析，當我們得到這些參數，並且建構出預測漲跌的model後，就可以將model產生的結果拿來回測</p>



<h3 id="回測績效">回測績效</h3>



<p>這邊總共用了三種方法來回測：</p>



<ol><li>假如預測會漲，就持續於整段回測週期持有股票</li><li>當預測會漲機率上升時，持有股票，不然則賣出</li><li>當預測會漲時，持有，反之則賣出</li></ol>



<p>以下是回測的結果：<a href="https://www.finlab.tw/%E6%A9%9F%E5%99%A8%E5%AD%B8%E7%BF%92-%E7%B8%BD%E9%AB%94%E7%B6%93%E6%BF%9F/backtest.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="664" src="http://34.96.136.135/wp-content/uploads/2020/07/backtest-1-1024x664.png" alt="backtest 1" class="wp-image-786" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/backtest-1-1024x664.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/backtest-1-300x195.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/backtest-1-768x498.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/backtest-1.png 1042w" sizes="(max-width: 1024px) 100vw, 1024px" title="如何用machine learning學習 總體經濟？ 61"></figure></div>



<p>可以發現利用第三種方式，回測的績效比較好，這邊跟我自己做出來的結論是差不多的。</p>



<h3 id="總結">總結</h3>



<p>今天學到的一些知識：</p>



<ol><li>用cross-correlation來分析features</li><li>利用SVM來測驗單個features是否有辦法預測漲跌，進而分析feature的好壞</li><li>使用移動窗格來找出最佳的f1_score</li></ol>



<p>這篇paper利用ML的方式，找出世界上重要的商品價格之間的關聯，並且也有使用SVM或是MART來預測NASDAQ指數的漲跌，個人覺得滿有趣的。經總就應該這樣作研究！</p>



<p>美中不足的是應該可以歸納出一些現象，輔助一般不會程式的投資人，這樣會更好！</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/%e6%a9%9f%e5%99%a8%e5%ad%b8%e7%bf%92-%e7%b8%bd%e9%ab%94%e7%b6%93%e6%bf%9f/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">779</post-id>	</item>
	</channel>
</rss>
