<?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/%E7%B0%A1%E6%98%93%E7%AD%96%E7%95%A5/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.finlab.tw</link>
	<description>深入淺出的量化投資，讓你在在茫茫股海中，找到專屬於自己的投資方法</description>
	<lastBuildDate>Wed, 25 May 2022 07:48:58 +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/python-biotech-stock-portfolio/</link>
					<comments>https://www.finlab.tw/python-biotech-stock-portfolio/#respond</comments>
		
		<dc:creator><![CDATA[FinLab - 韓承佑]]></dc:creator>
		<pubDate>Wed, 05 Aug 2020 14:44:59 +0000</pubDate>
				<category><![CDATA[PYTHON財經]]></category>
		<category><![CDATA[技術面]]></category>
		<category><![CDATA[股票策略]]></category>
		<category><![CDATA[財經PYTHON教學]]></category>
		<category><![CDATA[選股策略]]></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=2039</guid>

					<description><![CDATA[國光生、中天、亞諾法、合一，這些妖怪股最近的漲跌每天都是10％上下，非常的可怕，要如何才能買在低點、賣在高點？ [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>國光生、中天、亞諾法、合一，這些妖怪股最近的漲跌每天都是10％上下，非常的可怕，要如何才能買在低點、賣在高點？本文教你怎麼設計策略，在 2008 ～2020 年翻 6 倍的穩定策略，獲利不錯且風險小，從零開始研究生技股策略？讓 FinLab 做實驗跟你分享！請原諒我標題殺人，這篇還滿學術且實用的，但往往最有用的東西反而沒人看，只好標題殺人吸引你的目光，看完後保證你值回票價。</p>



<figure class="wp-block-image size-large"><img width="1024" height="683" src="https://www.finlab.tw/wp-content/uploads/2020/08/photo-1591696205602-2f950c417cb9-1024x683.jpeg" alt="生技股（國光生、中天、亞諾法、合一）股價波動大 - 如何寫出穩定的策略呢？" class="wp-image-2055" srcset="https://www.finlab.tw/wp-content/uploads/2020/08/photo-1591696205602-2f950c417cb9-1024x683.jpeg 1024w, https://www.finlab.tw/wp-content/uploads/2020/08/photo-1591696205602-2f950c417cb9-300x200.jpeg 300w, https://www.finlab.tw/wp-content/uploads/2020/08/photo-1591696205602-2f950c417cb9-768x512.jpeg 768w, https://www.finlab.tw/wp-content/uploads/2020/08/photo-1591696205602-2f950c417cb9-1536x1024.jpeg 1536w, https://www.finlab.tw/wp-content/uploads/2020/08/photo-1591696205602-2f950c417cb9.jpeg 1650w" sizes="(max-width: 1024px) 100vw, 1024px" title="生技股如何安全買？逆勢爆賺策略分享 1"><figcaption>生技股（國光生、中天、亞諾法、合一）股價波動大 &#8211; 如何寫出穩定的策略呢？</figcaption></figure>



<h2>生技股 ，漲停又跌停，如何判斷？</h2>



<p>上禮拜問大家最想看什麼股票的回測，很多人都說「國光生」、「合一」，這些生技股。在我的機器學習策略中，上禮拜也出現非常多檔，像是「亞諾法」、「中天」等等，當時打開看盤軟體，跌停好幾天了，看到真的會怕，一邊買手一邊抖。</p>



<p>但對我來講，科學比賺錢還要重要，假如我主觀的干預，就算獲利了，也不會開心，<strong>不相信自己的策略，就等於背棄量化交易的信仰</strong>，等於無時無刻都要檢查策略是否出錯，<strong>檢驗股票，汲汲營營於股市，會犧牲很多時間</strong>！還是要交給量化交易，資金才能有系統的放大！</p>



<p>所以無論如何我都不想干預它選出的結果，咬緊牙關低接，事後發現，報酬相當不錯，果然，別人恐慌我貪婪，是股票中的真理。雖然我也很恐慌，但我相信自己做出來的策略。上述經驗，是上禮拜的持股，這禮拜我並沒有建議買生技股呀！</p>



<p>雖然大家可能沒有機器學習策略，但是也想要買生技股，那</p>



<h3>要如何判斷對的時機加碼呢？</h3>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="681" src="https://www.finlab.tw/wp-content/uploads/2020/08/photo-1512767254318-423c816efbf3-1024x681.jpeg" alt="photo 1512767254318 423c816efbf3" class="wp-image-2054" srcset="https://www.finlab.tw/wp-content/uploads/2020/08/photo-1512767254318-423c816efbf3-1024x681.jpeg 1024w, https://www.finlab.tw/wp-content/uploads/2020/08/photo-1512767254318-423c816efbf3-300x199.jpeg 300w, https://www.finlab.tw/wp-content/uploads/2020/08/photo-1512767254318-423c816efbf3-768x510.jpeg 768w, https://www.finlab.tw/wp-content/uploads/2020/08/photo-1512767254318-423c816efbf3-1536x1021.jpeg 1536w, https://www.finlab.tw/wp-content/uploads/2020/08/photo-1512767254318-423c816efbf3.jpeg 1953w" sizes="(max-width: 1024px) 100vw, 1024px" title="生技股如何安全買？逆勢爆賺策略分享 2"><figcaption>如何加碼生技股呢？</figcaption></figure>



<p>這篇文章就帶大家來設計一個簡單的策略，雖然設計的簡單，但過程不簡單，我們只要由上次「<a href="https://www.finlab.tw/twii-2330-invest/" class="rank-math-link">如何買台積電？</a>」這篇文章的範例改寫而來，加入了一個回測上的技巧，來防止過擬合，找到適當的參數，同時<strong>避免優化雜訊的風險</strong>！</p>



<h2>生技股策略研發</h2>



<p>策略人人都會寫，特別是用 multicharts ，提供簡單好用的功能，10行以內就可以有績效不錯的策略。只要參數夠多，想要績效多好就有多好，只要透過參數優化就可以了！但是重點就在於，<strong>參數優化真的是有效的嗎？還是你只是優化了歷史，沒有優化未來呢？</strong></p>



<h3>優化歷史不等於優化未來？</h3>



<p>為什麼策略上線後，績效表現不好？為什麼無法優化未來？主要可以分成以下幾個原因：</p>



<ul><li><strong>策略參數維度太大，</strong>相較之下，樣本太少，有點像是買樂透，只要買夠多張，一定會中獎，但不代表你會知道下一期的開獎號碼！更學術的講法，就是策略<strong>誤將歷史雜訊當成規律來優化</strong>（overfitting）。</li><li>第二種可能是，策略雖然有抓到股價的型態，但是隨著越來越多人用一樣的策略，<strong>導致市場效率上升，獲利空間被壓縮</strong>。</li><li>商品因為<strong>基本面和消息面、黑天鵝事件，有重大的變化</strong>，導致價格的特性跟以往不一樣。</li></ul>



<figure class="wp-block-image size-large"><img loading="lazy" width="640" height="182" src="https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-9-1.png" alt="thumbnail 9 1" class="wp-image-1153" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-9-1.png 640w, https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-9-1-300x85.png 300w" sizes="(max-width: 640px) 100vw, 640px" title="生技股如何安全買？逆勢爆賺策略分享 3"><figcaption>overfitting 的結果：只是在優化雜訊</figcaption></figure>



<h3>要如何避免優化失敗呢？</h3>



<p>針對上述的 1 跟 2 點的問題，我們可以用以下的方式，在策略研發時，避免 overfitting：</p>



<ol><li>限制策略的維度：研發策略時，不要用太多參數，或是參數盡量重複使用，讓<strong>可調整的維度盡量縮小</strong>。</li><li>限制回測的次數：當你手動修改策略時，也是一種最佳化，所以<strong>盡量避免盲目的修改程式碼並回測的過程</strong>，有些人把「大於」換成「小於」，就測一次，參數隨便改一改，也測一次，條件拿掉一個，再測一次，濾網增加一個，又測一次。在這樣不斷的測試中，其實是「工人」智慧的最佳化，也會導致 overfitting 喔！</li><li>增加樣本數量：<strong>我們可以取不同的商品，將所有商品用同一個策略來優化</strong>，這樣針對單獨商品的績效會變差，但是整體來說，由於樣本數量變多，商品之間的correlation比較小，找到的 pattern 更 robust（不知道中文怎麼翻：魯棒性？超詭異的）不容易 overfitting。</li><li><strong>使用 hold-out method</strong>：將資料分成樣本內（in-sample IS）跟樣本外（out-of-sample OOS）並且在 IS 做最佳化後，再用 OOS 驗證。</li><li>但 hold-out method 會讓 samples 變少，所以也有其他更複雜的方法，可以參考「<a href="https://www.finlab.tw/backtesting-overfitting-probability/" class="rank-math-link">策略最佳化是有效的嗎？</a>」這篇文章</li><li>驗證近期績效，當你研發出來的策略報酬是凸狀，這種策略可能在近期就不管用了，假如是股票策略，尤其是選股策略，<strong>一定要將兩三年的績效，跟大盤做均一化（normalize、rebase）後的比較</strong>，才能確保策略在近年是有效的，也有人會用 rolling n years 的方式，來看近期績效是否下滑。</li></ol>



<p>上述這麼多種方法，我們今天先簡單挑幾個，接下來就可以開始實做策略囉！</p>



<h2>生技股策略實做</h2>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="683" src="https://www.finlab.tw/wp-content/uploads/2020/08/photo-1575503802870-45de6a6217c8-1024x683.jpeg" alt="photo 1575503802870 45de6a6217c8" class="wp-image-2058" srcset="https://www.finlab.tw/wp-content/uploads/2020/08/photo-1575503802870-45de6a6217c8-1024x683.jpeg 1024w, https://www.finlab.tw/wp-content/uploads/2020/08/photo-1575503802870-45de6a6217c8-300x200.jpeg 300w, https://www.finlab.tw/wp-content/uploads/2020/08/photo-1575503802870-45de6a6217c8-768x512.jpeg 768w, https://www.finlab.tw/wp-content/uploads/2020/08/photo-1575503802870-45de6a6217c8-1536x1024.jpeg 1536w, https://www.finlab.tw/wp-content/uploads/2020/08/photo-1575503802870-45de6a6217c8.jpeg 1650w" sizes="(max-width: 1024px) 100vw, 1024px" title="生技股如何安全買？逆勢爆賺策略分享 4"></figure>



<p>為了避免 overfitting，我們遵守上面「避免優化失敗」的前三個要點：</p>



<ul><li>首先，我們<strong>使用最傳統的均線策略即可，不用作任何修改</strong>，上次怎麼買台積電，就怎麼買生技股！由於是均線策略，只有兩個維度，就是短週期、長週期的均線參數而已。</li><li><strong>增加了停損 -30%</strong>，畢竟生技股大漲大跌還是挺可怕的，使用 &#8211; 30％最主要是防止策略由於基本面、消息面的因素，產生巨幅下跌。此參數是靠經驗設定，不太需要重新回測，所以不太會造成研發策略時的過擬合。</li><li><strong>使用多商品回測，來確保參數的 robustness</strong> ，避免 overfitting。</li></ul>



<p>我們跟上次一樣，使用 Colab 進行回測，Colab 是一個免費線上運行 Python 的平台，請大家打開 <a href="https://colab.research.google.com/drive/1OeZGldvveMZKFErEi1LPdi_OkyhLNmqC?usp=sharing" class="rank-math-link" target="_blank" rel="noopener">Colab</a>，跟我們一起運行程式吧！（只要複製貼上就可以囉！）文末附上完整程式碼，假如你連複製貼上都懶，拉到下方，也可以直接運行喔！</p>



<h3>安裝 Packages</h3>



<p>這個步驟跟上次一樣，是股票回測最基本的起手勢：</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers"># 要一小段時間安裝 Packages
!pip install yfinance > log.txt
!pip install Backtesting==0.2.0 > log.txt
!pip install talib-binary</code></pre>



<p>接下來，使用 yahoo finance 下載各種股票的數據來回測，這次的標的有：</p>



<figure class="wp-block-table aligncenter is-style-regular"><table class="has-subtle-light-gray-background-color has-fixed-layout has-background"><thead><tr><th>股票名稱</th><th>Yahoo 股票代碼</th></tr></thead><tbody><tr><td>國光生</td><td>4142.TW</td></tr><tr><td>中天</td><td>4124.TWO</td></tr><tr><td>亞諾法</td><td>4133.TW</td></tr><tr><td>合一</td><td>4743.TW</td></tr></tbody></table><figcaption>股票代號與代碼</figcaption></figure>



<p>上述股票的 yahoo 代碼，假如是上市，就是「TW」結尾，假如是上櫃，就是「TWO」，我們將上述股票的代碼列出來(stocks)，並且使用 <code>get_historical_data</code> 來取得歷史資料，將歷史資料存在 <code>dfs</code> 裡面：</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()

stocks = ['4142.TW', '4743.TWO', '4128.TWO', '4133.TW']
dfs = {s:get_historical_data(s) for s in stocks}</code></pre>



<p>接下來就是本篇的重頭戲，<strong>要如何一次考慮所有股票進行優化呢？</strong>當然我們可以一檔一檔優化，並將結果（如 sharpe ratio）平均起來，但是這樣的方式，要修改不少程式，還要加入 for 迴圈，會讓程式碼不好維護。</p>



<p>所以我用了一個簡單的方法，把它取名為「price fusion」，顧名思義，就是將<strong>所有商品的開高低收整合起來，融合成一個商品</strong>，這樣就可以用一樣優化方法，但是最後的結果同時考慮了上述 5 檔股票，是不是方便很多呢？</p>



<p>由於程式碼稍微複雜，所以我就不詳細介紹是怎麼寫的，有興趣的人可以自行研究，假如你時間有限，可以直接呼叫下方的「price_fusion」這個 function，就可以了。</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">import numpy as np
def price_fusion(ohlcv, symbols):
  start_bar = 0
  close_ref = pd.Series(np.concatenate([ohlcv[s].Close.astype(float).pct_change().values[start_bar:] for s in symbols]))
  close_ref[close_ref.abs() > 0.1] = 0
  ret_close = (close_ref + 1).cumprod()

  close = pd.Series(np.concatenate([ohlcv[s].Close.astype(float).values[start_bar:] for s in symbols]))
  high = pd.Series(np.concatenate([ohlcv[s].High.astype(float).values[start_bar:] for s in symbols]))
  low = pd.Series(np.concatenate([ohlcv[s].Low.astype(float).values[start_bar:] for s in symbols]))
  open_ = pd.Series(np.concatenate([ohlcv[s].Open.astype(float).values[start_bar:] for s in symbols]))
  volume = pd.Series(np.concatenate([ohlcv[s].Volume.astype(float).values[start_bar:] for s in symbols]))

  ret_high = ret_close * high / close
  ret_low = ret_close * low / close
  ret_open = ret_close * open_ / close

  return pd.DataFrame({
      'Open': ret_open.values,
      'High': ret_high.values,
      'Low': ret_low.values,
      'Close': ret_close.values,
      'Volume': volume.values,
  }, index=pd.date_range('2000-1-1', periods=len(ret_close), freq='1h')).dropna().astype(float)

df = price_fusion(dfs, stocks)
print('price dataframe shape', df.shape)
df.head()</code></pre>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="318" src="https://www.finlab.tw/wp-content/uploads/2020/08/Screen-Shot-2020-08-05-at-4.01.22-PM-1-1024x318.png" alt="Screen Shot 2020 08 05 at 4.01.22 PM 1" class="wp-image-2042" srcset="https://www.finlab.tw/wp-content/uploads/2020/08/Screen-Shot-2020-08-05-at-4.01.22-PM-1-1024x318.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/08/Screen-Shot-2020-08-05-at-4.01.22-PM-1-300x93.png 300w, https://www.finlab.tw/wp-content/uploads/2020/08/Screen-Shot-2020-08-05-at-4.01.22-PM-1-768x239.png 768w, https://www.finlab.tw/wp-content/uploads/2020/08/Screen-Shot-2020-08-05-at-4.01.22-PM-1.png 1370w" sizes="(max-width: 1024px) 100vw, 1024px" title="生技股如何安全買？逆勢爆賺策略分享 5"></figure>



<p>我們可以發現，原本六檔股票，已經整合成同一個商品了，<strong>總共有11861天，大約是47年的績效</strong>！你可以想像一下，假如你可以找到<strong>一個策略，長達 47年有效，是不是覺得這個策略的可靠性變高很多</strong>，對這個策略更有信心了呢？這就是有效增加sample的方法！</p>



<h3>回測生技股</h3>



<p>融合完以上的商品，我們可以來回測了，回測的策略跟「<a href="https://www.finlab.tw/twii-2330-invest/" class="rank-math-link">研發台積電策略</a>」的文章是一模一樣的，所以我們在這邊只列出程式碼，不額外講解，假如對於下方的程式碼有任何不清楚，都可以前往<a href="https://www.finlab.tw/twii-2330-invest/" class="rank-math-link">該篇文章</a>詳讀喔！</p>



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

class Strategy(Strategy):
    
    n1 = 40
    n2 = 30
    
    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()

        for trade in self.trades:
          if self.data.Close[-1] &lt; trade.entry_price * 0.7:
            trade.close()

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



<p>下圖就是回測跑完的結果，我偷偷先使用了最佳化參數，但你這個階段理論上，不應該得到如此好的績效，這是優化後的結果，為了省去大家設參數的辛勞！</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="581" src="https://www.finlab.tw/wp-content/uploads/2020/08/Screen-Shot-2020-08-05-at-10.15.15-PM-1024x581.png" alt="Screen Shot 2020 08 05 at 10.15.15 PM" class="wp-image-2060" srcset="https://www.finlab.tw/wp-content/uploads/2020/08/Screen-Shot-2020-08-05-at-10.15.15-PM-1024x581.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/08/Screen-Shot-2020-08-05-at-10.15.15-PM-300x170.png 300w, https://www.finlab.tw/wp-content/uploads/2020/08/Screen-Shot-2020-08-05-at-10.15.15-PM-768x436.png 768w, https://www.finlab.tw/wp-content/uploads/2020/08/Screen-Shot-2020-08-05-at-10.15.15-PM-1536x872.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/08/Screen-Shot-2020-08-05-at-10.15.15-PM-2048x1163.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="生技股如何安全買？逆勢爆賺策略分享 6"></figure>



<h3>策略優化</h3>



<p>可以回測後，我們就可以做策略的最佳化，這邊要注意的地方是，為了避免 overfitting，在參數枚舉時（列舉所有參數時），不要間格太密，例如「5」，我覺得就是很剛好的數字，不用到「1」，不然容易 overfitting。</p>



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

# plot results
result2._equity_curve.Equity.plot(use_index=False, logy=True)</code></pre>



<p>下圖是最後策略的結果，我們可以看到47年總共獲利30000％！由於數字太大了，所以我們用 log 將數值變得比較有可看性，以一個粗糙的策略來說，我覺得很棒了，事實是，有時候均線策略，只要用對的方法來製作策略，就能夠有不錯的績效！你可以說我研發策略返璞歸真，也可以說我懶，但不論如何，有效最重要！</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1010" height="564" src="https://www.finlab.tw/wp-content/uploads/2020/08/Screen-Shot-2020-08-05-at-8.57.37-PM.png" alt="Screen Shot 2020 08 05 at 8.57.37 PM" class="wp-image-2051" srcset="https://www.finlab.tw/wp-content/uploads/2020/08/Screen-Shot-2020-08-05-at-8.57.37-PM.png 1010w, https://www.finlab.tw/wp-content/uploads/2020/08/Screen-Shot-2020-08-05-at-8.57.37-PM-300x168.png 300w, https://www.finlab.tw/wp-content/uploads/2020/08/Screen-Shot-2020-08-05-at-8.57.37-PM-768x429.png 768w" sizes="(max-width: 1010px) 100vw, 1010px" title="生技股如何安全買？逆勢爆賺策略分享 7"><figcaption>fusion price 回測結果</figcaption></figure>



<p>上圖中有一行「Strategy(n1=49, n2=30)」可以看到優化後，程式設定最佳參數為（n1=40, n2=30）這兩條均線，<strong>代表30日均線跌到40日下方時，我們可以購買這些生技股，停損一律是30％，直到股價回升，均線黃金交叉為止。歷史績效會有不錯的表現</strong>。雖然使用融合商品，得到不錯的績效，但在個股單一表現實用上，究竟能不能重現這樣驚人的績效呢？</p>



<h2>回到單檔股票回測</h2>



<p>上述是我們用融合的商品，回測47年的狀況，但是我們實際交易時，應該是會有很多商品，而商品的價格是同步進行的，怎麼修正呢？最終還是得一檔一檔測測看，使用 for 迴圈測，不過這時候因為策略都研發完了，所以只是做最後的檢驗動作：</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">eqs = {}
for s in stocks:
  bt = Backtest(dfs[s], Strategy)
  r = bt.run()
  eqs[s] = r._equity_curve.Equity
eqs = pd.DataFrame(eqs)
eqs.plot()</code></pre>



<p>下圖是跑出來的結果，可以看到這個策略在單一商品上，也表現的還算OK，但當然偶爾虧損還是滿大的，例如 4128（綠色）這檔股票 2018 年的跌幅，目測應該三個月虧損了快30％，這樣的策略是不能使用的！太危險！</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1018" height="468" src="https://www.finlab.tw/wp-content/uploads/2020/08/Screen-Shot-2020-08-05-at-9.03.53-PM.png" alt="Screen Shot 2020 08 05 at 9.03.53 PM" class="wp-image-2052" srcset="https://www.finlab.tw/wp-content/uploads/2020/08/Screen-Shot-2020-08-05-at-9.03.53-PM.png 1018w, https://www.finlab.tw/wp-content/uploads/2020/08/Screen-Shot-2020-08-05-at-9.03.53-PM-300x138.png 300w, https://www.finlab.tw/wp-content/uploads/2020/08/Screen-Shot-2020-08-05-at-9.03.53-PM-768x353.png 768w" sizes="(max-width: 1018px) 100vw, 1018px" title="生技股如何安全買？逆勢爆賺策略分享 8"><figcaption>生技股回測結果</figcaption></figure>



<h3>多商品合併以降低風險</h3>



<p>最後，為了將風險降低，我們來寫一個資產分配的回測，模擬將資產平均分配到這 4 個商品上，每個月重新再平衡，會得到如何的報酬率呢？</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">(eqs.resample('M')
    .last()
    .pct_change()+1
).mean(axis=1).cumprod().plot()</code></pre>



<figure class="wp-block-image size-large"><img loading="lazy" width="898" height="528" src="https://www.finlab.tw/wp-content/uploads/2020/08/Screen-Shot-2020-08-05-at-9.10.56-PM.png" alt="Screen Shot 2020 08 05 at 9.10.56 PM" class="wp-image-2053" srcset="https://www.finlab.tw/wp-content/uploads/2020/08/Screen-Shot-2020-08-05-at-9.10.56-PM.png 898w, https://www.finlab.tw/wp-content/uploads/2020/08/Screen-Shot-2020-08-05-at-9.10.56-PM-300x176.png 300w, https://www.finlab.tw/wp-content/uploads/2020/08/Screen-Shot-2020-08-05-at-9.10.56-PM-768x452.png 768w" sizes="(max-width: 898px) 100vw, 898px" title="生技股如何安全買？逆勢爆賺策略分享 9"><figcaption>多商品合併</figcaption></figure>



<p>從2009年到2019年，總共將資產翻了6倍，drawdown 看起來不大，我不會覺得太差，送給大家囉！由於此策略是擇時策略，所以會有很多閒置資金，所以績效應該比 6 倍好很多。另外，由於我們對多商品都用同一個策略，所以過擬合的機率算低，而此策略又是大家最舒服的逆勢加碼，相信除了學術練習外，實用上也會有一定的價值，不過任何策略都有失效和過擬合的可能，我們只能將其機率降低，無法保證 100％有效。假如大家有興趣看那個產業的策略，請在下方留言！我會不定時參考一下，決定之後要出的文章喔！</p>



<p>最後我們可以任意觀看其中一檔標的，是否值得買入，例如法諾亞（4133.TW）：</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">s = '4133.TW'
bt = Backtest(dfs[s], Strategy)
r = bt.run()
bt.plot()</code></pre>



<p>法諾亞最近五筆交易，使用此策略，勝率為80％！雖然大波段沒抱到，但是也賺了4～50％，很不錯了啦（畢竟是逆勢策略）！不過當前的股價，由於均線沒有死亡交叉，所以對此策略來說，價格偏高，不適合買入，大家可以隨時跑程式，來觀察是否有生技股有均線死亡交叉，都會是很好的買入時機喔（根據歷史統計來說）！這就是簡單但又不簡單的均線最佳化策略！</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="581" src="https://www.finlab.tw/wp-content/uploads/2020/08/Screen-Shot-2020-08-06-at-9.12.55-AM-1024x581.png" alt="Screen Shot 2020 08 06 at 9.12.55 AM" class="wp-image-2068" srcset="https://www.finlab.tw/wp-content/uploads/2020/08/Screen-Shot-2020-08-06-at-9.12.55-AM-1024x581.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/08/Screen-Shot-2020-08-06-at-9.12.55-AM-300x170.png 300w, https://www.finlab.tw/wp-content/uploads/2020/08/Screen-Shot-2020-08-06-at-9.12.55-AM-768x436.png 768w, https://www.finlab.tw/wp-content/uploads/2020/08/Screen-Shot-2020-08-06-at-9.12.55-AM-1536x872.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/08/Screen-Shot-2020-08-06-at-9.12.55-AM-2048x1163.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="生技股如何安全買？逆勢爆賺策略分享 10"></figure>



<p>接下來一系列，我會介紹加密貨幣。其實早在 2020 年 04 月 20 號，我就低調開始撰寫一系列 BTC 的文章，當時價格為 6838 BTC/USDT，現在已經破 12000了！要是你那時候有追蹤 finlab，就算放著不動，可能已經獲利 70％。</p>



<p>我自己也有不少資產放在 BTC，並且用 Python 自動交易，因為 BTC 是新商品，算是非效率市場（個人回測時的感覺），尤其是其他的加密貨幣（alternative coin 簡稱 altcoin），用量化交易操作，就像就是用坦克跟原始人打仗一樣！現在開始，使用量化投資做低風險的BTC交易，為時不晚，下一篇，我們從加密貨幣的基本面開始講起。可以<a href="https://www.facebook.com/finlab.python" class="rank-math-link" target="_blank" rel="noopener">追蹤 finlab 粉絲團，收到最新的文章</a>喔！</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/python-biotech-stock-portfolio/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2039</post-id>	</item>
		<item>
		<title>Python 低風險高報酬投資組合</title>
		<link>https://www.finlab.tw/low-risk-fft-spy-strategy/</link>
					<comments>https://www.finlab.tw/low-risk-fft-spy-strategy/#respond</comments>
		
		<dc:creator><![CDATA[FinLab - 韓承佑]]></dc:creator>
		<pubDate>Wed, 22 Jul 2020 23:20:00 +0000</pubDate>
				<category><![CDATA[財經PYTHON教學]]></category>
		<category><![CDATA[PYTHON]]></category>
		<category><![CDATA[程式交易]]></category>
		<category><![CDATA[簡易策略]]></category>
		<guid isPermaLink="false">http://34.96.136.135/?p=932</guid>

					<description><![CDATA[投資可以很複雜，超多的商品選擇，分批持有買賣點設定等等，但是每天花這麼多心力，真的有比大盤好嗎？
其實投資也可以很簡單的，我們可以稍微更智慧一點，投資「大盤」跟「公債」！]]></description>
										<content:encoded><![CDATA[
<p>投資可以很複雜，超多的商品選擇，分批持有買賣點設定等等，但是每天花這麼多心力，真的有比大盤好嗎？<br>其實投資也可以很簡單的，我們可以稍微更智慧一點，投資「大盤」跟「公債」！<a href="https://www.finlab.tw/low-risk-fft-spy-strategy/big.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="989" height="491" src="http://34.96.136.135/wp-content/uploads/2020/07/big.png" alt="big" class="wp-image-933" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/big.png 989w, https://www.finlab.tw/wp-content/uploads/2020/07/big-300x149.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/big-768x381.png 768w" sizes="(max-width: 989px) 100vw, 989px" title="Python 低風險高報酬投資組合 11"></figure></div>



<p>今天就是要來介紹一個簡單的策略，<br>此策略的 sharpe ratio 高達 1.2 非常高，但其實原理並不難，也不需要太多的技巧<br>用一句話就講完了：</p>



<h3 id="將資產分兩半：SPY-跟-20年公債">將資產分兩半：SPY 跟 20年公債</h3>



<ul><li>一半投資「標準普爾500指數ETF」</li><li>一半投資「iShares 20年期以上美國公債ETF〈TLT〉」</li></ul>



<p>這種策略的大致上的原理就是「找兩個相關係數為負，且會隨時間增值的商品」<br>這樣的策略效果究竟如何呢？一半一半？這樣的比例真的好嗎？<br>我們可以用<a href="https://www.finlab.tw/ffn-intro/">上一篇文章 ffn python package</a>，來做回測看看效果如何</p>



<p>大家可以點<a href="https://colab.research.google.com/drive/1rR3fvVliWQ1Q93xjO9qpd-nOhzfvWY2a" rel="noreferrer noopener" target="_blank">這裡到程式碼，並且線上打扣！</a></p>



<h3 id="安裝-ffn：">安裝 ffn：</h3>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">!pip install ffn</code></pre>



<h3 id="獲取資料">獲取資料</h3>



<pre class="wp-block-code"><code class="">import ffn
prices = ffn.get("spy,tlt", )
prices.plot()</code></pre>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="444" src="http://34.96.136.135/wp-content/uploads/2020/07/spytlt-1024x444.png" alt="spytlt" class="wp-image-934" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/spytlt-1024x444.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/spytlt-300x130.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/spytlt-768x333.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/spytlt.png 1159w" sizes="(max-width: 1024px) 100vw, 1024px" title="Python 低風險高報酬投資組合 12"></figure></div>



<p><a href="https://www.finlab.tw/low-risk-fft-spy-strategy/spytlt.png"></a>仔細看這兩個指數確實有呈現一點負相關，特別是 SPY 下跌的時候，TLT會些微的上漲</p>



<h3 id="將資產分一半，投資回測">將資產分一半，投資回測</h3>



<p>這邊我們只拿「SPY」跟「TLT」，其實有很多的策略組合也會有「石油」、「新興市場」、「黃金」等等<br>大家到時候也可以去自行變化，找出比較好的投資組合</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">prices.rebase().mean(axis=1).plot()</code></pre>



<p>雖然比直接投資sp500還要差，但是整體來說看起來更穩定的感覺<br>究竟我們有沒有辦法橫兩，這樣的組合是否是最好的呢？</p>



<p>不然我們就暴力計算一下，將幾種組合都寫出來：</p>



<figure class="wp-block-table"><table><thead><tr><th>策略</th><th>配置1</th><th>配置2</th><th>配置3</th><th>…</th><th>配置10</th><th>配置11</th></tr></thead><tbody><tr><td>SPY</td><td>0</td><td>0.1</td><td>0.2</td><td>…</td><td>0.9</td><td>1.0</td></tr><tr><td>TLT</td><td>1.0</td><td>0.9</td><td>0.8</td><td>…</td><td>0.1</td><td>0</td></tr></tbody></table></figure>



<p>那我們把這幾種配置都回測一次試試看：</p>



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

strategies = {}

for i in np.arange(0, 1.1, 0.1):
    title = "spy: %.1f | tlt: %.1f" % (i, 1-i)
    strategies[title] = (prices.rebase() * [i, 1-i]).mean(axis=1).rebase()

strategies = pd.DataFrame(strategies)

strategies.plot()</code></pre>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="444" src="http://34.96.136.135/wp-content/uploads/2020/07/combination-1024x444.png" alt="combination" class="wp-image-935" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/combination-1024x444.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/combination-300x130.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/combination-768x333.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/combination.png 1159w" sizes="(max-width: 1024px) 100vw, 1024px" title="Python 低風險高報酬投資組合 13"></figure></div>



<p><a href="https://www.finlab.tw/low-risk-fft-spy-strategy/combination.png"></a></p>



<p>可以發現TLT比重比較重，則報酬率比較低，<br>SPY比重比較重，則報酬率比較高<br>除了報酬率以外，我們還有哪些指標可以來量化這些策略的績效呢？</p>



<p>我們可以用 ffn 提供的&nbsp;<code>calc_stats</code>&nbsp;來計算：</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">stats = strategies.calc_stats()
stats = pd.DataFrame(
    {
        name:pd.Series({key:getattr(pf, key) for key in dir(pf) if isinstance(getattr(pf, key), float)}, name=name) 
        for name,pf in stats.items()
    }).transpose()

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



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="346" src="http://34.96.136.135/wp-content/uploads/2020/07/performance-2-1024x346.png" alt="performance 2" class="wp-image-937" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/performance-2-1024x346.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/performance-2-300x101.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/performance-2-768x259.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/performance-2-1536x518.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/performance-2-2048x691.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="Python 低風險高報酬投資組合 14"></figure></div>



<p><a href="https://www.finlab.tw/low-risk-fft-spy-strategy/performance.png"></a>這樣我們就有一張策略的績效總表了，這張 dataframe 非常大一張，要怎麼看有哪些分析數據呢？<br>我們可以利用&nbsp;<code>stats.columns</code>&nbsp;查看可以比較的策略績效指標：</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">stats.columns</code></pre>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="307" src="http://34.96.136.135/wp-content/uploads/2020/07/plist-1024x307.png" alt="plist" class="wp-image-938" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/plist-1024x307.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/plist-300x90.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/plist-768x230.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/plist.png 1380w" sizes="(max-width: 1024px) 100vw, 1024px" title="Python 低風險高報酬投資組合 15"></figure></div>



<p><a href="https://www.finlab.tw/low-risk-fft-spy-strategy/plist.png"></a>我們可以利用&nbsp;<code>.plot</code>&nbsp;將不同的績效比較給畫出來，例如：</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">stats['daily_sharpe'].plot(rot=10, color='blue')
stats['monthly_vol'].plot(rot=10, color='red', secondary_y=True)</code></pre>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="453" src="http://34.96.136.135/wp-content/uploads/2020/07/volsp-1024x453.png" alt="volsp" class="wp-image-939" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/volsp-1024x453.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/volsp-300x133.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/volsp-768x340.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/volsp.png 1217w" sizes="(max-width: 1024px) 100vw, 1024px" title="Python 低風險高報酬投資組合 16"></figure></div>



<p><a href="https://www.finlab.tw/low-risk-fft-spy-strategy/volsp.png"></a>上圖中有兩線，</p>



<ul><li>藍色的是&nbsp;<a href="https://www.finlab.tw/Python%E6%96%B0%E6%89%8B%E6%95%99%E5%AD%B8%EF%BC%9A%E9%A2%A8%E9%9A%AA%E8%88%87%E5%A0%B1%E9%85%AC/">sharpe ratio</a>，代表 「報酬」/ 「風險」 的比例</li><li>紅色的是「每月報酬」的波動程度，</li></ul>



<p>可以發現，風險報酬比（藍色）最佳位置，剛好就是在 「一半一半」的資產配置上<br>對應到「每月報酬」最穩定的，也剛好就是在「一半一半」的資產配置上</p>



<p>這說明了投資好像不用搞太多花俏的東西，直要簡單粗暴就是最好的！<br>上面的 sharpe ratio 是用簡單的「每天」的 sharpe ratio，</p>



<p>不過假如你是投資長線的話，其實不用太計較每天的 sharpe，應該要看的是每個月，甚至是每年的：</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">stats['yearly_sharpe'].plot()
stats['monthly_sharpe'].plot()
stats['daily_sharpe'].plot()</code></pre>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="443" src="http://34.96.136.135/wp-content/uploads/2020/07/srs-1024x443.png" alt="srs" class="wp-image-940" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/srs-1024x443.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/srs-300x130.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/srs-768x332.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/srs.png 1212w" sizes="(max-width: 1024px) 100vw, 1024px" title="Python 低風險高報酬投資組合 17"></figure></div>



<p><a href="https://www.finlab.tw/low-risk-fft-spy-strategy/srs.png"></a>假如我們不要「每天」跟報酬率計較，而改成是「每個月」或「每年」的時候，<br>由上圖中可以知道，SPY 比例從 0.5~0.7 都是不錯的配置方式<br>不過這 1.3 以上的 sharpe ratio 其實算是滿驚人的（不過沒算上金融海嘯，所以…稍微不準）<br>我平常可能大費周章，搞了半天也弄不出這麼好的資產配置XD</p>



<p>接下來看平均年報酬率：</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">stats['yearly_mean']</code></pre>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="658" height="430" src="http://34.96.136.135/wp-content/uploads/2020/07/returns.png" alt="returns" class="wp-image-941" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/returns.png 658w, https://www.finlab.tw/wp-content/uploads/2020/07/returns-300x196.png 300w" sizes="(max-width: 658px) 100vw, 658px" title="Python 低風險高報酬投資組合 18"></figure></div>



<p><a href="https://www.finlab.tw/low-risk-fft-spy-strategy/returns.png"></a></p>



<p>還可以！你想想看完全不看盤得到5%以上的獲利，已經非常爽了！<br>老實說這樣的組合還有很多可以玩的地方，例如加入定期權益平衡，<br>也就是每個月去重新調整持股比例，漲多的賣，跌多的買，重新將權重調整回原點。<br>我們下次會來介紹進化版策略的回測，讓這個簡單的策略再進化<br>可以定期追蹤 FinLab 一起來研究投資這件事情吧！</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/low-risk-fft-spy-strategy/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">932</post-id>	</item>
		<item>
		<title>加速度指標選股：免費Python實做教學看這裡！</title>
		<link>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/</link>
					<comments>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/#respond</comments>
		
		<dc:creator><![CDATA[FinLab - 韓承佑]]></dc:creator>
		<pubDate>Wed, 22 Jul 2020 23:05:39 +0000</pubDate>
				<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=806</guid>

					<description><![CDATA[今天終於要來介紹加速度指標，這個指標的用處，在於可以篩選出「止跌回升」或「加速往上漲」的股票，經過回測驗證是有效的。搭配其他指標，可以獲得約20％的年報酬率。接下來我們就來用 python 實做它吧！]]></description>
										<content:encoded><![CDATA[
<p>今天終於要來介紹加速度指標，這個指標的用處，在於可以篩選出「止跌回升」或「加速往上漲」的股票，經過<a href="https://www.finlab.tw/%E5%8A%A0%E9%80%9F%E5%BA%A6%E6%8C%87%E6%A8%99-%E5%8A%A0%E9%80%9F%E4%BD%A0%E7%9A%84%E7%8D%B2%E5%88%A9">回測驗證</a>是有效的。搭配其他指標，可以獲得約20％的年報酬率。接下來我們就來用 python 實做它吧！<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/thumbnail.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/thumbnail-2-3-1024x664.png" alt="thumbnail 2 3" class="wp-image-808" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-2-3-1024x664.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-2-3-300x194.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-2-3-768x498.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-2-3-1536x996.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-2-3.png 1606w" sizes="(max-width: 1024px) 100vw, 1024px" title="加速度指標選股：免費Python實做教學看這裡！ 19"></figure></div>



<p>這個 blog 會永久推出免費的教學，讓大家可以免費的學習 python 又賺錢，學習程式語言是很多人憧憬的目標，但是常常會有學了不知道拿來做什麼？要是寫程式不只能在工作上增加效率，還能幫你挑股票賺錢，那還有什麼理由不學習呢？</p>



<p>我喜歡寫程式，也希望可以做出很好的工具，幫助到大家，帶著這個初衷，我創立了finlab 並且持續到了現在（不過中間因為博士班論文所以暫停了一段時間）。與其販賣選股軟體，我們分享代碼，讓大家自己零成本 DIY，假如想要支持我們，可以考慮我們的<a href="https://hahow.in/cr/python-finance" rel="noreferrer noopener" target="_blank">影音課程</a>，獲得完整的 python 選股知識跟大量實用代碼。</p>



<p>好了廢話不多說，開始今天的 python 程式碼吧！</p>



<h3 id="製作時間序列">製作時間序列</h3>



<p>首先我們必須先做出時間序列，時間序列其實就是一條條股價隨時間的變化圖，有點像是K線圖，我們習慣將這些資料整理成以下的樣貌：<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/close.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/close-1024x325.png" alt="close" class="wp-image-809" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/close-1024x325.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/close-300x95.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/close-768x244.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/close-1536x487.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/close-2048x650.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="加速度指標選股：免費Python實做教學看這裡！ 20"></figure></div>



<p>要如何獲得此資料結構呢？</p>



<ol><li>假如您沒有購買課程的話，可以參考<a href="https://www.finlab.tw/Python-%E6%99%82%E9%96%93%E5%BA%8F%E5%88%97%E5%AF%A6%E4%BD%9C%EF%BC%81">這篇文章來免費獲得時間序列資料</a>，調整當中的參數，獲得至少200天的收盤價喔！</li><li>假如您已經有課程中的代碼，就變得很簡單，只需要：</li></ol>



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

close = data.get('收盤價', 200)</code></pre>



<p>就可以獲得兩百天內的所有上市股價資料。</p>



<p>在這個階段完成後，我們會有一個&nbsp;<code>close</code>&nbsp;的 variable，裡面的資料結構就如上圖一樣，是一個&nbsp;<code>dataframe</code>&nbsp;而其中就是一條條時間序列，每一檔股票的收盤價。</p>



<h3 id="撰寫加速度指標">撰寫加速度指標</h3>



<p>加速度指標的原理，可以參考</p>



<ul><li><a href="https://www.finlab.tw/%E7%B0%A1%E6%98%93%E7%9A%84%E5%A4%96%E8%B3%87-%E5%9F%BA%E6%9C%AC%E9%9D%A2%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%8A%A0%E9%80%9F%E4%BD%A0%E7%9A%84%E7%8D%B2%E5%88%A9">加速度指標回測</a></li></ul>



<p>簡單來說，加速度指標，其實就是看均線的曲率是正負，來決定是否買賣，但是由於股價的雜訊太大了，與其用微分的，我們提供一個比較簡單的方式，來判斷曲率的正負：</p>



<p>(n天前 + 當天)/2 &gt; n/2天前 的k天均線</p>



<p>我們把以上這個判斷式寫成代碼：</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">close60 = close.rolling(60, min_periods=10).mean()

def rising_curve(n):
    return (close60.iloc[-n] + close60.iloc[-1]) / 2 &gt; close60.iloc[-int((n+1)/2)]

</code></pre>



<p>以上的代碼中，第一行，我們創建了<code>close60</code>這個<code>variable</code>，裡面的資料就是每檔股票60天的均線的數值。</p>



<p>接下來，在第三行中，我們定義了一個<code>function</code>叫做<code>rising_curve</code>，來判斷條件是否符合，<br>第四行，就是最重要的判斷式：</p>



<p>其中我們只用到了<code>iloc(k)</code>這個<code>method</code>，這個<code>method</code>是將<code>close60</code>中第<code>k</code>條<code>row</code>給拿出來的意思。而<code>k</code>可以是正的，代表從<code>dataframe</code>的第0條row開始數，也可以是負的，代表從&nbsp;<code>dataframe</code>的最後一條row倒著數。</p>



<h3 id="試用看看">試用看看</h3>



<p>接下來我們就可以呼叫這個rising_curve，來看哪些股票符合這個條件：</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">rising_curve(10)</code></pre>



<p>以上這行就是判斷10日內的取率是多少，會得出以下的結果：<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/rising_curve.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="286" src="http://34.96.136.135/wp-content/uploads/2020/07/rising_curve-1024x286.png" alt="rising curve" class="wp-image-810" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/rising_curve-1024x286.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/rising_curve-300x84.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/rising_curve-768x214.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/rising_curve-1536x429.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/rising_curve-2048x572.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="加速度指標選股：免費Python實做教學看這裡！ 21"></figure></div>



<p>代表哪些檔股票符合條件，而哪些不符合條件。</p>



<h3 id="組裝策略">組裝策略</h3>



<p>接下來就到了多個策略組合的時候了，<a href="https://www.finlab.tw/%E5%8A%A0%E9%80%9F%E5%BA%A6%E6%8C%87%E6%A8%99-%E5%8A%A0%E9%80%9F%E4%BD%A0%E7%9A%84%E7%8D%B2%E5%88%A9">前一篇文章</a>有說過，必須要用多次的rising_curve來判斷不同週期下，是否都是符合條件！</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">rising = (
    rising_curve(5) &amp;
    rising_curve(10) &amp; 
    rising_curve(20) &amp;
    rising_curve(60) &amp;
    rising_curve(30) &amp;
    rising_curve(40) &amp;
    rising_curve(50) &amp;
    (close.iloc[-1] &gt; close60.iloc[-1])
)

print(rising[rising])</code></pre>



<p>以上，第2～9行，我們將所有的條件做交集（&amp;），代表必須要全部的條件都符合，才能被選入清單，我們以非常嚴苛的方式，來判斷股價的曲率。<br>最後一行，我們使用<code>rising[rising]</code>，這個意思是，從<code>rising</code>這條序列中，選取<code>rising</code>為&nbsp;<code>True</code>的股票，忽略<code>False</code>的股票。</p>



<p>最後得出了一串清單，代表符合所有條件的股票代號：<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/and.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="378" src="http://34.96.136.135/wp-content/uploads/2020/07/and-1024x378.png" alt="and" class="wp-image-811" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/and-1024x378.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/and-300x111.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/and-768x283.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/and-1536x567.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/and-2048x756.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="加速度指標選股：免費Python實做教學看這裡！ 22"></figure></div>



<h3 id="選股個股概覽">選股個股概覽</h3>



<p>我們將選出來的股票畫出來，來瞭解這些股票的特性，下圖中，黃色的為股價，而藍色的為均線，我們可以發現這些股票的特性，就是均線會呈現圓弧型：<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/stocks.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="887" src="http://34.96.136.135/wp-content/uploads/2020/07/stocks-2-1024x887.png" alt="stocks 2" class="wp-image-813" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/stocks-2-1024x887.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/stocks-2-300x260.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/stocks-2-768x665.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/stocks-2-1536x1331.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/stocks-2.png 1810w" sizes="(max-width: 1024px) 100vw, 1024px" title="加速度指標選股：免費Python實做教學看這裡！ 23"></figure></div>



<p>可以看到大部分都是抓出止跌回漲的股票居多，加速度指標可以抓出兩種股票：</p>



<ol><li>止跌</li><li>起漲<br>至於要更細部的設定，就留給各位看官來實做了。</li></ol>



<p>假如將以上代碼的不等式反過來用，也可以抓出股票的賣點，進而抓出止漲的股票，我發現加速度指標拿來抓賣點，搭配一些技術指標效果非常好，可以試試看！</p>



<h3 id="今天的重點整理">今天的重點整理</h3>



<ol><li>加速度指標實做</li><li>利用「iloc」選取特定的row</li><li>利用「&amp;」來做條件交集，篩選股票</li></ol>
]]></content:encoded>
					
					<wfw:commentRss>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/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">806</post-id>	</item>
		<item>
		<title>加速度指標：歷史年報酬20％的策略</title>
		<link>https://www.finlab.tw/%e5%8a%a0%e9%80%9f%e5%ba%a6%e6%8c%87%e6%a8%99-%e5%8a%a0%e9%80%9f%e4%bd%a0%e7%9a%84%e7%8d%b2%e5%88%a9/</link>
					<comments>https://www.finlab.tw/%e5%8a%a0%e9%80%9f%e5%ba%a6%e6%8c%87%e6%a8%99-%e5%8a%a0%e9%80%9f%e4%bd%a0%e7%9a%84%e7%8d%b2%e5%88%a9/#respond</comments>
		
		<dc:creator><![CDATA[FinLab - 韓承佑]]></dc:creator>
		<pubDate>Wed, 22 Jul 2020 07:05:38 +0000</pubDate>
				<category><![CDATA[選股策略]]></category>
		<category><![CDATA[歷史回測]]></category>
		<category><![CDATA[程式交易]]></category>
		<category><![CDATA[簡易策略]]></category>
		<guid isPermaLink="false">http://34.96.136.135/?p=765</guid>

					<description><![CDATA[之前分享加速度指標，讓大家找出股價正在加速向上的股票，然而並沒有說明怎麼搭配，本篇文章就是在提供大家一個例子，我發現這個指標可以用在非常多種不同的程式交易策略上，績效很不錯，但是有訣竅。]]></description>
										<content:encoded><![CDATA[
<p>之前分享加速度指標，讓大家找出股價正在加速向上的股票，然而並沒有說明怎麼搭配，本篇文章就是在提供大家一個例子，我發現這個指標可以用在非常多種不同的程式交易策略上，績效很不錯，但是有訣竅。</p>



<h3 id="加速度指標回顧">加速度指標回顧</h3>



<p>加速度指標，其實就是看均線的曲率是正的還是負的，但是由於股價的雜訊太大了，與其用微分的，我們提供一個比較間單的方式，來判斷曲率的正負：</p>



<p>(n天前 + 當天)/2 &gt; n/2天前 的k天均線</p>



<p>我們就說它正在加速，是很不錯的持有標的，至於背後的原理可以參考<a href="https://www.finlab.tw/%E7%B0%A1%E6%98%93%E7%9A%84%E5%A4%96%E8%B3%87-%E5%9F%BA%E6%9C%AC%E9%9D%A2%E7%AD%96%E7%95%A5/">之前的文章</a>！但是加速度指標還是有其弱點，必須要搭配其他指標，才能發揮作用</p>



<h3 id="加速度指標的癥結1：初始速度">加速度指標的癥結1：初始速度</h3>



<p>加速度最大的癥結就在於，你不知道其速度！例如現在有兩個人賽跑，其中一個人加速度是正的，另一個人是負的，究竟誰會先抵達終點？</p>



<p>答案是不知道</p>



<p>因為你不知道起始速度是多少，假如有一個人根本逆著終點跑，就算他加速多快都沒有用！<br>就像有一支股票，只要止跌，其曲率就會看起來是正的，但是止跌的股票還會有一段震蕩，甚至有續跌的可能，所以買剛止跌的時候就買是沒有意義的，我們應該是要買剛起漲的股票才對～</p>



<p>下圖就是曲率正負和股價之間的分類，曲率為正時，股價有兩種可能：止跌、起漲。曲率為負時，股價也有兩種可能：止漲、起跌。<a href="https://www.finlab.tw/%E5%8A%A0%E9%80%9F%E5%BA%A6%E6%8C%87%E6%A8%99-%E5%8A%A0%E9%80%9F%E4%BD%A0%E7%9A%84%E7%8D%B2%E5%88%A9/cases.jpg"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="441" height="193" src="http://34.96.136.135/wp-content/uploads/2020/07/cases.jpg" alt="cases" class="wp-image-766" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/cases.jpg 441w, https://www.finlab.tw/wp-content/uploads/2020/07/cases-300x131.jpg 300w" sizes="(max-width: 441px) 100vw, 441px" title="加速度指標：歷史年報酬20％的策略 24"></figure></div>



<p>當我們使用曲率為正的條件時，就會發現我們選到「止跌」或「起漲」股，然而我們真正是想選取「起漲」股，假如我們選了起漲股，那賣出時，曲率為負，自然就是止漲，而不會選到起跌股。</p>



<h3 id="解決方法">解決方法</h3>



<p>所以我們加上一個股價的向上指標即可，這邊你可以使用KD值的K&gt;D（參數：240、120、120），來找出股價向上的股票，這樣加速度指標才有意義喔！</p>



<p>當然有很多種趨勢型指標都可以拿來用用看～我相信一定會有更好的選項，這邊只是舉例。</p>



<h3 id="加速度指標的癥結2：採樣點太少">加速度指標的癥結2：採樣點太少</h3>



<p>基本上加速度指標就是三個點比大小，採樣的點非常少，就像電影只看開頭和結尾，想要把中間劇情都猜出來，是不太容易的。</p>



<p>下圖左方的例子中，我們只用了三個點來衡量曲率是正的還是負的（或是你可以想像是凹的還是凸的），可以發現就算曲率是正的，也有可能並不是我們想要的股價曲線。其中，紅色的股價是我們比較希望的，而不是綠色的。</p>



<h3 id="解決方法：多增加條件">解決方法：多增加條件</h3>



<p>所以我們可以測試多個點，右圖我們用「兩組」三個點來觀察曲率（藍色跟黃色）可以發現，右上方得圖，不論用藍色的三個點或是黃色的三個點，曲率都是正的，而右下角的圖中，雖然用藍色的點看，曲率是正的，但是用黃色的點看的話，曲率是負的，於是就可以將這類型的股價給排除。<a href="https://www.finlab.tw/%E5%8A%A0%E9%80%9F%E5%BA%A6%E6%8C%87%E6%A8%99-%E5%8A%A0%E9%80%9F%E4%BD%A0%E7%9A%84%E7%8D%B2%E5%88%A9/samples.jpg"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="626" height="445" src="http://34.96.136.135/wp-content/uploads/2020/07/samples.jpg" alt="samples" class="wp-image-767" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/samples.jpg 626w, https://www.finlab.tw/wp-content/uploads/2020/07/samples-300x213.jpg 300w" sizes="(max-width: 626px) 100vw, 626px" title="加速度指標：歷史年報酬20％的策略 25"></figure></div>



<p>加速度指標要決定一個變數：n，是一個時間長度。我們可以列出多個n值不同加速度指標，這些加速度指標都符合時，我們再進行買入的動作。</p>



<p>我們讓n設定為50、20、15、10，一次增加四個加速度指標，來監控60天均線的曲率<br>賣出條件是n=30這個指標不符合條件時，於隔天剃除</p>



<h3 id="加速度指標的癥結3：沒有考慮公司營運狀況">加速度指標的癥結3：沒有考慮公司營運狀況</h3>



<p>加速度指標為技術指標，並沒有考慮財報面，只要稍微判斷一下財報的狀況，就可以選出很不錯的股票～</p>



<h3 id="解決辦法">解決辦法</h3>



<p>由於財報並不是這個策略的主角，我只用 ROE &gt; 3 這樣的條件就很足夠了</p>



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



<p>我們敘述了加速度指標的不足，並且有根據的介紹怎麼樣新增條件，來完善我們的策略，以下就是這個策略的績效：<a href="https://www.finlab.tw/%E5%8A%A0%E9%80%9F%E5%BA%A6%E6%8C%87%E6%A8%99-%E5%8A%A0%E9%80%9F%E4%BD%A0%E7%9A%84%E7%8D%B2%E5%88%A9/eq.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="618" height="357" src="http://34.96.136.135/wp-content/uploads/2020/07/eq-14.png" alt="eq 14" class="wp-image-768" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/eq-14.png 618w, https://www.finlab.tw/wp-content/uploads/2020/07/eq-14-300x173.png 300w" sizes="(max-width: 618px) 100vw, 618px" title="加速度指標：歷史年報酬20％的策略 26"></figure></div>



<p>藍色的為不添加手續費，而紅色的則是添加了手續費～效果滿不錯的！</p>



<p>這些參數我都沒有做任何優化，當然這些參數的選擇上還是得靠經驗，然而假如對於這些數字指標比較熟悉，大概就可以抓出有效的區間，進而選出好的標的。經過簡單的優化，甚至是增刪條件，都可以讓績效再提升。</p>



<p>下圖可以看到，最大下跌幅度在金融海嘯的時候莫名的高，必須要注意一下～～<a href="https://www.finlab.tw/%E5%8A%A0%E9%80%9F%E5%BA%A6%E6%8C%87%E6%A8%99-%E5%8A%A0%E9%80%9F%E4%BD%A0%E7%9A%84%E7%8D%B2%E5%88%A9/mdd.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="624" height="172" src="http://34.96.136.135/wp-content/uploads/2020/07/mdd.png" alt="mdd" class="wp-image-769" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/mdd.png 624w, https://www.finlab.tw/wp-content/uploads/2020/07/mdd-300x83.png 300w" sizes="(max-width: 624px) 100vw, 624px" title="加速度指標：歷史年報酬20％的策略 27"></figure></div>



<p>對了，補充一下，我們的新平台悄悄上線，目前正在測試中，此策略的選股清單可以免費觀看：<a href="https://ai.finlab.tw/strategy/%E5%8A%A0%E9%80%9F%E5%BA%A6%E9%A0%86%E5%8B%A2%E7%AD%96%E7%95%A5" rel="noreferrer noopener" target="_blank">加速度策略</a></p>



<p>這邊只是給大家一個雛形，可以將加速度指標用在股價，甚至是其他的財務數據上（月營收？），感覺都會滿有趣的！</p>



<p>假如你想用Python來實做，可以參考下一篇：<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/">實做加速度指標</a>！</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/%e5%8a%a0%e9%80%9f%e5%ba%a6%e6%8c%87%e6%a8%99-%e5%8a%a0%e9%80%9f%e4%bd%a0%e7%9a%84%e7%8d%b2%e5%88%a9/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">765</post-id>	</item>
		<item>
		<title>如何定義KD鈍化？</title>
		<link>https://www.finlab.tw/kd1/</link>
					<comments>https://www.finlab.tw/kd1/#respond</comments>
		
		<dc:creator><![CDATA[FinLab - 韓承佑]]></dc:creator>
		<pubDate>Wed, 22 Jul 2020 07:05:02 +0000</pubDate>
				<category><![CDATA[技術面]]></category>
		<category><![CDATA[如何買股票]]></category>
		<category><![CDATA[歷史回測]]></category>
		<category><![CDATA[簡易策略]]></category>
		<category><![CDATA[選股策略]]></category>
		<guid isPermaLink="false">http://34.96.136.135/?p=529</guid>

					<description><![CDATA[今天先來看一下KD值好了，畢竟都還沒有看到太多指標相關的文章，其實KD值是非常簡單的，但在這邊我不想要介紹公式，因為太無聊了，而且每次看每次忘，我只想介紹如何看KD，以及參數如何設定。]]></description>
										<content:encoded><![CDATA[
<p>謝謝大家的鼓勵，最近有點太忙了，加上懶惰蟲上身，上禮拜中斷了XD，這禮拜會繼續加油！希望可以知道大家最想要看什麼，有看到留言說希望可以增 python 有關的教學文！收到了，甚至可以更仔細說明，例如爬哪個網站之類的，我都可以幫你寫喔！大家想要看什麼可以在下面留言！</p>



<p>今天先來看一下KD值好了，畢竟都還沒有看到太多指標相關的文章，其實KD值是非常簡單的，但在這邊我不想要介紹公式，因為太無聊了，而且每次看每次忘，我只想介紹如何看KD，以及參數如何設定：</p>



<h3 id="KD-的意義">KD 的意義</h3>



<p>KD就是像坊間說的，兩條線，K跟D，一條反應較快，一條慢，都介於0～100之間。其意義在於股票在n天之內的相對位置，相對位置就是指n天內的最高最低，將當前的股價做normalize。</p>



<p>給一個簡單的例子，例如今天全班考試，有人拿30分，請問他考的好不好？</p>



<p>答案是：不知道，因為沒有辦法比較，說不定考卷很難，30分就是全班最高分了！要是考卷出太難，大家的成績介於10～30之間，那老師就可以做 normalize 讓成績分佈好看一點：</p>



<p>新成績 = ( 成績 &#8211; 10 ) / (30 &#8211; 10)</p>



<p>這樣子，考最好的人就是100分，而考最爛的人就是0分，這個就是KD指標的意義，而每個學生的成績，就是每日的收盤價。</p>



<p>最後我們將 新成績 對時間平滑一次，變成K值，再對K值平滑一次，變成D值。</p>



<h3 id="KD-的參數">KD 的參數</h3>



<p>介紹完之後，K D 指標的參數就很好理解了：</p>



<ol><li>9天：只考慮9天內的最高最低</li><li>3天：K的平滑</li><li>3天：D的平滑</li></ol>



<p>平滑數字越大，數字變動越慢，雜訊越少<br>平滑數字越小，數字變動越快，雜訊越多</p>



<p>我們用台積電為例子：<a href="https://www.finlab.tw/KD1/tsmc.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="624" height="299" src="http://34.96.136.135/wp-content/uploads/2020/07/tsmc-1.png" alt="tsmc 1" class="wp-image-530" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/tsmc-1.png 624w, https://www.finlab.tw/wp-content/uploads/2020/07/tsmc-1-300x144.png 300w" sizes="(max-width: 624px) 100vw, 624px" title="如何定義KD鈍化？ 28"></figure></div>



<p>以上就是用正統的參數：9、3、3的KD指標（橘色、綠色），紫色是股價，可以看到KD值低檔交叉，算是好買點，最近就等著台積點低於20 XDD，（隨便說的，不是投資建議），我們試著換一個參數（9、6、6）看看：<a href="https://www.finlab.tw/KD1/tsmc2.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="624" height="299" src="http://34.96.136.135/wp-content/uploads/2020/07/tsmc2.png" alt="tsmc2" class="wp-image-531" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/tsmc2.png 624w, https://www.finlab.tw/wp-content/uploads/2020/07/tsmc2-300x144.png 300w" sizes="(max-width: 624px) 100vw, 624px" title="如何定義KD鈍化？ 29"></figure></div>



<p>可以看到曲線比較平滑一點，且K跟D差距比較明顯，相較於第一張圖，8月初比較不會有雜訊，但是反應變慢很多。</p>



<h3 id="KD-坊間策略">KD 坊間策略</h3>



<p>大家都說<br>K超越D時，代表黃金交叉，可以買進<br>K落於D時，代表死亡交叉，可以賣出</p>



<p>真的是這樣嗎？讓我們來看看：</p>



<p>黃金交叉買，死亡交叉賣：</p>



<p>參數（9,3,3）勝率：0.386<br>參數（45,15,15）勝率：0.407<br>參數（180,60,60）勝率：0.364</p>



<p>以下是這三個參數的獲利曲線：<a href="https://www.finlab.tw/KD1/summary.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="202" src="http://34.96.136.135/wp-content/uploads/2020/07/summary-1024x202.png" alt="summary" class="wp-image-532" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/summary-1024x202.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/summary-300x59.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/summary-768x152.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/summary.png 1211w" sizes="(max-width: 1024px) 100vw, 1024px" title="如何定義KD鈍化？ 30"></figure></div>



<p>結果好像不太好，看來真的不太能直接用，尤其短週期的KD，進出太平凡，導致手續費飆高，根本就是一直賠錢（紅色），用長週期的KD才稍微好轉。而藍線（不考慮手續費），則是中間的（類似週KD）表現比較好，但總之效果都不太好XD。</p>



<h3 id="KD-鈍化">KD 鈍化</h3>



<p>另外一個網路上的偏方：KD鈍化，但大家沒有定義什麼時候賣，也沒有數據顯示幾天賣比較好，於是我們就來做個實驗：</p>



<p>買入條件：k, d （參數為 9，9，3）都大於80，至少 n 天則買入<br>賣出條件：m 天賣出</p>



<p>當然還有很多種買法我沒測過，有興趣的話可以在下面留言，我幫你測！<a href="https://www.finlab.tw/KD1/kdbest.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="360" height="323" src="http://34.96.136.135/wp-content/uploads/2020/07/kdbest.png" alt="kdbest" class="wp-image-533" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/kdbest.png 360w, https://www.finlab.tw/wp-content/uploads/2020/07/kdbest-300x269.png 300w" sizes="(max-width: 360px) 100vw, 360px" title="如何定義KD鈍化？ 31"></figure></div>



<p>色溫越暖，代表10年獲利越高，這張圖的 x軸 為 m 天， y軸 為 KD大於80 至少 n 天，可以發現，幾乎十幾個交易日賣出是最保險的，而5~6天連續高檔，代表鈍化，會有比較好的效果，第十天突然異軍突起，超紅，可能有些股票末路狂飆吧。。。</p>



<p>然而上述是不考慮手續費的情況，所以當我們將最好的一組參數(10,12)拿來跑回測，會是這個樣子：<a href="https://www.finlab.tw/KD1/kdbesteq.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="612" height="340" src="http://34.96.136.135/wp-content/uploads/2020/07/kdbesteq.png" alt="kdbesteq" class="wp-image-534" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/kdbesteq.png 612w, https://www.finlab.tw/wp-content/uploads/2020/07/kdbesteq-300x167.png 300w" sizes="(max-width: 612px) 100vw, 612px" title="如何定義KD鈍化？ 32"></figure></div>



<p>藍線代表沒有考慮手續費，一飛沖天<br>紅現代表考慮手續費，完全沒賺到什麼錢</p>



<p>看來手續費真的差很大，短線選股真的是比較困難，但滿有潛力的就是了。</p>



<p>以下是我調整後覺得最好的參數：</p>



<p>KD（5、3、3）連續10天大於75時買進 30 天<a href="https://www.finlab.tw/KD1/bestforself.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="612" height="340" src="http://34.96.136.135/wp-content/uploads/2020/07/bestforself.png" alt="bestforself" class="wp-image-535" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/bestforself.png 612w, https://www.finlab.tw/wp-content/uploads/2020/07/bestforself-300x167.png 300w" sizes="(max-width: 612px) 100vw, 612px" title="如何定義KD鈍化？ 33"></figure></div>



<p>扣除手續費後終於贏過大盤！不知道KD拿來加入其它策略效果如何？<br>另外，也可以跟我說想要看到哪一類的文章，或有什麼技術上的問題，都歡迎留言喔！</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/kd1/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">529</post-id>	</item>
		<item>
		<title>外資大賣，反而要買！？</title>
		<link>https://www.finlab.tw/%e8%b7%9f%e8%91%97%e5%a4%96%e8%b3%87%e8%b2%b7%e8%82%a1%e7%a5%a8/</link>
					<comments>https://www.finlab.tw/%e8%b7%9f%e8%91%97%e5%a4%96%e8%b3%87%e8%b2%b7%e8%82%a1%e7%a5%a8/#respond</comments>
		
		<dc:creator><![CDATA[FinLab - 韓承佑]]></dc:creator>
		<pubDate>Wed, 22 Jul 2020 07:05:01 +0000</pubDate>
				<category><![CDATA[籌碼面]]></category>
		<category><![CDATA[如何買股票]]></category>
		<category><![CDATA[歷史回測]]></category>
		<category><![CDATA[程式交易]]></category>
		<category><![CDATA[簡易策略]]></category>
		<category><![CDATA[選股策略]]></category>
		<guid isPermaLink="false">http://34.96.136.135/?p=504</guid>

					<description><![CDATA[外資近年來幾乎稱霸台股，每天台股上上下下，都得看它臉色，今天我們來進行簡單的參數優化，看看跟隨外資買賣有沒有搞頭！藉由程式交易，讓我們來找尋外資與股價的規律吧！]]></description>
										<content:encoded><![CDATA[
<p>外資近年來幾乎稱霸台股，每天台股上上下下，都得看它臉色，今天我們來進行簡單的參數優化，看看跟隨外資買賣有沒有搞頭！藉由程式交易，讓我們來找尋外資與股價的規律吧！</p>



<h3 id="最佳化外資買賣策略">最佳化外資買賣策略</h3>



<p>假設 n 天內外資總買賣超超過 a 張，則買入，而低於 -a 張，就賣出，我們可以得到一下這張表：<a href="https://www.finlab.tw/%E8%B7%9F%E8%91%97%E5%A4%96%E8%B3%87%E8%B2%B7%E8%82%A1%E7%A5%A8/color.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="445" height="442" src="http://34.96.136.135/wp-content/uploads/2020/07/color.png" alt="color" class="wp-image-505" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/color.png 445w, https://www.finlab.tw/wp-content/uploads/2020/07/color-300x298.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/color-150x150.png 150w" sizes="(max-width: 445px) 100vw, 445px" title="外資大賣，反而要買！？ 34"></figure></div>



<p>在上圖中，跑了25種不同的回測，每一次回測，n跟a的值都不一樣，紅色代表獲利較多的策略，而藍色代表獲利較少的策略，我們發現 a = 0 的時候結果普遍比較好，另外 n=10~30 天都是合理的選擇，太高或太低不夠具有代表性。</p>



<p>當然這樣的條件其實還是太弱了，完全沒辦法當作一個策略，一定得配合其它的條件，目前開發的策略中，我也有加入這個條件，有些策略無效，但有些績效明顯上升很多，可以把它想成一個助攻手。假如你本身也有寫偏短線的回測，可以將 外資10天買賣超 &gt; 0 這個條件加入看看，有時候效果會變好。然而，假如你沒有寫回測的話，其實外資買賣對你的影響有限，幾乎不需要管它。</p>



<h3 id="外資大買大賣，跟著操作？">外資大買大賣，跟著操作？</h3>



<p>外資已經很進步了，這個時代並不是看外資大買，隔天股票就會漲了，甚至，看到外資大買，隔天最好還是別輕舉妄動比較好，以下我做了兩個實驗，一個是外資大買，一個是外資大賣，不考慮手續費：</p>



<ol><li>外資總買賣 &#8211; 昨天外資總買賣 &gt; 5000 （外資大買） 持該股兩天後賣出</li><li>外資總買賣 &#8211; 昨天外資總買賣 &lt; -5000 （外資大賣） 持該股兩天後賣出</li></ol>



<p>你以為一號策略比較好嗎？</p>



<p>錯…</p>



<p>我回測時也小震驚了一下，原來外資大買，隔天買入可能會不太好！還不如趁外資大賣的時候買。怎麼會這樣！？實在是太顛覆常理了…<a href="https://www.finlab.tw/%E8%B7%9F%E8%91%97%E5%A4%96%E8%B3%87%E8%B2%B7%E8%82%A1%E7%A5%A8/buysudden.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="589" height="161" src="http://34.96.136.135/wp-content/uploads/2020/07/buysudden.png" alt="buysudden" class="wp-image-506" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/buysudden.png 589w, https://www.finlab.tw/wp-content/uploads/2020/07/buysudden-300x82.png 300w" sizes="(max-width: 589px) 100vw, 589px" title="外資大賣，反而要買！？ 35"></figure></div>



<p>上圖可以看出，策略2比策略1的報酬好很多。其結論是外資大買，請不要跟著買，因為說不定是外資太多人看了，導致股票隔天衝很高，導致買在高點。相反，大家看到外資大賣，也會恐慌性賣出，造成隔天開盤價格異常低，而剛好被我們買到了！賺到了短線價差。只能說，股票就是人性呀！大家還是太依賴外資籌碼了。總之假如你沒有好策略的話，請不要直接看外資來決定買什麼。</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/%e8%b7%9f%e8%91%97%e5%a4%96%e8%b3%87%e8%b2%b7%e8%82%a1%e7%a5%a8/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">504</post-id>	</item>
		<item>
		<title>超短線上影黑密技！</title>
		<link>https://www.finlab.tw/%e8%b6%85%e7%9f%ad%e7%b7%9a%e4%b8%8a%e5%bd%b1%e9%bb%91%e5%af%86%e6%8a%80%ef%bc%81/</link>
					<comments>https://www.finlab.tw/%e8%b6%85%e7%9f%ad%e7%b7%9a%e4%b8%8a%e5%bd%b1%e9%bb%91%e5%af%86%e6%8a%80%ef%bc%81/#respond</comments>
		
		<dc:creator><![CDATA[FinLab - 韓承佑]]></dc:creator>
		<pubDate>Wed, 22 Jul 2020 07:05:01 +0000</pubDate>
				<category><![CDATA[技術面]]></category>
		<category><![CDATA[如何買股票]]></category>
		<category><![CDATA[歷史回測]]></category>
		<category><![CDATA[簡易策略]]></category>
		<category><![CDATA[選股策略]]></category>
		<guid isPermaLink="false">http://34.96.136.135/?p=512</guid>

					<description><![CDATA[很多來拜訪本blog的人，都是搜尋 “財報狗” 來的，大部分都是價值投資策略，而沒有使用技術分析，或曾經使用技術分析，因為太難用了而放棄。價值投資跟技術分析最大的差異是，價值投資看的財報是經過嚴格審核的精確數字，而技術分析是在看雜訊中找規律。]]></description>
										<content:encoded><![CDATA[
<p>很多來拜訪本blog的人，都是搜尋 “財報狗” 來的，大部分都是價值投資策略，而沒有使用技術分析，或曾經使用技術分析，因為太難用了而放棄。價值投資跟技術分析最大的差異是，價值投資看的財報是經過嚴格審核的精確數字，而技術分析是在看雜訊中找規律。</p>



<p>有人會說價值投資，是學會看一家公司的價值，而不像技術分析，是在玩股票。我覺得各有各的好，都是在一堆數字裡面找規律，只要不要被股票玩，哪一種策略我都願意接受XDD。</p>



<p>今天想當一下標題黨，我幫這個策略取了一個超級中二的名字：”超短線上影黑密技”，無論看幾眼都覺得很彆扭，但是還是讓我一一的解釋每個字的用意：</p>



<h2 id="超短線">超短線</h2>



<p>這個絕對是 “日” 週期裡面，最短的策略了，因為這個策略持股一天隔天直接賣出，適合不想要跟某支股票產生愛恨情仇，喜歡斬釘截鐵，無情操作的人。</p>



<h2 id="上影">上影</h2>



<p>這絕對不是火影忍者裡的上忍、火影，其實是個上影線策略，也就是當看到上影線，那代表這支股票可以空，當然也沒這麼簡單，要有一層層過濾。</p>



<h2 id="黑">黑</h2>



<p>黑就是指下跌的意思，這是一個空股票的策略，我不常寫空股票的策略，因為本身沒有在融資融券，但就是因為很少有人空股票，這個策略才沒有因為被挖掘而失效，放空有時候比看多的策略好寫。</p>



<h2 id="密技">密技</h2>



<p>好啦，其實這也不算什麼密技，上影線大家也不是不知道：<a href="https://www.finlab.tw/%E8%B6%85%E7%9F%AD%E7%B7%9A%E4%B8%8A%E5%BD%B1%E9%BB%91%E5%AF%86%E6%8A%80%EF%BC%81/pp.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="924" height="417" src="http://34.96.136.135/wp-content/uploads/2020/07/pp.png" alt="pp" class="wp-image-513" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/pp.png 924w, https://www.finlab.tw/wp-content/uploads/2020/07/pp-300x135.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/pp-768x347.png 768w" sizes="(max-width: 924px) 100vw, 924px" title="超短線上影黑密技！ 36"></figure></div>



<p>大家都說看到上影線，代表要下跌了，但是這是很不負責任的介紹，因為沒人跟你講會跌多少？上影線多長算長？什麼時候買賣？完全沒有數據，頂多是附圖說，你看這支股票，上影線出現後一路跌。</p>



<h2 id="策略人多口雜，沒有回測看看就好">策略人多口雜，沒有回測看看就好</h2>



<p>同樣上影線，可以找到100張K線圖，驗證之後真的會跌，反過來，也可以找到100張K線圖，驗證之後其實會漲。</p>



<p>看過很多自稱是技術分析高手，分享一些方法，KD、MACD、OBV什麼都用上了，回測起來績效不太好，也不知道他是靠投資掙錢，還是靠嘴掙錢。也看過一些人，突然PO文說自己打開多年投資經驗的任督二脈，把blog加密起來，付費觀看，火紅一時。然而過了半年，那個人不見了，消失在茫茫股海中，應該是他的策略就好這麼幾個月，之後就爛掉了XDD。</p>



<h2 id="回測的重要性">回測的重要性</h2>



<p>所以我覺得回測很重要，才能知道是否安穩的獲利，而且還不用每天盯盤。可能有人會反問： W 底要怎麼回測？有些型態學根本不可能寫程式怎麼辦？要是我的話，就會選擇不用，反正還有其它的策略可以用，我比較膽小，只用有驗證過的策略XD。</p>



<h2 id="策略">策略</h2>



<p>突然啪啦啪啦寫了一堆，不好意思讓各位眼睛痛了，以下就是本篇策略：</p>



<ul><li>上影線佔 60% （（高 &#8211; max(收, 開)）／（高 &#8211; 低）&gt; 0.6）</li><li>突然放量 （成交量 &gt; 十日均量 * 4）</li><li>流動率高 （十日均量 &gt; 1000）</li><li>股票不在高檔 （收盤 &#8211; 120日最低價）/ (（120日最高價 &#8211; 120日最低價）&lt; 0.7</li></ul>



<p>第四條拿出來說明一下，高檔的股票，有時候會被主力炒作，太飆了，還是不要拿來放空比較好XD。</p>



<p>以下的權益曲線是空1天，即回補，我另外有測試n天的，基本上獲利更高，但曲線比較不好看。<a href="https://www.finlab.tw/%E8%B6%85%E7%9F%AD%E7%B7%9A%E4%B8%8A%E5%BD%B1%E9%BB%91%E5%AF%86%E6%8A%80%EF%BC%81/eq.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="595" height="291" src="http://34.96.136.135/wp-content/uploads/2020/07/eq-10.png" alt="eq 10" class="wp-image-514" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/eq-10.png 595w, https://www.finlab.tw/wp-content/uploads/2020/07/eq-10-300x147.png 300w" sizes="(max-width: 595px) 100vw, 595px" title="超短線上影黑密技！ 37"></figure></div>



<p>但這個策略沒有加上手續費，槓桿是調整成0，但假如考慮融券手續費，效果可能就沒那麼好就是了，當沖手續費低會更好？滿有可能的。</p>



<p>下圖是 賣出/買入 價格的漲跌分佈圖：<a href="https://www.finlab.tw/%E8%B6%85%E7%9F%AD%E7%B7%9A%E4%B8%8A%E5%BD%B1%E9%BB%91%E5%AF%86%E6%8A%80%EF%BC%81/ratio.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="595" height="143" src="http://34.96.136.135/wp-content/uploads/2020/07/ratio.png" alt="ratio" class="wp-image-515" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/ratio.png 595w, https://www.finlab.tw/wp-content/uploads/2020/07/ratio-300x72.png 300w" sizes="(max-width: 595px) 100vw, 595px" title="超短線上影黑密技！ 38"></figure></div>



<p>我們可以看到，這些股票下跌（小於1）的數目真的比較多（橘色），然而加上手續費（約千分之8），後，就沒有這麼明顯了（淺藍色），手續費多少是關鍵！像我這種散戶，手續費太高自然是無法使用這個策略QQ。<a href="https://www.finlab.tw/%E8%B6%85%E7%9F%AD%E7%B7%9A%E4%B8%8A%E5%BD%B1%E9%BB%91%E5%AF%86%E6%8A%80%EF%BC%81/ns.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="598" height="193" src="http://34.96.136.135/wp-content/uploads/2020/07/ns-5.png" alt="ns 5" class="wp-image-516" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/ns-5.png 598w, https://www.finlab.tw/wp-content/uploads/2020/07/ns-5-300x97.png 300w" sizes="(max-width: 598px) 100vw, 598px" title="超短線上影黑密技！ 39"></figure></div>



<p>可以看到每年都只買了超少次，而且快進快出，大部分時候是空手狀態，很輕鬆。<a href="https://www.finlab.tw/%E8%B6%85%E7%9F%AD%E7%B7%9A%E4%B8%8A%E5%BD%B1%E9%BB%91%E5%AF%86%E6%8A%80%EF%BC%81/md.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="613" height="193" src="http://34.96.136.135/wp-content/uploads/2020/07/md.png" alt="md" class="wp-image-517" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/md.png 613w, https://www.finlab.tw/wp-content/uploads/2020/07/md-300x94.png 300w" sizes="(max-width: 613px) 100vw, 613px" title="超短線上影黑密技！ 40"></figure></div>



<p>可以看到最大虧損也不是很嚴重，尤其時近期，幾乎很少虧損到20%的投資資產。</p>



<p>當然，大部分的策略看看就好，這個策略也是（由於手續費的關係），重點應該是學到一些東西，以下列舉此篇的重點：</p>



<ul><li>用簡單的公式看股價高檔低檔（條件4）</li><li>股票不再高檔、近期上影線放量，假如想放空，可以空n天，(n&lt;10)回測獲利都是很可觀，持有時間長，股價漲跌波動大，可以淡化手續費的影響，但持有時間越長，權益曲線越不美。</li><li>股票不在高檔、近期上影線放量，假如想買多，隔幾天再買入較可能買到更好的價格！（假如你用的是長線策略）</li></ul>



<p>假如大家有興趣，我想找時間來跑一些統計結果，看看上影線對於股價的影響。假如覺得本blog還可以的話，可以定期來觀看～我每個禮拜都會更新幾篇喔！</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/%e8%b6%85%e7%9f%ad%e7%b7%9a%e4%b8%8a%e5%bd%b1%e9%bb%91%e5%af%86%e6%8a%80%ef%bc%81/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">512</post-id>	</item>
		<item>
		<title>大盤要跌了嗎？利用企業本益比分佈來判斷！</title>
		<link>https://www.finlab.tw/%e5%a4%a7%e7%9b%a4%e8%a6%81%e8%b7%8c%e4%ba%86%e5%97%8e%ef%bc%9f%e5%88%a9%e7%94%a8%e4%bc%81%e6%a5%ad%e6%9c%ac%e7%9b%8a%e6%af%94%e5%88%86%e4%bd%88%e4%be%86%e5%88%a4%e6%96%b7%ef%bc%81/</link>
					<comments>https://www.finlab.tw/%e5%a4%a7%e7%9b%a4%e8%a6%81%e8%b7%8c%e4%ba%86%e5%97%8e%ef%bc%9f%e5%88%a9%e7%94%a8%e4%bc%81%e6%a5%ad%e6%9c%ac%e7%9b%8a%e6%af%94%e5%88%86%e4%bd%88%e4%be%86%e5%88%a4%e6%96%b7%ef%bc%81/#respond</comments>
		
		<dc:creator><![CDATA[FinLab - 韓承佑]]></dc:creator>
		<pubDate>Wed, 22 Jul 2020 07:04:43 +0000</pubDate>
				<category><![CDATA[大盤漲跌]]></category>
		<category><![CDATA[大盤]]></category>
		<category><![CDATA[本益比]]></category>
		<category><![CDATA[簡易策略]]></category>
		<guid isPermaLink="false">http://34.96.136.135/?p=384</guid>

					<description><![CDATA[最近大盤一直跌，大家都不禁懷疑是否開始大崩盤了？因為前幾天寫了一篇用淨值比判斷大盤漲跌，想說本益比是不是也可以這樣如法炮製呢？於是做了台股企業本益比中位數隨時間的變化圖。]]></description>
										<content:encoded><![CDATA[
<p>最近大盤一直跌，大家都不禁懷疑是否開始大崩盤了？因為前幾天寫了一篇<a href="https://www.finlab.tw/%E7%94%A8%E8%82%A1%E5%83%B9%E6%B7%A8%E5%80%BC%E6%AF%94%E4%BE%86%E5%88%A4%E6%96%B7%E5%A4%A7%E7%9B%A4%E6%BC%B2%E8%B7%8C/">用淨值比判斷大盤漲跌</a>，想說本益比是不是也可以這樣如法炮製呢？於是做了台股企業本益比中位數隨時間的變化圖。</p>



<p>在看圖之前不免俗的先講講本益比（PE）</p>



<h3 id="本益比中位數介紹">本益比中位數介紹</h3>



<p>本益比的簡單公式是：本益比 = 每股市價／每股盈利。</p>



<p>本益比越高，代表你用較多錢買一間盈利低的公司股票<br>本益比越低，代表你用較少錢買一間盈利高的公司股票</p>



<h3 id="利用本益比中位數來判斷大盤大趨勢">利用本益比中位數來判斷大盤大趨勢</h3>



<p>下圖紅線是是每天大盤上市上櫃股票的本益比中位數（取過對數的）隨時間變化圖，藍線是2個標準差，灰色是大盤：<a href="https://www.finlab.tw/%E5%A4%A7%E7%9B%A4%E8%A6%81%E8%B7%8C%E4%BA%86%E5%97%8E%EF%BC%9F%E5%88%A9%E7%94%A8%E4%BC%81%E6%A5%AD%E6%9C%AC%E7%9B%8A%E6%AF%94%E5%88%86%E4%BD%88%E4%BE%86%E5%88%A4%E6%96%B7%EF%BC%81/pe-mid.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="667" height="357" src="http://34.96.136.135/wp-content/uploads/2020/07/pe-mid.png" alt="pe mid" class="wp-image-385" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/pe-mid.png 667w, https://www.finlab.tw/wp-content/uploads/2020/07/pe-mid-300x161.png 300w" sizes="(max-width: 667px) 100vw, 667px" title="大盤要跌了嗎？利用企業本益比分佈來判斷！ 41"></figure></div>



<p>大家可以觀察一下，以下是我發現有趣的點：</p>



<ul><li>假如我們現在有個策略在紅線為2.5左右買進大盤，而3左右出清，感覺獲利會滿可觀的！（然而金融海嘯還是得凹一下單就是了XD）</li><li>用本益比中位數台股2000年上萬點為3.5，而今年上萬點只有2.6，代表兩次上萬點意義不太一樣，2000年那次比較像是泡沫，破了後來很慘烈；而今年是大盤破新高，而紅線沒破新高，代表企業的盈利目前來講還算是跟的上股價的漲幅，沒有太誇張，所以這幾天雖然都慘慘的，我個人還是保持平常心。</li></ul>



<p>大家可以搭配之前<a href="https://www.finlab.tw/%E7%94%A8%E8%82%A1%E5%83%B9%E6%B7%A8%E5%80%BC%E6%AF%94%E4%BE%86%E5%88%A4%E6%96%B7%E5%A4%A7%E7%9B%A4%E6%BC%B2%E8%B7%8C/">用淨值比判斷大盤漲跌</a>的文章看，雖然股價淨值比的中位數有點偏高，但目前都沒有大暴跌的明顯徵兆，但我真的不是叫你相信這些指標，因為每個指標的結論很有可能不一樣，例如下面就是一個例子：</p>



<h3 id="反面例子：GOOGLE-TREND">反面例子：GOOGLE TREND</h3>



<p>這個指標已經被Mr.Market在<a href="https://www.google.fr/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=1&amp;cad=rja&amp;uact=8&amp;ved=0ahUKEwiQ3be9wsXWAhVGvBoKHWDjBV4QFggnMAA&amp;url=http%3A%2F%2Fwww.rich01.com%2F2014%2F11%2Fgoogle-trend.html&amp;usg=AFQjCNEx4wbBR0ycvg-GFcB5SZUS7K3IeQ" rel="noreferrer noopener" target="_blank">這篇文中</a>介紹過了，簡而言之：<br>google trend 指標就是 “台股” 這個關鍵字的熱門程度，是反指標。</p>



<p>事隔多年看一下，發現最近有點散戶真的是灌入台股這樣：<a href="https://www.finlab.tw/%E5%A4%A7%E7%9B%A4%E8%A6%81%E8%B7%8C%E4%BA%86%E5%97%8E%EF%BC%9F%E5%88%A9%E7%94%A8%E4%BC%81%E6%A5%AD%E6%9C%AC%E7%9B%8A%E6%AF%94%E5%88%86%E4%BD%88%E4%BE%86%E5%88%A4%E6%96%B7%EF%BC%81/trend.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="664" height="269" src="http://34.96.136.135/wp-content/uploads/2020/07/trend.png" alt="trend" class="wp-image-386" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/trend.png 664w, https://www.finlab.tw/wp-content/uploads/2020/07/trend-300x122.png 300w" sizes="(max-width: 664px) 100vw, 664px" title="大盤要跌了嗎？利用企業本益比分佈來判斷！ 42"></figure></div>



<p>最近”股票”的搜尋人氣已經達到歷史新高更勝2008金融海嘯前…</p>



<p>為什麼”股票”關鍵字人氣越高，股票越容易跌？因為用google搜”股票”這兩個字的，大部分都是新手散戶，有人把股市當做是一種心理學的競技場，新手往往沒有交易的心理素質，容易買高賣低。引用巴菲特的名言：</p>



<blockquote class="wp-block-quote"><p>We simply attempt to be fearful when others are greedy and to be greedy only when others are fearful.</p></blockquote>



<p>總結：雖然淨值比來看，企業的盈利目前來講還算是跟的上股價的漲幅，但投資時還是得參考更多的指標再做決定，並自行負責！</p>



<p>我喜歡跑一些歷史數據找一些規律性，但絕對不做預測，希望可以用最中性、較科學的方式來跟大家一起研究投資這門學問。</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/%e5%a4%a7%e7%9b%a4%e8%a6%81%e8%b7%8c%e4%ba%86%e5%97%8e%ef%bc%9f%e5%88%a9%e7%94%a8%e4%bc%81%e6%a5%ad%e6%9c%ac%e7%9b%8a%e6%af%94%e5%88%86%e4%bd%88%e4%be%86%e5%88%a4%e6%96%b7%ef%bc%81/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">384</post-id>	</item>
		<item>
		<title>用股價淨值比來判斷大盤漲跌</title>
		<link>https://www.finlab.tw/%e7%94%a8%e8%82%a1%e5%83%b9%e6%b7%a8%e5%80%bc%e6%af%94%e4%be%86%e5%88%a4%e6%96%b7%e5%a4%a7%e7%9b%a4%e6%bc%b2%e8%b7%8c/</link>
					<comments>https://www.finlab.tw/%e7%94%a8%e8%82%a1%e5%83%b9%e6%b7%a8%e5%80%bc%e6%af%94%e4%be%86%e5%88%a4%e6%96%b7%e5%a4%a7%e7%9b%a4%e6%bc%b2%e8%b7%8c/#respond</comments>
		
		<dc:creator><![CDATA[FinLab - 韓承佑]]></dc:creator>
		<pubDate>Wed, 22 Jul 2020 07:04:42 +0000</pubDate>
				<category><![CDATA[大盤漲跌]]></category>
		<category><![CDATA[大盤]]></category>
		<category><![CDATA[簡易策略]]></category>
		<category><![CDATA[股價淨值比]]></category>
		<guid isPermaLink="false">http://34.96.136.135/?p=372</guid>

					<description><![CDATA[股價淨值比(PB)真的能夠判斷台股大盤漲跌嗎？
今天做了一張gif動圖，讓各位用眼睛觀察台股是否漲多了，是否有泡沫要破的跡象，甚至讓你有機會可以買在大盤低點。]]></description>
										<content:encoded><![CDATA[
<p>股價淨值比(PB)真的能夠判斷台股大盤漲跌嗎？<br>今天做了一張gif動圖，讓各位用眼睛觀察台股是否漲多了，是否有泡沫要破的跡象，甚至讓你有機會可以買在大盤低點。</p>



<p>股價淨值比(PB)，可以拿來判斷股民對這某家公司的看法，假如大家覺得這家公司未來會壯大，則淨值比會大於1，如果這家公司會衰退，則淨值比會小於1。那剛好我們就可以做出一張分佈圖，來看一下全體投資人對每一家公司看好看衰的分佈圖，跟大盤之間的變化（這張圖稍大可能要等久一點…）。結果發現，當大盤大跌之前，會有類似的前兆，想知道前兆是什麼？請接著看這張圖：<a href="https://www.finlab.tw/%E7%94%A8%E8%82%A1%E5%83%B9%E6%B7%A8%E5%80%BC%E6%AF%94%E4%BE%86%E5%88%A4%E6%96%B7%E5%A4%A7%E7%9B%A4%E6%BC%B2%E8%B7%8C/pb-min.gif"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="432" height="288" src="http://34.96.136.135/wp-content/uploads/2020/07/pb-min.gif" alt="pb min" class="wp-image-373" title="用股價淨值比來判斷大盤漲跌 43"></figure></div>



<p>這張圖的上半部，是用來看多少個企業被看好，多少企業被看衰。分佈圖的x軸分成左右兩邊，大於零代表樂觀，小於零代表悲觀。其實x軸就是股價淨值比取log(PB)的分佈，為什麼要用log呢？是為了讓分佈圖更接近高斯，也讓多空變成在零的對稱位置。此圖的每一根bar代表有多少支股票，其股價淨值比為log(PB)。此圖有五條垂直線，代表著中位數加減兩個標準差。這張圖的下半部則是對照大盤的某個時間點，我們從2010年統計到2015年，每20天計算一次股價淨值比分佈圖。</p>



<p>大部分的時候，投資人基本上看好台灣的市場，所以分佈普遍偏向0的右邊，而且事實發現，近來台股加權指數破萬，並不是大泡泡，而是台灣的企業真的慢慢隨著時間在壯大，因為當大盤破萬點時，分佈圖並沒有超級偏右邊，代表台灣的企業是真的有跟上投資人的期待。然而最近還是有點太過樂觀的氣氛瀰漫，還是得懂得居高思危才行XD。</p>



<p>可以發現一些有趣的現象：</p>



<ol><li>中位數平常都待在log(PB) = 0 ~ 1 之間，當大盤跌到最低點時，會回到0～0.05附近，可以當作大盤買點，成功在2004、2005、2012、2015歸零附近時買入成功買在超低點，唯獨金融海嘯時，中位數最小來到了-0.4左右才反轉，所以還是要看一下中位數是否在&lt;=0附近反轉，比較保險。</li><li>大盤在高點時，PB標準差會比其它時候略小，而中位數最大約在 log(PB) = 0.4～0.5 左右（可以當作大盤賣點，但較難判斷）</li><li>當大盤要大跌前的前兆是分佈的標準差會明顯變大，且伴隨中位數些許變低</li></ol>



<p>接下來我們用更簡明的圖讓大家更一目了然：<a href="https://www.finlab.tw/%E7%94%A8%E8%82%A1%E5%83%B9%E6%B7%A8%E5%80%BC%E6%AF%94%E4%BE%86%E5%88%A4%E6%96%B7%E5%A4%A7%E7%9B%A4%E6%BC%B2%E8%B7%8C/pb-benchmark.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="642" height="340" src="http://34.96.136.135/wp-content/uploads/2020/07/pb-benchmark.png" alt="pb benchmark" class="wp-image-374" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/pb-benchmark.png 642w, https://www.finlab.tw/wp-content/uploads/2020/07/pb-benchmark-300x159.png 300w" sizes="(max-width: 642px) 100vw, 642px" title="用股價淨值比來判斷大盤漲跌 44"></figure></div>



<p>圖中的五條線（紅、黃、藍）分別對應到上面動畫圖分佈的中位數及兩個標準差（紅、黃、白）唯獨中位數的顏色從白色改成藍色，比較清楚。另外灰色的是大盤，發現近五年藍色線接近0且反轉時，都是大盤很好的買點，另外當大盤到高點時，通常這五條線會跟大盤產生背離！也就是大盤越來越高，但分佈線高點卻越來越低。現階段，雖然大盤到 10500 點了，但還未產生背離現象，可以推斷最近的大跌應該不是真正的超大跌（吧？），但這也只是我的猜測啦，股市中沒有什麼是絕對的。</p>



<p>以上就是簡單判斷大盤多空的簡單方法！</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/%e7%94%a8%e8%82%a1%e5%83%b9%e6%b7%a8%e5%80%bc%e6%af%94%e4%be%86%e5%88%a4%e6%96%b7%e5%a4%a7%e7%9b%a4%e6%bc%b2%e8%b7%8c/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">372</post-id>	</item>
	</channel>
</rss>
