安裝命令以下:html
pip install stockstats
複製代碼
conda install -c conda-forge ta-lib
複製代碼
能夠在mbalib 網站上查詢各個指標的含義。例如: wiki.mbalib.com/wiki/三重指數平滑…bash
縮寫 | 描述 |
---|---|
K | KDJ中的K值 |
D | KDJ中的D值 |
J | KDJ中的J值 |
MACD | 異同移動平均線 |
MOM | 動量線 |
BIAS | 乖離率 |
CMO | 錢德動量擺動指標 |
TRIX | 三重指數平滑平均線 |
OBV | 能量潮 |
ROC | 變更率指標 |
AMA | 移動平均平行線差指標 |
VR | 成交量變異率 |
PSY | 心理線指標 |
Force Index | 強力指數指標 |
DPO | 區間震盪線 |
VHF | 十字過濾線指標 |
RVI | 相對活力指數 |
先導入幾個包,除了talib、numpy和pandas之外還有stockstats、pandas_talibmarkdown
import pandas as pd
import numpy as np
import talib
import stockstats
import pandas_talib
''' 這裏雖然沒有定義df這個變量,但這很明顯就是dateframe格式的某隻股票基礎數據 包括開盤價、收盤價、最高價、最低價和成交量 建議用tushare來獲取數據(固然僅限日數據) '''
stockStat = stockstats.StockDataFrame.retype(df)
close = df.close
highPrice = df.high
lowPrice = df.low
volume = df.volume
複製代碼
而後把一些人家庫已經實現好的指標放出來app
df.rename(columns={'close': 'Close', 'volume': 'Volume'}, inplace=True)
sig_k , sig_d = talib.STOCH(np.array(highPrice), np.array(lowPrice),
np.array(close), fastk_period=9,slowk_period=3,
slowk_matype=0, slowd_period=3, slowd_matype=0)
sig_j = sig_k * 3 - sig_d * 2
sig = pd.concat([sig_k, sig_d, sig_j], axis=1, keys=['K', 'D', 'J'])
sig['MACD'], MACDsignal, MACDhist = talib.MACD(np.array(close), fastperiod=6,
slowperiod=12, signalperiod=9)
sig['MOM'] = talib.MOM(np.array(close), timeperiod=5)
sig['CMO'] = talib.CMO(close, timeperiod=10)
sig['TRIX'] = talib.TRIX(close, timeperiod=14)
sig['OBV'] = talib.OBV(close, volume)
sig['ROC'] = talib.ROC(close, timeperiod=10)
sig['VR'] = stockStat['vr']
sig['Force_Index'] = pandas_talib.FORCE(df, 12)['Force_12']
複製代碼
def BIAS(close, timeperiod=20):
if isinstance(close,np.ndarray):
pass
else:
close = np.array(close)
MA = talib.MA(close,timeperiod=timeperiod)
return (close-MA)/MA
複製代碼
def AMA(stockStat):
return talib.MA(stockStat['dma'], timeperiod=10)
複製代碼
def PSY(priceData, period):
difference = priceData[1:] - priceData[:-1]
difference = np.append(0, difference)
difference_dir = np.where(difference > 0, 1, 0)
psy = np.zeros((len(priceData),))
psy[:period] *= np.nan
for i in range(period, len(priceData)):
psy[i] = (difference_dir[i-period+1:i+1].sum()) / period
return psy*100
複製代碼
def DPO(close):
p = talib.MA(close, timeperiod=11)
p.shift()
return close-p
複製代碼
def VHF(close):
LCP = talib.MIN(close, timeperiod=28)
HCP = talib.MAX(close, timeperiod=28)
NUM = HCP - LCP
pre = close.copy()
pre = pre.shift()
DEN = abs(close-close.shift())
DEN = talib.MA(DEN, timeperiod=28)*28
return NUM.div(DEN)
複製代碼
def RVI(df):
close = df.close
open = df.open
high = df.high
low = df.low
X = close-open+2*(close.shift()-open.shift())+
2*(close.shift(periods=2)-open.shift(periods=2))*(close.shift(periods=3)-
open.shift(periods=3))/6
Y = high-low+2*(high.shift()-low.shift())+
2*(high.shift(periods=2)-low.shift(periods=2))*(high.shift(periods=3)-
low.shift(periods=3))/6
Z = talib.MA(X, timeperiod=10)*10
D = talib.MA(Y, timeperiod=10)*10
return Z/D
複製代碼