DAY 13
1
Elastic Stack on Cloud

## TA-Lib

TA-Lib 是基於 Python 的一個計算各種金融數據指標的套件，目前支援 158 種指標，你想得到的移動平均線、MACD、KD... 等，都可以計算。其實目前成名的股票大師，大多都不會看超過５個指標，所以 TA-Lib 是同好圈中的首選，沒有其它。TA-Lib 的安裝可見官方的 GithubDay08 我分享的 Dockerfile 已包含 TA-Lib 的安裝，有興趣的朋友可以參考。

## 移動平均線計算

``````closePrices = elastic_df.iloc[:, 6].astype('float').values
close_sma_20 = np.round(talib.SMA(closePrices, timeperiod=20), 2)
print(close_sma_100)
# [  nan   nan   nan   nan   nan   nan   nan   nan   nan   nan   nan   nan
nan   nan   nan   nan   nan   nan   nan 78.13 78.08 77.98 77.95 77.91
77.89 77.94 77.9  77.9  77.82 77.74]
``````

## Index 移動平均指標

``````PUT /history-prices-sma
{
"mappings": {
"properties": {
"stock_id" : {
"type" : "keyword"
},
"date" : {
"type" : "date"
},
"sma_20" : {
"type" : "float"
}
}
}
}
``````

Indexing Documents:

``````close_sma_20 = np.round(talib.SMA(closePrices, timeperiod=20), 2)
stock_id = elastic_df.iloc[:, 0].values
date = elastic_df.iloc[:, 1].values

documents = []
for i in range(len(stock_id)):
document = {}
document['stock_id'] = stock_id[i]
document['date']     = date[i]
document['sma_20']   = close_sma_20[i]

action = {}
actionProperties = {}
actionProperties["_id"] = document['stock_id'] + document['date']
action["index"] = actionProperties
documents.append(action)
documents.append(document)

result = es.bulk(body=documents, index='history-prices-sma')
``````

Elastic 戰台股30