首页 > 解决方案 > Python TA-Lib RSI 错误结果

问题描述

我试图在 python 中使用 TA-Lib 获取股票的 RSI,但它一直给我错误的数字。

import talib
import pandas as pd
from td.client import TDClient

ticker = 'GOOG'
data = TDSession.get_price_history(
    symbol = ticker,
    period_type = 'month',
    frequency_type = 'daily',
    frequency = 1,
    period = 1,
)

df = pd.DataFrame(data['candles'])

close = df['close']

# Gets the RSI of the ticker 
rsi = str(talib.RSI(close, timeperiod=14))

current = float(rsi[len(rsi)-40:len(rsi)-33])

有解决办法吗?

标签: pythonpandasdataframefinance

解决方案


这是自己计算 RSI 的一种方法。代码可以优化,但我更喜欢让它易于理解,并让您优化。

然后,您应该将其与 Ta-Lib 进行比较。

例如,我们假设您有一个名为 df 的 DataFrame,其中有一列名为“Close”,用​​于表示收盘价。顺便说一句,请注意,例如,如果您将 RSI 的结果与站点进行比较,您应该确保比较相同的值。例如,如果在站内,您的买盘已收盘,而您在中间或卖盘上自行计算,则结果不会相同。

让我们看看代码:

def rsi(df,_window=14,_plot=0,_start=None,_end=None):
    """[RS functionI]

    Args:
        df ([DataFrame]): [DataFrame with a column 'Close' for the close price]
        _window ([int]): [The lookback window.](default : {14})
        _plot ([int]): [1 if you want to see the plot](default : {0})
        _start ([Date]):[if _plot=1, start of plot](default : {None})
        _end ([Date]):[if _plot=1, end of plot](default : {None})
    """    

    ##### Diff for the différences between last close and now
    df['Diff'] = df['Close'].transform(lambda x: x.diff())
    ##### In 'Up', just keep the positive values
    df['Up'] = df['Diff']
    df.loc[(df['Up']<0), 'Up'] = 0
    ##### Diff for the différences between last close and now
    df['Down'] = df['Diff']
    ##### In 'Down', just keep the negative values
    df.loc[(df['Down']>0), 'Down'] = 0 
    df['Down'] = abs(df['Down'])

    ##### Moving average on Up & Down
    df['avg_up'+str(_window)] = df['Up'].transform(lambda x: x.rolling(window=_window).mean())
    df['avg_down'+str(_window)] = df['Down'].transform(lambda x: x.rolling(window=_window).mean())

    ##### RS is the ratio of the means of Up & Down
    df['RS_'+str(_window)] = df['avg_up'+str(_window)] / df['avg_down'+str(_window)]

    ##### RSI Calculation
    ##### 100 - (100/(1 + RS))
    df['RSI_'+str(_window)] = 100 - (100/(1+df['RS_'+str(_fast)]))

    ##### Drop useless columns
    df = df.drop(['Diff','Up','Down','avg_up'+str(_window),'avg_down'+str(_window),'RS_'+str(_window)],axis=1)

    ##### If asked, plot it!
    if _plot == 1:
        sns.set()
        fig = plt.figure(facecolor = 'white', figsize = (30,5))
        ax0 = plt.subplot2grid((6,4), (1,0), rowspan=4, colspan=4)
        ax0.plot(df[(df.index<=end)&(df.index>=start)&(df.Symbol==_ticker.replace('/',''))]['Close'])
        ax0.set_facecolor('ghostwhite')
        ax0.legend(['Close'],ncol=3, loc = 'upper left', fontsize = 15)
        plt.title(_ticker+" Close from "+str(start)+' to '+str(end), fontsize = 20)

        ax1 = plt.subplot2grid((6,4), (5,0), rowspan=1, colspan=4, sharex = ax0)
        ax1.plot(df[(df.index<=end)&(df.index>=start)&(df.Symbol==_ticker.replace('/',''))]['RSI_'+str(_window)], color = 'blue')
        ax1.legend(['RSI_'+str(_window)],ncol=3, loc = 'upper left', fontsize = 12)
        ax1.set_facecolor('silver')
        plt.subplots_adjust(left=.09, bottom=.09, right=1, top=.95, wspace=.20, hspace=0)
        plt.show()
    return(df)

要调用该函数,您只需键入

df = rsi(df)

如果您将其保留为默认值,或者更改 arg 的 _window 和/或 _plot。请注意,如果您输入 _plot=1,则需要使用字符串或日期时间来提供绘图的开始和结束。


推荐阅读