初學者的Python金融分析日記 EP5 – 移動平均、指數移動平均、MACD

我們這邊講一下怎麼用pandas來計算常見的技術指標,包括

  • 移動平均線
  • 指數移動平均線
  • MACD
#載入套件庫與讀入資料
import pandas as pd
import matplotlib.pyplot as plt
import sqlite3

db = sqlite3.connect('TWStock_2')
tsmc = pd.read_sql(con=db,sql='SELECT * FROM "2330"')

#清理資料
#我們需要成交股數、開盤價、最高價、最低價、收盤價的資料
#並使用Date當作我們的索引值

tsmc.index = pd.to_datetime(tsmc['Date'])
tsmc = tsmc[['成交股數','開盤價','最高價','最低價','收盤價']]
tsmc.columns = ['Volume','Open','High','Low','Close']
tsmc['Close'] = pd.to_numeric(tsmc['Close'])

移動平均線

移動平均線(Moving Average)應該是我們最常運用的技術指標了,當我們畫出均線後,我們就可以比較目前價格與均價之間的關係。其n天移動平均線的計算公式為


為n天的收盤價的平均,我們如何利用pandas來計算移動平均線勒?其實非常簡單,我們可以利用DataFrame下面的rolling方法,就能計算出移動平均線了

#我們分別計算7天,15天與30天的移動平均線
tsmc['MA_7'] = tsmc['Close'].rolling(7).mean()
tsmc['MA_15'] = tsmc['Close'].rolling(15).mean()
tsmc['MA_30'] = tsmc['Close'].rolling(30).mean()

指數移動平均線

當我們要比較均價的趨勢快慢時,我們可以利用指數移動平均數(EMA),計算公式為

這邊alpha一般取2/(n+1),另外,由於我們需要初始值來計算EMA,我們可以直接取第一天的收盤價當做$EMA_1$
,而在DataFrame下面,我們也有對應的方法ewm來計算指數移動平均線

tsmc['EMA_12'] = tsmc['Close'].ewm(span=12).mean()
tsmc['EMA_26'] = tsmc['Close'].ewm(span=26).mean()
[/python</code></pre>
<!-- /wp:code -->

<!-- wp:heading -->
<h2>MACD</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>根據<a href="https://www.wikiwand.com/zh-tw/MACD">維基百科</a>:<br> 是股票交易中一種常見的技術分析工具,由Gerald Appel於1970年代提出,用於研判股票價格變化的強度、方向、能量,以及趨勢周期,以便把握股票買進和賣出的時機。MACD指標由一組曲線與圖形組成,通過收盤時股價或指數的快變及慢變的指數移動平均值(EMA)之間的差計算出來。「快」指更短時段的EMA,而「慢」則指較長時段的EMA,最常用的是12及26日EMA。<br> 其計算公式為</p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":561} -->
<figure class="wp-block-image"><img src="https://pyecontech.com/wp-content/uploads/2019/06/圖片-5.png" alt="" class="wp-image-561"/></figure>
<!-- /wp:image -->

<!-- wp:code -->
<pre class="wp-block-code"><code>[python]
tsmc['DIF'] = tsmc['EMA_12'] - tsmc['EMA_26']
tsmc['DEM'] = tsmc['DIF'].ewm(span=9).mean()
tsmc['OSC'] = tsmc['DIF'] - tsmc['DEM']

最後,我們來畫個圖

tsmc = tsmc['2019-01-01':]
fig,ax = plt.subplots(3,1,figsize=(10,10))
plt.subplots_adjust(hspace=0.8)
tsmc['MA_7'].plot(ax=ax[0])
tsmc['MA_15'].plot(ax=ax[0])
tsmc['MA_30'].plot(ax=ax[0])
tsmc['EMA_12'].plot(ax=ax[1])
tsmc['EMA_26'].plot(ax=ax[1])
tsmc['Close'].plot(ax=ax[0])
tsmc['Close'].plot(ax=ax[1])
ax[0].legend()
ax[1].legend()
tsmc['DIF'].plot(ax=ax[2])
tsmc['DEM'].plot(ax=ax[2])
ax[2].fill_between(tsmc.index,0,tsmc['OSC'])
ax[2].legend()
plt.show()
Share

2 thoughts on “初學者的Python金融分析日記 EP5 – 移動平均、指數移動平均、MACD

  1. I am just writing to make you understand what a outstanding experience my wife’s girl had using your web site. She mastered so many pieces, which included what it is like to possess an excellent helping nature to let other people with ease learn some specialized things. You truly surpassed people’s expected results. Thank you for producing these precious, trusted, informative and in addition fun tips about this topic to Lizeth.

  2. A lot of thanks for each of your hard work on this web page. Kim really likes going through investigation and it’s really easy to understand why. Many of us know all of the dynamic method you make invaluable steps on this web blog and as well as improve participation from people on that idea so our girl is in fact learning a lot of things. Have fun with the remaining portion of the new year. You are conducting a splendid job.

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *