Python talib 模块,RSI 实例源码

我们从Python开源项目中,提取了以下38个代码示例,用于说明如何使用talib.RSI

项目:InplusTrader_Linux    作者:zhengwsh    | 项目源码 | 文件源码
def onInit(self):
        """????????????????"""
        self.writeCtaLog(u'%s?????' %self.name)

        # ???RSI????
        self.rsiBuy = 50 + self.rsiEntry
        self.rsiSell = 50 - self.rsiEntry

        # ????????????????????????
        initData = self.loadBar(self.initDays)
        for bar in initData:
            self.onBar(bar)

        self.putEvent()

    #----------------------------------------------------------------------
项目:catalyst    作者:enigmampc    | 项目源码 | 文件源码
def isBuy(context, analysis):
    # Bullish SMA Crossover
    if (getLast(analysis, 'sma_test') == 1):
        # Bullish MACD
        if (getLast(analysis, 'macd_test') == 1):
            return True

    # # Bullish Stochastics
    # if(getLast(analysis, 'stoch_over_sold') == 1):
    #     return True

    # # Bullish RSI
    # if(getLast(analysis, 'rsi_over_sold') == 1):
    #     return True

    return False
项目:catalyst    作者:enigmampc    | 项目源码 | 文件源码
def isSell(context, analysis):
    # Bearish SMA Crossover
    if (getLast(analysis, 'sma_test') == 0):
        # Bearish MACD
        if (getLast(analysis, 'macd_test') == 0):
            return True

    # # Bearish Stochastics
    # if(getLast(analysis, 'stoch_over_bought') == 0):
    #     return True

    # # Bearish RSI
    # if(getLast(analysis, 'rsi_over_bought') == 0):
    #     return True

    return False
项目:stock_dqn_f    作者:wdy06    | 项目源码 | 文件源码
def getStrategy_RSI(start_trading_day,end_trading_day,_time,_close):
    point = []
    iday = _time.index(start_trading_day)
    eday = _time.index(end_trading_day)
    rsi = ta.RSI(np.array(_close,dtype='f8'),timeperiod=14)
    rsi = rsi[iday:eday]
    point.append(0)
    for i in range(1,len(rsi)):
        if (rsi[i] <= 30) and (rsi[i - 1] > 30):
            point.append(1)
        elif (rsi[i] >= 50) and (rsi[i - 1] < 50):
            point.append(-1)
        else:
            point.append(0)

    return point
项目:stock_dqn    作者:wdy06    | 项目源码 | 文件源码
def getStrategy_RSI(start_trading_day,end_trading_day,_time,_close):
    point = []
    iday = _time.index(start_trading_day)
    eday = _time.index(end_trading_day)
    rsi = ta.RSI(np.array(_close,dtype='f8'),timeperiod=14)
    rsi = rsi[iday:eday]
    point.append(0)
    for i in range(1,len(rsi)):
        if (rsi[i] <= 30) and (rsi[i - 1] > 30):
            point.append(1)
        elif (rsi[i] >= 50) and (rsi[i - 1] < 50):
            point.append(-1)
        else:
            point.append(0)

    return point
项目:zStock    作者:superxhy    | 项目源码 | 文件源码
def KDJ_COM(high, low, close, fastk_period=9, slowk_period=3, slowd_period=3, fixpre=True) :
        len1 = len(high)
        len2 = len(low)
        len3 = len(close)
        if len1 != len2 or len1 != len3:
            print (("KDJ_COM input invalid for len:%s %s %s " %(str(len1),str(len2),str(len3))))
            return np.array([np.nan]),np.array([np.nan]),np.array([np.nan])
        hValue = SecurityDataSrcBase.HHV_COM(high, fastk_period, fixpre)
        lValue = SecurityDataSrcBase.LLV_COM(low, fastk_period, fixpre)
        rsValue = (close - lValue) / (hValue - lValue) * 100
        kValue = SecurityDataSrcBase.SMA_COM(rsValue, slowk_period)
        dValue = SecurityDataSrcBase.SMA_COM(kValue,  slowd_period)
        jValue = 3 * kValue - 2 * dValue
        return kValue, dValue, jValue

    # RSI COMMON
项目:autoxd    作者:nessessary    | 项目源码 | 文件源码
def test_JiShuZhiBiao():
    """??????"""
    pl = publish.Publish()
    code = '002440'
    code = '999999'

    #?????????rsi
    df = FenshiEx(code, '2014-10-8', '2014-10-8').df
    #df = FENSHI_MA(df)
    df = FENSHI_BIAS(df)
    df['rsi'] = RSI(df['p'])
    df1 = df.drop(['v','b','bias','rsi'], axis=1)
    ui.drawDf(pl, df1)
    df2 = df.drop(['v','b','p','avg', 'rsi'], axis=1)
    ui.drawDf(pl, df2)
    df2 = df.drop(['v','b','p','avg', 'bias'], axis=1)
    ui.drawDf(pl, df2)
项目:DeepTrade_keras    作者:happynoom    | 项目源码 | 文件源码
def __init__(self, selector):
        self.selector = selector
        self.supported = {"ROCP", "OROCP", "HROCP", "LROCP", "MACD", "RSI", "VROCP", "BOLL", "MA", "VMA", "PRICE_VOLUME"}
        self.feature = []
项目:InplusTrader_Linux    作者:zhengwsh    | 项目源码 | 文件源码
def handle_bar(context, bar_dict):
    # ?????????????

    # bar_dict[order_book_id] ?????????bar??
    # context.portfolio ???????????????

    # ??order_shares(id_or_ins, amount)??????

    # TODO: ??????????

    # ????????????loop?????????RSI??
    for stock in context.stocks:
        # ??????
        prices = history_bars(stock, context.TIME_PERIOD+1, '1d', 'close')

        # ?Talib??RSI?
        rsi_data = talib.RSI(prices, timeperiod=context.TIME_PERIOD)[-1]

        cur_position = context.portfolio.positions[stock].quantity
        # ??????30%???????
        target_available_cash = context.portfolio.cash * context.ORDER_PERCENT

        # ?RSI???????????????
        if rsi_data > context.HIGH_RSI and cur_position > 0:
            order_target_value(stock, 0)

        # ?RSI?????????????cash?????????
        if rsi_data < context.LOW_RSI:
            logger.info("target available cash caled: " + str(target_available_cash))
            # ??????????? - 100shares?????ricequant ?order management system reject?
            order_value(stock, target_available_cash)
项目:InplusTrader_Linux    作者:zhengwsh    | 项目源码 | 文件源码
def handle_bar(context, bar_dict):
    # ?????????????

    # bar_dict[order_book_id] ?????????bar??
    # context.portfolio ???????????????

    # ??order_shares(id_or_ins, amount)??????

    # TODO: ??????????

    # ????????????loop?????????RSI??
    for stock in context.stocks:
        # ??????
        prices = history_bars(stock, context.TIME_PERIOD+1, '1d', 'close')

        # ?Talib??RSI?
        rsi_data = talib.RSI(prices, timeperiod=context.TIME_PERIOD)[-1]

        cur_position = context.portfolio.positions[stock].quantity
        # ??????30%???????
        target_available_cash = context.portfolio.cash * context.ORDER_PERCENT

        # ?RSI???????????????
        if rsi_data > context.HIGH_RSI and cur_position > 0:
            order_target_value(stock, 0)

        # ?RSI?????????????cash?????????
        if rsi_data < context.LOW_RSI:
            logger.info("target available cash caled: " + str(target_available_cash))
            # ??????????? - 100shares?????ricequant ?order management system reject?
            order_value(stock, target_available_cash)
项目:InplusTrader_Linux    作者:zhengwsh    | 项目源码 | 文件源码
def handle_bar(context, bar_dict):
    # ?????????????

    # bar_dict[order_book_id] ?????????bar??
    # context.portfolio ???????????????

    # ??order_shares(id_or_ins, amount)??????

    # TODO: ??????????

    # ????????????loop?????????RSI??
    for stock in context.stocks:
        # ??????
        prices = history_bars(stock, context.TIME_PERIOD+1, '1d', 'close')

        # ?Talib??RSI?
        rsi_data = talib.RSI(prices, timeperiod=context.TIME_PERIOD)[-1]

        cur_position = context.portfolio.positions[stock].quantity
        # ??????30%???????
        target_available_cash = context.portfolio.cash * context.ORDER_PERCENT

        # ?RSI???????????????
        if rsi_data > context.HIGH_RSI and cur_position > 0:
            order_target_value(stock, 0)

        # ?RSI?????????????cash?????????
        if rsi_data < context.LOW_RSI:
            logger.info("target available cash caled: " + str(target_available_cash))
            # ??????????? - 100shares?????ricequant ?order management system reject?
            order_value(stock, target_available_cash)
