TaLib在股票技術分析中的應用

1、TaLib與技術分析

  • 技術分析是股票分析十分有效直接的手段,在實際投資中我們常常需要計算各種簡單或複雜的技術指標來分析參考

  • 對於技術指標的定義基本都大同小異,很多都是通用的且模塊化的東西

  • 對於不會寫代碼或者不想自己寫函數計算這些技術指標的人而言,強大的Talib給我們帶來了福音

  • 只需要調用Talib的函數,輸入簡單的參數就可以得到自己想要的結果

2、初看Talib

先簡單看看Talib都給我們提供了那些計算技術指標的函數,按技術指標的類型列示如下:

Overlap Studies Functions

BBANDS - Bollinger Bandsnupperband, middleband, lowerband = BBANDS(close, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)nnDEMA - Double Exponential Moving Averagenreal = DEMA(close, timeperiod=30)nnEMA - Exponential Moving Averagenreal = EMA(close, timeperiod=30)nnHT_TRENDLINE - Hilbert Transform - Instantaneous Trendlinenreal = HT_TRENDLINE(close)nnKAMA - Kaufman Adaptive Moving Averagenreal = KAMA(close, timeperiod=30)nnMA - Moving averagenreal = MA(close, timeperiod=30, matype=0)nnMAMA - MESA Adaptive Moving Averagenmama, fama = MAMA(close, fastlimit=0, slowlimit=0)nnMAVP - Moving average with variable periodnreal = MAVP(close, periods, minperiod=2, maxperiod=30, matype=0)nnMIDPOINT - MidPoint over periodnreal = MIDPOINT(close, timeperiod=14)nnMIDPRICE - Midpoint Price over periodnreal = MIDPRICE(high, low, timeperiod=14)nnSAR - Parabolic SARnreal = SAR(high, low, acceleration=0, maximum=0)nnSAREXT - Parabolic SAR - Extendednreal = SAREXT(high, low, startvalue=0, offsetonreverse=0, accelerationinitlong=0, naccelerationlong=0, accelerationmaxlong=0, accelerationinitshort=0, accelerationshort=0, accelerationmaxshort=0)nnSMA - Simple Moving Averagenreal = SMA(close, timeperiod=30)nnT3 - Triple Exponential Moving Average (T3)nreal = T3(close, timeperiod=5, vfactor=0)nnTEMA - Triple Exponential Moving Averagenreal = TEMA(close, timeperiod=30)nnTRIMA - Triangular Moving Averagenreal = TRIMA(close, timeperiod=30)nnWMA - Weighted Moving Averagenreal = WMA(close, timeperiod=30) n

Momentum Indicator Functions

ADX - Average Directional Movement Indexnreal = ADX(high, low, close, timeperiod=14)nnADXR - Average Directional Movement Index Ratingnreal = ADXR(high, low, close, timeperiod=14)nnAPO - Absolute Price Oscillatornreal = APO(close, fastperiod=12, slowperiod=26, matype=0)nnAROON - Aroonnaroondown, aroonup = AROON(high, low, timeperiod=14)nnAROONOSC - Aroon Oscillatornreal = AROONOSC(high, low, timeperiod=14)nnBOP - Balance Of Powernreal = BOP(open, high, low, close)nnCCI - Commodity Channel Indexnreal = CCI(high, low, close, timeperiod=14)nnCMO - Chande Momentum Oscillatornreal = CMO(close, timeperiod=14)nnDX - Directional Movement Indexnreal = DX(high, low, close, timeperiod=14)nnMACD - Moving Average Convergence/Divergencenmacd, macdsignal, macdhist = MACD(close, fastperiod=12, slowperiod=26, signalperiod=9)nnMACDEXT - MACD with controllable MA typenmacd, macdsignal, macdhist = MACDEXT(close, fastperiod=12, fastmatype=0, slowperiod=26, nslowmatype=0, signalperiod=9, signalmatype=0)nnMACDFIX - Moving Average Convergence/Divergence Fix 12/26nmacd, macdsignal, macdhist = MACDFIX(close, signalperiod=9)nnMFI - Money Flow Indexnreal = MFI(high, low, close, volume, timeperiod=14)nnMINUS_DI - Minus Directional Indicatornreal = MINUS_DI(high, low, close, timeperiod=14)nnMINUS_DM - Minus Directional Movementnreal = MINUS_DM(high, low, timeperiod=14)nnMOM - Momentumnreal = MOM(close, timeperiod=10)nnRSI - Relative Strength Indexnreal = RSI(close, timeperiod=14)n

Volume Indicator Functions

