<?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/%E5%8F%B0%E7%A9%8D%E9%9B%BB/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.finlab.tw</link>
	<description>深入淺出的量化投資，讓你在在茫茫股海中，找到專屬於自己的投資方法</description>
	<lastBuildDate>Sun, 02 Oct 2022 11:29:08 +0000</lastBuildDate>
	<language>zh-TW</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.0.9</generator>

<image>
	<url>https://www.finlab.tw/wp-content/uploads/2020/07/favicon.png</url>
	<title>台積電 &#8211; FinLab</title>
	<link>https://www.finlab.tw</link>
	<width>32</width>
	<height>32</height>
</image> 
<site xmlns="com-wordpress:feed-additions:1">179699571</site>	<item>
		<title>護國神山抄底策略</title>
		<link>https://www.finlab.tw/2330_bband_rebound/</link>
					<comments>https://www.finlab.tw/2330_bband_rebound/#respond</comments>
		
		<dc:creator><![CDATA[Ben]]></dc:creator>
		<pubDate>Wed, 09 Mar 2022 03:11:25 +0000</pubDate>
				<category><![CDATA[技術面]]></category>
		<category><![CDATA[VIP文章]]></category>
		<category><![CDATA[股票策略]]></category>
		<category><![CDATA[財經PYTHON教學]]></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=3474</guid>

					<description><![CDATA[俄烏戰地風雲讓資本市場遍地烽火，股市逆風吹，世局紛擾，通膨被火上加油。今年以來多數市場指數都呈現下跌，還有再漲 [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p class="has-normal-font-size">俄烏戰地風雲讓資本市場遍地烽火，股市逆風吹，世局紛擾，通膨被火上加油。今年以來多數市場指數都呈現下跌，還有再漲的多是原物料大國如巴西、阿根廷、印尼&#8230;俄羅斯封盤墊底，歐元區國家即將跌入20%熊市，美國科技股也被k了-15%，台股在去年高基期下的跌幅還算輕，表現贏過亞股裡的中港日韓。</p>



<p class="has-normal-font-size">在這樣淒風苦雨的環境下，也是左側交易者或是抄底搶反彈投機客大展身手的時候！有沒有什麼標的平常貴鬆鬆買不下手，現在難得打折了？<br></p>



<figure class="wp-block-image size-large"><img width="1024" height="244" src="https://www.finlab.tw/wp-content/uploads/2022/03/newplot-19-1024x244.png" alt="newplot 19" class="wp-image-3475" srcset="https://www.finlab.tw/wp-content/uploads/2022/03/newplot-19-1024x244.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/03/newplot-19-300x72.png 300w, https://www.finlab.tw/wp-content/uploads/2022/03/newplot-19-768x183.png 768w, https://www.finlab.tw/wp-content/uploads/2022/03/newplot-19-1536x366.png 1536w, https://www.finlab.tw/wp-content/uploads/2022/03/newplot-19.png 1678w" sizes="(max-width: 1024px) 100vw, 1024px" title="護國神山抄底策略 1"><figcaption>2022主要股市表現回顧</figcaption></figure>



<h2><meta charset="utf-8">護國神山抄底抄起來？</h2>



<p class="has-normal-font-size">台積電這類法人機構影響力大的標的，擁有高效率市場特性，很難從已知的基本面佔到優勢，還記得1月初<a href="https://tw.stock.yahoo.com/news/%E5%8D%8A%E5%B0%8E%E9%AB%94-%E5%8F%B0%E7%A9%8D1%E6%9C%8813%E6%97%A5%E6%B3%95%E8%AA%AA-q1%E7%87%9F%E6%94%B6%E6%88%B0%E6%96%B0%E9%AB%98-084509130.html" class="rank-math-link" target="_blank" rel="noopener">台積電法說</a>會前後，當時外資紛紛樂觀調高目標價到千元，股價攻高到680波段高點，若當時見到法說利多攻進去，現在就面臨套牢的窘況，雖然台積電的基本面仍很好。</p>



<p class="has-normal-font-size"><meta charset="utf-8">高效率市場特性的標的最好的買點就是<meta charset="utf-8">大環境全面崩壞、投資人紛紛逃出的時候。近日戰爭與通膨剛堅強的護國神山也扛不住了，一週被外資狂賣30萬張，跌破600元，外資報告跟著調低目標價 (仍有800多元)，而本土投顧、法人則喊600元以下台積電是<a href="https://udn.com/news/story/12806/6147175" class="rank-math-link" target="_blank" rel="noopener">天上掉下來的禮物</a>，趕快買就對了。<br>如今台積電已從高點回檔18%，今天看到新聞標題:「<a href="https://udn.com/news/story/12806/6147175" class="rank-math-link" target="_blank" rel="noopener">台積電大跌狂撿甜甜價，他一路抄底4次「綠到發慌」</a>。」</p>



<blockquote class="wp-block-quote"><p>你也抄底抄到手軟了嗎？若買在600，短短幾天賬損也到6%，若你攤平前沒有做過數據分析，那你很難先對「<meta charset="utf-8">抄到沒錢時，股價繼續下跌。」有所準備，只是憑直覺去猜。</p></blockquote>



<h2>布林通道逆勢策略</h2>



<p class="has-normal-font-size">抄底就是所謂的逆勢策略，能不能用量化的方式實測呢？<br>布林通道是最廣為人知的逆勢方法，原理是運用均線和標準差，大部分 K 線都涵蓋在 d日 MA 上下 n 個標準差的範圍之內操作。<br>d數值越大，價格曲線越平滑，能減少波動雜訊。<br>n數值越大，能產生越極端的訊號，一般n值範圍依據<strong>68–95–99.7法則</strong>（68–95–99.7 rule），設定在1-3，在<a href="https://zh.m.wikipedia.org/wiki/%E6%AD%A3%E6%80%81%E5%88%86%E5%B8%83" target="_blank" rel="noopener">常態分布</a>中，距平均值小於一個<a href="https://zh.m.wikipedia.org/wiki/%E6%A8%99%E6%BA%96%E5%B7%AE" target="_blank" rel="noopener">標準差</a>、二個標準差、三個標準差以內的百分比。當股價跌破下軌通道，可能出現超賣訊號，會在之後均值回歸，產生反彈到中軌通道附近。</p>



<h2>策略實作</h2>



<p class="has-normal-font-size"><meta charset="utf-8">用<a href="https://ai.finlab.tw/" class="rank-math-link" target="_blank" rel="noopener">finlab套件</a>能很輕易讓我們實作上述的策略來驗證想法，如果你還沒裝過finlab量化回測套件，可以參考我們的<a href="https://ai.finlab.tw/document" class="rank-math-link" target="_blank" rel="noopener">文檔</a>，快速安裝來體驗。這邊以<meta charset="utf-8">2.5個標準差、40日平均線週期設定布林通道，讀者可自行使用其他數值做簡單實驗。</p>



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

from finlab import data
from finlab.backtest import sim

close=data.get('price:收盤價')
upperband, middleband, lowerband = data.indicator('BBANDS', resample='D', nbdevup=float(2.5), nbdevdn=float(2.5), timeperiod=40)
entries = lowerband &gt; close
exits = close &gt; middleband

position = entries.hold_until(exits)['2330']
report=sim(position, upload=True, mae_mfe_window=40, name='護國神山救難隊')
trade_record=report.trades
report.display_mae_mfe_analysis().show()
report.display()
</code></pre>



<h3>回測數據分析</h3>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="623" src="https://www.finlab.tw/wp-content/uploads/2022/03/截圖-2022-03-09-上午7.40.40-1024x623.png" alt="截圖 2022 03 09 上午7.40.40" class="wp-image-3476" srcset="https://www.finlab.tw/wp-content/uploads/2022/03/截圖-2022-03-09-上午7.40.40-1024x623.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/03/截圖-2022-03-09-上午7.40.40-300x183.png 300w, https://www.finlab.tw/wp-content/uploads/2022/03/截圖-2022-03-09-上午7.40.40-768x468.png 768w, https://www.finlab.tw/wp-content/uploads/2022/03/截圖-2022-03-09-上午7.40.40-1536x935.png 1536w, https://www.finlab.tw/wp-content/uploads/2022/03/截圖-2022-03-09-上午7.40.40-2048x1247.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="護國神山抄底策略 2"></figure>



<ul class="has-normal-font-size"><li>win ratio: 86.96 %</li><li>return_mean: 4.73  %</li><li>mae_mean: -3.88  %</li><li>bmfe_mean: 2.46  %</li><li>gmfe_mean: 6.1  %</li><li>mdd_mean: -6.55 %</li></ul>



<p class="has-normal-font-size"><br>台積電歷往出現的訊號次數不多，要讓護國神山山崩不太容易，每次都發生在大環境崩壞的時刻，2007年後共出現過23次，平均持有20日，每筆平均搶到4.9%獲利，勝率87%。<br>不過要注意的是MAE (最大不利方向幅度)、MDD (最大回撤)都有一定的數值，代表抄底買進後往往都還有回檔、持有過程震盪不小，難有抄在最低點這回事。<br>gmfe_mean比return_mean大，代表持股歷程中的最大平均漲幅比最終平均報酬還高，我們可能有停利空間可以操作。<meta charset="utf-8">俗話說搶反彈如搶銀行，行動要快狠準，不求多，可以設獲利10%時就出場，有機會取得比平均報酬5%以上更高的獲利。只要在hold_until的function就可以設置停利 (<meta charset="utf-8">takeprofit)，是不是很簡單呢？</p>



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

close=data.get('price:收盤價')
upperband, middleband, lowerband = data.indicator('BBANDS', resample='D', nbdevup=float(2.5), nbdevdn=float(2.5), timeperiod=40)
entries = lowerband &gt; close
exits = close &gt; middleband

position = entries.hold_until(exits,take_profit=0.1)['2330']
report=sim(position, upload=True, mae_mfe_window=40, name='護國神山救難隊')
trade_record=report.trades
report.display_mae_mfe_analysis().show()
report.display()

</code></pre>



<p class="has-normal-font-size">加入停利後，可以發現報酬率提升一點點到5.1%，MAE從 -3.88 %縮小到 -3.58 %，MDD也從 -6.55 %縮小到 -5.5 %，持股歷程更舒服了。</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="1024" src="https://www.finlab.tw/wp-content/uploads/2022/07/newplot-22-1024x1024.png" alt="newplot 22" class="wp-image-4086" srcset="https://www.finlab.tw/wp-content/uploads/2022/07/newplot-22-1024x1024.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/07/newplot-22-300x300.png 300w, https://www.finlab.tw/wp-content/uploads/2022/07/newplot-22-150x150.png 150w, https://www.finlab.tw/wp-content/uploads/2022/07/newplot-22-768x768.png 768w, https://www.finlab.tw/wp-content/uploads/2022/07/newplot-22-600x600.png 600w, https://www.finlab.tw/wp-content/uploads/2022/07/newplot-22-96x96.png 96w, https://www.finlab.tw/wp-content/uploads/2022/07/newplot-22.png 1200w" sizes="(max-width: 1024px) 100vw, 1024px" title="護國神山抄底策略 3"></figure>



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



<figure class="wp-block-image size-full"><img loading="lazy" width="432" height="361" src="https://www.finlab.tw/wp-content/uploads/2022/10/2330_edge_ratio.png" alt="2330 edge ratio" class="wp-image-4653" srcset="https://www.finlab.tw/wp-content/uploads/2022/10/2330_edge_ratio.png 432w, https://www.finlab.tw/wp-content/uploads/2022/10/2330_edge_ratio-300x251.png 300w" sizes="(max-width: 432px) 100vw, 432px" title="護國神山抄底策略 4"><figcaption><br></figcaption></figure>



<p class="has-medium-font-size">10天內優勢比率波動較不穩定，短期衝高後容易有回檔，若10天後沒虧損，優勢會放大，勝率更能提高。 可以考慮分兩批資金操作，第二批等10天後更確認訊號再向上加碼，而不向下攤平。</p>



<h2>結論</h2>



<p class="has-normal-font-size">拜外資瘋狂倒貨所致，這個少見的抄底訊號在昨日出現，神山要倒也只有這個時候，3/8以563元買入，最終會如何呢？<br>藉由布林通道，我們能知道何時會有相對低點的極端反轉機會，藉由report.trades，我們可以取得回測結果的波動分析，了解反彈報酬目標、可能回檔範圍、停損停利空間的輪廓，進而知道應對進退，而不是跟投顧老師一樣&#8221;<strong>避著眼睛買&#8221;!</strong><br>如果你對台積電很有愛，可以複習另一篇台積電均線策略的<a class="rank-math-link" href="https://www.finlab.tw/twii-2330-invest/">範例</a>。也許你能夠有更多想法，開發出更棒的策略！</p>



<h2>程式碼範例</h2>



<p class="has-normal-font-size"><a class="rank-math-link" href="https://drive.google.com/file/d/1ejl8YM9J-uGAojJVFdWAvYgcVvg-e1Gz/view?usp=sharing" target="_blank" rel="noopener">檔案連結</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/2330_bband_rebound/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3474</post-id>	</item>
		<item>
		<title>台積電如何買？用 Python 研發投資策略</title>
		<link>https://www.finlab.tw/twii-2330-invest/</link>
					<comments>https://www.finlab.tw/twii-2330-invest/#respond</comments>
		
		<dc:creator><![CDATA[FinLab - 韓承佑]]></dc:creator>
		<pubDate>Wed, 29 Jul 2020 05:28:08 +0000</pubDate>
				<category><![CDATA[選股策略]]></category>
		<category><![CDATA[PYTHON財經]]></category>
		<category><![CDATA[技術面]]></category>
		<category><![CDATA[股票策略]]></category>
		<category><![CDATA[台積電]]></category>
		<category><![CDATA[如何投資]]></category>
		<category><![CDATA[如何買股票]]></category>
		<category><![CDATA[股票]]></category>
		<category><![CDATA[股票分析]]></category>
		<category><![CDATA[財經PYTHON教學]]></category>
		<guid isPermaLink="false">https://www.finlab.tw/?p=1928</guid>

					<description><![CDATA[人人都想買台積電，獲得穩定的報酬，然而股價現在這麼高了，還安全嗎？怎麼才能安全的享受台積電的上漲的獲利，又可以在下跌時加碼呢？我們可以針對台積電，用 Python 研發擇時買賣！]]></description>
										<content:encoded><![CDATA[
<p>最近股票圈最熱門的話題，不外乎就是「台積電」，以前我們都說，市值太大的股票，上漲的幅度有限。但是台積電果然是國家棟梁，身為台股最大市值的股票，竟然可以漲停板！然而現在這麼高了，還安全嗎？怎麼才能安全的享受台積電的上漲的獲利，又可以在下跌時加碼呢？我們可以針對台積電，用 Python 研發擇時買賣，文末附上完整程式範例！</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="577" src="https://www.finlab.tw/wp-content/uploads/2020/07/Picture1-6-1024x577.png" alt="台積電" class="wp-image-1957" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/Picture1-6-1024x577.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/Picture1-6-300x169.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/Picture1-6-768x433.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/Picture1-6-1536x866.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/Picture1-6-2048x1155.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="台積電如何買？用 Python 研發投資策略 5"><figcaption>台積電要如何買賣呢？</figcaption></figure>



<h3>3步驟帶你分析台積電</h3>



<p>這篇文章會分享怎麼研發台積電的投資策略，主要有三個步驟：</p>



<ol><li>使用 <strong>Colab</strong> 並安裝 yfinance 、 backtesting、talib 的函式庫</li><li><strong>下載台積電股價歷史紀錄</strong>，研發買賣訊號</li><li><strong>回測交易結果分析</strong>，並且研究策略如何<strong>優化</strong></li></ol>



<h2>1. 使用 <a href="https://colab.research.google.com/" target="_blank" rel="noreferrer noopener">Colab</a> 並下載環境</h2>



<p>要建構一個股票策略，只要會基本的 Python ，就可以開始了，我們使用 <a rel="noreferrer noopener" href="https://colab.research.google.com/" target="_blank">Colab</a> 來當作撰寫 Python 的平台，這是 Google 佛心推出的，讓我們可以線上撰寫程式，而且<strong>完全免費</strong>！我自己已經把幾乎所有程式碼搬到 Colab 上了！雖然速度比桌機稍慢，但是<strong>可以雲端任何地點編輯，就算換電腦也不用擔心！</strong></p>



<h3>安裝 Package</h3>



<p>我們今天要用的 Package，有兩個，一個是 <a href="https://pypi.org/project/yfinance/" target="_blank" rel="noreferrer noopener">yfinance</a> ，負責下載 yahoo finance 上的股價資料，另外一個是 <a href="https://github.com/kernc/backtesting.py" target="_blank" rel="noreferrer noopener">backtesting</a>，顧名思義就是用來研發策略用的！但研發策略，有時候會需要製作技術指標，並根據技術指標來交易，所以需要用到 <a href="http://mrjbq7.github.io/ta-lib/" target="_blank" rel="noreferrer noopener">talib</a> 這個 Package，我們可以用簡單的三行指令完成安裝：</p>



<pre class="wp-block-code"><code lang="python" class="language-python">!pip install yfinance
!pip install Backtesting
!pip install talib-binary</code></pre>



<p>上述三行，只要在程式碼輸入欄輸入，系統就會幫你安裝好這三款 package，這三行的第一個字符是驚嘆號，代表我們要執行 <a href="https://zh.wikipedia.org/wiki/%E6%AE%BC%E5%B1%A4" target="_blank" rel="noreferrer noopener">Shell</a> 的語法，不是 Python 的語法！假如你不是用 Colab，而是用個人電腦，也可以在打開 <a href="https://zh.wikipedia.org/wiki/%E6%AE%BC%E5%B1%A4" target="_blank" rel="noreferrer noopener">Shell</a> 輸入這些指令，記得將指令的驚嘆號移除喔！</p>



<h2>2. 下載台積電股價，研發買賣訊號！</h2>



<p>首先，我們先來下載台積電的歷史紀錄，在下方的程式碼中，我們已經幫大家寫好一個函式，叫做「get_historical_data」，可以直接呼叫它來獲取股價。由於 yfinance 的歷史紀錄算是滿豐富的，所以有很多股票都可以下載，包含美股台股，例如蘋果（AAPL），特斯拉（TSLA），微軟（MSFT），然而台股的部分，比較可惜的地方，就是只有上市資料，如台積電（2330.TW），以下是完整的範例。<strong>你可以 <a href="https://finance.yahoo.com/quote/2330.TW?p=2330.TW&amp;.tsrc=fin-srch" target="_blank" rel="noreferrer noopener">參考 yahoo finance</a> 來下載你有興趣股票！</strong></p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">import yfinance as yf
import pandas as pd

def get_historical_data(ticker):
  d = yf.Ticker(ticker)
  df = d.history(period="max")
  df.columns = df.columns.str.lower()
  df.columns = pd.Series(df.columns).str.capitalize().values
  return df.dropna()

df = get_historical_data('2330.TW')
df</code></pre>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="373" src="https://www.finlab.tw/wp-content/uploads/2020/07/Screen-Shot-2020-07-29-at-11.57.25-AM-1024x373.png" alt="Screen Shot 2020 07 29 at 11.57.25 AM" class="wp-image-1938" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/Screen-Shot-2020-07-29-at-11.57.25-AM-1024x373.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/Screen-Shot-2020-07-29-at-11.57.25-AM-300x109.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/Screen-Shot-2020-07-29-at-11.57.25-AM-768x279.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/Screen-Shot-2020-07-29-at-11.57.25-AM.png 1242w" sizes="(max-width: 1024px) 100vw, 1024px" title="台積電如何買？用 Python 研發投資策略 6"></figure>



<h3>策略訊號研發</h3>



<p>有了股票的歷史紀錄，就可以來研發策略了，由於 Python 是個執行速度很慢的語言（比起 C、C++），所以我們不太使用 <a href="https://www.w3schools.com/python/python_for_loops.asp" target="_blank" rel="noreferrer noopener">for 迴圈</a> 來回測，而是用向量矩陣的方式產生訊號，<strong>速度會快很多</strong>，其中的「sma1」、「sma2」、「signal_long」、「signal_short」都是時間序列，下方為均線為範例，假如你不喜歡均線，<strong>可以參考 <a href="http://mrjbq7.github.io/ta-lib/" target="_blank" rel="noreferrer noopener">talib</a> 來製作你有興趣的技術指標喔</strong>！</p>



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

# compute simple moving average using talib
sma1 = talib.SMA(df.Close, timeperiod=20)
sma2 = talib.SMA(df.Close, timeperiod=60)

# compute buy and sell signals (golden cross and death cross)
signal_long = (sma1 > sma2) &amp; (sma1.shift() &lt; sma2.shift())
signal_short = (sma1 &lt; sma2) &amp; (sma1.shift() > sma2.shift())

# combine long and short signals
signal = signal_long.copy()
signal[signal_short] = -1</code></pre>



<p>程式碼看不懂嗎？沒關係，我們將這些時間序列 2020 年的數值繪製出來：</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">df.Close['2020'].plot()
sma1['2020'].plot()
sma2['2020'].plot()
signal['2020'].astype(int).plot(secondary_y=True)</code></pre>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="433" src="https://www.finlab.tw/wp-content/uploads/2020/07/Screen-Shot-2020-07-29-at-12.08.26-PM-1024x433.png" alt="Screen Shot 2020 07 29 at 12.08.26 PM" class="wp-image-1943" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/Screen-Shot-2020-07-29-at-12.08.26-PM-1024x433.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/Screen-Shot-2020-07-29-at-12.08.26-PM-300x127.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/Screen-Shot-2020-07-29-at-12.08.26-PM-768x324.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/Screen-Shot-2020-07-29-at-12.08.26-PM.png 1198w" sizes="(max-width: 1024px) 100vw, 1024px" title="台積電如何買？用 Python 研發投資策略 7"></figure>



<ul><li>藍色：df.Close &#8212;&#8211;&gt; 台積電的股價（一飛沖天！）</li><li>黃色：sma1 &#8212;-&gt; 20日均線</li><li>綠色：sma2 &#8212;-&gt; 60日均線</li><li>紅色：signal &#8212;-&gt; 買賣訊號</li></ul>



<p>接下來，我們就可以根據上圖中，<strong>紅色訊號為 1 時買入， -1 時賣出</strong>，這樣的的方式來交易，但是效果會如何呢？沒有人知道，所以我們還要進行「<strong>回測</strong>」，也就是將此策略放在歷史上模擬交易的報酬率！</p>



<h2>3. 回測和參數優化</h2>



<p>接下來我們就可以來測測看，究竟這樣子買台積電效果如何？我們可以用 backtesting 這個工具來幫我們回測，完整的程式碼如下，雖然有點長，但你會發現核心程式碼，跟剛剛是非常類似的！所以不用擔心太複雜！你也可以參考 <a href="https://github.com/kernc/backtesting.py" target="_blank" rel="noreferrer noopener">backtesting</a> 的官方教學，來獲得更詳細的用法喔！</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">from backtesting import Backtest, Strategy

class Strategy(Strategy):
    
    n1 = 20
    n2 = 60
    
    def init(self):
        super().init()
        
        # Precompute the two moving averages
        close = pd.Series(self.data.Close)
        sma1 = talib.SMA(close, timeperiod=self.n1)
        sma2 = talib.SMA(close, timeperiod=self.n2)

        # Precompute signal
        signal_long = (sma1 > sma2) &amp; (sma1.shift() &lt; sma2.shift())
        signal_short = (sma1 &lt; sma2) &amp; (sma1.shift() > sma2.shift())

        # combine signal
        signal = signal_long
        signal[signal_short] = -1
        
        # plot sma
        self.I(lambda x: sma1, 'sma1')
        self.I(lambda x: sma2, 'sma2')

        # set signal to trade
        self.signal = self.I(lambda x: signal, 'signal')

    def next(self):
        super().next()

        entry_size = self.signal[-1]

        if entry_size > 0:
            self.buy()
        elif entry_size &lt; 0:
          for trade in self.trades:
              trade.close()

bt = Backtest(df, Strategy)
result1 = bt.run()
bt.plot()</code></pre>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="571" src="https://www.finlab.tw/wp-content/uploads/2020/07/Screen-Shot-2020-07-29-at-12.13.35-PM-1024x571.png" alt="Screen Shot 2020 07 29 at 12.13.35 PM" class="wp-image-1944" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/Screen-Shot-2020-07-29-at-12.13.35-PM-1024x571.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/Screen-Shot-2020-07-29-at-12.13.35-PM-300x167.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/Screen-Shot-2020-07-29-at-12.13.35-PM-768x428.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/Screen-Shot-2020-07-29-at-12.13.35-PM-1536x856.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/Screen-Shot-2020-07-29-at-12.13.35-PM-2048x1141.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="台積電如何買？用 Python 研發投資策略 8"></figure>



<p>上圖就是我們的回測結果，這是一個動態的圖表，所以我們可以將一部分放大：</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="571" src="https://www.finlab.tw/wp-content/uploads/2020/07/Screen-Shot-2020-07-29-at-12.20.57-PM-1024x571.png" alt="Screen Shot 2020 07 29 at 12.20.57 PM" class="wp-image-1946" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/Screen-Shot-2020-07-29-at-12.20.57-PM-1024x571.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/Screen-Shot-2020-07-29-at-12.20.57-PM-300x167.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/Screen-Shot-2020-07-29-at-12.20.57-PM-768x428.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/Screen-Shot-2020-07-29-at-12.20.57-PM-1536x856.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/Screen-Shot-2020-07-29-at-12.20.57-PM-2048x1141.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="台積電如何買？用 Python 研發投資策略 9"></figure>



<p>上圖從上到下，總共有五個小圖，我們一張一張解釋：</p>



<p>圖一：為最後的總績效結果（藍色線段），代表策略的報酬率，從2000到現在可以獲利約400％，而當中的紅色水平線段，代表最久沒有創新高的時間段，這段時間可能會讓你懷疑，這個策略有沒有效果，而放棄策略，這段時間當然是越短越好！</p>



<p>圖二：有很多的三角形，假如是正三角就是做多，倒三角就是做空，我們這次寫的策略是做多的策略！所以不會有做空的倒三角喔！另外顏色代表獲利或是虧損，綠色為獲利，紅色為虧損，這些三角形的高度代表獲利或虧損的程度，以虛線做區分，虛線上方是獲利，而虛線下方式虧損，可以看到這種交易方法 2008 年以後每次虧損不會太多，獲利有時候還滿驚人的！</p>



<p>圖三是交易的明細，除了股價 K 棒外，我們也看到了兩條均線（藍色跟橘色），方便我們核對交易的時間，另外我們可以看到綠色和紅色的虛線，每一條虛線都代表一次交易，虛線的起始和結束，代表交易的價格跟時間，綠色代表獲利，而紅色代表虧損。</p>



<p>第四和第五張圖，則是成交量以及 signal 訊號，此策略就是模擬 signal 訊號為 1 時買進，而 -1 時賣出，比對其他圖片的數據，非常合理！</p>



<h3>策略效果不夠好？尋找最佳參數！</h3>



<p>剛剛我們用的均線是20日跟60日，來做交易，然而這是最好的均線嗎？我們可以將這兩個參數，當成策略的參數，分別叫 n1 和 n2 ，透過暴力枚舉（range(5, 200)），來從 5 到 200 裡面挑出 <a href="https://www.investopedia.com/terms/s/sharperatio.asp" target="_blank" rel="noreferrer noopener">Sharpe ratio</a> 比較好的參數：</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">result2 = bt.optimize(n1=range(5, 200, 10),
                      n2=range(5, 200, 10))
result2._strategy</code></pre>



<pre class="wp-block-code"><code lang="python" class="language-python"># 程式碼顯示結果：
&lt;Strategy Strategy(n1=165,n2=5)></code></pre>



<p>以上，就是整個優化的過程，程式碼非常簡潔，最後優化完的數字是</p>



<ul><li>n1 = 165</li><li>n2 = 2</li></ul>



<p>眼尖的人會發現，奇怪怎麼長短週期倒過來了？代表我們死亡交叉買入，而黃金交叉賣出，這種交易比較像是均值回歸，在低點買，高點賣，屬於逆勢策略，我們用這兩個新的參數，來測測看結果如何？</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="578" src="https://www.finlab.tw/wp-content/uploads/2020/07/Screen-Shot-2020-07-29-at-12.32.06-PM-1024x578.png" alt="Screen Shot 2020 07 29 at 12.32.06 PM" class="wp-image-1952" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/Screen-Shot-2020-07-29-at-12.32.06-PM-1024x578.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/Screen-Shot-2020-07-29-at-12.32.06-PM-300x169.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/Screen-Shot-2020-07-29-at-12.32.06-PM-768x434.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/Screen-Shot-2020-07-29-at-12.32.06-PM-1536x867.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/Screen-Shot-2020-07-29-at-12.32.06-PM-2048x1156.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="台積電如何買？用 Python 研發投資策略 10"></figure>



<p>雖然報酬率雖然比較低，但是交易的風險小滿多的，我們可以將順勢跟逆勢策略結合，獲得更穩定的報酬率，下方就是程式碼</p>



<pre class="wp-block-code"><code lang="python" class="language-python">((result1._equity_curve.Equity + 
result2._equity_curve.Equity)/2).plot()</code></pre>



<figure class="wp-block-image size-large"><img loading="lazy" width="974" height="482" src="https://www.finlab.tw/wp-content/uploads/2020/07/Screen-Shot-2020-07-29-at-12.40.45-PM.png" alt="Screen Shot 2020 07 29 at 12.40.45 PM" class="wp-image-1954" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/Screen-Shot-2020-07-29-at-12.40.45-PM.png 974w, https://www.finlab.tw/wp-content/uploads/2020/07/Screen-Shot-2020-07-29-at-12.40.45-PM-300x148.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/Screen-Shot-2020-07-29-at-12.40.45-PM-768x380.png 768w" sizes="(max-width: 974px) 100vw, 974px" title="台積電如何買？用 Python 研發投資策略 11"><figcaption>績效合併後的結果</figcaption></figure>



<p>基本上2008 到現在，沒什麼虧損過，台積電上漲時，會追蹤到漲幅，而下跌時也會危機入市，算是一個非常簡單，但績效很舒服的策略，分享給大家，現在就<a href="https://colab.research.google.com/drive/18U4QvoqH99450ixNBDKCm_ESqQW-slvr?usp=sharing" target="_blank" rel="noreferrer noopener">打開現成的 Colab 直接運行程式碼</a>。假如大家對於我們這樣的分享有興趣，可以幫我們推廣一下！我們也有其他類似的文章可以參考：</p>



<ul><li><a href="https://www.finlab.tw/low-risk-fft-spy-strategy/">低風險高報酬投資組合，股債平衡策略研發</a></li><li><a href="https://www.finlab.tw/python%e6%96%b0%e6%89%8b%e6%95%99%e5%ad%b8%ef%bc%9a%e5%a4%8f%e6%99%ae%e6%8c%87%e6%95%b8%e7%ad%96%e7%95%a5/">避開危險的投資時機 – 夏普指數策略</a></li><li><a href="https://www.finlab.tw/%e5%8a%a0%e9%80%9f%e5%ba%a6%e6%8c%87%e6%a8%99%e5%af%a6%e5%81%9a/">找出會加速的股票 &#8211; 加速度指標實做</a></li></ul>



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