项目:catalyst    作者:enigmampc    | 项目源码 | 文件源码
def handle_data(context, data):
    print('handling bar: {}'.format(data.current_dt))

    price = data.current(context.asset, 'close')
    print('got price {price}'.format(price=price))

    prices = data.history(
        context.asset,
        fields='price',
        bar_count=20,
        frequency='30T'
    )
    last_traded = prices.index[-1]
    print('last candle date: {}'.format(last_traded))

    rsi = talib.RSI(prices.values, timeperiod=14)[-1]
    print('got rsi: {}'.format(rsi))

    # If base_price is not set, we use the current value. This is the
    # price at the first bar which we reference to calculate price_change.
    if context.base_price is None:
        context.base_price = price

    price_change = (price - context.base_price) / context.base_price
    cash = context.portfolio.cash

    # Now that we've collected all current data for this frame, we use
    # the record() method to save it. This data will be available as
    # a parameter of the analyze() function for further analysis.
    record(
        price=price,
        price_change=price_change,
        cash=cash
    )
项目:pyktrader2    作者:harveywwu    | 项目源码 | 文件源码
def RSI(df, n, field='close'):
    return pd.Series(talib.RSI(df[field].values, n), index = df.index, name='RSI%s' % str(n))
项目:pyktrader2    作者:harveywwu    | 项目源码 | 文件源码
def rsi(df, n, field = 'close'):
    RSI_key = 'RSI%s' % str(n)
    df[RSI_key][-1] = talib.RSI(df[field][(-n-1):], n)[-1]
项目:pyktrader2    作者:harveywwu    | 项目源码 | 文件源码
def RSI_F(df, n, field='close'):
    UpMove = df[field] - df[field].shift(1)
    DoMove = df[field].shift(1) - df[field]
    UpD = pd.Series(UpMove)
    DoD = pd.Series(DoMove)
    UpD[(UpMove <= 0)] = 0
    DoD[(DoMove <= 0)] = 0
    PosDI = pd.Series(pd.ewma(UpD, com = n-1), name = "RSI"+str(n)+'_UP')
    NegDI = pd.Series(pd.ewma(DoD, com = n-1), name = "RSI"+str(n)+'_DN')
    RSI = pd.Series(PosDI / (PosDI + NegDI) * 100, name = 'RSI' + str(n))
    return pd.concat([RSI, PosDI, NegDI], join='outer', axis=1)
项目:pyktrader2    作者:harveywwu    | 项目源码 | 文件源码
def rsi_f(df, n, field = 'close'):
    RSI_key = 'RSI%s' % str(n)
    dx = df[field][-1] - df[field][-2]
    alpha = 1.0/n
    if dx > 0:
        upx = dx
        dnx = 0
    else:
        upx = 0
        dnx = -dx
    udi = df[RSI_key + '_UP'][-1] = df[RSI_key + '_UP'][-2] * (1 - alpha) + upx * alpha
    ddi = df[RSI_key + '_DN'][-1] = df[RSI_key + '_DN'][-2] * (1 - alpha) + dnx * alpha
    df[RSI_key][-1] = udi/(udi + ddi) * 100.0

#True Strength Index
项目:dash-technical-charting    作者:plotly    | 项目源码 | 文件源码
def add_RSI(self, timeperiod=14,
            type='line', color='secondary', **kwargs):
    """Relative Strength Index."""

    if not self.has_close:
        raise Exception()

    utils.kwargs_check(kwargs, VALID_TA_KWARGS)
    if 'kind' in kwargs:
        type = kwargs['kind']

    name = 'RSI({})'.format(str(timeperiod))
    self.sec[name] = dict(type=type, color=color)
    self.ind[name] = talib.RSI(self.df[self.cl].values,
                               timeperiod)
项目:LIE    作者:EmbraceLife    | 项目源码 | 文件源码
def __init__(self, selector):
        self.selector = selector
        self.supported = {"ROCP", "OROCP", "HROCP", "LROCP", "MACD", "RSI", "VROCP", "BOLL", "MA", "VMA", "PRICE_VOLUME"}
        self.feature = []
项目:LIE    作者:EmbraceLife    | 项目源码 | 文件源码
def __init__(self, selector):
        self.selector = selector
        self.supported = {"ROCP", "OROCP", "HROCP", "LROCP", "MACD", "RSI", "VROCP", "BOLL", "MA", "VMA", "PRICE_VOLUME"}
        self.feature = []
项目:LIE    作者:EmbraceLife    | 项目源码 | 文件源码
def __init__(self, selector):
        self.selector = selector
        self.supported = {"ROCP", "OROCP", "HROCP", "LROCP", "MACD", "RSI", "VROCP", "BOLL", "MA", "VMA", "PRICE_VOLUME"}
        self.feature = []