AD - Chaikin A/D Linenreal = AD(high, low, close, volume)nnADOSC - Chaikin A/D Oscillatornreal = ADOSC(high, low, close, volume, fastperiod=3, slowperiod=10)nnOBV - On Balance Volumenreal = OBV(close, volume) n

Volatility Indicator Functions

ATR - Average True Rangenreal = ATR(high, low, close, timeperiod=14)nnNATR - Normalized Average True Rangenreal = NATR(high, low, close, timeperiod=14)nnTRANGE - True Rangenreal = TRANGE(high, low, close) n

Price Transform Functions

AVGPRICE - Average Pricenreal = AVGPRICE(open, high, low, close)nnMEDPRICE - Median Pricenreal = MEDPRICE(high, low)nnTYPPRICE - Typical Pricenreal = TYPPRICE(high, low, close)nnWCLPRICE - Weighted Close Pricenreal = WCLPRICE(high, low, close) n

Cycle Indicator Functions

HT_DCPERIOD - Hilbert Transform - Dominant Cycle Periodnreal = HT_DCPERIOD(close)nnHT_DCPHASE - Hilbert Transform - Dominant Cycle Phasenreal = HT_DCPHASE(close)nnHT_PHASOR - Hilbert Transform - Phasor Componentsninphase, quadrature = HT_PHASOR(close)nnHT_SINE - Hilbert Transform - SineWavensine, leadsine = HT_SINE(close)nnHT_TRENDMODE - Hilbert Transform - Trend vs Cycle Modeninteger = HT_TRENDMODE(close) n

Statistic Functions

BETA - Betanreal = BETA(high, low, timeperiod=5)nnCORREL - Pearsons Correlation Coefficient (r)nreal = CORREL(high, low, timeperiod=30)nnLINEARREG - Linear Regressionnreal = LINEARREG(close, timeperiod=14)nnLINEARREG_ANGLE - Linear Regression Anglenreal = LINEARREG_ANGLE(close, timeperiod=14)nnLINEARREG_INTERCEPT - Linear Regression Interceptnreal = LINEARREG_INTERCEPT(close, timeperiod=14)nnLINEARREG_SLOPE - Linear Regression Slopenreal = LINEARREG_SLOPE(close, timeperiod=14)nnSTDDEV - Standard Deviationnreal = STDDEV(close, timeperiod=5, nbdev=1)nnTSF - Time Series Forecastnreal = TSF(close, timeperiod=14)nnVAR - Variancenreal = VAR(close, timeperiod=5, nbdev=1) n

Math Transform Functions

ACOS - Vector Trigonometric ACosnreal = ACOS(close)nnASIN - Vector Trigonometric ASinnreal = ASIN(close)nnATAN - Vector Trigonometric ATannreal = ATAN(close)nnCEIL - Vector Ceilnreal = CEIL(close)nnCOS - Vector Trigonometric Cosnreal = COS(close)nnCOSH - Vector Trigonometric Coshnreal = COSH(close)nnEXP - Vector Arithmetic Expnreal = EXP(close)nnFLOOR - Vector Floornreal = FLOOR(close)nnLN - Vector Log Naturalnreal = LN(close)nnLOG10 - Vector Log10nreal = LOG10(close)nnSIN - Vector Trigonometric Sinnreal = SIN(close)nnSINH - Vector Trigonometric Sinhnreal = SINH(close)nnSQRT - Vector Square Rootnreal = SQRT(close)nnTAN - Vector Trigonometric Tannreal = TAN(close)nnTANH - Vector Trigonometric Tanhnreal = TANH(close) n

Math Operator Functions

ADD - Vector Arithmetic Addnreal = ADD(high, low)nnDIV - Vector Arithmetic Divnreal = DIV(high, low)nnMAX - Highest value over a specified periodnreal = MAX(close, timeperiod=30)nnMAXINDEX - Index of highest value over a specified periodninteger = MAXINDEX(close, timeperiod=30)nnMIN - Lowest value over a specified periodnreal = MIN(close, timeperiod=30)nnMININDEX - Index of lowest value over a specified periodninteger = MININDEX(close, timeperiod=30)nnMINMAX - Lowest and highest values over a specified periodnmin, max = MINMAX(close, timeperiod=30)nnMINMAXINDEX - Indexes of lowest and highest values over a specified periodnminidx, maxidx = MINMAXINDEX(close, timeperiod=30)nnMULT - Vector Arithmetic Multnreal = MULT(high, low)nnSUB - Vector Arithmetic Substractionnreal = SUB(high, low)nnSUM - Summationnreal = SUM(close, timeperiod=30) n

上面只是列舉了一部分,更多函數可以參見官網,點擊鏈接

