# Python 股票演算法交易實務 - Chap. 6 判斷漲跌的趨勢
###### tags: `讀書會`
Date: 2019-10-15(W2) By 蓉爸
---
#### 技巧85 【觀念】趨勢的發生與判斷
1. 交易首要:做多或做空 (買或賣)
買進 -> 後市看漲
賣出 -> 後市看跌
2. 短線多空:透過當天的資料來判斷。
長期投資:拿更長週期資料來看趨勢。
3. 利用多時間序列的趨勢,來輔助日內交易。
4. 交易策略中,判斷「多空時機」與「進場時機」並不相等。
多空時機:斷定當天的趨勢。(當天?)
進場時機:找一個好的時間點下單。(一個較長期的趨勢?)
5. 趨勢改變:考慮停損並反向新倉。(做多->改做空)
同一個趨勢中,不該隨意反倉,否則很可能導致大虧損。
P.S 新倉:建立新的買賣合約
https://enrumoney.net/%e5%a6%82%e4%bd%95%e8%b2%b7%e8%b3%a3%e6%9c%9f%e8%b2%a8%ef%bc%9f%e5%be%88%e7%b0%a1%e5%96%ae%ef%bc%8c3%e6%ad%a5%e9%a9%9f%e5%b0%b1%e6%90%9e%e5%ae%9a%ef%bc%81
---
#### 技巧86 【觀念】趨勢在策略中的應用
1. 交易策略:
(1) 趨勢交易:需判斷多空趨勢。本章節的演算法是「趨勢判斷」+「進場」。(文句語意不明確)
(2) 順勢交易:不需判斷趨勢,只要滿足特定條件,立即進場。
---
#### 技巧87 【觀念】取得股票日K
1. 取得歷史日K資料:
(1) 需尋找免費的日K資料。(證交所網站上的資料)
(2) 網頁爬蟲技巧。(善用網站提供的 API)
證交所網站:
http://www.twse.com.tw/zh/page/trading/exchange/STOCK_DAY.html

:::success
**API取得資料的概念:**
輸入每個月的某一天,就可以取得該月的所有日期。
:::
**API 用法像這樣:**
http://www.twse.com.tw/exchangeReport/STOCK_DAY?response=json&date=日期&stockNo=股票代碼
**書本範例程式:**
書本SampleCode\Python股票技巧範例\實單範例\function.py
書本SampleCode\Python股票技巧範例\實單範例\88.py
註:function.py 用到 tailer 套件安裝如下圖