项目:LIE    作者:EmbraceLife    | 项目源码 | 文件源码
def __init__(self, selector):
        self.selector = selector
        self.supported = {"ROCP", "OROCP", "HROCP", "LROCP", "MACD", "RSI", "VROCP", "BOLL", "MA", "VMA", "PRICE_VOLUME"}
        self.feature = []
项目:DeepTrade    作者:happynoom    | 项目源码 | 文件源码
def __init__(self, selector):
        self.selector = selector
        self.supported = {"ROCP", "OROCP", "HROCP", "LROCP", "MACD", "RSI", "VROCP", "BOLL", "MA", "VMA", "PRICE_VOLUME"}
        self.feature = []
项目:zStock    作者:superxhy    | 项目源码 | 文件源码
def RSI_CN(close, timeperiod=6):
        return tl.RSI(close, timeperiod)

    # MA
项目:futuquant    作者:FutunnOpen    | 项目源码 | 文件源码
def rsi(self, n, array=False):
        """RSI??"""
        result = talib.RSI(self.close, n)
        if array:
            return result
        return result[-1]

    # ----------------------------------------------------------------------
项目:autoxd    作者:nessessary    | 项目源码 | 文件源码
def RSI(self):
        """??????? 30????? 70????"""
        closes = self.getCloses()
        return talib.RSI(closes)
项目:autoxd    作者:nessessary    | 项目源码 | 文件源码
def RSI(closes, timeperiod=12):
    """??????? 30????? 70???? return: np.darray"""
    closes = np.array(closes)
    closes = closes[np.isnan(closes) == False]
    return talib.RSI(closes, timeperiod)
项目:autoxd    作者:nessessary    | 项目源码 | 文件源码
def unittest_ma():
    closes = Guider('600100').getCloses()
    print(MA(closes))
    fours = FOUR(closes)
    print( len(closes), len(fours))
    print(fours)
    rsi = RSI(closes)
    #rsi = rsi/100 - 0.5
    rsi -= 50
    fours *= 100
    pl.figure
    #pl.plot(closes)
    pl.plot(fours,'r')
    pl.plot(rsi)
    pl.show()
项目:autoxd    作者:nessessary    | 项目源码 | 文件源码
def test_fenshi_rsi():
    """???????rsi??"""
    code = '300059'
    fenshi = CreateFenshiPd(code, '2015-8-6').resample('1min').mean().dropna()
    print( fenshi)
    closes = fenshi['p']
    print(closes)
    rsi = RSI(closes, 6)
    print(rsi)
    ui.DrawTs(pl, rsi)
项目:BlackCoffee    作者:IMYin    | 项目源码 | 文件源码
def get_rsi_info(df):
    """
    calculate rsi quotation.
    :param df:
    :return: rsi
    """
    close = get_close_data(df)
    rsi = ta.RSI(close, timeperiod=12)
    return pd.DataFrame({u'rsi': rsi[-view_days:]})
项目:DataAnalysis    作者:IMYin    | 项目源码 | 文件源码
def Get_TA(df_Code,Dist):
    operate_array1=[]
    operate_array2=[]
    operate_array3=[]

    count = 0
    for code in df_Code.index:
# index,0 - 6 date??? open???? high???? close???? low???? volume???? price_change????? p_change????
# 7-12 ma5?5??? ma10?10??? ma20:20??? v_ma5:5???v_ma10:10??? v_ma20:20???
        df = ts.get_hist_data(code,start='2014-11-20')
        dflen = df.shape[0]
        count = count + 1       
        if dflen>35:
            try:
                (df,operate1) = Get_MACD(df) 
                (df,operate2) = Get_KDJ(df)
                (df,operate3) = Get_RSI(df)
            except Exception, e:
                 Write_Blog(e,Dist)
                 pass
        operate_array1.append(operate1)  #round(df.iat[(dflen-1),16],2)
        operate_array2.append(operate2)
        operate_array3.append(operate3)
        if count == 0:
            Write_Blog(str(count),Dist)
    df_Code['MACD']=pd.Series(operate_array1,index=df_Code.index)
    df_Code['KDJ']=pd.Series(operate_array2,index=df_Code.index)
    df_Code['RSI']=pd.Series(operate_array3,index=df_Code.index)
    return df_Code

