python - 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])
有解决办法吗?
解决方案
这是自己计算 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,则需要使用字符串或日期时间来提供绘图的开始和结束。
推荐阅读
- security - 与集成团队共享密钥的最佳方式
- c# - WPF C# 从页面打开一个新窗口
- pandas - 在 python 中编写 csv 文件时,字母数字数据被转换为科学记数法
- nginx - GoAccess nginx 日志格式未知
- reactjs - 标签“img”的父标签是“span”,但只能是“i-amphtml-sizer-intrinsic”。错误 不允许自定义 JavaScript
- r - 使用“plot_ly”的线条和标记的自定义颜色问题
- css - 使用我自己的自定义列表中的随机渐变作为背景( SCSS )
- html - 为什么“margin:0 auto”会删除我的div中的空白?如何将 div 与它的空白居中?
- react-native - 如何写下面的代码组件didmount代码在使用效果?
- powershell - 如何使用 PowerShell 在文件名中连续添加数字?