Python talib.MA Examples

The following are 30 code examples of talib.MA(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module talib , or try the search function .
Example #1
Source File: data_preprocessing.py    From StarTrader with MIT License 22 votes vote down vote up
def technical_indicators_df(self, daily_data):
        """
        Assemble a dataframe of technical indicator series for a single stock
        """
        o = daily_data['Open'].values
        c = daily_data['Close'].values
        h = daily_data['High'].values
        l = daily_data['Low'].values
        v = daily_data['Volume'].astype(float).values
        # define the technical analysis matrix

        # Most data series are normalized by their series' mean
        ta = pd.DataFrame()
        ta['MA5'] = tb.MA(c, timeperiod=5) / tb.MA(c, timeperiod=5).mean()
        ta['MA10'] = tb.MA(c, timeperiod=10) / tb.MA(c, timeperiod=10).mean()
        ta['MA20'] = tb.MA(c, timeperiod=20) / tb.MA(c, timeperiod=20).mean()
        ta['MA60'] = tb.MA(c, timeperiod=60) / tb.MA(c, timeperiod=60).mean()
        ta['MA120'] = tb.MA(c, timeperiod=120) / tb.MA(c, timeperiod=120).mean()
        ta['MA5'] = tb.MA(v, timeperiod=5) / tb.MA(v, timeperiod=5).mean()
        ta['MA10'] = tb.MA(v, timeperiod=10) / tb.MA(v, timeperiod=10).mean()
        ta['MA20'] = tb.MA(v, timeperiod=20) / tb.MA(v, timeperiod=20).mean()
        ta['ADX'] = tb.ADX(h, l, c, timeperiod=14) / tb.ADX(h, l, c, timeperiod=14).mean()
        ta['ADXR'] = tb.ADXR(h, l, c, timeperiod=14) / tb.ADXR(h, l, c, timeperiod=14).mean()
        ta['MACD'] = tb.MACD(c, fastperiod=12, slowperiod=26, signalperiod=9)[0] / \
                     tb.MACD(c, fastperiod=12, slowperiod=26, signalperiod=9)[0].mean()
        ta['RSI'] = tb.RSI(c, timeperiod=14) / tb.RSI(c, timeperiod=14).mean()
        ta['BBANDS_U'] = tb.BBANDS(c, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)[0] / \
                         tb.BBANDS(c, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)[0].mean()
        ta['BBANDS_M'] = tb.BBANDS(c, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)[1] / \
                         tb.BBANDS(c, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)[1].mean()
        ta['BBANDS_L'] = tb.BBANDS(c, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)[2] / \
                         tb.BBANDS(c, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)[2].mean()
        ta['AD'] = tb.AD(h, l, c, v) / tb.AD(h, l, c, v).mean()
        ta['ATR'] = tb.ATR(h, l, c, timeperiod=14) / tb.ATR(h, l, c, timeperiod=14).mean()
        ta['HT_DC'] = tb.HT_DCPERIOD(c) / tb.HT_DCPERIOD(c).mean()
        ta["High/Open"] = h / o
        ta["Low/Open"] = l / o
        ta["Close/Open"] = c / o

        self.ta = ta 
Example #2
Source File: features.py    From trading-server with GNU General Public License v3.0 7 votes vote down vote up
def CCI(self, period: int, bars: list):
        """
        Return CCI (Commodity Chanel Index) for n bars close price.
​
        CCI = (Typical Price − MA) / 0.015 * Mean Deviation

        where:
            Typical Price = ∑P((H + L + C) / 3))
            P = number of bars (period)
            MA = Moving Average = (∑P Typical Price) / P
            Mean Deviation=(∑P | Typical Price - MA |) / P
        """

        self.check_bars_type(bars)

        cci = ta.CCI(
            bars['high'], bars['low'], bars['close'], timeperiod=period)

        return cci 
Example #3
Source File: DyST_IntraDayT.py    From DevilYuan with MIT License 7 votes vote down vote up
def _getAtrExtreme(cls, highs, lows, closes, atrPeriod=14, slowPeriod=30, fastPeriod=3):
        """
            获取TTI ATR Exterme通道, which is based on 《Volatility-Based Technical Analysis》
            TTI is 'Trading The Invisible'

            @return: fasts, slows
        """
        # talib 的源码,它的 ATR 不是 N 日简单平均,而是类似 EMA 的方法计算的指数平均
        atr = talib.ATR(highs, lows, closes, timeperiod=atrPeriod)

        highsMean = talib.EMA(highs, 5)
        lowsMean = talib.EMA(lows, 5)
        closesMean = talib.EMA(closes, 5)

        atrExtremes = np.where(closes > closesMean,
                               ((highs - highsMean)/closes * 100) * (atr/closes * 100),
                               ((lows - lowsMean)/closes * 100) * (atr/closes * 100)
                               )

        fasts = talib.MA(atrExtremes, fastPeriod)
        slows = talib.EMA(atrExtremes, slowPeriod)

        return fasts, slows, np.std(atrExtremes[-slowPeriod:]) 
Example #4
Source File: zscore.py    From jesse with MIT License 6 votes vote down vote up
def zscore(candles: np.ndarray, period=14, matype=0, nbdev=1, source_type="close", sequential=False) -> Union[
    float, np.ndarray]:
    """
    zScore

    :param candles: np.ndarray
    :param period: int - default: 14
    :param matype: int - default: 0
    :param nbdev: int - default: 1
    :param source_type: str - default: "close"
    :param sequential: bool - default=False

    :return: float | np.ndarray
    """
    if not sequential and len(candles) > 240:
        candles = candles[-240:]

    source = get_candle_source(candles, source_type=source_type)
    means = talib.MA(source, timeperiod=period, matype=matype)
    sigmas = talib.STDDEV(source, timeperiod=period, nbdev=nbdev)
    zScores = (source - means) / sigmas

    return zScores if sequential else zScores[-1] 
Example #5
Source File: uiKLine.py    From uiKLine with MIT License 6 votes vote down vote up
def reinit(self,pingzhongname,filename,dailyresultname,jsonname):
        """更换品种,重新初始化"""
        # K线界面
        ui.loadKLineSetting(jsonname)
        ui.KLtitle.setText(pingzhongname+'   '+ui.StrategyName ,size='10pt',color='FFFF00')
        ui.loadData(pd.DataFrame.from_csv(filename))
        ui.loadData_listsig(pd.DataFrame.from_csv(dailyresultname))
        # 初始化界面显示
        self.SHORT_TERM_SHOW_ALL =False
        self.SHORT_TERM_SHOW_FIRST =False
        self.SHORT_TERM_SHOW_LIMIT =False
        ui.initIndicator(u'MA SHORT')
        ui.initIndicator(u'MA LONG')
        ui.initIndicator(u'KLINE')
        ui.initIndicator(u'SHORT TERM(First)')
        ui.initIndicator(u'SHORT TERM(All)')
        ui.initIndicator(u'SHORT TERM(Limit)')
        if ui.signal_show == True :
            ui.initIndicator(u'信号显示')
        else:
            ui.initIndicator(u'信号隐藏')
        ui.refreshAll()
    #----------------------------------------------------------------------
    #  画图相关 
    #---------------------------------------------------------------------- 
Example #6
Source File: ADXSAR.py    From Rqalpha-myquant-learning with Apache License 2.0 6 votes vote down vote up
def before_trading(context):
    prices = history_bars(context.s1, context.window, '1d', fields=['high', 'low', 'close', 'open'])
    highP = prices['high']
    lowP = prices['low']
    closeP = prices['close']
    openP = prices['open']

    context.ADX = ta.ADXR(highP, lowP, closeP, timeperiod=14)
    context.Pdi = ta.PLUS_DI(highP, lowP, closeP, timeperiod=14)
    context.Ndi = ta.MINUS_DI(highP, lowP, closeP, timeperiod=14)

    context.MA_tw = ta.MA(closeP, timeperiod=20)[-5:]
    context.MA_fi = ta.MA(closeP, timeperiod=50)[-5:]
    context.MA_fork = context.MA_tw > context.MA_fi

    context.SAR = ta.SAR(highP, lowP, acceleration=context.acceleration, maximum=0.2)

    # context.JQ_selOpen = (context.ADX[-1]>=20) #& (context.ADX[-2]>=20) & (context.ADX[-1]<=30) & (context.ADX[-2]<=30)
    context.JW_selOpen = (context.Pdi[-1] <= context.Ndi[-1]) & (context.Pdi[-2] >= context.Ndi[-2])
    context.JE_selOpen = (context.MA_fork[-1]) & (context.MA_fork[-2]) & (not context.MA_fork[-3])
    context.JR_selOpen = (context.SAR[-1] >= 0.95 * openP[-1]) & (context.SAR[-2] <= 1.05 * closeP[-2])
    context.J_selOpen = context.JQ_selOpen & context.JW_selOpen & context.JE_selOpen & context.JR_selOpen

    # context.JQ_buyOpen = context.JQ_selOpen
    context.JW_buyOpen = (context.Pdi[-1] >= context.Ndi[-1]) & (context.Pdi[-2] <= context.Ndi[-2])
    context.JE_buyOpen = (not context.MA_fork[-1]) & (not context.MA_fork[-2]) & (not context.MA_fork[-3])
    context.JR_buyOpen = (context.SAR[-2] >= 0.95 * openP[-2]) & (context.SAR[-1] <= 1.05 * closeP[-1])
    context.J_buyOpen = context.JQ_buyOpen & context.JW_buyOpen & context.JE_buyOpen & context.JR_buyOpen


# 你选择的期货数据更新将会触发此段逻辑,例如日线或分钟线更新 
Example #7
Source File: DualMA.py    From equant with GNU General Public License v2.0 6 votes vote down vote up
def handle_data(context):
    if len(Close()) < p2:
        return
    
    # 使用talib计算均价
    ma1 = talib.MA(Close(), p1)
    ma2 = talib.MA(Close(), p2) 

    # 执行下单操作
    if MarketPosition() <= 0 and ma1[-1] > ma2[-1]:
        Buy(1, Close()[-1])
    if MarketPosition() >= 0 and ma1[-1] < ma2[-1]:
        SellShort(1, Close()[-1])
    
    # 绘制指标图形
    PlotNumeric("ma1", ma1[-1], RGB_Red())
    PlotNumeric("ma2", ma2[-1], RGB_Green())    
    PlotNumeric("fit", NetProfit() + FloatProfit() - TradeCost(), RGB_Red(), False) 
Example #8
Source File: DMA.py    From equant with GNU General Public License v2.0 6 votes vote down vote up
def handle_data(context):
    if len(Close()) < p2:
        return;
        
    ma1 = talib.MA(Close(), p1)
    ma2 = talib.MA(Close(), p2)  
    
    his = BarStatus() != 2
    if his:
        his_trigger(ma1, ma2) 
    else: 
        tim_trigger(ma1, ma2) 
    
    PlotNumeric("ma1", ma1[-1], 0xFF0000)
    PlotNumeric("ma2", ma2[-1], 0x00aa00) 
    fit = NetProfit() + FloatProfit() - TradeCost() if his else A_CoverProfit() + A_ProfitLoss() - A_Cost()
    PlotNumeric("fit", fit, 0x0000FF, False) 
Example #9
Source File: QAQuery_Advance_Test.py    From QUANTAXIS with MIT License 6 votes vote down vote up
def ma30_cross(data):
        MA5 = talib.MA(data.close, 5)
        MA30 = talib.MA(data.close, 30)
    
        MA30_CROSS_JX = CROSS(MA5, MA30)
        MA30_CROSS_JX_Integral = Timeline_Integral_with_cross_before(MA30_CROSS_JX)
        MA30_CROSS_SX = CROSS(MA30, MA5)
        MA30_CROSS_SX_Integral = Timeline_Integral_with_cross_before(MA30_CROSS_SX)
    
        MA30_CROSS = pd.DataFrame(columns=['MA30_CROSS', 'MA30_CROSS_JX', 'MA30_CROSS_SX', 'MA30_TP_CROSS_JX', 'MA30_TP_CROSS_SX'], index=data.index)
        MA30_CROSS.loc[MA30_CROSS_JX == 1, 'MA30_CROSS'] = 1
        MA30_CROSS.loc[MA30_CROSS_SX == 1, 'MA30_CROSS'] = -1
        MA30_CROSS['MA30_CROSS_JX'] = Timeline_Integral_with_cross_before(MA30_CROSS_JX)
        MA30_CROSS['MA30_CROSS_SX'] = Timeline_Integral_with_cross_before(MA30_CROSS_SX)
    
        # MA30 前29个是 NaN,处理会抛出 Warning,使用 [29:] 则不会计算 NaN,相应的 return_index+29
        MA30_tp_min, MA30_tp_max = signal.argrelextrema(MA30.values[29:], np.less)[0] + 29, signal.argrelextrema(MA30.values[29:], np.greater)[0] + 29
        MA30_TP_CROSS = pd.DataFrame(columns=['MA30_TP_CROSS_JX', 'MA30_TP_CROSS_SX'], index=data.index)
        MA30_TP_CROSS['MA30_TP_CROSS_SX'] = MA30_TP_CROSS['MA30_TP_CROSS_JX'] = 0
        MA30_TP_CROSS.iloc[MA30_tp_min, MA30_TP_CROSS.columns.get_loc('MA30_TP_CROSS_JX')] = 1
        MA30_TP_CROSS.iloc[MA30_tp_max, MA30_TP_CROSS.columns.get_loc('MA30_TP_CROSS_SX')] = 1
        MA30_CROSS['MA30_TP_CROSS_JX'] = Timeline_Integral_with_cross_before(MA30_TP_CROSS['MA30_TP_CROSS_JX'])
        MA30_CROSS['MA30_TP_CROSS_SX'] = Timeline_Integral_with_cross_before(MA30_TP_CROSS['MA30_TP_CROSS_SX'])
        return MA30_CROSS 
Example #10
Source File: DyStockDataUtility.py    From DevilYuan with MIT License 6 votes vote down vote up
def getAtrRatio(df, period=14):
        """
            平均波动率:ATR(14)/MA(14)
        """
        highs = df['high']
        lows = df['low']
        closes = df['close']

        atr = talib.ATR(highs, lows, closes, timeperiod=period)
        ma = talib.MA(closes, timeperiod=period)

        volatility = atr/ma

        s = pd.Series(volatility, index=df.index, name='volatility').dropna()

        return s 
Example #11
Source File: DyST_IntraDayT.py    From DevilYuan with MIT License 6 votes vote down vote up
def _getAtrExtreme(cls, highs, lows, closes, atrPeriod=14, slowPeriod=30, fastPeriod=3):
        """
            获取TTI ATR Exterme通道, which is based on 《Volatility-Based Technical Analysis》
            TTI is 'Trading The Invisible'

            @return: fasts, slows
        """
        # talib 的源码,它的 ATR 不是 N 日简单平均,而是类似 EMA 的方法计算的指数平均
        atr = talib.ATR(highs, lows, closes, timeperiod=atrPeriod)

        highsMean = talib.EMA(highs, 5)
        lowsMean = talib.EMA(lows, 5)
        closesMean = talib.EMA(closes, 5)

        atrExtremes = np.where(closes > closesMean,
                               ((highs - highsMean)/closes * 100) * (atr/closes * 100),
                               ((lows - lowsMean)/closes * 100) * (atr/closes * 100)
                               )

        fasts = talib.MA(atrExtremes, fastPeriod)
        slows = talib.EMA(atrExtremes, slowPeriod)

        return fasts, slows, np.std(atrExtremes[-slowPeriod:]) 
Example #12
Source File: ABuNDMa.py    From abu with GNU General Public License v3.0 6 votes vote down vote up
def _calc_ma_from_ta(prices, time_period=10, from_calc=EMACalcType.E_MA_MA):
    """
    使用talib计算ma,即透传talib.MA or talib.EMA计算结果
    :param prices: 收盘价格序列,pd.Series或者np.array
    :param time_period: 移动平均的N值,int
    :param from_calc: EMACalcType enum对象,移动移动平均使用的方法
    """

    import talib
    if isinstance(prices, pd.Series):
        prices = prices.values

    if from_calc == EMACalcType.E_MA_MA:
        ma = talib.MA(prices, timeperiod=time_period)
    else:
        ma = talib.EMA(prices, timeperiod=time_period)
    return ma 
Example #13
Source File: api_strategy.py    From QTSSTM4 with Apache License 2.0 5 votes vote down vote up
def ma(order, buy_index, sell_index,rate,args):
    close = []
    for i in order:
        close.append(i['close'])
    close = np.array(close)
    result = talib.MA(close, timeperiod=int(args))
    result = [float(x) for x in result]
    if(result[-1] > close[-1]):
        buy_index.append(float(rate))
    elif(result[-1] < close[-1]):
        sell_index.append(float(rate))
    else:
        pass
    print('2') 
Example #14
Source File: SpdTrade2.py    From equant with GNU General Public License v2.0 5 votes vote down vote up
def handle_data(context):
    prc_lst1 = Close(code1, bt, bi)
    prc_lst2 = Close(code2, bt, bi)
    if len(prc_lst1) == 0 or len(prc_lst2) == 0:
        return

    # 生成价差序列
    global spds
    spd_c = prc_lst1[-1] - prc_lst2[-1]
    if len(prc_lst1) > len(spds):
        spds.append(spd_c)
    else:
        spds[-1] = spd_c    

    if len(spds) < p2:
        return

    # 计算价差ma
    sma1 = talib.MA(np.array(spds), p1)  
    sma2 = talib.MA(np.array(spds), p2)         

    # 根据两根ma的交叉关系下单
    if sma1[-1] > sma2[-1] + dot * PriceTick() and MarketPosition(code1) <= 0:
        Buy(qty, prc_lst1[-1], code1)
        SellShort(qty, prc_lst2[-1], code2)
    elif sma1[-1] < sma2[-1] - dot * PriceTick() and MarketPosition(code1) >= 0:
        SellShort(qty, prc_lst1[-1], code1)
        Buy(qty, prc_lst2[-1], code2)

    # 绘制指标线   
    PlotNumeric("sma1", sma1[-1], 0x0000FF, False)
    PlotNumeric("sma2", sma2[-1], 0xFF0000, False)
    PlotNumeric("fit", NetProfit() - TradeCost(), RGB_Purple(), False, True) 
Example #15
Source File: TestMA.py    From equant with GNU General Public License v2.0 5 votes vote down vote up
def handle_data(context):
    ma11 = talib.MA(Close(contA, 'M', 1), p1, 0)
    ma12 = talib.MA(Close(contA, 'M', 1), p2, 0)

    ma31 = talib.MA(Close(contA, 'M', 3), p1, 0)
    ma32 = talib.MA(Close(contA, 'M', 3), p2, 0)

    diff2 = getVn(ma11, 2) - getVn(ma31, 2)    

    PlotNumeric("ma11", ma11[-1], color=RGB_Red())
    PlotNumeric("ma12", ma12[-1], color=RGB_Green())
    PlotNumeric("diff2", diff2, color=RGB_Blue(), main=False) 
Example #16
Source File: TestVol.py    From equant with GNU General Public License v2.0 5 votes vote down vote up
def handle_data(context):
    
    vol = talib.MA(Vol().astype(float), timeperiod=20, matype=0)
    PlotNumeric("VOL", vol[-1], main=False, color=RGB_Yellow()) 
Example #17
Source File: TestPlotIcon.py    From equant with GNU General Public License v2.0 5 votes vote down vote up
def handle_data(context):
   
    ma1 = talib.MA(Close(), timeperiod=5, matype=0)
    ma2 = talib.MA(Close(), timeperiod=20, matype=0)

    diff = ma1[-1] - ma2[-1]

    PlotNumeric("ICON",diff, color=RGB_Brown(),main=False)
    if diff == 0:
        PlotIcon(diff, 14)    
    elif diff > 0: 
        PlotIcon(diff, 15)
    else:
        PlotIcon(diff, 9) 
Example #18
Source File: TestPlotText.py    From equant with GNU General Public License v2.0 5 votes vote down vote up
def handle_data(context):
    global N, keep
    ma1 = talib.MA(Close(), timeperiod=N, matype=0)
    ma2 = talib.MA(Close(), timeperiod=P, matype=0)

    keep += 1

    if keep % 5 == 0:
        color=RGB_Blue()
    else:
        color=RGB_Red() 

    PlotText(Open()[-1], "A", main=True, color=color, barsback=N)
    #UnPlotText(True, N+1) 
Example #19
Source File: talib_indicators.py    From qtpylib with Apache License 2.0 5 votes vote down vote up
def MA(data, **kwargs):
    _check_talib_presence()
    prices = _extract_series(data)
    return talib.MA(prices, **kwargs) 
Example #20
Source File: talib_wrapper.py    From tia with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def MA(series, n=30, matype=0):
    return _series_to_series(series, talib.MA, n, matype) 
Example #21
Source File: features.py    From trading-server with GNU General Public License v3.0 5 votes vote down vote up
def SMA(self, period: int, bars: int):
        """
        Simple moving average of previous n bars close price.

        SMA = (sum of all closes in period) / period.
        """
        self.check_bars_type(bars)

        ma = ta.MA(bars['close'], timeperiod=period, matype=0)

        return ma 
Example #22
Source File: Strategy_fun.py    From BakTst_Org with Apache License 2.0 5 votes vote down vote up
def ma(data,index):
    close_arry = tranform_arry(data['close'])
    index['ma'] = talib.MA(close_arry, timeperiod=10) 
Example #23
Source File: technical_indicators.py    From 51bitqunt with MIT License 5 votes vote down vote up
def calculate_cmi_indicator(df):  # RSI

    cmi_period = 30
    cmi_ma_period = 10
    roc = df['close'].diff(cmi_period)
    h1 = ta.MAX(df['high'], cmi_period) - ta.MIN(df['low'], cmi_period)
    cmi = abs(roc / h1) * 100
    cmi_ma = ta.MA(cmi, cmi_ma_period)  # rolling.
    return cmi_ma 
Example #24
Source File: ctaLineBar.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def getRuntimeMa(self, ma_num):
        """
        实时计算MA得值
        :param ma_num:第几条均线, 1,对应inputMa1Len,,,,
        :return:
        """
        if ma_num not in [1, 2, 3]:
            return None

        ma_len = 1
        if ma_num == 1 and self.inputMa1Len > 0:
            ma_len = self.inputMa1Len
        elif ma_num == 2 and self.inputMa2Len > 0:
            ma_len = self.inputMa2Len
        elif ma_num == 3 and self.inputMa3Len > 0:
            ma_len = self.inputMa3Len
        else:
            return None
        ma_data_len = ma_len + 2

        if len(self.lineBar) < ma_data_len:
            self.debugCtaLog(u'数据未充分,当前Bar数据数量:{},计算实时MA {} 需要:{}'.
                             format(len(self.lineBar), ma_len, ma_data_len))
            return None

        # 3、获取前InputN周期(不包含当前周期)的K线
        listClose = [x.close for x in self.lineBar[-ma_data_len:]]
        barMa = ta.MA(np.array(listClose, dtype=float), ma_len)[-1]
        barMa = round(float(barMa), self.round_n)

        return barMa

    #---------------------------------------------------------------------- 
Example #25
Source File: CrossMarketSpotArbitrageStrategy.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def onBarRatio(self, bar):
        """比率线的OnBar事件"""
        # 获取比率线的长度
        l = len(self.lineRatio.lineStateMean)
        if l > 0:
            ma = self.lineRatio.lineStateMean[-1]
        else:
            ma = bar.close

        if l > 6:
            listKf = [x for x in self.lineRatio.lineStateMean[-7:-1]]
            # MA():?
            # numpy.array(listKf, dtype = float:转浮点型
            malist = ta.MA(numpy.array(listKf, dtype=float), 5)
            ma5 = malist[-1]
            ma5_ref1 = malist[-2]
            if ma5 <= 0 or ma5_ref1 <= 0:
                self.writeCtaLog(u'卡尔曼均线异常')
                return
            # ?
            self.m1_atan = math.atan((ma5 / ma5_ref1 - 1) * 100 * 180 / math.pi)
        # M1的切线队列长度 > 10
        if len(self.m1_atan_list) > 10:
            del self.m1_atan_list[0]
        # m1_atan_list加入m1_atan
        self.m1_atan_list.append(self.m1_atan)
        # displayLastBar()显示最后一个Bar的信息
        self.writeCtaLog(self.lineRatio.displayLastBar())

    # 残差线更新 
Example #26
Source File: DyStockDataUtility.py    From DevilYuan with MIT License 5 votes vote down vote up
def getAtrRatio(df, period=14):
        """
            平均波动率:ATR(14)/MA(14)
        """
        highs = df['high']
        lows = df['low']
        closes = df['close']

        atr = talib.ATR(highs, lows, closes, timeperiod=period)
        ma = talib.MA(closes, timeperiod=period)

        volatility = atr/ma

        s = pd.Series(volatility, index=df.index, name='volatility').dropna()

        return s 
Example #27
Source File: QAQuery_Advance_Test.py    From QUANTAXIS with MIT License 5 votes vote down vote up
def ifup20_TA(data):
        # TA-lib计算
        return (talib.MA(data.close, 5) - talib.MA(data.close, 20)).dropna() > 0

    # 写个自定义指标 MAX_FACTOR TA-lib计算 
Example #28
Source File: QAQuery_Advance_Test.py    From QUANTAXIS with MIT License 5 votes vote down vote up
def boll_cross(data):
        BBANDS = QA.TA_BBANDS(data.close, timeperiod=20, nbdevup=2)

        BOLL_CROSS = pd.DataFrame(columns=['min_peak', 'max_peak', 'BOLL_CROSS', 'BOLL_CROSS_JX', 'BOLL_CROSS_SX'], index=data.index)
        
        # 防止插针行情突然搞乱
        data['smooth_low'] = talib.MA(data.low, 2)
        data['smooth_high'] = talib.MA(data.high, 2)

        BOLL_CROSS['min_peak'] = data.apply(lambda x: min(x['open'], x['close'], x['smooth_low']), axis=1)
        BOLL_CROSS['max_peak'] = data.apply(lambda x: max(x['open'], x['close'], x['smooth_high']), axis=1)

        BOLL_CROSS_JX = CROSS(BOLL_CROSS['min_peak'], BBANDS[:,2])
        BOLL_CROSS_SX = CROSS(BBANDS[:,0], BOLL_CROSS['max_peak'])

        BOLL_CROSS.loc[BOLL_CROSS_JX == 1, 'BOLL_CROSS'] = 1
        BOLL_CROSS.loc[BOLL_CROSS_SX == 1, 'BOLL_CROSS'] = -1
        BOLL_TP_CROSS = pd.DataFrame(columns=['BOLL_TP_CROSS_JX', 'BOLL_TP_CROSS_SX'], index=data.index)
        BOLL_TP_CROSS['BOLL_TP_CROSS_SX'] = BOLL_TP_CROSS['BOLL_TP_CROSS_JX'] = 0
        BOLL_TP_CROSS.loc[BOLL_CROSS_JX == 1, 'BOLL_TP_CROSS_JX'] = 1
        BOLL_TP_CROSS.loc[BOLL_CROSS_SX == 1, 'BOLL_TP_CROSS_SX'] = 1

        BOLL_CROSS = BOLL_CROSS.assign(BOLL_UB=BBANDS[:,0])
        BOLL_CROSS = BOLL_CROSS.assign(BOLL_MA=BBANDS[:,1])
        BOLL_CROSS = BOLL_CROSS.assign(BOLL_LB=BBANDS[:,2])
        BOLL_CROSS['BOLL_CROSS_JX'] = QA.Timeline_Integral_with_cross_before(BOLL_TP_CROSS['BOLL_TP_CROSS_JX'])
        BOLL_CROSS['BOLL_CROSS_SX'] = QA.Timeline_Integral_with_cross_before(BOLL_TP_CROSS['BOLL_TP_CROSS_SX'])
        return BOLL_CROSS 
Example #29
Source File: QAQuery_Advance_Test.py    From QUANTAXIS with MIT License 5 votes vote down vote up
def boll_cross_lf(data):
        BBANDS = QA.TA_BBANDS(data.close, timeperiod=20, nbdevup=2)

        BOLL_CROSS_JX1 = CROSS(data.open, BBANDS[:,2])
        BOLL_CROSS_JX2 = CROSS(data.close, BBANDS[:,2])
        BOLL_CROSS_JX3 = CROSS(talib.MA(data.low, 2), BBANDS[:,2])
        BOLL_CROSS_SX1 = CROSS(BBANDS[:,0], data.open)
        BOLL_CROSS_SX2 = CROSS(BBANDS[:,0], data.close)
        BOLL_CROSS_SX3 = CROSS(BBANDS[:,0], talib.MA(data.high, 2))

        BOLL_CROSS = pd.DataFrame(columns=['BOLL_CROSS', 'BOLL_CROSS_JX', 'BOLL_CROSS_SX'], index=data.index)
        BOLL_CROSS.loc[BOLL_CROSS_JX1 == 1, 'BOLL_CROSS'] = 1
        BOLL_CROSS.loc[BOLL_CROSS_JX2 == 1, 'BOLL_CROSS'] = 1
        BOLL_CROSS.loc[BOLL_CROSS_JX3 == 1, 'BOLL_CROSS'] = 1
        BOLL_CROSS.loc[BOLL_CROSS_SX1 == 1, 'BOLL_CROSS'] = -1
        BOLL_CROSS.loc[BOLL_CROSS_SX2 == 1, 'BOLL_CROSS'] = -1
        BOLL_CROSS.loc[BOLL_CROSS_SX3 == 1, 'BOLL_CROSS'] = -1
        BOLL_TP_CROSS = pd.DataFrame(columns=['BOLL_TP_CROSS_JX', 'BOLL_TP_CROSS_SX'], index=data.index)
        BOLL_TP_CROSS['BOLL_TP_CROSS_SX'] = BOLL_TP_CROSS['BOLL_TP_CROSS_JX'] = 0
        BOLL_TP_CROSS.loc[(BOLL_CROSS_JX1 | BOLL_CROSS_JX2 | BOLL_CROSS_JX3) == 1, 'BOLL_TP_CROSS_JX'] = 1
        BOLL_TP_CROSS.loc[(BOLL_CROSS_SX1 | BOLL_CROSS_SX2 | BOLL_CROSS_SX3) == 1, 'BOLL_TP_CROSS_SX'] = 1

        BOLL_CROSS = BOLL_CROSS.assign(BOLL_UB=BBANDS[:,0])
        BOLL_CROSS = BOLL_CROSS.assign(BOLL_MA=BBANDS[:,1])
        BOLL_CROSS = BOLL_CROSS.assign(BOLL_LB=BBANDS[:,2])
        BOLL_CROSS['BOLL_CROSS_JX'] = QA.Timeline_Integral_with_cross_before(BOLL_TP_CROSS['BOLL_TP_CROSS_JX'])
        BOLL_CROSS['BOLL_CROSS_SX'] = QA.Timeline_Integral_with_cross_before(BOLL_TP_CROSS['BOLL_TP_CROSS_SX'])
        return BOLL_CROSS 
Example #30
Source File: ta_indicator_mixin.py    From strategy with Apache License 2.0 5 votes vote down vote up
def ma_close(self, sym, frequency, period=30, ma_type=0):
        if not self.kbars_ready(sym, frequency):
            return []

        closes = self.close(sym, frequency)
        ma = ta.MA(closes, timeperiod=period, matype=ma_type)

        return ma