#??MACD??????
项目:rqalpha    作者:ricequant    | 项目源码 | 文件源码
def handle_bar(context, bar_dict):
    # ?????????????

    # bar_dict[order_book_id] ?????????bar??
    # context.portfolio ???????????????

    # ??order_shares(id_or_ins, amount)??????

    # TODO: ??????????

    # ????????????loop?????????RSI??
    for stock in context.stocks:
        # ??????
        prices = history_bars(stock, context.TIME_PERIOD+1, '1d', 'close')

        # ?Talib??RSI?
        rsi_data = talib.RSI(prices, timeperiod=context.TIME_PERIOD)[-1]

        cur_position = context.portfolio.positions[stock].quantity
        # ??????30%???????
        target_available_cash = context.portfolio.cash * context.ORDER_PERCENT

        # ?RSI???????????????
        if rsi_data > context.HIGH_RSI and cur_position > 0:
            order_target_value(stock, 0)

        # ?RSI?????????????cash?????????
        if rsi_data < context.LOW_RSI:
            logger.info("target available cash caled: " + str(target_available_cash))
            # ??????????? - 100shares?????ricequant ?order management system reject?
            order_value(stock, target_available_cash)
项目:InplusTrader_Linux    作者:zhengwsh    | 项目源码 | 文件源码
def __recountRsi(self):
        """??K??RSI"""

        if self.inputRsiLen <= 0: return

        # 1?lineBar?????????
        if len(self.lineBar) < self.inputRsiLen+2:
            self.debugCtaLog(u'?????,??Bar?????{0}???RSI???{1}'.
                             format(len(self.lineBar), self.inputRsiLen+2))
            return

        # 3?inputRsiLen(????????????
        listClose=[x.close for x in self.lineBar[-self.inputRsiLen - 2:]]
        barRsi = ta.RSI(numpy.array(listClose, dtype=float), self.inputRsiLen)[-1]
        barRsi = round(float(barRsi), 3)

        l = len(self.lineRsi)
        if l > self.inputRsiLen*8:
            del self.lineRsi[0]

        self.lineRsi.append(barRsi)

        if l > 3:
            # ?
            if self.lineRsi[-1] < self.lineRsi[-2] and self.lineRsi[-3] < self.lineRsi[-2]:

                t={}
                t["Type"] = u'T'
                t["RSI"] = self.lineRsi[-2]
                t["Close"] = self.lineBar[-2].close


                if len(self.lineRsiTop) > self.inputRsiLen:
                    del self.lineRsiTop[0]

                self.lineRsiTop.append( t )
                self.lastRsiTopButtom = self.lineRsiTop[-1]

            # ?
            elif self.lineRsi[-1] > self.lineRsi[-2] and self.lineRsi[-3] > self.lineRsi[-2]:

                b={}
                b["Type"] = u'B'
                b["RSI"] = self.lineRsi[-2]
                b["Close"] = self.lineBar[-2].close

                if len(self.lineRsiButtom) > self.inputRsiLen:
                    del self.lineRsiButtom[0]
                self.lineRsiButtom.append(b)
                self.lastRsiTopButtom = self.lineRsiButtom[-1]
项目:catalyst    作者:enigmampc    | 项目源码 | 文件源码
def _handle_data_rsi_only(context, data):
    price = data.current(context.asset, 'close')
    log.info('got price {price}'.format(price=price))

    if price is np.nan:
        log.warn('no pricing data')
        return

    if context.base_price is None:
        context.base_price = price

    try:
        prices = data.history(
            context.asset,
            fields='price',
            bar_count=20,
            frequency='30T'
        )
    except Exception as e:
        log.warn('historical data not available: '.format(e))
        return

    rsi = talib.RSI(prices.values, timeperiod=16)[-1]
    log.info('got rsi {}'.format(rsi))

    signal = None
    if rsi < context.RSI_OVERSOLD:
        signal = 'long'

    # Making sure that the price is still current
    price = data.current(context.asset, 'close')
    cash = context.portfolio.cash
    log.info(
        'base currency available: {cash}, cap: {cap}'.format(
            cash=cash,
            cap=context.MAX_HOLDINGS
        )
    )
    volume = data.current(context.asset, 'volume')
    price_change = (price - context.base_price) / context.base_price
    record(
        price=price,
        price_change=price_change,
        rsi=rsi,
        volume=volume,
        cash=cash,
        starting_cash=context.portfolio.starting_cash,
        leverage=context.account.leverage,
    )

    _handle_buy_sell_decision(context, data, signal, price)