3、如何應用:MA實例

  • 從上面可以看到,MA這個函數的參數為:real = MA(close, timeperiod=30, matype=0)

  • close表示收盤價序列,timeperiod指定義好均線的計算長度即幾日均線,不輸入的話,默認為30日,matype可以默認不用輸入,然後就可以得到均線的值

  • 所以簡單來講,只取獲取收盤價序列,就可以輕鬆計算MA值

  • 下面以萬科A為例進行說明

data=DataAPI.MktEqudGet(ticker=u"000002",beginDate=u"20160601",endDate=u"20160804",field=u"secShortName,tradeDate,closePrice",pandas="1") #取數據ndata[MA5] = talib.MA(data[closePrice].values, timeperiod=5) #調用talib計算5日均線的值ndata.tail(10) #後十行結果n

就這樣,我們便捷地計算出了均線,下面計算更複雜的EMA,MACD

有關EMA,MACD的基礎知識,可以參考社區帖子『研究|技術指標|第一彈』MACD

關於EMA,MACD計算的函數的描述是:

real = EMA(close, timeperiod=30)nmacd, macdsignal, macdhist = MACD(close, fastperiod=12, slowperiod=26, signalperiod=9)n

輸入參數:close是收盤價,timeperiod指的是指數移動平均線EMA的長度,fastperiod指更短時段的EMA的長度,slowperiod指更長時段的EMA的長度,signalperiod指DEA長度

返回值:注意有些地方的macdhist = 2(dif-dea),但是talib中MACD的計算是macdhist = dif-dea

data[EMA12] = talib.EMA(data[closePrice].values, timeperiod=12) #調用talib 計算12日移動移動平均線的值ndata[EMA26] = talib.EMA(data[closePrice].values, timeperiod=26)ndata[MACD],data[MACDsignal],data[MACDhist] = talib.MACD(data[closePrice].values)n

在構建策略時也會更加方便。

4、策略實戰:雙均線策略

  • 當5日均線上穿60日均線,買入

  • 當5日均線下穿60日均線,賣出

  • 我們不再需要自己寫函數計算均線,只需要調用函數就可以方便的解決問題(對於更複雜的指標,talib的便捷就更加明顯)

import pandas as pdnimport numpy as npnimport talibnnstart = 2013-01-01 # 回測起始時間nend = 2016-07-01 # 回測結束時間nbenchmark = HS300 # 策略參考標準nuniverse = set_universe(HS300) ncapital_base = 1000000 # 起始資金nfreq = d # 策略類型,d表示日間策略使用日線回測,m表示日內策略使用分鐘線回測nrefresh_rate = 5 # 調倉頻率,表示執行handle_data的時間間隔,若freq = d時間間隔的單位為交易日,若freq = m時間間隔為分鐘nndef initialize(account): # 初始化虛擬賬戶狀態n passnndef handle_data(account): # 每個交易日的買入賣出指令nn period1 = 5 #取5日數據n period2 = 60 #取60日數據n all_close_prices = account.get_attribute_history(closePrice, period2) # 獲取歷史closePrice數據n buy_list = [] # 備選買入清單n sell_list = [] # 賣出清單n for stk in account.universe:n prices = all_close_prices[stk]n if prices is None:n continuen try:n MA5 = talib.MA(prices, timeperiod=period1) # 計算5日均線n MA60 = talib.MA(prices, timeperiod=period2) #計算60日均線n except:n continue n # 買入賣出判斷n if MA5[-1]-MA60[-1] > 0: #talib計算返回的MA5是一個數組,對應於日期,最後一個元素就是當前交易日前一天的5日均線值n buy_list.append(stk) n elif MA5[-1]-MA60[-1] < 0: #當5日均線下穿60日均線,賣出n sell_list.append(stk)n hold = []n buy = [] # 最終買入清單 n # 買入賣出n for stk in account.valid_secpos:n # sell_list賣出n if stk in sell_list:n order_to(stk, 0) n # 其餘繼續持股n else:n hold.append(stk) n buy = holdn for stk in buy_list:n # 若buy_list中股票有未買入的,加入n if stk not in hold:n buy.append(stk) n if len(buy) > 0:n # 等倉位買入n amout = account.referencePortfolioValue/len(buy) # 每隻股票買入數量n for stk in buy:n num = int(amout/account.referencePrice[stk] / 100.0) * 100n order_to(stk, num) n returnn

原文鏈接:TaLib在股票技術分析中的應用
推薦閱讀:

2017 年 A 股 IPO 數量增長 93% 的原因有哪些?由此可以預測出哪些發展趨勢?
2017.03.31 本輪迴調的回顧與預期

TAG:量化 | 股票 | Python |