圖片來源: 元大Smart API
(https://www.yuantafutures.com.tw/file-repository/content/smartAPI/page8-1.html)
書本範例 function.py 執行狀況:

---
#### 技巧88 【觀念】日週期-開盤價格跳空判斷
**跳空缺口**:又稱「**開盤跳空**」,因非開盤時間,發生影響價格的因素,而讓隔天的開盤價「高於」或「低於」前一天的開盤價。
程式範例:參考 88.py
```python=
# -*- coding: UTF-8 -*-
# 載入相關套件
import datetime,function
import sys
# 取得當天日期
Date=datetime.datetime.now().strftime("%Y%m%d")
# 測試股票下單
Sid=sys.argv[1]
# 取得前日K棒
LastKBar=function.getDayKBarbyNum(Sid,1)
LastClose=LastKBar[-1][4]
# 趨勢判斷
Trend=0
for i in function.getSIDMatch(Date,Sid):
price=float(i[2])
if price > LastClose:
print('開盤向上跳空')
Trend=1
break
elif price < LastClose:
print('開盤向下跳空')
Trend=-1
break
else:
print('無跳空缺口')
break
```
---
#### 技巧89 【觀念】日週期-開盤與日移動平均線判斷
**開盤與日移動平均線比較**:當開盤價高過移動平均線時,就代表**市場有一股力量要哄抬價格**,這時順勢進行操作。
程式範例:參考 89.py
```python=
# -*- coding: UTF-8 -*-
# 載入相關套件
import datetime,function
import talib,numpy
import sys
# 取得當天日期
Date=datetime.datetime.now().strftime("%Y%m%d")
# 測試股票下單
Sid=sys.argv[1]
# 取得前日K棒
LastKBar=function.getDayKBarbyNum(Sid,20)
LastClose=numpy.array([ i[4] for i in LastKBar ])
DayMA=talib.MA(LastClose,timeperiod=20)[-1]
# 趨勢判斷
Trend=0
for i in function.getSIDMatch(Date,Sid):
price=float(i[2])
if price > DayMA:
print('開盤大於20日MA')
Trend=1
break
elif price < DayMA:
print('開盤小於20日MA')
Trend=-1
break
else:
print('開盤等於20日MA')
break
```
依據自己的環境,下載相對應的 TA_Lib,例如 python 3.7 的就下載:TA_Lib-0.4.17-cp37-cp37m-win_amd64.whl https://www.lfd.uci.edu/~gohlke/pythonlibs/#ta-lib

<br/>
安裝 TA-lib
```dos=
pip install TA_Lib-0.4.17-cp37-cp37m-win_amd64.whl
```

參考:Python Fintech 學習筆記 : 安裝技術指標套件 TA-Lib http://yhhuang1966.blogspot.com/2018/05/python-ta-lib.html
---
#### 技巧90 【觀念】日週期-RSI判斷當日走勢
**RSI技術指標**:是一種「日週期」及「相對強弱」的指標,主要用來查看 **當前市場趨勢** 的指標。這個指標是透過 **日K** 來計算。
程式範例:參考 90.py
```python=
# -*- coding: UTF-8 -*-
# 載入相關套件
import datetime,function
import talib,numpy
import sys
# 取得當天日期
Date=datetime.datetime.now().strftime("%Y%m%d")
# 測試股票下單
Sid=sys.argv[1]
# 取得前日K棒
LastKBar=function.getDayKBarbyNum(Sid,21)
LastClose=numpy.array([ i[4] for i in LastKBar ])
DayRSI=talib.RSI(LastClose,timeperiod=20)[-1]
# 趨勢判斷
Trend=0
if DayRSI>50:
print('當日只做多單')
Trend=1
elif DayRSI<50:
print('當日只做空單')
Trend=-1
else:
print('當日趨勢不明')
```
---
#### 技巧91 【觀念】日內判斷-時間區段價格走勢判斷
**時間區段價格走勢**:利用兩個時間點比較,查看買賣雙方互相對抗後,形成的 **價格漲跌** 趨勢,作為進場操作多空的依據。
程式範例:參考 91.py(從開盤到 0930 的價格走勢)
```python=
# -*- coding: UTF-8 -*-
# 載入相關套件
import datetime,function,indicator
import talib,numpy
import sys
# 取得當天日期
Date=datetime.datetime.now().strftime("%Y%m%d")
# 測試股票下單
Sid=sys.argv[1]
# 趨勢判斷
Trend=0
TrendEndTime=datetime.datetime.strptime(Date+'09:30:00','%Y%m%d%H:%M:%S')
KBar1M=indicator.KBar(date=Date)
for i in function.getSIDMatch(Date,Sid):
time=datetime.datetime.strptime(Date+i[0],'%Y%m%d%H:%M:%S.%f')
price=float(i[2])
qty=int(i[3])
KBar1M.Add(time,price,qty)
if time > TrendEndTime:
startprice = KBar1M.GetOpen()[0]
endprice = KBar1M.GetClose()[-1]
if startprice > endprice:
print('當日只做多單')
Trend=1
break
elif startprice < endprice:
print('當日只做空單')
Trend=-1
break
else:
print('當日趨勢不明')
break
```
---
#### 技巧92 【觀念】日內判斷-根據內外盤總量判斷區勢
**內外盤總量區勢**:內外盤代表買賣方的 **積極度**,可以透過某個時間點的 **內外盤總量** 比較,來預測目前 **市場趨勢**。
程式範例:參考 92.py
```python=
# -*- coding: UTF-8 -*-
# 載入相關套件
import datetime,function,indicator
import talib,numpy
import sys
# 取得當天日期
Date=datetime.datetime.now().strftime("%Y%m%d")
# 測試股票下單
Sid=sys.argv[1]
# 趨勢判斷
Trend=0
TrendEndTime=datetime.datetime.strptime(Date+'09:30:00','%Y%m%d%H:%M:%S')
BSPower2= indicator.BSPower2()
for i in function.getSIDMatch(Date,Sid):
time=datetime.datetime.strptime(Date+i[0],'%Y%m%d%H:%M:%S.%f')
price=float(i[2])
qty=int(i[3])
ask=float(i[5])
bid=float(i[6])
BSPower2.Add(price,qty,ask,bid)
if time > TrendEndTime:
sig = BSPower2.Get()
if sig[0] > sig[1]:
print('當日只做多單')
Trend=1
break
elif sig[0] < sig[1]:
print('當日只做空單')
Trend=-1
break
else:
print('當日趨勢不明')
break
```