项目:mosquito    作者:miti0    | 项目源码 | 文件源码
def calculate_features(df):
        """
        Method which calculates and generates features
        """
        close = df['close'].values
        high = df['high'].values
        low = df['low'].values
        volume = df['volume'].values
        last_row = df.tail(1).copy()

        # ************** Calc EMAs
        ema_periods = [2, 4, 8, 12, 16, 20]
        for ema_period in ema_periods:
            ema = talib.EMA(close[-ema_period:], timeperiod=ema_period)[-1]
            last_row['ema' + str(ema_period)] = ema

        # ************** Calc RSIs
        rsi_periods = [5]
        for rsi_period in rsi_periods:
            rsi = talib.RSI(close[-rsi_period:], timeperiod=rsi_period-1)[-1]
            last_row['rsi' + str(rsi_period)] = rsi
            last_row['rsi_above_50' + str(rsi_period)] = int(rsi > 50.0)

        # ************** Calc CCIs
        cci_periods = [5]
        for cci_period in cci_periods:
            cci = talib.CCI(high[-cci_period:],
                            low[-cci_period:],
                            close[-cci_period:],
                            timeperiod=cci_period)[-1]
            last_row['cci' + str(cci_period)] = cci

        # ************** Calc MACD 1
        macd_periods = [34]
        for macd_period in macd_periods:
            macd, macd_signal, _ = talib.MACD(close[-macd_period:],
                                              fastperiod=12,
                                              slowperiod=26,
                                              signalperiod=9)
            macd = macd[-1]
            signal_line = macd_signal[-1]
            last_row['macd_above_signal' + str(macd_period)] = int(macd > signal_line)
            last_row['macd_above_zero' + str(macd_period)] = int(macd > 0.0)

        # ************** Calc OBVs
        obv_periods = [2, 4, 8, 12, 16, 20]
        for obv_period in obv_periods:
            obv = talib.OBV(close[-obv_period:], volume[-obv_period:])[-1]
            last_row['obv' + str(obv_period)] = obv

        return last_row
项目:mosquito    作者:miti0    | 项目源码 | 文件源码
def calculate_features(df):
        """
        Method which calculates and generates features
        """
        close = df['close'].values
        high = df['high'].values
        low = df['low'].values
        volume = df['volume'].values
        last_row = df.tail(1).copy()

        # ************** Calc EMAs
        ema_periods = [2, 4, 8, 12, 16, 20]
        for ema_period in ema_periods:
            ema = talib.EMA(close[-ema_period:], timeperiod=ema_period)[-1]
            last_row['ema' + str(ema_period)] = ema

        # ************** Calc RSIs
        rsi_periods = [5]
        for rsi_period in rsi_periods:
            rsi = talib.RSI(close[-rsi_period:], timeperiod=rsi_period-1)[-1]
            last_row['rsi' + str(rsi_period)] = rsi
            last_row['rsi_above_50' + str(rsi_period)] = int(rsi > 50.0)

        # ************** Calc CCIs
        cci_periods = [5]
        for cci_period in cci_periods:
            cci = talib.CCI(high[-cci_period:],
                            low[-cci_period:],
                            close[-cci_period:],
                            timeperiod=cci_period)[-1]
            last_row['cci' + str(cci_period)] = cci

        # ************** Calc MACD 1
        macd_periods = [34]
        for macd_period in macd_periods:
            macd, macd_signal, _ = talib.MACD(close[-macd_period:],
                                              fastperiod=12,
                                              slowperiod=26,
                                              signalperiod=9)
            macd = macd[-1]
            signal_line = macd_signal[-1]
            last_row['macd_above_signal' + str(macd_period)] = int(macd > signal_line)
            last_row['macd_above_zero' + str(macd_period)] = int(macd > 0.0)

        # ************** Calc OBVs
        obv_periods = [2, 4, 8, 12, 16, 20]
        for obv_period in obv_periods:
            obv = talib.OBV(close[-obv_period:], volume[-obv_period:])[-1]
            last_row['obv' + str(obv_period)] = obv

        return last_row
