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

<channel>
	<title>深度學習 &#8211; FinLab</title>
	<atom:link href="https://www.finlab.tw/tag/%E6%B7%B1%E5%BA%A6%E5%AD%B8%E7%BF%92/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.finlab.tw</link>
	<description>深入淺出的量化投資，讓你在在茫茫股海中，找到專屬於自己的投資方法</description>
	<lastBuildDate>Wed, 22 Jul 2020 07:05:21 +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>用深度學習幫你解析K線圖！</title>
		<link>https://www.finlab.tw/%e7%94%a8%e6%b7%b1%e5%ba%a6%e5%ad%b8%e7%bf%92%e5%b9%ab%e4%bd%a0%e8%a7%a3%e6%9e%90k%e7%b7%9a%e5%9c%96%ef%bc%81/</link>
					<comments>https://www.finlab.tw/%e7%94%a8%e6%b7%b1%e5%ba%a6%e5%ad%b8%e7%bf%92%e5%b9%ab%e4%bd%a0%e8%a7%a3%e6%9e%90k%e7%b7%9a%e5%9c%96%ef%bc%81/#respond</comments>
		
		<dc:creator><![CDATA[FinLab - 韓承佑]]></dc:creator>
		<pubDate>Wed, 22 Jul 2020 07:05:21 +0000</pubDate>
				<category><![CDATA[AI看股票]]></category>
		<category><![CDATA[CANDLESTICKS]]></category>
		<category><![CDATA[DEEP-LEARNING]]></category>
		<category><![CDATA[K棒]]></category>
		<category><![CDATA[K線圖]]></category>
		<category><![CDATA[LSTM]]></category>
		<category><![CDATA[PYTHON]]></category>
		<category><![CDATA[型態學]]></category>
		<category><![CDATA[深度學習]]></category>
		<category><![CDATA[程式交易]]></category>
		<guid isPermaLink="false">http://34.96.136.135/?p=635</guid>

					<description><![CDATA[現今在股市裡有三大分析方法，即：技術面、基本面、籌碼面等，而各流派似乎也都有自己能自圓其說的選股策略。這三種方法並無法直接說出孰好孰壞，分析方法的選擇跟操作者的心態、個性、紀律都有很大的關係。而我個人覺得買股票除了要買得好（投報率高）以外，賣得快（IRR高）也是很重要的，畢竟投報率會因為時間的流逝而漸漸下降。]]></description>
										<content:encoded><![CDATA[
<p>現今在股市裡有三大分析方法，即：技術面、基本面、籌碼面等，而各流派似乎也都有自己能自圓其說的選股策略。這三種方法並無法直接說出孰好孰壞，分析方法的選擇跟操作者的心態、個性、紀律都有很大的關係。而我個人覺得買股票除了要買得好（投報率高）以外，賣得快（IRR高）也是很重要的，畢竟投報率會因為時間的流逝而漸漸下降。</p>



<p>因為重視時間對股價影響的我，日K線裡藏有的奧妙便是我想一探究竟的。K線型態學主要就是在探討每根K棒的開盤價、收盤價、最高價、最低價、以及成交量這五大要素所反映出多空雙方的心理交戰。日本著名的投資大師本間宗久影響後人而產生一系列「酒田戰法」的相關書籍裡頭便對K線型態學有了不少篇幅的評析。但人心是會變的，K線型態也是。有沒有方法能幫助我們解讀每天數百張詭譎多變的K線圖呢？<a href="https://www.finlab.tw/%E7%94%A8%E6%B7%B1%E5%BA%A6%E5%AD%B8%E7%BF%92%E5%B9%AB%E4%BD%A0%E8%A7%A3%E6%9E%90K%E7%B7%9A%E5%9C%96%EF%BC%81/K-trends.jpg"></a></p>



<figure class="wp-block-image size-large"><img width="640" height="480" src="http://34.96.136.135/wp-content/uploads/2020/07/K-trends.jpg" alt="K trends" class="wp-image-636" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/K-trends.jpg 640w, https://www.finlab.tw/wp-content/uploads/2020/07/K-trends-300x225.jpg 300w" sizes="(max-width: 640px) 100vw, 640px" title="用深度學習幫你解析K線圖！ 1"></figure>



<h3 id="長短期記憶-Long-Short-Term-Memory-LSTM-神經網路">長短期記憶 (Long Short-Term Memory, LSTM) 神經網路</h3>



<p>長短期記憶 (LSTM) 神經網路屬於循環神經網路 (RNN) 的一種，特別適合處理和預測與時間序列相關的重要事件。以下面的句子做為一個上下文推測的例子：</p>



<blockquote class="wp-block-quote"><p>“我從小在法國長大，我會說一口流利的？？”</p></blockquote>



<p>由於同一句話裡前面提及到<strong>法國</strong>這個國家，且後面提到<strong>說</strong>這個動作。因此，LSTM便能從<strong>法國</strong>以及<strong>說</strong>這兩個長短期的記憶中重要的訊號推測出可能性較大的<strong>法文</strong>這個結果。</p>



<p>K線圖也述說著類似的事情，股價是隨著時間的流動及重要訊號的出現而做出反應的：</p>



<ul><li>在價穩量縮的盤整區間中突然出現一帶量突破的大紅K，表示股價可能要上漲了</li><li>在跳空缺口後出現島狀反轉，表示股價可能要下跌了</li><li>在連漲幾天的走勢突然出現帶有長上下影線的十字線，表示股價有反轉的可能</li></ul>



<p>LSTM 要做的事情就是找出一段時間區間的K棒當中有沒有重要訊號（如帶量紅K）並學習之後股價的走勢。</p>



<h3 id="LSTM-實作股價預測">LSTM 實作股價預測</h3>



<p>資料是以鴻海(2317)從2013年初到2017年底每天的開盤價、收盤價、最高價、最低價、以及成交量等數據，如果你對這筆資料有興趣請參考附註的方式索取。<a href="https://www.finlab.tw/%E7%94%A8%E6%B7%B1%E5%BA%A6%E5%AD%B8%E7%BF%92%E5%B9%AB%E4%BD%A0%E8%A7%A3%E6%9E%90K%E7%B7%9A%E5%9C%96%EF%BC%81/2317_prices.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="392" height="249" src="http://34.96.136.135/wp-content/uploads/2020/07/2317_prices.png" alt="2317 prices" class="wp-image-637" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/2317_prices.png 392w, https://www.finlab.tw/wp-content/uploads/2020/07/2317_prices-300x191.png 300w" sizes="(max-width: 392px) 100vw, 392px" title="用深度學習幫你解析K線圖！ 2"></figure></div>



<p>首先將資料讀入並存至pandas的DataFrame，另外對可能有N/A的row進行剔除：</p>



<p>資料讀入</p>



<pre class="wp-block-code"><code>import pandas as pd

foxconndf= pd.read_csv('./foxconn_2013-2017.csv', index_col=0 )
foxconndf.dropna(how='any',inplace=True)</code></pre>



<p>為了避免原始數據太大或是太小沒有統一的範圍而導致 LSTM 在訓練時難以收斂，我們以一個最小最大零一正規化方法對數據做正規化：</p>



<p>資料正規化</p>



<pre class="wp-block-code"><code>from sklearn import preprocessing

def normalize(df):
    newdf= df.copy()
    min_max_scaler = preprocessing.MinMaxScaler()
    
    newdf&#91;'open'] = min_max_scaler.fit_transform(df.open.values.reshape(-1,1))
    newdf&#91;'low'] = min_max_scaler.fit_transform(df.low.values.reshape(-1,1))
    newdf&#91;'high'] = min_max_scaler.fit_transform(df.high.values.reshape(-1,1))
    newdf&#91;'volume'] = min_max_scaler.fit_transform(df.volume.values.reshape(-1,1))
    newdf&#91;'close'] = min_max_scaler.fit_transform(df.close.values.reshape(-1,1))
    
    return newdf

foxconndf_norm= normalize(foxconndf)</code></pre>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="746" height="228" src="http://34.96.136.135/wp-content/uploads/2020/07/normdf_head.png" alt="normdf head" class="wp-image-638" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/normdf_head.png 746w, https://www.finlab.tw/wp-content/uploads/2020/07/normdf_head-300x92.png 300w" sizes="(max-width: 746px) 100vw, 746px" title="用深度學習幫你解析K線圖！ 3"></figure></div>



<p><a href="https://www.finlab.tw/%E7%94%A8%E6%B7%B1%E5%BA%A6%E5%AD%B8%E7%BF%92%E5%B9%AB%E4%BD%A0%E8%A7%A3%E6%9E%90K%E7%B7%9A%E5%9C%96%EF%BC%81/normdf_head.png"></a>然後對資料進行訓練集與測試集的切割，另外也定義每一筆資料要有多長的時間框架：</p>



<p>資料編輯</p>



<pre class="wp-block-code"><code>import numpy as np

def data_helper(df, time_frame):
    
    # 資料維度: 開盤價、收盤價、最高價、最低價、成交量, 5維
    number_features = len(df.columns)

    # 將dataframe 轉成 numpy array
    datavalue = df.as_matrix()

    result = &#91;]
    # 若想要觀察的 time_frame 為20天, 需要多加一天做為驗證答案
    for index in range( len(datavalue) - (time_frame+1) ): # 從 datavalue 的第0個跑到倒數第 time_frame+1 個
        result.append(datavalue&#91;index: index + (time_frame+1) ]) # 逐筆取出 time_frame+1 個K棒數值做為一筆 instance
    
    result = np.array(result)
    number_train = round(0.9 * result.shape&#91;0]) # 取 result 的前90% instance做為訓練資料
    
    x_train = result&#91;:int(number_train), :-1] # 訓練資料中, 只取每一個 time_frame 中除了最後一筆的所有資料做為feature
    y_train = result&#91;:int(number_train), -1]&#91;:,-1] # 訓練資料中, 取每一個 time_frame 中最後一筆資料的最後一個數值(收盤價)做為答案
    
    # 測試資料
    x_test = result&#91;int(number_train):, :-1]
    y_test = result&#91;int(number_train):, -1]&#91;:,-1]
    
    # 將資料組成變好看一點
    x_train = np.reshape(x_train, (x_train.shape&#91;0], x_train.shape&#91;1], number_features))
    x_test = np.reshape(x_test, (x_test.shape&#91;0], x_test.shape&#91;1], number_features))  

    return &#91;x_train, y_train, x_test, y_test]

# 以20天為一區間進行股價預測
X_train, y_train, X_test, y_test = data_helper(foxconndf_norm, 20)</code></pre>



<p>我們以 Keras 框架做為 LSTM 的實作選擇，首先在面前加了兩層 256個神經元的 LSTM layer，並都加上了Dropout層來防止資料過度擬合（overfitting）。最後再加上兩層有不同數目神經元的全連結層來得到只有1維數值的輸出結果，也就是預測股價：</p>



<p>Keras 模型建立</p>



<pre class="wp-block-code"><code>from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation
from keras.layers.recurrent import LSTM
import keras

def build_model(input_length, input_dim):
    d = 0.3
    model = Sequential()

    model.add(LSTM(256, input_shape=(input_length, input_dim), return_sequences=True))
    model.add(Dropout(d))

    model.add(LSTM(256, input_shape=(input_length, input_dim), return_sequences=False))
    model.add(Dropout(d))

    model.add(Dense(16,kernel_initializer="uniform",activation='relu'))
    model.add(Dense(1,kernel_initializer="uniform",activation='linear'))

    model.compile(loss='mse',optimizer='adam', metrics=&#91;'accuracy'])

    return model

# 20天、5維
model = build_model( 20, 5 )</code></pre>



<p>建立好 LSTM 模型後，我們就用前面編輯好的<strong>訓練資料集</strong>開始進行模型的訓練：LSTM 模型訓練</p>



<pre class="wp-block-code"><code># 一個batch有128個instance，總共跑50個迭代
model.fit( X_train, y_train, batch_size=128, epochs=50, validation_split=0.1, verbose=1)</code></pre>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="350" src="http://34.96.136.135/wp-content/uploads/2020/07/lstm-training-1024x350.png" alt="lstm training" class="wp-image-639" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/lstm-training-1024x350.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/lstm-training-300x103.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/lstm-training-768x263.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/lstm-training.png 1119w" sizes="(max-width: 1024px) 100vw, 1024px" title="用深度學習幫你解析K線圖！ 4"></figure></div>



<p><a href="https://www.finlab.tw/%E7%94%A8%E6%B7%B1%E5%BA%A6%E5%AD%B8%E7%BF%92%E5%B9%AB%E4%BD%A0%E8%A7%A3%E6%9E%90K%E7%B7%9A%E5%9C%96%EF%BC%81/lstm-training.png"></a>在經過一段時間的訓練過程後，我們便能得到 LSTM 模型（model）。接著再用這個模型對測試資料進行預測，以及將預測出來的數值（pred）與正確答案（y_test）還原回原始股價的大小區間：</p>



<p>LSTM 模型預測股價及還原數值</p>



<pre class="wp-block-code"><code>def denormalize(df, norm_value):
    original_value = df&#91;'close'].values.reshape(-1,1)
    norm_value = norm_value.reshape(-1,1)
    
    min_max_scaler = preprocessing.MinMaxScaler()
    min_max_scaler.fit_transform(original_value)
    denorm_value = min_max_scaler.inverse_transform(norm_value)
    
    return denorm_value

# 用訓練好的 LSTM 模型對測試資料集進行預測
pred = model.predict(X_test)

# 將預測值與正確答案還原回原來的區間值
denorm_pred = denormalize(foxconndf, pred)
denorm_ytest = denormalize(foxconndf, y_test)</code></pre>



<h3 id="LSTM-預測股價結果">LSTM 預測股價結果</h3>



<p>讓我們把還原後的數值與答案畫出來，看看效果如何：</p>



<p>LSTM 預測股價結果</p>



<pre class="wp-block-code"><code>import matplotlib.pyplot as plt
%matplotlib inline  

plt.plot(denorm_pred,color='red', label='Prediction')
plt.plot(denorm_ytest,color='blue', label='Answer')
plt.legend(loc='best')
plt.show()</code></pre>



<p>如下圖，藍線是正確答案、紅線是預測股價。雖然整體看起來預測股價與正確答案有類似的走勢，但仔細一看預測股價都比正確答案落後了幾天。如果真的將這個模型應用在買賣策略上我們應該很快就畢業了。<a href="https://www.finlab.tw/%E7%94%A8%E6%B7%B1%E5%BA%A6%E5%AD%B8%E7%BF%92%E5%B9%AB%E4%BD%A0%E8%A7%A3%E6%9E%90K%E7%B7%9A%E5%9C%96%EF%BC%81/performance-default.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="382" height="252" src="http://34.96.136.135/wp-content/uploads/2020/07/performance-default.png" alt="performance default" class="wp-image-640" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/performance-default.png 382w, https://www.finlab.tw/wp-content/uploads/2020/07/performance-default-300x198.png 300w" sizes="(max-width: 382px) 100vw, 382px" title="用深度學習幫你解析K線圖！ 5"></figure></div>



<p>所以我們試著來調整一些設定：</p>



<ul><li>時間框架長度的調整</li><li>Keras 模型裡全連結層的 activation 與 optimizaer 的調整</li><li>Keras 模型用不同的神經網路（種類、順序、數量）來組合</li><li>batch_size 的調整、epochs 的調整</li><li>…</li></ul>



<p>經過我們對上述的幾個參數稍微調整過後，我們就得到一個更貼近正確答案的預測結果囉。如果你發現哪些設置能得到更好的結果歡迎你在下面留言跟大家分享。<a href="https://www.finlab.tw/%E7%94%A8%E6%B7%B1%E5%BA%A6%E5%AD%B8%E7%BF%92%E5%B9%AB%E4%BD%A0%E8%A7%A3%E6%9E%90K%E7%B7%9A%E5%9C%96%EF%BC%81/performance-finetuned.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="388" height="252" src="http://34.96.136.135/wp-content/uploads/2020/07/performance-finetuned.png" alt="performance finetuned" class="wp-image-641" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/performance-finetuned.png 388w, https://www.finlab.tw/wp-content/uploads/2020/07/performance-finetuned-300x195.png 300w" sizes="(max-width: 388px) 100vw, 388px" title="用深度學習幫你解析K線圖！ 6"></figure></div>



<h3 id="參考資料">參考資料</h3>



<ol><li>詳細的python教學：<a href="https://www.finlab.tw/%E5%88%A9%E7%94%A8Machine-Learning-%E9%81%B8%E8%82%A1%E6%96%B0%E6%89%8B%E6%95%99%E5%AD%B8/">利用Machine-Learning-選股新手教學</a></li><li>Keras 說明文件：<a href="https://keras.io/" rel="noreferrer noopener" target="_blank">Keras Documentation</a></li><li>另一種 RNN：<a href="https://arxiv.org/abs/1406.1078" rel="noreferrer noopener" target="_blank">GRU, Gated Recurrent Unit</a></li><li>Kaggle 相關競賽：<a href="https://www.kaggle.com/dgawlik/nyse" rel="noreferrer noopener" target="_blank">New York Stock Exchange</a></li></ol>



<h3 id="附註：現在就開始AI選股，免費取得訓練資料">附註：現在就開始AI選股，免費取得訓練資料</h3>



<p>取得訓練資料的方法很簡單，幫冷清的寒舍小小宣傳一下：</p>



<ol><li>按右下角分享這篇文章到你的FB</li><li>將分享截圖傳到&nbsp;<a href="mailto:finlabstaff@gmail.com" rel="noreferrer noopener" target="_blank">finlabstaff@gmail.com</a></li><li>一兩天內即可獲得原始資料喔！</li></ol>



<p class="has-text-align-center">熟悉Python與Machine learning，對量化交易有興趣，想挑戰用Machine learning找出股價漲跌的節奏。</p>



<p class="has-text-align-center"><a rel="noreferrer noopener" href="mailto:justzupi@gmail.com" target="_blank">Jeffrey</a></p>



<p class="has-text-align-center">AI科學家</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/%e7%94%a8%e6%b7%b1%e5%ba%a6%e5%ad%b8%e7%bf%92%e5%b9%ab%e4%bd%a0%e8%a7%a3%e6%9e%90k%e7%b7%9a%e5%9c%96%ef%bc%81/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">635</post-id>	</item>
	</channel>
</rss>