项目:AutoTrading    作者:curme    | 项目源码 | 文件源码
def oscillator2(data):
    float_close = Data.toFloatArray(df['Close'])
    float_high = Data.toFloatArray(df['High'])
    float_low = Data.toFloatArray(df['Low'])
    float_open = Data.toFloatArray(df['Open'])
    adx_values = tl.ADX(np.array(float_high),np.array(float_low),np.array(float_close), timeperiod = 14)
    dmi = tl.DX(np.array(float_high),np.array(float_low),np.array(float_close), timeperiod = 14)
    mdmi = tl.MINUS_DI(np.array(float_high),np.array(float_low),np.array(float_close), timeperiod = 14)
    rsi = tl.RSI(np.array(float_close),timeperiod = 4 )
    signals = []
    flag = 0
    for i in xrange(40 , len(adx_values) - 2):
        if flag ==0:
            if adx_values[i]>20  and dmi[i]>mdmi[i] and df.loc[i+1, 'Open']> (df.loc[i, 'Close']+1.8) and rsi[i]<50:
                signal = ['HSI', df.loc[i+1, 'Date'], 'Long',  df.loc[i+1, 'Close']]
                flag =1
                signals.append(signal)
            if adx_values[i]>20  and dmi[i]<mdmi[i] and df.loc[i+1, 'Open']< (df.loc[i, 'Close']-1.8) and rsi[i]<50:
                signal = ['HSI', df.loc[i+1, 'Date'], 'Short',  df.loc[i+1, 'Close']]
                flag =2
                signals.append(signal)
        elif flag ==1:
            if df.loc[i, 'Close']>= signal[3]*1.01 or df.loc[i, 'Close']<= signal[3]*0.90 or (df.loc[i, 'Date']-signal[1])>timedelta(days=5):
                signal = ['HSI', df.loc[i, 'Date'], 'Short',  df.loc[i+1, 'Open']]
                flag = 0
                signals.append(signal)
        elif flag ==2:
            if df.loc[i, 'Close']<= signal[3]*0.99 or df.loc[i, 'Close']>= signal[3]*1.10 or (df.loc[i, 'Date']-signal[1])>timedelta(days=5):
                signal = ['HSI', df.loc[i+1, 'Date'], 'Long',  df.loc[i+1, 'Close']]
                flag = 0
                signals.append(signal)

    sig = pd.DataFrame(signals, columns=['Code', 'Time', 'Action',  'Price'])
    print sig['Time'][10]-sig['Time'][0]
    profits = []
    print sig
    for k in range(0,len(signals)/2):
        if sig['Action'][k*2] == "Long":
            profit = sig['Price'][k*2+1] - sig['Price'][k*2]
        else:
            profit = sig['Price'][k*2]- sig['Price'][k*2+1]
        profits.append(profit)
    print np.sum(profits)
    print(profits)
    ###### PLOT #######
    longSignals = sig[sig['Action'] == 'Long']
    shortSignals = sig[sig['Action'] == 'Short']
    plt.plot(df['Date'], df['Close'], longSignals['Time'], longSignals['Price'], 'r^', shortSignals['Time'],
             shortSignals['Price'], 'gv', markersize=10)
    red_patch = mpatches.Patch(color='red', label='Long')
    green_patch = mpatches.Patch(color='green', label='Short')
    plt.legend(handles=[red_patch, green_patch])
    plt.grid()
    plt.show()
    ###### PLOT #######
项目:DataAnalysis    作者:IMYin    | 项目源码 | 文件源码
def Get_KDJ(df):
    #??9,3,3
    slowk, slowd = ta.STOCH(np.array(df['high']), np.array(df['low']), np.array(df['close']), fastk_period=9, slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0)

    slowkMA5 = ta.MA(slowk, timeperiod=5, matype=0)
    slowkMA10 = ta.MA(slowk, timeperiod=10, matype=0)
    slowkMA20 = ta.MA(slowk, timeperiod=20, matype=0)
    slowdMA5 = ta.MA(slowd, timeperiod=5, matype=0)
    slowdMA10 = ta.MA(slowd, timeperiod=10, matype=0)
    slowdMA20 = ta.MA(slowd, timeperiod=20, matype=0)
    #16-17 K,D      
    df['slowk']=pd.Series(slowk,index=df.index) #K
    df['slowd']=pd.Series(slowd,index=df.index)#D
    dflen = df.shape[0]
    MAlen = len(slowkMA5)
    operate = 0
    #1.K???????——???90?????????10??????D??80???????????D??20???????????
    if df.iat[(dflen-1),16]>=90:
        operate = operate + 3
    elif df.iat[(dflen-1),16]<=10:
        operate = operate - 3

    if df.iat[(dflen-1),17]>=80:
        operate = operate + 3
    elif df.iat[(dflen-1),17]<=20:
        operate = operate - 3

    #2.??????K???D??K?????D?????????#???
    if df.iat[(dflen-1),16]> df.iat[(dflen-1),17] and df.iat[(dflen-2),16]<=df.iat[(dflen-2),17]:
        operate = operate + 10
    #??????K??D?K?????D?????????#???
    elif df.iat[(dflen-1),16]< df.iat[(dflen-1),17] and df.iat[(dflen-2),16]>=df.iat[(dflen-2),17]:
        operate = operate - 10


    #3.???????????????????????
    if df.iat[(dflen-1),7]>=df.iat[(dflen-1),8] and df.iat[(dflen-1),8]>=df.iat[(dflen-1),9]:#K???
        if (slowkMA5[MAlen-1]<=slowkMA10[MAlen-1] and slowkMA10[MAlen-1]<=slowkMA20[MAlen-1]) or \
           (slowdMA5[MAlen-1]<=slowdMA10[MAlen-1] and slowdMA10[MAlen-1]<=slowdMA20[MAlen-1]): #K,D??
            operate = operate - 1
    elif df.iat[(dflen-1),7]<=df.iat[(dflen-1),8] and df.iat[(dflen-1),8]<=df.iat[(dflen-1),9]:#K???
        if (slowkMA5[MAlen-1]>=slowkMA10[MAlen-1] and slowkMA10[MAlen-1]>=slowkMA20[MAlen-1]) or \
           (slowdMA5[MAlen-1]>=slowdMA10[MAlen-1] and slowdMA10[MAlen-1]>=slowdMA20[MAlen-1]): #K,D??
            operate = operate + 1

    return (df,operate)

#??RSI??????
项目:DataAnalysis    作者:IMYin    | 项目源码 | 文件源码
def Get_RSI(df):
    #??14,5
    slowreal = ta.RSI(np.array(df['close']), timeperiod=14)
    fastreal = ta.RSI(np.array(df['close']), timeperiod=5)
    slowrealMA5 = ta.MA(slowreal, timeperiod=5, matype=0)
    slowrealMA10 = ta.MA(slowreal, timeperiod=10, matype=0)
    slowrealMA20 = ta.MA(slowreal, timeperiod=20, matype=0)
    fastrealMA5 = ta.MA(fastreal, timeperiod=5, matype=0)
    fastrealMA10 = ta.MA(fastreal, timeperiod=10, matype=0)
    fastrealMA20 = ta.MA(fastreal, timeperiod=20, matype=0)
    #18-19 ??real???real      
    df['slowreal']=pd.Series(slowreal,index=df.index) #??real 18
    df['fastreal']=pd.Series(fastreal,index=df.index)#??real 19
    dflen = df.shape[0]
    MAlen = len(slowrealMA5)
    operate = 0
    #RSI>80?????RSI<20????
    if df.iat[(dflen-1),18]>80 or df.iat[(dflen-1),19]>80:
        operate = operate - 2
    elif df.iat[(dflen-1),18]<20 or df.iat[(dflen-1),19]<20:
        operate = operate + 2

    #RSI??50???????????50????????
    if (df.iat[(dflen-2),18]<=50 and df.iat[(dflen-1),18]>50) or (df.iat[(dflen-2),19]<=50 and df.iat[(dflen-1),19]>50):
        operate = operate + 4
    elif (df.iat[(dflen-2),18]>=50 and df.iat[(dflen-1),18]<50) or (df.iat[(dflen-2),19]>=50 and df.iat[(dflen-1),19]<50):
        operate = operate - 4

    #RSI??????????RSI?????????
    if df.iat[(dflen-1),7]>=df.iat[(dflen-1),8] and df.iat[(dflen-1),8]>=df.iat[(dflen-1),9]:#K???
        if (slowrealMA5[MAlen-1]<=slowrealMA10[MAlen-1] and slowrealMA10[MAlen-1]<=slowrealMA20[MAlen-1]) or \
           (fastrealMA5[MAlen-1]<=fastrealMA10[MAlen-1] and fastrealMA10[MAlen-1]<=fastrealMA20[MAlen-1]): #RSI??
            operate = operate - 1
    elif df.iat[(dflen-1),7]<=df.iat[(dflen-1),8] and df.iat[(dflen-1),8]<=df.iat[(dflen-1),9]:#K???
        if (slowrealMA5[MAlen-1]>=slowrealMA10[MAlen-1] and slowrealMA10[MAlen-1]>=slowrealMA20[MAlen-1]) or \
           (fastrealMA5[MAlen-1]>=fastrealMA10[MAlen-1] and fastrealMA10[MAlen-1]>=fastrealMA20[MAlen-1]): #RSI??
            operate = operate + 1

    #?????????????????????????????????????????????????????????????????
    if df.iat[(dflen-1),19]> df.iat[(dflen-1),18] and df.iat[(dflen-2),19]<=df.iat[(dflen-2),18]:
        operate = operate + 10
    elif df.iat[(dflen-1),19]< df.iat[(dflen-1),18] and df.iat[(dflen-2),19]>=df.iat[(dflen-2),18]:
        operate = operate - 10      
    return (df,operate)